@v-office/website-sdk 2.30.2 → 2.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { $t as V9_HUB_OBJECT_GROUP_SCOPE_FILTER_KEY, Jt as defineV9PropertyHighlightSourcesFromUnknown, Kt as defineWebsiteSDKOptions, Qt as V9_HUB_OBJECT_GROUP_FILTER_KEY, Xt as V9_HUB_FACILITY_SCOPE_FILTER_KEY, Zt as V9_HUB_FACILITY_SEARCH_FILTER_KEY, en as V9_HUB_OFFERS_FILTER_KEY, f as makeV9GraphQLClient, h as makeV0OpenApiClientFetchLive, i as toV9SdkOwnedHubFilterKeys, n as checkV9HubFilters, nn as V9_HUB_RENTAL_IDS_FILTER_KEY, p as V0OpenApiClient, r as toV9RequiredHubFilterKeys, rn as V9_SDK_OWNED_HUB_FILTER_KEYS, t as createWebsiteSDK, tn as V9_HUB_OFFER_FILTER_KEY } from "./client-Wbat4mKe.mjs";
3
- import { _ as parseVofficeRatingData, i as hubFiltersQuery, l as rentalsAllWithoutFeedbacksQuery } from "./operations-CfjJjdrw.mjs";
4
- import { SearchSearchSortSchema, defineCustomAttributesFromUnknown } from "@v-office/sdk-core";
2
+ import { $t as V9_HUB_FACILITY_SEARCH_FILTER_KEY, Jt as defineWebsiteSDKOptions, Qt as V9_HUB_FACILITY_SCOPE_FILTER_KEY, Xt as defineV9PropertyHighlightSourcesFromUnknown, _ as rental_attributes_default$1, an as V9_HUB_RENTAL_IDS_FILTER_KEY, cn as stable_filters_default, en as V9_HUB_OBJECT_GROUP_FILTER_KEY, f as makeV9GraphQLClient, h as makeV0OpenApiClientFetchLive, i as toV9SdkOwnedHubFilterKeys, in as V9_HUB_REGION_FILTER_KEY, n as checkV9HubFilters, nn as V9_HUB_OFFERS_FILTER_KEY, on as V9_HUB_UNIT_TYPE_FILTER_KEY, p as V0OpenApiClient, r as toV9RequiredHubFilterKeys, rn as V9_HUB_OFFER_FILTER_KEY, sn as V9_SDK_OWNED_HUB_FILTER_KEYS, t as createWebsiteSDK, tn as V9_HUB_OBJECT_GROUP_SCOPE_FILTER_KEY, v as rental_attributes_default } from "./client-RLKoee2Y.mjs";
3
+ import { a as hubRentalDataQuery, g as parseJsonData, i as hubFiltersQuery, m as VofficeUnitDataPropertyMetadata, u as rentalsAllWithoutFeedbacksQuery, y as parseVofficeRatingData } from "./operations-CUWcmNGK.mjs";
4
+ import { STABLE_SEARCH_INPUTS, SearchSearchSortSchema, defineCustomAttributesFromUnknown, toStableSearchInputQueryKeys } from "@v-office/sdk-core";
5
5
  import { ByteSize, Console, Effect, FileSystem, Layer, Option, Path, Schema, Stdio, Terminal } from "effect";
6
6
  import { Command, Flag } from "effect/unstable/cli";
7
7
  import { inspect } from "node:util";
@@ -17,7 +17,7 @@ var CLICheckFailed = class extends Error {
17
17
  const toCLIError = (message, cause) => cause instanceof Error ? new CLICheckFailed(`${message}: ${cause.message}`, { cause }) : new CLICheckFailed(message, { cause });
18
18
  //#endregion
19
19
  //#region package.json
20
- var version = "2.30.2";
20
+ var version = "2.31.1";
21
21
  //#endregion
22
22
  //#region src/cli/output.ts
23
23
  const toJson = (value) => Effect.try({
@@ -466,6 +466,35 @@ const fetchV9HubFilters = (config) => Effect.runPromise(makeV9GraphQLClient(conf
466
466
  name,
467
467
  options: options ?? []
468
468
  })))));
469
+ const fetchV9HubRentalData = ({ config, attributes }) => Effect.runPromise(makeV9GraphQLClient(config).execute(hubRentalDataQuery, { attributes: [...attributes] }).pipe(Effect.map((data) => data.all.map((rental) => parseJsonData({}, rental.data).unknown))));
470
+ //#endregion
471
+ //#region src/cli/v9-unit-fields.ts
472
+ const BUILT_IN_FILTER_BY_FIELD = new Map(Object.entries(stable_filters_default).map(([key, filter]) => ["property" in filter ? filter.property : filter.custom_query.query[0].key.slice(21), key]));
473
+ const labelFor = (labelKey, labelsByKey) => labelsByKey[labelKey] ?? labelKey;
474
+ const toUnitField = (field, metadata) => {
475
+ if (metadata.sourceType !== "BOOL" && metadata.sourceType !== "INT") return [];
476
+ const builtInFilter = BUILT_IN_FILTER_BY_FIELD.get(field);
477
+ return [{
478
+ field,
479
+ type: metadata.sourceType,
480
+ de: labelFor(metadata.labelKey, rental_attributes_default),
481
+ en: labelFor(metadata.labelKey, rental_attributes_default$1),
482
+ category: metadata.category.key,
483
+ ...builtInFilter === void 0 ? {} : { builtInFilter }
484
+ }];
485
+ };
486
+ const V9_UNIT_FIELDS = new Map(Object.entries(VofficeUnitDataPropertyMetadata).flatMap(([field, metadata]) => toUnitField(field, metadata)).map((unitField) => [unitField.field, unitField]));
487
+ const isCustomV9UnitField = (field) => /^p_\d+$/.test(field);
488
+ const CUSTOM_V9_UNIT_FIELD_HINT = "An agency's own vOffice features are p_<number> fields. With the agency's vOffice key (not the be-on key), https://api.v-office.com/export/properties?key=<vOffice key> lists them as p_<number> with their names; the user opens it in a browser, and the vOffice key never goes into the chat or the site.";
489
+ const findV9UnitField = (field) => V9_UNIT_FIELDS.get(field);
490
+ const searchV9UnitFields = (search) => {
491
+ const needle = search?.trim().toLowerCase() ?? "";
492
+ return [...V9_UNIT_FIELDS.values()].filter((field) => [
493
+ field.field,
494
+ field.de,
495
+ field.en
496
+ ].some((text) => text.toLowerCase().includes(needle)));
497
+ };
469
498
  //#endregion
