← back to Norma
app/api/scheduled/[id]/route.ts
76 lines
import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';
import { auditLog } from '@/lib/audit';
/**
* DELETE /api/scheduled/[id]
* Cancel a scheduled dispatch. Only works if status is still 'scheduled'.
*/
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
try {
const { id } = await params;
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(id)) {
return NextResponse.json({ error: 'Invalid ID format' }, { status: 400 });
}
const result = await query(
`UPDATE scheduled_dispatches
SET status = 'cancelled'
WHERE id = $1 AND status = 'scheduled'
RETURNING *`,
[id],
);
if (result.rows.length === 0) {
return NextResponse.json(
{ error: 'Scheduled dispatch not found or already processed' },
{ status: 404 },
);
}
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || undefined;
await auditLog('scheduled.cancelled', 'scheduled_dispatches', id, {
cancelled_by: auth.username,
platform: result.rows[0].platform,
}, ip);
return NextResponse.json({ cancelled: result.rows[0] });
} catch (err) {
console.error('[api/scheduled/[id]] error:', (err as Error).message);
return NextResponse.json({ error: 'Failed to cancel scheduled dispatch' }, { status: 500 });
}
}
/**
* GET /api/scheduled/[id]
* Fetch a single scheduled dispatch by ID.
*/
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
try {
const { id } = await params;
const { rows } = await query(`SELECT * FROM scheduled_dispatches WHERE id = $1`, [id]);
if (rows.length === 0) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ item: rows[0] });
} catch (err) {
console.error('[api/scheduled/[id]] error:', (err as Error).message);
return NextResponse.json({ error: 'Failed to fetch scheduled dispatch' }, { status: 500 });
}
}