@managesome/eposmatic-toolkit 0.4.58 → 0.4.60

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 (54) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +41 -0
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-day-readiness.js +94 -0
  4. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +3 -0
  5. package/esm/helpers/materialized-reports/report-platform/definition.js +12 -2
  6. package/esm/helpers/order/generate-warehouse-purchase-order.js +3 -0
  7. package/esm/helpers/reporting-contract/report-contract.js +12 -0
  8. package/esm/helpers/store/common-tenant-purchase-order-actions.js +23 -0
  9. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +21 -0
  10. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +60 -12
  11. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +58 -13
  12. package/esm/schemas/models/index.js +1 -0
  13. package/esm/schemas/models/materialized_tenant_day_readiness.js +66 -0
  14. package/esm/schemas/models/tenant_purchase_orders.js +36 -0
  15. package/esm/schemas/models/warehouse_purchase_orders.js +48 -0
  16. package/esm/schemas/types/index.js +1 -0
  17. package/esm/schemas/types/materialized_tenant_day_readiness.js +1 -0
  18. package/lib/constants/MATERIALIZED_REPORTS.d.ts +38 -0
  19. package/lib/constants/MATERIALIZED_REPORTS.js +42 -1
  20. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  21. package/lib/helpers/materialized-reports/index.js +1 -0
  22. package/lib/helpers/materialized-reports/materialized-day-readiness.d.ts +84 -0
  23. package/lib/helpers/materialized-reports/materialized-day-readiness.js +100 -0
  24. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +3 -0
  25. package/lib/helpers/materialized-reports/report-platform/definition.js +12 -2
  26. package/lib/helpers/order/generate-warehouse-purchase-order.js +3 -0
  27. package/lib/helpers/reporting-contract/report-contract.d.ts +13 -1
  28. package/lib/helpers/reporting-contract/report-contract.js +12 -0
  29. package/lib/helpers/store/common-tenant-purchase-order-actions.d.ts +2 -1
  30. package/lib/helpers/store/common-tenant-purchase-order-actions.js +24 -0
  31. package/lib/helpers/store/common-warehouse-purchase-order-actions.d.ts +2 -1
  32. package/lib/helpers/store/common-warehouse-purchase-order-actions.js +22 -0
  33. package/lib/helpers/store/tenant-purchase-orders-cart-actions.d.ts +15 -1
  34. package/lib/helpers/store/tenant-purchase-orders-cart-actions.js +61 -12
  35. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.d.ts +10 -1
  36. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.js +59 -13
  37. package/lib/schemas/models/index.d.ts +1 -0
  38. package/lib/schemas/models/index.js +1 -0
  39. package/lib/schemas/models/materialized_tenant_day_readiness.d.ts +78 -0
  40. package/lib/schemas/models/materialized_tenant_day_readiness.js +69 -0
  41. package/lib/schemas/models/orders.d.ts +240 -240
  42. package/lib/schemas/models/tenant_purchase_orders.d.ts +132 -0
  43. package/lib/schemas/models/tenant_purchase_orders.js +36 -0
  44. package/lib/schemas/models/warehouse_purchase_orders.d.ts +132 -0
  45. package/lib/schemas/models/warehouse_purchase_orders.js +48 -0
  46. package/lib/schemas/types/index.d.ts +1 -0
  47. package/lib/schemas/types/index.js +1 -0
  48. package/lib/schemas/types/materialized_tenant_day_readiness.d.ts +28 -0
  49. package/lib/schemas/types/materialized_tenant_day_readiness.js +2 -0
  50. package/lib/schemas/types/tenant_purchase_orders.d.ts +28 -0
  51. package/lib/schemas/types/warehouse_purchase_orders.d.ts +12 -0
  52. package/lib/tests/materialized-reports/materialized-day-readiness.test.d.ts +1 -0
  53. package/lib/tests/materialized-reports/materialized-day-readiness.test.js +64 -0
  54. package/package.json +1 -1
