You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

72 lines
2.3 KiB

import { forwardRef, HttpException, HttpStatus, Inject, Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize";
import { Invoice } from "./entities/invoice.entity";
import { CartService } from "src/cart/cart.service";
import { User } from "src/users/entities/user.entity";
@Injectable()
export class InvoiceService {
constructor(
@InjectModel(Invoice) private readonly invoiceModel: typeof Invoice,
@Inject(forwardRef(() => CartService))
private cartService: CartService,
) {}
async createInvoiceFromCart(userId: number): Promise<Invoice[]> {
const user = await User.findByPk(userId);
if (!user) {
throw new HttpException("User not found", HttpStatus.NOT_FOUND);
}
const userCartItems = await this.cartService.getUserCart(userId);
if (!userCartItems || userCartItems.cartItems.length === 0) {
throw new HttpException("Cart is empty", HttpStatus.BAD_REQUEST);
}
const invoices: Invoice[] = [];
for (const cartItem of userCartItems.cartItems) {
const invoice = await this.invoiceModel.create({
userId,
firstName: user.firstName,
lastName: user.lastName,
phoneNumber: user.phoneNumber,
email: user.email,
totalPaymentAmount: userCartItems.totalPrice,
productId: cartItem.productId,
quantity: cartItem.quantity,
price: cartItem.productPrice,
totalPrice:(cartItem.quantity*cartItem.productPrice),
productName: cartItem.productName,
});
invoices.push(invoice);
}
return invoices; // بازگرداندن آرایهای از فاکتورها
}
async getInvoicesByUser(userId: number): Promise<Invoice[]> {
try {
if (!userId) {
throw new HttpException("User ID is required.", HttpStatus.BAD_REQUEST);
}
const invoices = await this.invoiceModel.findAll({
where: { userId },
});
if (!invoices || invoices.length === 0) {
throw new HttpException("No invoices found for this user.", HttpStatus.NOT_FOUND);
}
return invoices;
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException("An error occurred while retrieving invoices.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}