diff --git a/routes/employees.js b/routes/employees.js index d12aea5..3ebb39a 100644 --- a/routes/employees.js +++ b/routes/employees.js @@ -198,6 +198,14 @@ async function update(req, res) { params.push(id) await pool.query(`UPDATE employees SET ${sets.join(', ')} WHERE id = ?`, params) + // 部门联动:员工部门变更时同步更新关联用户的部门 + if (req.body.department !== undefined) { + const [[dept]] = await pool.query('SELECT id FROM departments WHERE description = ?', [req.body.department]) + if (dept) { + await pool.query('UPDATE users SET department_id = ? WHERE employee_id = ?', [dept.id, id]) + } + } + const [rows] = await pool.query('SELECT * FROM employees WHERE id = ?', [id]) res.json({ code: 0, message: 'ok', data: rows[0] }) } catch (e) { diff --git a/routes/users.js b/routes/users.js index ed9212d..e2c5704 100644 --- a/routes/users.js +++ b/routes/users.js @@ -308,7 +308,7 @@ async function update(req, res) { const fields = ['username', 'department_id', 'employee_id', 'is_active'] try { - const [existing] = await pool.query('SELECT id, department_id, is_active FROM users WHERE id = ?', [id]) + const [existing] = await pool.query('SELECT id, department_id, is_active, employee_id FROM users WHERE id = ?', [id]) if (existing.length === 0) { return res.status(404).json({ code: 404, message: '用户不存在' }) } @@ -358,6 +358,14 @@ async function update(req, res) { params.push(id) await pool.query(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`, params) + // 部门联动:用户部门变更时同步更新关联员工的部门 + if (req.body.department_id !== undefined && existing[0].employee_id) { + const [[dept]] = await pool.query('SELECT description FROM departments WHERE id = ?', [req.body.department_id]) + if (dept) { + await pool.query('UPDATE employees SET department = ? WHERE id = ?', [dept.description, existing[0].employee_id]) + } + } + const [rows] = await pool.query( `${USER_LIST_SQL} WHERE u.id = ?`, [id]