@@ -898,3 +898,44 @@ export const MATERIALIZED_DIALER_HOUR_KEYS = Array.from({ length: 24 }, (_, hour
898
898
  */
899
899
  export const MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES = 15 * 1024 * 1024;
900
900
  export const MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES = 15 * 1024 * 1024;
901
+ /* ======================================================================== */
902
+ /* Day readiness (five production writers) */
903
+ /* ======================================================================== */
904
+ /**
905
+ * COMMITTED-READINESS ledger for the five reports written by END_TENANT_DAY and
906
+ * the range sync: Overview, Discounts, Prep Time, Delivery and Dialer.
907
+ *
908
+ * One row per (tenant_id, localDate, report_key, schema_version). The row is
909
+ * written in the SAME transaction/session as the report documents, so it can
910
+ * never disagree with them: a transaction that aborts leaves no readiness row,
911
+ * and a row can only exist when every report document of that day committed
912
+ * together (or the day was genuinely empty).
913
+ *
914
+ * Historical reads check this ledger AFTER the closed-day validation and BEFORE
915
+ * any report document read:
916
+ * - missing row(s) -> 409 HISTORICAL_NOT_MATERIALIZED;
917
+ * - NEEDS_RECONCILIATION -> 409 HISTORICAL_NEEDS_RECONCILIATION.
918
+ *
919
+ * The four out-of-scope reports (Cash In/Out, Sales Comparison, Hourly
920
+ * Comparison, Payments Comparison) deliberately have NO readiness rows.
921
+ */
922
+ export const MATERIALIZED_TENANT_DAY_READINESS_COLLECTION_NAME = 'materialized_tenant_day_readiness';
923
+ /** Version of the readiness row shape. Pinned to 1 with the other collections. */
924
+ export const MATERIALIZED_TENANT_DAY_READINESS_SCHEMA_VERSION = 1;
925
+ /** The readiness state of one tenant-day-report. */
926
+ export var MATERIALIZED_REPORT_READINESS_STATUS_ENUM;
927
+ (function (MATERIALIZED_REPORT_READINESS_STATUS_ENUM) {
928
+ /** Every document of the tenant-day-report committed together. */
929
+ MATERIALIZED_REPORT_READINESS_STATUS_ENUM["COMMITTED"] = "COMMITTED";
930
+ /**
931
+ * The day committed, but a known gap makes the stored report untrustworthy
932
+ * as final. Delivery sets this when a stale cross-day update was skipped.
933
+ */
934
+ MATERIALIZED_REPORT_READINESS_STATUS_ENUM["NEEDS_RECONCILIATION"] = "NEEDS_RECONCILIATION";
935
+ })(MATERIALIZED_REPORT_READINESS_STATUS_ENUM || (MATERIALIZED_REPORT_READINESS_STATUS_ENUM = {}));
936
+ export const ALL_MATERIALIZED_REPORT_READINESS_STATUSES = Object.values(MATERIALIZED_REPORT_READINESS_STATUS_ENUM);
937
+ /**
938
+ * The ONLY reports that own a readiness row. Adding another report here means
939
+ * giving it a writer that participates in the same day transaction.
940
+ */
941
+ export const MATERIALIZED_READINESS_REPORT_KEYS = ['OVERVIEW', 'DISCOUNTS', 'PREP_TIME', 'DELIVERY', 'DIALER'];
@@ -1,5 +1,6 @@
1
1
  export * from './key-helpers';
2
2
  export * from './materialized-credit-bills-helpers';
3
+ export * from './materialized-day-readiness';
3
4
  export * from './materialized-index-bootstrap';
4
5
  export * from './materialized-integer-contract';
5
6
  export * from './materialized-discount-accumulator-helpers';
@@ -0,0 +1,94 @@
1
+ import { MATERIALIZED_READINESS_REPORT_KEYS, MATERIALIZED_REPORT_READINESS_STATUS_ENUM, MATERIALIZED_TENANT_DAY_READINESS_SCHEMA_VERSION, } from '../../constants/MATERIALIZED_REPORTS';
2
+ const uniqueSorted = (values) => [...new Set(values)].sort();
3
+ /** Whether `report` is one of the FIVE reports that own readiness rows. */
4
+ export function isMaterializedReadinessReportKey(report) {
5
+ return MATERIALIZED_READINESS_REPORT_KEYS.includes(report);
6
+ }
7
+ /**
8
+ * The readiness doc identity key. Kept as a string so the same helper can index
9
+ * a Map and build a Mongo filter.
10
+ */
11
+ export function materializedDayReadinessKey(parts) {
12
+ return [
13
+ String(parts.tenantId),
14
+ String(parts.localDate),
15
+ String(parts.reportKey),
16
+ String(parts.schemaVersion ?? MATERIALIZED_TENANT_DAY_READINESS_SCHEMA_VERSION),
17
+ ].join('|');
18
+ }
19
+ /**
20
+ * Summarizes the readiness gap of a historical read.
21
+ *
22
+ * - A requested pair with NO record is MISSING.
23
+ * - A requested pair whose record is not COMMITTED (i.e.
24
+ * NEEDS_RECONCILIATION) is not final; it is reported separately.
25
+ * - Records for another report key / schema version are ignored, so a stale
26
+ * writer version can never satisfy a v1 read.
27
+ *
28
+ * The two failure families are mutually exclusive by precedence: the caller
29
+ * answers MISSING first, then NEEDS_RECONCILIATION.
30
+ */
31
+ export function summarizeMaterializedDayReadiness(input) {
32
+ const schemaVersion = input.schemaVersion ?? MATERIALIZED_TENANT_DAY_READINESS_SCHEMA_VERSION;
33
+ const tenants = uniqueSorted((input.tenants ?? []).map((tenant) => String(tenant).trim()).filter((tenant) => tenant !== ''));
34
+ const dates = uniqueSorted((input.dates ?? []).map((date) => String(date).trim()).filter((date) => date !== ''));
35
+ const byKey = new Map();
36
+ for (const record of input.records ?? []) {
37
+ if (record == null)
38
+ continue;
39
+ if (String(record.report_key) !== String(input.reportKey))
40
+ continue;
41
+ if (Number(record.schema_version) !== Number(schemaVersion))
42
+ continue;
43
+ byKey.set(materializedDayReadinessKey({
44
+ tenantId: String(record.tenant_id),
45
+ localDate: String(record.localDate),
46
+ reportKey: String(record.report_key),
47
+ schemaVersion: Number(record.schema_version),
48
+ }), record);
49
+ }
50
+ const missingPairs = [];
51
+ const needsPairs = [];
52
+ for (const tenant_id of tenants) {
53
+ for (const localDate of dates) {
54
+ const key = materializedDayReadinessKey({
55
+ tenantId: tenant_id,
56
+ localDate,
57
+ reportKey: input.reportKey,
58
+ schemaVersion,
59
+ });
60
+ const record = byKey.get(key);
61
+ if (record == null) {
62
+ missingPairs.push({ tenant_id, localDate });
63
+ continue;
64
+ }
65
+ if (record.status !== MATERIALIZED_REPORT_READINESS_STATUS_ENUM.COMMITTED) {
66
+ needsPairs.push({ tenant_id, localDate });
67
+ }
68
+ }
69
+ }
70
+ return {
71
+ missing_tenants: uniqueSorted(missingPairs.map((pair) => pair.tenant_id)),
72
+ missing_dates: uniqueSorted(missingPairs.map((pair) => pair.localDate)),
73
+ needs_reconciliation_tenants: uniqueSorted(needsPairs.map((pair) => pair.tenant_id)),
74
+ needs_reconciliation_dates: uniqueSorted(needsPairs.map((pair) => pair.localDate)),
75
+ missing_pairs: missingPairs,
76
+ needs_reconciliation_pairs: needsPairs,
77
+ };
78
+ }
79
+ export function buildMaterializedDayReadinessDocument(input) {
80
+ if (!isMaterializedReadinessReportKey(String(input.reportKey))) {
81
+ throw new Error('buildMaterializedDayReadinessDocument: report ' +
82
+ String(input.reportKey) +
83
+ ' is outside the five report readiness contract');
84
+ }
85
+ return {
86
+ tenant_id: String(input.tenantId),
87
+ localDate: String(input.localDate),
88
+ report_key: String(input.reportKey),
89
+ schema_version: input.schemaVersion ?? MATERIALIZED_TENANT_DAY_READINESS_SCHEMA_VERSION,
90
+ status: input.status,
91
+ run_id: String(input.runId),
92
+ committed_at: input.committedAt,
93
+ };
94
+ }
@@ -5,6 +5,8 @@ import { MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME, MATERIALIZED_TENA
5
5
  import { MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_COLLECTION_NAME, MATERIALIZED_TENANT_DELIVERY_GEO_CELLS_INDEX_OPTIONS, } from '../../schemas/models/materialized_tenant_delivery_geo_cells';
6
6
  import { MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_INDEX_OPTIONS } from '../../schemas/models/materialized_tenant_delivery_geo_scopes';
7
7
  import { MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME, MATERIALIZED_TENANT_DELIVERY_REPORTS_INDEX_OPTIONS, } from '../../schemas/models/materialized_tenant_delivery_reports';
8
+ import { MATERIALIZED_TENANT_DAY_READINESS_COLLECTION_NAME } from '../../constants/MATERIALIZED_REPORTS';
9
+ import { MATERIALIZED_TENANT_DAY_READINESS_INDEX_OPTIONS } from '../../schemas/models/materialized_tenant_day_readiness';
8
10
  import { MATERIALIZED_TENANT_DIALER_ENTRIES_COLLECTION_NAME, MATERIALIZED_TENANT_DIALER_ENTRIES_INDEX_OPTIONS, } from '../../schemas/models/materialized_tenant_dialer_entries';
9
11
  import { MATERIALIZED_TENANT_DIALER_REPORTS_COLLECTION_NAME, MATERIALIZED_TENANT_DIALER_REPORTS_INDEX_OPTIONS, } from '../../schemas/models/materialized_tenant_dialer_reports';
10
12
  import { MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME, MATERIALIZED_TENANT_DISCOUNT_ENTRIES_INDEX_OPTIONS, } from '../../schemas/models/materialized_tenant_discount_entries';
@@ -44,6 +46,7 @@ const INDEXES = {
44
46
  [MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_COLLECTION_NAME]: MATERIALIZED_TENANT_DELIVERY_GEO_SCOPES_INDEX_OPTIONS,
45
47
  [MATERIALIZED_TENANT_DELIVERY_ENTRIES_COLLECTION_NAME]: MATERIALIZED_TENANT_DELIVERY_ENTRIES_INDEX_OPTIONS,
46
48
  [MATERIALIZED_TENANT_DELIVERY_REPORTS_COLLECTION_NAME]: MATERIALIZED_TENANT_DELIVERY_REPORTS_INDEX_OPTIONS,
49
+ [MATERIALIZED_TENANT_DAY_READINESS_COLLECTION_NAME]: MATERIALIZED_TENANT_DAY_READINESS_INDEX_OPTIONS,
47
50
  [MATERIALIZED_TENANT_DIALER_REPORTS_COLLECTION_NAME]: MATERIALIZED_TENANT_DIALER_REPORTS_INDEX_OPTIONS,
48
51
  [MATERIALIZED_TENANT_DIALER_ENTRIES_COLLECTION_NAME]: MATERIALIZED_TENANT_DIALER_ENTRIES_INDEX_OPTIONS,
49
52
  [MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME]: MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS,
@@ -156,6 +156,7 @@ const OVERVIEW_DEFINITION = {
156
156
  'Map-only counters: no sales_overview_counter_rows.',
157
157
  'LIVE is raw + stored credit ledger and resolves the running day server-side.',
158
158
  'Writes the credit ledger and may patch prior issue-day counters.',
159
+ 'Writes a COMMITTED materialized_tenant_day_readiness row in the SAME transaction.',
159
160
  ],
160
161
  };
161
162
  const DISCOUNTS_DEFINITION = {
@@ -242,6 +243,7 @@ const DISCOUNTS_DEFINITION = {
242
243
  'Month-capped scope set; a wider selection is refused, never narrowed.',
243
244
  'Page-partitioned entries; no #N splitter and no budget assertion today.',
244
245
  'Derived source projection has no independent iteration history.',
246
+ 'Writes a COMMITTED materialized_tenant_day_readiness row in the SAME transaction.',
245
247
  ],
246
248
  };
247
249
  const PREP_TIME_DEFINITION = {
@@ -311,6 +313,7 @@ const PREP_TIME_DEFINITION = {
311
313
  'Coverage-first counters: MEASURED/UNMEASURED anchor split and target provenance.',
312
314
  'No hour scope; entries are one document per scope, not pages.',
313
315
  'Item reads are capped at 31 effective days at the route.',
316
+ 'Writes a COMMITTED materialized_tenant_day_readiness row in the SAME transaction.',
314
317
  ],
315
318
  };
316
319
  const DELIVERY_DEFINITION = {
@@ -409,7 +412,10 @@ const DELIVERY_DEFINITION = {
409
412
  mode: 'SERVER',
410
413
  appliesTo: 'BOTH',
411
414
  },
412
- { id: 'RIDER_ID', kind: 'ROW', mode: 'SERVER', appliesTo: 'BOTH' },
415
+ // Rider is NOT a delivery request filter. Rider ids are high-cardinality and
416
+ // rider analysis is a bounded `riders` map inside each document; a
417
+ // `rider_id` request is REJECTED (400 INVALID_REQUEST,
418
+ // details.unsupported_filters: ["rider_id"]) instead of silently ignored.
413
419
  { id: 'DETAILS_VIEW', kind: 'REQUEST', mode: 'SERVER', appliesTo: 'DETAILS' },
414
420
  ],
415
421
  cursor: REPORT_CURSOR_KIND.KEYSET_STRUCTURED,
@@ -424,7 +430,10 @@ const DELIVERY_DEFINITION = {
424
430
  'Separate H3 geo collection and cap metadata; live geo is computed in memory.',
425
431
  'Cross-day completion re-materializes the prior ORDER day within the same transaction.',
426
432
  'Page entries split deterministically into #N sub-pages.',
427
- 'Historical totals do not pin schema_version today (baseline debt).',
433
+ 'Historical totals PIN schema_version (mixed-version documents are never summed).',
434
+ 'A skipped stale cross-day update writes readiness NEEDS_RECONCILIATION, never COMMITTED.',
435
+ 'Writes its materialized_tenant_day_readiness row in the SAME transaction.',
436
+ 'Rider is not a request filter; rider_id is rejected with 400 INVALID_REQUEST.',
428
437
  ],
429
438
  };
430
439
  const DIALER_DEFINITION = {
@@ -507,6 +516,7 @@ const DIALER_DEFINITION = {
507
516
  'Counters are filtered by ACTION / POS_ID / STAFF_ID key components server-side.',
508
517
  'Page entries split deterministically into #N sub-pages when over the 15 MiB budget.',
509
518
  'Late events are not included until the day is re-closed.',
519
+ 'Writes a COMMITTED materialized_tenant_day_readiness row in the SAME transaction.',
510
520
  ],
511
521
  };
512
522
  export const REPORT_DEFINITIONS = {
@@ -18,6 +18,7 @@ function getCommonOptionalBoolFieldsPurchaseOrderIteration(order, partial) {
18
18
  const defaultValue = partial ? undefined : false;
19
19
  return {
20
20
  is_gst_inclusive: order.is_gst_inclusive || defaultValue,
21
+ exclude_discount_from_gst: order.exclude_discount_from_gst || defaultValue,
21
22
  };
22
23
  }
23
24
  function getCommonOptionalNumFieldsPurchaseOrderIteration(order, partial) {
@@ -25,6 +26,7 @@ function getCommonOptionalNumFieldsPurchaseOrderIteration(order, partial) {
25
26
  return {
26
27
  gst: order.gst || defaultValue,
27
28
  gst_amount: order.gst_amount || defaultValue,
29
+ total_discount_applied: order.total_discount_applied || defaultValue,
28
30
  };
29
31
  }
30
32
  export function generateWarehousePurchaseOrderIteration(order, partial = true, skipItemMetadata) {
@@ -45,6 +47,7 @@ export function generateWarehousePurchaseOrderIteration(order, partial = true, s
45
47
  price: order.price,
46
48
  amount_earned: order.amount_earned,
47
49
  grand_total: order.grand_total,
50
+ order_discount_details: order.order_discount_details ?? undefined,
48
51
  tax_number: order.tax_number,
49
52
  updatedAt: order.updatedAt,
50
53
  };
@@ -107,6 +107,18 @@ export var REPORT_ERROR_CODE_ENUM;
107
107
  REPORT_ERROR_CODE_ENUM["INVALID_BASELINE"] = "INVALID_BASELINE";
108
108
  REPORT_ERROR_CODE_ENUM["INVALID_CURSOR"] = "INVALID_CURSOR";
109
109
  REPORT_ERROR_CODE_ENUM["DRILLDOWN_PROJECTION_UNAVAILABLE"] = "DRILLDOWN_PROJECTION_UNAVAILABLE";
110
+ /**
111
+ * Historical read of a report/day that was never materialized (no committed
112
+ * readiness row). HTTP 409; details: { report, missing_tenants, missing_dates }.
113
+ */
114
+ REPORT_ERROR_CODE_ENUM["HISTORICAL_NOT_MATERIALIZED"] = "HISTORICAL_NOT_MATERIALIZED";
115
+ /**
116
+ * Historical read whose committed readiness row says the report is not final
117
+ * (e.g. Delivery skipped a stale cross-day update). HTTP 409; details:
118
+ * { report, missing_tenants, missing_dates } (the tenants/days awaiting
119
+ * reconciliation).
120
+ */
121
+ REPORT_ERROR_CODE_ENUM["HISTORICAL_NEEDS_RECONCILIATION"] = "HISTORICAL_NEEDS_RECONCILIATION";
110
122
  })(REPORT_ERROR_CODE_ENUM || (REPORT_ERROR_CODE_ENUM = {}));
111
123
  const isNonEmptyString = (value) => typeof value === 'string' && value.trim() !== '';
112
124
  const toIsoString = (value) => {
@@ -46,6 +46,19 @@ export function getTenantPurchaseOrderCategoriesWithPrice(categories, convertToP
46
46
  items: getTenantPurchaseOrderItemsWithPrice(category.items, convertToPrice),
47
47
  }));
48
48
  }
49
+ export function getTenantPurchaseOrderDiscountDetailsWithPrice(discount, convertToPrice) {
50
+ if (!discount)
51
+ return null;
52
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
53
+ return {
54
+ ...discount,
55
+ // Percentage values are not prices, so only fixed amounts are converted.
56
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
57
+ ? { special_discount: convertToPrice(special_discount) }
58
+ : {}),
59
+ total_discount: convertToPrice(total_discount ?? 0),
60
+ };
61
+ }
49
62
  export function getTenantPurchaseOrderWithPrice(order, writeable) {
50
63
  const convertToPrice = writeable ? convertDecimalToInt : convertIntToDecimal;
51
64
  const payload = {
@@ -71,6 +84,14 @@ export function getTenantPurchaseOrderWithPrice(order, writeable) {
71
84
  ...(order.amount_earned != null ? { amount_earned: convertToPrice(order.amount_earned) } : {}),
72
85
  ...(order.grand_total != null ? { grand_total: convertToPrice(order.grand_total) } : {}),
73
86
  ...(order.price != null ? { price: convertToPrice(order.price) } : {}),
87
+ ...(order.order_discount_details != null
88
+ ? {
89
+ order_discount_details: getTenantPurchaseOrderDiscountDetailsWithPrice(order.order_discount_details, convertToPrice),
90
+ }
91
+ : {}),
92
+ ...(order.total_discount_applied != null
93
+ ? { total_discount_applied: convertToPrice(order.total_discount_applied) }
94
+ : {}),
74
95
  };
75
96
  return payload;
76
97
  }
@@ -108,6 +129,7 @@ function getCommonOptionalBoolFieldsTenantPurchaseOrder(order, partial) {
108
129
  return {
109
130
  is_gst_inclusive: order['is_gst_inclusive'] || defaultValue,
110
131
  is_reopened: order['is_reopened'] || defaultValue,
132
+ exclude_discount_from_gst: order['exclude_discount_from_gst'] || defaultValue,
111
133
  };
112
134
  }
113
135
  function getCommonOptionalNumFieldsTenantPurchaseOrder(order, partial) {
@@ -115,6 +137,7 @@ function getCommonOptionalNumFieldsTenantPurchaseOrder(order, partial) {
115
137
  return {
116
138
  gst: order['gst'] || defaultValue,
117
139
  gst_amount: order['gst_amount'] || defaultValue,
140
+ total_discount_applied: order['total_discount_applied'] || defaultValue,
118
141
  };
119
142
  }
120
143
  export function getTenantPurchaseOrderWithAllFields(order, skipItemMetadata) {
@@ -42,6 +42,19 @@ export function getWarehousePurchaseOrderCategoriesWithPrice(categories, convert
42
42
  items: getWarehousePurchaseOrderItemsWithPrice(category.items, convertToPrice),
43
43
  }));
44
44
  }
