Fix issue with ID in invoice module

master
nicekid1 2 months ago
parent 7fa178b293
commit 7da8f22cb2
  1. 27
      migrations/20250105085732-create-invoice.js
  2. 2
      src/cart/cart.controller.ts
  3. 17
      src/cart/cart.service.ts
  4. 8
      src/invoice/entities/invoice.entity.ts
  5. 31
      src/invoice/invoice.service.ts

@ -1,10 +1,10 @@
'use strict'; "use strict";
module.exports = { module.exports = {
up: async (queryInterface, Sequelize) => { up: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Invoices', { cascade: true }); await queryInterface.dropTable("Invoices", { cascade: true });
await queryInterface.createTable('Invoices', { await queryInterface.createTable("Invoices", {
id: { id: {
type: Sequelize.INTEGER, type: Sequelize.INTEGER,
autoIncrement: true, autoIncrement: true,
@ -15,10 +15,10 @@ module.exports = {
type: Sequelize.INTEGER, type: Sequelize.INTEGER,
allowNull: false, allowNull: false,
references: { references: {
model: 'Users', model: "Users",
key: 'id', key: "id",
}, },
onDelete: 'CASCADE', onDelete: "CASCADE",
}, },
firstName: { firstName: {
type: Sequelize.STRING, type: Sequelize.STRING,
@ -37,8 +37,8 @@ module.exports = {
allowNull: false, allowNull: false,
unique: false, unique: false,
}, },
totalAmount: { totalPaymentAmount: {
type: Sequelize.FLOAT, type: Sequelize.DECIMAL(10, 2),
allowNull: true, allowNull: true,
}, },
productId: { productId: {
@ -53,6 +53,10 @@ module.exports = {
type: Sequelize.DECIMAL(10, 2), type: Sequelize.DECIMAL(10, 2),
allowNull: false, allowNull: false,
}, },
totalPrice: {
type: Sequelize.DECIMAL(10, 2),
allowNull: false,
},
productName: { productName: {
type: Sequelize.STRING, type: Sequelize.STRING,
allowNull: false, allowNull: false,
@ -60,18 +64,17 @@ module.exports = {
createdAt: { createdAt: {
type: Sequelize.DATE, type: Sequelize.DATE,
allowNull: false, allowNull: false,
defaultValue: Sequelize.fn('NOW'), defaultValue: Sequelize.fn("NOW"),
}, },
updatedAt: { updatedAt: {
type: Sequelize.DATE, type: Sequelize.DATE,
allowNull: false, allowNull: false,
defaultValue: Sequelize.fn('NOW'), defaultValue: Sequelize.fn("NOW"),
}, },
}); });
}, },
down: async (queryInterface, Sequelize) => { down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("Invoices");
await queryInterface.dropTable('Invoices');
}, },
}; };

@ -49,7 +49,7 @@ export class CartController {
async processOrder( async processOrder(
@Param('userId') userId: number, @Param('userId') userId: number,
@Body('totalAmount') totalAmount: number, @Body('totalAmount') totalAmount: number,
): Promise<{ message: string; invoices: Invoice[] }> { ):Promise<{ message: string; invoices: Invoice[] }> {
if (!totalAmount || totalAmount <= 0) { if (!totalAmount || totalAmount <= 0) {
throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST); throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST);
} }

@ -120,8 +120,7 @@ export class CartService {
throw new HttpException("Cart is empty.", HttpStatus.BAD_REQUEST); throw new HttpException("Cart is empty.", HttpStatus.BAD_REQUEST);
} }
// Process each cart item and update stock, create invoice for each product // Process each cart item and update stock
const invoices: Invoice[] = [];
for (const cartItem of cartItems) { for (const cartItem of cartItems) {
const { productId, quantity } = cartItem; const { productId, quantity } = cartItem;
@ -135,16 +134,14 @@ export class CartService {
throw new HttpException(`Insufficient stock for product ID ${productId}.`, HttpStatus.BAD_REQUEST); throw new HttpException(`Insufficient stock for product ID ${productId}.`, HttpStatus.BAD_REQUEST);
} }
// Reduce stock product.quantity -= quantity; // Reduce stock
product.quantity -= quantity;
await product.save(); await product.save();
// Create invoice for this product
const newInvoice = await this.invoiceService.createInvoiceFromCart(userId); // اصلاح اینجا
invoices.push(...newInvoice); // اضافه کردن همه فاکتورها به آرایه invoices
} }
return { message: "Order processed successfully", invoices }; // Create the invoices for all cart items
const invoices = await this.invoiceService.createInvoiceFromCart(userId);
return { message: "Order processed successfully", invoices }; // Return invoices as an array
} catch (error) { } catch (error) {
console.log(error); console.log(error);
if (error instanceof HttpException) { if (error instanceof HttpException) {
@ -155,4 +152,6 @@ export class CartService {
} }
} }
} }

@ -37,7 +37,7 @@ export class Invoice extends Model<Invoice> {
email: string; email: string;
@Column @Column
totalAmount: number; totalPaymentAmount: number;
@Column({ @Column({
type: DataType.INTEGER, type: DataType.INTEGER,
@ -57,6 +57,12 @@ export class Invoice extends Model<Invoice> {
}) })
price: number; price: number;
@Column({
type: DataType.DECIMAL(10, 2),
allowNull: false,
})
totalPrice: number;
@Column({ @Column({
type: DataType.STRING, type: DataType.STRING,
allowNull: false, allowNull: false,

@ -23,37 +23,30 @@ export class InvoiceService {
throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST); throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST);
} }
const products = userCartItems.cartItems.map(item => {
return {
productId: item.productId,
quantity: item.quantity,
price: item.productPrice,
productName: item.productName,
totalPrice: item.totalPrice,
};
});
// ذخیره کردن فاکتورهای هر محصول و بازگشت آرایه فاکتورها
const invoices: Invoice[] = []; const invoices: Invoice[] = [];
for (const product of products) {
for (const cartItem of userCartItems.cartItems) {
const invoice = await this.invoiceModel.create({ const invoice = await this.invoiceModel.create({
userId, userId,
firstName: user.firstName, firstName: user.firstName,
lastName: user.lastName, lastName: user.lastName,
phoneNumber: user.phoneNumber, phoneNumber: user.phoneNumber,
email: user.email, email: user.email,
totalAmount: userCartItems.totalPrice, totalPaymentAmount: userCartItems.totalPrice,
productId: product.productId, productId: cartItem.productId,
quantity: product.quantity, quantity: cartItem.quantity,
price: product.price, price: cartItem.productPrice,
productName: product.productName, totalPrice:(cartItem.quantity*cartItem.productPrice),
productName: cartItem.productName,
}); });
invoices.push(invoice); // ذخیره فاکتور برای هر محصول
invoices.push(invoice);
} }
return invoices; return invoices; // بازگرداندن آرایهای از فاکتورها
} }
async getInvoicesByUser(userId: number): Promise<Invoice[]> { async getInvoicesByUser(userId: number): Promise<Invoice[]> {
try { try {
if (!userId) { if (!userId) {

Loading…
Cancel
Save