@managesome/eposmatic-toolkit 0.4.62 → 0.4.64

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 (120) hide show
  1. package/esm/constants/MATERIALIZED_SCHEMA_VERSIONS.js +17 -0
  2. package/esm/constants/WORKER_ENDPOINTS.js +2 -2
  3. package/esm/helpers/materialized-reports/index.js +3 -0
  4. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +3 -3
  5. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +5 -5
  6. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +2 -2
  7. package/esm/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +5 -5
  8. package/esm/helpers/materialized-reports/materialized-dialer-compile-helpers.js +2 -2
  9. package/esm/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +5 -5
  10. package/esm/helpers/materialized-reports/materialized-dinein-compile-helpers.js +2 -2
  11. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +3 -3
  12. package/esm/helpers/materialized-reports/materialized-document-size.js +2 -2
  13. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -3
  14. package/esm/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +3 -3
  15. package/esm/helpers/materialized-reports/report-compile.js +38 -0
  16. package/esm/helpers/materialized-reports/tenant-sales-overview-bson.js +27 -0
  17. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +3 -22
  18. package/esm/helpers/store/common-tenant-purchase-order-actions.js +12 -0
  19. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +20 -0
  20. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +24 -7
  21. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +23 -10
  22. package/esm/helpers/utils/index.js +1 -0
  23. package/esm/helpers/utils/tenant-purchase-order-engine.js +47 -0
  24. package/esm/helpers/utils/warehouse-purchase-order-engine.js +63 -4
  25. package/esm/schemas/models/materialized_credit_bills.js +2 -1
  26. package/esm/schemas/models/materialized_tenant_delivery_entries.js +2 -1
  27. package/esm/schemas/models/materialized_tenant_delivery_reports.js +2 -1
  28. package/esm/schemas/models/materialized_tenant_dialer_entries.js +2 -1
  29. package/esm/schemas/models/materialized_tenant_dialer_reports.js +2 -1
  30. package/esm/schemas/models/materialized_tenant_dinein_entries.js +2 -1
  31. package/esm/schemas/models/materialized_tenant_dinein_reports.js +2 -1
  32. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +2 -1
  33. package/esm/schemas/models/tenant_purchase_orders.js +4 -0
  34. package/esm/schemas/models/warehouse_purchase_orders.js +4 -0
  35. package/lib/constants/MATERIALIZED_SCHEMA_VERSIONS.d.ts +17 -0
  36. package/lib/constants/MATERIALIZED_SCHEMA_VERSIONS.js +20 -0
  37. package/lib/constants/WORKER_ENDPOINTS.d.ts +0 -2
  38. package/lib/constants/WORKER_ENDPOINTS.js +2 -2
  39. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  40. package/lib/helpers/materialized-reports/index.js +26 -0
  41. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +4 -4
  42. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +6 -6
  43. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +4 -4
  44. package/lib/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +6 -6
  45. package/lib/helpers/materialized-reports/materialized-dialer-compile-helpers.js +6 -6
  46. package/lib/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +6 -6
  47. package/lib/helpers/materialized-reports/materialized-dinein-compile-helpers.js +6 -6
  48. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +3 -3
  49. package/lib/helpers/materialized-reports/materialized-document-size.js +2 -5
  50. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -3
  51. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +3 -3
  52. package/lib/helpers/materialized-reports/report-compile.d.ts +38 -0
  53. package/lib/helpers/materialized-reports/report-compile.js +87 -0
  54. package/lib/helpers/materialized-reports/tenant-sales-overview-bson.d.ts +12 -0
  55. package/lib/helpers/materialized-reports/tenant-sales-overview-bson.js +33 -0
  56. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +1 -12
  57. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -24
  58. package/lib/helpers/store/common-tenant-purchase-order-actions.d.ts +6 -1
  59. package/lib/helpers/store/common-tenant-purchase-order-actions.js +13 -0
  60. package/lib/helpers/store/common-warehouse-purchase-order-actions.js +20 -0
  61. package/lib/helpers/store/tenant-purchase-orders-cart-actions.js +23 -6
  62. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.js +23 -10
  63. package/lib/helpers/utils/index.d.ts +1 -0
  64. package/lib/helpers/utils/index.js +1 -0
  65. package/lib/helpers/utils/tenant-purchase-order-engine.d.ts +24 -0
  66. package/lib/helpers/utils/tenant-purchase-order-engine.js +51 -0
  67. package/lib/helpers/utils/warehouse-purchase-order-engine.d.ts +23 -1
  68. package/lib/helpers/utils/warehouse-purchase-order-engine.js +65 -4
  69. package/lib/schemas/models/materialized_credit_bills.d.ts +29 -46
  70. package/lib/schemas/models/materialized_credit_bills.js +3 -2
  71. package/lib/schemas/models/materialized_tenant_cash_entries.d.ts +9 -9
  72. package/lib/schemas/models/materialized_tenant_cash_reports.d.ts +9 -9
  73. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +11 -10
  74. package/lib/schemas/models/materialized_tenant_delivery_entries.js +3 -2
  75. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +9 -9
  76. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +6 -6
  77. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +11 -10
  78. package/lib/schemas/models/materialized_tenant_delivery_reports.js +3 -2
  79. package/lib/schemas/models/materialized_tenant_dialer_entries.d.ts +8 -7
  80. package/lib/schemas/models/materialized_tenant_dialer_entries.js +3 -2
  81. package/lib/schemas/models/materialized_tenant_dialer_reports.d.ts +11 -10
  82. package/lib/schemas/models/materialized_tenant_dialer_reports.js +3 -2
  83. package/lib/schemas/models/materialized_tenant_dinein_entries.d.ts +8 -7
  84. package/lib/schemas/models/materialized_tenant_dinein_entries.js +3 -2
  85. package/lib/schemas/models/materialized_tenant_dinein_reports.d.ts +11 -10
  86. package/lib/schemas/models/materialized_tenant_dinein_reports.js +3 -2
  87. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +9 -9
  88. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +9 -9
  89. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +9 -9
  90. package/lib/schemas/models/materialized_tenant_hourly_comparison_entries.d.ts +9 -9
  91. package/lib/schemas/models/materialized_tenant_hourly_comparison_reports.d.ts +9 -9
  92. package/lib/schemas/models/materialized_tenant_payments_comparison_entries.d.ts +9 -9
  93. package/lib/schemas/models/materialized_tenant_payments_comparison_reports.d.ts +9 -9
  94. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +9 -9
  95. package/lib/schemas/models/materialized_tenant_prep_time_reports.d.ts +9 -9
  96. package/lib/schemas/models/materialized_tenant_sales_comparison_entries.d.ts +9 -9
  97. package/lib/schemas/models/materialized_tenant_sales_comparison_reports.d.ts +9 -9
  98. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +11 -35
  99. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +3 -2
  100. package/lib/schemas/models/tenant_purchase_orders.d.ts +972 -0
  101. package/lib/schemas/models/tenant_purchase_orders.js +4 -0
  102. package/lib/schemas/models/warehouse_purchase_orders.d.ts +972 -0
  103. package/lib/schemas/models/warehouse_purchase_orders.js +4 -0
  104. package/lib/schemas/types/tenant_purchase_orders.d.ts +2 -1
  105. package/lib/schemas/types/warehouse_purchase_orders.d.ts +2 -1
  106. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +2 -1
  107. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +5 -4
  108. package/lib/tests/reporting-contract/no-live-transport.test.js +106 -0
  109. package/package.json +2 -1
  110. package/lib/helpers/order/payment-collection.d.ts +0 -25
  111. package/lib/helpers/order/payment-collection.js +0 -51
  112. package/lib/schemas/models/applied_order_discounts.d.ts +0 -80
  113. package/lib/schemas/models/applied_order_discounts.js +0 -106
  114. package/lib/schemas/types/applied_order_discounts.d.ts +0 -22
  115. package/lib/schemas/types/applied_order_discounts.js +0 -2
  116. package/lib/tests/materialized-reports/analytics-overview-helpers.test.d.ts +0 -1
  117. package/lib/tests/materialized-reports/analytics-performance-helpers.test.d.ts +0 -1
  118. package/lib/tests/payment-collection-timestamps.test.d.ts +0 -1
  119. package/lib/tests/payment-collection-timestamps.test.js +0 -71
  120. /package/lib/tests/{materialized-reports/analytics-growth-helpers.test.d.ts → reporting-contract/no-live-transport.test.d.ts} +0 -0
