@artisan-commerce/shopping-cart-core 0.12.0-canary.73

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.
@@ -0,0 +1,2232 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@artisan-commerce/products')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@artisan-commerce/products'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ArtisnShoppingCart = {}, global.ArtisnProducts));
5
+ })(this, (function (exports, products) { 'use strict';
6
+
7
+ const CONSTANTS = {
8
+ PRODUCT_DATE_FORMAT: "YYYY-MM-DD hh:mm:ss.SSS",
9
+ DEFAULT_SHOPPING_CART_NAME: "default",
10
+ DEFAULT_MAX_SHOPPING_CARTS: 2
11
+ };
12
+
13
+ class ActionQueue {
14
+ constructor() {
15
+ this.queue = [];
16
+ }
17
+ get length() {
18
+ return this.queue.length;
19
+ }
20
+ enqueue(newItem) {
21
+ this.queue.push(newItem);
22
+ }
23
+ dequeue() {
24
+ return this.queue.shift();
25
+ }
26
+ }
27
+
28
+ class EventLoop {
29
+ constructor() {
30
+ this.running = false;
31
+ }
32
+ async run() {
33
+ const { queue } = getState();
34
+ const next = queue.dequeue();
35
+ if (!next) {
36
+ this.running = false;
37
+ return;
38
+ }
39
+ return await next();
40
+ }
41
+ get isRunning() {
42
+ return this.running;
43
+ }
44
+ async start() {
45
+ this.running = true;
46
+ while (this.running) {
47
+ await this.run();
48
+ }
49
+ }
50
+ }
51
+
52
+ var __defProp$i = Object.defineProperty;
53
+ var __getOwnPropSymbols$i = Object.getOwnPropertySymbols;
54
+ var __hasOwnProp$i = Object.prototype.hasOwnProperty;
55
+ var __propIsEnum$i = Object.prototype.propertyIsEnumerable;
56
+ var __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
57
+ var __spreadValues$i = (a, b) => {
58
+ for (var prop in b || (b = {}))
59
+ if (__hasOwnProp$i.call(b, prop))
60
+ __defNormalProp$i(a, prop, b[prop]);
61
+ if (__getOwnPropSymbols$i)
62
+ for (var prop of __getOwnPropSymbols$i(b)) {
63
+ if (__propIsEnum$i.call(b, prop))
64
+ __defNormalProp$i(a, prop, b[prop]);
65
+ }
66
+ return a;
67
+ };
68
+ const { DEFAULT_SHOPPING_CART_NAME: DEFAULT_SHOPPING_CART_NAME$2, DEFAULT_MAX_SHOPPING_CARTS } = CONSTANTS;
69
+ const initialState = {
70
+ accountId: void 0,
71
+ customerId: void 0,
72
+ activeShoppingCart: DEFAULT_SHOPPING_CART_NAME$2,
73
+ maxShoppingCarts: DEFAULT_MAX_SHOPPING_CARTS,
74
+ wallets: {},
75
+ anonymous: false,
76
+ initialized: false,
77
+ queue: new ActionQueue(),
78
+ eventLoop: new EventLoop(),
79
+ debug: false
80
+ };
81
+ Object.freeze(initialState);
82
+ let state = __spreadValues$i({}, initialState);
83
+ Object.seal(state);
84
+ const setState = (overrides) => {
85
+ state = __spreadValues$i(__spreadValues$i({}, state), overrides);
86
+ };
87
+ const getState = () => {
88
+ return __spreadValues$i({}, state);
89
+ };
90
+
91
+ var __defProp$h = Object.defineProperty;
92
+ var __defProps$b = Object.defineProperties;
93
+ var __getOwnPropDescs$b = Object.getOwnPropertyDescriptors;
94
+ var __getOwnPropSymbols$h = Object.getOwnPropertySymbols;
95
+ var __hasOwnProp$h = Object.prototype.hasOwnProperty;
96
+ var __propIsEnum$h = Object.prototype.propertyIsEnumerable;
97
+ var __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
98
+ var __spreadValues$h = (a, b) => {
99
+ for (var prop in b || (b = {}))
100
+ if (__hasOwnProp$h.call(b, prop))
101
+ __defNormalProp$h(a, prop, b[prop]);
102
+ if (__getOwnPropSymbols$h)
103
+ for (var prop of __getOwnPropSymbols$h(b)) {
104
+ if (__propIsEnum$h.call(b, prop))
105
+ __defNormalProp$h(a, prop, b[prop]);
106
+ }
107
+ return a;
108
+ };
109
+ var __spreadProps$b = (a, b) => __defProps$b(a, __getOwnPropDescs$b(b));
110
+ const defaultSort = (a, b) => {
111
+ if (a > b) {
112
+ return 1;
113
+ } else if (b > a) {
114
+ return -1;
115
+ } else {
116
+ return 0;
117
+ }
118
+ };
119
+ const sortByField = (field, a, b) => {
120
+ const idA = a[field];
121
+ const idB = b[field];
122
+ if (idA > idB) {
123
+ return 1;
124
+ } else if (idB > idA) {
125
+ return -1;
126
+ } else {
127
+ return 0;
128
+ }
129
+ };
130
+ const sortByProductId = (a, b) => {
131
+ return sortByField("productId", a, b);
132
+ };
133
+ const sortByQuestionId = (a, b) => {
134
+ return sortByField("questionId", a, b);
135
+ };
136
+ const logError = (message) => {
137
+ if (process.env.NODE_ENV === "production") {
138
+ console.error(message);
139
+ } else {
140
+ throw new Error(message);
141
+ }
142
+ };
143
+ const logDebug = (message) => {
144
+ const { debug } = getState();
145
+ if (!debug)
146
+ return;
147
+ console.warn(message);
148
+ };
149
+ const reuseGlobalConfig = (config) => {
150
+ const { debug: configDebug } = config != null ? config : {};
151
+ const { store: configStore } = config != null ? config : {};
152
+ const { accountId: configAccountId } = config != null ? config : {};
153
+ const { anonymous: configAnonymous } = config != null ? config : {};
154
+ const { customerId: configCustomerId } = config != null ? config : {};
155
+ const { shoppingCartName: configCartName } = config != null ? config : {};
156
+ const { maxShoppingCarts: configMaxShoppingCarts } = config != null ? config : {};
157
+ const { accountId: globalAccountId } = getState();
158
+ const { customerId: globalCustomerId } = getState();
159
+ const { store: globalStore, anonymous: globalAnonymous } = getState();
160
+ const { activeShoppingCart: globalCartName } = getState();
161
+ const { maxShoppingCarts: globalMaxShoppingCarts } = getState();
162
+ const { debug: globalDebug } = getState();
163
+ const accountId = configAccountId != null ? configAccountId : globalAccountId;
164
+ const customerId = configCustomerId != null ? configCustomerId : globalCustomerId;
165
+ const prunedConfigStore = configStore ? __spreadProps$b(__spreadValues$h({}, configStore), { polygons: null }) : void 0;
166
+ const store = prunedConfigStore != null ? prunedConfigStore : globalStore;
167
+ const shoppingCartName = configCartName != null ? configCartName : globalCartName;
168
+ const maxShoppingCarts = configMaxShoppingCarts != null ? configMaxShoppingCarts : globalMaxShoppingCarts;
169
+ const anonymous = configAnonymous != null ? configAnonymous : globalAnonymous;
170
+ const debug = configDebug != null ? configDebug : globalDebug;
171
+ return __spreadProps$b(__spreadValues$h({}, config), {
172
+ shoppingCartName,
173
+ customerId,
174
+ store,
175
+ accountId,
176
+ anonymous,
177
+ maxShoppingCarts,
178
+ debug
179
+ });
180
+ };
181
+
182
+ var __defProp$g = Object.defineProperty;
183
+ var __defProps$a = Object.defineProperties;
184
+ var __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;
185
+ var __getOwnPropSymbols$g = Object.getOwnPropertySymbols;
186
+ var __hasOwnProp$g = Object.prototype.hasOwnProperty;
187
+ var __propIsEnum$g = Object.prototype.propertyIsEnumerable;
188
+ var __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
189
+ var __spreadValues$g = (a, b) => {
190
+ for (var prop in b || (b = {}))
191
+ if (__hasOwnProp$g.call(b, prop))
192
+ __defNormalProp$g(a, prop, b[prop]);
193
+ if (__getOwnPropSymbols$g)
194
+ for (var prop of __getOwnPropSymbols$g(b)) {
195
+ if (__propIsEnum$g.call(b, prop))
196
+ __defNormalProp$g(a, prop, b[prop]);
197
+ }
198
+ return a;
199
+ };
200
+ var __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
201
+ const { DEFAULT_SHOPPING_CART_NAME: DEFAULT_SHOPPING_CART_NAME$1 } = CONSTANTS;
202
+ const initShoppingCart = (config = {}) => {
203
+ const { initialized } = getState();
204
+ if (initialized) {
205
+ logDebug(`initShoppingCart has been called more than once.
206
+ This behavior will very likely result in unexpected outcomes so its
207
+ call was skipped. Please make sure initShoppingCart is only called once`);
208
+ return;
209
+ }
210
+ const { shoppingCartName } = config;
211
+ setState(__spreadProps$a(__spreadValues$g({}, config), {
212
+ activeShoppingCart: shoppingCartName != null ? shoppingCartName : DEFAULT_SHOPPING_CART_NAME$1
213
+ }));
214
+ const isServer = typeof window === "undefined";
215
+ if (!isServer)
216
+ setState({ initialized: true });
217
+ };
218
+ const closeShoppingCart = () => {
219
+ setState(__spreadValues$g({}, initialState));
220
+ };
221
+
222
+ var __defProp$f = Object.defineProperty;
223
+ var __getOwnPropSymbols$f = Object.getOwnPropertySymbols;
224
+ var __hasOwnProp$f = Object.prototype.hasOwnProperty;
225
+ var __propIsEnum$f = Object.prototype.propertyIsEnumerable;
226
+ var __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
227
+ var __spreadValues$f = (a, b) => {
228
+ for (var prop in b || (b = {}))
229
+ if (__hasOwnProp$f.call(b, prop))
230
+ __defNormalProp$f(a, prop, b[prop]);
231
+ if (__getOwnPropSymbols$f)
232
+ for (var prop of __getOwnPropSymbols$f(b)) {
233
+ if (__propIsEnum$f.call(b, prop))
234
+ __defNormalProp$f(a, prop, b[prop]);
235
+ }
236
+ return a;
237
+ };
238
+ const getStore = (storeData, stores) => {
239
+ const { storeId } = storeData != null ? storeData : {};
240
+ return __spreadValues$f(__spreadValues$f({}, storeData), stores[storeId]);
241
+ };
242
+ const checkInit = () => getState().initialized;
243
+ const cleanShoppingCart = (shoppingCart, product) => {
244
+ const { benefits } = shoppingCart;
245
+ if (!(benefits == null ? void 0 : benefits.length))
246
+ return shoppingCart;
247
+ const benefit = benefits.find((benefit2) => {
248
+ if (!product)
249
+ return true;
250
+ const { type } = benefit2;
251
+ if (type !== "PRODUCT")
252
+ return void 0;
253
+ if (!Array.isArray(benefit2.award))
254
+ return void 0;
255
+ return benefit2.award.find((award) => award.productId.toString() === product.productId);
256
+ });
257
+ if (!benefit)
258
+ return shoppingCart;
259
+ delete shoppingCart.benefits;
260
+ delete shoppingCart.benefitsHash;
261
+ return shoppingCart;
262
+ };
263
+
264
+ const getShoppingCart = async (builders, config) => {
265
+ const { getShoppingCartNode } = builders != null ? builders : {};
266
+ return new Promise((resolve, reject) => {
267
+ const action = async () => {
268
+ try {
269
+ const { shoppingCartName } = reuseGlobalConfig(config);
270
+ const shoppingCartNode = await getShoppingCartNode(config);
271
+ if (!shoppingCartNode || !checkInit()) {
272
+ resolve(null);
273
+ return null;
274
+ }
275
+ setState({ activeShoppingCart: shoppingCartName });
276
+ const shoppingCart = shoppingCartNode.data();
277
+ resolve(shoppingCart);
278
+ return shoppingCart;
279
+ } catch (e) {
280
+ reject(e);
281
+ return null;
282
+ }
283
+ };
284
+ const { eventLoop, queue } = getState();
285
+ queue.enqueue(action);
286
+ if (!eventLoop.isRunning)
287
+ eventLoop.start();
288
+ });
289
+ };
290
+
291
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
292
+
293
+ var dayjs_min = {exports: {}};
294
+
295
+ (function (module, exports) {
296
+ !function(t,e){module.exports=e();}(commonjsGlobal,(function(){var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",f="month",h="quarter",c="year",d="date",$="Invalid Date",l=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_")},m=function(t,e,n){var r=String(t);return !r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},g={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return (e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return -t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,f),s=n-i<0,u=e.clone().add(r+(s?-1:1),f);return +(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return {M:f,y:c,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:h}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},v="en",D={};D[v]=M;var p=function(t){return t instanceof _},S=function t(e,n,r){var i;if(!e)return v;if("string"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split("-");if(!i&&u.length>1)return t(u[0])}else {var a=e.name;D[a]=e,i=a;}return !r&&i&&(v=i),i||!r&&v},w=function(t,e){if(p(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},O=g;O.l=S,O.i=p,O.w=function(t,e){return w(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=S(t.locale,null,!0),this.parse(t);}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(O.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match(l);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.$x=t.x||{},this.init();},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds();},m.$utils=function(){return O},m.isValid=function(){return !(this.$d.toString()===$)},m.isSame=function(t,e){var n=w(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return w(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<w(t)},m.$g=function(t,e,n){return O.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!O.u(e)||e,h=O.p(t),$=function(t,e){var i=O.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},l=function(t,e){return O.w(n.toDate()[t].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,g="set"+(this.$u?"UTC":"");switch(h){case c:return r?$(1,0):$(31,11);case f:return r?$(1,M):$(0,M+1);case o:var v=this.$locale().weekStart||0,D=(y<v?y+7:y)-v;return $(r?m-D:m+(6-D),M);case a:case d:return l(g+"Hours",0);case u:return l(g+"Minutes",1);case s:return l(g+"Seconds",2);case i:return l(g+"Milliseconds",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=O.p(t),h="set"+(this.$u?"UTC":""),$=(n={},n[a]=h+"Date",n[d]=h+"Date",n[f]=h+"Month",n[c]=h+"FullYear",n[u]=h+"Hours",n[s]=h+"Minutes",n[i]=h+"Seconds",n[r]=h+"Milliseconds",n)[o],l=o===a?this.$D+(e-this.$W):e;if(o===f||o===c){var y=this.clone().set(d,1);y.$d[$](l),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d;}else $&&this.$d[$](l);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[O.p(t)]()},m.add=function(r,h){var d,$=this;r=Number(r);var l=O.p(h),y=function(t){var e=w($);return O.w(e.date(e.date()+Math.round(t*r)),$)};if(l===f)return this.set(f,this.$M+r);if(l===c)return this.set(c,this.$y+r);if(l===a)return y(1);if(l===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[l]||1,m=this.$d.getTime()+r*M;return O.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||$;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=O.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,f=n.months,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},c=function(t){return O.s(s%12||12,t,"0")},d=n.meridiem||function(t,e,n){var r=t<12?"AM":"PM";return n?r.toLowerCase():r},l={YY:String(this.$y).slice(-2),YYYY:this.$y,M:a+1,MM:O.s(a+1,2,"0"),MMM:h(n.monthsShort,a,f,3),MMMM:h(f,a),D:this.$D,DD:O.s(this.$D,2,"0"),d:String(this.$W),dd:h(n.weekdaysMin,this.$W,o,2),ddd:h(n.weekdaysShort,this.$W,o,3),dddd:o[this.$W],H:String(s),HH:O.s(s,2,"0"),h:c(1),hh:c(2),a:d(s,u,!0),A:d(s,u,!1),m:String(u),mm:O.s(u,2,"0"),s:String(this.$s),ss:O.s(this.$s,2,"0"),SSS:O.s(this.$ms,3,"0"),Z:i};return r.replace(y,(function(t,e){return e||l[t]||i.replace(":","")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,$){var l,y=O.p(d),M=w(r),m=(M.utcOffset()-this.utcOffset())*e,g=this-M,v=O.m(this,M);return v=(l={},l[c]=v/12,l[f]=v,l[h]=v/3,l[o]=(g-m)/6048e5,l[a]=(g-m)/864e5,l[u]=g/n,l[s]=g/e,l[i]=g/t,l)[y]||g,$?v:O.a(v)},m.daysInMonth=function(){return this.endOf(f).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=S(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return O.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),T=_.prototype;return w.prototype=T,[["$ms",r],["$s",i],["$m",s],["$H",u],["$W",a],["$M",f],["$y",c],["$D",d]].forEach((function(t){T[t[1]]=function(e){return this.$g(e,t[0],t[1])};})),w.extend=function(t,e){return t.$i||(t(e,_,w),t.$i=!0),w},w.locale=S,w.isDayjs=p,w.unix=function(t){return w(1e3*t)},w.en=D[v],w.Ls=D,w.p={},w}));
297
+ }(dayjs_min));
298
+
299
+ var dayjs = dayjs_min.exports;
300
+
301
+ const checkAccountId = (accountId, message = "") => {
302
+ const { accountId: globalAccountId } = getState();
303
+ if (typeof accountId === "undefined" && typeof globalAccountId === "undefined") {
304
+ throw new Error(`AccountId must be defined. Either provide a global accountId or at the function call level. ${message}`);
305
+ }
306
+ };
307
+ const checkCustomerId = (customerId, message = "") => {
308
+ const { customerId: globalCustomerId } = getState();
309
+ if (typeof customerId === "undefined" && typeof globalCustomerId === "undefined") {
310
+ throw new Error(`CustomerId must be defined. Either provide a global customerId or at the function call level. ${message}`);
311
+ }
312
+ };
313
+ const checkInitialized = () => {
314
+ const { initialized } = getState();
315
+ if (!initialized) {
316
+ throw new Error(`Shopping cart not initialized. Make sure initShoppingCart has been called.`);
317
+ }
318
+ };
319
+ const checkStoreId = (store, message = "") => {
320
+ const { store: globalStore } = getState();
321
+ if (typeof store === "undefined" && typeof globalStore === "undefined") {
322
+ throw new Error(`Store must be defined. Either provide a global store or at the function call level. ${message}`);
323
+ }
324
+ };
325
+ const checkApiURL = (apiURL, message = "") => {
326
+ if (typeof apiURL === "undefined") {
327
+ throw new Error(`ApiURL must be defined. Either provide a global ApiURL or at the function call level. ${message}`);
328
+ }
329
+ };
330
+ const checkMinimumConfigProvided = (config = {}) => {
331
+ const { accountId, customerId } = config;
332
+ checkAccountId(accountId);
333
+ checkCustomerId(customerId);
334
+ };
335
+ const checkBenefitConfigProvided = (wallets, cartName, config) => {
336
+ const { benefitId } = config != null ? config : {};
337
+ const activeWallet = wallets[cartName];
338
+ const benefits = activeWallet == null ? void 0 : activeWallet.benefits;
339
+ checkBenefitId(benefitId);
340
+ if (!activeWallet || !benefits) {
341
+ return `No benefits wallet available for ${cartName}, you probably forgot to call listenBenefitsWallet beforehand.`;
342
+ }
343
+ };
344
+ const checkBenefitId = (benefitId) => {
345
+ if (typeof benefitId !== "undefined")
346
+ return;
347
+ throw new Error(`BenefitId must be defined. Provide it at the function call level.`);
348
+ };
349
+ const checkVendorId = (vendorId, message = "") => {
350
+ if (typeof vendorId === "undefined") {
351
+ throw new Error(`VendorId must be defined. Provide a global vendorId at the function call level. ${message}`);
352
+ }
353
+ };
354
+ const checkMinimumFetchWalletConfigProvided = (config) => {
355
+ const { customerId } = config != null ? config : {};
356
+ checkCustomerId(customerId);
357
+ };
358
+ const checkAuthToken = (authToken) => {
359
+ if (!authToken) {
360
+ throw new Error(`No auth token provided. Please make sure you provide one globally or a the function level call. You may included it in the Authorization header.`);
361
+ }
362
+ const validAuthToken = authToken.startsWith("Bearer ");
363
+ if (!validAuthToken) {
364
+ throw new Error(`The provided auth token is invalid. Please provide a valid one.`);
365
+ }
366
+ };
367
+ const checkStoreCouponDetailConfig = (config, message = "") => {
368
+ const { countryId, couponId } = config;
369
+ if (typeof countryId === "undefined" || typeof couponId === "undefined") {
370
+ throw new Error(`Country id or coupon id must be defined. Provide those params at the function call level. ${message}`);
371
+ }
372
+ };
373
+
374
+ const checkProductAmount = (amount) => {
375
+ if (typeof amount !== "number") {
376
+ throw new Error("Invalid amount received, please make sure you include a valid amount.");
377
+ }
378
+ if (amount < 0) {
379
+ throw new Error(`Cannot receive a negative amount of an item. Please ensure you have added a proper amount of items.`);
380
+ }
381
+ if (amount === 0) {
382
+ throw new Error("Attempting to pass 0 amount. This might indicate a problem with your code. Please ensure you have added a proper amount of items.");
383
+ }
384
+ };
385
+ const checkModifyProductConfig = (config) => {
386
+ const { store, amount } = config;
387
+ checkStoreId(store);
388
+ checkProductAmount(amount);
389
+ };
390
+ const checkRemoveProductConfig = (config) => {
391
+ const { store } = config;
392
+ checkStoreId(store);
393
+ };
394
+ const checkReplaceProductConfig = (config) => {
395
+ const { store } = config;
396
+ checkStoreId(store);
397
+ };
398
+
399
+ var sha1$1 = {exports: {}};
400
+
401
+ var crypt = {exports: {}};
402
+
403
+ (function() {
404
+ var base64map
405
+ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
406
+
407
+ crypt$1 = {
408
+ // Bit-wise rotation left
409
+ rotl: function(n, b) {
410
+ return (n << b) | (n >>> (32 - b));
411
+ },
412
+
413
+ // Bit-wise rotation right
414
+ rotr: function(n, b) {
415
+ return (n << (32 - b)) | (n >>> b);
416
+ },
417
+
418
+ // Swap big-endian to little-endian and vice versa
419
+ endian: function(n) {
420
+ // If number given, swap endian
421
+ if (n.constructor == Number) {
422
+ return crypt$1.rotl(n, 8) & 0x00FF00FF | crypt$1.rotl(n, 24) & 0xFF00FF00;
423
+ }
424
+
425
+ // Else, assume array and swap all items
426
+ for (var i = 0; i < n.length; i++)
427
+ n[i] = crypt$1.endian(n[i]);
428
+ return n;
429
+ },
430
+
431
+ // Generate an array of any length of random bytes
432
+ randomBytes: function(n) {
433
+ for (var bytes = []; n > 0; n--)
434
+ bytes.push(Math.floor(Math.random() * 256));
435
+ return bytes;
436
+ },
437
+
438
+ // Convert a byte array to big-endian 32-bit words
439
+ bytesToWords: function(bytes) {
440
+ for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
441
+ words[b >>> 5] |= bytes[i] << (24 - b % 32);
442
+ return words;
443
+ },
444
+
445
+ // Convert big-endian 32-bit words to a byte array
446
+ wordsToBytes: function(words) {
447
+ for (var bytes = [], b = 0; b < words.length * 32; b += 8)
448
+ bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
449
+ return bytes;
450
+ },
451
+
452
+ // Convert a byte array to a hex string
453
+ bytesToHex: function(bytes) {
454
+ for (var hex = [], i = 0; i < bytes.length; i++) {
455
+ hex.push((bytes[i] >>> 4).toString(16));
456
+ hex.push((bytes[i] & 0xF).toString(16));
457
+ }
458
+ return hex.join('');
459
+ },
460
+
461
+ // Convert a hex string to a byte array
462
+ hexToBytes: function(hex) {
463
+ for (var bytes = [], c = 0; c < hex.length; c += 2)
464
+ bytes.push(parseInt(hex.substr(c, 2), 16));
465
+ return bytes;
466
+ },
467
+
468
+ // Convert a byte array to a base-64 string
469
+ bytesToBase64: function(bytes) {
470
+ for (var base64 = [], i = 0; i < bytes.length; i += 3) {
471
+ var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
472
+ for (var j = 0; j < 4; j++)
473
+ if (i * 8 + j * 6 <= bytes.length * 8)
474
+ base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
475
+ else
476
+ base64.push('=');
477
+ }
478
+ return base64.join('');
479
+ },
480
+
481
+ // Convert a base-64 string to a byte array
482
+ base64ToBytes: function(base64) {
483
+ // Remove non-base-64 characters
484
+ base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');
485
+
486
+ for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
487
+ imod4 = ++i % 4) {
488
+ if (imod4 == 0) continue;
489
+ bytes.push(((base64map.indexOf(base64.charAt(i - 1))
490
+ & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
491
+ | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
492
+ }
493
+ return bytes;
494
+ }
495
+ };
496
+
497
+ crypt.exports = crypt$1;
498
+ })();
499
+
500
+ var charenc = {
501
+ // UTF-8 encoding
502
+ utf8: {
503
+ // Convert a string to a byte array
504
+ stringToBytes: function(str) {
505
+ return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
506
+ },
507
+
508
+ // Convert a byte array to a string
509
+ bytesToString: function(bytes) {
510
+ return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));
511
+ }
512
+ },
513
+
514
+ // Binary encoding
515
+ bin: {
516
+ // Convert a string to a byte array
517
+ stringToBytes: function(str) {
518
+ for (var bytes = [], i = 0; i < str.length; i++)
519
+ bytes.push(str.charCodeAt(i) & 0xFF);
520
+ return bytes;
521
+ },
522
+
523
+ // Convert a byte array to a string
524
+ bytesToString: function(bytes) {
525
+ for (var str = [], i = 0; i < bytes.length; i++)
526
+ str.push(String.fromCharCode(bytes[i]));
527
+ return str.join('');
528
+ }
529
+ }
530
+ };
531
+
532
+ var charenc_1 = charenc;
533
+
534
+ (function() {
535
+ var crypt$1 = crypt.exports,
536
+ utf8 = charenc_1.utf8,
537
+ bin = charenc_1.bin,
538
+
539
+ // The core
540
+ sha1 = function (message) {
541
+ // Convert to byte array
542
+ if (message.constructor == String)
543
+ message = utf8.stringToBytes(message);
544
+ else if (typeof Buffer !== 'undefined' && typeof Buffer.isBuffer == 'function' && Buffer.isBuffer(message))
545
+ message = Array.prototype.slice.call(message, 0);
546
+ else if (!Array.isArray(message))
547
+ message = message.toString();
548
+
549
+ // otherwise assume byte array
550
+
551
+ var m = crypt$1.bytesToWords(message),
552
+ l = message.length * 8,
553
+ w = [],
554
+ H0 = 1732584193,
555
+ H1 = -271733879,
556
+ H2 = -1732584194,
557
+ H3 = 271733878,
558
+ H4 = -1009589776;
559
+
560
+ // Padding
561
+ m[l >> 5] |= 0x80 << (24 - l % 32);
562
+ m[((l + 64 >>> 9) << 4) + 15] = l;
563
+
564
+ for (var i = 0; i < m.length; i += 16) {
565
+ var a = H0,
566
+ b = H1,
567
+ c = H2,
568
+ d = H3,
569
+ e = H4;
570
+
571
+ for (var j = 0; j < 80; j++) {
572
+
573
+ if (j < 16)
574
+ w[j] = m[i + j];
575
+ else {
576
+ var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
577
+ w[j] = (n << 1) | (n >>> 31);
578
+ }
579
+
580
+ var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
581
+ j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
582
+ j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
583
+ j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
584
+ (H1 ^ H2 ^ H3) - 899497514);
585
+
586
+ H4 = H3;
587
+ H3 = H2;
588
+ H2 = (H1 << 30) | (H1 >>> 2);
589
+ H1 = H0;
590
+ H0 = t;
591
+ }
592
+
593
+ H0 += a;
594
+ H1 += b;
595
+ H2 += c;
596
+ H3 += d;
597
+ H4 += e;
598
+ }
599
+
600
+ return [H0, H1, H2, H3, H4];
601
+ },
602
+
603
+ // Public API
604
+ api = function (message, options) {
605
+ var digestbytes = crypt$1.wordsToBytes(sha1(message));
606
+ return options && options.asBytes ? digestbytes :
607
+ options && options.asString ? bin.bytesToString(digestbytes) :
608
+ crypt$1.bytesToHex(digestbytes);
609
+ };
610
+
611
+ api._blocksize = 16;
612
+ api._digestsize = 20;
613
+
614
+ sha1$1.exports = api;
615
+ })();
616
+
617
+ var sha1 = sha1$1.exports;
618
+
619
+ var __defProp$e = Object.defineProperty;
620
+ var __defProps$9 = Object.defineProperties;
621
+ var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
622
+ var __getOwnPropSymbols$e = Object.getOwnPropertySymbols;
623
+ var __hasOwnProp$e = Object.prototype.hasOwnProperty;
624
+ var __propIsEnum$e = Object.prototype.propertyIsEnumerable;
625
+ var __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
626
+ var __spreadValues$e = (a, b) => {
627
+ for (var prop in b || (b = {}))
628
+ if (__hasOwnProp$e.call(b, prop))
629
+ __defNormalProp$e(a, prop, b[prop]);
630
+ if (__getOwnPropSymbols$e)
631
+ for (var prop of __getOwnPropSymbols$e(b)) {
632
+ if (__propIsEnum$e.call(b, prop))
633
+ __defNormalProp$e(a, prop, b[prop]);
634
+ }
635
+ return a;
636
+ };
637
+ var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
638
+ const { toCartProduct: toCartProduct$4 } = products.transformers;
639
+ const { divideProductQA: divideProductQA$3 } = products.modifierUtils;
640
+ const getProductHash = (product) => {
641
+ const resetedProduct = divideProductQA$3(product);
642
+ const { productId, questionsAndAnswers, priceCategory } = resetedProduct;
643
+ const prunedQuestions = pruneQuestionsAndAnswers(questionsAndAnswers);
644
+ const sortedQuestions = prunedQuestions.sort(sortByQuestionId);
645
+ const questionAndAnswersIds = sortedQuestions.reduce((acc, question) => {
646
+ const sortedAnswers = question.answers.sort(sortByProductId);
647
+ const answerIds = sortedAnswers.reduce((acc2, answer, index) => {
648
+ const { productId: productId2, amount } = answer;
649
+ const childrenHash = getProductHash(answer);
650
+ const concatChildrenHash = childrenHash ? `{${childrenHash}}` : "";
651
+ if (index === 0) {
652
+ return `${productId2}=${amount}${concatChildrenHash}`;
653
+ }
654
+ return `${acc2}|${productId2}=${amount}${concatChildrenHash}`;
655
+ }, "");
656
+ const questionIds = `${question.questionId}:${answerIds}`;
657
+ if (acc === "") {
658
+ return `${questionIds}`;
659
+ }
660
+ return `${acc}-${questionIds}`;
661
+ }, "");
662
+ const sequence = `${productId}-${questionAndAnswersIds}*${priceCategory}`;
663
+ return sha1(sequence);
664
+ };
665
+ const pruneQuestionsAndAnswers = (questions) => {
666
+ const prunedQuestions = questions.reduce((acc, question) => {
667
+ const prunedAnswers = question.answers.filter((answer) => {
668
+ return answer.amount > 0;
669
+ });
670
+ const prunedAnswersAndChildren = prunedAnswers.map((answer) => {
671
+ const prunedChildren = pruneQuestionsAndAnswers(answer.questionsAndAnswers);
672
+ return __spreadProps$9(__spreadValues$e({}, answer), { questionsAndAnswers: prunedChildren });
673
+ });
674
+ return [...acc, __spreadProps$9(__spreadValues$e({}, question), { answers: prunedAnswersAndChildren })];
675
+ }, []);
676
+ const prunedQuestionsAndAnswers = prunedQuestions.filter((question) => {
677
+ return question.answers.length > 0;
678
+ });
679
+ return prunedQuestionsAndAnswers;
680
+ };
681
+ const getShoppingCartTotal = (shoppingCart, config = {}) => {
682
+ const initialValue = {
683
+ subtotal: 0,
684
+ totalDiscounts: null,
685
+ shippingCost: null,
686
+ totalTaxes: null,
687
+ totalPoints: null,
688
+ total: 0
689
+ };
690
+ const products$1 = getShoppingCartProducts(shoppingCart);
691
+ if (!products$1.length)
692
+ return initialValue;
693
+ const totals = products$1.reduce((acc, product) => {
694
+ const cartProduct = toCartProduct$4(product);
695
+ const { priceCategory } = cartProduct;
696
+ const productTotal = products.getProductTotals(cartProduct);
697
+ const isPoints = priceCategory === "POINTS";
698
+ const points = isPoints ? productTotal.netPrice : 0;
699
+ const normal = !isPoints ? productTotal.netPrice : 0;
700
+ const subtotalNormal = !isPoints ? productTotal.grossPrice : 0;
701
+ return {
702
+ subtotal: acc.subtotal + subtotalNormal,
703
+ totalDiscounts: productTotal.totalDiscounts !== null ? Number(acc.totalDiscounts) + productTotal.totalDiscounts : null,
704
+ totalTaxes: productTotal.totalTaxes !== null ? Number(acc.totalTaxes) + productTotal.totalTaxes : null,
705
+ shippingCost: null,
706
+ totalPoints: points !== null ? Number(acc.totalPoints) + points : null,
707
+ total: acc.total + normal
708
+ };
709
+ }, initialValue);
710
+ const totalsWithBenefits = applyBenefits(shoppingCart, totals);
711
+ const { shippingCost = shoppingCart.shippingCost } = config;
712
+ if (!shippingCost) {
713
+ return totalsWithBenefits;
714
+ }
715
+ const { grossPrice, netPrice, taxTotal, discountTotal } = shippingCost;
716
+ const totalsWithShippingCost = {
717
+ subtotal: totalsWithBenefits.subtotal + grossPrice,
718
+ totalDiscounts: totalsWithBenefits.totalDiscounts !== null ? totalsWithBenefits.totalDiscounts + discountTotal : discountTotal,
719
+ totalTaxes: totalsWithBenefits.totalTaxes !== null ? totalsWithBenefits.totalTaxes + taxTotal : taxTotal,
720
+ shippingCost: netPrice,
721
+ totalPoints: totalsWithBenefits.totalPoints,
722
+ total: totalsWithBenefits.total + netPrice
723
+ };
724
+ return totalsWithShippingCost;
725
+ };
726
+ const getShoppingCartProducts = (shoppingCart, storeId) => {
727
+ let stores;
728
+ if (typeof storeId === "undefined") {
729
+ stores = Object.values(shoppingCart.stores);
730
+ } else {
731
+ stores = [shoppingCart.stores[storeId]];
732
+ }
733
+ return stores.reduce((acc, store) => {
734
+ if (!store)
735
+ return acc;
736
+ const products = Object.values(store.products);
737
+ return [...acc, ...products];
738
+ }, []);
739
+ };
740
+ const applyBenefits = (shoppingCart, shoppingCartTotals) => {
741
+ const additionalInfo = shoppingCart["additional_info"];
742
+ const benefits = shoppingCart["benefits"];
743
+ if (!benefits) {
744
+ return shoppingCartTotals;
745
+ }
746
+ const benefitsValues = Object.values(benefits);
747
+ return benefitsValues.reduce((acc, benefit) => {
748
+ if (benefit.type === "DISCOUNT_PERCENTAGE" && benefit.discountPercentage) {
749
+ return applyBenefitByDiscountPercentage(benefit, acc, shoppingCart);
750
+ }
751
+ if (benefit.type === "DISCOUNT_FIXED" && benefit.discountFixed) {
752
+ return applyBenefitByDiscountFixed(benefit, acc, additionalInfo);
753
+ }
754
+ return acc;
755
+ }, shoppingCartTotals);
756
+ };
757
+ const applyBenefitByDiscountPercentage = (benefit, shoppingCartTotals, shoppingCart) => {
758
+ let taxValue = 0;
759
+ const additionalInfo = shoppingCart["additional_info"];
760
+ const { billTotal } = shoppingCart;
761
+ const { NORMAL } = billTotal;
762
+ const { discounts } = NORMAL != null ? NORMAL : {};
763
+ discounts == null ? void 0 : discounts.forEach((discount) => {
764
+ if (discount.taxValue) {
765
+ taxValue += discount.taxValue;
766
+ }
767
+ });
768
+ const { subtotal, total: prevTotal } = shoppingCartTotals;
769
+ const { totalDiscounts: prevTotalDiscounts } = shoppingCartTotals;
770
+ const discountPercentage = benefit.discountPercentage * 0.01;
771
+ if (typeof (additionalInfo == null ? void 0 : additionalInfo.copayment) !== "undefined") {
772
+ const copayment = additionalInfo == null ? void 0 : additionalInfo.copayment;
773
+ const totalDiscount2 = copayment * discountPercentage + taxValue;
774
+ const newTotalDiscounts2 = prevTotalDiscounts !== null ? prevTotalDiscounts + totalDiscount2 : totalDiscount2;
775
+ const newTotal2 = (copayment - totalDiscount2).toFixed(4);
776
+ return __spreadProps$9(__spreadValues$e({}, shoppingCartTotals), {
777
+ totalDiscounts: newTotalDiscounts2,
778
+ total: Number(newTotal2)
779
+ });
780
+ }
781
+ const totalDiscount = subtotal * discountPercentage + taxValue;
782
+ const newTotalDiscounts = prevTotalDiscounts !== null ? prevTotalDiscounts + totalDiscount : totalDiscount;
783
+ const newTotal = prevTotal - totalDiscount;
784
+ return __spreadProps$9(__spreadValues$e({}, shoppingCartTotals), {
785
+ totalDiscounts: newTotalDiscounts,
786
+ total: newTotal
787
+ });
788
+ };
789
+ const applyBenefitByDiscountFixed = (benefit, shoppingCartTotals, additionalInfo) => {
790
+ const { total: prevTotal } = shoppingCartTotals;
791
+ const { totalDiscounts: prevTotalDiscounts } = shoppingCartTotals;
792
+ const discountFixed = Number(benefit.discountFixed);
793
+ if (typeof (additionalInfo == null ? void 0 : additionalInfo.copayment) !== "undefined") {
794
+ const copayment = additionalInfo == null ? void 0 : additionalInfo.copayment;
795
+ const newTotalDiscounts2 = prevTotalDiscounts !== null ? prevTotalDiscounts + discountFixed : discountFixed;
796
+ const newTotal2 = (copayment - discountFixed).toFixed(4);
797
+ return __spreadProps$9(__spreadValues$e({}, shoppingCartTotals), {
798
+ totalDiscounts: newTotalDiscounts2,
799
+ total: Number(newTotal2)
800
+ });
801
+ }
802
+ const newTotalDiscounts = prevTotalDiscounts !== null ? prevTotalDiscounts + discountFixed : discountFixed;
803
+ const newTotal = prevTotal - discountFixed;
804
+ return __spreadProps$9(__spreadValues$e({}, shoppingCartTotals), {
805
+ totalDiscounts: newTotalDiscounts,
806
+ total: newTotal
807
+ });
808
+ };
809
+ const findProduct = async (builders, config) => {
810
+ const { getShoppingCartNode } = builders != null ? builders : {};
811
+ const { shoppingCartName } = config;
812
+ const { accountId, customerId, hash, productId, store } = config;
813
+ try {
814
+ if (!hash && typeof productId === "undefined") {
815
+ throw new Error(`You must provide either a product id or a product hash,
816
+ but none were given.`);
817
+ }
818
+ const shoppingCart = await getShoppingCart({ getShoppingCartNode }, {
819
+ accountId,
820
+ customerId,
821
+ store,
822
+ shoppingCartName
823
+ });
824
+ if (!shoppingCart)
825
+ return;
826
+ const products = getShoppingCartProducts(shoppingCart);
827
+ let product;
828
+ if (hash) {
829
+ product = products.find((item) => item.hash === hash);
830
+ } else {
831
+ product = products.find((item) => item.productId === productId);
832
+ }
833
+ return product;
834
+ } catch (e) {
835
+ console.error(e);
836
+ return void 0;
837
+ }
838
+ };
839
+
840
+ var __defProp$d = Object.defineProperty;
841
+ var __defProps$8 = Object.defineProperties;
842
+ var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
843
+ var __getOwnPropSymbols$d = Object.getOwnPropertySymbols;
844
+ var __hasOwnProp$d = Object.prototype.hasOwnProperty;
845
+ var __propIsEnum$d = Object.prototype.propertyIsEnumerable;
846
+ var __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
847
+ var __spreadValues$d = (a, b) => {
848
+ for (var prop in b || (b = {}))
849
+ if (__hasOwnProp$d.call(b, prop))
850
+ __defNormalProp$d(a, prop, b[prop]);
851
+ if (__getOwnPropSymbols$d)
852
+ for (var prop of __getOwnPropSymbols$d(b)) {
853
+ if (__propIsEnum$d.call(b, prop))
854
+ __defNormalProp$d(a, prop, b[prop]);
855
+ }
856
+ return a;
857
+ };
858
+ var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
859
+ const { PRODUCT_DATE_FORMAT: PRODUCT_DATE_FORMAT$2 } = CONSTANTS;
860
+ const { toCartProduct: toCartProduct$3 } = products.transformers;
861
+ const { multiplyProductQA: multiplyProductQA$2, divideProductQA: divideProductQA$2 } = products.modifierUtils;
862
+ const addProduct = async (builders, product, config) => {
863
+ const { getShoppingCartNode, setDoc, createShoppingCart } = builders != null ? builders : {};
864
+ const { createCart } = config;
865
+ if (createCart) {
866
+ const reusedConfig = reuseGlobalConfig(config);
867
+ const shoppingCart = await getShoppingCart(builders, reusedConfig);
868
+ if (!shoppingCart)
869
+ await (createShoppingCart == null ? void 0 : createShoppingCart(reusedConfig, createCart === true ? void 0 : createCart));
870
+ }
871
+ return new Promise((resolve, reject) => {
872
+ const action = async () => {
873
+ try {
874
+ const reusedConfig = reuseGlobalConfig(config);
875
+ checkModifyProductConfig(reusedConfig);
876
+ const shoppingCartNode = await getShoppingCartNode(reusedConfig);
877
+ if (!shoppingCartNode) {
878
+ console.warn("Cannot add a product because no shopping cart node was found. Please ensure you have a shopping cart before continue.");
879
+ resolve(null);
880
+ return null;
881
+ }
882
+ const shoppingCart = shoppingCartNode.data();
883
+ const updatedCart = addProductToCartHelper(shoppingCart, product, config);
884
+ await (setDoc == null ? void 0 : setDoc({
885
+ reusedConfig,
886
+ shoppingCartNode,
887
+ payload: updatedCart
888
+ }));
889
+ resolve(updatedCart);
890
+ return updatedCart;
891
+ } catch (e) {
892
+ reject(e);
893
+ return null;
894
+ }
895
+ };
896
+ const { eventLoop, queue } = getState();
897
+ queue.enqueue(action);
898
+ if (!eventLoop.isRunning)
899
+ eventLoop.start();
900
+ });
901
+ };
902
+ const addProductToCartHelper = (shoppingCart, product, config) => {
903
+ const reusedConfig = reuseGlobalConfig(config);
904
+ if (process.env.NODE_ENV === "test") {
905
+ checkModifyProductConfig(reusedConfig);
906
+ }
907
+ const { amount: originalAmount } = product;
908
+ const amount = originalAmount ? originalAmount : 1;
909
+ const hashCartProduct = toCartProduct$3(product, __spreadProps$8(__spreadValues$d({}, reusedConfig), {
910
+ amount: amount != null ? amount : 1
911
+ }));
912
+ const cartProduct = toCartProduct$3(product, reusedConfig);
913
+ const { store: configStore } = reusedConfig;
914
+ const { storeId } = configStore != null ? configStore : {};
915
+ const hash = getProductHash(hashCartProduct);
916
+ const updatedCart = __spreadValues$d({}, shoppingCart);
917
+ const stores = __spreadValues$d({}, shoppingCart.stores);
918
+ const store = getStore(configStore, stores);
919
+ const products = __spreadValues$d({}, store.products);
920
+ const productExist = products[hash];
921
+ const now = dayjs().format(PRODUCT_DATE_FORMAT$2);
922
+ if (!productExist) {
923
+ products[hash] = cartProduct;
924
+ products[hash].hash = hash;
925
+ products[hash].createdAt = now;
926
+ } else {
927
+ products[hash] = divideProductQA$2(products[hash]);
928
+ products[hash].amount += cartProduct.amount;
929
+ }
930
+ products[hash].updatedAt = now;
931
+ let updatedProduct = products[hash];
932
+ updatedProduct = multiplyProductQA$2(updatedProduct);
933
+ const { questionsAndAnswers } = updatedProduct;
934
+ const newCartModifiers = pruneQuestionsAndAnswers(questionsAndAnswers);
935
+ products[hash] = __spreadProps$8(__spreadValues$d({}, updatedProduct), { questionsAndAnswers: newCartModifiers });
936
+ store.products = products;
937
+ stores[storeId] = store;
938
+ updatedCart.stores = stores;
939
+ return updatedCart;
940
+ };
941
+
942
+ var __defProp$c = Object.defineProperty;
943
+ var __defProps$7 = Object.defineProperties;
944
+ var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
945
+ var __getOwnPropSymbols$c = Object.getOwnPropertySymbols;
946
+ var __hasOwnProp$c = Object.prototype.hasOwnProperty;
947
+ var __propIsEnum$c = Object.prototype.propertyIsEnumerable;
948
+ var __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
949
+ var __spreadValues$c = (a, b) => {
950
+ for (var prop in b || (b = {}))
951
+ if (__hasOwnProp$c.call(b, prop))
952
+ __defNormalProp$c(a, prop, b[prop]);
953
+ if (__getOwnPropSymbols$c)
954
+ for (var prop of __getOwnPropSymbols$c(b)) {
955
+ if (__propIsEnum$c.call(b, prop))
956
+ __defNormalProp$c(a, prop, b[prop]);
957
+ }
958
+ return a;
959
+ };
960
+ var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
961
+ const { PRODUCT_DATE_FORMAT: PRODUCT_DATE_FORMAT$1 } = CONSTANTS;
962
+ const { toCartProduct: toCartProduct$2 } = products.transformers;
963
+ const { multiplyProductQA: multiplyProductQA$1, divideProductQA: divideProductQA$1 } = products.modifierUtils;
964
+ const subtractProduct = async (builders, product, config) => {
965
+ return new Promise((resolve, reject) => {
966
+ const action = async () => {
967
+ try {
968
+ const { setDoc, getShoppingCartNode } = builders != null ? builders : {};
969
+ const reusedConfig = reuseGlobalConfig(config);
970
+ checkModifyProductConfig(reusedConfig);
971
+ const shoppingCartNode = await getShoppingCartNode(reusedConfig);
972
+ if (!shoppingCartNode) {
973
+ console.warn("Cannot subtract product because no shopping cart nodes found. Please ensure you have a shopping cart before continue.");
974
+ resolve(null);
975
+ return null;
976
+ }
977
+ const shoppingCart = shoppingCartNode.data();
978
+ const updatedCart = subtractProductHelper(shoppingCart, product, reusedConfig);
979
+ await (setDoc == null ? void 0 : setDoc({
980
+ reusedConfig,
981
+ shoppingCartNode,
982
+ payload: updatedCart
983
+ }));
984
+ resolve(updatedCart);
985
+ return updatedCart;
986
+ } catch (e) {
987
+ reject(e);
988
+ return null;
989
+ }
990
+ };
991
+ const { eventLoop, queue } = getState();
992
+ queue.enqueue(action);
993
+ if (!eventLoop.isRunning)
994
+ eventLoop.start();
995
+ });
996
+ };
997
+ const subtractProductHelper = (shoppingCart, product, config) => {
998
+ const reusedConfig = reuseGlobalConfig(config);
999
+ if (process.env.NODE_ENV === "test") {
1000
+ checkModifyProductConfig(reusedConfig);
1001
+ }
1002
+ const { amount: originalAmount } = product;
1003
+ const amount = originalAmount ? originalAmount : 1;
1004
+ const hashCartProduct = toCartProduct$2(product, __spreadProps$7(__spreadValues$c({}, reusedConfig), {
1005
+ amount: amount != null ? amount : 1
1006
+ }));
1007
+ const cartProduct = toCartProduct$2(product, reusedConfig);
1008
+ const { store: configStore } = reusedConfig;
1009
+ const { storeId } = configStore != null ? configStore : {};
1010
+ const hash = getProductHash(hashCartProduct);
1011
+ let updatedCart = __spreadValues$c({}, shoppingCart);
1012
+ const stores = __spreadValues$c({}, shoppingCart.stores);
1013
+ if (typeof stores[storeId] === "undefined") {
1014
+ console.warn(`StoreId given is invalid. There is no store with id ${storeId} on the shopping cart.`);
1015
+ return shoppingCart;
1016
+ }
1017
+ const store = getStore(configStore, stores);
1018
+ const products = __spreadValues$c({}, store.products);
1019
+ const productExist = products[hash];
1020
+ const now = dayjs().format(PRODUCT_DATE_FORMAT$1);
1021
+ if (!productExist) {
1022
+ console.warn(`Attempting to subtract the amount of product that is not in the given shopping cart store.`);
1023
+ return shoppingCart;
1024
+ }
1025
+ products[hash] = divideProductQA$1(products[hash]);
1026
+ const newAmount = products[hash].amount - cartProduct.amount;
1027
+ if (newAmount > 0) {
1028
+ products[hash].amount = newAmount;
1029
+ products[hash].updatedAt = now;
1030
+ products[hash] = multiplyProductQA$1(products[hash]);
1031
+ } else {
1032
+ delete products[hash];
1033
+ updatedCart = cleanShoppingCart(shoppingCart, product);
1034
+ }
1035
+ store.products = products;
1036
+ if (!Object.keys(store.products).length) {
1037
+ delete stores[storeId];
1038
+ } else {
1039
+ stores[storeId] = store;
1040
+ }
1041
+ updatedCart.stores = stores;
1042
+ return updatedCart;
1043
+ };
1044
+
1045
+ var __defProp$b = Object.defineProperty;
1046
+ var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
1047
+ var __hasOwnProp$b = Object.prototype.hasOwnProperty;
1048
+ var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
1049
+ var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1050
+ var __spreadValues$b = (a, b) => {
1051
+ for (var prop in b || (b = {}))
1052
+ if (__hasOwnProp$b.call(b, prop))
1053
+ __defNormalProp$b(a, prop, b[prop]);
1054
+ if (__getOwnPropSymbols$b)
1055
+ for (var prop of __getOwnPropSymbols$b(b)) {
1056
+ if (__propIsEnum$b.call(b, prop))
1057
+ __defNormalProp$b(a, prop, b[prop]);
1058
+ }
1059
+ return a;
1060
+ };
1061
+ const { toCartProduct: toCartProduct$1 } = products.transformers;
1062
+ const removeProduct = async (builders, product, config = {}) => {
1063
+ return new Promise((resolve, reject) => {
1064
+ const action = async () => {
1065
+ try {
1066
+ const { setDoc, getShoppingCartNode } = builders != null ? builders : {};
1067
+ const reusedConfig = reuseGlobalConfig(config);
1068
+ checkRemoveProductConfig(reusedConfig);
1069
+ const shoppingCartNode = await getShoppingCartNode(reusedConfig);
1070
+ if (!shoppingCartNode) {
1071
+ console.warn("Cannot remove a product because no shopping cart nodes found. Please ensure you have a shopping cart before continue.");
1072
+ resolve(null);
1073
+ return null;
1074
+ }
1075
+ const shoppingCart = shoppingCartNode.data();
1076
+ const cart = removeProductHelper(shoppingCart, product, reusedConfig);
1077
+ const updatedCart = cleanShoppingCart(cart, product);
1078
+ await (setDoc == null ? void 0 : setDoc({
1079
+ reusedConfig,
1080
+ shoppingCartNode,
1081
+ payload: updatedCart
1082
+ }));
1083
+ resolve(updatedCart);
1084
+ return updatedCart;
1085
+ } catch (e) {
1086
+ reject(e);
1087
+ return null;
1088
+ }
1089
+ };
1090
+ const { eventLoop, queue } = getState();
1091
+ queue.enqueue(action);
1092
+ if (!eventLoop.isRunning)
1093
+ eventLoop.start();
1094
+ });
1095
+ };
1096
+ const removeProductHelper = (shoppingCart, product, config) => {
1097
+ const reusedConfig = reuseGlobalConfig(config);
1098
+ if (process.env.NODE_ENV === "test") {
1099
+ checkRemoveProductConfig(reusedConfig);
1100
+ }
1101
+ let productHash = product.hash;
1102
+ if (!productHash) {
1103
+ const cartProduct = toCartProduct$1(product);
1104
+ productHash = getProductHash(cartProduct);
1105
+ }
1106
+ const { store: configStore } = reusedConfig;
1107
+ const { storeId } = configStore != null ? configStore : {};
1108
+ const updatedCart = __spreadValues$b({}, shoppingCart);
1109
+ const stores = __spreadValues$b({}, shoppingCart.stores);
1110
+ if (typeof stores[storeId] === "undefined") {
1111
+ console.warn(`StoreId given is invalid. There is no store with id ${storeId} on the shopping cart.`);
1112
+ return shoppingCart;
1113
+ }
1114
+ const store = getStore(configStore, stores);
1115
+ const products = __spreadValues$b({}, store.products);
1116
+ const productExist = products[productHash];
1117
+ if (!productExist) {
1118
+ console.warn(`Attempting to remove product that is not in the given shopping cart store.`);
1119
+ return shoppingCart;
1120
+ }
1121
+ delete products[productHash];
1122
+ store.products = products;
1123
+ if (!Object.keys(store.products).length) {
1124
+ delete stores[storeId];
1125
+ } else {
1126
+ stores[storeId] = store;
1127
+ }
1128
+ updatedCart.stores = stores;
1129
+ return updatedCart;
1130
+ };
1131
+
1132
+ var __defProp$a = Object.defineProperty;
1133
+ var __defProps$6 = Object.defineProperties;
1134
+ var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
1135
+ var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
1136
+ var __hasOwnProp$a = Object.prototype.hasOwnProperty;
1137
+ var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
1138
+ var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1139
+ var __spreadValues$a = (a, b) => {
1140
+ for (var prop in b || (b = {}))
1141
+ if (__hasOwnProp$a.call(b, prop))
1142
+ __defNormalProp$a(a, prop, b[prop]);
1143
+ if (__getOwnPropSymbols$a)
1144
+ for (var prop of __getOwnPropSymbols$a(b)) {
1145
+ if (__propIsEnum$a.call(b, prop))
1146
+ __defNormalProp$a(a, prop, b[prop]);
1147
+ }
1148
+ return a;
1149
+ };
1150
+ var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
1151
+ const { PRODUCT_DATE_FORMAT } = CONSTANTS;
1152
+ const { toCartProduct } = products.transformers;
1153
+ const { multiplyProductQA, divideProductQA } = products.modifierUtils;
1154
+ const setProduct = async (builders, product, config = {}) => {
1155
+ return new Promise((resolve, reject) => {
1156
+ const action = async () => {
1157
+ var _a, _b;
1158
+ try {
1159
+ const { setDoc, getShoppingCartNode } = builders != null ? builders : {};
1160
+ const reusedConfig = reuseGlobalConfig(config);
1161
+ const amount = (_b = (_a = reusedConfig.amount) != null ? _a : product == null ? void 0 : product.amount) != null ? _b : 1;
1162
+ const actionConfig = __spreadProps$6(__spreadValues$a({}, reusedConfig), { amount });
1163
+ checkModifyProductConfig(actionConfig);
1164
+ const shoppingCartNode = await getShoppingCartNode(reusedConfig);
1165
+ if (!shoppingCartNode) {
1166
+ console.warn("Cannot set product because no shopping cart nodes found. Please ensure you have a shopping cart before continue.");
1167
+ resolve(null);
1168
+ return null;
1169
+ }
1170
+ const shoppingCart = shoppingCartNode.data();
1171
+ const cart = setProductHelper(shoppingCart, product, actionConfig);
1172
+ const updatedCart = cleanShoppingCart(cart, product);
1173
+ await (setDoc == null ? void 0 : setDoc({
1174
+ reusedConfig,
1175
+ shoppingCartNode,
1176
+ payload: updatedCart
1177
+ }));
1178
+ resolve(updatedCart);
1179
+ return updatedCart;
1180
+ } catch (e) {
1181
+ reject(e);
1182
+ return null;
1183
+ }
1184
+ };
1185
+ const { eventLoop, queue } = getState();
1186
+ queue.enqueue(action);
1187
+ if (!eventLoop.isRunning)
1188
+ eventLoop.start();
1189
+ });
1190
+ };
1191
+ const setProductHelper = (shoppingCart, product, config) => {
1192
+ var _a;
1193
+ const reusedConfig = reuseGlobalConfig(config);
1194
+ if (process.env.NODE_ENV === "test") {
1195
+ checkModifyProductConfig(reusedConfig);
1196
+ }
1197
+ const amount = (_a = product == null ? void 0 : product.amount) != null ? _a : 1;
1198
+ const hashCartProduct = toCartProduct(product, __spreadProps$6(__spreadValues$a({}, reusedConfig), { amount }));
1199
+ const { store: configStore } = reusedConfig;
1200
+ const { storeId } = configStore != null ? configStore : {};
1201
+ const hash = getProductHash(hashCartProduct);
1202
+ const updatedCart = __spreadValues$a({}, shoppingCart);
1203
+ const stores = __spreadValues$a({}, shoppingCart.stores);
1204
+ const store = getStore(configStore, stores);
1205
+ const products = __spreadValues$a({}, store.products);
1206
+ const productExist = products[hash];
1207
+ const now = dayjs().format(PRODUCT_DATE_FORMAT);
1208
+ products[hash] = hashCartProduct;
1209
+ if (!productExist) {
1210
+ products[hash].createdAt = now;
1211
+ products[hash].hash = hash;
1212
+ } else {
1213
+ products[hash] = divideProductQA(products[hash]);
1214
+ }
1215
+ products[hash].updatedAt = now;
1216
+ let updatedProduct = toCartProduct(products[hash], reusedConfig);
1217
+ updatedProduct = multiplyProductQA(updatedProduct);
1218
+ const { questionsAndAnswers } = updatedProduct;
1219
+ const newCartModifiers = pruneQuestionsAndAnswers(questionsAndAnswers);
1220
+ products[hash] = __spreadProps$6(__spreadValues$a({}, updatedProduct), { questionsAndAnswers: newCartModifiers });
1221
+ store.products = products;
1222
+ stores[storeId] = __spreadProps$6(__spreadValues$a({}, store), { polygons: null });
1223
+ updatedCart.stores = stores;
1224
+ return updatedCart;
1225
+ };
1226
+
1227
+ var __defProp$9 = Object.defineProperty;
1228
+ var __defProps$5 = Object.defineProperties;
1229
+ var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
1230
+ var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
1231
+ var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
1232
+ var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
1233
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1234
+ var __spreadValues$9 = (a, b) => {
1235
+ for (var prop in b || (b = {}))
1236
+ if (__hasOwnProp$9.call(b, prop))
1237
+ __defNormalProp$9(a, prop, b[prop]);
1238
+ if (__getOwnPropSymbols$9)
1239
+ for (var prop of __getOwnPropSymbols$9(b)) {
1240
+ if (__propIsEnum$9.call(b, prop))
1241
+ __defNormalProp$9(a, prop, b[prop]);
1242
+ }
1243
+ return a;
1244
+ };
1245
+ var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
1246
+ const replaceProduct = async (builders, product, config) => {
1247
+ return new Promise((resolve, reject) => {
1248
+ const action = async () => {
1249
+ try {
1250
+ const { setDoc, getShoppingCartNode } = builders != null ? builders : {};
1251
+ const reusedConfig = reuseGlobalConfig(config);
1252
+ checkReplaceProductConfig(reusedConfig);
1253
+ const shoppingCartNode = await getShoppingCartNode(reusedConfig);
1254
+ if (!shoppingCartNode) {
1255
+ console.warn("Cannot replace product because no shopping cart nodes found. Please ensure you have a shopping cart before continue.");
1256
+ resolve(null);
1257
+ return null;
1258
+ }
1259
+ const shoppingCart = shoppingCartNode.data();
1260
+ const cart = replaceProductHelper(shoppingCart, product, reusedConfig);
1261
+ const updatedCart = cleanShoppingCart(cart, product);
1262
+ await (setDoc == null ? void 0 : setDoc({
1263
+ reusedConfig,
1264
+ shoppingCartNode,
1265
+ payload: updatedCart
1266
+ }));
1267
+ resolve(updatedCart);
1268
+ return updatedCart;
1269
+ } catch (e) {
1270
+ reject(e);
1271
+ return null;
1272
+ }
1273
+ };
1274
+ const { eventLoop, queue } = getState();
1275
+ queue.enqueue(action);
1276
+ if (!eventLoop.isRunning)
1277
+ eventLoop.start();
1278
+ });
1279
+ };
1280
+ const replaceProductHelper = (shoppingCart, product, config) => {
1281
+ const reusedConfig = reuseGlobalConfig(config);
1282
+ if (process.env.NODE_ENV === "test") {
1283
+ checkReplaceProductConfig(reusedConfig);
1284
+ }
1285
+ const { hash: configHash } = reusedConfig;
1286
+ const hash = configHash != null ? configHash : product.hash;
1287
+ const { store: configStore } = reusedConfig;
1288
+ const { storeId } = configStore != null ? configStore : {};
1289
+ const stores = __spreadValues$9({}, shoppingCart.stores);
1290
+ const store = getStore(configStore, stores);
1291
+ const products = __spreadValues$9({}, store.products);
1292
+ const productExist = products[hash];
1293
+ if (!productExist) {
1294
+ console.warn("Cannot replace a product because no product was found in the given store");
1295
+ return shoppingCart;
1296
+ }
1297
+ delete products[hash];
1298
+ store.products = products;
1299
+ if (!Object.keys(store.products).length) {
1300
+ delete stores[storeId];
1301
+ } else {
1302
+ stores[storeId] = store;
1303
+ }
1304
+ let updatedCart = __spreadValues$9({}, shoppingCart);
1305
+ updatedCart.stores = stores;
1306
+ const newProduct = __spreadProps$5(__spreadValues$9({}, product), { amount: 0 });
1307
+ updatedCart = addProductToCartHelper(updatedCart, newProduct, reusedConfig);
1308
+ return updatedCart;
1309
+ };
1310
+
1311
+ var __defProp$8 = Object.defineProperty;
1312
+ var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
1313
+ var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
1314
+ var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
1315
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1316
+ var __spreadValues$8 = (a, b) => {
1317
+ for (var prop in b || (b = {}))
1318
+ if (__hasOwnProp$8.call(b, prop))
1319
+ __defNormalProp$8(a, prop, b[prop]);
1320
+ if (__getOwnPropSymbols$8)
1321
+ for (var prop of __getOwnPropSymbols$8(b)) {
1322
+ if (__propIsEnum$8.call(b, prop))
1323
+ __defNormalProp$8(a, prop, b[prop]);
1324
+ }
1325
+ return a;
1326
+ };
1327
+ const { DEFAULT_SHOPPING_CART_NAME } = CONSTANTS;
1328
+ const buildInitialShoppingCart = (overrides = {}) => {
1329
+ const date = new Date().toISOString();
1330
+ return __spreadValues$8({
1331
+ id: "",
1332
+ name: DEFAULT_SHOPPING_CART_NAME,
1333
+ latitude: -1,
1334
+ longitude: -1,
1335
+ createdAt: date,
1336
+ updatedAt: date,
1337
+ channelId: 1,
1338
+ stores: {},
1339
+ billTotal: {},
1340
+ shippingCost: null
1341
+ }, overrides);
1342
+ };
1343
+
1344
+ var __defProp$7 = Object.defineProperty;
1345
+ var __defProps$4 = Object.defineProperties;
1346
+ var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
1347
+ var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
1348
+ var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
1349
+ var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
1350
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1351
+ var __spreadValues$7 = (a, b) => {
1352
+ for (var prop in b || (b = {}))
1353
+ if (__hasOwnProp$7.call(b, prop))
1354
+ __defNormalProp$7(a, prop, b[prop]);
1355
+ if (__getOwnPropSymbols$7)
1356
+ for (var prop of __getOwnPropSymbols$7(b)) {
1357
+ if (__propIsEnum$7.call(b, prop))
1358
+ __defNormalProp$7(a, prop, b[prop]);
1359
+ }
1360
+ return a;
1361
+ };
1362
+ var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
1363
+ const emptyShoppingCart = async (builders, config) => {
1364
+ return new Promise((resolve, reject) => {
1365
+ const action = async () => {
1366
+ try {
1367
+ const { getShoppingCartNode, setDoc } = builders != null ? builders : {};
1368
+ const shoppingCartNode = await getShoppingCartNode(config);
1369
+ const reusedConfig = reuseGlobalConfig(config);
1370
+ const { shoppingCartName, vendorId } = reusedConfig;
1371
+ if (!shoppingCartNode) {
1372
+ logDebug(`Cannot empty cart, shopping cart nodes not found. Please ensure you have a shopping cart with name ${shoppingCartName} before continue.`);
1373
+ resolve(null);
1374
+ return null;
1375
+ }
1376
+ const shoppingCart = await shoppingCartNode.data();
1377
+ delete shoppingCart.pickUpTime;
1378
+ const stores = {};
1379
+ if (typeof vendorId !== "undefined") {
1380
+ const filteredStores = Object.values(shoppingCart.stores).filter((store) => store.vendor.id != vendorId);
1381
+ filteredStores.forEach((store) => {
1382
+ stores[`${store.storeId}`] = store;
1383
+ });
1384
+ }
1385
+ const cart = __spreadProps$4(__spreadValues$7({}, shoppingCart), { stores });
1386
+ const updatedCart = cleanShoppingCart(cart);
1387
+ await (setDoc == null ? void 0 : setDoc({
1388
+ reusedConfig,
1389
+ shoppingCartNode,
1390
+ payload: updatedCart
1391
+ }));
1392
+ resolve(updatedCart);
1393
+ return updatedCart;
1394
+ } catch (e) {
1395
+ reject(e);
1396
+ return null;
1397
+ }
1398
+ };
1399
+ const { eventLoop, queue } = getState();
1400
+ queue.enqueue(action);
1401
+ if (!eventLoop.isRunning)
1402
+ eventLoop.start();
1403
+ });
1404
+ };
1405
+
1406
+ const deleteShoppingCart = async (builders, config) => {
1407
+ return new Promise((resolve, reject) => {
1408
+ const action = async () => {
1409
+ try {
1410
+ const { getShoppingCartNode, deleteDoc } = builders != null ? builders : {};
1411
+ const shoppingCartNode = await getShoppingCartNode(config);
1412
+ const reusedConfig = reuseGlobalConfig(config);
1413
+ const { shoppingCartName } = reusedConfig;
1414
+ if (!shoppingCartNode) {
1415
+ logDebug(`Couldn't find any shopping cart with name ${shoppingCartName} with the given config.`);
1416
+ resolve(null);
1417
+ return null;
1418
+ }
1419
+ const shoppingCart = shoppingCartNode.data();
1420
+ await (deleteDoc == null ? void 0 : deleteDoc({ shoppingCartNode, reusedConfig }));
1421
+ resolve(shoppingCart);
1422
+ return shoppingCart;
1423
+ } catch (e) {
1424
+ reject(e);
1425
+ return null;
1426
+ }
1427
+ };
1428
+ const { eventLoop, queue } = getState();
1429
+ queue.enqueue(action);
1430
+ if (!eventLoop.isRunning)
1431
+ eventLoop.start();
1432
+ });
1433
+ };
1434
+
1435
+ const verifyHeaders = (headers) => {
1436
+ var _a;
1437
+ const validPlatforms = [
1438
+ "web",
1439
+ "ios",
1440
+ "android",
1441
+ "windows",
1442
+ "macos",
1443
+ "call center"
1444
+ ];
1445
+ const platform = headers.get("Platform");
1446
+ const validPlatformsText = validPlatforms.join(", ");
1447
+ if (!headers.has("account")) {
1448
+ throw new Error("Missing account");
1449
+ }
1450
+ if (!platform) {
1451
+ throw new Error("Missing Platform");
1452
+ }
1453
+ if (!validPlatforms.includes(platform)) {
1454
+ throw new Error(`Invalid Platform: ${platform}, please use ${validPlatformsText}`);
1455
+ }
1456
+ checkAuthToken((_a = headers.get("Authorization")) != null ? _a : void 0);
1457
+ };
1458
+
1459
+ const checkValidateShoppingCartConfig = (config, headers) => {
1460
+ const { apiURL } = config;
1461
+ checkApiURL(apiURL);
1462
+ verifyHeaders(headers);
1463
+ };
1464
+
1465
+ const commonHeaders = {
1466
+ "Content-Type": "application/json"
1467
+ };
1468
+
1469
+ var __defProp$6 = Object.defineProperty;
1470
+ var __defProps$3 = Object.defineProperties;
1471
+ var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
1472
+ var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
1473
+ var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
1474
+ var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
1475
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1476
+ var __spreadValues$6 = (a, b) => {
1477
+ for (var prop in b || (b = {}))
1478
+ if (__hasOwnProp$6.call(b, prop))
1479
+ __defNormalProp$6(a, prop, b[prop]);
1480
+ if (__getOwnPropSymbols$6)
1481
+ for (var prop of __getOwnPropSymbols$6(b)) {
1482
+ if (__propIsEnum$6.call(b, prop))
1483
+ __defNormalProp$6(a, prop, b[prop]);
1484
+ }
1485
+ return a;
1486
+ };
1487
+ var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
1488
+ const buildServiceHeaders = async (settings, headers) => {
1489
+ var _a, _b, _c, _d, _e, _f, _g;
1490
+ const { token, platform, accountId: globalAccountId } = settings != null ? settings : {};
1491
+ const { accountId: localAccountId } = getState();
1492
+ const account = (_c = (_b = (_a = headers.get("account")) != null ? _a : localAccountId == null ? void 0 : localAccountId.toString()) != null ? _b : globalAccountId == null ? void 0 : globalAccountId.toString()) != null ? _c : "";
1493
+ const selectedPlatform = (_e = (_d = headers.get("Platform")) != null ? _d : platform) != null ? _e : "";
1494
+ const Platform = selectedPlatform;
1495
+ const Authorization = (_g = (_f = headers.get("Authorization")) != null ? _f : token) != null ? _g : "";
1496
+ return new Headers(__spreadProps$3(__spreadValues$6(__spreadValues$6({}, commonHeaders), headers), {
1497
+ Authorization,
1498
+ Platform,
1499
+ account
1500
+ }));
1501
+ };
1502
+
1503
+ const validateShoppingCart$1 = async (config, headers) => {
1504
+ const { id, latitude, longitude, apiURL } = config;
1505
+ verifyHeaders(headers);
1506
+ const token = headers.get("Authorization");
1507
+ const platform = headers.get("Platform");
1508
+ const accountId = headers.get("account");
1509
+ const settings = { token, platform, accountId };
1510
+ const selectedHeaders = await buildServiceHeaders(settings, headers);
1511
+ let url = `${apiURL}/api/shopping-cart/${id}/validateShoppingCart`;
1512
+ try {
1513
+ if (typeof latitude !== "undefined" && typeof longitude !== "undefined") {
1514
+ url += `?latitude=${latitude}&longitude=${longitude}`;
1515
+ }
1516
+ const data = await fetch(url, {
1517
+ headers: selectedHeaders
1518
+ }).then(async (data2) => {
1519
+ return await data2.json();
1520
+ });
1521
+ const shoppingCart = data.data;
1522
+ if (!shoppingCart)
1523
+ throw new Error("No shopping cart was found.");
1524
+ const storeAlerts = Object.values(shoppingCart.stores).reduce((acc, store) => {
1525
+ if (store.alerts.length)
1526
+ return [...acc, ...store.alerts];
1527
+ return acc;
1528
+ }, []);
1529
+ const products = getShoppingCartProducts(shoppingCart);
1530
+ const productsAlerts = products.map((item) => item.alerts).flat();
1531
+ const alerts = {
1532
+ stores: storeAlerts,
1533
+ products: productsAlerts
1534
+ };
1535
+ return alerts;
1536
+ } catch (e) {
1537
+ console.error(e.message);
1538
+ return {
1539
+ stores: [
1540
+ {
1541
+ errorLevel: 1,
1542
+ message: "Ocurri\xF3 un error desconocido, comun\xEDquese con soporte",
1543
+ type: ""
1544
+ }
1545
+ ],
1546
+ products: []
1547
+ };
1548
+ }
1549
+ };
1550
+
1551
+ const validateShoppingCart = async (builders, config = {}, headers) => {
1552
+ const { getShoppingCartNode } = builders != null ? builders : {};
1553
+ const reusedConfig = reuseGlobalConfig(config);
1554
+ checkValidateShoppingCartConfig(reusedConfig, headers);
1555
+ const { latitude, longitude, shoppingCartName, apiURL } = reusedConfig;
1556
+ const shoppingCartNode = await getShoppingCartNode(reusedConfig);
1557
+ const { id } = shoppingCartNode != null ? shoppingCartNode : {};
1558
+ if (typeof id === "undefined") {
1559
+ console.error(`Cannot use undefined as a shopping cart id. Shopping cart ${shoppingCartName} was not found. Validation canceled.`);
1560
+ return;
1561
+ }
1562
+ if (typeof apiURL === "undefined") {
1563
+ console.error("apiURL must be provided");
1564
+ return;
1565
+ }
1566
+ return await validateShoppingCart$1({ id, latitude, longitude, apiURL }, headers);
1567
+ };
1568
+
1569
+ var __defProp$5 = Object.defineProperty;
1570
+ var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
1571
+ var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
1572
+ var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
1573
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1574
+ var __spreadValues$5 = (a, b) => {
1575
+ for (var prop in b || (b = {}))
1576
+ if (__hasOwnProp$5.call(b, prop))
1577
+ __defNormalProp$5(a, prop, b[prop]);
1578
+ if (__getOwnPropSymbols$5)
1579
+ for (var prop of __getOwnPropSymbols$5(b)) {
1580
+ if (__propIsEnum$5.call(b, prop))
1581
+ __defNormalProp$5(a, prop, b[prop]);
1582
+ }
1583
+ return a;
1584
+ };
1585
+ const unsubscriber = (shoppingCartName, unsubscribe) => {
1586
+ const { wallets } = getState();
1587
+ const newWallets = __spreadValues$5({}, wallets);
1588
+ delete newWallets[shoppingCartName];
1589
+ setState({ wallets: newWallets });
1590
+ if (unsubscribe)
1591
+ unsubscribe();
1592
+ };
1593
+
1594
+ const fetchWalletByUser = async (config, headers) => {
1595
+ const { vendorId, customerId, apiURL } = config;
1596
+ verifyHeaders(headers);
1597
+ const token = headers.get("Authorization");
1598
+ const platform = headers.get("Platform");
1599
+ const accountId = headers.get("account");
1600
+ const settings = { token, platform, accountId };
1601
+ headers.set("uid", customerId.toString());
1602
+ const selectedHeaders = await buildServiceHeaders(settings, headers);
1603
+ let serviceURL = "/api/shopping-cart/retrieveBenefits";
1604
+ if (vendorId)
1605
+ serviceURL = serviceURL + `?vendorId=${vendorId}`;
1606
+ const url = `${apiURL}${serviceURL}`;
1607
+ const data = await fetch(url, {
1608
+ headers: selectedHeaders
1609
+ }).then(async (data2) => {
1610
+ return await data2.json();
1611
+ }).catch((e) => {
1612
+ throw new Error(`Failed to retrieve the user's wallet
1613
+ ${e.message}`);
1614
+ });
1615
+ if (!data) {
1616
+ throw new Error(`The benefits wallet is not defined. Make sure coupons are well configured`);
1617
+ }
1618
+ };
1619
+ const redeemCouponService = async (config, code, headers) => {
1620
+ const { customerId, apiURL } = config;
1621
+ verifyHeaders(headers);
1622
+ const token = headers.get("Authorization");
1623
+ const platform = headers.get("Platform");
1624
+ const accountId = headers.get("account");
1625
+ const settings = { token, platform, accountId };
1626
+ headers.set("uid", customerId.toString());
1627
+ const selectedHeaders = await buildServiceHeaders(settings, headers);
1628
+ try {
1629
+ const url = `${apiURL}/api/wallet_profit/apply`;
1630
+ const result = await fetch(url, {
1631
+ method: "post",
1632
+ body: JSON.stringify({ code }),
1633
+ headers: selectedHeaders
1634
+ }).then(async (data2) => {
1635
+ return await data2.json();
1636
+ });
1637
+ const response = result;
1638
+ const { code: responseCode, data, message } = response;
1639
+ if (responseCode === 200)
1640
+ return true;
1641
+ if (!data)
1642
+ throw new Error(message.code);
1643
+ logError(`Unhandled response when redeeming coupon ${JSON.stringify(response, void 0, 2)}`);
1644
+ return false;
1645
+ } catch (e) {
1646
+ throw new Error(e.message);
1647
+ }
1648
+ };
1649
+ const applyBenefitService = async (config, headers) => {
1650
+ var _a, _b;
1651
+ const { benefit, customerId, shoppingCartId, apiURL } = config;
1652
+ const { benefitId } = benefit;
1653
+ verifyHeaders(headers);
1654
+ const token = headers.get("Authorization");
1655
+ const platform = headers.get("Platform");
1656
+ const accountId = headers.get("account");
1657
+ const settings = { token, platform, accountId };
1658
+ headers.set("uid", customerId.toString());
1659
+ const selectedHeaders = await buildServiceHeaders(settings, headers);
1660
+ const selectedBenefitBody = {
1661
+ benefitId,
1662
+ shoppingCartId
1663
+ };
1664
+ const url = `${apiURL}/api/shopping-cart/applyBenefit`;
1665
+ const data = await fetch(url, {
1666
+ method: "post",
1667
+ body: JSON.stringify(selectedBenefitBody),
1668
+ headers: selectedHeaders
1669
+ }).then(async (data2) => {
1670
+ return await data2.json();
1671
+ });
1672
+ if ((data == null ? void 0 : data.code) !== 200) {
1673
+ throw new Error((_b = (_a = data.message) == null ? void 0 : _a.message) != null ? _b : data.message);
1674
+ }
1675
+ if ((data == null ? void 0 : data.data.length) === 0) {
1676
+ throw new Error("No benefits were applied to the current shopping cart");
1677
+ }
1678
+ return data;
1679
+ };
1680
+ const fetchStoreCoupons = async (config, headers) => {
1681
+ const { vendorId, apiURL } = config;
1682
+ checkVendorId(vendorId);
1683
+ const url = `${apiURL}/api/couponByPromotion/categories?orderBy=created_at&sortBy=DESC&vendorId=${vendorId}`;
1684
+ verifyHeaders(headers);
1685
+ const token = headers.get("Authorization");
1686
+ const platform = headers.get("Platform");
1687
+ const accountId = headers.get("account");
1688
+ const settings = { token, platform, accountId };
1689
+ const selectedHeaders = await buildServiceHeaders(settings, headers);
1690
+ const data = await fetch(url, {
1691
+ method: "get",
1692
+ headers: selectedHeaders
1693
+ }).then(async (data2) => {
1694
+ return await data2.json();
1695
+ });
1696
+ if ((data == null ? void 0 : data.code) !== 200)
1697
+ throw new Error(data.message);
1698
+ return data.data;
1699
+ };
1700
+ const fetchStoreCouponDetail = async (config, headers) => {
1701
+ const { couponId, countryId, apiURL } = config;
1702
+ checkStoreCouponDetailConfig(config);
1703
+ const url = `${apiURL}/api/coupon/${couponId}?countryId=${countryId}`;
1704
+ verifyHeaders(headers);
1705
+ const token = headers.get("Authorization");
1706
+ const platform = headers.get("Platform");
1707
+ const accountId = headers.get("account");
1708
+ const settings = { token, platform, accountId };
1709
+ const selectedHeaders = await buildServiceHeaders(settings, headers);
1710
+ const data = await fetch(url, {
1711
+ method: "get",
1712
+ headers: selectedHeaders
1713
+ }).then(async (data2) => {
1714
+ return await data2.json();
1715
+ });
1716
+ if ((data == null ? void 0 : data.code) !== 200)
1717
+ throw new Error(data.message);
1718
+ return data.data;
1719
+ };
1720
+
1721
+ var __defProp$4 = Object.defineProperty;
1722
+ var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
1723
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
1724
+ var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
1725
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1726
+ var __spreadValues$4 = (a, b) => {
1727
+ for (var prop in b || (b = {}))
1728
+ if (__hasOwnProp$4.call(b, prop))
1729
+ __defNormalProp$4(a, prop, b[prop]);
1730
+ if (__getOwnPropSymbols$4)
1731
+ for (var prop of __getOwnPropSymbols$4(b)) {
1732
+ if (__propIsEnum$4.call(b, prop))
1733
+ __defNormalProp$4(a, prop, b[prop]);
1734
+ }
1735
+ return a;
1736
+ };
1737
+ const applyBenefit = async (builders, config, headers) => {
1738
+ const reusedConfig = reuseGlobalConfig(config);
1739
+ checkMinimumConfigProvided(reusedConfig);
1740
+ const { benefitId, shoppingCartName } = reusedConfig;
1741
+ const { wallets } = getState();
1742
+ const errorMessage = checkBenefitConfigProvided(wallets, shoppingCartName, reusedConfig);
1743
+ if (errorMessage) {
1744
+ logError(errorMessage);
1745
+ return;
1746
+ }
1747
+ const activeWallet = wallets[shoppingCartName];
1748
+ const benefits = activeWallet.benefits;
1749
+ const benefitToApply = benefits.find((benefit) => benefit.benefitId === benefitId);
1750
+ if (!benefitToApply) {
1751
+ logError(`No benefit was found in the benefits wallet with the benefitId provided.`);
1752
+ return;
1753
+ }
1754
+ const { type: benefitType } = benefitToApply;
1755
+ switch (benefitType) {
1756
+ case "PRODUCT":
1757
+ return applyProductBenefitHelper(builders, reusedConfig, benefitToApply);
1758
+ case "ALTER_DELIVERY":
1759
+ return applyAlterDeliveryBenefitHelper(builders, reusedConfig, benefitToApply, headers);
1760
+ case "DISCOUNT_PERCENTAGE":
1761
+ case "DISCOUNT_FIXED":
1762
+ return applyDiscountBenefitHelper(builders, reusedConfig, benefitToApply, headers);
1763
+ default:
1764
+ logError("The benefit to be applied is not of type PRODUCT, DISCOUNT_PERCENTAGE, DISCOUNT_FIXED or ALTER_DELIVERY.");
1765
+ break;
1766
+ }
1767
+ };
1768
+ const applyProductBenefitHelper = async (builders, config, benefit) => {
1769
+ const { applyBenefitsToCart } = builders != null ? builders : {};
1770
+ const reusedConfig = reuseGlobalConfig(config);
1771
+ const { product, productConfig, anonymous } = reusedConfig;
1772
+ const { benefitId } = benefit;
1773
+ if (!product || !productConfig) {
1774
+ logError(`The product or the product configuration has not been provided to apply the selected benefit.`);
1775
+ return;
1776
+ }
1777
+ product.benefitId = benefitId;
1778
+ await (applyBenefitsToCart == null ? void 0 : applyBenefitsToCart(reusedConfig, benefit));
1779
+ await addProduct(builders, product, __spreadValues$4({
1780
+ anonymous
1781
+ }, productConfig));
1782
+ };
1783
+ const applyAlterDeliveryBenefitHelper = async (builders, config, benefit, headers) => {
1784
+ const { applyBenefitsToCart, getShoppingCartNode } = builders != null ? builders : {};
1785
+ const reusedConfig = reuseGlobalConfig(config);
1786
+ const { shippingCost, latitude, longitude, shoppingCartName } = reusedConfig;
1787
+ const { anonymous } = reusedConfig;
1788
+ if (!shippingCost || !latitude || !longitude) {
1789
+ logError("The shippingCost, latitude and longitude are required to apply the selected benefit.");
1790
+ return;
1791
+ }
1792
+ const { benefitWalletId, award } = benefit;
1793
+ if (Array.isArray(award)) {
1794
+ logError("To apply a ALTER_DELIVERY benefit, the award associated with the benefit cannot be an array.");
1795
+ return;
1796
+ }
1797
+ const { benefitId: awardBenefitId, discountPercentage } = award;
1798
+ const { subtotalBeforeTaxes } = shippingCost;
1799
+ const value = subtotalBeforeTaxes * (discountPercentage / 100);
1800
+ const benefitList = [];
1801
+ benefitList.push({
1802
+ benefitWalletId,
1803
+ benefitId: awardBenefitId,
1804
+ discountBase: subtotalBeforeTaxes,
1805
+ percentage: discountPercentage,
1806
+ priceCategory: "NORMAL",
1807
+ value
1808
+ });
1809
+ shippingCost.discounts = benefitList;
1810
+ await (applyBenefitsToCart == null ? void 0 : applyBenefitsToCart(reusedConfig, benefit, shippingCost));
1811
+ await validateShoppingCart({ getShoppingCartNode }, {
1812
+ latitude,
1813
+ longitude,
1814
+ shoppingCartName,
1815
+ anonymous
1816
+ }, headers);
1817
+ };
1818
+ const applyBenefitsHelper = (shoppingCart, benefit, shippingCost) => {
1819
+ const { hash } = benefit;
1820
+ const { benefits } = shoppingCart;
1821
+ const temporalBenefits = benefits != null ? benefits : [];
1822
+ temporalBenefits.push(benefit);
1823
+ shoppingCart.benefits = temporalBenefits;
1824
+ shoppingCart.benefitsHash = hash;
1825
+ if (shippingCost)
1826
+ shoppingCart.shippingCost = shippingCost;
1827
+ return shoppingCart;
1828
+ };
1829
+ const applyDiscountBenefitHelper = async (builders, config, benefit, headers) => {
1830
+ const reuseConfig = reuseGlobalConfig(config);
1831
+ const { customerId, shoppingCartId, shoppingCartName, apiURL } = reuseConfig;
1832
+ if (!customerId) {
1833
+ logError("To apply a DISCOUNT_PERCENTAGE or DISCOUNT_FIXED benefit, a customerId must be provided.");
1834
+ return;
1835
+ }
1836
+ if (!shoppingCartId) {
1837
+ logError("To apply a DISCOUNT_PERCENTAGE or DISCOUNT_FIXED benefit, a shoppingCartId must be provided.");
1838
+ return;
1839
+ }
1840
+ const shoppingCart = await getShoppingCart(builders, reuseConfig);
1841
+ if (!shoppingCart) {
1842
+ logError(`Cannot apply discount benefit because no shopping cart was found. Please ensure you create a shopping cart with name ${shoppingCartName} before continue.`);
1843
+ return;
1844
+ }
1845
+ const { subtotal } = getShoppingCartTotal(shoppingCart);
1846
+ if (benefit.type === "DISCOUNT_FIXED" && subtotal < Number(benefit.discountFixed)) {
1847
+ logError("Cannot apply DISCOUNT_FIXED benefit because discount is greater than cart subtotal.");
1848
+ return;
1849
+ }
1850
+ await applyBenefitService({ benefit, customerId, shoppingCartId, apiURL }, headers);
1851
+ };
1852
+
1853
+ var __defProp$3 = Object.defineProperty;
1854
+ var __defProps$2 = Object.defineProperties;
1855
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
1856
+ var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
1857
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1858
+ var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
1859
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1860
+ var __spreadValues$3 = (a, b) => {
1861
+ for (var prop in b || (b = {}))
1862
+ if (__hasOwnProp$3.call(b, prop))
1863
+ __defNormalProp$3(a, prop, b[prop]);
1864
+ if (__getOwnPropSymbols$3)
1865
+ for (var prop of __getOwnPropSymbols$3(b)) {
1866
+ if (__propIsEnum$3.call(b, prop))
1867
+ __defNormalProp$3(a, prop, b[prop]);
1868
+ }
1869
+ return a;
1870
+ };
1871
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
1872
+ const removeBenefit = async (builders, config) => {
1873
+ const { getShoppingCartNode, removeBenefitsFromCart } = builders != null ? builders : {};
1874
+ const { removeProduct } = builders != null ? builders : {};
1875
+ const reusedConfig = reuseGlobalConfig(config);
1876
+ checkMinimumConfigProvided(reusedConfig);
1877
+ const { benefitId, shoppingCartName } = reusedConfig;
1878
+ const { wallets } = getState();
1879
+ const errorMessage = checkBenefitConfigProvided(wallets, shoppingCartName, reusedConfig);
1880
+ if (errorMessage) {
1881
+ logError(errorMessage);
1882
+ return;
1883
+ }
1884
+ const activeWallet = wallets[shoppingCartName];
1885
+ const benefits = activeWallet.benefits;
1886
+ const benefitToRemove = benefits.find((benefit) => benefit.benefitId === benefitId);
1887
+ if (!benefitToRemove) {
1888
+ logError(`No benefit was found in the benefits wallet with the benefitId provided.`);
1889
+ return;
1890
+ }
1891
+ const { type: benefitType } = benefitToRemove;
1892
+ switch (benefitType) {
1893
+ case "PRODUCT":
1894
+ return removeProductBenefitHelper({ getShoppingCartNode, removeBenefitsFromCart, removeProduct }, reusedConfig, benefitToRemove);
1895
+ case "ALTER_DELIVERY":
1896
+ return removeAlterDeliveryBenefitHelper({ getShoppingCartNode, removeBenefitsFromCart }, reusedConfig, benefitToRemove);
1897
+ case "DISCOUNT_PERCENTAGE":
1898
+ case "DISCOUNT_FIXED":
1899
+ return removeBenefitsFromCart == null ? void 0 : removeBenefitsFromCart(reusedConfig, benefitToRemove);
1900
+ default:
1901
+ logError("The benefit to be removed is not of type PRODUCT, DISCOUNT_PERCENTAGE, DISCOUNT_FIXED or ALTER_DELIVERY.");
1902
+ break;
1903
+ }
1904
+ };
1905
+ const removeProductBenefitHelper = async (builders, config, benefit) => {
1906
+ const { removeBenefitsFromCart } = builders != null ? builders : {};
1907
+ const { removeProduct } = builders != null ? builders : {};
1908
+ const reusedConfig = reuseGlobalConfig(config);
1909
+ const { product, productConfig } = reusedConfig;
1910
+ const { store } = productConfig != null ? productConfig : {};
1911
+ if (!product || !store) {
1912
+ logError("The cart product and the store, inside benefitProductConfig object, are required to remove the selected benefit.");
1913
+ return;
1914
+ }
1915
+ reusedConfig.productConfig.store = __spreadProps$2(__spreadValues$3({}, store), { polygons: null });
1916
+ await (removeBenefitsFromCart == null ? void 0 : removeBenefitsFromCart(reusedConfig, benefit));
1917
+ await (removeProduct == null ? void 0 : removeProduct(product, productConfig));
1918
+ };
1919
+ const removeAlterDeliveryBenefitHelper = async (builders, config, benefit) => {
1920
+ const { removeBenefitsFromCart } = builders != null ? builders : {};
1921
+ const reusedConfig = reuseGlobalConfig(config);
1922
+ const { shippingCost } = reusedConfig;
1923
+ if (!shippingCost) {
1924
+ logError(`The shippingCost is require to remove the selected benefit.`);
1925
+ return;
1926
+ }
1927
+ return removeBenefitsFromCart == null ? void 0 : removeBenefitsFromCart(reusedConfig, benefit, shippingCost);
1928
+ };
1929
+ const removeBenefitsHelper = (shoppingCart, benefit, shippingCost) => {
1930
+ const { benefits } = shoppingCart;
1931
+ const { benefitId } = benefit;
1932
+ if (!benefits) {
1933
+ console.warn(`Cannot remove benefit because the shopping cart does not have benefits applied.`);
1934
+ return shoppingCart;
1935
+ }
1936
+ const benefitIdIndex = benefits.findIndex((benefit2) => benefit2.benefitId === benefitId);
1937
+ if (benefitIdIndex < 0) {
1938
+ console.warn(`This benefit cannot be removed because it is not applied to the shopping cart.`);
1939
+ return shoppingCart;
1940
+ }
1941
+ benefits.splice(benefitIdIndex, 1);
1942
+ delete shoppingCart.benefitsHash;
1943
+ if (shippingCost)
1944
+ shoppingCart.shippingCost = shippingCost;
1945
+ return shoppingCart;
1946
+ };
1947
+
1948
+ var __defProp$2 = Object.defineProperty;
1949
+ var __defProps$1 = Object.defineProperties;
1950
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
1951
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
1952
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
1953
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
1954
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1955
+ var __spreadValues$2 = (a, b) => {
1956
+ for (var prop in b || (b = {}))
1957
+ if (__hasOwnProp$2.call(b, prop))
1958
+ __defNormalProp$2(a, prop, b[prop]);
1959
+ if (__getOwnPropSymbols$2)
1960
+ for (var prop of __getOwnPropSymbols$2(b)) {
1961
+ if (__propIsEnum$2.call(b, prop))
1962
+ __defNormalProp$2(a, prop, b[prop]);
1963
+ }
1964
+ return a;
1965
+ };
1966
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
1967
+ const getInitialBenefitsWallet = (overrides = {}) => {
1968
+ return __spreadValues$2({ benefits: [] }, overrides);
1969
+ };
1970
+ const mapCollectionToBenefits = (benefitsNode, hash) => {
1971
+ const benefits = Object.values(benefitsNode).map((benefit) => {
1972
+ const newBenefit = __spreadProps$1(__spreadValues$2({}, benefit), { hash });
1973
+ return newBenefit;
1974
+ });
1975
+ return benefits;
1976
+ };
1977
+ const updateBenefitsWallets = (walletName, newWallet) => {
1978
+ const { wallets } = getState();
1979
+ const newWallets = __spreadProps$1(__spreadValues$2({}, wallets), {
1980
+ [walletName]: __spreadValues$2({}, newWallet)
1981
+ });
1982
+ setState({ wallets: newWallets });
1983
+ };
1984
+ const getBenefitsNode = async (builders, config = {}) => {
1985
+ const { getBenefitsCollection } = builders != null ? builders : {};
1986
+ const { accountId: globalAccountId } = getState();
1987
+ const { customerId: globalCustomerId } = getState();
1988
+ const { accountId, customerId } = config;
1989
+ checkMinimumConfigProvided(config);
1990
+ const benefitsCollection = await (getBenefitsCollection == null ? void 0 : getBenefitsCollection("benefitsByUser", String(customerId != null ? customerId : globalCustomerId), String(accountId != null ? accountId : globalAccountId)));
1991
+ return benefitsCollection;
1992
+ };
1993
+ const getWalletNode = async (builders, config) => {
1994
+ try {
1995
+ const { getBenefitsDocuments } = builders != null ? builders : {};
1996
+ const benefitsCollection = await getBenefitsNode(builders, config);
1997
+ if (!benefitsCollection)
1998
+ return;
1999
+ const newestBenefits = await (getBenefitsDocuments == null ? void 0 : getBenefitsDocuments(benefitsCollection));
2000
+ return newestBenefits;
2001
+ } catch (e) {
2002
+ console.error(e.message);
2003
+ }
2004
+ };
2005
+ const getWallet = async (builders, config) => {
2006
+ const benefitsByUserNode = await getWalletNode(builders, config);
2007
+ if (!benefitsByUserNode)
2008
+ return;
2009
+ if (Object.keys(benefitsByUserNode.data()).length === 0)
2010
+ return [];
2011
+ const hash = benefitsByUserNode.id;
2012
+ const benefitsData = Object.values(benefitsByUserNode.data());
2013
+ const benefits = benefitsData.map((benefit) => {
2014
+ const newBenefit = __spreadProps$1(__spreadValues$2({}, benefit), { hash });
2015
+ return newBenefit;
2016
+ });
2017
+ return benefits;
2018
+ };
2019
+
2020
+ var __defProp$1 = Object.defineProperty;
2021
+ var __defProps = Object.defineProperties;
2022
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2023
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2024
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2025
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2026
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2027
+ var __spreadValues$1 = (a, b) => {
2028
+ for (var prop in b || (b = {}))
2029
+ if (__hasOwnProp$1.call(b, prop))
2030
+ __defNormalProp$1(a, prop, b[prop]);
2031
+ if (__getOwnPropSymbols$1)
2032
+ for (var prop of __getOwnPropSymbols$1(b)) {
2033
+ if (__propIsEnum$1.call(b, prop))
2034
+ __defNormalProp$1(a, prop, b[prop]);
2035
+ }
2036
+ return a;
2037
+ };
2038
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
2039
+ const redeemCoupon = async (builders, config, code, headers) => {
2040
+ const { getWallet } = builders != null ? builders : {};
2041
+ const reusedConfig = reuseGlobalConfig(config);
2042
+ const { customerId, shoppingCartName } = reusedConfig;
2043
+ checkMinimumConfigProvided(config);
2044
+ verifyHeaders(headers);
2045
+ const { wallets } = getState();
2046
+ const activeWallet = wallets[shoppingCartName];
2047
+ if (!activeWallet) {
2048
+ logError(`No benefits wallet available for ${shoppingCartName}, you probably forgot to call listenBenefitsWallet beforehand.`);
2049
+ }
2050
+ await redeemCouponService(reusedConfig, code, headers);
2051
+ await fetchWalletByUser(reusedConfig, headers);
2052
+ const benefits = await (getWallet == null ? void 0 : getWallet({
2053
+ customerId,
2054
+ shoppingCartName
2055
+ }));
2056
+ if (!benefits) {
2057
+ throw new Error(`Failed to fetch benefits from firestore for the current customer after redeeming coupon`);
2058
+ }
2059
+ const updatedWallet = getInitialBenefitsWallet({
2060
+ benefits
2061
+ });
2062
+ const newInternalWallet = {
2063
+ benefits: [...updatedWallet.benefits],
2064
+ onSnapshot: activeWallet.onSnapshot
2065
+ };
2066
+ const newWallets = __spreadProps(__spreadValues$1({}, wallets), {
2067
+ [shoppingCartName]: newInternalWallet
2068
+ });
2069
+ setState({ wallets: newWallets });
2070
+ activeWallet.onSnapshot(updatedWallet);
2071
+ };
2072
+
2073
+ const mergeShoppingCart = async (builders, shoppingCart, config) => {
2074
+ return new Promise((resolve, reject) => {
2075
+ const action = async () => {
2076
+ try {
2077
+ const { getShoppingCartNode, setDoc } = builders != null ? builders : {};
2078
+ const shoppingCartNode = await (getShoppingCartNode == null ? void 0 : getShoppingCartNode(config));
2079
+ const reusedConfig = reuseGlobalConfig(config);
2080
+ if (!shoppingCartNode) {
2081
+ logDebug("Cannot merge the shopping carts because no shopping cart nodes were usedConfig found. Please ensure you have a shopping cart before continue.");
2082
+ resolve(null);
2083
+ return null;
2084
+ }
2085
+ let destinyShoppingCart = shoppingCartNode.data();
2086
+ const stores = Object.values(shoppingCart.stores);
2087
+ stores.forEach((store) => {
2088
+ const products = Object.values(store.products);
2089
+ products.forEach((product) => {
2090
+ const { amount } = product;
2091
+ destinyShoppingCart = addProductToCartHelper(destinyShoppingCart, product, {
2092
+ store,
2093
+ amount
2094
+ });
2095
+ });
2096
+ });
2097
+ await (setDoc == null ? void 0 : setDoc({
2098
+ reusedConfig,
2099
+ shoppingCartNode,
2100
+ payload: destinyShoppingCart
2101
+ }));
2102
+ resolve(destinyShoppingCart);
2103
+ return destinyShoppingCart;
2104
+ } catch (e) {
2105
+ reject(e);
2106
+ return null;
2107
+ }
2108
+ };
2109
+ const { eventLoop, queue } = getState();
2110
+ queue.enqueue(action);
2111
+ if (!eventLoop.isRunning)
2112
+ eventLoop.start();
2113
+ });
2114
+ };
2115
+
2116
+ var __defProp = Object.defineProperty;
2117
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
2118
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
2119
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
2120
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2121
+ var __spreadValues = (a, b) => {
2122
+ for (var prop in b || (b = {}))
2123
+ if (__hasOwnProp.call(b, prop))
2124
+ __defNormalProp(a, prop, b[prop]);
2125
+ if (__getOwnPropSymbols)
2126
+ for (var prop of __getOwnPropSymbols(b)) {
2127
+ if (__propIsEnum.call(b, prop))
2128
+ __defNormalProp(a, prop, b[prop]);
2129
+ }
2130
+ return a;
2131
+ };
2132
+ const updateShoppingCart = async (builders, setShoppingCart, config) => {
2133
+ return new Promise((resolve, reject) => {
2134
+ const action = async () => {
2135
+ try {
2136
+ const { setDoc, getShoppingCartNode } = builders != null ? builders : {};
2137
+ const reusedConfig = reuseGlobalConfig(config);
2138
+ const { shoppingCartName } = reuseGlobalConfig(config);
2139
+ const shoppingCartNode = await getShoppingCartNode(config);
2140
+ if (!shoppingCartNode) {
2141
+ console.warn(`Cannot update remote cart because no shopping cart was found. Please ensure you create a shopping cart with name ${shoppingCartName} before continue.`);
2142
+ resolve(null);
2143
+ return null;
2144
+ }
2145
+ const cart = await shoppingCartNode.data();
2146
+ const updatedCart = updateShoppingCartHelper(cart, setShoppingCart);
2147
+ await (setDoc == null ? void 0 : setDoc({
2148
+ reusedConfig,
2149
+ shoppingCartNode,
2150
+ payload: updatedCart
2151
+ }));
2152
+ resolve(updatedCart);
2153
+ return updatedCart;
2154
+ } catch (e) {
2155
+ reject(e);
2156
+ return null;
2157
+ }
2158
+ };
2159
+ const { eventLoop, queue } = getState();
2160
+ queue.enqueue(action);
2161
+ if (!eventLoop.isRunning)
2162
+ eventLoop.start();
2163
+ });
2164
+ };
2165
+ const updateShoppingCartHelper = (cart, setShoppingCart) => {
2166
+ const updatedCart = __spreadValues(__spreadValues({}, cart), setShoppingCart(cart));
2167
+ return updatedCart;
2168
+ };
2169
+
2170
+ exports.ActionQueue = ActionQueue;
2171
+ exports.CONSTANTS = CONSTANTS;
2172
+ exports.EventLoop = EventLoop;
2173
+ exports.addProduct = addProduct;
2174
+ exports.addProductToCartHelper = addProductToCartHelper;
2175
+ exports.applyBenefit = applyBenefit;
2176
+ exports.applyBenefitsHelper = applyBenefitsHelper;
2177
+ exports.buildInitialShoppingCart = buildInitialShoppingCart;
2178
+ exports.buildServiceHeaders = buildServiceHeaders;
2179
+ exports.checkInit = checkInit;
2180
+ exports.checkInitialized = checkInitialized;
2181
+ exports.checkMinimumConfigProvided = checkMinimumConfigProvided;
2182
+ exports.checkMinimumFetchWalletConfigProvided = checkMinimumFetchWalletConfigProvided;
2183
+ exports.cleanShoppingCart = cleanShoppingCart;
2184
+ exports.closeShoppingCart = closeShoppingCart;
2185
+ exports.defaultSort = defaultSort;
2186
+ exports.deleteShoppingCart = deleteShoppingCart;
2187
+ exports.emptyShoppingCart = emptyShoppingCart;
2188
+ exports.fetchStoreCouponDetail = fetchStoreCouponDetail;
2189
+ exports.fetchStoreCoupons = fetchStoreCoupons;
2190
+ exports.fetchWalletByUser = fetchWalletByUser;
2191
+ exports.findProduct = findProduct;
2192
+ exports.getBenefitsNode = getBenefitsNode;
2193
+ exports.getInitialBenefitsWallet = getInitialBenefitsWallet;
2194
+ exports.getProductHash = getProductHash;
2195
+ exports.getShoppingCart = getShoppingCart;
2196
+ exports.getShoppingCartProducts = getShoppingCartProducts;
2197
+ exports.getShoppingCartTotal = getShoppingCartTotal;
2198
+ exports.getState = getState;
2199
+ exports.getStore = getStore;
2200
+ exports.getWallet = getWallet;
2201
+ exports.getWalletNode = getWalletNode;
2202
+ exports.initShoppingCart = initShoppingCart;
2203
+ exports.initialState = initialState;
2204
+ exports.logDebug = logDebug;
2205
+ exports.logError = logError;
2206
+ exports.mapCollectionToBenefits = mapCollectionToBenefits;
2207
+ exports.mergeShoppingCart = mergeShoppingCart;
2208
+ exports.pruneQuestionsAndAnswers = pruneQuestionsAndAnswers;
2209
+ exports.redeemCoupon = redeemCoupon;
2210
+ exports.redeemCouponService = redeemCouponService;
2211
+ exports.removeBenefit = removeBenefit;
2212
+ exports.removeBenefitsHelper = removeBenefitsHelper;
2213
+ exports.removeProduct = removeProduct;
2214
+ exports.replaceProduct = replaceProduct;
2215
+ exports.reuseGlobalConfig = reuseGlobalConfig;
2216
+ exports.setProduct = setProduct;
2217
+ exports.setState = setState;
2218
+ exports.sortByField = sortByField;
2219
+ exports.sortByProductId = sortByProductId;
2220
+ exports.sortByQuestionId = sortByQuestionId;
2221
+ exports.subtractProduct = subtractProduct;
2222
+ exports.unsubscriber = unsubscriber;
2223
+ exports.updateBenefitsWallets = updateBenefitsWallets;
2224
+ exports.updateShoppingCart = updateShoppingCart;
2225
+ exports.validateShoppingCart = validateShoppingCart;
2226
+ exports.validateShoppingCartService = validateShoppingCart$1;
2227
+ exports.verifyHeaders = verifyHeaders;
2228
+
2229
+ Object.defineProperty(exports, '__esModule', { value: true });
2230
+
2231
+ }));
2232
+ //# sourceMappingURL=bundle.umd.js.map