@managesome/eposmatic-toolkit 0.4.89 → 0.4.90

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 (34) hide show
  1. package/esm/helpers/order/generate-warehouse-internal-movement.js +3 -0
  2. package/esm/helpers/store/common-warehouse-internal-movement-actions.js +124 -4
  3. package/esm/helpers/utils/discount-amounts.js +64 -0
  4. package/esm/helpers/utils/index.js +2 -0
  5. package/esm/helpers/utils/internal-movement-items.js +30 -0
  6. package/esm/helpers/utils/tenant-purchase-order-engine.js +10 -18
  7. package/esm/helpers/utils/warehouse-purchase-order-engine.js +10 -18
  8. package/esm/schemas/models/warehouse_internal_movements.js +54 -0
  9. package/lib/helpers/order/generate-warehouse-internal-movement.js +3 -0
  10. package/lib/helpers/store/common-warehouse-internal-movement-actions.d.ts +33 -1
  11. package/lib/helpers/store/common-warehouse-internal-movement-actions.js +126 -3
  12. package/lib/helpers/utils/discount-amounts.d.ts +50 -0
  13. package/lib/helpers/utils/discount-amounts.js +69 -0
  14. package/lib/helpers/utils/index.d.ts +2 -0
  15. package/lib/helpers/utils/index.js +2 -0
  16. package/lib/helpers/utils/internal-movement-items.d.ts +35 -0
  17. package/lib/helpers/utils/internal-movement-items.js +36 -0
  18. package/lib/helpers/utils/tenant-purchase-order-engine.js +9 -17
  19. package/lib/helpers/utils/warehouse-purchase-order-engine.js +9 -17
  20. package/lib/schemas/models/inventories.d.ts +3 -3
  21. package/lib/schemas/models/inventory_transactions.d.ts +3 -3
  22. package/lib/schemas/models/item_transactions.d.ts +3 -3
  23. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +3 -3
  24. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +3 -3
  25. package/lib/schemas/models/orders.d.ts +120 -120
  26. package/lib/schemas/models/tenant_inventory_department_transactions.d.ts +3 -3
  27. package/lib/schemas/models/tenant_inventory_department_utilities.d.ts +3 -3
  28. package/lib/schemas/models/warehouse_internal_movements.d.ts +570 -0
  29. package/lib/schemas/models/warehouse_internal_movements.js +54 -0
  30. package/lib/schemas/models/warehouse_inventory_transactions.d.ts +3 -3
  31. package/lib/schemas/models/warehouse_item_transactions.d.ts +3 -3
  32. package/lib/schemas/models/warehouse_items.d.ts +3 -3
  33. package/lib/schemas/types/warehouse_internal_movements.d.ts +17 -1
  34. package/package.json +1 -1
@@ -1,11 +1,40 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getWarehouseInternalMovementItemDiscountAmount = getWarehouseInternalMovementItemDiscountAmount;
4
+ exports.withResolvedWarehouseInternalMovementItemDiscountTotal = withResolvedWarehouseInternalMovementItemDiscountTotal;
3
5
  exports.getWarehouseInternalMovementItemsWithPrice = getWarehouseInternalMovementItemsWithPrice;
4
6
  exports.getWarehouseInternalMovementIterationsWithPrice = getWarehouseInternalMovementIterationsWithPrice;
5
7
  exports.getWarehouseInternalMovementWithPrice = getWarehouseInternalMovementWithPrice;
8
+ exports.getWarehouseInternalMovementOrderDiscountDetails = getWarehouseInternalMovementOrderDiscountDetails;
6
9
  exports.calculateCartInternalMovementInfoAndSyncData = calculateCartInternalMovementInfoAndSyncData;
7
10
  const utils_1 = require("../utils");
8
11
  const common_order_actions_1 = require("./common-order-actions");