45
+ export function getWarehousePurchaseOrderDiscountDetailsWithPrice(discount, convertToPrice) {
46
+ if (!discount)
47
+ return null;
48
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
49
+ return {
50
+ ...discount,
51
+ // Percentage values are not prices, so only fixed amounts are converted.
52
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
53
+ ? { special_discount: convertToPrice(special_discount) }
54
+ : {}),
55
+ total_discount: convertToPrice(total_discount ?? 0),
56
+ };
57
+ }
45
58
  export function getWarehousePurchaseOrderWithPrice(order, writeable) {
46
59
  const convertToPrice = writeable ? convertDecimalToInt : convertIntToDecimal;
47
60
  const payload = {
@@ -67,6 +80,14 @@ export function getWarehousePurchaseOrderWithPrice(order, writeable) {
67
80
  ...(order.amount_earned != null ? { amount_earned: convertToPrice(order.amount_earned) } : {}),
68
81
  ...(order.grand_total != null ? { grand_total: convertToPrice(order.grand_total) } : {}),
69
82
  ...(order.price != null ? { price: convertToPrice(order.price) } : {}),
83
+ ...(order.order_discount_details != null
84
+ ? {
85
+ order_discount_details: getWarehousePurchaseOrderDiscountDetailsWithPrice(order.order_discount_details, convertToPrice),
86
+ }
87
+ : {}),
88
+ ...(order.total_discount_applied != null
89
+ ? { total_discount_applied: convertToPrice(order.total_discount_applied) }
90
+ : {}),
70
91
  };
71
92
  return payload;
72
93
  }
@@ -2,6 +2,42 @@ import ObjectID from 'bson-objectid';
2
2
  import isEqual from 'lodash/isEqual';
3
3
  import { TENANT_PURCHASE_ORDER_STATUS_ENUM } from '../../constants';
4
4
  import { getCardChargesAndAmountCollected, getPercentageAmount, parseFloatCeil, parseNum } from '../utils';
5
+ /**
6
+ * Resolves the order-level discount details for a tenant purchase order.
7
+ *
8
+ * Mirrors how `ITenantPurchaseOrder` handles `order_discount_details`:
9
+ * - percentage discounts are calculated against the order subtotal (pre-discount)
10
+ * - fixed discounts are used as-is
11
+ * - the applied discount can never exceed the order subtotal
12
+ */
13
+ export function getTenantPurchaseOrderOrderDiscountDetails(discountDetails, baseAmount) {
14
+ if (!discountDetails) {
15
+ return { order_discount_details: null, total_discount_applied: 0 };
16
+ }
17
+ const base = Math.max(0, baseAmount);
18
+ const specialDiscount = discountDetails.special_discount != null && discountDetails.special_discount > 0
19
+ ? discountDetails.is_special_discount_percentage
20
+ ? getPercentageAmount(base, discountDetails.special_discount)
21
+ : discountDetails.special_discount
22
+ : 0;
23
+ // Fallback for callers that only persist the already-calculated amount.
24
+ const requestedTotal = specialDiscount > 0
25
+ ? specialDiscount
26
+ : discountDetails.total_discount != null && discountDetails.total_discount > 0
27
+ ? discountDetails.total_discount
28
+ : 0;
29
+ const totalDiscount = parseNum(Math.min(base, Math.max(0, requestedTotal)));
30
+ if (totalDiscount <= 0) {
31
+ return { order_discount_details: null, total_discount_applied: 0 };
32
+ }
33
+ return {
34
+ order_discount_details: {
35
+ ...discountDetails,
36
+ total_discount: totalDiscount,
37
+ },
38
+ total_discount_applied: totalDiscount,
39
+ };
40
+ }
5
41
  export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
6
42
  const isCompleted = data.order_status === TENANT_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
7
43
  let subtotal = 0;
@@ -32,7 +68,12 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
32
68
  items: newItems,
33
69
  });
