@pisell/pisellos 2.2.147 → 2.2.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/dist/apis/picoding.d.ts +0 -0
  2. package/dist/apis/picoding.js +1 -0
  3. package/dist/model/strategy/adapter/index.d.ts +2 -0
  4. package/dist/model/strategy/adapter/index.js +3 -1
  5. package/dist/model/strategy/adapter/itemRule/adapter.d.ts +67 -0
  6. package/dist/model/strategy/adapter/itemRule/adapter.js +483 -0
  7. package/dist/model/strategy/adapter/itemRule/evaluator.d.ts +43 -0
  8. package/dist/model/strategy/adapter/itemRule/evaluator.js +169 -0
  9. package/dist/model/strategy/adapter/itemRule/examples.d.ts +79 -0
  10. package/dist/model/strategy/adapter/itemRule/examples.js +382 -0
  11. package/dist/model/strategy/adapter/itemRule/index.d.ts +5 -0
  12. package/dist/model/strategy/adapter/itemRule/index.js +5 -0
  13. package/dist/model/strategy/adapter/itemRule/type.d.ts +225 -0
  14. package/dist/model/strategy/adapter/itemRule/type.js +101 -0
  15. package/dist/modules/Cart/types.d.ts +2 -0
  16. package/dist/modules/Cart/utils/cartProduct.js +22 -1
  17. package/dist/modules/Cart/utils/changePrice.js +6 -0
  18. package/dist/modules/Date/index.d.ts +1 -1
  19. package/dist/modules/Date/index.js +16 -8
  20. package/dist/modules/Date/types.d.ts +3 -1
  21. package/dist/modules/OpenData/index.d.ts +24 -0
  22. package/dist/modules/OpenData/index.js +173 -0
  23. package/dist/modules/OpenData/types.d.ts +73 -0
  24. package/dist/modules/OpenData/types.js +1 -0
  25. package/dist/modules/OpenData/utils.d.ts +2 -0
  26. package/dist/modules/OpenData/utils.js +75 -0
  27. package/dist/modules/Order/index.d.ts +171 -1
  28. package/dist/modules/Order/index.js +2052 -112
  29. package/dist/modules/Order/types.d.ts +441 -20
  30. package/dist/modules/Order/types.js +23 -0
  31. package/dist/modules/Order/utils.d.ts +120 -0
  32. package/dist/modules/Order/utils.js +653 -2
  33. package/dist/modules/Product/utils.js +2 -2
  34. package/dist/modules/ProductList/index.js +2 -1
  35. package/dist/modules/Quotation/index.d.ts +8 -1
  36. package/dist/modules/Quotation/index.js +40 -10
  37. package/dist/modules/Quotation/types.d.ts +5 -0
  38. package/dist/modules/Rules/index.d.ts +3 -1
  39. package/dist/modules/Rules/index.js +136 -50
  40. package/dist/modules/Rules/types.d.ts +6 -0
  41. package/dist/modules/Rules/types.js +8 -0
  42. package/dist/modules/SalesSummary/index.d.ts +70 -0
  43. package/dist/modules/SalesSummary/index.js +175 -0
  44. package/dist/modules/SalesSummary/types.d.ts +64 -0
  45. package/dist/modules/SalesSummary/types.js +1 -0
  46. package/dist/modules/SalesSummary/utils.d.ts +34 -0
  47. package/dist/modules/SalesSummary/utils.js +488 -0
  48. package/dist/modules/ScanOrderLogger/index.d.ts +21 -0
  49. package/dist/modules/ScanOrderLogger/index.js +161 -0
  50. package/dist/modules/ScanOrderLogger/providers/feishu.d.ts +2 -0
  51. package/dist/modules/ScanOrderLogger/providers/feishu.js +203 -0
  52. package/dist/modules/ScanOrderLogger/providers/grafana.d.ts +2 -0
  53. package/dist/modules/ScanOrderLogger/providers/grafana.js +50 -0
  54. package/dist/modules/ScanOrderLogger/types.d.ts +52 -0
  55. package/dist/modules/ScanOrderLogger/types.js +1 -0
  56. package/dist/modules/Schedule/getDateIsInSchedule.js +7 -7
  57. package/dist/modules/Schedule/index.d.ts +4 -13
  58. package/dist/modules/Schedule/index.js +6 -23
  59. package/dist/modules/Schedule/utils.d.ts +1 -1
  60. package/dist/modules/Summary/index.d.ts +3 -0
  61. package/dist/modules/Summary/index.js +134 -15
  62. package/dist/modules/Summary/types.d.ts +7 -0
  63. package/dist/modules/Summary/utils.d.ts +104 -1
  64. package/dist/modules/Summary/utils.js +1116 -13
  65. package/dist/modules/index.d.ts +4 -0
  66. package/dist/modules/index.js +5 -1
  67. package/dist/server/index.d.ts +41 -4
  68. package/dist/server/index.js +900 -405
  69. package/dist/server/modules/order/index.d.ts +10 -2
  70. package/dist/server/modules/order/index.js +251 -196
  71. package/dist/server/modules/products/index.d.ts +26 -0
  72. package/dist/server/modules/products/index.js +618 -338
  73. package/dist/server/modules/products/types.d.ts +5 -1
  74. package/dist/solution/BaseSales/index.d.ts +175 -0
  75. package/dist/solution/BaseSales/index.js +1293 -0
  76. package/dist/solution/BaseSales/types.d.ts +305 -0
  77. package/dist/solution/BaseSales/types.js +38 -0
  78. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +143 -0
  79. package/dist/solution/BaseSales/utils/parseSalesResponse.js +159 -0
  80. package/dist/solution/BaseSales/utils.d.ts +40 -0
  81. package/dist/solution/BaseSales/utils.js +222 -0
  82. package/dist/solution/BookingByStep/index.d.ts +14 -0
  83. package/dist/solution/BookingByStep/index.js +699 -212
  84. package/dist/solution/BookingByStep/types.d.ts +3 -1
  85. package/dist/solution/BookingByStep/types.js +5 -1
  86. package/dist/solution/BookingByStep/utils/capacity.js +1 -1
  87. package/dist/solution/BookingByStep/utils/resources.js +6 -1
  88. package/dist/solution/BookingTicket/index.d.ts +113 -15
  89. package/dist/solution/BookingTicket/index.js +534 -196
  90. package/dist/solution/BookingTicket/types.d.ts +69 -6
  91. package/dist/solution/BookingTicket/types.js +40 -9
  92. package/dist/solution/BookingTicket/utils/bookingStatus.d.ts +37 -0
  93. package/dist/solution/BookingTicket/utils/bookingStatus.js +66 -0
  94. package/dist/solution/BookingTicket/utils/cartView.d.ts +26 -0
  95. package/dist/solution/BookingTicket/utils/cartView.js +84 -0
  96. package/dist/solution/Sales/index.d.ts +1 -0
  97. package/dist/solution/Sales/index.js +1 -0
  98. package/dist/solution/ScanOrder/index.d.ts +146 -0
  99. package/dist/solution/ScanOrder/index.js +3029 -0
  100. package/dist/solution/ScanOrder/types.d.ts +305 -0
  101. package/dist/solution/ScanOrder/types.js +35 -0
  102. package/dist/solution/ScanOrder/utils.d.ts +167 -0
  103. package/dist/solution/ScanOrder/utils.js +768 -0
  104. package/dist/solution/ShopDiscount/index.d.ts +2 -0
  105. package/dist/solution/ShopDiscount/index.js +9 -5
  106. package/dist/solution/ShopDiscount/types.d.ts +4 -0
  107. package/dist/solution/VenueBooking/index.d.ts +197 -0
  108. package/dist/solution/VenueBooking/index.js +3411 -0
  109. package/dist/solution/VenueBooking/sales-section-4-annotated.json +343 -0
  110. package/dist/solution/VenueBooking/types.d.ts +153 -0
  111. package/dist/solution/VenueBooking/types.js +21 -0
  112. package/dist/solution/VenueBooking/utils/dateSummary.d.ts +11 -0
  113. package/dist/solution/VenueBooking/utils/dateSummary.js +104 -0
  114. package/dist/solution/VenueBooking/utils/resource.d.ts +14 -0
  115. package/dist/solution/VenueBooking/utils/resource.js +130 -0
  116. package/dist/solution/VenueBooking/utils/slotMerge.d.ts +34 -0
  117. package/dist/solution/VenueBooking/utils/slotMerge.js +224 -0
  118. package/dist/solution/VenueBooking/utils/timeSlot.d.ts +32 -0
  119. package/dist/solution/VenueBooking/utils/timeSlot.js +453 -0
  120. package/dist/solution/VenueBooking/utils.d.ts +1 -0
  121. package/dist/solution/VenueBooking/utils.js +1 -0
  122. package/dist/solution/index.d.ts +3 -0
  123. package/dist/solution/index.js +4 -1
  124. package/lib/apis/picoding.d.ts +0 -0
  125. package/lib/apis/picoding.js +0 -0
  126. package/lib/model/strategy/adapter/index.d.ts +2 -0
  127. package/lib/model/strategy/adapter/index.js +6 -0
  128. package/lib/model/strategy/adapter/itemRule/adapter.d.ts +67 -0
  129. package/lib/model/strategy/adapter/itemRule/adapter.js +377 -0
  130. package/lib/model/strategy/adapter/itemRule/evaluator.d.ts +43 -0
  131. package/lib/model/strategy/adapter/itemRule/evaluator.js +124 -0
  132. package/lib/model/strategy/adapter/itemRule/examples.d.ts +79 -0
  133. package/lib/model/strategy/adapter/itemRule/examples.js +316 -0
  134. package/lib/model/strategy/adapter/itemRule/index.d.ts +5 -0
  135. package/lib/model/strategy/adapter/itemRule/index.js +60 -0
  136. package/lib/model/strategy/adapter/itemRule/type.d.ts +225 -0
  137. package/lib/model/strategy/adapter/itemRule/type.js +46 -0
  138. package/lib/model/strategy/adapter/promotion/index.js +49 -0
  139. package/lib/modules/Cart/types.d.ts +2 -0
  140. package/lib/modules/Cart/utils/cartProduct.js +17 -1
  141. package/lib/modules/Cart/utils/changePrice.js +5 -0
  142. package/lib/modules/Date/index.d.ts +1 -1
  143. package/lib/modules/Date/index.js +7 -1
  144. package/lib/modules/Date/types.d.ts +3 -1
  145. package/lib/modules/OpenData/index.d.ts +24 -0
  146. package/lib/modules/OpenData/index.js +119 -0
  147. package/lib/modules/OpenData/types.d.ts +73 -0
  148. package/lib/modules/OpenData/types.js +17 -0
  149. package/lib/modules/OpenData/utils.d.ts +2 -0
  150. package/lib/modules/OpenData/utils.js +111 -0
  151. package/lib/modules/Order/index.d.ts +171 -1
  152. package/lib/modules/Order/index.js +1396 -5
  153. package/lib/modules/Order/types.d.ts +441 -20
  154. package/lib/modules/Order/types.js +1 -0
  155. package/lib/modules/Order/utils.d.ts +120 -0
  156. package/lib/modules/Order/utils.js +562 -2
  157. package/lib/modules/Product/utils.js +2 -2
  158. package/lib/modules/ProductList/index.js +2 -1
  159. package/lib/modules/Quotation/index.d.ts +8 -1
  160. package/lib/modules/Quotation/index.js +33 -4
  161. package/lib/modules/Quotation/types.d.ts +5 -0
  162. package/lib/modules/Rules/index.d.ts +3 -1
  163. package/lib/modules/Rules/index.js +46 -6
  164. package/lib/modules/Rules/types.d.ts +6 -0
  165. package/lib/modules/Rules/types.js +11 -2
  166. package/lib/modules/SalesSummary/index.d.ts +70 -0
  167. package/lib/modules/SalesSummary/index.js +106 -0
  168. package/lib/modules/SalesSummary/types.d.ts +64 -0
  169. package/lib/modules/SalesSummary/types.js +17 -0
  170. package/lib/modules/SalesSummary/utils.d.ts +34 -0
  171. package/lib/modules/SalesSummary/utils.js +430 -0
  172. package/lib/modules/ScanOrderLogger/index.d.ts +21 -0
  173. package/lib/modules/ScanOrderLogger/index.js +135 -0
  174. package/lib/modules/ScanOrderLogger/providers/feishu.d.ts +2 -0
  175. package/lib/modules/ScanOrderLogger/providers/feishu.js +148 -0
  176. package/lib/modules/ScanOrderLogger/providers/grafana.d.ts +2 -0
  177. package/lib/modules/ScanOrderLogger/providers/grafana.js +52 -0
  178. package/lib/modules/ScanOrderLogger/types.d.ts +52 -0
  179. package/lib/modules/ScanOrderLogger/types.js +17 -0
  180. package/lib/modules/Schedule/getDateIsInSchedule.js +5 -5
  181. package/lib/modules/Schedule/index.d.ts +4 -13
  182. package/lib/modules/Schedule/index.js +4 -15
  183. package/lib/modules/Schedule/utils.d.ts +1 -1
  184. package/lib/modules/Summary/index.d.ts +3 -0
  185. package/lib/modules/Summary/index.js +61 -2
  186. package/lib/modules/Summary/types.d.ts +7 -0
  187. package/lib/modules/Summary/utils.d.ts +104 -1
  188. package/lib/modules/Summary/utils.js +659 -8
  189. package/lib/modules/index.d.ts +4 -0
  190. package/lib/modules/index.js +9 -1
  191. package/lib/server/index.d.ts +41 -4
  192. package/lib/server/index.js +272 -10
  193. package/lib/server/modules/order/index.d.ts +10 -2
  194. package/lib/server/modules/order/index.js +31 -4
  195. package/lib/server/modules/products/index.d.ts +26 -0
  196. package/lib/server/modules/products/index.js +174 -22
  197. package/lib/server/modules/products/types.d.ts +5 -1
  198. package/lib/solution/BaseSales/index.d.ts +175 -0
  199. package/lib/solution/BaseSales/index.js +655 -0
  200. package/lib/solution/BaseSales/types.d.ts +305 -0
  201. package/lib/solution/BaseSales/types.js +40 -0
  202. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +143 -0
  203. package/lib/solution/BaseSales/utils/parseSalesResponse.js +160 -0
  204. package/lib/solution/BaseSales/utils.d.ts +40 -0
  205. package/lib/solution/BaseSales/utils.js +200 -0
  206. package/lib/solution/BookingByStep/index.d.ts +14 -0
  207. package/lib/solution/BookingByStep/index.js +469 -91
  208. package/lib/solution/BookingByStep/types.d.ts +3 -1
  209. package/lib/solution/BookingByStep/types.js +10 -0
  210. package/lib/solution/BookingByStep/utils/capacity.js +1 -1
  211. package/lib/solution/BookingByStep/utils/resources.js +5 -2
  212. package/lib/solution/BookingTicket/index.d.ts +113 -15
  213. package/lib/solution/BookingTicket/index.js +253 -61
  214. package/lib/solution/BookingTicket/types.d.ts +69 -6
  215. package/lib/solution/BookingTicket/types.js +16 -14
  216. package/lib/solution/BookingTicket/utils/bookingStatus.d.ts +37 -0
  217. package/lib/solution/BookingTicket/utils/bookingStatus.js +65 -0
  218. package/lib/solution/BookingTicket/utils/cartView.d.ts +26 -0
  219. package/lib/solution/BookingTicket/utils/cartView.js +103 -0
  220. package/lib/solution/Sales/index.d.ts +1 -0
  221. package/lib/solution/ScanOrder/index.d.ts +146 -0
  222. package/lib/solution/ScanOrder/index.js +1820 -0
  223. package/lib/solution/ScanOrder/types.d.ts +305 -0
  224. package/lib/solution/ScanOrder/types.js +36 -0
  225. package/lib/solution/ScanOrder/utils.d.ts +167 -0
  226. package/lib/solution/ScanOrder/utils.js +639 -0
  227. package/lib/solution/ShopDiscount/index.d.ts +2 -0
  228. package/lib/solution/ShopDiscount/index.js +9 -4
  229. package/lib/solution/ShopDiscount/types.d.ts +4 -0
  230. package/lib/solution/VenueBooking/index.d.ts +197 -0
  231. package/lib/solution/VenueBooking/index.js +1892 -0
  232. package/lib/solution/VenueBooking/sales-section-4-annotated.json +343 -0
  233. package/lib/solution/VenueBooking/types.d.ts +153 -0
  234. package/lib/solution/VenueBooking/types.js +44 -0
  235. package/lib/solution/VenueBooking/utils/dateSummary.d.ts +11 -0
  236. package/lib/solution/VenueBooking/utils/dateSummary.js +110 -0
  237. package/lib/solution/VenueBooking/utils/resource.d.ts +14 -0
  238. package/lib/solution/VenueBooking/utils/resource.js +91 -0
  239. package/lib/solution/VenueBooking/utils/slotMerge.d.ts +34 -0
  240. package/lib/solution/VenueBooking/utils/slotMerge.js +225 -0
  241. package/lib/solution/VenueBooking/utils/timeSlot.d.ts +32 -0
  242. package/lib/solution/VenueBooking/utils/timeSlot.js +339 -0
  243. package/lib/solution/VenueBooking/utils.d.ts +1 -0
  244. package/lib/solution/VenueBooking/utils.js +69 -0
  245. package/lib/solution/index.d.ts +3 -0
  246. package/lib/solution/index.js +7 -1
  247. package/package.json +1 -1
