import api from './index'; import { validateResponse } from '../utils/validate'; import { importRunEnvelopeSchema } from './schemas'; import type { ImportPreviewResult, ImportReceipt, ImportRunDetail, ImportStageRequest, } from '../components/ImportWizard/types'; interface ApiEnvelope { success: boolean; data: T; message?: string; } export async function createImportRun( file: File, options: { source: 'ai' | 'manual'; conversationId?: number; stages?: ImportStageRequest[]; mapping?: Record>; }, ): Promise { const form = new FormData(); form.append('file', file); form.append('source', options.source); if (options.conversationId) form.append('conversationId', String(options.conversationId)); if (options.stages?.length) form.append('stages', JSON.stringify(options.stages)); if (options.mapping && Object.keys(options.mapping).length > 0) { form.append('mapping', JSON.stringify(options.mapping)); } const res = await api.post>('/imports/runs', form, { headers: { 'Content-Type': 'multipart/form-data' }, }); return res.data; } export async function getImportRun(runId: string): Promise { const res = await api.get>( `/imports/runs/${encodeURIComponent(runId)}`, ); return validateResponse>(importRunEnvelopeSchema, res).data; } export async function previewImportStep( runId: string, stepKey: string, body: { sheets?: string[]; mapping?: Record }, ): Promise { const res = await api.post>( `/imports/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(stepKey)}/preview`, body, ); return res.data; } export async function commitImportStep( runId: string, stepKey: string, decisions: Array<{ rowId: number; action: 'create' | 'update' | 'skip' }>, ): Promise { const res = await api.post>( `/imports/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(stepKey)}/commit`, { decisions }, ); return res.data; } export function importErrorReportUrl(runId: string, stepKey?: string): string { const base = import.meta.env.PROD ? '/api' : `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`; const params = new URLSearchParams(); if (stepKey) params.set('stepKey', stepKey); const query = params.toString(); return `${base}/imports/runs/${encodeURIComponent(runId)}/report${query ? `?${query}` : ''}`; }