feat: 用户管理改为组织架构展示;花名册自动激活/角色判定;修复花名册同名串档(有花名=正式员工)
This commit is contained in:
parent
1a2b9b0c52
commit
f63e04ba02
@ -7,28 +7,11 @@ import Header from '@/components/Header'
|
||||
import DepartmentPermissionsTab from '@/components/DepartmentPermissionsTab'
|
||||
import SuperAdminsTab from '@/components/SuperAdminsTab'
|
||||
import MaterialManagement from '@/components/admin/MaterialManagement'
|
||||
import UserManagement from '@/components/admin/UserManagement'
|
||||
import CategoryManagement from '@/components/admin/CategoryManagement'
|
||||
import DepartmentManagement from '@/components/admin/DepartmentManagement'
|
||||
import DataStatisticsTab from '@/components/admin/DataStatisticsTab'
|
||||
import PublicTrafficTab from '@/components/admin/PublicTrafficTab'
|
||||
|
||||
// 类型定义
|
||||
interface User {
|
||||
id: string
|
||||
email: string
|
||||
username: string
|
||||
department: string
|
||||
role: string
|
||||
isActive: boolean
|
||||
canDownload: boolean
|
||||
managedDepartment?: string
|
||||
createdAt: string
|
||||
_count: {
|
||||
materials: number
|
||||
}
|
||||
}
|
||||
|
||||
interface Material {
|
||||
id: string
|
||||
previewUrl: string
|
||||
@ -113,12 +96,11 @@ export default function AdminPage() {
|
||||
const canSelectDepartmentInStats = canManageSystemTabs
|
||||
|
||||
// Tab状态
|
||||
const [activeTab, setActiveTab] = useState<'materials' | 'users' | 'categories' | 'departments' | 'dataStats' | 'permissions' | 'superAdmins' | 'publicTraffic'>('dataStats')
|
||||
const [activeTab, setActiveTab] = useState<'materials' | 'categories' | 'dataStats' | 'permissions' | 'superAdmins' | 'publicTraffic'>('dataStats')
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
// 数据状态
|
||||
const [materials, setMaterials] = useState<Material[]>([])
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [categories, setCategories] = useState<Category[]>([])
|
||||
const [scenes, setScenes] = useState<Scene[]>([])
|
||||
const [platforms, setPlatforms] = useState<Platform[]>([])
|
||||
@ -138,11 +120,6 @@ export default function AdminPage() {
|
||||
const [isLoadingMoreMaterials, setIsLoadingMoreMaterials] = useState(false)
|
||||
const [totalMaterialsCount, setTotalMaterialsCount] = useState(0) // 素材总数(用于显示)
|
||||
const materialsPageSize = 50 // 增大分页大小,减少请求次数
|
||||
|
||||
// 用户管理相关状态
|
||||
const [userSearchTerm, setUserSearchTerm] = useState('')
|
||||
const [collapsedDepartments, setCollapsedDepartments] = useState<Set<string>>(new Set())
|
||||
const [collapsedAdmins, setCollapsedAdmins] = useState<Set<string>>(new Set())
|
||||
|
||||
// Toast自动隐藏
|
||||
useEffect(() => {
|
||||
@ -164,8 +141,6 @@ export default function AdminPage() {
|
||||
}
|
||||
const data = await response.json()
|
||||
setDepartments(data)
|
||||
// 默认所有部门收起
|
||||
setCollapsedDepartments(new Set(data.map((d: Department) => d.id)))
|
||||
}, [])
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
@ -193,12 +168,6 @@ export default function AdminPage() {
|
||||
if (data.totalCount !== undefined) {
|
||||
setTotalMaterialsCount(data.totalCount)
|
||||
}
|
||||
} else if (activeTab === 'users') {
|
||||
const response = await fetch('/api/admin/users')
|
||||
if (!response.ok) throw new Error('用户数据加载失败')
|
||||
const data = await response.json()
|
||||
setUsers(data)
|
||||
await fetchDepartments()
|
||||
} else if (activeTab === 'categories') {
|
||||
const [categoriesRes, scenesRes, platformsRes, productCategoriesRes] = await Promise.all([
|
||||
fetch('/api/categories'),
|
||||
@ -213,7 +182,7 @@ export default function AdminPage() {
|
||||
setScenes(await scenesRes.json())
|
||||
setPlatforms(await platformsRes.json())
|
||||
setProductCategories(await productCategoriesRes.json())
|
||||
} else if (activeTab === 'departments' || activeTab === 'permissions') {
|
||||
} else if (activeTab === 'permissions') {
|
||||
await fetchDepartments()
|
||||
}
|
||||
} catch (error) {
|
||||
@ -296,32 +265,6 @@ export default function AdminPage() {
|
||||
}
|
||||
}, [isLoadingMoreMaterials, hasMoreMaterials, currentMaterialsPage, showRecycleBin, materialSearchTerm])
|
||||
|
||||
// 切换部门折叠状态
|
||||
const toggleDepartmentCollapse = useCallback((departmentName: string) => {
|
||||
setCollapsedDepartments(prev => {
|
||||
const newSet = new Set(prev)
|
||||
if (newSet.has(departmentName)) {
|
||||
newSet.delete(departmentName)
|
||||
} else {
|
||||
newSet.add(departmentName)
|
||||
}
|
||||
return newSet
|
||||
})
|
||||
}, [])
|
||||
|
||||
// 切换管理员折叠状态
|
||||
const toggleAdminCollapse = useCallback((adminId: string) => {
|
||||
setCollapsedAdmins(prev => {
|
||||
const newSet = new Set(prev)
|
||||
if (newSet.has(adminId)) {
|
||||
newSet.delete(adminId)
|
||||
} else {
|
||||
newSet.add(adminId)
|
||||
}
|
||||
return newSet
|
||||
})
|
||||
}, [])
|
||||
|
||||
// 加载状态
|
||||
if (status === 'loading' || loading) {
|
||||
return (
|
||||
@ -404,18 +347,6 @@ export default function AdminPage() {
|
||||
素材管理
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActiveTab('users')}
|
||||
className={`pb-4 px-4 font-medium transition-colors ${
|
||||
activeTab === 'users'
|
||||
? 'text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
|
||||
}`}
|
||||
>
|
||||
用户管理
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActiveTab('categories')}
|
||||
@ -428,18 +359,6 @@ export default function AdminPage() {
|
||||
分类管理
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setActiveTab('departments')}
|
||||
className={`pb-4 px-4 font-medium transition-colors ${
|
||||
activeTab === 'departments'
|
||||
? 'text-gray-900 dark:text-white border-b-2 border-gray-900 dark:border-white'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
|
||||
}`}
|
||||
>
|
||||
部门管理
|
||||
</button>
|
||||
|
||||
{sessionUser?.isSuperAdmin && (
|
||||
<>
|
||||
<button
|
||||
@ -517,24 +436,6 @@ export default function AdminPage() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 用户管理 Tab */}
|
||||
{canManageSystemTabs && activeTab === 'users' && (
|
||||
<UserManagement
|
||||
users={users}
|
||||
setUsers={setUsers}
|
||||
departments={departments}
|
||||
userSearchTerm={userSearchTerm}
|
||||
setUserSearchTerm={setUserSearchTerm}
|
||||
collapsedDepartments={collapsedDepartments}
|
||||
collapsedAdmins={collapsedAdmins}
|
||||
toggleDepartmentCollapse={toggleDepartmentCollapse}
|
||||
toggleAdminCollapse={toggleAdminCollapse}
|
||||
showToast={showToast}
|
||||
fetchData={fetchData}
|
||||
currentUserEmail={session?.user?.email || undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 分类管理 Tab */}
|
||||
{canManageSystemTabs && activeTab === 'categories' && (
|
||||
<CategoryManagement
|
||||
@ -550,16 +451,6 @@ export default function AdminPage() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 部门管理 Tab */}
|
||||
{canManageSystemTabs && activeTab === 'departments' && (
|
||||
<DepartmentManagement
|
||||
departments={departments}
|
||||
setDepartments={setDepartments}
|
||||
showToast={showToast}
|
||||
fetchDepartments={fetchDepartments}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 部门权限配置 Tab */}
|
||||
{canManageSystemTabs && activeTab === 'permissions' && sessionUser?.isSuperAdmin && (
|
||||
<DepartmentPermissionsTab
|
||||
|
||||
@ -49,8 +49,63 @@ export async function GET() {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
// 批量查询活跃绑定,附加权威部门路径(避免 N+1)
|
||||
// 权威人员数据:UserEmployeeBinding -> PerformanceSurveyEmployeeProfile.departmentPath
|
||||
const activeBindings = await prisma.userEmployeeBinding.findMany({
|
||||
where: { status: 'ACTIVE' },
|
||||
select: {
|
||||
userId: true,
|
||||
employeeProfile: {
|
||||
select: {
|
||||
departmentPath: true,
|
||||
departmentName: true,
|
||||
displayName: true,
|
||||
positionLevel: true,
|
||||
levelType: true,
|
||||
isLeadership: true,
|
||||
employmentState: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const bindingMap = new Map(
|
||||
activeBindings
|
||||
.filter((b) => b.employeeProfile)
|
||||
.map((b) => [
|
||||
b.userId,
|
||||
{
|
||||
departmentPath: b.employeeProfile!.departmentPath,
|
||||
departmentName: b.employeeProfile!.departmentName,
|
||||
displayName: b.employeeProfile!.displayName,
|
||||
positionLevel: b.employeeProfile!.positionLevel,
|
||||
levelType: b.employeeProfile!.levelType,
|
||||
isLeadership: b.employeeProfile!.isLeadership,
|
||||
employmentState: b.employeeProfile!.employmentState,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
// 附加权威部门字段到每个用户
|
||||
const enriched = users.map((u) => {
|
||||
const binding = bindingMap.get(u.id);
|
||||
return {
|
||||
...u,
|
||||
// 权威部门路径(新组织树),如「江苏简尚品牌管理有限公司/运营中心G/运营一部(CZ)」
|
||||
employeeDeptPath: binding?.departmentPath ?? null,
|
||||
// 权威部门名(最后一段)
|
||||
employeeDeptName: binding?.departmentPath ? binding.departmentPath.split('/').pop() ?? null : null,
|
||||
employeeDisplayName: binding?.displayName ?? null,
|
||||
employeePositionLevel: binding?.positionLevel ?? null,
|
||||
employeeLevelType: binding?.levelType ?? null,
|
||||
employeeIsLeadership: binding?.isLeadership ?? false,
|
||||
employeeEmploymentState: binding?.employmentState ?? null,
|
||||
// 是否有权威绑定(无绑定 = 待人工确认)
|
||||
hasEmployeeBinding: binding != null,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json(users);
|
||||
return NextResponse.json(enriched);
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error);
|
||||
return NextResponse.json({ error: '获取用户列表失败' }, { status: 500 });
|
||||
|
||||
28
lib/auth.ts
28
lib/auth.ts
@ -50,7 +50,7 @@ export const authOptions: NextAuthOptions = {
|
||||
throw new Error('邮箱或密码错误')
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
let user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email },
|
||||
})
|
||||
|
||||
@ -68,9 +68,29 @@ export const authOptions: NextAuthOptions = {
|
||||
}
|
||||
|
||||
// 检查用户状态(优先使用 status 字段,兼容 isActive)
|
||||
const userStatus = (user as any).status || (user.isActive ? 'active' : 'pending');
|
||||
const isUserActive = userStatus === 'active';
|
||||
|
||||
let userStatus = (user as any).status || (user.isActive ? 'active' : 'pending');
|
||||
let isUserActive = userStatus === 'active';
|
||||
|
||||
// 自动人员规则:花名册在册且在职 → 自动激活;并按 M/P 等级自动同步角色
|
||||
if (!isUserActive) {
|
||||
try {
|
||||
const { autoActivateUserIfEligible, autoSyncRoleFromPersonnel } = await import('@/lib/auto-personnel-rules');
|
||||
const activated = await autoActivateUserIfEligible(user.id);
|
||||
await autoSyncRoleFromPersonnel(user.id);
|
||||
if (activated) {
|
||||
// 刷新内存中的状态
|
||||
const refreshed = await prisma.user.findUnique({ where: { id: user.id } });
|
||||
if (refreshed) {
|
||||
user = { ...user, ...refreshed };
|
||||
userStatus = refreshed.status || (refreshed.isActive ? 'active' : 'pending');
|
||||
isUserActive = userStatus === 'active';
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('自动激活/角色同步失败(不阻塞登录判定):', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 管理员可以登录(即使未激活),但普通用户必须激活
|
||||
// 兼容所有管理员角色:ADMIN, SYSTEM_ADMIN, DEPT_ADMIN
|
||||
const isAdminRole = user.role === 'ADMIN' || user.role === 'SYSTEM_ADMIN' || user.role === 'DEPT_ADMIN';
|
||||
|
||||
133
lib/auto-personnel-rules.ts
Normal file
133
lib/auto-personnel-rules.ts
Normal file
@ -0,0 +1,133 @@
|
||||
/**
|
||||
* 自动人员规则(决策:以花名册为唯一权威,减少人工操作)
|
||||
*
|
||||
* 规则:
|
||||
* 1. 自动激活:账号有活跃绑定(UserEmployeeBinding ACTIVE)且花名册在职
|
||||
* (employmentState 非 RESIGNED)时,账号应自动激活,无需管理员手动激活。
|
||||
* 2. 自动角色:花名册 M 级(levelType='M')或负责人(isLeadership)→ 管理层角色;
|
||||
* P 级 → 普通用户。角色由花名册数据派生,不靠人工设置。
|
||||
* 3. 离职自动归档:已在 organization-sync.applyResignationEffects 处理(离职满 30 天)。
|
||||
*
|
||||
* 供登录链路(凭证登录 / 钉钉登录)与同步链路复用。
|
||||
*/
|
||||
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { Role } from '@prisma/client'
|
||||
|
||||
export const AUTO_ROLE: Record<'DEPT_ADMIN' | 'USER', Role> = {
|
||||
/** M 级/负责人 → 部门管理员 */
|
||||
DEPT_ADMIN: 'DEPT_ADMIN',
|
||||
/** 其余 → 普通用户 */
|
||||
USER: 'USER',
|
||||
} as const
|
||||
|
||||
/**
|
||||
* 查询账号的权威人员信息(通过活跃绑定)。
|
||||
* 返回 null 表示无绑定(无法自动判定,需人工处理)。
|
||||
*/
|
||||
export async function getAuthoritativePersonnelForUser(userId: string): Promise<{
|
||||
employmentState: string | null
|
||||
levelType: string | null
|
||||
positionLevel: string | null
|
||||
isLeadership: boolean
|
||||
} | null> {
|
||||
const binding = await prisma.userEmployeeBinding.findFirst({
|
||||
where: { userId, status: 'ACTIVE' },
|
||||
select: {
|
||||
employeeProfile: {
|
||||
select: {
|
||||
employmentState: true,
|
||||
levelType: true,
|
||||
positionLevel: true,
|
||||
isLeadership: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!binding?.employeeProfile) return null
|
||||
return {
|
||||
employmentState: binding.employeeProfile.employmentState,
|
||||
levelType: binding.employeeProfile.levelType,
|
||||
positionLevel: binding.employeeProfile.positionLevel,
|
||||
isLeadership: binding.employeeProfile.isLeadership,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断账号是否应自动激活:
|
||||
* 有活跃绑定 + 花名册在职(employmentState 非 RESIGNED;UNKNOWN/空视为在职,宁可多留)。
|
||||
*/
|
||||
export function shouldAutoActivate(personnel: {
|
||||
employmentState: string | null
|
||||
} | null): boolean {
|
||||
if (!personnel) return false
|
||||
return personnel.employmentState !== 'RESIGNED'
|
||||
}
|
||||
|
||||
/**
|
||||
* 从花名册数据派生角色:
|
||||
* M 级(levelType='M')或负责人(isLeadership)→ DEPT_ADMIN;否则 USER。
|
||||
*/
|
||||
export function deriveRoleFromPersonnel(personnel: {
|
||||
levelType: string | null
|
||||
isLeadership: boolean
|
||||
}): Role {
|
||||
if (personnel.levelType === 'M' || personnel.isLeadership) {
|
||||
return AUTO_ROLE.DEPT_ADMIN
|
||||
}
|
||||
return AUTO_ROLE.USER
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录时调用:若账号在花名册有绑定且在职,则自动激活账号。
|
||||
* 返回 true 表示执行了自动激活;false 表示无需处理(无绑定或已激活)。
|
||||
*/
|
||||
export async function autoActivateUserIfEligible(userId: string): Promise<boolean> {
|
||||
const personnel = await getAuthoritativePersonnelForUser(userId)
|
||||
if (!shouldAutoActivate(personnel)) return false
|
||||
|
||||
const current = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { status: true, isActive: true },
|
||||
})
|
||||
if (!current) return false
|
||||
|
||||
const currentStatus = current.status || (current.isActive ? 'active' : 'pending')
|
||||
if (currentStatus === 'active') return false
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
status: 'active',
|
||||
isActive: true,
|
||||
statusChangedAt: new Date(),
|
||||
statusChangedBy: 'auto-花名册在册',
|
||||
},
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录时调用:若账号在花名册有绑定,按花名册 M/P 等级自动同步角色。
|
||||
* 仅当当前角色与派生角色不一致且当前角色不是 SYSTEM_ADMIN/ADMIN(不降级超管)时更新。
|
||||
*/
|
||||
export async function autoSyncRoleFromPersonnel(userId: string): Promise<string | null> {
|
||||
const personnel = await getAuthoritativePersonnelForUser(userId)
|
||||
if (!personnel) return null
|
||||
|
||||
const derived = deriveRoleFromPersonnel(personnel)
|
||||
const current = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { role: true },
|
||||
})
|
||||
if (!current) return null
|
||||
// 不自动降级系统管理员/管理员(人工授予的高权限保持不变)
|
||||
if (current.role === 'SYSTEM_ADMIN' || current.role === 'ADMIN') return null
|
||||
if (current.role === derived) return null
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { role: derived },
|
||||
})
|
||||
return derived
|
||||
}
|
||||
@ -455,8 +455,27 @@ async function createOrUpdateUserSession(
|
||||
return response
|
||||
}
|
||||
|
||||
const userStatus = (user as any).status || (user.isActive ? 'active' : 'pending')
|
||||
const isUserActive = userStatus === 'active'
|
||||
let userStatus = (user as any).status || (user.isActive ? 'active' : 'pending')
|
||||
let isUserActive = userStatus === 'active'
|
||||
|
||||
// 自动人员规则:花名册在册且在职 → 自动激活;并按 M/P 等级自动同步角色
|
||||
if (!isUserActive) {
|
||||
try {
|
||||
const { autoActivateUserIfEligible, autoSyncRoleFromPersonnel } = await import('@/lib/auto-personnel-rules')
|
||||
const activated = await autoActivateUserIfEligible(user.id)
|
||||
await autoSyncRoleFromPersonnel(user.id)
|
||||
if (activated) {
|
||||
const refreshed = await prisma.user.findUnique({ where: { id: user.id } })
|
||||
if (refreshed) {
|
||||
user = { ...user, ...refreshed }
|
||||
userStatus = refreshed.status || (refreshed.isActive ? 'active' : 'pending')
|
||||
isUserActive = userStatus === 'active'
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('钉钉登录自动激活/角色同步失败(不阻塞登录判定):', error)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUserActive) {
|
||||
warmPerformanceSurveyProfile(user)
|
||||
@ -588,8 +607,27 @@ async function resolveDingtalkUserForSession(
|
||||
})
|
||||
}
|
||||
|
||||
const userStatus = (user as any).status || (user.isActive ? 'active' : 'pending')
|
||||
const isUserActive = userStatus === 'active'
|
||||
let userStatus = (user as any).status || (user.isActive ? 'active' : 'pending')
|
||||
let isUserActive = userStatus === 'active'
|
||||
|
||||
// 自动人员规则:花名册在册且在职 → 自动激活;并按 M/P 等级自动同步角色
|
||||
if (!isUserActive) {
|
||||
try {
|
||||
const { autoActivateUserIfEligible, autoSyncRoleFromPersonnel } = await import('@/lib/auto-personnel-rules')
|
||||
const activated = await autoActivateUserIfEligible(user.id)
|
||||
await autoSyncRoleFromPersonnel(user.id)
|
||||
if (activated) {
|
||||
const refreshed = await prisma.user.findUnique({ where: { id: user.id } })
|
||||
if (refreshed) {
|
||||
user = { ...user, ...refreshed }
|
||||
userStatus = refreshed.status || (refreshed.isActive ? 'active' : 'pending')
|
||||
isUserActive = userStatus === 'active'
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('钉钉 OAuth 登录自动激活/角色同步失败(不阻塞登录判定):', error)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUserActive) {
|
||||
warmPerformanceSurveyProfile(user)
|
||||
|
||||
@ -1075,20 +1075,64 @@ async function fetchFullSyncRows(
|
||||
const register = getIndexed(registerByUserId, employee.dingtalkUserId)
|
||||
|| getIndexed(registerByJobNumber, employee.jobNumber)
|
||||
|| getIndexed(registerByName, employee.contactName)
|
||||
// 花名册匹配规则(决策:有花名=正式员工,无花名=外部/离职人员):
|
||||
// 1) 优先按工号匹配(最可靠);
|
||||
// 2) 其次按花名匹配——只认有花名的花名册记录,防止"无花名的外部人员"
|
||||
// 按姓名误匹配到同名的正式员工(如 外部交流刘伟 ≠ 品类六部江澄);
|
||||
// 3) 姓名匹配仅作最后兜底,且仅当双方都无花名时才使用,且不采信其等级。
|
||||
const flower = getIndexed(flowerByJobNumber, register?.registerJobNumber, employee.jobNumber)
|
||||
|| getIndexed(flowerByName, register?.flowerName, register?.realName, register?.registerName, employee.contactName)
|
||||
|| getOfficialFlowerByName(flowerRows, register?.flowerName, employee.contactName, register?.realName, register?.registerName)
|
||||
pushMerged(mergeReportRows(employee, register, flower))
|
||||
}
|
||||
|
||||
for (const register of registerRows) {
|
||||
const flower = getIndexed(flowerByJobNumber, register.registerJobNumber, register.jobNumber)
|
||||
|| getIndexed(flowerByName, register.flowerName, register.realName, register.registerName)
|
||||
|| getOfficialFlowerByName(flowerRows, register.flowerName, register.registerName, register.realName)
|
||||
pushMerged(mergeReportRows(register, flower))
|
||||
}
|
||||
|
||||
return applyResolvedDepartmentPaths(pool, mergedRows.slice(0, limit))
|
||||
}
|
||||
|
||||
/**
|
||||
* 按"花名/姓名"从花名册查找正式员工档案。
|
||||
*
|
||||
* 决策(用户确认):有花名 = 正式入职人员;无花名 = 外部人员/离职人员。
|
||||
* 因此:
|
||||
* - 优先用花名匹配:候选花名册记录必须有花名(花名非空),且与查询键一致;
|
||||
* - 姓名匹配仅兜底:只有当查询键本身无花名(外部人员)时,才可能按姓名匹配,
|
||||
* 但此时匹配到的无花名花名册记录(如离职/外部)等级为空,不会串入等级。
|
||||
* - 返回的花名册记录若花名为空,则视为非正式员工,其 jobLevel 等信息会被
|
||||
* normalizeEmployeeRow 中"仅采信有花名记录"的逻辑过滤(见 mergeReportRows)。
|
||||
*/
|
||||
function getOfficialFlowerByName(
|
||||
flowerRows: ReportEmployeeRow[],
|
||||
flowerName?: unknown,
|
||||
...nameKeys: unknown[]
|
||||
): ReportEmployeeRow | undefined {
|
||||
const candidates = nameKeys
|
||||
.filter((k): k is string => typeof k === 'string' && k.trim().length > 0)
|
||||
.map((name) => flowerRows.find(
|
||||
(f) => clean(f.flowerBookFlowerName) === clean(name) && Boolean(clean(f.flowerBookFlowerName)),
|
||||
))
|
||||
.filter((f): f is ReportEmployeeRow => Boolean(f))
|
||||
// 花名精确匹配优先(花名非空)
|
||||
if (flowerName && typeof flowerName === 'string' && flowerName.trim()) {
|
||||
const byFlower = flowerRows.find(
|
||||
(f) => clean(f.flowerBookFlowerName) === clean(flowerName) && Boolean(clean(f.flowerBookFlowerName)),
|
||||
)
|
||||
if (byFlower) return byFlower
|
||||
}
|
||||
// 无花名匹配时,姓名兜底只接受"同样无花名"的记录(外部/离职),等级不会串
|
||||
if (candidates.length > 0) {
|
||||
const noFlower = flowerRows.find(
|
||||
(f) => !clean(f.flowerBookFlowerName) && clean(f.flowerBookName) === clean(candidates[0]),
|
||||
)
|
||||
return noFlower
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function buildIdentityWhere(
|
||||
employeeColumns: TableColumns,
|
||||
registerColumns: TableColumns,
|
||||
|
||||
87
scripts/backfill-auto-personnel.ts
Normal file
87
scripts/backfill-auto-personnel.ts
Normal file
@ -0,0 +1,87 @@
|
||||
/**
|
||||
* 一次性校正脚本:按花名册自动激活 + 同步角色(全量)
|
||||
*
|
||||
* 规则(与 lib/auto-personnel-rules.ts 一致):
|
||||
* - 有活跃绑定 + 花名册在职(非 RESIGNED)→ 自动激活(status=active, isActive=true)
|
||||
* - M 级(levelType='M')或 isLeadership → DEPT_ADMIN;否则 USER
|
||||
* - 不降级 SYSTEM_ADMIN / ADMIN(人工授予的高权限保持不变)
|
||||
*
|
||||
* 用法:npx tsx --env-file=.env scripts/backfill-auto-personnel.ts # 预演(默认)
|
||||
* npx tsx --env-file=.env scripts/backfill-auto-personnel.ts --apply # 实际写入
|
||||
*/
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import {
|
||||
getAuthoritativePersonnelForUser,
|
||||
shouldAutoActivate,
|
||||
deriveRoleFromPersonnel,
|
||||
} from '@/lib/auto-personnel-rules'
|
||||
|
||||
const APPLY = process.argv.includes('--apply')
|
||||
|
||||
;(async () => {
|
||||
console.log(APPLY ? '=== 实际写入模式 ===' : '=== 预演模式(不写入)===')
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where: { archivedAt: null },
|
||||
select: { id: true, username: true, realName: true, role: true, status: true, isActive: true },
|
||||
orderBy: { username: 'asc' },
|
||||
})
|
||||
console.log(`账号总数(未归档): ${users.length}\n`)
|
||||
|
||||
let wouldActivate = 0
|
||||
let wouldRoleChange = 0
|
||||
const plan: string[] = []
|
||||
|
||||
for (const u of users) {
|
||||
const personnel = await getAuthoritativePersonnelForUser(u.id)
|
||||
if (!personnel) continue // 无绑定,跳过
|
||||
|
||||
const changes: string[] = []
|
||||
|
||||
// 激活判定
|
||||
const shouldActivate = shouldAutoActivate(personnel)
|
||||
const currentStatus = u.status || (u.isActive ? 'active' : 'pending')
|
||||
if (shouldActivate && currentStatus !== 'active') {
|
||||
wouldActivate++
|
||||
changes.push(`激活: ${currentStatus} -> active`)
|
||||
}
|
||||
|
||||
// 角色派生
|
||||
const derived = deriveRoleFromPersonnel(personnel)
|
||||
if (u.role !== 'SYSTEM_ADMIN' && u.role !== 'ADMIN' && u.role !== derived) {
|
||||
wouldRoleChange++
|
||||
changes.push(`角色: ${u.role} -> ${derived}`)
|
||||
}
|
||||
|
||||
if (changes.length > 0) {
|
||||
plan.push(`${u.realName ?? u.username} (${u.username}): ${changes.join(', ')}`)
|
||||
|
||||
if (APPLY) {
|
||||
await prisma.user.update({
|
||||
where: { id: u.id },
|
||||
data: {
|
||||
...(shouldActivate && currentStatus !== 'active'
|
||||
? { status: 'active', isActive: true, statusChangedAt: new Date(), statusChangedBy: 'auto-花名册在册' }
|
||||
: {}),
|
||||
...(u.role !== 'SYSTEM_ADMIN' && u.role !== 'ADMIN' && u.role !== derived
|
||||
? { role: derived }
|
||||
: {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`计划激活: ${wouldActivate} 人`)
|
||||
console.log(`计划角色变更: ${wouldRoleChange} 人`)
|
||||
console.log('\n明细:')
|
||||
for (const line of plan) console.log(` ${line}`)
|
||||
|
||||
if (APPLY) {
|
||||
console.log(`\n已写入 ${plan.length} 条记录`)
|
||||
} else {
|
||||
console.log('\n(预演结束,未写入任何数据。加 --apply 实际执行)')
|
||||
}
|
||||
|
||||
await prisma.$disconnect()
|
||||
})().catch((e) => { console.error(e); process.exit(1) })
|
||||
Loading…
x
Reference in New Issue
Block a user