@pisell/pisellos 2.2.196 → 2.2.198

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,16 +1,20 @@
1
+ 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); }
2
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
3
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
5
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
6
+ 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; } } }; }
1
7
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
2
8
  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."); }
9
+ 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); }
3
10
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
4
11
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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); }
12
+ 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; }
6
13
  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
14
  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
15
  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
16
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
10
17
  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; }
14
18
  import Decimal from 'decimal.js';
15
19
  import { getSurcharge, getSurchargeAmount } from "../Summary/utils";
16
20
  import { getProductSkuOptions } from "../Order/utils";
@@ -89,6 +93,7 @@ function buildSurchargeServiceItems(products) {
89
93
  var quantity = getSafeNum(product.num);
90
94
  var unitTotal = getUnitPaymentTotal(product);
91
95
  var options = getProductSkuOptions(product);
96
+ var persistedSurchargeFee = getPersistedMainSurchargeFee(product);
92
97
  return {
93
98
  id: product.product_id,
94
99
  num: quantity,
@@ -109,19 +114,20 @@ function buildSurchargeServiceItems(products) {
109
114
  option: options,
110
115
  options: options,
111
116
  relation_details: [],
112
- metadata: product.metadata || {},
117
+ metadata: _objectSpread(_objectSpread({}, product.metadata || {}), {}, {
118
+ __persisted_surcharge_fee: persistedSurchargeFee === null || persistedSurchargeFee === void 0 ? void 0 : persistedSurchargeFee.toFixed(2)
119
+ }),
113
120
  start_date: ((_product$metadata5 = product.metadata) === null || _product$metadata5 === void 0 ? void 0 : _product$metadata5.start_date) || '',
114
121
  start_time: ((_product$metadata6 = product.metadata) === null || _product$metadata6 === void 0 ? void 0 : _product$metadata6.start_time) || ''
115
122
  };
116
123
  });
117
124
  }
118
125
  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) {
126
+ var _item$metadata;
127
+ var ids = [].concat(_toConsumableArray(Array.isArray(item === null || item === void 0 ? void 0 : item.relation_surcharge_ids) ? item.relation_surcharge_ids : []), _toConsumableArray(Array.isArray(item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.relation_surcharge_ids) ? item.metadata.relation_surcharge_ids : []));
128
+ return _toConsumableArray(new Set(ids.filter(function (id) {
123
129
  return id !== undefined && id !== null && id !== '';
124
- });
130
+ })));
125
131
  }
