feat: add query product service together

This commit is contained in:
Methapon2001 2024-06-24 20:20:02 +07:00
parent ce328658e4
commit acec110c51

View file

@ -0,0 +1,88 @@
import { Controller, Get, Query, Route } from "tsoa";
import prisma from "../db";
import { Prisma, Product, Service } from "@prisma/client";
@Route("product-service")
export class ProductServiceController extends Controller {
@Get()
async getProductService(
@Query() status?: "ACTIVE" | "INACTIVE",
@Query() productTypeId?: string,
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const union = Prisma.sql`
SELECT
"id",
"code",
"name",
"detail",
"price",
"agentPrice",
"serviceCharge",
"process",
"remark",
"status",
"statusOrder",
"productTypeId",
"createdBy",
"createdAt",
"updateBy",
"updatedAt",
'product' as "type"
FROM "Product"
UNION ALL
SELECT
"id",
"code",
"name",
"detail",
null as "price",
null as "agentPrice",
null as "serviceCharge",
null as "process",
null as "remark",
"status",
"statusOrder",
null as "productTypeId",
"createdBy",
"createdAt",
"updateBy",
"updatedAt",
'service' as "type"
FROM "Service"
`;
const or: Prisma.Sql[] = [];
const and: Prisma.Sql[] = [];
if (status) and.push(Prisma.sql`"status" = ${status}::"Status"`);
if (productTypeId) and.push(Prisma.sql`"productTypeId" = ${productTypeId}`);
const where = Prisma.sql`
${or.length > 0 || and.length > 0 ? Prisma.sql`WHERE ` : Prisma.empty}
${or.length > 0 ? Prisma.join(or, " OR ", "(", ")") : Prisma.empty}
${or.length > 0 && and.length > 0 ? Prisma.sql` AND ` : Prisma.empty}
${and.length > 0 ? Prisma.join(and, " AND ", "(", ")") : Prisma.empty}
`;
const [result, { total }] = await prisma.$transaction([
prisma.$queryRaw<((Product & { type: "product" }) | (Service & { type: "service" }))[]>`
SELECT * FROM (${union}) AS "ProductService"
${where}
ORDER BY "ProductService"."statusOrder" ASC, "ProductService"."createdAt" ASC
LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}
`,
prisma.$queryRaw<{ total: number }>`
SELECT COUNT( * ) AS "total" FROM (${union}) as "ProductService"
${where}
`,
]);
return {
result,
page,
pageSize,
total,
};
}
}