Socket
Socket
Sign inDemoInstall

@vtex/order-items

Package Overview
Dependencies
Maintainers
74
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vtex/order-items - npm Package Compare versions

Comparing version 0.0.1-6 to 0.0.1-7

797

dist/index.esm.js
/*!
* @vtex/order-items v0.0.1-6
* @vtex/order-items v0.0.1-7
* (c) VTEX

@@ -11,70 +11,4 @@ * Released under the MIT License.

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var noop = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); };
var OrderItemsContext = createContext({
const noop = async () => { };
const OrderItemsContext = createContext({
addItem: noop,

@@ -85,16 +19,16 @@ updateQuantity: noop,

});
var useOrderItems = function () {
const useOrderItems = () => {
return useContext(OrderItemsContext);
};
var DEFAULT_LOCAL_ORDER_QUEUE = {
const DEFAULT_LOCAL_ORDER_QUEUE = {
queue: [],
};
var getLocalOrderQueue = function () {
const getLocalOrderQueue = () => {
var _a;
var queue = null;
let queue = null;
try {
queue = JSON.parse((_a = localStorage.getItem('orderQueue')) !== null && _a !== void 0 ? _a : 'null');
}
catch (_b) {
catch {
// ignore

@@ -107,15 +41,14 @@ }

};
var saveLocalOrderQueue = function (orderQueue) {
const saveLocalOrderQueue = (orderQueue) => {
localStorage.setItem('orderQueue', JSON.stringify(orderQueue));
};
var pushLocalOrderQueue = function (task) {
var orderQueue = getLocalOrderQueue();
var index = orderQueue.queue.push(task);
const pushLocalOrderQueue = (task) => {
const orderQueue = getLocalOrderQueue();
const index = orderQueue.queue.push(task);
saveLocalOrderQueue(orderQueue);
return index;
};
var popLocalOrderQueue = function (index) {
if (index === void 0) { index = 0; }
var orderQueue = getLocalOrderQueue();
var task = orderQueue.queue[index];
const popLocalOrderQueue = (index = 0) => {
const orderQueue = getLocalOrderQueue();
const task = orderQueue.queue[index];
if (!task) {

@@ -128,12 +61,14 @@ return undefined;

};
var updateLocalQueueItemIds = function (_a) {
var fakeUniqueId = _a.fakeUniqueId, uniqueId = _a.uniqueId;
var orderQueue = getLocalOrderQueue();
orderQueue.queue = orderQueue.queue.map(function (task) {
const updateLocalQueueItemIds = ({ fakeUniqueId, uniqueId, }) => {
const orderQueue = getLocalOrderQueue();
orderQueue.queue = orderQueue.queue.map((task) => {
if (task.type !== 'update_mutation') {
return task;
}
var itemIndex = task.variables.orderItems.findIndex(function (input) { return 'uniqueId' in input && input.uniqueId === fakeUniqueId; });
const itemIndex = task.variables.orderItems.findIndex((input) => 'uniqueId' in input && input.uniqueId === fakeUniqueId);
if (itemIndex > -1) {
task.variables.orderItems[itemIndex] = __assign(__assign({}, task.variables.orderItems[itemIndex]), { uniqueId: uniqueId });
task.variables.orderItems[itemIndex] = {
...task.variables.orderItems[itemIndex],
uniqueId,
};
}

@@ -146,7 +81,7 @@ return task;

/* eslint-disable @typescript-eslint/no-non-null-assertion */
var AVAILABLE = 'available';
var isSameItem = function (input, item, items) {
const AVAILABLE = 'available';
const isSameItem = (input, item, items) => {
var _a, _b;
var isSameId = ((_a = input.id) === null || _a === void 0 ? void 0 : _a.toString()) === item.id;
var isSameSeller = input.seller === item.seller;
const isSameId = ((_a = input.id) === null || _a === void 0 ? void 0 : _a.toString()) === item.id;
const isSameSeller = input.seller === item.seller;
// input has no options

@@ -162,6 +97,6 @@ if (input.options == null) {

// does every option (assuming assembly option) existing in the cart as separate products?
var optionsExistInCart = input.options.every(function (opItem) { return items.find(function (i) { return i.id === opItem.id; }); });
const optionsExistInCart = input.options.every((opItem) => items.find((i) => i.id === opItem.id));
return isSameId && isSameSeller && optionsExistInCart;
};
var adjustForItemInput = function (item) {
const adjustForItemInput = (item) => {
var _a;

@@ -176,3 +111,3 @@ return {

};
var mapToOrderFormItem = function (itemInput, cartItem) {
const mapToOrderFormItem = (itemInput, cartItem) => {
var _a, _b, _c, _d;

@@ -209,90 +144,79 @@ return {

};
var filterUndefined = function (value) {
const filterUndefined = (value) => {
return value !== undefined;
};
function createUseAddItems(_a) {
var _this = this;
var useMutateAddItems = _a.useMutateAddItems, useOrderForm = _a.useOrderForm;
var useAddItems = function (fakeUniqueIdMapRef) {
var setOrderForm = useOrderForm().setOrderForm;
var mutate = useMutateAddItems();
var addItemTask = useCallback(function (_a) {
var mutationInputItems = _a.mutationInputItems, mutationInputMarketingData = _a.mutationInputMarketingData, orderFormItems = _a.orderFormItems, salesChannel = _a.salesChannel;
return ({
execute: function () { return __awaiter(_this, void 0, void 0, function () {
var _a, updatedOrderForm, errors;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, mutate({
items: mutationInputItems,
marketingData: mutationInputMarketingData,
salesChannel: salesChannel,
})];
case 1:
_a = _c.sent(), updatedOrderForm = _a.data, errors = _a.errors;
if (!updatedOrderForm || ((_b = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _b !== void 0 ? _b : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
// update the uniqueId of the items that were
// added locally with the value from the server
orderFormItems.forEach(function (orderFormItem) {
var updatedItem = updatedOrderForm === null || updatedOrderForm === void 0 ? void 0 : updatedOrderForm.items.find(function (updatedOrderFormItem) {
return updatedOrderFormItem.id === orderFormItem.id;
});
if (!updatedItem) {
// the item wasn't added to the cart. the reason for this
// may vary, but could be something like the item doesn't
// have stock left, etc.
return;
}
var fakeUniqueId = orderFormItem.uniqueId;
// update all mutations in the queue that referenced
// this item with it's fake `uniqueId`
updateLocalQueueItemIds({
fakeUniqueId: fakeUniqueId,
uniqueId: updatedItem.uniqueId,
});
fakeUniqueIdMapRef.current[fakeUniqueId] = updatedItem.uniqueId;
});
// update the `uniqueId` in the remaining items on local orderForm
setOrderForm(function (prevOrderForm) {
return __assign(__assign({}, prevOrderForm), { items: prevOrderForm.items
.map(function (item) {
var inputIndex = mutationInputItems.findIndex(function (inputItem) {
return isSameItem(inputItem, item, prevOrderForm.items);
});
if (inputIndex === -1) {
// this item wasn't part of the initial mutation, skip it
return item;
}
var updatedItem = updatedOrderForm.items.find(function (updatedOrderFormItem) {
return updatedOrderFormItem.id === item.id;
});
if (!updatedItem) {
// item was not added to the cart
return null;
}
return __assign(__assign({}, item), { uniqueId: updatedItem.uniqueId });
})
.filter(function (item) { return item != null; }), marketingData: mutationInputMarketingData !== null && mutationInputMarketingData !== void 0 ? mutationInputMarketingData : prevOrderForm.marketingData });
});
return [2 /*return*/, updatedOrderForm];
}
function createUseAddItems({ useMutateAddItems, useOrderForm, }) {
const useAddItems = (fakeUniqueIdMapRef) => {
const { setOrderForm } = useOrderForm();
const mutate = useMutateAddItems();
const addItemTask = useCallback(({ mutationInputItems, mutationInputMarketingData, orderFormItems, salesChannel, }) => ({
execute: async () => {
var _a;
const { data: updatedOrderForm, errors } = await mutate({
items: mutationInputItems,
marketingData: mutationInputMarketingData,
salesChannel,
});
if (!updatedOrderForm || ((_a = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _a !== void 0 ? _a : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
// update the uniqueId of the items that were
// added locally with the value from the server
orderFormItems.forEach((orderFormItem) => {
const updatedItem = updatedOrderForm === null || updatedOrderForm === void 0 ? void 0 : updatedOrderForm.items.find((updatedOrderFormItem) => updatedOrderFormItem.id === orderFormItem.id);
if (!updatedItem) {
// the item wasn't added to the cart. the reason for this
// may vary, but could be something like the item doesn't
// have stock left, etc.
return;
}
const fakeUniqueId = orderFormItem.uniqueId;
// update all mutations in the queue that referenced
// this item with it's fake `uniqueId`
updateLocalQueueItemIds({
fakeUniqueId,
uniqueId: updatedItem.uniqueId,
});
}); },
rollback: function () {
setOrderForm(function (prevOrderForm) {
var itemIds = mutationInputItems.map(function (_a) {
var id = _a.id;
return id.toString();
});
return __assign(__assign({}, prevOrderForm), { items: prevOrderForm.items.filter(function (orderFormItem) {
return !itemIds.includes(orderFormItem.id);
}) });
});
},
});
}, [fakeUniqueIdMapRef, mutate, setOrderForm]);
fakeUniqueIdMapRef.current[fakeUniqueId] = updatedItem.uniqueId;
});
// update the `uniqueId` in the remaining items on local orderForm
setOrderForm((prevOrderForm) => {
return {
...prevOrderForm,
items: prevOrderForm.items
.map((item) => {
const inputIndex = mutationInputItems.findIndex((inputItem) => isSameItem(inputItem, item, prevOrderForm.items));
if (inputIndex === -1) {
// this item wasn't part of the initial mutation, skip it
return item;
}
const updatedItem = updatedOrderForm.items.find((updatedOrderFormItem) => updatedOrderFormItem.id === item.id);
if (!updatedItem) {
// item was not added to the cart
return null;
}
return {
...item,
uniqueId: updatedItem.uniqueId,
};
})
.filter((item) => item != null),
marketingData: mutationInputMarketingData !== null && mutationInputMarketingData !== void 0 ? mutationInputMarketingData : prevOrderForm.marketingData,
};
});
return updatedOrderForm;
},
rollback: () => {
setOrderForm((prevOrderForm) => {
const itemIds = mutationInputItems.map(({ id }) => id.toString());
return {
...prevOrderForm,
items: prevOrderForm.items.filter((orderFormItem) => {
return !itemIds.includes(orderFormItem.id);
}),
};
});
},
}), [fakeUniqueIdMapRef, mutate, setOrderForm]);
return addItemTask;

@@ -303,26 +227,17 @@ };

function createUseSetManualPrice(_a) {
var _this = this;
var useMutateSetManualPrice = _a.useMutateSetManualPrice;
var useSetManualPrice = function () {
var mutate = useMutateSetManualPrice();
var setManualPriceTask = useCallback(function (price, itemIndex) {
function createUseSetManualPrice({ useMutateSetManualPrice, }) {
const useSetManualPrice = () => {
const mutate = useMutateSetManualPrice();
const setManualPriceTask = useCallback((price, itemIndex) => {
if (!mutate)
return;
return {
execute: function () { return __awaiter(_this, void 0, void 0, function () {
var _a, data, errors;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, mutate({ itemIndex: itemIndex, price: price })];
case 1:
_a = _c.sent(), data = _a.data, errors = _a.errors;
if (!data || ((_b = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _b !== void 0 ? _b : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return [2 /*return*/, data];
}
});
}); },
execute: async () => {
var _a;
const { data, errors } = await mutate({ itemIndex, price });
if (!data || ((_a = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _a !== void 0 ? _a : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return data;
},
};

@@ -335,84 +250,67 @@ }, [mutate]);

function createUseUpdateQuantity(_a) {
var _this = this;
var useMutateUpdateQuantity = _a.useMutateUpdateQuantity, useOrderForm = _a.useOrderForm;
var useUpdateItem = function (fakeUniqueIdMapRef) {
var setOrderForm = useOrderForm().setOrderForm;
var mutate = useMutateUpdateQuantity();
var updateItemTask = useCallback(function (_a) {
var items = _a.items, orderFormItems = _a.orderFormItems, id = _a.id;
function createUseUpdateQuantity({ useMutateUpdateQuantity, useOrderForm, }) {
const useUpdateItem = (fakeUniqueIdMapRef) => {
const { setOrderForm } = useOrderForm();
const mutate = useMutateUpdateQuantity();
const updateItemTask = useCallback(({ items, orderFormItems, id, }) => {
return {
id: id,
execute: function () { return __awaiter(_this, void 0, void 0, function () {
var mutationVariables, _a, data, errors;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
mutationVariables = {
orderItems: items.map(function (input) {
if ('uniqueId' in input) {
// here we need to update the uniqueId again in the mutation
// because it may have been a "fake" `uniqueId` that were generated
// locally so we could manage the items when offline.
//
// so, we will read the value using the `fakeUniqueIdMapRef` because
// it maps a fake `uniqueId` to a real `uniqueId` that was generated by
// the API. if it doesn't contain the value, we will assume that this uniqueId
// is a real one.
var uniqueId = fakeUniqueIdMapRef.current[input.uniqueId] || input.uniqueId;
return { uniqueId: uniqueId, quantity: input.quantity };
}
return input;
}),
};
return [4 /*yield*/, mutate(mutationVariables)];
case 1:
_a = _c.sent(), data = _a.data, errors = _a.errors;
if (!data || ((_b = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _b !== void 0 ? _b : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return [2 /*return*/, data];
}
});
}); },
rollback: function () {
var deletedItemsInput = items.filter(function (_a) {
var quantity = _a.quantity;
return quantity === 0;
});
var updatedItemsInput = items.filter(function (_a) {
var quantity = _a.quantity;
return quantity !== 0;
});
var deletedItems = deletedItemsInput
.map(function (input) {
return orderFormItems.find(function (orderFormItem, itemIndex) {
return 'uniqueId' in input
? orderFormItem.uniqueId === input.uniqueId
: input.index === itemIndex;
});
id,
execute: async () => {
var _a;
const mutationVariables = {
orderItems: items.map((input) => {
if ('uniqueId' in input) {
// here we need to update the uniqueId again in the mutation
// because it may have been a "fake" `uniqueId` that were generated
// locally so we could manage the items when offline.
//
// so, we will read the value using the `fakeUniqueIdMapRef` because
// it maps a fake `uniqueId` to a real `uniqueId` that was generated by
// the API. if it doesn't contain the value, we will assume that this uniqueId
// is a real one.
const uniqueId = fakeUniqueIdMapRef.current[input.uniqueId] || input.uniqueId;
return { uniqueId, quantity: input.quantity };
}
return input;
}),
};
const { data, errors } = await mutate(mutationVariables);
if (!data || ((_a = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _a !== void 0 ? _a : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return data;
},
rollback: () => {
const deletedItemsInput = items.filter(({ quantity }) => quantity === 0);
const updatedItemsInput = items.filter(({ quantity }) => quantity !== 0);
const deletedItems = deletedItemsInput
.map((input) => {
return orderFormItems.find((orderFormItem, itemIndex) => 'uniqueId' in input
? orderFormItem.uniqueId === input.uniqueId
: input.index === itemIndex);
})
.filter(filterUndefined);
setOrderForm(function (prevOrderForm) {
return __assign(__assign({}, prevOrderForm), { items: prevOrderForm.items
.map(function (orderFormItem) {
var updatedIndex = updatedItemsInput.findIndex(function (item, itemIndex) {
return 'uniqueId' in item
? orderFormItem.uniqueId === item.uniqueId
: itemIndex === item.index;
});
setOrderForm((prevOrderForm) => {
return {
...prevOrderForm,
items: prevOrderForm.items
.map((orderFormItem) => {
const updatedIndex = updatedItemsInput.findIndex((item, itemIndex) => 'uniqueId' in item
? orderFormItem.uniqueId === item.uniqueId
: itemIndex === item.index);
if (updatedIndex !== -1) {
var updatedItemInput_1 = updatedItemsInput[updatedIndex];
var previousItem = orderFormItems.find(function (prevOrderFormItem, prevOrderFormItemIndex) {
return 'uniqueId' in updatedItemInput_1
? prevOrderFormItem.uniqueId ===
updatedItemInput_1.uniqueId
: prevOrderFormItemIndex === updatedItemInput_1.index;
});
return __assign(__assign({}, orderFormItem), { quantity: previousItem.quantity });
const updatedItemInput = updatedItemsInput[updatedIndex];
const previousItem = orderFormItems.find((prevOrderFormItem, prevOrderFormItemIndex) => 'uniqueId' in updatedItemInput
? prevOrderFormItem.uniqueId ===
updatedItemInput.uniqueId
: prevOrderFormItemIndex === updatedItemInput.index);
return {
...orderFormItem,
quantity: previousItem.quantity,
};
}
return orderFormItem;
})
.concat(deletedItems) });
.concat(deletedItems),
};
});

@@ -427,19 +325,18 @@ },

var updateTotalizersAndValue = function (_a) {
var _b, _c, _d, _e, _f;
var totalizers = _a.totalizers, _g = _a.currentValue, currentValue = _g === void 0 ? 0 : _g, newItem = _a.newItem, oldItem = _a.oldItem;
const updateTotalizersAndValue = ({ totalizers, currentValue = 0, newItem, oldItem, }) => {
var _a, _b, _c, _d, _e;
if ((oldItem === null || oldItem === void 0 ? void 0 : oldItem.availability) !== AVAILABLE) {
return { totalizers: totalizers, value: currentValue };
return { totalizers, value: currentValue };
}
var oldItemPrice = ((_b = oldItem.price) !== null && _b !== void 0 ? _b : 0) * ((_c = oldItem.unitMultiplier) !== null && _c !== void 0 ? _c : 1);
var oldItemQuantity = (_d = oldItem.quantity) !== null && _d !== void 0 ? _d : 0;
var oldItemSellingPrice = (_e = oldItem.sellingPrice) !== null && _e !== void 0 ? _e : 0;
var oldPrice = oldItemPrice * oldItemQuantity;
var newItemPrice = newItem.price * ((_f = newItem.unitMultiplier) !== null && _f !== void 0 ? _f : 1);
var newPrice = newItemPrice * newItem.quantity;
var subtotalDifference = newPrice - oldPrice;
var oldDiscount = (oldItemSellingPrice - oldItemPrice) * oldItemQuantity;
var newDiscount = (newItem.sellingPrice - newItemPrice) * newItem.quantity;
var discountDifference = newDiscount - oldDiscount;
var updatedValue = currentValue + subtotalDifference + discountDifference;
const oldItemPrice = ((_a = oldItem.price) !== null && _a !== void 0 ? _a : 0) * ((_b = oldItem.unitMultiplier) !== null && _b !== void 0 ? _b : 1);
const oldItemQuantity = (_c = oldItem.quantity) !== null && _c !== void 0 ? _c : 0;
const oldItemSellingPrice = (_d = oldItem.sellingPrice) !== null && _d !== void 0 ? _d : 0;
const oldPrice = oldItemPrice * oldItemQuantity;
const newItemPrice = newItem.price * ((_e = newItem.unitMultiplier) !== null && _e !== void 0 ? _e : 1);
const newPrice = newItemPrice * newItem.quantity;
const subtotalDifference = newPrice - oldPrice;
const oldDiscount = (oldItemSellingPrice - oldItemPrice) * oldItemQuantity;
const newDiscount = (newItem.sellingPrice - newItemPrice) * newItem.quantity;
const discountDifference = newDiscount - oldDiscount;
const updatedValue = currentValue + subtotalDifference + discountDifference;
if (!totalizers.length) {

@@ -462,8 +359,14 @@ return {

}
var newTotalizers = totalizers.map(function (totalizer) {
const newTotalizers = totalizers.map((totalizer) => {
switch (totalizer.id) {
case 'Items':
return __assign(__assign({}, totalizer), { value: totalizer.value + subtotalDifference });
return {
...totalizer,
value: totalizer.value + subtotalDifference,
};
case 'Discounts':
return __assign(__assign({}, totalizer), { value: totalizer.value + discountDifference });
return {
...totalizer,
value: totalizer.value + discountDifference,
};
default:

@@ -479,90 +382,85 @@ return totalizer;

var useEnqueueTask = function (_a) {
var useOrderForm = _a.useOrderForm, useLogger = _a.useLogger, useOrderQueue = _a.useOrderQueue, useQueueStatus = _a.useQueueStatus;
var log = useLogger().log;
var _b = useOrderQueue(), enqueue = _b.enqueue, listen = _b.listen;
var queueStatusRef = useQueueStatus(listen);
var setOrderForm = useOrderForm().setOrderForm;
var enqueueTask = useCallback(function (task) {
return enqueue(task.execute, task.id).then(function (orderForm) {
popLocalOrderQueue();
if (queueStatusRef.current === 'Fulfilled') {
setOrderForm(orderForm);
}
else {
setOrderForm(function (prevOrderForm) { return (__assign(__assign({}, prevOrderForm), { messages: __assign({}, orderForm.messages) })); });
}
}, function (error) {
if (error && error.code === TASK_CANCELLED_CODE) {
popLocalOrderQueue(error.index);
return;
}
popLocalOrderQueue();
log({
type: 'Error',
level: 'Critical',
event: error,
workflowType: 'OrderItems',
workflowInstance: 'enqueue-task-error',
});
throw error;
const useEnqueueTask = ({ useOrderForm, useLogger, useOrderQueue, useQueueStatus, }) => {
const { log } = useLogger();
const { enqueue, listen } = useOrderQueue();
const queueStatusRef = useQueueStatus(listen);
const { setOrderForm } = useOrderForm();
const enqueueTask = useCallback((task) => enqueue(task.execute, task.id).then((orderForm) => {
popLocalOrderQueue();
if (queueStatusRef.current === 'Fulfilled') {
setOrderForm(orderForm);
}
else {
setOrderForm((prevOrderForm) => ({
...prevOrderForm,
messages: {
...orderForm.messages,
},
}));
}
}, (error) => {
if (error && error.code === TASK_CANCELLED_CODE) {
popLocalOrderQueue(error.index);
return;
}
popLocalOrderQueue();
log({
type: 'Error',
level: 'Critical',
event: error,
workflowType: 'OrderItems',
workflowInstance: 'enqueue-task-error',
});
}, [enqueue, queueStatusRef, setOrderForm, log]);
throw error;
}), [enqueue, queueStatusRef, setOrderForm, log]);
return enqueueTask;
};
function useFakeUniqueIdMap(_a) {
var useOrderQueue = _a.useOrderQueue;
var fakeUniqueIdMapRef = useRef({});
var listen = useOrderQueue().listen;
useEffect(function () {
return listen('Fulfilled', function () {
// avoid leaking "fake" `uniqueId`.
// this works because everytime we fulfill the queue, we know
// for sure that we won't have any locally generated uniqueId's
// left to map to a real uniqueId.
fakeUniqueIdMapRef.current = {};
});
}, [listen]);
function useFakeUniqueIdMap({ useOrderQueue, }) {
const fakeUniqueIdMapRef = useRef({});
const { listen } = useOrderQueue();
useEffect(() => listen('Fulfilled', () => {
// avoid leaking "fake" `uniqueId`.
// this works because everytime we fulfill the queue, we know
// for sure that we won't have any locally generated uniqueId's
// left to map to a real uniqueId.
fakeUniqueIdMapRef.current = {};
}), [listen]);
return fakeUniqueIdMapRef;
}
function createOrderItemsProvider$1(_a) {
var useMutateAddItems = _a.useMutateAddItems, useMutateUpdateQuantity = _a.useMutateUpdateQuantity, useMutateSetManualPrice = _a.useMutateSetManualPrice, useOrderForm = _a.useOrderForm, useLogger = _a.useLogger, useOrderQueue = _a.useOrderQueue, useQueueStatus = _a.useQueueStatus;
var useAddItem = createUseAddItems({ useMutateAddItems: useMutateAddItems, useOrderForm: useOrderForm });
var useSetManualPrice = createUseSetManualPrice({
useMutateSetManualPrice: useMutateSetManualPrice,
function createOrderItemsProvider$1({ useMutateAddItems, useMutateUpdateQuantity, useMutateSetManualPrice, useOrderForm, useLogger, useOrderQueue, useQueueStatus, }) {
const useAddItem = createUseAddItems({ useMutateAddItems, useOrderForm });
const useSetManualPrice = createUseSetManualPrice({
useMutateSetManualPrice,
});
var useUpdateQuantity = createUseUpdateQuantity({
useMutateUpdateQuantity: useMutateUpdateQuantity,
useOrderForm: useOrderForm,
const useUpdateQuantity = createUseUpdateQuantity({
useMutateUpdateQuantity,
useOrderForm,
});
var OrderItemsProvider = function (_a) {
var children = _a.children;
var _b = useOrderForm(), orderForm = _b.orderForm, setOrderForm = _b.setOrderForm;
var fakeUniqueIdMapRef = useFakeUniqueIdMap({ useOrderQueue: useOrderQueue });
var enqueueTask = useEnqueueTask({
useOrderForm: useOrderForm,
useLogger: useLogger,
useOrderQueue: useOrderQueue,
useQueueStatus: useQueueStatus,
const OrderItemsProvider = ({ children }) => {
const { orderForm, setOrderForm } = useOrderForm();
const fakeUniqueIdMapRef = useFakeUniqueIdMap({ useOrderQueue });
const enqueueTask = useEnqueueTask({
useOrderForm,
useLogger,
useOrderQueue,
useQueueStatus,
});
var addItemsTask = useAddItem(fakeUniqueIdMapRef);
var updateItemsTask = useUpdateQuantity(fakeUniqueIdMapRef);
var setManualPriceTask = useSetManualPrice();
var orderFormItemsRef = useRef(orderForm.items);
useEffect(function () {
const addItemsTask = useAddItem(fakeUniqueIdMapRef);
const updateItemsTask = useUpdateQuantity(fakeUniqueIdMapRef);
const setManualPriceTask = useSetManualPrice();
const orderFormItemsRef = useRef(orderForm.items);
useEffect(() => {
orderFormItemsRef.current = orderForm.items;
}, [orderForm.items]);
var updateQuantity = useCallback(function (input) {
const updateQuantity = useCallback((input) => {
var _a, _b, _c;
var index;
var uniqueId = '';
var currentOrderFormItems = orderFormItemsRef.current;
let index;
let uniqueId = '';
const currentOrderFormItems = orderFormItemsRef.current;
if (input.id) {
index = currentOrderFormItems.findIndex(function (orderItem) {
return isSameItem(input, orderItem, currentOrderFormItems);
});
index = currentOrderFormItems.findIndex((orderItem) => isSameItem(input, orderItem, currentOrderFormItems));
}
else if (input.uniqueId) {
uniqueId = input.uniqueId;
index = currentOrderFormItems.findIndex(function (orderItem) { return orderItem.uniqueId === input.uniqueId; });
index = currentOrderFormItems.findIndex((orderItem) => orderItem.uniqueId === input.uniqueId);
}

@@ -573,3 +471,3 @@ else {

if (index < 0 || index >= currentOrderFormItems.length) {
throw new Error("Item " + ((_b = input.id) !== null && _b !== void 0 ? _b : input.uniqueId) + " not found");
throw new Error(`Item ${(_b = input.id) !== null && _b !== void 0 ? _b : input.uniqueId} not found`);
}

@@ -579,7 +477,10 @@ if (!uniqueId) {

}
var quantity = (_c = input.quantity) !== null && _c !== void 0 ? _c : 1;
setOrderForm(function (prevOrderForm) {
var updatedItems = prevOrderForm.items.slice();
var oldItem = updatedItems[index];
var newItem = __assign(__assign({}, oldItem), { quantity: quantity });
const quantity = (_c = input.quantity) !== null && _c !== void 0 ? _c : 1;
setOrderForm((prevOrderForm) => {
const updatedItems = prevOrderForm.items.slice();
const oldItem = updatedItems[index];
const newItem = {
...oldItem,
quantity,
};
if (quantity > 0) {

@@ -591,21 +492,25 @@ updatedItems[index] = newItem;

}
return __assign(__assign(__assign({}, prevOrderForm), updateTotalizersAndValue({
totalizers: prevOrderForm.totalizers,
currentValue: prevOrderForm.value,
newItem: newItem,
oldItem: oldItem,
})), { items: updatedItems });
return {
...prevOrderForm,
...updateTotalizersAndValue({
totalizers: prevOrderForm.totalizers,
currentValue: prevOrderForm.value,
newItem,
oldItem,
}),
items: updatedItems,
};
});
var mutationVariables;
var id = uuid.v4();
let mutationVariables;
let id = uuid.v4();
if (quantity > 0) {
var localQueue = getLocalOrderQueue().queue;
var previousTaskIndex = -1;
var originalId = id;
const localQueue = getLocalOrderQueue().queue;
let previousTaskIndex = -1;
const originalId = id;
// Skip the first element in the queue (which is currently being executed)
// because we can't cancel an in-progress task.
for (var i = 1; i < localQueue.length; i++) {
var task = localQueue[i];
for (let i = 1; i < localQueue.length; i++) {
const task = localQueue[i];
if (task.type === 'update_mutation' &&
task.variables.orderItems.every(function (itemInput) { return itemInput.quantity > 0; })) {
task.variables.orderItems.every((itemInput) => itemInput.quantity > 0)) {
// If we find an update-only mutation (without removed items)

@@ -635,26 +540,22 @@ // we will re-use it's id so we minimize the number of updates

}
var previousTask = previousTaskIndex === -1 ? undefined : localQueue[previousTaskIndex];
var previousTaskItems = (previousTask === null || previousTask === void 0 ? void 0 : previousTask.type) === 'update_mutation'
const previousTask = previousTaskIndex === -1 ? undefined : localQueue[previousTaskIndex];
const previousTaskItems = (previousTask === null || previousTask === void 0 ? void 0 : previousTask.type) === 'update_mutation'
? previousTask.variables.orderItems
: [];
var itemIndexInPreviousTask_1 = previousTaskItems.findIndex(function (prevInput) {
return 'uniqueId' in prevInput
? prevInput.uniqueId === uniqueId
: prevInput.index === index;
});
const itemIndexInPreviousTask = previousTaskItems.findIndex((prevInput) => 'uniqueId' in prevInput
? prevInput.uniqueId === uniqueId
: prevInput.index === index);
mutationVariables = {
orderItems: itemIndexInPreviousTask_1 > -1
? previousTaskItems.map(function (prevInput, prevInputIndex) {
return prevInputIndex === itemIndexInPreviousTask_1
? { uniqueId: uniqueId, quantity: quantity }
: prevInput;
})
: previousTaskItems.concat([{ uniqueId: uniqueId, quantity: quantity }]),
orderItems: itemIndexInPreviousTask > -1
? previousTaskItems.map((prevInput, prevInputIndex) => prevInputIndex === itemIndexInPreviousTask
? { uniqueId, quantity }
: prevInput)
: previousTaskItems.concat([{ uniqueId, quantity }]),
};
}
else {
mutationVariables = { orderItems: [{ uniqueId: uniqueId, quantity: quantity }] };
mutationVariables = { orderItems: [{ uniqueId, quantity }] };
}
pushLocalOrderQueue({
id: id,
id,
type: 'update_mutation',

@@ -667,3 +568,3 @@ variables: mutationVariables,

orderFormItems: currentOrderFormItems,
id: id,
id,
}));

@@ -675,13 +576,11 @@ }, [enqueueTask, setOrderForm, updateItemsTask]);

*/
var addItem = useCallback(function (items, marketingData, salesChannel) {
var _a = items.reduce(function (acc, item) {
const addItem = useCallback((items, marketingData, salesChannel) => {
const { newItems, updatedItems } = items.reduce((acc, item) => {
var _a;
var newList = acc.newItems, updateList = acc.updatedItems;
const { newItems: newList, updatedItems: updateList } = acc;
// assembly items are always different
var isAssemblyItem = item.options && item.options.length > 0;
var existingItem = isAssemblyItem
const isAssemblyItem = item.options && item.options.length > 0;
const existingItem = isAssemblyItem
? undefined
: orderFormItemsRef.current.find(function (i) {
return isSameItem(item, i, items);
});
: orderFormItemsRef.current.find((i) => isSameItem(item, i, items));
if (existingItem == null) {

@@ -691,8 +590,11 @@ newList.push(item);

else {
updateList.push(__assign(__assign({}, item), { quantity: ((_a = item.quantity) !== null && _a !== void 0 ? _a : 1) + existingItem.quantity }));
updateList.push({
...item,
quantity: ((_a = item.quantity) !== null && _a !== void 0 ? _a : 1) + existingItem.quantity,
});
}
return acc;
}, { newItems: [], updatedItems: [] }), newItems = _a.newItems, updatedItems = _a.updatedItems;
}, { newItems: [], updatedItems: [] });
if (updatedItems.length) {
updatedItems.forEach(function (item) { return updateQuantity(item); });
updatedItems.forEach((item) => updateQuantity(item));
}

@@ -702,13 +604,17 @@ if (newItems.length === 0) {

}
var mutationInputItems = newItems.map(adjustForItemInput);
var orderFormItems = newItems.map(function (cartItem, index) {
return mapToOrderFormItem(mutationInputItems[index], cartItem);
});
setOrderForm(function (prevOrderForm) {
const mutationInputItems = newItems.map(adjustForItemInput);
const orderFormItems = newItems.map((cartItem, index) => mapToOrderFormItem(mutationInputItems[index], cartItem));
setOrderForm((prevOrderForm) => {
var _a;
return __assign(__assign({}, prevOrderForm), { items: [].concat(orderFormItemsRef.current, orderFormItems), totalizers: orderFormItems.reduce(function (totalizers, item) {
return updateTotalizersAndValue({ totalizers: totalizers, newItem: item })
return {
...prevOrderForm,
items: [].concat(orderFormItemsRef.current, orderFormItems),
totalizers: orderFormItems.reduce((totalizers, item) => {
return updateTotalizersAndValue({ totalizers, newItem: item })
.totalizers;
}, (_a = prevOrderForm.totalizers) !== null && _a !== void 0 ? _a : []), marketingData: marketingData !== null && marketingData !== void 0 ? marketingData : prevOrderForm.marketingData, value: prevOrderForm.value +
orderFormItems.reduce(function (total, item) { return total + item.sellingPrice * item.quantity; }, 0) });
}, (_a = prevOrderForm.totalizers) !== null && _a !== void 0 ? _a : []),
marketingData: marketingData !== null && marketingData !== void 0 ? marketingData : prevOrderForm.marketingData,
value: prevOrderForm.value +
orderFormItems.reduce((total, item) => total + item.sellingPrice * item.quantity, 0),
};
});

@@ -719,16 +625,16 @@ pushLocalOrderQueue({

items: mutationInputItems,
marketingData: marketingData,
salesChannel: salesChannel,
marketingData,
salesChannel,
},
orderFormItems: orderFormItems,
orderFormItems,
});
enqueueTask(addItemsTask({
mutationInputItems: mutationInputItems,
mutationInputItems,
mutationInputMarketingData: marketingData,
orderFormItems: orderFormItems,
salesChannel: salesChannel,
orderFormItems,
salesChannel,
}));
}, [addItemsTask, enqueueTask, setOrderForm, updateQuantity]);
var setManualPrice = useCallback(function (price, itemIndex) {
var task = setManualPriceTask(price, itemIndex);
const setManualPrice = useCallback((price, itemIndex) => {
const task = setManualPriceTask(price, itemIndex);
if (!task)

@@ -738,7 +644,7 @@ return;

}, [enqueueTask, setManualPriceTask]);
var removeItem = useCallback(function (input) { return updateQuantity(__assign(__assign({}, input), { quantity: 0 })); }, [updateQuantity]);
var value = useMemo(function () { return ({ addItem: addItem, updateQuantity: updateQuantity, removeItem: removeItem, setManualPrice: setManualPrice }); }, [addItem, updateQuantity, removeItem, setManualPrice]);
useEffect(function () {
var localOrderQueue = getLocalOrderQueue();
localOrderQueue.queue.forEach(function (task) {
const removeItem = useCallback((input) => updateQuantity({ ...input, quantity: 0 }), [updateQuantity]);
const value = useMemo(() => ({ addItem, updateQuantity, removeItem, setManualPrice }), [addItem, updateQuantity, removeItem, setManualPrice]);
useEffect(() => {
const localOrderQueue = getLocalOrderQueue();
localOrderQueue.queue.forEach((task) => {
if (task.type === 'add_mutation') {

@@ -763,15 +669,14 @@ enqueueTask(addItemsTask({

};
return { OrderItemsProvider: OrderItemsProvider, useOrderItems: useOrderItems };
return { OrderItemsProvider, useOrderItems };
}
function createOrderItemsProvider(_a) {
var useMutateAddItems = _a.useMutateAddItems, useMutateUpdateQuantity = _a.useMutateUpdateQuantity, useMutateSetManualPrice = _a.useMutateSetManualPrice, useOrderForm = _a.useOrderForm, useLogger = _a.useLogger, useOrderQueue = _a.useOrderQueue, useQueueStatus = _a.useQueueStatus;
function createOrderItemsProvider({ useMutateAddItems, useMutateUpdateQuantity, useMutateSetManualPrice, useOrderForm, useLogger, useOrderQueue, useQueueStatus, }) {
return createOrderItemsProvider$1({
useMutateAddItems: useMutateAddItems,
useMutateUpdateQuantity: useMutateUpdateQuantity,
useMutateSetManualPrice: useMutateSetManualPrice,
useOrderForm: useOrderForm,
useLogger: useLogger,
useOrderQueue: useOrderQueue,
useQueueStatus: useQueueStatus,
useMutateAddItems,
useMutateUpdateQuantity,
useMutateSetManualPrice,
useOrderForm,
useLogger,
useOrderQueue,
useQueueStatus,
});

@@ -778,0 +683,0 @@ }

/*!
* @vtex/order-items v0.0.1-6
* @vtex/order-items v0.0.1-7
* (c) VTEX

@@ -18,19 +18,19 @@ * Released under the MIT License.

function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
n['default'] = e;
return Object.freeze(n);
}
});
}
n['default'] = e;
return Object.freeze(n);
}

@@ -41,70 +41,4 @@

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var noop = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); };
var OrderItemsContext = React.createContext({
const noop = async () => { };
const OrderItemsContext = React.createContext({
addItem: noop,

@@ -115,16 +49,16 @@ updateQuantity: noop,

});
var useOrderItems = function () {
const useOrderItems = () => {
return React.useContext(OrderItemsContext);
};
var DEFAULT_LOCAL_ORDER_QUEUE = {
const DEFAULT_LOCAL_ORDER_QUEUE = {
queue: [],
};
var getLocalOrderQueue = function () {
const getLocalOrderQueue = () => {
var _a;
var queue = null;
let queue = null;
try {
queue = JSON.parse((_a = localStorage.getItem('orderQueue')) !== null && _a !== void 0 ? _a : 'null');
}
catch (_b) {
catch {
// ignore

@@ -137,15 +71,14 @@ }

};
var saveLocalOrderQueue = function (orderQueue) {
const saveLocalOrderQueue = (orderQueue) => {
localStorage.setItem('orderQueue', JSON.stringify(orderQueue));
};
var pushLocalOrderQueue = function (task) {
var orderQueue = getLocalOrderQueue();
var index = orderQueue.queue.push(task);
const pushLocalOrderQueue = (task) => {
const orderQueue = getLocalOrderQueue();
const index = orderQueue.queue.push(task);
saveLocalOrderQueue(orderQueue);
return index;
};
var popLocalOrderQueue = function (index) {
if (index === void 0) { index = 0; }
var orderQueue = getLocalOrderQueue();
var task = orderQueue.queue[index];
const popLocalOrderQueue = (index = 0) => {
const orderQueue = getLocalOrderQueue();
const task = orderQueue.queue[index];
if (!task) {

@@ -158,12 +91,14 @@ return undefined;

};
var updateLocalQueueItemIds = function (_a) {
var fakeUniqueId = _a.fakeUniqueId, uniqueId = _a.uniqueId;
var orderQueue = getLocalOrderQueue();
orderQueue.queue = orderQueue.queue.map(function (task) {
const updateLocalQueueItemIds = ({ fakeUniqueId, uniqueId, }) => {
const orderQueue = getLocalOrderQueue();
orderQueue.queue = orderQueue.queue.map((task) => {
if (task.type !== 'update_mutation') {
return task;
}
var itemIndex = task.variables.orderItems.findIndex(function (input) { return 'uniqueId' in input && input.uniqueId === fakeUniqueId; });
const itemIndex = task.variables.orderItems.findIndex((input) => 'uniqueId' in input && input.uniqueId === fakeUniqueId);
if (itemIndex > -1) {
task.variables.orderItems[itemIndex] = __assign(__assign({}, task.variables.orderItems[itemIndex]), { uniqueId: uniqueId });
task.variables.orderItems[itemIndex] = {
...task.variables.orderItems[itemIndex],
uniqueId,
};
}

@@ -176,7 +111,7 @@ return task;

/* eslint-disable @typescript-eslint/no-non-null-assertion */
var AVAILABLE = 'available';
var isSameItem = function (input, item, items) {
const AVAILABLE = 'available';
const isSameItem = (input, item, items) => {
var _a, _b;
var isSameId = ((_a = input.id) === null || _a === void 0 ? void 0 : _a.toString()) === item.id;
var isSameSeller = input.seller === item.seller;
const isSameId = ((_a = input.id) === null || _a === void 0 ? void 0 : _a.toString()) === item.id;
const isSameSeller = input.seller === item.seller;
// input has no options

@@ -192,6 +127,6 @@ if (input.options == null) {

// does every option (assuming assembly option) existing in the cart as separate products?
var optionsExistInCart = input.options.every(function (opItem) { return items.find(function (i) { return i.id === opItem.id; }); });
const optionsExistInCart = input.options.every((opItem) => items.find((i) => i.id === opItem.id));
return isSameId && isSameSeller && optionsExistInCart;
};
var adjustForItemInput = function (item) {
const adjustForItemInput = (item) => {
var _a;

@@ -206,3 +141,3 @@ return {

};
var mapToOrderFormItem = function (itemInput, cartItem) {
const mapToOrderFormItem = (itemInput, cartItem) => {
var _a, _b, _c, _d;

@@ -239,90 +174,79 @@ return {

};
var filterUndefined = function (value) {
const filterUndefined = (value) => {
return value !== undefined;
};
function createUseAddItems(_a) {
var _this = this;
var useMutateAddItems = _a.useMutateAddItems, useOrderForm = _a.useOrderForm;
var useAddItems = function (fakeUniqueIdMapRef) {
var setOrderForm = useOrderForm().setOrderForm;
var mutate = useMutateAddItems();
var addItemTask = React.useCallback(function (_a) {
var mutationInputItems = _a.mutationInputItems, mutationInputMarketingData = _a.mutationInputMarketingData, orderFormItems = _a.orderFormItems, salesChannel = _a.salesChannel;
return ({
execute: function () { return __awaiter(_this, void 0, void 0, function () {
var _a, updatedOrderForm, errors;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, mutate({
items: mutationInputItems,
marketingData: mutationInputMarketingData,
salesChannel: salesChannel,
})];
case 1:
_a = _c.sent(), updatedOrderForm = _a.data, errors = _a.errors;
if (!updatedOrderForm || ((_b = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _b !== void 0 ? _b : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
// update the uniqueId of the items that were
// added locally with the value from the server
orderFormItems.forEach(function (orderFormItem) {
var updatedItem = updatedOrderForm === null || updatedOrderForm === void 0 ? void 0 : updatedOrderForm.items.find(function (updatedOrderFormItem) {
return updatedOrderFormItem.id === orderFormItem.id;
});
if (!updatedItem) {
// the item wasn't added to the cart. the reason for this
// may vary, but could be something like the item doesn't
// have stock left, etc.
return;
}
var fakeUniqueId = orderFormItem.uniqueId;
// update all mutations in the queue that referenced
// this item with it's fake `uniqueId`
updateLocalQueueItemIds({
fakeUniqueId: fakeUniqueId,
uniqueId: updatedItem.uniqueId,
});
fakeUniqueIdMapRef.current[fakeUniqueId] = updatedItem.uniqueId;
});
// update the `uniqueId` in the remaining items on local orderForm
setOrderForm(function (prevOrderForm) {
return __assign(__assign({}, prevOrderForm), { items: prevOrderForm.items
.map(function (item) {
var inputIndex = mutationInputItems.findIndex(function (inputItem) {
return isSameItem(inputItem, item, prevOrderForm.items);
});
if (inputIndex === -1) {
// this item wasn't part of the initial mutation, skip it
return item;
}
var updatedItem = updatedOrderForm.items.find(function (updatedOrderFormItem) {
return updatedOrderFormItem.id === item.id;
});
if (!updatedItem) {
// item was not added to the cart
return null;
}
return __assign(__assign({}, item), { uniqueId: updatedItem.uniqueId });
})
.filter(function (item) { return item != null; }), marketingData: mutationInputMarketingData !== null && mutationInputMarketingData !== void 0 ? mutationInputMarketingData : prevOrderForm.marketingData });
});
return [2 /*return*/, updatedOrderForm];
}
function createUseAddItems({ useMutateAddItems, useOrderForm, }) {
const useAddItems = (fakeUniqueIdMapRef) => {
const { setOrderForm } = useOrderForm();
const mutate = useMutateAddItems();
const addItemTask = React.useCallback(({ mutationInputItems, mutationInputMarketingData, orderFormItems, salesChannel, }) => ({
execute: async () => {
var _a;
const { data: updatedOrderForm, errors } = await mutate({
items: mutationInputItems,
marketingData: mutationInputMarketingData,
salesChannel,
});
if (!updatedOrderForm || ((_a = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _a !== void 0 ? _a : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
// update the uniqueId of the items that were
// added locally with the value from the server
orderFormItems.forEach((orderFormItem) => {
const updatedItem = updatedOrderForm === null || updatedOrderForm === void 0 ? void 0 : updatedOrderForm.items.find((updatedOrderFormItem) => updatedOrderFormItem.id === orderFormItem.id);
if (!updatedItem) {
// the item wasn't added to the cart. the reason for this
// may vary, but could be something like the item doesn't
// have stock left, etc.
return;
}
const fakeUniqueId = orderFormItem.uniqueId;
// update all mutations in the queue that referenced
// this item with it's fake `uniqueId`
updateLocalQueueItemIds({
fakeUniqueId,
uniqueId: updatedItem.uniqueId,
});
}); },
rollback: function () {
setOrderForm(function (prevOrderForm) {
var itemIds = mutationInputItems.map(function (_a) {
var id = _a.id;
return id.toString();
});
return __assign(__assign({}, prevOrderForm), { items: prevOrderForm.items.filter(function (orderFormItem) {
return !itemIds.includes(orderFormItem.id);
}) });
});
},
});
}, [fakeUniqueIdMapRef, mutate, setOrderForm]);
fakeUniqueIdMapRef.current[fakeUniqueId] = updatedItem.uniqueId;
});
// update the `uniqueId` in the remaining items on local orderForm
setOrderForm((prevOrderForm) => {
return {
...prevOrderForm,
items: prevOrderForm.items
.map((item) => {
const inputIndex = mutationInputItems.findIndex((inputItem) => isSameItem(inputItem, item, prevOrderForm.items));
if (inputIndex === -1) {
// this item wasn't part of the initial mutation, skip it
return item;
}
const updatedItem = updatedOrderForm.items.find((updatedOrderFormItem) => updatedOrderFormItem.id === item.id);
if (!updatedItem) {
// item was not added to the cart
return null;
}
return {
...item,
uniqueId: updatedItem.uniqueId,
};
})
.filter((item) => item != null),
marketingData: mutationInputMarketingData !== null && mutationInputMarketingData !== void 0 ? mutationInputMarketingData : prevOrderForm.marketingData,
};
});
return updatedOrderForm;
},
rollback: () => {
setOrderForm((prevOrderForm) => {
const itemIds = mutationInputItems.map(({ id }) => id.toString());
return {
...prevOrderForm,
items: prevOrderForm.items.filter((orderFormItem) => {
return !itemIds.includes(orderFormItem.id);
}),
};
});
},
}), [fakeUniqueIdMapRef, mutate, setOrderForm]);
return addItemTask;

@@ -333,26 +257,17 @@ };

function createUseSetManualPrice(_a) {
var _this = this;
var useMutateSetManualPrice = _a.useMutateSetManualPrice;
var useSetManualPrice = function () {
var mutate = useMutateSetManualPrice();
var setManualPriceTask = React.useCallback(function (price, itemIndex) {
function createUseSetManualPrice({ useMutateSetManualPrice, }) {
const useSetManualPrice = () => {
const mutate = useMutateSetManualPrice();
const setManualPriceTask = React.useCallback((price, itemIndex) => {
if (!mutate)
return;
return {
execute: function () { return __awaiter(_this, void 0, void 0, function () {
var _a, data, errors;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, mutate({ itemIndex: itemIndex, price: price })];
case 1:
_a = _c.sent(), data = _a.data, errors = _a.errors;
if (!data || ((_b = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _b !== void 0 ? _b : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return [2 /*return*/, data];
}
});
}); },
execute: async () => {
var _a;
const { data, errors } = await mutate({ itemIndex, price });
if (!data || ((_a = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _a !== void 0 ? _a : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return data;
},
};

@@ -365,84 +280,67 @@ }, [mutate]);

function createUseUpdateQuantity(_a) {
var _this = this;
var useMutateUpdateQuantity = _a.useMutateUpdateQuantity, useOrderForm = _a.useOrderForm;
var useUpdateItem = function (fakeUniqueIdMapRef) {
var setOrderForm = useOrderForm().setOrderForm;
var mutate = useMutateUpdateQuantity();
var updateItemTask = React.useCallback(function (_a) {
var items = _a.items, orderFormItems = _a.orderFormItems, id = _a.id;
function createUseUpdateQuantity({ useMutateUpdateQuantity, useOrderForm, }) {
const useUpdateItem = (fakeUniqueIdMapRef) => {
const { setOrderForm } = useOrderForm();
const mutate = useMutateUpdateQuantity();
const updateItemTask = React.useCallback(({ items, orderFormItems, id, }) => {
return {
id: id,
execute: function () { return __awaiter(_this, void 0, void 0, function () {
var mutationVariables, _a, data, errors;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
mutationVariables = {
orderItems: items.map(function (input) {
if ('uniqueId' in input) {
// here we need to update the uniqueId again in the mutation
// because it may have been a "fake" `uniqueId` that were generated
// locally so we could manage the items when offline.
//
// so, we will read the value using the `fakeUniqueIdMapRef` because
// it maps a fake `uniqueId` to a real `uniqueId` that was generated by
// the API. if it doesn't contain the value, we will assume that this uniqueId
// is a real one.
var uniqueId = fakeUniqueIdMapRef.current[input.uniqueId] || input.uniqueId;
return { uniqueId: uniqueId, quantity: input.quantity };
}
return input;
}),
};
return [4 /*yield*/, mutate(mutationVariables)];
case 1:
_a = _c.sent(), data = _a.data, errors = _a.errors;
if (!data || ((_b = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _b !== void 0 ? _b : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return [2 /*return*/, data];
}
});
}); },
rollback: function () {
var deletedItemsInput = items.filter(function (_a) {
var quantity = _a.quantity;
return quantity === 0;
});
var updatedItemsInput = items.filter(function (_a) {
var quantity = _a.quantity;
return quantity !== 0;
});
var deletedItems = deletedItemsInput
.map(function (input) {
return orderFormItems.find(function (orderFormItem, itemIndex) {
return 'uniqueId' in input
? orderFormItem.uniqueId === input.uniqueId
: input.index === itemIndex;
});
id,
execute: async () => {
var _a;
const mutationVariables = {
orderItems: items.map((input) => {
if ('uniqueId' in input) {
// here we need to update the uniqueId again in the mutation
// because it may have been a "fake" `uniqueId` that were generated
// locally so we could manage the items when offline.
//
// so, we will read the value using the `fakeUniqueIdMapRef` because
// it maps a fake `uniqueId` to a real `uniqueId` that was generated by
// the API. if it doesn't contain the value, we will assume that this uniqueId
// is a real one.
const uniqueId = fakeUniqueIdMapRef.current[input.uniqueId] || input.uniqueId;
return { uniqueId, quantity: input.quantity };
}
return input;
}),
};
const { data, errors } = await mutate(mutationVariables);
if (!data || ((_a = errors === null || errors === void 0 ? void 0 : errors.length) !== null && _a !== void 0 ? _a : 0) > 0) {
throw errors === null || errors === void 0 ? void 0 : errors[0];
}
return data;
},
rollback: () => {
const deletedItemsInput = items.filter(({ quantity }) => quantity === 0);
const updatedItemsInput = items.filter(({ quantity }) => quantity !== 0);
const deletedItems = deletedItemsInput
.map((input) => {
return orderFormItems.find((orderFormItem, itemIndex) => 'uniqueId' in input
? orderFormItem.uniqueId === input.uniqueId
: input.index === itemIndex);
})
.filter(filterUndefined);
setOrderForm(function (prevOrderForm) {
return __assign(__assign({}, prevOrderForm), { items: prevOrderForm.items
.map(function (orderFormItem) {
var updatedIndex = updatedItemsInput.findIndex(function (item, itemIndex) {
return 'uniqueId' in item
? orderFormItem.uniqueId === item.uniqueId
: itemIndex === item.index;
});
setOrderForm((prevOrderForm) => {
return {
...prevOrderForm,
items: prevOrderForm.items
.map((orderFormItem) => {
const updatedIndex = updatedItemsInput.findIndex((item, itemIndex) => 'uniqueId' in item
? orderFormItem.uniqueId === item.uniqueId
: itemIndex === item.index);
if (updatedIndex !== -1) {
var updatedItemInput_1 = updatedItemsInput[updatedIndex];
var previousItem = orderFormItems.find(function (prevOrderFormItem, prevOrderFormItemIndex) {
return 'uniqueId' in updatedItemInput_1
? prevOrderFormItem.uniqueId ===
updatedItemInput_1.uniqueId
: prevOrderFormItemIndex === updatedItemInput_1.index;
});
return __assign(__assign({}, orderFormItem), { quantity: previousItem.quantity });
const updatedItemInput = updatedItemsInput[updatedIndex];
const previousItem = orderFormItems.find((prevOrderFormItem, prevOrderFormItemIndex) => 'uniqueId' in updatedItemInput
? prevOrderFormItem.uniqueId ===
updatedItemInput.uniqueId
: prevOrderFormItemIndex === updatedItemInput.index);
return {
...orderFormItem,
quantity: previousItem.quantity,
};
}
return orderFormItem;
})
.concat(deletedItems) });
.concat(deletedItems),
};
});

@@ -457,19 +355,18 @@ },

var updateTotalizersAndValue = function (_a) {
var _b, _c, _d, _e, _f;
var totalizers = _a.totalizers, _g = _a.currentValue, currentValue = _g === void 0 ? 0 : _g, newItem = _a.newItem, oldItem = _a.oldItem;
const updateTotalizersAndValue = ({ totalizers, currentValue = 0, newItem, oldItem, }) => {
var _a, _b, _c, _d, _e;
if ((oldItem === null || oldItem === void 0 ? void 0 : oldItem.availability) !== AVAILABLE) {
return { totalizers: totalizers, value: currentValue };
return { totalizers, value: currentValue };
}
var oldItemPrice = ((_b = oldItem.price) !== null && _b !== void 0 ? _b : 0) * ((_c = oldItem.unitMultiplier) !== null && _c !== void 0 ? _c : 1);
var oldItemQuantity = (_d = oldItem.quantity) !== null && _d !== void 0 ? _d : 0;
var oldItemSellingPrice = (_e = oldItem.sellingPrice) !== null && _e !== void 0 ? _e : 0;
var oldPrice = oldItemPrice * oldItemQuantity;
var newItemPrice = newItem.price * ((_f = newItem.unitMultiplier) !== null && _f !== void 0 ? _f : 1);
var newPrice = newItemPrice * newItem.quantity;
var subtotalDifference = newPrice - oldPrice;
var oldDiscount = (oldItemSellingPrice - oldItemPrice) * oldItemQuantity;
var newDiscount = (newItem.sellingPrice - newItemPrice) * newItem.quantity;
var discountDifference = newDiscount - oldDiscount;
var updatedValue = currentValue + subtotalDifference + discountDifference;
const oldItemPrice = ((_a = oldItem.price) !== null && _a !== void 0 ? _a : 0) * ((_b = oldItem.unitMultiplier) !== null && _b !== void 0 ? _b : 1);
const oldItemQuantity = (_c = oldItem.quantity) !== null && _c !== void 0 ? _c : 0;
const oldItemSellingPrice = (_d = oldItem.sellingPrice) !== null && _d !== void 0 ? _d : 0;
const oldPrice = oldItemPrice * oldItemQuantity;
const newItemPrice = newItem.price * ((_e = newItem.unitMultiplier) !== null && _e !== void 0 ? _e : 1);
const newPrice = newItemPrice * newItem.quantity;
const subtotalDifference = newPrice - oldPrice;
const oldDiscount = (oldItemSellingPrice - oldItemPrice) * oldItemQuantity;
const newDiscount = (newItem.sellingPrice - newItemPrice) * newItem.quantity;
const discountDifference = newDiscount - oldDiscount;
const updatedValue = currentValue + subtotalDifference + discountDifference;
if (!totalizers.length) {

@@ -492,8 +389,14 @@ return {

}
var newTotalizers = totalizers.map(function (totalizer) {
const newTotalizers = totalizers.map((totalizer) => {
switch (totalizer.id) {
case 'Items':
return __assign(__assign({}, totalizer), { value: totalizer.value + subtotalDifference });
return {
...totalizer,
value: totalizer.value + subtotalDifference,
};
case 'Discounts':
return __assign(__assign({}, totalizer), { value: totalizer.value + discountDifference });
return {
...totalizer,
value: totalizer.value + discountDifference,
};
default:

@@ -509,90 +412,85 @@ return totalizer;

var useEnqueueTask = function (_a) {
var useOrderForm = _a.useOrderForm, useLogger = _a.useLogger, useOrderQueue = _a.useOrderQueue, useQueueStatus = _a.useQueueStatus;
var log = useLogger().log;
var _b = useOrderQueue(), enqueue = _b.enqueue, listen = _b.listen;
var queueStatusRef = useQueueStatus(listen);
var setOrderForm = useOrderForm().setOrderForm;
var enqueueTask = React.useCallback(function (task) {
return enqueue(task.execute, task.id).then(function (orderForm) {
popLocalOrderQueue();
if (queueStatusRef.current === 'Fulfilled') {
setOrderForm(orderForm);
}
else {
setOrderForm(function (prevOrderForm) { return (__assign(__assign({}, prevOrderForm), { messages: __assign({}, orderForm.messages) })); });
}
}, function (error) {
if (error && error.code === orderManager.TASK_CANCELLED_CODE) {
popLocalOrderQueue(error.index);
return;
}
popLocalOrderQueue();
log({
type: 'Error',
level: 'Critical',
event: error,
workflowType: 'OrderItems',
workflowInstance: 'enqueue-task-error',
});
throw error;
const useEnqueueTask = ({ useOrderForm, useLogger, useOrderQueue, useQueueStatus, }) => {
const { log } = useLogger();
const { enqueue, listen } = useOrderQueue();
const queueStatusRef = useQueueStatus(listen);
const { setOrderForm } = useOrderForm();
const enqueueTask = React.useCallback((task) => enqueue(task.execute, task.id).then((orderForm) => {
popLocalOrderQueue();
if (queueStatusRef.current === 'Fulfilled') {
setOrderForm(orderForm);
}
else {
setOrderForm((prevOrderForm) => ({
...prevOrderForm,
messages: {
...orderForm.messages,
},
}));
}
}, (error) => {
if (error && error.code === orderManager.TASK_CANCELLED_CODE) {
popLocalOrderQueue(error.index);
return;
}
popLocalOrderQueue();
log({
type: 'Error',
level: 'Critical',
event: error,
workflowType: 'OrderItems',
workflowInstance: 'enqueue-task-error',
});
}, [enqueue, queueStatusRef, setOrderForm, log]);
throw error;
}), [enqueue, queueStatusRef, setOrderForm, log]);
return enqueueTask;
};
function useFakeUniqueIdMap(_a) {
var useOrderQueue = _a.useOrderQueue;
var fakeUniqueIdMapRef = React.useRef({});
var listen = useOrderQueue().listen;
React.useEffect(function () {
return listen('Fulfilled', function () {
// avoid leaking "fake" `uniqueId`.
// this works because everytime we fulfill the queue, we know
// for sure that we won't have any locally generated uniqueId's
// left to map to a real uniqueId.
fakeUniqueIdMapRef.current = {};
});
}, [listen]);
function useFakeUniqueIdMap({ useOrderQueue, }) {
const fakeUniqueIdMapRef = React.useRef({});
const { listen } = useOrderQueue();
React.useEffect(() => listen('Fulfilled', () => {
// avoid leaking "fake" `uniqueId`.
// this works because everytime we fulfill the queue, we know
// for sure that we won't have any locally generated uniqueId's
// left to map to a real uniqueId.
fakeUniqueIdMapRef.current = {};
}), [listen]);
return fakeUniqueIdMapRef;
}
function createOrderItemsProvider$1(_a) {
var useMutateAddItems = _a.useMutateAddItems, useMutateUpdateQuantity = _a.useMutateUpdateQuantity, useMutateSetManualPrice = _a.useMutateSetManualPrice, useOrderForm = _a.useOrderForm, useLogger = _a.useLogger, useOrderQueue = _a.useOrderQueue, useQueueStatus = _a.useQueueStatus;
var useAddItem = createUseAddItems({ useMutateAddItems: useMutateAddItems, useOrderForm: useOrderForm });
var useSetManualPrice = createUseSetManualPrice({
useMutateSetManualPrice: useMutateSetManualPrice,
function createOrderItemsProvider$1({ useMutateAddItems, useMutateUpdateQuantity, useMutateSetManualPrice, useOrderForm, useLogger, useOrderQueue, useQueueStatus, }) {
const useAddItem = createUseAddItems({ useMutateAddItems, useOrderForm });
const useSetManualPrice = createUseSetManualPrice({
useMutateSetManualPrice,
});
var useUpdateQuantity = createUseUpdateQuantity({
useMutateUpdateQuantity: useMutateUpdateQuantity,
useOrderForm: useOrderForm,
const useUpdateQuantity = createUseUpdateQuantity({
useMutateUpdateQuantity,
useOrderForm,
});
var OrderItemsProvider = function (_a) {
var children = _a.children;
var _b = useOrderForm(), orderForm = _b.orderForm, setOrderForm = _b.setOrderForm;
var fakeUniqueIdMapRef = useFakeUniqueIdMap({ useOrderQueue: useOrderQueue });
var enqueueTask = useEnqueueTask({
useOrderForm: useOrderForm,
useLogger: useLogger,
useOrderQueue: useOrderQueue,
useQueueStatus: useQueueStatus,
const OrderItemsProvider = ({ children }) => {
const { orderForm, setOrderForm } = useOrderForm();
const fakeUniqueIdMapRef = useFakeUniqueIdMap({ useOrderQueue });
const enqueueTask = useEnqueueTask({
useOrderForm,
useLogger,
useOrderQueue,
useQueueStatus,
});
var addItemsTask = useAddItem(fakeUniqueIdMapRef);
var updateItemsTask = useUpdateQuantity(fakeUniqueIdMapRef);
var setManualPriceTask = useSetManualPrice();
var orderFormItemsRef = React.useRef(orderForm.items);
React.useEffect(function () {
const addItemsTask = useAddItem(fakeUniqueIdMapRef);
const updateItemsTask = useUpdateQuantity(fakeUniqueIdMapRef);
const setManualPriceTask = useSetManualPrice();
const orderFormItemsRef = React.useRef(orderForm.items);
React.useEffect(() => {
orderFormItemsRef.current = orderForm.items;
}, [orderForm.items]);
var updateQuantity = React.useCallback(function (input) {
const updateQuantity = React.useCallback((input) => {
var _a, _b, _c;
var index;
var uniqueId = '';
var currentOrderFormItems = orderFormItemsRef.current;
let index;
let uniqueId = '';
const currentOrderFormItems = orderFormItemsRef.current;
if (input.id) {
index = currentOrderFormItems.findIndex(function (orderItem) {
return isSameItem(input, orderItem, currentOrderFormItems);
});
index = currentOrderFormItems.findIndex((orderItem) => isSameItem(input, orderItem, currentOrderFormItems));
}
else if (input.uniqueId) {
uniqueId = input.uniqueId;
index = currentOrderFormItems.findIndex(function (orderItem) { return orderItem.uniqueId === input.uniqueId; });
index = currentOrderFormItems.findIndex((orderItem) => orderItem.uniqueId === input.uniqueId);
}

@@ -603,3 +501,3 @@ else {

if (index < 0 || index >= currentOrderFormItems.length) {
throw new Error("Item " + ((_b = input.id) !== null && _b !== void 0 ? _b : input.uniqueId) + " not found");
throw new Error(`Item ${(_b = input.id) !== null && _b !== void 0 ? _b : input.uniqueId} not found`);
}

@@ -609,7 +507,10 @@ if (!uniqueId) {

}
var quantity = (_c = input.quantity) !== null && _c !== void 0 ? _c : 1;
setOrderForm(function (prevOrderForm) {
var updatedItems = prevOrderForm.items.slice();
var oldItem = updatedItems[index];
var newItem = __assign(__assign({}, oldItem), { quantity: quantity });
const quantity = (_c = input.quantity) !== null && _c !== void 0 ? _c : 1;
setOrderForm((prevOrderForm) => {
const updatedItems = prevOrderForm.items.slice();
const oldItem = updatedItems[index];
const newItem = {
...oldItem,
quantity,
};
if (quantity > 0) {

@@ -621,21 +522,25 @@ updatedItems[index] = newItem;

}
return __assign(__assign(__assign({}, prevOrderForm), updateTotalizersAndValue({
totalizers: prevOrderForm.totalizers,
currentValue: prevOrderForm.value,
newItem: newItem,
oldItem: oldItem,
})), { items: updatedItems });
return {
...prevOrderForm,
...updateTotalizersAndValue({
totalizers: prevOrderForm.totalizers,
currentValue: prevOrderForm.value,
newItem,
oldItem,
}),
items: updatedItems,
};
});
var mutationVariables;
var id = uuid__namespace.v4();
let mutationVariables;
let id = uuid__namespace.v4();
if (quantity > 0) {
var localQueue = getLocalOrderQueue().queue;
var previousTaskIndex = -1;
var originalId = id;
const localQueue = getLocalOrderQueue().queue;
let previousTaskIndex = -1;
const originalId = id;
// Skip the first element in the queue (which is currently being executed)
// because we can't cancel an in-progress task.
for (var i = 1; i < localQueue.length; i++) {
var task = localQueue[i];
for (let i = 1; i < localQueue.length; i++) {
const task = localQueue[i];
if (task.type === 'update_mutation' &&
task.variables.orderItems.every(function (itemInput) { return itemInput.quantity > 0; })) {
task.variables.orderItems.every((itemInput) => itemInput.quantity > 0)) {
// If we find an update-only mutation (without removed items)

@@ -665,26 +570,22 @@ // we will re-use it's id so we minimize the number of updates

}
var previousTask = previousTaskIndex === -1 ? undefined : localQueue[previousTaskIndex];
var previousTaskItems = (previousTask === null || previousTask === void 0 ? void 0 : previousTask.type) === 'update_mutation'
const previousTask = previousTaskIndex === -1 ? undefined : localQueue[previousTaskIndex];
const previousTaskItems = (previousTask === null || previousTask === void 0 ? void 0 : previousTask.type) === 'update_mutation'
? previousTask.variables.orderItems
: [];
var itemIndexInPreviousTask_1 = previousTaskItems.findIndex(function (prevInput) {
return 'uniqueId' in prevInput
? prevInput.uniqueId === uniqueId
: prevInput.index === index;
});
const itemIndexInPreviousTask = previousTaskItems.findIndex((prevInput) => 'uniqueId' in prevInput
? prevInput.uniqueId === uniqueId
: prevInput.index === index);
mutationVariables = {
orderItems: itemIndexInPreviousTask_1 > -1
? previousTaskItems.map(function (prevInput, prevInputIndex) {
return prevInputIndex === itemIndexInPreviousTask_1
? { uniqueId: uniqueId, quantity: quantity }
: prevInput;
})
: previousTaskItems.concat([{ uniqueId: uniqueId, quantity: quantity }]),
orderItems: itemIndexInPreviousTask > -1
? previousTaskItems.map((prevInput, prevInputIndex) => prevInputIndex === itemIndexInPreviousTask
? { uniqueId, quantity }
: prevInput)
: previousTaskItems.concat([{ uniqueId, quantity }]),
};
}
else {
mutationVariables = { orderItems: [{ uniqueId: uniqueId, quantity: quantity }] };
mutationVariables = { orderItems: [{ uniqueId, quantity }] };
}
pushLocalOrderQueue({
id: id,
id,
type: 'update_mutation',

@@ -697,3 +598,3 @@ variables: mutationVariables,

orderFormItems: currentOrderFormItems,
id: id,
id,
}));

@@ -705,13 +606,11 @@ }, [enqueueTask, setOrderForm, updateItemsTask]);

*/
var addItem = React.useCallback(function (items, marketingData, salesChannel) {
var _a = items.reduce(function (acc, item) {
const addItem = React.useCallback((items, marketingData, salesChannel) => {
const { newItems, updatedItems } = items.reduce((acc, item) => {
var _a;
var newList = acc.newItems, updateList = acc.updatedItems;
const { newItems: newList, updatedItems: updateList } = acc;
// assembly items are always different
var isAssemblyItem = item.options && item.options.length > 0;
var existingItem = isAssemblyItem
const isAssemblyItem = item.options && item.options.length > 0;
const existingItem = isAssemblyItem
? undefined
: orderFormItemsRef.current.find(function (i) {
return isSameItem(item, i, items);
});
: orderFormItemsRef.current.find((i) => isSameItem(item, i, items));
if (existingItem == null) {

@@ -721,8 +620,11 @@ newList.push(item);

else {
updateList.push(__assign(__assign({}, item), { quantity: ((_a = item.quantity) !== null && _a !== void 0 ? _a : 1) + existingItem.quantity }));
updateList.push({
...item,
quantity: ((_a = item.quantity) !== null && _a !== void 0 ? _a : 1) + existingItem.quantity,
});
}
return acc;
}, { newItems: [], updatedItems: [] }), newItems = _a.newItems, updatedItems = _a.updatedItems;
}, { newItems: [], updatedItems: [] });
if (updatedItems.length) {
updatedItems.forEach(function (item) { return updateQuantity(item); });
updatedItems.forEach((item) => updateQuantity(item));
}

@@ -732,13 +634,17 @@ if (newItems.length === 0) {

}
var mutationInputItems = newItems.map(adjustForItemInput);
var orderFormItems = newItems.map(function (cartItem, index) {
return mapToOrderFormItem(mutationInputItems[index], cartItem);
});
setOrderForm(function (prevOrderForm) {
const mutationInputItems = newItems.map(adjustForItemInput);
const orderFormItems = newItems.map((cartItem, index) => mapToOrderFormItem(mutationInputItems[index], cartItem));
setOrderForm((prevOrderForm) => {
var _a;
return __assign(__assign({}, prevOrderForm), { items: [].concat(orderFormItemsRef.current, orderFormItems), totalizers: orderFormItems.reduce(function (totalizers, item) {
return updateTotalizersAndValue({ totalizers: totalizers, newItem: item })
return {
...prevOrderForm,
items: [].concat(orderFormItemsRef.current, orderFormItems),
totalizers: orderFormItems.reduce((totalizers, item) => {
return updateTotalizersAndValue({ totalizers, newItem: item })
.totalizers;
}, (_a = prevOrderForm.totalizers) !== null && _a !== void 0 ? _a : []), marketingData: marketingData !== null && marketingData !== void 0 ? marketingData : prevOrderForm.marketingData, value: prevOrderForm.value +
orderFormItems.reduce(function (total, item) { return total + item.sellingPrice * item.quantity; }, 0) });
}, (_a = prevOrderForm.totalizers) !== null && _a !== void 0 ? _a : []),
marketingData: marketingData !== null && marketingData !== void 0 ? marketingData : prevOrderForm.marketingData,
value: prevOrderForm.value +
orderFormItems.reduce((total, item) => total + item.sellingPrice * item.quantity, 0),
};
});

@@ -749,16 +655,16 @@ pushLocalOrderQueue({

items: mutationInputItems,
marketingData: marketingData,
salesChannel: salesChannel,
marketingData,
salesChannel,
},
orderFormItems: orderFormItems,
orderFormItems,
});
enqueueTask(addItemsTask({
mutationInputItems: mutationInputItems,
mutationInputItems,
mutationInputMarketingData: marketingData,
orderFormItems: orderFormItems,
salesChannel: salesChannel,
orderFormItems,
salesChannel,
}));
}, [addItemsTask, enqueueTask, setOrderForm, updateQuantity]);
var setManualPrice = React.useCallback(function (price, itemIndex) {
var task = setManualPriceTask(price, itemIndex);
const setManualPrice = React.useCallback((price, itemIndex) => {
const task = setManualPriceTask(price, itemIndex);
if (!task)

@@ -768,7 +674,7 @@ return;

}, [enqueueTask, setManualPriceTask]);
var removeItem = React.useCallback(function (input) { return updateQuantity(__assign(__assign({}, input), { quantity: 0 })); }, [updateQuantity]);
var value = React.useMemo(function () { return ({ addItem: addItem, updateQuantity: updateQuantity, removeItem: removeItem, setManualPrice: setManualPrice }); }, [addItem, updateQuantity, removeItem, setManualPrice]);
React.useEffect(function () {
var localOrderQueue = getLocalOrderQueue();
localOrderQueue.queue.forEach(function (task) {
const removeItem = React.useCallback((input) => updateQuantity({ ...input, quantity: 0 }), [updateQuantity]);
const value = React.useMemo(() => ({ addItem, updateQuantity, removeItem, setManualPrice }), [addItem, updateQuantity, removeItem, setManualPrice]);
React.useEffect(() => {
const localOrderQueue = getLocalOrderQueue();
localOrderQueue.queue.forEach((task) => {
if (task.type === 'add_mutation') {

@@ -793,15 +699,14 @@ enqueueTask(addItemsTask({

};
return { OrderItemsProvider: OrderItemsProvider, useOrderItems: useOrderItems };
return { OrderItemsProvider, useOrderItems };
}
function createOrderItemsProvider(_a) {
var useMutateAddItems = _a.useMutateAddItems, useMutateUpdateQuantity = _a.useMutateUpdateQuantity, useMutateSetManualPrice = _a.useMutateSetManualPrice, useOrderForm = _a.useOrderForm, useLogger = _a.useLogger, useOrderQueue = _a.useOrderQueue, useQueueStatus = _a.useQueueStatus;
function createOrderItemsProvider({ useMutateAddItems, useMutateUpdateQuantity, useMutateSetManualPrice, useOrderForm, useLogger, useOrderQueue, useQueueStatus, }) {
return createOrderItemsProvider$1({
useMutateAddItems: useMutateAddItems,
useMutateUpdateQuantity: useMutateUpdateQuantity,
useMutateSetManualPrice: useMutateSetManualPrice,
useOrderForm: useOrderForm,
useLogger: useLogger,
useOrderQueue: useOrderQueue,
useQueueStatus: useQueueStatus,
useMutateAddItems,
useMutateUpdateQuantity,
useMutateSetManualPrice,
useOrderForm,
useLogger,
useOrderQueue,
useQueueStatus,
});

@@ -808,0 +713,0 @@ }

{
"name": "@vtex/order-items",
"version": "0.0.1-6",
"version": "0.0.1-7",
"description": "",

@@ -5,0 +5,0 @@ "cdn": "dist/index.umd.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc