From acec110c513efa45ffaca347973a81b31480ebef Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Mon, 24 Jun 2024 20:20:02 +0700 Subject: [PATCH] feat: add query product service together --- src/controllers/product-service-controller.ts | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/controllers/product-service-controller.ts diff --git a/src/controllers/product-service-controller.ts b/src/controllers/product-service-controller.ts new file mode 100644 index 0000000..13585ac --- /dev/null +++ b/src/controllers/product-service-controller.ts @@ -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, + }; + } +}