Files
TurboHR/backend/prisma/seed-multi-org.ts
T

432 lines
22 KiB
TypeScript

/**
* 多企业测试种子脚本
* 创建多个不同企业(含管理员、员工、合同、社保配置等),用于多租户测试
*
* 用法: npx tsx prisma/seed-multi-org.ts
*
* 注意:此脚本不会清空已有数据,而是在现有基础上追加新企业。
* 如需重置,请先运行 prisma/seed.ts(会清空所有数据)。
*/
import { PrismaClient, Prisma } from '@prisma/client'
import bcrypt from 'bcryptjs'
import { encrypt } from '../src/lib/crypto'
const prisma = new PrismaClient()
// ========== 社保计算工具 ==========
function calcSocial(base: number, config: any) {
const actualBase = Math.min(Math.max(base, config.baseMin), config.baseMax)
const socialEmp = actualBase * (config.pensionEmp + config.medicalEmp + config.unemploymentEmp) / 100
const socialOrg = actualBase * (config.pensionOrg + config.medicalOrg + config.unemploymentOrg + config.injuryOrg + config.maternityOrg) / 100
return { socialEmp: Math.round(socialEmp * 100) / 100, socialOrg: Math.round(socialOrg * 100) / 100 }
}
function calcHousing(base: number, config: any) {
const actualBase = Math.min(Math.max(base, config.baseMin), config.baseMax)
const housingEmp = actualBase * config.housingEmp / 100
const housingOrg = actualBase * config.housingOrg / 100
return { housingEmp: Math.round(housingEmp * 100) / 100, housingOrg: Math.round(housingOrg * 100) / 100 }
}
function calcTax(taxableIncome: number): number {
if (taxableIncome <= 0) return 0
let tax = 0
if (taxableIncome <= 36000) tax = taxableIncome * 0.03
else if (taxableIncome <= 144000) tax = taxableIncome * 0.10 - 2520
else if (taxableIncome <= 300000) tax = taxableIncome * 0.20 - 16920
else if (taxableIncome <= 420000) tax = taxableIncome * 0.25 - 31920
else if (taxableIncome <= 660000) tax = taxableIncome * 0.30 - 52920
else if (taxableIncome <= 960000) tax = taxableIncome * 0.35 - 85920
else tax = taxableIncome * 0.45 - 181920
return Math.max(0, Math.round(tax * 100) / 100)
}
// ========== 企业配置定义 ==========
interface OrgConfig {
name: string
city: string
plan: 'FREE' | 'PRO' | 'ENTERPRISE'
maxEmployees: number
adminPhone: string
adminName: string
contactName: string
contactPhone: string
payrollFrequency: number
retirementReminderEnabled: boolean
socialConfig: {
city: string
pensionOrg: number; pensionEmp: number
medicalOrg: number; medicalEmp: number
unemploymentOrg: number; unemploymentEmp: number
injuryOrg: number; maternityOrg: number
baseMin: number; baseMax: number
medicalBaseMin?: number; medicalBaseMax?: number
extraInsurances?: any[]
}
housingConfig: {
city: string
housingOrg: number; housingEmp: number
baseMin: number; baseMax: number
}
employees: {
name: string; gender: string; dept: string; phone: string
idCard: string; salary: number; hireDate: string
socialBase: number; housingBase: number; specialDeduction: number
contractType: 'FIXED' | 'UNFIXED'; years: number
probation: number; probationSalary: number
bank: string; account: string
emergency: string; emergencyPhone: string; address: string
pregnant?: boolean
}[]
}
// 3 个测试企业配置
const ORGS: OrgConfig[] = [
{
name: '北京华夏制造有限公司',
city: '北京',
plan: 'PRO',
maxEmployees: 100,
adminPhone: '13800000010',
adminName: '王建国',
contactName: '王建国',
contactPhone: '13800000010',
payrollFrequency: 1,
retirementReminderEnabled: true,
socialConfig: {
city: '北京',
pensionOrg: 16, pensionEmp: 8,
medicalOrg: 9.8, medicalEmp: 2,
unemploymentOrg: 0.5, unemploymentEmp: 0.5,
injuryOrg: 0.2, maternityOrg: 0.8,
baseMin: 6326, baseMax: 33891,
},
housingConfig: {
city: '北京',
housingOrg: 12, housingEmp: 12,
baseMin: 6326, baseMax: 33891,
},
employees: [
{ name: '刘大壮', gender: '男', dept: '生产车间', phone: '13900001001', idCard: '110101198501011001', salary: 8500, hireDate: '2022-03-01', socialBase: 8500, housingBase: 8500, specialDeduction: 2000, contractType: 'FIXED', years: 3, probation: 3, probationSalary: 6800, bank: '工商银行', account: '6222020100010001001', emergency: '刘父', emergencyPhone: '13800001001', address: '北京市朝阳区工业路1号' },
{ name: '陈秀英', gender: '女', dept: '生产车间', phone: '13900001002', idCard: '110102198803021002', salary: 7500, hireDate: '2023-06-15', socialBase: 7500, housingBase: 7500, specialDeduction: 1000, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 6000, bank: '建设银行', account: '6227000100020002002', emergency: '陈母', emergencyPhone: '13800001002', address: '北京市海淀区中关村2号' },
{ name: '赵铁柱', gender: '男', dept: '生产车间', phone: '13900001003', idCard: '110103199012030003', salary: 9000, hireDate: '2021-01-10', socialBase: 9000, housingBase: 9000, specialDeduction: 3000, contractType: 'UNFIXED', years: 0, probation: 0, probationSalary: 0, bank: '农业银行', account: '6228480100030003003', emergency: '赵妻', emergencyPhone: '13800001003', address: '北京市丰台区南三环3号' },
{ name: '孙美丽', gender: '女', dept: '行政部', phone: '13900001004', idCard: '110104199506040004', salary: 11000, hireDate: '2022-09-01', socialBase: 11000, housingBase: 11000, specialDeduction: 1500, contractType: 'FIXED', years: 3, probation: 3, probationSalary: 8800, bank: '中国银行', account: '6217000100040004004', emergency: '孙父', emergencyPhone: '13800001004', address: '北京市西城区西直门4号', pregnant: true },
{ name: '周大伟', gender: '男', dept: '生产车间', phone: '13900001005', idCard: '110105199807050005', salary: 7000, hireDate: '2024-07-01', socialBase: 7000, housingBase: 7000, specialDeduction: 0, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 5600, bank: '交通银行', account: '6222600100050005005', emergency: '周母', emergencyPhone: '13800001005', address: '北京市石景山区八角5号' },
{ name: '吴小红', gender: '女', dept: '质检部', phone: '13900001006', idCard: '110106199311060006', salary: 9500, hireDate: '2023-11-15', socialBase: 9500, housingBase: 9500, specialDeduction: 2500, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 7600, bank: '招商银行', account: '6225880100060006006', emergency: '吴父', emergencyPhone: '13800001006', address: '北京市通州区新华大街6号' },
],
},
{
name: '深圳鹏程物流有限公司',
city: '深圳',
plan: 'ENTERPRISE',
maxEmployees: 200,
adminPhone: '13800000020',
adminName: '李明华',
contactName: '李明华',
contactPhone: '13800000020',
payrollFrequency: 2,
retirementReminderEnabled: true,
socialConfig: {
city: '深圳',
pensionOrg: 15, pensionEmp: 8,
medicalOrg: 5.2, medicalEmp: 2,
unemploymentOrg: 0.7, unemploymentEmp: 0.3,
injuryOrg: 0.3, maternityOrg: 0.5,
baseMin: 3523, baseMax: 27927,
medicalBaseMin: 6060, medicalBaseMax: 29892,
},
housingConfig: {
city: '深圳',
housingOrg: 5, housingEmp: 5,
baseMin: 3523, baseMax: 27927,
},
employees: [
{ name: '黄志强', gender: '男', dept: '运输部', phone: '13900002001', idCard: '440301198501072001', salary: 12000, hireDate: '2021-04-01', socialBase: 12000, housingBase: 12000, specialDeduction: 2000, contractType: 'UNFIXED', years: 0, probation: 0, probationSalary: 0, bank: '工商银行', account: '6222020200010001001', emergency: '黄妻', emergencyPhone: '13800002001', address: '深圳市南山区科技园1号' },
{ name: '林晓燕', gender: '女', dept: '财务部', phone: '13900002002', idCard: '440302199003082002', salary: 14000, hireDate: '2022-06-15', socialBase: 14000, housingBase: 14000, specialDeduction: 1500, contractType: 'FIXED', years: 3, probation: 3, probationSalary: 11200, bank: '建设银行', account: '6227000200020002002', emergency: '林母', emergencyPhone: '13800002002', address: '深圳市福田区华强北2号' },
{ name: '张海涛', gender: '男', dept: '运输部', phone: '13900002003', idCard: '440303198812092003', salary: 10000, hireDate: '2023-01-10', socialBase: 10000, housingBase: 10000, specialDeduction: 3000, contractType: 'FIXED', years: 3, probation: 3, probationSalary: 8000, bank: '招商银行', account: '6225880200030003003', emergency: '张父', emergencyPhone: '13800002003', address: '深圳市罗湖区东门3号' },
{ name: '何丽萍', gender: '女', dept: '客服部', phone: '13900002004', idCard: '440304199506102004', salary: 8000, hireDate: '2024-01-01', socialBase: 8000, housingBase: 8000, specialDeduction: 1000, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 6400, bank: '农业银行', account: '6228480200040004004', emergency: '何父', emergencyPhone: '13800002004', address: '深圳市宝安区西乡4号' },
{ name: '马俊杰', gender: '男', dept: '运输部', phone: '13900002005', idCard: '440305199907112005', salary: 9500, hireDate: '2024-07-01', socialBase: 9500, housingBase: 9500, specialDeduction: 0, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 7600, bank: '中国银行', account: '6217000200050005005', emergency: '马母', emergencyPhone: '13800002005', address: '深圳市龙岗区中心城5号' },
{ name: '高雅婷', gender: '女', dept: '行政部', phone: '13900002006', idCard: '440306199311122006', salary: 11000, hireDate: '2023-05-15', socialBase: 11000, housingBase: 11000, specialDeduction: 2500, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 8800, bank: '交通银行', account: '6222600200060006006', emergency: '高父', emergencyPhone: '13800002006', address: '深圳市龙华区民治6号' },
{ name: '罗建军', gender: '男', dept: '运输部', phone: '13900002007', idCard: '440307198504132007', salary: 13000, hireDate: '2020-08-01', socialBase: 27927, housingBase: 27927, specialDeduction: 4000, contractType: 'UNFIXED', years: 0, probation: 0, probationSalary: 0, bank: '民生银行', account: '6226160200070007007', emergency: '罗妻', emergencyPhone: '13800002007', address: '深圳市南山区前海7号' },
],
},
{
name: '杭州云创科技有限公司',
city: '杭州',
plan: 'FREE',
maxEmployees: 20,
adminPhone: '13800000030',
adminName: '赵雪梅',
contactName: '赵雪梅',
contactPhone: '13800000030',
payrollFrequency: 1,
retirementReminderEnabled: false,
socialConfig: {
city: '杭州',
pensionOrg: 14, pensionEmp: 8,
medicalOrg: 9.9, medicalEmp: 2,
unemploymentOrg: 0.5, unemploymentEmp: 0.5,
injuryOrg: 0.2, maternityOrg: 1.2,
baseMin: 4812, baseMax: 24060,
},
housingConfig: {
city: '杭州',
housingOrg: 12, housingEmp: 12,
baseMin: 4812, baseMax: 24060,
},
employees: [
{ name: '钱学文', gender: '男', dept: '研发部', phone: '13900003001', idCard: '330101199001013001', salary: 20000, hireDate: '2022-03-01', socialBase: 20000, housingBase: 20000, specialDeduction: 2000, contractType: 'FIXED', years: 3, probation: 3, probationSalary: 16000, bank: '工商银行', account: '6222020300010001001', emergency: '钱父', emergencyPhone: '13800003001', address: '杭州市西湖区文三路1号' },
{ name: '孙雨晴', gender: '女', dept: '研发部', phone: '13900003002', idCard: '330102199503023002', salary: 18000, hireDate: '2023-06-15', socialBase: 18000, housingBase: 18000, specialDeduction: 1000, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 14400, bank: '建设银行', account: '6227000300020002002', emergency: '孙母', emergencyPhone: '13800003002', address: '杭州市滨江区江南大道2号' },
{ name: '周明杰', gender: '男', dept: '产品部', phone: '13900003003', idCard: '330103198812033003', salary: 16000, hireDate: '2021-01-10', socialBase: 16000, housingBase: 16000, specialDeduction: 3000, contractType: 'UNFIXED', years: 0, probation: 0, probationSalary: 0, bank: '招商银行', account: '6225880300030003003', emergency: '周妻', emergencyPhone: '13800003003', address: '杭州市余杭区未来科技城3号' },
{ name: '吴雅芳', gender: '女', dept: '市场部', phone: '13900003004', idCard: '330104199806043004', salary: 12000, hireDate: '2024-07-01', socialBase: 12000, housingBase: 12000, specialDeduction: 500, contractType: 'FIXED', years: 3, probation: 2, probationSalary: 9600, bank: '农业银行', account: '6228480300040004004', emergency: '吴父', emergencyPhone: '13800003004', address: '杭州市拱墅区莫干山路4号' },
],
},
]
// ========== 薪酬模版默认项 ==========
const DEFAULT_PAYSILP_ITEMS = [
{ name: '基本工资', code: 'baseSalary', type: 'INPUT' as const, formula: null, order: 1, isDefault: true, isEditable: true },
{ name: '加班费', code: 'overtimePay', type: 'CALCULATED' as const, formula: 'weekdayOvertimePay + weekendOvertimePay + holidayOvertimePay', order: 2, isDefault: true, isEditable: false },
{ name: '津贴补贴', code: 'allowance', type: 'INPUT' as const, formula: null, order: 3, isDefault: true, isEditable: true },
{ name: '奖金', code: 'bonus', type: 'INPUT' as const, formula: null, order: 4, isDefault: true, isEditable: true },
{ name: '扣款', code: 'deduction', type: 'INPUT' as const, formula: null, order: 5, isDefault: true, isEditable: true },
{ name: '应发合计', code: 'totalPay', type: 'CALCULATED' as const, formula: 'baseSalary + overtimePay + allowance + bonus - deduction', order: 6, isDefault: true, isEditable: false },
{ name: '个人社保', code: 'socialEmp', type: 'CALCULATED' as const, formula: 'SOCIAL_EMP', order: 7, isDefault: true, isEditable: false },
{ name: '个人公积金', code: 'housingEmp', type: 'CALCULATED' as const, formula: 'HOUSING_EMP', order: 8, isDefault: true, isEditable: false },
{ name: '个人所得税', code: 'tax', type: 'CALCULATED' as const, formula: 'TAX', order: 9, isDefault: true, isEditable: false },
{ name: '实发工资', code: 'netPay', type: 'CALCULATED' as const, formula: 'totalPay - socialEmp - housingEmp - tax', order: 10, isDefault: true, isEditable: false },
]
// ========== 创建单个企业 ==========
async function createOrg(orgConfig: OrgConfig) {
// 检查是否已存在(按管理员手机号判断)
const existingUser = await prisma.user.findUnique({ where: { phone: orgConfig.adminPhone } })
if (existingUser) {
console.log(` ⏭ 企业「${orgConfig.name}」已存在(管理员 ${orgConfig.adminPhone}),跳过`)
return
}
// 1. 创建企业
const org = await prisma.organization.create({
data: {
name: orgConfig.name,
plan: orgConfig.plan,
maxEmployees: orgConfig.maxEmployees,
city: orgConfig.city,
contactName: orgConfig.contactName,
contactPhone: orgConfig.contactPhone,
payrollFrequency: orgConfig.payrollFrequency,
retirementReminderEnabled: orgConfig.retirementReminderEnabled,
},
})
console.log(` ✅ 企业已创建: ${org.name} (${org.id})`)
// 2. 创建管理员
const passwordHash = await bcrypt.hash('12345678', 10)
const admin = await prisma.user.create({
data: {
orgId: org.id,
phone: orgConfig.adminPhone,
name: orgConfig.adminName,
passwordHash,
role: 'ADMIN',
},
})
console.log(` ✅ 管理员已创建: ${admin.phone} (${admin.name})`)
// 3. 创建社保配置
await prisma.socialInsuranceConfig.create({
data: {
orgId: org.id,
city: orgConfig.socialConfig.city,
pensionOrg: orgConfig.socialConfig.pensionOrg,
pensionEmp: orgConfig.socialConfig.pensionEmp,
medicalOrg: orgConfig.socialConfig.medicalOrg,
medicalEmp: orgConfig.socialConfig.medicalEmp,
unemploymentOrg: orgConfig.socialConfig.unemploymentOrg,
unemploymentEmp: orgConfig.socialConfig.unemploymentEmp,
injuryOrg: orgConfig.socialConfig.injuryOrg,
maternityOrg: orgConfig.socialConfig.maternityOrg,
baseMin: orgConfig.socialConfig.baseMin,
baseMax: orgConfig.socialConfig.baseMax,
medicalBaseMin: orgConfig.socialConfig.medicalBaseMin || 0,
medicalBaseMax: orgConfig.socialConfig.medicalBaseMax || 0,
extraInsurances: orgConfig.socialConfig.extraInsurances || Prisma.JsonNull,
effectiveFrom: '2025-07',
createdBy: admin.id,
},
})
console.log(` ✅ 社保配置已创建 (${orgConfig.socialConfig.city})`)
// 4. 创建公积金配置
await prisma.housingFundConfig.create({
data: {
orgId: org.id,
city: orgConfig.housingConfig.city,
housingOrg: orgConfig.housingConfig.housingOrg,
housingEmp: orgConfig.housingConfig.housingEmp,
baseMin: orgConfig.housingConfig.baseMin,
baseMax: orgConfig.housingConfig.baseMax,
effectiveFrom: '2025-07',
createdBy: admin.id,
},
})
console.log(` ✅ 公积金配置已创建 (${orgConfig.housingConfig.city})`)
// 5. 创建通知设置
await prisma.notificationSetting.create({
data: { orgId: org.id },
})
// 6. 创建加班配置
await prisma.overtimeConfig.create({
data: { orgId: org.id },
})
// 7. 创建薪酬模版
for (const item of DEFAULT_PAYSILP_ITEMS) {
await prisma.payslipItem.create({
data: { orgId: org.id, ...item },
})
}
console.log(` ✅ 薪酬模版已创建 (10项)`)
// 8. 创建员工 + 合同
for (let i = 0; i < orgConfig.employees.length; i++) {
const e = orgConfig.employees[i]
const emp = await prisma.employee.create({
data: {
orgId: org.id,
name: e.name,
department: e.dept,
hireDate: new Date(e.hireDate),
monthlySalary: encrypt(String(e.salary)),
phone: e.phone,
idCardNumber: encrypt(e.idCard),
gender: e.gender,
socialInsBase: e.socialBase,
housingFundBase: e.housingBase,
specialDeduction: e.specialDeduction,
bankName: e.bank,
bankAccount: encrypt(e.account),
emergencyContact: e.emergency,
emergencyPhone: e.emergencyPhone,
address: e.address,
isPregnant: e.pregnant || false,
createdBy: admin.id,
},
})
// 创建合同
const startDate = new Date(e.hireDate)
const endDate = e.contractType === 'FIXED'
? new Date(startDate.getFullYear() + e.years, startDate.getMonth(), startDate.getDate() - 1)
: null
await prisma.laborContract.create({
data: {
orgId: org.id,
employeeId: emp.id,
signDate: new Date(e.hireDate),
startDate,
endDate,
contractType: e.contractType as any,
signMethod: 'PAPER',
contractYears: e.years,
probationMonths: e.probation,
probationSalary: e.probationSalary,
createdBy: admin.id,
},
})
console.log(` ✅ 员工 ${i + 1}/${orgConfig.employees.length}: ${e.name} - ${e.dept} - ¥${e.salary}/月`)
}
// 9. 生成 1-6 月历史工资条
console.log(` 📄 生成历史工资条...`)
const socialConfig = await prisma.socialInsuranceConfig.findFirst({ where: { orgId: org.id, isCurrent: true } })
const housingConfig = await prisma.housingFundConfig.findFirst({ where: { orgId: org.id, isCurrent: true } })
const allEmployees = await prisma.employee.findMany({ where: { orgId: org.id } })
for (const emp of allEmployees) {
const hireYear = emp.hireDate.getFullYear()
if (hireYear > 2026) continue
const hireMonth = hireYear === 2026 ? emp.hireDate.getMonth() + 1 : 1
let ytdIncome = 0, ytdSocialEmp = 0, ytdHousingEmp = 0, ytdTaxDeducted = 0
for (let m = 1; m <= 6; m++) {
if (m < hireMonth) continue
const monthStr = `2026-${String(m).padStart(2, '0')}`
const baseSalary = emp.socialInsBase || 0
const social = calcSocial(emp.socialInsBase || baseSalary, socialConfig)
const housing = calcHousing(emp.housingFundBase || baseSalary, housingConfig || socialConfig)
const totalPay = baseSalary
const specialDeduction = emp.specialDeduction * m
ytdIncome += totalPay
ytdSocialEmp += social.socialEmp
ytdHousingEmp += housing.housingEmp
const ytdTaxableIncome = Math.max(0, ytdIncome - 5000 * m - ytdSocialEmp - ytdHousingEmp - specialDeduction)
const ytdTax = calcTax(ytdTaxableIncome)
const monthTax = Math.max(0, Math.round((ytdTax - ytdTaxDeducted) * 100) / 100)
ytdTaxDeducted += monthTax
const netPay = Math.round((totalPay - social.socialEmp - housing.housingEmp - monthTax) * 100) / 100
await prisma.payslip.create({
data: {
org: { connect: { id: org.id } },
employee: { connect: { id: emp.id } },
month: monthStr,
baseSalary,
overtimePay: 0,
allowance: 0,
deduction: 0,
bonus: 0,
totalPay,
socialEmp: social.socialEmp,
housingEmp: housing.housingEmp,
tax: monthTax,
netPay,
ytdIncome,
ytdTaxDeducted,
ytdSocialEmp,
ytdHousingEmp,
status: 'PUBLISHED',
publishedAt: new Date(`${monthStr}-10T10:00:00Z`),
confirmedAt: new Date(`${monthStr}-12T10:00:00Z`),
},
})
}
}
console.log(` ✅ 历史工资条已生成`)
}
// ========== 主函数 ==========
async function main() {
console.log('\n🚀 开始创建多企业测试数据...\n')
for (let i = 0; i < ORGS.length; i++) {
console.log(`\n--- [${i + 1}/${ORGS.length}] 创建企业: ${ORGS[i].name} ---`)
await createOrg(ORGS[i])
}
console.log('\n===== 多企业测试数据创建完成 =====\n')
console.log('可用登录账号:')
console.log('┌────────────────────────────┬──────────────┬──────────┐')
console.log('│ 企业名称 │ 管理员手机号 │ 密码 │')
console.log('├────────────────────────────┼──────────────┼──────────┤')
for (const org of ORGS) {
console.log(`${org.name.padEnd(26)}${org.adminPhone} │ 12345678 │`)
}
console.log('└────────────────────────────┴──────────────┴──────────┘')
}
main()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})