470
499
  //#region src/cli/v9-hub-filters.ts
471
500
  const GROUP = "Beliebte Filter";
@@ -519,6 +548,16 @@ const HUB_FILTER_REQUESTS = {
519
548
  property: "facility"
520
549
  }
521
550
  },
551
+ [V9_HUB_REGION_FILTER_KEY]: {
552
+ purpose: "Filter nach Region in der Suche der Website. Eine Region schließt ihre Unterregionen ein. Die Auswahl der Regionen erzeugt der be-on! Hub selbst.",
553
+ entry: {
554
+ name: "Region",
555
+ type: "SpecialFilter\\RegionFilter",
556
+ display_type: "searchselect",
557
+ group: GROUP,
558
+ property: "region.id"
559
+ }
560
+ },
522
561
  [V9_HUB_OFFERS_FILTER_KEY]: {
523
562
  purpose: "Zeigt nur Unterkünfte mit einem Angebot.",
524
563
  entry: {
@@ -542,6 +581,7 @@ const REQUEST_ORDER = [
542
581
  V9_HUB_RENTAL_IDS_FILTER_KEY,
543
582
  V9_HUB_OBJECT_GROUP_FILTER_KEY,
544
583
  V9_HUB_FACILITY_SEARCH_FILTER_KEY,
584
+ V9_HUB_REGION_FILTER_KEY,
545
585
  V9_HUB_OFFERS_FILTER_KEY,
546
586
  V9_HUB_OFFER_FILTER_KEY
547
587
  ];
@@ -551,14 +591,307 @@ const toRequestedHubFilterKeys = ({ selection, sdkOwnedKeys }) => {
551
591
  ...selection.unit ? [V9_HUB_RENTAL_IDS_FILTER_KEY] : [],
552
592
  ...selection.objectGroup ? [V9_HUB_OBJECT_GROUP_FILTER_KEY] : [],
553
593
  ...selection.facility ? [V9_HUB_FACILITY_SEARCH_FILTER_KEY] : [],
594
+ ...selection.region ? [V9_HUB_REGION_FILTER_KEY] : [],
554
595
  ...selection.offers ? [V9_HUB_OFFERS_FILTER_KEY] : [],
555
596
  ...selection.offer ? [V9_HUB_OFFER_FILTER_KEY] : []
556
597
  ]);
557
598
  return REQUEST_ORDER.filter((key) => wanted.has(key));
558
599
  };
