@managesome/eposmatic-toolkit 0.4.63 → 0.4.65

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 (55) hide show
  1. package/esm/constants/MATERIALIZED_SCHEMA_VERSIONS.js +3 -0
  2. package/esm/helpers/materialized-reports/index.js +1 -1
  3. package/esm/helpers/materialized-reports/materialized-cash-compile-helpers.js +1 -2
  4. package/esm/helpers/materialized-reports/{materialized-discount-source-helpers.js → materialized-discount-source-assembly.js} +13 -3
  5. package/esm/helpers/materialized-reports/report-compile.js +2 -0
  6. package/esm/helpers/store/common-tenant-purchase-order-actions.js +12 -0
  7. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +20 -0
  8. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +24 -7
  9. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +23 -10
  10. package/esm/helpers/utils/index.js +1 -0
  11. package/esm/helpers/utils/tenant-purchase-order-engine.js +47 -0
  12. package/esm/helpers/utils/warehouse-purchase-order-engine.js +63 -4
  13. package/esm/schemas/models/materialized_tenant_cash_entries.js +1 -1
  14. package/esm/schemas/models/materialized_tenant_cash_reports.js +1 -1
  15. package/esm/schemas/models/materialized_tenant_discount_sources.js +1 -1
  16. package/esm/schemas/models/tenant_purchase_orders.js +4 -0
  17. package/esm/schemas/models/warehouse_purchase_orders.js +4 -0
  18. package/lib/constants/MATERIALIZED_SCHEMA_VERSIONS.d.ts +3 -0
  19. package/lib/constants/MATERIALIZED_SCHEMA_VERSIONS.js +4 -1
  20. package/lib/helpers/materialized-reports/index.d.ts +1 -1
  21. package/lib/helpers/materialized-reports/index.js +1 -1
  22. package/lib/helpers/materialized-reports/materialized-cash-compile-helpers.js +3 -4
  23. package/lib/helpers/materialized-reports/{materialized-discount-source-helpers.js → materialized-discount-source-assembly.js} +14 -4
  24. package/lib/helpers/materialized-reports/report-compile.d.ts +2 -0
  25. package/lib/helpers/materialized-reports/report-compile.js +5 -1
  26. package/lib/helpers/store/common-tenant-purchase-order-actions.d.ts +6 -1
  27. package/lib/helpers/store/common-tenant-purchase-order-actions.js +13 -0
  28. package/lib/helpers/store/common-warehouse-purchase-order-actions.js +20 -0
  29. package/lib/helpers/store/tenant-purchase-orders-cart-actions.js +23 -6
  30. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.js +23 -10
  31. package/lib/helpers/utils/index.d.ts +1 -0
  32. package/lib/helpers/utils/index.js +1 -0
  33. package/lib/helpers/utils/tenant-purchase-order-engine.d.ts +24 -0
  34. package/lib/helpers/utils/tenant-purchase-order-engine.js +51 -0
  35. package/lib/helpers/utils/warehouse-purchase-order-engine.d.ts +23 -1
  36. package/lib/helpers/utils/warehouse-purchase-order-engine.js +65 -4
  37. package/lib/schemas/models/materialized_tenant_cash_entries.d.ts +0 -13
  38. package/lib/schemas/models/materialized_tenant_cash_entries.js +3 -3
  39. package/lib/schemas/models/materialized_tenant_cash_reports.d.ts +0 -20
  40. package/lib/schemas/models/materialized_tenant_cash_reports.js +3 -3
  41. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +0 -19
  42. package/lib/schemas/models/materialized_tenant_discount_sources.js +3 -3
  43. package/lib/schemas/models/tenant_purchase_orders.d.ts +972 -0
  44. package/lib/schemas/models/tenant_purchase_orders.js +4 -0
  45. package/lib/schemas/models/warehouse_purchase_orders.d.ts +972 -0
  46. package/lib/schemas/models/warehouse_purchase_orders.js +4 -0
  47. package/lib/schemas/types/tenant_purchase_orders.d.ts +2 -1
  48. package/lib/schemas/types/warehouse_purchase_orders.d.ts +2 -1
  49. package/lib/tests/materialized-reports/materialized-discount-scenarios.test.js +2 -2
  50. package/lib/tests/materialized-reports/materialized-discount-sources.test.js +41 -41
  51. package/lib/tests/materialized-reports/materialized-integer-contract.test.js +2 -2
  52. package/lib/tests/materialized-reports/real-discount-orders.test.js +2 -2
  53. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +2 -1
  54. package/package.json +1 -1
  55. /package/lib/helpers/materialized-reports/{materialized-discount-source-helpers.d.ts → materialized-discount-source-assembly.d.ts} +0 -0
