Enhance invoicing system

master
nicekid1 2 months ago
parent 187811a048
commit 7fa178b293
  1. 29
      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

@ -46,23 +46,20 @@ export class CartController {
}
@Post(':userId/checkout')
async processOrder(
@Param('userId') userId: number,
@Body('totalAmount') totalAmount: number,
): Promise<{ message: string; invoice: Invoice }> {
if (!totalAmount || totalAmount <= 0 || isNaN(totalAmount)) {
throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST);
}
async processOrder(
@Param('userId') userId: number,
@Body('totalAmount') totalAmount: number,
): Promise<{ message: string; invoices: Invoice[] }> {
if (!totalAmount || totalAmount <= 0) {
throw new HttpException('Invalid total amount.', HttpStatus.BAD_REQUEST);
}
try {
const result = await this.cartService.processOrder(userId, totalAmount);
return result;
} catch (error) {
throw new HttpException(
error.message || 'An unexpected error occurred while processing the order.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
try {
const result = await this.cartService.processOrder(userId, totalAmount);
return result;
} catch (error) {
throw new HttpException(error.message || 'Order processing failed.', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
}

@ -108,8 +108,8 @@ export class CartService {
await this.cartModel.destroy({ where: { userId } });
}
//order(clearCart unable)
async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoice: Invoice }> {
//order(clearCart disable)
async processOrder(userId: number, totalAmount: number): Promise<{ message: string; invoices: Invoice[] }> {
try {
// Deducting credit from wallet
await this.walletService.processPayment(userId, totalAmount);
@ -120,7 +120,8 @@ export class CartService {
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) {
const { productId, quantity } = cartItem;
@ -134,14 +135,16 @@ export class CartService {
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();
}
// Create the invoice after processing the cart
const invoice = await this.invoiceService.createInvoiceFromCart(userId);
// Create invoice for this product
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) {
console.log(error);
if (error instanceof HttpException) {

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

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

Loading…
Cancel
Save