126
132
  function getSurchargeConfigId(config) {
127
133
  var _config$id;
@@ -161,15 +167,51 @@ function getBundleProductId(bundle) {
161
167
  if (!Number.isFinite(parsed)) return null;
162
168
  return parsed;
163
169
  }
170
+ function getPersistedMainSurchargeFee(product) {
171
+ var _ref7, _product$surcharge_fe, _product$metadata7;
172
+ if ((product === null || product === void 0 ? void 0 : product.order_detail_id) === undefined || (product === null || product === void 0 ? void 0 : product.order_detail_id) === null) return null;
173
+ var value = (_ref7 = (_product$surcharge_fe = product === null || product === void 0 ? void 0 : product.surcharge_fee) !== null && _product$surcharge_fe !== void 0 ? _product$surcharge_fe : product === null || product === void 0 ? void 0 : product.main_product_attached_bundle_surcharge_fee) !== null && _ref7 !== void 0 ? _ref7 : product === null || product === void 0 || (_product$metadata7 = product.metadata) === null || _product$metadata7 === void 0 ? void 0 : _product$metadata7.main_product_attached_bundle_surcharge_fee;
174
+ if (value === undefined || value === null || value === '') return null;
175
+ return toDecimal(value);
176
+ }
177
+ function getPersistedSourceSurchargeFee(sourceItem) {
178
+ var _sourceItem$metadata;
179
+ var value = sourceItem === null || sourceItem === void 0 || (_sourceItem$metadata = sourceItem.metadata) === null || _sourceItem$metadata === void 0 ? void 0 : _sourceItem$metadata.__persisted_surcharge_fee;
180
+ if (value === undefined || value === null || value === '') return null;
181
+ return toDecimal(value);
182
+ }
183
+ function getPersistedSurchargeRemainder(item, sourceItem) {
184
+ var _ref8, _sourceItem$metadata$, _sourceItem$metadata2, _item$metadata2;
185
+ var value = (_ref8 = (_sourceItem$metadata$ = sourceItem === null || sourceItem === void 0 || (_sourceItem$metadata2 = sourceItem.metadata) === null || _sourceItem$metadata2 === void 0 ? void 0 : _sourceItem$metadata2.surcharge_rounding_remainder) !== null && _sourceItem$metadata$ !== void 0 ? _sourceItem$metadata$ : item === null || item === void 0 ? void 0 : item.surcharge_rounding_remainder) !== null && _ref8 !== void 0 ? _ref8 : item === null || item === void 0 || (_item$metadata2 = item.metadata) === null || _item$metadata2 === void 0 ? void 0 : _item$metadata2.surcharge_rounding_remainder;
186
+ if (value === undefined || value === null || value === '') return null;
187
+ return toDecimal(value);
188
+ }
189
+ function getPersistedQuantity(item, fallbackQuantity) {
190
+ var _item$product_quantit;
191
+ 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;
192
+ if (!isPersistedLine) return new Decimal(0);
193
+ var value = (_item$product_quantit = item === null || item === void 0 ? void 0 : item.product_quantity) !== null && _item$product_quantit !== void 0 ? _item$product_quantit : item === null || item === void 0 ? void 0 : item.quantity;
194
+ var parsed = new Decimal(value || 0);
195
+ if (parsed.lte(0)) return Decimal.min(fallbackQuantity, 1);
196
+ return Decimal.min(fallbackQuantity, parsed);
197
+ }
198
+ function getPersistedBundleSurchargeFee(bundle, product) {
199
+ var _bundle$surcharge_fee, _bundle$metadata;
200
+ if ((bundle === null || bundle === void 0 ? void 0 : bundle.order_detail_id) === undefined && (product === null || product === void 0 ? void 0 : product.order_detail_id) === undefined) return null;
201
+ if ((bundle === null || bundle === void 0 ? void 0 : bundle.order_detail_id) === null && (product === null || product === void 0 ? void 0 : product.order_detail_id) === null) return null;
202
+ var value = (_bundle$surcharge_fee = bundle === null || bundle === void 0 ? void 0 : bundle.surcharge_fee) !== null && _bundle$surcharge_fee !== void 0 ? _bundle$surcharge_fee : bundle === null || bundle === void 0 || (_bundle$metadata = bundle.metadata) === null || _bundle$metadata === void 0 ? void 0 : _bundle$metadata.surcharge_fee;
203
+ if (value === undefined || value === null || value === '') return null;
204
+ return toDecimal(value);
205
+ }
164
206
  function createSurchargeAllocationNodes(products, sourceItems) {
165
207
  var nodes = [];
166
208
  for (var productIndex = 0; productIndex < products.length; productIndex++) {
167
- var _product$product_id;
209
+ var _product$product_id, _getPersistedSourceSu;
168
210
  var product = products[productIndex];
169
211
  var sourceItem = sourceItems[productIndex] || {};
170
212
  var productQuantity = new Decimal(getSafeNum(product.num));
171
213
  for (var bundleIndex = 0; bundleIndex < (product.product_bundle || []).length; bundleIndex++) {
172
- var _sourceItem$bundle, _bundle$num;
214
+ var _sourceItem$bundle, _bundle$num, _bundle$num2;
173
215
  var bundle = product.product_bundle[bundleIndex];
174
216
  if (!isBundleOriginalPrice(bundle)) continue;
175
217
  var sourceBundle = (sourceItem === null || sourceItem === void 0 || (_sourceItem$bundle = sourceItem.bundle) === null || _sourceItem$bundle === void 0 ? void 0 : _sourceItem$bundle[bundleIndex]) || {};
@@ -180,7 +222,10 @@ function createSurchargeAllocationNodes(products, sourceItems) {
180
222
  productId: getBundleProductId(bundle),
181
223
  unitAmount: getBundleSurchargeUnitAmount(bundle),
182
224
  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)
225
+ persistedQuantity: getPersistedQuantity(bundle, new Decimal(getSafeNum((_bundle$num2 = bundle === null || bundle === void 0 ? void 0 : bundle.num) !== null && _bundle$num2 !== void 0 ? _bundle$num2 : bundle === null || bundle === void 0 ? void 0 : bundle.quantity)).times(productQuantity)),
226
+ relationSurchargeIds: getRelationSurchargeIds(sourceBundle).length ? getRelationSurchargeIds(sourceBundle) : getRelationSurchargeIds(bundle),
227
+ persistedUnitSurchargeFee: getPersistedBundleSurchargeFee(bundle, product),
228
+ persistedSurchargeRemainder: getPersistedSurchargeRemainder(bundle, sourceBundle)
184
229
  });
185
230
  }
186
231
  nodes.push({
@@ -190,7 +235,10 @@ function createSurchargeAllocationNodes(products, sourceItems) {
190
235
  productId: (_product$product_id = product.product_id) !== null && _product$product_id !== void 0 ? _product$product_id : null,
191
236
  unitAmount: getMainSurchargeUnitAmount(product),
192
237
  quantity: productQuantity,
193
- relationSurchargeIds: getRelationSurchargeIds(sourceItem)
238
+ persistedQuantity: getPersistedQuantity(product, productQuantity),
239
+ relationSurchargeIds: getRelationSurchargeIds(sourceItem).length ? getRelationSurchargeIds(sourceItem) : getRelationSurchargeIds(product),
240
+ persistedUnitSurchargeFee: (_getPersistedSourceSu = getPersistedSourceSurchargeFee(sourceItem)) !== null && _getPersistedSourceSu !== void 0 ? _getPersistedSourceSu : getPersistedMainSurchargeFee(product),
241
+ persistedSurchargeRemainder: getPersistedSurchargeRemainder(product, sourceItem)
194
242
  });
195
243
  }
196
244
  return nodes;
@@ -222,19 +270,20 @@ function resetProductSurchargeFields(products) {
222
270
  }
223
271
  }
224
272
  }
225
- function buildSurchargeQuantityTotals(nodes) {
226
- var totals = new Map();
273
+ function getPersistedSurchargeIds(nodes) {
274
+ var ids = new Set();
227
275
  var _iterator3 = _createForOfIteratorHelper(nodes),
228
276
  _step3;
229
277
  try {
230
278
  for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
231
279
  var node = _step3.value;
280
+ if (!node.persistedUnitSurchargeFee || node.persistedUnitSurchargeFee.lte(0)) continue;
232
281
  var _iterator4 = _createForOfIteratorHelper(node.relationSurchargeIds),
233
282
  _step4;
234
283
  try {
235
284
  for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
236
285
  var surchargeId = _step4.value;
237
- totals.set(surchargeId, (totals.get(surchargeId) || new Decimal(0)).plus(node.quantity));
286
+ ids.add(surchargeId);
238
287
  }
239
288
  } catch (err) {
240
289
  _iterator4.e(err);
@@ -247,6 +296,33 @@ function buildSurchargeQuantityTotals(nodes) {
247
296
  } finally {
248
297
  _iterator3.f();
249
298
  }
299
+ return ids;
300
+ }
301
+ function buildSurchargeQuantityTotals(nodes) {
302
+ var totals = new Map();
303
+ var _iterator5 = _createForOfIteratorHelper(nodes),
304
+ _step5;
305
+ try {
306
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
307
+ var node = _step5.value;
308
+ var _iterator6 = _createForOfIteratorHelper(node.relationSurchargeIds),
309
+ _step6;
310
+ try {
311
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
312
+ var surchargeId = _step6.value;
313
+ totals.set(surchargeId, (totals.get(surchargeId) || new Decimal(0)).plus(node.quantity));
314
+ }
315
+ } catch (err) {
316
+ _iterator6.e(err);
317
+ } finally {
318
+ _iterator6.f();
319
+ }
320
+ }
321
+ } catch (err) {
322
+ _iterator5.e(err);
323
+ } finally {
324
+ _iterator5.f();
325
+ }
250
326
  return totals;
251
327
  }
