import type { PrismaClient } from '@prisma/client' import type { PermissionPackMap } from '../lib/organization-material-permissions' const ACTIONS = ['canView', 'canDownload', 'canDownloadSource', 'canShare'] as const const PAGE_SIZE = 100 export async function auditPermissionPackParity(client: PrismaClient) { const [ { getLegacyRosterPermissionSources, getPermissionPackViewableTypes, loadLegacyDepartmentPermissionPacks, mergeRosterPermissionPack, pickPermissionFlags, }, { getEmployeeOrganizationPathsByUserId }, { expandCompatibleMaterialTypes }, { loadDepartmentGroupPacks }, { loadUserInheritPack }, ] = await Promise.all([ import('../lib/department-permission'), import('../lib/employee-directory'), import('../lib/material-query'), import('../lib/permission-groups'), import('../lib/user-permission-inherit'), ]) function comparePacks(current: PermissionPackMap | null, organizationOnly: PermissionPackMap | null) { const materialTypes = expandCompatibleMaterialTypes([ ...Object.keys(current ?? {}), ...Object.keys(organizationOnly ?? {}), ]).sort() const currentList = new Set(expandCompatibleMaterialTypes(getPermissionPackViewableTypes(current))) const organizationList = new Set(expandCompatibleMaterialTypes(getPermissionPackViewableTypes(organizationOnly))) return materialTypes.flatMap((materialType) => { const currentFlags = pickPermissionFlags(current, materialType) const organizationFlags = pickPermissionFlags(organizationOnly, materialType) const checks = ACTIONS.map((action) => ({ action, entryPoint: 'permission' as const, current: currentFlags?.[action] ?? false, organizationOnly: organizationFlags?.[action] ?? false, })) return [ ...checks, { action: 'canView' as const, entryPoint: 'listing' as const, current: currentList.has(materialType), organizationOnly: organizationList.has(materialType), }, ].filter((check) => check.current !== check.organizationOnly) .map((check) => ({ materialType, ...check })) }) } type UserDifference = { userId: string username: string rosterPaths: string[] legacySources: ReturnType changes: ReturnType } return client.$transaction(async (tx) => { await tx.$executeRaw`SET TRANSACTION READ ONLY` const legacyPacks = await loadLegacyDepartmentPermissionPacks(tx) const differences: UserDifference[] = [] let activeUsers = 0 let superAdmins = 0 let usersWithoutRosterPath = 0 let afterId: string | undefined for (;;) { const users = await tx.user.findMany({ where: { OR: [{ isActive: true }, { status: 'active' }], id: { gt: afterId }, }, orderBy: { id: 'asc' }, take: PAGE_SIZE, select: { id: true, username: true, isSuperAdmin: true }, }) if (users.length === 0) break activeUsers += users.length superAdmins += users.filter((user) => user.isSuperAdmin).length afterId = users[users.length - 1].id const rosterUsers = await Promise.all(users.filter((user) => !user.isSuperAdmin).map(async (user) => ({ ...user, paths: await getEmployeeOrganizationPathsByUserId(user.id, {}, tx), }))) const groupPacks = await loadDepartmentGroupPacks(rosterUsers.flatMap((user) => user.paths), tx) for (const { id, username, paths } of rosterUsers) { if (paths.length === 0) { usersWithoutRosterPath += 1 continue } const legacySources = getLegacyRosterPermissionSources(paths, groupPacks, legacyPacks) if (legacySources.length === 0) continue const inheritPack = await loadUserInheritPack(id, tx) const current = mergeRosterPermissionPack(paths, groupPacks, inheritPack, legacyPacks) const organizationOnly = mergeRosterPermissionPack(paths, groupPacks, inheritPack) const changes = comparePacks(current, organizationOnly) if (changes.length > 0) differences.push({ userId: id, username, rosterPaths: paths, legacySources, changes }) } } return { activeUsers, superAdmins, usersWithoutRosterPath, differenceUsers: differences.length, differences } }, { isolationLevel: 'RepeatableRead', timeout: 300_000 }) } async function main() { if (process.argv.includes('--help')) { console.log('用法:设置 DATABASE_URL 后运行 npx tsx scripts/audit-permission-pack-parity.ts') return } if (!process.env.DATABASE_URL) throw new Error('请显式设置待对账数据库的 DATABASE_URL') const { PrismaClient } = await import('@prisma/client') const client = new PrismaClient() try { const report = await auditPermissionPackParity(client) const result = report.activeUsers === 0 ? '未找到活跃账号' : report.differenceUsers ? '存在权限差异' : '全员权限零差异' console.log(JSON.stringify({ result, ...report }, null, 2)) process.exitCode = report.activeUsers === 0 ? 2 : report.differenceUsers ? 1 : 0 } finally { await client.$disconnect() } } if (require.main === module) { main().catch((error: unknown) => { console.error('权限对账失败:', error instanceof Error ? error.message : error) process.exitCode = 2 }) }