diff --git a/src/services/permission.ts b/src/services/permission.ts index 8607aa3..0262a62 100644 --- a/src/services/permission.ts +++ b/src/services/permission.ts @@ -1,4 +1,4 @@ -import { Prisma } from "@prisma/client"; +import { Prisma, Status } from "@prisma/client"; import prisma from "../db"; import HttpError from "../interfaces/http-error"; import HttpStatus from "../interfaces/http-status"; @@ -18,30 +18,46 @@ export function branchRelationPermInclude(user: RequestWithUser["user"]) { }; } -export function createPermCondition(globalAllow: (user: RequestWithUser["user"]) => boolean) { - return ( - user: RequestWithUser["user"], - opts?: { alwaysIncludeHead?: boolean; includeInActive?: boolean }, - ) => +export function createPermCondition( + globalAllow: (user: RequestWithUser["user"]) => boolean, +): ( + user: RequestWithUser["user"], + opts?: { alwaysIncludeHead?: boolean; activeOnly?: boolean }, +) => Prisma.BranchWhereInput["OR"] { + return (user, opts) => isSystem(user) ? undefined : [ { + status: opts?.activeOnly ? { not: Status.INACTIVE } : undefined, user: { some: { userId: user.sub } }, }, { + status: opts?.activeOnly ? { not: Status.INACTIVE } : undefined, branch: opts?.alwaysIncludeHead || globalAllow(user) - ? { some: { user: { some: { userId: user.sub } } } } + ? { + some: { user: { some: { userId: user.sub } } }, + } : undefined, }, { headOffice: globalAllow(user) - ? { branch: { some: { user: { some: { userId: user.sub } } } } } + ? { + status: opts?.activeOnly ? { not: Status.INACTIVE } : undefined, + branch: { + some: { user: { some: { userId: user.sub } } }, + }, + } : undefined, }, { - headOffice: globalAllow(user) ? { user: { some: { userId: user.sub } } } : undefined, + headOffice: globalAllow(user) + ? { + status: opts?.activeOnly ? { not: Status.INACTIVE } : undefined, + user: { some: { userId: user.sub } }, + } + : undefined, }, ]; }