63 lines
2.8 KiB
TypeScript
63 lines
2.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { parseBody, documentExtractionSchema } from "@/src/validation/0pt-schemas";
|
|
import { documentExtractionService } from "@/src/services/document-extraction-service";
|
|
import { assertTenantMatchesVerified, resolveDocumentActor } from "@/src/http/tenant-guard";
|
|
|
|
export async function POST(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
|
try {
|
|
const { documentId } = await params;
|
|
const __raw = await request.json();
|
|
const __parsed = parseBody(documentExtractionSchema, __raw);
|
|
if (!__parsed.ok) {
|
|
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
|
}
|
|
const body = __parsed.data;
|
|
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
|
if (tenantGuard) return tenantGuard;
|
|
const actor = resolveDocumentActor(request, body.actor_id);
|
|
if (actor.response) return actor.response;
|
|
if (!actor.actorId || !body.model_id) {
|
|
return NextResponse.json({ error: "actor and model_id are required" }, { status: 400 });
|
|
}
|
|
const result = await documentExtractionService.extractDocument(documentId, {
|
|
tenant_id: body.tenant_id,
|
|
project_id: body.project_id,
|
|
actor_id: actor.actorId,
|
|
correlation_id: body.correlation_id ?? crypto.randomUUID(),
|
|
model_id: body.model_id,
|
|
});
|
|
return NextResponse.json(result, { status: 201 });
|
|
} catch (error: unknown) {
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
if (/not configured/i.test(message)) {
|
|
return NextResponse.json({ error: message }, { status: 501 });
|
|
}
|
|
if (/^Policy denied/i.test(message)) {
|
|
return NextResponse.json({ error: message }, { status: 403 });
|
|
}
|
|
if (/^Policy requires approval/i.test(message)) {
|
|
return NextResponse.json({ error: message }, { status: 409 });
|
|
}
|
|
const status = /not found/i.test(message) ? 404 : 400;
|
|
return NextResponse.json({ error: message }, { status });
|
|
}
|
|
}
|
|
|
|
export async function GET(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
|
try {
|
|
const { documentId } = await params;
|
|
const { searchParams } = new URL(request.url);
|
|
const tenantId = searchParams.get("tenant_id");
|
|
if (!tenantId) {
|
|
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
|
}
|
|
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
|
if (tenantGuard) return tenantGuard;
|
|
const extractions = await documentExtractionService.listExtractionsForDocument(documentId, tenantId);
|
|
return NextResponse.json(extractions);
|
|
} catch (error: unknown) {
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
return NextResponse.json({ error: message }, { status: 404 });
|
|
}
|
|
}
|