@@ -1,10 +1,11 @@
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); }
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
2
  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
3
3
  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
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
5
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
6
6
  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
7
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
+ 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); }
8
9
  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; }
9
10
  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; }
10
11
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
@@ -24,101 +25,1755 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
24
25
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
25
26
  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); }
26
27
  import { BaseModule } from "../BaseModule";
27
- import { generateDuration, getAllDiscountList, mergeRelationForms } from "./utils";
28
+ import { OrderHooks } from "./types";
29
+ import { generateDuration, getAllDiscountList, mergeRelationForms, buildSubmitPayload, createDefaultTempOrder, createDefaultOrderRulesHooks, createEmptySummary, createUuidV4, formatDateTime, isTempOrder, normalizeBookingIsAll, normalizeBookingSubType, mapPaymentItemsToOrderPayments } from "./utils";
28
30
  import { isNormalProduct } from "../Product/utils";
29
31
  import dayjs from 'dayjs';
32
+ import { buildProductLineFingerprint, getProductIdentityIndex, getSafeProductNum, isIdentityMatch, normalizeOrderProduct } from "../../solution/ScanOrder/utils";
33
+ import { DiscountModule } from "../Discount";
34
+ import { RulesModule } from "../Rules";
35
+ import { UnavailableReason } from "../Rules/types";
36
+ import Decimal from 'decimal.js';
37
+ import { cloneDeep } from 'lodash-es';
38
+ var LOCAL_ORDER_STORE_NAME = 'orders';
30
39
  export var OrderModule = /*#__PURE__*/function (_BaseModule) {
31
40
  _inherits(OrderModule, _BaseModule);
32
41
  var _super = _createSuper(OrderModule);
33
- // LoggerManager 实例
42
+ function OrderModule(name, version) {
43
+ var _this;
44
+ _classCallCheck(this, OrderModule);
45
+ _this = _super.call(this, name || 'order', version);
46
+ _defineProperty(_assertThisInitialized(_this), "defaultName", 'order');
47
+ _defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
48
+ _defineProperty(_assertThisInitialized(_this), "store", void 0);
49
+ _defineProperty(_assertThisInitialized(_this), "request", void 0);
50
+ _defineProperty(_assertThisInitialized(_this), "logger", void 0);
51
+ // LoggerManager 实例
52
+ _defineProperty(_assertThisInitialized(_this), "dbManager", void 0);
53
+ _defineProperty(_assertThisInitialized(_this), "window", void 0);
54
+ _defineProperty(_assertThisInitialized(_this), "cacheId", void 0);
55
+ _defineProperty(_assertThisInitialized(_this), "salesSummaryModuleName", void 0);
56
+ _defineProperty(_assertThisInitialized(_this), "rulesHooksOverride", void 0);
57
+ _defineProperty(_assertThisInitialized(_this), "otherParams", void 0);
58
+ return _this;
59
+ }
60
+ _createClass(OrderModule, [{
61
+ key: "initialize",
62
+ value: function () {
63
+ var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
64
+ var _otherParams$rules;
65
+ var appPlugin, app, otherParams;
66
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
67
+ while (1) switch (_context.prev = _context.next) {
68
+ case 0:
69
+ this.core = core;
70
+ this.store = options.store;
71
+ if (!this.store.tempOrder) {
72
+ this.store.tempOrder = null;
73
+ }
74
+ if (!this.store.summary) {
75
+ this.store.summary = createEmptySummary();
76
+ }
77
+ this.request = this.core.getPlugin('request');
78
+ appPlugin = this.core.getPlugin('app');
79
+ if (appPlugin) {
80
+ _context.next = 8;
81
+ break;
82
+ }
83
+ throw new Error('Order 模块需要 app 插件支持');
84
+ case 8:
85
+ app = appPlugin.getApp();
86
+ this.logger = app.logger;
87
+ this.dbManager = app.sqlite;
88
+ this.window = this.core.getPlugin('window');
89
+ otherParams = options.otherParams || {};
90
+ this.cacheId = otherParams.cacheId;
91
+ this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
92
+ this.rulesHooksOverride = (_otherParams$rules = otherParams.rules) === null || _otherParams$rules === void 0 ? void 0 : _otherParams$rules.hooks;
93
+ this.otherParams = otherParams;
94
+ this.registerDiscountModules(options);
95
+ this.restoreTempOrderFromStorage();
96
+ this.logInfo('OrderModule initialized successfully');
97
+ case 20:
98
+ case "end":
99
+ return _context.stop();
100
+ }
101
+ }, _callee, this);
102
+ }));
103
+ function initialize(_x, _x2) {
104
+ return _initialize.apply(this, arguments);
105
+ }
106
+ return initialize;
107
+ }()
108
+ /**
109
+ * 记录信息日志
110
+ */
111
+ }, {
112
+ key: "logInfo",
113
+ value: function logInfo(title, metadata) {
114
+ if (this.logger) {
115
+ this.logger.addLog({
116
+ type: 'info',
117
+ title: "[OrderModule] ".concat(title),
118
+ metadata: metadata || {}
119
+ });
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 记录警告日志
125
+ */
126
+ }, {
127
+ key: "logWarning",
128
+ value: function logWarning(title, metadata) {
129
+ if (this.logger) {
130
+ this.logger.addLog({
131
+ type: 'warning',
132
+ title: "[OrderModule] ".concat(title),
133
+ metadata: metadata || {}
134
+ });
135
+ }
136
+ }
137
+
138
+ /**
139
+ * 记录错误日志
140
+ */
141
+ }, {
142
+ key: "logError",
143
+ value: function logError(title, metadata) {
144
+ if (this.logger) {
145
+ this.logger.addLog({
146
+ type: 'error',
147
+ title: "[OrderModule] ".concat(title),
148
+ metadata: metadata || {}
149
+ });
150
+ }
151
+ }
152
+
153
+ // ─── Discount: 子模块注册 ───
154
+ }, {
155
+ key: "registerDiscountModules",
156
+ value: function registerDiscountModules(options) {
157
+ var _targetCacheData;
158
+ var targetCacheData = {};
159
+ if (this.cacheId && this.window) {
160
+ var sessionData = this.window.sessionStorage.getItem(this.name);
161
+ if (sessionData) {
162
+ try {
163
+ var data = JSON.parse(sessionData);
164
+ targetCacheData = (data === null || data === void 0 ? void 0 : data[this.cacheId]) || {};
165
+ } catch (_unused) {
166
+ // sessionStorage 损坏则忽略,按空 initialState 走
167
+ }
168
+ }
169
+ }
170
+ var discount = new DiscountModule("".concat(this.name, "_discount"));
171
+ this.core.registerModule(discount, {
172
+ initialState: (_targetCacheData = targetCacheData) === null || _targetCacheData === void 0 ? void 0 : _targetCacheData[discount.name],
173
+ otherParams: {
174
+ fatherModule: this.name,
175
+ openCache: !!this.cacheId,
176
+ cacheId: this.cacheId
177
+ }
178
+ });
179
+ this.store.discount = discount;
180
+ var rules = new RulesModule("".concat(this.name, "_rules"));
181
+ this.core.registerModule(rules, {
182
+ hooks: this.rulesHooksOverride || this.createDefaultRulesHooks()
183
+ });
184
+ this.store.rules = rules;
185
+ }
186
+ }, {
187
+ key: "createDefaultRulesHooks",
188
+ value: function createDefaultRulesHooks() {
189
+ return createDefaultOrderRulesHooks();
190
+ }
191
+
192
+ // ─── Discount: 公共 API ───
193
+ }, {
194
+ key: "loadDiscountConfig",
195
+ value: function () {
196
+ var _loadDiscountConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(params) {
197
+ var _this$store$discount, _this$store$tempOrder;
198
+ var discountList, _this$store$discount2;
199
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
200
+ while (1) switch (_context2.prev = _context2.next) {
201
+ case 0:
202
+ _context2.next = 2;
203
+ return (_this$store$discount = this.store.discount) === null || _this$store$discount === void 0 ? void 0 : _this$store$discount.loadPrepareConfig({
204
+ customer_id: params.customerId,
205
+ action: params.action || 'create',
206
+ with_good_pass: 1,
207
+ with_discount_card: 1,
208
+ with_wallet_pass_holder: 1,
209
+ request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
210
+ });
211
+ case 2:
212
+ discountList = _context2.sent;
213
+ if (discountList) {
214
+ (_this$store$discount2 = this.store.discount) === null || _this$store$discount2 === void 0 || _this$store$discount2.setDiscountList(discountList);
215
+ }
216
+ if ((_this$store$tempOrder = this.store.tempOrder) !== null && _this$store$tempOrder !== void 0 && (_this$store$tempOrder = _this$store$tempOrder.products) !== null && _this$store$tempOrder !== void 0 && _this$store$tempOrder.length) {
217
+ this.applyDiscount();
218
+ }
219
+ case 5:
220
+ case "end":
221
+ return _context2.stop();
222
+ }
223
+ }, _callee2, this);
224
+ }));
225
+ function loadDiscountConfig(_x3) {
226
+ return _loadDiscountConfig.apply(this, arguments);
227
+ }
228
+ return loadDiscountConfig;
229
+ }()
230
+ }, {
231
+ key: "getDiscountList",
232
+ value: function getDiscountList() {
233
+ var _this$store$discount3;
234
+ return ((_this$store$discount3 = this.store.discount) === null || _this$store$discount3 === void 0 ? void 0 : _this$store$discount3.getDiscountList()) || [];
235
+ }
236
+ }, {
237
+ key: "scanCode",
238
+ value: function () {
239
+ var _scanCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(code, customerId) {
240
+ var _this$store$discount4, _tempOrder$holder, _this$store$summary, _tempOrder$holder2;
241
+ var resultDiscountList, rulesModule, withScanList, currentSelected, tempOrder, holders, _ref, isAvailable, newDiscountList, unavailableReason, _this$store$discount5;
242
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
243
+ while (1) switch (_context3.prev = _context3.next) {
244
+ case 0:
245
+ _context3.next = 2;
246
+ return (_this$store$discount4 = this.store.discount) === null || _this$store$discount4 === void 0 ? void 0 : _this$store$discount4.batchSearch(code, customerId);
247
+ case 2:
248
+ _context3.t0 = _context3.sent;
249
+ if (_context3.t0) {
250
+ _context3.next = 5;
251
+ break;
252
+ }
253
+ _context3.t0 = [];
254
+ case 5:
255
+ resultDiscountList = _context3.t0;
256
+ rulesModule = this.store.rules;
257
+ if (rulesModule) {
258
+ _context3.next = 9;
259
+ break;
260
+ }
261
+ return _context3.abrupt("return", {
262
+ type: 'clientCalc',
263
+ isAvailable: false,
264
+ discountList: this.getDiscountList(),
265
+ unavailableReason: UnavailableReason.Unknown
266
+ });
267
+ case 9:
268
+ if (resultDiscountList.length) {
269
+ _context3.next = 11;
270
+ break;
271
+ }
272
+ return _context3.abrupt("return", {
273
+ type: 'server',
274
+ isAvailable: false,
275
+ discountList: this.getDiscountList()
276
+ });
277
+ case 11:
278
+ withScanList = resultDiscountList.map(function (item) {
279
+ return _objectSpread(_objectSpread({}, item), {}, {
280
+ isScan: true
281
+ });
282
+ });
283
+ currentSelected = this.getDiscountList().filter(function (n) {
284
+ return n.isSelected;
285
+ });
286
+ if (!(currentSelected.length && currentSelected.some(function (n) {
287
+ return withScanList.some(function (m) {
288
+ return m.id === n.id;
289
+ });
290
+ }))) {
291
+ _context3.next = 15;
292
+ break;
293
+ }
294
+ return _context3.abrupt("return", {
295
+ type: 'clientCalc',
296
+ isAvailable: true,
297
+ discountList: this.getDiscountList()
298
+ });
299
+ case 15:
300
+ tempOrder = this.store.tempOrder;
301
+ holders = tempOrder !== null && tempOrder !== void 0 && (_tempOrder$holder = tempOrder.holder) !== null && _tempOrder$holder !== void 0 && _tempOrder$holder.form_record_id ? [{
302
+ form_record_id: tempOrder.holder.form_record_id
303
+ }] : [];
304
+ _ref = rulesModule.isDiscountListAvailable({
305
+ productList: (tempOrder === null || tempOrder === void 0 ? void 0 : tempOrder.products) || [],
306
+ oldDiscountList: this.getDiscountList(),
307
+ newDiscountList: withScanList,
308
+ orderTotalAmount: Number(((_this$store$summary = this.store.summary) === null || _this$store$summary === void 0 ? void 0 : _this$store$summary.total_amount) || 0),
309
+ holders: holders,
310
+ isFormSubject: !!(tempOrder !== null && tempOrder !== void 0 && (_tempOrder$holder2 = tempOrder.holder) !== null && _tempOrder$holder2 !== void 0 && _tempOrder$holder2.type) && tempOrder.holder.type === 'form'
311
+ }) || {
312
+ isAvailable: false,
313
+ discountList: this.getDiscountList()
314
+ }, isAvailable = _ref.isAvailable, newDiscountList = _ref.discountList, unavailableReason = _ref.unavailableReason;
315
+ if (isAvailable && newDiscountList) {
316
+ (_this$store$discount5 = this.store.discount) === null || _this$store$discount5 === void 0 || _this$store$discount5.setDiscountList(newDiscountList);
317
+ this.applyDiscount();
318
+ }
319
+ return _context3.abrupt("return", {
320
+ type: 'clientCalc',
321
+ isAvailable: isAvailable || false,
322
+ discountList: newDiscountList || this.getDiscountList(),
323
+ unavailableReason: unavailableReason
324
+ });
325
+ case 20:
326
+ case "end":
327
+ return _context3.stop();
328
+ }
329
+ }, _callee3, this);
330
+ }));
331
+ function scanCode(_x4, _x5) {
332
+ return _scanCode.apply(this, arguments);
333
+ }
334
+ return scanCode;
335
+ }()
336
+ }, {
337
+ key: "applyDiscount",
338
+ value: function applyDiscount() {
339
+ var _this$store$discount6, _tempOrder$holder3, _tempOrder$holder4, _this$store$summary2;
340
+ var tempOrder = this.store.tempOrder;
341
+ // 任意 products CRUD 后都应当重算 discount 状态;即使 products 为空,
342
+ // 也需要让 Rules.calcDiscount 把 DiscountModule 的 isSelected / isAvailable /
343
+ // appliedProductDetails / savedAmount 以及 tempOrder.discount_list 复位。
344
+ if (!tempOrder) return;
345
+ var rulesModule = this.store.rules;
346
+ if (!rulesModule) return;
347
+ var discountList = ((_this$store$discount6 = this.store.discount) === null || _this$store$discount6 === void 0 ? void 0 : _this$store$discount6.getDiscountList()) || [];
348
+ var holders = (_tempOrder$holder3 = tempOrder.holder) !== null && _tempOrder$holder3 !== void 0 && _tempOrder$holder3.form_record_id ? [{
349
+ form_record_id: tempOrder.holder.form_record_id
350
+ }] : [];
351
+ var result = rulesModule.calcDiscount({
352
+ productList: tempOrder.products,
353
+ discountList: discountList,
354
+ holders: holders,
355
+ isFormSubject: !!((_tempOrder$holder4 = tempOrder.holder) !== null && _tempOrder$holder4 !== void 0 && _tempOrder$holder4.type) && tempOrder.holder.type === 'form',
356
+ orderTotalAmount: Number(((_this$store$summary2 = this.store.summary) === null || _this$store$summary2 === void 0 ? void 0 : _this$store$summary2.total_amount) || 0)
357
+ });
358
+ if (result !== null && result !== void 0 && result.productList) {
359
+ tempOrder.products = result.productList;
360
+ }
361
+ if (result !== null && result !== void 0 && result.discountList) {
362
+ var _this$store$discount7;
363
+ OrderModule.populateSavedAmounts(result.productList || tempOrder.products, result.discountList);
364
+ (_this$store$discount7 = this.store.discount) === null || _this$store$discount7 === void 0 || _this$store$discount7.setDiscountList(result.discountList);
365
+ tempOrder.discount_list = result.discountList.filter(function (d) {
366
+ return d.isSelected;
367
+ });
368
+ }
369
+ }
370
+
371
+ // ─── TempOrder: 初始化入口 ───
372
+ }, {
373
+ key: "initTempOrder",
374
+ value: function initTempOrder(params) {
375
+ if (params.cacheId !== undefined) this.cacheId = params.cacheId;
376
+ if (params.salesSummaryModuleName !== undefined) this.salesSummaryModuleName = params.salesSummaryModuleName;
377
+ this.restoreTempOrderFromStorage();
378
+ }
379
+
380
+ // ─── TempOrder: localStorage 持久化 ───
381
+ }, {
382
+ key: "getTempOrderStorageKey",
383
+ value: function getTempOrderStorageKey() {
384
+ if (!this.cacheId) return null;
385
+ return "scanOrder:tempOrder:".concat(this.cacheId);
386
+ }
387
+ }, {
388
+ key: "restoreTempOrderFromStorage",
389
+ value: function restoreTempOrderFromStorage() {
390
+ var key = this.getTempOrderStorageKey();
391
+ if (!key) return;
392
+ if (!this.window) return;
393
+ var cachedData = this.window.localStorage.getItem(key);
394
+ if (!cachedData) return;
395
+ try {
396
+ var parsedData = JSON.parse(cachedData);
397
+ if (!isTempOrder(parsedData)) {
398
+ this.window.localStorage.removeItem(key);
399
+ return;
400
+ }
401
+ if (Array.isArray(parsedData.products)) {
402
+ for (var i = 0; i < parsedData.products.length; i++) {
403
+ var p = parsedData.products[i];
404
+ if (!p || _typeof(p) !== 'object') continue;
405
+ if (!Array.isArray(p.product_option_item)) {
406
+ p.product_option_item = [];
407
+ }
408
+ if (!Array.isArray(p.product_bundle)) {
409
+ p.product_bundle = [];
410
+ }
411
+ var row = p;
412
+ // 价格 schema 迁移:重跑 normalizeOrderProduct。
413
+ // `metadata.price_schema_version === 2` → 已是新语义,保留现有 main_product_* 折扣;
414
+ // 否则(v1 或无 metadata)→ 走 legacyDiscount 反推分支,基于新的 source + options
415
+ // 重算出含 option 的 main_product_*,并打上 price_schema_version: 2。
416
+ // 幂等:多次 restore 不会重复叠加 option/bundle。
417
+ parsedData.products[i] = normalizeOrderProduct(row);
418
+ }
419
+ }
420
+ var parsedRecord = parsedData;
421
+ this.store.summary = parsedRecord.summary || createEmptySummary();
422
+ delete parsedData.summary;
423
+ if (parsedRecord.lastOrderInfo) {
424
+ this.store.lastOrderInfo = parsedRecord.lastOrderInfo;
425
+ delete parsedData.lastOrderInfo;
426
+ }
427
+ if (!parsedData._extend || _typeof(parsedData._extend) !== 'object') {
428
+ parsedData._extend = {
429
+ productsByUid: {}
430
+ };
431
+ } else if (!parsedData._extend.productsByUid) {
432
+ parsedData._extend.productsByUid = {};
433
+ }
434
+ this.store.tempOrder = parsedData;
435
+ } catch (_unused2) {
436
+ var _this$window;
437
+ (_this$window = this.window) === null || _this$window === void 0 || (_this$window = _this$window.localStorage) === null || _this$window === void 0 || _this$window.removeItem(key);
438
+ }
439
+ }
440
+ }, {
441
+ key: "persistTempOrder",
442
+ value: function persistTempOrder() {
443
+ var key = this.getTempOrderStorageKey();
444
+ if (!key || !this.store.tempOrder) return;
445
+ if (!this.window) return;
446
+ this.window.localStorage.setItem(key, JSON.stringify(this.store.tempOrder));
447
+ }
448
+
449
+ // ─── TempOrder: 创建 & 获取 ───
450
+ }, {
451
+ key: "createDefaultTempOrderInstance",
452
+ value: function createDefaultTempOrderInstance() {
453
+ return createDefaultTempOrder({
454
+ now: formatDateTime(new Date())
455
+ });
456
+ }
457
+ }, {
458
+ key: "createExternalSaleNumber",
459
+ value: function createExternalSaleNumber() {
460
+ var _this$core;
461
+ var timestamp = dayjs().format('YYYYMMDDHHmmssSSS');
462
+ var random6 = String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
463
+ var parts = ['LOCAL'];
464
+ var context = (_this$core = this.core) === null || _this$core === void 0 ? void 0 : _this$core.context;
465
+ var getData = context === null || context === void 0 ? void 0 : context.getData;
466
+ if (typeof getData === 'function') {
467
+ var shopId = getData.call(context, 'shop_id');
468
+ var deviceId = getData.call(context, 'device_id');
469
+ if (shopId !== undefined && shopId !== null && shopId !== '') {
470
+ parts.push(String(shopId));
471
+ }
472
+ if (deviceId !== undefined && deviceId !== null && deviceId !== '') {
473
+ parts.push(String(deviceId).slice(-8));
474
+ }
475
+ } else {
476
+ this.logWarning('external_sale_number context getData unavailable', {
477
+ key: 'shop_id'
478
+ });
479
+ this.logWarning('external_sale_number context getData unavailable', {
480
+ key: 'device_id'
481
+ });
482
+ }
483
+ parts.push(timestamp, random6);
484
+ return parts.join('_');
485
+ }
486
+ }, {
487
+ key: "ensureExternalSaleNumber",
488
+ value: function ensureExternalSaleNumber(tempOrder) {
489
+ if (!tempOrder.external_sale_number) {
490
+ tempOrder.external_sale_number = this.createExternalSaleNumber();
491
+ }
492
+ this.ensureRequestUniqueIdempotencyToken(tempOrder);
493
+ return tempOrder.external_sale_number;
494
+ }
495
+ }, {
496
+ key: "ensureRequestUniqueIdempotencyToken",
497
+ value: function ensureRequestUniqueIdempotencyToken(tempOrder) {
498
+ if (!tempOrder.request_unique_idempotency_token) {
499
+ tempOrder.request_unique_idempotency_token = "".concat(tempOrder.external_sale_number, "_").concat(Date.now());
500
+ }
501
+ return tempOrder.request_unique_idempotency_token;
502
+ }
503
+ }, {
504
+ key: "hasLocalDatabase",
505
+ value: function hasLocalDatabase() {
506
+ return !!this.dbManager;
507
+ }
508
+ }, {
509
+ key: "buildLocalOrderRecord",
510
+ value: function buildLocalOrderRecord(tempOrder) {
511
+ var _tempOrder$order_id;
512
+ var externalSaleNumber = this.ensureExternalSaleNumber(tempOrder);
513
+ return _objectSpread(_objectSpread({}, tempOrder), {}, {
514
+ id: (_tempOrder$order_id = tempOrder.order_id) !== null && _tempOrder$order_id !== void 0 ? _tempOrder$order_id : externalSaleNumber,
515
+ external_sale_number: externalSaleNumber,
516
+ summary: this.store.summary || createEmptySummary(),
517
+ lastOrderInfo: this.store.lastOrderInfo
518
+ });
519
+ }
520
+ }, {
521
+ key: "getLocalOrderByOrderId",
522
+ value: function () {
523
+ var _getLocalOrderByOrderId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(orderId) {
524
+ var _this$dbManager$get, _this$dbManager, _this$dbManager$getAl, _this$dbManager2, direct, orders;
525
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
526
+ while (1) switch (_context4.prev = _context4.next) {
527
+ case 0:
528
+ if (!(!this.dbManager || orderId === undefined || orderId === null)) {
529
+ _context4.next = 2;
530
+ break;
531
+ }
532
+ return _context4.abrupt("return", null);
533
+ case 2:
534
+ _context4.prev = 2;
535
+ _context4.next = 5;
536
+ return (_this$dbManager$get = (_this$dbManager = this.dbManager).get) === null || _this$dbManager$get === void 0 ? void 0 : _this$dbManager$get.call(_this$dbManager, LOCAL_ORDER_STORE_NAME, orderId);
537
+ case 5:
538
+ direct = _context4.sent;
539
+ if (!direct) {
540
+ _context4.next = 8;
541
+ break;
542
+ }
543
+ return _context4.abrupt("return", direct);
544
+ case 8:
545
+ _context4.next = 10;
546
+ return (_this$dbManager$getAl = (_this$dbManager2 = this.dbManager).getAll) === null || _this$dbManager$getAl === void 0 ? void 0 : _this$dbManager$getAl.call(_this$dbManager2, LOCAL_ORDER_STORE_NAME);
547
+ case 10:
548
+ orders = _context4.sent;
549
+ return _context4.abrupt("return", (orders || []).find(function (order) {
550
+ return String(order === null || order === void 0 ? void 0 : order.order_id) === String(orderId);
551
+ }) || null);
552
+ case 14:
553
+ _context4.prev = 14;
554
+ _context4.t0 = _context4["catch"](2);
555
+ this.logWarning('getLocalOrderByOrderId failed', {
556
+ orderId: orderId,
557
+ error: _context4.t0 instanceof Error ? _context4.t0.message : String(_context4.t0)
558
+ });
559
+ return _context4.abrupt("return", null);
560
+ case 18:
561
+ case "end":
562
+ return _context4.stop();
563
+ }
564
+ }, _callee4, this, [[2, 14]]);
565
+ }));
566
+ function getLocalOrderByOrderId(_x6) {
567
+ return _getLocalOrderByOrderId.apply(this, arguments);
568
+ }
569
+ return getLocalOrderByOrderId;
570
+ }()
571
+ }, {
572
+ key: "getLocalOrderByOrderNumber",
573
+ value: function () {
574
+ var _getLocalOrderByOrderNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(orderNumber) {
575
+ var _this$dbManager$get2, _this$dbManager3, _this$dbManager$getAl2, _this$dbManager4, direct, orders;
576
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
577
+ while (1) switch (_context5.prev = _context5.next) {
578
+ case 0:
579
+ if (!(!this.dbManager || !orderNumber)) {
580
+ _context5.next = 2;
581
+ break;
582
+ }
583
+ return _context5.abrupt("return", null);
584
+ case 2:
585
+ _context5.prev = 2;
586
+ _context5.next = 5;
587
+ return (_this$dbManager$get2 = (_this$dbManager3 = this.dbManager).get) === null || _this$dbManager$get2 === void 0 ? void 0 : _this$dbManager$get2.call(_this$dbManager3, LOCAL_ORDER_STORE_NAME, orderNumber);
588
+ case 5:
589
+ direct = _context5.sent;
590
+ if (!direct) {
591
+ _context5.next = 8;
592
+ break;
593
+ }
594
+ return _context5.abrupt("return", direct);
595
+ case 8:
596
+ _context5.next = 10;
597
+ return (_this$dbManager$getAl2 = (_this$dbManager4 = this.dbManager).getAll) === null || _this$dbManager$getAl2 === void 0 ? void 0 : _this$dbManager$getAl2.call(_this$dbManager4, LOCAL_ORDER_STORE_NAME);
598
+ case 10:
599
+ orders = _context5.sent;
600
+ return _context5.abrupt("return", (orders || []).find(function (order) {
601
+ return String(order === null || order === void 0 ? void 0 : order.order_number) === String(orderNumber);
602
+ }) || null);
603
+ case 14:
604
+ _context5.prev = 14;
605
+ _context5.t0 = _context5["catch"](2);
606
+ this.logWarning('getLocalOrderByOrderNumber failed', {
607
+ orderNumber: orderNumber,
608
+ error: _context5.t0 instanceof Error ? _context5.t0.message : String(_context5.t0)
609
+ });
610
+ return _context5.abrupt("return", null);
611
+ case 18:
612
+ case "end":
613
+ return _context5.stop();
614
+ }
615
+ }, _callee5, this, [[2, 14]]);
616
+ }));
617
+ function getLocalOrderByOrderNumber(_x7) {
618
+ return _getLocalOrderByOrderNumber.apply(this, arguments);
619
+ }
620
+ return getLocalOrderByOrderNumber;
621
+ }()
622
+ }, {
623
+ key: "getLocalOrderByExternalSaleNumber",
624
+ value: function () {
625
+ var _getLocalOrderByExternalSaleNumber = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(externalSaleNumber) {
626
+ var _this$dbManager$get3, _this$dbManager5, _this$dbManager$getAl3, _this$dbManager6, direct, orders;
627
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
628
+ while (1) switch (_context6.prev = _context6.next) {
629
+ case 0:
630
+ if (!(!this.dbManager || !externalSaleNumber)) {
631
+ _context6.next = 2;
632
+ break;
633
+ }
634
+ return _context6.abrupt("return", null);
635
+ case 2:
636
+ _context6.prev = 2;
637
+ _context6.next = 5;
638
+ return (_this$dbManager$get3 = (_this$dbManager5 = this.dbManager).get) === null || _this$dbManager$get3 === void 0 ? void 0 : _this$dbManager$get3.call(_this$dbManager5, LOCAL_ORDER_STORE_NAME, externalSaleNumber);
639
+ case 5:
640
+ direct = _context6.sent;
641
+ if (!direct) {
642
+ _context6.next = 8;
643
+ break;
644
+ }
645
+ return _context6.abrupt("return", direct);
646
+ case 8:
647
+ _context6.next = 10;
648
+ return (_this$dbManager$getAl3 = (_this$dbManager6 = this.dbManager).getAll) === null || _this$dbManager$getAl3 === void 0 ? void 0 : _this$dbManager$getAl3.call(_this$dbManager6, LOCAL_ORDER_STORE_NAME);
649
+ case 10:
650
+ orders = _context6.sent;
651
+ return _context6.abrupt("return", (orders || []).find(function (order) {
652
+ return String(order === null || order === void 0 ? void 0 : order.external_sale_number) === String(externalSaleNumber);
653
+ }) || null);
654
+ case 14:
655
+ _context6.prev = 14;
656
+ _context6.t0 = _context6["catch"](2);
657
+ this.logWarning('getLocalOrderByExternalSaleNumber failed', {
658
+ externalSaleNumber: externalSaleNumber,
659
+ error: _context6.t0 instanceof Error ? _context6.t0.message : String(_context6.t0)
660
+ });
661
+ return _context6.abrupt("return", null);
662
+ case 18:
663
+ case "end":
664
+ return _context6.stop();
665
+ }
666
+ }, _callee6, this, [[2, 14]]);
667
+ }));
668
+ function getLocalOrderByExternalSaleNumber(_x8) {
669
+ return _getLocalOrderByExternalSaleNumber.apply(this, arguments);
670
+ }
671
+ return getLocalOrderByExternalSaleNumber;
672
+ }()
673
+ }, {
674
+ key: "saveDraft",
675
+ value: function () {
676
+ var _saveDraft = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
677
+ var tempOrder, record, _this$dbManager$updat, _this$dbManager7;
678
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
679
+ while (1) switch (_context7.prev = _context7.next) {
680
+ case 0:
681
+ if (this.dbManager) {
682
+ _context7.next = 2;
683
+ break;
684
+ }
685
+ return _context7.abrupt("return");
686
+ case 2:
687
+ tempOrder = this.ensureTempOrder();
688
+ record = this.buildLocalOrderRecord(tempOrder);
689
+ _context7.prev = 4;
690
+ _context7.next = 7;
691
+ return (_this$dbManager$updat = (_this$dbManager7 = this.dbManager).update) === null || _this$dbManager$updat === void 0 ? void 0 : _this$dbManager$updat.call(_this$dbManager7, LOCAL_ORDER_STORE_NAME, record);
692
+ case 7:
693
+ _context7.next = 12;
694
+ break;
695
+ case 9:
696
+ _context7.prev = 9;
697
+ _context7.t0 = _context7["catch"](4);
698
+ this.logWarning('saveDraft failed', {
699
+ externalSaleNumber: tempOrder.external_sale_number,
700
+ orderNumber: tempOrder.order_number,
701
+ orderId: tempOrder.order_id,
702
+ error: _context7.t0 instanceof Error ? _context7.t0.message : String(_context7.t0)
703
+ });
704
+ case 12:
705
+ case "end":
706
+ return _context7.stop();
707
+ }
708
+ }, _callee7, this, [[4, 9]]);
709
+ }));
710
+ function saveDraft() {
711
+ return _saveDraft.apply(this, arguments);
712
+ }
713
+ return saveDraft;
714
+ }()
715
+ }, {
716
+ key: "hydrateTempOrderFromLocalRecord",
717
+ value: function () {
718
+ var _hydrateTempOrderFromLocalRecord = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(record) {
719
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
720
+ while (1) switch (_context8.prev = _context8.next) {
721
+ case 0:
722
+ return _context8.abrupt("return", this.hydrateTempOrderFromRecord(record));
723
+ case 1:
724
+ case "end":
725
+ return _context8.stop();
726
+ }
727
+ }, _callee8, this);
728
+ }));
729
+ function hydrateTempOrderFromLocalRecord(_x9) {
730
+ return _hydrateTempOrderFromLocalRecord.apply(this, arguments);
731
+ }
732
+ return hydrateTempOrderFromLocalRecord;
733
+ }()
734
+ }, {
735
+ key: "extractOrderIdFromSubmitResult",
736
+ value: function extractOrderIdFromSubmitResult(result) {
737
+ var _ref2, _ref3, _ref4, _result$data$order_id, _result$data, _result$data2;
738
+ return (_ref2 = (_ref3 = (_ref4 = (_result$data$order_id = result === null || result === void 0 || (_result$data = result.data) === null || _result$data === void 0 ? void 0 : _result$data.order_id) !== null && _result$data$order_id !== void 0 ? _result$data$order_id : result === null || result === void 0 ? void 0 : result.order_id) !== null && _ref4 !== void 0 ? _ref4 : result === null || result === void 0 || (_result$data2 = result.data) === null || _result$data2 === void 0 ? void 0 : _result$data2.id) !== null && _ref3 !== void 0 ? _ref3 : result === null || result === void 0 ? void 0 : result.id) !== null && _ref2 !== void 0 ? _ref2 : null;
739
+ }
740
+ }, {
741
+ key: "calculatePaymentTotal",
742
+ value: function calculatePaymentTotal(payments) {
743
+ return mapPaymentItemsToOrderPayments(payments, {
744
+ includeVoided: false
745
+ }).reduce(function (sum, payment) {
746
+ var amount = new Decimal(payment.amount || 0);
747
+ var rounding = new Decimal(payment.rounding_amount || 0);
748
+ return sum.plus(amount.minus(rounding));
749
+ }, new Decimal(0));
750
+ }
751
+ }, {
752
+ key: "calculatePaidPaymentSummary",
753
+ value: function calculatePaidPaymentSummary(payments) {
754
+ var _this2 = this;
755
+ return (payments || []).reduce(function (summary, payment) {
756
+ var paymentRecord = payment;
757
+ if ((paymentRecord === null || paymentRecord === void 0 ? void 0 : paymentRecord.status) !== 'paid') return summary;
758
+ return {
759
+ customerPaidAmount: summary.customerPaidAmount.plus(paymentRecord.amount || 0),
760
+ orderPaidAmount: summary.orderPaidAmount.plus(paymentRecord.origin_amount || 0),
761
+ payServiceChargeAmount: summary.payServiceChargeAmount.plus(_this2.calculatePaymentServiceFee(paymentRecord))
762
+ };
763
+ }, {
764
+ customerPaidAmount: new Decimal(0),
765
+ orderPaidAmount: new Decimal(0),
766
+ payServiceChargeAmount: new Decimal(0)
767
+ });
768
+ }
769
+ }, {
770
+ key: "calculatePaymentServiceFee",
771
+ value: function calculatePaymentServiceFee(payment) {
772
+ if (payment.service_fee !== undefined && payment.service_fee !== null && payment.service_fee !== '') {
773
+ return new Decimal(payment.service_fee || 0);
774
+ }
775
+ var serviceCharge = payment.service_charge && _typeof(payment.service_charge) === 'object' ? payment.service_charge : {};
776
+ var percentage = new Decimal(serviceCharge.percentage || 0);
777
+ var fixedAmount = new Decimal(serviceCharge.amount || 0);
778
+ return new Decimal(payment.amount || 0).times(percentage).plus(fixedAmount);
779
+ }
780
+ }, {
781
+ key: "getPaymentTargetAmount",
782
+ value: function getPaymentTargetAmount() {
783
+ var tempOrder = this.ensureTempOrder();
784
+ var summary = this.store.summary || createEmptySummary();
785
+ if (tempOrder.is_deposit === 1) {
786
+ return new Decimal(tempOrder.deposit_amount || summary.deposit_amount || 0);
787
+ }
788
+ return new Decimal(summary.total_amount || summary.expect_amount || 0);
789
+ }
790
+ }, {
791
+ key: "ensureTempOrder",
792
+ value: function ensureTempOrder() {
793
+ if (this.store.tempOrder) {
794
+ this.ensureExternalSaleNumber(this.store.tempOrder);
795
+ return this.store.tempOrder;
796
+ }
797
+ var newOrder = this.createDefaultTempOrderInstance();
798
+ this.ensureExternalSaleNumber(newOrder);
799
+ this.store.tempOrder = newOrder;
800
+ this.persistTempOrder();
801
+ return newOrder;
802
+ }
803
+ }, {
804
+ key: "restoreOrder",
805
+ value: function restoreOrder() {
806
+ var freshTempOrder = this.createDefaultTempOrderInstance();
807
+ this.ensureExternalSaleNumber(freshTempOrder);
808
+ this.store.tempOrder = freshTempOrder;
809
+ this.store.summary = createEmptySummary();
810
+ this.store.lastOrderInfo = undefined;
811
+ this.persistTempOrder();
812
+ return freshTempOrder;
813
+ }
814
+ }, {
815
+ key: "getTempOrder",
816
+ value: function getTempOrder() {
817
+ return this.store.tempOrder;
818
+ }
819
+ }, {
820
+ key: "getOrderIdentity",
821
+ value: function getOrderIdentity() {
822
+ var _ref5, _ref6, _tempOrder$order_id2, _tempOrder$_extend;
823
+ var tempOrder = this.store.tempOrder;
824
+ if (!tempOrder) return null;
825
+ var lastOrderInfo = this.store.lastOrderInfo || {};
826
+ var orderId = (_ref5 = (_ref6 = (_tempOrder$order_id2 = tempOrder.order_id) !== null && _tempOrder$order_id2 !== void 0 ? _tempOrder$order_id2 : lastOrderInfo.order_id) !== null && _ref6 !== void 0 ? _ref6 : lastOrderInfo.id) !== null && _ref5 !== void 0 ? _ref5 : null;
827
+ return {
828
+ localId: this.cacheId || ((_tempOrder$_extend = tempOrder._extend) === null || _tempOrder$_extend === void 0 ? void 0 : _tempOrder$_extend.localId),
829
+ orderId: orderId,
830
+ externalSaleNumber: tempOrder.external_sale_number || lastOrderInfo.external_sale_number || '',
831
+ orderNumber: tempOrder.order_number || lastOrderInfo.order_number || '',
832
+ shopOrderNumber: tempOrder.shop_order_number || lastOrderInfo.shop_order_number || '',
833
+ shopFullOrderNumber: tempOrder.shop_full_order_number || lastOrderInfo.shop_full_order_number || '',
834
+ isSubmitted: orderId !== null && orderId !== undefined
835
+ };
836
+ }
837
+ }, {
838
+ key: "getOrderSyncState",
839
+ value: function getOrderSyncState() {
840
+ var tempOrder = this.store.tempOrder;
841
+ if (!tempOrder) return 'local';
842
+ if (this.store.syncState) return this.store.syncState;
843
+ if (this.store.lastOrderInfo) return 'remoteLoaded';
844
+ if (tempOrder.order_id) return 'submitted';
845
+ return 'local';
846
+ }
847
+ }, {
848
+ key: "getOrderAmountSnapshot",
849
+ value: function getOrderAmountSnapshot() {
850
+ var tempOrder = this.store.tempOrder;
851
+ if (!tempOrder) return null;
852
+ var summary = this.store.summary || createEmptySummary();
853
+ var depositAmount = tempOrder.deposit_amount || summary.deposit_amount || '0.00';
854
+ var targetAmount = tempOrder.is_deposit === 1 ? new Decimal(depositAmount || 0) : new Decimal(summary.total_amount || summary.expect_amount || 0);
855
+ var paymentTotal = this.calculatePaymentTotal(tempOrder.payments || []);
856
+ var amountGap = Decimal.max(0, targetAmount.minus(paymentTotal)).toFixed(2);
857
+ return {
858
+ isDeposit: tempOrder.is_deposit === 1 || depositAmount !== '0.00',
859
+ depositAmount: depositAmount,
860
+ expectAmount: summary.expect_amount || '0.00',
861
+ totalAmount: summary.total_amount || '0.00',
862
+ amountGap: amountGap,
863
+ summary: summary
864
+ };
865
+ }
866
+ }, {
867
+ key: "getOrderSnapshot",
868
+ value: function getOrderSnapshot() {
869
+ var _tempOrder$customer_i, _tempOrder$products;
870
+ var tempOrder = this.store.tempOrder;
871
+ if (!tempOrder) return null;
872
+ var identity = this.getOrderIdentity();
873
+ var amount = this.getOrderAmountSnapshot();
874
+ if (!identity || !amount) return null;
875
+ return {
876
+ identity: identity,
877
+ syncState: this.getOrderSyncState(),
878
+ amount: amount,
879
+ status: tempOrder.status || '',
880
+ paymentStatus: tempOrder.payment_status || '',
881
+ shippingStatus: tempOrder.shipping_status || '',
882
+ note: tempOrder.note || '',
883
+ customer: {
884
+ customerId: (_tempOrder$customer_i = tempOrder.customer_id) !== null && _tempOrder$customer_i !== void 0 ? _tempOrder$customer_i : null,
885
+ customerName: tempOrder.customer_name || '',
886
+ phone: tempOrder.phone || '',
887
+ email: tempOrder.email || ''
888
+ },
889
+ productCount: ((_tempOrder$products = tempOrder.products) === null || _tempOrder$products === void 0 ? void 0 : _tempOrder$products.length) || 0,
890
+ lastOrderInfo: this.store.lastOrderInfo,
891
+ tempOrder: tempOrder
892
+ };
893
+ }
894
+ }, {
895
+ key: "addNewOrder",
896
+ value: function () {
897
+ var _addNewOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
898
+ var tempOrder;
899
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
900
+ while (1) switch (_context9.prev = _context9.next) {
901
+ case 0:
902
+ tempOrder = this.ensureTempOrder();
903
+ this.ensureExternalSaleNumber(tempOrder);
904
+ _context9.next = 4;
905
+ return this.recalculateSummary({
906
+ createIfMissing: true
907
+ });
908
+ case 4:
909
+ this.persistTempOrder();
910
+ _context9.next = 7;
911
+ return this.saveDraft();
912
+ case 7:
913
+ return _context9.abrupt("return", tempOrder);
914
+ case 8:
915
+ case "end":
916
+ return _context9.stop();
917
+ }
918
+ }, _callee9, this);
919
+ }));
920
+ function addNewOrder() {
921
+ return _addNewOrder.apply(this, arguments);
922
+ }
923
+ return addNewOrder;
924
+ }()
925
+ }, {
926
+ key: "getOrderProducts",
927
+ value: function getOrderProducts() {
928
+ var tempOrder = this.ensureTempOrder();
929
+ return tempOrder.products;
930
+ }
931
+ }, {
932
+ key: "getProductUid",
933
+ value: function getProductUid(product) {
934
+ var metadata = product.metadata && _typeof(product.metadata) === 'object' ? product.metadata : {};
935
+ var uid = metadata.unique_identification_number || product.unique_identification_number || createUuidV4();
936
+ metadata.unique_identification_number = String(uid);
937
+ product.metadata = metadata;
938
+ return String(uid);
939
+ }
940
+ }, {
941
+ key: "ensureExtend",
942
+ value: function ensureExtend(tempOrder) {
943
+ if (!tempOrder._extend || _typeof(tempOrder._extend) !== 'object') {
944
+ tempOrder._extend = {
945
+ productsByUid: {}
946
+ };
947
+ }
948
+ if (!tempOrder._extend.productsByUid) {
949
+ tempOrder._extend.productsByUid = {};
950
+ }
951
+ return tempOrder._extend;
952
+ }
953
+ }, {
954
+ key: "captureProductRuntime",
955
+ value: function captureProductRuntime(tempOrder, rawProduct, normalizedProduct, existedUid) {
956
+ var _extend$productsByUid, _ref7, _rawProduct$_origin;
957
+ var uid = existedUid || this.getProductUid(normalizedProduct);
958
+ var extend = this.ensureExtend(tempOrder);
959
+ var existed = ((_extend$productsByUid = extend.productsByUid) === null || _extend$productsByUid === void 0 ? void 0 : _extend$productsByUid[uid]) || {};
960
+ var origin = (_ref7 = (_rawProduct$_origin = rawProduct._origin) !== null && _rawProduct$_origin !== void 0 ? _rawProduct$_origin : normalizedProduct._origin) !== null && _ref7 !== void 0 ? _ref7 : existed.origin;
961
+ extend.productsByUid[uid] = _objectSpread(_objectSpread({}, existed), origin !== undefined ? {
962
+ origin: origin
963
+ } : {});
964
+ delete normalizedProduct._origin;
965
+ delete normalizedProduct.unique_identification_number;
966
+ }
967
+ }, {
968
+ key: "createLinkedProductAndBooking",
969
+ value: function createLinkedProductAndBooking(params) {
970
+ var productMetadata = params.product.metadata && _typeof(params.product.metadata) === 'object' ? _objectSpread({}, params.product.metadata) : {};
971
+ var bookingMetadata = params.booking.metadata && _typeof(params.booking.metadata) === 'object' ? _objectSpread({}, params.booking.metadata) : {};
972
+ var productUid = String(productMetadata.unique_identification_number || params.product.unique_identification_number || createUuidV4());
973
+ var bookingUid = String(bookingMetadata.unique_identification_number || createUuidV4());
974
+ productMetadata.unique_identification_number = productUid;
975
+ bookingMetadata.unique_identification_number = bookingUid;
976
+ return {
977
+ productUid: productUid,
978
+ bookingUid: bookingUid,
979
+ product: _objectSpread(_objectSpread({}, params.product), {}, {
980
+ unique_identification_number: productUid,
981
+ metadata: _objectSpread(_objectSpread({}, productMetadata), {}, {
982
+ booking_uid: bookingUid
983
+ }),
984
+ booking_uid: bookingUid
985
+ }),
986
+ booking: _objectSpread(_objectSpread({}, params.booking), {}, {
987
+ is_all: normalizeBookingIsAll(params.booking),
988
+ product_uid: productUid,
989
+ sub_type: normalizeBookingSubType(params.booking),
990
+ metadata: bookingMetadata
991
+ })
992
+ };
993
+ }
994
+
995
+ // ─── TempOrder: 金额汇总 ───
996
+ }, {
997
+ key: "getSalesSummary",
998
+ value: function getSalesSummary() {
999
+ if (!this.salesSummaryModuleName) return null;
1000
+ return this.core.getModule(this.salesSummaryModuleName);
1001
+ }
1002
+ }, {
1003
+ key: "recalculateSummary",
1004
+ value: function () {
1005
+ var _recalculateSummary = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(options) {
1006
+ var tempOrder, salesSummary, existedSummary, paidPaymentSummary, emptySummary, salesSummaryResult, summary;
1007
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1008
+ while (1) switch (_context10.prev = _context10.next) {
1009
+ case 0:
1010
+ tempOrder = options !== null && options !== void 0 && options.createIfMissing ? this.ensureTempOrder() : this.store.tempOrder;
1011
+ if (tempOrder) {
1012
+ _context10.next = 3;
1013
+ break;
1014
+ }
1015
+ return _context10.abrupt("return", null);
1016
+ case 3:
1017
+ salesSummary = this.getSalesSummary();
1018
+ existedSummary = this.store.summary || createEmptySummary();
1019
+ paidPaymentSummary = this.calculatePaidPaymentSummary(tempOrder.payments || []);
1020
+ if (salesSummary) {
1021
+ _context10.next = 11;
1022
+ break;
1023
+ }
1024
+ emptySummary = _objectSpread(_objectSpread({}, createEmptySummary()), {}, {
1025
+ total_refund_amount: existedSummary.total_refund_amount || '0.00',
1026
+ customer_paid_amount: paidPaymentSummary.customerPaidAmount.toFixed(2),
1027
+ order_paid_amount: paidPaymentSummary.orderPaidAmount.toFixed(2),
1028
+ pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2)
1029
+ });
1030
+ this.store.summary = emptySummary;
1031
+ tempOrder.surcharge_fee = emptySummary.surcharge_fee;
1032
+ return _context10.abrupt("return", this.store.summary);
1033
+ case 11:
1034
+ _context10.next = 13;
1035
+ return salesSummary.getSummary({
1036
+ products: tempOrder.products,
1037
+ isPriceIncludeTax: tempOrder.is_price_include_tax,
1038
+ shopDiscount: tempOrder.shop_discount
1039
+ });
1040
+ case 13:
1041
+ salesSummaryResult = _context10.sent;
1042
+ summary = _objectSpread(_objectSpread({}, salesSummaryResult), {}, {
1043
+ total_refund_amount: existedSummary.total_refund_amount || '0.00',
1044
+ customer_paid_amount: paidPaymentSummary.customerPaidAmount.toFixed(2),
1045
+ order_paid_amount: paidPaymentSummary.orderPaidAmount.toFixed(2),
1046
+ pay_service_charge_amount: paidPaymentSummary.payServiceChargeAmount.toFixed(2)
1047
+ });
1048
+ this.store.summary = summary;
1049
+ if (summary.is_price_include_tax !== undefined) {
1050
+ tempOrder.is_price_include_tax = summary.is_price_include_tax;
1051
+ }
1052
+ if (typeof summary.tax_title === 'string' && summary.tax_title) {
1053
+ tempOrder.tax_title = summary.tax_title;
1054
+ }
1055
+ tempOrder.surcharge_fee = summary.surcharge_fee;
1056
+ tempOrder.surcharges = summary.surcharges || [];
1057
+ tempOrder.deposit_amount = summary.deposit_amount || '0.00';
1058
+ tempOrder.is_deposit = summary.deposit_amount !== '0.00' ? 1 : 0;
1059
+ return _context10.abrupt("return", this.store.summary);
1060
+ case 23:
1061
+ case "end":
1062
+ return _context10.stop();
1063
+ }
1064
+ }, _callee10, this);
1065
+ }));
1066
+ function recalculateSummary(_x10) {
1067
+ return _recalculateSummary.apply(this, arguments);
1068
+ }
1069
+ return recalculateSummary;
1070
+ }()
1071
+ }, {
1072
+ key: "getOrderSummary",
1073
+ value: function () {
1074
+ var _getOrderSummary = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
1075
+ var summary;
1076
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1077
+ while (1) switch (_context11.prev = _context11.next) {
1078
+ case 0:
1079
+ _context11.next = 2;
1080
+ return this.recalculateSummary({
1081
+ createIfMissing: true
1082
+ });
1083
+ case 2:
1084
+ summary = _context11.sent;
1085
+ if (summary) {
1086
+ _context11.next = 5;
1087
+ break;
1088
+ }
1089
+ return _context11.abrupt("return", createEmptySummary());
1090
+ case 5:
1091
+ this.persistTempOrder();
1092
+ return _context11.abrupt("return", summary);
1093
+ case 7:
1094
+ case "end":
1095
+ return _context11.stop();
1096
+ }
1097
+ }, _callee11, this);
1098
+ }));
1099
+ function getOrderSummary() {
1100
+ return _getOrderSummary.apply(this, arguments);
1101
+ }
1102
+ return getOrderSummary;
1103
+ }() // ─── TempOrder: 备注 ───
1104
+ }, {
1105
+ key: "updateTempOrderNote",
1106
+ value: function updateTempOrderNote(note) {
1107
+ var tempOrder = this.ensureTempOrder();
1108
+ tempOrder.note = String(note || '');
1109
+ this.persistTempOrder();
1110
+ return tempOrder.note;
1111
+ }
1112
+ }, {
1113
+ key: "getTempOrderNote",
1114
+ value: function getTempOrderNote() {
1115
+ var _this$store$tempOrder2;
1116
+ return ((_this$store$tempOrder2 = this.store.tempOrder) === null || _this$store$tempOrder2 === void 0 ? void 0 : _this$store$tempOrder2.note) || '';
1117
+ }
1118
+ }, {
1119
+ key: "updateTempOrderShopDiscount",
1120
+ value: function updateTempOrderShopDiscount(amount) {
1121
+ var tempOrder = this.ensureTempOrder();
1122
+ var discount = Decimal.max(new Decimal(Number(amount) || 0), 0).toDecimalPlaces(2).toFixed(2);
1123
+ tempOrder.shop_discount = discount;
1124
+ this.persistTempOrder();
1125
+ return tempOrder.shop_discount;
1126
+ }
1127
+ }, {
1128
+ key: "updateTempOrderBuzzer",
1129
+ value: function updateTempOrderBuzzer(buzzer) {
1130
+ var tempOrder = this.ensureTempOrder();
1131
+ tempOrder.buzzer = String(buzzer || '');
1132
+ this.persistTempOrder();
1133
+ return tempOrder.buzzer;
1134
+ }
1135
+ }, {
1136
+ key: "updateTempOrderContactsInfo",
1137
+ value: function updateTempOrderContactsInfo(contactsInfo) {
1138
+ var tempOrder = this.ensureTempOrder();
1139
+ tempOrder.contacts_info = contactsInfo && _typeof(contactsInfo) === 'object' && !Array.isArray(contactsInfo) ? contactsInfo : null;
1140
+ this.persistTempOrder();
1141
+ return tempOrder.contacts_info;
1142
+ }
1143
+
1144
+ /**
1145
+ * 更新当前 tempOrder 的客户协议字段。
1146
+ *
1147
+ * PaymentModal 只需要修改订单里的客户字段;如果外部还有客户模块需要同步,
1148
+ * 应由调用方通过回调处理,不能把外部 UI 状态写进 tempOrder。
1149
+ */
1150
+ }, {
1151
+ key: "updateTempOrderCustomer",
1152
+ value: function updateTempOrderCustomer(customer) {
1153
+ var _ref8, _ref9, _customer$customer_id, _ref10, _ref11, _ref12, _customer$customer_na, _ref13, _customer$country_cal;
1154
+ var tempOrder = this.ensureTempOrder();
1155
+ var customerId = (_ref8 = (_ref9 = (_customer$customer_id = customer.customer_id) !== null && _customer$customer_id !== void 0 ? _customer$customer_id : customer.customerId) !== null && _ref9 !== void 0 ? _ref9 : customer.id) !== null && _ref8 !== void 0 ? _ref8 : null;
1156
+ var customerName = (_ref10 = (_ref11 = (_ref12 = (_customer$customer_na = customer.customer_name) !== null && _customer$customer_na !== void 0 ? _customer$customer_na : customer.customerName) !== null && _ref12 !== void 0 ? _ref12 : customer.display_name) !== null && _ref11 !== void 0 ? _ref11 : customer.name) !== null && _ref10 !== void 0 ? _ref10 : '';
1157
+ tempOrder.customer_id = customerId === null || customerId === undefined || customerId === '' ? null : Number(customerId);
1158
+ tempOrder.customer_name = String(customerName || '');
1159
+ tempOrder.country_calling_code = String((_ref13 = (_customer$country_cal = customer.country_calling_code) !== null && _customer$country_cal !== void 0 ? _customer$country_cal : customer.countryCallingCode) !== null && _ref13 !== void 0 ? _ref13 : '');
1160
+ tempOrder.phone = String(customer.phone || '');
1161
+ tempOrder.email = String(customer.email || '');
1162
+ this.persistTempOrder();
1163
+ return {
1164
+ customerId: tempOrder.customer_id,
1165
+ customerName: tempOrder.customer_name,
1166
+ phone: tempOrder.phone,
1167
+ email: tempOrder.email
1168
+ };
1169
+ }
1170
+ }, {
1171
+ key: "setOrderCustomer",
1172
+ value: function setOrderCustomer(patch, snapshot) {
1173
+ if (!patch) {
1174
+ this.clearOrderCustomer();
1175
+ return;
1176
+ }
1177
+ var tempOrder = this.ensureTempOrder();
1178
+ tempOrder.customer_id = patch.customer_id || patch.id || null;
1179
+ tempOrder.customer_name = String(patch.customer_name || '');
1180
+ tempOrder.country_calling_code = String(patch.country_calling_code || '');
1181
+ tempOrder.phone = String(patch.phone || '');
1182
+ tempOrder.email = String(patch.email || '');
1183
+ if (snapshot !== undefined) {
1184
+ var extend = this.ensureExtend(tempOrder);
1185
+ if (snapshot === null) delete extend.customerSnapshot;else extend.customerSnapshot = cloneDeep(snapshot);
1186
+ }
1187
+ this.persistTempOrder();
1188
+ this.emitOrderCustomerChange();
1189
+ }
1190
+ }, {
1191
+ key: "getOrderCustomer",
1192
+ value: function getOrderCustomer() {
1193
+ var tempOrder = this.store.tempOrder;
1194
+ if (!tempOrder || tempOrder.customer_id === null || tempOrder.customer_id === undefined) {
1195
+ return null;
1196
+ }
1197
+ return {
1198
+ customer_id: tempOrder.customer_id,
1199
+ customer_name: tempOrder.customer_name || '',
1200
+ country_calling_code: tempOrder.country_calling_code || '',
1201
+ phone: tempOrder.phone || '',
1202
+ email: tempOrder.email || ''
1203
+ };
1204
+ }
1205
+ }, {
1206
+ key: "getOrderCustomerSnapshot",
1207
+ value: function getOrderCustomerSnapshot() {
1208
+ var _this$store$tempOrder3;
1209
+ var snapshot = (_this$store$tempOrder3 = this.store.tempOrder) === null || _this$store$tempOrder3 === void 0 || (_this$store$tempOrder3 = _this$store$tempOrder3._extend) === null || _this$store$tempOrder3 === void 0 ? void 0 : _this$store$tempOrder3.customerSnapshot;
1210
+ return snapshot ? cloneDeep(snapshot) : null;
1211
+ }
1212
+ }, {
1213
+ key: "clearOrderCustomer",
1214
+ value: function clearOrderCustomer() {
1215
+ var tempOrder = this.ensureTempOrder();
1216
+ tempOrder.customer_id = null;
1217
+ tempOrder.customer_name = '';
1218
+ tempOrder.country_calling_code = '';
1219
+ tempOrder.phone = '';
1220
+ tempOrder.email = '';
1221
+ if (tempOrder._extend) delete tempOrder._extend.customerSnapshot;
1222
+ this.persistTempOrder();
1223
+ this.core.effects.emit(OrderHooks.OnOrderCustomerChange, null);
1224
+ }
1225
+ }, {
1226
+ key: "emitOrderCustomerChange",
1227
+ value: function emitOrderCustomerChange() {
1228
+ var patch = this.getOrderCustomer();
1229
+ if (!patch) {
1230
+ this.core.effects.emit(OrderHooks.OnOrderCustomerChange, null);
1231
+ return;
1232
+ }
1233
+ var payload = {
1234
+ patch: patch,
1235
+ snapshot: this.getOrderCustomerSnapshot()
1236
+ };
1237
+ this.core.effects.emit(OrderHooks.OnOrderCustomerChange, payload);
1238
+ }
1239
+
1240
+ /**
1241
+ * 读取当前订单的 Sales 协议支付项。
1242
+ *
1243
+ * 这里返回的是 tempOrder.payments,而不是旧 PaymentModule 的本地
1244
+ * payment order / tender session。Sales checkout 以该数组为提交事实来源。
1245
+ */
1246
+ }, {
1247
+ key: "getOrderPayments",
1248
+ value: function getOrderPayments() {
1249
+ var tempOrder = this.ensureTempOrder();
1250
+ return tempOrder.payments || [];
1251
+ }
1252
+
1253
+ /**
1254
+ * 用一组支付来源覆盖当前订单支付项。
1255
+ *
1256
+ * 入参允许来自 PaymentModule 的 PaymentItem,内部统一映射为 Sales 协议:
1257
+ * uuid -> metadata.unique_payment_number,id -> custom_payment_id,
1258
+ * isSynced 等运行态字段不会进入 tempOrder.payments。
1259
+ */
1260
+ }, {
1261
+ key: "setOrderPayments",
1262
+ value: function setOrderPayments(payments) {
1263
+ var tempOrder = this.ensureTempOrder();
1264
+ tempOrder.payments = mapPaymentItemsToOrderPayments(payments);
1265
+ this.persistTempOrder();
1266
+ return tempOrder.payments;
1267
+ }
1268
+
1269
+ /** 追加单个支付项,并立即持久化当前 tempOrder。 */
1270
+ }, {
1271
+ key: "addOrderPayment",
1272
+ value: function addOrderPayment(payment) {
1273
+ var tempOrder = this.ensureTempOrder();
1274
+ var mapped = mapPaymentItemsToOrderPayments([payment]);
1275
+ tempOrder.payments = [].concat(_toConsumableArray(tempOrder.payments || []), _toConsumableArray(mapped));
1276
+ this.persistTempOrder();
1277
+ return tempOrder.payments;
1278
+ }
1279
+
1280
+ /**
1281
+ * 按支付唯一号、后端支付 ID、自定义支付方式 ID 或旧 uuid 更新支付项。
1282
+ *
1283
+ * 该方法服务 PaymentModal 的 void / 编辑场景;更新 metadata 时会做浅合并,
1284
+ * 避免覆盖 unique_payment_number、现金实付/找零等已有元数据。
1285
+ */
1286
+ }, {
1287
+ key: "updateOrderPayment",
1288
+ value: function updateOrderPayment(paymentIdentity, updates) {
1289
+ var tempOrder = this.ensureTempOrder();
1290
+ var identity = String(paymentIdentity);
1291
+ tempOrder.payments = (tempOrder.payments || []).map(function (payment) {
1292
+ var _payment$metadata;
1293
+ var uniquePaymentNumber = payment === null || payment === void 0 || (_payment$metadata = payment.metadata) === null || _payment$metadata === void 0 ? void 0 : _payment$metadata.unique_payment_number;
1294
+ var orderPaymentId = payment === null || payment === void 0 ? void 0 : payment.order_payment_id;
1295
+ var customPaymentId = payment === null || payment === void 0 ? void 0 : payment.custom_payment_id;
1296
+ var uuid = payment === null || payment === void 0 ? void 0 : payment.uuid;
1297
+ var matched = [uniquePaymentNumber, orderPaymentId, customPaymentId, uuid].some(function (value) {
1298
+ return value !== undefined && String(value) === identity;
1299
+ });
1300
+ if (!matched) return payment;
1301
+ return _objectSpread(_objectSpread(_objectSpread({}, payment), updates), {}, {
1302
+ metadata: _objectSpread(_objectSpread({}, payment.metadata || {}), updates.metadata || {})
1303
+ });
1304
+ });
1305
+ this.persistTempOrder();
1306
+ return tempOrder.payments;
1307
+ }
34
1308
 
35
- function OrderModule(name, version) {
36
- var _this;
37
- _classCallCheck(this, OrderModule);
38
- _this = _super.call(this, name || "order", version);
39
- _defineProperty(_assertThisInitialized(_this), "defaultName", 'order');
40
- _defineProperty(_assertThisInitialized(_this), "defaultVersion", '1.0.0');
41
- _defineProperty(_assertThisInitialized(_this), "store", void 0);
42
- _defineProperty(_assertThisInitialized(_this), "request", void 0);
43
- _defineProperty(_assertThisInitialized(_this), "logger", void 0);
44
- return _this;
45
- }
46
- _createClass(OrderModule, [{
47
- key: "initialize",
1309
+ /** 从当前订单支付项中移除指定支付项。 */
1310
+ }, {
1311
+ key: "deleteOrderPayment",
1312
+ value: function deleteOrderPayment(paymentIdentity) {
1313
+ var tempOrder = this.ensureTempOrder();
1314
+ var identity = String(paymentIdentity);
1315
+ tempOrder.payments = (tempOrder.payments || []).filter(function (payment) {
1316
+ var _payment$metadata2;
1317
+ var uniquePaymentNumber = payment === null || payment === void 0 || (_payment$metadata2 = payment.metadata) === null || _payment$metadata2 === void 0 ? void 0 : _payment$metadata2.unique_payment_number;
1318
+ var orderPaymentId = payment === null || payment === void 0 ? void 0 : payment.order_payment_id;
1319
+ var customPaymentId = payment === null || payment === void 0 ? void 0 : payment.custom_payment_id;
1320
+ var uuid = payment === null || payment === void 0 ? void 0 : payment.uuid;
1321
+ return ![uniquePaymentNumber, orderPaymentId, customPaymentId, uuid].some(function (value) {
1322
+ return value !== undefined && String(value) === identity;
1323
+ });
1324
+ });
1325
+ this.persistTempOrder();
1326
+ return tempOrder.payments;
1327
+ }
1328
+
1329
+ /**
1330
+ * 覆盖当前订单中的 wallet pass 支付项。
1331
+ *
1332
+ * 判断口径与 PaymentModal 保持一致:voucher_id 存在且不为 0 的支付项
1333
+ * 视为 wallet pass;其它支付项保持不变。
1334
+ */
1335
+ }, {
1336
+ key: "updateVoucherOrderPayments",
1337
+ value: function updateVoucherOrderPayments(payments) {
1338
+ var tempOrder = this.ensureTempOrder();
1339
+ var mappedVouchers = mapPaymentItemsToOrderPayments(payments).filter(function (payment) {
1340
+ return payment.voucher_id !== undefined && Number(payment.voucher_id) !== 0;
1341
+ });
1342
+ var nonVoucherPayments = (tempOrder.payments || []).filter(function (payment) {
1343
+ return payment.voucher_id === undefined || Number(payment.voucher_id) === 0;
1344
+ });
1345
+ tempOrder.payments = [].concat(_toConsumableArray(nonVoucherPayments), _toConsumableArray(mappedVouchers));
1346
+ this.persistTempOrder();
1347
+ return tempOrder.payments;
1348
+ }
1349
+
1350
+ // ─── TempOrder: 商品 CRUD ───
1351
+ }, {
1352
+ key: "addProductToOrder",
48
1353
  value: function () {
49
- var _initialize = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(core, options) {
50
- var appPlugin, app;
51
- return _regeneratorRuntime().wrap(function _callee$(_context) {
52
- while (1) switch (_context.prev = _context.next) {
1354
+ var _addProductToOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(product, booking) {
1355
+ var _this3 = this;
1356
+ var tempOrder, linked, productToAdd, incomingFingerprint, normalizedIncoming, hasIncomingGoodPass, shouldForceNewLine, matchedIndex, _targetProduct$metada, targetProduct, targetUid, normalizedProduct;
1357
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1358
+ while (1) switch (_context12.prev = _context12.next) {
53
1359
  case 0:
54
- this.core = core;
55
- this.store = options.store;
56
- this.request = this.core.getPlugin('request');
57
- appPlugin = this.core.getPlugin('app');
58
- if (appPlugin) {
59
- _context.next = 6;
1360
+ tempOrder = this.ensureTempOrder();
1361
+ linked = booking ? this.createLinkedProductAndBooking({
1362
+ product: product,
1363
+ booking: booking
1364
+ }) : null;
1365
+ productToAdd = (linked === null || linked === void 0 ? void 0 : linked.product) || product;
1366
+ incomingFingerprint = buildProductLineFingerprint(productToAdd.product_option_item, productToAdd.product_bundle);
1367
+ normalizedIncoming = normalizeOrderProduct(productToAdd);
1368
+ hasIncomingGoodPass = this.hasGoodPassDiscount(normalizedIncoming);
1369
+ shouldForceNewLine = !!booking;
1370
+ matchedIndex = hasIncomingGoodPass || shouldForceNewLine ? -1 : tempOrder.products.findIndex(function (item) {
1371
+ if (_this3.hasGoodPassDiscount(item)) return false;
1372
+ if (item.product_id !== productToAdd.product_id) return false;
1373
+ if (item.product_variant_id !== productToAdd.product_variant_id) return false;
1374
+ var existedFingerprint = buildProductLineFingerprint(item.product_option_item, item.product_bundle);
1375
+ return existedFingerprint === incomingFingerprint;
1376
+ });
1377
+ if (matchedIndex === -1) {
1378
+ this.captureProductRuntime(tempOrder, productToAdd, normalizedIncoming);
1379
+ if (linked) {
1380
+ normalizedIncoming.booking_uid = linked.bookingUid;
1381
+ normalizedIncoming.metadata = _objectSpread(_objectSpread({}, normalizedIncoming.metadata || {}), {}, {
1382
+ booking_uid: linked.bookingUid
1383
+ });
1384
+ }
1385
+ tempOrder.products.push(normalizedIncoming);
1386
+ } else {
1387
+ targetProduct = tempOrder.products[matchedIndex];
1388
+ targetUid = (_targetProduct$metada = targetProduct.metadata) === null || _targetProduct$metada === void 0 ? void 0 : _targetProduct$metada.unique_identification_number;
1389
+ normalizedProduct = normalizeOrderProduct(_objectSpread(_objectSpread({}, productToAdd), {}, {
1390
+ metadata: _objectSpread(_objectSpread({}, productToAdd.metadata || {}), {}, {
1391
+ unique_identification_number: targetUid
1392
+ })
1393
+ }));
1394
+ tempOrder.products[matchedIndex] = _objectSpread(_objectSpread(_objectSpread({}, targetProduct), normalizedProduct), {}, {
1395
+ metadata: _objectSpread(_objectSpread(_objectSpread({}, targetProduct.metadata || {}), normalizedProduct.metadata || {}), {}, {
1396
+ unique_identification_number: targetUid
1397
+ }),
1398
+ note: targetProduct.note,
1399
+ order_detail_id: targetProduct.order_detail_id,
1400
+ num: getSafeProductNum(targetProduct.num + normalizedProduct.num)
1401
+ });
1402
+ this.captureProductRuntime(tempOrder, productToAdd, tempOrder.products[matchedIndex], targetUid);
1403
+ }
1404
+ if (linked) {
1405
+ tempOrder.bookings = [].concat(_toConsumableArray(tempOrder.bookings || []), [linked.booking]);
1406
+ }
1407
+ this.applyDiscount();
1408
+ _context12.next = 13;
1409
+ return this.recalculateSummary({
1410
+ createIfMissing: true
1411
+ });
1412
+ case 13:
1413
+ this.persistTempOrder();
1414
+ return _context12.abrupt("return", tempOrder.products);
1415
+ case 15:
1416
+ case "end":
1417
+ return _context12.stop();
1418
+ }
1419
+ }, _callee12, this);
1420
+ }));
1421
+ function addProductToOrder(_x11, _x12) {
1422
+ return _addProductToOrder.apply(this, arguments);
1423
+ }
1424
+ return addProductToOrder;
1425
+ }()
1426
+ }, {
1427
+ key: "hasGoodPassDiscount",
1428
+ value: function hasGoodPassDiscount(product) {
1429
+ var _product$_extend;
1430
+ var hasMainGoodPass = (product.discount_list || []).some(function (item) {
1431
+ return (item === null || item === void 0 ? void 0 : item.type) === 'good_pass' || (item === null || item === void 0 ? void 0 : item.tag) === 'good_pass';
1432
+ });
1433
+ if (hasMainGoodPass) return true;
1434
+ var bundleDiscountList = [];
1435
+ (product.product_bundle || []).forEach(function (item) {
1436
+ bundleDiscountList.push.apply(bundleDiscountList, _toConsumableArray((item === null || item === void 0 ? void 0 : item.discount_list) || []));
1437
+ });
1438
+ ((product === null || product === void 0 || (_product$_extend = product._extend) === null || _product$_extend === void 0 || (_product$_extend = _product$_extend.other) === null || _product$_extend === void 0 ? void 0 : _product$_extend.bundle) || []).forEach(function (item) {
1439
+ bundleDiscountList.push.apply(bundleDiscountList, _toConsumableArray((item === null || item === void 0 ? void 0 : item.discount_list) || []));
1440
+ });
1441
+ return bundleDiscountList.some(function (item) {
1442
+ return (item === null || item === void 0 ? void 0 : item.type) === 'good_pass' || (item === null || item === void 0 ? void 0 : item.tag) === 'good_pass';
1443
+ });
1444
+ }
1445
+ }, {
1446
+ key: "updateProductInOrder",
1447
+ value: function () {
1448
+ var _updateProductInOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(params) {
1449
+ var _targetProduct$metada2, _metadata, _metadata2, _metadata3, _tempOrder$products$p;
1450
+ var product_id, product_variant_id, updates, unique_identification_number, product_option_item, product_bundle, tempOrder, identityLookup, productIndex, targetProduct, nextProduct, callerUpdatesTopPrice, callerUpdatesMainMeta, existedMeta;
1451
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1452
+ while (1) switch (_context13.prev = _context13.next) {
1453
+ case 0:
1454
+ product_id = params.product_id, product_variant_id = params.product_variant_id, updates = params.updates, unique_identification_number = params.unique_identification_number, product_option_item = params.product_option_item, product_bundle = params.product_bundle;
1455
+ tempOrder = this.ensureTempOrder();
1456
+ identityLookup = {
1457
+ product_id: product_id,
1458
+ product_variant_id: product_variant_id
1459
+ };
1460
+ if (unique_identification_number !== undefined) {
1461
+ identityLookup.unique_identification_number = unique_identification_number;
1462
+ }
1463
+ if (product_option_item !== undefined) identityLookup.product_option_item = product_option_item;
1464
+ if (product_bundle !== undefined) identityLookup.product_bundle = product_bundle;
1465
+ productIndex = getProductIdentityIndex(tempOrder.products, identityLookup);
1466
+ if (!(productIndex === -1)) {
1467
+ _context13.next = 9;
60
1468
  break;
61
1469
  }
62
- throw new Error('Order 模块需要 app 插件支持');
63
- case 6:
64
- app = appPlugin.getApp();
65
- this.logger = app.logger;
66
- this.logInfo('OrderModule initialized successfully');
1470
+ throw new Error('[Order] 目标商品不存在,无法更新');
67
1471
  case 9:
1472
+ targetProduct = tempOrder.products[productIndex];
1473
+ nextProduct = _objectSpread(_objectSpread(_objectSpread({}, targetProduct), updates), {}, {
1474
+ product_id: product_id,
1475
+ product_variant_id: product_variant_id,
1476
+ metadata: _objectSpread(_objectSpread(_objectSpread({}, targetProduct.metadata || {}), (updates === null || updates === void 0 ? void 0 : updates.metadata) || {}), {}, {
1477
+ unique_identification_number: ((_targetProduct$metada2 = targetProduct.metadata) === null || _targetProduct$metada2 === void 0 ? void 0 : _targetProduct$metada2.unique_identification_number) || unique_identification_number
1478
+ })
1479
+ });
1480
+ nextProduct.num = getSafeProductNum(nextProduct.num);
1481
+ // 兜底:caller 通过 updates 直接改了 selling_price / original_price 时,
1482
+ // 视为 "重新给 source-level 主价"(caller 侧旧约定仍是 main-only 单价)。
1483
+ // 清掉 metadata 里的 source_product_price / main_product_* / price_schema_version,
1484
+ // 让 normalize 把顶层 selling_price 当作 source 来重算 main_original(=source+options) /
1485
+ // main_selling / composite;否则旧 metadata 会反压顶层新值,触发口径不一致。
1486
+ // 如果 caller 走推荐路径(updates.metadata.* 显式指定主价),保留 metadata 由 normalize 认它。
1487
+ callerUpdatesTopPrice = Object.prototype.hasOwnProperty.call(updates || {}, 'selling_price') || Object.prototype.hasOwnProperty.call(updates || {}, 'original_price');
1488
+ callerUpdatesMainMeta = (updates === null || updates === void 0 || (_metadata = updates.metadata) === null || _metadata === void 0 ? void 0 : _metadata.main_product_selling_price) !== undefined || (updates === null || updates === void 0 || (_metadata2 = updates.metadata) === null || _metadata2 === void 0 ? void 0 : _metadata2.main_product_original_price) !== undefined || (updates === null || updates === void 0 || (_metadata3 = updates.metadata) === null || _metadata3 === void 0 ? void 0 : _metadata3.source_product_price) !== undefined;
1489
+ if (callerUpdatesTopPrice && !callerUpdatesMainMeta) {
1490
+ existedMeta = nextProduct.metadata || {};
1491
+ nextProduct.metadata = _objectSpread({}, existedMeta);
1492
+ delete nextProduct.metadata.source_product_price;
1493
+ delete nextProduct.metadata.main_product_selling_price;
1494
+ delete nextProduct.metadata.main_product_original_price;
1495
+ delete nextProduct.metadata.price_schema_version;
1496
+ }
1497
+ // normalizeOrderProduct 幂等:v2 metadata 存在 → 保留 main_product_* 折扣重算 composite;
1498
+ // 否则 → 把顶层 selling_price 视作 source,派生 main_product_* 并写 price_schema_version: 2。
1499
+ tempOrder.products[productIndex] = normalizeOrderProduct(nextProduct);
1500
+ this.captureProductRuntime(tempOrder, updates, tempOrder.products[productIndex], (_tempOrder$products$p = tempOrder.products[productIndex].metadata) === null || _tempOrder$products$p === void 0 ? void 0 : _tempOrder$products$p.unique_identification_number);
1501
+ this.applyDiscount();
1502
+ _context13.next = 20;
1503
+ return this.recalculateSummary({
1504
+ createIfMissing: true
1505
+ });
1506
+ case 20:
1507
+ this.persistTempOrder();
1508
+ return _context13.abrupt("return", tempOrder.products);
1509
+ case 22:
68
1510
  case "end":
69
- return _context.stop();
1511
+ return _context13.stop();
70
1512
  }
71
- }, _callee, this);
1513
+ }, _callee13, this);
72
1514
  }));
