All files / src/controllers/orders-controllers addNewOrder.js

75% Statements 15/20
75% Branches 3/4
100% Functions 1/1
75% Lines 15/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                        2x 2x   2x   2x   2x 2x             2x       2x               2x   2x 2x 2x     2x 2x                             2x    
import mongoose from "mongoose";
import OrdersModel from "../../models/Orders.js";
import UsersModel from "../../models/Users.js";
import { userDefaultProjection } from "../../CONSTANT/projections.js";
import sendOrderCreatedSuccessfully from "../../utilities/sendOrderCreatedSuccessfully.js";
import getYearStatisticsDocument from "../statistics-controllers/getYearStatisticsDocument.js";
import registerProductsStatistics from "../statistics-controllers/registerProductsStatistics.js";
import registerOrderStatistics from "../statistics-controllers/registerOrderStatistics.js";
 
 
export default async function addNewOrder(theOrder) {
 
    const session = await mongoose.startSession();
    session.startTransaction();
 
    try {
 
        const { products, totalPrice } = theOrder;
 
        const newOrder = await new OrdersModel(theOrder).save({ session })
        const userData = await UsersModel.findOneAndUpdate(
            { _id: theOrder.userId },
            { $set: { userShoppingCart: [] }, $push: { userOrders: newOrder._id } },
            { session, projection: userDefaultProjection }
        );
 
        // Bring the document that contains the statistics of current year
        const currentYearStatistics = await getYearStatisticsDocument();
 
        // Add order's total price to the total earnings of current month.
        // And Sum order's products count with the total of the sold products in current month.
        const addingOrderStatisticsDone = registerOrderStatistics({ products, totalPrice }, currentYearStatistics);
 
        /*
            Update order's products: 
            - decrementing product's quantity in stock.
            - incrementing how many times the product sold. 
            ect...
        */
        const addingProductsStatisticsDone = await registerProductsStatistics(products, currentYearStatistics, session);
 
        if (addingOrderStatisticsDone && addingProductsStatisticsDone) {
            await currentYearStatistics.save({ session })
            await sendOrderCreatedSuccessfully(userData)
 
            // if all processes above done successfully, the changes will saved in the database
            await session.commitTransaction();
            return { ok: true, newOrder };
        }
        else E{
            /*
                if one of the processes above failed, 
                `session.abortTransaction` function will undo all changes
            */
            await session.abortTransaction();
            return { ok: false };
        }
    } catch (error) {
        console.log(error?.message);
        await session.abortTransaction();
        return { ok: false }
    } finally {
        await session.endSession();
    }
}