Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const makeAnOrder = async (
- userId,
- shopId,
- branchId,
- items,
- notes,
- payment_method,
- address
- ) => {
- if (!userId) throw new AppError('user id not specified in the request', 400);
- if (!shopId || !branchId || !address)
- throw new AppError('Missing parameters in the request', 400);
- if (!payment_method || !['Visa', 'Cash'].includes(payment_method))
- throw new AppError('Missing payment method or invalid payment method');
- if (!items || !Array.isArray(items))
- throw new AppError('Missing items argument or it is not an array');
- const itemsIds = items.map((el) => el.id);
- let itemsObjects = (
- await Item.find({ _id: { $in: itemsIds }, active: true }).select(
- '_id addons'
- )
- ).map((el) => el.toObject());
- itemsObjects.forEach((item) => {
- item.addons.forEach((addon) => {
- addon.options = convertArrayToObject(addon.options, '_id');
- });
- item.addons = convertArrayToObject(item.addons, '_id');
- });
- itemsObjects = convertArrayToObject(itemsObjects, '_id');
- //console.log(JSON.stringify(itemsObjects, null, 2));
- //console.log(JSON.stringify(items, null, 2));
- itemsToBeInserted = [];
- items.forEach((item) => {
- const itemToBeInserted = {
- item: item,
- addons: [],
- };
- if (item.addons && Array.isArray(item.addons)) {
- item.addons.forEach((addon) => {
- const originalAddon = itemsObjects[item.id].addons[addon.id];
- if (!originalAddon)
- throw new AppError('Addon not found for an item', 400);
- if (!addon.options || addon.options.length === 0)
- throw new AppError('A requested item does not have any addons', 400);
- addon.options.forEach((option) => {
- if (!originalAddon.options[option])
- throw new AppError(
- 'A requested option does not belong to its addon',
- 400
- );
- });
- if (originalAddon.multiple === false) {
- if (addon.options.length > 1)
- throw new AppError(
- 'A requested addon can only contain one option but you requested more than one option'
- );
- }
- const addonToBeInserted = {
- name: originalAddon.name,
- multiple: originalAddon.mutliple,
- options: [],
- };
- addon.options.forEach((option) => {
- const originalOption = originalAddon.options[option];
- addonToBeInserted.options.push({
- name: originalOption.name,
- price: originalOption.price,
- });
- });
- itemToBeInserted.addons.push(addonToBeInserted);
- });
- } else {
- throw new AppError('Invalid addons parameter in an item', 400);
- }
- itemsToBeInserted.push(itemToBeInserted);
- });
- console.log(itemsToBeInserted);
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement