@voyant-travel/commerce 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.
Files changed (210) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +145 -0
  3. package/dist/accepted-quote-version-reservation-golden-flow.test.d.ts +2 -0
  4. package/dist/accepted-quote-version-reservation-golden-flow.test.d.ts.map +1 -0
  5. package/dist/accepted-quote-version-reservation-golden-flow.test.js +398 -0
  6. package/dist/index.d.ts +15 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +14 -0
  9. package/dist/interface.d.ts +18 -0
  10. package/dist/interface.d.ts.map +1 -0
  11. package/dist/interface.js +246 -0
  12. package/dist/interface.test.d.ts +2 -0
  13. package/dist/interface.test.d.ts.map +1 -0
  14. package/dist/interface.test.js +357 -0
  15. package/dist/markets/index.d.ts +11 -0
  16. package/dist/markets/index.d.ts.map +1 -0
  17. package/dist/markets/index.js +12 -0
  18. package/dist/markets/routes.d.ts +1182 -0
  19. package/dist/markets/routes.d.ts.map +1 -0
  20. package/dist/markets/routes.js +209 -0
  21. package/dist/markets/schema.d.ts +1527 -0
  22. package/dist/markets/schema.d.ts.map +1 -0
  23. package/dist/markets/schema.js +240 -0
  24. package/dist/markets/service-core.d.ts +253 -0
  25. package/dist/markets/service-core.d.ts.map +1 -0
  26. package/dist/markets/service-core.js +242 -0
  27. package/dist/markets/service-rules.d.ts +191 -0
  28. package/dist/markets/service-rules.d.ts.map +1 -0
  29. package/dist/markets/service-rules.js +155 -0
  30. package/dist/markets/service-shared.d.ts +36 -0
  31. package/dist/markets/service-shared.d.ts.map +1 -0
  32. package/dist/markets/service-shared.js +7 -0
  33. package/dist/markets/service.d.ts +43 -0
  34. package/dist/markets/service.d.ts.map +1 -0
  35. package/dist/markets/service.js +42 -0
  36. package/dist/markets/validation.d.ts +451 -0
  37. package/dist/markets/validation.d.ts.map +1 -0
  38. package/dist/markets/validation.js +160 -0
  39. package/dist/pricing/events.d.ts +53 -0
  40. package/dist/pricing/events.d.ts.map +1 -0
  41. package/dist/pricing/events.js +28 -0
  42. package/dist/pricing/index.d.ts +15 -0
  43. package/dist/pricing/index.d.ts.map +1 -0
  44. package/dist/pricing/index.js +18 -0
  45. package/dist/pricing/routes-core.d.ts +981 -0
  46. package/dist/pricing/routes-core.d.ts.map +1 -0
  47. package/dist/pricing/routes-core.js +102 -0
  48. package/dist/pricing/routes-public.d.ts +136 -0
  49. package/dist/pricing/routes-public.d.ts.map +1 -0
  50. package/dist/pricing/routes-public.js +14 -0
  51. package/dist/pricing/routes-rules.d.ts +1339 -0
  52. package/dist/pricing/routes-rules.d.ts.map +1 -0
  53. package/dist/pricing/routes-rules.js +138 -0
  54. package/dist/pricing/routes-shared.d.ts +14 -0
  55. package/dist/pricing/routes-shared.d.ts.map +1 -0
  56. package/dist/pricing/routes-shared.js +3 -0
  57. package/dist/pricing/routes.d.ts +7 -0
  58. package/dist/pricing/routes.d.ts.map +1 -0
  59. package/dist/pricing/routes.js +6 -0
  60. package/dist/pricing/schema-catalogs.d.ts +467 -0
  61. package/dist/pricing/schema-catalogs.d.ts.map +1 -0
  62. package/dist/pricing/schema-catalogs.js +47 -0
  63. package/dist/pricing/schema-categories.d.ts +497 -0
  64. package/dist/pricing/schema-categories.d.ts.map +1 -0
  65. package/dist/pricing/schema-categories.js +54 -0
  66. package/dist/pricing/schema-departure-overrides.d.ts +228 -0
  67. package/dist/pricing/schema-departure-overrides.d.ts.map +1 -0
  68. package/dist/pricing/schema-departure-overrides.js +36 -0
  69. package/dist/pricing/schema-option-rules.d.ts +1770 -0
  70. package/dist/pricing/schema-option-rules.d.ts.map +1 -0
  71. package/dist/pricing/schema-option-rules.js +181 -0
  72. package/dist/pricing/schema-policies.d.ts +395 -0
  73. package/dist/pricing/schema-policies.d.ts.map +1 -0
  74. package/dist/pricing/schema-policies.js +41 -0
  75. package/dist/pricing/schema-relations.d.ts +59 -0
  76. package/dist/pricing/schema-relations.d.ts.map +1 -0
  77. package/dist/pricing/schema-relations.js +111 -0
  78. package/dist/pricing/schema-shared.d.ts +11 -0
  79. package/dist/pricing/schema-shared.d.ts.map +1 -0
  80. package/dist/pricing/schema-shared.js +67 -0
  81. package/dist/pricing/schema.d.ts +8 -0
  82. package/dist/pricing/schema.d.ts.map +1 -0
  83. package/dist/pricing/schema.js +7 -0
  84. package/dist/pricing/service-catalog-plane-pricing.d.ts +95 -0
  85. package/dist/pricing/service-catalog-plane-pricing.d.ts.map +1 -0
  86. package/dist/pricing/service-catalog-plane-pricing.js +382 -0
  87. package/dist/pricing/service-catalogs.d.ts +139 -0
  88. package/dist/pricing/service-catalogs.d.ts.map +1 -0
  89. package/dist/pricing/service-catalogs.js +89 -0
  90. package/dist/pricing/service-categories.d.ts +147 -0
  91. package/dist/pricing/service-categories.d.ts.map +1 -0
  92. package/dist/pricing/service-categories.js +105 -0
  93. package/dist/pricing/service-departure-overrides.d.ts +67 -0
  94. package/dist/pricing/service-departure-overrides.d.ts.map +1 -0
  95. package/dist/pricing/service-departure-overrides.js +54 -0
  96. package/dist/pricing/service-option-rules.d.ts +321 -0
  97. package/dist/pricing/service-option-rules.d.ts.map +1 -0
  98. package/dist/pricing/service-option-rules.js +340 -0
  99. package/dist/pricing/service-policies.d.ts +123 -0
  100. package/dist/pricing/service-policies.d.ts.map +1 -0
  101. package/dist/pricing/service-policies.js +95 -0
  102. package/dist/pricing/service-public.d.ts +89 -0
  103. package/dist/pricing/service-public.d.ts.map +1 -0
  104. package/dist/pricing/service-public.js +473 -0
  105. package/dist/pricing/service-rule-resolver.d.ts +67 -0
  106. package/dist/pricing/service-rule-resolver.d.ts.map +1 -0
  107. package/dist/pricing/service-rule-resolver.js +204 -0
  108. package/dist/pricing/service-shared.d.ts +53 -0
  109. package/dist/pricing/service-shared.d.ts.map +1 -0
  110. package/dist/pricing/service-shared.js +4 -0
  111. package/dist/pricing/service-transfer-rules.d.ts +211 -0
  112. package/dist/pricing/service-transfer-rules.d.ts.map +1 -0
  113. package/dist/pricing/service-transfer-rules.js +139 -0
  114. package/dist/pricing/service.d.ts +79 -0
  115. package/dist/pricing/service.d.ts.map +1 -0
  116. package/dist/pricing/service.js +78 -0
  117. package/dist/pricing/validation-public.d.ts +412 -0
  118. package/dist/pricing/validation-public.d.ts.map +1 -0
  119. package/dist/pricing/validation-public.js +111 -0
  120. package/dist/pricing/validation-shared.d.ts +71 -0
  121. package/dist/pricing/validation-shared.d.ts.map +1 -0
  122. package/dist/pricing/validation-shared.js +63 -0
  123. package/dist/pricing/validation.d.ts +987 -0
  124. package/dist/pricing/validation.d.ts.map +1 -0
  125. package/dist/pricing/validation.js +307 -0
  126. package/dist/promotions/events.d.ts +38 -0
  127. package/dist/promotions/events.d.ts.map +1 -0
  128. package/dist/promotions/events.js +25 -0
  129. package/dist/promotions/index.d.ts +12 -0
  130. package/dist/promotions/index.d.ts.map +1 -0
  131. package/dist/promotions/index.js +17 -0
  132. package/dist/promotions/routes-shared.d.ts +14 -0
  133. package/dist/promotions/routes-shared.d.ts.map +1 -0
  134. package/dist/promotions/routes-shared.js +3 -0
  135. package/dist/promotions/routes.d.ts +395 -0
  136. package/dist/promotions/routes.d.ts.map +1 -0
  137. package/dist/promotions/routes.js +55 -0
  138. package/dist/promotions/schema.d.ts +675 -0
  139. package/dist/promotions/schema.d.ts.map +1 -0
  140. package/dist/promotions/schema.js +126 -0
  141. package/dist/promotions/service-booking-confirmed.d.ts +77 -0
  142. package/dist/promotions/service-booking-confirmed.d.ts.map +1 -0
  143. package/dist/promotions/service-booking-confirmed.js +134 -0
  144. package/dist/promotions/service-boundary-scheduler.d.ts +85 -0
  145. package/dist/promotions/service-boundary-scheduler.d.ts.map +1 -0
  146. package/dist/promotions/service-boundary-scheduler.js +141 -0
  147. package/dist/promotions/service-catalog-evaluator.d.ts +22 -0
  148. package/dist/promotions/service-catalog-evaluator.d.ts.map +1 -0
  149. package/dist/promotions/service-catalog-evaluator.js +33 -0
  150. package/dist/promotions/service-catalog-plane-promotions.d.ts +73 -0
  151. package/dist/promotions/service-catalog-plane-promotions.d.ts.map +1 -0
  152. package/dist/promotions/service-catalog-plane-promotions.js +118 -0
  153. package/dist/promotions/service-evaluator.d.ts +134 -0
  154. package/dist/promotions/service-evaluator.d.ts.map +1 -0
  155. package/dist/promotions/service-evaluator.js +302 -0
  156. package/dist/promotions/service-storefront.d.ts +147 -0
  157. package/dist/promotions/service-storefront.d.ts.map +1 -0
  158. package/dist/promotions/service-storefront.js +326 -0
  159. package/dist/promotions/service.d.ts +143 -0
  160. package/dist/promotions/service.d.ts.map +1 -0
  161. package/dist/promotions/service.js +359 -0
  162. package/dist/promotions/validation.d.ts +195 -0
  163. package/dist/promotions/validation.d.ts.map +1 -0
  164. package/dist/promotions/validation.js +167 -0
  165. package/dist/promotions/workflow-bulk-reindex.d.ts +36 -0
  166. package/dist/promotions/workflow-bulk-reindex.d.ts.map +1 -0
  167. package/dist/promotions/workflow-bulk-reindex.js +53 -0
  168. package/dist/promotions/workflow-runtime.d.ts +17 -0
  169. package/dist/promotions/workflow-runtime.d.ts.map +1 -0
  170. package/dist/promotions/workflow-runtime.js +9 -0
  171. package/dist/runtime.d.ts +18 -0
  172. package/dist/runtime.d.ts.map +1 -0
  173. package/dist/runtime.js +27 -0
  174. package/dist/runtime.test.d.ts +2 -0
  175. package/dist/runtime.test.d.ts.map +1 -0
  176. package/dist/runtime.test.js +25 -0
  177. package/dist/schema.d.ts +5 -0
  178. package/dist/schema.d.ts.map +1 -0
  179. package/dist/schema.js +4 -0
  180. package/dist/sellability/index.d.ts +13 -0
  181. package/dist/sellability/index.d.ts.map +1 -0
  182. package/dist/sellability/index.js +17 -0
  183. package/dist/sellability/routes.d.ts +2332 -0
  184. package/dist/sellability/routes.d.ts.map +1 -0
  185. package/dist/sellability/routes.js +166 -0
  186. package/dist/sellability/schema.d.ts +1716 -0
  187. package/dist/sellability/schema.d.ts.map +1 -0
  188. package/dist/sellability/schema.js +278 -0
  189. package/dist/sellability/service-records.d.ts +316 -0
  190. package/dist/sellability/service-records.d.ts.map +1 -0
  191. package/dist/sellability/service-records.js +253 -0
  192. package/dist/sellability/service-resolve.d.ts +72 -0
  193. package/dist/sellability/service-resolve.d.ts.map +1 -0
  194. package/dist/sellability/service-resolve.js +580 -0
  195. package/dist/sellability/service-shared.d.ts +124 -0
  196. package/dist/sellability/service-shared.d.ts.map +1 -0
  197. package/dist/sellability/service-shared.js +96 -0
  198. package/dist/sellability/service-snapshots.d.ts +191 -0
  199. package/dist/sellability/service-snapshots.d.ts.map +1 -0
  200. package/dist/sellability/service-snapshots.js +153 -0
  201. package/dist/sellability/service.d.ts +1038 -0
  202. package/dist/sellability/service.d.ts.map +1 -0
  203. package/dist/sellability/service.js +17 -0
  204. package/dist/sellability/validation.d.ts +477 -0
  205. package/dist/sellability/validation.d.ts.map +1 -0
  206. package/dist/sellability/validation.js +192 -0
  207. package/dist/types.d.ts +239 -0
  208. package/dist/types.d.ts.map +1 -0
  209. package/dist/types.js +1 -0
  210. package/package.json +62 -0