73
- function initialize(_x, _x2) {
74
- return _initialize.apply(this, arguments);
1515
+ function updateProductInOrder(_x13) {
1516
+ return _updateProductInOrder.apply(this, arguments);
75
1517
  }
76
- return initialize;
1518
+ return updateProductInOrder;
77
1519
  }()
78
- /**
79
- * 记录信息日志
80
- */
81
1520
  }, {
82
- key: "logInfo",
83
- value: function logInfo(title, metadata) {
84
- if (this.logger) {
85
- this.logger.addLog({
86
- type: 'info',
87
- title: "[OrderModule] ".concat(title),
88
- metadata: metadata || {}
89
- });
1521
+ key: "removeProductFromOrder",
1522
+ value: function () {
1523
+ var _removeProductFromOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(identity) {
1524
+ var tempOrder;
1525
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1526
+ while (1) switch (_context14.prev = _context14.next) {
1527
+ case 0:
1528
+ tempOrder = this.ensureTempOrder();
1529
+ tempOrder.products = tempOrder.products.filter(function (item) {
1530
+ return !isIdentityMatch(item, identity);
1531
+ });
1532
+ this.applyDiscount();
1533
+ _context14.next = 5;
1534
+ return this.recalculateSummary({
1535
+ createIfMissing: true
1536
+ });
1537
+ case 5:
1538
+ this.persistTempOrder();
1539
+ return _context14.abrupt("return", tempOrder.products);
1540
+ case 7:
1541
+ case "end":
1542
+ return _context14.stop();
1543
+ }
1544
+ }, _callee14, this);
1545
+ }));
1546
+ function removeProductFromOrder(_x14) {
1547
+ return _removeProductFromOrder.apply(this, arguments);
90
1548
  }
