Migration timeouts (#258)

* feat: optimize migration process with bulk reads and chunked inserts to improve performance

* feat: add SIE-import requirement banner for specific providers in migration workflow

* feat: enhance error handling in TIC API integration with structured HTTP responses

* Update components/extensions/general/ArcimMigrationWorkspace.tsx

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
This commit is contained in:
Mattsson
2026-04-16 16:52:14 +02:00
committed by GitHub
co-authored by greptile-apps[bot]
parent fe137346df
commit 942ab7636f
4 changed files with 561 additions and 256 deletions
@@ -204,9 +204,33 @@ function ProviderStep({
isLoadingStatus: boolean
}) {
const activeConsents = connectionStatus?.consents.filter(c => c.status === 1) ?? []
const hasSieImport = (connectionStatus?.sieImports.filter(i => i.status === 'completed').length ?? 0) > 0
const allFortnox = activeConsents.length > 0 && activeConsents.every(c => c.provider === 'fortnox')
const showSieRequiredBanner = !isLoadingStatus && !hasSieImport && !allFortnox
return (
<div className="space-y-4">
{/* SIE-required banner (not relevant for Fortnox — it fetches SIE itself) */}
{showSieRequiredBanner && (
<div className="flex gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 p-4">
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-amber-600 dark:text-amber-500" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">SIE-import krävs först</p>
<p className="mt-0.5 text-xs text-muted-foreground">
Bokio, Visma, Björn Lundén och Briox hämtar endast kunder, leverantörer och fakturor via API:et. Bokföringsdata (kontoplan, verifikationer och balanser) måste importeras via SIE-fil först. Gäller inte Fortnox — där hämtar vi SIE direkt via API:et.
</p>
<Link
href="/import?mode=sie"
className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'mt-3')}
>
<BookOpen className="mr-2 h-4 w-4" />
Ladda upp SIE-fil
<ExternalLink className="ml-2 h-3.5 w-3.5" />
</Link>
</div>
</div>
)}
{/* Existing connections */}
{activeConsents.length > 0 && (
<Card>
File diff suppressed because it is too large Load Diff
@@ -17,6 +17,7 @@ import {
getEmails,
getPhones,
} from '../lib/tic-client'
import { TICAPIError } from '../lib/tic-types'
import type { TICCompanyDocument } from '../lib/tic-types'
const mockSearch = vi.mocked(searchCompanyByOrgNumber)
@@ -142,4 +143,50 @@ describe('TIC lookup route', () => {
const { data } = await res.json()
expect(data.isCeased).toBe(true)
})
it('returns 503 when TIC is not configured', async () => {
mockSearch.mockRejectedValue(
new TICAPIError('TIC_API_PROXY_URL is not configured', undefined, 'NOT_CONFIGURED')
)
const res = await lookupHandler(makeRequest('556036-0793'))
expect(res.status).toBe(503)
})
it('returns 429 when TIC rate-limits us', async () => {
mockSearch.mockRejectedValue(
new TICAPIError('Rate limit exceeded', 429, 'RATE_LIMIT_EXCEEDED')
)
const res = await lookupHandler(makeRequest('556036-0793'))
expect(res.status).toBe(429)
})
it('returns 504 when TIC times out', async () => {
mockSearch.mockRejectedValue(new TICAPIError('Request timeout', undefined, 'TIMEOUT'))
const res = await lookupHandler(makeRequest('556036-0793'))
expect(res.status).toBe(504)
})
it('returns 400 when upstream rejects the org number (4xx)', async () => {
mockSearch.mockRejectedValue(new TICAPIError('TIC API error: Bad Request', 400))
const res = await lookupHandler(makeRequest('1234567-1234'))
expect(res.status).toBe(400)
})
it('returns 502 when upstream returns 5xx', async () => {
mockSearch.mockRejectedValue(new TICAPIError('TIC API error: Bad Gateway', 502))
const res = await lookupHandler(makeRequest('556036-0793'))
expect(res.status).toBe(502)
})
it('returns 502 when fetch fails (network error)', async () => {
mockSearch.mockRejectedValue(new TICAPIError('Failed to fetch from TIC: ECONNRESET'))
const res = await lookupHandler(makeRequest('556036-0793'))
expect(res.status).toBe(502)
})
it('returns 500 for non-TICAPIError unexpected errors', async () => {
mockSearch.mockRejectedValue(new Error('boom'))
const res = await lookupHandler(makeRequest('556036-0793'))
expect(res.status).toBe(500)
})
})
+93 -59
View File
@@ -43,6 +43,88 @@ function bankAccountTypeLabel(type?: number): string {
}
}
/**
* Translate any error from the TIC pipeline into a structured HTTP response.
*
* Status mapping:
* - NOT_CONFIGURED → 503 (proxy URL missing)
* - RATE_LIMIT_EXCEEDED → 429 (TIC quota hit)
* - TIMEOUT → 504 (TIC took longer than 15s)
* - upstream 4xx → 400 (TIC rejected the input — typically a malformed org number)
* - upstream 5xx → 502 (TIC outage)
* - other / unknown → 500
*
* Always logs the cleaned org number so we can correlate failures with input
* in Vercel logs.
*/
function handleTicError(
error: unknown,
log: { error: (msg: string, meta?: unknown) => void } | Console,
route: 'lookup' | 'profile',
orgNumber: string,
fallbackMessage: string
): Response {
if (error instanceof TICAPIError) {
const meta = {
route,
orgNumber,
message: error.message,
statusCode: error.statusCode,
code: error.code,
}
if (error.code === 'NOT_CONFIGURED') {
log.error(`[tic] ${route}: not configured`, meta)
return NextResponse.json({ error: 'TIC is not configured' }, { status: 503 })
}
if (error.code === 'RATE_LIMIT_EXCEEDED') {
log.error(`[tic] ${route}: rate limit exceeded`, meta)
return NextResponse.json({ error: 'Rate limit exceeded, try again later' }, { status: 429 })
}
if (error.code === 'TIMEOUT') {
log.error(`[tic] ${route}: upstream timeout`, meta)
return NextResponse.json(
{ error: 'TIC service did not respond in time' },
{ status: 504 }
)
}
// Upstream returned a non-OK status we surfaced as a TICAPIError
if (typeof error.statusCode === 'number') {
if (error.statusCode >= 400 && error.statusCode < 500) {
log.error(`[tic] ${route}: upstream rejected request`, meta)
return NextResponse.json(
{ error: 'Invalid request to TIC (upstream rejected)' },
{ status: 400 }
)
}
if (error.statusCode >= 500) {
log.error(`[tic] ${route}: upstream error`, meta)
return NextResponse.json(
{ error: 'TIC service is temporarily unavailable' },
{ status: 502 }
)
}
}
// Network/DNS/parse failure surfaced as a TICAPIError without code or statusCode
log.error(`[tic] ${route}: upstream failure`, meta)
return NextResponse.json(
{ error: 'TIC service is temporarily unavailable' },
{ status: 502 }
)
}
log.error(`[tic] ${route}: unexpected error`, {
route,
orgNumber,
error: error instanceof Error ? { name: error.name, message: error.message, stack: error.stack } : String(error),
})
return NextResponse.json({ error: fallbackMessage }, { status: 500 })
}
export const ticExtension: Extension = {
id: 'tic',
name: 'Bolagsuppgifter',
@@ -65,6 +147,8 @@ export const ticExtension: Extension = {
)
}
const cleanedOrgNumber = orgNumber.replace(/[\s-]/g, '')
try {
// Phase 1: Search — returns name, address, registration flags
const doc = await searchCompanyByOrgNumber(orgNumber)
@@ -137,10 +221,10 @@ export const ticExtension: Extension = {
// Log Phase 2 failures for debugging
if (bankResult.status === 'rejected') {
log.warn('[tic] bank accounts fetch failed', { reason: String(bankResult.reason) })
log.warn('[tic] bank accounts fetch failed', { orgNumber: cleanedOrgNumber, companyId, reason: String(bankResult.reason) })
}
if (sniResult.status === 'rejected') {
log.warn('[tic] SNI codes fetch failed', { reason: String(sniResult.reason) })
log.warn('[tic] SNI codes fetch failed', { orgNumber: cleanedOrgNumber, companyId, reason: String(sniResult.reason) })
}
const result: CompanyLookupResult = {
@@ -156,33 +240,7 @@ export const ticExtension: Extension = {
return NextResponse.json({ data: result })
} catch (error) {
if (error instanceof TICAPIError) {
log.error('[tic] lookup failed', {
message: error.message,
statusCode: error.statusCode,
code: error.code,
})
if (error.code === 'NOT_CONFIGURED') {
return NextResponse.json(
{ error: 'TIC is not configured' },
{ status: 503 }
)
}
if (error.code === 'RATE_LIMIT_EXCEEDED') {
return NextResponse.json(
{ error: 'Rate limit exceeded, try again later' },
{ status: 429 }
)
}
}
log.error('[tic] unexpected error', { error: String(error) })
return NextResponse.json(
{ error: 'Failed to look up company' },
{ status: 500 }
)
return handleTicError(error, log, 'lookup', cleanedOrgNumber, 'Failed to look up company')
}
},
},
@@ -201,6 +259,8 @@ export const ticExtension: Extension = {
)
}
const cleanedOrgNumber = orgNumber.replace(/[\s-]/g, '')
try {
const doc = await searchCompanyByOrgNumber(orgNumber)
@@ -267,13 +327,13 @@ export const ticExtension: Extension = {
// Log Phase 2 failures
if (bankResult.status === 'rejected') {
log.warn('[tic] profile: bank accounts fetch failed', { reason: String(bankResult.reason) })
log.warn('[tic] profile: bank accounts fetch failed', { orgNumber: cleanedOrgNumber, companyId, reason: String(bankResult.reason) })
}
if (sniResult.status === 'rejected') {
log.warn('[tic] profile: SNI codes fetch failed', { reason: String(sniResult.reason) })
log.warn('[tic] profile: SNI codes fetch failed', { orgNumber: cleanedOrgNumber, companyId, reason: String(sniResult.reason) })
}
if (reportsResult.status === 'rejected') {
log.warn('[tic] profile: financial reports fetch failed', { reason: String(reportsResult.reason) })
log.warn('[tic] profile: financial reports fetch failed', { orgNumber: cleanedOrgNumber, companyId, reason: String(reportsResult.reason) })
}
const fin = doc.mostRecentFinancialSummary
@@ -329,33 +389,7 @@ export const ticExtension: Extension = {
return NextResponse.json({ data: profile })
} catch (error) {
if (error instanceof TICAPIError) {
log.error('[tic] profile failed', {
message: error.message,
statusCode: error.statusCode,
code: error.code,
})
if (error.code === 'NOT_CONFIGURED') {
return NextResponse.json(
{ error: 'TIC is not configured' },
{ status: 503 }
)
}
if (error.code === 'RATE_LIMIT_EXCEEDED') {
return NextResponse.json(
{ error: 'Rate limit exceeded, try again later' },
{ status: 429 }
)
}
}
log.error('[tic] profile unexpected error', { error: String(error) })
return NextResponse.json(
{ error: 'Failed to fetch company profile' },
{ status: 500 }
)
return handleTicError(error, log, 'profile', cleanedOrgNumber, 'Failed to fetch company profile')
}
},
},