/home/bdqbpbxa/dev-subdomains/admin.pixory.goodface.com.ua/src/api/cart/services/cart.ts
import { Core, Data } from "@strapi/strapi";
import { Cart } from "../common/types/cart";
import { PrintboxProject } from "src/api/project/common/types/project";
import { BookTypeService } from "src/api/book-type/services/book-type";
import { BookSizeService } from "src/api/book-size/services/book-size";
import { PaperFinishService } from "src/api/paper-finish/services/paper-finish";
export class CartService {
constructor(private readonly strapi: Core.Strapi) {}
public transform(cart: Cart) {
const cartPrice = cart.orderedProjects?.reduce((acc, orderedProject) => acc + orderedProject.project.priceDiscounted * orderedProject.quantity, 0);
const cartPriceDiscounted = cart.orderedProjects?.reduce((acc, orderedProject) => acc + orderedProject.project.price * orderedProject.quantity, 0);
return {
...cart,
cartPrice,
cartPriceDiscounted,
}
}
public async findOrCreate(userId: number): Promise<Cart & { cartPrice: number; cartPriceDiscounted: number }> {
let cart = await this.strapi.db.query('api::cart.cart').findOne({
where: { user: userId },
populate: {
orderedProjects: {
populate: {
project: {
populate: {
bookType: true,
bookSize: true,
paperFinish: true,
}
}
}
},
orderAdditives: true,
}
});
if (!cart) {
cart = await this.strapi.db.query('api::cart.cart').create({
data: {
user: userId,
},
populate: {
project: {
populate: {
bookType: true,
bookSize: true,
paperFinish: true,
}
}
}
});
}
return this.transform(cart);
}
public async appendOrderedProject(cartId: Data.ID, orderedProjectId: Data.ID[]) {
await this.strapi.db.query('api::cart.cart').update({
where: { id: cartId },
data: {
orderedProjects: {
connect: orderedProjectId,
}
}
})
}
public async getBookAttributes(projectData: PrintboxProject) {
const bookTypeService = new BookTypeService(strapi);
const bookSizeService = new BookSizeService(strapi);
const paperFinishService = new PaperFinishService(strapi);
const bookType = await bookSizeService.findByPrintboxIds(projectData.params[0].attribute_values_ids);
const bookSize = await bookTypeService.findByPrintboxIds(projectData.params[0].attribute_values_ids);
const paperFinish = await paperFinishService.findByPrintboxIds(projectData.params[0].attribute_values_ids);
return { bookType, bookSize, paperFinish };
}
}