Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[finsishes #187354262] fixing product sizes's price #74

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions src/controllers/orderController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,35 +39,40 @@ export const createOrder = async (req: Request, res: Response): Promise<void> =>
}

const [orderItems]: any = await sequelize.query(
'SELECT "productId", quantity FROM "CartsProducts" WHERE "cartId" = ?',
'SELECT "productId", "sizeId", quantity FROM "CartsProducts" WHERE "cartId" = ?',
{
replacements: [cart.id],
}
);

const sizes = await Promise.all(
orderItems.map(async (item: any) => {
const product = await Product.findOne({
where: { id: item.productId },
include: {
model: Size,
as: 'sizes',
attributes: ['price'],
},
const productSize = await Size.findOne({
where: { id: item.sizeId },
attributes: ['id', 'price', 'discount'],
});

if (!product) {
throw new Error(`Product with id ${item.productId} not found`);
if (!productSize) {
throw new Error(`Size with id ${item.sizeId} not found`);
}

const size = product.sizes[0];
const totalSum = size.price * item.quantity;
const discountDecimal = 1 - productSize.discount / 100;
const discountedPrice = productSize.price * discountDecimal;
const sizeQtyPrice = discountedPrice * item.quantity;

return { productId: item.productId, quantity: item.quantity, price: size.price, totalSum };
return {
productId: item.productId,
sizeId: productSize.id,
quantity: item.quantity,
price: discountedPrice,
sizeQtyPrice,
};
})
);

const totalPrice = sizes.reduce((prev: number, cur: any) => prev + cur.totalSum, 0);
// combine all products sizes retrieved by flat()
const combinedproductsAndSizes = sizes.flat();
const totalPrice = combinedproductsAndSizes.reduce((prev: number, curr: any) => prev + curr.sizeQtyPrice, 0);

const order = await Order.create({
phone,
Expand All @@ -81,10 +86,11 @@ export const createOrder = async (req: Request, res: Response): Promise<void> =>
});

await Promise.all(
sizes.map(async (item: any) =>
combinedproductsAndSizes.map(async (item: any) =>
OrderItems.create({
orderId: order.id,
productId: item.productId,
sizeId: item.sizeId,
quantity: item.quantity,
price: item.price,
})
Expand Down
2 changes: 0 additions & 2 deletions src/controllers/productsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ import User from '../database/models/user';
import { sendEmail } from '../helpers/send-email';
import { destroyImage } from '../helpers/destroyImage';
import { extractImageId } from '../helpers/extractImageId';
// import Review, { ReviewAttributes } from '../database/models/Review';
import Review, { ReviewAttributes } from '../database/models/Review';
import Cart from '../database/models/cart';
import Order from '../database/models/order';
import OrderItems from '../database/models/orderItems';

Expand Down
20 changes: 20 additions & 0 deletions src/database/migrations/20240527203432-add-sizeId-to-orderItems.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn('orderItems', 'sizeId', {
type: Sequelize.UUID,
allowNull: false,
references: {
model: 'sizes',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
});
},

down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn('orderItems', 'sizeId');
},
};
14 changes: 14 additions & 0 deletions src/database/models/orderItems.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { DataTypes, Model, Optional, UUIDV4 } from 'sequelize';
import sequelize from './index';
import Order from './order';
import { Product } from './Product';
import { Size } from './Size';

interface OrderItemsAttributes {
id: string;
orderId: string;
productId: string;
sizeId: string;
quantity: number;
price: number;
createdAt?: Date;
Expand All @@ -19,6 +21,7 @@ class OrderItems extends Model<OrderItemsAttributes, OrderItemCreationAttributes
public id!: string;
public orderId!: string;
public productId!: string;
public sizeId!: string;
public quantity!: number;
public price!: number;
public readonly createdAt!: Date;
Expand Down Expand Up @@ -52,6 +55,16 @@ OrderItems.init(
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
},
sizeId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'sizes',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false,
Expand Down Expand Up @@ -80,6 +93,7 @@ OrderItems.init(

OrderItems.belongsTo(Order, { foreignKey: 'orderId', as: 'orders' });
OrderItems.belongsTo(Product, { foreignKey: 'productId', as: 'products' });
OrderItems.belongsTo(Size, { foreignKey: 'sizeId', as: 'sizes' });

Order.hasMany(OrderItems, { foreignKey: 'orderId', as: 'orderItems' });
Product.hasMany(OrderItems, { foreignKey: 'productId', as: 'orderItems' });
Expand Down
Loading