Enhance invoicing system

master
nicekid1 2 months ago
parent 187811a048
commit 7fa178b293
  1. 9
      src/cart/cart.controller.ts
  2. 19
      src/cart/cart.service.ts
  3. 2
      src/invoice/entities/invoice.entity.ts
  4. 17
      src/invoice/invoice.service.ts

@ -49,8 +49,8 @@ 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; invoice: Invoice }> { ): Promise<{ message: string; invoices: Invoice[] }> {
if (!totalAmount || totalAmount <= 0 || isNaN(totalAmount)) { if (!totalAmount || totalAmount <= 0) {
throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST); throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST);
} }
@ -58,10 +58,7 @@ async processOrder(
const result = await this.cartService.processOrder(userId, totalAmount); const result = await this.cartService.processOrder(userId, totalAmount);
return result; return result;
} catch (error) { } catch (error) {
throw new HttpException( throw new HttpException(error.message || 'Order processing failed.', HttpStatus.INTERNAL_SERVER_ERROR);
error.message || 'An unexpected error occurred while processing the order.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }

@ -108,8 +108,8 @@ export class CartService {
await this.cartModel.destroy({ where: { userId } }); await this.cartModel.destroy({ where: { userId } });
} }
//order(clearCart unable) //order(clearCart disable)
async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoice: Invoice }> { async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoices: Invoice[] }> {
try { try {
// Deducting credit from wallet // Deducting credit from wallet
await this.walletService.processPayment(userId, totalAmount); await this.walletService.processPayment(userId, totalAmount);
@ -120,7 +120,8 @@ 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 // Process each cart item and update stock, create invoice for each product
const invoices: Invoice[] = [];
for (const cartItem of cartItems) { for (const cartItem of cartItems) {
const { productId, quantity } = cartItem; const { productId, quantity } = cartItem;
@ -134,14 +135,16 @@ 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);
} }
product.quantity -= quantity; // Reduce stock // Reduce stock
product.quantity -= quantity;
await product.save(); await product.save();
}
// Create the invoice after processing the cart // Create invoice for this product
const invoice = await this.invoiceService.createInvoiceFromCart(userId); const newInvoice = await this.invoiceService.createInvoiceFromCart(userId); // اصلاح اینجا
invoices.push(...newInvoice); // اضافه کردن همه فاکتورها به آرایه invoices
}
return { message: "Order processed successfully", invoice }; return { message: "Order processed successfully", invoices };
} catch (error) { } catch (error) {
console.log(error); console.log(error);
if (error instanceof HttpException) { if (error instanceof HttpException) {

@ -3,6 +3,8 @@ import { User } from "../../users/entities/user.entity";
@Table @Table
export class Invoice extends Model<Invoice> { export class Invoice extends Model<Invoice> {
@ForeignKey(() => User) @ForeignKey(() => User)
@Column @Column
userId: number; userId: number;

@ -12,7 +12,7 @@ export class InvoiceService {
private cartService: CartService, private cartService: CartService,
) {} ) {}
async createInvoiceFromCart(userId: number): Promise<Invoice> { async createInvoiceFromCart(userId: number): Promise<Invoice[]> {
const user = await User.findByPk(userId); const user = await User.findByPk(userId);
if (!user) { if (!user) {
throw new HttpException("User not found", HttpStatus.NOT_FOUND); throw new HttpException("User not found", HttpStatus.NOT_FOUND);
@ -33,8 +33,10 @@ export class InvoiceService {
}; };
}); });
// ذخیره کردن فاکتورهای هر محصول و بازگشت آرایه فاکتورها
const invoices: Invoice[] = [];
for (const product of products) { for (const product of products) {
await this.invoiceModel.create({ const invoice = await this.invoiceModel.create({
userId, userId,
firstName: user.firstName, firstName: user.firstName,
lastName: user.lastName, lastName: user.lastName,
@ -46,17 +48,10 @@ export class InvoiceService {
price: product.price, price: product.price,
productName: product.productName, productName: product.productName,
}); });
invoices.push(invoice); // ذخیره فاکتور برای هر محصول
} }
const newInvoice = new Invoice({
userId,
firstName: user.firstName,
lastName: user.lastName,
phoneNumber: user.phoneNumber,
email: user.email,
totalAmount: userCartItems.totalPrice,
});
return newInvoice; return invoices;
} }
async getInvoicesByUser(userId: number): Promise<Invoice[]> { async getInvoicesByUser(userId: number): Promise<Invoice[]> {

Loading…
Cancel
Save