34
70
  }
71
+ const { order_discount_details, total_discount_applied } = getTenantPurchaseOrderOrderDiscountDetails(data.order_discount_details, subtotal);
72
+ const applyGSTOnOriginalPrice = data.exclude_discount_from_gst;
35
73
  let grand_total = subtotal;
74
+ if (!applyGSTOnOriginalPrice) {
75
+ grand_total -= total_discount_applied;
76
+ }
36
77
  let gst_amount = 0;
37
78
  const gst = data.gst ?? 0;
38
79
  if (data.is_gst_inclusive) {
@@ -42,34 +83,39 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
42
83
  gst_amount = getPercentageAmount(grand_total, gst);
43
84
  grand_total += gst_amount;
44
85
  }
86
+ if (applyGSTOnOriginalPrice) {
87
+ grand_total -= total_discount_applied;
88
+ }
45
89
  const { cardCharges, amountCollected } = getCardChargesAndAmountCollected(data.payments);
46
90
  grand_total += cardCharges;
47
91
  grand_total = parseNum(grand_total);
48
92
  const amount_collected = parseNum(amountCollected);
49
93
  const amount_earned = parseNum(grand_total - cardCharges);
50
94
  if (calculateItemMetadata) {
95
+ const discountedSubtotal = parseNum(Math.max(0, subtotal - total_discount_applied));
51
96
  let leftGrossAmount = subtotal;
52
- let leftNetAmount = subtotal;
53
- let leftDiscountAmount = 0;
97
+ let leftNetAmount = discountedSubtotal;
98
+ let leftDiscountAmount = total_discount_applied;
54
99
  let leftGstAmount = gst_amount;
55
100
  categories.forEach((category, categoryIndex) => {
56
101
  const isLastCategory = categoryIndex === categories.length - 1;
57
102
  category.items.forEach((item, itemIndex) => {
58
103
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
104
+ const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
59
105
  let grossAmount = item.subtotal;
60
- let netAmount = item.subtotal;
61
- let itemTotalDiscountAmount = 0;
106
+ let netAmount = item.subtotal - itemOrderDiscountAmount;
107
+ let itemTotalDiscountAmount = itemOrderDiscountAmount;
62
108
  let itemGst = 0;
63
109
  if (gst_amount > 0) {
64
110
  itemGst = (item.subtotal / subtotal) * gst_amount;
65
111
  }
66
112
  grossAmount = parseFloatCeil(grossAmount);
67
- const netAmountParsed = parseFloatCeil(netAmount);
68
- const itemTotalDiscountAmountParsed = parseFloatCeil(itemTotalDiscountAmount);
113
+ netAmount = parseFloatCeil(netAmount);
114
+ itemTotalDiscountAmount = parseFloatCeil(itemTotalDiscountAmount);
69
115
  itemGst = parseFloatCeil(itemGst);
70
116
  leftGrossAmount -= grossAmount;
71
- leftNetAmount -= netAmountParsed;
72
- leftDiscountAmount -= itemTotalDiscountAmountParsed;
117
+ leftNetAmount -= netAmount;
118
+ leftDiscountAmount -= itemTotalDiscountAmount;
73
119
  leftGstAmount -= itemGst;
74
120
  if (isLastItem) {
75
121
  grossAmount += leftGrossAmount;
@@ -77,10 +123,10 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
77
123
  itemTotalDiscountAmount += leftDiscountAmount;
78
124
  itemGst += leftGstAmount;
79
125
  }
80
- item._gross_amount = Math.max(grossAmount, 0);
81
- item._net_amount = Math.max(netAmount, 0);
82
- item._discount_amount = Math.max(itemTotalDiscountAmount, 0);
83
- item._gst_amount = Math.max(itemGst, 0);
126
+ item._gross_amount = Math.max(parseFloatCeil(grossAmount), 0);
127
+ item._net_amount = Math.max(parseFloatCeil(netAmount), 0);
128
+ item._discount_amount = Math.max(parseFloatCeil(itemTotalDiscountAmount), 0);
129
+ item._gst_amount = Math.max(parseFloatCeil(itemGst), 0);
84
130
  });
85
131
  });
86
132
  }
