feat: count stats

This commit is contained in:
Methapon Metanipat 2024-09-05 15:05:38 +07:00
parent 097e2df4fb
commit 277860805b

View file

@ -107,32 +107,45 @@ export class BranchController extends Controller {
@Get("stats") @Get("stats")
@Security("keycloak") @Security("keycloak")
async getStats(@Request() req: RequestWithUser) { async getStats(@Request() req: RequestWithUser) {
const list = await prisma.branch.groupBy({ const where = {
_count: true, AND: isSystem(req.user)
by: "isHeadOffice", ? undefined
where: { : [
AND: isSystem(req.user) {
? undefined user: { some: { userId: req.user.sub } },
: [ },
{ {
user: { some: { userId: req.user.sub } }, headOffice: globalAllow(req.user)
}, ? { user: { some: { userId: req.user.sub } } }
{ : undefined,
headOffice: globalAllow(req.user) },
? { user: { some: { userId: req.user.sub } } } ],
: undefined, };
},
],
},
});
return list.reduce<Record<"hq" | "br", number>>( const [hq, br, virtual] = await prisma.$transaction([
(a, c) => { prisma.branch.count({
a[c.isHeadOffice ? "hq" : "br"] = c._count; where: {
return a; headOfficeId: null,
}, ...where,
{ hq: 0, br: 0 }, },
); }),
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") @Get("user-stats")