91
- }
92
-
1549
+ return removeProductFromOrder;
1550
+ }() // ─── TempOrder: 提交 ───
93
1551
  /**
94
- * 记录警告日志
1552
+ * 提交当前 Sales tempOrder。
1553
+ *
1554
+ * smallTicketDataFlag 用于 B 端 checkout 小票数据返回。PaymentModal 在支付提交时
1555
+ * 应传 1,确保 /order/sales/checkout 返回打印所需数据。
95
1556
  */
96
1557
  }, {
97
- key: "logWarning",
98
- value: function logWarning(title, metadata) {
99
- if (this.logger) {
100
- this.logger.addLog({
101
- type: 'warning',
102
- title: "[OrderModule] ".concat(title),
103
- metadata: metadata || {}
104
- });
1558
+ key: "submitTempOrder",
1559
+ value: function () {
1560
+ var _submitTempOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(params) {
1561
+ var _params$cacheId, _this$otherParams;
1562
+ var tempOrder, effectiveCacheId, hasPaymentOverride, hasPaymentStatusOverride, hasSmallTicketDataFlagOverride, enhancePayload, payload, result, _payload$payments, _payload$payments2, backendErrorResponse, submittedOrderId, resultRecord;
1563
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1564
+ while (1) switch (_context15.prev = _context15.next) {
1565
+ case 0:
1566
+ tempOrder = this.ensureTempOrder();
1567
+ this.persistTempOrder();
1568
+ effectiveCacheId = (_params$cacheId = params === null || params === void 0 ? void 0 : params.cacheId) !== null && _params$cacheId !== void 0 ? _params$cacheId : this.cacheId;
1569
+ hasPaymentOverride = (params === null || params === void 0 ? void 0 : params.payments) !== undefined;
1570
+ hasPaymentStatusOverride = (params === null || params === void 0 ? void 0 : params.paymentStatus) !== undefined;
1571
+ hasSmallTicketDataFlagOverride = (params === null || params === void 0 ? void 0 : params.smallTicketDataFlag) !== undefined;
1572
+ enhancePayload = hasPaymentOverride || hasPaymentStatusOverride || hasSmallTicketDataFlagOverride || params !== null && params !== void 0 && params.enhancePayload ? function (payload, ctx) {
1573
+ var nextPayload = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, payload), hasPaymentOverride ? {
1574
+ payments: mapPaymentItemsToOrderPayments((params === null || params === void 0 ? void 0 : params.payments) || [])
1575
+ } : {}), hasPaymentStatusOverride ? {
1576
+ payment_status: params === null || params === void 0 ? void 0 : params.paymentStatus
1577
+ } : {}), hasSmallTicketDataFlagOverride ? {
1578
+ small_ticket_data_flag: params === null || params === void 0 ? void 0 : params.smallTicketDataFlag
1579
+ } : {});
1580
+ return params !== null && params !== void 0 && params.enhancePayload ? params.enhancePayload(nextPayload, ctx) : nextPayload;
1581
+ } : undefined;
1582
+ payload = buildSubmitPayload({
1583
+ tempOrder: tempOrder,
1584
+ cacheId: effectiveCacheId,
1585
+ platform: (params === null || params === void 0 ? void 0 : params.platform) || ((_this$otherParams = this.otherParams) === null || _this$otherParams === void 0 ? void 0 : _this$otherParams.platform),
1586
+ businessCode: params === null || params === void 0 ? void 0 : params.businessCode,
1587
+ channel: params === null || params === void 0 ? void 0 : params.channel,
1588
+ type: params === null || params === void 0 ? void 0 : params.type,
1589
+ enhance: enhancePayload
1590
+ });
1591
+ _context15.next = 10;
1592
+ return this.saveDraft();
1593
+ case 10:
1594
+ _context15.prev = 10;
1595
+ this.logInfo('submitTempOrder calling sales checkout', {
1596
+ orderId: payload.order_id,
1597
+ externalSaleNumber: payload.external_sale_number,
1598
+ paymentStatus: payload.payment_status,
1599
+ paymentsCount: ((_payload$payments = payload.payments) === null || _payload$payments === void 0 ? void 0 : _payload$payments.length) || 0,
1600
+ smallTicketDataFlag: payload.small_ticket_data_flag
1601
+ });
1602
+ _context15.next = 14;
1603
+ return this.submitSalesOrder({
1604
+ query: payload
1605
+ });
1606
+ case 14:
1607
+ result = _context15.sent;
1608
+ _context15.next = 27;
1609
+ break;
1610
+ case 17:
1611
+ _context15.prev = 17;
1612
+ _context15.t0 = _context15["catch"](10);
1613
+ backendErrorResponse = this.extractSubmitErrorResponse(_context15.t0);
1614
+ if (!backendErrorResponse) {
1615
+ _context15.next = 24;
1616
+ break;
1617
+ }
1618
+ this.store.syncState = 'failed';
1619
+ this.logSubmitBackendRejected(backendErrorResponse, payload);
1620
+ return _context15.abrupt("return", backendErrorResponse);
1621
+ case 24:
1622
+ this.store.syncState = 'failed';
1623
+ this.logError('submitTempOrder failed', {
1624
+ error: _context15.t0 instanceof Error ? _context15.t0.message : String(_context15.t0),
1625
+ orderId: payload.order_id,
1626
+ externalSaleNumber: payload.external_sale_number,
1627
+ paymentStatus: payload.payment_status,
1628
+ paymentsCount: ((_payload$payments2 = payload.payments) === null || _payload$payments2 === void 0 ? void 0 : _payload$payments2.length) || 0
1629
+ });
1630
+ throw _context15.t0;
1631
+ case 27:
1632
+ if (!this.isSubmitResponseRejected(result)) {
1633
+ _context15.next = 31;
1634
+ break;
1635
+ }
1636
+ this.store.syncState = 'failed';
1637
+ this.logSubmitBackendRejected(result, payload);
1638
+ return _context15.abrupt("return", result);
1639
+ case 31:
1640
+ submittedOrderId = this.extractOrderIdFromSubmitResult(result);
1641
+ if (!(submittedOrderId !== null && submittedOrderId !== undefined)) {
1642
+ _context15.next = 37;
1643
+ break;
1644
+ }
1645
+ tempOrder.order_id = submittedOrderId;
1646
+ resultRecord = result;
1647
+ _context15.next = 37;
1648
+ return this.markLocalOrderSynced(submittedOrderId, (resultRecord === null || resultRecord === void 0 ? void 0 : resultRecord.data) || resultRecord || {});
1649
+ case 37:
1650
+ return _context15.abrupt("return", result);
1651
+ case 38:
1652
+ case "end":
1653
+ return _context15.stop();
1654
+ }
1655
+ }, _callee15, this, [[10, 17]]);
1656
+ }));
1657
+ function submitTempOrder(_x15) {
1658
+ return _submitTempOrder.apply(this, arguments);
105
1659
  }
