feat: refactor permission product service
This commit is contained in:
parent
f9cc39522c
commit
8c0932f6d8
4 changed files with 189 additions and 292 deletions
|
|
@ -0,0 +1,46 @@
|
||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- You are about to drop the column `registeredBranchId` on the `Product` table. All the data in the column will be lost.
|
||||||
|
- You are about to drop the column `registeredBranchId` on the `Service` table. All the data in the column will be lost.
|
||||||
|
- Made the column `productGroupId` on table `Product` required. This step will fail if there are existing NULL values in that column.
|
||||||
|
- Made the column `registeredBranchId` on table `ProductGroup` required. This step will fail if there are existing NULL values in that column.
|
||||||
|
- Made the column `productGroupId` on table `Service` required. This step will fail if there are existing NULL values in that column.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- DropForeignKey
|
||||||
|
ALTER TABLE "Product" DROP CONSTRAINT "Product_productGroupId_fkey";
|
||||||
|
|
||||||
|
-- DropForeignKey
|
||||||
|
ALTER TABLE "Product" DROP CONSTRAINT "Product_registeredBranchId_fkey";
|
||||||
|
|
||||||
|
-- DropForeignKey
|
||||||
|
ALTER TABLE "ProductGroup" DROP CONSTRAINT "ProductGroup_registeredBranchId_fkey";
|
||||||
|
|
||||||
|
-- DropForeignKey
|
||||||
|
ALTER TABLE "Service" DROP CONSTRAINT "Service_productGroupId_fkey";
|
||||||
|
|
||||||
|
-- DropForeignKey
|
||||||
|
ALTER TABLE "Service" DROP CONSTRAINT "Service_registeredBranchId_fkey";
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Product" DROP COLUMN "registeredBranchId",
|
||||||
|
ADD COLUMN "shared" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ALTER COLUMN "productGroupId" SET NOT NULL;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "ProductGroup" ALTER COLUMN "registeredBranchId" SET NOT NULL;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Service" DROP COLUMN "registeredBranchId",
|
||||||
|
ADD COLUMN "shared" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
ALTER COLUMN "productGroupId" SET NOT NULL;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ProductGroup" ADD CONSTRAINT "ProductGroup_registeredBranchId_fkey" FOREIGN KEY ("registeredBranchId") REFERENCES "Branch"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Product" ADD CONSTRAINT "Product_productGroupId_fkey" FOREIGN KEY ("productGroupId") REFERENCES "ProductGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Service" ADD CONSTRAINT "Service_productGroupId_fkey" FOREIGN KEY ("productGroupId") REFERENCES "ProductGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
@ -238,8 +238,6 @@ model Branch {
|
||||||
contact BranchContact[]
|
contact BranchContact[]
|
||||||
user BranchUser[]
|
user BranchUser[]
|
||||||
|
|
||||||
productRegistration Product[]
|
|
||||||
serviceRegistration Service[]
|
|
||||||
customerRegistration Customer[]
|
customerRegistration Customer[]
|
||||||
productGroup ProductGroup[]
|
productGroup ProductGroup[]
|
||||||
}
|
}
|
||||||
|
|
@ -662,8 +660,8 @@ model ProductGroup {
|
||||||
status Status @default(CREATED)
|
status Status @default(CREATED)
|
||||||
statusOrder Int @default(0)
|
statusOrder Int @default(0)
|
||||||
|
|
||||||
registeredBranchId String?
|
registeredBranchId String
|
||||||
registeredBranch Branch? @relation(fields: [registeredBranchId], references: [id])
|
registeredBranch Branch @relation(fields: [registeredBranchId], references: [id])
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
createdBy User? @relation(name: "ProductGroupCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
|
createdBy User? @relation(name: "ProductGroupCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
|
||||||
|
|
@ -696,11 +694,8 @@ model Product {
|
||||||
|
|
||||||
remark String?
|
remark String?
|
||||||
|
|
||||||
productGroup ProductGroup? @relation(fields: [productGroupId], references: [id], onDelete: SetNull)
|
productGroup ProductGroup @relation(fields: [productGroupId], references: [id], onDelete: Cascade)
|
||||||
productGroupId String?
|
productGroupId String
|
||||||
|
|
||||||
registeredBranchId String?
|
|
||||||
registeredBranch Branch? @relation(fields: [registeredBranchId], references: [id])
|
|
||||||
|
|
||||||
workProduct WorkProduct[]
|
workProduct WorkProduct[]
|
||||||
quotationServiceWorkProduct QuotationServiceWorkProduct[]
|
quotationServiceWorkProduct QuotationServiceWorkProduct[]
|
||||||
|
|
@ -729,11 +724,8 @@ model Service {
|
||||||
work Work[]
|
work Work[]
|
||||||
quotationService QuotationService[]
|
quotationService QuotationService[]
|
||||||
|
|
||||||
productGroup ProductGroup? @relation(fields: [productGroupId], references: [id], onDelete: SetNull)
|
productGroup ProductGroup @relation(fields: [productGroupId], references: [id], onDelete: Cascade)
|
||||||
productGroupId String?
|
productGroupId String
|
||||||
|
|
||||||
registeredBranchId String?
|
|
||||||
registeredBranch Branch? @relation(fields: [registeredBranchId], references: [id])
|
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
createdBy User? @relation(name: "ServiceCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
|
createdBy User? @relation(name: "ServiceCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
|
||||||
|
|
|
||||||
|
|
@ -15,25 +15,34 @@ import {
|
||||||
import { Prisma, Status } from "@prisma/client";
|
import { Prisma, Status } from "@prisma/client";
|
||||||
|
|
||||||
import prisma from "../db";
|
import prisma from "../db";
|
||||||
import minio, { presignedGetObjectIfExist } from "../services/minio";
|
|
||||||
import { RequestWithUser } from "../interfaces/user";
|
import { RequestWithUser } from "../interfaces/user";
|
||||||
import HttpError from "../interfaces/http-error";
|
import HttpError from "../interfaces/http-error";
|
||||||
import HttpStatus from "../interfaces/http-status";
|
import HttpStatus from "../interfaces/http-status";
|
||||||
|
import {
|
||||||
|
branchRelationPermInclude,
|
||||||
|
createPermCheck,
|
||||||
|
createPermCondition,
|
||||||
|
} from "../services/permission";
|
||||||
|
import { isSystem } from "../utils/keycloak";
|
||||||
|
import { filterStatus } from "../services/prisma";
|
||||||
|
|
||||||
if (!process.env.MINIO_BUCKET) {
|
|
||||||
throw Error("Require MinIO bucket.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const MINIO_BUCKET = process.env.MINIO_BUCKET;
|
|
||||||
const MANAGE_ROLES = [
|
const MANAGE_ROLES = [
|
||||||
"system",
|
"system",
|
||||||
"head_of_admin",
|
"head_of_admin",
|
||||||
"admin",
|
"admin",
|
||||||
"branch_manager",
|
|
||||||
"head_of_account",
|
"head_of_account",
|
||||||
"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));
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissionCond = createPermCondition(globalAllow);
|
||||||
|
const permissionCheck = createPermCheck(globalAllow);
|
||||||
|
|
||||||
type ProductCreate = {
|
type ProductCreate = {
|
||||||
status?: Status;
|
status?: Status;
|
||||||
code:
|
code:
|
||||||
|
|
@ -61,8 +70,6 @@ type ProductCreate = {
|
||||||
expenseType?: string;
|
expenseType?: string;
|
||||||
productGroupId: string;
|
productGroupId: string;
|
||||||
remark?: string;
|
remark?: string;
|
||||||
|
|
||||||
registeredBranchId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type ProductUpdate = {
|
type ProductUpdate = {
|
||||||
|
|
@ -77,56 +84,43 @@ type ProductUpdate = {
|
||||||
vatIncluded?: boolean;
|
vatIncluded?: boolean;
|
||||||
expenseType?: string;
|
expenseType?: string;
|
||||||
productGroupId?: string;
|
productGroupId?: string;
|
||||||
|
|
||||||
registeredBranchId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function imageLocation(id: string) {
|
|
||||||
return `product/${id}/image`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function globalAllow(roles?: string[]) {
|
|
||||||
return ["system", "head_of_admin", "admin", "branch_manager", "head_of_account"].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 {
|
||||||
@Get("stats")
|
@Get("stats")
|
||||||
async getProductStats(@Query() productGroupId?: string) {
|
@Security("keycloak")
|
||||||
return await prisma.product.count({ where: { productGroupId } });
|
async getProductStats(@Request() req: RequestWithUser, @Query() productGroupId?: string) {
|
||||||
|
return await prisma.product.count({
|
||||||
|
where: {
|
||||||
|
productGroupId,
|
||||||
|
productGroup: isSystem(req.user)
|
||||||
|
? undefined
|
||||||
|
: { registeredBranch: { OR: permissionCond(req.user) } },
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Security("keycloak")
|
@Security("keycloak")
|
||||||
async getProduct(
|
async getProduct(
|
||||||
|
@Request() req: RequestWithUser,
|
||||||
@Query() status?: Status,
|
@Query() status?: Status,
|
||||||
@Query() productGroupId?: string,
|
@Query() productGroupId?: string,
|
||||||
@Query() query: string = "",
|
@Query() query: string = "",
|
||||||
@Query() page: number = 1,
|
@Query() page: number = 1,
|
||||||
@Query() pageSize: number = 30,
|
@Query() pageSize: number = 30,
|
||||||
@Query() registeredBranchId?: string,
|
|
||||||
) {
|
) {
|
||||||
const filterStatus = (val?: Status) => {
|
|
||||||
if (!val) return {};
|
|
||||||
|
|
||||||
return val !== Status.CREATED && val !== Status.ACTIVE
|
|
||||||
? { status: val }
|
|
||||||
: { OR: [{ status: Status.CREATED }, { status: Status.ACTIVE }] };
|
|
||||||
};
|
|
||||||
|
|
||||||
const where = {
|
const where = {
|
||||||
OR: [
|
OR: query ? [{ name: { contains: query } }, { detail: { contains: query } }] : undefined,
|
||||||
{ name: { contains: query }, productGroupId, ...filterStatus(status) },
|
AND: {
|
||||||
{ detail: { contains: query }, productGroupId, ...filterStatus(status) },
|
...filterStatus(status),
|
||||||
],
|
productGroupId,
|
||||||
AND: registeredBranchId
|
productGroup: isSystem(req.user)
|
||||||
? {
|
? undefined
|
||||||
OR: [{ registeredBranchId: registeredBranchId }, { registeredBranchId: null }],
|
: { registeredBranch: { OR: permissionCond(req.user) } },
|
||||||
}
|
},
|
||||||
: undefined,
|
|
||||||
} satisfies Prisma.ProductWhereInput;
|
} satisfies Prisma.ProductWhereInput;
|
||||||
|
|
||||||
const [result, total] = await prisma.$transaction([
|
const [result, total] = await prisma.$transaction([
|
||||||
|
|
@ -144,16 +138,7 @@ export class ProductController extends Controller {
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
result: await Promise.all(
|
result,
|
||||||
result.map(async (v) => ({
|
|
||||||
...v,
|
|
||||||
imageUrl: await presignedGetObjectIfExist(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(v.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
total,
|
total,
|
||||||
|
|
@ -175,47 +160,25 @@ export class ProductController extends Controller {
|
||||||
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
|
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.assign(record, {
|
return record;
|
||||||
imageUrl: await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(record.id), 60 * 60),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Get("{productId}/image")
|
|
||||||
async getProductImageById(@Request() req: RequestWithUser, @Path() productId: string) {
|
|
||||||
const url = await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(productId), 60 * 60);
|
|
||||||
|
|
||||||
if (!url) {
|
|
||||||
throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound");
|
|
||||||
}
|
|
||||||
|
|
||||||
return req.res?.redirect(url);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@Security("keycloak", MANAGE_ROLES)
|
@Security("keycloak", MANAGE_ROLES)
|
||||||
async createProduct(@Request() req: RequestWithUser, @Body() body: ProductCreate) {
|
async createProduct(@Request() req: RequestWithUser, @Body() body: ProductCreate) {
|
||||||
const [productGroup, branch] = await prisma.$transaction([
|
const [productGroup] = await prisma.$transaction([
|
||||||
prisma.productGroup.findFirst({
|
prisma.productGroup.findFirst({
|
||||||
include: {
|
include: {
|
||||||
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
createdBy: true,
|
createdBy: true,
|
||||||
updatedBy: true,
|
updatedBy: true,
|
||||||
},
|
},
|
||||||
where: { id: body.productGroupId },
|
where: { id: body.productGroupId },
|
||||||
}),
|
}),
|
||||||
prisma.branch.findFirst({
|
|
||||||
include: { user: { where: { userId: 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 (!productGroup) {
|
if (!productGroup) {
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
|
|
@ -224,22 +187,18 @@ export class ProductController extends Controller {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body.registeredBranchId && !branch) {
|
await permissionCheck(req.user, productGroup.registeredBranch);
|
||||||
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 branch = productGroup.registeredBranch;
|
||||||
|
const company = (branch.headOffice || branch).code;
|
||||||
const last = await tx.runningNo.upsert({
|
const last = await tx.runningNo.upsert({
|
||||||
where: {
|
where: {
|
||||||
key: `PRODUCT_${body.code.toLocaleUpperCase()}`,
|
key: `PRODUCT_${company}_${body.code.toLocaleUpperCase()}`,
|
||||||
},
|
},
|
||||||
create: {
|
create: {
|
||||||
key: `PRODUCT_${body.code.toLocaleUpperCase()}`,
|
key: `PRODUCT_${company}_${body.code.toLocaleUpperCase()}`,
|
||||||
value: 1,
|
value: 1,
|
||||||
},
|
},
|
||||||
update: { value: { increment: 1 } },
|
update: { value: { increment: 1 } },
|
||||||
|
|
@ -276,18 +235,7 @@ export class ProductController extends Controller {
|
||||||
|
|
||||||
this.setStatus(HttpStatus.CREATED);
|
this.setStatus(HttpStatus.CREATED);
|
||||||
|
|
||||||
return Object.assign(record, {
|
return record;
|
||||||
imageUrl: await presignedGetObjectIfExist(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
imageUploadUrl: await minio.presignedPutObject(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put("{productId}")
|
@Put("{productId}")
|
||||||
|
|
@ -297,12 +245,14 @@ export class ProductController extends Controller {
|
||||||
@Body() body: ProductUpdate,
|
@Body() body: ProductUpdate,
|
||||||
@Path() productId: string,
|
@Path() productId: string,
|
||||||
) {
|
) {
|
||||||
const [product, productGroup, branch] = await prisma.$transaction([
|
const [product, productGroup] = await prisma.$transaction([
|
||||||
prisma.product.findUnique({
|
prisma.product.findUnique({
|
||||||
include: {
|
include: {
|
||||||
registeredBranch: {
|
productGroup: {
|
||||||
where: {
|
include: {
|
||||||
user: { some: { userId: req.user.sub } },
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -310,27 +260,21 @@ export class ProductController extends Controller {
|
||||||
}),
|
}),
|
||||||
prisma.productGroup.findFirst({
|
prisma.productGroup.findFirst({
|
||||||
include: {
|
include: {
|
||||||
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
createdBy: true,
|
createdBy: true,
|
||||||
updatedBy: true,
|
updatedBy: true,
|
||||||
},
|
},
|
||||||
where: { id: body.productGroupId },
|
where: { id: body.productGroupId },
|
||||||
}),
|
}),
|
||||||
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!product) {
|
if (!product) {
|
||||||
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) && !product.registeredBranch) {
|
if (!!body.productGroupId && !productGroup) {
|
||||||
throw new HttpError(
|
|
||||||
HttpStatus.FORBIDDEN,
|
|
||||||
"You do not have permission to perform this action.",
|
|
||||||
"noPermission",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!productGroup) {
|
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
"Product Group cannot be found.",
|
"Product Group cannot be found.",
|
||||||
|
|
@ -338,12 +282,9 @@ export class ProductController extends Controller {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body.registeredBranchId && !branch) {
|
await permissionCheck(req.user, product.productGroup.registeredBranch);
|
||||||
throw new HttpError(
|
if (body.productGroupId && productGroup) {
|
||||||
HttpStatus.BAD_REQUEST,
|
await permissionCheck(req.user, productGroup.registeredBranch);
|
||||||
"Branch cannot be found.",
|
|
||||||
"relationBranchNotFound",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const record = await prisma.product.update({
|
const record = await prisma.product.update({
|
||||||
|
|
@ -355,25 +296,14 @@ export class ProductController extends Controller {
|
||||||
where: { id: productId },
|
where: { id: productId },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (productGroup.status === "CREATED") {
|
if (productGroup?.status === "CREATED") {
|
||||||
await prisma.productGroup.updateMany({
|
await prisma.productGroup.updateMany({
|
||||||
where: { id: body.productGroupId, status: Status.CREATED },
|
where: { id: body.productGroupId, status: Status.CREATED },
|
||||||
data: { status: Status.ACTIVE },
|
data: { status: Status.ACTIVE },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.assign(record, {
|
return record;
|
||||||
imageUrl: await presignedGetObjectIfExist(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
imageUploadUrl: await minio.presignedPutObject(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete("{productId}")
|
@Delete("{productId}")
|
||||||
|
|
@ -381,9 +311,11 @@ export class ProductController extends Controller {
|
||||||
async deleteProduct(@Request() req: RequestWithUser, @Path() productId: string) {
|
async deleteProduct(@Request() req: RequestWithUser, @Path() productId: string) {
|
||||||
const record = await prisma.product.findFirst({
|
const record = await prisma.product.findFirst({
|
||||||
include: {
|
include: {
|
||||||
registeredBranch: {
|
productGroup: {
|
||||||
where: {
|
include: {
|
||||||
user: { some: { userId: req.user.sub } },
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -395,14 +327,6 @@ export class ProductController extends Controller {
|
||||||
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");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,25 +15,34 @@ import {
|
||||||
import { Prisma, Status } from "@prisma/client";
|
import { Prisma, Status } from "@prisma/client";
|
||||||
|
|
||||||
import prisma from "../db";
|
import prisma from "../db";
|
||||||
import minio, { presignedGetObjectIfExist } from "../services/minio";
|
|
||||||
import { RequestWithUser } from "../interfaces/user";
|
import { RequestWithUser } from "../interfaces/user";
|
||||||
import HttpError from "../interfaces/http-error";
|
import HttpError from "../interfaces/http-error";
|
||||||
import HttpStatus from "../interfaces/http-status";
|
import HttpStatus from "../interfaces/http-status";
|
||||||
|
import { isSystem } from "../utils/keycloak";
|
||||||
|
import {
|
||||||
|
branchRelationPermInclude,
|
||||||
|
createPermCheck,
|
||||||
|
createPermCondition,
|
||||||
|
} from "../services/permission";
|
||||||
|
import { filterStatus } from "../services/prisma";
|
||||||
|
|
||||||
if (!process.env.MINIO_BUCKET) {
|
|
||||||
throw Error("Require MinIO bucket.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const MINIO_BUCKET = process.env.MINIO_BUCKET;
|
|
||||||
const MANAGE_ROLES = [
|
const MANAGE_ROLES = [
|
||||||
"system",
|
"system",
|
||||||
"head_of_admin",
|
"head_of_admin",
|
||||||
"admin",
|
"admin",
|
||||||
"branch_manager",
|
|
||||||
"head_of_account",
|
"head_of_account",
|
||||||
"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));
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissionCond = createPermCondition(globalAllow);
|
||||||
|
const permissionCheck = createPermCheck(globalAllow);
|
||||||
|
|
||||||
type ServiceCreate = {
|
type ServiceCreate = {
|
||||||
code: string;
|
code: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
|
@ -48,7 +57,6 @@ type ServiceCreate = {
|
||||||
attributes?: { [key: string]: any };
|
attributes?: { [key: string]: any };
|
||||||
}[];
|
}[];
|
||||||
productGroupId: string;
|
productGroupId: string;
|
||||||
registeredBranchId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type ServiceUpdate = {
|
type ServiceUpdate = {
|
||||||
|
|
@ -64,55 +72,52 @@ type ServiceUpdate = {
|
||||||
attributes?: { [key: string]: any };
|
attributes?: { [key: string]: any };
|
||||||
}[];
|
}[];
|
||||||
productGroupId?: string;
|
productGroupId?: string;
|
||||||
registeredBranchId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function imageLocation(id: string) {
|
|
||||||
return `service/${id}/service-image`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function globalAllow(roles?: string[]) {
|
|
||||||
return ["system", "head_of_admin", "admin", "head_of_account"].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 {
|
||||||
@Get("stats")
|
@Get("stats")
|
||||||
@Security("keycloak")
|
@Security("keycloak")
|
||||||
async getServiceStats(@Query() productGroupId?: string) {
|
async getServiceStats(@Request() req: RequestWithUser, @Query() productGroupId?: string) {
|
||||||
return await prisma.service.count({ where: { productGroupId } });
|
return await prisma.service.count({
|
||||||
|
where: {
|
||||||
|
productGroupId,
|
||||||
|
productGroup: isSystem(req.user)
|
||||||
|
? undefined
|
||||||
|
: {
|
||||||
|
registeredBranch: {
|
||||||
|
OR: permissionCond(req.user),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Security("keycloak")
|
@Security("keycloak")
|
||||||
async getService(
|
async getService(
|
||||||
|
@Request() req: RequestWithUser,
|
||||||
@Query() query: string = "",
|
@Query() query: string = "",
|
||||||
@Query() page: number = 1,
|
@Query() page: number = 1,
|
||||||
@Query() pageSize: number = 30,
|
@Query() pageSize: number = 30,
|
||||||
@Query() status?: Status,
|
@Query() status?: Status,
|
||||||
@Query() productGroupId?: string,
|
@Query() productGroupId?: string,
|
||||||
@Query() registeredBranchId?: string,
|
|
||||||
@Query() fullDetail?: boolean,
|
@Query() fullDetail?: boolean,
|
||||||
) {
|
) {
|
||||||
const filterStatus = (val?: Status) => {
|
|
||||||
if (!val) return {};
|
|
||||||
|
|
||||||
return val !== Status.CREATED && val !== Status.ACTIVE
|
|
||||||
? { status: val }
|
|
||||||
: { OR: [{ status: Status.CREATED }, { status: Status.ACTIVE }] };
|
|
||||||
};
|
|
||||||
|
|
||||||
const where = {
|
const where = {
|
||||||
OR: [
|
OR: query ? [{ name: { contains: query } }, { detail: { contains: query } }] : undefined,
|
||||||
{ name: { contains: query }, productGroupId, ...filterStatus(status) },
|
AND: {
|
||||||
{ detail: { contains: query }, productGroupId, ...filterStatus(status) },
|
...filterStatus(status),
|
||||||
],
|
productGroupId,
|
||||||
AND: registeredBranchId
|
productGroup: isSystem(req.user)
|
||||||
? {
|
? undefined
|
||||||
OR: [{ registeredBranchId: registeredBranchId }, { registeredBranchId: null }],
|
: {
|
||||||
}
|
registeredBranch: {
|
||||||
: undefined,
|
OR: permissionCond(req.user),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
} satisfies Prisma.ServiceWhereInput;
|
} satisfies Prisma.ServiceWhereInput;
|
||||||
|
|
||||||
const [result, total] = await prisma.$transaction([
|
const [result, total] = await prisma.$transaction([
|
||||||
|
|
@ -141,16 +146,7 @@ export class ServiceController extends Controller {
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
result: await Promise.all(
|
result,
|
||||||
result.map(async (v) => ({
|
|
||||||
...v,
|
|
||||||
imageUrl: await presignedGetObjectIfExist(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(v.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
total,
|
total,
|
||||||
|
|
@ -181,9 +177,7 @@ export class ServiceController extends Controller {
|
||||||
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
|
throw new HttpError(HttpStatus.NOT_FOUND, "Service cannot be found.", "serviceNotFound");
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.assign(record, {
|
return record;
|
||||||
imageUrl: await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(record.id), 60 * 60),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("{serviceId}/work")
|
@Get("{serviceId}/work")
|
||||||
|
|
@ -218,44 +212,24 @@ export class ServiceController extends Controller {
|
||||||
return { result, page, pageSize, total };
|
return { result, page, pageSize, total };
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("{serviceId}/image")
|
|
||||||
async getServiceImageById(@Request() req: RequestWithUser, @Path() serviceId: string) {
|
|
||||||
const url = await presignedGetObjectIfExist(MINIO_BUCKET, imageLocation(serviceId), 60 * 60);
|
|
||||||
|
|
||||||
if (!url) {
|
|
||||||
throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound");
|
|
||||||
}
|
|
||||||
|
|
||||||
return req.res?.redirect(url);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@Security("keycloak", MANAGE_ROLES)
|
@Security("keycloak", MANAGE_ROLES)
|
||||||
async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) {
|
async createService(@Request() req: RequestWithUser, @Body() body: ServiceCreate) {
|
||||||
const { work, productGroupId, ...payload } = body;
|
const { work, productGroupId, ...payload } = body;
|
||||||
|
|
||||||
const [productGroup, branch] = await prisma.$transaction([
|
const [productGroup] = await prisma.$transaction([
|
||||||
prisma.productGroup.findFirst({
|
prisma.productGroup.findFirst({
|
||||||
include: {
|
include: {
|
||||||
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
createdBy: true,
|
createdBy: true,
|
||||||
updatedBy: true,
|
updatedBy: true,
|
||||||
},
|
},
|
||||||
where: { id: body.productGroupId },
|
where: { id: body.productGroupId },
|
||||||
}),
|
}),
|
||||||
prisma.branch.findFirst({
|
|
||||||
include: { user: { where: { userId: 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 (!productGroup) {
|
if (!productGroup) {
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
|
|
@ -264,13 +238,7 @@ export class ServiceController extends Controller {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body.registeredBranchId && !branch) {
|
await permissionCheck(req.user, productGroup.registeredBranch);
|
||||||
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) => {
|
||||||
|
|
@ -325,18 +293,7 @@ export class ServiceController extends Controller {
|
||||||
);
|
);
|
||||||
this.setStatus(HttpStatus.CREATED);
|
this.setStatus(HttpStatus.CREATED);
|
||||||
|
|
||||||
return Object.assign(record, {
|
return record;
|
||||||
imageUrl: await presignedGetObjectIfExist(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
imageUploadUrl: await minio.presignedPutObject(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Put("{serviceId}")
|
@Put("{serviceId}")
|
||||||
|
|
@ -351,12 +308,14 @@ export class ServiceController extends Controller {
|
||||||
}
|
}
|
||||||
const { work, productGroupId, ...payload } = body;
|
const { work, productGroupId, ...payload } = body;
|
||||||
|
|
||||||
const [service, productGroup, branch] = await prisma.$transaction([
|
const [service, productGroup] = await prisma.$transaction([
|
||||||
prisma.service.findUnique({
|
prisma.service.findUnique({
|
||||||
include: {
|
include: {
|
||||||
registeredBranch: {
|
productGroup: {
|
||||||
where: {
|
include: {
|
||||||
user: { some: { userId: req.user.sub } },
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -364,27 +323,21 @@ export class ServiceController extends Controller {
|
||||||
}),
|
}),
|
||||||
prisma.productGroup.findFirst({
|
prisma.productGroup.findFirst({
|
||||||
include: {
|
include: {
|
||||||
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
createdBy: true,
|
createdBy: true,
|
||||||
updatedBy: true,
|
updatedBy: true,
|
||||||
},
|
},
|
||||||
where: { id: body.productGroupId },
|
where: { id: body.productGroupId },
|
||||||
}),
|
}),
|
||||||
prisma.branch.findFirst({ where: { id: body.registeredBranchId } }),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!service) {
|
if (!service) {
|
||||||
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) && !service.registeredBranch) {
|
if (!!body.productGroupId && !productGroup) {
|
||||||
throw new HttpError(
|
|
||||||
HttpStatus.FORBIDDEN,
|
|
||||||
"You do not have permission to perform this action.",
|
|
||||||
"noPermission",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!productGroup) {
|
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
"Product Type cannot be found.",
|
"Product Type cannot be found.",
|
||||||
|
|
@ -392,12 +345,9 @@ export class ServiceController extends Controller {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body.registeredBranchId && !branch) {
|
await permissionCheck(req.user, service.productGroup.registeredBranch);
|
||||||
throw new HttpError(
|
if (!!body.productGroupId && productGroup) {
|
||||||
HttpStatus.BAD_REQUEST,
|
await permissionCheck(req.user, productGroup.registeredBranch);
|
||||||
"Branch cannot be found.",
|
|
||||||
"relationBranchNotFound",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const record = await prisma.$transaction(async (tx) => {
|
const record = await prisma.$transaction(async (tx) => {
|
||||||
|
|
@ -429,18 +379,7 @@ export class ServiceController extends Controller {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return Object.assign(record, {
|
return record;
|
||||||
imageUrl: await presignedGetObjectIfExist(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
imageUploadUrl: await minio.presignedPutObject(
|
|
||||||
MINIO_BUCKET,
|
|
||||||
imageLocation(record.id),
|
|
||||||
12 * 60 * 60,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete("{serviceId}")
|
@Delete("{serviceId}")
|
||||||
|
|
@ -448,9 +387,11 @@ export class ServiceController extends Controller {
|
||||||
async deleteService(@Request() req: RequestWithUser, @Path() serviceId: string) {
|
async deleteService(@Request() req: RequestWithUser, @Path() serviceId: string) {
|
||||||
const record = await prisma.service.findFirst({
|
const record = await prisma.service.findFirst({
|
||||||
include: {
|
include: {
|
||||||
registeredBranch: {
|
productGroup: {
|
||||||
where: {
|
include: {
|
||||||
user: { some: { userId: req.user.sub } },
|
registeredBranch: {
|
||||||
|
include: branchRelationPermInclude(req.user),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -461,13 +402,7 @@ export class ServiceController extends Controller {
|
||||||
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) {
|
await permissionCheck(req.user, record.productGroup.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");
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue