import type ExcelJS from 'exceljs' import { SALARY_ROLES } from './performance-salary-roles' import { getSalaryTemplate, getPositionSalaryTemplate, isSalaryMonth, SALARY_TEMPLATE_BLANK_ROWS, type SalaryTemplate } from './performance-salary-templates' import { performancePositions, performanceVersionLabel, positionAtMonth, sharedSalaryGradeLabel, type SalaryPosition } from './salary-position-contract' import { SALARY_XLSX_MIME, type SalaryDetails, type SalaryDetailRow } from './performance-salary-details-contract' export function salaryExportFileName(month: string) { if (!isSalaryMonth(month)) throw new Error('请选择有效月份后重试。') return `绩效薪资模板_${month}.xlsx` } export async function buildSalaryTemplateWorkbook(month: string, positions?: SalaryPosition[]) { salaryExportFileName(month) const monthlyPositions = positions?.map(position => positionAtMonth(position, month)) ?? [] const configured = performancePositions(monthlyPositions) const sections = SALARY_ROLES.flatMap(role => { const schemes = configured.filter(position => position.salaryRole === role.key) if (schemes.length) return schemes.map(position => ({ template: getPositionSalaryTemplate(position, month), versionLabel: position.performanceVersion && performanceVersionLabel(position.performanceVersion), gradeLabel: sharedSalaryGradeLabel(position, month), })) const position = monthlyPositions.find(position => position.salaryRole === role.key && !position.personnelPositionId) return [{ template: position ? getPositionSalaryTemplate({ ...position, dimensions: [] }, month) : getSalaryTemplate(role.key, month), versionLabel: undefined, gradeLabel: undefined }] }) return buildWorkbook(month, sections) } export async function buildSalaryDetailsWorkbook(details: SalaryDetails) { if (!isSalaryMonth(details.displayMonth)) throw new Error('请选择有效月份后重试。') const sections = SALARY_ROLES.flatMap(role => details.positionGroups .filter(group => group.position.salaryRole === role.key && group.rows.length > 0) .map(({ position, template, rows }) => ({ template, rows, versionLabel: position.performanceVersion ? performanceVersionLabel(position.performanceVersion) : rows.some(row => row.performanceMatch === 'unmatched') ? '未匹配绩效方案' : undefined, gradeLabel: sharedSalaryGradeLabel(position, details.displayMonth), }))) if (!sections.length) throw new Error('该月暂无可导出的薪资明细。') return buildWorkbook(details.displayMonth, sections) } type WorkbookSection = { template: SalaryTemplate versionLabel?: string gradeLabel?: string rows?: SalaryDetailRow[] } async function buildWorkbook(month: string, sections: WorkbookSection[]) { const { default: Excel } = await import('exceljs') const workbook = new Excel.Workbook() workbook.creator = '品牌中心' const border: Partial = { top: { style: 'thin', color: { argb: 'FFE2E8F0' } }, bottom: { style: 'thin', color: { argb: 'FFE2E8F0' } }, left: { style: 'thin', color: { argb: 'FFE2E8F0' } }, right: { style: 'thin', color: { argb: 'FFE2E8F0' } }, } const used = new Set() for (const { template, versionLabel, gradeLabel, rows } of sections) { const baseName = template.title.replace(/[\\/*?:\[\]\x00-\x1f]/g, ' ').trim().replace(/^'+|'+$/g, '').trim() || '岗位' let sheetName = baseName.slice(0, 31).replace(/'+$/g, ''), counter = 1 while (used.has(sheetName.toLocaleLowerCase()) || sheetName.toLocaleLowerCase() === 'history') { const suffix = `_${++counter}` sheetName = `${baseName.slice(0, 31 - suffix.length)}${suffix}` } used.add(sheetName.toLocaleLowerCase()) const sheet = workbook.addWorksheet(sheetName) const size = template.columns.length const headerRow = template.grouped ? 3 : 2 const lastRow = headerRow + (rows?.length ?? SALARY_TEMPLATE_BLANK_ROWS) sheet.mergeCells(1, 1, 1, size) const title = sheet.getCell(1, 1) title.value = [`${month} ${template.title}薪资明细`, gradeLabel, versionLabel].filter(Boolean).join(' · ') title.font = { name: '微软雅黑', size: 14, bold: true, color: { argb: 'FF101828' } } title.alignment = { vertical: 'middle', horizontal: 'left' } sheet.getRow(1).height = 34 if (template.grouped) { let start = 1 for (const group of template.groups) { const end = start + group.columns.length - 1 if (end > start) sheet.mergeCells(2, start, 2, end) sheet.getCell(2, start).value = group.label start = end + 1 } sheet.getRow(2).height = 28 } template.columns.forEach((column, index) => { sheet.getColumn(index + 1).width = Math.round(column.width / 7) sheet.getCell(headerRow, index + 1).value = column.label }) sheet.getRow(headerRow).height = 64 for (let row = 2; row <= lastRow; row += 1) { if (row > headerRow) sheet.getRow(row).height = 30 for (let col = 1; col <= size; col += 1) { const cell = sheet.getCell(row, col) cell.border = border cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true } cell.font = { name: '微软雅黑', size: 11, color: { argb: 'FF344054' }, bold: row <= headerRow } if (row <= headerRow) cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: row < headerRow ? 'FFE6EDF5' : 'FFF8FAFC' } } else { const { kind, key } = template.columns[col - 1] // Raw delivery rates use percentage points (100 means 100%), not fractions. cell.numFmt = kind === 'money' ? '#,##0.00' : kind === 'percent' ? rows ? '0.00%' : '0.00"%"' : key === 'performanceCoefficient' || key.endsWith('RawValue') || key.endsWith('Score') ? '0.00' : kind === 'number' ? '0.##' : '@' const value = rows?.[row - headerRow - 1].values[key] if (value !== null && value !== undefined && value !== '') { if (kind === 'text') cell.value = String(value) else { const numeric = Number(value) if (!Number.isFinite(numeric)) throw new Error('薪资数据格式异常,请重新读取后重试。') cell.value = kind === 'percent' ? numeric / 100 : numeric } } } } } sheet.views = [{ state: 'frozen', xSplit: 1, ySplit: headerRow, topLeftCell: `B${headerRow + 1}` }] sheet.pageSetup = { orientation: 'landscape', printTitlesRow: `1:${headerRow}` } sheet.pageSetup.printArea = `A1:${sheet.getColumn(size).letter}${lastRow}` } return workbook } export async function saveSalaryTemplateWorkbook(month: string, positions?: SalaryPosition[]) { const workbook = await buildSalaryTemplateWorkbook(month, positions) const buffer = await workbook.xlsx.writeBuffer() const blob = new Blob([buffer], { type: SALARY_XLSX_MIME }) if (typeof URL.createObjectURL !== 'function') throw new Error('当前浏览器无法下载文件,请更换浏览器后重试。') const url = URL.createObjectURL(blob) const anchor = document.createElement('a') anchor.href = url anchor.download = salaryExportFileName(month) anchor.style.display = 'none' document.body.appendChild(anchor) try { anchor.click() } finally { anchor.remove() window.setTimeout(() => URL.revokeObjectURL(url), 1000) } }