600
+ const toFixedHubFilterRequests = (keys) => keys.map((key) => ({
601
+ key,
602
+ ...HUB_FILTER_REQUESTS[key]
603
+ }));
604
+ const UNIT_TYPE_LABELS = {
605
+ HOUSE: {
606
+ de: "Ferienhaus",
607
+ en: "Holiday home"
608
+ },
609
+ FLAT: {
610
+ de: "Ferienwohnung",
611
+ en: "Holiday apartment"
612
+ },
613
+ ROOM: {
614
+ de: "Zimmer",
615
+ en: "Room"
616
+ },
617
+ PRIVAT: {
618
+ de: "Privatunterkunft",
619
+ en: "Private accommodation"
620
+ },
621
+ MOBILEHOME: {
622
+ de: "Mobilheim",
623
+ en: "Mobile home"
624
+ },
625
+ YACHT: {
626
+ de: "Yacht",
627
+ en: "Yacht"
628
+ }
629
+ };
630
+ const UNIT_TYPE_ORDER = Object.keys(UNIT_TYPE_LABELS);
631
+ const RESERVED_KEYS = /* @__PURE__ */ new Set([
632
+ ...toStableSearchInputQueryKeys(STABLE_SEARCH_INPUTS.period),
633
+ ...toStableSearchInputQueryKeys(STABLE_SEARCH_INPUTS.occupancy),
634
+ ...Object.keys(stable_filters_default),
635
+ ...REQUEST_ORDER,
636
+ V9_HUB_UNIT_TYPE_FILTER_KEY
637
+ ]);
638
+ const KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;
639
+ const FIELD_PATTERN = /^[A-Za-z0-9_]+$/;
640
+ const parseFieldFlag = ({ flag, value, singleField }) => {
641
+ const [key = "", fieldList = "", ...rest] = value.split("=");
642
+ const fields = fieldList.split(",");
643
+ if (rest.length > 0 || !KEY_PATTERN.test(key) || !fields.every((f) => FIELD_PATTERN.test(f))) return `--${flag} ${value}: expected <key>=<vOffice field>${singleField ? "" : "[,<vOffice field>...]"}, for example --${flag} ${singleField ? "beachdistance_max=beachdistance" : "reet=p_14418"}.`;
644
+ if (singleField && fields.length > 1) return `--${flag} ${value}: takes one vOffice field.`;
645
+ if (RESERVED_KEYS.has(key)) return `--${flag} ${value}: ${key} is a built-in filter or search key; choose another key.`;
646
+ const fieldError = fields.map((field) => toFieldTypeError({
647
+ flag,
648
+ field
649
+ })).find(Boolean);
650
+ if (fieldError !== void 0) return `--${flag} ${value}: ${fieldError}`;
651
+ const single = fields.length === 1 ? findV9UnitField(fields[0] ?? "") : void 0;
652
+ if (flag !== "max" && single?.builtInFilter !== void 0) return `--${flag} ${value}: the built-in filter ${single.builtInFilter} already filters by ${single.field} („${single.de}“); use it, it needs no Hub entry.`;
653
+ return {
654
+ key,
655
+ fields
656
+ };
657
+ };
658
+ const toFieldTypeError = ({ flag, field }) => {
659
+ if (isCustomV9UnitField(field)) return void 0;
660
+ const known = findV9UnitField(field);
661
+ if (known === void 0) return `${field} is not a vOffice field. Find it with \`website-sdk --backend v9 hub-filters fields --search <word>\`. ${CUSTOM_V9_UNIT_FIELD_HINT}`;
662
+ if (flag === "field" && known.type !== "BOOL") return `${field} („${known.de}“) is a number; use --min or --max.`;
663
+ if (flag !== "field" && known.type !== "INT") return `${field} („${known.de}“) is a yes/no field; use --field.`;
664
+ };
665
+ const describeFields = (fields) => fields.map((field) => {
666
+ const known = findV9UnitField(field);
667
+ return known === void 0 ? field : `„${known.de}“ (${field})`;
668
+ }).join(" oder ");
669
+ const toFieldLabels = ({ key, fields }) => {
670
+ const known = fields.map(findV9UnitField).find((field) => field !== void 0);
671
+ return known === void 0 ? {
672
+ name: key,
673
+ de: key,
674
+ en: key,
675
+ note: `${key}: replace the labels with the filter's name. ${CUSTOM_V9_UNIT_FIELD_HINT}`
676
+ } : {
677
+ name: known.de,
678
+ de: known.de,
679
+ en: known.en,
680
+ note: void 0
681
+ };
682
+ };
683
+ const parseRentalDataSelection = (selection) => {
684
+ const errors = [];
685
+ const parse = (flag, values, singleField) => values.flatMap((value) => {
686
+ const parsed = parseFieldFlag({
687
+ flag,
688
+ value,
689
+ singleField
690
+ });
691
+ if (typeof parsed === "string") {
692
+ errors.push(parsed);
693
+ return [];
694
+ }
695
+ return [parsed];
696
+ });
697
+ const parsed = {
698
+ field: parse("field", selection.field, false),
699
+ min: parse("min", selection.min, true),
700
+ max: parse("max", selection.max, true)
701
+ };
702
+ const keys = [
703
+ ...parsed.field,
704
+ ...parsed.min,
705
+ ...parsed.max
706
+ ].map(({ key }) => key);
707
+ const repeated = [...new Set(keys.filter((key, index) => keys.indexOf(key) !== index))];
708
+ if (repeated.length > 0) errors.push(`Each key may be requested once: ${repeated.join(", ")}.`);
709
+ return {
710
+ parsed,
711
+ errors
712
+ };
713
+ };
714
+ const toRentalDataAttributes = (selection) => {
715
+ const { parsed, errors } = parseRentalDataSelection(selection);
716
+ return {
717
+ attributes: [.../* @__PURE__ */ new Set([...selection.type ? ["type"] : [], ...[
718
+ ...parsed.field,
719
+ ...parsed.min,
720
+ ...parsed.max
721
+ ].flatMap(({ fields }) => fields)])],
722
+ errors
723
+ };
724
+ };
725
+ const toSetValue = (value) => value === true || value === 1 ? true : value === "1" ? "1" : void 0;
726
+ const toNumber = (value) => {
727
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
728
+ return Number.isFinite(number) ? number : void 0;
729
+ };
730
+ const label = (text) => ({
731
+ "de-DE": text,
732
+ "en-US": text
733
+ });
734
+ const toUnitTypeRequest = (rentals) => {
735
+ const types = [...new Set(rentals.flatMap(({ type }) => typeof type === "string" && type !== "" ? [type] : []))].toSorted((a, b) => (UNIT_TYPE_ORDER.indexOf(a) + 1 || Infinity) - (UNIT_TYPE_ORDER.indexOf(b) + 1 || Infinity));
736
+ const [first, ...others] = types.map((type) => ({
737
+ value: type,
738
+ label: UNIT_TYPE_LABELS[type] ? {
739
+ "de-DE": UNIT_TYPE_LABELS[type].de,
740
+ "en-US": UNIT_TYPE_LABELS[type].en
741
+ } : label(type)
742
+ }));
743
+ if (first === void 0) return "--type: no rental of this be-on key has a type in the be-on! Hub.";
744
+ const unknown = types.filter((type) => UNIT_TYPE_LABELS[type] === void 0);
745
+ return {
746
+ key: V9_HUB_UNIT_TYPE_FILTER_KEY,
747
+ purpose: `Filter nach Objekttyp (${types.join(", ")}). Ein Objekttyp, den es erst später gibt, fehlt in der Auswahl, bis der Filter neu angefragt wird.`,
748
+ hubOptionKeys: types,
749
+ entry: {
750
+ name: "Objekttyp",
751
+ type: "OptionFilter",
752
+ display_type: "select",
753
+ group: GROUP,
754
+ property: "type",
755
+ options: Object.fromEntries([first, ...others].map((o) => [o.value, o.label["de-DE"]]))
756
+ },
757
+ definition: definition({
758
+ key: V9_HUB_UNIT_TYPE_FILTER_KEY,
759
+ de: "Objekttyp",
760
+ en: "Property type",
761
+ type: "option",
762
+ options: [first, ...others]
763
+ }),
764
+ ...unknown.length === 0 ? {} : { note: `type: label the options ${unknown.join(", ")}; the SDK does not know them.` }
765
+ };
766
+ };
767
+ const joinNotes = (notes) => {
768
+ const present = notes.filter((note) => note !== void 0);
769
+ return present.length === 0 ? {} : { note: present.join(" ") };
770
+ };
771
+ const unsetNote = ({ key, fields }) => `${key}: no rental of this be-on key has ${fields.join(", ")} set today, so the filter finds nothing until the agency maintains it in vOffice. The request file asks the user to check the field's spelling${fields.some(isCustomV9UnitField) ? " and p_ number" : ""}; confirm it with them before you offer the filter.`;
772
+ const unsetWarning = ({ key, fields }) => [
773
+ `\`${key}\`: Heute hat keine Unterkunft ${fields.map((field) => `\`${field}\``).join(", ")} gesetzt. Bitte prüfen, ${fields.some(isCustomV9UnitField) ? "ob Schreibweise und p_-Nummer stimmen" : "ob der Feldname richtig geschrieben ist"}.`,
774
+ ...fields.some(isCustomV9UnitField) ? ["Die p_-Nummern der eigenen Merkmale zeigt vOffice mit dem vOffice-Key der Agentur (nicht dem be-on Key) unter https://api.v-office.com/export/properties?key=<vOffice-Key>. Den vOffice-Key nirgends eintragen oder weitergeben."] : [],
775
+ "Stimmt alles, findet der Filter erst etwas, wenn das Merkmal in vOffice gepflegt ist."
776
+ ].join(" ");
777
+ const toFieldRequest = ({ key, fields, rentals }) => {
778
+ const conditions = fields.flatMap((field) => {
779
+ const seen = [...new Set(rentals.flatMap((rental) => toSetValue(rental[field]) ?? []))];
780
+ return (seen.length > 0 ? seen : [isCustomV9UnitField(field) ? "1" : true]).map((value) => ({
781
+ key: `VofficeUnit.raw_data.${field}`,
782
+ operator: "EQUAL",
783
+ value
784
+ }));
785
+ });
786
+ const unset = fields.filter((field) => !rentals.some((rental) => toSetValue(rental[field]) !== void 0));
787
+ const matching = rentals.filter((rental) => fields.some((field) => toSetValue(rental[field]) !== void 0)).length;
788
+ const { name, de, en, note } = toFieldLabels({
789
+ key,
790
+ fields
791
+ });
792
+ return {
793
+ key,
794
+ purpose: `Zeigt nur Unterkünfte, bei denen in vOffice ${describeFields(fields)} gesetzt ist. Heute sind das ${matching} Unterkünfte.`,
795
+ entry: {
796
+ name,
797
+ type: "ComplexFilter",
798
+ display_type: "checkbox",
799
+ group: GROUP,
800
+ custom_query: {
801
+ query: conditions,
802
+ ...conditions.length > 1 ? { relation: "OR" } : {}
803
+ }
804
+ },
805
+ definition: definition({
806
+ key,
807
+ de,
808
+ en,
809
+ type: "boolean"
810
+ }),
811
+ ...joinNotes([note, unset.length === 0 ? void 0 : unsetNote({
812
+ key,
813
+ fields: unset
814
+ })]),
815
+ ...unset.length === 0 ? {} : { warning: unsetWarning({
816
+ key,
817
+ fields: unset
818
+ }) }
819
+ };
820
+ };
821
+ const toThresholdRequest = ({ key, fields: [field = ""], bound, rentals }) => {
822
+ const values = rentals.flatMap((rental) => toNumber(rental[field]) ?? []);
823
+ const range = values.length === 0 ? void 0 : {
824
+ low: Math.min(...values),
825
+ high: Math.max(...values)
826
+ };
827
+ const { name, de, en, note } = toFieldLabels({
828
+ key,
829
+ fields: [field]
830
+ });
831
+ return {
832
+ key,
833
+ purpose: `Findet Unterkünfte, bei denen ${describeFields([field])} ${bound === "min" ? "mindestens" : "höchstens"} den eingegebenen Wert hat. ${range === void 0 ? "Heute hat keine Unterkunft dort einen Wert." : `Heute reicht der Wert von ${range.low} bis ${range.high}.`}`,
834
+ entry: {
835
+ name,
836
+ type: "InputFilter",
837
+ display_type: "number",
838
+ group: GROUP,
839
+ custom_query: { query: [{
840
+ key: `VofficeUnit.raw_data.${field}`,
841
+ operator: bound === "min" ? "GREATER_THAN_OR_EQUAL" : "LESS_THAN_OR_EQUAL",
842
+ value: null
843
+ }] }
844
+ },
845
+ definition: definition({
846
+ key,
847
+ de,
848
+ en,
849
+ type: "int",
850
+ numericBounds: { min: 0 }
851
+ }),
852
+ ...joinNotes([note, range === void 0 ? unsetNote({
853
+ key,
854
+ fields: [field]
855
+ }) : `${field} ranges from ${range.low} to ${range.high} across ${values.length} rentals.`]),
856
+ ...range === void 0 ? { warning: unsetWarning({
857
+ key,
858
+ fields: [field]
859
+ }) } : {}
860
+ };
861
+ };
862
+ const toRentalDataHubFilterRequests = ({ selection, rentals }) => {
863
+ const { parsed, errors } = parseRentalDataSelection(selection);
864
+ if (errors.length > 0) return {
865
+ requests: [],
866
+ errors
867
+ };
868
+ const results = [
869
+ ...selection.type ? [toUnitTypeRequest(rentals)] : [],
870
+ ...parsed.field.map((flag) => toFieldRequest({
871
+ ...flag,
872
+ rentals
873
+ })),
874
+ ...parsed.min.map((flag) => toThresholdRequest({
875
+ ...flag,
876
+ bound: "min",
877
+ rentals
878
+ })),
879
+ ...parsed.max.map((flag) => toThresholdRequest({
880
+ ...flag,
881
+ bound: "max",
882
+ rentals
883
+ }))
884
+ ];
885
+ return {
886
+ requests: results.filter((result) => typeof result !== "string"),
887
+ errors: results.filter((result) => typeof result === "string")
888
+ };
889
+ };
559
890
  const REQUEST_FLAGS = /* @__PURE__ */ new Map([
560
891
  [V9_HUB_OBJECT_GROUP_FILTER_KEY, "--object-group"],
561
892
  [V9_HUB_FACILITY_SEARCH_FILTER_KEY, "--facility"],
893
+ [V9_HUB_REGION_FILTER_KEY, "--region"],
894
+ [V9_HUB_UNIT_TYPE_FILTER_KEY, "--type"],
562
895
  [V9_HUB_OFFERS_FILTER_KEY, "--offers"],
563
896
  [V9_HUB_OFFER_FILTER_KEY, "--offer"]
564
897
  ]);
@@ -568,16 +901,21 @@ const renderMissingHubFilters = (missing) => {
568
901
  const custom = missing.filter((key) => !requestable.includes(key));
569
902
  return [
570
903
  `Missing Hub filters: ${missing.join(", ")}.`,
571
- ...requestable.length === 0 ? [] : [`Run \`website-sdk hub-filters request${flags.map((flag) => ` ${flag}`).join("")}\`; the user adds the entries in the be-on! Hub with the file it writes.`],
572
- ...custom.length === 0 ? [] : [`hub-filters request cannot write entries for ${custom.join(", ")}; a developer adds them in the be-on! Hub.`]
904
+ ...requestable.length === 0 ? [] : [`Run \`website-sdk --backend v9 hub-filters request${flags.map((flag) => ` ${flag}`).join("")}\`; the user adds the entries in the be-on! Hub with the file it writes.`],
905
+ ...custom.length === 0 ? [] : [`For ${custom.join(", ")}, run \`website-sdk --backend v9 hub-filters request --field <key>=<vOffice field>\` for a yes/no field, or --min/--max <key>=<vOffice field> for a number; a developer adds any other entry in the be-on! Hub.`]
573
906
  ].join(" ");