@@ -0,0 +1,17 @@
1
+ /**
2
+ * PURE materialized-report schema versions.
3
+ *
4
+ * The close-day plans stamp these versions on the documents they build, so the
5
+ * COMPILE graph must be able to read them without importing a mongoose schema
6
+ * model (the schema files re-export these constants for their existing API).
7
+ *
8
+ * Keep this module dependency-free: it is imported by the worker compile path.
9
+ */
10
+ export const MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = 1;
11
+ export const MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION = 1;
12
+ export const MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION = 1;
13
+ export const MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION = 1;
14
+ export const MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION = 1;
15
+ export const MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION = 1;
16
+ export const MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION = 1;
17
+ export const MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION = 1;
@@ -31,8 +31,8 @@ export const WORKER_ENDPOINTS = {
31
31
  REMOVE_DINEIN_TABLE: '/remove-dinein-table',
32
32
  // ========================>> Modifiers / Catalog <<======================= //
33
33
  UPDATE_MODIFIER_NAME_IN_ITEMS: '/update-modifier-name-in-items',
34
- ITEMS_USING_MODIFIER: '/items-using-modifier',
35
- AUDIT_ITEM_MODIFIERS: '/audit-item-modifiers',
34
+ // The two catalog reads that used to live here (items-using-modifier and
35
+ // audit-item-modifiers) are OWNED by items-service now and run locally.
36
36
  // ========================>> Payment (SwitchPay) <<======================= //
37
37
  PROCESS_SWITCHPAY_PAYMENT_FOR_ORDER: '/process-switchpay-payment-for-order',
38
38
  COMMIT_SWITCHPAY_PAYMENT_FOR_ORDER: '/commit-switchpay-payment-for-order',
@@ -69,4 +69,7 @@ export * from './tenant-dinein-formatter';
69
69
  export * from './tenant-prep-time-formatter';
70
70
  export * from './tenant-sales-overview-formatter';
71
71
  export * from './tenant-sales-overview-helpers';
72
+ export * from './tenant-sales-overview-bson';
72
73
  export * from './report-platform';
74
+ // Worker-only PURE compile surface (also importable via the deep lib path).
75
+ export * as reportCompile from './report-compile';
@@ -1,7 +1,7 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { PAYMENT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
3
3
  import { ALL_MATERIALIZED_REPORT_SCOPES, MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM, SALES_OVERVIEW_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
4
- import { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION } from '../../schemas/models/materialized_credit_bills';
4
+ import { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
5
5
  import { getLocalDocumentFields, getLocalFieldsFromLocalDate } from '../utils/time-helpers';
6
6
  import { buildMaterializedReportKey } from './key-helpers';
7
7
  import { materializedDayInputSignatureChanged } from './materialized-day-input-signature';
@@ -521,7 +521,7 @@ export function buildMaterializedCreditBillDayReports(input) {
521
521
  return [];
522
522
  const sourceWatermark = watermark ?? computedAt;
523
523
  const makeDoc = (scopeContext, scopeField, sections) => ({
524
- _id: new mongoose.Types.ObjectId().toHexString(),
524
+ _id: new ObjectID().toHexString(),
525
525
  tenant_id: tenantId,
526
526
  brand_id: brandId,
527
527
  scope_context: scopeContext,
@@ -1,6 +1,6 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { DELIVERY_KEY_FILTERS, MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DELIVERY_REPORT_MAX_BSON_BYTES, MATERIALIZED_DELIVERY_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
- import { MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_delivery_reports';
3
+ import { MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
4
4
  import { mergeMaterializedDeliveryCounters } from './materialized-delivery-accumulator-helpers';
5
5
  import { freshDeliveryCounters } from './materialized-delivery-classification-helpers';
6
6
  import { pruneDocumentDeliveryAreas, pruneDocumentDeliveryRiders } from './materialized-delivery-compile-helpers';
@@ -154,7 +154,7 @@ export function buildTenantDeliveryCloseDayPlan(input) {
154
154
  const existing = storedReportsByScope.get(deliveryScopeKey(compiledDateDoc));
155
155
  const next = {
156
156
  ...compiledDateDoc,
157
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
157
+ _id: existing?._id ?? new ObjectID().toHexString(),
158
158
  iteration: Number(existing?.iteration ?? 0) + 1,
159
159
  };
160
160
  if (force || needsMaterializedDeliveryReportWrite(existing, next))
@@ -236,7 +236,7 @@ export function buildTenantDeliveryCloseDayPlan(input) {
236
236
  counterRows.push({ key, counters: folded[key] });
237
237
  }
238
238
  const report = {
239
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
239
+ _id: existing?._id ?? new ObjectID().toHexString(),
240
240
  tenant_id: tenantId,
241
241
  brand_id: existing?.brand_id ?? compiledDateDoc?.brand_id ?? '',
242
242
  scope_context: scope,
@@ -275,7 +275,7 @@ export function buildTenantDeliveryCloseDayPlan(input) {
275
275
  const existing = storedEntriesByPage.get(key) ?? null;
276
276
  const next = {
277
277
  ...compiled,
278
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
278
+ _id: existing?._id ?? new ObjectID().toHexString(),
279
279
  iteration: Number(existing?.iteration ?? 0) + 1,
280
280
  };
281
281
  if (existing == null || force || needsMaterializedDeliveryEntriesWrite(existing, next)) {
@@ -1,8 +1,8 @@
1
1
  import { ALL_DAY_INDEX } from '../../constants/ENUMS';
2
2
  import { DELIVERY_KEY_FILTERS, MATERIALIZED_DELIVERY_AREA_LIMIT, MATERIALIZED_DELIVERY_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DELIVERY_ENTRY_SCOPES, MATERIALIZED_DELIVERY_OTHER_TOKEN, MATERIALIZED_DELIVERY_REPORT_MAX_BSON_BYTES, MATERIALIZED_DELIVERY_RIDER_LIMIT, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { DELIVERY_STATUS_ENUM, RIDER_EARNINGS_STATUS_ENUM } from '../../constants/enums/delivery';
4
- import { MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_delivery_entries';
5
- import { MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_delivery_reports';
4
+ import { MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
5
+ import { MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
6
6
  import { mergeMaterializedDeliveryCounters } from './materialized-delivery-accumulator-helpers';
7
7
  import { addDelivery, addDeliveryOrder, buildMaterializedDeliveryKey, DELIVERY_UNKNOWN_TOKEN, finalizeDeliveryAccumulator, freshDeliveryAccumulator, freshDeliveryCounters, isDeliveryOrder, MATERIALIZED_DELIVERY_KEY_SEPARATOR, parseMaterializedDeliveryKey, } from './materialized-delivery-classification-helpers';
8
8
  import { deliveryEntryPageOf, splitMaterializedDeliveryEntryPage } from './materialized-delivery-entry-pages';
@@ -1,6 +1,6 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { DIALER_KEY_FILTERS, MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES, MATERIALIZED_DIALER_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
- import { MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dialer_reports';
3
+ import { MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
4
4
  import { freshDialerCounters, mergeDialerCounters } from './materialized-dialer-accumulator-helpers';
5
5
  import { dialerEntryPageOf, materializedDialerEntryPageKey } from './materialized-dialer-entry-pages';
6
6
  import { assertMaterializedDocumentSize } from './materialized-document-size';
@@ -154,7 +154,7 @@ export function buildTenantDialerCloseDayPlan(input) {
154
154
  const existing = storedReportsByScope.get(dialerScopeKey(compiledDateDoc));
155
155
  const next = {
156
156
  ...compiledDateDoc,
157
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
157
+ _id: existing?._id ?? new ObjectID().toHexString(),
158
158
  iteration: Number(existing?.iteration ?? 0) + 1,
159
159
  };
160
160
  if (force || needsMaterializedDialerReportWrite(existing, next))
@@ -227,7 +227,7 @@ export function buildTenantDialerCloseDayPlan(input) {
227
227
  for (const key of keys)
228
228
  counters[key] = folded[key];
229
229
  const report = {
230
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
230
+ _id: existing?._id ?? new ObjectID().toHexString(),
231
231
  tenant_id: tenantId,
232
232
  brand_id: existing?.brand_id ?? compiledDateDoc?.brand_id ?? '',
233
233
  scope_context: scope,
@@ -259,7 +259,7 @@ export function buildTenantDialerCloseDayPlan(input) {
259
259
  const existing = storedEntriesByPage.get(key) ?? null;
260
260
  const next = {
261
261
  ...compiled,
262
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
262
+ _id: existing?._id ?? new ObjectID().toHexString(),
263
263
  iteration: Number(existing?.iteration ?? 0) + 1,
264
264
  };
265
265
  if (existing == null || force || needsMaterializedDialerEntriesWrite(existing, next)) {
@@ -1,6 +1,6 @@
1
1
  import { MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DIALER_ENTRY_SCOPES, MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
- import { MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dialer_entries';
3
- import { MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION as REPORT_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dialer_reports';
2
+ import { MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
3
+ import { MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION as REPORT_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
4
4
  import { MATERIALIZED_DIALER_REPORT_KEY_FILTERS, } from '../../schemas/types/materialized_tenant_dialer_reports';
5
5
  import { addDialerEvent, dialerHourKey, freshDialerCounters } from './materialized-dialer-accumulator-helpers';
6
6
  import { dialerEntryPageOf, splitMaterializedDialerEntryPage } from './materialized-dialer-entry-pages';
@@ -1,6 +1,6 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { DINEIN_KEY_FILTERS, MATERIALIZED_DINEIN_COURSE_LIMIT, MATERIALIZED_DINEIN_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DINEIN_FLOOR_LIMIT, MATERIALIZED_DINEIN_REPORT_MAX_BSON_BYTES, MATERIALIZED_DINEIN_REPORT_SCOPES, MATERIALIZED_DINEIN_SERVICE_CHARGE_RATE_LIMIT, MATERIALIZED_DINEIN_TABLE_LIMIT, MATERIALIZED_DINEIN_TOP_EDITED_CHECK_LIMIT, MATERIALIZED_DINEIN_UPCOMING_RESERVATION_LIMIT, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
- import { MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dinein_reports';
3
+ import { MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
4
4
  import { freshMaterializedDineinCounters, freshMaterializedDineinReservationCounters, mergeMaterializedDineinCounters, mergeMaterializedDineinReservationCounters, mergeMaterializedDineinTopEditedChecks, mergeMaterializedDineinUpcomingReservations, pruneDocumentDineinMaps, } from './materialized-dinein-accumulator-helpers';
5
5
  import { assertMaterializedDocumentSize } from './materialized-document-size';
6
6
  import { dineinEntryPageOf, materializedDineinEntryPageKey } from './materialized-dinein-entry-pages';
@@ -171,7 +171,7 @@ export function buildTenantDineinCloseDayPlan(input) {
171
171
  const existing = storedReportsByScope.get(dineinScopeKey(compiledDateDoc));
172
172
  const next = {
173
173
  ...compiledDateDoc,
174
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
174
+ _id: existing?._id ?? new ObjectID().toHexString(),
175
175
  iteration: Number(existing?.iteration ?? 0) + 1,
176
176
  };
177
177
  if (force || needsMaterializedDineinReportWrite(existing, next))
@@ -259,7 +259,7 @@ export function buildTenantDineinCloseDayPlan(input) {
259
259
  for (const key of keys)
260
260
  counters[key] = folded.counters[key];
261
261
  const report = {
262
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
262
+ _id: existing?._id ?? new ObjectID().toHexString(),
263
263
  tenant_id: tenantId,
264
264
  brand_id: existing?.brand_id ?? compiledDateDoc?.brand_id ?? '',
265
265
  scope_context: scope,
@@ -297,7 +297,7 @@ export function buildTenantDineinCloseDayPlan(input) {
297
297
  const existing = storedEntriesByPage.get(key) ?? null;
298
298
  const next = {
299
299
  ...compiled,
300
- _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
300
+ _id: existing?._id ?? new ObjectID().toHexString(),
301
301
  iteration: Number(existing?.iteration ?? 0) + 1,
302
302
  };
303
303
  if (existing == null || force || needsMaterializedDineinEntriesWrite(existing, next)) {
@@ -1,6 +1,6 @@
1
1
  import { MATERIALIZED_DINEIN_ENTRY_SCOPES, MATERIALIZED_DINEIN_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DINEIN_HOUR_KEYS, MATERIALIZED_DINEIN_REPORT_MAX_BSON_BYTES, MATERIALIZED_DINEIN_TOP_EDITED_CHECK_LIMIT, MATERIALIZED_DINEIN_UNKNOWN_TOKEN, MATERIALIZED_DINEIN_UPCOMING_RESERVATION_LIMIT, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
- import { MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dinein_entries';
3
- import { MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dinein_reports';
2
+ import { MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
3
+ import { MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
4
4
  import { MATERIALIZED_DINEIN_REPORT_KEY_FILTERS, } from '../../schemas/types/materialized_tenant_dinein_reports';
5
5
  import { freshMaterializedDineinCounters, freshMaterializedDineinReservationCounters, mergeMaterializedDineinTopEditedChecks, mergeMaterializedDineinUpcomingReservations, pruneDocumentDineinMaps, } from './materialized-dinein-accumulator-helpers';
6
6
  import { addDineinOrderToCounters, classifyMaterializedDineinOrigin, freshDineinCoverage, isDeletedSplitParent, isDineinOrder, itemLineDelta, itemQuantityOf, splitRoleOf, toDineinDate as toDate, toDineinInt as num, validRatingOf, } from './materialized-dinein-classification-helpers';
@@ -1,4 +1,4 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL, MATERIALIZED_DISCOUNT_REPORT_SCOPES, MATERIALIZED_REPORT_KEY_FILTER_ENUM, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { accumulateOrderDiscounts, toDiscountHourLabel, } from './materialized-discount-accumulator-helpers';
4
4
  import { createEmptyDiscountOrderCounters } from './materialized-discount-classification-helpers';
@@ -156,7 +156,7 @@ export function compileTenantDiscountReports(input) {
156
156
  const docWatermark = watermark ?? sourceWatermark;
157
157
  const isDateScoped = scope === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE || scope === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR;
158
158
  reports.push({
159
- _id: new mongoose.Types.ObjectId().toHexString(),
159
+ _id: new ObjectID().toHexString(),
160
160
  tenant_id: tenantId,
161
161
  brand_id: brandId,
162
162
  scope_context: scope,
@@ -179,7 +179,7 @@ export function compileTenantDiscountReports(input) {
179
179
  // Entries documents exist only when there is at least one row.
180
180
  if (Object.keys(entrySections).length > 0) {
181
181
  entriesDocs.push({
182
- _id: new mongoose.Types.ObjectId().toHexString(),
182
+ _id: new ObjectID().toHexString(),
183
183
  tenant_id: tenantId,
184
184
  brand_id: brandId,
185
185
  scope_context: scope,
@@ -1,4 +1,4 @@
1
- import mongoose from 'mongoose';
1
+ import { calculateObjectSize } from 'bson';
2
2
  /**
3
3
  * The BSON SIZE BUDGET of a materialized report/entry/geo document.
4
4
  *
@@ -31,7 +31,7 @@ import mongoose from 'mongoose';
31
31
  export function materializedDocumentBsonBytes(document) {
32
32
  if (document == null)
33
33
  return 0;
34
- return mongoose.mongo.BSON.calculateObjectSize(document);
34
+ return calculateObjectSize(document);
35
35
  }
36
36
  /**
37
37
  * Throws when ONE document exceeds its budget.
@@ -1,4 +1,4 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { MATERIALIZED_PREP_TIME_ITEM_SCOPES, MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { freshMaterializedPrepTimeCounters } from './materialized-prep-time-classification-helpers';
4
4
  import { mergeMaterializedPrepTimeCounters } from './materialized-prep-time-compile-helpers';
@@ -359,7 +359,7 @@ export function buildTenantPrepTimeCloseDayPlan(input) {
359
359
  const report = {
360
360
  // A period document created by the fold gets a fresh id; an existing one keeps
361
361
  // its identity so the upsert targets the same row.
362
- _id: existingDoc?._id ?? new mongoose.Types.ObjectId().toHexString(),
362
+ _id: existingDoc?._id ?? new ObjectID().toHexString(),
363
363
  tenant_id: tenantId,
364
364
  brand_id: existingDoc?.brand_id ?? reports[0]?.brand_id ?? '',
365
365
  scope_context: scope,
@@ -470,7 +470,7 @@ export function buildTenantPrepTimeCloseDayPlan(input) {
470
470
  }
471
471
  }
472
472
  const report = {
473
- _id: existingDoc?._id ?? new mongoose.Types.ObjectId().toHexString(),
473
+ _id: existingDoc?._id ?? new ObjectID().toHexString(),
474
474
  tenant_id: tenantId,
475
475
  brand_id: existingDoc?.brand_id ?? entries[0]?.brand_id ?? '',
476
476
  scope_context: scope,
@@ -1,4 +1,4 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
2
  import { MATERIALIZED_PREP_TIME_ITEM_SCOPES, MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, PREP_TIME_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { accumulateOrderPrepTime, freshMaterializedPrepTimeCounters, } from './materialized-prep-time-classification-helpers';
4
4
  import { getDayIndexFromLocalDate, getMaterializedPeriodScopeFields } from './scope-helpers';
@@ -169,7 +169,7 @@ export function compileTenantPrepTimeReports(input) {
169
169
  const docWatermark = watermark ?? sourceWatermark;
170
170
  const isDateScoped = scopeContext === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
171
171
  reports.push({
172
- _id: new mongoose.Types.ObjectId().toHexString(),
172
+ _id: new ObjectID().toHexString(),
173
173
  tenant_id: tenantId,
174
174
  brand_id: brandId,
175
175
  scope_context: scopeContext,
@@ -187,7 +187,7 @@ export function compileTenantPrepTimeReports(input) {
187
187
  });
188
188
  if (itemScopes.has(scopeContext) && Object.keys(entrySections).length > 0) {
189
189
  entries.push({
190
- _id: new mongoose.Types.ObjectId().toHexString(),
190
+ _id: new ObjectID().toHexString(),
191
191
  tenant_id: tenantId,
192
192
  brand_id: brandId,
193
193
  scope_context: scopeContext,
@@ -0,0 +1,38 @@
1
+ /**
2
+ * PURE materialized-report COMPILE entrypoint.
3
+ *
4
+ * This module is the workers-service Piscina worker's toolkit surface. Its
5
+ * transitive import graph contains NO mongoose, NO schema model, NO DB
6
+ * initializer and NO model registration: every close-day plan/compile helper
7
+ * was moved to pure modules (schema-version constants live in
8
+ * `constants/MATERIALIZED_SCHEMA_VERSIONS`, ObjectIds are generated with
9
+ * `bson-objectid`, document size uses the `bson` calculator).
10
+ *
11
+ * Import the ROOT toolkit barrel for the service-facing API; import THIS module
12
+ * (or its built `lib/helpers/materialized-reports/report-compile.js` path) from
13
+ * a worker.
14
+ */
15
+ export { MATERIALIZED_DINEIN_ORIGIN_ENUM, MATERIALIZED_DINEIN_REPORT_SCOPES, MATERIALIZED_DINEIN_SPLIT_PARENT_DELETE_REASON, MATERIALIZED_DINEIN_UNKNOWN_TOKEN, MATERIALIZED_PREP_TIME_ITEM_SCOPES, MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
16
+ export { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION, MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION, MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION, } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
17
+ export { SALES_OVERVIEW_KEY_FILTERS } from '../../constants/MATERIALIZED_REPORTS';
18
+ export { REPORT_SALE_TYPE_ENUM } from '../../constants/ANALYTICS';
19
+ export { compileTenantPrepTimeReports } from './materialized-prep-time-compile-helpers';
20
+ export { buildTenantPrepTimeCloseDayPlan, getMaterializedPrepTimePeriodDayScopeFields, getMaterializedPrepTimeReportPeriodDayScopeFields, } from './materialized-prep-time-close-day-helpers';
21
+ export { compileTenantDiscountReports } from './materialized-discount-compile-helpers';
22
+ export { buildTenantDiscountCloseDayPlan } from './materialized-discount-close-day-helpers';
23
+ export { compileTenantDeliveryReports } from './materialized-delivery-compile-helpers';
24
+ export { buildTenantDeliveryCloseDayPlan } from './materialized-delivery-close-day-helpers';
25
+ export { compileTenantDeliveryGeoCellsWithStats } from './materialized-tenant-delivery-geo-helpers';
26
+ export { compileTenantDialerReports } from './materialized-dialer-compile-helpers';
27
+ export { buildTenantDialerCloseDayPlan } from './materialized-dialer-close-day-helpers';
28
+ export { compileTenantDineinReports } from './materialized-dinein-compile-helpers';
29
+ export { buildTenantDineinCloseDayPlan, foldMaterializedDineinPeriodCounters, } from './materialized-dinein-close-day-helpers';
30
+ export { pruneDocumentDineinMaps } from './materialized-dinein-accumulator-helpers';
31
+ export { dineinKeyPassesFilters } from './materialized-dinein-key-helpers';
32
+ export { mergeMaterializedDineinEntryPages } from './materialized-dinein-entry-pages';
33
+ export { getMaterializedPeriodScopeFields, parseMaterializedLocalDate } from './scope-helpers';
34
+ export { REPORT_KEY_ENUM, REPORT_MODE_ENUM, buildReportDetailsResponse, buildReportMeta, buildReportResponse, } from '../reporting-contract/report-contract';
35
+ export { convertOrdersToMaterializedTenantSalesOverviewReports, sumMaterializedTenantSalesOverviewReports, } from './tenant-sales-overview-helpers';
36
+ export { buildTenantSalesOverviewCloseDayPlan } from './tenant-sales-overview-close-day-helpers';
37
+ export { applyCreditResolutionToReportDocuments, buildMaterializedCreditBillSelectionFromScopeGroups, computeMaterializedCreditBillTotalsFromReportsByKey, getMaterializedCreditBillScopeRefsForDay, getMaterializedCreditBillScopeRefsForIssue, resolveCreditBillDay, } from './materialized-credit-bills-helpers';
38
+ export { normalizeOverviewAggregatedShape } from '../reporting-contract/overview-contract';
@@ -0,0 +1,27 @@
1
+ import mongoose from 'mongoose';
2
+ import { MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, MaterializedTenantSalesOverviewReportSchema, } from '../../schemas/models/materialized_tenant_sales_overview_reports';
3
+ /**
4
+ * MAIN-THREAD-ONLY Overview persistence adapter.
5
+ *
6
+ * Deliberately SPLIT from `tenant-sales-overview-helpers.ts`: the compile
7
+ * helpers must stay mongoose-free for the workers-service Piscina compile
8
+ * graph, while the BSON casting step needs the mongoose schema. Importing this
9
+ * file is the ONLY way to pull mongoose into the Overview compile path — and
10
+ * the worker never imports it.
11
+ */
12
+ function getMaterializedTenantSalesOverviewReportModel() {
13
+ return (mongoose.models[MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME] ??
14
+ mongoose.model(MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, MaterializedTenantSalesOverviewReportSchema, MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME));
15
+ }
16
+ /**
17
+ * Casts a JSON materialized report through the collection's mongoose schema,
18
+ * returning a hydrated document ready to be saved / bulk-written (the
19
+ * `sale_type_metrics` plain object becomes a `Map`, date strings become
20
+ * `Date` instances, etc.).
21
+ *
22
+ * The document is NOT validated here — `save()` / `Model.validate()` still
23
+ * runs the schema validators.
24
+ */
25
+ export function convertMaterializedTenantSalesOverviewReportJsonToBson(report) {
26
+ return new (getMaterializedTenantSalesOverviewReportModel())(report);
27
+ }
@@ -1,7 +1,7 @@
1
- import mongoose from 'mongoose';
1
+ import ObjectID from 'bson-objectid';
2
+ import { MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
2
3
  import { PAYMENT_STATUS_ENUM, PAYMENT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
3
4
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX, SALES_OVERVIEW_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
4
- import { MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION, MaterializedTenantSalesOverviewReportSchema, } from '../../schemas/models/materialized_tenant_sales_overview_reports';
5
5
  import { buildMaterializedReportKey } from './key-helpers';
6
6
  import { buildMaterializedDayInputSignature, } from './materialized-day-input-signature';
7
7
  import { buildCreditBillEventCandidatesFromOrder, buildCreditBillIssuedCandidatesFromOrder, isMaterializedCreditBillPayment, resolveOrderLocalHour, resolveReceivedLocalHour, } from './materialized-credit-bills-helpers';
@@ -328,7 +328,7 @@ const createEmptyReportDocument = (args) => {
328
328
  ? getDayIndexFromLocalDate(scopeField.split(' ')[0])
329
329
  : null;
330
330
  return {
331
- _id: new mongoose.Types.ObjectId().toString(),
331
+ _id: new ObjectID().toHexString(),
332
332
  tenant_id: tenantId,
333
333
  brand_id: brandId,
334
334
  scope_context: scopeContext,
@@ -533,25 +533,6 @@ export function convertOrdersToMaterializedTenantSalesOverviewReports(localDate,
533
533
  return { materializedReports, credit_bill_issues: creditBillIssues, credit_bill_events: creditEventCandidates };
534
534
  }
535
535
  /* ------------------------------------------------------------------------ */
536
- /* 2. JSON → BSON (mongoose document) */
537
- /* ------------------------------------------------------------------------ */
538
- function getMaterializedTenantSalesOverviewReportModel() {
539
- return (mongoose.models[MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME] ??
540
- mongoose.model(MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, MaterializedTenantSalesOverviewReportSchema, MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME));
541
- }
542
- /**
543
- * Casts a JSON materialized report through the collection's mongoose schema,
544
- * returning a hydrated document ready to be saved / bulk-written (the
545
- * `sale_type_metrics` plain object becomes a `Map`, date strings become
546
- * `Date` instances, etc.).
547
- *
548
- * The document is NOT validated here — `save()` / `Model.validate()` still
549
- * runs the schema validators.
550
- */
551
- export function convertMaterializedTenantSalesOverviewReportJsonToBson(report) {
552
- return new (getMaterializedTenantSalesOverviewReportModel())(report);
553
- }
554
- /* ------------------------------------------------------------------------ */
555
536
  /* 3. Summing documents (period accumulation) */
556
537
  /* ------------------------------------------------------------------------ */
557
538
  const sumOrderMetrics = (target, source) => {
@@ -24,6 +24,13 @@ export function getTenantPurchaseOrderPaymentsWithPrice(payments, convertToPrice
24
24
  amount_refunded: convertToPrice(payment.amount_refunded),
25
25
  }));
26
26
  }
27
+ /**
28
+ * An item discount mixes money and percentages, so the shared order-discount
29
+ * conversion is applied: percentages are left untouched.
30
+ */
31
+ export function getTenantPurchaseOrderItemDiscountDetailsWithPrice(discount, convertToPrice) {
32
+ return getTenantPurchaseOrderDiscountDetailsWithPrice(discount, convertToPrice);
33
+ }
27
34
  export function getTenantPurchaseOrderItemsWithPrice(items, convertToPrice) {
28
35
  if (!items)
29
36
  return [];
@@ -32,6 +39,11 @@ export function getTenantPurchaseOrderItemsWithPrice(items, convertToPrice) {
32
39
  quantity: parseNum(item.quantity || 1, true),
33
40
  price: convertToPrice(item.price ?? 0),
34
41
  subtotal: convertToPrice(item.subtotal ?? 0),
42
+ ...(item.item_discount_details != null
43
+ ? {
44
+ item_discount_details: getTenantPurchaseOrderItemDiscountDetailsWithPrice(item.item_discount_details, convertToPrice),
45
+ }
46
+ : {}),
35
47
  _gst_amount: convertToPrice(item._gst_amount ?? 0),
36
48
  _net_amount: convertToPrice(item._net_amount ?? 0),
37
49
  _gross_amount: convertToPrice(item._gross_amount ?? 0),
@@ -28,12 +28,32 @@ export function getWarehousePurchaseOrderItemsWithPrice(items, convertToPrice) {
28
28
  quantity: parseNum(item.quantity || 1, true),
29
29
  price: convertToPrice(item.price ?? 0),
30
30
  subtotal: convertToPrice(item.subtotal ?? 0),
31
+ // A percentage is not a price, so only fixed discounts are converted.
32
+ ...(item.item_discount_details != null
33
+ ? {
34
+ item_discount_details: getWarehouseItemDiscountDetailsWithPrice(item.item_discount_details, convertToPrice),
35
+ }
36
+ : {}),
31
37
  _gst_amount: convertToPrice(item._gst_amount ?? 0),
32
38
  _net_amount: convertToPrice(item._net_amount ?? 0),
33
39
  _gross_amount: convertToPrice(item._gross_amount ?? 0),
34
40
  _discount_amount: convertToPrice(item._discount_amount ?? 0),
35
41
  }));
36
42
  }
43
+ /**
44
+ * Same conversion as the order-level discount details, but a percentage is left
45
+ * untouched — only money values are scaled.
46
+ */
47
+ function getWarehouseItemDiscountDetailsWithPrice(discount, convertToPrice) {
48
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
49
+ return {
50
+ ...discount,
51
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
52
+ ? { special_discount: convertToPrice(special_discount) }
53
+ : {}),
54
+ total_discount: convertToPrice(total_discount ?? 0),
55
+ };
56
+ }
37
57
  export function getWarehousePurchaseOrderCategoriesWithPrice(categories, convertToPrice) {
38
58
  if (!categories)
39
59
  return [];
@@ -1,7 +1,7 @@
1
1
  import ObjectID from 'bson-objectid';
2
2
  import isEqual from 'lodash/isEqual';
3
3
  import { TENANT_PURCHASE_ORDER_STATUS_ENUM } from '../../constants';
4
- import { getCardChargesAndAmountCollected, getPercentageAmount, parseFloatCeil, parseNum } from '../utils';
4
+ import { getCardChargesAndAmountCollected, getPercentageAmount, getTenantPurchaseOrderItemDiscountAmount, parseFloatCeil, parseNum, withResolvedTenantItemDiscountTotal, } from '../utils';
5
5
  /**
6
6
  * Resolves the order-level discount details for a tenant purchase order.
7
7
  *
@@ -40,7 +40,13 @@ export function getTenantPurchaseOrderOrderDiscountDetails(discountDetails, base
40
40
  }
41
41
  export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
42
42
  const isCompleted = data.order_status === TENANT_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
43
+ /* ===============================><=============================== */
44
+ // `grossSubtotal` is the list value (price × quantity) of every line;
45
+ // `subtotal` is what the order actually costs after item-level discounts.
46
+ // Order-level discounts are then applied on top of `subtotal`.
47
+ let grossSubtotal = 0;
43
48
  let subtotal = 0;
49
+ let totalItemDiscount = 0;
44
50
  const categories = [];
45
51
  const length = data.categories?.length ?? 0;
46
52
  for (let c = 0; c < length; c++) {
@@ -49,11 +55,16 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
49
55
  const itemsLength = category.items.length;
50
56
  for (let i = 0; i < itemsLength; i++) {
51
57
  const item = category.items[i];
52
- const itemSubtotal = parseNum(item.price * item.quantity);
58
+ // Recalculate from price × quantity so edits to price/quantity are always
59
+ // reflected, then take the item-level discount off the line.
60
+ const itemGrossSubtotal = parseNum(item.price * item.quantity);
61
+ const itemDiscountAmount = getTenantPurchaseOrderItemDiscountAmount(item);
62
+ const itemSubtotal = parseNum(Math.max(0, itemGrossSubtotal - itemDiscountAmount));
53
63
  const newItem = {
54
64
  ...item,
55
65
  is_ready: item.is_ready || isCompleted,
56
66
  subtotal: itemSubtotal,
67
+ item_discount_details: withResolvedTenantItemDiscountTotal(item),
57
68
  _discount_amount: 0,
58
69
  _gross_amount: 0,
59
70
  _gst_amount: 0,
@@ -61,7 +72,9 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
61
72
  };
62
73
  delete newItem.void_reason;
63
74
  newItems.push(newItem);
75
+ grossSubtotal += itemGrossSubtotal;
64
76
  subtotal += itemSubtotal;
77
+ totalItemDiscount += itemDiscountAmount;
65
78
  }
66
79
  categories.push({
67
80
  ...category,
@@ -93,20 +106,24 @@ export function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateI
93
106
  const amount_earned = parseNum(grand_total - cardCharges);
94
107
  if (calculateItemMetadata) {
95
108
  const discountedSubtotal = parseNum(Math.max(0, subtotal - total_discount_applied));
96
- let leftGrossAmount = subtotal;
109
+ let leftGrossAmount = grossSubtotal;
97
110
  let leftNetAmount = discountedSubtotal;
98
- let leftDiscountAmount = total_discount_applied;
111
+ let leftDiscountAmount = parseNum(totalItemDiscount + total_discount_applied);
99
112
  let leftGstAmount = gst_amount;
100
113
  categories.forEach((category, categoryIndex) => {
101
114
  const isLastCategory = categoryIndex === categories.length - 1;
102
115
  category.items.forEach((item, itemIndex) => {
103
116
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
117
+ // `item.subtotal` is already net of the item-level discount, so the
118
+ // order-level discount is distributed over the discounted subtotal.
104
119
  const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
105
- let grossAmount = item.subtotal;
120
+ // Whatever the line lost to its own item-level discount.
121
+ const itemLevelDiscountAmount = parseNum(Math.max(0, item.price * item.quantity - item.subtotal));
122
+ let grossAmount = item.price * item.quantity;
106
123
  let netAmount = item.subtotal - itemOrderDiscountAmount;
107
- let itemTotalDiscountAmount = itemOrderDiscountAmount;
124
+ let itemTotalDiscountAmount = itemLevelDiscountAmount + itemOrderDiscountAmount;
108
125
  let itemGst = 0;
109
- if (gst_amount > 0) {
126
+ if (gst_amount > 0 && subtotal > 0) {
110
127
  itemGst = (item.subtotal / subtotal) * gst_amount;
111
128
  }
112
129
  grossAmount = parseFloatCeil(grossAmount);