@managesome/eposmatic-toolkit 0.4.57 → 0.4.59

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 (56) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +45 -0
  2. package/esm/helpers/materialized-reports/index.js +1 -0
  3. package/esm/helpers/materialized-reports/materialized-day-readiness.js +94 -0
  4. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +3 -0
  5. package/esm/helpers/materialized-reports/report-platform/definition.js +12 -2
  6. package/esm/helpers/order/generate-warehouse-purchase-order.js +3 -0
  7. package/esm/helpers/reporting-contract/report-contract.js +12 -0
  8. package/esm/helpers/store/common-tenant-purchase-order-actions.js +23 -0
  9. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +21 -0
  10. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +60 -12
  11. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +58 -13
  12. package/esm/schemas/models/index.js +1 -0
  13. package/esm/schemas/models/materialized_tenant_day_readiness.js +66 -0
  14. package/esm/schemas/models/tenant_purchase_orders.js +36 -0
  15. package/esm/schemas/models/tenants.js +3 -8
  16. package/esm/schemas/models/warehouse_purchase_orders.js +48 -0
  17. package/esm/schemas/types/index.js +1 -0
  18. package/esm/schemas/types/materialized_tenant_day_readiness.js +1 -0
  19. package/lib/constants/MATERIALIZED_REPORTS.d.ts +42 -0
  20. package/lib/constants/MATERIALIZED_REPORTS.js +46 -1
  21. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  22. package/lib/helpers/materialized-reports/index.js +1 -0
  23. package/lib/helpers/materialized-reports/materialized-day-readiness.d.ts +84 -0
  24. package/lib/helpers/materialized-reports/materialized-day-readiness.js +100 -0
  25. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +3 -0
  26. package/lib/helpers/materialized-reports/report-platform/definition.js +12 -2
  27. package/lib/helpers/order/generate-warehouse-purchase-order.js +3 -0
  28. package/lib/helpers/reporting-contract/report-contract.d.ts +13 -1
  29. package/lib/helpers/reporting-contract/report-contract.js +12 -0
  30. package/lib/helpers/store/common-tenant-purchase-order-actions.d.ts +2 -1
  31. package/lib/helpers/store/common-tenant-purchase-order-actions.js +24 -0
  32. package/lib/helpers/store/common-warehouse-purchase-order-actions.d.ts +2 -1
  33. package/lib/helpers/store/common-warehouse-purchase-order-actions.js +22 -0
  34. package/lib/helpers/store/tenant-purchase-orders-cart-actions.d.ts +15 -1
  35. package/lib/helpers/store/tenant-purchase-orders-cart-actions.js +61 -12
  36. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.d.ts +10 -1
  37. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.js +59 -13
  38. package/lib/schemas/models/index.d.ts +1 -0
  39. package/lib/schemas/models/index.js +1 -0
  40. package/lib/schemas/models/materialized_tenant_day_readiness.d.ts +78 -0
  41. package/lib/schemas/models/materialized_tenant_day_readiness.js +69 -0
  42. package/lib/schemas/models/orders.d.ts +240 -240
  43. package/lib/schemas/models/tenant_purchase_orders.d.ts +132 -0
  44. package/lib/schemas/models/tenant_purchase_orders.js +36 -0
  45. package/lib/schemas/models/tenants.js +3 -8
  46. package/lib/schemas/models/warehouse_purchase_orders.d.ts +132 -0
  47. package/lib/schemas/models/warehouse_purchase_orders.js +48 -0
  48. package/lib/schemas/types/index.d.ts +1 -0
  49. package/lib/schemas/types/index.js +1 -0
  50. package/lib/schemas/types/materialized_tenant_day_readiness.d.ts +28 -0
  51. package/lib/schemas/types/materialized_tenant_day_readiness.js +2 -0
  52. package/lib/schemas/types/tenant_purchase_orders.d.ts +28 -0
  53. package/lib/schemas/types/warehouse_purchase_orders.d.ts +12 -0
  54. package/lib/tests/materialized-reports/materialized-day-readiness.test.d.ts +1 -0
  55. package/lib/tests/materialized-reports/materialized-day-readiness.test.js +64 -0
  56. package/package.json +1 -1
@@ -67,7 +67,19 @@ export declare enum REPORT_ERROR_CODE_ENUM {
67
67
  TIME_WINDOW_NOT_SUPPORTED_LIVE = "TIME_WINDOW_NOT_SUPPORTED_LIVE",
68
68
  INVALID_BASELINE = "INVALID_BASELINE",
69
69
  INVALID_CURSOR = "INVALID_CURSOR",
70
- DRILLDOWN_PROJECTION_UNAVAILABLE = "DRILLDOWN_PROJECTION_UNAVAILABLE"
70
+ DRILLDOWN_PROJECTION_UNAVAILABLE = "DRILLDOWN_PROJECTION_UNAVAILABLE",
71
+ /**
72
+ * Historical read of a report/day that was never materialized (no committed
73
+ * readiness row). HTTP 409; details: { report, missing_tenants, missing_dates }.
74
+ */
75
+ HISTORICAL_NOT_MATERIALIZED = "HISTORICAL_NOT_MATERIALIZED",
76
+ /**
77
+ * Historical read whose committed readiness row says the report is not final
78
+ * (e.g. Delivery skipped a stale cross-day update). HTTP 409; details:
79
+ * { report, missing_tenants, missing_dates } (the tenants/days awaiting
80
+ * reconciliation).
81
+ */
82
+ HISTORICAL_NEEDS_RECONCILIATION = "HISTORICAL_NEEDS_RECONCILIATION"
71
83
  }
