@managesome/eposmatic-toolkit 0.4.63 → 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 (27) hide show
  1. package/esm/helpers/store/common-tenant-purchase-order-actions.js +12 -0
  2. package/esm/helpers/store/common-warehouse-purchase-order-actions.js +20 -0
  3. package/esm/helpers/store/tenant-purchase-orders-cart-actions.js +24 -7
  4. package/esm/helpers/store/warehouse-purchase-orders-cart-actions.js +23 -10
  5. package/esm/helpers/utils/index.js +1 -0
  6. package/esm/helpers/utils/tenant-purchase-order-engine.js +47 -0
  7. package/esm/helpers/utils/warehouse-purchase-order-engine.js +63 -4
  8. package/esm/schemas/models/tenant_purchase_orders.js +4 -0
  9. package/esm/schemas/models/warehouse_purchase_orders.js +4 -0
  10. package/lib/helpers/store/common-tenant-purchase-order-actions.d.ts +6 -1
  11. package/lib/helpers/store/common-tenant-purchase-order-actions.js +13 -0
  12. package/lib/helpers/store/common-warehouse-purchase-order-actions.js +20 -0
  13. package/lib/helpers/store/tenant-purchase-orders-cart-actions.js +23 -6
  14. package/lib/helpers/store/warehouse-purchase-orders-cart-actions.js +23 -10
  15. package/lib/helpers/utils/index.d.ts +1 -0
  16. package/lib/helpers/utils/index.js +1 -0
  17. package/lib/helpers/utils/tenant-purchase-order-engine.d.ts +24 -0
  18. package/lib/helpers/utils/tenant-purchase-order-engine.js +51 -0
  19. package/lib/helpers/utils/warehouse-purchase-order-engine.d.ts +23 -1
  20. package/lib/helpers/utils/warehouse-purchase-order-engine.js +65 -4
  21. package/lib/schemas/models/tenant_purchase_orders.d.ts +972 -0
  22. package/lib/schemas/models/tenant_purchase_orders.js +4 -0
  23. package/lib/schemas/models/warehouse_purchase_orders.d.ts +972 -0
  24. package/lib/schemas/models/warehouse_purchase_orders.js +4 -0
  25. package/lib/schemas/types/tenant_purchase_orders.d.ts +2 -1
  26. package/lib/schemas/types/warehouse_purchase_orders.d.ts +2 -1
  27. package/package.json +1 -1
@@ -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
  }
@@ -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: '',
@@ -1,8 +1,13 @@
1
- import { IOrderPayment, ITenantPurchaseOrder, ITenantPurchaseOrderCategory, ITenantPurchaseOrderDiscountDetails, ITenantPurchaseOrderItem, ITenantPurchaseOrderIteration } from '../../schemas';
1
+ import { IDiscountDetails, 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
+ /**
7
+ * An item discount mixes money and percentages, so the shared order-discount
8
+ * conversion is applied: percentages are left untouched.
9
+ */
10
+ export declare function getTenantPurchaseOrderItemDiscountDetailsWithPrice(discount: IDiscountDetails, convertToPrice: (price: number) => number): IDiscountDetails;
6
11
  export declare function getTenantPurchaseOrderItemsWithPrice(items: ITenantPurchaseOrderItem[] | undefined, convertToPrice: (price: number) => number): ITenantPurchaseOrderItem[];
7
12
  export declare function getTenantPurchaseOrderCategoriesWithPrice(categories: ITenantPurchaseOrderCategory[] | undefined, convertToPrice: (price: number) => number): ITenantPurchaseOrderCategory[];
8
13
  export declare function getTenantPurchaseOrderDiscountDetailsWithPrice(discount: ITenantPurchaseOrderDiscountDetails | null | undefined, convertToPrice: (price: number) => number): ITenantPurchaseOrderDiscountDetails | null;
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getTenantPurchaseOrderIterationsWithPrice = getTenantPurchaseOrderIterationsWithPrice;
7
7
  exports.getTenantPurchaseOrderPaymentsWithPrice = getTenantPurchaseOrderPaymentsWithPrice;
8
+ exports.getTenantPurchaseOrderItemDiscountDetailsWithPrice = getTenantPurchaseOrderItemDiscountDetailsWithPrice;
8
9
  exports.getTenantPurchaseOrderItemsWithPrice = getTenantPurchaseOrderItemsWithPrice;
9
10
  exports.getTenantPurchaseOrderCategoriesWithPrice = getTenantPurchaseOrderCategoriesWithPrice;
10
11
  exports.getTenantPurchaseOrderDiscountDetailsWithPrice = getTenantPurchaseOrderDiscountDetailsWithPrice;
@@ -40,6 +41,13 @@ function getTenantPurchaseOrderPaymentsWithPrice(payments, convertToPrice) {
40
41
  amount_refunded: convertToPrice(payment.amount_refunded),
41
42
  }));
42
43
  }
44
+ /**
45
+ * An item discount mixes money and percentages, so the shared order-discount
46
+ * conversion is applied: percentages are left untouched.
47
+ */
48
+ function getTenantPurchaseOrderItemDiscountDetailsWithPrice(discount, convertToPrice) {
49
+ return getTenantPurchaseOrderDiscountDetailsWithPrice(discount, convertToPrice);
50
+ }
43
51
  function getTenantPurchaseOrderItemsWithPrice(items, convertToPrice) {
44
52
  if (!items)
45
53
  return [];
@@ -48,6 +56,11 @@ function getTenantPurchaseOrderItemsWithPrice(items, convertToPrice) {
48
56
  quantity: (0, utils_1.parseNum)(item.quantity || 1, true),
49
57
  price: convertToPrice(item.price ?? 0),
50
58
  subtotal: convertToPrice(item.subtotal ?? 0),
59
+ ...(item.item_discount_details != null
60
+ ? {
61
+ item_discount_details: getTenantPurchaseOrderItemDiscountDetailsWithPrice(item.item_discount_details, convertToPrice),
62
+ }
63
+ : {}),
51
64
  _gst_amount: convertToPrice(item._gst_amount ?? 0),
52
65
  _net_amount: convertToPrice(item._net_amount ?? 0),
53
66
  _gross_amount: convertToPrice(item._gross_amount ?? 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';