@@ -8,6 +8,9 @@
8
8
  * Keep this module dependency-free: it is imported by the worker compile path.
9
9
  */
10
10
  export const MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = 1;
11
+ export const MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION = 1;
12
+ export const MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION = 1;
13
+ export const MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION = 1;
11
14
  export const MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION = 1;
12
15
  export const MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION = 1;
13
16
  export const MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION = 1;
@@ -9,7 +9,7 @@ export * from './materialized-discount-classification-helpers';
9
9
  export * from './materialized-discount-close-day-helpers';
10
10
  export * from './materialized-discount-compile-helpers';
11
11
  export * from './materialized-discount-details-helpers';
12
- export * from './materialized-discount-source-helpers';
12
+ export * from './materialized-discount-source-assembly';
13
13
  export * from './materialized-hourly-comparison-close-day-helpers';
14
14
  export * from './materialized-hourly-comparison-compile-helpers';
15
15
  export * from './materialized-hourly-comparison-selection-helpers';
@@ -1,8 +1,7 @@
1
1
  import { ALL_DAY_INDEX } from '../../constants/ENUMS';
2
2
  import { CASH_IN_OUT_REF_ENUM, CASH_IN_OUT_TYPE_ENUM } from '../../constants/enums/cash';
3
3
  import { CASH_KEY_FILTERS, MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
4
- import { MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_cash_entries';
5
- import { MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_cash_reports';
4
+ import { MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION, MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION, } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
6
5
  import { addCashMovement, classifyCashMovement, addCashSession, finalizeCashAccumulator, freshCashAccumulator, } from './materialized-cash-classification-helpers';
7
6
  /**
8
7
  * M3 cash - key grammar and the day compile.
@@ -1,6 +1,16 @@
1
- import mongoose from 'mongoose';
1
+ /**
2
+ * PURE "by discount" source ASSEMBLY.
3
+ *
4
+ * This module contains the complete source-identity classifier + document
5
+ * assembly used by BOTH the materialization write path and the operations live
6
+ * compile worker. It has NO mongoose import, NO model import and NO DB access:
7
+ * ids are generated with the same `bson-objectid` approach as the other pure
8
+ * close-day helpers (below the legacy `_id` was a Mongoose ObjectId, which was
9
+ * the only reason this helper could not run in a worker).
10
+ */
11
+ import ObjectID from 'bson-objectid';
2
12
  import { DISCOUNTS_KEY_FILTERS, MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM, MATERIALIZED_DISCOUNT_RATE_KIND_ENUM, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM, MATERIALIZED_DISCOUNT_SOURCE_KEY, MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
- import { MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_discount_sources';
13
+ import { MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
4
14
  /** `'VISA CARD'` / `'visa-card'` → `'visa_card'`; bounded and lowercase. */
5
15
  export function normalizeDiscountSourceKeyPart(value) {
6
16
  if (typeof value !== 'string')
@@ -380,7 +390,7 @@ export function buildDiscountSourcesForScope(input) {
380
390
  ? MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.FREE_ITEM
381
391
  : MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT;
382
392
  docs.push({
383
- _id: new mongoose.Types.ObjectId().toHexString(),
393
+ _id: new ObjectID().toHexString(),
384
394
  tenant_id: tenantId,
385
395
  brand_id: brandId,
386
396
  scope_context: scopeContext,
@@ -20,6 +20,8 @@ export { compileTenantPrepTimeReports } from './materialized-prep-time-compile-h
20
20
  export { buildTenantPrepTimeCloseDayPlan, getMaterializedPrepTimePeriodDayScopeFields, getMaterializedPrepTimeReportPeriodDayScopeFields, } from './materialized-prep-time-close-day-helpers';
21
21
  export { compileTenantDiscountReports } from './materialized-discount-compile-helpers';
22
22
  export { buildTenantDiscountCloseDayPlan } from './materialized-discount-close-day-helpers';
23
+ export { buildDiscountSourcesForScope } from './materialized-discount-source-assembly';
24
+ export { compileTenantCashReports } from './materialized-cash-compile-helpers';
23
25
  export { compileTenantDeliveryReports } from './materialized-delivery-compile-helpers';
24
26
  export { buildTenantDeliveryCloseDayPlan } from './materialized-delivery-close-day-helpers';
25
27
  export { compileTenantDeliveryGeoCellsWithStats } from './materialized-tenant-delivery-geo-helpers';
@@ -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);
@@ -2,6 +2,7 @@ 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
+ import { getWarehousePurchaseOrderItemDiscountAmount, withResolvedWarehouseItemDiscountTotal, } from '../utils/warehouse-purchase-order-engine';
5
6
  export function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails, baseAmount) {
6
7
  if (!discountDetails) {
7
8
  return { order_discount_details: null, total_discount_applied: 0 };
@@ -34,7 +35,12 @@ export function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails, b
34
35
  export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
35
36
  const isCompleted = data.order_status === WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
36
37
  /* ===============================><=============================== */
38
+ // `grossSubtotal` is the list value (price × quantity) of every line;
39
+ // `subtotal` is what the order actually costs after item-level discounts.
40
+ // Order-level discounts are then applied on top of `subtotal`.
41
+ let grossSubtotal = 0;
37
42
  let subtotal = 0;
43
+ let totalItemDiscount = 0;
38
44
  const categories = [];
39
45
  const length = data.categories?.length ?? 0;
40
46
  for (let c = 0; c < length; c++) {
@@ -43,13 +49,16 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
43
49
  const itemsLength = category.items.length;
44
50
  for (let i = 0; i < itemsLength; i++) {
45
51
  const item = category.items[i];
46
- // For purchase orders, subtotal is already set as price * quantity
47
- // But to ensure, we can recalculate
48
- const itemSubtotal = parseNum(item.price * item.quantity);
52
+ // Recalculate from price × quantity so edits to price/quantity are always
53
+ // reflected, then take the item-level discount off the line.
54
+ const itemGrossSubtotal = parseNum(item.price * item.quantity);
55
+ const itemDiscountAmount = getWarehousePurchaseOrderItemDiscountAmount(item);
56
+ const itemSubtotal = parseNum(Math.max(0, itemGrossSubtotal - itemDiscountAmount));
49
57
  const newItem = {
50
58
  ...item,
51
59
  is_ready: item.is_ready || isCompleted,
52
60
  subtotal: itemSubtotal,
61
+ item_discount_details: withResolvedWarehouseItemDiscountTotal(item),
53
62
  // These values will be auto calculated
54
63
  _discount_amount: 0,
55
64
  _gross_amount: 0,
@@ -58,7 +67,9 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
58
67
  };
59
68
  delete newItem.void_reason;
60
69
  newItems.push(newItem);
70
+ grossSubtotal += itemGrossSubtotal;
61
71
  subtotal += itemSubtotal;
72
+ totalItemDiscount += itemDiscountAmount;
62
73
  }
63
74
  categories.push({
64
75
  ...category,
@@ -98,22 +109,24 @@ export function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calcula
98
109
  const amount_earned = parseNum(grand_total - cardCharges);
99
110
  if (calculateItemMetadata) {
100
111
  const discountedSubtotal = parseNum(Math.max(0, subtotal - total_discount_applied));
101
- let leftGrossAmount = subtotal;
112
+ let leftGrossAmount = grossSubtotal;
102
113
  let leftNetAmount = discountedSubtotal;
103
- let leftDiscountAmount = total_discount_applied;
114
+ let leftDiscountAmount = parseNum(totalItemDiscount + total_discount_applied);
104
115
  let leftGstAmount = gst_amount;
105
116
  categories.forEach((category, categoryIndex) => {
106
117
  const isLastCategory = categoryIndex === categories.length - 1;
107
118
  category.items.forEach((item, itemIndex) => {
108
119
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
109
- // Order-level discounts are distributed proportionally across items,
110
- // mirroring how `IOrder` calculates item metadata.
120
+ // `item.subtotal` is already net of the item-level discount, so the
121
+ // order-level discount is distributed over the discounted subtotal.
111
122
  const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
112
- let grossAmount = item.subtotal;
123
+ // Whatever the line lost to its own item-level discount.
124
+ const itemLevelDiscountAmount = parseNum(Math.max(0, item.price * item.quantity - item.subtotal));
125
+ let grossAmount = item.price * item.quantity;
113
126
  let netAmount = item.subtotal - itemOrderDiscountAmount;
114
- let itemTotalDiscountAmount = itemOrderDiscountAmount;
127
+ let itemTotalDiscountAmount = itemLevelDiscountAmount + itemOrderDiscountAmount;
115
128
  let itemGst = 0;
116
- if (gst_amount > 0) {
129
+ if (gst_amount > 0 && subtotal > 0) {
117
130
  itemGst = (item.subtotal / subtotal) * gst_amount;
118
131
  }
119
132
  grossAmount = parseFloatCeil(grossAmount);
@@ -77,6 +77,7 @@ export * from './tenant-cash-drawers-helpers';
77
77
  export * from './tenant-cash-in-out-helpers';
78
78
  export * from './tenant-day-sessions-helpers';
79
79
  export * from './tenant-instore-shift-sessions-helpers';
80
+ export * from './tenant-purchase-order-engine';
80
81
  export * from './tenant-staff-helpers';
81
82
  export * from './tenant_cash_in_hand_transactions';
82
83
  export * from './time-helpers';
@@ -0,0 +1,47 @@
1
+ import { getPercentageAmount, parseNum } from './common';
2
+ // ==========================================================><====================================================
3
+ /**
4
+ * Total item-level discount for a tenant purchase order line, in money.
5
+ *
6
+ * The discount is applied per cart line through the cart's "Item Discount"
7
+ * action and lives in `item_discount_details` — the same record an order item
8
+ * uses:
9
+ * - `special_discount` is a **per-unit** amount when fixed, so the discount
10
+ * scales with quantity, and a percentage of the line's gross when
11
+ * `is_special_discount_percentage` is set.
12
+ * - `total_discount` is a fallback for records written without a
13
+ * `special_discount`.
14
+ *
15
+ * The result is clamped to the line's gross value so a discount can never make
16
+ * a line negative.
17
+ */
18
+ export function getTenantPurchaseOrderItemDiscountAmount(orderItem) {
19
+ const details = orderItem.item_discount_details;
20
+ if (!details)
21
+ return 0;
22
+ const quantity = orderItem.quantity ?? 0;
23
+ const grossAmount = parseNum((orderItem.price ?? 0) * quantity);
24
+ const value = details.special_discount;
25
+ if (typeof value !== 'number' || !(value > 0)) {
26
+ return parseNum(Math.max(0, Math.min(grossAmount, details.total_discount ?? 0)));
27
+ }
28
+ const discountAmount = details.is_special_discount_percentage
29
+ ? getPercentageAmount(grossAmount, value)
30
+ : value * quantity;
31
+ return parseNum(Math.min(grossAmount, Math.max(0, discountAmount)));
32
+ }
33
+ /**
34
+ * Refreshes `total_discount` on a line's discount record so the amount it
35
+ * reports matches the line's current price/quantity. Preserves every other
36
+ * field (id, name, reason, reference) and returns null when there is no
37
+ * discount.
38
+ */
39
+ export function withResolvedTenantItemDiscountTotal(orderItem) {
40
+ const details = orderItem.item_discount_details;
41
+ if (!details)
42
+ return null;
43
+ return {
44
+ ...details,
45
+ total_discount: getTenantPurchaseOrderItemDiscountAmount(orderItem),
46
+ };
47
+ }
@@ -1,15 +1,75 @@
1
1
  import ObjectID from 'bson-objectid';
2
+ import { getPercentageAmount, parseNum } from './common';
3
+ // ==========================================================><====================================================
4
+ /**
5
+ * Total item-level discount for a purchase order line, in money.
6
+ *
7
+ * The line's discount lives in `item_discount_details` (the same record an order
8
+ * item uses):
9
+ * - `special_discount` is a **per-unit** amount when fixed, so the discount
10
+ * scales with quantity, and a percentage of the line's gross when
11
+ * `is_special_discount_percentage` is set.
12
+ * - `total_discount` is used as a fallback for records written without a
13
+ * `special_discount` (e.g. a discount carried over from elsewhere).
14
+ *
15
+ * The result is clamped to the line's gross value so a discount can never make a
16
+ * line negative.
17
+ */
18
+ export function getWarehousePurchaseOrderItemDiscountAmount(orderItem) {
19
+ const details = orderItem.item_discount_details;
20
+ if (!details)
21
+ return 0;
22
+ const quantity = orderItem.quantity ?? 0;
23
+ const grossAmount = parseNum((orderItem.price ?? 0) * quantity);
24
+ const value = details.special_discount;
25
+ if (typeof value !== 'number' || !(value > 0)) {
26
+ return parseNum(Math.max(0, Math.min(grossAmount, details.total_discount ?? 0)));
27
+ }
28
+ const discountAmount = details.is_special_discount_percentage
29
+ ? getPercentageAmount(grossAmount, value)
30
+ : value * quantity;
31
+ return parseNum(Math.min(grossAmount, Math.max(0, discountAmount)));
32
+ }
33
+ /**
34
+ * Refreshes `total_discount` on a line's discount record so the amount it
35
+ * reports matches the line's current price/quantity. Preserves every other
36
+ * field (id, name, reason, reference) and returns null when there is no
37
+ * discount.
38
+ */
39
+ export function withResolvedWarehouseItemDiscountTotal(orderItem) {
40
+ const details = orderItem.item_discount_details;
41
+ if (!details)
42
+ return null;
43
+ return {
44
+ ...details,
45
+ total_discount: getWarehousePurchaseOrderItemDiscountAmount(orderItem),
46
+ };
47
+ }
2
48
  export function convertWarehouseItemToPurchaseOrderItem({ vendorId, item, orderItem, }) {
3
49
  const { _id = ObjectID().toHexString(), price = item.purchase_price?.[vendorId] ?? item.purchase_price?.BASE_PRICE ?? 0, quantity = 1, special_instructions = '', is_ready, } = orderItem ?? {};
50
+ // Item discounts are applied per cart line; an existing order item (split /
51
+ // re-add) keeps the discount it was given.
52
+ const item_discount_details = orderItem?.item_discount_details ?? null;
53
+ const discount_amount = getWarehousePurchaseOrderItemDiscountAmount({
54
+ price,
55
+ quantity,
56
+ item_discount_details,
57
+ });
4
58
  const purchaseOrderItem = {
5
59
  _id,
6
60
  item_id: item._id,
7
61
  name: item.name,
8
62
  price,
9
- subtotal: price * quantity,
63
+ subtotal: parseNum(price * quantity - discount_amount),
10
64
  quantity,
11
65
  special_instructions,
12
66
  is_ready,
67
+ item_discount_details: item_discount_details == null
68
+ ? null
69
+ : {
70
+ ...item_discount_details,
71
+ total_discount: discount_amount,
72
+ },
13
73
  // These values will be auto calculated
14
74
  _discount_amount: 0,
15
75
  _gross_amount: 0,
@@ -20,8 +80,7 @@ export function convertWarehouseItemToPurchaseOrderItem({ vendorId, item, orderI
20
80
  }
21
81
  // ==========================================================><====================================================
22
82
  export function getCurrentWarehousePurchaseOrderItemTotalPrice(orderItem) {
23
- // For purchase orders, total is simply price * quantity
24
- // No modifiers, discounts, etc.
25
- const total = orderItem.price * orderItem.quantity;
83
+ // The line's payable value: price × quantity minus any item-level discount.
84
+ const total = parseNum(orderItem.price * orderItem.quantity - getWarehousePurchaseOrderItemDiscountAmount(orderItem));
26
85
  return total;
27
86
  }
@@ -14,7 +14,7 @@ import { ALL_MATERIALIZED_REPORT_KEY_FILTERS, CASH_KEY_FILTERS, MATERIALIZED_CAS
14
14
  * Version of the cash ENTRY rules. Bump when row semantics change - historical
15
15
  * documents must then be re-materialized. PRE-RELEASE: folds into version `1`.
16
16
  */
17
- export const MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION = 1;
17
+ import { MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
18
18
  const CashEntrySchema = new Schema({
19
19
  cash_in_out_id: { type: String, required: true },
20
20
  entry_key: { type: String, required: true },
@@ -20,7 +20,7 @@ import { ALL_MATERIALIZED_REPORT_KEY_FILTERS, CASH_KEY_FILTERS, MATERIALIZED_CAS
20
20
  * historical documents must then be re-materialized. PRE-RELEASE: folds into
21
21
  * version `1`.
22
22
  */
23
- export const MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION = 1;
23
+ import { MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
24
24
  export const MaterializedTenantCashReportSchema = new Schema({
25
25
  tenant_id: { type: String, required: true },
26
26
  brand_id: { type: String, required: true },
@@ -19,7 +19,7 @@ import { ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS, ALL_MATERIALIZED_DISCOUNT_LEVELS
19
19
  * grouping or rate rule changes — historical documents must then be rebuilt
20
20
  * with the backfill script.
21
21
  */
22
- export const MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION = 1;
22
+ import { MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
23
23
  const DiscountSourceKeyMetricsSchema = new Schema({
24
24
  key: { type: String, required: true },
25
25
  order_count: { type: Number, required: true, min: 0, default: 0 },
@@ -53,6 +53,10 @@ const ItemsSchema = new Schema({
53
53
  _net_amount: { type: Number, min: 0, required: true },
54
54
  _gross_amount: { type: Number, min: 0, required: true },
55
55
  _discount_amount: { type: Number, min: 0, required: true },
56
+ item_discount_details: {
57
+ type: DiscountDetailsSchema,
58
+ required: false,
59
+ },
56
60
  special_instructions: { type: String, default: '' },
57
61
  });
58
62
  const CategoriesSchema = new Schema({
@@ -107,6 +107,10 @@ const ItemsModal = new Schema({
107
107
  min: 0,
108
108
  required: true,
109
109
  },
110
+ item_discount_details: {
111
+ type: DiscountDetailsSchema,
112
+ default: null,
113
+ },
110
114
  special_instructions: {
111
115
  type: String,
112
116
  default: '',
@@ -8,6 +8,9 @@
8
8
  * Keep this module dependency-free: it is imported by the worker compile path.
9
9
  */
10
10
  export declare const MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = 1;
11
+ export declare const MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION = 1;
12
+ export declare const MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION = 1;
13
+ export declare const MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION = 1;
11
14
  export declare const MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION = 1;
12
15
  export declare const MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION = 1;
13
16
  export declare const MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION = 1;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = void 0;
3
+ exports.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = void 0;
4
4
  /**
5
5
  * PURE materialized-report schema versions.
6
6
  *
@@ -11,6 +11,9 @@ exports.MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_SCHEMA_VERSION = exports.MATE
11
11
  * Keep this module dependency-free: it is imported by the worker compile path.
12
12
  */
13
13
  exports.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = 1;
14
+ exports.MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION = 1;
15
+ exports.MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION = 1;
16
+ exports.MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION = 1;
14
17
  exports.MATERIALIZED_TENANT_DELIVERY_ENTRIES_SCHEMA_VERSION = 1;
15
18
  exports.MATERIALIZED_TENANT_DELIVERY_REPORTS_SCHEMA_VERSION = 1;
16
19
  exports.MATERIALIZED_TENANT_DIALER_ENTRIES_SCHEMA_VERSION = 1;
@@ -9,7 +9,7 @@ export * from './materialized-discount-classification-helpers';
9
9
  export * from './materialized-discount-close-day-helpers';
10
10
  export * from './materialized-discount-compile-helpers';
11
11
  export * from './materialized-discount-details-helpers';
12
- export * from './materialized-discount-source-helpers';
12
+ export * from './materialized-discount-source-assembly';
13
13
  export * from './materialized-hourly-comparison-close-day-helpers';
14
14
  export * from './materialized-hourly-comparison-compile-helpers';
15
15
  export * from './materialized-hourly-comparison-selection-helpers';
@@ -48,7 +48,7 @@ __exportStar(require("./materialized-discount-classification-helpers"), exports)
48
48
  __exportStar(require("./materialized-discount-close-day-helpers"), exports);
49
49
  __exportStar(require("./materialized-discount-compile-helpers"), exports);
50
50
  __exportStar(require("./materialized-discount-details-helpers"), exports);
51
- __exportStar(require("./materialized-discount-source-helpers"), exports);
51
+ __exportStar(require("./materialized-discount-source-assembly"), exports);
52
52
  __exportStar(require("./materialized-hourly-comparison-close-day-helpers"), exports);
53
53
  __exportStar(require("./materialized-hourly-comparison-compile-helpers"), exports);
54
54
  __exportStar(require("./materialized-hourly-comparison-selection-helpers"), exports);
@@ -8,8 +8,7 @@ exports.compileTenantCashReports = compileTenantCashReports;
8
8
  const ENUMS_1 = require("../../constants/ENUMS");
9
9
  const cash_1 = require("../../constants/enums/cash");
10
10
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
11
- const materialized_tenant_cash_entries_1 = require("../../schemas/models/materialized_tenant_cash_entries");
12
- const materialized_tenant_cash_reports_1 = require("../../schemas/models/materialized_tenant_cash_reports");
11
+ const MATERIALIZED_SCHEMA_VERSIONS_1 = require("../../constants/MATERIALIZED_SCHEMA_VERSIONS");
13
12
  const materialized_cash_classification_helpers_1 = require("./materialized-cash-classification-helpers");
14
13
  /**
15
14
  * M3 cash - key grammar and the day compile.
@@ -192,7 +191,7 @@ function compileTenantCashReports(input) {
192
191
  sale_type_key_filters: [...MATERIALIZED_REPORTS_1.CASH_KEY_FILTERS],
193
192
  cash_counters: cashCounters,
194
193
  cash_counter_rows: cashCounterRows,
195
- schema_version: materialized_tenant_cash_reports_1.MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION,
194
+ schema_version: MATERIALIZED_SCHEMA_VERSIONS_1.MATERIALIZED_TENANT_CASH_REPORTS_SCHEMA_VERSION,
196
195
  source_watermark: watermark,
197
196
  computed_at: computedAt,
198
197
  createdAt: computedAt,
@@ -209,7 +208,7 @@ function compileTenantCashReports(input) {
209
208
  day_index: dayIndexOf(localDate),
210
209
  sale_type_key_filters: [...MATERIALIZED_REPORTS_1.CASH_KEY_FILTERS],
211
210
  cash_entries: Object.keys(cashEntries).length === 0 ? null : cashEntries,
212
- schema_version: materialized_tenant_cash_entries_1.MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION,
211
+ schema_version: MATERIALIZED_SCHEMA_VERSIONS_1.MATERIALIZED_TENANT_CASH_ENTRIES_SCHEMA_VERSION,
213
212
  source_watermark: watermark,
214
213
  computed_at: computedAt,
215
214
  createdAt: computedAt,
@@ -9,9 +9,19 @@ exports.classifyDiscountEntrySource = classifyDiscountEntrySource;
9
9
  exports.buildDiscountSourcesForScope = buildDiscountSourcesForScope;
10
10
  exports.discountSourceDeltaCovers = discountSourceDeltaCovers;
11
11
  exports.applyDiscountSourceDelta = applyDiscountSourceDelta;
12
- const mongoose_1 = __importDefault(require("mongoose"));
12
+ /**
13
+ * PURE "by discount" source ASSEMBLY.
14
+ *
15
+ * This module contains the complete source-identity classifier + document
16
+ * assembly used by BOTH the materialization write path and the operations live
17
+ * compile worker. It has NO mongoose import, NO model import and NO DB access:
18
+ * ids are generated with the same `bson-objectid` approach as the other pure
19
+ * close-day helpers (below the legacy `_id` was a Mongoose ObjectId, which was
20
+ * the only reason this helper could not run in a worker).
21
+ */
22
+ const bson_objectid_1 = __importDefault(require("bson-objectid"));
13
23
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
14
- const materialized_tenant_discount_sources_1 = require("../../schemas/models/materialized_tenant_discount_sources");
24
+ const MATERIALIZED_SCHEMA_VERSIONS_1 = require("../../constants/MATERIALIZED_SCHEMA_VERSIONS");
15
25
  /** `'VISA CARD'` / `'visa-card'` → `'visa_card'`; bounded and lowercase. */
16
26
  function normalizeDiscountSourceKeyPart(value) {
17
27
  if (typeof value !== 'string')
@@ -391,7 +401,7 @@ function buildDiscountSourcesForScope(input) {
391
401
  ? MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.FREE_ITEM
392
402
  : MATERIALIZED_REPORTS_1.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM.DISCOUNT;
393
403
  docs.push({
394
- _id: new mongoose_1.default.Types.ObjectId().toHexString(),
404
+ _id: new bson_objectid_1.default().toHexString(),
395
405
  tenant_id: tenantId,
396
406
  brand_id: brandId,
397
407
  scope_context: scopeContext,
@@ -420,7 +430,7 @@ function buildDiscountSourcesForScope(input) {
420
430
  .sort(([a], [b]) => a.localeCompare(b))
421
431
  .map(([key, metrics]) => metricsToKeyMetrics(key, metrics)),
422
432
  sale_type_key_filters: [...MATERIALIZED_REPORTS_1.DISCOUNTS_KEY_FILTERS],
423
- schema_version: materialized_tenant_discount_sources_1.MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION,
433
+ schema_version: MATERIALIZED_SCHEMA_VERSIONS_1.MATERIALIZED_TENANT_DISCOUNT_SOURCES_SCHEMA_VERSION,
424
434
  source_watermark: sourceWatermark,
425
435
  computed_at: computedAt,
426
436
  createdAt: computedAt,
@@ -20,6 +20,8 @@ export { compileTenantPrepTimeReports } from './materialized-prep-time-compile-h
20
20
  export { buildTenantPrepTimeCloseDayPlan, getMaterializedPrepTimePeriodDayScopeFields, getMaterializedPrepTimeReportPeriodDayScopeFields, } from './materialized-prep-time-close-day-helpers';
21
21
  export { compileTenantDiscountReports } from './materialized-discount-compile-helpers';
22
22
  export { buildTenantDiscountCloseDayPlan } from './materialized-discount-close-day-helpers';
23
+ export { buildDiscountSourcesForScope } from './materialized-discount-source-assembly';
24
+ export { compileTenantCashReports } from './materialized-cash-compile-helpers';
23
25
  export { compileTenantDeliveryReports } from './materialized-delivery-compile-helpers';
24
26
  export { buildTenantDeliveryCloseDayPlan } from './materialized-delivery-close-day-helpers';
25
27
  export { compileTenantDeliveryGeoCellsWithStats } from './materialized-tenant-delivery-geo-helpers';