72
84
  export interface IReportErrorResponse {
73
85
  error: {
@@ -118,6 +118,18 @@ var REPORT_ERROR_CODE_ENUM;
118
118
  REPORT_ERROR_CODE_ENUM["INVALID_BASELINE"] = "INVALID_BASELINE";
119
119
  REPORT_ERROR_CODE_ENUM["INVALID_CURSOR"] = "INVALID_CURSOR";
120
120
  REPORT_ERROR_CODE_ENUM["DRILLDOWN_PROJECTION_UNAVAILABLE"] = "DRILLDOWN_PROJECTION_UNAVAILABLE";
121
+ /**
122
+ * Historical read of a report/day that was never materialized (no committed
123
+ * readiness row). HTTP 409; details: { report, missing_tenants, missing_dates }.
124
+ */
125
+ REPORT_ERROR_CODE_ENUM["HISTORICAL_NOT_MATERIALIZED"] = "HISTORICAL_NOT_MATERIALIZED";
126
+ /**
127
+ * Historical read whose committed readiness row says the report is not final
128
+ * (e.g. Delivery skipped a stale cross-day update). HTTP 409; details:
129
+ * { report, missing_tenants, missing_dates } (the tenants/days awaiting
130
+ * reconciliation).
131
+ */
132
+ REPORT_ERROR_CODE_ENUM["HISTORICAL_NEEDS_RECONCILIATION"] = "HISTORICAL_NEEDS_RECONCILIATION";
121
133
  })(REPORT_ERROR_CODE_ENUM || (exports.REPORT_ERROR_CODE_ENUM = REPORT_ERROR_CODE_ENUM = {}));
122
134
  const isNonEmptyString = (value) => typeof value === 'string' && value.trim() !== '';
123
135
  const toIsoString = (value) => {
@@ -1,10 +1,11 @@
1
- import { IOrderPayment, ITenantPurchaseOrder, ITenantPurchaseOrderCategory, ITenantPurchaseOrderItem, ITenantPurchaseOrderIteration } from '../../schemas';
1
+ import { IOrderPayment, ITenantPurchaseOrder, ITenantPurchaseOrderCategory, ITenantPurchaseOrderDiscountDetails, ITenantPurchaseOrderItem, ITenantPurchaseOrderIteration } from '../../schemas';
2
2
  import { SORT_TYPE_ENUM } from '../../constants';
3
3
  import { ITenantGeneralPurchaseOrderItem, ITenantPurchaseOrderCartItemsObj } from '../types/tenant-purchase-order-cart-actions';
4
4
  export declare function getTenantPurchaseOrderIterationsWithPrice(iterations?: ITenantPurchaseOrderIteration[] | undefined, writeable?: boolean): ITenantPurchaseOrderIteration[];
5
5
  export declare function getTenantPurchaseOrderPaymentsWithPrice(payments: IOrderPayment[] | undefined, convertToPrice: (price: number) => number): IOrderPayment[];
6
6
  export declare function getTenantPurchaseOrderItemsWithPrice(items: ITenantPurchaseOrderItem[] | undefined, convertToPrice: (price: number) => number): ITenantPurchaseOrderItem[];
7
7
  export declare function getTenantPurchaseOrderCategoriesWithPrice(categories: ITenantPurchaseOrderCategory[] | undefined, convertToPrice: (price: number) => number): ITenantPurchaseOrderCategory[];
8
+ export declare function getTenantPurchaseOrderDiscountDetailsWithPrice(discount: ITenantPurchaseOrderDiscountDetails | null | undefined, convertToPrice: (price: number) => number): ITenantPurchaseOrderDiscountDetails | null;
8
9
  export declare function getTenantPurchaseOrderWithPrice<T extends Partial<ITenantPurchaseOrder> | ITenantPurchaseOrder | ITenantPurchaseOrderIteration>(order: T, writeable?: boolean): T;
9
10
  export declare function syncTenantPurchaseOrderData(order: ITenantPurchaseOrder): ITenantPurchaseOrder;
10
11
  export declare function skipItemMetadataFromTenantPurchaseOrderCategories(categories: ITenantPurchaseOrder['categories'], previousCategories?: ITenantPurchaseOrder['categories']): ITenantPurchaseOrder['categories'];
@@ -7,6 +7,7 @@ exports.getTenantPurchaseOrderIterationsWithPrice = getTenantPurchaseOrderIterat
7
7
  exports.getTenantPurchaseOrderPaymentsWithPrice = getTenantPurchaseOrderPaymentsWithPrice;
8
8
  exports.getTenantPurchaseOrderItemsWithPrice = getTenantPurchaseOrderItemsWithPrice;
9
9
  exports.getTenantPurchaseOrderCategoriesWithPrice = getTenantPurchaseOrderCategoriesWithPrice;
10
+ exports.getTenantPurchaseOrderDiscountDetailsWithPrice = getTenantPurchaseOrderDiscountDetailsWithPrice;
10
11
  exports.getTenantPurchaseOrderWithPrice = getTenantPurchaseOrderWithPrice;
11
12
  exports.syncTenantPurchaseOrderData = syncTenantPurchaseOrderData;
12
13
  exports.skipItemMetadataFromTenantPurchaseOrderCategories = skipItemMetadataFromTenantPurchaseOrderCategories;
@@ -61,6 +62,19 @@ function getTenantPurchaseOrderCategoriesWithPrice(categories, convertToPrice) {
61
62
  items: getTenantPurchaseOrderItemsWithPrice(category.items, convertToPrice),
62
63
  }));
63
64
  }
