66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getDb } from '@/lib/db'
|
|
import { initDatabase } from '@/lib/db-schema'
|
|
import { getCurrentUser } from '@/lib/auth'
|
|
import { hasPermission } from '@/lib/permissions'
|
|
import { writeAuditLog, getClientIP } from '@/lib/audit'
|
|
|
|
export async function PUT(request: NextRequest) {
|
|
try {
|
|
initDatabase()
|
|
const user = await getCurrentUser()
|
|
if (!user) return NextResponse.json({ error: '未登录' }, { status: 401 })
|
|
if (!hasPermission(user, 'tickets:edit')) return NextResponse.json({ error: '权限不足' }, { status: 403 })
|
|
|
|
const body = await request.json()
|
|
const updates: Array<{ id: number; fault_category?: string; current_status?: string; counted_in_sla?: number }> = body.updates || []
|
|
|
|
if (!Array.isArray(updates) || updates.length === 0) {
|
|
return NextResponse.json({ error: '无更新数据' }, { status: 400 })
|
|
}
|
|
|
|
const db = getDb()
|
|
const allowedFields = ['fault_category', 'current_status', 'counted_in_sla']
|
|
let updated = 0
|
|
|
|
for (const item of updates) {
|
|
if (!item.id) continue
|
|
const fields: string[] = []
|
|
const values: unknown[] = []
|
|
|
|
for (const f of allowedFields) {
|
|
if (f in item && item[f as keyof typeof item] !== undefined) {
|
|
fields.push(`${f} = ?`)
|
|
values.push(item[f as keyof typeof item])
|
|
}
|
|
}
|
|
|
|
if (fields.length === 0) continue
|
|
fields.push("updated_at = datetime('now', '+8 hours')")
|
|
fields.push('updated_by = ?')
|
|
values.push(user.id)
|
|
values.push(item.id)
|
|
|
|
const result = db.prepare(`UPDATE tickets SET ${fields.join(', ')} WHERE id = ?`).run(...values)
|
|
updated += result.changes
|
|
}
|
|
|
|
if (updated > 0) {
|
|
writeAuditLog({
|
|
userId: user.id,
|
|
apiKeyId: null,
|
|
action: 'batch_update',
|
|
entityType: 'ticket',
|
|
entityId: null,
|
|
details: { updated, total: updates.length },
|
|
ipAddress: getClientIP(request),
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({ updated, total: updates.length })
|
|
} catch (e) {
|
|
const msg = e instanceof Error ? e.message : '批量更新失败'
|
|
return NextResponse.json({ error: msg }, { status: 500 })
|
|
}
|
|
}
|