@@ -0,0 +1,580 @@
1
+ // agent-quality: file-size exception -- owner: sellability; resolve remains a single pricing/sellability workflow after #1734 split the surrounding service operations.
2
+ import { channelInventoryAllotments, channelInventoryAllotmentTargets, channelInventoryReleaseRules, channels, } from "@voyant-travel/distribution/schema";
3
+ import { and, desc, eq, inArray, sql } from "drizzle-orm";
4
+ import { exchangeRates, fxRateSets, marketChannelRules, marketPriceCatalogs, marketProductRules, markets, } from "../markets/schema.js";
5
+ import { departurePriceOverrides, optionPriceRules, optionStartTimeRules, optionUnitPriceRules, optionUnitTiers, pickupPriceRules, priceCatalogs, priceSchedules, pricingCategories, } from "../pricing/schema.js";
6
+ import { applyAdjustment, chooseBestScheduledRule, chooseBestSpecificRule, computeUnitAmounts, scheduleMatches, toNumeric, } from "./service-shared.js";
7
+ async function executeRows(db, query) {
8
+ // biome-ignore lint/suspicious/noExplicitAny: #1141 keeps cross-package SQL boundary reads driver-agnostic.
9
+ const result = await db.execute(query);
10
+ return Array.isArray(result) ? result : (result?.rows ?? []);
11
+ }
12
+ function sqlList(values) {
13
+ return sql.join(values.map((value) => sql `${value}`), sql `, `);
14
+ }
15
+ function andSql(conditions) {
16
+ return sql.join(conditions, sql ` AND `);
17
+ }
18
+ function normalizeDateOnly(value) {
19
+ if (!value)
20
+ return null;
21
+ return value instanceof Date ? value.toISOString().slice(0, 10) : value.slice(0, 10);
22
+ }
23
+ async function loadResolveOptions(db, query) {
24
+ const conditions = [sql `product.status::text = 'active'`, sql `option.status::text = 'active'`];
25
+ if (query.productId)
26
+ conditions.push(sql `product.id = ${query.productId}`);
27
+ if (query.optionId)
28
+ conditions.push(sql `option.id = ${query.optionId}`);
29
+ const rows = await executeRows(db,
30
+ // agent-quality: raw-sql reviewed -- owner: sellability; cross-module Product option read with parameter-bound filters.
31
+ sql `
32
+ SELECT
33
+ product.id AS product_id,
34
+ product.name AS product_name,
35
+ product.sell_currency AS product_sell_currency,
36
+ option.id AS option_id,
37
+ option.name AS option_name,
38
+ option.code AS option_code,
39
+ option.is_default AS option_is_default,
40
+ option.available_from AS option_available_from,
41
+ option.available_to AS option_available_to
42
+ FROM product_options option
43
+ INNER JOIN products product
44
+ ON option.product_id = product.id
45
+ WHERE ${andSql(conditions)}
46
+ ORDER BY product.name ASC, option.sort_order ASC
47
+ `);
48
+ return rows.map((row) => {
49
+ const value = row;
50
+ return {
51
+ productId: value.product_id,
52
+ productName: value.product_name,
53
+ productSellCurrency: value.product_sell_currency,
54
+ optionId: value.option_id,
55
+ optionName: value.option_name,
56
+ optionCode: value.option_code,
57
+ optionIsDefault: value.option_is_default,
58
+ optionAvailableFrom: normalizeDateOnly(value.option_available_from),
59
+ optionAvailableTo: normalizeDateOnly(value.option_available_to),
60
+ };
61
+ });
62
+ }
63
+ async function loadResolveSlots(db, optionIds, query) {
64
+ if (optionIds.length === 0)
65
+ return [];
66
+ const conditions = [
67
+ sql `slot.option_id IN (${sqlList(optionIds)})`,
68
+ sql `slot.status::text = 'open'`,
69
+ ];
70
+ if (query.slotId)
71
+ conditions.push(sql `slot.id = ${query.slotId}`);
72
+ if (query.dateLocal)
73
+ conditions.push(sql `slot.date_local = ${query.dateLocal}`);
74
+ if (query.startTimeId)
75
+ conditions.push(sql `slot.start_time_id = ${query.startTimeId}`);
76
+ const rows = await executeRows(db,
77
+ // agent-quality: raw-sql reviewed -- owner: sellability; cross-module Availability slot read with parameter-bound filters.
78
+ sql `
79
+ SELECT
80
+ slot.id,
81
+ slot.product_id,
82
+ slot.option_id,
83
+ slot.start_time_id,
84
+ slot.date_local,
85
+ slot.starts_at,
86
+ slot.timezone,
87
+ slot.unlimited,
88
+ slot.remaining_pax,
89
+ slot.remaining_pickups,
90
+ slot.past_cutoff,
91
+ slot.too_early
92
+ FROM availability_slots slot
93
+ WHERE ${andSql(conditions)}
94
+ ORDER BY slot.starts_at ASC
95
+ LIMIT ${query.limit}
96
+ `);
97
+ return rows.map((row) => {
98
+ const value = row;
99
+ return {
100
+ id: value.id,
101
+ productId: value.product_id,
102
+ optionId: value.option_id,
103
+ startTimeId: value.start_time_id,
104
+ dateLocal: normalizeDateOnly(value.date_local) ?? "",
105
+ startsAt: value.starts_at,
106
+ timezone: value.timezone,
107
+ unlimited: value.unlimited,
108
+ remainingPax: value.remaining_pax,
109
+ remainingPickups: value.remaining_pickups,
110
+ pastCutoff: value.past_cutoff,
111
+ tooEarly: value.too_early,
112
+ };
113
+ });
114
+ }
115
+ async function loadResolveUnits(db) {
116
+ const rows = await executeRows(db,
117
+ // agent-quality: raw-sql reviewed -- owner: sellability; cross-module Product unit labels/types read for resolved price components.
118
+ sql `SELECT id, name, unit_type::text AS unit_type FROM option_units`);
119
+ return rows.map((row) => {
120
+ const value = row;
121
+ return { id: value.id, name: value.name, unitType: value.unit_type };
122
+ });
123
+ }
124
+ export async function resolve(db, query) {
125
+ const optionRows = await loadResolveOptions(db, query);
126
+ if (optionRows.length === 0) {
127
+ return { data: [], meta: { total: 0 } };
128
+ }
129
+ const optionIds = optionRows.map((row) => row.optionId);
130
+ const productIds = [...new Set(optionRows.map((row) => row.productId))];
131
+ const slots = await loadResolveSlots(db, optionIds, query);
132
+ const startTimeIds = [
133
+ ...new Set(slots.flatMap((slot) => (slot.startTimeId ? [slot.startTimeId] : []))),
134
+ ];
135
+ const slotIds = slots.map((slot) => slot.id);
136
+ const [marketRow, channelRow, marketProductRuleRows, marketChannelRuleRows, marketCatalogRows, catalogRows, optionPriceRuleRows, optionScheduleRows, unitPriceRuleRows, unitTierRows, unitRows, pricingCategoryRows, startTimeRuleRows, pickupRuleRows, allotmentRows, allotmentTargetRows, releaseRuleRows, exchangeRateRow, departureOverrideRows,] = await Promise.all([
137
+ query.marketId
138
+ ? db
139
+ .select()
140
+ .from(markets)
141
+ .where(eq(markets.id, query.marketId))
142
+ .limit(1)
143
+ .then((rows) => rows[0] ?? null)
144
+ : Promise.resolve(null),
145
+ query.channelId
146
+ ? db
147
+ .select({ id: channels.id, kind: channels.kind })
148
+ .from(channels)
149
+ .where(eq(channels.id, query.channelId))
150
+ .limit(1)
151
+ .then((rows) => rows[0] ?? null)
152
+ : Promise.resolve(null),
153
+ query.marketId
154
+ ? db
155
+ .select()
156
+ .from(marketProductRules)
157
+ .where(and(eq(marketProductRules.marketId, query.marketId), eq(marketProductRules.active, true), inArray(marketProductRules.productId, productIds)))
158
+ : Promise.resolve([]),
159
+ query.marketId && query.channelId
160
+ ? db
161
+ .select()
162
+ .from(marketChannelRules)
163
+ .where(and(eq(marketChannelRules.marketId, query.marketId), eq(marketChannelRules.channelId, query.channelId), eq(marketChannelRules.active, true)))
164
+ : Promise.resolve([]),
165
+ query.marketId
166
+ ? db
167
+ .select({
168
+ id: marketPriceCatalogs.id,
169
+ marketId: marketPriceCatalogs.marketId,
170
+ priceCatalogId: marketPriceCatalogs.priceCatalogId,
171
+ isDefault: marketPriceCatalogs.isDefault,
172
+ priority: marketPriceCatalogs.priority,
173
+ active: marketPriceCatalogs.active,
174
+ })
175
+ .from(marketPriceCatalogs)
176
+ .where(and(eq(marketPriceCatalogs.marketId, query.marketId), eq(marketPriceCatalogs.active, true)))
177
+ : Promise.resolve([]),
178
+ db
179
+ .select({ id: priceCatalogs.id, currencyCode: priceCatalogs.currencyCode })
180
+ .from(priceCatalogs),
181
+ db
182
+ .select()
183
+ .from(optionPriceRules)
184
+ .where(and(inArray(optionPriceRules.optionId, optionIds), eq(optionPriceRules.active, true))),
185
+ db.select().from(priceSchedules),
186
+ db
187
+ .select()
188
+ .from(optionUnitPriceRules)
189
+ .where(and(inArray(optionUnitPriceRules.optionId, optionIds), eq(optionUnitPriceRules.active, true))),
190
+ db.select().from(optionUnitTiers).where(eq(optionUnitTiers.active, true)),
191
+ loadResolveUnits(db),
192
+ db
193
+ .select({ id: pricingCategories.id, name: pricingCategories.name })
194
+ .from(pricingCategories)
195
+ .where(eq(pricingCategories.active, true)),
196
+ startTimeIds.length
197
+ ? db
198
+ .select()
199
+ .from(optionStartTimeRules)
200
+ .where(and(inArray(optionStartTimeRules.optionId, optionIds), inArray(optionStartTimeRules.startTimeId, startTimeIds), eq(optionStartTimeRules.active, true)))
201
+ : Promise.resolve([]),
202
+ query.pickupPointId
203
+ ? db
204
+ .select()
205
+ .from(pickupPriceRules)
206
+ .where(and(inArray(pickupPriceRules.optionId, optionIds), eq(pickupPriceRules.pickupPointId, query.pickupPointId), eq(pickupPriceRules.active, true)))
207
+ : Promise.resolve([]),
208
+ query.channelId
209
+ ? db
210
+ .select()
211
+ .from(channelInventoryAllotments)
212
+ .where(and(eq(channelInventoryAllotments.channelId, query.channelId), eq(channelInventoryAllotments.active, true), inArray(channelInventoryAllotments.productId, productIds)))
213
+ : Promise.resolve([]),
214
+ query.channelId && slotIds.length
215
+ ? db
216
+ .select()
217
+ .from(channelInventoryAllotmentTargets)
218
+ .where(and(inArray(channelInventoryAllotmentTargets.slotId, slotIds), eq(channelInventoryAllotmentTargets.active, true)))
219
+ : Promise.resolve([]),
220
+ query.channelId ? db.select().from(channelInventoryReleaseRules) : Promise.resolve([]),
221
+ query.currencyCode
222
+ ? db
223
+ .select({
224
+ rateDecimal: exchangeRates.rateDecimal,
225
+ baseCurrency: exchangeRates.baseCurrency,
226
+ quoteCurrency: exchangeRates.quoteCurrency,
227
+ fxRateSetId: exchangeRates.fxRateSetId,
228
+ effectiveAt: fxRateSets.effectiveAt,
229
+ })
230
+ .from(exchangeRates)
231
+ .innerJoin(fxRateSets, eq(exchangeRates.fxRateSetId, fxRateSets.id))
232
+ .where(eq(exchangeRates.quoteCurrency, query.currencyCode))
233
+ .orderBy(desc(fxRateSets.effectiveAt))
234
+ : Promise.resolve([]),
235
+ slotIds.length
236
+ ? db
237
+ .select({
238
+ departureId: departurePriceOverrides.departureId,
239
+ priceCatalogId: departurePriceOverrides.priceCatalogId,
240
+ optionUnitId: departurePriceOverrides.optionUnitId,
241
+ sellAmountCents: departurePriceOverrides.sellAmountCents,
242
+ costAmountCents: departurePriceOverrides.costAmountCents,
243
+ })
244
+ .from(departurePriceOverrides)
245
+ .where(and(inArray(departurePriceOverrides.departureId, slotIds), eq(departurePriceOverrides.active, true)))
246
+ : Promise.resolve([]),
247
+ ]);
248
+ const optionMap = new Map(optionRows.map((row) => [row.optionId, row]));
249
+ const scheduleMap = new Map(optionScheduleRows.map((row) => [row.id, row]));
250
+ const marketCatalogMap = new Map(marketCatalogRows.map((row) => [row.id, row]));
251
+ const catalogMap = new Map(catalogRows.map((row) => [row.id, row]));
252
+ const unitMap = new Map(unitRows.map((row) => [row.id, row]));
253
+ const pricingCategoryMap = new Map(pricingCategoryRows.map((row) => [row.id, row]));
254
+ const departureOverrideMap = new Map(departureOverrideRows.map((row) => [
255
+ `${row.departureId}:${row.priceCatalogId}:${row.optionUnitId}`,
256
+ row,
257
+ ]));
258
+ const candidates = [];
259
+ for (const slot of slots) {
260
+ if (!slot.optionId)
261
+ continue;
262
+ const option = optionMap.get(slot.optionId);
263
+ if (!option)
264
+ continue;
265
+ if (option.optionAvailableFrom && slot.dateLocal < option.optionAvailableFrom)
266
+ continue;
267
+ if (option.optionAvailableTo && slot.dateLocal > option.optionAvailableTo)
268
+ continue;
269
+ if (slot.pastCutoff || slot.tooEarly)
270
+ continue;
271
+ if (!slot.unlimited && (slot.remainingPax ?? 0) <= 0)
272
+ continue;
273
+ const marketRule = query.marketId
274
+ ? chooseBestSpecificRule(marketProductRuleRows.filter((row) => {
275
+ if (row.productId !== option.productId)
276
+ return false;
277
+ if (row.optionId && row.optionId !== option.optionId)
278
+ return false;
279
+ if (query.dateLocal && row.availableFrom && query.dateLocal < row.availableFrom)
280
+ return false;
281
+ if (query.dateLocal && row.availableTo && query.dateLocal > row.availableTo)
282
+ return false;
283
+ return true;
284
+ }))
285
+ : null;
286
+ if (marketRule?.sellability === "unavailable")
287
+ continue;
288
+ const channelRule = query.marketId && query.channelId
289
+ ? [...marketChannelRuleRows]
290
+ .sort((a, b) => b.priority - a.priority)
291
+ .find((row) => row.sellability !== "unavailable")
292
+ : null;
293
+ if (query.marketId && query.channelId && !channelRule && marketChannelRuleRows.length > 0) {
294
+ continue;
295
+ }
296
+ const catalogSelection = (channelRule?.priceCatalogId ? marketCatalogMap.get(channelRule.priceCatalogId) : null) ??
297
+ (marketRule?.priceCatalogId ? marketCatalogMap.get(marketRule.priceCatalogId) : null) ??
298
+ [...marketCatalogRows].sort((a, b) => {
299
+ const scoreA = Number(a.isDefault) * 10 - a.priority;
300
+ const scoreB = Number(b.isDefault) * 10 - b.priority;
301
+ return scoreB - scoreA;
302
+ })[0] ??
303
+ null;
304
+ const applicableRules = optionPriceRuleRows.filter((row) => {
305
+ if (row.optionId !== option.optionId || row.productId !== option.productId)
306
+ return false;
307
+ if (catalogSelection && row.priceCatalogId !== catalogSelection.priceCatalogId)
308
+ return false;
309
+ const schedule = row.priceScheduleId ? scheduleMap.get(row.priceScheduleId) : null;
310
+ return scheduleMatches({
311
+ validFrom: schedule?.validFrom ?? null,
312
+ validTo: schedule?.validTo ?? null,
313
+ weekdays: schedule?.weekdays ?? null,
314
+ }, slot.dateLocal);
315
+ });
316
+ const chosenRule = chooseBestScheduledRule(applicableRules);
317
+ if (!chosenRule)
318
+ continue;
319
+ const applicableStartRule = slot.startTimeId
320
+ ? (startTimeRuleRows.find((row) => row.optionPriceRuleId === chosenRule.id && row.startTimeId === slot.startTimeId) ?? null)
321
+ : null;
322
+ if (applicableStartRule?.ruleMode === "excluded")
323
+ continue;
324
+ const ruleUnitRows = unitPriceRuleRows.filter((row) => row.optionPriceRuleId === chosenRule.id);
325
+ const ruleTierRows = unitTierRows.filter((row) => ruleUnitRows.some((unitRule) => unitRule.id === row.optionUnitPriceRuleId));
326
+ const requestedUnits = query.requestedUnits.length > 0 ? query.requestedUnits : [];
327
+ const breakdown = [];
328
+ const components = [];
329
+ let sellAmountCents = chosenRule.baseSellAmountCents ?? 0;
330
+ let costAmountCents = chosenRule.baseCostAmountCents ?? 0;
331
+ let onRequest = chosenRule.pricingMode === "on_request";
332
+ if ((chosenRule.baseSellAmountCents ?? 0) !== 0 ||
333
+ (chosenRule.baseCostAmountCents ?? 0) !== 0) {
334
+ components.push({
335
+ kind: "base",
336
+ title: option.optionName,
337
+ quantity: 1,
338
+ pricingMode: chosenRule.pricingMode,
339
+ sellAmountCents: chosenRule.baseSellAmountCents ?? 0,
340
+ costAmountCents: chosenRule.baseCostAmountCents ?? 0,
341
+ unitId: null,
342
+ unitName: null,
343
+ unitType: null,
344
+ pricingCategoryId: null,
345
+ pricingCategoryName: null,
346
+ requestRef: null,
347
+ sourceRuleId: chosenRule.id,
348
+ tierId: null,
349
+ });
350
+ }
351
+ for (const request of requestedUnits) {
352
+ const candidateUnitRules = ruleUnitRows.filter((row) => {
353
+ if (request.unitId && row.unitId !== request.unitId)
354
+ return false;
355
+ if (request.pricingCategoryId &&
356
+ row.pricingCategoryId &&
357
+ row.pricingCategoryId !== request.pricingCategoryId)
358
+ return false;
359
+ if (row.minQuantity && request.quantity < row.minQuantity)
360
+ return false;
361
+ if (row.maxQuantity && request.quantity > row.maxQuantity)
362
+ return false;
363
+ return true;
364
+ });
365
+ const unitRule = [...candidateUnitRules].sort((a, b) => {
366
+ const scoreA = Number(Boolean(request.unitId && a.unitId === request.unitId)) * 10 +
367
+ Number(Boolean(request.pricingCategoryId && a.pricingCategoryId === request.pricingCategoryId));
368
+ const scoreB = Number(Boolean(request.unitId && b.unitId === request.unitId)) * 10 +
369
+ Number(Boolean(request.pricingCategoryId && b.pricingCategoryId === request.pricingCategoryId));
370
+ return scoreB - scoreA;
371
+ })[0] ?? null;
372
+ const tier = unitRule
373
+ ? ([...ruleTierRows]
374
+ .filter((row) => row.optionUnitPriceRuleId === unitRule.id &&
375
+ row.active &&
376
+ request.quantity >= row.minQuantity &&
377
+ (row.maxQuantity === null || request.quantity <= row.maxQuantity))
378
+ .sort((a, b) => a.sortOrder - b.sortOrder)[0] ?? null)
379
+ : null;
380
+ if (unitRule?.pricingMode === "on_request")
381
+ onRequest = true;
382
+ const overrideUnitId = request.unitId ?? unitRule?.unitId ?? null;
383
+ const override = overrideUnitId == null
384
+ ? null
385
+ : (departureOverrideMap.get(`${slot.id}:${chosenRule.priceCatalogId}:${overrideUnitId}`) ?? null);
386
+ const item = computeUnitAmounts(request, {
387
+ unitName: request.unitId ? (unitMap.get(request.unitId)?.name ?? null) : null,
388
+ unitType: request.unitId ? (unitMap.get(request.unitId)?.unitType ?? null) : null,
389
+ pricingCategoryName: request.pricingCategoryId
390
+ ? (pricingCategoryMap.get(request.pricingCategoryId)?.name ?? null)
391
+ : null,
392
+ }, unitRule, tier, override);
393
+ breakdown.push(item);
394
+ components.push({
395
+ kind: "unit",
396
+ title: [option.optionName, item.unitName, item.pricingCategoryName]
397
+ .filter(Boolean)
398
+ .join(" · ") || option.optionName,
399
+ quantity: item.quantity,
400
+ pricingMode: item.pricingMode,
401
+ sellAmountCents: item.sellAmountCents,
402
+ costAmountCents: item.costAmountCents,
403
+ unitId: item.unitId,
404
+ unitName: item.unitName,
405
+ unitType: item.unitType,
406
+ pricingCategoryId: item.pricingCategoryId,
407
+ pricingCategoryName: item.pricingCategoryName,
408
+ requestRef: item.requestRef,
409
+ sourceRuleId: item.sourceRuleId,
410
+ tierId: item.tierId,
411
+ });
412
+ sellAmountCents += item.sellAmountCents;
413
+ costAmountCents += item.costAmountCents;
414
+ }
415
+ if (query.pickupPointId) {
416
+ const pickupRule = pickupRuleRows.find((row) => row.optionPriceRuleId === chosenRule.id && row.pickupPointId === query.pickupPointId) ?? null;
417
+ if (pickupRule) {
418
+ const quantity = Math.max(1, query.requestedUnits.reduce((sum, unit) => sum + unit.quantity, 0));
419
+ const pickupSellAmountCents = pickupRule.pricingMode === "per_person"
420
+ ? (pickupRule.sellAmountCents ?? 0) * quantity
421
+ : (pickupRule.sellAmountCents ?? 0);
422
+ const pickupCostAmountCents = pickupRule.pricingMode === "per_person"
423
+ ? (pickupRule.costAmountCents ?? 0) * quantity
424
+ : (pickupRule.costAmountCents ?? 0);
425
+ if (pickupRule.pricingMode === "on_request")
426
+ onRequest = true;
427
+ components.push({
428
+ kind: "pickup",
429
+ title: "Pickup",
430
+ quantity: pickupRule.pricingMode === "per_person" ? quantity : 1,
431
+ pricingMode: pickupRule.pricingMode,
432
+ sellAmountCents: pickupSellAmountCents,
433
+ costAmountCents: pickupCostAmountCents,
434
+ unitId: null,
435
+ unitName: null,
436
+ unitType: null,
437
+ pricingCategoryId: null,
438
+ pricingCategoryName: null,
439
+ requestRef: null,
440
+ sourceRuleId: pickupRule.id,
441
+ tierId: null,
442
+ });
443
+ if (pickupRule.pricingMode === "per_booking") {
444
+ sellAmountCents += pickupRule.sellAmountCents ?? 0;
445
+ costAmountCents += pickupRule.costAmountCents ?? 0;
446
+ }
447
+ else if (pickupRule.pricingMode === "per_person") {
448
+ sellAmountCents += (pickupRule.sellAmountCents ?? 0) * quantity;
449
+ costAmountCents += (pickupRule.costAmountCents ?? 0) * quantity;
450
+ }
451
+ }
452
+ }
453
+ const preAdjustmentTotal = { sellAmountCents, costAmountCents };
454
+ const adjusted = applicableStartRule
455
+ ? applyAdjustment(preAdjustmentTotal, {
456
+ adjustmentType: applicableStartRule.adjustmentType,
457
+ sellAdjustmentCents: applicableStartRule.sellAdjustmentCents,
458
+ costAdjustmentCents: applicableStartRule.costAdjustmentCents,
459
+ adjustmentBasisPoints: applicableStartRule.adjustmentBasisPoints,
460
+ })
461
+ : { sellAmountCents, costAmountCents };
462
+ sellAmountCents = adjusted.sellAmountCents;
463
+ costAmountCents = adjusted.costAmountCents;
464
+ const startTimeAdjustmentSellAmountCents = adjusted.sellAmountCents - preAdjustmentTotal.sellAmountCents;
465
+ const startTimeAdjustmentCostAmountCents = adjusted.costAmountCents - preAdjustmentTotal.costAmountCents;
466
+ if (applicableStartRule &&
467
+ (startTimeAdjustmentSellAmountCents !== 0 || startTimeAdjustmentCostAmountCents !== 0)) {
468
+ components.push({
469
+ kind: "start_time_adjustment",
470
+ title: "Start time adjustment",
471
+ quantity: 1,
472
+ pricingMode: applicableStartRule.adjustmentType ?? "fixed",
473
+ sellAmountCents: startTimeAdjustmentSellAmountCents,
474
+ costAmountCents: startTimeAdjustmentCostAmountCents,
475
+ unitId: null,
476
+ unitName: null,
477
+ unitType: null,
478
+ pricingCategoryId: null,
479
+ pricingCategoryName: null,
480
+ requestRef: null,
481
+ sourceRuleId: applicableStartRule.id,
482
+ tierId: null,
483
+ });
484
+ }
485
+ const relevantAllotments = allotmentRows.filter((row) => {
486
+ if (row.productId !== option.productId)
487
+ return false;
488
+ if (row.optionId && row.optionId !== option.optionId)
489
+ return false;
490
+ if (row.startTimeId && row.startTimeId !== slot.startTimeId)
491
+ return false;
492
+ if (slot.dateLocal && row.validFrom && slot.dateLocal < row.validFrom)
493
+ return false;
494
+ if (slot.dateLocal && row.validTo && slot.dateLocal > row.validTo)
495
+ return false;
496
+ return true;
497
+ });
498
+ const relevantTargets = allotmentTargetRows.filter((row) => relevantAllotments.some((allotment) => allotment.id === row.allotmentId) &&
499
+ (row.slotId === slot.id || (!row.slotId && row.startTimeId === slot.startTimeId)));
500
+ let allotmentStatus = "not_applicable";
501
+ let releaseRuleId = null;
502
+ if (relevantAllotments.length > 0) {
503
+ const remaining = relevantTargets.reduce((sum, row) => sum + Math.max(0, row.remainingCapacity ?? 0), 0);
504
+ allotmentStatus = remaining > 0 ? "sellable" : "sold_out";
505
+ const firstReleaseRule = releaseRuleRows.find((row) => relevantAllotments.some((allotment) => allotment.id === row.allotmentId));
506
+ releaseRuleId = firstReleaseRule?.id ?? null;
507
+ if (allotmentStatus === "sold_out")
508
+ continue;
509
+ }
510
+ let displayCurrency = (catalogSelection ? catalogMap.get(catalogSelection.priceCatalogId)?.currencyCode : null) ??
511
+ option.productSellCurrency;
512
+ let convertedSellAmountCents = sellAmountCents;
513
+ let convertedCostAmountCents = costAmountCents;
514
+ let fx = null;
515
+ if (query.currencyCode && query.currencyCode !== displayCurrency) {
516
+ const fxRate = exchangeRateRow.find((row) => row.baseCurrency === displayCurrency && row.quoteCurrency === query.currencyCode);
517
+ if (fxRate) {
518
+ const rate = toNumeric(fxRate.rateDecimal) ?? 1;
519
+ convertedSellAmountCents = Math.round(sellAmountCents * rate);
520
+ convertedCostAmountCents = Math.round(costAmountCents * rate);
521
+ fx = {
522
+ fxRateSetId: fxRate.fxRateSetId,
523
+ baseCurrency: displayCurrency,
524
+ quoteCurrency: query.currencyCode,
525
+ rateDecimal: rate,
526
+ };
527
+ displayCurrency = query.currencyCode;
528
+ }
529
+ }
530
+ candidates.push({
531
+ product: {
532
+ id: option.productId,
533
+ name: option.productName,
534
+ },
535
+ option: {
536
+ id: option.optionId,
537
+ name: option.optionName,
538
+ code: option.optionCode,
539
+ },
540
+ slot,
541
+ market: marketRow
542
+ ? {
543
+ id: marketRow.id,
544
+ code: marketRow.code,
545
+ name: marketRow.name,
546
+ }
547
+ : null,
548
+ channel: channelRow,
549
+ sellability: {
550
+ mode: marketRule?.sellability ?? channelRule?.sellability ?? "sellable",
551
+ onRequest,
552
+ allotmentStatus,
553
+ },
554
+ pricing: {
555
+ currencyCode: displayCurrency,
556
+ sellAmountCents: convertedSellAmountCents,
557
+ costAmountCents: convertedCostAmountCents,
558
+ marginAmountCents: convertedSellAmountCents - convertedCostAmountCents,
559
+ breakdown,
560
+ components,
561
+ fx,
562
+ },
563
+ sources: {
564
+ marketProductRuleId: marketRule?.id ?? null,
565
+ marketChannelRuleId: channelRule?.id ?? null,
566
+ marketPriceCatalogId: catalogSelection?.id ?? null,
567
+ optionPriceRuleId: chosenRule.id,
568
+ optionStartTimeRuleId: applicableStartRule?.id ?? null,
569
+ channelInventoryAllotmentIds: relevantAllotments.map((row) => row.id),
570
+ channelInventoryReleaseRuleId: releaseRuleId,
571
+ },
572
+ });
573
+ }
574
+ return {
575
+ data: candidates,
576
+ meta: {
577
+ total: candidates.length,
578
+ },
579
+ };
580
+ }