65
+ function getTenantPurchaseOrderDiscountDetailsWithPrice(discount, convertToPrice) {
66
+ if (!discount)
67
+ return null;
68
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
69
+ return {
70
+ ...discount,
71
+ // Percentage values are not prices, so only fixed amounts are converted.
72
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
73
+ ? { special_discount: convertToPrice(special_discount) }
74
+ : {}),
75
+ total_discount: convertToPrice(total_discount ?? 0),
76
+ };
77
+ }
64
78
  function getTenantPurchaseOrderWithPrice(order, writeable) {
65
79
  const convertToPrice = writeable ? utils_1.convertDecimalToInt : utils_1.convertIntToDecimal;
66
80
  const payload = {
@@ -86,6 +100,14 @@ function getTenantPurchaseOrderWithPrice(order, writeable) {
86
100
  ...(order.amount_earned != null ? { amount_earned: convertToPrice(order.amount_earned) } : {}),
87
101
  ...(order.grand_total != null ? { grand_total: convertToPrice(order.grand_total) } : {}),
88
102
  ...(order.price != null ? { price: convertToPrice(order.price) } : {}),
103
+ ...(order.order_discount_details != null
104
+ ? {
105
+ order_discount_details: getTenantPurchaseOrderDiscountDetailsWithPrice(order.order_discount_details, convertToPrice),
106
+ }
107
+ : {}),
108
+ ...(order.total_discount_applied != null
109
+ ? { total_discount_applied: convertToPrice(order.total_discount_applied) }
110
+ : {}),
89
111
  };
90
112
  return payload;
91
113
  }
@@ -123,6 +145,7 @@ function getCommonOptionalBoolFieldsTenantPurchaseOrder(order, partial) {
123
145
  return {
124
146
  is_gst_inclusive: order['is_gst_inclusive'] || defaultValue,
125
147
  is_reopened: order['is_reopened'] || defaultValue,
148
+ exclude_discount_from_gst: order['exclude_discount_from_gst'] || defaultValue,
126
149
  };
127
150
  }
128
151
  function getCommonOptionalNumFieldsTenantPurchaseOrder(order, partial) {
@@ -130,6 +153,7 @@ function getCommonOptionalNumFieldsTenantPurchaseOrder(order, partial) {
130
153
  return {
131
154
  gst: order['gst'] || defaultValue,
132
155
  gst_amount: order['gst_amount'] || defaultValue,
156
+ total_discount_applied: order['total_discount_applied'] || defaultValue,
133
157
  };
134
158
  }
135
159
  function getTenantPurchaseOrderWithAllFields(order, skipItemMetadata) {
@@ -1,10 +1,11 @@
1
1
  import { SORT_TYPE_ENUM } from '../../constants';
2
- import { IOrderPayment, IWarehousePurchaseOrder, IWarehousePurchaseOrderCategory, IWarehousePurchaseOrderItem, IWarehousePurchaseOrderIteration } from '../../schemas';
2
+ import { IOrderPayment, IWarehousePurchaseOrder, IWarehousePurchaseOrderCategory, IWarehousePurchaseOrderDiscountDetails, IWarehousePurchaseOrderItem, IWarehousePurchaseOrderIteration } from '../../schemas';
3
3
  import { IWarehouseGeneralPurchaseOrderItem, IWarehousePurchaseOrderCartItemsObj } from '../types';
4
4
  export declare function getWarehousePurchaseOrderIterationsWithPrice(iterations?: IWarehousePurchaseOrderIteration[] | undefined, writeable?: boolean): IWarehousePurchaseOrderIteration[];
5
5
  export declare function getWarehousePurchaseOrderPaymentsWithPrice(payments: IOrderPayment[] | undefined, convertToPrice: (price: number) => number): IOrderPayment[];
6
6
  export declare function getWarehousePurchaseOrderItemsWithPrice(items: IWarehousePurchaseOrderItem[] | undefined, convertToPrice: (price: number) => number): IWarehousePurchaseOrderItem[];
7
7
  export declare function getWarehousePurchaseOrderCategoriesWithPrice(categories: IWarehousePurchaseOrderCategory[] | undefined, convertToPrice: (price: number) => number): IWarehousePurchaseOrderCategory[];
8
+ export declare function getWarehousePurchaseOrderDiscountDetailsWithPrice(discount: IWarehousePurchaseOrderDiscountDetails | null | undefined, convertToPrice: (price: number) => number): IWarehousePurchaseOrderDiscountDetails | null;
8
9
  export declare function getWarehousePurchaseOrderWithPrice<T extends Partial<IWarehousePurchaseOrder> | IWarehousePurchaseOrder | IWarehousePurchaseOrderIteration>(order: T, writeable?: boolean): T;
9
10
  export declare function syncWarehousePurchaseOrderData(order: IWarehousePurchaseOrder): IWarehousePurchaseOrder;
10
11
  export declare function skipItemMetadataFromWarehousePurchaseOrderCategories(categories: IWarehousePurchaseOrder['categories'], previousCategories?: IWarehousePurchaseOrder['categories']): IWarehousePurchaseOrder['categories'];
@@ -7,6 +7,7 @@ exports.getWarehousePurchaseOrderIterationsWithPrice = getWarehousePurchaseOrder
7
7
  exports.getWarehousePurchaseOrderPaymentsWithPrice = getWarehousePurchaseOrderPaymentsWithPrice;
8
8
  exports.getWarehousePurchaseOrderItemsWithPrice = getWarehousePurchaseOrderItemsWithPrice;
9
9
  exports.getWarehousePurchaseOrderCategoriesWithPrice = getWarehousePurchaseOrderCategoriesWithPrice;
10
+ exports.getWarehousePurchaseOrderDiscountDetailsWithPrice = getWarehousePurchaseOrderDiscountDetailsWithPrice;
10
11
  exports.getWarehousePurchaseOrderWithPrice = getWarehousePurchaseOrderWithPrice;
11
12
  exports.syncWarehousePurchaseOrderData = syncWarehousePurchaseOrderData;
12
13
  exports.skipItemMetadataFromWarehousePurchaseOrderCategories = skipItemMetadataFromWarehousePurchaseOrderCategories;
@@ -57,6 +58,19 @@ function getWarehousePurchaseOrderCategoriesWithPrice(categories, convertToPrice
57
58
  items: getWarehousePurchaseOrderItemsWithPrice(category.items, convertToPrice),
58
59
  }));
59
60
  }
