Files
backmanager-server/routes/employees.js

250 lines
7.7 KiB
JavaScript
Raw Normal View History

2026-06-22 20:48:29 +08:00
// routes/employees.js —— 员工管理 CRUD
const { pool } = require('../db')
2026-06-24 22:44:14 +08:00
const { getDataScope } = require('../middleware/permissions')
2026-06-22 20:48:29 +08:00
2026-06-25 21:18:13 +08:00
// 格式化日期为 YYYY-MM-DD
function formatDate(dateStr) {
if (!dateStr) return null
if (typeof dateStr === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
return dateStr // 已经是正确格式
}
try {
const date = new Date(dateStr)
if (isNaN(date.getTime())) return null
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
} catch {
return null
}
}
2026-06-22 20:48:29 +08:00
function pagination(query) {
const page = Math.max(Number(query.page) || 1, 1)
const pageSize = Math.min(Math.max(Number(query.pageSize) || 10, 1), 100)
const offset = (page - 1) * pageSize
return { page, pageSize, offset }
}
// GET /api/employees —— 列表
async function list(req, res) {
try {
const { page, pageSize, offset } = pagination(req.query)
2026-06-25 21:18:13 +08:00
const { id, name, status, department } = req.query
2026-06-22 20:48:29 +08:00
let where = 'WHERE 1=1'
const params = []
2026-06-24 22:44:14 +08:00
// 数据范围过滤(部门隔离)
const scope = getDataScope(req.user, 'employees')
if (scope.deny) {
return res.status(403).json({ code: 403, message: '无权访问此资源' })
}
if (scope.where) {
where += ' AND ' + scope.where
params.push(...scope.values)
}
2026-06-25 21:18:13 +08:00
if (id) {
where += ' AND id = ?'
params.push(Number(id))
}
2026-06-22 20:48:29 +08:00
if (name) {
where += ' AND name LIKE ?'
params.push(`%${name}%`)
}
if (status !== undefined && status !== '') {
where += ' AND status = ?'
params.push(Number(status))
}
2026-06-25 21:18:13 +08:00
if (department) {
where += ' AND department LIKE ?'
params.push(`%${department}%`)
}
2026-06-22 20:48:29 +08:00
const [[{ total }]] = await pool.query(
`SELECT COUNT(*) AS total FROM employees ${where}`,
params
)
const [rows] = await pool.query(
`SELECT * FROM employees ${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
[...params, pageSize, offset]
)
res.json({
code: 0,
message: 'ok',
data: {
list: rows,
total,
page,
pageSize,
totalPages: Math.ceil(total / pageSize),
},
})
} catch (e) {
console.error('[employees list] error:', e)
res.status(500).json({ code: 500, message: e.message })
}
}
// GET /api/employees/:id —— 详情
async function detail(req, res) {
try {
2026-06-24 22:44:14 +08:00
let sql = 'SELECT * FROM employees WHERE id = ?'
const params = [req.params.id]
const scope = getDataScope(req.user, 'employees')
if (scope.deny) {
return res.status(403).json({ code: 403, message: '无权访问此资源' })
}
if (scope.where) {
sql += ' AND ' + scope.where
params.push(...scope.values)
}
const [rows] = await pool.query(sql, params)
2026-06-22 20:48:29 +08:00
if (rows.length === 0) {
return res.status(404).json({ code: 404, message: '员工不存在' })
}
res.json({ code: 0, message: 'ok', data: rows[0] })
} catch (e) {
console.error('[employees detail] error:', e)
res.status(500).json({ code: 500, message: e.message })
}
}
// POST /api/employees —— 新增
async function create(req, res) {
const {
name, gender, age, education, department,
entry_date, position, salary, phone, email, status, remark,
} = req.body || {}
if (!name) {
return res.status(400).json({ code: 400, message: '员工姓名必填' })
}
try {
const [result] = await pool.query(
`INSERT INTO employees (name, gender, age, education, department, entry_date, position, salary, phone, email, status, remark)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[name,
gender || null,
age !== undefined ? age : null,
education || null,
department || null,
2026-06-25 21:18:13 +08:00
formatDate(entry_date),
2026-06-22 20:48:29 +08:00
position || null,
salary !== undefined ? salary : null,
phone || null,
email || null,
status !== undefined ? status : 1,
remark || null]
)
const [rows] = await pool.query('SELECT * FROM employees WHERE id = ?', [result.insertId])
res.json({ code: 0, message: 'ok', data: rows[0] })
} catch (e) {
console.error('[employees create] error:', e)
res.status(500).json({ code: 500, message: e.message })
}
}
// PUT /api/employees/:id —— 更新
async function update(req, res) {
const { id } = req.params
const fields = [
'name', 'gender', 'age', 'education', 'department',
'entry_date', 'position', 'salary', 'phone', 'email', 'status', 'remark',
]
try {
2026-06-24 22:44:14 +08:00
// 确认记录存在且在数据范围内
let checkSql = 'SELECT id FROM employees WHERE id = ?'
const checkParams = [id]
const scope = getDataScope(req.user, 'employees')
if (scope.deny) {
return res.status(403).json({ code: 403, message: '无权访问此资源' })
}
if (scope.where) {
checkSql += ' AND ' + scope.where
checkParams.push(...scope.values)
}
const [existing] = await pool.query(checkSql, checkParams)
2026-06-22 20:48:29 +08:00
if (existing.length === 0) {
2026-06-24 22:44:14 +08:00
return res.status(404).json({ code: 404, message: '员工不存在或无权操作' })
2026-06-22 20:48:29 +08:00
}
const sets = []
const params = []
for (const f of fields) {
if (req.body[f] !== undefined) {
sets.push(`${f} = ?`)
2026-06-25 21:18:13 +08:00
// 日期字段需要格式化
if (f === 'entry_date') {
params.push(formatDate(req.body[f]))
} else {
params.push(req.body[f])
}
2026-06-22 20:48:29 +08:00
}
}
if (sets.length === 0) {
return res.status(400).json({ code: 400, message: '没有需要更新的字段' })
}
params.push(id)
await pool.query(`UPDATE employees SET ${sets.join(', ')} WHERE id = ?`, params)
2026-06-25 21:18:13 +08:00
// 同步 department 到关联的 users 表
if (req.body.department !== undefined) {
await pool.query('UPDATE users SET department = ? WHERE employee_id = ?', [req.body.department, id])
}
2026-06-22 20:48:29 +08:00
const [rows] = await pool.query('SELECT * FROM employees WHERE id = ?', [id])
res.json({ code: 0, message: 'ok', data: rows[0] })
} catch (e) {
console.error('[employees update] error:', e)
res.status(500).json({ code: 500, message: e.message })
}
}
// DELETE /api/employees/:id —— 删除
async function remove(req, res) {
const { id } = req.params
try {
2026-06-24 22:44:14 +08:00
let checkSql = 'SELECT id FROM employees WHERE id = ?'
const checkParams = [id]
const scope = getDataScope(req.user, 'employees')
if (scope.deny) {
return res.status(403).json({ code: 403, message: '无权访问此资源' })
}
if (scope.where) {
checkSql += ' AND ' + scope.where
checkParams.push(...scope.values)
}
const [existing] = await pool.query(checkSql, checkParams)
2026-06-22 20:48:29 +08:00
if (existing.length === 0) {
2026-06-24 22:44:14 +08:00
return res.status(404).json({ code: 404, message: '员工不存在或无权操作' })
2026-06-22 20:48:29 +08:00
}
2026-06-25 21:18:13 +08:00
// 禁止删除自己关联的员工
const [selfCheck] = await pool.query('SELECT id FROM users WHERE employee_id = ? AND id = ?', [id, req.user.id])
if (selfCheck.length > 0) {
return res.status(400).json({ code: 400, message: '不能删除自己的员工账号' })
}
// 同步删除关联的用户账号
await pool.query('DELETE FROM users WHERE employee_id = ?', [id])
2026-06-22 20:48:29 +08:00
await pool.query('DELETE FROM employees WHERE id = ?', [id])
res.json({ code: 0, message: 'ok' })
} catch (e) {
console.error('[employees delete] error:', e)
2026-06-25 21:18:13 +08:00
if (e.code === 'ER_ROW_IS_REFERENCED_2') {
return res.status(400).json({ code: 400, message: '该员工被合同或售后记录引用,无法删除' })
}
2026-06-22 20:48:29 +08:00
res.status(500).json({ code: 500, message: e.message })
}
}
module.exports = { list, detail, create, update, remove }