106
- }
107
-
108
- /**
109
- * 记录错误日志
110
- */
1660
+ return submitTempOrder;
1661
+ }()
111
1662
  }, {
112
- key: "logError",
113
- value: function logError(title, metadata) {
114
- if (this.logger) {
115
- this.logger.addLog({
116
- type: 'error',
117
- title: "[OrderModule] ".concat(title),
118
- metadata: metadata || {}
119
- });
1663
+ key: "markLocalOrderSynced",
1664
+ value: function () {
1665
+ var _markLocalOrderSynced = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(orderId, remoteOrder) {
1666
+ var tempOrder;
1667
+ return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1668
+ while (1) switch (_context16.prev = _context16.next) {
1669
+ case 0:
1670
+ tempOrder = this.ensureTempOrder();
1671
+ tempOrder.order_id = orderId;
1672
+ this.store.lastOrderInfo = remoteOrder;
1673
+ this.store.syncState = 'submitted';
1674
+ this.persistTempOrder();
1675
+ _context16.next = 7;
1676
+ return this.saveDraft();
1677
+ case 7:
1678
+ case "end":
1679
+ return _context16.stop();
1680
+ }
1681
+ }, _callee16, this);
1682
+ }));
1683
+ function markLocalOrderSynced(_x16, _x17) {
1684
+ return _markLocalOrderSynced.apply(this, arguments);
120
1685
  }
