@artisan-commerce/shopping-cart-rn 0.1.0-canary.148.1

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.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ ## Artisn's Shopping Cart library
2
+
3
+ Manages a Artisn's framework shoppingcart
@@ -0,0 +1,265 @@
1
+ import * as _artisan_commerce_shopping_cart_core from '@artisan-commerce/shopping-cart-core';
2
+ import { ProductAddConfig, ProductRemoveConfig, ShoppingCartFetchConfig, ProductActionConfig, ProductSetConfig, ProductReplaceConfig, ShoppingCartCreateConfig, EmptyShoppingCartConfig, ShoppingCartConfig, BenefitsWalletConfig, ApplyBenefitConfig, RemoveBenefitConfig, RedeemCouponResponse, MoveCartConfig, ShoppingCartMergeConfig, FindProductConfig } from '@artisan-commerce/shopping-cart-core';
3
+ export { ProductActionConfig, ShoppingCartTotals, ValidateShoppingCartResult, fetchStoreCouponDetail, fetchStoreCoupons, getProductHash, getShoppingCartProducts, getShoppingCartTotal } from '@artisan-commerce/shopping-cart-core';
4
+ import { FirebaseFirestoreTypes } from '@react-native-firebase/firestore';
5
+ import * as _artisan_commerce_types from '@artisan-commerce/types';
6
+ import { ShoppingCart, Product, CartProduct, Wallet, AdditionalInfo } from '@artisan-commerce/types';
7
+
8
+ type ArtisnDBDocumentData = FirebaseFirestoreTypes.DocumentData;
9
+ type ArtisnDBCollectionReference<T extends ArtisnDBDocumentData> = FirebaseFirestoreTypes.CollectionReference<T>;
10
+ type ArtisnDBDocumentReference<T extends ArtisnDBDocumentData> = FirebaseFirestoreTypes.DocumentReference<T>;
11
+ type ArtisnDBQueryDocumentSnapshot<T extends ArtisnDBDocumentData> = FirebaseFirestoreTypes.QueryDocumentSnapshot<T>;
12
+ type ShoppingCartNode = ArtisnDBQueryDocumentSnapshot<ArtisnDBDocumentData>;
13
+ type ShoppingCartNodes = ArtisnDBCollectionReference<ArtisnDBDocumentData>;
14
+ type ShoppingCartReference = ArtisnDBDocumentReference<ArtisnDBDocumentData>;
15
+ interface CompatibleShoppingCartNode extends Omit<ShoppingCartNode, "isEqual"> {
16
+ }
17
+ interface SetDoc {
18
+ reusedConfig?: Omit<ProductAddConfig | ProductRemoveConfig, "store">;
19
+ shoppingCartNode?: CompatibleShoppingCartNode;
20
+ payload: ShoppingCartReference;
21
+ }
22
+ interface DeleteDoc {
23
+ reusedConfig?: Omit<ProductAddConfig | ProductRemoveConfig, "store">;
24
+ shoppingCartNode?: CompatibleShoppingCartNode;
25
+ }
26
+
27
+ /**
28
+ * Fetches a shopping cart of the given customer and account, given by the
29
+ * specified name.
30
+ *
31
+ * @since 0.1.0
32
+ * @param {ShoppingCartConfig} config Function call level shopping cart
33
+ * configuration
34
+ * @returns {ShoppingCartNode} The shopping cart of a given customer in the form
35
+ * of firestore document nodes given by its name
36
+ */
37
+ declare const getShoppingCartNode: (config: ShoppingCartFetchConfig) => Promise<ShoppingCartNode | undefined>;
38
+ /**
39
+ * Fetches a shopping cart of the given customer and account, given by the
40
+ * specified name.
41
+ * .
42
+ *
43
+ * @since 0.1.0
44
+ * @param config Function call level shopping cart configuration
45
+ * @returns The shopping cart of a given customer given by its specified name
46
+ */
47
+ declare const getShoppingCart: (config: ShoppingCartFetchConfig) => Promise<ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
48
+ /**
49
+ * Listens on realtime to any change of the default or
50
+ * named shopping cart of a given customer.
51
+ *
52
+ * @template T Shopping cart generic type
53
+ * @since 0.1.0
54
+ * @param {Function} onSnapshot Callback function that receives the latest
55
+ * shopping cart on any updates to the cart
56
+ * @param {ShoppingCartConfig} config Shopping cart custom configuration
57
+ */
58
+ declare const listenShoppingCart: <T extends ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> = ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo>>(onSnapshot: (shoppingCart: T | undefined) => void, config: ShoppingCartFetchConfig) => () => void;
59
+
60
+ declare const addProduct: (product: Product, config: ProductAddConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
61
+
62
+ /**
63
+ * Subtracts a product amount async to the remote shopping cart.
64
+ *
65
+ * @template T Shopping cart generic type
66
+ * @since 0.1.0
67
+ * @param {Product} product The product object that will be subtracted from the
68
+ * cart. It can be a BaseProduct, a DetailedProduct or a CartProduct
69
+ * @param {ProductActionConfig} config A configuration that specifies how to
70
+ * make an action over a product. E.g specify the amount
71
+ */
72
+ declare const subtractProduct: (product: Product, config: ProductActionConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
73
+
74
+ /**
75
+ * Removes a product async from the remote shopping cart
76
+ *
77
+ * @template T Shopping cart generic type
78
+ * @since 0.1.0
79
+ * @param {Product} product the product object that will be removed from the
80
+ * cart. It can be a BaseProduct, a DetailedProduct or a CartProduct
81
+ * @param {ProductRemoveConfig} config global configuration overrides. E.g
82
+ * storeId
83
+ */
84
+ declare const removeProduct: (product: Product, config: ProductRemoveConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
85
+
86
+ /**
87
+ * Sets a product async in the remote shopping cart
88
+ *
89
+ * @template T Shopping cart generic type
90
+ * @since 0.1.0
91
+ * @param {Product} product The product object that will be set in the cart. It
92
+ * can be a BaseProduct, a DetailedProduct or a CartProduct
93
+ * @param {ProductSetConfig} config A configuration that specifies how to make
94
+ * an action over a product. E.g specify the amount
95
+ */
96
+ declare const setProduct: (product: Product, config: ProductSetConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
97
+
98
+ /**
99
+ * Replaces an existing product async in the remote shopping cart
100
+ *
101
+ * @template T Shopping cart generic type
102
+ * @since 0.1.0
103
+ * @param {CartProduct} product The product object that will be replaced in the
104
+ * cart. It can only be a CartProduct
105
+ * @param {ProductReplaceConfig} config A configuration that specifies how to
106
+ * make an action over a product. E.g specify the store
107
+ */
108
+ declare const replaceProduct: (product: CartProduct, config: ProductReplaceConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
109
+
110
+ /**
111
+ * Creates a new shopping cart to the authenticated user.
112
+ *
113
+ * @template T Shopping cart generic type
114
+ * @since 0.1.0
115
+ * @param {Partial<ShoppingCart>} overrides Initial state for one or
116
+ * more shopping cart properties
117
+ * @param {ShoppingCartCreateConfig} config Shopping cart custom configuration
118
+ */
119
+ declare const createShoppingCart: <T extends ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> = ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo>>(config: ShoppingCartCreateConfig, overrides?: Partial<T>) => Promise<T | null>;
120
+
121
+ /**
122
+ * Removes all products in all stores of a given cart. It will attempt to delete
123
+ * the last active shopping cart otherwise the default.
124
+ *
125
+ * If a vendor identifier is specified in the configuration object, it will
126
+ * remove all stores that have the specified vendor.
127
+ *
128
+ * @template T Shopping cart generic type
129
+ * @since 0.1.0
130
+ * @param {ShoppingCartConfig} config Empty shopping cart configuration
131
+ */
132
+ declare const emptyShoppingCart: (config: EmptyShoppingCartConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
133
+
134
+ /**
135
+ * Deletes a customer shopping cart given by its name. It will attempt to delete
136
+ * the last active shopping cart otherwise the default.
137
+ *
138
+ * @template T Shopping cart generic type
139
+ * @since 0.1.0
140
+ * @param {ShoppingCartConfig} config Function call level shopping cart
141
+ * configuration
142
+ */
143
+ declare const deleteShoppingCart: (config: ShoppingCartConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
144
+
145
+ /**
146
+ * Shopping cart validation options.
147
+ *
148
+ * @interface ValidateConfig
149
+ * @since 0.1.0
150
+ */
151
+ interface ValidateConfig extends ShoppingCartConfig {
152
+ /** Location latitude of the user */
153
+ latitude?: number;
154
+ /** Location latitude of the user */
155
+ longitude?: number;
156
+ /** Artisn project api url */
157
+ apiURL?: string;
158
+ }
159
+
160
+ /**
161
+ * Validate shopping cart integrity.
162
+ *
163
+ * @since 0.1.0
164
+ * @param {ValidateConfig} config Object that defines the properties to check
165
+ * whether the shopping cart is valid.
166
+ * @param {Partial<ValidateHeaders>} headers The shopping cart that will be
167
+ * validated. If none provided, then it will use default as its name.
168
+ * @return {Promise<ValidateShoppingCartResult | undefined>} An object which
169
+ * contains stores and products alerts
170
+ */
171
+ declare const validateShoppingCart: (config: ValidateConfig, headers?: Headers) => Promise<_artisan_commerce_shopping_cart_core.ValidateShoppingCartResult | undefined>;
172
+
173
+ /**
174
+ * Listens on realtime to any change of the default or named wallet
175
+ * of a given customer.
176
+ *
177
+ * @since 0.1.0
178
+ * @param {Function} onSnapshot Callback function that
179
+ * receives the latest wallet on any updates to the cart
180
+ * @param {BenefitsWalletConfig} config Configuration object to fetch a wallet
181
+ * @param {Partial<WalletHeaders>} headers Optional headers to be passed to
182
+ * retrieve the wallet of the current user
183
+ */
184
+ declare const listenBenefitsWallet: (onSnapshot: (wallet: Wallet) => void, config: BenefitsWalletConfig, headers?: Headers) => () => void;
185
+
186
+ /**
187
+ * Apply a benefit with the given configuration on the current shopping cart.
188
+ *
189
+ * @since 0.1.0
190
+ * @param {ApplyBenefitConfig} config Benefits wallet configuration and
191
+ * parameters to be passed to apply in shopping cart
192
+ */
193
+ declare const applyBenefit: (config: ApplyBenefitConfig, headers?: Headers) => Promise<void>;
194
+
195
+ /**
196
+ * Remove a benefit with the given config on the current shopping cart.
197
+ *
198
+ * @since 0.1.0
199
+ * @param {RemoveBenefitConfig} config Benefits wallet configuration and
200
+ * parameters to be passed to remove in shopping cart
201
+ */
202
+ declare const removeBenefit: (config: RemoveBenefitConfig) => Promise<void>;
203
+
204
+ /**
205
+ * Redeems a coupon based on the code given.
206
+ *
207
+ * @since 0.1.0
208
+ * @param {BenefitsWalletConfig} config Benefits wallet configuration parameters
209
+ * to be passed to call the endpoint.
210
+ * @param {string} code The code that the user inputs on the app.
211
+ * @param {Partial<WalletHeaders>} headers Headers to be passed to call the
212
+ * endpoint, as a default header, the uid is fetched internally.
213
+ * @returns {Promise<RedeemCouponResponse>} Redeem coupon response.
214
+ */
215
+ declare const redeemCoupon: (config: BenefitsWalletConfig, code: string, headers?: Headers) => Promise<RedeemCouponResponse>;
216
+
217
+ /**
218
+ * Moves the current shopping cart to the provided latitude and longitude and
219
+ * replaces the current store id inside the shopping cart with the provided one.
220
+ *
221
+ * @param config Shopping cart configuration to get the current shopping cart
222
+ */
223
+ declare const moveShoppingCart: (config: MoveCartConfig) => Promise<_artisan_commerce_types.ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> | null>;
224
+
225
+ /**
226
+ * Merge a shopping cart to the current shopping cart or to the one specified
227
+ * through the configuration.
228
+ *
229
+ * @template T Shopping cart generic type
230
+ * @since 0.1.0
231
+ * @param {ShoppingCart} shoppingCart Shopping cart to be merged
232
+ * @param {ShoppingCartMergeConfig} config Configuration to get the current shopping
233
+ * cart
234
+ */
235
+ declare const mergeShoppingCart: <T extends ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> = ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo>>(shoppingCart: T, config: ShoppingCartMergeConfig) => Promise<T | null>;
236
+
237
+ /**
238
+ * Returns the specified product based on its id or hash if it exists on the
239
+ * active shopping cart. If both are provided, the hash takes precedence
240
+ * over the product id.
241
+ *
242
+ * @param {FindProductConfig} config Configuration provided to find the
243
+ * desired product
244
+ * @returns {Promise<Product|undefined>} The product if found in the
245
+ * shopping cart
246
+ */
247
+ declare const findProduct: <T extends AdditionalInfo = AdditionalInfo, U extends AdditionalInfo = AdditionalInfo>(config: FindProductConfig) => Promise<CartProduct<T, U> | undefined>;
248
+
249
+ /**
250
+ * Sets properties in the shopping cart remotely.
251
+ *
252
+ * @template T Shopping cart generic type
253
+ * @since 0.1.0
254
+ * @param {Function} shoppingCart The cart that will be set remotely
255
+ * @param {ShoppingCartConfig} config Shopping cart configuration
256
+ */
257
+ declare const updateShoppingCart: <T extends ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo> = ShoppingCart<_artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo, _artisan_commerce_types.AdditionalInfo>>(setShoppingCart: (previousShoppingCart: T) => T, config: ShoppingCartConfig) => Promise<T | null>;
258
+
259
+ declare const setDoc: (config: SetDoc) => Promise<void>;
260
+ declare const deleteDoc: (config: DeleteDoc) => Promise<void>;
261
+ declare const getCollectionReference: (collectionName: string, ...path: string[]) => Promise<ShoppingCartNodes>;
262
+ declare const getDocumentsByCollections: (collectionReference: ShoppingCartNodes) => Promise<ShoppingCartNode>;
263
+
264
+ export { addProduct, applyBenefit, createShoppingCart, deleteDoc, deleteShoppingCart, emptyShoppingCart, findProduct, getCollectionReference, getDocumentsByCollections, getShoppingCart, getShoppingCartNode, listenBenefitsWallet, listenShoppingCart, mergeShoppingCart, moveShoppingCart, redeemCoupon, removeBenefit, removeProduct, replaceProduct, setDoc, setProduct, subtractProduct, updateShoppingCart, validateShoppingCart };
265
+ export type { ShoppingCartReference };
@@ -0,0 +1,338 @@
1
+ import { updateShoppingCart as updateShoppingCart$1, reuseGlobalConfig, State, logDebug, updateCartProductsHash, getShoppingCart as getShoppingCart$1, checkMinimumConfigProvided, createShoppingCartSync, addProduct as addProduct$1, subtractProduct as subtractProduct$1, removeProduct as removeProduct$1, setProduct as setProduct$1, replaceProduct as replaceProduct$1, emptyShoppingCart as emptyShoppingCart$1, deleteShoppingCart as deleteShoppingCart$1, validateShoppingCart as validateShoppingCart$1, getBenefitsNode as getBenefitsNode$1, getWallet as getWallet$1, buildServiceHeaders, checkMinimumFetchWalletConfigProvided, verifyHeaders, listenBenefitsWalletUnsubscribe, logError, getInitialBenefitsWallet, updateBenefitsWallets, fetchWalletByUser, mapCollectionToBenefits, applyBenefit as applyBenefit$1, applyBenefitSync, removeBenefit as removeBenefit$1, removeBenefitsHelper, redeemCoupon as redeemCoupon$1, moveShoppingCart as moveShoppingCart$1, mergeShoppingCart as mergeShoppingCart$1, findProduct as findProduct$1 } from '@artisan-commerce/shopping-cart-core';
2
+ export { fetchStoreCouponDetail, fetchStoreCoupons, getProductHash, getShoppingCartProducts, getShoppingCartTotal } from '@artisan-commerce/shopping-cart-core';
3
+ import firestore from '@react-native-firebase/firestore';
4
+
5
+ const setDoc = async (config) => {
6
+ const { payload, shoppingCartNode } = config != null ? config : {};
7
+ await (shoppingCartNode == null ? void 0 : shoppingCartNode.ref.set(payload));
8
+ };
9
+ const deleteDoc = async (config) => {
10
+ const { shoppingCartNode } = config != null ? config : {};
11
+ await (shoppingCartNode == null ? void 0 : shoppingCartNode.ref.delete());
12
+ };
13
+ const getCollectionReference = async (collectionName, ...path) => {
14
+ var _a, _b;
15
+ const [customerId, accountId] = path;
16
+ const db = firestore();
17
+ const collection = await ((_b = (_a = db == null ? void 0 : db.collection(collectionName)) == null ? void 0 : _a.doc(String(customerId))) == null ? void 0 : _b.collection(String(accountId)));
18
+ return collection;
19
+ };
20
+ const getDocumentsByCollections = async (collectionReference) => {
21
+ const queryDocuments = await collectionReference.get().then((result) => result.docs[0]);
22
+ return queryDocuments;
23
+ };
24
+
25
+ const updateShoppingCart = async (setShoppingCart, config) => {
26
+ return updateShoppingCart$1({ getShoppingCartNode, setDoc }, setShoppingCart, config);
27
+ };
28
+
29
+ var __defProp$2 = Object.defineProperty;
30
+ var __defProps$2 = Object.defineProperties;
31
+ var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
32
+ var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
33
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
34
+ var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
35
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
36
+ var __spreadValues$2 = (a, b) => {
37
+ for (var prop in b || (b = {}))
38
+ if (__hasOwnProp$2.call(b, prop))
39
+ __defNormalProp$2(a, prop, b[prop]);
40
+ if (__getOwnPropSymbols$2)
41
+ for (var prop of __getOwnPropSymbols$2(b)) {
42
+ if (__propIsEnum$2.call(b, prop))
43
+ __defNormalProp$2(a, prop, b[prop]);
44
+ }
45
+ return a;
46
+ };
47
+ var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
48
+ const getShoppingCartNodes = (config) => {
49
+ var _a, _b;
50
+ const reusedConfig = reuseGlobalConfig(config);
51
+ const { accountId, customerId, anonymous } = reusedConfig;
52
+ checkMinimumConfigProvided(reusedConfig);
53
+ const path = anonymous ? "anonymousShoppingCartByUser" : "shoppingCartByUser";
54
+ const db = firestore();
55
+ const cartsCollection = (_b = (_a = db == null ? void 0 : db.collection(path)) == null ? void 0 : _a.doc(String(customerId))) == null ? void 0 : _b.collection(String(accountId));
56
+ return cartsCollection;
57
+ };
58
+ const getShoppingCartNode = async (config) => {
59
+ const reusedConfig = reuseGlobalConfig(config);
60
+ const { shoppingCartName } = reusedConfig;
61
+ const cartsCollection = getShoppingCartNodes(reusedConfig);
62
+ if (!cartsCollection)
63
+ return;
64
+ const newestCart = await cartsCollection.where("name", "==", shoppingCartName).get().then((userCarts) => {
65
+ return userCarts.docs[0];
66
+ });
67
+ return newestCart;
68
+ };
69
+ const getShoppingCart = async (config) => {
70
+ const cart = await getShoppingCart$1({ getShoppingCartNode }, config);
71
+ if (!cart)
72
+ return cart;
73
+ const updatedCart = updateCartProductsHash(cart);
74
+ if (!updatedCart)
75
+ return cart;
76
+ updateShoppingCart((prev) => __spreadProps$2(__spreadValues$2({}, prev), { stores: updatedCart.stores }), config);
77
+ return updatedCart;
78
+ };
79
+ const listenShoppingCart = (onSnapshot, config) => {
80
+ const reusedConfig = reuseGlobalConfig(config);
81
+ const { shoppingCartName, debug } = reusedConfig;
82
+ const shoppingCartDocs = getShoppingCartNodes(reusedConfig);
83
+ if (!shoppingCartDocs) {
84
+ return () => {
85
+ };
86
+ }
87
+ State().setState({
88
+ activeShoppingCart: shoppingCartName,
89
+ debug: debug != null ? debug : false
90
+ });
91
+ return shoppingCartDocs.where("name", "==", shoppingCartName).onSnapshot((snapshot) => {
92
+ var _a;
93
+ if (!((_a = snapshot == null ? void 0 : snapshot.docs) == null ? void 0 : _a[0])) {
94
+ logDebug(`Failed to fetch a shopping cart with name ${shoppingCartName} because there wasn't any.`);
95
+ return onSnapshot(void 0);
96
+ }
97
+ const cart = snapshot.docs[0].data();
98
+ const cartProductsUpdated = updateCartProductsHash(cart);
99
+ if (cartProductsUpdated) {
100
+ updateShoppingCart((prev) => {
101
+ return __spreadProps$2(__spreadValues$2({}, prev), { stores: cartProductsUpdated.stores });
102
+ }, reusedConfig);
103
+ return;
104
+ }
105
+ if ((cart == null ? void 0 : cart.id) === "" || (cart == null ? void 0 : cart.id) === null)
106
+ return;
107
+ return onSnapshot(cart);
108
+ });
109
+ };
110
+
111
+ var __defProp$1 = Object.defineProperty;
112
+ var __defProps$1 = Object.defineProperties;
113
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
114
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
115
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
116
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
117
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
118
+ var __spreadValues$1 = (a, b) => {
119
+ for (var prop in b || (b = {}))
120
+ if (__hasOwnProp$1.call(b, prop))
121
+ __defNormalProp$1(a, prop, b[prop]);
122
+ if (__getOwnPropSymbols$1)
123
+ for (var prop of __getOwnPropSymbols$1(b)) {
124
+ if (__propIsEnum$1.call(b, prop))
125
+ __defNormalProp$1(a, prop, b[prop]);
126
+ }
127
+ return a;
128
+ };
129
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
130
+ const createShoppingCart = async (config, overrides = {}) => {
131
+ return new Promise((resolve, reject) => {
132
+ const action = async () => {
133
+ var _a;
134
+ try {
135
+ const reusedConfig = reuseGlobalConfig(config);
136
+ const { shoppingCartName } = reusedConfig;
137
+ const cartsCollection = getShoppingCartNodes(reusedConfig);
138
+ const newShoppingCart = createShoppingCartSync(__spreadValues$1({
139
+ name: shoppingCartName,
140
+ channelId: config == null ? void 0 : config.channelId
141
+ }, overrides));
142
+ if (!cartsCollection) {
143
+ console.warn(`Couldn't find a shopping cart collection with the given config.
144
+ Please make sure everything is correct in your configuration
145
+ before continue.`);
146
+ resolve(null);
147
+ return null;
148
+ }
149
+ const { name } = newShoppingCart;
150
+ const numberOfCarts = (_a = await cartsCollection.get()) == null ? void 0 : _a.docs.length;
151
+ const maxNumberOfCarts = State().state.maxShoppingCarts;
152
+ if (numberOfCarts >= maxNumberOfCarts) {
153
+ throw new Error(`Cannot add more carts. Carts limit (${maxNumberOfCarts}) reached.`);
154
+ }
155
+ const namedCartsDocs = await cartsCollection.where("name", "==", name).get();
156
+ const cartsLength = namedCartsDocs.docs.length;
157
+ if (cartsLength > 0) {
158
+ throw new Error(`Attempted to create a shopping cart with the name ${name}, but there is already one shopping cart with that name.`);
159
+ }
160
+ const node = await cartsCollection.add(newShoppingCart);
161
+ if (!node) {
162
+ console.error("Failed to create a new shopping cart");
163
+ resolve(null);
164
+ return null;
165
+ }
166
+ const updatedCart = __spreadProps$1(__spreadValues$1({}, newShoppingCart), { id: node.id });
167
+ await node.set(updatedCart);
168
+ resolve(updatedCart);
169
+ return updatedCart;
170
+ } catch (e) {
171
+ reject(e);
172
+ return null;
173
+ }
174
+ };
175
+ const { eventLoop, queue } = State().state;
176
+ queue.enqueue(action);
177
+ if (!eventLoop.isRunning)
178
+ eventLoop.start();
179
+ });
180
+ };
181
+
182
+ const addProduct = (product, config) => {
183
+ return addProduct$1({ getShoppingCartNode, setDoc, createShoppingCart }, product, config);
184
+ };
185
+
186
+ const subtractProduct = async (product, config) => {
187
+ return subtractProduct$1({ getShoppingCartNode, setDoc }, product, config);
188
+ };
189
+
190
+ const removeProduct = (product, config) => {
191
+ return removeProduct$1({ getShoppingCartNode, setDoc }, product, config);
192
+ };
193
+
194
+ const setProduct = async (product, config) => {
195
+ return setProduct$1({ getShoppingCartNode, setDoc }, product, config);
196
+ };
197
+
198
+ const replaceProduct = (product, config) => {
199
+ return replaceProduct$1({ getShoppingCartNode, setDoc }, product, config);
200
+ };
201
+
202
+ const emptyShoppingCart = async (config) => await emptyShoppingCart$1({ getShoppingCartNode, setDoc }, config);
203
+
204
+ const deleteShoppingCart = async (config) => await deleteShoppingCart$1({ getShoppingCartNode, deleteDoc }, config);
205
+
206
+ const validateShoppingCart = (config, headers = new Headers()) => {
207
+ return validateShoppingCart$1({ getShoppingCartNode }, config, headers);
208
+ };
209
+
210
+ const getBenefitsNode = (config) => {
211
+ return getBenefitsNode$1({ getBenefitsCollection: getCollectionReference }, config);
212
+ };
213
+ const getWallet = async (config) => {
214
+ return getWallet$1({
215
+ getBenefitsCollection: getCollectionReference,
216
+ getBenefitsDocuments: getDocumentsByCollections
217
+ }, config);
218
+ };
219
+
220
+ var __defProp = Object.defineProperty;
221
+ var __defProps = Object.defineProperties;
222
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
223
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
224
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
225
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
226
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
227
+ var __spreadValues = (a, b) => {
228
+ for (var prop in b || (b = {}))
229
+ if (__hasOwnProp.call(b, prop))
230
+ __defNormalProp(a, prop, b[prop]);
231
+ if (__getOwnPropSymbols)
232
+ for (var prop of __getOwnPropSymbols(b)) {
233
+ if (__propIsEnum.call(b, prop))
234
+ __defNormalProp(a, prop, b[prop]);
235
+ }
236
+ return a;
237
+ };
238
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
239
+ const listenBenefitsWallet = (onSnapshot, config, headers = new Headers()) => {
240
+ const selectedHeaders = buildServiceHeaders(headers);
241
+ const reusedConfig = reuseGlobalConfig(config);
242
+ checkMinimumFetchWalletConfigProvided(reusedConfig);
243
+ verifyHeaders(selectedHeaders);
244
+ const { shoppingCartName, customerId, anonymous } = reusedConfig;
245
+ const { wallets } = State().state;
246
+ const walletExists = wallets[shoppingCartName];
247
+ if (anonymous)
248
+ return () => listenBenefitsWalletUnsubscribe(shoppingCartName);
249
+ if (walletExists) {
250
+ logError(`There is already a listener for wallet of name ${shoppingCartName}. Either unsubscribe to the other listener or create a new listener for a different cart`);
251
+ return () => listenBenefitsWalletUnsubscribe(shoppingCartName);
252
+ }
253
+ const newWallet = getInitialBenefitsWallet();
254
+ updateBenefitsWallets(shoppingCartName, __spreadProps(__spreadValues({}, newWallet), { onSnapshot }));
255
+ let dbUnsubscriber = void 0;
256
+ (async () => {
257
+ const fetchConfig = __spreadProps(__spreadValues({}, reusedConfig), { customerId });
258
+ try {
259
+ await fetchWalletByUser(fetchConfig, selectedHeaders);
260
+ const benefitsNode = await getBenefitsNode(reusedConfig);
261
+ if (!benefitsNode) {
262
+ throw new Error("Failed to retrieve the benefits wallet node");
263
+ }
264
+ dbUnsubscriber = benefitsNode.onSnapshot(async (collection) => {
265
+ var _a, _b, _c;
266
+ const benefitsByUser = (_c = (_b = (_a = collection == null ? void 0 : collection.docs) == null ? void 0 : _a[0]) == null ? void 0 : _b.data()) != null ? _c : {};
267
+ if (Object.keys(benefitsByUser).length === 0) {
268
+ const newWallet3 = getInitialBenefitsWallet();
269
+ updateBenefitsWallets(shoppingCartName, __spreadProps(__spreadValues({}, newWallet3), {
270
+ onSnapshot
271
+ }));
272
+ onSnapshot(newWallet3);
273
+ return;
274
+ }
275
+ const hash = collection.docs[0].id;
276
+ const benefits = mapCollectionToBenefits(benefitsByUser, hash);
277
+ const newWallet2 = getInitialBenefitsWallet({
278
+ benefits
279
+ });
280
+ updateBenefitsWallets(shoppingCartName, __spreadProps(__spreadValues({}, newWallet2), { onSnapshot }));
281
+ onSnapshot(newWallet2);
282
+ });
283
+ } catch (e) {
284
+ console.error(e.message);
285
+ }
286
+ })();
287
+ return () => listenBenefitsWalletUnsubscribe(shoppingCartName, dbUnsubscriber);
288
+ };
289
+
290
+ const applyBenefit = async (config, headers = new Headers()) => {
291
+ return applyBenefit$1({ getShoppingCartNode, applyBenefitsToCart, setDoc }, config, headers);
292
+ };
293
+ const applyBenefitsToCart = async (config, benefit, shippingCost) => {
294
+ const shoppingCartNode = await getShoppingCartNode(config);
295
+ if (!shoppingCartNode) {
296
+ console.warn("Cannot add benefit because no shopping cart nodes were found. Please ensure you have a shopping cart before continue.");
297
+ return;
298
+ }
299
+ const shoppingCart = await shoppingCartNode.data();
300
+ const updatedCart = applyBenefitSync(shoppingCart, benefit, shippingCost);
301
+ await shoppingCartNode.ref.set(updatedCart);
302
+ };
303
+
304
+ const removeBenefit = (config) => {
305
+ return removeBenefit$1({
306
+ getShoppingCartNode,
307
+ removeBenefitsFromCart,
308
+ removeProduct
309
+ }, config);
310
+ };
311
+ const removeBenefitsFromCart = async (config, benefit, shippingCost) => {
312
+ const shoppingCartNode = await getShoppingCartNode(config);
313
+ if (!shoppingCartNode) {
314
+ console.warn(`Cannot remove benefit because no shopping cart nodes were found. Please ensure you have a shopping cart before continue.`);
315
+ return;
316
+ }
317
+ const shoppingCart = await shoppingCartNode.data();
318
+ const updatedCart = removeBenefitsHelper(shoppingCart, benefit, shippingCost);
319
+ await shoppingCartNode.ref.set(updatedCart);
320
+ };
321
+
322
+ const redeemCoupon = async (config, code, headers = new Headers()) => {
323
+ return redeemCoupon$1({ getWallet, getShoppingCartNode }, config, code, headers);
324
+ };
325
+
326
+ const moveShoppingCart = async (config) => {
327
+ return await moveShoppingCart$1({ getShoppingCartNode, setDoc }, config);
328
+ };
329
+
330
+ const mergeShoppingCart = async (shoppingCart, config) => {
331
+ return mergeShoppingCart$1({ getShoppingCartNode, setDoc }, shoppingCart, config);
332
+ };
333
+
334
+ const findProduct = async (config) => {
335
+ return findProduct$1({ getShoppingCartNode }, config);
336
+ };
337
+
338
+ export { addProduct, applyBenefit, createShoppingCart, deleteDoc, deleteShoppingCart, emptyShoppingCart, findProduct, getCollectionReference, getDocumentsByCollections, getShoppingCart, getShoppingCartNode, listenBenefitsWallet, listenShoppingCart, mergeShoppingCart, moveShoppingCart, redeemCoupon, removeBenefit, removeProduct, replaceProduct, setDoc, setProduct, subtractProduct, updateShoppingCart, validateShoppingCart };
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@artisan-commerce/shopping-cart-rn",
3
+ "description": "Artisn's shopping cart",
4
+ "version": "0.1.0-canary.148.1",
5
+ "type": "module",
6
+ "main": "./dist/bundle.mjs",
7
+ "module": "./dist/bundle.mjs",
8
+ "types": "./dist/bundle.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "sideEffects": false,
13
+ "scripts": {
14
+ "compile": "rollup -c && npx agadoo",
15
+ "dev": "yarn compile -w",
16
+ "clean": "rimraf dist",
17
+ "prebuild": "yarn clean",
18
+ "build": "yarn compile",
19
+ "test": "jest --watchAll --runInBand",
20
+ "test:all": "yarn test --watchAll=false --coverage",
21
+ "test:ci": "cross-env CI=true jest --runInBand",
22
+ "test:staged": "yarn test:ci",
23
+ "check-types": "tsc --noEmit",
24
+ "lint": "eslint --ignore-path .gitignore --ignore-pattern !cypress/.eslintrc.cjs --ext .js,jsx,.ts,.tsx .",
25
+ "lint:staged": "yarn lint --max-warnings=0",
26
+ "prettier": "prettier --ignore-path .gitignore \"**/*.+(js|jsx|ts|tsx|json|css|scss|html)\"",
27
+ "format": "yarn prettier --write",
28
+ "check-format": "yarn prettier --list-different",
29
+ "validate": "cross-env CI=true npm-run-all --parallel test:ci check-types check-format lint build",
30
+ "validate:ci": "npm-run-all --parallel check-types check-format lint"
31
+ },
32
+ "author": "Luis Eduardo Andrade",
33
+ "license": "MIT",
34
+ "devDependencies": {
35
+ "@artisan-commerce/builders": "0.7.0-canary.44",
36
+ "@artisan-commerce/products": "0.9.0-canary.47",
37
+ "@artisan-commerce/state": "0.1.0-canary.148.1",
38
+ "@artisan-commerce/types": "0.1.0-canary.148.1",
39
+ "@react-native-firebase/firestore": "^12.8.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@artisan-commerce/products": "*",
43
+ "@artisan-commerce/state": "*",
44
+ "@react-native-firebase/app": "*",
45
+ "@react-native-firebase/firestore": "*"
46
+ },
47
+ "gitHead": "6eba4472f02d97014a030d651610de6e3ebcfbed",
48
+ "nx": {
49
+ "targets": {
50
+ "build": {
51
+ "outputs": [
52
+ "{projectRoot}/dist"
53
+ ]
54
+ },
55
+ "compile": {
56
+ "outputs": [
57
+ "{projectRoot}/dist"
58
+ ]
59
+ },
60
+ "test:all": {
61
+ "outputs": [
62
+ "{projectRoot}/coverage"
63
+ ]
64
+ }
65
+ }
66
+ },
67
+ "dependencies": {
68
+ "@artisan-commerce/shopping-cart-core": "0.1.0-canary.148.1"
69
+ }
70
+ }