61
+ function getWarehousePurchaseOrderDiscountDetailsWithPrice(discount, convertToPrice) {
62
+ if (!discount)
63
+ return null;
64
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
65
+ return {
66
+ ...discount,
67
+ // Percentage values are not prices, so only fixed amounts are converted.
68
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
69
+ ? { special_discount: convertToPrice(special_discount) }
70
+ : {}),
71
+ total_discount: convertToPrice(total_discount ?? 0),
72
+ };
73
+ }
60
74
  function getWarehousePurchaseOrderWithPrice(order, writeable) {
61
75
  const convertToPrice = writeable ? utils_1.convertDecimalToInt : utils_1.convertIntToDecimal;
62
76
  const payload = {
@@ -82,6 +96,14 @@ function getWarehousePurchaseOrderWithPrice(order, writeable) {
82
96
  ...(order.amount_earned != null ? { amount_earned: convertToPrice(order.amount_earned) } : {}),
83
97
  ...(order.grand_total != null ? { grand_total: convertToPrice(order.grand_total) } : {}),
84
98
  ...(order.price != null ? { price: convertToPrice(order.price) } : {}),
99
+ ...(order.order_discount_details != null
100
+ ? {
101
+ order_discount_details: getWarehousePurchaseOrderDiscountDetailsWithPrice(order.order_discount_details, convertToPrice),
102
+ }
103
+ : {}),
104
+ ...(order.total_discount_applied != null
105
+ ? { total_discount_applied: convertToPrice(order.total_discount_applied) }
106
+ : {}),
85
107
  };
86
108
  return payload;
87
109
  }
@@ -1,4 +1,17 @@
1
- import { ITenantPurchaseOrder, ITenantPurchaseOrderItem } from '../../schemas';
1
+ import { ITenantPurchaseOrder, ITenantPurchaseOrderDiscountDetails, ITenantPurchaseOrderItem } from '../../schemas';
2
+ interface ITenantOrderDiscountResult {
3
+ order_discount_details: ITenantPurchaseOrderDiscountDetails | null;
4
+ total_discount_applied: number;
5
+ }
6
+ /**
7
+ * Resolves the order-level discount details for a tenant purchase order.
8
+ *
9
+ * Mirrors how `ITenantPurchaseOrder` handles `order_discount_details`:
10
+ * - percentage discounts are calculated against the order subtotal (pre-discount)
11
+ * - fixed discounts are used as-is
12
+ * - the applied discount can never exceed the order subtotal
13
+ */
14
+ export declare function getTenantPurchaseOrderOrderDiscountDetails(discountDetails: Partial<ITenantPurchaseOrderDiscountDetails> | null | undefined, baseAmount: number): ITenantOrderDiscountResult;
2
15
  export declare function calculateCartTenantPurchaseOrderInfoAndSyncData<T extends ITenantPurchaseOrder | Partial<ITenantPurchaseOrder>>(data: T, calculateItemMetadata?: boolean): T;
3
16
  export declare const getTenantPurchaseOrderItemComparableData: (item: ITenantPurchaseOrderItem) => Partial<ITenantPurchaseOrderItem>;
4
17
  export declare function getUpdatedTenantPurchaseOrderCartInfoOnInit(data: Partial<ITenantPurchaseOrder>, order: Partial<ITenantPurchaseOrder>): Partial<ITenantPurchaseOrder>;
@@ -22,3 +35,4 @@ export interface IGetSplitTenantPurchaseOrderCartItemToTwo {
22
35
  }
23
36
  export declare function getSplitTenantPurchaseOrderCartItemToTwo({ data, orderItemId, }: IGetSplitTenantPurchaseOrderCartItemToTwo): Partial<ITenantPurchaseOrder>;
24
37
  export declare function getAddItemsToTenantPurchaseOrderCartData(data: Partial<ITenantPurchaseOrder>, payload: ISetAddItemToTenantPurchaseOrderCartActionPayload[]): Partial<ITenantPurchaseOrder>;
38
+ export {};
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getTenantPurchaseOrderItemComparableData = void 0;
7
+ exports.getTenantPurchaseOrderOrderDiscountDetails = getTenantPurchaseOrderOrderDiscountDetails;
7
8
  exports.calculateCartTenantPurchaseOrderInfoAndSyncData = calculateCartTenantPurchaseOrderInfoAndSyncData;
8
9
  exports.getUpdatedTenantPurchaseOrderCartInfoOnInit = getUpdatedTenantPurchaseOrderCartInfoOnInit;
9
10
  exports.getRemoveItemFromTenantPurchaseOrderCartData = getRemoveItemFromTenantPurchaseOrderCartData;
@@ -17,6 +18,42 @@ const bson_objectid_1 = __importDefault(require("bson-objectid"));
17
18
  const isEqual_1 = __importDefault(require("lodash/isEqual"));
18
19
  const constants_1 = require("../../constants");
19
20
  const utils_1 = require("../utils");
21
+ /**
22
+ * Resolves the order-level discount details for a tenant purchase order.
23
+ *
24
+ * Mirrors how `ITenantPurchaseOrder` handles `order_discount_details`:
25
+ * - percentage discounts are calculated against the order subtotal (pre-discount)
26
+ * - fixed discounts are used as-is
27
+ * - the applied discount can never exceed the order subtotal
28
+ */
29
+ function getTenantPurchaseOrderOrderDiscountDetails(discountDetails, baseAmount) {
30
+ if (!discountDetails) {
31
+ return { order_discount_details: null, total_discount_applied: 0 };
32
+ }
33
+ const base = Math.max(0, baseAmount);
34
+ const specialDiscount = discountDetails.special_discount != null && discountDetails.special_discount > 0
35
+ ? discountDetails.is_special_discount_percentage
36
+ ? (0, utils_1.getPercentageAmount)(base, discountDetails.special_discount)
37
+ : discountDetails.special_discount
38
+ : 0;
39
+ // Fallback for callers that only persist the already-calculated amount.
40
+ const requestedTotal = specialDiscount > 0
41
+ ? specialDiscount
42
+ : discountDetails.total_discount != null && discountDetails.total_discount > 0
43
+ ? discountDetails.total_discount
44
+ : 0;
45
+ const totalDiscount = (0, utils_1.parseNum)(Math.min(base, Math.max(0, requestedTotal)));
46
+ if (totalDiscount <= 0) {
47
+ return { order_discount_details: null, total_discount_applied: 0 };
48
+ }
49
+ return {
50
+ order_discount_details: {
51
+ ...discountDetails,
52
+ total_discount: totalDiscount,
53
+ },
54
+ total_discount_applied: totalDiscount,
55
+ };
56
+ }
20
57
  function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
21
58
  const isCompleted = data.order_status === constants_1.TENANT_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
22
59
  let subtotal = 0;
@@ -47,7 +84,12 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
47
84
  items: newItems,
48
85
  });
