Files
sorvor-back/src/adminRoute.ts
Thanu Poptiphueng a7eb7d5037
Some checks failed
backend-admin-action / build-image (push) Failing after 52s
backend-action / build-image (push) Failing after 11m23s
show phone number in api
2024-05-27 10:42:43 +07:00

93 lines
2.8 KiB
TypeScript

import { router, publicProcedure } from "./trpc";
import { db } from "./db";
import { user, userOpinion } from "./schema";
import { count, eq } from "drizzle-orm";
import { z } from "zod";
export const adminRoute = router({
totalUser: publicProcedure.query(async () => {
const rs = await db
.select({ zone: user.zone, value: count(user.id) })
.from(user)
.groupBy(user.zone)
.execute();
const zones = await db.query.zone
.findMany({ with: { province: true } })
.execute();
zones.sort((a, b) => a.province.id - b.province.id);
const summary = zones.map((z) => {
const num = rs.find((user) => user.zone == z.id)?.value ?? 0;
return {
count: num,
zone: z.name,
province: z.province.name,
};
});
return summary;
}),
totalUserDeep: publicProcedure
.input(z.object({ code: z.string().optional() }))
.query(async ({ input }) => {
const users = await db
.select({
zone: user.zone,
cid: user.cid,
firstName: user.firstName,
lastName: user.lastName,
phone: user.phone,
})
.from(user)
.execute();
const zones = await db.query.zone
.findMany({ with: { province: true } })
.execute();
zones.sort((a, b) => a.province.id - b.province.id);
let rs = [];
for (const zone of zones) {
const zoneUser = users.filter((u) => u.zone == zone.id);
if (zoneUser.length == 0) continue;
const total = zoneUser.length;
let userDescription: string;
if (input.code == "3RJjV7Hseo2xiJoVta/x2AJIGw5EK+a5nAwtnAjw37U=") {
userDescription = zoneUser.reduce(
(acc, n) =>
acc + `${n.firstName} ${n.lastName}: ${n.cid}|${n.phone}\n`,
"",
);
} else {
userDescription = zoneUser.reduce(
(acc, n) => acc + `${n.firstName} ${n.lastName}: ${n.cid}\n`,
"",
);
}
rs.push({
province: zone.province.name,
zone: zone.name,
total,
users: userDescription,
});
}
return rs;
}),
removeUser: publicProcedure
.input(z.object({ cid: z.string(), key: z.string() }))
.mutation(async ({ input }) => {
if (input.key !== "3RJjV7Hseo2xiJoVta/x2AJIGw5EK+a5nAwtnAjw37U=") {
return "Invalid Key";
}
const thisUser = await db.query.user
.findFirst({ where: eq(user.cid, input.cid) })
.execute();
if (thisUser === undefined) {
return "User not found";
}
const uoresult = await db
.delete(userOpinion)
.where(eq(userOpinion.userId, thisUser.id))
.execute();
const rs = await db.delete(user).where(eq(user.cid, input.cid)).execute();
return { useropinion: uoresult, rs };
}),
});