@@ -89,6 +135,8 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
89
135
  categories,
90
136
  amount_collected,
91
137
  amount_earned,
138
+ order_discount_details,
139
+ total_discount_applied,
92
140
  gst_amount,
93
141
  price: parseNum(subtotal),
94
142
  grand_total,
@@ -2,6 +2,35 @@ import ObjectID from 'bson-objectid';
2
2
  import isEqual from 'lodash/isEqual';
3
3
  import { WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM } from '../../constants';
4
4
  import { getCardChargesAndAmountCollected, getPercentageAmount, parseFloatCeil, parseNum } from '../utils';
5
+ export function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails, baseAmount) {
6
+ if (!discountDetails) {
7
+ return { order_discount_details: null, total_discount_applied: 0 };
8
+ }
9
+ const base = Math.max(0, baseAmount);
10
+ const specialDiscount = discountDetails.special_discount != null && discountDetails.special_discount > 0
11
+ ? discountDetails.is_special_discount_percentage
12
+ ? getPercentageAmount(base, discountDetails.special_discount)
13
+ : discountDetails.special_discount
14
+ : 0;
15
+ // Fallback for callers that only persist the already-calculated amount
16
+ // (for example, older purchase orders or integrations).
17
+ const requestedTotal = specialDiscount > 0
18
+ ? specialDiscount
19
+ : discountDetails.total_discount != null && discountDetails.total_discount > 0
20
+ ? discountDetails.total_discount
21
+ : 0;
22
+ const totalDiscount = parseNum(Math.min(base, Math.max(0, requestedTotal)));
23
+ if (totalDiscount <= 0) {
24
+ return { order_discount_details: null, total_discount_applied: 0 };
25
+ }
26
+ return {
27
+ order_discount_details: {
28
+ ...discountDetails,
29
+ total_discount: totalDiscount,
30
+ },
31
+ total_discount_applied: totalDiscount,
32
+ };
33
+ }
5
34
  export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
