@managesome/eposmatic-toolkit 0.4.1 → 0.4.3

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.
@@ -0,0 +1,382 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFormattedTenantSalesOverviewReporting = getFormattedTenantSalesOverviewReporting;
4
+ const constants_1 = require("../../constants");
5
+ const ENUMS_1 = require("../../constants/ENUMS");
6
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
7
+ const price_conversion_1 = require("../utils/price-conversion");
8
+ const key_helpers_1 = require("./key-helpers");
9
+ const materialized_reports_read_helpers_1 = require("./materialized-reports-read-helpers");
10
+ const tenant_sales_overview_helpers_1 = require("./tenant-sales-overview-helpers");
11
+ /* ------------------------------------------------------------------------ */
12
+ /* Raw (cents) accumulators */
13
+ /* ------------------------------------------------------------------------ */
14
+ const createRawOrderMetric = () => ({
15
+ count: 0,
16
+ gross_amount: 0,
17
+ discount_amount: 0,
18
+ discount_by_type: { special_discount: 0, loyalty_discount: 0, voucher_discount: 0 },
19
+ gst_amount: 0,
20
+ tax_amount: 0,
21
+ tip_amount: 0,
22
+ tax_invoice_provider_charges: 0,
23
+ delivery_charges: 0,
24
+ });
25
+ const addRawOrderMetric = (target, source) => {
26
+ if (source == null)
27
+ return;
28
+ target.count += source.count ?? 0;
29
+ target.gross_amount += source.gross_amount ?? 0;
30
+ target.discount_amount += source.discount_amount ?? 0;
31
+ target.discount_by_type.special_discount += source.discount_by_type?.special_discount ?? 0;
32
+ target.discount_by_type.loyalty_discount += source.discount_by_type?.loyalty_discount ?? 0;
33
+ target.discount_by_type.voucher_discount += source.discount_by_type?.voucher_discount ?? 0;
34
+ target.gst_amount += source.gst_amount ?? 0;
35
+ target.tax_amount += source.tax_amount ?? 0;
36
+ target.tip_amount += source.tip_amount ?? 0;
37
+ target.tax_invoice_provider_charges += source.tax_invoice_provider_charges ?? 0;
38
+ target.delivery_charges += source.delivery_charges ?? 0;
39
+ };
40
+ const toDecimal = (cents) => (0, price_conversion_1.convertPriceFromCents)(cents ?? 0);
41
+ const formatRawOrderMetric = (raw) => ({
42
+ count: raw.count,
43
+ gross_amount: toDecimal(raw.gross_amount),
44
+ discount_amount: toDecimal(raw.discount_amount),
45
+ discount_by_type: {
46
+ special_discount: toDecimal(raw.discount_by_type.special_discount),
47
+ loyalty_discount: toDecimal(raw.discount_by_type.loyalty_discount),
48
+ voucher_discount: toDecimal(raw.discount_by_type.voucher_discount),
49
+ },
50
+ gst_amount: toDecimal(raw.gst_amount),
51
+ tax_amount: toDecimal(raw.tax_amount),
52
+ tip_amount: toDecimal(raw.tip_amount),
53
+ tax_invoice_provider_charges: toDecimal(raw.tax_invoice_provider_charges),
54
+ delivery_charges: toDecimal(raw.delivery_charges),
55
+ });
56
+ /* ------------------------------------------------------------------------ */
57
+ /* Key-map filtering */
58
+ /* ------------------------------------------------------------------------ */
59
+ const getKeyDimValue = (components, keyFilters, dim) => {
60
+ const index = keyFilters.indexOf(dim);
61
+ return index >= 0 ? (components[index] ?? null) : null;
62
+ };
63
+ const matchesFilters = (components, keyFilters, filters) => {
64
+ if (filters == null)
65
+ return true;
66
+ const platforms = filters.platforms;
67
+ if (Array.isArray(platforms) && platforms.length > 0) {
68
+ const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM);
69
+ if (platform == null || !platforms.includes(platform))
70
+ return false;
71
+ }
72
+ const orderStatuses = filters.order_statuses;
73
+ if (Array.isArray(orderStatuses) && orderStatuses.length > 0) {
74
+ const status = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS);
75
+ if (status == null || !orderStatuses.includes(status))
76
+ return false;
77
+ }
78
+ return true;
79
+ };
80
+ /** Drops non-matching keys from a document's metric map (bills included). */
81
+ const pruneReportForFilters = (doc, filters) => {
82
+ const keyFilters = doc.sale_type_key_filters ?? [];
83
+ const kept = {};
84
+ for (const [key, metric] of Object.entries(doc.sale_type_metrics ?? {})) {
85
+ const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
86
+ // Unparseable key — cannot be matched; skipping keeps the sums honest
87
+ // (the write side rejects such keys, so this is defensive only).
88
+ if (components == null)
89
+ continue;
90
+ if (!matchesFilters(components, keyFilters, filters))
91
+ continue;
92
+ kept[key] = metric;
93
+ }
94
+ return { ...doc, sale_type_metrics: kept };
95
+ };
96
+ /* ------------------------------------------------------------------------ */
97
+ /* Section extraction */
98
+ /* ------------------------------------------------------------------------ */
99
+ const isCancelledKey = (components, keyFilters) => getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS) ===
100
+ constants_1.ORDER_STATUS_ENUM.CANCELLED;
101
+ /** Non-cancelled `TOTAL_SALES` aggregate of a merged document (cents). */
102
+ const extractNonCancelledTotalSales = (merged) => {
103
+ const raw = createRawOrderMetric();
104
+ const keyFilters = merged.sale_type_key_filters ?? [];
105
+ for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
106
+ const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
107
+ if (components == null || isCancelledKey(components, keyFilters))
108
+ continue;
109
+ addRawOrderMetric(raw, entry[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES]?.orders);
110
+ }
111
+ return raw;
112
+ };
113
+ const addRawPayment = (map, payment) => {
114
+ const paymentType = (0, tenant_sales_overview_helpers_1.normalizeMaterializedPaymentType)(payment.payment_type);
115
+ const entry = map[paymentType] ??
116
+ (map[paymentType] = {
117
+ payment_type: paymentType,
118
+ count: 0,
119
+ gross_amount: 0,
120
+ amount_due: 0,
121
+ amount_paid: 0,
122
+ amount_refunded: 0,
123
+ card_charges: 0,
124
+ });
125
+ entry.count += payment.count ?? 0;
126
+ entry.gross_amount += payment.gross_amount ?? 0;
127
+ entry.amount_due += payment.amount_due ?? 0;
128
+ entry.amount_paid += payment.amount_paid ?? 0;
129
+ entry.amount_refunded += payment.amount_refunded ?? 0;
130
+ entry.card_charges += payment.card_charges ?? 0;
131
+ };
132
+ const formatRawPayment = (raw, derived) => ({
133
+ payment_type: raw.payment_type,
134
+ count: raw.count,
135
+ gross_amount: toDecimal(raw.gross_amount),
136
+ amount_due: toDecimal(raw.amount_due),
137
+ amount_paid: toDecimal(raw.amount_paid),
138
+ amount_refunded: toDecimal(raw.amount_refunded),
139
+ card_charges: toDecimal(raw.card_charges),
140
+ derived,
141
+ });
142
+ /** UNPAID first, then COMPLIMENTARY, then count desc / name asc. */
143
+ const orderPayments = (payments) => {
144
+ const unpaid = payments.filter((payment) => payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.UNPAID);
145
+ const complimentary = payments.filter((payment) => payment.payment_type === constants_1.PAYMENT_TYPE_ENUM.COMPLIMENTARY);
146
+ const rest = payments
147
+ .filter((payment) => payment.payment_type !== constants_1.PAYMENT_TYPE_ENUM.UNPAID && payment.payment_type !== constants_1.PAYMENT_TYPE_ENUM.COMPLIMENTARY)
148
+ .sort((a, b) => b.count - a.count || a.payment_type.localeCompare(b.payment_type));
149
+ return [...unpaid, ...complimentary, ...rest];
150
+ };
151
+ const splitPlatformName = (platform) => {
152
+ const name = constants_1.PLATFORM_NAMES[platform] ?? platform;
153
+ const [orderFrom, ...orderTypeParts] = name.split(' ');
154
+ return { order_from: orderFrom, order_type: orderTypeParts.join(' ') };
155
+ };
156
+ /* ------------------------------------------------------------------------ */
157
+ /* Page building */
158
+ /* ------------------------------------------------------------------------ */
159
+ const uniqueTenantIds = (docs) => {
160
+ const ids = new Set();
161
+ for (const doc of docs) {
162
+ if (typeof doc.tenant_id === 'string' && doc.tenant_id.length > 0)
163
+ ids.add(doc.tenant_id);
164
+ }
165
+ return [...ids].sort();
166
+ };
167
+ const buildEmptyOrderMetric = () => formatRawOrderMetric(createRawOrderMetric());
168
+ const buildEmptyPageData = (scopeContext, tenantIds) => ({
169
+ tenant_ids: tenantIds,
170
+ summary: buildEmptyOrderMetric(),
171
+ amount_collected: buildEmptyOrderMetric(),
172
+ cancelled: buildEmptyOrderMetric(),
173
+ payments: [],
174
+ channels: [],
175
+ credit_bills: {
176
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
177
+ received: { count: 0, amount: 0 },
178
+ outstanding_amount: 0,
179
+ },
180
+ weekday: scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext) ? [] : null,
181
+ hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? [] : null,
182
+ });
183
+ const buildWeekdaySection = (scopedDocs, filters) => {
184
+ const byDayIndex = new Map();
185
+ for (const doc of scopedDocs) {
186
+ if (doc.day_index == null)
187
+ continue;
188
+ const group = byDayIndex.get(doc.day_index) ?? [];
189
+ group.push(doc);
190
+ byDayIndex.set(doc.day_index, group);
191
+ }
192
+ const result = [];
193
+ for (const dayIndex of ENUMS_1.ALL_DAY_INDEX) {
194
+ const group = byDayIndex.get(dayIndex);
195
+ if (group == null)
196
+ continue;
197
+ const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(group.map((doc) => pruneReportForFilters(doc, filters)), { allowTenantMismatch: true });
198
+ if (merged == null)
199
+ return [];
200
+ result.push({ day_index: dayIndex, metric: formatRawOrderMetric(extractNonCancelledTotalSales(merged)) });
201
+ }
202
+ return result;
203
+ };
204
+ const buildHourlySection = (scopedDocs, filters) => {
205
+ // Buckets are merged per `scope_field` — combined brand reads carry one
206
+ // document per tenant for the same hour, and the series must aggregate them.
207
+ const byScopeField = new Map();
208
+ for (const doc of scopedDocs) {
209
+ if (typeof doc.scope_field !== 'string' || doc.scope_field.length === 0)
210
+ continue;
211
+ const group = byScopeField.get(doc.scope_field) ?? [];
212
+ group.push(doc);
213
+ byScopeField.set(doc.scope_field, group);
214
+ }
215
+ const points = [];
216
+ for (const [scopeField, group] of byScopeField) {
217
+ const parts = scopeField.split(' ');
218
+ const localDate = parts[0];
219
+ const hour = Number.parseInt(parts[1] ?? '', 10);
220
+ const businessHourIndex = (0, materialized_reports_read_helpers_1.getMaterializedBusinessHourIndex)(hour);
221
+ if (localDate == null || businessHourIndex == null)
222
+ continue;
223
+ const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(group.map((doc) => pruneReportForFilters(doc, filters)), { allowTenantMismatch: true });
224
+ if (merged == null)
225
+ continue;
226
+ points.push({
227
+ local_date: localDate,
228
+ hour,
229
+ business_hour_index: businessHourIndex,
230
+ metric: formatRawOrderMetric(extractNonCancelledTotalSales(merged)),
231
+ });
232
+ }
233
+ return points.sort((a, b) => a.local_date.localeCompare(b.local_date) || a.business_hour_index - b.business_hour_index);
234
+ };
235
+ const buildPageDataForDocs = (docs, scopeContext, filters) => {
236
+ // Weekday filter is a document-level predicate (date/hour scopes only).
237
+ const dayIndexes = filters?.day_indexes;
238
+ const scopedDocs = Array.isArray(dayIndexes) && dayIndexes.length > 0
239
+ ? docs.filter((doc) => doc.day_index != null && dayIndexes.includes(doc.day_index))
240
+ : docs;
241
+ const tenantIds = uniqueTenantIds(scopedDocs);
242
+ if (scopedDocs.length === 0) {
243
+ return buildEmptyPageData(scopeContext, tenantIds);
244
+ }
245
+ // Filter the key map FIRST so the merge (and the bill ledger) only sees the
246
+ // requested slices.
247
+ const pruned = scopedDocs.map((doc) => pruneReportForFilters(doc, filters));
248
+ const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(pruned, { allowTenantMismatch: true });
249
+ if (merged == null)
250
+ return null;
251
+ const keyFilters = merged.sale_type_key_filters ?? [];
252
+ const summaryRaw = createRawOrderMetric();
253
+ const collectedRaw = createRawOrderMetric();
254
+ const cancelledRaw = createRawOrderMetric();
255
+ const paymentsMap = {};
256
+ const channelsMap = {};
257
+ const issuedRaw = { count: 0, amount: 0, settled_count: 0, settled_amount: 0 };
258
+ const receivedRaw = { count: 0, amount: 0 };
259
+ for (const [key, entry] of Object.entries(merged.sale_type_metrics ?? {})) {
260
+ const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
261
+ if (components == null)
262
+ continue;
263
+ const totalSales = entry[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
264
+ const amountCollected = entry[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
265
+ const creditBills = entry[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
266
+ // Cancelled facet: cancelled orders are materialized under `CANCELLED:*`
267
+ // keys and excluded from every other facet (payments included).
268
+ if (isCancelledKey(components, keyFilters)) {
269
+ addRawOrderMetric(cancelledRaw, totalSales?.orders);
270
+ continue;
271
+ }
272
+ addRawOrderMetric(summaryRaw, totalSales?.orders);
273
+ addRawOrderMetric(collectedRaw, amountCollected?.orders);
274
+ for (const payment of totalSales?.payments ?? []) {
275
+ addRawPayment(paymentsMap, payment);
276
+ }
277
+ issuedRaw.count += creditBills?.issued?.count ?? 0;
278
+ issuedRaw.amount += creditBills?.issued?.amount ?? 0;
279
+ issuedRaw.settled_count += creditBills?.issued?.settled_count ?? 0;
280
+ issuedRaw.settled_amount += creditBills?.issued?.settled_amount ?? 0;
281
+ receivedRaw.count += creditBills?.received?.count ?? 0;
282
+ receivedRaw.amount += creditBills?.received?.amount ?? 0;
283
+ const platform = getKeyDimValue(components, keyFilters, MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_KEY_FILTER_ENUM.PLATFORM) ?? '';
284
+ const channel = channelsMap[platform] ?? (channelsMap[platform] = { platform, count: 0, gross_amount: 0 });
285
+ channel.count += totalSales?.orders?.count ?? 0;
286
+ channel.gross_amount += totalSales?.orders?.gross_amount ?? 0;
287
+ }
288
+ const payments = orderPayments(Object.values(paymentsMap).map((raw) => formatRawPayment(raw, false)));
289
+ // Derived settlement line — composed ONLY from the ledger's `received`
290
+ // bucket (the formatter counts a receipt exactly once).
291
+ if (receivedRaw.count > 0 || receivedRaw.amount !== 0) {
292
+ payments.push(formatRawPayment({
293
+ payment_type: MATERIALIZED_REPORTS_1.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE,
294
+ count: receivedRaw.count,
295
+ gross_amount: receivedRaw.amount,
296
+ amount_due: 0,
297
+ amount_paid: 0,
298
+ amount_refunded: 0,
299
+ card_charges: 0,
300
+ }, true));
301
+ }
302
+ const channels = Object.values(channelsMap)
303
+ .map((channel) => ({
304
+ platform: channel.platform,
305
+ ...splitPlatformName(channel.platform),
306
+ count: channel.count,
307
+ gross_amount: toDecimal(channel.gross_amount),
308
+ }))
309
+ .sort((a, b) => b.count - a.count || a.platform.localeCompare(b.platform));
310
+ const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
311
+ return {
312
+ tenant_ids: tenantIds,
313
+ summary: formatRawOrderMetric(summaryRaw),
314
+ amount_collected: formatRawOrderMetric(collectedRaw),
315
+ cancelled: formatRawOrderMetric(cancelledRaw),
316
+ payments,
317
+ channels,
318
+ credit_bills: {
319
+ issued: {
320
+ count: issuedRaw.count,
321
+ amount: toDecimal(issuedRaw.amount),
322
+ settled_count: issuedRaw.settled_count,
323
+ settled_amount: toDecimal(issuedRaw.settled_amount),
324
+ },
325
+ received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
326
+ outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
327
+ },
328
+ weekday: supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null,
329
+ hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null,
330
+ };
331
+ };
332
+ /* ------------------------------------------------------------------------ */
333
+ /* Public API */
334
+ /* ------------------------------------------------------------------------ */
335
+ /**
336
+ * Formats materialized overview documents into page-ready data (see the
337
+ * module docblock for the full contract). Returns
338
+ * `[formattedPageData[], null]` — with `separate_view_per_tenant: true` one
339
+ * entry per tenant (comparative view seam; the analysis result is TBD), the
340
+ * default mode returns a single combined entry. Returns `null` (never throws)
341
+ * when the documents cannot be formatted together.
342
+ */
343
+ function getFormattedTenantSalesOverviewReporting(docs, filters = null, separate_view_per_tenant = false) {
344
+ if (!Array.isArray(docs) || docs.some((doc) => doc == null)) {
345
+ return null;
346
+ }
347
+ const scopeContext = docs.length > 0 ? docs[0].scope_context : null;
348
+ if (docs.length > 0) {
349
+ const first = docs[0];
350
+ const keyFilterSignature = (first.sale_type_key_filters ?? []).join(':');
351
+ for (const doc of docs) {
352
+ if (doc.scope_context !== first.scope_context ||
353
+ doc.schema_version !== first.schema_version ||
354
+ (doc.sale_type_key_filters ?? []).join(':') !== keyFilterSignature) {
355
+ return null;
356
+ }
357
+ }
358
+ }
359
+ const groups = [];
360
+ if (separate_view_per_tenant) {
361
+ const byTenant = new Map();
362
+ for (const doc of docs) {
363
+ const group = byTenant.get(doc.tenant_id) ?? [];
364
+ group.push(doc);
365
+ byTenant.set(doc.tenant_id, group);
366
+ }
367
+ for (const tenantId of [...byTenant.keys()].sort()) {
368
+ groups.push(byTenant.get(tenantId));
369
+ }
370
+ }
371
+ else {
372
+ groups.push(docs);
373
+ }
374
+ const results = [];
375
+ for (const group of groups) {
376
+ const pageData = buildPageDataForDocs(group, scopeContext, filters);
377
+ if (pageData == null)
378
+ return null;
379
+ results.push(pageData);
380
+ }
381
+ return [results, null];
382
+ }
@@ -149,10 +149,13 @@ export declare function convertMaterializedTenantSalesOverviewReportJsonToBson(r
149
149
  *
150
150
  * Returns `null` (never throws) when the inputs cannot be summed — empty list
151
151
  * or mismatched tenant / brand / schema version / key filters. `null` means a
152
- * data issue the caller must surface.
152
+ * data issue the caller must surface. Pass `allowTenantMismatch: true` for the
153
+ * brand-level combined read (cross-tenant sums; same brand / schema version /
154
+ * key filters required).
153
155
  */
154
156
  export declare function sumMaterializedTenantSalesOverviewReports(reports: IMaterializedTenantSalesOverviewReport[], options?: {
155
157
  computedAt?: Date;
158
+ allowTenantMismatch?: boolean;
156
159
  }): IMaterializedTenantSalesOverviewReport | null;
157
160
  /**
158
161
  * Subtracts `subtrahend`'s metric tree from `minuend` — the first half of the
@@ -648,6 +648,14 @@ const canMergeMaterializedReports = (base, other) => base.tenant_id === other.te
648
648
  base.brand_id === other.brand_id &&
649
649
  base.schema_version === other.schema_version &&
650
650
  base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
651
+ /**
652
+ * Same brand / schema version / key filters — mergeable ACROSS tenants (the
653
+ * brand-level combined read). Order ids are unique across tenants, so the
654
+ * `(order_id, payment_id)` bill de-dupe stays correct.
655
+ */
656
+ const canMergeMaterializedReportsIgnoringTenant = (base, other) => base.brand_id === other.brand_id &&
657
+ base.schema_version === other.schema_version &&
658
+ base.sale_type_key_filters.join(':') === other.sale_type_key_filters.join(':');
651
659
  /** Sums one report's metric tree into a mutable accumulator. */
652
660
  const applyReportAddition = (metrics, report) => {
653
661
  for (const [key, metric] of Object.entries(normalizeMaterializedSaleTypeMetrics(report.sale_type_metrics))) {
@@ -725,15 +733,21 @@ const dedupeAllBillLedgers = (metrics) => {
725
733
  *
726
734
  * Returns `null` (never throws) when the inputs cannot be summed — empty list
727
735
  * or mismatched tenant / brand / schema version / key filters. `null` means a
728
- * data issue the caller must surface.
736
+ * data issue the caller must surface. Pass `allowTenantMismatch: true` for the
737
+ * brand-level combined read (cross-tenant sums; same brand / schema version /
738
+ * key filters required).
729
739
  */
730
740
  function sumMaterializedTenantSalesOverviewReports(reports, options = {}) {
731
741
  if (!Array.isArray(reports) || reports.length === 0) {
732
742
  return null;
733
743
  }
744
+ const allowTenantMismatch = options.allowTenantMismatch === true;
734
745
  const [base, ...rest] = reports;
735
746
  for (const report of rest) {
736
- if (!canMergeMaterializedReports(base, report)) {
747
+ const mergeable = allowTenantMismatch
748
+ ? canMergeMaterializedReportsIgnoringTenant(base, report)
749
+ : canMergeMaterializedReports(base, report);
750
+ if (!mergeable) {
737
751
  return null;
738
752
  }
739
753
  }
@@ -15,6 +15,7 @@ export * from './internal-leads';
15
15
  export * from './inventory-catalog';
16
16
  export * from './kpra-generate-invoice';
17
17
  export * from './marketing';
18
+ export * from './materialized-reports-apis';
18
19
  export * from './order-engine';
19
20
  export * from './pra-generate-invoice';
20
21
  export * from './report-webview';
@@ -31,6 +31,7 @@ __exportStar(require("./internal-leads"), exports);
31
31
  __exportStar(require("./inventory-catalog"), exports);
32
32
  __exportStar(require("./kpra-generate-invoice"), exports);
33
33
  __exportStar(require("./marketing"), exports);
34
+ __exportStar(require("./materialized-reports-apis"), exports);
34
35
  __exportStar(require("./order-engine"), exports);
35
36
  __exportStar(require("./pra-generate-invoice"), exports);
36
37
  __exportStar(require("./report-webview"), exports);
@@ -0,0 +1,65 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants';
2
+ /**
3
+ * Request body contracts for the materialized reports READ APIs
4
+ * (operations-service, mounted at `/reports`) — shared between
5
+ * the backend service and the reports frontend so both sides agree on the
6
+ * wire shape.
7
+ *
8
+ * Every endpoint takes the tenant scope as an ARRAY (`tenants`, minimum
9
+ * length 1) so a single call can serve one tenant or many (brand-level
10
+ * reports). Responses are the persisted documents themselves (see
11
+ * `IMaterializedTenantSalesOverviewReport` /
12
+ * `IMaterializedTenantReportIteration`) — amounts are INTEGER CENTS.
13
+ */
14
+ /**
15
+ * Body of `POST /reports/overview` — materialized sales overview
16
+ * documents (`materialized_tenant_sales_overview_reports`).
17
+ *
18
+ * The scope query is either the exact `scope_field`, or the inclusive
19
+ * lexicographic range `from`..`to` (all scope_field formats are fixed-width,
20
+ * so lexicographic order equals chronological order).
21
+ */
22
+ export interface IGetMaterializedTenantSalesOverviewReportsBody {
23
+ /** One or more tenant ids to read (minimum length 1). */
24
+ tenants: string[];
25
+ /**
26
+ * Scope granularity — one of `MATERIALIZED_REPORT_SCOPE_ENUM`. Optional;
27
+ * the backend defaults to `LOCAL_DATE`.
28
+ */
29
+ scope_context?: MATERIALIZED_REPORT_SCOPE_ENUM;
30
+ /** Exact scope value (e.g. '2026-09-30' or '2026-09-30 18'). */
31
+ scope_field?: string;
32
+ /**
33
+ * Inclusive lower bound on `scope_field` — required together with `to` when
34
+ * `scope_field` is absent.
35
+ */
36
+ from?: string;
37
+ /**
38
+ * Inclusive upper bound on `scope_field` — required together with `from`
39
+ * when `scope_field` is absent.
40
+ */
41
+ to?: string;
42
+ }
43
+ /**
44
+ * Body of `POST /reports/iterations` — the latest stored versions
45
+ * of ONE report document from `materialized_tenant_reports_iterations` (the
46
+ * shared version history of every materialized report collection). Rows
47
+ * return newest-first, each carrying the full post-write `snapshot`.
48
+ */
49
+ export interface IGetMaterializedReportIterationsBody {
50
+ /**
51
+ * One or more tenant ids — every returned row is guarded by the snapshot's
52
+ * `tenant_id` (the report itself is addressed by `report_id` alone).
53
+ */
54
+ tenants: string[];
55
+ /** `_id` of the report document (the `report_id` of the history rows). */
56
+ report_id: string;
57
+ /**
58
+ * Which report collection `report_id` belongs to
59
+ * (`MATERIALIZED_REPORT_TYPE_ENUM`). Optional; defaults to
60
+ * `TENANT_SALES_OVERVIEW`.
61
+ */
62
+ report_type?: MATERIALIZED_REPORT_TYPE_ENUM;
63
+ /** Latest N iterations, newest-first. Optional; default 5, capped at 50. */
64
+ limit?: number;
65
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });