import { Router } from 'express'
import { getDb } from '../db.js'
import { requireAuth, canAccessCustomer, writeLog } from '../auth.js'
import { clientIp, parseJson } from '../utils.js'
const router = Router()
router.use(requireAuth)
/** 检查当前用户能否访问某客户(内部) */
async function accessibleCustomer(user, id) {
const db = getDb()
const row = (await db.query('SELECT * FROM customers WHERE id=$1', [id])).rows[0]
if (!row || row.deleted_at) return { error: 404, message: '客户不存在' }
if (!(await canAccessCustomer(user, row))) return { error: 403, message: '无权访问该客户' }
return { row }
}
/** GET /api/customers/:id/followups —— 客户的跟进历史 */
router.get('/customers/:id/followups', async (req, res, next) => {
try {
const chk = await accessibleCustomer(req.user, req.params.id)
if (chk.error) return res.status(chk.error).json({ message: chk.message })
const r = await getDb().query(
'SELECT * FROM follow_ups WHERE customer_id=$1 ORDER BY follow_at DESC, id DESC',
[req.params.id])
res.json({ list: r.rows })
} catch (err) { next(err) }
})
/** POST /api/customers/:id/followups —— 新增跟进 */
router.post('/customers/:id/followups', async (req, res, next) => {
try {
const { method, content, follow_at } = req.body || {}
if (!content || !String(content).trim()) return res.status(400).json({ message: '跟进内容必填' })
const chk = await accessibleCustomer(req.user, req.params.id)
if (chk.error) return res.status(chk.error).json({ message: chk.message })
const db = getDb()
const at = follow_at || new Date().toISOString()
const r = await db.query(
`INSERT INTO follow_ups (customer_id,author_id,author_name,method,content,follow_at,created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
[req.params.id, req.user.id, req.user.display_name, method || 'phone',
String(content).trim(), at, new Date().toISOString()])
// 更新客户最后跟进时间(触发公海回收计时)
await db.query('UPDATE customers SET last_follow_at=$1, updated_at=$1 WHERE id=$2', [at, req.params.id])
await writeLog({ user: req.user, action: 'followup', targetType: 'customer',
targetId: req.params.id, targetName: chk.row.name,
detail: { method }, ip: clientIp(req) })
res.json({ message: '跟进已记录', followup: r.rows[0] })
} catch (err) { next(err) }
})
/** DELETE /api/followups/:id —— 删除跟进(作者本人或管理权限)*/
router.delete('/followups/:id', async (req, res, next) => {
try {
const db = getDb()
const row = (await db.query('SELECT * FROM follow_ups WHERE id=$1', [req.params.id])).rows[0]
if (!row) return res.status(404).json({ message: '跟进记录不存在' })
if (row.author_id !== req.user.id && !req.user.permissions.includes('manage')) {
return res.status(403).json({ message: '只能删除自己写的跟进' })
}
await db.query('DELETE FROM follow_ups WHERE id=$1', [req.params.id])
await writeLog({ user: req.user, action: 'followup_delete', targetType: 'followup',
targetId: req.params.id, ip: clientIp(req) })
res.json({ message: '跟进已删除' })
} catch (err) { next(err) }
})
export default router