252
328
  function getFallbackAllProductSurchargeIds(surchargeList) {
@@ -275,6 +351,24 @@ function getBackendSurchargeState(stateMap, surchargeId, config) {
275
351
  }
276
352
  return state;
277
353
  }
354
+ function buildSurchargeResultItem(config, surchargeId, amount, index) {
355
+ var name = (config === null || config === void 0 ? void 0 : config.name) || (config === null || config === void 0 ? void 0 : config.label) || {};
356
+ return {
357
+ key: "custom_surcharge_".concat(index),
358
+ label: name,
359
+ name: name,
360
+ value: amount.toNumber(),
361
+ surcharge_id: surchargeId,
362
+ description: config === null || config === void 0 ? void 0 : config.description,
363
+ type: 'default',
364
+ fixed: config === null || config === void 0 ? void 0 : config.fixed,
365
+ amount: amount.toNumber(),
366
+ percentage: config === null || config === void 0 ? void 0 : config.percentage,
367
+ metadata: {
368
+ open_product: config === null || config === void 0 ? void 0 : config.open_product
369
+ }
370
+ };
371
+ }
278
372
  function applySurchargeNodeResult(node, params) {
279
373
  var unitSurchargeFee = params.unitSurchargeFee,
280
374
  roundingRemainder = params.roundingRemainder,
@@ -302,45 +396,77 @@ function calculateBackendProductSurcharges(params) {
302
396
  var configById = getSurchargeConfigById(surchargeList);
303
397
  var nodes = createSurchargeAllocationNodes(products, sourceItems);
304
398
  var fallbackAllProductSurchargeIds = getFallbackAllProductSurchargeIds(surchargeList);
305
- var _iterator5 = _createForOfIteratorHelper(nodes),
306
- _step5;
399
+ var _iterator7 = _createForOfIteratorHelper(nodes),
400
+ _step7;
307
401
  try {
308
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
309
- var node = _step5.value;
402
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
403
+ var node = _step7.value;
310
404
  if (node.relationSurchargeIds.length === 0) {
311
405
  node.relationSurchargeIds = fallbackAllProductSurchargeIds;
312
406
  }
313
407
  }
314
408
  } catch (err) {
315
- _iterator5.e(err);
409
+ _iterator7.e(err);
316
410
  } finally {
317
- _iterator5.f();
411
+ _iterator7.f();
318
412
  }
413
+ var persistedSurchargeIds = getPersistedSurchargeIds(nodes);
319
414
  var quantityTotals = buildSurchargeQuantityTotals(nodes);
320
415
  var stateMap = new Map();
321
- var _iterator6 = _createForOfIteratorHelper(nodes),
322
- _step6;
416
+ var _iterator8 = _createForOfIteratorHelper(nodes),
417
+ _step8;
323
418
  try {
324
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
325
- var _node = _step6.value;
419
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
420
+ var _node = _step8.value;
326
421
  var unitSurchargeFee = new Decimal(0);
327
422
  var roundingRemainder = new Decimal(0);
328
423
  var appliedSurchargeIds = [];
329
- var _iterator7 = _createForOfIteratorHelper(_node.relationSurchargeIds),
330
- _step7;
424
+ var persistedRemainderApplied = false;
425
+ var _iterator10 = _createForOfIteratorHelper(_node.relationSurchargeIds),
426
+ _step10;
331
427
  try {
332
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
333
- var surchargeId = _step7.value;
428
+ for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
429
+ var surchargeId = _step10.value;
334
430
  var config = configById.get(surchargeId);
335
431
  var totalQuantity = quantityTotals.get(surchargeId) || new Decimal(0);
336
- if (!config || totalQuantity.lte(0)) continue;
432
+ if (totalQuantity.lte(0)) continue;
433
+ var persistedUnitSurchargeFee = _node.persistedUnitSurchargeFee;
434
+ if (persistedUnitSurchargeFee && persistedUnitSurchargeFee.gt(0)) {
435
+ var persistedQuantity = Decimal.min(_node.persistedQuantity, _node.quantity);
436
+ var deltaQuantity = Decimal.max(_node.quantity.minus(persistedQuantity), 0);
437
+ var _state = getBackendSurchargeState(stateMap, surchargeId, config || {
438
+ surcharge_id: surchargeId
439
+ });
440
+ var persistedSurchargeRemainder = !persistedRemainderApplied && _node.persistedSurchargeRemainder ? _node.persistedSurchargeRemainder : new Decimal(0);
441
+ _state.amount = bcAdd(bcAdd(_state.amount, bcMul(persistedUnitSurchargeFee, persistedQuantity, 2), 2), persistedSurchargeRemainder, 2);
442
+ var _fixed = new Decimal((config === null || config === void 0 ? void 0 : config.fixed) || 0);
443
+ if (_fixed.gt(0)) _state.fixedIncluded = true;
444
+ var nodeTotalSurcharge = bcAdd(bcMul(persistedUnitSurchargeFee, persistedQuantity, 2), persistedSurchargeRemainder, 2);
445
+ if (config && deltaQuantity.gt(0)) {
446
+ var _percentage = new Decimal(config.percentage || 0);
447
+ var deltaUnitPercentageFee = Decimal.max(0, bcMul(_node.unitAmount, _percentage, 2));
448
+ var deltaSurcharge = bcMul(deltaQuantity, deltaUnitPercentageFee, 2);
449
+ _state.amount = bcAdd(_state.amount, deltaSurcharge, 2);
450
+ nodeTotalSurcharge = bcAdd(nodeTotalSurcharge, deltaSurcharge, 2);
451
+ }
452
+ if (_node.quantity.gt(0)) {
453
+ unitSurchargeFee = bcAdd(unitSurchargeFee, bcDiv(nodeTotalSurcharge, _node.quantity, 2), 2);
454
+ }
455
+ if (!persistedSurchargeRemainder.eq(0)) {
456
+ roundingRemainder = bcAdd(roundingRemainder, persistedSurchargeRemainder, 2);
457
+ persistedRemainderApplied = true;
458
+ }
459
+ appliedSurchargeIds.push(surchargeId);
460
+ continue;
461
+ }
462
+ if (!config) continue;
337
463
  var percentage = new Decimal(config.percentage || 0);
338
464
  var fixed = new Decimal(config.fixed || 0);
339
465
  var unitPercentageFee = Decimal.max(0, bcMul(_node.unitAmount, percentage, 2));
340
466
  var percentageTotalFee = bcMul(_node.quantity, unitPercentageFee, 2);
341
467
  var unitFixedFee = new Decimal(0);
342
468
  var fixedRemainder = new Decimal(0);
343
- if (fixed.gt(0)) {
469
+ if (fixed.gt(0) && !persistedSurchargeIds.has(surchargeId)) {
344
470
  unitFixedFee = bcDiv(fixed, totalQuantity, 2);
345
471
  var distributedFixed = bcMul(unitFixedFee, totalQuantity, 2);
346
472
  fixedRemainder = bcSub(fixed, distributedFixed, 2);
@@ -353,7 +479,7 @@ function calculateBackendProductSurcharges(params) {
353
479
  var offsetBaseFee = Decimal.max(0, bcSub(precisePercentage, unitPercentageFee, 6));
354
480
  state.totalOffsetFee = bcAdd(state.totalOffsetFee, bcMul(offsetBaseFee, _node.quantity, 6), 6);
355
481
  state.calculatedQuantity = bcAdd(state.calculatedQuantity, _node.quantity, 6);
356
- if (!state.fixedIncluded && fixed.gt(0)) {
482
+ if (!state.fixedIncluded && fixed.gt(0) && !persistedSurchargeIds.has(surchargeId)) {
357
483
  state.amount = bcAdd(state.amount, fixed, 2);
358
484
  state.fixedIncluded = true;
359
485
  }
@@ -371,9 +497,9 @@ function calculateBackendProductSurcharges(params) {
371
497
  appliedSurchargeIds.push(surchargeId);
372
498
  }
373
499
  } catch (err) {
374
- _iterator7.e(err);
500
+ _iterator10.e(err);
375
501
  } finally {
376
- _iterator7.f();
502
+ _iterator10.f();
377
503
  }
378
504
  applySurchargeNodeResult(_node, {
379
505
  unitSurchargeFee: unitSurchargeFee,
@@ -382,33 +508,39 @@ function calculateBackendProductSurcharges(params) {
382
508
  });
383
509
  }
384
510
  } catch (err) {
385
- _iterator6.e(err);
511
+ _iterator8.e(err);
386
512
  } finally {
387
- _iterator6.f();
513
+ _iterator8.f();
388
514
  }
389
- return (surchargeList || []).reduce(function (result, config, index) {
515
+ var result = (surchargeList || []).reduce(function (items, config, index) {
390
516
  var surchargeId = getSurchargeConfigId(config);
391
- if (surchargeId === undefined) return result;
517
+ if (surchargeId === undefined) return items;
392
518
  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;
519
+ if (!state || state.amount.lte(0)) return items;
520
+ items.push(buildSurchargeResultItem(config, surchargeId, state.amount, index));
521
+ return items;
411
522
  }, []);
523
+ var includedIds = new Set(result.map(function (item) {
524
+ return item === null || item === void 0 ? void 0 : item.surcharge_id;
525
+ }).filter(function (id) {
526
+ return id !== undefined;
527
+ }));
528
+ var _iterator9 = _createForOfIteratorHelper(stateMap.entries()),
529
+ _step9;
530
+ try {
531
+ for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
532
+ var _step9$value = _slicedToArray(_step9.value, 2),
533
+ _surchargeId = _step9$value[0],
534
+ _state2 = _step9$value[1];
535
+ if (includedIds.has(_surchargeId) || _state2.amount.lte(0)) continue;
536
+ result.push(buildSurchargeResultItem(_state2.config, _surchargeId, _state2.amount, result.length));
537
+ }
538
+ } catch (err) {
539
+ _iterator9.e(err);
540
+ } finally {
541
+ _iterator9.f();
542
+ }
543
+ return result;
412
544
  }
413
545
  function getProductDepositData(product) {
414
546
  var _product$_origin, _product$_origin2;
@@ -444,11 +576,11 @@ function calculateProductsDeposit(products) {
444
576
  var hasDeposit = false;
445
577
  var policyIds = new Set();
446
578
  var policyDataMap = new Map();
447
- var _iterator8 = _createForOfIteratorHelper(products),
448
- _step8;
579
+ var _iterator11 = _createForOfIteratorHelper(products),
580
+ _step11;
449
581
  try {
450
- for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
451
- var product = _step8.value;
582
+ for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
583
+ var product = _step11.value;
452
584
  var depositData = getProductDepositData(product);
453
585
  if (!depositData || depositData.has_deposit != 1) continue;
454
586
  var num = getSafeNum(product.num);
@@ -461,45 +593,45 @@ function calculateProductsDeposit(products) {
461
593
  var itemDeposit = fixed.plus(percentage.times(productTotal));
462
594
  totalDeposit = totalDeposit.plus(itemDeposit);
463
595
  hasDeposit = true;
464
- var _iterator10 = _createForOfIteratorHelper(collectDepositPolicyIds(depositData)),
465
- _step10;
596
+ var _iterator13 = _createForOfIteratorHelper(collectDepositPolicyIds(depositData)),
597
+ _step13;
466
598
  try {
467
- for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
468
- var id = _step10.value;
599
+ for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
600
+ var id = _step13.value;
469
601
  policyIds.add(id);
470
602
  }
471
603
  } catch (err) {
472
- _iterator10.e(err);
604
+ _iterator13.e(err);
473
605
  } finally {
474
- _iterator10.f();
606
+ _iterator13.f();
475
607
  }
476
- var _iterator11 = _createForOfIteratorHelper(collectDepositPolicyData(depositData)),
477
- _step11;
608
+ var _iterator14 = _createForOfIteratorHelper(collectDepositPolicyData(depositData)),
609
+ _step14;
478
610
  try {
479
- for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
480
- var policy = _step11.value;
611
+ for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
612
+ var policy = _step14.value;
481
613
  if (!policyDataMap.has(policy.id)) {
482
614
  policyDataMap.set(policy.id, policy);
483
615
  }
484
616
  policyIds.add(policy.id);
485
617
  }
486
618
  } catch (err) {
487
- _iterator11.e(err);
619
+ _iterator14.e(err);
488
620
  } finally {
489
- _iterator11.f();
621
+ _iterator14.f();
490
622
  }
491
623
  }
492
624
  } catch (err) {
493
- _iterator8.e(err);
625
+ _iterator11.e(err);
494
626
  } finally {
495
- _iterator8.f();
627
+ _iterator11.f();
496
628
  }
497
629
  if (!hasDeposit) return undefined;
498
- var _iterator9 = _createForOfIteratorHelper(policyIds),
499
- _step9;
630
+ var _iterator12 = _createForOfIteratorHelper(policyIds),
631
+ _step12;
500
632
  try {
501
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
502
- var _id = _step9.value;
633
+ for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
634
+ var _id = _step12.value;
503
635
  if (!policyDataMap.has(_id)) {
504
636
  policyDataMap.set(_id, {
505
637
  id: _id,
@@ -508,9 +640,9 @@ function calculateProductsDeposit(products) {
508
640
  }
509
641
  }
510
642
  } catch (err) {
511
- _iterator9.e(err);
643
+ _iterator12.e(err);
512
644
  } finally {
513
- _iterator9.f();
645
+ _iterator12.f();
514
646
  }
515
647
  return {
516
648
  total: totalDeposit.toFixed(2),
@@ -559,32 +691,32 @@ function calculateSingleItemTax(params) {
559
691
  * - 仅需叠加 `markup` / `markdown` 类 bundle(原价 bundle 已由 `calculateProductsTax` 独立处理)。
560
692
  */
561
693
  function getMainProductPaymentTotal(product) {
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;
694
+ var _ref9, _product$metadata$mai, _product$metadata8, _product$metadata9;
695
+ var mainSelling = (_ref9 = (_product$metadata$mai = (_product$metadata8 = product.metadata) === null || _product$metadata8 === void 0 ? void 0 : _product$metadata8.main_product_selling_price) !== null && _product$metadata$mai !== void 0 ? _product$metadata$mai : (_product$metadata9 = product.metadata) === null || _product$metadata9 === void 0 ? void 0 : _product$metadata9.main_product_original_price) !== null && _ref9 !== void 0 ? _ref9 : 0;
564
696
  var total = toDecimal(mainSelling);
565
697
  var bundleItems = product.product_bundle || [];
566
- var _iterator12 = _createForOfIteratorHelper(bundleItems),
567
- _step12;
698
+ var _iterator15 = _createForOfIteratorHelper(bundleItems),
699
+ _step15;
568
700
  try {
569
- for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
570
- var bundleItem = _step12.value;
701
+ for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
702
+ var bundleItem = _step15.value;
571
703
  if (isBundleMarkupOrDiscount(bundleItem)) {
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);
704
+ var _ref10, _bundleItem$bundle_se, _bundleItem$num;
705
+ var unit = toDecimal((_ref10 = (_bundleItem$bundle_se = bundleItem.bundle_selling_price) !== null && _bundleItem$bundle_se !== void 0 ? _bundleItem$bundle_se : bundleItem.price) !== null && _ref10 !== void 0 ? _ref10 : 0);
574
706
  var qty = getSafeNum((_bundleItem$num = bundleItem.num) !== null && _bundleItem$num !== void 0 ? _bundleItem$num : bundleItem.quantity);
575
707
  total = total.plus(unit.times(qty));
576
708
  }
577
709
  }
578
710
  } catch (err) {
579
- _iterator12.e(err);
711
+ _iterator15.e(err);
580
712
  } finally {
581
- _iterator12.f();
713
+ _iterator15.f();
582
714
  }
583
715
  return Decimal.max(total, 0);
584
716
  }
585
717
  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;
718
+ var _item$tax_fee_roundin, _item$metadata3;
719
+ 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$metadata3 = item.metadata) === null || _item$metadata3 === void 0 ? void 0 : _item$metadata3.tax_fee_rounding_remainder;
588
720
  if (value === undefined || value === null || value === '') return null;
589
721
  return new Decimal(value || 0);
590
722
  }
@@ -593,6 +725,13 @@ function getPersistedTaxRemainder(item, parentProduct) {
593
725
  if (!isPersistedLine) return null;
594
726
  return getExplicitTaxRemainder(item);
595
727
  }
728
+ function getPersistedMainTaxFee(product) {
729
+ var _ref11, _product$metadata$mai2, _product$metadata10;
730
+ if ((product === null || product === void 0 ? void 0 : product.order_detail_id) === undefined || (product === null || product === void 0 ? void 0 : product.order_detail_id) === null) return null;
731
+ var value = (_ref11 = (_product$metadata$mai2 = product === null || product === void 0 || (_product$metadata10 = product.metadata) === null || _product$metadata10 === void 0 ? void 0 : _product$metadata10.main_product_attached_bundle_tax_fee) !== null && _product$metadata$mai2 !== void 0 ? _product$metadata$mai2 : product === null || product === void 0 ? void 0 : product.main_product_attached_bundle_tax_fee) !== null && _ref11 !== void 0 ? _ref11 : product === null || product === void 0 ? void 0 : product.tax_fee;
732
+ if (value === undefined || value === null || value === '') return null;
733
+ return toDecimal(value);
734
+ }
596
735
  function writeTaxRemainder(item, roundingRemainder) {
597
736
  item.tax_fee_rounding_remainder = roundingRemainder.toNumber();
598
737
  if (item.metadata && _typeof(item.metadata) === 'object') {
@@ -601,35 +740,41 @@ function writeTaxRemainder(item, roundingRemainder) {
601
740
  }
602
741
  function resetTaxRemainderFields(products) {
603
742
  for (var _i2 = 0, _arr2 = products; _i2 < _arr2.length; _i2++) {
604
- var _productRemainder$toN;
605
743
  var product = _arr2[_i2];
606
744
  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;
745
+ if (productRemainder !== null) {
746
+ product.tax_fee_rounding_remainder = productRemainder.toNumber();
747
+ } else {
748
+ delete product.tax_fee_rounding_remainder;
749
+ }
608
750
  product.original_tax_fee_rounding_remainder = 0;
609
- var _iterator13 = _createForOfIteratorHelper(product.product_bundle || []),
610
- _step13;
751
+ var _iterator16 = _createForOfIteratorHelper(product.product_bundle || []),
752
+ _step16;
611
753
  try {
612
- for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
613
- var _bundleRemainder$toFi, _bundleRemainder$toNu;
614
- var bundle = _step13.value;
754
+ for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
755
+ var bundle = _step16.value;
615
756
  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;
757
+ bundle.metadata = _objectSpread({}, bundle.metadata || {});
758
+ if (bundleRemainder !== null) {
759
+ bundle.metadata.tax_fee_rounding_remainder = bundleRemainder.toFixed(2);
760
+ bundle.tax_fee_rounding_remainder = bundleRemainder.toNumber();
761
+ } else {
762
+ delete bundle.metadata.tax_fee_rounding_remainder;
763
+ delete bundle.tax_fee_rounding_remainder;
764
+ }
620
765
  bundle.original_tax_fee_rounding_remainder = 0;
621
766
  }
622
767
  } catch (err) {
623
- _iterator13.e(err);
768
+ _iterator16.e(err);
624
769
  } finally {
625
- _iterator13.f();
770
+ _iterator16.f();
626
771
  }
627
772
  }
628
773
  }
629
774
  function getBundlePaymentPrice(bundle, product) {
630
- var _ref9, _ref10, _bundle$bundle_sellin2, _metadata$average_dis, _metadata;
775
+ var _ref12, _ref13, _bundle$bundle_sellin2, _metadata$average_dis, _metadata;
631
776
  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);
777
+ var basePrice = toDecimal((_ref12 = (_ref13 = (_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 && _ref13 !== void 0 ? _ref13 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref12 !== void 0 ? _ref12 : 0);
633
778
  if (!isBundleOriginalPrice(bundle)) return basePrice;
634
779
  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
780
  return toAmountFormat(bcMul(basePrice, averageDiscountRate, 6));
@@ -661,33 +806,33 @@ function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
661
806
  var totalTax = new Decimal(0);
662
807
  var totalOriginTax = new Decimal(0);
663
808
  resetTaxRemainderFields(products);
664
- var _iterator14 = _createForOfIteratorHelper(products),
665
- _step14;
809
+ var _iterator17 = _createForOfIteratorHelper(products),
810
+ _step17;
666
811
  try {
667
- for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
812
+ for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
668
813
  var _product$is_charge_ta2, _product$is_charge_ta3;
669
- var product = _step14.value;
814
+ var product = _step17.value;
670
815
  var quantity = new Decimal(getSafeNum(product.num));
671
816
  var productUnitTax = new Decimal(0);
672
817
  var productUnitOriginTax = new Decimal(0);
673
818
  var bundleItems = product.product_bundle || [];
674
- var _iterator15 = _createForOfIteratorHelper(bundleItems),
675
- _step15;
819
+ var _iterator18 = _createForOfIteratorHelper(bundleItems),
820
+ _step18;
676
821
  try {
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;
822
+ for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
823
+ var _bundleItem$num2, _ref14, _ref15, _bundleItem$original_, _ref16, _bundleItem$is_charge, _ref17, _bundleItem$is_charge2;
824
+ var bundleItem = _step18.value;
680
825
  if (!isBundleOriginalPrice(bundleItem)) continue;
681
826
  var bundleQuantity = new Decimal(getSafeNum((_bundleItem$num2 = bundleItem.num) !== null && _bundleItem$num2 !== void 0 ? _bundleItem$num2 : bundleItem.quantity));
682
827
  var totalBundleQuantity = bundleQuantity.times(quantity);
683
828
  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);
829
+ var bundleOriginalPrice = toDecimal((_ref14 = (_ref15 = (_bundleItem$original_ = bundleItem.original_price) !== null && _bundleItem$original_ !== void 0 ? _bundleItem$original_ : bundleItem.product_price) !== null && _ref15 !== void 0 ? _ref15 : bundleItem.price) !== null && _ref14 !== void 0 ? _ref14 : 0);
685
830
  var bundleSurchargeFee = toDecimal(bundleItem.surcharge_fee);
686
831
  var bundleTaxPrecise = calculateSingleItemTax({
687
832
  price: bundlePrice.plus(bundleSurchargeFee),
688
833
  taxRate: rate,
689
834
  isPriceIncludeTax: isPriceIncludeTax,
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
835
+ isChargeTax: (_ref16 = (_bundleItem$is_charge = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge !== void 0 ? _bundleItem$is_charge : product.is_charge_tax) !== null && _ref16 !== void 0 ? _ref16 : 0
691
836
  });
692
837
  var bundleTaxRounded = toBackendTaxFee(bundleTaxPrecise);
693
838
  bundleItem.tax_fee = bundleTaxRounded.toNumber();
@@ -704,7 +849,7 @@ function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
704
849
  price: bundleOriginalPrice.plus(bundleSurchargeFee),
705
850
  taxRate: rate,
706
851
  isPriceIncludeTax: isPriceIncludeTax,
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
852
+ isChargeTax: (_ref17 = (_bundleItem$is_charge2 = bundleItem.is_charge_tax) !== null && _bundleItem$is_charge2 !== void 0 ? _bundleItem$is_charge2 : product.is_charge_tax) !== null && _ref17 !== void 0 ? _ref17 : 0
708
853
  });
709
854
  var bundleOrigTaxRounded = toAmountFormat(bundleOrigTaxPrecise);
710
855
  bundleItem.original_tax_fee = bundleOrigTaxRounded.toNumber();
@@ -714,9 +859,9 @@ function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
714
859
  totalOriginTax = totalOriginTax.plus(bundleOrigTaxRounded.times(totalBundleQuantity));
715
860
  }
716
861
  } catch (err) {
717
- _iterator15.e(err);
862
+ _iterator18.e(err);
718
863
  } finally {
719
- _iterator15.f();
864
+ _iterator18.f();
720
865
  }
721
866
  var mainTotal = getMainProductPaymentTotal(product);
722
867
  var surchargeFee = toDecimal(product.surcharge_fee);
@@ -728,16 +873,22 @@ function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
728
873
  isChargeTax: (_product$is_charge_ta2 = product.is_charge_tax) !== null && _product$is_charge_ta2 !== void 0 ? _product$is_charge_ta2 : 0
729
874
  });
730
875
  var mainTaxRounded = toBackendTaxFee(mainTaxPrecise);
731
- product.main_product_attached_bundle_tax_fee = mainTaxRounded.toFixed(2);
732
876
  var persistedMainRemainder = getPersistedTaxRemainder(product);
733
- var mainRemainder = persistedMainRemainder !== null && persistedMainRemainder !== void 0 ? persistedMainRemainder : applyBackendTaxRemainder({
877
+ var persistedMainTaxFee = getPersistedMainTaxFee(product);
878
+ var persistedQuantity = getPersistedQuantity(product, quantity);
879
+ var deltaQuantity = Decimal.max(quantity.minus(persistedQuantity), 0);
880
+ var shouldUsePersistedMainTax = persistedMainTaxFee && persistedMainTaxFee.gt(0) && persistedQuantity.gte(quantity);
881
+ var shouldSplitPersistedMainTax = persistedMainTaxFee && persistedMainTaxFee.gt(0) && persistedQuantity.gt(0) && deltaQuantity.gt(0);
882
+ var mainRemainder = shouldUsePersistedMainTax || shouldSplitPersistedMainTax ? new Decimal(0) : persistedMainRemainder !== null && persistedMainRemainder !== void 0 ? persistedMainRemainder : applyBackendTaxRemainder({
734
883
  target: product,
735
884
  rawTax: mainTaxPrecise,
736
885
  formattedTax: mainTaxRounded,
737
886
  quantity: quantity,
738
887
  state: taxRemainderState
739
888
  });
740
- if (persistedMainRemainder) writeTaxRemainder(product, persistedMainRemainder);
889
+ if (persistedMainRemainder && !shouldSplitPersistedMainTax) {
890
+ writeTaxRemainder(product, persistedMainRemainder);
891
+ }
741
892
  var originalTotal = getUnitOriginalTotal(product);
742
893
  var originalTaxableBase = originalTotal.lte(0) ? surchargeFee : originalTotal.plus(surchargeFee);
743
894
  var originalTaxPrecise = calculateSingleItemTax({
@@ -747,23 +898,77 @@ function calculateProductsTax(products, taxRate, isPriceIncludeTax) {
747
898
  isChargeTax: (_product$is_charge_ta3 = product.is_charge_tax) !== null && _product$is_charge_ta3 !== void 0 ? _product$is_charge_ta3 : 0
748
899
  });
749
900
  var originalTaxRounded = toAmountFormat(originalTaxPrecise);
750
- productUnitTax = productUnitTax.plus(mainTaxRounded);
901
+ var effectiveMainUnitTax = shouldUsePersistedMainTax ? persistedMainTaxFee : shouldSplitPersistedMainTax ? persistedMainTaxFee.times(persistedQuantity).plus(mainTaxRounded.times(deltaQuantity)).div(quantity).toDecimalPlaces(2, Decimal.ROUND_HALF_UP) : mainTaxRounded;
902
+ productUnitTax = productUnitTax.plus(effectiveMainUnitTax);
751
903
  productUnitOriginTax = productUnitOriginTax.plus(originalTaxRounded);
904
+ product.main_product_attached_bundle_tax_fee = effectiveMainUnitTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
752
905
  product.tax_fee = productUnitTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toFixed(2);
753
906
  product.original_tax_fee = productUnitOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
754
- totalTax = totalTax.plus(mainTaxRounded.times(quantity)).plus(mainRemainder);
907
+ totalTax = totalTax.plus(shouldUsePersistedMainTax ? persistedMainTaxFee.times(quantity).plus(persistedMainRemainder || 0) : shouldSplitPersistedMainTax ? persistedMainTaxFee.times(persistedQuantity).plus(mainTaxRounded.times(deltaQuantity)) : mainTaxRounded.times(quantity).plus(mainRemainder));
755
908
  totalOriginTax = totalOriginTax.plus(originalTaxRounded.times(quantity));
909
+ if (product.tax_fee_rounding_remainder === undefined) {
910
+ product.tax_fee_rounding_remainder = 0;
911
+ }
756
912
  }
757
913
  } catch (err) {
758
- _iterator14.e(err);
914
+ _iterator17.e(err);
759
915
  } finally {
760
- _iterator14.f();
916
+ _iterator17.f();
761
917
  }
762
918
  return {
763
919
  tax: totalTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP),
764
920
  originTax: totalOriginTax.toDecimalPlaces(2, Decimal.ROUND_HALF_UP)
765
921
  };
766
922
  }
923
+ function applyShopDiscountToSurchargeBase(products, productAmount, shopDiscountAmount) {
924
+ if (productAmount.lte(0) || shopDiscountAmount.lte(0)) return function () {};
925
+ var effectiveDiscount = Decimal.min(productAmount, shopDiscountAmount);
926
+ if (effectiveDiscount.lte(0)) return function () {};
927
+ var snapshots = products.map(function (product) {
928
+ var _product$metadata11;
929
+ return {
930
+ product: product,
931
+ metadata: product.metadata,
932
+ attachedBundleSellingPrice: (_product$metadata11 = product.metadata) === null || _product$metadata11 === void 0 ? void 0 : _product$metadata11.main_product_attached_bundle_selling_price
933
+ };
934
+ });
935
+ var allocatedDiscount = new Decimal(0);
936
+ products.forEach(function (product, index) {
937
+ var quantity = new Decimal(getSafeNum(product.num));
938
+ var lineAmount = getUnitPaymentTotal(product).times(quantity);
939
+ var lineDiscount = index === products.length - 1 ? effectiveDiscount.minus(allocatedDiscount) : toAmountFormat(lineAmount.div(productAmount).times(effectiveDiscount));
940
+ allocatedDiscount = allocatedDiscount.plus(lineDiscount);
941
+ var unitDiscount = quantity.lte(0) ? new Decimal(0) : lineDiscount.div(quantity);
942
+ var currentBase = getMainSurchargeUnitAmount(product);
943
+ var adjustedBase = Decimal.max(currentBase.minus(unitDiscount), 0);
944
+ product.metadata = _objectSpread(_objectSpread({}, product.metadata || {}), {}, {
945
+ main_product_attached_bundle_selling_price: adjustedBase.toFixed(2)
946
+ });
947
+ });
948
+ return function () {
949
+ var _iterator19 = _createForOfIteratorHelper(snapshots),
950
+ _step19;
951
+ try {
952
+ for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
953
+ var snapshot = _step19.value;
954
+ if (!snapshot.metadata) {
955
+ delete snapshot.product.metadata;
956
+ continue;
957
+ }
958
+ snapshot.product.metadata = _objectSpread(_objectSpread({}, snapshot.product.metadata), {}, {
959
+ main_product_attached_bundle_selling_price: snapshot.attachedBundleSellingPrice
960
+ });
961
+ if (snapshot.attachedBundleSellingPrice === undefined) {
962
+ delete snapshot.product.metadata.main_product_attached_bundle_selling_price;
963
+ }
964
+ }
965
+ } catch (err) {
966
+ _iterator19.e(err);
967
+ } finally {
968
+ _iterator19.f();
969
+ }
970
+ };
971
+ }
767
972
  export function createEmptySalesSummary() {
768
973
  return {
769
974
  product_quantity: 0,
@@ -811,6 +1016,12 @@ export function calculateSalesSummary(params) {
811
1016
  var productAmount = summaryProducts.reduce(function (sum, item) {
812
1017
  return sum.plus(getUnitPaymentTotal(item).times(getSafeNum(item.num)));
813
1018
  }, new Decimal(0));
1019
+ var shopDiscountAmount = Decimal.max(new Decimal(Number(shopDiscount) || 0), 0);
1020
+ var hasPersistedSurchargeSnapshot = summaryProducts.some(function (product) {
1021
+ var _getPersistedMainSurc;
1022
+ return (_getPersistedMainSurc = getPersistedMainSurchargeFee(product)) === null || _getPersistedMainSurc === void 0 ? void 0 : _getPersistedMainSurc.gt(0);
1023
+ });
1024
+ var restoreSurchargeBase = hasPersistedSurchargeSnapshot ? function () {} : applyShopDiscountToSurchargeBase(summaryProducts, productAmount, shopDiscountAmount);
814
1025
  var surchargeServiceItems = buildSurchargeServiceItems(summaryProducts);
815
1026
  getSurcharge({
816
1027
  service: surchargeServiceItems,
@@ -828,6 +1039,7 @@ export function calculateSalesSummary(params) {
828
1039
  sourceItems: surchargeServiceItems,
829
1040
  surchargeList: surchargeList
830
1041
  });
1042
+ restoreSurchargeBase();
831
1043
  var surchargeAmount = new Decimal(getSurchargeAmount({
832
1044
  bookingDetail: null,
833
1045
  bookingId: undefined
@@ -844,9 +1056,8 @@ export function calculateSalesSummary(params) {
844
1056
  return sum.plus(toDecimal(item.tax_fee).times(getSafeNum(item.num)));
845
1057
  }, new Decimal(0));
846
1058
  }
847
- var shopDiscountAmount = Decimal.max(new Decimal(Number(shopDiscount) || 0), 0);
848
- var preTaxExpectAmount = Decimal.max(0, productAmount.plus(surchargeAmount).minus(shopDiscountAmount));
849
- var totalAmount = isPriceIncludeTax === 1 ? preTaxExpectAmount : preTaxExpectAmount.plus(productTaxFee);
1059
+ var orderAmountBeforeDiscount = productAmount.plus(surchargeAmount).plus(isPriceIncludeTax === 1 ? 0 : productTaxFee);
1060
+ var totalAmount = Decimal.max(0, orderAmountBeforeDiscount.minus(shopDiscountAmount));
850
1061
  var deposit = calculateProductsDeposit(summaryProducts);
851
1062
  return {
852
1063
  product_quantity: productQuantity,