@adatechnology/channel-sync-module 0.0.0-stage → 0.1.0

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/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @adatechnology/channel-sync-module
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sincronização com channel manager independente do fornecedor (Beds24 hoje, Channex depois), sobre o `ChannelSyncPort`
4
+ de `@adatechnology/scheduling-contracts`.
5
+
6
+ O produto continua dono da regra de negócio: ele diz quais estadias vende e por quanto (`ArrivalStay`, uma por dia de
7
+ entrada, com o total que o site cobraria). O módulo transforma isso no que um portal entende.
8
+
9
+ ```ts
10
+ import { buildChannelInventory } from '@adatechnology/channel-sync-module'
11
+
12
+ const plan = buildChannelInventory({
13
+ fromDate: '2027-01-01',
14
+ untilDate: '2027-04-01',
15
+ stays, // entradas até 30 dias antes e depois da janela, para acertar as pontas
16
+ unitCount: 1,
17
+ occupiedUnits, // Map<'YYYY-MM-DD', unidades tomadas>
18
+ closedDates, // Set de dias fechados
19
+ noDepartureDates, // Set de dias sem saída (folga da equipe)
20
+ })
21
+ await channel.pushInventory({ updates: [{ externalRoomId, days: plan.days }] })
22
+ // plan.priceMismatches: entradas cujo total no portal difere do preço do produto (mostre antes de ligar)
23
+ ```
24
+
25
+ Regras:
26
+
27
+ - **Diária** = total da menor estadia que cobre a noite ÷ noites (o pacote de fim de semana vence o longo do meio da semana).
28
+ - **Estadia mínima** = noites da estadia daquela entrada; **máxima** igual quando a saída é fixa.
29
+ - **Sem entrada** = dia sem estadia; **sem saída** = dia em que nenhuma estadia fixa termina e nenhuma flexível já poderia
30
+ ter terminado, ou folga de saída.
31
+ - **Divergência**: toda entrada cuja soma das diárias se afasta do preço do produto em mais de 1 centavo por noite.
32
+
33
+ Próximas peças (mesmo pacote): fila de envio coalescida por quarto sobre o `job-queue-module` respeitando a cota do
34
+ fornecedor, recebimento do webhook com releitura, reconciliação periódica e a ligação recurso ↔ quarto em schema próprio.
package/dist/index.cjs ADDED
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ buildChannelInventory: () => buildChannelInventory
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/civilDates.ts
29
+ var DAY_MS = 864e5;
30
+ function addDays(date, days) {
31
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);
32
+ }
33
+ __name(addDays, "addDays");
34
+ function listDates(from, until) {
35
+ const dates = [];
36
+ for (let date = from; date < until; date = addDays(date, 1)) dates.push(date);
37
+ return dates;
38
+ }
39
+ __name(listDates, "listDates");
40
+
41
+ // src/buildChannelInventory.ts
42
+ function nightsOf(stay) {
43
+ return Array.from({
44
+ length: stay.nights
45
+ }, (_, index) => addDays(stay.arrival, index));
46
+ }
47
+ __name(nightsOf, "nightsOf");
48
+ function nightlyPrices(stays) {
49
+ const chosen = /* @__PURE__ */ new Map();
50
+ for (const stay of stays) {
51
+ for (const night of nightsOf(stay)) {
52
+ const current = chosen.get(night);
53
+ if (!current || stay.nights < current.nights) chosen.set(night, stay);
54
+ }
55
+ }
56
+ return new Map([
57
+ ...chosen
58
+ ].map(([night, stay]) => [
59
+ night,
60
+ Math.round(stay.totalCents / stay.nights)
61
+ ]));
62
+ }
63
+ __name(nightlyPrices, "nightlyPrices");
64
+ function findMismatches(params) {
65
+ return params.stays.flatMap((stay) => {
66
+ const channelCents = nightsOf(stay).reduce((sum, night) => sum + (params.prices.get(night) ?? 0), 0);
67
+ if (Math.abs(channelCents - stay.totalCents) <= stay.nights) return [];
68
+ return [
69
+ {
70
+ arrival: stay.arrival,
71
+ nights: stay.nights,
72
+ productCents: stay.totalCents,
73
+ channelCents
74
+ }
75
+ ];
76
+ });
77
+ }
78
+ __name(findMismatches, "findMismatches");
79
+ function buildDepartureCheck(params) {
80
+ const ends = /* @__PURE__ */ __name((stay) => addDays(stay.arrival, stay.nights), "ends");
81
+ const fixedEnds = new Set(params.stays.filter((stay) => stay.isFixedLength).map(ends));
82
+ const earliestFlexibleEnd = params.stays.filter((stay) => !stay.isFixedLength).map(ends).sort()[0];
83
+ return (date) => {
84
+ if (params.noDepartureDates?.has(date)) return false;
85
+ return fixedEnds.has(date) || earliestFlexibleEnd !== void 0 && date >= earliestFlexibleEnd;
86
+ };
87
+ }
88
+ __name(buildDepartureCheck, "buildDepartureCheck");
89
+ function assertStays(stays) {
90
+ const arrivals = /* @__PURE__ */ new Set();
91
+ for (const stay of stays) {
92
+ if (!Number.isInteger(stay.nights) || stay.nights < 1) throw new RangeError(`noites inv\xE1lidas em ${stay.arrival}`);
93
+ if (!Number.isInteger(stay.totalCents) || stay.totalCents < 0) throw new RangeError(`pre\xE7o inv\xE1lido em ${stay.arrival}`);
94
+ if (arrivals.has(stay.arrival)) throw new RangeError(`duas estadias para a mesma entrada: ${stay.arrival}`);
95
+ arrivals.add(stay.arrival);
96
+ }
97
+ }
98
+ __name(assertStays, "assertStays");
99
+ function buildChannelInventory(params) {
100
+ assertStays(params.stays);
101
+ const unitCount = params.unitCount ?? 1;
102
+ const prices = nightlyPrices(params.stays);
103
+ const canDepart = buildDepartureCheck(params);
104
+ const stayByArrival = new Map(params.stays.map((stay) => [
105
+ stay.arrival,
106
+ stay
107
+ ]));
108
+ const days = listDates(params.fromDate, params.untilDate).map((date) => {
109
+ const closed = params.closedDates?.has(date) ?? false;
110
+ const stay = stayByArrival.get(date);
111
+ const free = Math.max(unitCount - (params.occupiedUnits.get(date) ?? 0), 0);
112
+ return {
113
+ date,
114
+ available: closed ? 0 : free,
115
+ closed,
116
+ priceCents: prices.get(date),
117
+ minStay: stay?.nights,
118
+ maxStay: stay?.isFixedLength ? stay.nights : void 0,
119
+ closedToArrival: stay === void 0,
120
+ closedToDeparture: !canDepart(date)
121
+ };
122
+ });
123
+ const windowStays = params.stays.filter((stay) => stay.arrival >= params.fromDate && stay.arrival < params.untilDate);
124
+ return {
125
+ days,
126
+ priceMismatches: findMismatches({
127
+ stays: windowStays,
128
+ prices
129
+ })
130
+ };
131
+ }
132
+ __name(buildChannelInventory, "buildChannelInventory");
133
+ // Annotate the CommonJS export names for ESM import in node:
134
+ 0 && (module.exports = {
135
+ buildChannelInventory
136
+ });
137
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/civilDates.ts","../src/buildChannelInventory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { buildChannelInventory } from './buildChannelInventory'\nexport type {\n ArrivalStay,\n BuildChannelInventoryParams,\n ChannelInventoryPlan,\n ChannelPriceMismatch,\n} from './channelInventory.types'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Datas civis `YYYY-MM-DD` em UTC: a diária não tem fuso.\n */\n\nimport type { CivilDate } from '@adatechnology/scheduling-contracts'\n\nconst DAY_MS = 86_400_000\n\nexport function addDays(date: CivilDate, days: number): CivilDate {\n return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10)\n}\n\nexport function listDates(from: CivilDate, until: CivilDate): CivilDate[] {\n const dates: CivilDate[] = []\n for (let date = from; date < until; date = addDays(date, 1)) dates.push(date)\n return dates\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Estadias do produto → o que um portal entende: diária por noite, estadia mínima e máxima, sem entrada, sem\n * saída e fechado. A noite pega o preço da menor estadia que a cobre (o pacote de fim de semana vence o longo\n * do meio da semana); toda entrada cujo total no portal se afasta do preço do produto é apontada, nunca escondida.\n */\n\nimport type { ChannelDayInventory, CivilDate } from '@adatechnology/scheduling-contracts'\n\nimport type {\n ArrivalStay,\n BuildChannelInventoryParams,\n ChannelInventoryPlan,\n ChannelPriceMismatch,\n} from './channelInventory.types'\nimport { addDays, listDates } from './civilDates'\n\nfunction nightsOf(stay: ArrivalStay): CivilDate[] {\n return Array.from({ length: stay.nights }, (_, index) => addDays(stay.arrival, index))\n}\n\nfunction nightlyPrices(stays: readonly ArrivalStay[]): Map<CivilDate, number> {\n const chosen = new Map<CivilDate, ArrivalStay>()\n for (const stay of stays) {\n for (const night of nightsOf(stay)) {\n const current = chosen.get(night)\n if (!current || stay.nights < current.nights) chosen.set(night, stay)\n }\n }\n return new Map([...chosen].map(([night, stay]) => [night, Math.round(stay.totalCents / stay.nights)]))\n}\n\n// Arredondar a diária move o total em até um centavo por noite: só diferença maior é divergência.\nfunction findMismatches(params: {\n readonly stays: readonly ArrivalStay[]\n readonly prices: ReadonlyMap<CivilDate, number>\n}): ChannelPriceMismatch[] {\n return params.stays.flatMap((stay) => {\n const channelCents = nightsOf(stay).reduce((sum, night) => sum + (params.prices.get(night) ?? 0), 0)\n if (Math.abs(channelCents - stay.totalCents) <= stay.nights) return []\n return [{ arrival: stay.arrival, nights: stay.nights, productCents: stay.totalCents, channelCents }]\n })\n}\n\n// Dá para sair num dia quando alguma estadia fixa termina nele ou uma flexível já poderia ter terminado.\nfunction buildDepartureCheck(params: BuildChannelInventoryParams): (date: CivilDate) => boolean {\n const ends = (stay: ArrivalStay): CivilDate => addDays(stay.arrival, stay.nights)\n const fixedEnds = new Set(params.stays.filter((stay) => stay.isFixedLength).map(ends))\n const earliestFlexibleEnd = params.stays\n .filter((stay) => !stay.isFixedLength)\n .map(ends)\n .sort()[0]\n return (date) => {\n if (params.noDepartureDates?.has(date)) return false\n return fixedEnds.has(date) || (earliestFlexibleEnd !== undefined && date >= earliestFlexibleEnd)\n }\n}\n\nfunction assertStays(stays: readonly ArrivalStay[]): void {\n const arrivals = new Set<CivilDate>()\n for (const stay of stays) {\n if (!Number.isInteger(stay.nights) || stay.nights < 1) throw new RangeError(`noites inválidas em ${stay.arrival}`)\n if (!Number.isInteger(stay.totalCents) || stay.totalCents < 0)\n throw new RangeError(`preço inválido em ${stay.arrival}`)\n if (arrivals.has(stay.arrival)) throw new RangeError(`duas estadias para a mesma entrada: ${stay.arrival}`)\n arrivals.add(stay.arrival)\n }\n}\n\nexport function buildChannelInventory(params: BuildChannelInventoryParams): ChannelInventoryPlan {\n assertStays(params.stays)\n const unitCount = params.unitCount ?? 1\n const prices = nightlyPrices(params.stays)\n const canDepart = buildDepartureCheck(params)\n const stayByArrival = new Map(params.stays.map((stay) => [stay.arrival, stay]))\n const days = listDates(params.fromDate, params.untilDate).map((date): ChannelDayInventory => {\n const closed = params.closedDates?.has(date) ?? false\n const stay = stayByArrival.get(date)\n const free = Math.max(unitCount - (params.occupiedUnits.get(date) ?? 0), 0)\n return {\n date,\n available: closed ? 0 : free,\n closed,\n priceCents: prices.get(date),\n minStay: stay?.nights,\n maxStay: stay?.isFixedLength ? stay.nights : undefined,\n closedToArrival: stay === undefined,\n closedToDeparture: !canDepart(date),\n }\n })\n const windowStays = params.stays.filter((stay) => stay.arrival >= params.fromDate && stay.arrival < params.untilDate)\n return { days, priceMismatches: findMismatches({ stays: windowStays, prices }) }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;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ACxB,QAAMuC,YAAY3B,OAAO2B,aAAa;AACtC,QAAMtB,SAASlB,cAAca,OAAOZ,KAAK;AACzC,QAAMwC,YAAYpB,oBAAoBR,MAAAA;AACtC,QAAM6B,gBAAgB,IAAIvC,IAAIU,OAAOZ,MAAMO,IAAI,CAACjB,SAAS;IAACA,KAAKQ;IAASR;GAAK,CAAA;AAC7E,QAAMoD,OAAOC,UAAU/B,OAAOgC,UAAUhC,OAAOiC,SAAS,EAAEtC,IAAI,CAACqB,SAAAA;AAC7D,UAAMkB,SAASlC,OAAOmC,aAAajB,IAAIF,IAAAA,KAAS;AAChD,UAAMtC,OAAOmD,cAAcpC,IAAIuB,IAAAA;AAC/B,UAAMoB,OAAOxC,KAAKyC,IAAIV,aAAa3B,OAAOsC,cAAc7C,IAAIuB,IAAAA,KAAS,IAAI,CAAA;AACzE,WAAO;MACLA;MACAuB,WAAWL,SAAS,IAAIE;MACxBF;MACAM,YAAYnC,OAAOZ,IAAIuB,IAAAA;MACvByB,SAAS/D,MAAMI;MACf4D,SAAShE,MAAMmC,gBAAgBnC,KAAKI,SAASqC;MAC7CwB,iBAAiBjE,SAASyC;MAC1ByB,mBAAmB,CAAChB,UAAUZ,IAAAA;IAChC;EACF,CAAA;AACA,QAAM6B,cAAc7C,OAAOZ,MAAMwB,OAAO,CAAClC,SAASA,KAAKQ,WAAWc,OAAOgC,YAAYtD,KAAKQ,UAAUc,OAAOiC,SAAS;AACpH,SAAO;IAAEH;IAAMgB,iBAAiB/C,eAAe;MAAEX,OAAOyD;MAAaxC;IAAO,CAAA;EAAG;AACjF;AAvBgBqB;","names":["DAY_MS","addDays","date","days","Date","parse","toISOString","slice","listDates","from","until","dates","push","nightsOf","stay","Array","from","length","nights","_","index","addDays","arrival","nightlyPrices","stays","chosen","Map","night","current","get","set","map","Math","round","totalCents","findMismatches","params","flatMap","channelCents","reduce","sum","prices","abs","productCents","buildDepartureCheck","ends","fixedEnds","Set","filter","isFixedLength","earliestFlexibleEnd","sort","date","noDepartureDates","has","undefined","assertStays","arrivals","Number","isInteger","RangeError","add","buildChannelInventory","unitCount","canDepart","stayByArrival","days","listDates","fromDate","untilDate","closed","closedDates","free","max","occupiedUnits","available","priceCents","minStay","maxStay","closedToArrival","closedToDeparture","windowStays","priceMismatches"]}
@@ -0,0 +1,58 @@
1
+ import { CivilDate, ChannelDayInventory } from '@adatechnology/scheduling-contracts';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+
7
+ /**
8
+ * Uma estadia que o produto vende para uma entrada em `arrival`, com o preço que o site cobraria. A regra
9
+ * de negócio (temporada, perfil, pacote) fica no produto: aqui chega só o resultado.
10
+ */
11
+ type ArrivalStay = {
12
+ readonly arrival: CivilDate;
13
+ readonly nights: number;
14
+ /** A saída é fixa (ex.: sempre no domingo): vira estadia máxima igual à mínima. */
15
+ readonly isFixedLength: boolean;
16
+ readonly totalCents: number;
17
+ };
18
+ /** Os portais somam diárias; um preço por estadia pode não fechar igual para toda entrada. */
19
+ type ChannelPriceMismatch = {
20
+ readonly arrival: CivilDate;
21
+ readonly nights: number;
22
+ readonly productCents: number;
23
+ readonly channelCents: number;
24
+ };
25
+ type BuildChannelInventoryParams = {
26
+ /** Primeiro dia (inclusivo) e último (exclusivo) enviados ao channel manager. */
27
+ readonly fromDate: CivilDate;
28
+ readonly untilDate: CivilDate;
29
+ /**
30
+ * Toda estadia que o produto vende, incluindo entradas até 30 dias antes e depois da janela: elas decidem a
31
+ * diária e a saída nas pontas.
32
+ */
33
+ readonly stays: readonly ArrivalStay[];
34
+ /** Unidades iguais do quarto (chalé avulso = 1). */
35
+ readonly unitCount?: number | undefined;
36
+ /** Quantas unidades já estão tomadas em cada noite (reserva confirmada, pré-reserva, bloqueio, portal). */
37
+ readonly occupiedUnits: ReadonlyMap<CivilDate, number>;
38
+ /** Dias fechados para tudo (reforma, data bloqueada). */
39
+ readonly closedDates?: ReadonlySet<CivilDate> | undefined;
40
+ /** Dias em que ninguém pode sair (folga da equipe na saída). */
41
+ readonly noDepartureDates?: ReadonlySet<CivilDate> | undefined;
42
+ };
43
+ type ChannelInventoryPlan = {
44
+ readonly days: readonly ChannelDayInventory[];
45
+ readonly priceMismatches: readonly ChannelPriceMismatch[];
46
+ };
47
+
48
+ /**
49
+ * Copyright (c) 2026 Ada Technology. MIT License.
50
+ *
51
+ * Estadias do produto → o que um portal entende: diária por noite, estadia mínima e máxima, sem entrada, sem
52
+ * saída e fechado. A noite pega o preço da menor estadia que a cobre (o pacote de fim de semana vence o longo
53
+ * do meio da semana); toda entrada cujo total no portal se afasta do preço do produto é apontada, nunca escondida.
54
+ */
55
+
56
+ declare function buildChannelInventory(params: BuildChannelInventoryParams): ChannelInventoryPlan;
57
+
58
+ export { type ArrivalStay, type BuildChannelInventoryParams, type ChannelInventoryPlan, type ChannelPriceMismatch, buildChannelInventory };
@@ -0,0 +1,58 @@
1
+ import { CivilDate, ChannelDayInventory } from '@adatechnology/scheduling-contracts';
2
+
3
+ /**
4
+ * Copyright (c) 2026 Ada Technology. MIT License.
5
+ */
6
+
7
+ /**
8
+ * Uma estadia que o produto vende para uma entrada em `arrival`, com o preço que o site cobraria. A regra
9
+ * de negócio (temporada, perfil, pacote) fica no produto: aqui chega só o resultado.
10
+ */
11
+ type ArrivalStay = {
12
+ readonly arrival: CivilDate;
13
+ readonly nights: number;
14
+ /** A saída é fixa (ex.: sempre no domingo): vira estadia máxima igual à mínima. */
15
+ readonly isFixedLength: boolean;
16
+ readonly totalCents: number;
17
+ };
18
+ /** Os portais somam diárias; um preço por estadia pode não fechar igual para toda entrada. */
19
+ type ChannelPriceMismatch = {
20
+ readonly arrival: CivilDate;
21
+ readonly nights: number;
22
+ readonly productCents: number;
23
+ readonly channelCents: number;
24
+ };
25
+ type BuildChannelInventoryParams = {
26
+ /** Primeiro dia (inclusivo) e último (exclusivo) enviados ao channel manager. */
27
+ readonly fromDate: CivilDate;
28
+ readonly untilDate: CivilDate;
29
+ /**
30
+ * Toda estadia que o produto vende, incluindo entradas até 30 dias antes e depois da janela: elas decidem a
31
+ * diária e a saída nas pontas.
32
+ */
33
+ readonly stays: readonly ArrivalStay[];
34
+ /** Unidades iguais do quarto (chalé avulso = 1). */
35
+ readonly unitCount?: number | undefined;
36
+ /** Quantas unidades já estão tomadas em cada noite (reserva confirmada, pré-reserva, bloqueio, portal). */
37
+ readonly occupiedUnits: ReadonlyMap<CivilDate, number>;
38
+ /** Dias fechados para tudo (reforma, data bloqueada). */
39
+ readonly closedDates?: ReadonlySet<CivilDate> | undefined;
40
+ /** Dias em que ninguém pode sair (folga da equipe na saída). */
41
+ readonly noDepartureDates?: ReadonlySet<CivilDate> | undefined;
42
+ };
43
+ type ChannelInventoryPlan = {
44
+ readonly days: readonly ChannelDayInventory[];
45
+ readonly priceMismatches: readonly ChannelPriceMismatch[];
46
+ };
47
+
48
+ /**
49
+ * Copyright (c) 2026 Ada Technology. MIT License.
50
+ *
51
+ * Estadias do produto → o que um portal entende: diária por noite, estadia mínima e máxima, sem entrada, sem
52
+ * saída e fechado. A noite pega o preço da menor estadia que a cobre (o pacote de fim de semana vence o longo
53
+ * do meio da semana); toda entrada cujo total no portal se afasta do preço do produto é apontada, nunca escondida.
54
+ */
55
+
56
+ declare function buildChannelInventory(params: BuildChannelInventoryParams): ChannelInventoryPlan;
57
+
58
+ export { type ArrivalStay, type BuildChannelInventoryParams, type ChannelInventoryPlan, type ChannelPriceMismatch, buildChannelInventory };
package/dist/index.js ADDED
@@ -0,0 +1,112 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/civilDates.ts
5
+ var DAY_MS = 864e5;
6
+ function addDays(date, days) {
7
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10);
8
+ }
9
+ __name(addDays, "addDays");
10
+ function listDates(from, until) {
11
+ const dates = [];
12
+ for (let date = from; date < until; date = addDays(date, 1)) dates.push(date);
13
+ return dates;
14
+ }
15
+ __name(listDates, "listDates");
16
+
17
+ // src/buildChannelInventory.ts
18
+ function nightsOf(stay) {
19
+ return Array.from({
20
+ length: stay.nights
21
+ }, (_, index) => addDays(stay.arrival, index));
22
+ }
23
+ __name(nightsOf, "nightsOf");
24
+ function nightlyPrices(stays) {
25
+ const chosen = /* @__PURE__ */ new Map();
26
+ for (const stay of stays) {
27
+ for (const night of nightsOf(stay)) {
28
+ const current = chosen.get(night);
29
+ if (!current || stay.nights < current.nights) chosen.set(night, stay);
30
+ }
31
+ }
32
+ return new Map([
33
+ ...chosen
34
+ ].map(([night, stay]) => [
35
+ night,
36
+ Math.round(stay.totalCents / stay.nights)
37
+ ]));
38
+ }
39
+ __name(nightlyPrices, "nightlyPrices");
40
+ function findMismatches(params) {
41
+ return params.stays.flatMap((stay) => {
42
+ const channelCents = nightsOf(stay).reduce((sum, night) => sum + (params.prices.get(night) ?? 0), 0);
43
+ if (Math.abs(channelCents - stay.totalCents) <= stay.nights) return [];
44
+ return [
45
+ {
46
+ arrival: stay.arrival,
47
+ nights: stay.nights,
48
+ productCents: stay.totalCents,
49
+ channelCents
50
+ }
51
+ ];
52
+ });
53
+ }
54
+ __name(findMismatches, "findMismatches");
55
+ function buildDepartureCheck(params) {
56
+ const ends = /* @__PURE__ */ __name((stay) => addDays(stay.arrival, stay.nights), "ends");
57
+ const fixedEnds = new Set(params.stays.filter((stay) => stay.isFixedLength).map(ends));
58
+ const earliestFlexibleEnd = params.stays.filter((stay) => !stay.isFixedLength).map(ends).sort()[0];
59
+ return (date) => {
60
+ if (params.noDepartureDates?.has(date)) return false;
61
+ return fixedEnds.has(date) || earliestFlexibleEnd !== void 0 && date >= earliestFlexibleEnd;
62
+ };
63
+ }
64
+ __name(buildDepartureCheck, "buildDepartureCheck");
65
+ function assertStays(stays) {
66
+ const arrivals = /* @__PURE__ */ new Set();
67
+ for (const stay of stays) {
68
+ if (!Number.isInteger(stay.nights) || stay.nights < 1) throw new RangeError(`noites inv\xE1lidas em ${stay.arrival}`);
69
+ if (!Number.isInteger(stay.totalCents) || stay.totalCents < 0) throw new RangeError(`pre\xE7o inv\xE1lido em ${stay.arrival}`);
70
+ if (arrivals.has(stay.arrival)) throw new RangeError(`duas estadias para a mesma entrada: ${stay.arrival}`);
71
+ arrivals.add(stay.arrival);
72
+ }
73
+ }
74
+ __name(assertStays, "assertStays");
75
+ function buildChannelInventory(params) {
76
+ assertStays(params.stays);
77
+ const unitCount = params.unitCount ?? 1;
78
+ const prices = nightlyPrices(params.stays);
79
+ const canDepart = buildDepartureCheck(params);
80
+ const stayByArrival = new Map(params.stays.map((stay) => [
81
+ stay.arrival,
82
+ stay
83
+ ]));
84
+ const days = listDates(params.fromDate, params.untilDate).map((date) => {
85
+ const closed = params.closedDates?.has(date) ?? false;
86
+ const stay = stayByArrival.get(date);
87
+ const free = Math.max(unitCount - (params.occupiedUnits.get(date) ?? 0), 0);
88
+ return {
89
+ date,
90
+ available: closed ? 0 : free,
91
+ closed,
92
+ priceCents: prices.get(date),
93
+ minStay: stay?.nights,
94
+ maxStay: stay?.isFixedLength ? stay.nights : void 0,
95
+ closedToArrival: stay === void 0,
96
+ closedToDeparture: !canDepart(date)
97
+ };
98
+ });
99
+ const windowStays = params.stays.filter((stay) => stay.arrival >= params.fromDate && stay.arrival < params.untilDate);
100
+ return {
101
+ days,
102
+ priceMismatches: findMismatches({
103
+ stays: windowStays,
104
+ prices
105
+ })
106
+ };
107
+ }
108
+ __name(buildChannelInventory, "buildChannelInventory");
109
+ export {
110
+ buildChannelInventory
111
+ };
112
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/civilDates.ts","../src/buildChannelInventory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Datas civis `YYYY-MM-DD` em UTC: a diária não tem fuso.\n */\n\nimport type { CivilDate } from '@adatechnology/scheduling-contracts'\n\nconst DAY_MS = 86_400_000\n\nexport function addDays(date: CivilDate, days: number): CivilDate {\n return new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY_MS).toISOString().slice(0, 10)\n}\n\nexport function listDates(from: CivilDate, until: CivilDate): CivilDate[] {\n const dates: CivilDate[] = []\n for (let date = from; date < until; date = addDays(date, 1)) dates.push(date)\n return dates\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Estadias do produto → o que um portal entende: diária por noite, estadia mínima e máxima, sem entrada, sem\n * saída e fechado. A noite pega o preço da menor estadia que a cobre (o pacote de fim de semana vence o longo\n * do meio da semana); toda entrada cujo total no portal se afasta do preço do produto é apontada, nunca escondida.\n */\n\nimport type { ChannelDayInventory, CivilDate } from '@adatechnology/scheduling-contracts'\n\nimport type {\n ArrivalStay,\n BuildChannelInventoryParams,\n ChannelInventoryPlan,\n ChannelPriceMismatch,\n} from './channelInventory.types'\nimport { addDays, listDates } from './civilDates'\n\nfunction nightsOf(stay: ArrivalStay): CivilDate[] {\n return Array.from({ length: stay.nights }, (_, index) => addDays(stay.arrival, index))\n}\n\nfunction nightlyPrices(stays: readonly ArrivalStay[]): Map<CivilDate, number> {\n const chosen = new Map<CivilDate, ArrivalStay>()\n for (const stay of stays) {\n for (const night of nightsOf(stay)) {\n const current = chosen.get(night)\n if (!current || stay.nights < current.nights) chosen.set(night, stay)\n }\n }\n return new Map([...chosen].map(([night, stay]) => [night, Math.round(stay.totalCents / stay.nights)]))\n}\n\n// Arredondar a diária move o total em até um centavo por noite: só diferença maior é divergência.\nfunction findMismatches(params: {\n readonly stays: readonly ArrivalStay[]\n readonly prices: ReadonlyMap<CivilDate, number>\n}): ChannelPriceMismatch[] {\n return params.stays.flatMap((stay) => {\n const channelCents = nightsOf(stay).reduce((sum, night) => sum + (params.prices.get(night) ?? 0), 0)\n if (Math.abs(channelCents - stay.totalCents) <= stay.nights) return []\n return [{ arrival: stay.arrival, nights: stay.nights, productCents: stay.totalCents, channelCents }]\n })\n}\n\n// Dá para sair num dia quando alguma estadia fixa termina nele ou uma flexível já poderia ter terminado.\nfunction buildDepartureCheck(params: BuildChannelInventoryParams): (date: CivilDate) => boolean {\n const ends = (stay: ArrivalStay): CivilDate => addDays(stay.arrival, stay.nights)\n const fixedEnds = new Set(params.stays.filter((stay) => stay.isFixedLength).map(ends))\n const earliestFlexibleEnd = params.stays\n .filter((stay) => !stay.isFixedLength)\n .map(ends)\n .sort()[0]\n return (date) => {\n if (params.noDepartureDates?.has(date)) return false\n return fixedEnds.has(date) || (earliestFlexibleEnd !== undefined && date >= earliestFlexibleEnd)\n }\n}\n\nfunction assertStays(stays: readonly ArrivalStay[]): void {\n const arrivals = new Set<CivilDate>()\n for (const stay of stays) {\n if (!Number.isInteger(stay.nights) || stay.nights < 1) throw new RangeError(`noites inválidas em ${stay.arrival}`)\n if (!Number.isInteger(stay.totalCents) || stay.totalCents < 0)\n throw new RangeError(`preço inválido em ${stay.arrival}`)\n if (arrivals.has(stay.arrival)) throw new RangeError(`duas estadias para a mesma entrada: ${stay.arrival}`)\n arrivals.add(stay.arrival)\n }\n}\n\nexport function buildChannelInventory(params: BuildChannelInventoryParams): ChannelInventoryPlan {\n assertStays(params.stays)\n const unitCount = params.unitCount ?? 1\n const prices = nightlyPrices(params.stays)\n const canDepart = buildDepartureCheck(params)\n const stayByArrival = new Map(params.stays.map((stay) => [stay.arrival, stay]))\n const days = listDates(params.fromDate, params.untilDate).map((date): ChannelDayInventory => {\n const closed = params.closedDates?.has(date) ?? false\n const stay = stayByArrival.get(date)\n const free = Math.max(unitCount - (params.occupiedUnits.get(date) ?? 0), 0)\n return {\n date,\n available: closed ? 0 : free,\n closed,\n priceCents: prices.get(date),\n minStay: stay?.nights,\n maxStay: stay?.isFixedLength ? stay.nights : undefined,\n closedToArrival: stay === undefined,\n closedToDeparture: !canDepart(date),\n }\n })\n const windowStays = params.stays.filter((stay) => stay.arrival >= params.fromDate && stay.arrival < params.untilDate)\n return { days, priceMismatches: findMismatches({ stays: windowStays, prices }) }\n}\n"],"mappings":";;;;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AAMuC,YAAY3B,OAAO2B,aAAa;AACtC,QAAMtB,SAASlB,cAAca,OAAOZ,KAAK;AACzC,QAAMwC,YAAYpB,oBAAoBR,MAAAA;AACtC,QAAM6B,gBAAgB,IAAIvC,IAAIU,OAAOZ,MAAMO,IAAI,CAACjB,SAAS;IAACA,KAAKQ;IAASR;GAAK,CAAA;AAC7E,QAAMoD,OAAOC,UAAU/B,OAAOgC,UAAUhC,OAAOiC,SAAS,EAAEtC,IAAI,CAACqB,SAAAA;AAC7D,UAAMkB,SAASlC,OAAOmC,aAAajB,IAAIF,IAAAA,KAAS;AAChD,UAAMtC,OAAOmD,cAAcpC,IAAIuB,IAAAA;AAC/B,UAAMoB,OAAOxC,KAAKyC,IAAIV,aAAa3B,OAAOsC,cAAc7C,IAAIuB,IAAAA,KAAS,IAAI,CAAA;AACzE,WAAO;MACLA;MACAuB,WAAWL,SAAS,IAAIE;MACxBF;MACAM,YAAYnC,OAAOZ,IAAIuB,IAAAA;MACvByB,SAAS/D,MAAMI;MACf4D,SAAShE,MAAMmC,gBAAgBnC,KAAKI,SAASqC;MAC7CwB,iBAAiBjE,SAASyC;MAC1ByB,mBAAmB,CAAChB,UAAUZ,IAAAA;IAChC;EACF,CAAA;AACA,QAAM6B,cAAc7C,OAAOZ,MAAMwB,OAAO,CAAClC,SAASA,KAAKQ,WAAWc,OAAOgC,YAAYtD,KAAKQ,UAAUc,OAAOiC,SAAS;AACpH,SAAO;IAAEH;IAAMgB,iBAAiB/C,eAAe;MAAEX,OAAOyD;MAAaxC;IAAO,CAAA;EAAG;AACjF;AAvBgBqB;","names":["DAY_MS","addDays","date","days","Date","parse","toISOString","slice","listDates","from","until","dates","push","nightsOf","stay","Array","from","length","nights","_","index","addDays","arrival","nightlyPrices","stays","chosen","Map","night","current","get","set","map","Math","round","totalCents","findMismatches","params","flatMap","channelCents","reduce","sum","prices","abs","productCents","buildDepartureCheck","ends","fixedEnds","Set","filter","isFixedLength","earliestFlexibleEnd","sort","date","noDepartureDates","has","undefined","assertStays","arrivals","Number","isInteger","RangeError","add","buildChannelInventory","unitCount","canDepart","stayByArrival","days","listDates","fromDate","untilDate","closed","closedDates","free","max","occupiedUnits","available","priceCents","minStay","maxStay","closedToArrival","closedToDeparture","windowStays","priceMismatches"]}
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@adatechnology/channel-sync-module",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "Channel manager sync (portal-agnostic): turns the stays a product sells into what the portals understand (nightly price, min/max stay, closed to arrival/departure, closed) and reports where the portal total drifts from the product price",
6
+ "keywords": [
7
+ "channel-manager",
8
+ "ota",
9
+ "booking.com",
10
+ "airbnb",
11
+ "inventory"
12
+ ],
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "type": "module",
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "sideEffects": false,
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js",
24
+ "require": "./dist/index.cjs"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "dependencies": {
31
+ "@adatechnology/scheduling-contracts": "0.2.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/bun": "1.3.14",
35
+ "tsup": "^8.5.1",
36
+ "typescript": "^5.7.3"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup",
40
+ "check": "tsc -p tsconfig.json --noEmit",
41
+ "test": "bun test"
42
+ }
6
43
  }