From bf66b4c16eecee590a98ea6b4bba58276d16f534 Mon Sep 17 00:00:00 2001 From: Leonardo Matos Date: Sun, 25 Oct 2020 06:27:23 -0300 Subject: [PATCH] feat(method): add new 'fixItem' method force item quantity and final price fix by reference --- src/constructor.js | 5 ++++ src/methods/fix-item.js | 65 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/methods/fix-item.js diff --git a/src/constructor.js b/src/constructor.js index f4199ca..81e7cd6 100644 --- a/src/constructor.js +++ b/src/constructor.js @@ -3,6 +3,7 @@ import * as EventEmitter from 'eventemitter3' import addItem from './methods/add-item' import addPoduct from './methods/add-product' +import fixItem from './methods/fix-item' import increaseItemQnt from './methods/increase-item-qnt' import parseProduct from './methods/parse-product' import removeItem from './methods/remove-item' @@ -111,6 +112,10 @@ const EcomCart = function (storeId, storageKey = 'ecomShoppingCart', localStorag return methodsMiddleware(addPoduct, [product, variationId, quantity, canSave]) } + this.fixItem = (item, canSave) => { + return methodsMiddleware(fixItem, [item, canSave]) + } + this.increaseItemQnt = (itemId, quantity, canSave) => { return methodsMiddleware(increaseItemQnt, [itemId, quantity, canSave]) } diff --git a/src/methods/fix-item.js b/src/methods/fix-item.js new file mode 100644 index 0000000..4a361eb --- /dev/null +++ b/src/methods/fix-item.js @@ -0,0 +1,65 @@ +import fixItemQuantity from './../lib/fix-item-quantity' +import fixItemFinalPrice from './../lib/fix-item-final-price' +import fixSubtotal from './../lib/fix-subtotal' + +export default ({ data, save }, emitter, [item, canSave = true]) => { + if (!item) { + return null + } + + fixItemQuantity(item) + fixItemFinalPrice(item) + fixSubtotal(data) + + /** + * @event EcomCart#fixItem + * @type {object} + * @property {object} data - Shopping cart data + * @property {object} item - Cart item changed + * @example ecomCart.on('fixItem', ({ data, item }) => { console.log(data, item) }) + */ + emitter.emit('fixItem', { data, item }) + + if (canSave) { + save(false) + } + return item +} + +/** + * @method + * @name EcomCart#fixItem + * @description Check and fix (if needed) item quantity, final price and cart subtotal. + * + * @param {string} item - The cart item object (by reference) + * @param {boolean} [canSave=true] - Save cart data + * + * @returns {object|null} Returns the updated item object or null + * when item not found. + * + * @example + +const item = ecomCart.addItem({ + _id: '12300000000000000000000f', + product_id: '123a5432109876543210cdef', + sku: 's-MP_2B4', + name: 'Mens Pique Polo Shirt', + quantity: 4, + price: 42.9, + keep_item_price: false +}) +item.customizations = [{ + _id: 'c2300000000000000000000f', + label: 'Custom name', + option: { + text: 'Jonh Doe' + }, + add_to_price: { + type: 'fixed', + addition: 10 + } +}] +item.quantity = 6 +ecomCart.fixItemQnt(item) + + */