@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
@@ -44,12 +44,32 @@ function getWarehousePurchaseOrderItemsWithPrice(items, convertToPrice) {
44
44
  quantity: (0, utils_1.parseNum)(item.quantity || 1, true),
45
45
  price: convertToPrice(item.price ?? 0),
46
46
  subtotal: convertToPrice(item.subtotal ?? 0),
47
+ // A percentage is not a price, so only fixed discounts are converted.
48
+ ...(item.item_discount_details != null
49
+ ? {
50
+ item_discount_details: getWarehouseItemDiscountDetailsWithPrice(item.item_discount_details, convertToPrice),
51
+ }
52
+ : {}),
47
53
  _gst_amount: convertToPrice(item._gst_amount ?? 0),
48
54
  _net_amount: convertToPrice(item._net_amount ?? 0),
49
55
  _gross_amount: convertToPrice(item._gross_amount ?? 0),
50
56
  _discount_amount: convertToPrice(item._discount_amount ?? 0),
51
57
  }));
52
58
  }
59
+ /**
60
+ * Same conversion as the order-level discount details, but a percentage is left
61
+ * untouched — only money values are scaled.
62
+ */
63
+ function getWarehouseItemDiscountDetailsWithPrice(discount, convertToPrice) {
64
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
65
+ return {
66
+ ...discount,
67
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
68
+ ? { special_discount: convertToPrice(special_discount) }
69
+ : {}),
70
+ total_discount: convertToPrice(total_discount ?? 0),
71
+ };
72
+ }
53
73
  function getWarehousePurchaseOrderCategoriesWithPrice(categories, convertToPrice) {
54
74
  if (!categories)
55
75
  return [];
@@ -56,7 +56,13 @@ function getTenantPurchaseOrderOrderDiscountDetails(discountDetails, baseAmount)
56
56
  }
57
57
  function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
58
58
  const isCompleted = data.order_status === constants_1.TENANT_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
59
+ /* ===============================><=============================== */
60
+ // `grossSubtotal` is the list value (price × quantity) of every line;
61
+ // `subtotal` is what the order actually costs after item-level discounts.
62
+ // Order-level discounts are then applied on top of `subtotal`.
63
+ let grossSubtotal = 0;
59
64
  let subtotal = 0;
65
+ let totalItemDiscount = 0;
60
66
  const categories = [];
61
67
  const length = data.categories?.length ?? 0;
