Files
test-assignment/apps/api/src/access.ts
T

90 lines
3.4 KiB
TypeScript

import type { User } from '@merchantflow/contracts';
import type { Prisma } from '@merchantflow/database';
import type { Capabilities } from '@merchantflow/contracts';
import { workflowActions, validApproval, canReopenKyb, type Evidence } from './workflow-policy.js';
import { activationCodes, isIntegrationCheck, reviewPolicyVersion } from '@merchantflow/contracts';
import { ApiError } from './shared.js';
export function merchantScope(user: User): Prisma.MerchantWhereInput {
switch (user.role) {
case 'HEAD_OF_SALES':
return {};
case 'COMPLIANCE_OFFICER':
return {};
case 'ACCOUNT_MANAGER':
return { ownerId: user.id };
default:
return { id: '__no_access__' };
}
}
export function taskScope(user: User): Prisma.TaskWhereInput {
return {
merchant: merchantScope(user),
...(user.role === 'COMPLIANCE_OFFICER' ? { assigneeId: user.id, kind: 'COMPLIANCE' } : {}),
};
}
export function requireSales(user: User) {
if (!['HEAD_OF_SALES', 'ACCOUNT_MANAGER'].includes(user.role))
throw new ApiError('FORBIDDEN', 403);
}
export function capabilities(user: User, merchant: Evidence): Capabilities {
const sales =
user.role === 'HEAD_OF_SALES' ||
(user.role === 'ACCOUNT_MANAGER' && merchant.ownerId === user.id);
const locked =
merchant.reviews.some((review) => review.decision === 'PENDING') ||
(merchant.reviews[0]?.decision === 'APPROVED' &&
(merchant.reviews[0].policyVersion >= reviewPolicyVersion || merchant.status !== 'KYB'));
const actions = workflowActions(user, merchant);
const terminal = ['LIVE', 'REJECTED'].includes(merchant.status);
const reopen = canReopenKyb(merchant);
return {
editCommercial: sales,
editIdentity: sales && !locked,
assign: user.role === 'HEAD_OF_SALES',
collectChecklist: sales && merchant.status === 'KYB' && !locked,
review: user.role === 'COMPLIANCE_OFFICER' && merchant.status === 'COMPLIANCE_REVIEW',
reopenKyb: sales && reopen,
activationCodes:
sales && validApproval(merchant)
? activationCodes.filter((code) =>
isIntegrationCheck(code)
? merchant.status === 'INTEGRATION'
: merchant.status === 'TESTING',
)
: [],
handoff: {
owner: terminal
? 'NONE'
: merchant.status === 'COMPLIANCE_REVIEW'
? 'COMPLIANCE_OFFICER'
: !merchant.ownerId
? 'HEAD_OF_SALES'
: 'ACCOUNT_MANAGER',
ownerId: terminal || merchant.status === 'COMPLIANCE_REVIEW' ? null : merchant.ownerId,
action: terminal
? 'COMPLETE'
: merchant.status === 'COMPLIANCE_REVIEW'
? 'REVIEW'
: !merchant.ownerId
? 'ASSIGN'
: reopen
? 'REOPEN_KYB'
: merchant.status === 'KYB'
? 'COLLECT'
: merchant.status === 'INTEGRATION'
? 'INTEGRATE'
: merchant.status === 'TESTING'
? 'TEST'
: 'COMMERCIAL',
},
activityKinds:
user.role === 'COMPLIANCE_OFFICER'
? (['KYB_NOTE'] as const)
: (['NOTE', 'CALL', 'EMAIL', 'MEETING'] as const),
manageTaskKind: user.role === 'COMPLIANCE_OFFICER' ? 'COMPLIANCE' : 'COMMERCIAL',
actions,
nextStage:
actions.find((action) => action.kind === 'ADVANCE' && action.enabled)?.toStatus ?? null,
};
}