UNPKG

@open-tender/utils

Version:

A library of utils for use with Open Tender applications that utilize our cloud-based Order API.

75 lines (74 loc) 3.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCartPoints = void 0; const react_1 = require("react"); const useCartPoints = (cart, check, form, updatePoints) => { var _a; const [cartLength, setCartLength] = (0, react_1.useState)((cart === null || cart === void 0 ? void 0 : cart.length) || 0); const { points } = (check === null || check === void 0 ? void 0 : check.config) || {}; const pointsBalance = points ? parseInt(points.balance) : 0; const pointsRemaining = points ? parseInt(points.remaining) : 0; const { cart: items = [] } = check || {}; const itemsPoints = items.length ? items.reduce((obj, i, index) => { if (!i.points) return obj; return Object.assign(Object.assign({}, obj), { [index]: Object.assign({ index }, i.points) }); }, {}) : null; const hasPoints = points && itemsPoints; const cartWithPoints = (cart === null || cart === void 0 ? void 0 : cart.map((i, index) => (Object.assign(Object.assign({}, i), { index, points: hasPoints ? itemsPoints[index.toString()] : null })))) || []; const pointsApplied = (0, react_1.useMemo)(() => (form.points ? form.points.reduce((t, i) => (t += i.points), 0) : 0), [form.points]); const cartDiff = ((_a = cart === null || cart === void 0 ? void 0 : cart.length) !== null && _a !== void 0 ? _a : 0) - (cartLength !== null && cartLength !== void 0 ? cartLength : 0); const pointsName = points ? points.name.toLowerCase() : null; const applyPoints = (item) => { if (!item.points || item.index === undefined) return; const currentItem = form.points.find(i => i.index === item.index); const currentPoints = currentItem ? currentItem.points : 0; if (currentPoints >= item.points.total) return; const updatedItem = { index: item.index, points: currentPoints + item.points.per }; const otherItems = form.points.filter(i => i.index !== item.index); const updatedPoints = [...otherItems, updatedItem]; updatePoints(updatedPoints); }; const removePoints = (item) => { if (!item.points || item.index === undefined) return; const currentItem = form.points.find(i => i.index === item.index); const currentPoints = currentItem ? currentItem.points : 0; if (currentPoints === 0) return; const updatedItem = { index: item.index, points: currentPoints - item.points.per }; const otherItems = form.points.filter(i => i.index !== item.index); const updatedPoints = updatedItem.points > 0 ? [...otherItems, updatedItem] : otherItems; updatePoints(updatedPoints); }; const pointsObj = points ? { points, applied: form.points || [], apply: applyPoints, remove: removePoints } : null; return { cartDiff, cartWithPoints, points, pointsBalance, pointsRemaining, pointsApplied, pointsName, pointsObj, setCartLength }; }; exports.useCartPoints = useCartPoints;