1686
+ return markLocalOrderSynced;
1687
+ }()
1688
+ }, {
1689
+ key: "isSubmitResponseRejected",
1690
+ value: function isSubmitResponseRejected(response) {
1691
+ var isErrorCode = (response === null || response === void 0 ? void 0 : response.code) !== undefined && response.code !== 200 && response.code !== '200';
1692
+ var isErrorStatus = (response === null || response === void 0 ? void 0 : response.status) === false || typeof (response === null || response === void 0 ? void 0 : response.status) === 'number' && response.status >= 400;
1693
+ var isErrorSuccess = (response === null || response === void 0 ? void 0 : response.success) === false;
1694
+ return isErrorCode || isErrorStatus || isErrorSuccess;
1695
+ }
1696
+ }, {
1697
+ key: "isSubmitErrorResponse",
1698
+ value: function isSubmitErrorResponse(response) {
1699
+ if (!response || _typeof(response) !== 'object') return false;
1700
+ return this.isSubmitResponseRejected(response) || response.message !== undefined || response.msg !== undefined || response.error !== undefined;
1701
+ }
1702
+ }, {
1703
+ key: "extractSubmitErrorResponse",
1704
+ value: function extractSubmitErrorResponse(error) {
1705
+ var _error$response,
1706
+ _error$response2,
1707
+ _this4 = this;
1708
+ var candidates = [error === null || error === void 0 || (_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.data, error === null || error === void 0 ? void 0 : error.data, error === null || error === void 0 || (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.body, error === null || error === void 0 ? void 0 : error.body];
1709
+ return candidates.find(function (candidate) {
1710
+ return _this4.isSubmitErrorResponse(candidate);
1711
+ }) || null;
1712
+ }
1713
+ }, {
1714
+ key: "logSubmitBackendRejected",
1715
+ value: function logSubmitBackendRejected(response, payload) {
1716
+ var _payload$payments3;
1717
+ this.logError('submitTempOrder backend rejected', {
1718
+ response: response,
1719
+ payload: {
1720
+ order_id: payload.order_id,
1721
+ external_sale_number: payload.external_sale_number,
1722
+ payment_status: payload.payment_status,
1723
+ paymentsCount: ((_payload$payments3 = payload.payments) === null || _payload$payments3 === void 0 ? void 0 : _payload$payments3.length) || 0
1724
+ }
1725
+ });
121
1726
  }
1727
+ }, {
1728
+ key: "syncPaymentsToOrder",
1729
+ value: function () {
1730
+ var _syncPaymentsToOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(params) {
1731
+ var tempOrder, mappedPayments, paymentTotal, targetAmount, isFullyPaid, submitResult;
1732
+ return _regeneratorRuntime().wrap(function _callee17$(_context17) {
1733
+ while (1) switch (_context17.prev = _context17.next) {
1734
+ case 0:
1735
+ tempOrder = this.ensureTempOrder();
1736
+ mappedPayments = mapPaymentItemsToOrderPayments(params.payments || []);
1737
+ tempOrder.payments = mappedPayments;
1738
+ if (params.paymentStatus) tempOrder.payment_status = params.paymentStatus;
1739
+ this.persistTempOrder();
1740
+ _context17.next = 7;
1741
+ return this.saveDraft();
1742
+ case 7:
1743
+ paymentTotal = this.calculatePaymentTotal(mappedPayments);
1744
+ targetAmount = this.getPaymentTargetAmount();
1745
+ isFullyPaid = targetAmount.lte(0) ? false : paymentTotal.gte(targetAmount);
1746
+ if (!(!isFullyPaid || !params.submitWhenPaid)) {
1747
+ _context17.next = 12;
1748
+ break;
1749
+ }
1750
+ return _context17.abrupt("return", {
1751
+ isFullyPaid: isFullyPaid
1752
+ });
1753
+ case 12:
1754
+ _context17.next = 14;
1755
+ return this.submitTempOrder({
1756
+ payments: mappedPayments,
1757
+ paymentStatus: params.paymentStatus || 'paid',
1758
+ smallTicketDataFlag: params.smallTicketDataFlag
1759
+ });
1760
+ case 14:
1761
+ submitResult = _context17.sent;
1762
+ return _context17.abrupt("return", {
1763
+ isFullyPaid: isFullyPaid,
1764
+ submitResult: submitResult
1765
+ });
1766
+ case 16:
1767
+ case "end":
1768
+ return _context17.stop();
1769
+ }
1770
+ }, _callee17, this);
1771
+ }));
1772
+ function syncPaymentsToOrder(_x18) {
1773
+ return _syncPaymentsToOrder.apply(this, arguments);
1774
+ }
1775
+ return syncPaymentsToOrder;
1776
+ }()
122
1777
  }, {
123
1778
  key: "createOrder",
124
1779
  value: function createOrder(params) {
@@ -145,6 +1800,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
145
1800
  item._origin.duration = duration;
146
1801
  item._origin.sub_type = durationType;
147
1802
  }
1803
+ item._origin.sub_type = normalizeBookingSubType(item._origin);
148
1804
  var discountList = getAllDiscountList(item);
149
1805
  item._origin.product.discount_list = discountList;
150
1806
 
@@ -202,11 +1858,11 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
202
1858
  }, {
203
1859
  key: "submitOrder",
204
1860
  value: function () {
205
- var _submitOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(order) {
1861
+ var _submitOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18(order) {
206
1862
  var _order$query$cartItem, _params$bookings, _params$relation_prod;
207
1863
  var url, query, fetchUrl, params;
208
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
209
- while (1) switch (_context2.prev = _context2.next) {
1864
+ return _regeneratorRuntime().wrap(function _callee18$(_context18) {
1865
+ while (1) switch (_context18.prev = _context18.next) {
210
1866
  case 0:
211
1867
  this.logInfo('submitOrder called', {
212
1868
  url: order.url,
@@ -226,14 +1882,14 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
226
1882
  relationProductsCount: ((_params$relation_prod = params.relation_products) === null || _params$relation_prod === void 0 ? void 0 : _params$relation_prod.length) || 0,
227
1883
  scheduleDate: params.schedule_date
228
1884
  });
229
- return _context2.abrupt("return", this.request.post(fetchUrl, params));
1885
+ return _context18.abrupt("return", this.request.post(fetchUrl, params));
230
1886
  case 6:
231
1887
  case "end":
232
- return _context2.stop();
1888
+ return _context18.stop();
233
1889
  }
234
- }, _callee2, this);
1890
+ }, _callee18, this);
235
1891
  }));
