278 lines
7.1 KiB
TypeScript
278 lines
7.1 KiB
TypeScript
import {
|
|
Body,
|
|
Controller,
|
|
Delete,
|
|
Get,
|
|
Put,
|
|
Path,
|
|
Post,
|
|
Query,
|
|
Request,
|
|
Route,
|
|
Security,
|
|
Tags,
|
|
} from "tsoa";
|
|
import { Prisma, Status } from "@prisma/client";
|
|
|
|
import prisma from "../db";
|
|
import { RequestWithUser } from "../interfaces/user";
|
|
import HttpError from "../interfaces/http-error";
|
|
import HttpStatus from "../interfaces/http-status";
|
|
import { isSystem } from "../utils/keycloak";
|
|
import {
|
|
branchActiveOnlyCond,
|
|
branchRelationPermInclude,
|
|
createPermCheck,
|
|
createPermCondition,
|
|
} from "../services/permission";
|
|
import { filterStatus } from "../services/prisma";
|
|
import { isUsedError, notFoundError, relationError } from "../utils/error";
|
|
import { queryOrNot } from "../utils/relation";
|
|
|
|
type ProductGroupCreate = {
|
|
name: string;
|
|
detail: string;
|
|
remark: string;
|
|
status?: Status;
|
|
shared?: boolean;
|
|
registeredBranchId: string;
|
|
};
|
|
|
|
type ProductGroupUpdate = {
|
|
name?: string;
|
|
detail?: string;
|
|
remark?: string;
|
|
status?: "ACTIVE" | "INACTIVE";
|
|
shared?: boolean;
|
|
registeredBranchId?: string;
|
|
};
|
|
|
|
const MANAGE_ROLES = [
|
|
"system",
|
|
"head_of_admin",
|
|
"admin",
|
|
"head_of_accountant",
|
|
"accountant",
|
|
"head_of_sale",
|
|
];
|
|
|
|
function globalAllow(user: RequestWithUser["user"]) {
|
|
const allowList = ["system", "head_of_admin", "head_of_accountant", "head_of_sale"];
|
|
return allowList.some((v) => user.roles?.includes(v));
|
|
}
|
|
|
|
const permissionCond = createPermCondition((_) => true);
|
|
const permissionCheck = createPermCheck(globalAllow);
|
|
|
|
@Route("api/v1/product-group")
|
|
@Tags("Product Group")
|
|
export class ProductGroup extends Controller {
|
|
@Get("stats")
|
|
@Security("keycloak")
|
|
async getProductGroupStats(@Request() req: RequestWithUser) {
|
|
return await prisma.productGroup.count({
|
|
where: {
|
|
AND: [
|
|
{
|
|
registeredBranch: isSystem(req.user) ? undefined : { OR: permissionCond(req.user) },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
}
|
|
|
|
@Get()
|
|
@Security("keycloak")
|
|
async getProductGroup(
|
|
@Request() req: RequestWithUser,
|
|
@Query() query: string = "",
|
|
@Query() status?: Status,
|
|
@Query() page: number = 1,
|
|
@Query() pageSize: number = 30,
|
|
@Query() activeOnly?: boolean,
|
|
) {
|
|
const where = {
|
|
OR: queryOrNot<Prisma.ProductGroupWhereInput[]>(query, [
|
|
{ name: { contains: query } },
|
|
{ detail: { contains: query } },
|
|
{ code: { contains: query, mode: "insensitive" } },
|
|
]),
|
|
AND: [
|
|
{
|
|
...filterStatus(activeOnly ? Status.ACTIVE : status),
|
|
registeredBranch: isSystem(req.user)
|
|
? branchActiveOnlyCond(activeOnly)
|
|
: { OR: permissionCond(req.user, { activeOnly }) },
|
|
},
|
|
],
|
|
} satisfies Prisma.ProductGroupWhereInput;
|
|
|
|
const [result, total] = await prisma.$transaction([
|
|
prisma.productGroup.findMany({
|
|
include: {
|
|
_count: {
|
|
select: {
|
|
service: true,
|
|
product: true,
|
|
},
|
|
},
|
|
registeredBranch: true,
|
|
createdBy: true,
|
|
updatedBy: true,
|
|
},
|
|
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
|
|
where,
|
|
take: pageSize,
|
|
skip: (page - 1) * pageSize,
|
|
}),
|
|
prisma.productGroup.count({ where }),
|
|
]);
|
|
|
|
return {
|
|
result,
|
|
page,
|
|
pageSize,
|
|
total,
|
|
};
|
|
}
|
|
|
|
@Get("{groupId}")
|
|
@Security("keycloak")
|
|
async getProductGroupById(@Path() groupId: string) {
|
|
const record = await prisma.productGroup.findFirst({
|
|
include: {
|
|
registeredBranch: true,
|
|
},
|
|
where: { id: groupId },
|
|
});
|
|
|
|
if (!record) throw notFoundError("Product Group");
|
|
|
|
return record;
|
|
}
|
|
|
|
@Post()
|
|
@Security("keycloak", MANAGE_ROLES)
|
|
async createProductGroup(@Request() req: RequestWithUser, @Body() body: ProductGroupCreate) {
|
|
let company = await permissionCheck(req.user, body.registeredBranchId).then(
|
|
(v) => (v.headOffice || v).code,
|
|
);
|
|
|
|
const record = await prisma.$transaction(
|
|
async (tx) => {
|
|
const last = await tx.runningNo.upsert({
|
|
where: {
|
|
key: `PRODGRP_${company}`,
|
|
},
|
|
create: {
|
|
key: `PRODGRP_${company}`,
|
|
value: 1,
|
|
},
|
|
update: { value: { increment: 1 } },
|
|
});
|
|
|
|
return await tx.productGroup.create({
|
|
include: {
|
|
createdBy: true,
|
|
updatedBy: true,
|
|
},
|
|
data: {
|
|
...body,
|
|
statusOrder: +(body.status === "INACTIVE"),
|
|
code: `G${last.value.toString().padStart(2, "0")}`,
|
|
createdByUserId: req.user.sub,
|
|
updatedByUserId: req.user.sub,
|
|
},
|
|
});
|
|
},
|
|
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
|
);
|
|
|
|
this.setStatus(HttpStatus.CREATED);
|
|
|
|
return record;
|
|
}
|
|
|
|
@Put("{groupId}")
|
|
@Security("keycloak", MANAGE_ROLES)
|
|
async editProductGroup(
|
|
@Request() req: RequestWithUser,
|
|
@Body() body: ProductGroupUpdate,
|
|
@Path() groupId: string,
|
|
) {
|
|
const record = await prisma.productGroup.findUnique({
|
|
where: { id: groupId },
|
|
include: {
|
|
registeredBranch: {
|
|
include: branchRelationPermInclude(req.user),
|
|
},
|
|
},
|
|
});
|
|
if (!record) throw notFoundError("Product Group");
|
|
|
|
if (record.registeredBranch) await permissionCheck(req.user, record.registeredBranch);
|
|
|
|
const [branch] = await prisma.$transaction([
|
|
prisma.branch.findFirst({
|
|
where: { id: body.registeredBranchId },
|
|
include: branchRelationPermInclude(req.user),
|
|
}),
|
|
]);
|
|
|
|
if (body.registeredBranchId !== undefined) {
|
|
await permissionCheck(req.user, branch);
|
|
}
|
|
|
|
if (!!body.registeredBranchId && !branch) throw relationError("Branch");
|
|
|
|
let companyBefore = (record.registeredBranch.headOffice || record.registeredBranch).code;
|
|
let companyAfter =
|
|
!!body.registeredBranchId && branch ? (branch.headOffice || branch).code : false;
|
|
|
|
if (companyBefore && companyAfter && companyBefore !== companyAfter) {
|
|
throw new HttpError(
|
|
HttpStatus.BAD_REQUEST,
|
|
"Cannot move between different headoffice",
|
|
"crossCompanyNotPermit",
|
|
);
|
|
}
|
|
|
|
const result = await prisma.productGroup.update({
|
|
include: {
|
|
createdBy: true,
|
|
updatedBy: true,
|
|
},
|
|
data: { ...body, statusOrder: +(body.status === "INACTIVE"), updatedByUserId: req.user.sub },
|
|
where: { id: groupId },
|
|
});
|
|
|
|
return result;
|
|
}
|
|
|
|
@Delete("{groupId}")
|
|
@Security("keycloak", MANAGE_ROLES)
|
|
async deleteProductGroup(@Request() req: RequestWithUser, @Path() groupId: string) {
|
|
const record = await prisma.productGroup.findFirst({
|
|
where: { id: groupId },
|
|
include: {
|
|
registeredBranch: {
|
|
include: branchRelationPermInclude(req.user),
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!record) throw notFoundError("Product Group");
|
|
|
|
if (record.registeredBranch) await permissionCheck(req.user, record.registeredBranch);
|
|
|
|
if (record.status !== Status.CREATED) throw isUsedError("Product Group");
|
|
|
|
return await prisma.productGroup.delete({
|
|
include: {
|
|
createdBy: true,
|
|
updatedBy: true,
|
|
},
|
|
where: { id: groupId },
|
|
});
|
|
}
|
|
}
|