49
86
  }
87
+ const { order_discount_details, total_discount_applied } = getTenantPurchaseOrderOrderDiscountDetails(data.order_discount_details, subtotal);
88
+ const applyGSTOnOriginalPrice = data.exclude_discount_from_gst;
50
89
  let grand_total = subtotal;
90
+ if (!applyGSTOnOriginalPrice) {
91
+ grand_total -= total_discount_applied;
92
+ }
51
93
  let gst_amount = 0;
52
94
  const gst = data.gst ?? 0;
53
95
  if (data.is_gst_inclusive) {
@@ -57,34 +99,39 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
57
99
  gst_amount = (0, utils_1.getPercentageAmount)(grand_total, gst);
58
100
  grand_total += gst_amount;
59
101
  }
102
+ if (applyGSTOnOriginalPrice) {
103
+ grand_total -= total_discount_applied;
104
+ }
60
105
  const { cardCharges, amountCollected } = (0, utils_1.getCardChargesAndAmountCollected)(data.payments);
61
106
  grand_total += cardCharges;
62
107
  grand_total = (0, utils_1.parseNum)(grand_total);
63
108
  const amount_collected = (0, utils_1.parseNum)(amountCollected);
64
109
  const amount_earned = (0, utils_1.parseNum)(grand_total - cardCharges);
65
110
  if (calculateItemMetadata) {
111
+ const discountedSubtotal = (0, utils_1.parseNum)(Math.max(0, subtotal - total_discount_applied));
66
112
  let leftGrossAmount = subtotal;
67
- let leftNetAmount = subtotal;
68
- let leftDiscountAmount = 0;
113
+ let leftNetAmount = discountedSubtotal;
114
+ let leftDiscountAmount = total_discount_applied;
69
115
  let leftGstAmount = gst_amount;
70
116
  categories.forEach((category, categoryIndex) => {
71
117
  const isLastCategory = categoryIndex === categories.length - 1;
72
118
  category.items.forEach((item, itemIndex) => {
73
119
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
120
+ const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
74
121
  let grossAmount = item.subtotal;
75
- let netAmount = item.subtotal;
76
- let itemTotalDiscountAmount = 0;
122
+ let netAmount = item.subtotal - itemOrderDiscountAmount;
123
+ let itemTotalDiscountAmount = itemOrderDiscountAmount;
77
124
  let itemGst = 0;
78
125
  if (gst_amount > 0) {
79
126
  itemGst = (item.subtotal / subtotal) * gst_amount;
80
127
  }
81
128
  grossAmount = (0, utils_1.parseFloatCeil)(grossAmount);
82
- const netAmountParsed = (0, utils_1.parseFloatCeil)(netAmount);
83
- const itemTotalDiscountAmountParsed = (0, utils_1.parseFloatCeil)(itemTotalDiscountAmount);
129
+ netAmount = (0, utils_1.parseFloatCeil)(netAmount);
130
+ itemTotalDiscountAmount = (0, utils_1.parseFloatCeil)(itemTotalDiscountAmount);
84
131
  itemGst = (0, utils_1.parseFloatCeil)(itemGst);
85
132
  leftGrossAmount -= grossAmount;
86
- leftNetAmount -= netAmountParsed;
87
- leftDiscountAmount -= itemTotalDiscountAmountParsed;
133
+ leftNetAmount -= netAmount;
134
+ leftDiscountAmount -= itemTotalDiscountAmount;
88
135
  leftGstAmount -= itemGst;
89
136
  if (isLastItem) {
90
137
  grossAmount += leftGrossAmount;
@@ -92,10 +139,10 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
92
139
  itemTotalDiscountAmount += leftDiscountAmount;
93
140
  itemGst += leftGstAmount;
94
141
  }
95
- item._gross_amount = Math.max(grossAmount, 0);
96
- item._net_amount = Math.max(netAmount, 0);
97
- item._discount_amount = Math.max(itemTotalDiscountAmount, 0);
98
- item._gst_amount = Math.max(itemGst, 0);
142
+ item._gross_amount = Math.max((0, utils_1.parseFloatCeil)(grossAmount), 0);
143
+ item._net_amount = Math.max((0, utils_1.parseFloatCeil)(netAmount), 0);
144
+ item._discount_amount = Math.max((0, utils_1.parseFloatCeil)(itemTotalDiscountAmount), 0);
145
+ item._gst_amount = Math.max((0, utils_1.parseFloatCeil)(itemGst), 0);
99
146
  });
100
147
  });
101
148
  }