236
- function submitOrder(_x3) {
1892
+ function submitOrder(_x19) {
237
1893
  return _submitOrder.apply(this, arguments);
238
1894
  }
239
1895
  return submitOrder;
@@ -241,13 +1897,13 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
241
1897
  }, {
242
1898
  key: "cancelOrder",
243
1899
  value: function () {
244
- var _cancelOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(params) {
1900
+ var _cancelOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19(params) {
245
1901
  var payload;
246
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
247
- while (1) switch (_context3.prev = _context3.next) {
1902
+ return _regeneratorRuntime().wrap(function _callee19$(_context19) {
1903
+ while (1) switch (_context19.prev = _context19.next) {
248
1904
  case 0:
249
1905
  if (!(!Array.isArray(params.order_ids) || params.order_ids.length === 0)) {
250
- _context3.next = 2;
1906
+ _context19.next = 2;
251
1907
  break;
252
1908
  }
253
1909
  throw new Error('取消订单失败:order_ids 不能为空');
@@ -263,16 +1919,16 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
263
1919
  method: 'PUT',
264
1920
  orderIdsCount: params.order_ids.length
265
1921
  });
266
- return _context3.abrupt("return", this.request.put('/order/update-status', payload, {
1922
+ return _context19.abrupt("return", this.request.put('/order/update-status', payload, {
267
1923
  isShopApi: true
268
1924
  }));
269
1925
  case 5:
270
1926
  case "end":
271
- return _context3.stop();
1927
+ return _context19.stop();
272
1928
  }
273
- }, _callee3, this);
1929
+ }, _callee19, this);
274
1930
  }));
275
- function cancelOrder(_x4) {
1931
+ function cancelOrder(_x20) {
276
1932
  return _cancelOrder.apply(this, arguments);
277
1933
  }
278
1934
  return cancelOrder;
@@ -280,19 +1936,19 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
280
1936
  }, {
281
1937
  key: "changeBookingStatus",
282
1938
  value: function () {
283
- var _changeBookingStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(params) {
1939
+ var _changeBookingStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(params) {
284
1940
  var url, payload;
285
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
286
- while (1) switch (_context4.prev = _context4.next) {
1941
+ return _regeneratorRuntime().wrap(function _callee20$(_context20) {
1942
+ while (1) switch (_context20.prev = _context20.next) {
287
1943
  case 0:
288
1944
  if (params.booking_id) {
289
- _context4.next = 2;
1945
+ _context20.next = 2;
290
1946
  break;
291
1947
  }
292
1948
  throw new Error('变更预约状态失败:booking_id 不能为空');
293
1949
  case 2:
294
1950
  if (params.appointment_status) {
295
- _context4.next = 4;
1951
+ _context20.next = 4;
296
1952
  break;
297
1953
  }
298
1954
  throw new Error('变更预约状态失败:appointment_status 不能为空');
@@ -307,38 +1963,38 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
307
1963
  bookingId: params.booking_id,
308
1964
  appointmentStatus: params.appointment_status
309
1965
  });
310
- return _context4.abrupt("return", this.request.put(url, payload, {
1966
+ return _context20.abrupt("return", this.request.put(url, payload, {
311
1967
  isShopApi: true
312
1968
  }));
313
1969
  case 8:
314
1970
  case "end":
315
- return _context4.stop();
1971
+ return _context20.stop();
316
1972
  }
317
- }, _callee4, this);
1973
+ }, _callee20, this);
318
1974
  }));
319
- function changeBookingStatus(_x5) {
1975
+ function changeBookingStatus(_x21) {
320
1976
  return _changeBookingStatus.apply(this, arguments);
321
1977
  }
322
1978
  return changeBookingStatus;
323
1979
  }()
324
1980
  /**
325
1981
  * Checkout 专用:创建订单到后端
326
- *
1982
+ *
327
1983
  * 专门为 Checkout 模块设计的订单创建方法,
328
1984
  * 直接调用 /order/checkout 接口创建订单
329
1985
  * 接收已经处理好的订单数据,无需再处理购物车
330
- *
1986
+ *
331
1987
  * @param params Checkout 订单参数(已处理的订单数据)
332
1988
  * @returns 后端返回的订单数据(包含订单ID等)
333
1989
  */
334
1990
  }, {
335
1991
  key: "createOrderByCheckout",
336
1992
  value: (function () {
337
- var _createOrderByCheckout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(params) {
1993
+ var _createOrderByCheckout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(params) {
338
1994
  var _params$payments, _params$bookings2, _params$relation_prod2, _params$payments2, _params$payments3, _params$bookings3, _params$relation_prod3, _params$payments4;
339
1995
  var onlineStorePaymentCodeList, _orderData$payments, _orderData$bookings, _orderData$relation_p, _orderData$payments2, _orderData$payments3, _orderData$bookings2, _orderData$relation_p2, _orderData$payments4, _orderData$payments5, _response$data, orderData, response;
340
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
341
- while (1) switch (_context5.prev = _context5.next) {
1996
+ return _regeneratorRuntime().wrap(function _callee21$(_context21) {
1997
+ while (1) switch (_context21.prev = _context21.next) {
342
1998
  case 0:
343
1999
  // 过滤掉由在线店铺下单的 payment 支付数据
344
2000
  onlineStorePaymentCodeList = ['WXPAY', 'WECHAT', 'ALIPAY', 'APPLE_PAY', 'CREDIT_CARD_3DS', 'CREDIT_CARD_TOKEN', 'GOOGLE_PAY', 'GOOGLE_PAY_3DS', 'CREDIT_CARD'];
@@ -372,7 +2028,7 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
372
2028
  relationProductsCount: ((_params$relation_prod3 = params.relation_products) === null || _params$relation_prod3 === void 0 ? void 0 : _params$relation_prod3.length) || 0,
373
2029
  paymentsCount: ((_params$payments4 = params.payments) === null || _params$payments4 === void 0 ? void 0 : _params$payments4.length) || 0
374
2030
  });
375
- _context5.prev = 4;
2031
+ _context21.prev = 4;
376
2032
  // 构建订单数据,设置默认值并允许 params 覆盖
377
2033
  orderData = _objectSpread({
378
2034
  sales_channel: 'my_pisel',
@@ -436,10 +2092,10 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
436
2092
  });
437
2093
 
438
2094
  // 调用后端接口
439
- _context5.next = 12;
2095
+ _context21.next = 12;
440
2096
  return this.request.post('/order/checkout', orderData);
441
2097
  case 12:
442
- response = _context5.sent;
2098
+ response = _context21.sent;
443
2099
  this.logInfo('Order API called successfully', {
444
2100
  response: response
445
2101
  });
@@ -447,26 +2103,310 @@ export var OrderModule = /*#__PURE__*/function (_BaseModule) {
447
2103
  success: !!response,
448
2104
  hasOrderId: !!(response !== null && response !== void 0 && (_response$data = response.data) !== null && _response$data !== void 0 && _response$data.order_id || response !== null && response !== void 0 && response.order_id)
449
2105
  });
450
- return _context5.abrupt("return", response);
2106
+ return _context21.abrupt("return", response);
451
2107
  case 18:
452
- _context5.prev = 18;
453
- _context5.t0 = _context5["catch"](4);
454
- console.error('[Order] createOrderByCheckout 创建订单失败:', _context5.t0);
2108
+ _context21.prev = 18;
2109
+ _context21.t0 = _context21["catch"](4);
2110
+ console.error('[Order] createOrderByCheckout 创建订单失败:', _context21.t0);
455
2111
  this.logInfo('Order API called failed', {
456
- error: _context5.t0 instanceof Error ? _context5.t0.message : String(_context5.t0)
2112
+ error: _context21.t0 instanceof Error ? _context21.t0.message : String(_context21.t0)
457
2113
  });
458
- throw _context5.t0;
2114
+ throw _context21.t0;
459
2115
  case 23:
460
2116
  case "end":
461
- return _context5.stop();
2117
+ return _context21.stop();
462
2118
  }
463
- }, _callee5, this, [[4, 18]]);
2119
+ }, _callee21, this, [[4, 18]]);
464
2120
  }));