12
+ /**
13
+ * Resolved money value of one movement line's discount.
14
+ *
15
+ * Mirrors `getWarehousePurchaseOrderItemDiscountAmount`: a flat
16
+ * `special_discount` is PER UNIT (so it scales with quantity) and a percentage
17
+ * applies to the line's gross value. The result is clamped to the line total.
18
+ */
19
+ function getWarehouseInternalMovementItemDiscountAmount(item) {
20
+ // Shared rule with warehouse/tenant POs; this wrapper keeps the movement
21
+ // cart's currency-decimal rounding.
22
+ return (0, utils_1.parseNum)((0, utils_1.getItemDiscountAmount)({
23
+ grossAmount: (0, utils_1.parseNum)((item.unit_price ?? 0) * (item.quantity ?? 0)),
24
+ quantity: item.quantity,
25
+ details: item.item_discount_details,
26
+ }));
27
+ }
28
+ /**
29
+ * Refreshes `total_discount` on a line's discount record so it matches the
30
+ * line's current price/quantity, preserving every other field.
31
+ */
32
+ function withResolvedWarehouseInternalMovementItemDiscountTotal(item) {
33
+ const details = item.item_discount_details;
34
+ if (!details)
35
+ return null;
36
+ return (0, utils_1.withDiscountTotal)(details, getWarehouseInternalMovementItemDiscountAmount(item));
37
+ }
9
38
  /**
10
39
  * Convert unit_price on every internal movement item.
11
40
  */
@@ -15,8 +44,27 @@ function getWarehouseInternalMovementItemsWithPrice(items, convertToPrice) {
15
44
  return items.map((item) => ({
16
45
  ...item,
17
46
  unit_price: item.unit_price != null ? convertToPrice(item.unit_price) : undefined,
47
+ ...(item.item_discount_details != null
48
+ ? {
49
+ item_discount_details: getWarehouseInternalMovementItemDiscountDetailsWithPrice(item.item_discount_details, convertToPrice),
50
+ }
51
+ : {}),
18
52
  }));
19
53
  }
54
+ /**
55
+ * Scale a line discount record. A percentage is not a price, so only the fixed
56
+ * per-unit amount and the resolved total are converted.
57
+ */
58
+ function getWarehouseInternalMovementItemDiscountDetailsWithPrice(discount, convertToPrice) {
59
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
60
+ return {
61
+ ...discount,
62
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
63
+ ? { special_discount: convertToPrice(special_discount) }
64
+ : {}),
65
+ total_discount: convertToPrice(total_discount ?? 0),
66
+ };
67
+ }
20
68
  /**
21
69
  * Convert monetary fields on payments array.
22
70
  */
@@ -39,6 +87,22 @@ function getWarehouseInternalMovementIterationsWithPrice(iterations, writeable)
39
87
  return [];
40
88
  return iterations.map((iteration) => getWarehouseInternalMovementWithPrice(iteration, writeable));
41
89
  }
90
+ /**
91
+ * Convert the order-level discount record. A percentage is not a price, so only
92
+ * the resolved money value (and a fixed `special_discount`) are scaled.
93
+ */
94
+ function getWarehouseInternalMovementDiscountDetailsWithPrice(discount, convertToPrice) {
95
+ if (!discount)
96
+ return null;
97
+ const { special_discount, is_special_discount_percentage, total_discount } = discount;
98
+ return {
99
+ ...discount,
100
+ ...(typeof special_discount === 'number' && !is_special_discount_percentage
101
+ ? { special_discount: convertToPrice(special_discount) }
102
+ : {}),
103
+ total_discount: convertToPrice(total_discount ?? 0),
104
+ };
105
+ }
42
106
  /**
43
107
  * Convert all monetary fields on an internal movement.
44
108
  *
@@ -59,6 +123,14 @@ function getWarehouseInternalMovementWithPrice(order, writeable) {
59
123
  ...(order.amount_collected != null ? { amount_collected: convertToPrice(order.amount_collected) } : {}),
60
124
  ...(order.amount_earned != null ? { amount_earned: convertToPrice(order.amount_earned) } : {}),
61
125
  ...(order.gst != null ? { gst: convertToPrice(order.gst) } : {}),
126
+ ...(order.order_discount_details != null
127
+ ? {
128
+ order_discount_details: getWarehouseInternalMovementDiscountDetailsWithPrice(order.order_discount_details, convertToPrice),
129
+ }
130
+ : {}),
131
+ ...(order.total_discount_applied != null
132
+ ? { total_discount_applied: convertToPrice(order.total_discount_applied) }
133
+ : {}),
62
134
  ...(order.labor_charges != null && order.is_labor_charges_percentage !== true
63
135
  ? { labor_charges: convertToPrice(order.labor_charges) }
64
136
  : {}),
@@ -81,25 +153,70 @@ function getWarehouseInternalMovementWithPrice(order, writeable) {
81
153
  : {}),
82
154
  };
83
155
  }
156
+ /**
157
+ * Resolve the order-level discount of an internal movement against its items
158
+ * subtotal. Mirrors `getWarehousePurchaseOrderOrderDiscountDetails`.
159
+ *
160
+ * `special_discount` is a percentage when `is_special_discount_percentage` is
161
+ * true and a flat money amount otherwise. The resolved value is clamped to the
162
+ * subtotal, so a movement can never go negative.
163
+ */
164
+ function getWarehouseInternalMovementOrderDiscountDetails(discountDetails, baseAmount) {
165
+ if (!discountDetails) {
166
+ return { order_discount_details: null, total_discount_applied: 0 };
167
+ }
168
+ const totalDiscount = (0, utils_1.parseNum)((0, utils_1.getOrderDiscountAmount)({
169
+ baseAmount,
170
+ details: discountDetails,
171
+ }));
172
+ if (totalDiscount <= 0) {
173
+ return { order_discount_details: null, total_discount_applied: 0 };
174
+ }
175
+ return {
176
+ order_discount_details: (0, utils_1.withDiscountTotal)(discountDetails, totalDiscount),
177
+ total_discount_applied: totalDiscount,
178
+ };
179
+ }
84
180
  /**
85
181
  * Recalculate financial totals for an internal movement — mirrors
86
182
  * `calculateCartWarehousePurchaseOrderInfoAndSyncData` but for the flat
87
183
  * `items` array instead of nested `categories`.
184
+ *
185
+ * Each line's item discount is taken off first, then the order-level discount
186
+ * is applied to the resulting subtotal. GST and percentage charges are
187
+ * calculated on the discounted value. When `exclude_discount_from_gst` is true
188
+ * the order discount is taken off after GST instead.
88
189
  */
