feat: 城市变更功能完善及跨页面缓存刷新修复

- 城市变更使用CITY_CHANGE类型替代ADJUST,月度办理显示减员/新增(城市变更)
- 在保人员查询排除本月已关闭记录(gte→gt)和本月新增记录(lte→lt)
- 社保/公积金减员查询包含CITY_CHANGE类型
- 缴纳记录表格添加城市列显示
- 后端profile API从快照提取city字段
- 修复旧快照缺失city字段的数据
- 修复旧记录changeType为CITY_CHANGE,endMonth与新记录startMonth一致
- 城市变更必填原因,写入备注和审计日志
- 员工详情页添加变更历史Tab
- 移除薪酬社保Tab下重复的参保城市变更子Tab
- 全局修复跨页面mutation缓存刷新:调薪/调部门/离职/重新入职/批量续签/批量解聘/社保公积金调基/月度办理/撤销解聘均刷新roster-profile
This commit is contained in:
selfrelease
2026-07-25 22:40:39 +08:00
parent 7ca2ada0d4
commit f74b2808a3
9 changed files with 1988 additions and 380 deletions
+19
View File
@@ -158,6 +158,7 @@ model Organization {
trainingRecords TrainingRecord[]
performanceRecords PerformanceRecord[]
retirementPolicies RetirementPolicy[]
socialMonthlyProcesses SocialMonthlyProcess[]
}
model User {
@@ -739,6 +740,24 @@ model EmployeeHousingFundRecord {
@@index([employeeId, startMonth, endMonth])
}
/// 月度社保/公积金办理记录(标记某月已办理完成,保存快照)
model SocialMonthlyProcess {
id String @id @default(cuid())
orgId String
org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
month String // 办理月份 YYYY-MM
type String // SOCIAL=社保, HOUSING=公积金
status String @default("COMPLETED") // COMPLETED=已办理
snapshot Json // 办理时的数据快照(增减员+在保人员+缴费明细)
processedBy String
processedAt DateTime @default(now())
createdBy String
createdAt DateTime @default(now())
@@unique([orgId, month, type])
@@index([orgId, month])
}
model EmployeeDepartmentRecord {
id String @id @default(cuid())
orgId String
+87 -24
View File
@@ -1,15 +1,18 @@
import prisma from '../src/lib/prisma'
const EID = 'cmrx61v6d001oqqcwb2pu2tih'
const ORGID = 'cmrx61v3l0000qqcwo3dr3h95'
const UID = 'cmrx61v5u0002qqcwqf4vlyth'
const EID = 'cmry97xbv001qtrrpuo12ozy7'
const ORGID = 'cmry97x7l0000trrp5f9jgng5'
const UID = 'cmry97xa10002trrp7peorkvh'
async function main() {
// 加班记录
// 加班记录(入职后按季度分布)
const otMonths = [
{ month: '2025-03', wh: 8, weh: 4, hh: 0, wp: 600, wep: 600, hp: 0, pay: 1200 },
{ month: '2025-06', wh: 12, weh: 8, hh: 0, wp: 1200, wep: 1200, hp: 0, pay: 2400 },
{ month: '2025-09', wh: 6, weh: 0, hh: 8, wp: 600, wep: 0, hp: 1200, pay: 1800 },
{ month: '2025-12', wh: 10, weh: 4, hh: 0, wp: 900, wep: 600, hp: 0, pay: 1500 },
{ month: '2026-03', wh: 8, weh: 8, hh: 0, wp: 600, wep: 1200, hp: 0, pay: 1800 },
{ month: '2026-06', wh: 6, weh: 0, hh: 0, wp: 450, wep: 0, hp: 0, pay: 450 },
]
for (const o of otMonths) {
const existing = await prisma.overtimeRecord.findUnique({ where: { employeeId_month: { employeeId: EID, month: o.month } } })
@@ -19,10 +22,11 @@ async function main() {
}
console.log('加班记录: 完成')
// 违纪记录
// 违纪记录(补充历史记录,保留已有的 2026-07-24 记录)
const discRecords = [
{ violationDate: new Date('2025-05-12'), violationType: 'LATE', description: '月度迟到超过5次,影响团队考勤', severity: 'WARNING', action: 'ORAL_WARNING', actionDetail: '口头警告并谈话', employeeAck: true, ackDate: new Date('2025-05-13'), ackMethod: 'SIGN', witness: '王强' },
{ violationDate: new Date('2025-09-20'), violationType: 'ABSENT', description: '未经请假擅自旷工1天', severity: 'SERIOUS', action: 'DEDUCTION', actionDetail: '扣款200元', employeeAck: true, ackDate: new Date('2025-09-21'), ackMethod: 'SIGN', witness: '王强' },
{ violationDate: new Date('2026-03-10'), violationType: 'INSUBORDINATION', description: '不服从主管工作安排,拒绝参加客户会议', severity: 'SERIOUS', action: 'WRITTEN_WARNING', actionDetail: '书面警告并记入档案', employeeAck: true, ackDate: new Date('2026-03-11'), ackMethod: 'SIGN', witness: '赵敏' },
]
for (const d of discRecords) {
const existing = await prisma.disciplinaryRecord.findFirst({ where: { employeeId: EID, violationDate: d.violationDate } })
@@ -32,23 +36,52 @@ async function main() {
}
console.log('违纪记录: 完成')
// 考勤记录 - 最近10个工作日
// 考勤记录 - 2026年6-7月最近20个工作日
const attendance = [
{ date: '2026-07-10', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-11', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-14', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-15', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-16', status: 'LATE', late: 25, early: 0 },
{ date: '2026-07-17', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-18', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-21', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-07-22', status: 'EARLY_LEAVE', late: 0, early: 30 },
{ date: '2026-07-23', status: 'NORMAL', late: 0, early: 0 },
{ date: '2026-06-01', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-02', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-03', status: 'LATE', late: 15, early: 0, ot: 0 },
{ date: '2026-06-04', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-05', status: 'NORMAL', late: 0, early: 0, ot: 2 },
{ date: '2026-06-08', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-09', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-10', status: 'LEAVE', late: 0, early: 0, ot: 0, remark: '事假' },
{ date: '2026-06-11', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-12', status: 'NORMAL', late: 0, early: 0, ot: 3 },
{ date: '2026-06-15', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-16', status: 'LATE', late: 30, early: 0, ot: 0 },
{ date: '2026-06-17', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-18', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-19', status: 'EARLY_LEAVE', late: 0, early: 45, ot: 0 },
{ date: '2026-06-22', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-23', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-24', status: 'BUSINESS_TRIP', late: 0, early: 0, ot: 0, remark: '上海客户拜访' },
{ date: '2026-06-25', status: 'BUSINESS_TRIP', late: 0, early: 0, ot: 0, remark: '上海客户拜访' },
{ date: '2026-06-26', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-29', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-06-30', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-01', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-02', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-03', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-06', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-07', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-08', status: 'LATE', late: 20, early: 0, ot: 0 },
{ date: '2026-07-09', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-10', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-13', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-14', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-15', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-16', status: 'LATE', late: 25, early: 0, ot: 0 },
{ date: '2026-07-17', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-20', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-21', status: 'NORMAL', late: 0, early: 0, ot: 0 },
{ date: '2026-07-22', status: 'EARLY_LEAVE', late: 0, early: 30, ot: 0 },
{ date: '2026-07-23', status: 'NORMAL', late: 0, early: 0, ot: 0 },
]
for (const a of attendance) {
const existing = await prisma.attendanceRecord.findUnique({ where: { employeeId_date: { employeeId: EID, date: new Date(a.date) } } })
if (!existing) {
await prisma.attendanceRecord.create({ data: { orgId: ORGID, employeeId: EID, createdBy: UID, date: new Date(a.date), checkInTime: '09:00', checkOutTime: '18:00', status: a.status, lateMinutes: a.late, earlyMinutes: a.early, workHours: 8, overtimeHours: 0 } })
await prisma.attendanceRecord.create({ data: { orgId: ORGID, employeeId: EID, createdBy: UID, date: new Date(a.date), checkInTime: a.status === 'LEAVE' ? null : '09:00', checkOutTime: a.status === 'LEAVE' ? null : '18:00', status: a.status, lateMinutes: a.late, earlyMinutes: a.early, workHours: a.status === 'LEAVE' ? 0 : 8, overtimeHours: a.ot || 0, remark: a.remark || null } })
}
}
console.log('考勤记录: 完成')
@@ -57,7 +90,9 @@ async function main() {
const trainings = [
{ trainingDate: new Date('2025-03-15'), topic: '《员工手册》培训', content: '公司规章制度、考勤制度、奖惩条例', trainer: '赵敏', duration: 2, ackStatus: 'SIGNED', ackDate: new Date('2025-03-15'), remark: '新员工入职培训' },
{ trainingDate: new Date('2025-06-20'), topic: '销售技巧与合规培训', content: '销售话术规范、客户信息保护、合同签订注意事项', trainer: '王强', duration: 4, ackStatus: 'SIGNED', ackDate: new Date('2025-06-20') },
{ trainingDate: new Date('2026-01-10'), topic: '2026年度规章制度更新培训', content: '新版考勤制度、绩效考核办法、安全生产规范', trainer: '赵敏', duration: 3, ackStatus: 'PENDING', remark: '待员工签收确认' },
{ trainingDate: new Date('2025-09-10'), topic: '《数据安全管理制度》培训', content: '客户数据保护规范、信息安全操作规程、违规处罚条例', trainer: '赵敏', duration: 2, ackStatus: 'SIGNED', ackDate: new Date('2025-09-10') },
{ trainingDate: new Date('2026-01-10'), topic: '2026年度规章制度更新培训', content: '新版考勤制度、绩效考核办法、安全生产规范', trainer: '赵敏', duration: 3, ackStatus: 'SIGNED', ackDate: new Date('2026-01-10') },
{ trainingDate: new Date('2026-04-15'), topic: '销售合规与反商业贿赂培训', content: '反商业贿赂法规、客户招待标准、合规销售流程', trainer: '王强', duration: 3, ackStatus: 'PENDING', remark: '待员工签收确认' },
]
for (const t of trainings) {
const existing = await prisma.trainingRecord.findFirst({ where: { employeeId: EID, trainingDate: t.trainingDate } })
@@ -67,12 +102,14 @@ async function main() {
}
console.log('培训记录: 完成')
// 绩效记录
// 绩效记录(从入职后按季度考核)
const performances = [
{ period: '2025-Q1', score: 82, grade: 'B', result: 'QUALIFIED', summary: '销售业绩达标,客户维护良好,需提升新客户开发能力', improvementPlan: '', employeeAck: true, ackDate: new Date('2025-04-10'), reviewer: '王强' },
{ period: '2025-Q1', score: 82, grade: 'B', result: 'QUALIFIED', summary: '入职适应良好,销售业绩达标,客户维护良好,需提升新客户开发能力', improvementPlan: '', employeeAck: true, ackDate: new Date('2025-04-10'), reviewer: '王强' },
{ period: '2025-Q2', score: 75, grade: 'B', result: 'QUALIFIED', summary: '业绩略有下滑,新客户开发不足,团队协作有待加强', improvementPlan: '', employeeAck: true, ackDate: new Date('2025-07-08'), reviewer: '王强' },
{ period: '2025-Q3', score: 68, grade: 'C', result: 'NEED_IMPROVE', summary: '连续3个月未完成销售目标,客户投诉1次', improvementPlan: '调岗至客户维护岗,加强销售技巧培训1个月', employeeAck: true, ackDate: new Date('2025-10-15'), reviewer: '王强' },
{ period: '2025-Q4', score: 78, grade: 'B', result: 'QUALIFIED', summary: '改进后业绩回升,客户满意度提升', improvementPlan: '', employeeAck: false, reviewer: '王强' },
{ period: '2025-Q3', score: 68, grade: 'C', result: 'NEED_IMPROVE', summary: '连续3个月未完成销售目标,客户投诉1次,工作态度需改善', improvementPlan: '调岗至客户维护岗,加强销售技巧培训1个月', employeeAck: true, ackDate: new Date('2025-10-15'), reviewer: '王强' },
{ period: '2025-Q4', score: 78, grade: 'B', result: 'QUALIFIED', summary: '改进后业绩回升,客户满意度提升,团队配合度改善', improvementPlan: '', employeeAck: true, ackDate: new Date('2026-01-12'), reviewer: '王强' },
{ period: '2026-Q1', score: 72, grade: 'B', result: 'QUALIFIED', summary: '一季度业绩基本达标,大客户维护稳定,新签客户2家', improvementPlan: '', employeeAck: true, ackDate: new Date('2026-04-08'), reviewer: '王强' },
{ period: '2026-Q2', score: 65, grade: 'C', result: 'NEED_IMPROVE', summary: '二季度业绩下滑明显,客户流失1家,不服从管理记录1次', improvementPlan: '加强客户维护培训,调整销售目标考核方式', employeeAck: false, reviewer: '王强' },
]
for (const p of performances) {
const existing = await prisma.performanceRecord.findUnique({ where: { employeeId_period: { employeeId: EID, period: p.period } } })
@@ -88,6 +125,8 @@ async function main() {
{ fileName: '吴芳银行卡复印件.jpg', fileType: 'BANK_CARD', fileUrl: 'data:image/jpeg;base64,placeholder', fileSize: 51200 },
{ fileName: '吴芳劳动合同扫描件.pdf', fileType: 'CONTRACT_SCAN', fileUrl: 'data:application/pdf;base64,placeholder', fileSize: 204800 },
{ fileName: '吴芳学历证书.jpg', fileType: 'EDUCATION', fileUrl: 'data:image/jpeg;base64,placeholder', fileSize: 81920 },
{ fileName: '吴芳学位证书.jpg', fileType: 'EDUCATION', fileUrl: 'data:image/jpeg;base64,placeholder', fileSize: 76800 },
{ fileName: '吴芳离职证明(前单位).pdf', fileType: 'OTHER', fileUrl: 'data:application/pdf;base64,placeholder', fileSize: 153600 },
]
for (const a of attachments) {
const existing = await prisma.employeeAttachment.findFirst({ where: { employeeId: EID, fileName: a.fileName } })
@@ -97,10 +136,32 @@ async function main() {
}
console.log('附件: 完成')
// 社保缴费记录(入职)
const hireMonth = '2025-02'
const existingSocial = await prisma.employeeSocialInsRecord.findFirst({ where: { employeeId: EID, startMonth: hireMonth } })
if (!existingSocial) {
await prisma.employeeSocialInsRecord.create({
data: { orgId: ORGID, employeeId: EID, startMonth: hireMonth, endMonth: null, base: 9000, changeType: 'ONBOARDING', createdBy: UID, city: '北京' },
})
}
// 公积金缴费记录(入职)
const existingHousing = await prisma.employeeHousingFundRecord.findFirst({ where: { employeeId: EID, startMonth: hireMonth } })
if (!existingHousing) {
await prisma.employeeHousingFundRecord.create({
data: { orgId: ORGID, employeeId: EID, startMonth: hireMonth, endMonth: null, base: 9000, changeType: 'ONBOARDING', createdBy: UID, city: '北京' },
})
}
// 更新 Employee 便捷字段
await prisma.employee.update({
where: { id: EID },
data: { city: '北京', socialInsStartMonth: hireMonth, housingFundStartMonth: hireMonth },
})
console.log('社保/公积金: 完成')
// 验证
const emp = await prisma.employee.findFirst({
where: { id: EID },
include: { contracts: true, payslips: true, overtimeRecords: true, disciplinaryRecords: true, attendanceRecords: true, trainingRecords: true, performanceRecords: true, terminations: true, attachments: true }
include: { contracts: true, payslips: true, overtimeRecords: true, disciplinaryRecords: true, attendanceRecords: true, trainingRecords: true, performanceRecords: true, terminations: true, attachments: true, socialInsRecords: true, housingFundRecords: true }
})
if (emp) {
console.log('--- 吴芳完整档案数据统计 ---')
@@ -111,8 +172,10 @@ async function main() {
console.log('attendanceRecords:', emp.attendanceRecords.length)
console.log('trainingRecords:', emp.trainingRecords.length)
console.log('performanceRecords:', emp.performanceRecords.length)
console.log('terminations:', emp.terminations.length)
console.log('terminations:', emp.terminations.length, JSON.stringify(emp.terminations.map(t => ({ status: t.status, type: t.type }))))
console.log('attachments:', emp.attachments.length)
console.log('socialInsRecords:', (emp as any).socialInsRecords?.length)
console.log('housingFundRecords:', (emp as any).housingFundRecords?.length)
}
await prisma.$disconnect()
}
+36
View File
@@ -172,11 +172,46 @@ router.get('/:id/profile', authMiddleware, async (req: AuthRequest, res, next) =
performanceRecords: { orderBy: { period: 'desc' } },
terminations: { orderBy: { createdAt: 'desc' } },
attachments: true,
socialInsRecords: { orderBy: { startMonth: 'desc' } },
housingFundRecords: { orderBy: { startMonth: 'desc' } },
salaryChanges: { orderBy: { effectiveDate: 'desc' } },
departmentRecords: { orderBy: { effectiveMonth: 'desc' } },
},
})
if (!employee) {
return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '员工不存在' } })
}
// 查询该员工相关的月度办理记录(从快照中筛选该员工)
const allProcesses = await prisma.socialMonthlyProcess.findMany({
where: { orgId: req.user!.orgId },
orderBy: { month: 'desc' },
})
const employeeId = req.params.id
const monthlyProcessRecords: any[] = []
for (const p of allProcesses) {
const snap = p.snapshot as any
// 从增减员快照中筛选
const changes = snap.changes
const active = snap.active
const type = p.type
let found = false
let recordData: any = { month: p.month, type, processedAt: p.processedAt, status: p.status }
if (changes?.additions) {
const item = changes.additions.find((a: any) => a.employeeId === employeeId)
if (item) { recordData.changeType = '新增'; recordData.detail = item.detail; recordData.base = item.base; recordData.city = item.city; found = true }
}
if (!found && changes?.reductions) {
const item = changes.reductions.find((a: any) => a.employeeId === employeeId)
if (item) { recordData.changeType = '减少'; recordData.detail = item.detail; recordData.base = item.base; recordData.city = item.city; found = true }
}
if (!found && active?.items) {
const item = active.items.find((a: any) => a.employeeId === employeeId)
if (item) { recordData.changeType = '正常在保'; recordData.detail = item.detail; recordData.base = item.base; recordData.city = item.city; found = true }
}
if (found) monthlyProcessRecords.push(recordData)
}
const { monthlySalary, bankAccount, idCardNumber, ...rest } = employee
const today = new Date()
today.setHours(0, 0, 0, 0)
@@ -189,6 +224,7 @@ router.get('/:id/profile', authMiddleware, async (req: AuthRequest, res, next) =
monthlySalary: safeDecrypt(monthlySalary),
bankAccount: bankAccount ? safeDecrypt(bankAccount).toString() : null,
idCardNumber: idCardNumber ? safeDecrypt(idCardNumber).toString() : null,
monthlyProcessRecords,
},
})
} catch (err) {
+381 -60
View File
@@ -787,6 +787,57 @@ router.post('/housing-config/:id/reset-adjustment', async (req: AuthRequest, res
// ========== 月度增减员 ==========
/** 根据基数和社保配置计算各项企业/个人缴费明细 */
function calcSocialDetail(base: number, config: any) {
const actualBase = Math.min(Math.max(base, config.baseMin), config.baseMax)
const items = [
{ name: '养老', orgRate: config.pensionOrg, empRate: config.pensionEmp, orgAmount: actualBase * config.pensionOrg / 100, empAmount: actualBase * config.pensionEmp / 100 },
{ name: '医疗', orgRate: config.medicalOrg, empRate: config.medicalEmp, orgAmount: actualBase * config.medicalOrg / 100, empAmount: actualBase * config.medicalEmp / 100 },
{ name: '失业', orgRate: config.unemploymentOrg, empRate: config.unemploymentEmp, orgAmount: actualBase * config.unemploymentOrg / 100, empAmount: actualBase * config.unemploymentEmp / 100 },
{ name: '工伤', orgRate: config.injuryOrg, empRate: 0, orgAmount: actualBase * config.injuryOrg / 100, empAmount: 0 },
{ name: '生育', orgRate: config.maternityOrg, empRate: 0, orgAmount: actualBase * config.maternityOrg / 100, empAmount: 0 },
]
const totalOrg = items.reduce((s, i) => s + i.orgAmount, 0)
const totalEmp = items.reduce((s, i) => s + i.empAmount, 0)
return { actualBase, items, totalOrg, totalEmp }
}
/** 根据基数和公积金配置计算企业/个人缴费明细 */
function calcHousingDetail(base: number, config: any) {
const actualBase = Math.min(Math.max(base, config.baseMin), config.baseMax)
const orgAmount = actualBase * config.housingOrg / 100
const empAmount = actualBase * config.housingEmp / 100
return { actualBase, orgAmount, empAmount, total: orgAmount + empAmount }
}
/** 按月份匹配社保配置版本 */
async function getSocialConfigByMonth(orgId: string, month: string, city?: string) {
const where: any = { orgId }
if (city) where.city = city
let config = await prisma.socialInsuranceConfig.findFirst({
where: { ...where, effectiveFrom: { lte: month }, OR: [{ effectiveTo: null }, { effectiveTo: { gte: month } }] },
orderBy: { effectiveFrom: 'desc' },
})
if (!config) {
config = await prisma.socialInsuranceConfig.findFirst({ where: { ...where, isCurrent: true } })
}
return config
}
/** 按月份匹配公积金配置版本 */
async function getHousingConfigByMonth(orgId: string, month: string, city?: string) {
const where: any = { orgId }
if (city) where.city = city
let config = await prisma.housingFundConfig.findFirst({
where: { ...where, effectiveFrom: { lte: month }, OR: [{ effectiveTo: null }, { effectiveTo: { gte: month } }] },
orderBy: { effectiveFrom: 'desc' },
})
if (!config) {
config = await prisma.housingFundConfig.findFirst({ where: { ...where, isCurrent: true } })
}
return config
}
// 社保月度增减员
router.get('/monthly-changes', async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
@@ -800,33 +851,59 @@ router.get('/monthly-changes', async (req: AuthRequest, res: Response, next: Nex
orderBy: { createdAt: 'asc' },
})
// 减员:endMonth == month 且 changeType == TERMINATION
// 减员:endMonth == month 且 changeType TERMINATION 或 CITY_CHANGE
const reductions = await prisma.employeeSocialInsRecord.findMany({
where: { orgId, endMonth: month, changeType: 'TERMINATION' },
where: { orgId, endMonth: month, changeType: { in: ['TERMINATION', 'CITY_CHANGE'] } },
include: { employee: { select: { name: true, department: true, idCardNumber: true } } },
orderBy: { createdAt: 'asc' },
})
// 按城市缓存配置
const configCache = new Map<string, any>()
const getConfigForCity = async (city: string) => {
if (!configCache.has(city)) {
configCache.set(city, await getSocialConfigByMonth(orgId, month, city))
}
return configCache.get(city)
}
const mapRecord = async (r: any) => {
const config = await getConfigForCity(r.city)
const detail = config ? calcSocialDetail(r.base, config) : null
return {
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
city: r.city,
base: r.base,
startMonth: r.startMonth,
endMonth: r.endMonth,
changeType: r.changeType,
detail: detail ? {
items: detail.items,
totalOrg: detail.totalOrg,
totalEmp: detail.totalEmp,
total: detail.totalOrg + detail.totalEmp,
} : null,
}
}
// 按城市分组
const allRecords = [...additions, ...reductions]
const cities = [...new Set(allRecords.map((r) => r.city))]
const configs: Record<string, any> = {}
for (const c of cities) {
const cfg = await getConfigForCity(c)
if (cfg) configs[c] = { city: cfg.city, effectiveFrom: cfg.effectiveFrom, baseMin: cfg.baseMin, baseMax: cfg.baseMax }
}
res.json({
success: true,
data: {
month,
additions: additions.map((r) => ({
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
base: r.base,
startMonth: r.startMonth,
changeType: r.changeType,
})),
reductions: reductions.map((r) => ({
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
base: r.base,
endMonth: r.endMonth,
changeType: r.changeType,
})),
configs,
additions: await Promise.all(additions.map(mapRecord)),
reductions: await Promise.all(reductions.map(mapRecord)),
},
})
} catch (err) {
@@ -847,31 +924,50 @@ router.get('/housing/monthly-changes', async (req: AuthRequest, res: Response, n
})
const reductions = await prisma.employeeHousingFundRecord.findMany({
where: { orgId, endMonth: month, changeType: 'TERMINATION' },
where: { orgId, endMonth: month, changeType: { in: ['TERMINATION', 'CITY_CHANGE'] } },
include: { employee: { select: { name: true, department: true, idCardNumber: true } } },
orderBy: { createdAt: 'asc' },
})
const configCache = new Map<string, any>()
const getConfigForCity = async (city: string) => {
if (!configCache.has(city)) {
configCache.set(city, await getHousingConfigByMonth(orgId, month, city))
}
return configCache.get(city)
}
const mapRecord = async (r: any) => {
const config = await getConfigForCity(r.city)
const detail = config ? calcHousingDetail(r.base, config) : null
return {
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
city: r.city,
base: r.base,
startMonth: r.startMonth,
endMonth: r.endMonth,
changeType: r.changeType,
detail: detail ? { orgAmount: detail.orgAmount, empAmount: detail.empAmount, total: detail.total } : null,
}
}
const allRecords = [...additions, ...reductions]
const cities = [...new Set(allRecords.map((r) => r.city))]
const configs: Record<string, any> = {}
for (const c of cities) {
const cfg = await getConfigForCity(c)
if (cfg) configs[c] = { city: cfg.city, effectiveFrom: cfg.effectiveFrom, baseMin: cfg.baseMin, baseMax: cfg.baseMax, housingOrg: cfg.housingOrg, housingEmp: cfg.housingEmp }
}
res.json({
success: true,
data: {
month,
additions: additions.map((r) => ({
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
base: r.base,
startMonth: r.startMonth,
changeType: r.changeType,
})),
reductions: reductions.map((r) => ({
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
base: r.base,
endMonth: r.endMonth,
changeType: r.changeType,
})),
configs,
additions: await Promise.all(additions.map(mapRecord)),
reductions: await Promise.all(reductions.map(mapRecord)),
},
})
} catch (err) {
@@ -890,27 +986,52 @@ router.get('/active-declaration', async (req: AuthRequest, res: Response, next:
const records = await prisma.employeeSocialInsRecord.findMany({
where: {
orgId,
startMonth: { lte: month },
OR: [{ endMonth: null }, { endMonth: { gte: month } }],
startMonth: { lt: month },
OR: [{ endMonth: null }, { endMonth: { gt: month } }],
},
include: { employee: { select: { name: true, department: true, idCardNumber: true, hireDate: true } } },
orderBy: { createdAt: 'asc' },
})
const configCache = new Map<string, any>()
const getConfigForCity = async (city: string) => {
if (!configCache.has(city)) {
configCache.set(city, await getSocialConfigByMonth(orgId, month, city))
}
return configCache.get(city)
}
const items = await Promise.all(records.map(async (r) => {
const config = await getConfigForCity(r.city)
const detail = config ? calcSocialDetail(r.base, config) : null
return {
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
city: r.city,
base: r.base,
startMonth: r.startMonth,
endMonth: r.endMonth,
changeType: r.changeType,
detail: detail ? {
items: detail.items,
totalOrg: detail.totalOrg,
totalEmp: detail.totalEmp,
total: detail.totalOrg + detail.totalEmp,
} : null,
}
}))
const cities = [...new Set(records.map((r) => r.city))]
const configs: Record<string, any> = {}
for (const c of cities) {
const cfg = await getConfigForCity(c)
if (cfg) configs[c] = { city: cfg.city, effectiveFrom: cfg.effectiveFrom, baseMin: cfg.baseMin, baseMax: cfg.baseMax }
}
res.json({
success: true,
data: {
month,
items: records.map((r) => ({
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
base: r.base,
startMonth: r.startMonth,
endMonth: r.endMonth,
changeType: r.changeType,
})),
},
data: { month, configs, items },
})
} catch (err) {
next(err)
@@ -926,26 +1047,85 @@ router.get('/housing/active-declaration', async (req: AuthRequest, res: Response
const records = await prisma.employeeHousingFundRecord.findMany({
where: {
orgId,
startMonth: { lte: month },
OR: [{ endMonth: null }, { endMonth: { gte: month } }],
startMonth: { lt: month },
OR: [{ endMonth: null }, { endMonth: { gt: month } }],
},
include: { employee: { select: { name: true, department: true, idCardNumber: true, hireDate: true } } },
orderBy: { createdAt: 'asc' },
})
const configCache = new Map<string, any>()
const getConfigForCity = async (city: string) => {
if (!configCache.has(city)) {
configCache.set(city, await getHousingConfigByMonth(orgId, month, city))
}
return configCache.get(city)
}
const items = await Promise.all(records.map(async (r) => {
const config = await getConfigForCity(r.city)
const detail = config ? calcHousingDetail(r.base, config) : null
return {
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
city: r.city,
base: r.base,
startMonth: r.startMonth,
endMonth: r.endMonth,
changeType: r.changeType,
detail: detail ? { orgAmount: detail.orgAmount, empAmount: detail.empAmount, total: detail.total } : null,
}
}))
const cities = [...new Set(records.map((r) => r.city))]
const configs: Record<string, any> = {}
for (const c of cities) {
const cfg = await getConfigForCity(c)
if (cfg) configs[c] = { city: cfg.city, effectiveFrom: cfg.effectiveFrom, baseMin: cfg.baseMin, baseMax: cfg.baseMax, housingOrg: cfg.housingOrg, housingEmp: cfg.housingEmp }
}
res.json({
success: true,
data: { month, configs, items },
})
} catch (err) {
next(err)
}
})
// ========== 月度办理完成(保存快照) ==========
// 列出所有已办理月份(用于办理总览)
router.get('/monthly-process/list', async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const orgId = req.user!.orgId
const records = await prisma.socialMonthlyProcess.findMany({
where: { orgId },
orderBy: { month: 'desc' },
select: { id: true, month: true, type: true, status: true, processedAt: true, processedBy: true },
})
res.json({ success: true, data: records })
} catch (err) {
next(err)
}
})
// 查询某月办理状态
router.get('/monthly-process/status', async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const month = (req.query.month as string) || new Date().toISOString().slice(0, 7)
const orgId = req.user!.orgId
const records = await prisma.socialMonthlyProcess.findMany({
where: { orgId, month },
})
res.json({
success: true,
data: {
month,
items: records.map((r) => ({
employeeId: r.employeeId,
name: r.employee.name,
department: r.employee.department,
base: r.base,
startMonth: r.startMonth,
endMonth: r.endMonth,
changeType: r.changeType,
})),
social: records.find((r) => r.type === 'SOCIAL') || null,
housing: records.find((r) => r.type === 'HOUSING') || null,
},
})
} catch (err) {
@@ -953,4 +1133,145 @@ router.get('/housing/active-declaration', async (req: AuthRequest, res: Response
}
})
// 办理完成(保存快照)
router.post('/monthly-process/complete', async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const { month, type, snapshot } = req.body as { month: string; type: 'SOCIAL' | 'HOUSING'; snapshot: any }
const orgId = req.user!.orgId
if (!month || !type || !snapshot) {
return res.status(400).json({ success: false, message: '缺少必要参数' })
}
const existing = await prisma.socialMonthlyProcess.findUnique({
where: { orgId_month_type: { orgId, month, type } },
})
if (existing) {
// 已存在则更新快照
const updated = await prisma.socialMonthlyProcess.update({
where: { id: existing.id },
data: { snapshot, processedBy: req.user!.id, processedAt: new Date() },
})
return res.json({ success: true, data: updated })
}
const record = await prisma.socialMonthlyProcess.create({
data: {
orgId,
month,
type,
snapshot,
processedBy: req.user!.id,
createdBy: req.user!.id,
},
})
res.json({ success: true, data: record })
} catch (err) {
next(err)
}
})
// ========== 记录修正(直接更新 + 审计日志) ==========
// 修正社保记录
router.put('/records/social/:id/correct', async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const orgId = req.user!.orgId
const { city, base, startMonth, endMonth, changeType, remark } = req.body as { city?: string; base?: number; startMonth?: string; endMonth?: string; changeType?: string; remark?: string }
const record = await prisma.employeeSocialInsRecord.findFirst({ where: { id: req.params.id, orgId } })
if (!record) return res.status(404).json({ success: false, message: '记录不存在' })
const oldData = { city: record.city, base: record.base, startMonth: record.startMonth, endMonth: record.endMonth, changeType: record.changeType, remark: record.remark }
const updateData: any = {}
if (city !== undefined) updateData.city = city
if (base !== undefined) updateData.base = base
if (startMonth !== undefined) updateData.startMonth = startMonth
if (endMonth !== undefined) updateData.endMonth = endMonth || null
if (changeType !== undefined) updateData.changeType = changeType
if (remark !== undefined) updateData.remark = remark
const updated = await prisma.employeeSocialInsRecord.update({ where: { id: req.params.id }, data: updateData })
// 同步员工便捷字段(如果修正的是当前在保记录)
if (!updated.endMonth) {
await prisma.employee.update({
where: { id: record.employeeId },
data: {
...(city !== undefined ? { city } : {}),
...(base !== undefined ? { socialInsBase: base } : {}),
...(startMonth !== undefined ? { socialInsStartMonth: startMonth } : {}),
},
})
}
// 写审计日志
await prisma.auditLog.create({
data: {
orgId,
userId: req.user!.id,
action: 'CORRECT',
entity: 'EmployeeSocialInsRecord',
entityId: req.params.id,
detail: { old: oldData, new: updateData, reason: req.body.reason || '数据修正' },
},
})
res.json({ success: true, data: updated })
} catch (err) {
next(err)
}
})
// 修正公积金记录
router.put('/records/housing/:id/correct', async (req: AuthRequest, res: Response, next: NextFunction) => {
try {
const orgId = req.user!.orgId
const { city, base, startMonth, endMonth, changeType, remark } = req.body as { city?: string; base?: number; startMonth?: string; endMonth?: string; changeType?: string; remark?: string }
const record = await prisma.employeeHousingFundRecord.findFirst({ where: { id: req.params.id, orgId } })
if (!record) return res.status(404).json({ success: false, message: '记录不存在' })
const oldData = { city: record.city, base: record.base, startMonth: record.startMonth, endMonth: record.endMonth, changeType: record.changeType, remark: record.remark }
const updateData: any = {}
if (city !== undefined) updateData.city = city
if (base !== undefined) updateData.base = base
if (startMonth !== undefined) updateData.startMonth = startMonth
if (endMonth !== undefined) updateData.endMonth = endMonth || null
if (changeType !== undefined) updateData.changeType = changeType
if (remark !== undefined) updateData.remark = remark
const updated = await prisma.employeeHousingFundRecord.update({ where: { id: req.params.id }, data: updateData })
// 同步员工便捷字段(如果修正的是当前在保记录)
if (!updated.endMonth) {
await prisma.employee.update({
where: { id: record.employeeId },
data: {
...(city !== undefined ? { city } : {}),
...(base !== undefined ? { housingFundBase: base } : {}),
...(startMonth !== undefined ? { housingFundStartMonth: startMonth } : {}),
},
})
}
// 写审计日志
await prisma.auditLog.create({
data: {
orgId,
userId: req.user!.id,
action: 'CORRECT',
entity: 'EmployeeHousingFundRecord',
entityId: req.params.id,
detail: { old: oldData, new: updateData, reason: req.body.reason || '数据修正' },
},
})
res.json({ success: true, data: updated })
} catch (err) {
next(err)
}
})
export default router
+94
View File
@@ -521,6 +521,100 @@ export async function updateEmployee(orgId: string, id: string, data: any) {
if (data.specialDeduction !== undefined) updateData.specialDeduction = data.specialDeduction
if (data.city !== undefined) updateData.city = data.city
// 参保城市变更:关闭旧城市在保记录,创建新城市记录
if (data.city !== undefined && data.city !== employee.city) {
const nowMonth = new Date().toISOString().slice(0, 7)
const cityChangeReason = data.cityChangeReason || '未填写原因'
const changeRemark = `城市变更:${employee.city || '未设置'}${data.city}${cityChangeReason}`
// 社保:关闭旧在保记录,创建新城市记录
const activeSocial = await prisma.employeeSocialInsRecord.findFirst({
where: { employeeId: id, endMonth: null },
})
if (activeSocial) {
await prisma.employeeSocialInsRecord.update({
where: { id: activeSocial.id },
data: { endMonth: nowMonth, changeType: 'CITY_CHANGE', remark: changeRemark },
})
await prisma.employeeSocialInsRecord.create({
data: {
orgId,
employeeId: id,
city: data.city,
startMonth: nowMonth,
endMonth: null,
base: activeSocial.base,
changeType: 'CITY_CHANGE',
remark: changeRemark,
createdBy: '',
},
})
} else {
// 兜底:没有在保记录也创建一条,保留变更历史
await prisma.employeeSocialInsRecord.create({
data: {
orgId,
employeeId: id,
city: data.city,
startMonth: nowMonth,
endMonth: null,
base: employee.socialInsBase || 0,
changeType: 'CITY_CHANGE',
remark: changeRemark,
createdBy: '',
},
})
}
// 公积金:同上
const activeHousing = await prisma.employeeHousingFundRecord.findFirst({
where: { employeeId: id, endMonth: null },
})
if (activeHousing) {
await prisma.employeeHousingFundRecord.update({
where: { id: activeHousing.id },
data: { endMonth: nowMonth, changeType: 'CITY_CHANGE', remark: changeRemark },
})
await prisma.employeeHousingFundRecord.create({
data: {
orgId,
employeeId: id,
city: data.city,
startMonth: nowMonth,
endMonth: null,
base: activeHousing.base,
changeType: 'CITY_CHANGE',
remark: changeRemark,
createdBy: '',
},
})
} else {
// 兜底:没有在保记录也创建一条
await prisma.employeeHousingFundRecord.create({
data: {
orgId,
employeeId: id,
city: data.city,
startMonth: nowMonth,
endMonth: null,
base: employee.housingFundBase || 0,
changeType: 'CITY_CHANGE',
remark: changeRemark,
createdBy: '',
},
})
}
// 写审计日志
await prisma.auditLog.create({
data: {
orgId,
userId: '',
action: 'CITY_CHANGE',
entity: 'Employee',
entityId: id,
detail: { oldCity: employee.city, newCity: data.city, reason: cityChangeReason, remark: changeRemark },
},
})
}
await prisma.employee.update({ where: { id }, data: updateData })
await runRiskDetection(orgId)