import { Router } from 'express'
import { getDb } from '../db.js'
import { requireAuth, requireManage, visiblePoolIds, writeLog } from '../auth.js'
import { uid, now, clientIp } from '../utils.js'
const router = Router()
router.use(requireAuth)
/** 池 + 公海客户数 */
async function poolsWithCount(onlyIds = null) {
const db = getDb()
let sql = `SELECT p.*, (SELECT COUNT(*)::int FROM customers c
WHERE c.owner_id IS NULL AND c.pool_id = p.id) AS customer_count
FROM pools p`
const params = []
if (onlyIds !== null) {
if (!onlyIds.length) return []
sql += ` WHERE p.id = ANY($1::text[])`
params.push(onlyIds)
}
sql += ` ORDER BY p.sort_order ASC, p.created_at ASC`
const r = await db.query(sql, params)
return r.rows
}
/** GET /api/pools/mine —— 当前用户可见的池(供公海切换/导入选池) */
router.get('/mine', async (req, res, next) => {
try {
const ids = await visiblePoolIds(req.user)
const list = await poolsWithCount(ids) // null=全部
res.json({ list, all: ids === null })
} catch (err) { next(err) }
})
// ==================== 以下为管理接口 ====================
/** GET /api/pools —— 全部池(管理) */
router.get('/', requireManage, async (_req, res, next) => {
try { res.json({ list: await poolsWithCount() }) } catch (err) { next(err) }
})
/** POST /api/pools —— 新建池 */
router.post('/', requireManage, async (req, res, next) => {
try {
const { name, description, color, sort_order } = req.body || {}
if (!name || !String(name).trim()) return res.status(400).json({ message: '池名称必填' })
const id = 'pool_' + uid()
await getDb().query(
`INSERT INTO pools (id,name,description,color,sort_order,enabled,created_at)
VALUES ($1,$2,$3,$4,$5,true,$6)`,
[id, String(name).trim(), description || null, color || '#3b82f6', Number(sort_order) || 0, now()])
await writeLog({ user: req.user, action: 'pool_create', targetType: 'pool', targetId: id,
targetName: name, detail: {}, ip: clientIp(req) })
res.json({ message: '资源池已创建', id })
} catch (err) {
if (String(err.message).includes('unique') || String(err.code) === '23505') {
return res.status(409).json({ message: '池名称已存在' })
}
next(err)
}
})
/** PUT /api/pools/:id —— 编辑池 */
router.put('/:id', requireManage, async (req, res, next) => {
try {
const { name, description, color, sort_order, enabled } = req.body || {}
const db = getDb()
const cur = (await db.query('SELECT * FROM pools WHERE id=$1', [req.params.id])).rows[0]
if (!cur) return res.status(404).json({ message: '资源池不存在' })
await db.query(
`UPDATE pools SET name=$1,description=$2,color=$3,sort_order=$4,enabled=$5 WHERE id=$6`,
[name ?? cur.name, description ?? cur.description, color ?? cur.color,
Number(sort_order ?? cur.sort_order), enabled !== false, req.params.id])
await writeLog({ user: req.user, action: 'pool_edit', targetType: 'pool', targetId: req.params.id,
targetName: name || cur.name, detail: {}, ip: clientIp(req) })
res.json({ message: '已保存' })
} catch (err) { next(err) }
})
/** DELETE /api/pools/:id —— 删除池(客户迁回默认池) */
router.delete('/:id', requireManage, async (req, res, next) => {
try {
if (req.params.id === 'pool_default') {
return res.status(400).json({ message: '默认公海池不可删除' })
}
const db = getDb()
const cur = (await db.query('SELECT * FROM pools WHERE id=$1', [req.params.id])).rows[0]
if (!cur) return res.status(404).json({ message: '资源池不存在' })
// 该池客户迁回默认池(含已被认领的,保留来源池语义)
await db.query(`UPDATE customers SET pool_id='pool_default' WHERE pool_id=$1`, [req.params.id])
await db.query('DELETE FROM user_pools WHERE pool_id=$1', [req.params.id])
await db.query('DELETE FROM pools WHERE id=$1', [req.params.id])
await writeLog({ user: req.user, action: 'pool_delete', targetType: 'pool', targetId: req.params.id,
targetName: cur.name, detail: {}, ip: clientIp(req) })
res.json({ message: '资源池已删除,其客户已迁回默认池' })
} catch (err) { next(err) }
})
export default router