|
| 1 | +import { |
| 2 | + AnalyzeExpenseCommand, |
| 3 | + type ExpenseDocument, |
| 4 | + GetExpenseAnalysisCommand, |
| 5 | + StartExpenseAnalysisCommand, |
| 6 | + TextractClient, |
| 7 | +} from '@aws-sdk/client-textract' |
| 8 | +import { createLogger } from '@sim/logger' |
| 9 | +import type { NextRequest } from 'next/server' |
| 10 | +import { NextResponse } from 'next/server' |
| 11 | +import { textractAnalyzeExpenseContract } from '@/lib/api/contracts/tools/media/document-parse' |
| 12 | +import { getValidationErrorMessage, parseRequest } from '@/lib/api/server' |
| 13 | +import { checkInternalAuth } from '@/lib/auth/hybrid' |
| 14 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 15 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 16 | +import { |
| 17 | + mapTextractSdkError, |
| 18 | + parseS3Uri, |
| 19 | + pollTextractJob, |
| 20 | + resolveDocumentInput, |
| 21 | + textractErrorResponse, |
| 22 | +} from '@/app/api/tools/textract/shared' |
| 23 | + |
| 24 | +export const dynamic = 'force-dynamic' |
| 25 | +/** Mirrors maxDuration in ../parse/route.ts — see that file's TSDoc for details. */ |
| 26 | +export const maxDuration = 5400 |
| 27 | + |
| 28 | +const logger = createLogger('TextractAnalyzeExpenseAPI') |
| 29 | + |
| 30 | +/** Response shape shared by AnalyzeExpense and its async Get* counterpart. */ |
| 31 | +interface TextractExpenseResult { |
| 32 | + JobStatus?: string |
| 33 | + StatusMessage?: string |
| 34 | + NextToken?: string |
| 35 | + ExpenseDocuments?: ExpenseDocument[] |
| 36 | + DocumentMetadata?: { Pages?: number } |
| 37 | + AnalyzeExpenseModelVersion?: string |
| 38 | +} |
| 39 | + |
| 40 | +export function normalizeExpenseField(field: { |
| 41 | + Type?: { Text?: string; Confidence?: number } |
| 42 | + ValueDetection?: { Text?: string; Confidence?: number } |
| 43 | + LabelDetection?: { Text?: string; Confidence?: number } |
| 44 | + PageNumber?: number |
| 45 | + Currency?: { Code?: string; Confidence?: number } |
| 46 | + GroupProperties?: { Id?: string; Types?: string[] }[] |
| 47 | +}) { |
| 48 | + return { |
| 49 | + type: { text: field.Type?.Text, confidence: field.Type?.Confidence }, |
| 50 | + valueDetection: { |
| 51 | + text: field.ValueDetection?.Text, |
| 52 | + confidence: field.ValueDetection?.Confidence, |
| 53 | + }, |
| 54 | + labelDetection: field.LabelDetection |
| 55 | + ? { text: field.LabelDetection.Text, confidence: field.LabelDetection.Confidence } |
| 56 | + : undefined, |
| 57 | + pageNumber: field.PageNumber, |
| 58 | + currency: field.Currency |
| 59 | + ? { code: field.Currency.Code, confidence: field.Currency.Confidence } |
| 60 | + : undefined, |
| 61 | + groupProperties: field.GroupProperties?.map((group) => ({ |
| 62 | + id: group.Id ?? '', |
| 63 | + types: group.Types ?? [], |
| 64 | + })), |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +export function normalizeExpenseDocuments(documents: ExpenseDocument[]) { |
| 69 | + return documents.map((doc) => ({ |
| 70 | + expenseIndex: doc.ExpenseIndex, |
| 71 | + summaryFields: (doc.SummaryFields ?? []).map(normalizeExpenseField), |
| 72 | + lineItemGroups: (doc.LineItemGroups ?? []).map((group) => ({ |
| 73 | + lineItemGroupIndex: group.LineItemGroupIndex, |
| 74 | + lineItems: (group.LineItems ?? []).map((item) => ({ |
| 75 | + lineItemExpenseFields: (item.LineItemExpenseFields ?? []).map(normalizeExpenseField), |
| 76 | + })), |
| 77 | + })), |
| 78 | + })) |
| 79 | +} |
| 80 | + |
| 81 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 82 | + const requestId = generateRequestId() |
| 83 | + |
| 84 | + try { |
| 85 | + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) |
| 86 | + if (!authResult.success || !authResult.userId) { |
| 87 | + logger.warn(`[${requestId}] Unauthorized Textract analyze-expense attempt`, { |
| 88 | + error: authResult.error || 'Missing userId', |
| 89 | + }) |
| 90 | + return NextResponse.json( |
| 91 | + { success: false, error: authResult.error || 'Unauthorized' }, |
| 92 | + { status: 401 } |
| 93 | + ) |
| 94 | + } |
| 95 | + const userId = authResult.userId |
| 96 | + |
| 97 | + const parsed = await parseRequest( |
| 98 | + textractAnalyzeExpenseContract, |
| 99 | + request, |
| 100 | + {}, |
| 101 | + { |
| 102 | + validationErrorResponse: (error) => { |
| 103 | + logger.warn(`[${requestId}] Invalid request data`, { errors: error.issues }) |
| 104 | + return NextResponse.json( |
| 105 | + { |
| 106 | + success: false, |
| 107 | + error: getValidationErrorMessage(error, 'Invalid request data'), |
| 108 | + details: error.issues, |
| 109 | + }, |
| 110 | + { status: 400 } |
| 111 | + ) |
| 112 | + }, |
| 113 | + } |
| 114 | + ) |
| 115 | + if (!parsed.success) return parsed.response |
| 116 | + |
| 117 | + const validatedData = parsed.data.body |
| 118 | + const processingMode = validatedData.processingMode || 'sync' |
| 119 | + |
| 120 | + logger.info(`[${requestId}] Textract analyze-expense request`, { |
| 121 | + processingMode, |
| 122 | + hasFile: Boolean(validatedData.file), |
| 123 | + hasS3Uri: Boolean(validatedData.s3Uri), |
| 124 | + userId, |
| 125 | + }) |
| 126 | + |
| 127 | + const client = new TextractClient({ |
| 128 | + region: validatedData.region, |
| 129 | + credentials: { |
| 130 | + accessKeyId: validatedData.accessKeyId, |
| 131 | + secretAccessKey: validatedData.secretAccessKey, |
| 132 | + }, |
| 133 | + }) |
| 134 | + |
| 135 | + if (processingMode === 'async') { |
| 136 | + if (!validatedData.s3Uri) { |
| 137 | + return NextResponse.json( |
| 138 | + { |
| 139 | + success: false, |
| 140 | + error: 'S3 URI is required for multi-page processing (s3://bucket/key)', |
| 141 | + }, |
| 142 | + { status: 400 } |
| 143 | + ) |
| 144 | + } |
| 145 | + |
| 146 | + const { bucket, key } = parseS3Uri(validatedData.s3Uri) |
| 147 | + logger.info(`[${requestId}] Starting async Textract expense analysis job`, { |
| 148 | + s3Bucket: bucket, |
| 149 | + s3Key: key, |
| 150 | + }) |
| 151 | + |
| 152 | + const { JobId: jobId } = await client.send( |
| 153 | + new StartExpenseAnalysisCommand({ |
| 154 | + DocumentLocation: { S3Object: { Bucket: bucket, Name: key } }, |
| 155 | + }) |
| 156 | + ) |
| 157 | + if (!jobId) { |
| 158 | + throw new Error('Failed to start Textract expense analysis job: No JobId returned') |
| 159 | + } |
| 160 | + logger.info(`[${requestId}] Async expense analysis job started`, { jobId }) |
| 161 | + |
| 162 | + const result = await pollTextractJob<TextractExpenseResult>( |
| 163 | + requestId, |
| 164 | + logger, |
| 165 | + (nextToken) => |
| 166 | + client.send(new GetExpenseAnalysisCommand({ JobId: jobId, NextToken: nextToken })), |
| 167 | + (accumulated, page) => ({ |
| 168 | + ...page, |
| 169 | + ExpenseDocuments: [ |
| 170 | + ...(accumulated.ExpenseDocuments ?? []), |
| 171 | + ...(page.ExpenseDocuments ?? []), |
| 172 | + ], |
| 173 | + }) |
| 174 | + ) |
| 175 | + |
| 176 | + return NextResponse.json({ |
| 177 | + success: true, |
| 178 | + output: { |
| 179 | + expenseDocuments: normalizeExpenseDocuments(result.ExpenseDocuments ?? []), |
| 180 | + documentMetadata: { pages: result.DocumentMetadata?.Pages ?? 0 }, |
| 181 | + modelVersion: result.AnalyzeExpenseModelVersion, |
| 182 | + }, |
| 183 | + }) |
| 184 | + } |
| 185 | + |
| 186 | + const resolved = await resolveDocumentInput( |
| 187 | + { file: validatedData.file, filePath: validatedData.filePath }, |
| 188 | + userId, |
| 189 | + requestId, |
| 190 | + logger |
| 191 | + ) |
| 192 | + if (!resolved.ok) return resolved.response |
| 193 | + const { bytes, isPdf } = resolved.document |
| 194 | + |
| 195 | + let result: TextractExpenseResult |
| 196 | + try { |
| 197 | + result = await client.send(new AnalyzeExpenseCommand({ Document: { Bytes: bytes } })) |
| 198 | + } catch (error) { |
| 199 | + throw mapTextractSdkError(error, isPdf) |
| 200 | + } |
| 201 | + |
| 202 | + logger.info(`[${requestId}] Textract analyze-expense successful`, { |
| 203 | + pageCount: result.DocumentMetadata?.Pages ?? 0, |
| 204 | + expenseDocumentCount: result.ExpenseDocuments?.length ?? 0, |
| 205 | + }) |
| 206 | + |
| 207 | + return NextResponse.json({ |
| 208 | + success: true, |
| 209 | + output: { |
| 210 | + expenseDocuments: normalizeExpenseDocuments(result.ExpenseDocuments ?? []), |
| 211 | + documentMetadata: { pages: result.DocumentMetadata?.Pages ?? 0 }, |
| 212 | + }, |
| 213 | + }) |
| 214 | + } catch (error) { |
| 215 | + return textractErrorResponse(error, requestId, logger) |
| 216 | + } |
| 217 | +}) |
0 commit comments