574
907
  };
575
908
  const json = (value) => JSON.stringify(value, null, 2);
576
- const existingHubFilterKeys = ({ keys, hubFilters }) => keys.filter((key) => hubFilters.some((filter) => filter.key === key));
909
+ const isInHub = ({ request, hubFilters }) => hubFilters.some((filter) => filter.key === request.key && (request.hubOptionKeys === void 0 || filter.options.length === request.hubOptionKeys.length && filter.options.every(({ key }) => request.hubOptionKeys?.includes(key))));
910
+ const hasEveryHubFilter = ({ requests, hubFilters }) => requests.every((request) => isInHub({
911
+ request,
912
+ hubFilters
913
+ }));
914
+ const existingHubFilterKeys = ({ requests, hubFilters }) => requests.flatMap(({ key }) => hubFilters.some((filter) => filter.key === key) ? [key] : []);
577
915
  const code = (keys) => keys.map((key) => `\`${key}\``).join(", ");
578
- const renderHubFilterRequest = ({ beOnKey, keys, hubFilters }) => {
916
+ const renderHubFilterRequest = ({ beOnKey, requests, hubFilters }) => {
579
917
  const existing = existingHubFilterKeys({
580
- keys,
918
+ requests,
581
919
  hubFilters
582
920
  });
583
921
  return [
@@ -588,41 +926,74 @@ const renderHubFilterRequest = ({ beOnKey, keys, hubFilters }) => {
588
926
  "Die Website braucht die Filter unten im be-on! Hub. Ohne sie filtert die Suche nicht oder die Website lässt sich nicht bauen.",
589
927
  "",
590
928
  ...existing.length === 0 ? [] : [`> Achtung: Im be-on! Hub stehen für diesen be-on Key schon Filter (${code(existing)}). Den Code unten nicht einfügen, sondern diese Datei an einen Entwickler geben. Er führt die Einträge zusammen.`, ""],
929
+ ...requests.flatMap(({ warning }) => warning === void 0 ? [] : [`> Vor dem Einfügen prüfen: ${warning}`, ""]),
591
930
  "## So geht's",
592
931
  "",
593
932
  `1. Im be-on! Hub den be-on Key \`${beOnKey}\` suchen und öffnen.`,
594
933
  "2. Unten im Bereich „vOffice-Filter“ den Filter bearbeiten. Gibt es dort noch keinen, einen neuen anlegen.",
595
934
  "3. Das Feld „Filter“ muss leer sein. Steht dort schon etwas, nichts ändern und diese Datei an einen Entwickler geben. Er führt die Einträge zusammen.",
596
935
  "4. Den Code unten komplett kopieren, in das leere Feld „Filter“ einfügen und speichern.",
597
- "5. Danach Bescheid geben, dass die Filter eingetragen sind. Die Website prüft dann, ob alles da ist (`website-sdk hub-filters check`).",
936
+ "5. Danach Bescheid geben, dass die Filter eingetragen sind. Die Website prüft dann, ob alles da ist (`website-sdk --backend v9 hub-filters check`).",
598
937
  "",
599
938
  "## Code zum Einfügen",
600
939
  "",
601
940
  "```json",
602
- json(Object.fromEntries(keys.map((key) => [key, HUB_FILTER_REQUESTS[key].entry]))),
941
+ json(Object.fromEntries(requests.map(({ key, entry }) => [key, entry]))),
603
942
  "```",
604
943
  "",
605
944
  "## Was die Filter tun",
606
945
  "",
607
- ...keys.map((key) => `- \`${key}\`: ${HUB_FILTER_REQUESTS[key].purpose}`),
946
+ ...requests.map(({ key, purpose }) => `- \`${key}\`: ${purpose}`),
608
947
  ""
609
948
  ].join("\n");
610
949
  };
611
- const definition = ({ key, de, en, ...rest }) => ({
612
- key,
613
- source: "backendFilter",
614
- category: "OTHER",
615
- label: {
616
- "de-DE": de,
617
- "en-US": en
618
- },
619
- searchable: true,
620
- internal: false,
621
- ...rest
622
- });
623
- const toBackendFilterDefinitions = ({ keys, hubFilters }) => {
950
+ function definition({ key, de, en, ...rest }) {
951
+ return {
952
+ key,
953
+ source: "backendFilter",
954
+ category: "OTHER",
955
+ label: {
956
+ "de-DE": de,
957
+ "en-US": en
958
+ },
959
+ searchable: true,
960
+ internal: false,
961
+ ...rest
962
+ };
963
+ }
964
+ const toTreeOrder = (options) => {
965
+ const keys = new Set(options.map(({ key }) => key));
966
+ const childrenOf = (parent) => options.filter((option) => parent === null ? option.parent == null || !keys.has(option.parent) : option.parent === parent);
967
+ const visit = (parent) => childrenOf(parent).flatMap((option) => [option, ...visit(option.key)]);
968
+ return visit(null);
969
+ };
970
+ const hubOptionDefinition = ({ key, de, en, placeholder, hubFilters, tree }) => {
971
+ const hubOptions = hubFilters.find((filter) => filter.key === key)?.options ?? [];
972
+ const [first, ...others] = (tree ? toTreeOrder(hubOptions) : hubOptions).map(({ key, value }) => ({
973
+ value: key,
974
+ label: label(value ?? key)
975
+ }));
976
+ return {
977
+ hasOptions: first !== void 0,
978
+ definition: definition({
979
+ key,
980
+ de,
981
+ en,
982
+ type: "option",
983
+ options: first === void 0 ? [{
984
+ value: placeholder,
985
+ label: {
986
+ "de-DE": "<Name>",
987
+ "en-US": "<name>"
988
+ }
989
+ }] : [first, ...others]
990
+ })
991
+ };
992
+ };
993
+ const toBackendFilterDefinitions = ({ requests, hubFilters }) => {
624
994
  const definitions = [];
625
995
  const notes = [];
996
+ const keys = requests.map(({ key }) => key);
626
997
  if (keys.includes("objectGroup")) {
627
998
  definitions.push(definition({
628
999
  key: V9_HUB_OBJECT_GROUP_FILTER_KEY,
@@ -640,27 +1011,28 @@ const toBackendFilterDefinitions = ({ keys, hubFilters }) => {
640
1011
  notes.push(`${V9_HUB_OBJECT_GROUP_FILTER_KEY}: add one option per group. The value is the vOffice object group ID; the labels are the group names your site keeps, the Hub returns none.`);
641
1012
  }
642
1013
  if (keys.includes("facility_search")) {
643
- const [firstFacilityOption, ...otherFacilityOptions] = (hubFilters.find(({ key }) => key === "facility_search")?.options ?? []).map(({ key, value }) => ({
644
- value: key,
645
- label: {
646
- "de-DE": value ?? key,
647
- "en-US": value ?? key
648
- }
649
- }));
650
- definitions.push(definition({
1014
+ const facility = hubOptionDefinition({
651
1015
  key: V9_HUB_FACILITY_SEARCH_FILTER_KEY,
652
1016
  de: "Ferienanlage",
653
1017
  en: "Facility",
654
- type: "option",
655
- options: firstFacilityOption === void 0 ? [{
656
- value: "<vOffice facility ID>",
657
- label: {
658
- "de-DE": "<Name>",
659
- "en-US": "<name>"
660
- }
661
- }] : [firstFacilityOption, ...otherFacilityOptions]
662
- }));
663
- notes.push(firstFacilityOption === void 0 ? `${V9_HUB_FACILITY_SEARCH_FILTER_KEY}: the Hub has no options for this key yet. Run this command again once the Hub entry is saved.` : `${V9_HUB_FACILITY_SEARCH_FILTER_KEY}: options come from the Hub (vOffice facility IDs, not rental.property.id). The English labels are the German names; translate them.`);
1018
+ placeholder: "<vOffice facility ID>",
1019
+ hubFilters,
1020
+ tree: false
1021
+ });
1022
+ definitions.push(facility.definition);
1023
+ notes.push(facility.hasOptions ? `${V9_HUB_FACILITY_SEARCH_FILTER_KEY}: options come from the Hub (vOffice facility IDs, not rental.property.id). The English labels are the German names; translate them.` : `${V9_HUB_FACILITY_SEARCH_FILTER_KEY}: the Hub has no options for this key yet. Run this command again once the Hub entry is saved.`);
1024
+ }
1025
+ if (keys.includes("region")) {
1026
+ const region = hubOptionDefinition({
1027
+ key: V9_HUB_REGION_FILTER_KEY,
1028
+ de: "Region",
1029
+ en: "Region",
1030
+ placeholder: "<vOffice region ID>",
1031
+ hubFilters,
1032
+ tree: true
1033
+ });
1034
+ definitions.push(region.definition);
1035
+ notes.push(region.hasOptions ? `${V9_HUB_REGION_FILTER_KEY}: options come from the Hub (vOffice region IDs), each region before its subregions; a region also finds the rentals of its subregions. Drop the regions the site does not offer. The English labels are the German names; translate them.` : `${V9_HUB_REGION_FILTER_KEY}: the Hub has no options for this key yet. Run this command again once the Hub entry is saved.`);
664
1036
  }
665
1037
  if (keys.includes("offers")) definitions.push(definition({
666
1038
  key: V9_HUB_OFFERS_FILTER_KEY,
@@ -678,31 +1050,45 @@ const toBackendFilterDefinitions = ({ keys, hubFilters }) => {
678
1050
  }));
679
1051
  notes.push(`${V9_HUB_OFFER_FILTER_KEY}: the value is one vOffice offer ID.`);
680
1052
  }
1053
+ for (const request of requests) {
1054
+ if (request.definition !== void 0) definitions.push(request.definition);
1055
+ if (request.note !== void 0) notes.push(request.note);
1056
+ }
681
1057
  return {
682
1058
  definitions,
683
1059
  notes
684
1060
  };
685
1061
  };
686
- const renderRequestSummary = ({ file, keys, hubFilters }) => {
1062
+ const renderDefinitions = ({ requests, hubFilters }) => {
687
1063
  const { definitions, notes } = toBackendFilterDefinitions({
688
- keys,
1064
+ requests,
689
1065
  hubFilters
690
1066
  });
1067
+ return definitions.length === 0 ? [] : [
1068
+ "",
1069
+ "Add these to customAttributeFilterDefinitions. Replace a definition with the same key instead of adding a second one:",
1070
+ json(definitions),
1071
+ ...notes.length === 0 ? [] : ["", ...notes.map((note) => `- ${note}`)]
1072
+ ];
1073
+ };
1074
+ const renderRequestSummary = ({ file, requests, hubFilters }) => {
691
1075
  const existing = existingHubFilterKeys({
692
- keys,
1076
+ requests,
693
1077
  hubFilters
694
1078
  });
695
1079
  return [
696
- `Wrote ${file}. Show the user its steps and code: they paste the code into the be-on! Hub themselves. Once they have saved it, run \`website-sdk hub-filters check\`; when it passes, delete ${file}.`,
1080
+ `Wrote ${file}. Show the user its steps and code: they paste the code into the be-on! Hub themselves. Once they have saved it, run \`website-sdk --backend v9 hub-filters check\`; when it passes, delete ${file}.`,
697
1081
  ...existing.length === 0 ? [] : [`The be-on! Hub already has ${existing.join(", ")} for this be-on key, so its filter field is not empty: the file asks the user to hand it to a developer instead.`],
698
- ...definitions.length === 0 ? [] : [
699
- "",
700
- "Add these to customAttributeFilterDefinitions:",
701
- json(definitions),
702
- ...notes.length === 0 ? [] : ["", ...notes.map((note) => `- ${note}`)]
703
- ]
1082
+ ...renderDefinitions({
1083
+ requests,
1084
+ hubFilters
1085
+ })
704
1086
  ].join("\n");
705
1087
  };
1088
+ const renderExistingSummary = ({ requests, hubFilters }) => [`The be-on! Hub already has ${requests.map(({ key }) => key).join(", ")}. No file written; run \`website-sdk --backend v9 hub-filters check\`.`, ...renderDefinitions({
1089
+ requests,
1090
+ hubFilters
1091
+ })].join("\n");
706
1092
  //#endregion
707
1093
  //#region src/cli/commands/v9-hub-filters.ts
708
1094
  const DEFAULT_REQUEST_FILE = "hub-filter-request.md";
@@ -719,6 +1105,13 @@ const loadHubFilters = (config) => Effect.tryPromise({
719
1105
  try: () => fetchV9HubFilters(config),
720
1106
  catch: (cause) => toCLIError("Failed to read the Hub filters", cause)
721
1107
  });
1108
+ const loadRentalData = ({ config, attributes }) => Effect.tryPromise({
1109
+ try: () => fetchV9HubRentalData({
1110
+ config,
1111
+ attributes
1112
+ }),
1113
+ catch: (cause) => toCLIError("Failed to read the rentals from the Hub", cause)
1114
+ });
722
1115
  const writeTextFile = ({ path, text }) => Effect.tryPromise({
723
1116
  try: async () => {
724
1117
  const { writeFile } = await import("node:fs/promises");
@@ -727,6 +1120,7 @@ const writeTextFile = ({ path, text }) => Effect.tryPromise({
727
1120
  catch: (cause) => toCLIError(`Failed to write ${path}`, cause)
728
1121
  });
729
1122
  const flag = ({ name, description }) => Flag.Boolean(name).pipe(Flag.withDescription(description), Flag.withDefault(false));
1123
+ const fieldFlag = ({ name, description }) => Flag.String(name).pipe(Flag.withDescription(description), Flag.atLeast(0));
730
1124
  const request = Command.make("request", {
731
1125
  objectGroup: flag({
732
1126
  name: "object-group",
@@ -736,6 +1130,26 @@ const request = Command.make("request", {
736
1130
  name: "facility",
737
1131
  description: "Request the facility filter (facility_search)."
738
1132
  }),
1133
+ region: flag({
1134
+ name: "region",
1135
+ description: "Request the region filter (region); a region includes its subregions."
1136
+ }),
1137
+ type: flag({
1138
+ name: "type",
1139
+ description: "Request the property type filter (type), with the types the rentals have."
1140
+ }),
1141
+ field: fieldFlag({
1142
+ name: "field",
1143
+ description: "Request a yes/no filter on vOffice rental fields, as <key>=<field>[,<field>...]; several fields match with OR. Repeatable."
1144
+ }),
1145
+ min: fieldFlag({
1146
+ name: "min",
1147
+ description: "Request a filter for rentals whose vOffice field is at least the given number, as <key>=<field>. Repeatable."
1148
+ }),
1149
+ max: fieldFlag({
1150
+ name: "max",
1151
+ description: "Request a filter for rentals whose vOffice field is at most the given number, as <key>=<field>. Repeatable."
1152
+ }),
739
1153
  offers: flag({
740
1154
  name: "offers",
741
1155
  description: "Request the filter for units with any special offer (offers)."
@@ -749,39 +1163,72 @@ const request = Command.make("request", {
749
1163
  description: "Request the filter by vOffice unit ID, the favourites search (voffice_id)."
750
1164
  }),
751
1165
  out: Flag.String("out").pipe(Flag.withDescription("Path of the Markdown file to write."), Flag.withDefault(DEFAULT_REQUEST_FILE))
752
- }, ({ out, ...selection }) => Effect.gen(function* () {
1166
+ }, ({ out, type, field, min, max, ...selection }) => Effect.gen(function* () {
753
1167
  const root = yield* websiteSdkCommand;
754
1168
  const { config, options } = yield* loadV9Context(root);
755
- const keys = toRequestedHubFilterKeys({
1169
+ const rentalDataSelection = {
1170
+ type,
1171
+ field,
1172
+ min,
1173
+ max
1174
+ };
1175
+ const { attributes, errors } = toRentalDataAttributes(rentalDataSelection);
1176
+ if (errors.length > 0) return yield* Effect.fail(new CLICheckFailed(errors.join(" ")));
1177
+ const fixedRequests = toFixedHubFilterRequests(toRequestedHubFilterKeys({
756
1178
  selection,
757
1179
  sdkOwnedKeys: toV9SdkOwnedHubFilterKeys({
758
1180
  config,
759
1181
  rentalScope: options?.rentalScope
760
1182
  })
761
- });
762
- if (keys.length === 0) return yield* Console.log("Nothing to request: pass --object-group, --facility, --offers, --offer or --unit. No file written.");
1183
+ }));
1184
+ if (fixedRequests.length === 0 && attributes.length === 0) return yield* Console.log("Nothing to request: pass --object-group, --facility, --region, --type, --field, --min, --max, --offers, --offer or --unit. No file written.");
763
1185
  const hubFilters = yield* loadHubFilters(config);
764
- if (keys.every((key) => hubFilters.some((filter) => filter.key === key))) return yield* Console.log(`The be-on! Hub already has ${keys.join(", ")}. No file written; run \`website-sdk hub-filters check\`.`);
1186
+ const rentalData = attributes.length === 0 ? {
1187
+ requests: [],
1188
+ errors: []
1189
+ } : toRentalDataHubFilterRequests({
1190
+ selection: rentalDataSelection,
1191
+ rentals: yield* loadRentalData({
1192
+ config,
1193
+ attributes
1194
+ })
1195
+ });
1196
+ if (rentalData.errors.length > 0) return yield* Effect.fail(new CLICheckFailed(`${rentalData.errors.join(" ")} No file written.`));
1197
+ const requests = [...fixedRequests, ...rentalData.requests];
1198
+ if (hasEveryHubFilter({
1199
+ requests,
1200
+ hubFilters
1201
+ })) return yield* Console.log(renderExistingSummary({
1202
+ requests,
1203
+ hubFilters
1204
+ }));
765
1205
  yield* writeTextFile({
766
1206
  path: out,
767
1207
  text: renderHubFilterRequest({
768
1208
  beOnKey: config.apiKey,
769
- keys,
1209
+ requests,
770
1210
  hubFilters
771
1211
  })
772
1212
  });
773
1213
  yield* Console.log(renderRequestSummary({
774
1214
  file: out,
775
- keys,
1215
+ requests,
776
1216
  hubFilters
777
1217
  }));
778
- })).pipe(Command.withDescription("Write a Markdown file with the be-on! Hub filters this site needs and how to add them."), Command.withExamples([{
779
- command: "website-sdk --backend v9 hub-filters request --object-group --offers",
780
- description: "Write hub-filter-request.md for an object group and an offers filter."
781
- }, {
782
- command: "website-sdk --backend v9 --config ./config.json --options ./options.json hub-filters request --out ./request.md",
783
- description: "Request the scope and favourites filters the configuration already implies."
784
- }]));
1218
+ })).pipe(Command.withDescription("Write a Markdown file with the be-on! Hub filters this site needs and how to add them."), Command.withExamples([
1219
+ {
1220
+ command: "website-sdk --backend v9 hub-filters request --object-group --offers",
1221
+ description: "Write hub-filter-request.md for an object group and an offers filter."
1222
+ },
1223
+ {
1224
+ command: "website-sdk --backend v9 hub-filters request --region --field reet=p_14418 --max beachdistance_max=beachdistance",
1225
+ description: "Request a region select, a yes/no filter on a vOffice field and a maximum beach distance."
1226
+ },
1227
+ {
1228
+ command: "website-sdk --backend v9 --config ./config.json --options ./options.json hub-filters request --out ./request.md",
1229
+ description: "Request the scope and favourites filters the configuration already implies."
1230
+ }
1231
+ ]));
785
1232
  const check = Command.make("check", {}, () => Effect.gen(function* () {
786
1233
  const root = yield* websiteSdkCommand;
787
1234
  const { config, options } = yield* loadV9Context(root);
@@ -805,7 +1252,19 @@ const check = Command.make("check", {}, () => Effect.gen(function* () {
805
1252
  command: "website-sdk --backend v9 --config ./config.json --options ./options.json hub-filters check",
806
1253
  description: "Compare backend filters, the scope key and voffice_id with the Hub."
807
1254
  }]));
808
- const hubFiltersCommand = Command.make("hub-filters").pipe(Command.withDescription("Request and check be-on! Hub filters for v9 sites."), Command.withSubcommands([request, check]));
1255
+ const fields = Command.make("fields", { search: Flag.String("search").pipe(Flag.withDescription("Part of the field name or of its German or English label."), Flag.withDefault("")) }, ({ search }) => Effect.gen(function* () {
1256
+ const root = yield* websiteSdkCommand;
1257
+ if (root.backend !== "v9") return yield* Effect.fail(new CLICheckFailed("hub-filters requires --backend v9."));
1258
+ yield* printOutput(root, searchV9UnitFields(search));
1259
+ })).pipe(Command.withDescription("List the standard vOffice rental fields for --field (BOOL) and --min/--max (INT), with their labels. An agency's own features (p_<number>) are listed at https://api.v-office.com/export/properties?key=<the agency's vOffice key>."), Command.withExamples([{
1260
+ command: "website-sdk --backend v9 hub-filters fields --search kamin",
1261
+ description: "Find the field for a fireplace: fireside (Kamin/Ofen), not fireplace (Feuerstelle)."
1262
+ }]));
1263
+ const hubFiltersCommand = Command.make("hub-filters").pipe(Command.withDescription("Request and check be-on! Hub filters for v9 sites."), Command.withSubcommands([
1264
+ request,
1265
+ check,
1266
+ fields
1267
+ ]));
809
1268
  //#endregion
810
1269
  //#region src/cli/index.ts
811
1270
  const cliCommand = websiteSdkCommand.pipe(Command.withSubcommands([