@@ -104,6 +151,8 @@ function calculateCartTenantPurchaseOrderInfoAndSyncData(data, calculateItemMeta
104
151
  categories,
105
152
  amount_collected,
106
153
  amount_earned,
154
+ order_discount_details,
155
+ total_discount_applied,
107
156
  gst_amount,
108
157
  price: (0, utils_1.parseNum)(subtotal),
109
158
  grand_total,
@@ -1,5 +1,10 @@
1
1
  import { WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM } from '../../constants';
2
- import { IWarehousePurchaseOrder, IWarehousePurchaseOrderCategory, IWarehousePurchaseOrderItem, IWarehousePurchaseOrderIteration } from '../../schemas';
2
+ import { IWarehousePurchaseOrder, IWarehousePurchaseOrderCategory, IWarehousePurchaseOrderDiscountDetails, IWarehousePurchaseOrderItem, IWarehousePurchaseOrderIteration } from '../../schemas';
3
+ interface IOrderDiscountResult {
4
+ order_discount_details: IWarehousePurchaseOrderDiscountDetails | null;
5
+ total_discount_applied: number;
6
+ }
7
+ export declare function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails: Partial<IWarehousePurchaseOrderDiscountDetails> | null | undefined, baseAmount: number): IOrderDiscountResult;
3
8
  export declare function calculateCartWarehousePurchaseOrderInfoAndSyncData<T extends IWarehousePurchaseOrder | Partial<IWarehousePurchaseOrder>>(data: T, calculateItemMetadata?: boolean): T;
4
9
  export declare const getWarehousePurchaseOrderItemComaparableData: (item: IWarehousePurchaseOrderItem) => Partial<IWarehousePurchaseOrderItem>;
5
10
  export declare function getUpdatedWarehousePurchaseOrderCartInfoOnInit(data: Partial<IWarehousePurchaseOrder>, order: Partial<IWarehousePurchaseOrder>): {
@@ -30,6 +35,9 @@ export declare function getUpdatedWarehousePurchaseOrderCartInfoOnInit(data: Par
30
35
  price?: number | undefined;
31
36
  amount_earned?: number | undefined;
32
37
  grand_total?: number | undefined;
38
+ order_discount_details?: IWarehousePurchaseOrderDiscountDetails | null;
39
+ total_discount_applied?: number;
40
+ exclude_discount_from_gst?: boolean;
33
41
  order_status?: WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM | undefined;
34
42
  updatedAt?: Date | undefined;
35
43
  payments?: import("../../schemas").IOrderPayment[] | undefined;
@@ -55,3 +63,4 @@ export interface IGetSplitPurchaseOrderCartItemToTwo {
55
63
  }
56
64
  export declare function getSplitWarehousePurchaseOrderCartItemToTwo({ data, orderItemId, }: IGetSplitPurchaseOrderCartItemToTwo): Partial<IWarehousePurchaseOrder>;
57
65
  export declare function getAddItemsToWarehousePurchaseOrderCartData(data: Partial<IWarehousePurchaseOrder>, payload: ISetAddItemToPurchaseOrderCartActionPayload[]): Partial<IWarehousePurchaseOrder>;
66
+ export {};
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getWarehousePurchaseOrderItemComaparableData = void 0;
7
+ exports.getWarehousePurchaseOrderOrderDiscountDetails = getWarehousePurchaseOrderOrderDiscountDetails;
7
8
  exports.calculateCartWarehousePurchaseOrderInfoAndSyncData = calculateCartWarehousePurchaseOrderInfoAndSyncData;
8
9
  exports.getUpdatedWarehousePurchaseOrderCartInfoOnInit = getUpdatedWarehousePurchaseOrderCartInfoOnInit;
9
10
  exports.getRemoveItemFromWarehousePurchaseOrderCartData = getRemoveItemFromWarehousePurchaseOrderCartData;
@@ -17,6 +18,35 @@ const bson_objectid_1 = __importDefault(require("bson-objectid"));
17
18
  const isEqual_1 = __importDefault(require("lodash/isEqual"));
18
19
  const constants_1 = require("../../constants");
19
20
  const utils_1 = require("../utils");
21
+ function getWarehousePurchaseOrderOrderDiscountDetails(discountDetails, baseAmount) {
22
+ if (!discountDetails) {
23
+ return { order_discount_details: null, total_discount_applied: 0 };
24
+ }
25
+ const base = Math.max(0, baseAmount);
26
+ const specialDiscount = discountDetails.special_discount != null && discountDetails.special_discount > 0
27
+ ? discountDetails.is_special_discount_percentage
28
+ ? (0, utils_1.getPercentageAmount)(base, discountDetails.special_discount)
29
+ : discountDetails.special_discount
30
+ : 0;
31
+ // Fallback for callers that only persist the already-calculated amount
32
+ // (for example, older purchase orders or integrations).
33
+ const requestedTotal = specialDiscount > 0
34
+ ? specialDiscount
35
+ : discountDetails.total_discount != null && discountDetails.total_discount > 0
36
+ ? discountDetails.total_discount
37
+ : 0;
38
+ const totalDiscount = (0, utils_1.parseNum)(Math.min(base, Math.max(0, requestedTotal)));
39
+ if (totalDiscount <= 0) {
40
+ return { order_discount_details: null, total_discount_applied: 0 };
41
+ }
42
+ return {
43
+ order_discount_details: {
44
+ ...discountDetails,
45
+ total_discount: totalDiscount,
46
+ },
47
+ total_discount_applied: totalDiscount,
48
+ };
49
+ }
20
50
  function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemMetadata) {
21
51
  const isCompleted = data.order_status === constants_1.WAREHOUSE_PURCHASE_ORDER_STATUS_ENUM.COMPLETED;
22
52
  /* ===============================><=============================== */
@@ -51,7 +81,14 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
51
81
  items: newItems,
52
82
  });
