jws-backend/src/controllers/04-product-group-controller.ts

287 lines
7.1 KiB
TypeScript
Raw Normal View History

2024-06-06 16:50:44 +07:00
import {
Body,
Controller,
Delete,
Get,
Put,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import { Prisma, Status } from "@prisma/client";
2024-09-05 09:19:48 +07:00
import prisma from "../db";
import { RequestWithUser } from "../interfaces/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
2024-09-09 09:42:16 +07:00
import { isSystem } from "../utils/keycloak";
2024-09-10 13:33:59 +07:00
import {
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
import { filterStatus } from "../services/prisma";
2024-06-06 16:50:44 +07:00
type ProductGroupCreate = {
name: string;
detail: string;
remark: string;
2024-06-19 17:06:52 +07:00
status?: Status;
2024-09-10 13:33:59 +07:00
registeredBranchId: string;
2024-06-06 16:50:44 +07:00
};
type ProductGroupUpdate = {
name?: string;
detail?: string;
remark?: string;
2024-06-19 17:06:52 +07:00
status?: "ACTIVE" | "INACTIVE";
2024-09-09 09:42:16 +07:00
registeredBranchId?: string;
2024-06-06 16:50:44 +07:00
};
2024-09-09 09:42:16 +07:00
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"head_of_account",
"account",
"head_of_sale",
];
function globalAllow(user: RequestWithUser["user"]) {
const allowList = ["system", "head_of_admin", "admin", "head_of_account", "head_of_sale"];
return allowList.some((v) => user.roles?.includes(v));
}
2024-09-10 13:33:59 +07:00
const permissionCond = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow);
2024-09-09 09:42:16 +07:00
2024-06-11 13:35:54 +07:00
@Route("api/v1/product-group")
2024-06-06 16:50:44 +07:00
@Tags("Product Group")
export class ProductGroup extends Controller {
2024-06-11 09:31:10 +07:00
@Get("stats")
2024-07-02 16:54:19 +07:00
@Security("keycloak")
2024-09-10 13:33:59 +07:00
async getProductGroupStats(@Request() req: RequestWithUser) {
return await prisma.productGroup.count({
where: {
AND: [
{
registeredBranch: isSystem(req.user) ? undefined : { OR: permissionCond(req.user) },
},
],
},
});
2024-06-11 09:27:37 +07:00
}
2024-06-06 16:50:44 +07:00
@Get()
2024-07-02 16:54:19 +07:00
@Security("keycloak")
2024-06-26 11:12:53 +07:00
async getProductGroup(
2024-09-09 09:42:16 +07:00
@Request() req: RequestWithUser,
2024-06-26 11:12:53 +07:00
@Query() query: string = "",
@Query() status?: Status,
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
2024-06-06 16:50:44 +07:00
const where = {
2024-09-10 13:33:59 +07:00
OR: [{ name: { contains: query } }, { detail: { contains: query } }],
2024-09-09 09:42:16 +07:00
AND: [
{
2024-09-10 13:33:59 +07:00
...filterStatus(status),
registeredBranch: isSystem(req.user) ? undefined : { OR: permissionCond(req.user) },
2024-09-09 09:42:16 +07:00
},
],
2024-06-06 16:50:44 +07:00
} satisfies Prisma.ProductGroupWhereInput;
2024-06-26 11:12:53 +07:00
const [result, total] = await prisma.$transaction([
prisma.productGroup.findMany({
2024-06-28 18:00:07 +07:00
include: {
_count: {
select: {
2024-09-03 14:06:02 +07:00
service: true,
product: true,
2024-06-28 18:00:07 +07:00
},
},
2024-07-01 14:38:07 +07:00
createdBy: true,
updatedBy: true,
2024-06-28 18:00:07 +07:00
},
2024-06-26 11:12:53 +07:00
orderBy: [{ statusOrder: "asc" }, { createdAt: "asc" }],
where,
2024-06-26 13:01:01 +07:00
take: pageSize,
skip: (page - 1) * pageSize,
2024-06-26 11:12:53 +07:00
}),
prisma.productGroup.count({ where }),
]);
2024-06-28 18:00:07 +07:00
return {
2024-09-03 14:06:02 +07:00
result,
2024-06-28 18:00:07 +07:00
page,
pageSize,
total,
};
2024-06-06 16:50:44 +07:00
}
@Get("{groupId}")
2024-07-02 16:54:19 +07:00
@Security("keycloak")
2024-06-06 16:50:44 +07:00
async getProductGroupById(@Path() groupId: string) {
const record = await prisma.productGroup.findFirst({
where: { id: groupId },
});
if (!record)
2024-06-19 17:06:52 +07:00
throw new HttpError(
HttpStatus.NOT_FOUND,
"Product group cannot be found.",
"productGroupNotFound",
);
2024-06-06 16:50:44 +07:00
return record;
}
@Post()
2024-09-09 09:42:16 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-06-06 16:50:44 +07:00
async createProductGroup(@Request() req: RequestWithUser, @Body() body: ProductGroupCreate) {
2024-09-10 13:33:59 +07:00
let company = await permissionCheck(req.user, body.registeredBranchId).then(
(v) => (v.headOffice || v).code,
);
2024-09-09 09:42:16 +07:00
2024-06-11 14:00:45 +07:00
const record = await prisma.$transaction(
async (tx) => {
const last = await tx.runningNo.upsert({
where: {
2024-09-10 13:33:59 +07:00
key: `PRODGRP_${company}`,
2024-06-11 14:00:45 +07:00
},
create: {
2024-09-10 13:33:59 +07:00
key: `PRODGRP_${company}`,
2024-06-11 14:00:45 +07:00
value: 1,
},
update: { value: { increment: 1 } },
});
2024-06-11 13:01:20 +07:00
2024-06-11 14:00:45 +07:00
return await tx.productGroup.create({
2024-07-01 14:38:07 +07:00
include: {
createdBy: true,
updatedBy: true,
},
2024-06-11 14:00:45 +07:00
data: {
...body,
2024-06-24 13:14:44 +07:00
statusOrder: +(body.status === "INACTIVE"),
2024-06-11 14:00:45 +07:00
code: `G${last.value.toString().padStart(2, "0")}`,
2024-07-01 13:24:02 +07:00
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
2024-06-11 14:00:45 +07:00
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
2024-06-06 16:50:44 +07:00
this.setStatus(HttpStatus.CREATED);
return record;
}
@Put("{groupId}")
2024-09-09 09:42:16 +07:00
@Security("keycloak", MANAGE_ROLES)
2024-06-06 16:50:44 +07:00
async editProductGroup(
@Request() req: RequestWithUser,
@Body() body: ProductGroupUpdate,
@Path() groupId: string,
) {
2024-09-09 09:42:16 +07:00
const record = await prisma.productGroup.findUnique({
where: { id: groupId },
include: {
registeredBranch: {
2024-09-10 13:33:59 +07:00
include: branchRelationPermInclude(req.user),
2024-09-09 09:42:16 +07:00
},
},
});
if (!record) {
2024-06-19 17:06:52 +07:00
throw new HttpError(
HttpStatus.NOT_FOUND,
"Product group cannot be found.",
"productGroupNotFound",
);
2024-06-06 16:50:44 +07:00
}
2024-09-10 13:33:59 +07:00
if (record.registeredBranch) await permissionCheck(req.user, record.registeredBranch);
2024-09-09 09:42:16 +07:00
const [branch] = await prisma.$transaction([
prisma.branch.findFirst({
where: { id: body.registeredBranchId },
2024-09-10 13:33:59 +07:00
include: branchRelationPermInclude(req.user),
2024-09-09 09:42:16 +07:00
}),
]);
2024-09-10 13:33:59 +07:00
if (body.registeredBranchId !== undefined) {
await permissionCheck(req.user, branch);
2024-09-09 09:42:16 +07:00
}
if (!!body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
2024-09-10 17:00:21 +07:00
let companyBefore = (record.registeredBranch.headOffice || record.registeredBranch).code;
let companyAfter = branch ? (branch.headOffice || branch).code : false;
if (companyBefore && companyAfter && companyBefore !== companyAfter) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Cannot move between different headoffice",
"crossCompanyNotPermit",
);
}
2024-09-09 09:42:16 +07:00
const result = await prisma.productGroup.update({
2024-07-01 14:38:07 +07:00
include: {
createdBy: true,
updatedBy: true,
},
2024-07-01 13:24:02 +07:00
data: { ...body, statusOrder: +(body.status === "INACTIVE"), updatedByUserId: req.user.sub },
2024-06-06 16:50:44 +07:00
where: { id: groupId },
});
2024-09-09 09:42:16 +07:00
return result;
2024-06-06 16:50:44 +07:00
}
@Delete("{groupId}")
2024-09-09 09:42:16 +07:00
@Security("keycloak", MANAGE_ROLES)
async deleteProductGroup(@Request() req: RequestWithUser, @Path() groupId: string) {
const record = await prisma.productGroup.findFirst({
where: { id: groupId },
include: {
registeredBranch: {
2024-09-10 13:33:59 +07:00
include: branchRelationPermInclude(req.user),
2024-09-09 09:42:16 +07:00
},
},
});
2024-06-06 16:50:44 +07:00
if (!record) {
2024-06-19 17:06:52 +07:00
throw new HttpError(
HttpStatus.NOT_FOUND,
"Product group cannot be found.",
"productGroupNotFound",
);
2024-06-06 16:50:44 +07:00
}
2024-09-10 13:33:59 +07:00
if (record.registeredBranch) await permissionCheck(req.user, record.registeredBranch);
2024-09-09 09:42:16 +07:00
2024-06-06 16:50:44 +07:00
if (record.status !== Status.CREATED) {
2024-06-14 04:40:10 +00:00
throw new HttpError(HttpStatus.FORBIDDEN, "Product group is in used.", "productGroupInUsed");
2024-06-06 16:50:44 +07:00
}
2024-07-01 14:38:07 +07:00
return await prisma.productGroup.delete({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: groupId },
});
2024-06-06 16:50:44 +07:00
}
}