refactor/product-service-permission

This commit is contained in:
Methapon2001 2024-07-03 17:28:00 +07:00
parent 390b27716b
commit 6945761397
2 changed files with 233 additions and 29 deletions

View file

@ -25,6 +25,15 @@ if (!process.env.MINIO_BUCKET) {
} }
const MINIO_BUCKET = process.env.MINIO_BUCKET; const MINIO_BUCKET = process.env.MINIO_BUCKET;
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"branch_admin",
"branch_manager",
"accountant",
"branch_accountant",
];
type ProductCreate = { type ProductCreate = {
status?: Status; status?: Status;
@ -51,6 +60,8 @@ type ProductCreate = {
serviceCharge: number; serviceCharge: number;
productTypeId: string; productTypeId: string;
remark?: string; remark?: string;
registeredBranchId?: string;
}; };
type ProductUpdate = { type ProductUpdate = {
@ -63,12 +74,20 @@ type ProductUpdate = {
serviceCharge?: number; serviceCharge?: number;
remark?: string; remark?: string;
productTypeId?: string; productTypeId?: string;
registeredBranchId?: string;
}; };
function imageLocation(id: string) { function imageLocation(id: string) {
return `product/${id}/image`; return `product/${id}/image`;
} }
function globalAllow(roles?: string[]) {
return ["system", "head_of_admin", "admin", "branch_admin", "branch_manager", "accountant"].some(
(v) => roles?.includes(v),
);
}
@Route("api/v1/product") @Route("api/v1/product")
@Tags("Product") @Tags("Product")
export class ProductController extends Controller { export class ProductController extends Controller {
@ -85,6 +104,7 @@ export class ProductController extends Controller {
@Query() query: string = "", @Query() query: string = "",
@Query() page: number = 1, @Query() page: number = 1,
@Query() pageSize: number = 30, @Query() pageSize: number = 30,
@Query() branchId?: string,
) { ) {
const filterStatus = (val?: Status) => { const filterStatus = (val?: Status) => {
if (!val) return {}; if (!val) return {};
@ -99,6 +119,9 @@ export class ProductController extends Controller {
{ name: { contains: query }, productTypeId, ...filterStatus(status) }, { name: { contains: query }, productTypeId, ...filterStatus(status) },
{ detail: { contains: query }, productTypeId, ...filterStatus(status) }, { detail: { contains: query }, productTypeId, ...filterStatus(status) },
], ],
AND: {
OR: [{ registeredBranchId: branchId }, { registeredBranchId: null }],
},
} satisfies Prisma.ProductWhereInput; } satisfies Prisma.ProductWhereInput;
const [result, total] = await prisma.$transaction([ const [result, total] = await prisma.$transaction([
@ -164,15 +187,29 @@ export class ProductController extends Controller {
} }
@Post() @Post()
@Security("keycloak", ["system", "head_of_admin", "admin", "branch_accountant", "accountant"]) @Security("keycloak", MANAGE_ROLES)
async createProduct(@Request() req: RequestWithUser, @Body() body: ProductCreate) { async createProduct(@Request() req: RequestWithUser, @Body() body: ProductCreate) {
const productType = await prisma.productType.findFirst({ const [productType, branch] = await prisma.$transaction([
include: { prisma.productType.findFirst({
createdBy: true, include: {
updatedBy: true, createdBy: true,
}, updatedBy: true,
where: { id: body.productTypeId }, },
}); where: { id: body.productTypeId },
}),
prisma.branch.findFirst({
include: { user: { where: { id: req.user.sub } } },
where: { id: body.registeredBranchId },
}),
]);
if (!globalAllow(req.user.roles) && !branch?.user.find((v) => v.userId === req.user.sub)) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (!productType) { if (!productType) {
throw new HttpError( throw new HttpError(
@ -182,6 +219,14 @@ export class ProductController extends Controller {
); );
} }
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.$transaction( const record = await prisma.$transaction(
async (tx) => { async (tx) => {
const last = await tx.runningNo.upsert({ const last = await tx.runningNo.upsert({
@ -241,19 +286,44 @@ export class ProductController extends Controller {
} }
@Put("{productId}") @Put("{productId}")
@Security("keycloak", ["system", "head_of_admin", "admin", "branch_accountant", "accountant"]) @Security("keycloak", MANAGE_ROLES)
async editProduct( async editProduct(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Body() body: ProductUpdate, @Body() body: ProductUpdate,
@Path() productId: string, @Path() productId: string,
) { ) {
if (!(await prisma.product.findUnique({ where: { id: productId } }))) { const [product, productType, branch] = await prisma.$transaction([
prisma.product.findUnique({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: productId },
}),
prisma.productType.findFirst({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: body.productTypeId },
}),
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (!product) {
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound"); throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
} }
const productType = await prisma.productType.findFirst({ if (!globalAllow(req.user.roles) && !product.registeredBranch) {
where: { id: body.productTypeId }, throw new HttpError(
}); HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (!productType) { if (!productType) {
throw new HttpError( throw new HttpError(
@ -263,6 +333,14 @@ export class ProductController extends Controller {
); );
} }
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.product.update({ const record = await prisma.product.update({
include: { include: {
createdBy: true, createdBy: true,
@ -294,14 +372,32 @@ export class ProductController extends Controller {
} }
@Delete("{productId}") @Delete("{productId}")
@Security("keycloak", ["system", "head_of_admin", "admin", "branch_accountant", "accountant"]) @Security("keycloak", MANAGE_ROLES)
async deleteProduct(@Path() productId: string) { async deleteProduct(@Request() req: RequestWithUser, @Path() productId: string) {
const record = await prisma.product.findFirst({ where: { id: productId } }); const record = await prisma.product.findFirst({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: productId },
});
if (!record) { if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound"); throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
} }
if (!globalAllow(req.user.roles) && !record.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (record.status !== Status.CREATED) { if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Product is in used.", "productInUsed"); throw new HttpError(HttpStatus.FORBIDDEN, "Product is in used.", "productInUsed");
} }

View file

@ -25,6 +25,15 @@ if (!process.env.MINIO_BUCKET) {
} }
const MINIO_BUCKET = process.env.MINIO_BUCKET; const MINIO_BUCKET = process.env.MINIO_BUCKET;
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"branch_admin",
"branch_manager",
"accountant",
"branch_accountant",
];
type ServiceCreate = { type ServiceCreate = {
code: "MOU" | "mou"; code: "MOU" | "mou";
@ -40,6 +49,7 @@ type ServiceCreate = {
attributes?: { [key: string]: any }; attributes?: { [key: string]: any };
}[]; }[];
productTypeId: string; productTypeId: string;
registeredBranchId?: string;
}; };
type ServiceUpdate = { type ServiceUpdate = {
@ -55,12 +65,17 @@ type ServiceUpdate = {
attributes?: { [key: string]: any }; attributes?: { [key: string]: any };
}[]; }[];
productTypeId?: string; productTypeId?: string;
registeredBranchId?: string;
}; };
function imageLocation(id: string) { function imageLocation(id: string) {
return `service/${id}/service-image`; return `service/${id}/service-image`;
} }
function globalAllow(roles?: string[]) {
return ["system", "head_of_admin", "admin", "accountant"].some((v) => roles?.includes(v));
}
@Route("api/v1/service") @Route("api/v1/service")
@Tags("Service") @Tags("Service")
export class ServiceController extends Controller { export class ServiceController extends Controller {
@ -78,6 +93,7 @@ export class ServiceController extends Controller {
@Query() pageSize: number = 30, @Query() pageSize: number = 30,
@Query() status?: Status, @Query() status?: Status,
@Query() productTypeId?: string, @Query() productTypeId?: string,
@Query() branchId?: string,
) { ) {
const filterStatus = (val?: Status) => { const filterStatus = (val?: Status) => {
if (!val) return {}; if (!val) return {};
@ -92,6 +108,9 @@ export class ServiceController extends Controller {
{ name: { contains: query }, productTypeId, ...filterStatus(status) }, { name: { contains: query }, productTypeId, ...filterStatus(status) },
{ detail: { contains: query }, productTypeId, ...filterStatus(status) }, { detail: { contains: query }, productTypeId, ...filterStatus(status) },
], ],
AND: {
OR: [{ registeredBranchId: branchId }, { registeredBranchId: null }],
},
} satisfies Prisma.ServiceWhereInput; } satisfies Prisma.ServiceWhereInput;
const [result, total] = await prisma.$transaction([ const [result, total] = await prisma.$transaction([
@ -199,17 +218,31 @@ export class ServiceController extends Controller {
} }
@Post() @Post()
@Security("keycloak") @Security("keycloak", MANAGE_ROLES)
async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) { async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) {
const { work, productTypeId, ...payload } = body; const { work, productTypeId, ...payload } = body;
const productType = await prisma.productType.findFirst({ const [productType, branch] = await prisma.$transaction([
include: { prisma.productType.findFirst({
createdBy: true, include: {
updatedBy: true, createdBy: true,
}, updatedBy: true,
where: { id: body.productTypeId }, },
}); where: { id: body.productTypeId },
}),
prisma.branch.findFirst({
include: { user: { where: { id: req.user.sub } } },
where: { id: body.registeredBranchId },
}),
]);
if (!globalAllow(req.user.roles) && !branch?.user.find((v) => v.userId === req.user.sub)) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (!productType) { if (!productType) {
throw new HttpError( throw new HttpError(
@ -219,6 +252,14 @@ export class ServiceController extends Controller {
); );
} }
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.$transaction( const record = await prisma.$transaction(
async (tx) => { async (tx) => {
const last = await tx.runningNo.upsert({ const last = await tx.runningNo.upsert({
@ -297,7 +338,7 @@ export class ServiceController extends Controller {
} }
@Put("{serviceId}") @Put("{serviceId}")
@Security("keycloak") @Security("keycloak", MANAGE_ROLES)
async editService( async editService(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Body() body: ServiceUpdate, @Body() body: ServiceUpdate,
@ -306,7 +347,57 @@ export class ServiceController extends Controller {
if (!(await prisma.service.findUnique({ where: { id: serviceId } }))) { if (!(await prisma.service.findUnique({ where: { id: serviceId } }))) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound"); throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
} }
const { work, ...payload } = body; const { work, productTypeId, ...payload } = body;
const [service, productType, branch] = await prisma.$transaction([
prisma.service.findUnique({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: serviceId },
}),
prisma.productType.findFirst({
include: {
createdBy: true,
updatedBy: true,
},
where: { id: body.productTypeId },
}),
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
]);
if (!service) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
}
if (!globalAllow(req.user.roles) && !service.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (!productType) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Product Type cannot be found.",
"relationProductTypeNotFound",
);
}
if (body.registeredBranchId && !branch) {
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
const record = await prisma.$transaction(async (tx) => { const record = await prisma.$transaction(async (tx) => {
const workList = await Promise.all( const workList = await Promise.all(
(work || []).map(async (w, wIdx) => (work || []).map(async (w, wIdx) =>
@ -361,14 +452,31 @@ export class ServiceController extends Controller {
} }
@Delete("{serviceId}") @Delete("{serviceId}")
@Security("keycloak") @Security("keycloak", MANAGE_ROLES)
async deleteService(@Path() serviceId: string) { async deleteService(@Request() req: RequestWithUser, @Path() serviceId: string) {
const record = await prisma.service.findFirst({ where: { id: serviceId } }); const record = await prisma.service.findFirst({
include: {
registeredBranch: {
where: {
user: { some: { userId: req.user.sub } },
},
},
},
where: { id: serviceId },
});
if (!record) { if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound"); throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
} }
if (!globalAllow(req.user.roles) && !record.registeredBranch) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
if (record.status !== Status.CREATED) { if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Service is in used.", "serviceInUsed"); throw new HttpError(HttpStatus.FORBIDDEN, "Service is in used.", "serviceInUsed");
} }