89
190
  function calculateCartInternalMovementInfoAndSyncData(data) {
90
- const subtotal = (data.items ?? []).reduce((sum, item) => sum + (0, utils_1.parseNum)((item.unit_price ?? 0) * (item.quantity ?? 0)), 0);
191
+ let subtotal = 0;
192
+ const items = (data.items ?? []).map((item) => {
193
+ const grossAmount = (0, utils_1.parseNum)((item.unit_price ?? 0) * (item.quantity ?? 0));
194
+ const itemDiscountAmount = getWarehouseInternalMovementItemDiscountAmount(item);
195
+ subtotal += (0, utils_1.parseNum)(Math.max(0, grossAmount - itemDiscountAmount));
196
+ return {
197
+ ...item,
198
+ item_discount_details: withResolvedWarehouseInternalMovementItemDiscountTotal(item),
199
+ };
200
+ });
201
+ subtotal = (0, utils_1.parseNum)(subtotal);
202
+ const { order_discount_details, total_discount_applied } = getWarehouseInternalMovementOrderDiscountDetails(data.order_discount_details, subtotal);
203
+ const applyGSTOnOriginalPrice = data.exclude_discount_from_gst === true;
91
204
  let grand_total = subtotal;
205
+ if (!applyGSTOnOriginalPrice) {
206
+ grand_total -= total_discount_applied;
207
+ }
208
+ const postDiscountSubtotal = (0, utils_1.parseNum)(Math.max(0, subtotal - total_discount_applied));
92
209
  let gst_amount = 0;
93
210
  const gst = data.gst ?? 0;
94
211
  // Order-level charges (labor, freight): entered per movement, either a fixed
95
- // amount or a percentage of the items subtotal. `is_*_charges_taxable`
212
+ // amount or a percentage of the post-discount items subtotal. `is_*_charges_taxable`
96
213
  // (snapshot of the warehouse setting) decides the placement: taxable => added
97
214
  // BEFORE GST, untaxed => added after it.
98
215
  const getOrderCharge = (value, isPercentage) => {
99
216
  const entered = (0, utils_1.parseNum)(Math.max(0, value ?? 0));
100
217
  return {
101
218
  entered,
102
- amount: isPercentage ? (0, utils_1.parseNum)((0, utils_1.getPercentageAmount)(subtotal, entered)) : entered,
219
+ amount: isPercentage ? (0, utils_1.parseNum)((0, utils_1.getPercentageAmount)(postDiscountSubtotal, entered)) : entered,
103
220
  };
104
221
  };
105
222
  const labor = getOrderCharge(data.labor_charges, data.is_labor_charges_percentage);
@@ -121,6 +238,9 @@ function calculateCartInternalMovementInfoAndSyncData(data) {
121
238
  gst_amount = (0, utils_1.getPercentageAmount)(grand_total, gst);
122
239
  grand_total += gst_amount;
123
240
  }
241
+ if (applyGSTOnOriginalPrice) {
242
+ grand_total -= total_discount_applied;
243
+ }
124
244
  const untaxedCharges = (isLaborTaxable ? 0 : labor_charges_amount) + (isFreightTaxable ? 0 : freight_charges_amount);
125
245
  if (untaxedCharges > 0) {
126
246
  grand_total += untaxedCharges;
@@ -130,8 +250,11 @@ function calculateCartInternalMovementInfoAndSyncData(data) {
130
250
  grand_total = (0, utils_1.parseNum)(grand_total);
131
251
  return {
132
252
  ...data,
253
+ items,
133
254
  grand_total,
134
255
  gst_amount,
256
+ order_discount_details,
257
+ total_discount_applied,
135
258
  labor_charges,
136
259
  labor_charges_amount,
137
260
  freight_charges,
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Minimal shape shared by every discount record that stores a special
3
+ * discount (warehouse PO, tenant PO, internal movement line and order).
4
+ */
5
+ export interface IDiscountValues {
6
+ special_discount?: number;
7
+ is_special_discount_percentage?: boolean;
8
+ total_discount?: number;
9
+ }
10
+ export interface IItemDiscountInput {
11
+ /** Gross value of the line (unit price × quantity), in the caller's unit. */
12
+ grossAmount: number;
13
+ quantity: number;
14
+ details?: IDiscountValues | null;
15
+ }
16
+ /**
17
+ * Resolve one line's item discount to a money amount.
18
+ *
19
+ * This is the single source of truth for the rule shared by warehouse POs,
20
+ * tenant POs and internal movements:
21
+ * - a fixed `special_discount` is **per unit**, so it scales with quantity;
22
+ * - a percentage applies to the line's gross value;
23
+ * - `total_discount` is a fallback for records without a special discount;
24
+ * - the result is clamped to `[0, gross]`, so a line can never go negative.
25
+ *
26
+ * The function is deliberately rounding-free: callers decide whether they work
27
+ * in currency decimals (`parseNum`) or warehouse wire units (integer maths).
28
+ * Invalid/NaN/Infinity input resolves to `0` instead of poisoning totals.
29
+ */
30
+ export declare function getItemDiscountAmount({ grossAmount, quantity, details }: IItemDiscountInput): number;
31
+ export interface IOrderDiscountInput {
32
+ /** Order subtotal the discount is resolved against. */
33
+ baseAmount: number;
34
+ details?: IDiscountValues | null;
35
+ }
36
+ /**
37
+ * Resolve an order-level discount to a money amount.
38
+ *
39
+ * Same value rules as `getItemDiscountAmount` (except a fixed amount is a
40
+ * one-off order amount, not per unit). The result is clamped to the subtotal.
41
+ * Rounding is left to the caller.
42
+ */
43
+ export declare function getOrderDiscountAmount({ baseAmount, details }: IOrderDiscountInput): number;
44
+ /**
45
+ * Return a copy of a discount record with its resolved money value refreshed.
46
+ * Preserves every other field (id, name, reason, reference).
47
+ */
48
+ export declare function withDiscountTotal<T extends IDiscountValues>(details: T, totalDiscount: number): T & {
49
+ total_discount: number;
50
+ };
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getItemDiscountAmount = getItemDiscountAmount;
4
+ exports.getOrderDiscountAmount = getOrderDiscountAmount;
5
+ exports.withDiscountTotal = withDiscountTotal;
6
+ const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
7
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
8
+ /**
9
+ * Resolve one line's item discount to a money amount.
10
+ *
11
+ * This is the single source of truth for the rule shared by warehouse POs,
12
+ * tenant POs and internal movements:
13
+ * - a fixed `special_discount` is **per unit**, so it scales with quantity;
14
+ * - a percentage applies to the line's gross value;
15
+ * - `total_discount` is a fallback for records without a special discount;
16
+ * - the result is clamped to `[0, gross]`, so a line can never go negative.
17
+ *
18
+ * The function is deliberately rounding-free: callers decide whether they work
19
+ * in currency decimals (`parseNum`) or warehouse wire units (integer maths).
20
+ * Invalid/NaN/Infinity input resolves to `0` instead of poisoning totals.
21
+ */
22
+ function getItemDiscountAmount({ grossAmount, quantity, details }) {
23
+ if (!details)
24
+ return 0;
25
+ const safeGrossAmount = isFiniteNumber(grossAmount) ? Math.max(0, grossAmount) : 0;
26
+ const safeQuantity = isFiniteNumber(quantity) ? Math.max(0, quantity) : 0;
27
+ if (!(safeGrossAmount > 0))
28
+ return 0;
29
+ const value = details.special_discount;
30
+ if (isFiniteNumber(value) && value > 0) {
31
+ const rawAmount = details.is_special_discount_percentage
32
+ ? (safeGrossAmount * clamp(value, 0, 100)) / 100
33
+ : value * safeQuantity;
34
+ return clamp(rawAmount, 0, safeGrossAmount);
35
+ }
36
+ const fallback = details.total_discount;
37
+ return isFiniteNumber(fallback) ? clamp(fallback, 0, safeGrossAmount) : 0;
38
+ }
39
+ /**
40
+ * Resolve an order-level discount to a money amount.
41
+ *
42
+ * Same value rules as `getItemDiscountAmount` (except a fixed amount is a
43
+ * one-off order amount, not per unit). The result is clamped to the subtotal.
44
+ * Rounding is left to the caller.
45
+ */
46
+ function getOrderDiscountAmount({ baseAmount, details }) {
47
+ if (!details)
48
+ return 0;
49
+ const base = isFiniteNumber(baseAmount) ? Math.max(0, baseAmount) : 0;
50
+ if (!(base > 0))
51
+ return 0;
52
+ const value = details.special_discount;
53
+ if (isFiniteNumber(value) && value > 0) {
54
+ const rawAmount = details.is_special_discount_percentage ? (base * clamp(value, 0, 100)) / 100 : value;
55
+ return clamp(rawAmount, 0, base);
56
+ }
57
+ const fallback = details.total_discount;
58
+ return isFiniteNumber(fallback) ? clamp(fallback, 0, base) : 0;
59
+ }
60
+ /**
61
+ * Return a copy of a discount record with its resolved money value refreshed.
62
+ * Preserves every other field (id, name, reason, reference).
63
+ */
64
+ function withDiscountTotal(details, totalDiscount) {
65
+ return {
66
+ ...details,
67
+ total_discount: totalDiscount,
68
+ };
69
+ }
@@ -26,6 +26,7 @@ export * from './image-helpers';
26
26
  export * from './image-url-helpers';
27
27
  export * from './ingredients';
28
28
  export * from './internal-amount-helpers';
29
+ export * from './internal-movement-items';
29
30
  export * from './inventory';
30
31
  export * from './inventory_entries';
31
32
  export * from './inventory_transactions';
@@ -33,6 +34,7 @@ export * from './item-report-helpers';
33
34
  export * from './items-comparison-report-helpers';
34
35
  export * from './kds-helpers';
35
36
  export * from './location-helpers';
37
+ export * from './discount-amounts';
36
38
  export * from './menu-helpers';
37
39
  export * from './minified-catalog';
38
40
  export * from './offer-apply-helpers';
@@ -42,6 +42,7 @@ __exportStar(require("./image-helpers"), exports);
42
42
  __exportStar(require("./image-url-helpers"), exports);
43
43
  __exportStar(require("./ingredients"), exports);
44
44
  __exportStar(require("./internal-amount-helpers"), exports);
45
+ __exportStar(require("./internal-movement-items"), exports);
45
46
  __exportStar(require("./inventory"), exports);
46
47
  __exportStar(require("./inventory_entries"), exports);
47
48
  __exportStar(require("./inventory_transactions"), exports);
@@ -49,6 +50,7 @@ __exportStar(require("./item-report-helpers"), exports);
49
50
  __exportStar(require("./items-comparison-report-helpers"), exports);
50
51
  __exportStar(require("./kds-helpers"), exports);
51
52
  __exportStar(require("./location-helpers"), exports);
53
+ __exportStar(require("./discount-amounts"), exports);
52
54
  __exportStar(require("./menu-helpers"), exports);
53
55
  __exportStar(require("./minified-catalog"), exports);
54
56
  __exportStar(require("./offer-apply-helpers"), exports);
@@ -0,0 +1,35 @@
1
+ import { IDiscountDetails, IWarehouseInternalMovementItem } from '../../schemas';
2
+ /**
3
+ * The subset of a cart line needed to build an internal movement line. Both the
4
+ * warehouse and admin cart item shapes satisfy this structurally.
5
+ */
6
+ export interface IMovementCartLine {
7
+ _id?: string;
8
+ item_id: string;
9
+ inventory_code?: string;
10
+ name: string;
11
+ quantity: number;
12
+ unit_price?: number;
13
+ item_discount_details?: IDiscountDetails | null;
14
+ notes?: string | null;
15
+ }
16
+ export interface IBuildInternalMovementItemOptions {
17
+ /**
18
+ * Catalog inventory code to use when the cart line has none. The warehouse
19
+ * app resolves this from its catalog map; the admin app normally leaves it
20
+ * unset and falls back to `item_id`.
21
+ */
22
+ inventoryCodeFallback?: string;
23
+ }
24
+ /**
25
+ * Convert a cart line to the document line shape.
26
+ *
27
+ * This is the single mapper used by cart summaries and by both submit flows, so
28
+ * a field the pricing engine reads (notably `item_discount_details`) cannot be
29
+ * dropped in one place and kept in another.
30
+ *
31
+ * `item_discount_details` is always present (`null` when absent): a full
32
+ * document edit must be able to clear a discount by sending an explicit null.
33
+ * Partial updates that omit the field are handled separately by the backend.
34
+ */
35
+ export declare function buildInternalMovementItem(line: IMovementCartLine, options?: IBuildInternalMovementItemOptions): IWarehouseInternalMovementItem;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.buildInternalMovementItem = buildInternalMovementItem;
7
+ const bson_objectid_1 = __importDefault(require("bson-objectid"));
8
+ /**
9
+ * Convert a cart line to the document line shape.
10
+ *
11
+ * This is the single mapper used by cart summaries and by both submit flows, so
12
+ * a field the pricing engine reads (notably `item_discount_details`) cannot be
13
+ * dropped in one place and kept in another.
14
+ *
15
+ * `item_discount_details` is always present (`null` when absent): a full
16
+ * document edit must be able to clear a discount by sending an explicit null.
17
+ * Partial updates that omit the field are handled separately by the backend.
18
+ */
19
+ function buildInternalMovementItem(line, options) {
20
+ const parsedQuantity = Number(line.quantity);
21
+ const quantity = Number.isFinite(parsedQuantity) ? Math.max(0, parsedQuantity) : 0;
22
+ const parsedUnitPrice = line.unit_price != null ? Number(line.unit_price) : undefined;
23
+ const unitPrice = parsedUnitPrice != null && Number.isFinite(parsedUnitPrice) ? parsedUnitPrice : undefined;
24
+ const notes = line.notes?.trim();
25
+ return {
26
+ _id: line._id?.trim() || (0, bson_objectid_1.default)().toHexString(),
27
+ item_id: line.item_id,
28
+ inventory_code: line.inventory_code?.trim() || options?.inventoryCodeFallback?.trim() || line.item_id,
29
+ item_name: line.name,
30
+ quantity,
31
+ received_qty: 0,
32
+ ...(unitPrice != null ? { unit_price: unitPrice } : {}),
33
+ item_discount_details: line.item_discount_details ?? null,
34
+ ...(notes ? { notes } : {}),
35
+ };
36
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getTenantPurchaseOrderItemDiscountAmount = getTenantPurchaseOrderItemDiscountAmount;
4
4
  exports.withResolvedTenantItemDiscountTotal = withResolvedTenantItemDiscountTotal;
5
5
  const common_1 = require("./common");
6
+ const discount_amounts_1 = require("./discount-amounts");
6
7
  // ==========================================================><====================================================
7
8
  /**
8
9
  * Total item-level discount for a tenant purchase order line, in money.
@@ -20,19 +21,13 @@ const common_1 = require("./common");
20
21
  * a line negative.
21
22
  */
22
23
  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)));
24
+ // Shared rule with warehouse POs and internal movements; this wrapper keeps
25
+ // the tenant PO's currency-decimal rounding.
26
+ return (0, common_1.parseNum)((0, discount_amounts_1.getItemDiscountAmount)({
27
+ grossAmount: (0, common_1.parseNum)((orderItem.price ?? 0) * (orderItem.quantity ?? 0)),
28
+ quantity: orderItem.quantity,
29
+ details: orderItem.item_discount_details,
30
+ }));
36
31
  }
37
32
  /**
38
33
  * Refreshes `total_discount` on a line's discount record so the amount it
@@ -44,8 +39,5 @@ function withResolvedTenantItemDiscountTotal(orderItem) {
44
39
  const details = orderItem.item_discount_details;
45
40
  if (!details)
46
41
  return null;
47
- return {
48
- ...details,
49
- total_discount: getTenantPurchaseOrderItemDiscountAmount(orderItem),
50
- };
42
+ return (0, discount_amounts_1.withDiscountTotal)(details, getTenantPurchaseOrderItemDiscountAmount(orderItem));
51
43
  }
@@ -9,6 +9,7 @@ exports.convertWarehouseItemToPurchaseOrderItem = convertWarehouseItemToPurchase
9
9
  exports.getCurrentWarehousePurchaseOrderItemTotalPrice = getCurrentWarehousePurchaseOrderItemTotalPrice;
10
10
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
11
11
  const common_1 = require("./common");
12
+ const discount_amounts_1 = require("./discount-amounts");
12
13
  // ==========================================================><====================================================
13
14
  /**
14
15
  * Total item-level discount for a purchase order line, in money.
@@ -25,19 +26,13 @@ const common_1 = require("./common");
25
26
  * line negative.
26
27
  */
27
28
  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)));
