From 277860805b72e9d18ac977e6d9a1ece976b67daa Mon Sep 17 00:00:00 2001 From: Methapon Metanipat Date: Thu, 5 Sep 2024 15:05:38 +0700 Subject: [PATCH] feat: count stats --- src/controllers/01-branch-controller.ts | 63 +++++++++++++++---------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/src/controllers/01-branch-controller.ts b/src/controllers/01-branch-controller.ts index cb37822..73db470 100644 --- a/src/controllers/01-branch-controller.ts +++ b/src/controllers/01-branch-controller.ts @@ -107,32 +107,45 @@ export class BranchController extends Controller { @Get("stats") @Security("keycloak") async getStats(@Request() req: RequestWithUser) { - const list = await prisma.branch.groupBy({ - _count: true, - by: "isHeadOffice", - where: { - AND: isSystem(req.user) - ? undefined - : [ - { - user: { some: { userId: req.user.sub } }, - }, - { - headOffice: globalAllow(req.user) - ? { user: { some: { userId: req.user.sub } } } - : undefined, - }, - ], - }, - }); + const where = { + AND: isSystem(req.user) + ? undefined + : [ + { + user: { some: { userId: req.user.sub } }, + }, + { + headOffice: globalAllow(req.user) + ? { user: { some: { userId: req.user.sub } } } + : undefined, + }, + ], + }; - return list.reduce>( - (a, c) => { - a[c.isHeadOffice ? "hq" : "br"] = c._count; - return a; - }, - { hq: 0, br: 0 }, - ); + const [hq, br, virtual] = await prisma.$transaction([ + prisma.branch.count({ + where: { + headOfficeId: null, + ...where, + }, + }), + prisma.branch.count({ + where: { + headOfficeId: { not: null }, + virtual: false, + ...where, + }, + }), + prisma.branch.count({ + where: { + headOfficeId: { not: null }, + virtual: true, + ...where, + }, + }), + ]); + + return { hq, br, virtual }; } @Get("user-stats")