53
83
  }
84
+ // Order-level discount is applied on the order subtotal before GST,
85
+ // unless the order opts to calculate GST on the original price.
86
+ const { order_discount_details, total_discount_applied } = getWarehousePurchaseOrderOrderDiscountDetails(data.order_discount_details, subtotal);
87
+ const applyGSTOnOriginalPrice = data.exclude_discount_from_gst;
54
88
  let grand_total = subtotal;
89
+ if (!applyGSTOnOriginalPrice) {
90
+ grand_total -= total_discount_applied;
91
+ }
55
92
  // GST is represented in percentage. We convert it to decimal
56
93
  let gst_amount = 0;
57
94
  const gst = data.gst ?? 0;
@@ -66,6 +103,9 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
66
103
  // Add GST amount to orderSubtotal
67
104
  grand_total += gst_amount;
68
105
  }
106
+ if (applyGSTOnOriginalPrice) {
107
+ grand_total -= total_discount_applied;
108
+ }
69
109
  // Add Card Charges to grand_total
70
110
  const { cardCharges, amountCollected } = (0, utils_1.getCardChargesAndAmountCollected)(data.payments);
71
111
  grand_total += cardCharges;
@@ -73,28 +113,32 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
73
113
  const amount_collected = (0, utils_1.parseNum)(amountCollected);
74
114
  const amount_earned = (0, utils_1.parseNum)(grand_total - cardCharges);
75
115
  if (calculateItemMetadata) {
116
+ const discountedSubtotal = (0, utils_1.parseNum)(Math.max(0, subtotal - total_discount_applied));
76
117
  let leftGrossAmount = subtotal;
77
- let leftNetAmount = subtotal;
78
- let leftDiscountAmount = 0; // No discounts
118
+ let leftNetAmount = discountedSubtotal;
119
+ let leftDiscountAmount = total_discount_applied;
79
120
  let leftGstAmount = gst_amount;
80
121
  categories.forEach((category, categoryIndex) => {
81
122
  const isLastCategory = categoryIndex === categories.length - 1;
82
123
  category.items.forEach((item, itemIndex) => {
83
124
  const isLastItem = isLastCategory && itemIndex === category.items.length - 1;
84
- let grossAmount = item.subtotal; // No discounts, so gross = subtotal
85
- let netAmount = item.subtotal; // No discounts
86
- let itemTotalDiscountAmount = 0; // No discounts
125
+ // Order-level discounts are distributed proportionally across items,
126
+ // mirroring how `IOrder` calculates item metadata.
127
+ const itemOrderDiscountAmount = subtotal > 0 ? (item.subtotal / subtotal) * total_discount_applied : 0;
128
+ let grossAmount = item.subtotal;
129
+ let netAmount = item.subtotal - itemOrderDiscountAmount;
130
+ let itemTotalDiscountAmount = itemOrderDiscountAmount;
87
131
  let itemGst = 0;
88
132
  if (gst_amount > 0) {
89
133
  itemGst = (item.subtotal / subtotal) * gst_amount;
90
134
  }
91
135
  grossAmount = (0, utils_1.parseFloatCeil)(grossAmount);
92
- const netAmountParsed = (0, utils_1.parseFloatCeil)(netAmount);
93
- const itemTotalDiscountAmountParsed = (0, utils_1.parseFloatCeil)(itemTotalDiscountAmount);
136
+ netAmount = (0, utils_1.parseFloatCeil)(netAmount);
137
+ itemTotalDiscountAmount = (0, utils_1.parseFloatCeil)(itemTotalDiscountAmount);
94
138
  itemGst = (0, utils_1.parseFloatCeil)(itemGst);
95
139
  leftGrossAmount -= grossAmount;
96
- leftNetAmount -= netAmountParsed;
97
- leftDiscountAmount -= itemTotalDiscountAmountParsed;
140
+ leftNetAmount -= netAmount;
141
+ leftDiscountAmount -= itemTotalDiscountAmount;
98
142
  leftGstAmount -= itemGst;
99
143
  if (isLastItem) {
100
144
  grossAmount += leftGrossAmount;
@@ -102,10 +146,10 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
102
146
  itemTotalDiscountAmount += leftDiscountAmount;
103
147
  itemGst += leftGstAmount;
104
148
  }
105
- item._gross_amount = Math.max(grossAmount, 0);
106
- item._net_amount = Math.max(netAmount, 0);
107
- item._discount_amount = Math.max(itemTotalDiscountAmount, 0);
108
- item._gst_amount = Math.max(itemGst, 0);
149
+ item._gross_amount = Math.max((0, utils_1.parseFloatCeil)(grossAmount), 0);
150
+ item._net_amount = Math.max((0, utils_1.parseFloatCeil)(netAmount), 0);
151
+ item._discount_amount = Math.max((0, utils_1.parseFloatCeil)(itemTotalDiscountAmount), 0);
152
+ item._gst_amount = Math.max((0, utils_1.parseFloatCeil)(itemGst), 0);
109
153
  });
110
154
  });
111
155
  }
