@pisell/pisellos 2.2.193 → 2.2.194

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.
@@ -1,11 +1,16 @@
1
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
2
1
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
3
2
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
5
3
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
6
4
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
7
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
8
5
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
6
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
7
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
8
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
10
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
11
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
12
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
13
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
9
14
  import Decimal from 'decimal.js';
10
15
  import { getSurcharge, getSurchargeAmount } from "../Summary/utils";
11
16
  import { getProductSkuOptions } from "../Order/utils";
@@ -15,6 +20,30 @@ function toDecimal(value) {
15
20
  function toFixed2(value) {
16
21
  return new Decimal(value || 0).toFixed(2);
17
22
  }
23
+ function toAmountFormat(value) {
24
+ return new Decimal(value || 0).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
25
+ }
26
+ function toBackendTaxFee(value) {
27
+ return toBcScale(value, 2);
28
+ }
29
+ function toBcScale(value, scale) {
30
+ var factor = new Decimal(10).pow(scale);
31
+ return new Decimal(value || 0).times(factor).toDecimalPlaces(0, Decimal.ROUND_DOWN).div(factor);
32
+ }
33
+ function bcAdd(left, right, scale) {
34
+ return toBcScale(new Decimal(left || 0).plus(right || 0), scale);
35
+ }
36
+ function bcSub(left, right, scale) {
37
+ return toBcScale(new Decimal(left || 0).minus(right || 0), scale);
38
+ }
39
+ function bcMul(left, right, scale) {
40
+ return toBcScale(new Decimal(left || 0).times(right || 0), scale);
41
+ }
42
+ function bcDiv(left, right, scale) {
43
+ var divisor = new Decimal(right || 0);
44
+ if (divisor.eq(0)) return new Decimal(0);
45
+ return toBcScale(new Decimal(left || 0).div(divisor), scale);
46
+ }
18
47
  function getSafeNum(num) {
19
48
  if (!num || Number.isNaN(num)) return 1;
20
49
  if (num < 1) return 1;
@@ -49,6 +78,11 @@ function getUnitOriginalTotal(product) {
49
78
  var basePrice = mainOriginal !== undefined ? toDecimal(mainOriginal) : mainSelling !== undefined ? toDecimal(mainSelling) : toDecimal(product.original_price || product.selling_price);
50
79
  return basePrice.plus(getBundleUnitPrice(product, true));
51
80
  }
81
+ function isGeneratedVoucherProduct(product) {
82
+ var record = product;
83
+ var metadata = (record === null || record === void 0 ? void 0 : record.metadata) || {};
84
+ return (record === null || record === void 0 ? void 0 : record.extension_type) === 'product_voucher' || metadata.parent_order_detail_id !== undefined || metadata.gift_card_type !== undefined;
85
+ }
52
86
  function buildSurchargeServiceItems(products) {
53
87
  return products.map(function (product) {
54
88
  var _product$is_charge_ta, _product$metadata5, _product$metadata6;
@@ -81,6 +115,301 @@ function buildSurchargeServiceItems(products) {
81
115
  };
82
116
  });
83
117
  }
118
+ function getRelationSurchargeIds(item) {
119
+ var _item$relation_surcha, _item$metadata;
120
+ var ids = (_item$relation_surcha = item === null || item === void 0 ? void 0 : item.relation_surcharge_ids) !== null && _item$relation_surcha !== void 0 ? _item$relation_surcha : item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.relation_surcharge_ids;
121
+ if (!Array.isArray(ids)) return [];
122
+ return ids.filter(function (id) {
123
+ return id !== undefined && id !== null && id !== '';
124
+ });
125
+ }
126
+ function getSurchargeConfigId(config) {
127
+ var _config$id;
128
+ return (_config$id = config === null || config === void 0 ? void 0 : config.id) !== null && _config$id !== void 0 ? _config$id : config === null || config === void 0 ? void 0 : config.surcharge_id;
129
+ }
130
+ function getSurchargeConfigById(surchargeList) {
131
+ var map = new Map();
132
+ var _iterator = _createForOfIteratorHelper(surchargeList || []),
133
+ _step;
134
+ try {
135
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
136
+ var config = _step.value;
137
+ var id = getSurchargeConfigId(config);
138
+ if (id !== undefined) map.set(id, config);
139
+ }
140
+ } catch (err) {
141
+ _iterator.e(err);
142
+ } finally {
143
+ _iterator.f();
144
+ }
145
+ return map;
146
+ }
147
+ function getMainSurchargeUnitAmount(product) {
148
+ var _ref2, _ref3, _record$metadata$main, _record$metadata, _record$metadata2;
149
+ var record = product;
150
+ return toDecimal((_ref2 = (_ref3 = (_record$metadata$main = (_record$metadata = record.metadata) === null || _record$metadata === void 0 ? void 0 : _record$metadata.main_product_attached_bundle_selling_price) !== null && _record$metadata$main !== void 0 ? _record$metadata$main : (_record$metadata2 = record.metadata) === null || _record$metadata2 === void 0 ? void 0 : _record$metadata2.main_product_selling_price) !== null && _ref3 !== void 0 ? _ref3 : record.selling_price) !== null && _ref2 !== void 0 ? _ref2 : 0);
151
+ }
152
+ function getBundleSurchargeUnitAmount(bundle) {
153
+ var _ref4, _ref5, _bundle$bundle_sellin;
154
+ return toDecimal((_ref4 = (_ref5 = (_bundle$bundle_sellin = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_selling_price) !== null && _bundle$bundle_sellin !== void 0 ? _bundle$bundle_sellin : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_sum_price) !== null && _ref5 !== void 0 ? _ref5 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref4 !== void 0 ? _ref4 : 0);
155
+ }
156
+ function getBundleProductId(bundle) {
157
+ var _ref6, _bundle$bundle_produc;
158
+ var id = (_ref6 = (_bundle$bundle_produc = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_product_id) !== null && _bundle$bundle_produc !== void 0 ? _bundle$bundle_produc : bundle === null || bundle === void 0 ? void 0 : bundle._bundle_product_id) !== null && _ref6 !== void 0 ? _ref6 : bundle === null || bundle === void 0 ? void 0 : bundle.product_id;
159
+ if (id === undefined || id === null || id === '') return null;
160
+ var parsed = Number(id);
161
+ if (!Number.isFinite(parsed)) return null;
162
+ return parsed;
163
+ }
164
+ function createSurchargeAllocationNodes(products, sourceItems) {
165
+ var nodes = [];
166
+ for (var productIndex = 0; productIndex < products.length; productIndex++) {
167
+ var _product$product_id;
168
+ var product = products[productIndex];
169
+ var sourceItem = sourceItems[productIndex] || {};
170
+ var productQuantity = new Decimal(getSafeNum(product.num));
171
+ for (var bundleIndex = 0; bundleIndex < (product.product_bundle || []).length; bundleIndex++) {
172
+ var _sourceItem$bundle, _bundle$num;
173
+ var bundle = product.product_bundle[bundleIndex];
174
+ if (!isBundleOriginalPrice(bundle)) continue;
175
+ var sourceBundle = (sourceItem === null || sourceItem === void 0 || (_sourceItem$bundle = sourceItem.bundle) === null || _sourceItem$bundle === void 0 ? void 0 : _sourceItem$bundle[bundleIndex]) || {};
176
+ nodes.push({
177
+ kind: 'bundle',
178
+ target: bundle,
179
+ source: sourceBundle,
180
+ productId: getBundleProductId(bundle),
181
+ unitAmount: getBundleSurchargeUnitAmount(bundle),
182
+ quantity: new Decimal(getSafeNum((_bundle$num = bundle === null || bundle === void 0 ? void 0 : bundle.num) !== null && _bundle$num !== void 0 ? _bundle$num : bundle === null || bundle === void 0 ? void 0 : bundle.quantity)).times(productQuantity),
183
+ relationSurchargeIds: getRelationSurchargeIds(sourceBundle)
184
+ });
185
+ }
186
+ nodes.push({
187
+ kind: 'main',
188
+ target: product,
189
+ source: sourceItem,
190
+ productId: (_product$product_id = product.product_id) !== null && _product$product_id !== void 0 ? _product$product_id : null,
191
+ unitAmount: getMainSurchargeUnitAmount(product),
192
+ quantity: productQuantity,
193
+ relationSurchargeIds: getRelationSurchargeIds(sourceItem)
194
+ });
195
+ }
196
+ return nodes;
197
+ }
198
+ function resetProductSurchargeFields(products) {
199
+ for (var _i = 0, _arr = products; _i < _arr.length; _i++) {
200
+ var product = _arr[_i];
201
+ product.surcharge_fee = 0;
202
+ product.main_product_attached_bundle_surcharge_fee = '0.00';
203
+ product.surcharge_rounding_remainder = 0;
204
+ product.relation_surcharge_ids = [];
205
+ var _iterator2 = _createForOfIteratorHelper(product.product_bundle || []),
206
+ _step2;
207
+ try {
208
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
209
+ var bundle = _step2.value;
210
+ bundle.surcharge_fee = 0;
211
+ bundle.relation_surcharge_ids = [];
212
+ bundle.metadata = _objectSpread(_objectSpread({}, bundle.metadata || {}), {}, {
213
+ surcharge_fee: '0.00',
214
+ surcharge_rounding_remainder: '0.00',
215
+ relation_surcharge_ids: []
216
+ });
217
+ }
218
+ } catch (err) {
219
+ _iterator2.e(err);
220
+ } finally {
221
+ _iterator2.f();
222
+ }
223
+ }
224
+ }
225
+ function buildSurchargeQuantityTotals(nodes) {
226
+ var totals = new Map();
227
+ var _iterator3 = _createForOfIteratorHelper(nodes),
228
+ _step3;
229
+ try {
230
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
231
+ var node = _step3.value;
232
+ var _iterator4 = _createForOfIteratorHelper(node.relationSurchargeIds),
233
+ _step4;
234
+ try {
235
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
236
+ var surchargeId = _step4.value;
237
+ totals.set(surchargeId, (totals.get(surchargeId) || new Decimal(0)).plus(node.quantity));
238
+ }
239
+ } catch (err) {
240
+ _iterator4.e(err);
241
+ } finally {
242
+ _iterator4.f();
243
+ }
244
+ }
245
+ } catch (err) {
246
+ _iterator3.e(err);
247
+ } finally {
248
+ _iterator3.f();
249
+ }
250
+ return totals;
251
+ }
252
+ function getFallbackAllProductSurchargeIds(surchargeList) {
253
+ return (surchargeList || []).reduce(function (ids, config) {
254
+ var _config$open_product, _config$is_all;
255
+ var id = getSurchargeConfigId(config);
256
+ if (id === undefined) return ids;
257
+ if (Number((_config$open_product = config.open_product) !== null && _config$open_product !== void 0 ? _config$open_product : 0) === 0) return ids;
258
+ if (Number((_config$is_all = config.is_all) !== null && _config$is_all !== void 0 ? _config$is_all : 0) !== 1) return ids;
259
+ ids.push(id);
260
+ return ids;
261
+ }, []);
262
+ }
263
+ function getBackendSurchargeState(stateMap, surchargeId, config) {
264
+ var state = stateMap.get(surchargeId);
265
+ if (!state) {
266
+ state = {
267
+ config: config,
268
+ amount: new Decimal(0),
269
+ totalOffsetFee: new Decimal(0),
270
+ calculatedQuantity: new Decimal(0),
271
+ fixedIncluded: false,
272
+ fixedRemainderAssigned: false
273
+ };
274
+ stateMap.set(surchargeId, state);
275
+ }
276
+ return state;
277
+ }
278
+ function applySurchargeNodeResult(node, params) {
279
+ var unitSurchargeFee = params.unitSurchargeFee,
280
+ roundingRemainder = params.roundingRemainder,
281
+ surchargeIds = params.surchargeIds;
282
+ if (node.kind === 'main') {
283
+ node.target.surcharge_fee = unitSurchargeFee.toNumber();
284
+ node.target.main_product_attached_bundle_surcharge_fee = toFixed2(unitSurchargeFee);
285
+ node.target.surcharge_rounding_remainder = roundingRemainder.toNumber();
286
+ node.target.relation_surcharge_ids = surchargeIds;
287
+ return;
288
+ }
289
+ node.target.surcharge_fee = unitSurchargeFee.toNumber();
290
+ node.target.relation_surcharge_ids = surchargeIds;
291
+ node.target.metadata = _objectSpread(_objectSpread({}, node.target.metadata || {}), {}, {
292
+ surcharge_fee: toFixed2(unitSurchargeFee),
293
+ surcharge_rounding_remainder: toFixed2(roundingRemainder),
294
+ relation_surcharge_ids: surchargeIds
295
+ });
296
+ }
297
+ function calculateBackendProductSurcharges(params) {
298
+ var products = params.products,
299
+ sourceItems = params.sourceItems,
300
+ surchargeList = params.surchargeList;
301
+ resetProductSurchargeFields(products);
302
+ var configById = getSurchargeConfigById(surchargeList);
303
+ var nodes = createSurchargeAllocationNodes(products, sourceItems);
304
+ var fallbackAllProductSurchargeIds = getFallbackAllProductSurchargeIds(surchargeList);
305
+ var _iterator5 = _createForOfIteratorHelper(nodes),
306
+ _step5;
307
+ try {
308
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
309
+ var node = _step5.value;
310
+ if (node.relationSurchargeIds.length === 0) {
311
+ node.relationSurchargeIds = fallbackAllProductSurchargeIds;
312
+ }
313
+ }
314
+ } catch (err) {
315
+ _iterator5.e(err);
316
+ } finally {
317
+ _iterator5.f();
318
+ }
319
+ var quantityTotals = buildSurchargeQuantityTotals(nodes);
320
+ var stateMap = new Map();
321
+ var _iterator6 = _createForOfIteratorHelper(nodes),
322
+ _step6;
323
+ try {
324
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
325
+ var _node = _step6.value;
326
+ var unitSurchargeFee = new Decimal(0);
327
+ var roundingRemainder = new Decimal(0);
328
+ var appliedSurchargeIds = [];
329
+ var _iterator7 = _createForOfIteratorHelper(_node.relationSurchargeIds),
330
+ _step7;
331
+ try {
332
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
333
+ var surchargeId = _step7.value;
334
+ var config = configById.get(surchargeId);
335
+ var totalQuantity = quantityTotals.get(surchargeId) || new Decimal(0);
336
+ if (!config || totalQuantity.lte(0)) continue;
337
+ var percentage = new Decimal(config.percentage || 0);
338
+ var fixed = new Decimal(config.fixed || 0);
339
+ var unitPercentageFee = Decimal.max(0, bcMul(_node.unitAmount, percentage, 2));
340
+ var percentageTotalFee = bcMul(_node.quantity, unitPercentageFee, 2);
341
+ var unitFixedFee = new Decimal(0);
342
+ var fixedRemainder = new Decimal(0);
343
+ if (fixed.gt(0)) {
344
+ unitFixedFee = bcDiv(fixed, totalQuantity, 2);
345
+ var distributedFixed = bcMul(unitFixedFee, totalQuantity, 2);
346
+ fixedRemainder = bcSub(fixed, distributedFixed, 2);
347
+ }
348
+ var currentUnitSurcharge = Decimal.max(0, bcAdd(unitPercentageFee, unitFixedFee, 2));
349
+ if (currentUnitSurcharge.lte(0)) continue;
350
+ var state = getBackendSurchargeState(stateMap, surchargeId, config);
351
+ state.amount = bcAdd(state.amount, percentageTotalFee, 2);
352
+ var precisePercentage = Decimal.max(0, bcMul(_node.unitAmount, percentage, 6));
353
+ var offsetBaseFee = Decimal.max(0, bcSub(precisePercentage, unitPercentageFee, 6));
354
+ state.totalOffsetFee = bcAdd(state.totalOffsetFee, bcMul(offsetBaseFee, _node.quantity, 6), 6);
355
+ state.calculatedQuantity = bcAdd(state.calculatedQuantity, _node.quantity, 6);
356
+ if (!state.fixedIncluded && fixed.gt(0)) {
357
+ state.amount = bcAdd(state.amount, fixed, 2);
358
+ state.fixedIncluded = true;
359
+ }
360
+ if (!state.fixedRemainderAssigned && !fixedRemainder.eq(0)) {
361
+ state.fixedRemainderAssigned = true;
362
+ roundingRemainder = bcAdd(roundingRemainder, fixedRemainder, 2);
363
+ }
364
+ if (state.calculatedQuantity.gte(totalQuantity) && state.totalOffsetFee.gt(0)) {
365
+ var totalOffsetFee = toAmountFormat(state.totalOffsetFee);
366
+ state.amount = bcAdd(state.amount, totalOffsetFee, 2);
367
+ roundingRemainder = bcAdd(roundingRemainder, totalOffsetFee, 2);
368
+ state.totalOffsetFee = new Decimal(0);
369
+ }
370
+ unitSurchargeFee = bcAdd(unitSurchargeFee, currentUnitSurcharge, 2);
371
+ appliedSurchargeIds.push(surchargeId);
372
+ }
373
+ } catch (err) {
374
+ _iterator7.e(err);
375
+ } finally {
376
+ _iterator7.f();
377
+ }
378
+ applySurchargeNodeResult(_node, {
379
+ unitSurchargeFee: unitSurchargeFee,
380
+ roundingRemainder: roundingRemainder,
381
+ surchargeIds: appliedSurchargeIds
382
+ });
383
+ }
384
+ } catch (err) {
385
+ _iterator6.e(err);
386
+ } finally {
387
+ _iterator6.f();
388
+ }
389
+ return (surchargeList || []).reduce(function (result, config, index) {
390
+ var surchargeId = getSurchargeConfigId(config);
391
+ if (surchargeId === undefined) return result;
392
+ var state = stateMap.get(surchargeId);
393
+ if (!state || state.amount.lte(0)) return result;
394
+ var name = config.name || config.label || {};
395
+ result.push({
396
+ key: "custom_surcharge_".concat(index),
397
+ label: name,
398
+ name: name,
399
+ value: state.amount.toNumber(),
400
+ surcharge_id: surchargeId,
401
+ description: config.description,
402
+ type: 'default',
403
+ fixed: config.fixed,
404
+ amount: state.amount.toNumber(),
405
+ percentage: config.percentage,
406
+ metadata: {
407
+ open_product: config.open_product
408
+ }
409
+ });
410
+ return result;
411
+ }, []);
412
+ }
84
413
  function getProductDepositData(product) {
85
414
  var _product$_origin, _product$_origin2;
86
415
  var rootDepositData = (_product$_origin = product._origin) === null || _product$_origin === void 0 ? void 0 : _product$_origin.custom_deposit_data;
@@ -115,11 +444,11 @@ function calculateProductsDeposit(products) {
115
444
  var hasDeposit = false;
116
445
  var policyIds = new Set();
117
446
  var policyDataMap = new Map();
118
- var _iterator = _createForOfIteratorHelper(products),
119
- _step;
447
+ var _iterator8 = _createForOfIteratorHelper(products),
448
+ _step8;
120
449
  try {
121
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
122
- var product = _step.value;
450
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
451
+ var product = _step8.value;
123
452
  var depositData = getProductDepositData(product);
124
453
  if (!depositData || depositData.has_deposit != 1) continue;
125
454
  var num = getSafeNum(product.num);
@@ -132,45 +461,45 @@ function calculateProductsDeposit(products) {
132
461
  var itemDeposit = fixed.plus(percentage.times(productTotal));
133
462
  totalDeposit = totalDeposit.plus(itemDeposit);
134
463
  hasDeposit = true;
135
- var _iterator3 = _createForOfIteratorHelper(collectDepositPolicyIds(depositData)),
136
- _step3;
464
+ var _iterator10 = _createForOfIteratorHelper(collectDepositPolicyIds(depositData)),
465
+ _step10;
137
466
  try {
138
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
139
- var id = _step3.value;
467
+ for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
468
+ var id = _step10.value;
140
469
  policyIds.add(id);
141
470
  }
142
471
  } catch (err) {
143
- _iterator3.e(err);
472
+ _iterator10.e(err);
144
473
  } finally {
145
- _iterator3.f();
474
+ _iterator10.f();
146
475
  }
147
- var _iterator4 = _createForOfIteratorHelper(collectDepositPolicyData(depositData)),
148
- _step4;
476
+ var _iterator11 = _createForOfIteratorHelper(collectDepositPolicyData(depositData)),
477
+ _step11;
149
478
  try {
150
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
151
- var policy = _step4.value;
479
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
480
+ var policy = _step11.value;
152
481
  if (!policyDataMap.has(policy.id)) {
153
482
  policyDataMap.set(policy.id, policy);
154
483
  }
155
484
  policyIds.add(policy.id);
156
485
  }
157
486
  } catch (err) {
158
- _iterator4.e(err);
487
+ _iterator11.e(err);
159
488
  } finally {
160
- _iterator4.f();
489
+ _iterator11.f();
161
490
  }
162
491
  }
163
492
  } catch (err) {
164
- _iterator.e(err);
493
+ _iterator8.e(err);
165
494
  } finally {
166
- _iterator.f();
495
+ _iterator8.f();
167
496
  }