29
+ // Shared rule with tenant POs and internal movements; this wrapper keeps the
30
+ // warehouse PO's currency-decimal rounding.
31
+ return (0, common_1.parseNum)((0, discount_amounts_1.getItemDiscountAmount)({
32
+ grossAmount: (0, common_1.parseNum)((orderItem.price ?? 0) * (orderItem.quantity ?? 0)),
33
+ quantity: orderItem.quantity,
34
+ details: orderItem.item_discount_details,
35
+ }));
41
36
  }
42
37
  /**
43
38
  * Refreshes `total_discount` on a line's discount record so the amount it
@@ -49,10 +44,7 @@ function withResolvedWarehouseItemDiscountTotal(orderItem) {
49
44
  const details = orderItem.item_discount_details;
50
45
  if (!details)
51
46
  return null;
52
- return {
53
- ...details,
54
- total_discount: getWarehousePurchaseOrderItemDiscountAmount(orderItem),
55
- };
47
+ return (0, discount_amounts_1.withDiscountTotal)(details, getWarehousePurchaseOrderItemDiscountAmount(orderItem));
56
48
  }
57
49
  function convertWarehouseItemToPurchaseOrderItem({ vendorId, item, orderItem, }) {
58
50
  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 ?? {};
@@ -17,10 +17,10 @@ export declare const InventorySchema: Schema<any, import("mongoose").Model<any,
17
17
  updatedAt: NativeDate;
18
18
  active: boolean;
19
19
  tenant_id: string;
20
+ unit_price: number;
20
21
  unit: import("../../constants").INVENTORY_ITEM_UNIT_ENUM;
21
22
  threshold_quantity: number;
22
23
  quantity_left: number;
23
- unit_price: number;
24
24
  remaining_stock_price: number;
25
25
  category_id?: import("mongoose").Types.ObjectId | null | undefined;
26
26
  ingredients?: import("mongoose").Types.DocumentArray<{
@@ -49,10 +49,10 @@ export declare const InventorySchema: Schema<any, import("mongoose").Model<any,
49
49
  updatedAt: NativeDate;
50
50
  active: boolean;
51
51
  tenant_id: string;
52
+ unit_price: number;
52
53
  unit: import("../../constants").INVENTORY_ITEM_UNIT_ENUM;
53
54
  threshold_quantity: number;
54
55
  quantity_left: number;
55
- unit_price: number;
56
56
  remaining_stock_price: number;
57
57
  category_id?: import("mongoose").Types.ObjectId | null | undefined;
58
58
  ingredients?: import("mongoose").Types.DocumentArray<{
@@ -81,10 +81,10 @@ export declare const InventorySchema: Schema<any, import("mongoose").Model<any,
81
81
  updatedAt: NativeDate;
82
82
  active: boolean;
83
83
  tenant_id: string;
84
+ unit_price: number;
84
85
  unit: import("../../constants").INVENTORY_ITEM_UNIT_ENUM;
85
86
  threshold_quantity: number;
86
87
  quantity_left: number;
87
- unit_price: number;
88
88
  remaining_stock_price: number;
89
89
  category_id?: import("mongoose").Types.ObjectId | null | undefined;
90
90
  ingredients?: import("mongoose").Types.DocumentArray<{
@@ -13,8 +13,8 @@ export declare const InventoryTransactionsSchema: Schema<any, import("mongoose")
13
13
  inventory_code: string;
14
14
  tenant_id: string;
15
15
  createdAt_mins: number;
16
- quantity_left: number;
17
16
  unit_price: number;
17
+ quantity_left: number;
18
18
  remaining_stock_price: number;
19
19
  previous_quantity_left: number;
20
20
  previous_unit_price: number;
@@ -39,8 +39,8 @@ export declare const InventoryTransactionsSchema: Schema<any, import("mongoose")
39
39
  inventory_code: string;
40
40
  tenant_id: string;
41
41
  createdAt_mins: number;
42
- quantity_left: number;
43
42
  unit_price: number;
43
+ quantity_left: number;
44
44
  remaining_stock_price: number;
45
45
  previous_quantity_left: number;
46
46
  previous_unit_price: number;
@@ -65,8 +65,8 @@ export declare const InventoryTransactionsSchema: Schema<any, import("mongoose")
65
65
  inventory_code: string;
66
66
  tenant_id: string;
67
67
  createdAt_mins: number;
68
- quantity_left: number;
69
68
  unit_price: number;
69
+ quantity_left: number;
70
70
  remaining_stock_price: number;
71
71
  previous_quantity_left: number;
72
72
  previous_unit_price: number;
@@ -16,9 +16,9 @@ export declare const ItemTransactionsSchema: Schema<any, import("mongoose").Mode
16
16
  order_number: number;
17
17
  item_id: import("mongoose").Types.ObjectId;
18
18
  quantity: number;
19
+ item_name: string;
19
20
  transaction_type: import("../../constants").ITEM_TRANSACTION_TYPE_ENUM;
20
21
  selling_price: number;
21
- item_name: string;
22
22
  category_name: string;
23
23
  cost_price: number;
24
24
  description?: string | null | undefined;
@@ -36,9 +36,9 @@ export declare const ItemTransactionsSchema: Schema<any, import("mongoose").Mode
36
36
  order_number: number;
37
37
  item_id: import("mongoose").Types.ObjectId;
38
38
  quantity: number;
39
+ item_name: string;
39
40
  transaction_type: import("../../constants").ITEM_TRANSACTION_TYPE_ENUM;
40
41
  selling_price: number;
41
- item_name: string;
42
42
  category_name: string;
43
43
  cost_price: number;
44
44
  description?: string | null | undefined;
@@ -56,9 +56,9 @@ export declare const ItemTransactionsSchema: Schema<any, import("mongoose").Mode
56
56
  order_number: number;
57
57
  item_id: import("mongoose").Types.ObjectId;
58
58
  quantity: number;
59
+ item_name: string;
59
60
  transaction_type: import("../../constants").ITEM_TRANSACTION_TYPE_ENUM;
60
61
  selling_price: number;
61
- item_name: string;
62
62
  category_name: string;
63
63
  cost_price: number;
64
64
  description?: string | null | undefined;
@@ -35,13 +35,13 @@ declare const DiscountEntrySchema: Schema<any, import("mongoose").Model<any, any
35
35
  platform: string;
36
36
  slot: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SLOT_ENUM | null;
37
37
  item_id: string;
38
+ item_name: string;
38
39
  kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
39
40
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
40
41
  level: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_LEVEL_ENUM;
41
42
  entry_key: string;
42
43
  catalog_item_id: string;
43
44
  catalog_auto: boolean;
44
- item_name: string;
45
45
  rate: number;
46
46
  item_value: number;
47
47
  discount_id: string;
@@ -67,13 +67,13 @@ declare const DiscountEntrySchema: Schema<any, import("mongoose").Model<any, any
67
67
  platform: string;
68
68
  slot: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SLOT_ENUM | null;
69
69
  item_id: string;
70
+ item_name: string;
70
71
  kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
71
72
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
72
73
  level: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_LEVEL_ENUM;
73
74
  entry_key: string;
74
75
  catalog_item_id: string;
75
76
  catalog_auto: boolean;
76
- item_name: string;
77
77
  rate: number;
78
78
  item_value: number;
79
79
  discount_id: string;
@@ -99,13 +99,13 @@ declare const DiscountEntrySchema: Schema<any, import("mongoose").Model<any, any
99
99
  platform: string;
100
100
  slot: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SLOT_ENUM | null;
101
101
  item_id: string;
102
+ item_name: string;
102
103
  kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM;
103
104
  sub_kind: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_SUB_KIND_ENUM;
104
105
  level: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_DISCOUNT_LEVEL_ENUM;
105
106
  entry_key: string;
106
107
  catalog_item_id: string;
107
108
  catalog_auto: boolean;
108
- item_name: string;
109
109
  rate: number;
110
110
  item_value: number;
111
111
  discount_id: string;