@@ -114,6 +158,8 @@ function calculateCartWarehousePurchaseOrderInfoAndSyncData(data, calculateItemM
114
158
  categories,
115
159
  amount_collected,
116
160
  amount_earned,
161
+ order_discount_details,
162
+ total_discount_applied,
117
163
  gst_amount,
118
164
  price: (0, utils_1.parseNum)(subtotal),
119
165
  grand_total,
@@ -35,6 +35,7 @@ export * from './materialized_tenant_delivery_entries';
35
35
  export * from './materialized_tenant_delivery_geo_cells';
36
36
  export * from './materialized_tenant_delivery_geo_scopes';
37
37
  export * from './materialized_tenant_delivery_reports';
38
+ export * from './materialized_tenant_day_readiness';
38
39
  export * from './materialized_tenant_discount_entries';
39
40
  export * from './materialized_tenant_discount_reports';
40
41
  export * from './materialized_tenant_dialer_entries';
@@ -51,6 +51,7 @@ __exportStar(require("./materialized_tenant_delivery_entries"), exports);
51
51
  __exportStar(require("./materialized_tenant_delivery_geo_cells"), exports);
52
52
  __exportStar(require("./materialized_tenant_delivery_geo_scopes"), exports);
53
53
  __exportStar(require("./materialized_tenant_delivery_reports"), exports);
54
+ __exportStar(require("./materialized_tenant_day_readiness"), exports);
54
55
  __exportStar(require("./materialized_tenant_discount_entries"), exports);
55
56
  __exportStar(require("./materialized_tenant_discount_reports"), exports);
56
57
  __exportStar(require("./materialized_tenant_dialer_entries"), exports);
@@ -0,0 +1,78 @@
1
+ import { Schema } from 'mongoose';
2
+ import { MATERIALIZED_REPORT_READINESS_STATUS_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
+ /**
4
+ * Mongoose schema for `materialized_tenant_day_readiness`.
5
+ *
6
+ * The row's identity is the unique compound
7
+ * `(tenant_id, localDate, report_key, schema_version)`. It is written by the
8
+ * shared per-day materialization core on the caller's transaction session, so a
9
+ * rolled-back day leaves no row behind.
10
+ */
11
+ export declare const MaterializedTenantDayReadinessSchema: Schema<any, import("mongoose").Model<any, any, any, any, any, any>, {}, {}, {}, {}, {
12
+ timestamps: true;
13
+ versionKey: false;
14
+ minimize: false;
15
+ }, {
16
+ createdAt: NativeDate;
17
+ updatedAt: NativeDate;
18
+ } & {
19
+ localDate: string;
20
+ createdAt: NativeDate;
21
+ updatedAt: NativeDate;
22
+ tenant_id: string;
23
+ status: MATERIALIZED_REPORT_READINESS_STATUS_ENUM;
24
+ schema_version: number;
25
+ report_key: "DELIVERY" | "DISCOUNTS" | "OVERVIEW" | "PREP_TIME" | "DIALER";
26
+ run_id: string;
27
+ committed_at: NativeDate;
28
+ }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
29
+ createdAt: NativeDate;
30
+ updatedAt: NativeDate;
31
+ } & {
32
+ localDate: string;
33
+ createdAt: NativeDate;
34
+ updatedAt: NativeDate;
35
+ tenant_id: string;
36
+ status: MATERIALIZED_REPORT_READINESS_STATUS_ENUM;
37
+ schema_version: number;
38
+ report_key: "DELIVERY" | "DISCOUNTS" | "OVERVIEW" | "PREP_TIME" | "DIALER";
39
+ run_id: string;
40
+ committed_at: NativeDate;
41
+ }>> & import("mongoose").FlatRecord<{
42
+ createdAt: NativeDate;
43
+ updatedAt: NativeDate;
44
+ } & {
45
+ localDate: string;
46
+ createdAt: NativeDate;
47
+ updatedAt: NativeDate;
48
+ tenant_id: string;
49
+ status: MATERIALIZED_REPORT_READINESS_STATUS_ENUM;
50
+ schema_version: number;
51
+ report_key: "DELIVERY" | "DISCOUNTS" | "OVERVIEW" | "PREP_TIME" | "DIALER";
52
+ run_id: string;
53
+ committed_at: NativeDate;
54
+ }> & {
55
+ _id: import("mongoose").Types.ObjectId;
56
+ } & {
57
+ __v: number;
58
+ }>;
59
+ export declare const MATERIALIZED_TENANT_DAY_READINESS_COLLECTION_INDEXES: {
60
+ _id: {
61
+ _id: number;
62
+ };
63
+ tenant_id__localDate__report_key__schema_version: {
64
+ tenant_id: number;
65
+ localDate: number;
66
+ report_key: number;
67
+ schema_version: number;
68
+ };
69
+ };
70
+ /**
71
+ * Index OPTIONS the owner must CREATE (declared here, applied by a separate
72
+ * migration/deploy step — never by a read or a close at runtime).
73
+ */
74
+ export declare const MATERIALIZED_TENANT_DAY_READINESS_INDEX_OPTIONS: readonly {
75
+ key: Record<string, 1 | -1>;
76
+ name: string;
77
+ unique?: boolean;
78
+ }[];