38 lines
2.6 KiB
TypeScript
38 lines
2.6 KiB
TypeScript
import type { Prisma } from '@prisma/client'
|
|
import { normalizeOrganizationPath, resolveEmployeeOrganizationPaths, type EmployeeOrganizationPathSource } from './organization-material-permissions'
|
|
|
|
export type SalaryOrganizationUnit = { sourceDeptId: number; name: string; path: string }
|
|
type Profile = Omit<EmployeeOrganizationPathSource, 'departmentMemberships'> & {
|
|
departmentMemberships?: Array<{ sourceDeptId?: string | number | null; departmentPath?: string | null; isPrimary?: boolean }>
|
|
}
|
|
|
|
// Use the same current department identities and paths as the organization tree.
|
|
// A primary membership wins; ambiguous or retired departments require correction at the source.
|
|
export function resolveSalaryOrganizationUnit(profile: Profile, units: SalaryOrganizationUnit[]): SalaryOrganizationUnit | null {
|
|
const byId = new Map(units.map(unit => [String(unit.sourceDeptId), unit]))
|
|
const paths = resolveEmployeeOrganizationPaths(profile, new Map(units.map(unit => [String(unit.sourceDeptId), unit.path])))
|
|
const primary = (profile.departmentMemberships ?? []).filter(item => item.isPrimary)
|
|
const primaryPaths = Array.from(new Set(primary.map(item => byId.get(String(item.sourceDeptId))?.path).filter((path): path is string => !!path)))
|
|
if (primary.length && (primaryPaths.length !== 1 || primary.some(item => !byId.has(String(item.sourceDeptId))))) return null
|
|
const main = normalizeOrganizationPath(profile.departmentPath)
|
|
const selected = primaryPaths[0] ?? (paths.includes(main) ? main : paths.length === 1 ? paths[0] : null)
|
|
const matches = units.filter(unit => unit.path === selected)
|
|
return matches.length === 1 ? matches[0] : null
|
|
}
|
|
|
|
export function resolveSalaryOrganizationDepartment(profile: Profile, units: SalaryOrganizationUnit[]): string | null {
|
|
return resolveSalaryOrganizationUnit(profile, units)?.name ?? null
|
|
}
|
|
|
|
export async function readSalaryOrganizationDepartments(db: Prisma.TransactionClient, employeeProfileIds: string[]) {
|
|
if (!employeeProfileIds.length) return new Map<string, string | null>()
|
|
const [units, profiles] = await Promise.all([
|
|
db.organizationUnit.findMany({ where: { isActive: true }, select: { sourceDeptId: true, name: true, path: true } }),
|
|
db.performanceSurveyEmployeeProfile.findMany({ where: { id: { in: Array.from(new Set(employeeProfileIds)) } }, select: {
|
|
id: true, departmentPath: true, sourcePayload: true,
|
|
departmentMemberships: { select: { sourceDeptId: true, departmentPath: true, isPrimary: true } },
|
|
} }),
|
|
])
|
|
return new Map(profiles.map(profile => [profile.id, resolveSalaryOrganizationDepartment(profile, units)]))
|
|
}
|