6
35
  const isCompleted = data.order_status === WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
7
36
  /* ===============================><=============================== */
@@ -36,7 +65,14 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
36
65
  items: newItems,
37
66
  });
38
67
  }
68
+ // Order-level discount is applied on the order subtotal before GST,
69
+ // unless the order opts to calculate GST on the original price.
70
+ const { order_discount_details, total_discount_applied } = getWarehousePurchaseOrderOrderDiscountDetails(data.order_discount_details, subtotal);
71
+ const applyGSTOnOriginalPrice = data.exclude_discount_from_gst;
39
72
  let grand_total = subtotal;
73
+ if (!applyGSTOnOriginalPrice) {
74
+ grand_total -= total_discount_applied;
75
+ }
40
76
  // GST is represented in percentage. We convert it to decimal
41
77
  let gst_amount = 0;
42
78
  const gst = data.gst ?? 0;
@@ -51,6 +87,9 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
51
87
  // Add GST amount to orderSubtotal
52
88
  grand_total += gst_amount;
53
89
  }
90
+ if (applyGSTOnOriginalPrice) {
91
+ grand_total -= total_discount_applied;
92
+ }
54
93
  // Add Card Charges to grand_total
55
94
  const { cardCharges, amountCollected } = getCardChargesAndAmountCollected(data.payments);