62
68
  for (let c = 0; c < length; c++) {
@@ -65,11 +71,16 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
65
71
  const itemsLength = category.items.length;
66
72
  for (let i = 0; i < itemsLength; i++) {
67
73
  const item = category.items[i];
68
- const itemSubtotal = (0, utils_1.parseNum)(item.price * item.quantity);
74
+ // Recalculate from price × quantity so edits to price/quantity are always
75
+ // reflected, then take the item-level discount off the line.
76
+ const itemGrossSubtotal = (0, utils_1.parseNum)(item.price * item.quantity);
77
+ const itemDiscountAmount = (0, utils_1.getTenantPurchaseOrderItemDiscountAmount)(item);
78
+ const itemSubtotal = (0, utils_1.parseNum)(Math.max(0, itemGrossSubtotal - itemDiscountAmount));
69
79
  const newItem = {
70
80
  ...item,
71
81
  is_ready: item.is_ready || isCompleted,
72
82
  subtotal: itemSubtotal,
83
+ item_discount_details: (0, utils_1.withResolvedTenantItemDiscountTotal)(item),
73
84
  _discount_amount: 0,
74
85
  _gross_amount: 0,
75
86
  _gst_amount: 0,
@@ -77,7 +88,9 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
77
88
  };
78
89
  delete newItem.void_reason;
79
90
  newItems.push(newItem);
91
+ grossSubtotal += itemGrossSubtotal;
80
92
  subtotal += itemSubtotal;
93
+ totalItemDiscount += itemDiscountAmount;
81
94
  }
82
95
  categories.push({
83
96
  ...category,
@@ -109,20 +122,24 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
109
122
  const amount_earned = (0, utils_1.parseNum)(grand_total - cardCharges);
110
123
  if (calculateItemMetadata) {
111
124
  const discountedSubtotal = (0, utils_1.parseNum)(Math.max(0, subtotal - total_discount_applied));
112
- let leftGrossAmount = subtotal;
125
+ let leftGrossAmount = grossSubtotal;
113
126
  let leftNetAmount = discountedSubtotal;
114
- let leftDiscountAmount = total_discount_applied;
127
+ let leftDiscountAmount = (0, utils_1.parseNum)(totalItemDiscount + total_discount_applied);
115
128
  let leftGstAmount = gst_amount;
116
129
  categories.forEach((category, categoryIndex) => {
117
130
  const isLastCategory = categoryIndex === categories.length - 1;
118
131
  category.items.forEach((item, itemIndex) => {
119
132
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
133
+ // `item.subtotal` is already net of the item-level discount, so the
134
+ // order-level discount is distributed over the discounted subtotal.
120
135
  const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
121
- let grossAmount = item.subtotal;
136
+ // Whatever the line lost to its own item-level discount.
137
+ const itemLevelDiscountAmount = (0, utils_1.parseNum)(Math.max(0, item.price * item.quantity - item.subtotal));
138
+ let grossAmount = item.price * item.quantity;
122
139
  let netAmount = item.subtotal - itemOrderDiscountAmount;
123
- let itemTotalDiscountAmount = itemOrderDiscountAmount;
140
+ let itemTotalDiscountAmount = itemLevelDiscountAmount + itemOrderDiscountAmount;
124
141
  let itemGst = 0;
125
- if (gst_amount > 0) {
142
+ if (gst_amount > 0 && subtotal > 0) {
126
143
  itemGst = (item.subtotal / subtotal) * gst_amount;
127
144
  }
128
145
  grossAmount = (0, utils_1.parseFloatCeil)(grossAmount);
@@ -18,6 +18,7 @@ const bson_objectid_1 = __importDefault(require("bson-objectid"));
18
18
  const isEqual_1 = __importDefault(require("lodash/isEqual"));
19
19
  const constants_1 = require("../../constants");
20
20
  const utils_1 = require("../utils");
21
+ const warehouse_purchase_order_engine_1 = require("../utils/warehouse-purchase-order-engine");
21
22
  function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails, baseAmount) {
22
23
  if (!discountDetails) {
23
24
  return { order_discount_details: null, total_discount_applied: 0 };
@@ -50,7 +51,12 @@ function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails, baseAmou
50
51
  function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
51
52
  const isCompleted = data.order_status === constants_1.WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
52
53
  /* ===============================><=============================== */
54
+ // `grossSubtotal` is the list value (price × quantity) of every line;
55
+ // `subtotal` is what the order actually costs after item-level discounts.
56
+ // Order-level discounts are then applied on top of `subtotal`.
57
+ let grossSubtotal = 0;
53
58
  let subtotal = 0;
59
+ let totalItemDiscount = 0;
54
60
  const categories = [];
55
61
  const length = data.categories?.length ?? 0;
56
62
  for (let c = 0; c < length; c++) {
@@ -59,13 +65,16 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
59
65
  const itemsLength = category.items.length;
60
66
  for (let i = 0; i < itemsLength; i++) {
61
67
  const item = category.items[i];
62
- // For purchase orders, subtotal is already set as price * quantity
63
- // But to ensure, we can recalculate
64
- const itemSubtotal = (0, utils_1.parseNum)(item.price * item.quantity);
68
+ // Recalculate from price × quantity so edits to price/quantity are always
69
+ // reflected, then take the item-level discount off the line.
70
+ const itemGrossSubtotal = (0, utils_1.parseNum)(item.price * item.quantity);
71
+ const itemDiscountAmount = (0, warehouse_purchase_order_engine_1.getWarehousePurchaseOrderItemDiscountAmount)(item);
72
+ const itemSubtotal = (0, utils_1.parseNum)(Math.max(0, itemGrossSubtotal - itemDiscountAmount));
65
73
  const newItem = {
66
74
  ...item,
67
75
  is_ready: item.is_ready || isCompleted,
68
76
  subtotal: itemSubtotal,
77
+ item_discount_details: (0, warehouse_purchase_order_engine_1.withResolvedWarehouseItemDiscountTotal)(item),
69
78
  // These values will be auto calculated
70
79
  _discount_amount: 0,
71
80
  _gross_amount: 0,
@@ -74,7 +83,9 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
74
83
  };
75
84
  delete newItem.void_reason;
76
85
  newItems.push(newItem);
86
+ grossSubtotal += itemGrossSubtotal;
77
87
  subtotal += itemSubtotal;
88
+ totalItemDiscount += itemDiscountAmount;
78
89
  }
79
90
  categories.push({
80
91
  ...category,
@@ -114,22 +125,24 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
114
125
  const amount_earned = (0, utils_1.parseNum)(grand_total - cardCharges);
115
126
  if (calculateItemMetadata) {
116
127
  const discountedSubtotal = (0, utils_1.parseNum)(Math.max(0, subtotal - total_discount_applied));
117
- let leftGrossAmount = subtotal;
128
+ let leftGrossAmount = grossSubtotal;
118
129
  let leftNetAmount = discountedSubtotal;
119
- let leftDiscountAmount = total_discount_applied;
130
+ let leftDiscountAmount = (0, utils_1.parseNum)(totalItemDiscount + total_discount_applied);
120
131
  let leftGstAmount = gst_amount;
121
132
  categories.forEach((category, categoryIndex) => {
122
133
  const isLastCategory = categoryIndex === categories.length - 1;
123
134
  category.items.forEach((item, itemIndex) => {
124
135
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
125
- // Order-level discounts are distributed proportionally across items,
126
- // mirroring how `IOrder` calculates item metadata.
136
+ // `item.subtotal` is already net of the item-level discount, so the
137
+ // order-level discount is distributed over the discounted subtotal.
127
138
  const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
128
- let grossAmount = item.subtotal;
139
+ // Whatever the line lost to its own item-level discount.
140
+ const itemLevelDiscountAmount = (0, utils_1.parseNum)(Math.max(0, item.price * item.quantity - item.subtotal));
141
+ let grossAmount = item.price * item.quantity;
129
142
  let netAmount = item.subtotal - itemOrderDiscountAmount;
130
- let itemTotalDiscountAmount = itemOrderDiscountAmount;
143
+ let itemTotalDiscountAmount = itemLevelDiscountAmount + itemOrderDiscountAmount;
131
144
  let itemGst = 0;
132
- if (gst_amount > 0) {
145
+ if (gst_amount > 0 && subtotal > 0) {
133
146
  itemGst = (item.subtotal / subtotal) * gst_amount;
134
147
  }
135
148
  grossAmount = (0, utils_1.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';
@@ -93,6 +93,7 @@ __exportStar(require("./tenant-cash-drawers-helpers"), exports);
93
93
  __exportStar(require("./tenant-cash-in-out-helpers"), exports);
94
94
  __exportStar(require("./tenant-day-sessions-helpers"), exports);
95
95
  __exportStar(require("./tenant-instore-shift-sessions-helpers"), exports);
96
+ __exportStar(require("./tenant-purchase-order-engine"), exports);
96
97
  __exportStar(require("./tenant-staff-helpers"), exports);
97
98
  __exportStar(require("./tenant_cash_in_hand_transactions"), exports);
98
99
  __exportStar(require("./time-helpers"), exports);
@@ -0,0 +1,24 @@
1
+ import { IDiscountDetails, ITenantPurchaseOrderItem } from '../../schemas';
2
+ /**
3
+ * Total item-level discount for a tenant purchase order line, in money.
4
+ *
5
+ * The discount is applied per cart line through the cart's "Item Discount"
6
+ * action and lives in `item_discount_details` — the same record an order item
7
+ * uses:
8
+ * - `special_discount` is a **per-unit** amount when fixed, so the discount
9
+ * scales with quantity, and a percentage of the line's gross when
10
+ * `is_special_discount_percentage` is set.
11
+ * - `total_discount` is a fallback for records written without a
12
+ * `special_discount`.
13
+ *
14
+ * The result is clamped to the line's gross value so a discount can never make
15
+ * a line negative.
16
+ */
17
+ export declare function getTenantPurchaseOrderItemDiscountAmount(orderItem: Pick<ITenantPurchaseOrderItem, 'price' | 'quantity' | 'item_discount_details'>): number;
18
+ /**
19
+ * Refreshes `total_discount` on a line's discount record so the amount it
20
+ * reports matches the line's current price/quantity. Preserves every other
21
+ * field (id, name, reason, reference) and returns null when there is no
22
+ * discount.
23
+ */
24
+ export declare function withResolvedTenantItemDiscountTotal(orderItem: Pick<ITenantPurchaseOrderItem, 'price' | 'quantity' | 'item_discount_details'>): IDiscountDetails | null;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTenantPurchaseOrderItemDiscountAmount = getTenantPurchaseOrderItemDiscountAmount;
4
+ exports.withResolvedTenantItemDiscountTotal = withResolvedTenantItemDiscountTotal;
5
+ const common_1 = require("./common");
6
+ // ==========================================================><====================================================
7
+ /**
8
+ * Total item-level discount for a tenant purchase order line, in money.
9
+ *
10
+ * The discount is applied per cart line through the cart's "Item Discount"
11
+ * action and lives in `item_discount_details` — the same record an order item
12
+ * uses:
13
+ * - `special_discount` is a **per-unit** amount when fixed, so the discount
14
+ * scales with quantity, and a percentage of the line's gross when
15
+ * `is_special_discount_percentage` is set.
16
+ * - `total_discount` is a fallback for records written without a
17
+ * `special_discount`.
18
+ *
19
+ * The result is clamped to the line's gross value so a discount can never make
20
+ * a line negative.
21
+ */
22
+ function getTenantPurchaseOrderItemDiscountAmount(orderItem) {
23
+ const details = orderItem.item_discount_details;
24
+ if (!details)
25
+ return 0;
26
+ const quantity = orderItem.quantity ?? 0;
27
+ const grossAmount = (0, common_1.parseNum)((orderItem.price ?? 0) * quantity);
28
+ const value = details.special_discount;
29
+ if (typeof value !== 'number' || !(value > 0)) {
30
+ return (0, common_1.parseNum)(Math.max(0, Math.min(grossAmount, details.total_discount ?? 0)));
31
+ }
32
+ const discountAmount = details.is_special_discount_percentage
33
+ ? (0, common_1.getPercentageAmount)(grossAmount, value)
34
+ : value * quantity;
35
+ return (0, common_1.parseNum)(Math.min(grossAmount, Math.max(0, discountAmount)));
36
+ }
37
+ /**
38
+ * Refreshes `total_discount` on a line's discount record so the amount it
39
+ * reports matches the line's current price/quantity. Preserves every other
40
+ * field (id, name, reason, reference) and returns null when there is no
41
+ * discount.
42
+ */
43
+ function withResolvedTenantItemDiscountTotal(orderItem) {
44
+ const details = orderItem.item_discount_details;
45
+ if (!details)
46
+ return null;
47
+ return {
48
+ ...details,
49
+ total_discount: getTenantPurchaseOrderItemDiscountAmount(orderItem),
50
+ };
51
+ }
@@ -1,4 +1,26 @@
1
- import { IWarehousePurchaseOrderItem, IWarehouseItem } from '../../schemas';
1
+ import { IDiscountDetails, IWarehouseItem, IWarehousePurchaseOrderItem } from '../../schemas';
2
+ /**
3
+ * Total item-level discount for a purchase order line, in money.
4
+ *
5
+ * The line's discount lives in `item_discount_details` (the same record an order
6
+ * item uses):
7
+ * - `special_discount` is a **per-unit** amount when fixed, so the discount
8
+ * scales with quantity, and a percentage of the line's gross when
9
+ * `is_special_discount_percentage` is set.
10
+ * - `total_discount` is used as a fallback for records written without a
11
+ * `special_discount` (e.g. a discount carried over from elsewhere).
12
+ *
13
+ * The result is clamped to the line's gross value so a discount can never make a
14
+ * line negative.
15
+ */
16
+ export declare function getWarehousePurchaseOrderItemDiscountAmount(orderItem: Pick<IWarehousePurchaseOrderItem, 'price' | 'quantity' | 'item_discount_details'>): number;
17
+ /**
18
+ * Refreshes `total_discount` on a line's discount record so the amount it
19
+ * reports matches the line's current price/quantity. Preserves every other
20
+ * field (id, name, reason, reference) and returns null when there is no
21
+ * discount.
22
+ */
23
+ export declare function withResolvedWarehouseItemDiscountTotal(orderItem: Pick<IWarehousePurchaseOrderItem, 'price' | 'quantity' | 'item_discount_details'>): IDiscountDetails | null;
2
24
  interface IConvertWarehouseItemToPurchaseOrderItemParams {
3
25
  vendorId: string;
4
26
  item: IWarehouseItem;
@@ -3,20 +3,82 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getWarehousePurchaseOrderItemDiscountAmount = getWarehousePurchaseOrderItemDiscountAmount;
7
+ exports.withResolvedWarehouseItemDiscountTotal = withResolvedWarehouseItemDiscountTotal;
6
8
  exports.convertWarehouseItemToPurchaseOrderItem = convertWarehouseItemToPurchaseOrderItem;
7
9
  exports.getCurrentWarehousePurchaseOrderItemTotalPrice = getCurrentWarehousePurchaseOrderItemTotalPrice;
8
10
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
11
+ const common_1 = require("./common");
12
+ // ==========================================================><====================================================
13
+ /**
14
+ * Total item-level discount for a purchase order line, in money.
15
+ *
16
+ * The line's discount lives in `item_discount_details` (the same record an order
17
+ * item uses):
18
+ * - `special_discount` is a **per-unit** amount when fixed, so the discount
19
+ * scales with quantity, and a percentage of the line's gross when
20
+ * `is_special_discount_percentage` is set.
21
+ * - `total_discount` is used as a fallback for records written without a
22
+ * `special_discount` (e.g. a discount carried over from elsewhere).
23
+ *
24
+ * The result is clamped to the line's gross value so a discount can never make a
25
+ * line negative.
26
+ */
27
+ function getWarehousePurchaseOrderItemDiscountAmount(orderItem) {
28
+ const details = orderItem.item_discount_details;
29
+ if (!details)
30
+ return 0;
31
+ const quantity = orderItem.quantity ?? 0;
32
+ const grossAmount = (0, common_1.parseNum)((orderItem.price ?? 0) * quantity);
33
+ const value = details.special_discount;
34
+ if (typeof value !== 'number' || !(value > 0)) {
35
+ return (0, common_1.parseNum)(Math.max(0, Math.min(grossAmount, details.total_discount ?? 0)));
36
+ }
37
+ const discountAmount = details.is_special_discount_percentage
38
+ ? (0, common_1.getPercentageAmount)(grossAmount, value)
39
+ : value * quantity;
40
+ return (0, common_1.parseNum)(Math.min(grossAmount, Math.max(0, discountAmount)));
41
+ }
42
+ /**
43
+ * Refreshes `total_discount` on a line's discount record so the amount it
44
+ * reports matches the line's current price/quantity. Preserves every other
45
+ * field (id, name, reason, reference) and returns null when there is no
46
+ * discount.
47
+ */
48
+ function withResolvedWarehouseItemDiscountTotal(orderItem) {
49
+ const details = orderItem.item_discount_details;
50
+ if (!details)
51
+ return null;
52
+ return {
53
+ ...details,
54
+ total_discount: getWarehousePurchaseOrderItemDiscountAmount(orderItem),
55
+ };
56
+ }
9
57
  function convertWarehouseItemToPurchaseOrderItem({ vendorId, item, orderItem, }) {
10
58
  const { _id = (0, bson_objectid_1.default)().toHexString(), price = item.purchase_price?.[vendorId] ?? item.purchase_price?.BASE_PRICE ?? 0, quantity = 1, special_instructions = '', is_ready, } = orderItem ?? {};
59
+ // Item discounts are applied per cart line; an existing order item (split /
60
+ // re-add) keeps the discount it was given.
61
+ const item_discount_details = orderItem?.item_discount_details ?? null;
62
+ const discount_amount = getWarehousePurchaseOrderItemDiscountAmount({
63
+ price,
64
+ quantity,
65
+ item_discount_details,
66
+ });
11
67
  const purchaseOrderItem = {
12
68
  _id,
13
69
  item_id: item._id,
14
70
  name: item.name,
15
71
  price,
16
- subtotal: price * quantity,
72
+ subtotal: (0, common_1.parseNum)(price * quantity - discount_amount),
17
73
  quantity,
18
74
  special_instructions,
19
75
  is_ready,
76
+ item_discount_details: item_discount_details == null
77
+ ? null
78
+ : {
79
+ ...item_discount_details,
80
+ total_discount: discount_amount,
81
+ },
20
82
  // These values will be auto calculated
21
83
  _discount_amount: 0,
22
84
  _gross_amount: 0,
@@ -27,8 +89,7 @@ function convertWarehouseItemToPurchaseOrderItem({ vendorId, item, orderItem, })
27
89
  }
28
90
  // ==========================================================><====================================================
29
91
  function getCurrentWarehousePurchaseOrderItemTotalPrice(orderItem) {
30
- // For purchase orders, total is simply price * quantity
31
- // No modifiers, discounts, etc.
32
- const total = orderItem.price * orderItem.quantity;
92
+ // The line's payable value: price × quantity minus any item-level discount.
93
+ const total = (0, common_1.parseNum)(orderItem.price * orderItem.quantity - getWarehousePurchaseOrderItemDiscountAmount(orderItem));
33
94
  return total;
34
95
  }
@@ -1,23 +1,6 @@
1
+ import { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION } from '../../constants/MATERIALIZED_SCHEMA_VERSIONS';
2
+ export { MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION };
1
3
  import { Schema } from 'mongoose';
2
- /**
3
- * Mongoose schema for `materialized_tenant_credit_bills` — the SHARED
4
- * credit-bill ledger of the materialized reports (see `MATERIALIZED_REPORTS.md`).
5
- *
6
- * ONE document per (tenant, scope context, scope value), scopes CAPPED AT
7
- * `LOCAL_MONTH` (`MATERIALIZED_CREDIT_BILLS_SCOPES`) so a document can never
8
- * grow unboundedly: a month bounds its bill volume by construction. Each
9
- * document carries a per-key `credit_bills` map of slim `issued` / `received`
10
- * entries (ids + credit facts — the order document stays the single source of
11
- * the sale). See the type module `schemas/types/materialized_credit_bills.ts`
12
- * for the entry contract. Amounts are CENTS; reads pin `schema_version`.
13
- */
14
- /**
15
- * Version of the credit-entry rules of this collection. Bump when entry
16
- * semantics change (e.g. signed REFUND / WRITE_OFF deltas) — historical
17
- * documents must then be re-materialized. PRE-RELEASE: the collection has no
18
- * live tenants/consumers yet, so every change so far folds into version `1`.
19
- */
20
- export declare const MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = 1;
21
4
  export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, import("mongoose").Model<any, any, any, any, any, any>, {}, {}, {}, {}, {
22
5
  timestamps: true;
23
6
  versionKey: false;
@@ -33,42 +16,39 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
33
16
  tenant_id: string;
34
17
  day_index: import("../../constants/ENUMS").DAY_INDEX_ENUM | null;
35
18
  iteration: number;
36
- scope_context: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_REPORT_SCOPE_ENUM;
37
- scope_field: string;
38
- sale_type_key_filters: string[];
39
19
  credit_bills: Map<string, {
40
20
  issued: import("mongoose").Types.DocumentArray<{
41
21
  payment_id: string;
42
22
  order_id: string;
43
23
  amount: number;
24
+ settled_at: NativeDate;
25
+ settled_local_date: string;
44
26
  issued_at: NativeDate;
45
27
  issued_local_hour: string;
46
28
  received_at_issue: number;
47
29
  received_amount: number;
48
- settled_at: NativeDate;
49
- settled_local_date: string;
50
30
  credit_note: string;
51
31
  }, import("mongoose").Types.Subdocument<import("mongoose").Types.ObjectId, any, {
52
32
  payment_id: string;
53
33
  order_id: string;
54
34
  amount: number;
35
+ settled_at: NativeDate;
36
+ settled_local_date: string;
55
37
  issued_at: NativeDate;
56
38
  issued_local_hour: string;
57
39
  received_at_issue: number;
58
40
  received_amount: number;
59
- settled_at: NativeDate;
60
- settled_local_date: string;
61
41
  credit_note: string;
62
42
  }> & {
63
43
  payment_id: string;
64
44
  order_id: string;
65
45
  amount: number;
46
+ settled_at: NativeDate;
47
+ settled_local_date: string;
66
48
  issued_at: NativeDate;
67
49
  issued_local_hour: string;
68
50
  received_at_issue: number;
69
51
  received_amount: number;
70
- settled_at: NativeDate;
71
- settled_local_date: string;
72
52
  credit_note: string;
73
53
  }>;
74
54
  received: import("mongoose").Types.DocumentArray<{
@@ -109,6 +89,9 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
109
89
  schema_version: number;
110
90
  source_watermark: NativeDate;
111
91
  computed_at: NativeDate;
92
+ scope_context: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_REPORT_SCOPE_ENUM;
93
+ scope_field: string;
94
+ sale_type_key_filters: string[];
112
95
  source_input_signature?: string | null | undefined;
113
96
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
114
97
  createdAt: NativeDate;
@@ -121,42 +104,39 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
121
104
  tenant_id: string;
122
105
  day_index: import("../../constants/ENUMS").DAY_INDEX_ENUM | null;
123
106
  iteration: number;
124
- scope_context: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_REPORT_SCOPE_ENUM;
125
- scope_field: string;
126
- sale_type_key_filters: string[];
127
107
  credit_bills: Map<string, {
128
108
  issued: import("mongoose").Types.DocumentArray<{
129
109
  payment_id: string;
130
110
  order_id: string;
131
111
  amount: number;
112
+ settled_at: NativeDate;
113
+ settled_local_date: string;
132
114
  issued_at: NativeDate;
133
115
  issued_local_hour: string;
134
116
  received_at_issue: number;
135
117
  received_amount: number;
136
- settled_at: NativeDate;
137
- settled_local_date: string;
138
118
  credit_note: string;
139
119
  }, import("mongoose").Types.Subdocument<import("mongoose").Types.ObjectId, any, {
140
120
  payment_id: string;
141
121
  order_id: string;
142
122
  amount: number;
123
+ settled_at: NativeDate;
124
+ settled_local_date: string;
143
125
  issued_at: NativeDate;
144
126
  issued_local_hour: string;
145
127
  received_at_issue: number;
146
128
  received_amount: number;
147
- settled_at: NativeDate;
148
- settled_local_date: string;
149
129
  credit_note: string;
150
130
  }> & {
151
131
  payment_id: string;
152
132
  order_id: string;
153
133
  amount: number;
134
+ settled_at: NativeDate;
135
+ settled_local_date: string;
154
136
  issued_at: NativeDate;
155
137
  issued_local_hour: string;
156
138
  received_at_issue: number;
157
139
  received_amount: number;
158
- settled_at: NativeDate;
159
- settled_local_date: string;
160
140
  credit_note: string;
161
141
  }>;
162
142
  received: import("mongoose").Types.DocumentArray<{
@@ -197,6 +177,9 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
197
177
  schema_version: number;
198
178
  source_watermark: NativeDate;
199
179
  computed_at: NativeDate;
180
+ scope_context: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_REPORT_SCOPE_ENUM;
181
+ scope_field: string;
182
+ sale_type_key_filters: string[];
200
183
  source_input_signature?: string | null | undefined;
201
184
  }>> & import("mongoose").FlatRecord<{
202
185
  createdAt: NativeDate;
@@ -209,42 +192,39 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
209
192
  tenant_id: string;
210
193
  day_index: import("../../constants/ENUMS").DAY_INDEX_ENUM | null;
211
194
  iteration: number;
212
- scope_context: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_REPORT_SCOPE_ENUM;
213
- scope_field: string;
214
- sale_type_key_filters: string[];
215
195
  credit_bills: Map<string, {
216
196
  issued: import("mongoose").Types.DocumentArray<{
217
197
  payment_id: string;
218
198
  order_id: string;
219
199
  amount: number;
200
+ settled_at: NativeDate;
201
+ settled_local_date: string;
220
202
  issued_at: NativeDate;
221
203
  issued_local_hour: string;
222
204
  received_at_issue: number;
223
205
  received_amount: number;
224
- settled_at: NativeDate;
225
- settled_local_date: string;
226
206
  credit_note: string;
227
207
  }, import("mongoose").Types.Subdocument<import("mongoose").Types.ObjectId, any, {
228
208
  payment_id: string;
229
209
  order_id: string;
230
210
  amount: number;
211
+ settled_at: NativeDate;
212
+ settled_local_date: string;
231
213
  issued_at: NativeDate;
232
214
  issued_local_hour: string;
233
215
  received_at_issue: number;
234
216
  received_amount: number;
235
- settled_at: NativeDate;
236
- settled_local_date: string;
237
217
  credit_note: string;
238
218
  }> & {
239
219
  payment_id: string;
240
220
  order_id: string;
241
221
  amount: number;
222
+ settled_at: NativeDate;
223
+ settled_local_date: string;
242
224
  issued_at: NativeDate;
243
225
  issued_local_hour: string;
244
226
  received_at_issue: number;
245
227
  received_amount: number;
246
- settled_at: NativeDate;
247
- settled_local_date: string;
248
228
  credit_note: string;
249
229
  }>;
250
230
  received: import("mongoose").Types.DocumentArray<{
@@ -285,6 +265,9 @@ export declare const MaterializedTenantCreditBillsReportSchema: Schema<any, impo
285
265
  schema_version: number;
286
266
  source_watermark: NativeDate;
287
267
  computed_at: NativeDate;
268
+ scope_context: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_REPORT_SCOPE_ENUM;
269
+ scope_field: string;
270
+ sale_type_key_filters: string[];
288
271
  source_input_signature?: string | null | undefined;
289
272
  }> & Required<{
290
273
  _id: import("mongoose").Types.ObjectId;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MATERIALIZED_TENANT_CREDIT_BILLS_INDEX_OPTIONS = exports.MATERIALIZED_TENANT_CREDIT_BILLS_COLLECTION_INDEXES = exports.MATERIALIZED_TENANT_CREDIT_BILLS_COLLECTION_NAME = exports.MaterializedTenantCreditBillsReportSchema = exports.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = void 0;
4
+ const MATERIALIZED_SCHEMA_VERSIONS_1 = require("../../constants/MATERIALIZED_SCHEMA_VERSIONS");
5
+ Object.defineProperty(exports, "MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION", { enumerable: true, get: function () { return MATERIALIZED_SCHEMA_VERSIONS_1.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION; } });
4
6
  const mongoose_1 = require("mongoose");
5
7
  const ENUMS_1 = require("../../constants/ENUMS");
6
8
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
@@ -22,7 +24,6 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
22
24
  * documents must then be re-materialized. PRE-RELEASE: the collection has no
23
25
  * live tenants/consumers yet, so every change so far folds into version `1`.
24
26
  */
25
- exports.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION = 1;
26
27
  const CreditBillIssuedEntrySchema = new mongoose_1.Schema({
27
28
  order_id: {
28
29
  type: String,
@@ -198,7 +199,7 @@ exports.MaterializedTenantCreditBillsReportSchema = new mongoose_1.Schema({
198
199
  type: Number,
199
200
  required: true,
200
201
  immutable: true,
201
- default: exports.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
202
+ default: MATERIALIZED_SCHEMA_VERSIONS_1.MATERIALIZED_CREDIT_BILLS_SCHEMA_VERSION,
202
203
  },
203
204
  source_watermark: {
204
205
  type: mongoose_1.Schema.Types.Date,