This repository has been archived by the owner on Jun 9, 2022. It is now read-only.
forked from imranhsayed/woo-next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.js
323 lines (258 loc) · 8.83 KB
/
functions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { v4 } from 'uuid';
/**
* Extracts and returns float value from a string.
*
* @param {string} string String
* @return {any}
*/
export const getFloatVal = ( string ) => {
let floatValue = string.match( /[+-]?\d+(\.\d+)?/g )[0];
return ( null !== floatValue ) ? parseFloat( parseFloat( floatValue ).toFixed( 2 ) ) : '';
};
/**
* Add first product.
*
* @param {Object} product Product
* @return {{totalProductsCount: number, totalProductsPrice: any, products: Array}}
*/
export const addFirstProduct = ( product ) => {
let productPrice = getFloatVal( product.price );
let newCart = {
products: [],
totalProductsCount: 1,
totalProductsPrice: productPrice
};
const newProduct = createNewProduct( product, productPrice, 1 );
newCart.products.push( newProduct );
localStorage.setItem( 'woo-next-cart', JSON.stringify( newCart ) );
return newCart;
};
/**
* Create a new product object.
*
* @param {Object} product Product
* @param {Integer} productPrice Product Price
* @param {Integer} qty Quantity
* @return {{image: *, productId: *, totalPrice: number, price: *, qty: *, name: *}}
*/
export const createNewProduct = ( product, productPrice, qty ) => {
return {
productId: product.productId,
image: product.image,
name: product.name,
price: productPrice,
qty,
totalPrice: parseFloat( ( productPrice * qty ).toFixed( 2 ) )
};
};
/**
* Updates the existing cart with new item.
*
* @param {Object} existingCart Existing Cart.
* @param {Object} product Product.
* @param {Integer} qtyToBeAdded Quantity.
* @param {Integer} newQty New Qty to be updated.
* @return {{totalProductsCount: *, totalProductsPrice: *, products: *}}
*/
export const updateCart = ( existingCart, product, qtyToBeAdded, newQty = false ) => {
const updatedProducts = getUpdatedProducts( existingCart.products , product, qtyToBeAdded, newQty );
const addPrice = (total, item) => {
total.totalPrice += item.totalPrice;
total.qty += item.qty;
return total;
};
// Loop through the updated product array and add the totalPrice of each item to get the totalPrice
let total = updatedProducts.reduce( addPrice, { totalPrice: 0, qty: 0 } );
const updatedCart = {
products: updatedProducts,
totalProductsCount: parseInt( total.qty ),
totalProductsPrice: parseFloat( total.totalPrice )
};
localStorage.setItem( 'woo-next-cart', JSON.stringify( updatedCart ) );
return updatedCart;
};
/**
* Get updated products array
* Update the product if it exists else,
* add the new product to existing cart,
*
* @param {Object} existingProductsInCart Existing product in cart
* @param {Object} product Product
* @param {Integer} qtyToBeAdded Quantity
* @param {Integer} newQty New qty of the product (optional)
* @return {*[]}
*/
export const getUpdatedProducts = ( existingProductsInCart, product, qtyToBeAdded, newQty = false ) => {
// Check if the product already exits in the cart.
const productExitsIndex = isProductInCart( existingProductsInCart, product.productId );
// If product exits ( index of that product found in the array ), update the product quantity and totalPrice
if ( -1 < productExitsIndex ) {
let updatedProducts = existingProductsInCart;
let updatedProduct = updatedProducts[ productExitsIndex ];
// If have new qty of the product available, set that else add the qtyToBeAdded
updatedProduct.qty = ( newQty ) ? parseInt( newQty ) : parseInt( updatedProduct.qty + qtyToBeAdded );
updatedProduct.totalPrice = parseFloat( ( updatedProduct.price * updatedProduct.qty ).toFixed( 2 ) );
return updatedProducts;
} else {
// If product not found push the new product to the existing product array.
let productPrice = getFloatVal( product.price );
const newProduct = createNewProduct( product, productPrice, qtyToBeAdded );
existingProductsInCart.push( newProduct );
return existingProductsInCart;
}
};
/**
* Returns index of the product if it exists.
*
* @param {Object} existingProductsInCart Existing Products.
* @param {Integer} productId Product id.
* @return {number | *} Index Returns -1 if product does not exist in the array, index number otherwise
*/
const isProductInCart = ( existingProductsInCart, productId ) => {
const returnItemThatExits = ( item, index ) => {
if ( productId === item.productId ) {
return item;
}
};
// This new array will only contain the product which is matched.
const newArray = existingProductsInCart.filter( returnItemThatExits );
return existingProductsInCart.indexOf( newArray[0] );
};
/**
* Remove Item from the cart.
*
* @param {Integer} productId Product Id.
* @return {any | string} Updated cart
*/
export const removeItemFromCart = ( productId ) => {
let existingCart = localStorage.getItem( 'woo-next-cart' );
existingCart = JSON.parse( existingCart );
// If there is only one item in the cart, delete the cart.
if ( 1 === existingCart.products.length ) {
localStorage.removeItem( 'woo-next-cart' );
return null;
}
// Check if the product already exits in the cart.
const productExitsIndex = isProductInCart( existingCart.products, productId );
// If product to be removed exits
if ( -1 < productExitsIndex ) {
const productTobeRemoved = existingCart.products[ productExitsIndex ];
const qtyToBeRemovedFromTotal = productTobeRemoved.qty;
const priceToBeDeductedFromTotal = productTobeRemoved.totalPrice;
// Remove that product from the array and update the total price and total quantity of the cart
let updatedCart = existingCart;
updatedCart.products.splice( productExitsIndex, 1 );
updatedCart.totalProductsCount = updatedCart.totalProductsCount - qtyToBeRemovedFromTotal;
updatedCart.totalProductsPrice = updatedCart.totalProductsPrice - priceToBeDeductedFromTotal;
localStorage.setItem( 'woo-next-cart', JSON.stringify( updatedCart ) );
return updatedCart;
} else {
return existingCart;
}
};
/**
* Returns cart data in the required format.
* @param {String} data Cart data
*/
export const getFormattedCart = ( data ) => {
let formattedCart = null;
if ( undefined === data || ! data.cart.contents.nodes.length ) {
return formattedCart;
}
const givenProducts = data.cart.contents.nodes;
// Create an empty object.
formattedCart = {};
formattedCart.products = [];
let totalProductsCount = 0;
for( let i = 0; i < givenProducts.length; i++ ) {
const givenProduct = givenProducts[ i ].product;
const product = {};
const total = getFloatVal( givenProducts[ i ].total );
product.productId = givenProduct.productId;
product.cartKey = givenProducts[ i ].key;
product.name = givenProduct.name;
product.qty = givenProducts[ i ].quantity;
product.price = total / product.qty;
product.totalPrice = givenProducts[ i ].total;
product.image = {
sourceUrl: givenProduct.image.sourceUrl,
srcSet: givenProduct.image.srcSet,
title: givenProduct.image.title
};
totalProductsCount += givenProducts[ i ].quantity;
// Push each item into the products array.
formattedCart.products.push( product );
}
formattedCart.totalProductsCount = totalProductsCount;
formattedCart.totalProductsPrice = data.cart.total;
return formattedCart;
};
export const createCheckoutData = ( order ) => {
const checkoutData = {
clientMutationId: v4(),
billing: {
firstName: order.firstName,
lastName: order.lastName,
address1: order.address1,
address2: order.address2,
city: order.city,
country: order.country,
state: order.state,
postcode: order.postcode,
email: order.email,
phone: order.phone,
company: order.company,
},
shipping: {
firstName: order.firstName,
lastName: order.lastName,
address1: order.address1,
address2: order.address2,
city: order.city,
country: order.country,
state: order.state,
postcode: order.postcode,
email: order.email,
phone: order.phone,
company: order.company,
},
shipToDifferentAddress: false,
paymentMethod: order.paymentMethod,
isPaid: false,
transactionId: "hjkhjkhsdsdiui"
};
return checkoutData;
};
/**
* Get the updated items in the below format required for mutation input.
*
* [
* { "key": "33e75ff09dd601bbe6dd51039152189", "quantity": 1 },
* { "key": "02e74f10e0327ad868d38f2b4fdd6f0", "quantity": 1 },
* ]
*
* Creates an array in above format with the newQty (updated Qty ).
*
*/
export const getUpdatedItems = ( products, newQty, cartKey ) => {
// Create an empty array.
const updatedItems = [];
// Loop through the product array.
products.map( ( cartItem ) => {
// If you find the cart key of the product user is trying to update, push the key and new qty.
if ( cartItem.cartKey === cartKey ) {
updatedItems.push( {
key: cartItem.cartKey,
quantity: parseInt( newQty )
} );
// Otherwise just push the existing qty without updating.
} else {
updatedItems.push( {
key: cartItem.cartKey,
quantity: cartItem.qty
} );
}
} );
// Return the updatedItems array with new Qtys.
return updatedItems;
};