Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const makeAnOrder = async (
- userId,
- shopId,
- items,
- notes,
- payment_method,
- address,
- name,
- phoneNumber,
- deliveryArea
- ) => {
- // VALIDATIONS
- if (!userId && !(name && phoneNumber))
- // If user id not sent AND name and phoneNumber not sent
- throw new AppError('Missing parameters in the request', 400);
- if (!shopId || !address || !deliveryArea)
- 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');
- // CHECK USER
- if (userId) {
- const user = await User.findById(userId);
- if (!user) throw new AppError('Invalid user id', 400);
- name = user.name;
- phoneNumber = user.phoneNumber;
- }
- // GET BRANCH ID
- const deliveryAreas = (
- await Shop.findById(shopId).select('delivery_areas')
- ).toObject().delivery_areas;
- let deliveryPrice = -1;
- for (let el of deliveryAreas) {
- if (el.area === deliveryArea) {
- if (deliveryPrice === -1 || el.price < deliveryPrice) {
- branchId = el.branch;
- deliveryPrice = el.price;
- break;
- }
- }
- }
- if (!branchId)
- throw new AppError('Delivery area not found in the given shop', 404);
- // HANDLE ITEMS
- const itemsIds = items.map((el) => mongoose.Types.ObjectId(el.id));
- let itemsObjects = (
- await Item.find({ _id: { $in: itemsIds }, active: true }).select(
- '_id addons price'
- )
- ).map((el) => el.toObject());
- if (!itemsObjects || itemsObjects.length === 0)
- throw new AppError('The requested items do not exist', 400);
- itemsObjects.forEach((item) => {
- item.addons.forEach((addon) => {
- addon.options = convertArrayToObject(addon.options, '_id');
- });
- item.addons = convertArrayToObject(item.addons, '_id');
- });
- itemsObjects = convertArrayToObject(itemsObjects, '_id');
- let totalPrice = 0;
- itemsToBeInserted = [];
- items.forEach((item) => {
- const itemToBeInserted = {
- item: item.id,
- addons: [],
- qty: item.qty,
- };
- totalPrice += itemsObjects[item.id].price * item.qty;
- if (item.addons && Array.isArray(item.addons)) {
- item.addons.forEach((addon) => {
- if (!itemsObjects[item.id])
- throw new AppError("The shop doesn't have this addon", 400);
- 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.multiple,
- options: [],
- };
- addon.options.forEach((option) => {
- const originalOption = originalAddon.options[option];
- totalPrice += originalOption.price * item.qty;
- 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);
- });
- totalPrice += deliveryPrice;
- const order = await Order.create({
- shop: shopId,
- ...(userId && { user: userId }),
- branch: branchId,
- items: itemsToBeInserted,
- notes: notes,
- payment_method: payment_method,
- user_address: address,
- total_price: totalPrice,
- name: name,
- phoneNumber: phoneNumber,
- delivery_area: deliveryArea,
- });
- order.__v = undefined;
- return order;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement