From e76292fe382701f7fbe26516290312522a3a95c4 Mon Sep 17 00:00:00 2001 From: Methapon Metanipat Date: Mon, 28 Oct 2024 10:51:51 +0700 Subject: [PATCH] feat: add relation for agent --- .../migration.sql | 15 ++++++ prisma/schema.prisma | 5 +- .../03-customer-branch-controller.ts | 49 +++++++++++++++---- src/controllers/03-customer-controller.ts | 4 +- 4 files changed, 62 insertions(+), 11 deletions(-) create mode 100644 prisma/migrations/20241028033825_update_structure/migration.sql diff --git a/prisma/migrations/20241028033825_update_structure/migration.sql b/prisma/migrations/20241028033825_update_structure/migration.sql new file mode 100644 index 0000000..7aff7a3 --- /dev/null +++ b/prisma/migrations/20241028033825_update_structure/migration.sql @@ -0,0 +1,15 @@ +/* + Warnings: + + - You are about to drop the column `agent` on the `CustomerBranch` table. All the data in the column will be lost. + +*/ +-- AlterTable +ALTER TABLE "CustomerBranch" DROP COLUMN "agent", +ADD COLUMN "agentUserId" TEXT; + +-- AlterTable +ALTER TABLE "ProductGroup" ADD COLUMN "shared" BOOLEAN NOT NULL DEFAULT false; + +-- AddForeignKey +ALTER TABLE "CustomerBranch" ADD CONSTRAINT "CustomerBranch_agentUserId_fkey" FOREIGN KEY ("agentUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index de0e16c..58f534e 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -389,6 +389,7 @@ model User { userMenuComponentPermission UserMenuComponentPermission[] workflowTemplateStepUser WorkflowTemplateStepUser[] requestWork RequestWork[] + customerBranch CustomerBranch[] userCreated User[] @relation("UserCreatedByUser") userUpdated User[] @relation("UserUpdatedByUser") @@ -513,7 +514,8 @@ model CustomerBranch { contactTel String officeTel String contactName String - agent String + agentUserId String? + agentUser User? @relation(fields: [agentUserId], references: [id], onDelete: SetNull) // NOTE: Business businessType String @@ -952,6 +954,7 @@ model ProductGroup { name String detail String remark String + shared Boolean @default(false) status Status @default(CREATED) statusOrder Int @default(0) diff --git a/src/controllers/03-customer-branch-controller.ts b/src/controllers/03-customer-branch-controller.ts index b728785..b30b744 100644 --- a/src/controllers/03-customer-branch-controller.ts +++ b/src/controllers/03-customer-branch-controller.ts @@ -58,6 +58,7 @@ function globalAllow(user: RequestWithUser["user"]) { const permissionCondCompany = createPermCondition((_) => true); const permissionCond = createPermCondition(globalAllow); +const permissionCheckCompany = createPermCheck((_) => true); const permissionCheck = createPermCheck(globalAllow); export type CustomerBranchCreate = { @@ -103,7 +104,7 @@ export type CustomerBranchCreate = { contactTel: string; officeTel: string; contactName: string; - agent: string; + agentUserId?: string; businessType: string; jobPosition: string; @@ -161,7 +162,7 @@ export type CustomerBranchUpdate = { contactTel?: string; officeTel?: string; contactName?: string; - agent?: string; + agentUserId?: string; businessType?: string; jobPosition?: string; @@ -322,7 +323,7 @@ export class CustomerBranchController extends Controller { @Post() @Security("keycloak", MANAGE_ROLES) async create(@Request() req: RequestWithUser, @Body() body: CustomerBranchCreate) { - const [province, district, subDistrict, customer] = await prisma.$transaction([ + const [province, district, subDistrict, customer, agent] = await prisma.$transaction([ prisma.province.findFirst({ where: { id: body.provinceId || undefined } }), prisma.district.findFirst({ where: { id: body.districtId || undefined } }), prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }), @@ -338,17 +339,30 @@ export class CustomerBranchController extends Controller { }, }, }), + prisma.user.findFirst({ + where: { id: body.customerId || undefined }, + include: { + branch: { + include: { branch: { include: branchRelationPermInclude(req.user) } }, + }, + }, + }), ]); if (body.provinceId && !province) throw relationError("Province"); if (body.districtId && !district) throw relationError("District"); if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict"); + if (body.agentUserId && !agent) throw relationError("User"); if (!customer) throw relationError("Customer"); + if (agent) { + await Promise.all(agent.branch.map(({ branch }) => permissionCheckCompany(req.user, branch))); + } + await permissionCheck(req.user, customer.registeredBranch); let company = await permissionCheck(req.user, customer.registeredBranch).then( (v) => (v.headOffice || v).code, ); - const { provinceId, districtId, subDistrictId, customerId, ...rest } = body; + const { provinceId, districtId, subDistrictId, customerId, agentUserId, ...rest } = body; const record = await prisma.$transaction( async (tx) => { @@ -394,12 +408,14 @@ export class CustomerBranchController extends Controller { }, data: { ...rest, + code: `${runningKey.replace(`CUSTOMER_BRANCH_${company}_`, "")}-${`${last.value - 1}`.padStart(2, "0")}`, codeCustomer: runningKey.replace(`CUSTOMER_BRANCH_${company}_`, ""), customer: { connect: { id: customerId } }, - province: { connect: provinceId ? { id: provinceId } : undefined }, - district: { connect: districtId ? { id: districtId } : undefined }, - subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined }, + agentUser: connectOrNot(agentUserId), + province: connectOrNot(provinceId), + district: connectOrNot(districtId), + subDistrict: connectOrNot(subDistrictId), createdBy: { connect: { id: req.user.sub } }, updatedBy: { connect: { id: req.user.sub } }, }, @@ -440,7 +456,7 @@ export class CustomerBranchController extends Controller { if (!body.customerId) body.customerId = branch.customerId; if (body.provinceId || body.districtId || body.subDistrictId || body.customerId) { - const [province, district, subDistrict, customer] = await prisma.$transaction([ + const [province, district, subDistrict, customer, agent] = await prisma.$transaction([ prisma.province.findFirst({ where: { id: body.provinceId || undefined } }), prisma.district.findFirst({ where: { id: body.districtId || undefined } }), prisma.subDistrict.findFirst({ where: { id: body.subDistrictId || undefined } }), @@ -452,15 +468,29 @@ export class CustomerBranchController extends Controller { }, }, }), + prisma.user.findFirst({ + where: { id: body.customerId || undefined }, + include: { + branch: { + include: { branch: { include: branchRelationPermInclude(req.user) } }, + }, + }, + }), ]); if (body.provinceId && !province) throw relationError("Province"); if (body.districtId && !district) throw relationError("District"); if (body.subDistrictId && !subDistrict) throw relationError("SubDistrict"); + if (body.agentUserId && !agent) throw relationError("User"); if (!customer) throw relationError("Customer"); + if (agent) { + await Promise.all( + agent.branch.map(({ branch }) => permissionCheckCompany(req.user, branch)), + ); + } await permissionCheck(req.user, customer.registeredBranch); } - const { provinceId, districtId, subDistrictId, customerId, ...rest } = body; + const { provinceId, districtId, subDistrictId, customerId, agentUserId, ...rest } = body; return await prisma.customerBranch.update({ where: { id: branchId }, @@ -474,6 +504,7 @@ export class CustomerBranchController extends Controller { data: { ...rest, statusOrder: +(rest.status === "INACTIVE"), + agentUser: connectOrNot(agentUserId), customer: connectOrNot(customerId), province: connectOrDisconnect(provinceId), district: connectOrDisconnect(districtId), diff --git a/src/controllers/03-customer-controller.ts b/src/controllers/03-customer-controller.ts index 3bfebcf..0013421 100644 --- a/src/controllers/03-customer-controller.ts +++ b/src/controllers/03-customer-controller.ts @@ -103,7 +103,7 @@ export type CustomerCreate = { contactTel: string; officeTel: string; contactName: string; - agent: string; + agentUserId?: string; businessType: string; jobPosition: string; @@ -316,6 +316,8 @@ export class CustomerController extends Controller { ...v, code: `${runningKey.replace(`CUSTOMER_BRANCH_${company}_`, "")}-${`${last.value - branch.length + i}`.padStart(2, "0")}`, codeCustomer: runningKey.replace(`CUSTOMER_BRANCH_${company}_`, ""), + agentUser: connectOrNot(v.agentUserId), + agentUserId: undefined, province: connectOrNot(v.provinceId), provinceId: undefined, district: connectOrNot(v.districtId),