|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getErrorMessage } from '@sim/utils/errors' |
| 3 | +import { generateId } from '@sim/utils/id' |
| 4 | +import { type NextRequest, NextResponse } from 'next/server' |
| 5 | +import { rampUploadReceiptContract } from '@/lib/api/contracts/tools/ramp' |
| 6 | +import { parseRequest } from '@/lib/api/server' |
| 7 | +import { checkInternalAuth } from '@/lib/auth/hybrid' |
| 8 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 9 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 10 | +import { processFilesToUserFiles, type RawFileInput } from '@/lib/uploads/utils/file-utils' |
| 11 | +import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server' |
| 12 | +import { assertToolFileAccess } from '@/app/api/files/authorization' |
| 13 | +import { extractRampError } from '@/tools/ramp/utils' |
| 14 | + |
| 15 | +export const dynamic = 'force-dynamic' |
| 16 | + |
| 17 | +const logger = createLogger('RampUploadReceiptAPI') |
| 18 | + |
| 19 | +const RAMP_RECEIPTS_URL = 'https://api.ramp.com/developer/v1/receipts' |
| 20 | + |
| 21 | +/** |
| 22 | + * Builds the multipart body for Ramp's receipt upload endpoint. Ramp expects |
| 23 | + * metadata parts with `Content-Disposition: form-data` and the receipt image |
| 24 | + * as a part named `receipt` with `Content-Disposition: attachment`. |
| 25 | + */ |
| 26 | +function buildReceiptMultipartBody( |
| 27 | + boundary: string, |
| 28 | + fields: Record<string, string>, |
| 29 | + file: { name: string; type: string; buffer: Buffer } |
| 30 | +): Buffer { |
| 31 | + const parts: Buffer[] = [] |
| 32 | + |
| 33 | + for (const [name, value] of Object.entries(fields)) { |
| 34 | + parts.push( |
| 35 | + Buffer.from( |
| 36 | + `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n` |
| 37 | + ) |
| 38 | + ) |
| 39 | + } |
| 40 | + |
| 41 | + const safeFileName = file.name.replace(/[\r\n"]/g, '_') |
| 42 | + parts.push( |
| 43 | + Buffer.from( |
| 44 | + `--${boundary}\r\nContent-Disposition: attachment; name="receipt"; filename="${safeFileName}"\r\nContent-Type: ${file.type}\r\n\r\n` |
| 45 | + ) |
| 46 | + ) |
| 47 | + parts.push(file.buffer) |
| 48 | + parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)) |
| 49 | + |
| 50 | + return Buffer.concat(parts) |
| 51 | +} |
| 52 | + |
| 53 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 54 | + const requestId = generateRequestId() |
| 55 | + |
| 56 | + try { |
| 57 | + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) |
| 58 | + |
| 59 | + if (!authResult.success || !authResult.userId) { |
| 60 | + logger.warn(`[${requestId}] Unauthorized Ramp receipt upload attempt: ${authResult.error}`) |
| 61 | + return NextResponse.json( |
| 62 | + { success: false, error: authResult.error || 'Authentication required' }, |
| 63 | + { status: 401 } |
| 64 | + ) |
| 65 | + } |
| 66 | + |
| 67 | + const parsed = await parseRequest(rampUploadReceiptContract, request, {}) |
| 68 | + if (!parsed.success) return parsed.response |
| 69 | + const validatedData = parsed.data.body |
| 70 | + |
| 71 | + const userFiles = processFilesToUserFiles( |
| 72 | + [validatedData.file as RawFileInput], |
| 73 | + requestId, |
| 74 | + logger |
| 75 | + ) |
| 76 | + |
| 77 | + if (userFiles.length === 0) { |
| 78 | + return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 }) |
| 79 | + } |
| 80 | + |
| 81 | + const userFile = userFiles[0] |
| 82 | + logger.info( |
| 83 | + `[${requestId}] Downloading receipt file: ${userFile.name} (${userFile.size} bytes)` |
| 84 | + ) |
| 85 | + |
| 86 | + const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger) |
| 87 | + if (denied) return denied |
| 88 | + const fileBuffer = await downloadFileFromStorage(userFile, requestId, logger) |
| 89 | + |
| 90 | + const fields: Record<string, string> = { |
| 91 | + idempotency_key: generateId(), |
| 92 | + user_id: validatedData.userId, |
| 93 | + } |
| 94 | + if (validatedData.transactionId) { |
| 95 | + fields.transaction_id = validatedData.transactionId |
| 96 | + } |
| 97 | + |
| 98 | + const boundary = `----sim-ramp-receipt-${generateId()}` |
| 99 | + const body = buildReceiptMultipartBody(boundary, fields, { |
| 100 | + name: userFile.name, |
| 101 | + type: userFile.type || 'application/octet-stream', |
| 102 | + buffer: fileBuffer, |
| 103 | + }) |
| 104 | + |
| 105 | + logger.info(`[${requestId}] Uploading receipt to Ramp (${fileBuffer.length} bytes)`) |
| 106 | + |
| 107 | + const response = await fetch(RAMP_RECEIPTS_URL, { |
| 108 | + method: 'POST', |
| 109 | + headers: { |
| 110 | + Authorization: `Bearer ${validatedData.accessToken}`, |
| 111 | + 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 112 | + }, |
| 113 | + body: new Uint8Array(body), |
| 114 | + }) |
| 115 | + |
| 116 | + const data = await response.json().catch(() => ({})) |
| 117 | + |
| 118 | + if (!response.ok) { |
| 119 | + const errorMessage = extractRampError(data, 'Failed to upload receipt to Ramp') |
| 120 | + logger.error(`[${requestId}] Ramp API error:`, { status: response.status, data }) |
| 121 | + return NextResponse.json({ success: false, error: errorMessage }, { status: response.status }) |
| 122 | + } |
| 123 | + |
| 124 | + logger.info(`[${requestId}] Receipt uploaded successfully: ${data.id}`) |
| 125 | + |
| 126 | + return NextResponse.json({ |
| 127 | + success: true, |
| 128 | + output: { |
| 129 | + receiptId: data.id, |
| 130 | + }, |
| 131 | + }) |
| 132 | + } catch (error) { |
| 133 | + logger.error(`[${requestId}] Unexpected error:`, error) |
| 134 | + return NextResponse.json( |
| 135 | + { success: false, error: getErrorMessage(error, 'Unknown error') }, |
| 136 | + { status: 500 } |
| 137 | + ) |
| 138 | + } |
| 139 | +}) |
0 commit comments