465
- function createOrderByCheckout(_x6) {
2121
+ function createOrderByCheckout(_x22) {
466
2122
  return _createOrderByCheckout.apply(this, arguments);
467
2123
  }
468
2124
  return createOrderByCheckout;
469
2125
  }())
2126
+ }, {
2127
+ key: "submitSalesOrder",
2128
+ value: function () {
2129
+ var _submitSalesOrder = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22(params) {
2130
+ var url, query, fetchUrl;
2131
+ return _regeneratorRuntime().wrap(function _callee22$(_context22) {
2132
+ while (1) switch (_context22.prev = _context22.next) {
2133
+ case 0:
2134
+ url = params.url, query = params.query;
2135
+ fetchUrl = url || '/order/sales/checkout';
2136
+ return _context22.abrupt("return", this.request.post(fetchUrl, query, {
2137
+ customToast: function customToast() {}
2138
+ }));
2139
+ case 3:
2140
+ case "end":
2141
+ return _context22.stop();
2142
+ }
2143
+ }, _callee22, this);
2144
+ }));
2145
+ function submitSalesOrder(_x23) {
2146
+ return _submitSalesOrder.apply(this, arguments);
2147
+ }
2148
+ return submitSalesOrder;
2149
+ }()
2150
+ /**
2151
+ * 发送支付链接邮件。
2152
+ *
2153
+ * 调用前必须已经有远端 order_id。BaseSales 会在需要时先提交本地订单,
2154
+ * OrderModule 只负责校验 order_ids 并调用 /order/batch-email。
2155
+ */
2156
+ }, {
2157
+ key: "sendCustomerPayLink",
2158
+ value: (function () {
2159
+ var _sendCustomerPayLink = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23(params) {
2160
+ var _params$emails;
2161
+ var orderIds;
2162
+ return _regeneratorRuntime().wrap(function _callee23$(_context23) {
2163
+ while (1) switch (_context23.prev = _context23.next) {
2164
+ case 0:
2165
+ orderIds = params.order_ids || params.orderIds || [];
2166
+ if (orderIds.length) {
2167
+ _context23.next = 3;
2168
+ break;
2169
+ }
2170
+ throw new Error('发送支付链接前必须先提交本地订单并取得订单 ID');
2171
+ case 3:
2172
+ if ((_params$emails = params.emails) !== null && _params$emails !== void 0 && _params$emails.length) {
2173
+ _context23.next = 5;
2174
+ break;
2175
+ }
2176
+ throw new Error('发送支付链接需要至少一个邮箱');
2177
+ case 5:
2178
+ return _context23.abrupt("return", this.request.post('/order/batch-email', {
2179
+ order_ids: orderIds,
2180
+ notify_action: params.notify_action || 'order_payment_reminder',
2181
+ emails: params.emails
2182
+ }));
2183
+ case 6:
2184
+ case "end":
2185
+ return _context23.stop();
2186
+ }
2187
+ }, _callee23, this);
2188
+ }));
2189
+ function sendCustomerPayLink(_x24) {
2190
+ return _sendCustomerPayLink.apply(this, arguments);
2191
+ }
2192
+ return sendCustomerPayLink;
2193
+ }() // TODO 获取详情的接口
2194
+ )
2195
+ }, {
2196
+ key: "getOrderInfoByRemote",
2197
+ value: function () {
2198
+ var _getOrderInfoByRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24(order_id) {
2199
+ var res;
2200
+ return _regeneratorRuntime().wrap(function _callee24$(_context24) {
2201
+ while (1) switch (_context24.prev = _context24.next) {
2202
+ case 0:
2203
+ _context24.next = 2;
2204
+ return this.request.get("/order/sales/".concat(order_id), {
2205
+ with: ['products', 'scheduleEvents', 'payments', 'customer', 'summary', 'contacts_info']
2206
+ });
2207
+ case 2:
2208
+ res = _context24.sent;
2209
+ if (res.code === 200) {
2210
+ this.store.lastOrderInfo = res.data;
2211
+ }
2212
+ return _context24.abrupt("return", res);
2213
+ case 5:
2214
+ case "end":
2215
+ return _context24.stop();
2216
+ }
2217
+ }, _callee24, this);
2218
+ }));
2219
+ function getOrderInfoByRemote(_x25) {
2220
+ return _getOrderInfoByRemote.apply(this, arguments);
2221
+ }
2222
+ return getOrderInfoByRemote;
2223
+ }()
2224
+ /**
2225
+ * 把 sqlite / 后端返回的订单记录直接恢复为 tempOrder。
2226
+ *
2227
+ * 数据源应尽量返回 tempOrder 所需结构;这里仅做 SDK 运行必须字段兜底,
2228
+ * 例如数组字段、商品行唯一值、价格 metadata、summary 派生状态和 _extend。
2229
+ */
2230
+ }, {
2231
+ key: "hydrateTempOrderFromRecord",
2232
+ value: (function () {
2233
+ var _hydrateTempOrderFromRecord = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25(record, options) {
2234
+ var _this5 = this;
2235
+ var raw, defaults, nextTempOrder, TEMP_ORDER_KEYS;
2236
+ return _regeneratorRuntime().wrap(function _callee25$(_context25) {
2237
+ while (1) switch (_context25.prev = _context25.next) {
2238
+ case 0:
2239
+ raw = record && _typeof(record) === 'object' && record.data && record.order_id == null ? record.data : record || {};
2240
+ defaults = this.createDefaultTempOrderInstance();
2241
+ nextTempOrder = _objectSpread({}, defaults);
2242
+ TEMP_ORDER_KEYS = ['order_id', 'external_sale_number', 'order_number', 'shop_order_number', 'shop_full_order_number', 'type', 'business_code', 'platform', 'sales_channel', 'order_sales_channel', 'status', 'payment_status', 'shipping_status', 'customer_id', 'customer_name', 'country_calling_code', 'phone', 'email', 'customer', 'is_price_include_tax', 'tax_title', 'tax_country_code', 'currency_code', 'currency_symbol', 'currency_format', 'is_deposit', 'deposit_amount', 'shop_discount', 'surcharge_fee', 'note', 'buzzer', 'delivery_type', 'table_number', 'schedule_date', 'created_at', 'request_unique_idempotency_token'];
2243
+ TEMP_ORDER_KEYS.forEach(function (key) {
2244
+ if (raw[key] !== undefined) {
2245
+ nextTempOrder[key] = raw[key];
2246
+ }
2247
+ });
2248
+ nextTempOrder.metadata = raw.metadata && _typeof(raw.metadata) === 'object' ? _objectSpread({}, raw.metadata) : {};
2249
+ nextTempOrder.holder = raw.holder && _typeof(raw.holder) === 'object' ? _objectSpread({}, raw.holder) : null;
2250
+ nextTempOrder.products = Array.isArray(raw.products) ? raw.products.map(function (p) {
2251
+ return _this5.normalizeHydratedOrderProduct(p);
2252
+ }) : [];
2253
+ nextTempOrder.bookings = Array.isArray(raw.bookings) ? raw.bookings.map(function (b) {
2254
+ return _objectSpread(_objectSpread({}, b || {}), {}, {
2255
+ is_all: normalizeBookingIsAll(b || {}),
2256
+ sub_type: normalizeBookingSubType(b || {})
2257
+ });
2258
+ }) : [];
2259
+ nextTempOrder.payments = Array.isArray(raw.payments) ? raw.payments.map(function (p) {
2260
+ return _objectSpread({}, p || {});
2261
+ }) : [];
2262
+ nextTempOrder.surcharges = Array.isArray(raw.surcharges) ? raw.surcharges.map(function (s) {
2263
+ return _objectSpread({}, s || {});
2264
+ }) : [];
2265
+ nextTempOrder.discount_list = Array.isArray(raw.discount_list) ? raw.discount_list.map(function (d) {
2266
+ return _objectSpread({}, d || {});
2267
+ }) : [];
2268
+ nextTempOrder.relation_forms = Array.isArray(raw.relation_forms) ? raw.relation_forms.map(function (f) {
2269
+ return _objectSpread({}, f || {});
2270
+ }) : [];
2271
+ nextTempOrder.contacts = Array.isArray(raw.contacts) ? raw.contacts.map(function (c) {
2272
+ return _objectSpread({}, c || {});
2273
+ }) : [];
2274
+ nextTempOrder.contacts_info = raw.contacts_info && _typeof(raw.contacts_info) === 'object' && !Array.isArray(raw.contacts_info) ? _objectSpread({}, raw.contacts_info) : null;
2275
+ nextTempOrder._extend = raw._extend && _typeof(raw._extend) === 'object' ? _objectSpread(_objectSpread({}, raw._extend), {}, {
2276
+ productsByUid: raw._extend.productsByUid || {}
2277
+ }) : {
2278
+ productsByUid: {}
2279
+ };
2280
+ this.ensureExternalSaleNumber(nextTempOrder);
2281
+ this.store.tempOrder = nextTempOrder;
2282
+ this.store.summary = raw.summary && _typeof(raw.summary) === 'object' ? _objectSpread(_objectSpread({}, createEmptySummary()), raw.summary) : createEmptySummary();
2283
+ this.store.lastOrderInfo = raw.lastOrderInfo || raw;
2284
+ if (!(options !== null && options !== void 0 && options.recalcOnHydrate)) {
2285
+ _context25.next = 23;
2286
+ break;
2287
+ }
2288
+ _context25.next = 23;
2289
+ return this.recalculateSummary({
2290
+ createIfMissing: false
2291
+ });
2292
+ case 23:
2293
+ this.persistTempOrder();
2294
+ return _context25.abrupt("return", nextTempOrder);
2295
+ case 25:
2296
+ case "end":
2297
+ return _context25.stop();
2298
+ }
2299
+ }, _callee25, this);
2300
+ }));
2301
+ function hydrateTempOrderFromRecord(_x26, _x27) {
2302
+ return _hydrateTempOrderFromRecord.apply(this, arguments);
2303
+ }
2304
+ return hydrateTempOrderFromRecord;
2305
+ }())
2306
+ }, {
2307
+ key: "normalizeHydratedOrderProduct",
2308
+ value: function normalizeHydratedOrderProduct(product) {
2309
+ var row = _objectSpread({}, product || {});
2310
+ if (row.num === undefined && row.product_quantity !== undefined) {
2311
+ row.num = row.product_quantity;
2312
+ }
2313
+ if (!Array.isArray(row.product_option_item)) row.product_option_item = [];
2314
+ if (!Array.isArray(row.product_bundle)) row.product_bundle = [];
2315
+ if (!row.metadata || _typeof(row.metadata) !== 'object') row.metadata = {};
2316
+ var existingIdentity = row.metadata.unique_identification_number || row.unique_identification_number;
2317
+ if (!existingIdentity) {
2318
+ row.metadata.unique_identification_number = createUuidV4();
2319
+ }
2320
+ var normalized = normalizeOrderProduct(row);
2321
+ var result = _objectSpread(_objectSpread(_objectSpread({}, row), normalized), {}, {
2322
+ metadata: _objectSpread(_objectSpread({}, row.metadata), normalized.metadata)
2323
+ });
2324
+ if (result.metadata) delete result.metadata.price_schema_version;
2325
+ return result;
2326
+ }
2327
+ }, {
2328
+ key: "getLastOrderInfo",
2329
+ value: function getLastOrderInfo() {
2330
+ var _this$store;
2331
+ return (_this$store = this.store) === null || _this$store === void 0 ? void 0 : _this$store.lastOrderInfo;
2332
+ }
2333
+ }, {
2334
+ key: "getOrderInfo",
2335
+ value: function () {
2336
+ var _getOrderInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(order_id) {
2337
+ var res;
2338
+ return _regeneratorRuntime().wrap(function _callee26$(_context26) {
2339
+ while (1) switch (_context26.prev = _context26.next) {
2340
+ case 0:
2341
+ _context26.next = 2;
2342
+ return this.request.get("/order/sales/".concat(order_id), {
2343
+ with: ['products', 'scheduleEvents']
2344
+ });
2345
+ case 2:
2346
+ res = _context26.sent;
2347
+ return _context26.abrupt("return", res);
2348
+ case 4:
2349
+ case "end":
2350
+ return _context26.stop();
2351
+ }
2352
+ }, _callee26, this);
2353
+ }));
2354
+ function getOrderInfo(_x28) {
2355
+ return _getOrderInfo.apply(this, arguments);
2356
+ }
2357
+ return getOrderInfo;
2358
+ }()
2359
+ }], [{
2360
+ key: "populateSavedAmounts",
2361
+ value:
2362
+ /**
2363
+ * Populate `savedAmount` on each discount based on product-level discount details.
2364
+ * Only selected discounts get a non-zero value.
2365
+ */
2366
+ function populateSavedAmounts(productList, discountList) {
2367
+ var savedMap = new Map();
2368
+ var _iterator = _createForOfIteratorHelper(productList),
2369
+ _step;
2370
+ try {
2371
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2372
+ var product = _step.value;
2373
+ var qty = product.num || 1;
2374
+ var _iterator3 = _createForOfIteratorHelper(product.discount_list || []),
2375
+ _step3;
2376
+ try {
2377
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2378
+ var _pd$discount, _pd$metadata;
2379
+ var pd = _step3.value;
2380
+ var discountKey = ((_pd$discount = pd.discount) === null || _pd$discount === void 0 ? void 0 : _pd$discount.resource_id) || pd.id;
2381
+ if (discountKey == null) continue;
2382
+ var amount = new Decimal(pd.amount || 0).times(qty).plus(((_pd$metadata = pd.metadata) === null || _pd$metadata === void 0 ? void 0 : _pd$metadata.product_discount_difference) || 0);
2383
+ savedMap.set(discountKey, (savedMap.get(discountKey) || new Decimal(0)).plus(amount));
2384
+ }
2385
+ } catch (err) {
2386
+ _iterator3.e(err);
2387
+ } finally {
2388
+ _iterator3.f();
2389
+ }
2390
+ }
2391
+ } catch (err) {
2392
+ _iterator.e(err);
2393
+ } finally {
2394
+ _iterator.f();
2395
+ }
2396
+ var _iterator2 = _createForOfIteratorHelper(discountList),
2397
+ _step2;
2398
+ try {
2399
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2400
+ var d = _step2.value;
2401
+ var key = d.id;
2402
+ d.savedAmount = d.isSelected && key != null && savedMap.has(key) ? savedMap.get(key).toNumber() : 0;
2403
+ }
2404
+ } catch (err) {
2405
+ _iterator2.e(err);
2406
+ } finally {
2407
+ _iterator2.f();
2408
+ }
2409
+ }
470
2410
  }]);
471
2411
  return OrderModule;
472
2412
  }(BaseModule);