59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { cookies } from 'next/headers'
|
|
import db from '@/lib/db'
|
|
import { getSession } from '@/lib/auth'
|
|
import { checkPermission } from '@/lib/permissions'
|
|
|
|
|
|
|
|
const UPDATABLE_FIELDS = [
|
|
'device_type', 'device_purpose', 'room', 'rack_position', 'status',
|
|
'manufacturer', 'device_model', 'warranty_date',
|
|
]
|
|
|
|
export async function POST(request: Request) {
|
|
const session = await getSession()
|
|
if (!session) return NextResponse.json({ error: '未授权' }, { status: 401 })
|
|
if (!checkPermission(session.role, 'assets:update')) {
|
|
return NextResponse.json({ error: '权限不足' }, { status: 403 })
|
|
}
|
|
|
|
try {
|
|
const body = await request.json()
|
|
const { ids, fields } = body as { ids: number[]; fields: Record<string, unknown> }
|
|
|
|
if (!Array.isArray(ids) || ids.length === 0) {
|
|
return NextResponse.json({ error: '请选择设备' }, { status: 400 })
|
|
}
|
|
if (!fields || typeof fields !== 'object' || Object.keys(fields).length === 0) {
|
|
return NextResponse.json({ error: '请指定要修改的字段' }, { status: 400 })
|
|
}
|
|
|
|
const updates: string[] = []
|
|
const values: unknown[] = []
|
|
for (const [key, value] of Object.entries(fields)) {
|
|
if (!UPDATABLE_FIELDS.includes(key)) continue
|
|
updates.push(`${key} = ?`)
|
|
values.push(value === '' ? null : value)
|
|
}
|
|
|
|
if (updates.length === 0) {
|
|
return NextResponse.json({ error: '没有可更新的有效字段' }, { status: 400 })
|
|
}
|
|
|
|
updates.push("updated_at = datetime('now', '+8 hours')")
|
|
|
|
const placeholders = ids.map(() => '?').join(', ')
|
|
const stmt = db.prepare(`UPDATE assets SET ${updates.join(', ')} WHERE id IN (${placeholders})`)
|
|
const result = stmt.run(...values, ...ids)
|
|
|
|
db.prepare(`INSERT INTO audit_logs (user_id, action, entity_type, details, ip_address) VALUES (?, 'batch_update', 'asset', ?, ?)`)
|
|
.run(session.userId, JSON.stringify({ ids, fields }), null)
|
|
|
|
return NextResponse.json({ updated: result.changes })
|
|
} catch (e) {
|
|
const msg = e instanceof Error ? e.message : '批量更新失败'
|
|
return NextResponse.json({ error: msg }, { status: 500 })
|
|
}
|
|
}
|