168
497
  if (!hasDeposit) return undefined;
169
- var _iterator2 = _createForOfIteratorHelper(policyIds),
170
- _step2;
498
+ var _iterator9 = _createForOfIteratorHelper(policyIds),
499
+ _step9;
171
500
  try {
172
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
173
- var _id = _step2.value;
501
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
502
+ var _id = _step9.value;
174
503
  if (!policyDataMap.has(_id)) {
175
504
  policyDataMap.set(_id, {
176
505
  id: _id,
@@ -179,9 +508,9 @@ function calculateProductsDeposit(products) {
179
508
  }
180
509
  }
181
510
  } catch (err) {
182
- _iterator2.e(err);
511
+ _iterator9.e(err);
183
512
  } finally {
184
- _iterator2.f();
513
+ _iterator9.f();
185
514
  }
186
515
  return {
187
516
  total: totalDeposit.toFixed(2),
@@ -230,29 +559,95 @@ function calculateSingleItemTax(params) {
230
559
  * - 仅需叠加 `markup` / `markdown` 类 bundle(原价 bundle 已由 `calculateProductsTax` 独立处理)。
231
560
  */
232
561
  function getMainProductPaymentTotal(product) {
233
- var _ref2, _product$metadata$mai, _product$metadata7, _product$metadata8;
234
- var mainSelling = (_ref2 = (_product$metadata$mai = (_product$metadata7 = product.metadata) === null || _product$metadata7 === void 0 ? void 0 : _product$metadata7.main_product_selling_price) !== null && _product$metadata$mai !== void 0 ? _product$metadata$mai : (_product$metadata8 = product.metadata) === null || _product$metadata8 === void 0 ? void 0 : _product$metadata8.main_product_original_price) !== null && _ref2 !== void 0 ? _ref2 : 0;
562
+ var _ref7, _product$metadata$mai, _product$metadata7, _product$metadata8;
563
+ var mainSelling = (_ref7 = (_product$metadata$mai = (_product$metadata7 = product.metadata) === null || _product$metadata7 === void 0 ? void 0 : _product$metadata7.main_product_selling_price) !== null && _product$metadata$mai !== void 0 ? _product$metadata$mai : (_product$metadata8 = product.metadata) === null || _product$metadata8 === void 0 ? void 0 : _product$metadata8.main_product_original_price) !== null && _ref7 !== void 0 ? _ref7 : 0;
235
564
  var total = toDecimal(mainSelling);
236
565
  var bundleItems = product.product_bundle || [];
237
- var _iterator5 = _createForOfIteratorHelper(bundleItems),
238
- _step5;
566
+ var _iterator12 = _createForOfIteratorHelper(bundleItems),
567
+ _step12;
239
568
  try {
240
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
241
- var bundleItem = _step5.value;
569
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
570
+ var bundleItem = _step12.value;
242
571
  if (isBundleMarkupOrDiscount(bundleItem)) {
243
- var _ref3, _bundleItem$bundle_se, _bundleItem$num;
244
- var unit = toDecimal((_ref3 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref3 !== void 0 ? _ref3 : 0);
572
+ var _ref8, _bundleItem$bundle_se, _bundleItem$num;
573
+ var unit = toDecimal((_ref8 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref8 !== void 0 ? _ref8 : 0);
245
574
  var qty = getSafeNum((_bundleItem$num = bundleItem.num) !== null && _bundleItem$num !== void 0 ? _bundleItem$num : bundleItem.quantity);
246
575
  total = total.plus(unit.times(qty));
247
576
  }
248
577
  }
249
578
  } catch (err) {
250
- _iterator5.e(err);
579
+ _iterator12.e(err);
251
580
  } finally {
252
- _iterator5.f();
581
+ _iterator12.f();
253
582
  }
254
583
  return Decimal.max(total, 0);
255
584
  }
585
+ function getExplicitTaxRemainder(item) {
586
+ var _item$tax_fee_roundin, _item$metadata2;
587
+ var value = (_item$tax_fee_roundin = item === null || item === void 0 ? void 0 : item.tax_fee_rounding_remainder) !== null && _item$tax_fee_roundin !== void 0 ? _item$tax_fee_roundin : item === null || item === void 0 || (_item$metadata2 = item.metadata) === null || _item$metadata2 === void 0 ? void 0 : _item$metadata2.tax_fee_rounding_remainder;
588
+ if (value === undefined || value === null || value === '') return null;
589
+ return new Decimal(value || 0);
590
+ }
591
+ function getPersistedTaxRemainder(item, parentProduct) {
592
+ var isPersistedLine = (item === null || item === void 0 ? void 0 : item.order_detail_id) !== undefined && (item === null || item === void 0 ? void 0 : item.order_detail_id) !== null || (parentProduct === null || parentProduct === void 0 ? void 0 : parentProduct.order_detail_id) !== undefined && (parentProduct === null || parentProduct === void 0 ? void 0 : parentProduct.order_detail_id) !== null;
593
+ if (!isPersistedLine) return null;
594
+ return getExplicitTaxRemainder(item);
595
+ }
596
+ function writeTaxRemainder(item, roundingRemainder) {
597
+ item.tax_fee_rounding_remainder = roundingRemainder.toNumber();
598
+ if (item.metadata && _typeof(item.metadata) === 'object') {
599
+ item.metadata.tax_fee_rounding_remainder = roundingRemainder.toFixed(2);
600
+ }
601
+ }
602
+ function resetTaxRemainderFields(products) {
603
+ for (var _i2 = 0, _arr2 = products; _i2 < _arr2.length; _i2++) {
604
+ var _productRemainder$toN;
605
+ var product = _arr2[_i2];
606
+ var productRemainder = getPersistedTaxRemainder(product);
607
+ product.tax_fee_rounding_remainder = (_productRemainder$toN = productRemainder === null || productRemainder === void 0 ? void 0 : productRemainder.toNumber()) !== null && _productRemainder$toN !== void 0 ? _productRemainder$toN : 0;
608
+ product.original_tax_fee_rounding_remainder = 0;
609
+ var _iterator13 = _createForOfIteratorHelper(product.product_bundle || []),
610
+ _step13;
611
+ try {
612
+ for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
613
+ var _bundleRemainder$toFi, _bundleRemainder$toNu;
614
+ var bundle = _step13.value;
615
+ var bundleRemainder = getPersistedTaxRemainder(bundle, product);
616
+ bundle.metadata = _objectSpread(_objectSpread({}, bundle.metadata || {}), {}, {
617
+ tax_fee_rounding_remainder: (_bundleRemainder$toFi = bundleRemainder === null || bundleRemainder === void 0 ? void 0 : bundleRemainder.toFixed(2)) !== null && _bundleRemainder$toFi !== void 0 ? _bundleRemainder$toFi : '0.00'
618
+ });
619
+ bundle.tax_fee_rounding_remainder = (_bundleRemainder$toNu = bundleRemainder === null || bundleRemainder === void 0 ? void 0 : bundleRemainder.toNumber()) !== null && _bundleRemainder$toNu !== void 0 ? _bundleRemainder$toNu : 0;
620
+ bundle.original_tax_fee_rounding_remainder = 0;
621
+ }
622
+ } catch (err) {
623
+ _iterator13.e(err);
624
+ } finally {
625
+ _iterator13.f();
626
+ }
627
+ }
628
+ }
629
+ function getBundlePaymentPrice(bundle, product) {
630
+ var _ref9, _ref10, _bundle$bundle_sellin2, _metadata$average_dis, _metadata;
631
+ if ((bundle === null || bundle === void 0 ? void 0 : bundle.bundle_payment_price) !== undefined) return toDecimal(bundle.bundle_payment_price);
632
+ var basePrice = toDecimal((_ref9 = (_ref10 = (_bundle$bundle_sellin2 = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_selling_price) !== null && _bundle$bundle_sellin2 !== void 0 ? _bundle$bundle_sellin2 : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_sum_price) !== null && _ref10 !== void 0 ? _ref10 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref9 !== void 0 ? _ref9 : 0);
633
+ if (!isBundleOriginalPrice(bundle)) return basePrice;
634
+ var averageDiscountRate = toDecimal((_metadata$average_dis = (_metadata = product.metadata) === null || _metadata === void 0 ? void 0 : _metadata.average_discount_amount_rate) !== null && _metadata$average_dis !== void 0 ? _metadata$average_dis : 1);
635
+ return toAmountFormat(bcMul(basePrice, averageDiscountRate, 6));
636
+ }
637
+ function applyBackendTaxRemainder(params) {
638
+ var target = params.target,
639
+ rawTax = params.rawTax,
640
+ formattedTax = params.formattedTax,
641
+ quantity = params.quantity,
642
+ state = params.state;
643
+ var taxFeeDifference = bcMul(bcSub(rawTax, formattedTax, 6), quantity, 6);
644
+ state.difference = bcAdd(state.difference, taxFeeDifference, 6);
645
+ if (state.difference.lt(0.005)) return new Decimal(0);
646
+ var roundingRemainder = toAmountFormat(state.difference);
647
+ writeTaxRemainder(target, roundingRemainder);
648
+ state.difference = bcSub(state.difference, roundingRemainder, 6);
649
+ return roundingRemainder;
650
+ }
256
651
 
257
652
  /**
258
653
  * 遍历所有商品计算税费,回写 tax_fee 到每个商品及 bundle 原价子商品,处理舍入差值。
@@ -260,132 +655,113 @@ function getMainProductPaymentTotal(product) {
260
655
  */
261
656
  function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
262
657
  var rate = new Decimal(taxRate);
263
- var preciseTax = new Decimal(0);
264
- var roundedTax = new Decimal(0);
265
- var preciseOriginTax = new Decimal(0);
266
- var roundedOriginTax = new Decimal(0);
267
- var lastTaxableItem = null;
268
- var _iterator6 = _createForOfIteratorHelper(products),
269
- _step6;
658
+ var taxRemainderState = {
659
+ difference: new Decimal(0)
660
+ };
661
+ var totalTax = new Decimal(0);
662
+ var totalOriginTax = new Decimal(0);
663
+ resetTaxRemainderFields(products);
664
+ var _iterator14 = _createForOfIteratorHelper(products),
665
+ _step14;
270
666
  try {
271
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
667
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
272
668
  var _product$is_charge_ta2, _product$is_charge_ta3;
273
- var product = _step6.value;
669
+ var product = _step14.value;
274
670
  var quantity = new Decimal(getSafeNum(product.num));
275
-
276
- // --- 主商品折后税费 ---
277
- var mainTotal = getMainProductPaymentTotal(product);
278
- var surchargeFee = toDecimal(product.surcharge_fee);
279
- var mainTaxableBase = mainTotal.lte(0) ? surchargeFee : mainTotal.plus(surchargeFee);
280
- var mainTaxPrecise = calculateSingleItemTax({
281
- price: mainTaxableBase,
282
- taxRate: rate,
283
- isPriceIncludeTax: isPriceIncludeTax,
284
- isChargeTax: (_product$is_charge_ta2 = product.is_charge_tax) !== null && _product$is_charge_ta2 !== void 0 ? _product$is_charge_ta2 : 0
285
- });
286
- var mainTaxRounded = mainTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
287
- product.main_product_attached_bundle_tax_fee = mainTaxRounded.toFixed(2);
288
- if (mainTaxPrecise.gt(0)) {
289
- lastTaxableItem = {
290
- type: 'main',
291
- item: product
292
- };
293
- }
294
-
295
- // --- 主商品原价税费 ---
296
- var originalTotal = getUnitOriginalTotal(product);
297
- var originalTaxableBase = originalTotal.lte(0) ? surchargeFee : originalTotal.plus(surchargeFee);
298
- var originalTaxPrecise = calculateSingleItemTax({
299
- price: originalTaxableBase,
300
- taxRate: rate,
301
- isPriceIncludeTax: isPriceIncludeTax,
302
- isChargeTax: (_product$is_charge_ta3 = product.is_charge_tax) !== null && _product$is_charge_ta3 !== void 0 ? _product$is_charge_ta3 : 0
303
- });
304
-
305
- // --- bundle 原价子商品独立计税 ---
306
- var bundlePreciseTax = new Decimal(0);
307
- var bundleRoundedTax = new Decimal(0);
308
- var bundlePreciseOriginTax = new Decimal(0);
309
- var bundleRoundedOriginTax = new Decimal(0);
671
+ var productUnitTax = new Decimal(0);
672
+ var productUnitOriginTax = new Decimal(0);
310
673
  var bundleItems = product.product_bundle || [];
311
- var _iterator7 = _createForOfIteratorHelper(bundleItems),
312
- _step7;
674
+ var _iterator15 = _createForOfIteratorHelper(bundleItems),
675
+ _step15;
313
676
  try {
314
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
315
- var _bundleItem$num2, _ref4, _bundleItem$bundle_se2, _ref5, _ref6, _bundleItem$original_, _ref7, _bundleItem$is_charge, _ref8, _bundleItem$is_charge2;
316
- var bundleItem = _step7.value;
677
+ for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
678
+ var _bundleItem$num2, _ref11, _ref12, _bundleItem$original_, _ref13, _bundleItem$is_charge, _ref14, _bundleItem$is_charge2;
679
+ var bundleItem = _step15.value;
317
680
  if (!isBundleOriginalPrice(bundleItem)) continue;
318
681
  var bundleQuantity = new Decimal(getSafeNum((_bundleItem$num2 = bundleItem.num) !== null && _bundleItem$num2 !== void 0 ? _bundleItem$num2 : bundleItem.quantity));
319
- var bundlePrice = toDecimal((_ref4 = (_bundleItem$bundle_se2 = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se2 !== void 0 ? _bundleItem$bundle_se2 : bundleItem.price) !== null && _ref4 !== void 0 ? _ref4 : 0);
320
- var bundleOriginalPrice = toDecimal((_ref5 = (_ref6 = (_bundleItem$original_ = bundleItem.original_price) !== null && _bundleItem$original_ !== void 0 ? _bundleItem$original_ : bundleItem.product_price) !== null && _ref6 !== void 0 ? _ref6 : bundleItem.price) !== null && _ref5 !== void 0 ? _ref5 : 0);
682
+ var totalBundleQuantity = bundleQuantity.times(quantity);
683
+ var bundlePrice = getBundlePaymentPrice(bundleItem, product);
684
+ var bundleOriginalPrice = toDecimal((_ref11 = (_ref12 = (_bundleItem$original_ = bundleItem.original_price) !== null && _bundleItem$original_ !== void 0 ? _bundleItem$original_ : bundleItem.product_price) !== null && _ref12 !== void 0 ? _ref12 : bundleItem.price) !== null && _ref11 !== void 0 ? _ref11 : 0);
321
685
  var bundleSurchargeFee = toDecimal(bundleItem.surcharge_fee);
322
686
  var bundleTaxPrecise = calculateSingleItemTax({
323
687
  price: bundlePrice.plus(bundleSurchargeFee),
324
688
  taxRate: rate,
325
689
  isPriceIncludeTax: isPriceIncludeTax,
326
- isChargeTax: (_ref7 = (_bundleItem$is_charge = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge !== void 0 ? _bundleItem$is_charge : product.is_charge_tax) !== null && _ref7 !== void 0 ? _ref7 : 0
690
+ isChargeTax: (_ref13 = (_bundleItem$is_charge = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge !== void 0 ? _bundleItem$is_charge : product.is_charge_tax) !== null && _ref13 !== void 0 ? _ref13 : 0
691
+ });
692
+ var bundleTaxRounded = toBackendTaxFee(bundleTaxPrecise);
693
+ bundleItem.tax_fee = bundleTaxRounded.toNumber();
694
+ var persistedBundleRemainder = getPersistedTaxRemainder(bundleItem, product);
695
+ var bundleRemainder = persistedBundleRemainder !== null && persistedBundleRemainder !== void 0 ? persistedBundleRemainder : applyBackendTaxRemainder({
696
+ target: bundleItem,
697
+ rawTax: bundleTaxPrecise,
698
+ formattedTax: bundleTaxRounded,
699
+ quantity: totalBundleQuantity,
700
+ state: taxRemainderState
327
701
  });
328
- var bundleTaxRounded = bundleTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
702
+ if (persistedBundleRemainder) writeTaxRemainder(bundleItem, persistedBundleRemainder);
329
703
  var bundleOrigTaxPrecise = calculateSingleItemTax({
330
704
  price: bundleOriginalPrice.plus(bundleSurchargeFee),
331
705
  taxRate: rate,
332
706
  isPriceIncludeTax: isPriceIncludeTax,
333
- isChargeTax: (_ref8 = (_bundleItem$is_charge2 = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge2 !== void 0 ? _bundleItem$is_charge2 : product.is_charge_tax) !== null && _ref8 !== void 0 ? _ref8 : 0
707
+ isChargeTax: (_ref14 = (_bundleItem$is_charge2 = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge2 !== void 0 ? _bundleItem$is_charge2 : product.is_charge_tax) !== null && _ref14 !== void 0 ? _ref14 : 0
334
708
  });
335
- var bundleOrigTaxRounded = bundleOrigTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
336
- bundleItem.tax_fee = bundleTaxRounded.toNumber();
709
+ var bundleOrigTaxRounded = toAmountFormat(bundleOrigTaxPrecise);
337
710
  bundleItem.original_tax_fee = bundleOrigTaxRounded.toNumber();
338
- bundlePreciseTax = bundlePreciseTax.plus(bundleTaxPrecise.times(bundleQuantity));
339
- bundleRoundedTax = bundleRoundedTax.plus(bundleTaxRounded.times(bundleQuantity));
340
- bundlePreciseOriginTax = bundlePreciseOriginTax.plus(bundleOrigTaxPrecise.times(bundleQuantity));
341
- bundleRoundedOriginTax = bundleRoundedOriginTax.plus(bundleOrigTaxRounded.times(bundleQuantity));
342
- if (bundleTaxPrecise.gt(0)) {
343
- lastTaxableItem = {
344
- type: 'bundle',
345
- item: bundleItem
346
- };
347
- }
711
+ productUnitTax = productUnitTax.plus(bundleTaxRounded.times(bundleQuantity));
712
+ productUnitOriginTax = productUnitOriginTax.plus(bundleOrigTaxRounded.times(bundleQuantity));
713
+ totalTax = totalTax.plus(bundleTaxRounded.times(totalBundleQuantity)).plus(bundleRemainder);
714
+ totalOriginTax = totalOriginTax.plus(bundleOrigTaxRounded.times(totalBundleQuantity));
348
715
  }
349
-
350
- // --- 汇总到商品级 ---
351
716
  } catch (err) {
352
- _iterator7.e(err);
717
+ _iterator15.e(err);
353
718
  } finally {
354
- _iterator7.f();
719
+ _iterator15.f();
355
720
  }
356
- var itemTaxPrecise = mainTaxPrecise.plus(bundlePreciseTax);
357
- var itemTaxRounded = mainTaxRounded.plus(bundleRoundedTax);
358
- var itemOriginTaxPrecise = originalTaxPrecise.plus(bundlePreciseOriginTax);
359
- var itemOriginTaxRounded = originalTaxPrecise.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).plus(bundleRoundedOriginTax);
360
- product.tax_fee = itemTaxRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
361
- product.original_tax_fee = itemOriginTaxRounded.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
362
- preciseTax = preciseTax.plus(itemTaxPrecise.times(quantity));
363
- roundedTax = roundedTax.plus(itemTaxRounded.times(quantity));
364
- preciseOriginTax = preciseOriginTax.plus(itemOriginTaxPrecise.times(quantity));
365
- roundedOriginTax = roundedOriginTax.plus(itemOriginTaxRounded.times(quantity));
721
+ var mainTotal = getMainProductPaymentTotal(product);
722
+ var surchargeFee = toDecimal(product.surcharge_fee);
723
+ var mainTaxableBase = mainTotal.lte(0) ? surchargeFee : mainTotal.plus(surchargeFee);
724
+ var mainTaxPrecise = calculateSingleItemTax({
725
+ price: mainTaxableBase,
726
+ taxRate: rate,
727
+ isPriceIncludeTax: isPriceIncludeTax,
728
+ isChargeTax: (_product$is_charge_ta2 = product.is_charge_tax) !== null && _product$is_charge_ta2 !== void 0 ? _product$is_charge_ta2 : 0
729
+ });
730
+ var mainTaxRounded = toBackendTaxFee(mainTaxPrecise);
731
+ product.main_product_attached_bundle_tax_fee = mainTaxRounded.toFixed(2);
732
+ var persistedMainRemainder = getPersistedTaxRemainder(product);
733
+ var mainRemainder = persistedMainRemainder !== null && persistedMainRemainder !== void 0 ? persistedMainRemainder : applyBackendTaxRemainder({
734
+ target: product,
735
+ rawTax: mainTaxPrecise,
736
+ formattedTax: mainTaxRounded,
737
+ quantity: quantity,
738
+ state: taxRemainderState
739
+ });
740
+ if (persistedMainRemainder) writeTaxRemainder(product, persistedMainRemainder);
741
+ var originalTotal = getUnitOriginalTotal(product);
742
+ var originalTaxableBase = originalTotal.lte(0) ? surchargeFee : originalTotal.plus(surchargeFee);
743
+ var originalTaxPrecise = calculateSingleItemTax({
744
+ price: originalTaxableBase,
745
+ taxRate: rate,
746
+ isPriceIncludeTax: isPriceIncludeTax,
747
+ isChargeTax: (_product$is_charge_ta3 = product.is_charge_tax) !== null && _product$is_charge_ta3 !== void 0 ? _product$is_charge_ta3 : 0
748
+ });
749
+ var originalTaxRounded = toAmountFormat(originalTaxPrecise);
750
+ productUnitTax = productUnitTax.plus(mainTaxRounded);
751
+ productUnitOriginTax = productUnitOriginTax.plus(originalTaxRounded);
752
+ product.tax_fee = productUnitTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
753
+ product.original_tax_fee = productUnitOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
754
+ totalTax = totalTax.plus(mainTaxRounded.times(quantity)).plus(mainRemainder);
755
+ totalOriginTax = totalOriginTax.plus(originalTaxRounded.times(quantity));
366
756
  }
367
-
368
- // --- 舍入差值处理 ---
369
757
  } catch (err) {
370
- _iterator6.e(err);
758
+ _iterator14.e(err);
371
759
  } finally {
372
- _iterator6.f();
373
- }
374
- var expectedTax = preciseTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
375
- var expectedOriginTax = preciseOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
376
- var taxRemainder = expectedTax.minus(roundedTax).toNumber();
377
- var originTaxRemainder = expectedOriginTax.minus(roundedOriginTax).toNumber();
378
- if (lastTaxableItem) {
379
- if (taxRemainder !== 0) {
380
- lastTaxableItem.item.tax_fee_rounding_remainder = taxRemainder;
381
- }
382
- if (originTaxRemainder !== 0) {
383
- lastTaxableItem.item.original_tax_fee_rounding_remainder = originTaxRemainder;
384
- }
760
+ _iterator14.f();
385
761
  }
386
762
  return {
387
- tax: expectedTax,
388
- originTax: expectedOriginTax
763
+ tax: totalTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP),
764
+ originTax: totalOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP)
389
765
  };
390
766
  }
391
767
  export function createEmptySalesSummary() {
@@ -422,17 +798,21 @@ export function calculateSalesSummary(params) {
422
798
  isInScheduleByDate = params.isInScheduleByDate,
423
799
  shopDiscount = params.shopDiscount;
424
800
  if (!(products !== null && products !== void 0 && products.length)) return createEmptySalesSummary();
425
- var productQuantity = products.reduce(function (sum, item) {
801
+ var summaryProducts = products.filter(function (product) {
802
+ return !isGeneratedVoucherProduct(product);
803
+ });
804
+ if (!summaryProducts.length) return createEmptySalesSummary();
805
+ var productQuantity = summaryProducts.reduce(function (sum, item) {
426
806
  return sum + getSafeNum(item.num);
427
807
  }, 0);
428
- var productOriginalAmount = products.reduce(function (sum, item) {
808
+ var productOriginalAmount = summaryProducts.reduce(function (sum, item) {
429
809
  return sum.plus(getUnitOriginalTotal(item).times(getSafeNum(item.num)));
430
810
  }, new Decimal(0));
431
- var productAmount = products.reduce(function (sum, item) {
811
+ var productAmount = summaryProducts.reduce(function (sum, item) {
432
812
  return sum.plus(getUnitPaymentTotal(item).times(getSafeNum(item.num)));
433
813
  }, new Decimal(0));
434
- var surchargeServiceItems = buildSurchargeServiceItems(products);
435
- var surcharge = getSurcharge({
814
+ var surchargeServiceItems = buildSurchargeServiceItems(summaryProducts);
815
+ getSurcharge({
436
816
  service: surchargeServiceItems,
437
817
  addons: [],
438
818
  bookingDetail: null,
@@ -443,42 +823,31 @@ export function calculateSalesSummary(params) {
443
823
  surcharge_list: surchargeList,
444
824
  scheduleById: scheduleById
445
825
  });
826
+ var surcharge = calculateBackendProductSurcharges({
827
+ products: summaryProducts,
828
+ sourceItems: surchargeServiceItems,
829
+ surchargeList: surchargeList
830
+ });
446
831
  var surchargeAmount = new Decimal(getSurchargeAmount({
447
832
  bookingDetail: null,
448
833
  bookingId: undefined
449
834
  }, surcharge, {
450
835
  isEdit: false
451
836
  }) || 0);
452
- for (var i = 0; i < products.length; i++) {
453
- var sourceItem = surchargeServiceItems[i] || {};
454
- var product = products[i];
455
- product.surcharge_fee = sourceItem.surcharge_fee || 0;
456
- var relationSurchargeIds = Array.isArray(sourceItem.relation_surcharge_ids) ? sourceItem.relation_surcharge_ids : [];
457
- var hasSurcharge = new Decimal(product.surcharge_fee || 0).gt(0) || relationSurchargeIds.length > 0;
458
- if (hasSurcharge) {
459
- product.main_product_attached_bundle_surcharge_fee = toFixed2(product.surcharge_fee);
460
- }
461
- if (relationSurchargeIds.length > 0) {
462
- product.relation_surcharge_ids = sourceItem.relation_surcharge_ids;
463
- }
464
- if (hasSurcharge && sourceItem.surcharge_rounding_remainder !== undefined) {
465
- product.surcharge_rounding_remainder = sourceItem.surcharge_rounding_remainder;
466
- }
467
- }
468
837
  var hasTaxRate = taxRate !== undefined && taxRate !== null && taxRate > 0;
469
838
  var productTaxFee;
470
839
  if (hasTaxRate) {
471
- var taxResult = calculateProductsTax(products, taxRate, isPriceIncludeTax);
840
+ var taxResult = calculateProductsTax(summaryProducts, taxRate, isPriceIncludeTax);
472
841
  productTaxFee = taxResult.tax;
473
842
  } else {
474
- productTaxFee = products.reduce(function (sum, item) {
843
+ productTaxFee = summaryProducts.reduce(function (sum, item) {
475
844
  return sum.plus(toDecimal(item.tax_fee).times(getSafeNum(item.num)));
476
845
  }, new Decimal(0));
477
846
  }
478
847
  var shopDiscountAmount = Decimal.max(new Decimal(Number(shopDiscount) || 0), 0);
479
848
  var preTaxExpectAmount = Decimal.max(0, productAmount.plus(surchargeAmount).minus(shopDiscountAmount));
480
849
  var totalAmount = isPriceIncludeTax === 1 ? preTaxExpectAmount : preTaxExpectAmount.plus(productTaxFee);
481
- var deposit = calculateProductsDeposit(products);
850
+ var deposit = calculateProductsDeposit(summaryProducts);
482
851
  return {
483
852
  product_quantity: productQuantity,
484
853
  product_original_amount: toFixed2(productOriginalAmount),