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")
@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<Record<"hq" | "br", number>>(
(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")