56
95
  grand_total += cardCharges;
@@ -58,28 +97,32 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
58
97
  const amount_collected = parseNum(amountCollected);
59
98
  const amount_earned = parseNum(grand_total - cardCharges);
60
99
  if (calculateItemMetadata) {
100
+ const discountedSubtotal = parseNum(Math.max(0, subtotal - total_discount_applied));
61
101
  let leftGrossAmount = subtotal;
62
- let leftNetAmount = subtotal;
63
- let leftDiscountAmount = 0; // No discounts
102
+ let leftNetAmount = discountedSubtotal;
103
+ let leftDiscountAmount = total_discount_applied;
64
104
  let leftGstAmount = gst_amount;
65
105
  categories.forEach((category, categoryIndex) => {
66
106
  const isLastCategory = categoryIndex === categories.length - 1;
67
107
  category.items.forEach((item, itemIndex) => {
68
108
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
69
- let grossAmount = item.subtotal; // No discounts, so gross = subtotal
70
- let netAmount = item.subtotal; // No discounts
71
- let itemTotalDiscountAmount = 0; // No discounts
109
+ // Order-level discounts are distributed proportionally across items,
110
+ // mirroring how `IOrder` calculates item metadata.
111
+ const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
112
+ let grossAmount = item.subtotal;
113
+ let netAmount = item.subtotal - itemOrderDiscountAmount;
114
+ let itemTotalDiscountAmount = itemOrderDiscountAmount;
72
115
  let itemGst = 0;
73
116
  if (gst_amount > 0) {
74
117
  itemGst = (item.subtotal / subtotal) * gst_amount;
75
118
  }
76
119
  grossAmount = parseFloatCeil(grossAmount);
77
- const netAmountParsed = parseFloatCeil(netAmount);
78
- const itemTotalDiscountAmountParsed = parseFloatCeil(itemTotalDiscountAmount);
120
+ netAmount = parseFloatCeil(netAmount);
121
+ itemTotalDiscountAmount = parseFloatCeil(itemTotalDiscountAmount);
79
122
  itemGst = parseFloatCeil(itemGst);
80
123
  leftGrossAmount -= grossAmount;
81
- leftNetAmount -= netAmountParsed;
82
- leftDiscountAmount -= itemTotalDiscountAmountParsed;
124
+ leftNetAmount -= netAmount;
125
+ leftDiscountAmount -= itemTotalDiscountAmount;
83
126
  leftGstAmount -= itemGst;
84
127
  if (isLastItem) {
85
128
  grossAmount += leftGrossAmount;
@@ -87,10 +130,10 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
87
130
  itemTotalDiscountAmount += leftDiscountAmount;
88
131
  itemGst += leftGstAmount;
89
132
  }
90
- item._gross_amount = Math.max(grossAmount, 0);
91
- item._net_amount = Math.max(netAmount, 0);
92
- item._discount_amount = Math.max(itemTotalDiscountAmount, 0);
93
- item._gst_amount = Math.max(itemGst, 0);
133
+ item._gross_amount = Math.max(parseFloatCeil(grossAmount), 0);
134
+ item._net_amount = Math.max(parseFloatCeil(netAmount), 0);
135
+ item._discount_amount = Math.max(parseFloatCeil(itemTotalDiscountAmount), 0);
136
+ item._gst_amount = Math.max(parseFloatCeil(itemGst), 0);
94
137
  });
95
138
  });
96
139
  }
@@ -99,6 +142,8 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
99
142
  categories,
100
143
  amount_collected,
101
144
  amount_earned,
145
+ order_discount_details,
146
+ total_discount_applied,
102
147
  gst_amount,
103
148
  price: parseNum(subtotal),
104
149
  grand_total,
@@ -35,6 +35,7 @@ export * from './materialized_tenant_delivery_entries';
35
35
  export * from './materialized_tenant_delivery_geo_cells';
36
36
  export * from './materialized_tenant_delivery_geo_scopes';
37
37
  export * from './materialized_tenant_delivery_reports';
38
+ export * from './materialized_tenant_day_readiness';
38
39
  export * from './materialized_tenant_discount_entries';
39
40
  export * from './materialized_tenant_discount_reports';
40
41
  export * from './materialized_tenant_dialer_entries';