feat: enable banking hardening, arcim inference, SIE fixes, onboarding (#32)
* feat: import system improvements, INK2 fix, and Swedish text corrections - SIE parser: Windows-1252 and CP437 encoding detection and decoding - Bank file parser: add Nordea Business (Företag) CSV format - Bank file parser: improve format detection for SEB, Länsförsäkringar, generic CSV - INK2 engine: calculate årets resultat (7222) from income statement for open fiscal years - Dashboard: parallel Supabase queries, simplified dashboard page - Fix Swedish characters (å, ä, ö) in BAS data descriptions, validation messages, AI consent disclosures - Import wizard UI improvements across all steps - Migration: add 'bas_range' match type to sie_account_mappings constraint - Extensive new tests for SIE parser encoding and bank file parser Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: arcim migration wizard UX fixes, Sentry setup, and extension scaffolding Arcim migration wizard improvements: - Progress bar now excludes non-interactive steps (migrating/result) - Fix OAuth text to match target="_blank" behavior (new tab, not redirect) - Display month names instead of "Månad X" in preview - Fix Swedish typo "förifylla" in no-company-info message - Replace native checkboxes with shadcn Switch in options step - Add ConfirmationDialog before starting migration - Show progress percentage during migration - Add "Nästa steg" guidance and navigation links in result step - Add "Försök igen" button in error state (returns to options) - Add Bokio company ID help text (GUID from URL) - Add Fortnox integration add-on hint on connection failure Also includes: SIE import system improvements, INK2 fixes, Swedish text corrections, Sentry error tracking setup, and arcim-migration extension scaffolding. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address PR review feedback - Fix OAuth error recovery blank page (restore provider from URL params) - Pass real userId to MigrationWizard instead of empty string - Remove ~50 debug console.log statements from sie-import.ts - Fix comment referencing account 3740 → 3741 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: comprehensive UI design audit and normalization Dashboard audit: - Fix muted-foreground contrast (4.31:1 → 5.08:1) for WCAG AA - Add prefers-reduced-motion media query for all animations - Replace border-l-2 accent anti-pattern with subtle full-border colors - Add aria-expanded to toggle buttons, role="status" to live counters - Fix touch targets on deadline buttons (28px → 36px) - Vary section spacing for rhythm (mb-12/mb-10/mb-8) - Remove unused imports and dead code Transactions audit + hardening: - Add pagination (200 per page) with "Ladda fler" button - Replace height animation with transform-only exit animation - Show batch progress in floating action bar during processing - Fix batch bar mobile overlap (bottom-20 on mobile) - Replace clickable badges with proper button elements - Add safe area padding to fullscreen swipe view - Add response.ok check to suggestion fetch - Add truncation to invoice number buttons Invoicing audit: - Remove border-l-4 accent pattern from invoice cards - Replace string concatenation with cn() utility Systemic sweep (34 files): - All page headings: font-bold → font-display font-medium (Fraunces) - All stat numbers: font-bold → font-display font-medium tabular-nums - All hard-coded blue/amber/emerald colors → design tokens - Remove all dark mode overrides (tokens handle automatically) - Tint pure white card background to 99% Design context added to CLAUDE.md with brand personality, aesthetic direction, and 5 design principles. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: bookkeeping flow audit — design system, accessibility, UX - Replace raw <select> with shadcn Select component (JournalEntryForm) - Add confirmation dialog for account deletion (ChartOfAccountsManager) - Remove console.error from production code (JournalEntryList, JournalEntryForm) - Fix contradictory h-7/min-h-[44px] button sizing → h-10 (ChartOfAccountsManager) - Increase BAS catalog "Lägg till" touch target h-7 → h-9 - Improve loading state with spinner (JournalEntryList) - Improve empty state with icon, description, and guidance (JournalEntryList) - Add response.ok check on journal entry fetch - Add aria-expanded to entry expand buttons - Add tabular-nums to desktop debit/credit columns Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: onboarding and empty state improvements Onboarding: - Replace font-serif with font-display (Fraunces) for brand consistency - Remove console.error calls from production code Empty states: - Fix broken /transactions/new link in EmptyTransactions (route doesn't exist) - Add actionHref fallback to EmptyCustomers when no onAction prop provided - Improve EmptyTransactions description copy Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: clarify Swedish UX copy — terminology, errors, descriptions Terminology consistency: - "Försenad" → "Förfallen" for overdue invoices (customers/[id]) - "bokföringsorder" → actionable description in bookkeeping page - "verifikation har bifogats" → "underlag har bifogats" in doc warning - "Fortsätt ändå" → "Bokför utan underlag" (specific action) Error messages — replace generic "Fel" + "Något gick fel" with specific: - "Något gick fel vid bokföring" → "Transaktionen kunde inte bokföras" - "Något gick fel vid matchning" → "Transaktionen kunde inte matchas" - "Kunde inte hämta X" → "Kunde inte ladda X" + recovery hint - Add "Försök igen" guidance to all error toasts Page descriptions — replace redundant with actionable: - Invoices: "Skapa och hantera" → "Skicka, följ betalningar, skapa kreditnotor" - Bookkeeping: list of features → actionable description Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: design critique — dashboard affordance, reports description Dashboard: - Add ChevronRight indicator to clickable summary cards (Att få betalt, Koppla bank) to distinguish from static cards - Add cursor-pointer to linked cards Reports: - Replace feature list description with actionable guidance "Huvudbok, grundbok..." → "Generera skattedeklarationer..." Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: replace generic "Fel" error toasts with specific messages Deadlines: 5 generic "Fel" → specific per-action titles (create, toggle, edit, delete, load) Expenses detail: 5 generic "Fel" → specific per-action titles (load, approve, pay, credit, delete) Expenses new: 3 generic "Fel" → instructional validation messages (supplier name, supplier selection, invoice number) Customers: 1 generic "Fel" → specific load error with recovery hint All error toasts now follow pattern: title = what failed, description = how to recover Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: replace all remaining generic "Fel" error toasts (37 instances) Systematic sweep across 12 dashboard pages replacing generic title: 'Fel' with context-specific error titles: - Load errors: "Kunde inte ladda [resurs]" - Action errors: "[Åtgärd] misslyckades" - Validation: "[Fält] saknas" Every error toast now tells the user what failed without needing to read the description. Recovery hints added where missing. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: import flow — normalize stat typography, remove console.warn - Replace font-bold with font-display font-medium on 13 stat numbers across SIEPreviewStep, BankFilePreviewStep, BankFileConfirmStep, ImportResultStep (missed by systemic sweep since these are in components/import/, not app/(dashboard)/) - Add tabular-nums to stat numbers displaying counts/currency - Remove console.warn in ArcimMigrationWorkspace Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: final cleanup — console statements, remaining font-bold stats Remove production console statements: - Step1EntityType: remove debug console.warn (dead code after onNext) - TransactionBookingDialog: remove console.error on doc link failure - JournalEntryAttachments: remove 3 console.error calls Normalize remaining font-bold stat displays: - SwipeCategorizationView: 3 instances (completion, amount displays) - NEDeclarationView: yearly result heading + value Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review feedback loadMoreTransactions: add inbox item enrichment matching fetchTransactions - Paginated transactions now fetch invoice_inbox_items in parallel - Fixes missing document indicator, template suggestions, and inbox match card for transactions loaded via "Ladda fler" fetchAllPages: add maxPages guard (default 500) to prevent infinite loop - If Arcim gateway returns hasMore:true indefinitely, the loop now exits after 500 pages instead of running forever Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: minimize CLAUDE.md — remove derivable content, fix stale data Remove ~230 lines (51% reduction) of content that duplicates what's already in the source code (directory tree, function tables, type definitions, migration lists). Update migration count (63→65), add missing test helpers, fix cron job list. Keep all high-value sections: accounting guard rails, BAS accounts, VAT rutor, design context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: enable banking hardening, arcim entity inference, SIE import fixes, and onboarding improvements - Enable Banking: OAuth CSRF state tokens, JWT caching, retry with timeouts, raw PSD2 response archival (BFL 7 kap), expired/error connection UI, consent expiry notifications, pagination safety limits - Arcim migration: Smarter entity type inference from org numbers, VAT prefixes, company name suffixes (GmbH, Ltd, etc.), and country codes - SIE import: Parser and import fixes with new migration - BAS accounts: Added vehicle accounts (1241, 1242, 1249, 1259) - Dashboard: New SIE import and stale uncategorized transaction queries - Onboarding: Enhanced NewUserChecklist - Period service: Improvements with updated tests - Transaction ingest: Updated logic and tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address Greptile review — credit note type, EU country codes, notification thresholds, migration timestamps - Fix dead ternary: credit notes now correctly stored as 'credit_note' instead of 'invoice' - Add 'GR' (Greece ISO 3166-1) to EU_COUNTRIES alongside 'EL' (VAT prefix) - Fix consent notification condition: fire at exactly 7 days or ≤3 days, not every day in 7-day window - Deduplicate migration timestamps: rename SIE migration to 20260316120100 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
56fb117d16
commit
98cd253bce
@@ -51,6 +51,8 @@ export default async function DashboardPage() {
|
|||||||
{ data: entriesWithDocs },
|
{ data: entriesWithDocs },
|
||||||
{ data: recentReceiptActivity },
|
{ data: recentReceiptActivity },
|
||||||
{ data: enabledToggles },
|
{ data: enabledToggles },
|
||||||
|
{ count: sieImportCount },
|
||||||
|
{ count: staleUncategorizedCount },
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
|
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
|
||||||
supabase.from('company_settings').select('*').eq('user_id', user.id).single(),
|
supabase.from('company_settings').select('*').eq('user_id', user.id).single(),
|
||||||
@@ -74,6 +76,8 @@ export default async function DashboardPage() {
|
|||||||
supabase.from('document_attachments').select('journal_entry_id').eq('user_id', user.id).eq('is_current_version', true).not('journal_entry_id', 'is', null),
|
supabase.from('document_attachments').select('journal_entry_id').eq('user_id', user.id).eq('is_current_version', true).not('journal_entry_id', 'is', null),
|
||||||
supabase.from('receipts').select('created_at').eq('user_id', user.id).eq('status', 'confirmed').order('created_at', { ascending: false }).limit(30),
|
supabase.from('receipts').select('created_at').eq('user_id', user.id).eq('status', 'confirmed').order('created_at', { ascending: false }).limit(30),
|
||||||
supabase.from('extension_toggles').select('sector_slug, extension_slug').eq('user_id', user.id).eq('enabled', true),
|
supabase.from('extension_toggles').select('sector_slug, extension_slug').eq('user_id', user.id).eq('enabled', true),
|
||||||
|
supabase.from('sie_imports').select('*', { count: 'exact', head: true }).eq('user_id', user.id).eq('status', 'completed'),
|
||||||
|
supabase.from('transactions').select('*', { count: 'exact', head: true }).eq('user_id', user.id).is('journal_entry_id', null).not('is_business', 'eq', false).lt('date', new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]),
|
||||||
])
|
])
|
||||||
|
|
||||||
const firstName = profile?.full_name?.split(' ')[0] || null
|
const firstName = profile?.full_name?.split(' ')[0] || null
|
||||||
@@ -82,6 +86,7 @@ export default async function DashboardPage() {
|
|||||||
hasCustomers: (customerCount || 0) > 0,
|
hasCustomers: (customerCount || 0) > 0,
|
||||||
hasInvoices: (invoiceCount || 0) > 0,
|
hasInvoices: (invoiceCount || 0) > 0,
|
||||||
hasBankConnected: (transactionCount || 0) > 0,
|
hasBankConnected: (transactionCount || 0) > 0,
|
||||||
|
hasSIEImport: (sieImportCount || 0) > 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate totals from journal entry lines using account classes
|
// Calculate totals from journal entry lines using account classes
|
||||||
@@ -215,6 +220,7 @@ export default async function DashboardPage() {
|
|||||||
deadlines: (deadlines || []) as Deadline[],
|
deadlines: (deadlines || []) as Deadline[],
|
||||||
receiptQueue,
|
receiptQueue,
|
||||||
missingUnderlagCount,
|
missingUnderlagCount,
|
||||||
|
staleUncategorizedCount: staleUncategorizedCount || 0,
|
||||||
}}
|
}}
|
||||||
onboardingProgress={onboardingProgress}
|
onboardingProgress={onboardingProgress}
|
||||||
enabledExtensions={enabledToggles || []}
|
enabledExtensions={enabledToggles || []}
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
|
||||||
|
// Mock dependencies — factory must not reference outer variables
|
||||||
|
const mockCreateSession = vi.fn()
|
||||||
|
const mockGetAccountBalance = vi.fn()
|
||||||
|
vi.mock('@/extensions/general/enable-banking/lib/api-client', () => ({
|
||||||
|
createSession: (...args: unknown[]) => mockCreateSession(...args),
|
||||||
|
getAccountBalance: (...args: unknown[]) => mockGetAccountBalance(...args),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Use hoisted to safely create mock objects referenced in vi.mock factories
|
||||||
|
const { mockFrom } = vi.hoisted(() => {
|
||||||
|
const mockFrom = vi.fn()
|
||||||
|
return { mockFrom }
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('@/lib/supabase/server', () => ({
|
||||||
|
createServiceClient: vi.fn().mockResolvedValue({
|
||||||
|
from: mockFrom,
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000')
|
||||||
|
|
||||||
|
import { GET } from '../route'
|
||||||
|
|
||||||
|
function makeRequest(params: Record<string, string>) {
|
||||||
|
const url = new URL('http://localhost:3000/api/extensions/enable-banking/callback')
|
||||||
|
for (const [k, v] of Object.entries(params)) {
|
||||||
|
url.searchParams.set(k, v)
|
||||||
|
}
|
||||||
|
return new Request(url.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockChain(result: { data?: unknown; error?: unknown }) {
|
||||||
|
const chain: Record<string, unknown> = {}
|
||||||
|
for (const m of ['select', 'eq', 'single', 'update', 'order', 'limit']) {
|
||||||
|
chain[m] = vi.fn().mockReturnValue(chain)
|
||||||
|
}
|
||||||
|
chain.single = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
|
||||||
|
// For chains ending without .single()
|
||||||
|
chain.then = (resolve: (v: unknown) => void) => resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||||
|
return chain
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('GET /api/extensions/enable-banking/callback', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects when state does not match any pending connection', async () => {
|
||||||
|
mockFrom.mockImplementation(() =>
|
||||||
|
mockChain({ data: null, error: { message: 'not found' } })
|
||||||
|
)
|
||||||
|
|
||||||
|
const response = await GET(makeRequest({ code: 'auth-code', state: 'unknown-state' }))
|
||||||
|
|
||||||
|
expect(response.status).toBe(307)
|
||||||
|
const location = response.headers.get('location') || ''
|
||||||
|
expect(location).toContain('bank_error=invalid_state')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('activates connection and clears oauth_state on success', async () => {
|
||||||
|
let callIndex = 0
|
||||||
|
mockFrom.mockImplementation(() => {
|
||||||
|
callIndex++
|
||||||
|
if (callIndex === 1) {
|
||||||
|
// Find pending connection by oauth_state
|
||||||
|
return mockChain({ data: { id: 'conn-1', user_id: 'user-1' }, error: null })
|
||||||
|
}
|
||||||
|
if (callIndex === 2) {
|
||||||
|
// Update connection
|
||||||
|
return mockChain({ data: null, error: null })
|
||||||
|
}
|
||||||
|
// Company settings lookup
|
||||||
|
return mockChain({ data: { onboarding_complete: true }, error: null })
|
||||||
|
})
|
||||||
|
|
||||||
|
mockCreateSession.mockResolvedValue({
|
||||||
|
session_id: 'sess-1',
|
||||||
|
accounts: [],
|
||||||
|
access: { valid_until: '2024-12-31T00:00:00Z' },
|
||||||
|
aspsp: { name: 'TestBank', country: 'SE' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await GET(makeRequest({ code: 'auth-code', state: 'valid-state' }))
|
||||||
|
|
||||||
|
expect(response.status).toBe(307)
|
||||||
|
const location = response.headers.get('location') || ''
|
||||||
|
expect(location).toContain('bank_connected=true')
|
||||||
|
expect(location).toContain('connection_id=conn-1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('redirects with error when bank returns error param', async () => {
|
||||||
|
const response = await GET(makeRequest({ error: 'access_denied', error_description: 'User cancelled' }))
|
||||||
|
|
||||||
|
expect(response.status).toBe(307)
|
||||||
|
const location = response.headers.get('location') || ''
|
||||||
|
expect(location).toContain('bank_error=User%20cancelled')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('redirects with error when code or state is missing', async () => {
|
||||||
|
const response = await GET(makeRequest({ code: 'auth-code' }))
|
||||||
|
|
||||||
|
expect(response.status).toBe(307)
|
||||||
|
const location = response.headers.get('location') || ''
|
||||||
|
expect(location).toContain('bank_error=missing_parameters')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -14,7 +14,7 @@ export async function GET(request: Request) {
|
|||||||
const { searchParams } = new URL(request.url)
|
const { searchParams } = new URL(request.url)
|
||||||
|
|
||||||
const code = searchParams.get('code')
|
const code = searchParams.get('code')
|
||||||
const state = searchParams.get('state') // This is the user_id we passed during authorization
|
const state = searchParams.get('state') // Cryptographic oauth_state token
|
||||||
const error = searchParams.get('error')
|
const error = searchParams.get('error')
|
||||||
const errorDescription = searchParams.get('error_description')
|
const errorDescription = searchParams.get('error_description')
|
||||||
|
|
||||||
@@ -35,8 +35,25 @@ export async function GET(request: Request) {
|
|||||||
const supabase = await createServiceClient()
|
const supabase = await createServiceClient()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Look up pending connection by oauth_state (CSRF-safe)
|
||||||
|
const { data: pendingConnection, error: findError } = await supabase
|
||||||
|
.from('bank_connections')
|
||||||
|
.select('id, user_id')
|
||||||
|
.eq('oauth_state', state)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (findError || !pendingConnection) {
|
||||||
|
console.error('No pending connection for oauth_state:', findError)
|
||||||
|
return NextResponse.redirect(
|
||||||
|
`${baseUrl}/settings?bank_error=${encodeURIComponent('invalid_state')}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = pendingConnection.user_id
|
||||||
|
|
||||||
const sessionData = await createSession(code)
|
const sessionData = await createSession(code)
|
||||||
const { session_id, accounts, access, aspsp } = sessionData
|
const { session_id, accounts, access } = sessionData
|
||||||
const consentExpiresAt = access.valid_until
|
const consentExpiresAt = access.valid_until
|
||||||
|
|
||||||
const accountsWithBalances: StoredAccount[] = await Promise.all(
|
const accountsWithBalances: StoredAccount[] = await Promise.all(
|
||||||
@@ -63,61 +80,28 @@ export async function GET(request: Request) {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
const { data: pendingConnection, error: findError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from('bank_connections')
|
.from('bank_connections')
|
||||||
.select('id')
|
.update({
|
||||||
.eq('user_id', state)
|
session_id,
|
||||||
.eq('status', 'pending')
|
status: 'active',
|
||||||
.order('created_at', { ascending: false })
|
accounts_data: accountsWithBalances,
|
||||||
.limit(1)
|
consent_expires: consentExpiresAt,
|
||||||
.single()
|
last_synced_at: new Date().toISOString(),
|
||||||
|
oauth_state: null, // Clear to prevent replay
|
||||||
|
})
|
||||||
|
.eq('id', pendingConnection.id)
|
||||||
|
|
||||||
let connectionId: string
|
if (updateError) {
|
||||||
|
throw new Error('Failed to update connection')
|
||||||
if (findError || !pendingConnection) {
|
|
||||||
console.error('Could not find pending connection:', findError)
|
|
||||||
const { data: inserted, error: insertError } = await supabase
|
|
||||||
.from('bank_connections')
|
|
||||||
.insert({
|
|
||||||
user_id: state,
|
|
||||||
provider: `${aspsp.name.toLowerCase().replace(/\s+/g, '-')}-${aspsp.country.toLowerCase()}`,
|
|
||||||
bank_name: aspsp.name,
|
|
||||||
session_id,
|
|
||||||
status: 'active',
|
|
||||||
accounts_data: accountsWithBalances,
|
|
||||||
consent_expires: consentExpiresAt,
|
|
||||||
last_synced_at: new Date().toISOString(),
|
|
||||||
})
|
|
||||||
.select('id')
|
|
||||||
.single()
|
|
||||||
|
|
||||||
if (insertError || !inserted) {
|
|
||||||
console.error('Insert error:', insertError)
|
|
||||||
throw new Error('Failed to create connection')
|
|
||||||
}
|
|
||||||
connectionId = inserted.id
|
|
||||||
} else {
|
|
||||||
const { error: updateError } = await supabase
|
|
||||||
.from('bank_connections')
|
|
||||||
.update({
|
|
||||||
session_id,
|
|
||||||
status: 'active',
|
|
||||||
accounts_data: accountsWithBalances,
|
|
||||||
consent_expires: consentExpiresAt,
|
|
||||||
last_synced_at: new Date().toISOString(),
|
|
||||||
})
|
|
||||||
.eq('id', pendingConnection.id)
|
|
||||||
|
|
||||||
if (updateError) {
|
|
||||||
throw new Error('Failed to update connection')
|
|
||||||
}
|
|
||||||
connectionId = pendingConnection.id
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const connectionId = pendingConnection.id
|
||||||
|
|
||||||
const { data: userSettings } = await supabase
|
const { data: userSettings } = await supabase
|
||||||
.from('company_settings')
|
.from('company_settings')
|
||||||
.select('onboarding_complete')
|
.select('onboarding_complete')
|
||||||
.eq('user_id', state)
|
.eq('user_id', userId)
|
||||||
.single()
|
.single()
|
||||||
|
|
||||||
const redirectTarget = userSettings?.onboarding_complete
|
const redirectTarget = userSettings?.onboarding_complete
|
||||||
@@ -131,8 +115,8 @@ export async function GET(request: Request) {
|
|||||||
try {
|
try {
|
||||||
await supabase
|
await supabase
|
||||||
.from('bank_connections')
|
.from('bank_connections')
|
||||||
.update({ status: 'error' })
|
.update({ status: 'error', oauth_state: null })
|
||||||
.eq('user_id', state)
|
.eq('oauth_state', state)
|
||||||
.eq('status', 'pending')
|
.eq('status', 'pending')
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore cleanup errors
|
// Ignore cleanup errors
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import { createClient } from '@supabase/supabase-js'
|
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
||||||
import { NextResponse } from 'next/server'
|
import { NextResponse } from 'next/server'
|
||||||
import { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync'
|
import { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync'
|
||||||
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/general/enable-banking/lib/api-client'
|
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/general/enable-banking/lib/api-client'
|
||||||
|
import { getEmailService } from '@/lib/email/service'
|
||||||
|
import {
|
||||||
|
generateConsentExpiryEmailHtml,
|
||||||
|
generateConsentExpiryEmailText,
|
||||||
|
generateConsentExpiryEmailSubject,
|
||||||
|
} from '@/lib/email/consent-notification-templates'
|
||||||
import { ensureInitialized } from '@/lib/init'
|
import { ensureInitialized } from '@/lib/init'
|
||||||
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||||
|
|
||||||
@@ -12,7 +18,7 @@ ensureInitialized()
|
|||||||
* Automatic daily bank transaction sync
|
* Automatic daily bank transaction sync
|
||||||
* Runs at 05:00 UTC (07:00 Swedish time)
|
* Runs at 05:00 UTC (07:00 Swedish time)
|
||||||
*
|
*
|
||||||
* Processes up to 10 connections per run (Vercel Hobby 60s timeout).
|
* Processes up to 50 connections per run (Vercel Pro 300s timeout).
|
||||||
* Prioritizes connections not synced for the longest time.
|
* Prioritizes connections not synced for the longest time.
|
||||||
* Deduplication via external_id makes repeated runs safe.
|
* Deduplication via external_id makes repeated runs safe.
|
||||||
*/
|
*/
|
||||||
@@ -68,6 +74,7 @@ export async function GET(request: Request) {
|
|||||||
|
|
||||||
const startTime = Date.now()
|
const startTime = Date.now()
|
||||||
const TIME_BUDGET_MS = 50_000 // 50s — leave 10s margin for Vercel timeout
|
const TIME_BUDGET_MS = 50_000 // 50s — leave 10s margin for Vercel timeout
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||||
|
|
||||||
const results: {
|
const results: {
|
||||||
connectionId: string
|
connectionId: string
|
||||||
@@ -96,6 +103,11 @@ export async function GET(request: Request) {
|
|||||||
.update({ status: 'expired' })
|
.update({ status: 'expired' })
|
||||||
.eq('id', connection.id)
|
.eq('id', connection.id)
|
||||||
|
|
||||||
|
// Send expiry notification
|
||||||
|
await sendConsentExpiryNotification(
|
||||||
|
supabase, connection, 0, true, baseUrl
|
||||||
|
)
|
||||||
|
|
||||||
results.push({
|
results.push({
|
||||||
connectionId: connection.id,
|
connectionId: connection.id,
|
||||||
userId: connection.user_id,
|
userId: connection.user_id,
|
||||||
@@ -111,6 +123,13 @@ export async function GET(request: Request) {
|
|||||||
|
|
||||||
const expiringSoon = isConsentExpiringSoon(connection.consent_expires)
|
const expiringSoon = isConsentExpiringSoon(connection.consent_expires)
|
||||||
|
|
||||||
|
// Send consent expiry notifications at 7-day and 3-day thresholds
|
||||||
|
if (expiringSoon && daysLeft !== null && (daysLeft <= 3 || daysLeft === 7)) {
|
||||||
|
await sendConsentExpiryNotification(
|
||||||
|
supabase, connection, daysLeft, false, baseUrl
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const toDate = new Date().toISOString().split('T')[0]
|
const toDate = new Date().toISOString().split('T')[0]
|
||||||
const fromDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
const fromDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
||||||
.toISOString()
|
.toISOString()
|
||||||
@@ -133,11 +152,13 @@ export async function GET(request: Request) {
|
|||||||
const totalDuplicates = syncResults.reduce((sum, r) => sum + r.duplicates, 0)
|
const totalDuplicates = syncResults.reduce((sum, r) => sum + r.duplicates, 0)
|
||||||
const totalErrors = syncResults.reduce((sum, r) => sum + r.errors, 0)
|
const totalErrors = syncResults.reduce((sum, r) => sum + r.errors, 0)
|
||||||
|
|
||||||
|
// Successful sync: update connection and clear any previous error state
|
||||||
await supabase
|
await supabase
|
||||||
.from('bank_connections')
|
.from('bank_connections')
|
||||||
.update({
|
.update({
|
||||||
accounts_data: accounts,
|
accounts_data: accounts,
|
||||||
last_synced_at: new Date().toISOString(),
|
last_synced_at: new Date().toISOString(),
|
||||||
|
...(connection.error_message ? { error_message: null } : {}),
|
||||||
})
|
})
|
||||||
.eq('id', connection.id)
|
.eq('id', connection.id)
|
||||||
|
|
||||||
@@ -152,7 +173,15 @@ export async function GET(request: Request) {
|
|||||||
daysUntilExpiry: daysLeft,
|
daysUntilExpiry: daysLeft,
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||||
console.error(`Sync failed for connection ${connection.id}:`, error)
|
console.error(`Sync failed for connection ${connection.id}:`, error)
|
||||||
|
|
||||||
|
// Persist error status on sync failure
|
||||||
|
await supabase
|
||||||
|
.from('bank_connections')
|
||||||
|
.update({ status: 'error', error_message: message })
|
||||||
|
.eq('id', connection.id)
|
||||||
|
|
||||||
results.push({
|
results.push({
|
||||||
connectionId: connection.id,
|
connectionId: connection.id,
|
||||||
userId: connection.user_id,
|
userId: connection.user_id,
|
||||||
@@ -181,3 +210,65 @@ export async function GET(request: Request) {
|
|||||||
results,
|
results,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send consent expiry notification email.
|
||||||
|
* Guards with last_expiry_notification_at to avoid spamming (2-day cooldown).
|
||||||
|
*/
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
async function sendConsentExpiryNotification(
|
||||||
|
supabase: SupabaseClient<any>,
|
||||||
|
connection: Record<string, unknown>,
|
||||||
|
daysLeft: number,
|
||||||
|
isExpired: boolean,
|
||||||
|
baseUrl: string
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
// Check cooldown: skip if notified within last 2 days
|
||||||
|
const lastNotified = connection.last_expiry_notification_at as string | null
|
||||||
|
if (lastNotified) {
|
||||||
|
const hoursSinceNotified = (Date.now() - new Date(lastNotified).getTime()) / (1000 * 60 * 60)
|
||||||
|
if (hoursSinceNotified < 48) return
|
||||||
|
}
|
||||||
|
|
||||||
|
const emailService = getEmailService()
|
||||||
|
if (!emailService.isConfigured()) return
|
||||||
|
|
||||||
|
const userId = connection.user_id as string
|
||||||
|
|
||||||
|
// Look up user email
|
||||||
|
const { data: userData } = await supabase.auth.admin.getUserById(userId)
|
||||||
|
if (!userData?.user?.email) return
|
||||||
|
|
||||||
|
// Look up company name
|
||||||
|
const { data: companySettings } = await supabase
|
||||||
|
.from('company_settings')
|
||||||
|
.select('company_name')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
const emailData = {
|
||||||
|
bankName: connection.bank_name as string,
|
||||||
|
daysUntilExpiry: daysLeft,
|
||||||
|
renewalUrl: `${baseUrl}/settings?tab=banking`,
|
||||||
|
companyName: companySettings?.company_name || 'gnubok',
|
||||||
|
isExpired,
|
||||||
|
}
|
||||||
|
|
||||||
|
await emailService.sendEmail({
|
||||||
|
to: userData.user.email,
|
||||||
|
subject: generateConsentExpiryEmailSubject(emailData),
|
||||||
|
html: generateConsentExpiryEmailHtml(emailData),
|
||||||
|
text: generateConsentExpiryEmailText(emailData),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Update last notification timestamp
|
||||||
|
await supabase
|
||||||
|
.from('bank_connections')
|
||||||
|
.update({ last_expiry_notification_at: new Date().toISOString() })
|
||||||
|
.eq('id', connection.id as string)
|
||||||
|
} catch (error) {
|
||||||
|
// Notification failure must not break the cron job
|
||||||
|
console.error(`[bank-sync-cron] Failed to send consent expiry notification:`, error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export async function POST(request: Request) {
|
|||||||
if (duplicate) {
|
if (duplicate) {
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
error: 'duplicate',
|
error: 'duplicate',
|
||||||
message: `This file has already been imported on ${new Date(duplicate.imported_at!).toLocaleDateString('sv-SE')}`,
|
message: `This file has already been imported on ${duplicate.imported_at ? new Date(duplicate.imported_at).toLocaleDateString('sv-SE') : 'okänt datum'}`,
|
||||||
importId: duplicate.id,
|
importId: duplicate.id,
|
||||||
}, { status: 409 })
|
}, { status: 409 })
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -46,7 +46,7 @@ export default function RootLayout({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}>) {
|
}>) {
|
||||||
return (
|
return (
|
||||||
<html lang="sv" suppressHydrationWarning>
|
<html lang="sv" suppressHydrationWarning className={`${geistSans.variable} ${geistMono.variable} ${fraunces.variable}`}>
|
||||||
<head>
|
<head>
|
||||||
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
|
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
|
||||||
<script
|
<script
|
||||||
@@ -58,11 +58,11 @@ export default function RootLayout({
|
|||||||
/>
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body
|
<body
|
||||||
className={`${geistSans.variable} ${geistMono.variable} ${fraunces.variable} antialiased`}
|
className="antialiased"
|
||||||
>
|
>
|
||||||
<ThemeProvider
|
<ThemeProvider
|
||||||
attribute="class"
|
attribute="class"
|
||||||
defaultTheme="system"
|
defaultTheme="light"
|
||||||
enableSystem
|
enableSystem
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
Landmark,
|
Landmark,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
FileWarning,
|
FileWarning,
|
||||||
|
Clock,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { getExtensionDefinition } from '@/lib/extensions/sectors'
|
import { getExtensionDefinition } from '@/lib/extensions/sectors'
|
||||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||||
@@ -41,6 +42,7 @@ interface DashboardContentProps {
|
|||||||
deadlines: Deadline[]
|
deadlines: Deadline[]
|
||||||
receiptQueue: ReceiptQueueSummary | null
|
receiptQueue: ReceiptQueueSummary | null
|
||||||
missingUnderlagCount: number
|
missingUnderlagCount: number
|
||||||
|
staleUncategorizedCount: number
|
||||||
}
|
}
|
||||||
onboardingProgress?: OnboardingProgress
|
onboardingProgress?: OnboardingProgress
|
||||||
enabledExtensions?: { sector_slug: string; extension_slug: string }[]
|
enabledExtensions?: { sector_slug: string; extension_slug: string }[]
|
||||||
@@ -182,6 +184,26 @@ export default function DashboardContent({ firstName, settings, summary, onboard
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (summary.staleUncategorizedCount > 0) {
|
||||||
|
alertItems.push(
|
||||||
|
<Link key="stale-transactions" href="/transactions" className="group">
|
||||||
|
<Card className="h-full border-destructive/30 hover:bg-destructive/[0.03] transition-colors">
|
||||||
|
<CardContent className="p-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Clock className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||||
|
<div>
|
||||||
|
<p className="font-medium text-sm">Gamla transaktioner</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-0.5">
|
||||||
|
{summary.staleUncategorizedCount} transaktioner äldre än 14 dagar saknar bokföring
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Link>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (summary.expiringBankConnections && summary.expiringBankConnections.length > 0) {
|
if (summary.expiringBankConnections && summary.expiringBankConnections.length > 0) {
|
||||||
const conn = summary.expiringBankConnections[0]
|
const conn = summary.expiringBankConnections[0]
|
||||||
alertItems.push(
|
alertItems.push(
|
||||||
@@ -249,6 +271,7 @@ export default function DashboardContent({ firstName, settings, summary, onboard
|
|||||||
hasCustomers={onboardingProgress.hasCustomers}
|
hasCustomers={onboardingProgress.hasCustomers}
|
||||||
hasInvoices={onboardingProgress.hasInvoices}
|
hasInvoices={onboardingProgress.hasInvoices}
|
||||||
hasBankConnected={onboardingProgress.hasBankConnected}
|
hasBankConnected={onboardingProgress.hasBankConnected}
|
||||||
|
hasSIEImport={onboardingProgress.hasSIEImport}
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -2,14 +2,14 @@
|
|||||||
|
|
||||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||||
import EmptyExtensionState from '@/components/extensions/shared/EmptyExtensionState'
|
import EmptyExtensionState from '@/components/extensions/shared/EmptyExtensionState'
|
||||||
import { Sparkles } from 'lucide-react'
|
import { Wand } from 'lucide-react'
|
||||||
|
|
||||||
export default function AiCategorizationWorkspace({ userId }: WorkspaceComponentProps) {
|
export default function AiCategorizationWorkspace({ userId }: WorkspaceComponentProps) {
|
||||||
return (
|
return (
|
||||||
<EmptyExtensionState
|
<EmptyExtensionState
|
||||||
title="AI-kategorisering"
|
title="AI-kategorisering"
|
||||||
description="AI-kategorisering körs automatiskt när nya transaktioner synkas. Gå till Transaktioner för att se förslag."
|
description="AI-kategorisering körs automatiskt när nya transaktioner synkas. Gå till Transaktioner för att se förslag."
|
||||||
icon={<Sparkles className="h-12 w-12 text-muted-foreground/40 mb-4" />}
|
icon={<Wand className="h-12 w-12 text-muted-foreground/40 mb-4" />}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,12 @@ import {
|
|||||||
ExternalLink,
|
ExternalLink,
|
||||||
Info,
|
Info,
|
||||||
RotateCcw,
|
RotateCcw,
|
||||||
|
AlertTriangle,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronRight,
|
||||||
|
Calendar,
|
||||||
|
XCircle,
|
||||||
|
BookOpen,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||||
|
|
||||||
@@ -732,6 +738,213 @@ function MigratingStep({ currentStep, progress }: { currentStep: string; progres
|
|||||||
|
|
||||||
// ── Result step ─────────────────────────────────────────────────
|
// ── Result step ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Format a fiscal year label from ISO dates, e.g. "2024-01-01" → "2024" or "2024/2025" */
|
||||||
|
function formatFiscalYearLabel(start: string, end: string): string {
|
||||||
|
const startYear = start.slice(0, 4)
|
||||||
|
const endYear = end.slice(0, 4)
|
||||||
|
return startYear === endYear ? startYear : `${startYear}/${endYear}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Determine the overall status icon and color for a single FY import */
|
||||||
|
function getFYStatus(r: ImportResult): { icon: 'success' | 'warning' | 'error'; label: string } {
|
||||||
|
if (r.errors.length > 0 && r.journalEntriesCreated === 0) {
|
||||||
|
return { icon: 'error', label: 'Misslyckades' }
|
||||||
|
}
|
||||||
|
if (r.errors.length > 0 || (r.details?.skippedVouchers && r.details.skippedVouchers.total > 0)) {
|
||||||
|
return { icon: 'warning', label: 'Delvis importerad' }
|
||||||
|
}
|
||||||
|
return { icon: 'success', label: 'Importerad' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const StatusIcon = ({ status }: { status: 'success' | 'warning' | 'error' }) => {
|
||||||
|
if (status === 'error') return <XCircle className="h-4 w-4 text-destructive" />
|
||||||
|
if (status === 'warning') return <AlertTriangle className="h-4 w-4 text-amber-500" />
|
||||||
|
return <CheckCircle className="h-4 w-4 text-green-600" />
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Expandable per-fiscal-year detail card */
|
||||||
|
function FiscalYearResult({ result, index }: { result: ImportResult; index: number }) {
|
||||||
|
const [expanded, setExpanded] = useState(false)
|
||||||
|
const status = getFYStatus(result)
|
||||||
|
const d = result.details
|
||||||
|
const fyLabel = d?.fiscalYear
|
||||||
|
? formatFiscalYearLabel(d.fiscalYear.start, d.fiscalYear.end)
|
||||||
|
: `Räkenskapsår ${index + 1}`
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-border">
|
||||||
|
{/* Header — always visible */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setExpanded(!expanded)}
|
||||||
|
className="flex w-full items-center gap-3 p-4 text-left transition-colors hover:bg-accent/50"
|
||||||
|
>
|
||||||
|
<StatusIcon status={status.icon} />
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-baseline gap-2">
|
||||||
|
<span className="font-medium">{fyLabel}</span>
|
||||||
|
<span className={`text-sm ${
|
||||||
|
status.icon === 'error' ? 'text-destructive' :
|
||||||
|
status.icon === 'warning' ? 'text-amber-600' :
|
||||||
|
'text-muted-foreground'
|
||||||
|
}`}>
|
||||||
|
{status.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground tabular-nums">
|
||||||
|
{result.journalEntriesCreated.toLocaleString('sv-SE')} verifikationer importerade
|
||||||
|
{d?.skippedVouchers && d.skippedVouchers.total > 0 && (
|
||||||
|
<span className="text-amber-600">
|
||||||
|
{' · '}{d.skippedVouchers.total} hoppade över
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{expanded
|
||||||
|
? <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||||
|
: <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||||
|
}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Expanded details */}
|
||||||
|
{expanded && (
|
||||||
|
<div className="border-t border-border px-4 pb-4 pt-3 space-y-3">
|
||||||
|
{/* Errors — shown prominently */}
|
||||||
|
{result.errors.length > 0 && (
|
||||||
|
<div className="rounded-md border border-destructive/20 bg-destructive/5 p-3">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<p className="text-sm font-medium text-destructive">
|
||||||
|
{result.errors.length === 1 ? '1 fel vid import' : `${result.errors.length} fel vid import`}
|
||||||
|
</p>
|
||||||
|
{result.errors.map((e, i) => (
|
||||||
|
<p key={i} className="text-sm text-muted-foreground">{e}</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Opening balance adjustment */}
|
||||||
|
{d?.openingBalance && (
|
||||||
|
<div className="rounded-md border border-border bg-muted/30 p-3">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<BookOpen className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">Ingående balanser justerade</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{d.openingBalance.explanation === 'unallocated_result' && (
|
||||||
|
<>
|
||||||
|
Differens på <span className="tabular-nums font-medium">{Math.abs(d.openingBalance.imbalance).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK</span> bokförd
|
||||||
|
på konto {d.openingBalance.bookedToAccount}. Detta beror troligen på att föregående
|
||||||
|
års resultat inte allokerats till eget kapital i källsystemet — vanligt vid byte
|
||||||
|
av bokföringsprogram.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{d.openingBalance.explanation === 'excluded_accounts' && (
|
||||||
|
<>
|
||||||
|
Exkluderade systemkonton (t.ex. Fortnox 0099) hade ingående saldon. Differensen
|
||||||
|
(<span className="tabular-nums font-medium">{Math.abs(d.openingBalance.imbalance).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK</span>)
|
||||||
|
bokförd på konto {d.openingBalance.bookedToAccount}.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{d.openingBalance.explanation === 'rounding' && (
|
||||||
|
<>
|
||||||
|
Avrundningsdifferens (<span className="tabular-nums font-medium">{Math.abs(d.openingBalance.imbalance).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK</span>)
|
||||||
|
bokförd på konto {d.openingBalance.bookedToAccount}.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{!d.openingBalance.explanation && (
|
||||||
|
<>
|
||||||
|
Differens på <span className="tabular-nums font-medium">{Math.abs(d.openingBalance.imbalance).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK</span> bokförd
|
||||||
|
på konto {d.openingBalance.bookedToAccount}.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Skipped vouchers breakdown */}
|
||||||
|
{d?.skippedVouchers && d.skippedVouchers.total > 0 && (
|
||||||
|
<div className="rounded-md border border-amber-200 bg-amber-50/50 p-3 dark:border-amber-900/30 dark:bg-amber-950/20">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-amber-700 dark:text-amber-400">
|
||||||
|
{d.skippedVouchers.total} verifikationer hoppades över
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-sm text-muted-foreground">
|
||||||
|
Ofullständiga verifikationer i källsystemet som inte kan importeras.
|
||||||
|
Saldon har justerats automatiskt via omföringsverifikation.
|
||||||
|
</p>
|
||||||
|
<div className="mt-2 grid grid-cols-2 gap-x-6 gap-y-1 text-sm text-muted-foreground tabular-nums">
|
||||||
|
{d.skippedVouchers.unbalanced > 0 && (
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>Obalanserade</span>
|
||||||
|
<span className="font-medium">{d.skippedVouchers.unbalanced}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{d.skippedVouchers.unmapped > 0 && (
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>Ej mappade konton</span>
|
||||||
|
<span className="font-medium">{d.skippedVouchers.unmapped}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{d.skippedVouchers.singleLine > 0 && (
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>Enradsverifikationer</span>
|
||||||
|
<span className="font-medium">{d.skippedVouchers.singleLine}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{d.skippedVouchers.empty > 0 && (
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span>Tomma</span>
|
||||||
|
<span className="font-medium">{d.skippedVouchers.empty}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Migration adjustment info */}
|
||||||
|
{d?.migrationAdjustment?.created && (
|
||||||
|
<div className="rounded-md border border-border bg-muted/30 p-3">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">Omföringsverifikation skapad</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{d.migrationAdjustment.accountsAdjusted} konton justerade för att saldon ska matcha
|
||||||
|
källsystemet. Verifikationen kompenserar för hoppade verifikationer så att dina
|
||||||
|
balansräkning och resultaträkning stämmer.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Retry info (only shown if retries happened) */}
|
||||||
|
{d && d.retriedBatches > 0 && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{d.retriedBatches} {d.retriedBatches === 1 ? 'batch' : 'batcher'} behövde omförsök
|
||||||
|
{d.failedBatches > 0 && (
|
||||||
|
<span className="text-destructive">
|
||||||
|
{' · '}{d.failedBatches} misslyckades trots omförsök
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function ResultStep({
|
function ResultStep({
|
||||||
results,
|
results,
|
||||||
sieResults,
|
sieResults,
|
||||||
@@ -753,8 +966,8 @@ function ResultStep({
|
|||||||
<div className="flex gap-3 rounded-lg border border-destructive/20 bg-destructive/10 p-4">
|
<div className="flex gap-3 rounded-lg border border-destructive/20 bg-destructive/10 p-4">
|
||||||
<AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-destructive" />
|
<AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-destructive" />
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium text-destructive">Migreringen misslyckades</p>
|
<p className="text-base font-medium text-destructive">Migreringen misslyckades</p>
|
||||||
<p className="text-sm text-muted-foreground">{error}</p>
|
<p className="mt-1 text-sm text-muted-foreground">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -773,77 +986,119 @@ function ResultStep({
|
|||||||
const hasResults = results || sieResults.length > 0
|
const hasResults = results || sieResults.length > 0
|
||||||
if (!hasResults) return null
|
if (!hasResults) return null
|
||||||
|
|
||||||
// Compute combined SIE totals from all FY imports
|
// Compute combined SIE stats
|
||||||
const totalJournalEntries = sieResults.reduce((sum, r) => sum + r.journalEntriesCreated, 0)
|
const totalJournalEntries = sieResults.reduce((sum, r) => sum + r.journalEntriesCreated, 0)
|
||||||
const allSieErrors = sieResults.flatMap(r => r.errors)
|
const totalErrors = sieResults.reduce((sum, r) => sum + r.errors.length, 0)
|
||||||
const allSieWarnings = sieResults.flatMap(r => r.warnings)
|
const totalSkipped = sieResults.reduce((sum, r) => (r.details?.skippedVouchers?.total || 0) + sum, 0)
|
||||||
const allSieSucceeded = sieResults.length > 0 && sieResults.every(r => r.success)
|
const allSieSucceeded = sieResults.length > 0 && sieResults.every(r => r.success)
|
||||||
|
const anySieFailed = sieResults.some(r => r.errors.length > 0 && r.journalEntriesCreated === 0)
|
||||||
|
|
||||||
|
// Overall status
|
||||||
|
const overallIcon = anySieFailed ? 'error' as const :
|
||||||
|
(!allSieSucceeded || totalErrors > 0) ? 'warning' as const : 'success' as const
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{/* ── Header card with overall summary ── */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2">
|
<CardTitle className="flex items-center gap-2.5">
|
||||||
<CheckCircle className="h-5 w-5 text-green-600" />
|
<StatusIcon status={overallIcon} />
|
||||||
Migrering klar
|
{anySieFailed ? 'Migrering delvis genomförd' :
|
||||||
|
!allSieSucceeded ? 'Migrering klar med anmärkningar' :
|
||||||
|
'Migrering klar'}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription className="text-sm">
|
||||||
Din bokföringsdata har importerats till gnubok.
|
{totalJournalEntries > 0 && (
|
||||||
|
<>
|
||||||
|
<span className="tabular-nums font-medium text-foreground">
|
||||||
|
{totalJournalEntries.toLocaleString('sv-SE')}
|
||||||
|
</span>
|
||||||
|
{' verifikationer importerade'}
|
||||||
|
{sieResults.length > 1 && ` över ${sieResults.length} räkenskapsår`}
|
||||||
|
{totalSkipped > 0 && (
|
||||||
|
<span className="text-amber-600">
|
||||||
|
{' · '}{totalSkipped} hoppade över
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
</Card>
|
||||||
<div className="grid gap-3 sm:grid-cols-2">
|
|
||||||
{/* SIE import results — combined summary */}
|
{/* ── Per-fiscal-year SIE breakdown ── */}
|
||||||
{sieResults.length > 0 && (
|
{sieResults.length > 0 && (
|
||||||
<ResultRow
|
<div className="space-y-2">
|
||||||
label="Bokföringsdata (SIE)"
|
<h3 className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||||
value={allSieSucceeded ? 'Importerad' : 'Delvis importerad'}
|
<Database className="h-4 w-4" />
|
||||||
detail={totalJournalEntries > 0
|
Bokföringsdata (SIE)
|
||||||
? `${totalJournalEntries} verifikationer skapade (${sieResults.length} räkenskapsår)`
|
</h3>
|
||||||
: `${sieResults.length} räkenskapsår importerade`
|
<div className="space-y-2">
|
||||||
}
|
{sieResults.map((r, i) => (
|
||||||
errors={allSieErrors}
|
<FiscalYearResult key={i} result={r} index={i} />
|
||||||
warnings={allSieWarnings}
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── API import results (company info, customers, etc.) ── */}
|
||||||
|
{results && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||||
|
<FileText className="h-4 w-4" />
|
||||||
|
Övriga data
|
||||||
|
</h3>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2">
|
||||||
|
{results.companyInfo && (
|
||||||
|
<EntityResultRow
|
||||||
|
icon={<Building2 className="h-4 w-4" />}
|
||||||
|
label="Företagsinformation"
|
||||||
|
status={results.companyInfo.imported ? 'success' : 'skipped'}
|
||||||
|
statusText={results.companyInfo.imported ? 'Importerad' : 'Hoppades över'}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{results.customers && (
|
||||||
{/* API import results */}
|
<EntityResultRow
|
||||||
{results?.companyInfo && (
|
icon={<Users className="h-4 w-4" />}
|
||||||
<ResultRow label="Företagsinformation" value={results.companyInfo.imported ? 'Importerad' : 'Hoppad'} />
|
|
||||||
)}
|
|
||||||
{results?.customers && (
|
|
||||||
<ResultRow
|
|
||||||
label="Kunder"
|
label="Kunder"
|
||||||
value={`${results.customers.imported} importerade`}
|
status="success"
|
||||||
|
statusText={`${results.customers.imported} importerade`}
|
||||||
detail={results.customers.skipped > 0 ? `${results.customers.skipped} fanns redan` : undefined}
|
detail={results.customers.skipped > 0 ? `${results.customers.skipped} fanns redan` : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{results?.suppliers && (
|
{results.suppliers && (
|
||||||
<ResultRow
|
<EntityResultRow
|
||||||
|
icon={<Truck className="h-4 w-4" />}
|
||||||
label="Leverantörer"
|
label="Leverantörer"
|
||||||
value={`${results.suppliers.imported} importerade`}
|
status="success"
|
||||||
|
statusText={`${results.suppliers.imported} importerade`}
|
||||||
detail={results.suppliers.skipped > 0 ? `${results.suppliers.skipped} fanns redan` : undefined}
|
detail={results.suppliers.skipped > 0 ? `${results.suppliers.skipped} fanns redan` : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{results?.salesInvoices && (
|
{results.salesInvoices && (
|
||||||
<ResultRow
|
<EntityResultRow
|
||||||
|
icon={<FileText className="h-4 w-4" />}
|
||||||
label="Kundfakturor"
|
label="Kundfakturor"
|
||||||
value={`${results.salesInvoices.imported} importerade`}
|
status="success"
|
||||||
detail={results.salesInvoices.skipped > 0 ? `${results.salesInvoices.skipped} hoppade` : undefined}
|
statusText={`${results.salesInvoices.imported} importerade`}
|
||||||
|
detail={results.salesInvoices.skipped > 0 ? `${results.salesInvoices.skipped} hoppades över` : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{results?.supplierInvoices && (
|
{results.supplierInvoices && (
|
||||||
<ResultRow
|
<EntityResultRow
|
||||||
|
icon={<FileText className="h-4 w-4" />}
|
||||||
label="Leverantörsfakturor"
|
label="Leverantörsfakturor"
|
||||||
value={`${results.supplierInvoices.imported} importerade`}
|
status="success"
|
||||||
detail={results.supplierInvoices.skipped > 0 ? `${results.supplierInvoices.skipped} hoppade` : undefined}
|
statusText={`${results.supplierInvoices.imported} importerade`}
|
||||||
|
detail={results.supplierInvoices.skipped > 0 ? `${results.supplierInvoices.skipped} hoppades över` : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
)}
|
||||||
|
|
||||||
{/* Next steps guidance */}
|
{/* ── Next steps ── */}
|
||||||
<Card className="bg-muted/50">
|
<Card className="bg-muted/50">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-base">Nästa steg</CardTitle>
|
<CardTitle className="text-base">Nästa steg</CardTitle>
|
||||||
@@ -855,7 +1110,7 @@ function ResultStep({
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">Granska importerade verifikationer</p>
|
<p className="font-medium">Granska importerade verifikationer</p>
|
||||||
<p className="text-sm text-muted-foreground">Kontrollera att bokföringen ser korrekt ut</p>
|
<p className="text-sm text-muted-foreground">Kontrollera att bokföringen ser korrekt ut i huvudboken</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
@@ -863,8 +1118,8 @@ function ResultStep({
|
|||||||
2
|
2
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">Kontrollera kunder och leverantörer</p>
|
<p className="font-medium">Stäm av balansräkningen</p>
|
||||||
<p className="text-sm text-muted-foreground">Verifiera att kontaktuppgifter och bankinfo stämmer</p>
|
<p className="text-sm text-muted-foreground">Jämför ingående balanser och saldon mot ditt tidigare system</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
@@ -872,8 +1127,8 @@ function ResultStep({
|
|||||||
3
|
3
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="font-medium">Verifiera balanserna i rapporterna</p>
|
<p className="font-medium">Kontrollera kunder och leverantörer</p>
|
||||||
<p className="text-sm text-muted-foreground">Jämför med ditt tidigare system</p>
|
<p className="text-sm text-muted-foreground">Verifiera kontaktuppgifter, organisationsnummer och bankinfo</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -903,38 +1158,29 @@ function ResultStep({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function ResultRow({
|
/** Simple row for non-SIE entity results (customers, invoices, etc.) */
|
||||||
|
function EntityResultRow({
|
||||||
|
icon,
|
||||||
label,
|
label,
|
||||||
value,
|
status,
|
||||||
|
statusText,
|
||||||
detail,
|
detail,
|
||||||
errors,
|
|
||||||
warnings,
|
|
||||||
}: {
|
}: {
|
||||||
|
icon: React.ReactNode
|
||||||
label: string
|
label: string
|
||||||
value: string
|
status: 'success' | 'skipped'
|
||||||
|
statusText: string
|
||||||
detail?: string
|
detail?: string
|
||||||
errors?: string[]
|
|
||||||
warnings?: string[]
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border border-border p-3">
|
<div className="flex items-center gap-3 rounded-lg border border-border p-3">
|
||||||
<p className="text-sm font-medium">{label}</p>
|
<div className="text-muted-foreground">{icon}</div>
|
||||||
<p className="text-sm text-muted-foreground">{value}</p>
|
<div className="flex-1 min-w-0">
|
||||||
{detail && <p className="text-xs text-muted-foreground">{detail}</p>}
|
<p className="text-sm font-medium">{label}</p>
|
||||||
{warnings && warnings.length > 0 && (
|
<p className="text-sm text-muted-foreground">{statusText}</p>
|
||||||
<p className="mt-1 text-xs text-warning-foreground">{warnings.join('. ')}</p>
|
{detail && <p className="text-sm text-muted-foreground/70">{detail}</p>}
|
||||||
)}
|
</div>
|
||||||
{errors && errors.length > 0 && (
|
<StatusIcon status={status === 'success' ? 'success' : 'warning'} />
|
||||||
<details className="mt-1">
|
|
||||||
<summary className="cursor-pointer text-xs text-destructive">
|
|
||||||
{errors.length} fel
|
|
||||||
</summary>
|
|
||||||
<ul className="mt-1 space-y-0.5 text-xs text-muted-foreground">
|
|
||||||
{errors.slice(0, 5).map((e, i) => <li key={i}>{e}</li>)}
|
|
||||||
{errors.length > 5 && <li>...och {errors.length - 5} till</li>}
|
|
||||||
</ul>
|
|
||||||
</details>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,14 @@ import { Progress } from '@/components/ui/progress'
|
|||||||
import {
|
import {
|
||||||
Check,
|
Check,
|
||||||
Circle,
|
Circle,
|
||||||
Sparkles,
|
PartyPopper,
|
||||||
|
Rocket,
|
||||||
X,
|
X,
|
||||||
|
FileUp,
|
||||||
|
ArrowRight,
|
||||||
|
UserPlus,
|
||||||
|
Receipt,
|
||||||
|
ArrowLeftRight,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
@@ -19,17 +25,20 @@ interface ChecklistItem {
|
|||||||
description: string
|
description: string
|
||||||
href: string
|
href: string
|
||||||
completed: boolean
|
completed: boolean
|
||||||
|
icon: React.ElementType
|
||||||
}
|
}
|
||||||
|
|
||||||
interface NewUserChecklistProps {
|
interface NewUserChecklistProps {
|
||||||
hasCustomers: boolean
|
hasCustomers: boolean
|
||||||
hasInvoices: boolean
|
hasInvoices: boolean
|
||||||
hasBankConnected: boolean
|
hasBankConnected: boolean
|
||||||
|
hasSIEImport: boolean
|
||||||
onDismiss?: () => void
|
onDismiss?: () => void
|
||||||
className?: string
|
className?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const CHECKLIST_DISMISSED_KEY = 'erp_checklist_dismissed'
|
const CHECKLIST_DISMISSED_KEY = 'erp_checklist_dismissed'
|
||||||
|
const FRESH_START_KEY = 'erp_onboarding_fresh'
|
||||||
|
|
||||||
export default function NewUserChecklist({
|
export default function NewUserChecklist({
|
||||||
hasCustomers,
|
hasCustomers,
|
||||||
@@ -38,49 +47,24 @@ export default function NewUserChecklist({
|
|||||||
onDismiss,
|
onDismiss,
|
||||||
className,
|
className,
|
||||||
}: NewUserChecklistProps) {
|
}: NewUserChecklistProps) {
|
||||||
const [isDismissed, setIsDismissed] = useState(true) // Start hidden until we check localStorage
|
const [isDismissed, setIsDismissed] = useState(true)
|
||||||
const [isAnimatingOut, setIsAnimatingOut] = useState(false)
|
const [isAnimatingOut, setIsAnimatingOut] = useState(false)
|
||||||
|
const [showChecklist, setShowChecklist] = useState(false)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Check if checklist has been dismissed
|
|
||||||
const dismissed = localStorage.getItem(CHECKLIST_DISMISSED_KEY)
|
const dismissed = localStorage.getItem(CHECKLIST_DISMISSED_KEY)
|
||||||
setIsDismissed(dismissed === 'true')
|
setIsDismissed(dismissed === 'true')
|
||||||
|
|
||||||
|
const freshStart = localStorage.getItem(FRESH_START_KEY)
|
||||||
|
if (freshStart === 'true') {
|
||||||
|
setShowChecklist(true)
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const items: ChecklistItem[] = [
|
const handleFreshStart = () => {
|
||||||
{
|
setShowChecklist(true)
|
||||||
id: 'account',
|
localStorage.setItem(FRESH_START_KEY, 'true')
|
||||||
label: 'Skapa konto',
|
}
|
||||||
description: 'Du har ett konto!',
|
|
||||||
href: '#',
|
|
||||||
completed: true, // Always completed if they're seeing this
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'customer',
|
|
||||||
label: 'Lägg till din första kund',
|
|
||||||
description: 'Spara kunduppgifter för enkel fakturering',
|
|
||||||
href: '/customers/new',
|
|
||||||
completed: hasCustomers,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'invoice',
|
|
||||||
label: 'Skicka din första faktura',
|
|
||||||
description: 'Skapa en professionell faktura på 60 sekunder',
|
|
||||||
href: '/invoices/new',
|
|
||||||
completed: hasInvoices,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'bank',
|
|
||||||
label: 'Importera transaktioner',
|
|
||||||
description: 'Importera kontoutdrag från din bank',
|
|
||||||
href: '/import',
|
|
||||||
completed: hasBankConnected,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const completedCount = items.filter((item) => item.completed).length
|
|
||||||
const progress = (completedCount / items.length) * 100
|
|
||||||
const allCompleted = completedCount === items.length
|
|
||||||
|
|
||||||
const handleDismiss = () => {
|
const handleDismiss = () => {
|
||||||
setIsAnimatingOut(true)
|
setIsAnimatingOut(true)
|
||||||
@@ -91,19 +75,49 @@ export default function NewUserChecklist({
|
|||||||
}, 300)
|
}, 300)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't show if dismissed or all completed
|
const items: ChecklistItem[] = [
|
||||||
|
{
|
||||||
|
id: 'customer',
|
||||||
|
label: 'Lägg till din första kund',
|
||||||
|
description: 'Spara kunduppgifter för enkel fakturering',
|
||||||
|
href: '/customers/new',
|
||||||
|
completed: hasCustomers,
|
||||||
|
icon: UserPlus,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'invoice',
|
||||||
|
label: 'Skicka din första faktura',
|
||||||
|
description: 'Skapa en professionell faktura på 60 sekunder',
|
||||||
|
href: '/invoices/new',
|
||||||
|
completed: hasInvoices,
|
||||||
|
icon: Receipt,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'bank',
|
||||||
|
label: 'Importera transaktioner',
|
||||||
|
description: 'Koppla bank eller ladda upp kontoutdrag',
|
||||||
|
href: '/import',
|
||||||
|
completed: hasBankConnected,
|
||||||
|
icon: ArrowLeftRight,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const completedCount = items.filter((item) => item.completed).length
|
||||||
|
const progress = (completedCount / items.length) * 100
|
||||||
|
const allCompleted = completedCount === items.length
|
||||||
|
|
||||||
if (isDismissed) {
|
if (isDismissed) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-dismiss after all completed with celebration
|
// Celebration state when all checklist items done
|
||||||
if (allCompleted && !isAnimatingOut) {
|
if (showChecklist && allCompleted && !isAnimatingOut) {
|
||||||
return (
|
return (
|
||||||
<Card className={cn('border-success/50 bg-success/5', className)}>
|
<Card className={cn('border-success/50 bg-success/5', className)}>
|
||||||
<CardContent className="pt-6">
|
<CardContent className="pt-6">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<div className="p-3 rounded-full bg-success/10">
|
<div className="p-3 rounded-full bg-success/10">
|
||||||
<Sparkles className="h-6 w-6 text-success" />
|
<PartyPopper className="h-6 w-6 text-success" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<p className="font-medium text-success">Snyggt jobbat!</p>
|
<p className="font-medium text-success">Snyggt jobbat!</p>
|
||||||
@@ -120,6 +134,85 @@ export default function NewUserChecklist({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Path selection — shown initially
|
||||||
|
if (!showChecklist) {
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
className={cn(
|
||||||
|
'transition-[opacity,transform] duration-300',
|
||||||
|
isAnimatingOut && 'opacity-0 scale-95',
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle className="text-base">Välkommen till gnubok</CardTitle>
|
||||||
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
|
Hur vill du komma igång?
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-muted-foreground"
|
||||||
|
onClick={handleDismiss}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Stäng</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="pt-0">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
{/* Migration path — routes directly to import/migration wizard */}
|
||||||
|
<Link
|
||||||
|
href="/import"
|
||||||
|
className="group text-left p-4 rounded-xl border border-border/60 hover:border-primary/40 hover:bg-primary/[0.02] transition-all duration-150 active:scale-[0.98]"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="p-2 rounded-lg bg-primary/[0.06] group-hover:bg-primary/[0.1] transition-colors">
|
||||||
|
<FileUp className="h-4 w-4 text-primary" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-sm font-medium group-hover:text-primary transition-colors">
|
||||||
|
Migrera från annat system
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1 leading-relaxed">
|
||||||
|
Flytta bokföring, kunder, leverantörer och fakturor från Fortnox, Visma, Bokio, Björn Lundén eller Briox
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ArrowRight className="h-4 w-4 text-muted-foreground/40 group-hover:text-primary/60 mt-0.5 flex-shrink-0 transition-colors" />
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{/* Fresh start path */}
|
||||||
|
<button
|
||||||
|
onClick={handleFreshStart}
|
||||||
|
className="group text-left p-4 rounded-xl border border-border/60 hover:border-primary/40 hover:bg-primary/[0.02] transition-all duration-150 active:scale-[0.98]"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="p-2 rounded-lg bg-muted/60 group-hover:bg-primary/[0.06] transition-colors">
|
||||||
|
<Rocket className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-sm font-medium group-hover:text-primary transition-colors">
|
||||||
|
Börja från noll
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1 leading-relaxed">
|
||||||
|
Starta din bokföring utan tidigare data — perfekt för nya verksamheter
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ArrowRight className="h-4 w-4 text-muted-foreground/40 group-hover:text-primary/60 mt-0.5 flex-shrink-0 transition-colors" />
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fresh start checklist
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -136,21 +229,36 @@ export default function NewUserChecklist({
|
|||||||
{completedCount} av {items.length} steg klara
|
{completedCount} av {items.length} steg klara
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<div className="flex items-center gap-1">
|
||||||
variant="ghost"
|
<Button
|
||||||
size="icon"
|
variant="ghost"
|
||||||
className="h-8 w-8 text-muted-foreground"
|
size="sm"
|
||||||
onClick={handleDismiss}
|
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||||
>
|
onClick={() => {
|
||||||
<X className="h-4 w-4" />
|
setShowChecklist(false)
|
||||||
<span className="sr-only">Stäng checklista</span>
|
localStorage.removeItem(FRESH_START_KEY)
|
||||||
</Button>
|
}}
|
||||||
|
>
|
||||||
|
Byt
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8 text-muted-foreground"
|
||||||
|
onClick={handleDismiss}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Stäng checklista</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Progress value={progress} className="h-1.5 mt-3" />
|
<Progress value={progress} className="h-1.5 mt-3" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="pt-0">
|
<CardContent className="pt-0">
|
||||||
<ul className="space-y-1">
|
<ul className="space-y-1">
|
||||||
{items.map((item) => (
|
{items.map((item) => {
|
||||||
|
const Icon = item.icon
|
||||||
|
return (
|
||||||
<li key={item.id}>
|
<li key={item.id}>
|
||||||
{item.completed ? (
|
{item.completed ? (
|
||||||
<div className="flex items-center gap-3 p-2 rounded-lg">
|
<div className="flex items-center gap-3 p-2 rounded-lg">
|
||||||
@@ -170,7 +278,8 @@ export default function NewUserChecklist({
|
|||||||
<Circle className="h-3.5 w-3.5 text-muted-foreground" />
|
<Circle className="h-3.5 w-3.5 text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<p className="text-sm font-medium group-hover:text-primary transition-colors">
|
<p className="text-sm font-medium group-hover:text-primary transition-colors flex items-center gap-1.5">
|
||||||
|
<Icon className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
|
||||||
{item.label}
|
{item.label}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-muted-foreground truncate">
|
<p className="text-xs text-muted-foreground truncate">
|
||||||
@@ -180,7 +289,8 @@ export default function NewUserChecklist({
|
|||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
</li>
|
</li>
|
||||||
))}
|
)
|
||||||
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import {
|
|||||||
Check,
|
Check,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
Sparkles,
|
Wand,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import JournalEntryPreview from './JournalEntryPreview'
|
import JournalEntryPreview from './JournalEntryPreview'
|
||||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||||
@@ -436,7 +436,7 @@ export default function DescribeTransactionDialog({
|
|||||||
<div className="flex items-start justify-between gap-2">
|
<div className="flex items-start justify-between gap-2">
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-1.5 mb-1">
|
<div className="flex items-center gap-1.5 mb-1">
|
||||||
<Sparkles className="h-3.5 w-3.5 text-violet-500" />
|
<Wand className="h-3.5 w-3.5 text-violet-500" />
|
||||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300">
|
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300">
|
||||||
AI-förslag
|
AI-förslag
|
||||||
</Badge>
|
</Badge>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import { Upload, Sparkles, Plus, CheckSquare, FileText } from 'lucide-react'
|
import { Upload, Wand, Plus, CheckSquare, FileText } from 'lucide-react'
|
||||||
import type { ViewMode } from './transaction-types'
|
import type { ViewMode } from './transaction-types'
|
||||||
|
|
||||||
interface TransactionStatusBarProps {
|
interface TransactionStatusBarProps {
|
||||||
@@ -66,7 +66,7 @@ export default function TransactionStatusBar({
|
|||||||
onClick={onOpenSwipeView}
|
onClick={onOpenSwipeView}
|
||||||
disabled={isLoadingSuggestions}
|
disabled={isLoadingSuggestions}
|
||||||
>
|
>
|
||||||
<Sparkles className="mr-2 h-4 w-4" />
|
<Wand className="mr-2 h-4 w-4" />
|
||||||
{isLoadingSuggestions ? 'Laddar...' : 'Gå igenom alla'}
|
{isLoadingSuggestions ? 'Laddar...' : 'Gå igenom alla'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
"definition": {
|
"definition": {
|
||||||
"name": "AI-kategorisering",
|
"name": "AI-kategorisering",
|
||||||
"category": "operations",
|
"category": "operations",
|
||||||
"icon": "Sparkles",
|
"icon": "Wand",
|
||||||
"dataPattern": "core",
|
"dataPattern": "core",
|
||||||
"readsCoreTables": ["transactions"],
|
"readsCoreTables": ["transactions"],
|
||||||
"description": "AI-drivna kategoriförslag för transaktioner",
|
"description": "AI-drivna kategoriförslag för transaktioner",
|
||||||
|
|||||||
@@ -51,11 +51,85 @@ function getOrgNumber(party: PartyDto): string | null {
|
|||||||
return party.legalEntity?.companyId || null
|
return party.legalEntity?.companyId || null
|
||||||
}
|
}
|
||||||
|
|
||||||
const EU_COUNTRIES = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SI', 'SK']
|
const EU_COUNTRIES = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SI', 'SK']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a string looks like a Swedish org number (XXXXXX-XXXX or 10 digits).
|
||||||
|
* Swedish org numbers are 10 digits where the third digit is >= 2 (to distinguish
|
||||||
|
* from personal numbers where month 01-12 appears in positions 3-4).
|
||||||
|
*/
|
||||||
|
function looksLikeSwedishOrgNumber(orgNumber: string | null | undefined): boolean {
|
||||||
|
if (!orgNumber) return false
|
||||||
|
const digits = orgNumber.replace(/[-\s]/g, '')
|
||||||
|
if (digits.length !== 10 || !/^\d+$/.test(digits)) return false
|
||||||
|
// Third digit >= 2 distinguishes org numbers from personal numbers
|
||||||
|
const thirdDigit = parseInt(digits[2], 10)
|
||||||
|
return thirdDigit >= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Company name suffixes that indicate a foreign (non-Swedish) entity.
|
||||||
|
* These override the default swedish_business assumption when no other
|
||||||
|
* signals (VAT, country code, org number) are available.
|
||||||
|
*/
|
||||||
|
const FOREIGN_SUFFIXES: { suffix: string; region: 'eu' | 'non_eu' }[] = [
|
||||||
|
// German
|
||||||
|
{ suffix: 'gmbh', region: 'eu' },
|
||||||
|
{ suffix: 'ag', region: 'eu' },
|
||||||
|
{ suffix: 'e.v.', region: 'eu' },
|
||||||
|
{ suffix: 'ohg', region: 'eu' },
|
||||||
|
{ suffix: 'kg', region: 'eu' },
|
||||||
|
{ suffix: 'ug', region: 'eu' },
|
||||||
|
// French
|
||||||
|
{ suffix: 'sarl', region: 'eu' },
|
||||||
|
{ suffix: 's.a.r.l.', region: 'eu' },
|
||||||
|
{ suffix: 'sas', region: 'eu' },
|
||||||
|
// Dutch/Belgian
|
||||||
|
{ suffix: 'b.v.', region: 'eu' },
|
||||||
|
{ suffix: 'n.v.', region: 'eu' },
|
||||||
|
{ suffix: 'bv', region: 'eu' },
|
||||||
|
{ suffix: 'nv', region: 'eu' },
|
||||||
|
// Spanish/Italian
|
||||||
|
{ suffix: 's.l.', region: 'eu' },
|
||||||
|
{ suffix: 's.r.l.', region: 'eu' },
|
||||||
|
// Finnish
|
||||||
|
{ suffix: 'oy', region: 'eu' },
|
||||||
|
{ suffix: 'oyj', region: 'eu' },
|
||||||
|
// Danish/Norwegian
|
||||||
|
{ suffix: 'a/s', region: 'eu' },
|
||||||
|
{ suffix: 'aps', region: 'eu' },
|
||||||
|
// Anglo (could be UK, US, etc. — treat as non-EU since UK left)
|
||||||
|
{ suffix: 'ltd', region: 'non_eu' },
|
||||||
|
{ suffix: 'limited', region: 'non_eu' },
|
||||||
|
{ suffix: 'llc', region: 'non_eu' },
|
||||||
|
{ suffix: 'inc', region: 'non_eu' },
|
||||||
|
{ suffix: 'corp', region: 'non_eu' },
|
||||||
|
{ suffix: 'plc', region: 'non_eu' },
|
||||||
|
// Irish (EU)
|
||||||
|
{ suffix: 'dac', region: 'eu' },
|
||||||
|
]
|
||||||
|
|
||||||
|
function inferRegionFromName(name: string | undefined): 'eu' | 'non_eu' | null {
|
||||||
|
if (!name) return null
|
||||||
|
const lower = name.toLowerCase().trim()
|
||||||
|
for (const { suffix, region } of FOREIGN_SUFFIXES) {
|
||||||
|
// Match as a word boundary at the end: "Acme GmbH" but not "Gmbhsson"
|
||||||
|
if (lower.endsWith(suffix) || lower.endsWith(suffix + '.')) {
|
||||||
|
// Check that there's a space or start before the suffix
|
||||||
|
const pos = lower.lastIndexOf(suffix)
|
||||||
|
if (pos === 0 || lower[pos - 1] === ' ') {
|
||||||
|
return region
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
function inferTypeFromVatOrCountry(
|
function inferTypeFromVatOrCountry(
|
||||||
vatNumber: string | undefined,
|
vatNumber: string | undefined,
|
||||||
countryCode: string | undefined
|
countryCode: string | undefined,
|
||||||
|
orgNumber?: string | null,
|
||||||
|
companyName?: string
|
||||||
): 'swedish_business' | 'eu_business' | 'non_eu_business' {
|
): 'swedish_business' | 'eu_business' | 'non_eu_business' {
|
||||||
// 1. VAT number prefix is the strongest signal
|
// 1. VAT number prefix is the strongest signal
|
||||||
if (vatNumber) {
|
if (vatNumber) {
|
||||||
@@ -65,20 +139,68 @@ function inferTypeFromVatOrCountry(
|
|||||||
return 'non_eu_business'
|
return 'non_eu_business'
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Fall back to address country
|
// 2. Explicit country code
|
||||||
const country = countryCode?.toUpperCase()
|
const country = countryCode?.toUpperCase()
|
||||||
if (!country || country === 'SE') return 'swedish_business'
|
if (country === 'SE') return 'swedish_business'
|
||||||
if (EU_COUNTRIES.includes(country)) return 'eu_business'
|
if (country && EU_COUNTRIES.includes(country)) return 'eu_business'
|
||||||
return 'non_eu_business'
|
if (country) return 'non_eu_business'
|
||||||
|
|
||||||
|
// 3. Swedish-format org number is strong evidence of domestic entity
|
||||||
|
if (looksLikeSwedishOrgNumber(orgNumber)) return 'swedish_business'
|
||||||
|
|
||||||
|
// 4. Non-Swedish org number format (wrong digit count) → not Swedish
|
||||||
|
if (orgNumber) {
|
||||||
|
const digits = orgNumber.replace(/[-\s]/g, '')
|
||||||
|
if (digits.length > 0 && digits.length !== 10) {
|
||||||
|
// Not a Swedish org number — use name heuristic or default to non_eu
|
||||||
|
const nameRegion = inferRegionFromName(companyName)
|
||||||
|
if (nameRegion === 'eu') return 'eu_business'
|
||||||
|
return 'non_eu_business'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Company name suffix heuristic (GmbH, Ltd, etc.)
|
||||||
|
const nameRegion = inferRegionFromName(companyName)
|
||||||
|
if (nameRegion === 'eu') return 'eu_business'
|
||||||
|
if (nameRegion === 'non_eu') return 'non_eu_business'
|
||||||
|
|
||||||
|
// 6. No signal at all — default to swedish_business (most common in Swedish systems)
|
||||||
|
return 'swedish_business'
|
||||||
}
|
}
|
||||||
|
|
||||||
function inferCustomerType(dto: CustomerDto): CustomerType {
|
function inferCustomerType(dto: CustomerDto): CustomerType {
|
||||||
if (dto.type === 'private') return 'individual'
|
if (dto.type === 'private') return 'individual'
|
||||||
return inferTypeFromVatOrCountry(dto.vatNumber, dto.party.postalAddress?.countryCode)
|
return inferTypeFromVatOrCountry(
|
||||||
|
dto.vatNumber,
|
||||||
|
dto.party.postalAddress?.countryCode,
|
||||||
|
getOrgNumber(dto.party),
|
||||||
|
dto.party.name
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function inferSupplierType(dto: SupplierDto): SupplierType {
|
function inferSupplierType(dto: SupplierDto): SupplierType {
|
||||||
return inferTypeFromVatOrCountry(dto.vatNumber, dto.party.postalAddress?.countryCode)
|
return inferTypeFromVatOrCountry(
|
||||||
|
dto.vatNumber,
|
||||||
|
dto.party.postalAddress?.countryCode,
|
||||||
|
getOrgNumber(dto.party),
|
||||||
|
dto.party.name
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Infer customer/supplier type from a PartyDto (used by orchestrator for
|
||||||
|
* minimal entity creation from invoice data).
|
||||||
|
*/
|
||||||
|
export function inferTypeFromParty(
|
||||||
|
party: PartyDto,
|
||||||
|
vatNumber?: string
|
||||||
|
): 'swedish_business' | 'eu_business' | 'non_eu_business' {
|
||||||
|
return inferTypeFromVatOrCountry(
|
||||||
|
vatNumber,
|
||||||
|
party.postalAddress?.countryCode,
|
||||||
|
getOrgNumber(party),
|
||||||
|
party.name
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function inferVatTreatment(taxPercent?: number, currencyCode?: string): VatTreatment {
|
function inferVatTreatment(taxPercent?: number, currencyCode?: string): VatTreatment {
|
||||||
@@ -183,7 +305,7 @@ export function mapSalesInvoice(
|
|||||||
your_reference: null,
|
your_reference: null,
|
||||||
our_reference: null,
|
our_reference: null,
|
||||||
notes: dto.note || null,
|
notes: dto.note || null,
|
||||||
document_type: isCreditNote ? 'invoice' : 'invoice',
|
document_type: isCreditNote ? 'credit_note' : 'invoice',
|
||||||
paid_at: dto.paymentStatus.paid ? dto.paymentStatus.lastPaymentDate || dto.issueDate : null,
|
paid_at: dto.paymentStatus.paid ? dto.paymentStatus.lastPaymentDate || dto.issueDate : null,
|
||||||
paid_amount: dto.paymentStatus.paid ? total : round2(total - dto.paymentStatus.balance.value),
|
paid_amount: dto.paymentStatus.paid ? total : round2(total - dto.paymentStatus.balance.value),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
mapSalesInvoice,
|
mapSalesInvoice,
|
||||||
mapSupplierInvoice,
|
mapSupplierInvoice,
|
||||||
mapCompanyInfo,
|
mapCompanyInfo,
|
||||||
|
inferTypeFromParty,
|
||||||
} from './entity-mapper'
|
} from './entity-mapper'
|
||||||
|
|
||||||
export interface MigrationOptions {
|
export interface MigrationOptions {
|
||||||
@@ -246,12 +247,13 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!customerId) {
|
if (!customerId) {
|
||||||
|
const customerType = inferTypeFromParty(inv.customer)
|
||||||
const minimalCustomer = {
|
const minimalCustomer = {
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
name: inv.customer.name,
|
name: inv.customer.name,
|
||||||
customer_type: 'swedish_business',
|
customer_type: customerType,
|
||||||
default_payment_terms: 30,
|
default_payment_terms: 30,
|
||||||
country: 'SE',
|
country: inv.customer.postalAddress?.countryCode || (customerType === 'swedish_business' ? 'SE' : null),
|
||||||
vat_number_validated: false,
|
vat_number_validated: false,
|
||||||
}
|
}
|
||||||
const { data: created, error: custErr } = await supabase
|
const { data: created, error: custErr } = await supabase
|
||||||
@@ -356,13 +358,14 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!supplierId) {
|
if (!supplierId) {
|
||||||
|
const supplierType = inferTypeFromParty(inv.supplier)
|
||||||
const minimalSupplier = {
|
const minimalSupplier = {
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
name: inv.supplier.name,
|
name: inv.supplier.name,
|
||||||
supplier_type: 'swedish_business',
|
supplier_type: supplierType,
|
||||||
default_payment_terms: 30,
|
default_payment_terms: 30,
|
||||||
default_currency: 'SEK',
|
default_currency: 'SEK',
|
||||||
country: 'SE',
|
country: inv.supplier.postalAddress?.countryCode || (supplierType === 'swedish_business' ? 'SE' : null),
|
||||||
}
|
}
|
||||||
const { data: created, error: supErr } = await supabase
|
const { data: created, error: supErr } = await supabase
|
||||||
.from('suppliers')
|
.from('suppliers')
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ interface BankConnectionStatusProps {
|
|||||||
connection: BankConnection
|
connection: BankConnection
|
||||||
onSync: (connectionId: string) => void
|
onSync: (connectionId: string) => void
|
||||||
onDisconnect: (connectionId: string) => void
|
onDisconnect: (connectionId: string) => void
|
||||||
|
onReconnect?: (bank: { name: string; country: string }) => void
|
||||||
isSyncing?: boolean
|
isSyncing?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,39 +27,53 @@ export function BankConnectionStatus({
|
|||||||
connection,
|
connection,
|
||||||
onSync,
|
onSync,
|
||||||
onDisconnect,
|
onDisconnect,
|
||||||
|
onReconnect,
|
||||||
isSyncing = false,
|
isSyncing = false,
|
||||||
}: BankConnectionStatusProps) {
|
}: BankConnectionStatusProps) {
|
||||||
const daysUntilExpiry = getDaysUntilExpiry(connection.consent_expires)
|
const daysUntilExpiry = getDaysUntilExpiry(connection.consent_expires)
|
||||||
const isExpiring = isConsentExpiringSoon(connection.consent_expires)
|
const isExpiring = isConsentExpiringSoon(connection.consent_expires)
|
||||||
|
|
||||||
const statusConfig = {
|
type StatusEntry = {
|
||||||
|
icon: typeof CheckCircle
|
||||||
|
color: string
|
||||||
|
label: string
|
||||||
|
variant: 'success' | 'warning' | 'destructive' | 'secondary'
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusConfig: Record<string, StatusEntry> = {
|
||||||
active: {
|
active: {
|
||||||
icon: CheckCircle,
|
icon: CheckCircle,
|
||||||
color: 'text-success',
|
color: 'text-success',
|
||||||
label: 'Aktiv',
|
label: 'Aktiv',
|
||||||
variant: 'success' as const,
|
variant: 'success',
|
||||||
},
|
},
|
||||||
pending: {
|
pending: {
|
||||||
icon: Loader2,
|
icon: Loader2,
|
||||||
color: 'text-warning',
|
color: 'text-warning',
|
||||||
label: 'Väntar',
|
label: 'Väntar',
|
||||||
variant: 'warning' as const,
|
variant: 'warning',
|
||||||
|
},
|
||||||
|
expired: {
|
||||||
|
icon: AlertTriangle,
|
||||||
|
color: 'text-warning',
|
||||||
|
label: 'Utgånget samtycke',
|
||||||
|
variant: 'warning',
|
||||||
},
|
},
|
||||||
error: {
|
error: {
|
||||||
icon: XCircle,
|
icon: XCircle,
|
||||||
color: 'text-destructive',
|
color: 'text-destructive',
|
||||||
label: 'Fel',
|
label: 'Fel',
|
||||||
variant: 'destructive' as const,
|
variant: 'destructive',
|
||||||
},
|
},
|
||||||
revoked: {
|
revoked: {
|
||||||
icon: XCircle,
|
icon: XCircle,
|
||||||
color: 'text-gray-600',
|
color: 'text-gray-600',
|
||||||
label: 'Bortkopplad',
|
label: 'Bortkopplad',
|
||||||
variant: 'secondary' as const,
|
variant: 'secondary',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
const status = statusConfig[connection.status as keyof typeof statusConfig] || statusConfig.error
|
const status = statusConfig[connection.status] || statusConfig.error
|
||||||
const StatusIcon = status.icon
|
const StatusIcon = status.icon
|
||||||
|
|
||||||
// Parse accounts from connection
|
// Parse accounts from connection
|
||||||
@@ -81,6 +96,10 @@ export function BankConnectionStatus({
|
|||||||
return `${daysAgo}d sedan`
|
return `${daysAgo}d sedan`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isConnectionExpired = connection.status === 'expired'
|
||||||
|
const isConnectionError = connection.status === 'error'
|
||||||
|
const errorMessage = 'error_message' in connection ? String((connection as Record<string, unknown>).error_message || '') : ''
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border rounded-lg p-4 space-y-4">
|
<div className="border rounded-lg p-4 space-y-4">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -104,6 +123,35 @@ export function BankConnectionStatus({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
{isConnectionExpired && onReconnect && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onReconnect({
|
||||||
|
name: connection.bank_name,
|
||||||
|
country: (connection.provider as string)?.split('-').pop()?.toUpperCase() || 'SE',
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
Förnya anslutning
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{isConnectionError && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => onSync(connection.id)}
|
||||||
|
disabled={isSyncing}
|
||||||
|
>
|
||||||
|
{isSyncing ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<RefreshCw className="h-4 w-4 mr-1" />
|
||||||
|
Försök igen
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{connection.status === 'active' && (
|
{connection.status === 'active' && (
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -128,8 +176,28 @@ export function BankConnectionStatus({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Consent expiry warning */}
|
{/* Error message */}
|
||||||
{isExpiring && daysUntilExpiry !== null && (
|
{isConnectionError && errorMessage && (
|
||||||
|
<div className="flex items-center gap-2 p-3 bg-destructive/10 rounded-lg">
|
||||||
|
<XCircle className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||||
|
<span className="text-sm text-destructive">
|
||||||
|
{errorMessage}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Expired consent notice */}
|
||||||
|
{isConnectionExpired && (
|
||||||
|
<div className="flex items-center gap-2 p-3 bg-warning/10 rounded-lg">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-warning flex-shrink-0" />
|
||||||
|
<span className="text-sm">
|
||||||
|
PSD2-samtycket har löpt ut. Förnya anslutningen för att återuppta synkroniseringen.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Consent expiry warning (for active connections) */}
|
||||||
|
{!isConnectionExpired && isExpiring && daysUntilExpiry !== null && (
|
||||||
<div className="flex items-center gap-2 p-3 bg-warning/10 rounded-lg">
|
<div className="flex items-center gap-2 p-3 bg-warning/10 rounded-lg">
|
||||||
<AlertTriangle className="h-4 w-4 text-warning" />
|
<AlertTriangle className="h-4 w-4 text-warning" />
|
||||||
<span className="text-sm">
|
<span className="text-sm">
|
||||||
|
|||||||
@@ -151,11 +151,36 @@ export default function BankingSettingsPanel() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const activeConnections = bankConnections.filter((c) => c.status === 'active')
|
const activeConnections = bankConnections.filter((c) => c.status === 'active')
|
||||||
|
const actionRequiredConnections = bankConnections.filter((c) => ['expired', 'error'].includes(c.status))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<DestructiveConfirmDialog {...dialogProps} />
|
<DestructiveConfirmDialog {...dialogProps} />
|
||||||
|
|
||||||
|
{/* Action required — expired/error connections */}
|
||||||
|
{actionRequiredConnections.length > 0 && (
|
||||||
|
<Card className="border-warning/30">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Åtgärd krävs</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Dessa anslutningar behöver uppmärksamhet.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{actionRequiredConnections.map((connection) => (
|
||||||
|
<BankConnectionStatus
|
||||||
|
key={connection.id}
|
||||||
|
connection={connection}
|
||||||
|
onSync={handleSyncTransactions}
|
||||||
|
onDisconnect={handleDisconnectBank}
|
||||||
|
onReconnect={handleConnectBank}
|
||||||
|
isSyncing={syncingConnectionId === connection.id}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Connected banks */}
|
{/* Connected banks */}
|
||||||
{activeConnections.length > 0 && (
|
{activeConnections.length > 0 && (
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
@@ -94,11 +94,14 @@ export const enableBankingExtension: Extension = {
|
|||||||
|
|
||||||
const redirectUrl = `${process.env.NEXT_PUBLIC_APP_URL}/api/extensions/enable-banking/callback`
|
const redirectUrl = `${process.env.NEXT_PUBLIC_APP_URL}/api/extensions/enable-banking/callback`
|
||||||
|
|
||||||
|
// Generate cryptographic state token for CSRF protection
|
||||||
|
const oauthState = crypto.randomUUID()
|
||||||
|
|
||||||
const { url, authorization_id } = await startAuthorization(
|
const { url, authorization_id } = await startAuthorization(
|
||||||
aspsp_name,
|
aspsp_name,
|
||||||
aspsp_country,
|
aspsp_country,
|
||||||
redirectUrl,
|
redirectUrl,
|
||||||
user.id,
|
oauthState,
|
||||||
psuType
|
psuType
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -109,6 +112,7 @@ export const enableBankingExtension: Extension = {
|
|||||||
provider: `${aspsp_name.toLowerCase().replace(/\s+/g, '-')}-${aspsp_country.toLowerCase()}`,
|
provider: `${aspsp_name.toLowerCase().replace(/\s+/g, '-')}-${aspsp_country.toLowerCase()}`,
|
||||||
bank_name: aspsp_name,
|
bank_name: aspsp_name,
|
||||||
authorization_id,
|
authorization_id,
|
||||||
|
oauth_state: oauthState,
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
})
|
})
|
||||||
.select()
|
.select()
|
||||||
@@ -144,7 +148,8 @@ export const enableBankingExtension: Extension = {
|
|||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const { connection_id, days_back = 30 } = await request.json()
|
const { connection_id, days_back: rawDaysBack = 30 } = await request.json()
|
||||||
|
const days_back = Math.min(Math.max(1, rawDaysBack), 365)
|
||||||
|
|
||||||
const { data: connection, error: connectionError } = await supabase
|
const { data: connection, error: connectionError } = await supabase
|
||||||
.from('bank_connections')
|
.from('bank_connections')
|
||||||
@@ -168,6 +173,7 @@ export const enableBankingExtension: Extension = {
|
|||||||
const fromDate = new Date(Date.now() - days_back * 24 * 60 * 60 * 1000)
|
const fromDate = new Date(Date.now() - days_back * 24 * 60 * 60 * 1000)
|
||||||
.toISOString()
|
.toISOString()
|
||||||
.split('T')[0]
|
.split('T')[0]
|
||||||
|
const syncStartedAt = new Date().toISOString()
|
||||||
|
|
||||||
// Use ctx.services.ingestTransactions when available
|
// Use ctx.services.ingestTransactions when available
|
||||||
const ingestFn = ctx?.services.ingestTransactions
|
const ingestFn = ctx?.services.ingestTransactions
|
||||||
@@ -202,7 +208,7 @@ export const enableBankingExtension: Extension = {
|
|||||||
.select('*')
|
.select('*')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
.eq('bank_connection_id', connection.id)
|
.eq('bank_connection_id', connection.id)
|
||||||
.gte('created_at', fromDate)
|
.gte('created_at', syncStartedAt)
|
||||||
.order('created_at', { ascending: false })
|
.order('created_at', { ascending: false })
|
||||||
.limit(totalImported)
|
.limit(totalImported)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
|
||||||
|
// Mock jwt module before importing api-client
|
||||||
|
const mockGenerateJWT = vi.fn().mockReturnValue('test-jwt-token')
|
||||||
|
vi.mock('../jwt', () => ({
|
||||||
|
generateJWT: (...args: unknown[]) => mockGenerateJWT(...args),
|
||||||
|
getAuthorizationHeader: () => `Bearer ${mockGenerateJWT()}`,
|
||||||
|
_resetTokenCache: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Mock environment
|
||||||
|
vi.stubEnv('ENABLE_BANKING_API_URL', 'https://api.test.com')
|
||||||
|
|
||||||
|
import {
|
||||||
|
getASPSPs,
|
||||||
|
getAccountBalances,
|
||||||
|
getAccountTransactions,
|
||||||
|
getAllTransactions,
|
||||||
|
getAllTransactionsWithRaw,
|
||||||
|
} from '../api-client'
|
||||||
|
|
||||||
|
describe('api-client', () => {
|
||||||
|
let fetchSpy: ReturnType<typeof vi.spyOn>
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
fetchSpy = vi.spyOn(globalThis, 'fetch')
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
fetchSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Timeout
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
describe('timeout', () => {
|
||||||
|
it('aborts fetch after timeout', async () => {
|
||||||
|
fetchSpy.mockImplementation(
|
||||||
|
() => new Promise((_, reject) => {
|
||||||
|
// Simulate a hanging request — the AbortController will fire
|
||||||
|
setTimeout(() => reject(new DOMException('Aborted', 'AbortError')), 100)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(getAccountBalances('acc-1')).rejects.toThrow('Aborted')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Retry
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
describe('retry', () => {
|
||||||
|
it('retries on 503 and succeeds', async () => {
|
||||||
|
const failResponse = new Response('Service Unavailable', { status: 503 })
|
||||||
|
const successResponse = new Response(JSON.stringify({ balances: [] }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
|
||||||
|
fetchSpy
|
||||||
|
.mockResolvedValueOnce(failResponse)
|
||||||
|
.mockResolvedValueOnce(failResponse)
|
||||||
|
.mockResolvedValueOnce(successResponse)
|
||||||
|
|
||||||
|
const result = await getAccountBalances('acc-1')
|
||||||
|
expect(result).toEqual([])
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retries on AbortError (timeout) and succeeds', async () => {
|
||||||
|
const abortError = new DOMException('Aborted', 'AbortError')
|
||||||
|
const successResponse = new Response(JSON.stringify({ aspsps: [{ name: 'TestBank', country: 'SE' }] }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
|
||||||
|
fetchSpy
|
||||||
|
.mockRejectedValueOnce(abortError)
|
||||||
|
.mockResolvedValueOnce(successResponse)
|
||||||
|
|
||||||
|
const result = await getASPSPs('SE')
|
||||||
|
expect(result).toEqual([{ name: 'TestBank', country: 'SE' }])
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not retry on 400 errors', async () => {
|
||||||
|
const badRequest = new Response('Bad Request', { status: 400 })
|
||||||
|
fetchSpy.mockResolvedValueOnce(badRequest)
|
||||||
|
|
||||||
|
// getAccountTransactions throws on non-ok response
|
||||||
|
await expect(getAccountTransactions('acc-1')).rejects.toThrow('Failed to get transactions')
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Pagination cap
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
describe('pagination cap', () => {
|
||||||
|
it('stops at MAX_PAGINATION_PAGES', async () => {
|
||||||
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||||
|
|
||||||
|
// Every response returns a continuation_key
|
||||||
|
fetchSpy.mockImplementation(() => {
|
||||||
|
return Promise.resolve(
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
||||||
|
continuation_key: 'keep-going',
|
||||||
|
}),
|
||||||
|
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await getAllTransactions('acc-1', '2024-01-01', '2024-12-31')
|
||||||
|
|
||||||
|
// Should have exactly 100 transactions (1 per page, 100 pages)
|
||||||
|
expect(result).toHaveLength(100)
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(100)
|
||||||
|
expect(warnSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Pagination cap reached')
|
||||||
|
)
|
||||||
|
|
||||||
|
warnSpy.mockRestore()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// getAllTransactionsWithRaw
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
describe('getAllTransactionsWithRaw', () => {
|
||||||
|
it('returns both transactions and raw pages', async () => {
|
||||||
|
const page1 = {
|
||||||
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
||||||
|
continuation_key: 'page2',
|
||||||
|
}
|
||||||
|
const page2 = {
|
||||||
|
transactions: [{ transaction_amount: { amount: '200', currency: 'SEK' } }],
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchSpy
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
new Response(JSON.stringify(page1), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
new Response(JSON.stringify(page2), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||||
|
)
|
||||||
|
|
||||||
|
const result = await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
||||||
|
|
||||||
|
expect(result.transactions).toHaveLength(2)
|
||||||
|
expect(result.rawPages).toHaveLength(2)
|
||||||
|
expect(JSON.parse(result.rawPages[0])).toEqual(page1)
|
||||||
|
expect(JSON.parse(result.rawPages[1])).toEqual(page2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// JWT cache tests
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
describe('JWT cache', () => {
|
||||||
|
it('reuses cached token within validity window', async () => {
|
||||||
|
// Reset mocks and re-import to test cache behavior
|
||||||
|
vi.resetModules()
|
||||||
|
const jwtCallCount = { count: 0 }
|
||||||
|
|
||||||
|
vi.doMock('../jwt', () => ({
|
||||||
|
generateJWT: () => {
|
||||||
|
jwtCallCount.count++
|
||||||
|
return 'cached-token'
|
||||||
|
},
|
||||||
|
getAuthorizationHeader: () => {
|
||||||
|
// Simulate cached behavior: first call generates, subsequent calls reuse
|
||||||
|
jwtCallCount.count++
|
||||||
|
return `Bearer cached-token`
|
||||||
|
},
|
||||||
|
_resetTokenCache: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// The actual cache test is in jwt.ts — we verify the cache function exists
|
||||||
|
const jwt = await import('../jwt')
|
||||||
|
expect(typeof jwt._resetTokenCache).toBe('function')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
|
||||||
|
// Mock api-client
|
||||||
|
const mockGetAllTransactionsWithRaw = vi.fn()
|
||||||
|
const mockConvertTransaction = vi.fn()
|
||||||
|
const mockGetAccountBalance = vi.fn()
|
||||||
|
vi.mock('../api-client', () => ({
|
||||||
|
getAllTransactionsWithRaw: (...args: unknown[]) => mockGetAllTransactionsWithRaw(...args),
|
||||||
|
convertTransaction: (...args: unknown[]) => mockConvertTransaction(...args),
|
||||||
|
getAccountBalance: (...args: unknown[]) => mockGetAccountBalance(...args),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Mock document service
|
||||||
|
const mockUploadDocument = vi.fn()
|
||||||
|
vi.mock('@/lib/core/documents/document-service', () => ({
|
||||||
|
uploadDocument: (...args: unknown[]) => mockUploadDocument(...args),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Mock ingest
|
||||||
|
const mockIngest = vi.fn()
|
||||||
|
|
||||||
|
import { syncAccountTransactions } from '../sync'
|
||||||
|
import type { StoredAccount } from '../../types'
|
||||||
|
|
||||||
|
const USER_ID = 'user-1'
|
||||||
|
const CONNECTION_ID = 'conn-1'
|
||||||
|
|
||||||
|
function makeAccount(overrides: Partial<StoredAccount> = {}): StoredAccount {
|
||||||
|
return {
|
||||||
|
uid: 'acc-uid-1',
|
||||||
|
currency: 'SEK',
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('syncAccountTransactions', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mockGetAccountBalance.mockRejectedValue(new Error('skip'))
|
||||||
|
mockIngest.mockResolvedValue({ imported: 1, duplicates: 0, errors: 0, reconciled: 0, auto_categorized: 0, auto_matched_invoices: 0, transaction_ids: ['tx-1'] })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('calls uploadDocument for each raw page with correct filename pattern', async () => {
|
||||||
|
const rawPage1 = JSON.stringify({ transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }] })
|
||||||
|
const rawPage2 = JSON.stringify({ transactions: [{ transaction_amount: { amount: '200', currency: 'SEK' } }] })
|
||||||
|
|
||||||
|
mockGetAllTransactionsWithRaw.mockResolvedValue({
|
||||||
|
transactions: [
|
||||||
|
{ transaction_amount: { amount: '100', currency: 'SEK' } },
|
||||||
|
{ transaction_amount: { amount: '200', currency: 'SEK' } },
|
||||||
|
],
|
||||||
|
rawPages: [rawPage1, rawPage2],
|
||||||
|
})
|
||||||
|
|
||||||
|
mockConvertTransaction.mockImplementation((tx: { transaction_amount: { amount: string } }) => ({
|
||||||
|
id: `tx-${tx.transaction_amount.amount}`,
|
||||||
|
date: '2024-06-15',
|
||||||
|
booking_date: '2024-06-15',
|
||||||
|
amount: parseFloat(tx.transaction_amount.amount),
|
||||||
|
currency: 'SEK',
|
||||||
|
description: 'Test',
|
||||||
|
}))
|
||||||
|
|
||||||
|
mockUploadDocument.mockResolvedValue({ id: 'doc-1' })
|
||||||
|
|
||||||
|
const account = makeAccount()
|
||||||
|
await syncAccountTransactions(
|
||||||
|
{} as never,
|
||||||
|
USER_ID,
|
||||||
|
CONNECTION_ID,
|
||||||
|
account,
|
||||||
|
'2024-01-01',
|
||||||
|
'2024-12-31',
|
||||||
|
mockIngest
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(mockUploadDocument).toHaveBeenCalledTimes(2)
|
||||||
|
|
||||||
|
// Verify filename pattern
|
||||||
|
const firstCall = mockUploadDocument.mock.calls[0]
|
||||||
|
expect(firstCall[2].name).toMatch(/^psd2-response_conn-1_acc-uid-1_.*_p1\.json$/)
|
||||||
|
expect(firstCall[2].type).toBe('application/json')
|
||||||
|
expect(firstCall[3]).toEqual({ upload_source: 'api' })
|
||||||
|
|
||||||
|
const secondCall = mockUploadDocument.mock.calls[1]
|
||||||
|
expect(secondCall[2].name).toMatch(/^psd2-response_conn-1_acc-uid-1_.*_p2\.json$/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('completes sync even if uploadDocument throws', async () => {
|
||||||
|
mockGetAllTransactionsWithRaw.mockResolvedValue({
|
||||||
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
||||||
|
rawPages: ['{"transactions":[]}'],
|
||||||
|
})
|
||||||
|
|
||||||
|
mockConvertTransaction.mockReturnValue({
|
||||||
|
id: 'tx-1',
|
||||||
|
date: '2024-06-15',
|
||||||
|
booking_date: '2024-06-15',
|
||||||
|
amount: 100,
|
||||||
|
currency: 'SEK',
|
||||||
|
description: 'Test',
|
||||||
|
})
|
||||||
|
|
||||||
|
mockUploadDocument.mockRejectedValue(new Error('Storage error'))
|
||||||
|
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||||
|
|
||||||
|
const account = makeAccount()
|
||||||
|
const result = await syncAccountTransactions(
|
||||||
|
{} as never,
|
||||||
|
USER_ID,
|
||||||
|
CONNECTION_ID,
|
||||||
|
account,
|
||||||
|
'2024-01-01',
|
||||||
|
'2024-12-31',
|
||||||
|
mockIngest
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result.imported).toBe(1)
|
||||||
|
expect(result.errors).toBe(0)
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Failed to archive raw response'),
|
||||||
|
expect.any(Error)
|
||||||
|
)
|
||||||
|
|
||||||
|
errorSpy.mockRestore()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('passes raw transactions to ingest function', async () => {
|
||||||
|
mockGetAllTransactionsWithRaw.mockResolvedValue({
|
||||||
|
transactions: [{ transaction_amount: { amount: '500', currency: 'SEK' } }],
|
||||||
|
rawPages: ['{}'],
|
||||||
|
})
|
||||||
|
|
||||||
|
mockConvertTransaction.mockReturnValue({
|
||||||
|
id: 'tx-500',
|
||||||
|
date: '2024-06-15',
|
||||||
|
booking_date: '2024-06-15',
|
||||||
|
amount: -500,
|
||||||
|
currency: 'SEK',
|
||||||
|
description: 'Purchase',
|
||||||
|
counterparty_name: 'Store',
|
||||||
|
merchant_category_code: '5411',
|
||||||
|
})
|
||||||
|
|
||||||
|
mockUploadDocument.mockResolvedValue({ id: 'doc-1' })
|
||||||
|
|
||||||
|
const account = makeAccount()
|
||||||
|
await syncAccountTransactions(
|
||||||
|
{} as never,
|
||||||
|
USER_ID,
|
||||||
|
CONNECTION_ID,
|
||||||
|
account,
|
||||||
|
'2024-01-01',
|
||||||
|
'2024-12-31',
|
||||||
|
mockIngest
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(mockIngest).toHaveBeenCalledTimes(1)
|
||||||
|
const rawTxns = mockIngest.mock.calls[0][2]
|
||||||
|
expect(rawTxns).toHaveLength(1)
|
||||||
|
expect(rawTxns[0].external_id).toBe('conn-1_tx-500')
|
||||||
|
expect(rawTxns[0].import_source).toBe('enable_banking')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -142,6 +142,12 @@ export interface BankTransaction {
|
|||||||
merchant_category_code?: string
|
merchant_category_code?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Constants
|
||||||
|
const FETCH_TIMEOUT_MS = 15_000
|
||||||
|
const MAX_RETRIES = 2
|
||||||
|
const RETRY_DELAY_MS = 1000
|
||||||
|
const MAX_PAGINATION_PAGES = 100
|
||||||
|
|
||||||
// API Helper
|
// API Helper
|
||||||
|
|
||||||
async function authenticatedFetch(
|
async function authenticatedFetch(
|
||||||
@@ -149,17 +155,53 @@ async function authenticatedFetch(
|
|||||||
options: RequestInit = {}
|
options: RequestInit = {}
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
const url = `${ENABLE_BANKING_API_URL}${endpoint}`
|
const url = `${ENABLE_BANKING_API_URL}${endpoint}`
|
||||||
|
const controller = new AbortController()
|
||||||
|
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
|
||||||
|
|
||||||
const response = await fetch(url, {
|
try {
|
||||||
...options,
|
const response = await fetch(url, {
|
||||||
headers: {
|
...options,
|
||||||
'Authorization': getAuthorizationHeader(),
|
signal: controller.signal,
|
||||||
'Content-Type': 'application/json',
|
headers: {
|
||||||
...options.headers,
|
'Authorization': getAuthorizationHeader(),
|
||||||
},
|
'Content-Type': 'application/json',
|
||||||
})
|
...options.headers,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
return response
|
return response
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retry wrapper for idempotent read operations.
|
||||||
|
* Retries on 429, 502, 503, 504, and AbortError (timeout).
|
||||||
|
*/
|
||||||
|
async function authenticatedFetchWithRetry(
|
||||||
|
endpoint: string,
|
||||||
|
options: RequestInit = {}
|
||||||
|
): Promise<Response> {
|
||||||
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||||
|
try {
|
||||||
|
const response = await authenticatedFetch(endpoint, options)
|
||||||
|
if (attempt < MAX_RETRIES && [429, 502, 503, 504].includes(response.status)) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS * (attempt + 1)))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const isAbort = error instanceof Error && error.name === 'AbortError'
|
||||||
|
if (attempt < MAX_RETRIES && isAbort) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS * (attempt + 1)))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Unreachable, but satisfies TypeScript
|
||||||
|
throw new Error('Max retries exceeded')
|
||||||
}
|
}
|
||||||
|
|
||||||
// API Functions
|
// API Functions
|
||||||
@@ -175,7 +217,7 @@ export async function getASPSPs(country: string = 'SE'): Promise<ASPSP[]> {
|
|||||||
sandbox: String(isSandbox),
|
sandbox: String(isSandbox),
|
||||||
psu_type: psuType,
|
psu_type: psuType,
|
||||||
})
|
})
|
||||||
const response = await authenticatedFetch(`/aspsps?${params.toString()}`)
|
const response = await authenticatedFetchWithRetry(`/aspsps?${params.toString()}`)
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const error = await response.text()
|
const error = await response.text()
|
||||||
@@ -286,7 +328,7 @@ export async function createSession(code: string): Promise<SessionResponse> {
|
|||||||
* @param sessionId - The session ID
|
* @param sessionId - The session ID
|
||||||
*/
|
*/
|
||||||
export async function getSession(sessionId: string): Promise<SessionResponse> {
|
export async function getSession(sessionId: string): Promise<SessionResponse> {
|
||||||
const response = await authenticatedFetch(`/sessions/${sessionId}`)
|
const response = await authenticatedFetchWithRetry(`/sessions/${sessionId}`)
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to get session')
|
throw new Error('Failed to get session')
|
||||||
@@ -316,7 +358,7 @@ export async function deleteSession(sessionId: string): Promise<void> {
|
|||||||
* @param accountUid - The account UID (from session.accounts[].uid)
|
* @param accountUid - The account UID (from session.accounts[].uid)
|
||||||
*/
|
*/
|
||||||
export async function getAccountBalances(accountUid: string): Promise<Balance[]> {
|
export async function getAccountBalances(accountUid: string): Promise<Balance[]> {
|
||||||
const response = await authenticatedFetch(`/accounts/${accountUid}/balances`)
|
const response = await authenticatedFetchWithRetry(`/accounts/${accountUid}/balances`)
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to get account balances')
|
throw new Error('Failed to get account balances')
|
||||||
@@ -372,7 +414,7 @@ export async function getAccountTransactions(
|
|||||||
const queryString = params.toString()
|
const queryString = params.toString()
|
||||||
const endpoint = `/accounts/${accountUid}/transactions${queryString ? `?${queryString}` : ''}`
|
const endpoint = `/accounts/${accountUid}/transactions${queryString ? `?${queryString}` : ''}`
|
||||||
|
|
||||||
const response = await authenticatedFetch(endpoint)
|
const response = await authenticatedFetchWithRetry(endpoint)
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to get transactions')
|
throw new Error('Failed to get transactions')
|
||||||
@@ -391,6 +433,7 @@ export async function getAllTransactions(
|
|||||||
): Promise<Transaction[]> {
|
): Promise<Transaction[]> {
|
||||||
const allTransactions: Transaction[] = []
|
const allTransactions: Transaction[] = []
|
||||||
let continuationKey: string | undefined
|
let continuationKey: string | undefined
|
||||||
|
let page = 0
|
||||||
|
|
||||||
do {
|
do {
|
||||||
const response = await getAccountTransactions(
|
const response = await getAccountTransactions(
|
||||||
@@ -402,11 +445,63 @@ export async function getAllTransactions(
|
|||||||
|
|
||||||
allTransactions.push(...response.transactions)
|
allTransactions.push(...response.transactions)
|
||||||
continuationKey = response.continuation_key
|
continuationKey = response.continuation_key
|
||||||
|
page++
|
||||||
|
|
||||||
|
if (page >= MAX_PAGINATION_PAGES) {
|
||||||
|
console.warn(`[enable-banking] Pagination cap reached (${MAX_PAGINATION_PAGES} pages) for account ${accountUid}`)
|
||||||
|
break
|
||||||
|
}
|
||||||
} while (continuationKey)
|
} while (continuationKey)
|
||||||
|
|
||||||
return allTransactions
|
return allTransactions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all transactions with raw JSON responses for archival.
|
||||||
|
* Returns both parsed transactions and the raw response strings.
|
||||||
|
*/
|
||||||
|
export async function getAllTransactionsWithRaw(
|
||||||
|
accountUid: string,
|
||||||
|
dateFrom?: string,
|
||||||
|
dateTo?: string
|
||||||
|
): Promise<{ transactions: Transaction[]; rawPages: string[] }> {
|
||||||
|
const allTransactions: Transaction[] = []
|
||||||
|
const rawPages: string[] = []
|
||||||
|
let continuationKey: string | undefined
|
||||||
|
let page = 0
|
||||||
|
|
||||||
|
do {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
if (dateFrom) params.set('date_from', dateFrom)
|
||||||
|
if (dateTo) params.set('date_to', dateTo)
|
||||||
|
if (continuationKey) params.set('continuation_key', continuationKey)
|
||||||
|
|
||||||
|
const queryString = params.toString()
|
||||||
|
const endpoint = `/accounts/${accountUid}/transactions${queryString ? `?${queryString}` : ''}`
|
||||||
|
|
||||||
|
const response = await authenticatedFetchWithRetry(endpoint)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to get transactions')
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawText = await response.text()
|
||||||
|
rawPages.push(rawText)
|
||||||
|
|
||||||
|
const data: TransactionsResponse = JSON.parse(rawText)
|
||||||
|
allTransactions.push(...data.transactions)
|
||||||
|
continuationKey = data.continuation_key
|
||||||
|
page++
|
||||||
|
|
||||||
|
if (page >= MAX_PAGINATION_PAGES) {
|
||||||
|
console.warn(`[enable-banking] Pagination cap reached (${MAX_PAGINATION_PAGES} pages) for account ${accountUid}`)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} while (continuationKey)
|
||||||
|
|
||||||
|
return { transactions: allTransactions, rawPages }
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert Enable Banking transaction to legacy format
|
* Convert Enable Banking transaction to legacy format
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -89,10 +89,29 @@ export function generateJWT(expiresInSeconds: number = 3600): string {
|
|||||||
return `${headerBase64}.${payloadBase64}.${signatureBase64}`
|
return `${headerBase64}.${payloadBase64}.${signatureBase64}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// JWT token cache
|
||||||
|
let cachedToken: string | null = null
|
||||||
|
let cachedTokenExpiry: number = 0
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the Authorization header value for Enable Banking API
|
* Get the Authorization header value for Enable Banking API.
|
||||||
|
* Caches JWT tokens and reuses them until 60s before expiry.
|
||||||
*/
|
*/
|
||||||
export function getAuthorizationHeader(): string {
|
export function getAuthorizationHeader(): string {
|
||||||
const token = generateJWT()
|
const now = Math.floor(Date.now() / 1000)
|
||||||
|
if (cachedToken && now < cachedTokenExpiry - 60) {
|
||||||
|
return `Bearer ${cachedToken}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const expiresInSeconds = 3600
|
||||||
|
const token = generateJWT(expiresInSeconds)
|
||||||
|
cachedToken = token
|
||||||
|
cachedTokenExpiry = now + expiresInSeconds
|
||||||
return `Bearer ${token}`
|
return `Bearer ${token}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @internal Reset token cache — for testing only */
|
||||||
|
export function _resetTokenCache(): void {
|
||||||
|
cachedToken = null
|
||||||
|
cachedTokenExpiry = 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||||
import { getTransactions, getAccountBalance } from './api-client'
|
import { getAllTransactionsWithRaw, convertTransaction, getAccountBalance } from './api-client'
|
||||||
|
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||||
import { ingestTransactions as defaultIngest } from '@/lib/transactions/ingest'
|
import { ingestTransactions as defaultIngest } from '@/lib/transactions/ingest'
|
||||||
import type { RawTransaction, IngestResult } from '@/types'
|
import type { RawTransaction, IngestResult } from '@/types'
|
||||||
import type { StoredAccount } from '../types'
|
import type { StoredAccount } from '../types'
|
||||||
@@ -21,7 +22,8 @@ export interface SyncResult {
|
|||||||
* Sync transactions for a single bank account via Enable Banking PSD2.
|
* Sync transactions for a single bank account via Enable Banking PSD2.
|
||||||
*
|
*
|
||||||
* Fetches transactions from the Enable Banking API, converts to RawTransaction
|
* Fetches transactions from the Enable Banking API, converts to RawTransaction
|
||||||
* format, and delegates to the shared ingestion pipeline.
|
* format, and delegates to the shared ingestion pipeline. Raw API responses
|
||||||
|
* are archived as räkenskapsinformation per BFL 7 kap.
|
||||||
*
|
*
|
||||||
* @param ingest - Optional ingest function override (defaults to core ingestTransactions).
|
* @param ingest - Optional ingest function override (defaults to core ingestTransactions).
|
||||||
* When called from an extension handler with ctx.services.ingestTransactions,
|
* When called from an extension handler with ctx.services.ingestTransactions,
|
||||||
@@ -36,13 +38,14 @@ export async function syncAccountTransactions(
|
|||||||
toDate: string,
|
toDate: string,
|
||||||
ingest: IngestFn = defaultIngest
|
ingest: IngestFn = defaultIngest
|
||||||
): Promise<SyncResult> {
|
): Promise<SyncResult> {
|
||||||
const bankTransactions = await getTransactions(
|
const { transactions, rawPages } = await getAllTransactionsWithRaw(
|
||||||
account.uid,
|
account.uid,
|
||||||
fromDate,
|
fromDate,
|
||||||
toDate,
|
toDate,
|
||||||
account.currency
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const bankTransactions = transactions.map(tx => convertTransaction(tx, account.currency))
|
||||||
|
|
||||||
// Convert Enable Banking format to generic RawTransaction
|
// Convert Enable Banking format to generic RawTransaction
|
||||||
const rawTransactions: RawTransaction[] = bankTransactions.map((tx) => ({
|
const rawTransactions: RawTransaction[] = bankTransactions.map((tx) => ({
|
||||||
date: tx.booking_date || tx.date,
|
date: tx.booking_date || tx.date,
|
||||||
@@ -59,6 +62,21 @@ export async function syncAccountTransactions(
|
|||||||
|
|
||||||
const ingestResult = await ingest(supabase, userId, rawTransactions)
|
const ingestResult = await ingest(supabase, userId, rawTransactions)
|
||||||
|
|
||||||
|
// Archive raw PSD2 API responses as räkenskapsinformation (BFL 7 kap)
|
||||||
|
for (let i = 0; i < rawPages.length; i++) {
|
||||||
|
try {
|
||||||
|
const fileName = `psd2-response_${connectionId}_${account.uid}_${new Date().toISOString().replace(/[:.]/g, '-')}_p${i + 1}.json`
|
||||||
|
const buffer = new TextEncoder().encode(rawPages[i]).buffer as ArrayBuffer
|
||||||
|
await uploadDocument(supabase, userId,
|
||||||
|
{ name: fileName, buffer, type: 'application/json' },
|
||||||
|
{ upload_source: 'api' }
|
||||||
|
)
|
||||||
|
} catch (archiveError) {
|
||||||
|
console.error(`[enable-banking] Failed to archive raw response page ${i + 1}:`, archiveError)
|
||||||
|
// Archival failure must not fail the sync
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Update account balance
|
// Update account balance
|
||||||
try {
|
try {
|
||||||
const balance = await getAccountBalance(account.uid)
|
const balance = await getAccountBalance(account.uid)
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ describe('BAS_REFERENCE data integrity', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('Non-standard accounts removed', () => {
|
describe('Non-standard accounts removed', () => {
|
||||||
const nonStandard = ['1249', '1259', '1400', '1580', '3109', '4100', '4990', '7834', '7835', '7910', '8710']
|
const nonStandard = ['1400', '1580', '3109', '4100', '4990', '7834', '7835', '7910', '8710']
|
||||||
|
|
||||||
for (const num of nonStandard) {
|
for (const num of nonStandard) {
|
||||||
it(`${num} is not in the catalog`, () => {
|
it(`${num} is not in the catalog`, () => {
|
||||||
|
|||||||
@@ -695,27 +695,104 @@ export const CLASS_1_ACCOUNTS: BASReferenceAccount[] = [
|
|||||||
k2_excluded: false,
|
k2_excluded: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
account_number: '1250',
|
account_number: '1241',
|
||||||
account_name: '(Fritt konto för Inventarier, verktyg och installationer)',
|
account_name: 'Personbilar',
|
||||||
account_class: 1,
|
account_class: 1,
|
||||||
account_group: '12',
|
account_group: '12',
|
||||||
account_type: 'asset',
|
account_type: 'asset',
|
||||||
normal_balance: 'debit',
|
normal_balance: 'debit',
|
||||||
description: '(Fritt konto för Inventarier, verktyg och installationer)',
|
description: 'Personbilar',
|
||||||
sru_code: '7202',
|
sru_code: '7202',
|
||||||
k2_excluded: false,
|
k2_excluded: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
account_number: '1260',
|
account_number: '1242',
|
||||||
account_name: '(Fritt konto för Inventarier, verktyg och installationer)',
|
account_name: 'Lastbilar och andra transportmedel',
|
||||||
account_class: 1,
|
account_class: 1,
|
||||||
account_group: '12',
|
account_group: '12',
|
||||||
account_type: 'asset',
|
account_type: 'asset',
|
||||||
normal_balance: 'debit',
|
normal_balance: 'debit',
|
||||||
description: '(Fritt konto för Inventarier, verktyg och installationer)',
|
description: 'Lastbilar och andra transportmedel',
|
||||||
sru_code: '7202',
|
sru_code: '7202',
|
||||||
k2_excluded: false,
|
k2_excluded: false,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
account_number: '1249',
|
||||||
|
account_name: 'Ack. avskrivningar på bilar och andra transportmedel',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'credit',
|
||||||
|
description: 'Ackumulerade avskrivningar på bilar och andra transportmedel (kontra-tillgång)',
|
||||||
|
sru_code: '7202',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
account_number: '1250',
|
||||||
|
account_name: 'Inventarier och verktyg',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'debit',
|
||||||
|
description: 'Inventarier och verktyg',
|
||||||
|
sru_code: '7215',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
account_number: '1251',
|
||||||
|
account_name: 'Inventarier',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'debit',
|
||||||
|
description: 'Inventarier',
|
||||||
|
sru_code: '7215',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
account_number: '1259',
|
||||||
|
account_name: 'Ack. avskrivningar på inventarier och verktyg',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'credit',
|
||||||
|
description: 'Ackumulerade avskrivningar på inventarier och verktyg (kontra-tillgång)',
|
||||||
|
sru_code: '7215',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
account_number: '1260',
|
||||||
|
account_name: 'Datorer',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'debit',
|
||||||
|
description: 'Datorer',
|
||||||
|
sru_code: '7215',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
account_number: '1261',
|
||||||
|
account_name: 'Datorer, bärbara',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'debit',
|
||||||
|
description: 'Datorer, bärbara',
|
||||||
|
sru_code: '7215',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
account_number: '1269',
|
||||||
|
account_name: 'Ack. avskrivningar på datorer',
|
||||||
|
account_class: 1,
|
||||||
|
account_group: '12',
|
||||||
|
account_type: 'asset',
|
||||||
|
normal_balance: 'credit',
|
||||||
|
description: 'Ackumulerade avskrivningar på datorer (kontra-tillgång)',
|
||||||
|
sru_code: '7215',
|
||||||
|
k2_excluded: false,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
account_number: '1280',
|
account_number: '1280',
|
||||||
account_name: 'Pågående nyanläggningar och förskott för maskiner respektive inventarier',
|
account_name: 'Pågående nyanläggningar och förskott för maskiner respektive inventarier',
|
||||||
|
|||||||
@@ -44,8 +44,9 @@ describe('lockPeriod', () => {
|
|||||||
const lockedPeriod = { ...period, locked_at: '2024-12-31T23:59:59Z' }
|
const lockedPeriod = { ...period, locked_at: '2024-12-31T23:59:59Z' }
|
||||||
|
|
||||||
results = [
|
results = [
|
||||||
{ data: period, error: null }, // fetch
|
{ data: period, error: null }, // fetch
|
||||||
{ data: lockedPeriod, error: null }, // update
|
{ count: 0, data: null, error: null }, // uncategorized tx count check
|
||||||
|
{ data: lockedPeriod, error: null }, // update
|
||||||
]
|
]
|
||||||
|
|
||||||
const handler = vi.fn()
|
const handler = vi.fn()
|
||||||
|
|||||||
@@ -33,6 +33,22 @@ export async function lockPeriod(
|
|||||||
throw new Error('Period is already locked')
|
throw new Error('Period is already locked')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check for uncategorized business transactions in this period
|
||||||
|
const { count: unbookedCount } = await supabase
|
||||||
|
.from('transactions')
|
||||||
|
.select('id', { count: 'exact', head: true })
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.is('journal_entry_id', null)
|
||||||
|
.eq('is_business', true)
|
||||||
|
.gte('date', period.period_start)
|
||||||
|
.lte('date', period.period_end)
|
||||||
|
|
||||||
|
if (unbookedCount && unbookedCount > 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Kan inte låsa period: ${unbookedCount} affärstransaktion(er) saknar bokföring. Bokför alla transaktioner innan perioden låses.`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const { data: updated, error: updateError } = await supabase
|
const { data: updated, error: updateError } = await supabase
|
||||||
.from('fiscal_periods')
|
.from('fiscal_periods')
|
||||||
.update({ locked_at: new Date().toISOString() })
|
.update({ locked_at: new Date().toISOString() })
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
export interface ConsentExpiryEmailData {
|
||||||
|
bankName: string
|
||||||
|
daysUntilExpiry: number
|
||||||
|
renewalUrl: string
|
||||||
|
companyName: string
|
||||||
|
isExpired: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate HTML email for consent expiry notification
|
||||||
|
*/
|
||||||
|
export function generateConsentExpiryEmailHtml(data: ConsentExpiryEmailData): string {
|
||||||
|
const { bankName, daysUntilExpiry, renewalUrl, companyName, isExpired } = data
|
||||||
|
const headerColor = isExpired ? '#dc2626' : '#ea580c'
|
||||||
|
const title = isExpired
|
||||||
|
? 'Banksynkronisering har stoppats'
|
||||||
|
: `Samtycket för ${bankName} löper ut snart`
|
||||||
|
|
||||||
|
return `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="sv">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>${title}</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f9fafb;">
|
||||||
|
<div style="max-width: 600px; margin: 0 auto; padding: 40px 20px;">
|
||||||
|
<div style="background: white; border-radius: 12px; padding: 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
|
||||||
|
<div style="text-align: center; margin-bottom: 30px;">
|
||||||
|
<div style="display: inline-block; background: ${headerColor}15; color: ${headerColor}; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">
|
||||||
|
${isExpired ? 'Åtgärd krävs' : 'Påminnelse'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h1 style="margin: 0 0 20px 0; font-size: 22px; font-weight: 600; color: #111; text-align: center;">
|
||||||
|
${title}
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div style="margin-bottom: 30px;">
|
||||||
|
${isExpired ? `
|
||||||
|
<p style="margin: 0 0 15px 0; color: #dc2626; font-weight: 500;">
|
||||||
|
PSD2-samtycket för ${bankName} har löpt ut. Automatisk transaktionssynkronisering är stoppad.
|
||||||
|
</p>
|
||||||
|
<p style="margin: 0 0 15px 0;">
|
||||||
|
Förnya anslutningen för att återuppta synkroniseringen.
|
||||||
|
</p>
|
||||||
|
` : `
|
||||||
|
<p style="margin: 0 0 15px 0;">
|
||||||
|
Samtycket för ${bankName} löper ut om ${daysUntilExpiry} ${daysUntilExpiry === 1 ? 'dag' : 'dagar'}.
|
||||||
|
</p>
|
||||||
|
<p style="margin: 0 0 15px 0;">
|
||||||
|
Förnya anslutningen innan samtycket löper ut för att undvika avbrott i transaktionssynkroniseringen.
|
||||||
|
</p>
|
||||||
|
`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="text-align: center; margin-bottom: 30px;">
|
||||||
|
<a href="${renewalUrl}" style="display: inline-block; background: ${headerColor}; color: white; padding: 14px 28px; border-radius: 8px; text-decoration: none; font-weight: 500; font-size: 14px;">
|
||||||
|
${isExpired ? 'Förnya anslutning' : 'Hantera bankanslutningar'}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="padding-top: 20px; border-top: 1px solid #e5e7eb;">
|
||||||
|
<p style="margin: 0; color: #666; font-size: 14px;">
|
||||||
|
Med vänliga hälsningar,<br>
|
||||||
|
<strong>${companyName || 'gnubok'}</strong>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate plain text email for consent expiry notification
|
||||||
|
*/
|
||||||
|
export function generateConsentExpiryEmailText(data: ConsentExpiryEmailData): string {
|
||||||
|
const { bankName, daysUntilExpiry, renewalUrl, companyName, isExpired } = data
|
||||||
|
|
||||||
|
let text = ''
|
||||||
|
|
||||||
|
if (isExpired) {
|
||||||
|
text += `BANKSYNKRONISERING HAR STOPPATS\n`
|
||||||
|
text += `=`.repeat(40) + `\n\n`
|
||||||
|
text += `PSD2-samtycket för ${bankName} har löpt ut.\n`
|
||||||
|
text += `Automatisk transaktionssynkronisering är stoppad.\n\n`
|
||||||
|
text += `Förnya anslutningen för att återuppta synkroniseringen.\n\n`
|
||||||
|
} else {
|
||||||
|
text += `SAMTYCKET FÖR ${bankName.toUpperCase()} LÖPER UT SNART\n`
|
||||||
|
text += `=`.repeat(40) + `\n\n`
|
||||||
|
text += `Samtycket för ${bankName} löper ut om ${daysUntilExpiry} ${daysUntilExpiry === 1 ? 'dag' : 'dagar'}.\n\n`
|
||||||
|
text += `Förnya anslutningen innan samtycket löper ut för att undvika avbrott.\n\n`
|
||||||
|
}
|
||||||
|
|
||||||
|
text += `Hantera bankanslutningar: ${renewalUrl}\n\n`
|
||||||
|
text += `Med vänliga hälsningar,\n`
|
||||||
|
text += `${companyName || 'gnubok'}\n`
|
||||||
|
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate email subject for consent expiry notification
|
||||||
|
*/
|
||||||
|
export function generateConsentExpiryEmailSubject(data: ConsentExpiryEmailData): string {
|
||||||
|
if (data.isExpired) {
|
||||||
|
return `Banksynkronisering stoppad — ${data.bankName}`
|
||||||
|
}
|
||||||
|
return `Banksamtycke löper ut om ${data.daysUntilExpiry} ${data.daysUntilExpiry === 1 ? 'dag' : 'dagar'} — ${data.bankName}`
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
Camera,
|
Camera,
|
||||||
Sparkles,
|
Wand,
|
||||||
MessageSquare,
|
MessageSquare,
|
||||||
Bell,
|
Bell,
|
||||||
Inbox,
|
Inbox,
|
||||||
@@ -33,7 +33,7 @@ import {
|
|||||||
|
|
||||||
const ICON_MAP: Record<string, LucideIcon> = {
|
const ICON_MAP: Record<string, LucideIcon> = {
|
||||||
Camera,
|
Camera,
|
||||||
Sparkles,
|
Wand,
|
||||||
MessageSquare,
|
MessageSquare,
|
||||||
Bell,
|
Bell,
|
||||||
Inbox,
|
Inbox,
|
||||||
|
|||||||
+306
-102
@@ -94,11 +94,32 @@ export async function checkDuplicateImport(
|
|||||||
.select('*')
|
.select('*')
|
||||||
.eq('user_id', userId)
|
.eq('user_id', userId)
|
||||||
.eq('file_hash', fileHash)
|
.eq('file_hash', fileHash)
|
||||||
|
.eq('status', 'completed')
|
||||||
.single()
|
.single()
|
||||||
|
|
||||||
return data as SIEImport | null
|
return data as SIEImport | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clean up stale pending/failed import records for a given file hash.
|
||||||
|
* Prevents UNIQUE constraint conflicts when re-importing after a failure.
|
||||||
|
*/
|
||||||
|
async function cleanupStaleImportRecords(
|
||||||
|
supabase: SupabaseClient,
|
||||||
|
userId: string,
|
||||||
|
fileHash: string
|
||||||
|
): Promise<void> {
|
||||||
|
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString()
|
||||||
|
|
||||||
|
await supabase
|
||||||
|
.from('sie_imports')
|
||||||
|
.delete()
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.eq('file_hash', fileHash)
|
||||||
|
.in('status', ['pending', 'failed'])
|
||||||
|
.lt('created_at', oneHourAgo)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a fiscal period if one doesn't exist for the date range
|
* Create a fiscal period if one doesn't exist for the date range
|
||||||
*/
|
*/
|
||||||
@@ -342,6 +363,8 @@ async function importVouchers(
|
|||||||
originalLineCount?: number
|
originalLineCount?: number
|
||||||
}[]
|
}[]
|
||||||
voucherNumberMapping: Array<{ sourceId: string; targetNumber: number }>
|
voucherNumberMapping: Array<{ sourceId: string; targetNumber: number }>
|
||||||
|
retriedBatches: number
|
||||||
|
failedBatches: number
|
||||||
}> {
|
}> {
|
||||||
const results = {
|
const results = {
|
||||||
created: 0,
|
created: 0,
|
||||||
@@ -366,6 +389,8 @@ async function importVouchers(
|
|||||||
originalLineCount?: number
|
originalLineCount?: number
|
||||||
}[],
|
}[],
|
||||||
voucherNumberMapping: [] as Array<{ sourceId: string; targetNumber: number }>,
|
voucherNumberMapping: [] as Array<{ sourceId: string; targetNumber: number }>,
|
||||||
|
retriedBatches: 0,
|
||||||
|
failedBatches: 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pre-filter and prepare all valid vouchers
|
// Pre-filter and prepare all valid vouchers
|
||||||
@@ -507,17 +532,9 @@ async function importVouchers(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compute per-account net movements from vouchers that will be imported.
|
// NOTE: Per-account net movements are tracked inside the batch loop below,
|
||||||
// Used for UB/RES reconciliation to generate migration adjustment entries.
|
// so that only SUCCESSFULLY inserted vouchers are counted. This ensures
|
||||||
for (const v of preparedVouchers) {
|
// the migration adjustment entry correctly compensates for failed batches.
|
||||||
for (const l of v.lines) {
|
|
||||||
const net = l.debit_amount - l.credit_amount
|
|
||||||
results.movementsByAccount.set(
|
|
||||||
l.account_number,
|
|
||||||
(results.movementsByAccount.get(l.account_number) || 0) + net
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preparedVouchers.length === 0) {
|
if (preparedVouchers.length === 0) {
|
||||||
return results
|
return results
|
||||||
@@ -552,11 +569,17 @@ async function importVouchers(
|
|||||||
|
|
||||||
const currentVoucherNumber = (startNumber as number) || 1
|
const currentVoucherNumber = (startNumber as number) || 1
|
||||||
|
|
||||||
// Batch insert journal entries (in chunks of 100)
|
// Batch insert journal entries (in chunks of 100) with retry logic.
|
||||||
|
// Retries handle transient errors (Supabase rate limits, Cloudflare 500s).
|
||||||
const BATCH_SIZE = 100
|
const BATCH_SIZE = 100
|
||||||
|
const MAX_RETRIES = 3
|
||||||
|
const INTER_BATCH_DELAY_MS = 50 // Prevent rate limiting under sustained load
|
||||||
|
let retriedBatches = 0
|
||||||
|
let failedBatches = 0
|
||||||
|
|
||||||
for (let batchStart = 0; batchStart < preparedVouchers.length; batchStart += BATCH_SIZE) {
|
for (let batchStart = 0; batchStart < preparedVouchers.length; batchStart += BATCH_SIZE) {
|
||||||
const batch = preparedVouchers.slice(batchStart, batchStart + BATCH_SIZE)
|
const batch = preparedVouchers.slice(batchStart, batchStart + BATCH_SIZE)
|
||||||
|
const batchNumber = Math.floor(batchStart / BATCH_SIZE) + 1
|
||||||
|
|
||||||
// Prepare journal entry headers
|
// Prepare journal entry headers
|
||||||
const entryInserts = batch.map((v, i) => ({
|
const entryInserts = batch.map((v, i) => ({
|
||||||
@@ -571,14 +594,37 @@ async function importVouchers(
|
|||||||
committed_at: new Date().toISOString(),
|
committed_at: new Date().toISOString(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// Insert headers
|
// Insert headers with retry
|
||||||
const { data: entries, error: entryError } = await supabase
|
let entries: { id: string }[] | null = null
|
||||||
.from('journal_entries')
|
let lastEntryError: string | null = null
|
||||||
.insert(entryInserts)
|
|
||||||
.select('id')
|
|
||||||
|
|
||||||
if (entryError || !entries) {
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||||
results.errors.push(`Batch ${Math.floor(batchStart / BATCH_SIZE) + 1}: ${entryError?.message || 'Failed to insert entries'}`)
|
if (attempt > 0) {
|
||||||
|
retriedBatches++
|
||||||
|
const backoffMs = Math.pow(2, attempt - 1) * 1000 // 1s, 2s, 4s
|
||||||
|
console.log(`[sie-import] Retrying batch ${batchNumber} (attempt ${attempt + 1}/${MAX_RETRIES + 1}) after ${backoffMs}ms`)
|
||||||
|
await new Promise(resolve => setTimeout(resolve, backoffMs))
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error: entryError } = await supabase
|
||||||
|
.from('journal_entries')
|
||||||
|
.insert(entryInserts)
|
||||||
|
.select('id')
|
||||||
|
|
||||||
|
if (!entryError && data) {
|
||||||
|
entries = data
|
||||||
|
lastEntryError = null
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
lastEntryError = entryError?.message || 'Failed to insert entries'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!entries) {
|
||||||
|
failedBatches++
|
||||||
|
results.errors.push(
|
||||||
|
`Batch ${batchNumber} misslyckades efter ${MAX_RETRIES + 1} försök: ${lastEntryError}`
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -613,7 +659,6 @@ async function importVouchers(
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Fix 7: Capture voucher number mapping (source → target)
|
|
||||||
results.voucherNumberMapping.push({
|
results.voucherNumberMapping.push({
|
||||||
sourceId: voucher.sourceId,
|
sourceId: voucher.sourceId,
|
||||||
targetNumber: assignedNumber,
|
targetNumber: assignedNumber,
|
||||||
@@ -623,15 +668,68 @@ async function importVouchers(
|
|||||||
results.created++
|
results.created++
|
||||||
}
|
}
|
||||||
|
|
||||||
// Insert all lines for this batch
|
// Insert all lines with retry
|
||||||
if (allLines.length > 0) {
|
if (allLines.length > 0) {
|
||||||
const { error: linesError } = await supabase
|
let linesInserted = false
|
||||||
.from('journal_entry_lines')
|
let lastLinesError: string | null = null
|
||||||
.insert(allLines)
|
|
||||||
|
|
||||||
if (linesError) {
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||||
results.errors.push(`Batch ${Math.floor(batchStart / BATCH_SIZE) + 1} lines: ${linesError.message}`)
|
if (attempt > 0) {
|
||||||
|
retriedBatches++
|
||||||
|
const backoffMs = Math.pow(2, attempt - 1) * 1000
|
||||||
|
console.log(`[sie-import] Retrying batch ${batchNumber} lines (attempt ${attempt + 1}/${MAX_RETRIES + 1}) after ${backoffMs}ms`)
|
||||||
|
await new Promise(resolve => setTimeout(resolve, backoffMs))
|
||||||
|
}
|
||||||
|
|
||||||
|
const { error: linesError } = await supabase
|
||||||
|
.from('journal_entry_lines')
|
||||||
|
.insert(allLines)
|
||||||
|
|
||||||
|
if (!linesError) {
|
||||||
|
linesInserted = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
lastLinesError = linesError.message
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (linesInserted) {
|
||||||
|
// Track movements ONLY for successfully inserted vouchers.
|
||||||
|
// This ensures the migration adjustment correctly compensates for
|
||||||
|
// any batches that failed completely.
|
||||||
|
for (let i = 0; i < batch.length; i++) {
|
||||||
|
const voucher = batch[i]
|
||||||
|
for (const line of voucher.lines) {
|
||||||
|
const net = line.debit_amount - line.credit_amount
|
||||||
|
results.movementsByAccount.set(
|
||||||
|
line.account_number,
|
||||||
|
(results.movementsByAccount.get(line.account_number) || 0) + net
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
failedBatches++
|
||||||
|
results.errors.push(
|
||||||
|
`Batch ${batchNumber} rader misslyckades efter ${MAX_RETRIES + 1} försök: ${lastLinesError}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No lines to insert — still count movements for vouchers with entries
|
||||||
|
for (let i = 0; i < batch.length; i++) {
|
||||||
|
const voucher = batch[i]
|
||||||
|
for (const line of voucher.lines) {
|
||||||
|
const net = line.debit_amount - line.credit_amount
|
||||||
|
results.movementsByAccount.set(
|
||||||
|
line.account_number,
|
||||||
|
(results.movementsByAccount.get(line.account_number) || 0) + net
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Small delay between batches to prevent Supabase/Cloudflare rate limiting
|
||||||
|
if (batchStart + BATCH_SIZE < preparedVouchers.length) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, INTER_BATCH_DELAY_MS))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -648,6 +746,10 @@ async function importVouchers(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Propagate batch retry stats
|
||||||
|
results.retriedBatches = retriedBatches
|
||||||
|
results.failedBatches = failedBatches
|
||||||
|
|
||||||
return results
|
return results
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -882,19 +984,21 @@ async function ensureAccountExists(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Record the import in the database and archive the SIE file to Supabase Storage.
|
* Phase 1: Create a pending import record early, before any journal entries.
|
||||||
|
* This ensures the import is tracked even if later steps fail.
|
||||||
*/
|
*/
|
||||||
async function recordImport(
|
async function createPendingImportRecord(
|
||||||
supabase: SupabaseClient,
|
supabase: SupabaseClient,
|
||||||
userId: string,
|
userId: string,
|
||||||
parsed: ParsedSIEFile,
|
parsed: ParsedSIEFile,
|
||||||
fileContent: string,
|
fileContent: string,
|
||||||
filename: string,
|
filename: string
|
||||||
result: ImportResult,
|
|
||||||
documentation?: MigrationDocumentation
|
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const fileHash = await calculateFileHash(fileContent)
|
const fileHash = await calculateFileHash(fileContent)
|
||||||
|
|
||||||
|
// Clean up any stale pending/failed records for this hash to avoid UNIQUE conflicts
|
||||||
|
await cleanupStaleImportRecords(supabase, userId, fileHash)
|
||||||
|
|
||||||
const { data, error } = await supabase
|
const { data, error } = await supabase
|
||||||
.from('sie_imports')
|
.from('sie_imports')
|
||||||
.insert({
|
.insert({
|
||||||
@@ -911,40 +1015,65 @@ async function recordImport(
|
|||||||
? formatDate(parsed.stats.fiscalYearEnd)
|
? formatDate(parsed.stats.fiscalYearEnd)
|
||||||
: null,
|
: null,
|
||||||
accounts_count: parsed.stats.totalAccounts,
|
accounts_count: parsed.stats.totalAccounts,
|
||||||
transactions_count: result.journalEntriesCreated,
|
transactions_count: 0,
|
||||||
status: result.success ? 'completed' : 'failed',
|
status: 'pending',
|
||||||
error_message: result.errors.length > 0 ? result.errors.join('; ') : null,
|
imported_at: null,
|
||||||
fiscal_period_id: result.fiscalPeriodId,
|
|
||||||
opening_balance_entry_id: result.openingBalanceEntryId,
|
|
||||||
imported_at: new Date().toISOString(),
|
|
||||||
migration_documentation: documentation ?? null,
|
|
||||||
})
|
})
|
||||||
.select('id')
|
.select('id')
|
||||||
.single()
|
.single()
|
||||||
|
|
||||||
if (error || !data) {
|
if (error || !data) {
|
||||||
throw new Error(`Failed to record import: ${error?.message}`)
|
throw new Error(`Failed to create pending import record: ${error?.message}`)
|
||||||
}
|
|
||||||
|
|
||||||
// Archive the SIE file to Supabase Storage (BFL 7 kap 1-2§ retention)
|
|
||||||
const storagePath = `${userId}/${data.id}.se`
|
|
||||||
const fileBlob = new Blob([fileContent], { type: 'text/plain; charset=cp437' })
|
|
||||||
const { error: uploadError } = await supabase.storage
|
|
||||||
.from('sie-files')
|
|
||||||
.upload(storagePath, fileBlob, { upsert: false })
|
|
||||||
|
|
||||||
if (uploadError) {
|
|
||||||
console.error(`[sie-import] Failed to archive SIE file: ${uploadError.message}`)
|
|
||||||
} else {
|
|
||||||
await supabase
|
|
||||||
.from('sie_imports')
|
|
||||||
.update({ file_storage_path: storagePath })
|
|
||||||
.eq('id', data.id)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return data.id
|
return data.id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase 2: Finalize the import record with results and archive the SIE file.
|
||||||
|
*/
|
||||||
|
async function finalizeImportRecord(
|
||||||
|
supabase: SupabaseClient,
|
||||||
|
importId: string,
|
||||||
|
userId: string,
|
||||||
|
result: ImportResult,
|
||||||
|
fileContent: string,
|
||||||
|
documentation?: MigrationDocumentation
|
||||||
|
): Promise<void> {
|
||||||
|
const status = result.success ? 'completed' : 'failed'
|
||||||
|
|
||||||
|
await supabase
|
||||||
|
.from('sie_imports')
|
||||||
|
.update({
|
||||||
|
status,
|
||||||
|
imported_at: result.success ? new Date().toISOString() : null,
|
||||||
|
transactions_count: result.journalEntriesCreated,
|
||||||
|
error_message: result.errors.length > 0 ? result.errors.join('; ') : null,
|
||||||
|
fiscal_period_id: result.fiscalPeriodId,
|
||||||
|
opening_balance_entry_id: result.openingBalanceEntryId,
|
||||||
|
migration_documentation: documentation ?? null,
|
||||||
|
})
|
||||||
|
.eq('id', importId)
|
||||||
|
|
||||||
|
// Archive the SIE file to Supabase Storage (BFL 7 kap 1-2§ retention)
|
||||||
|
if (result.success) {
|
||||||
|
const storagePath = `${userId}/${importId}.se`
|
||||||
|
const fileBlob = new Blob([fileContent], { type: 'text/plain; charset=cp437' })
|
||||||
|
const { error: uploadError } = await supabase.storage
|
||||||
|
.from('sie-files')
|
||||||
|
.upload(storagePath, fileBlob, { upsert: false })
|
||||||
|
|
||||||
|
if (uploadError) {
|
||||||
|
console.error(`[sie-import] Failed to archive SIE file: ${uploadError.message}`)
|
||||||
|
} else {
|
||||||
|
await supabase
|
||||||
|
.from('sie_imports')
|
||||||
|
.update({ file_storage_path: storagePath })
|
||||||
|
.eq('id', importId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save account mappings to the database for future use
|
* Save account mappings to the database for future use
|
||||||
*/
|
*/
|
||||||
@@ -1043,15 +1172,24 @@ export async function executeSIEImport(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for duplicate import
|
// Check for duplicate import (only completed imports count as duplicates)
|
||||||
const duplicate = await checkDuplicateImport(supabase, userId, options.fileContent)
|
const duplicate = await checkDuplicateImport(supabase, userId, options.fileContent)
|
||||||
if (duplicate) {
|
if (duplicate) {
|
||||||
result.errors.push(
|
result.errors.push(
|
||||||
`This file has already been imported on ${new Date(duplicate.imported_at!).toLocaleDateString('sv-SE')}`
|
`This file has already been imported on ${duplicate.imported_at ? new Date(duplicate.imported_at).toLocaleDateString('sv-SE') : 'okänt datum'}`
|
||||||
)
|
)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create pending import record early — ensures tracking even if later steps fail
|
||||||
|
result.importId = await createPendingImportRecord(
|
||||||
|
supabase,
|
||||||
|
userId,
|
||||||
|
parsed,
|
||||||
|
options.fileContent,
|
||||||
|
options.filename
|
||||||
|
)
|
||||||
|
|
||||||
// Build account mapping lookup
|
// Build account mapping lookup
|
||||||
const accountMap = mappingsToMap(mappings)
|
const accountMap = mappingsToMap(mappings)
|
||||||
|
|
||||||
@@ -1108,8 +1246,10 @@ export async function executeSIEImport(
|
|||||||
|
|
||||||
// Track documentation data across import phases
|
// Track documentation data across import phases
|
||||||
let ibRoundingAdjustment = 0
|
let ibRoundingAdjustment = 0
|
||||||
|
let ibExplanation: 'unallocated_result' | 'excluded_accounts' | 'rounding' | null = null
|
||||||
let migrationAdjustmentInfo = { created: false, deltaAccounts: 0, entryId: null as string | null }
|
let migrationAdjustmentInfo = { created: false, deltaAccounts: 0, entryId: null as string | null }
|
||||||
let voucherNumberMapping: Array<{ sourceId: string; targetNumber: number }> = []
|
let voucherNumberMapping: Array<{ sourceId: string; targetNumber: number }> = []
|
||||||
|
let voucherRetryStats = { retriedBatches: 0, failedBatches: 0 }
|
||||||
let voucherStats = {
|
let voucherStats = {
|
||||||
total: parsed.vouchers.length,
|
total: parsed.vouchers.length,
|
||||||
imported: 0,
|
imported: 0,
|
||||||
@@ -1131,48 +1271,62 @@ export async function executeSIEImport(
|
|||||||
// explicit documentation. We never reject based on IB imbalance — the
|
// explicit documentation. We never reject based on IB imbalance — the
|
||||||
// original goal was to stop SILENT equity alteration, not prevent it.
|
// original goal was to stop SILENT equity alteration, not prevent it.
|
||||||
if (options.importOpeningBalances && parsed.openingBalances.length > 0 && result.fiscalPeriodId) {
|
if (options.importOpeningBalances && parsed.openingBalances.length > 0 && result.fiscalPeriodId) {
|
||||||
const ibValidation = validateIBBalance(parsed, accountMap)
|
// Check if opening balances already exist for this period
|
||||||
|
const { data: period } = await supabase
|
||||||
|
.from('fiscal_periods')
|
||||||
|
.select('opening_balances_set, opening_balance_entry_id')
|
||||||
|
.eq('id', result.fiscalPeriodId)
|
||||||
|
.single()
|
||||||
|
|
||||||
if (ibValidation.lines.length > 0) {
|
if (period?.opening_balances_set || period?.opening_balance_entry_id) {
|
||||||
const absAdj = Math.abs(ibValidation.roundingAdjustment)
|
result.warnings.push('Ingående balanser finns redan för denna period — hoppar över IB-import')
|
||||||
|
} else {
|
||||||
|
const ibValidation = validateIBBalance(parsed, accountMap)
|
||||||
|
|
||||||
if (absAdj > 0.01) {
|
if (ibValidation.lines.length > 0) {
|
||||||
ibRoundingAdjustment = ibValidation.roundingAdjustment
|
const absAdj = Math.abs(ibValidation.roundingAdjustment)
|
||||||
|
|
||||||
// Produce a descriptive warning explaining the source of the imbalance
|
if (absAdj > 0.01) {
|
||||||
if (Math.abs(ibValidation.excludedAccountsTotal) > 0.01 && ibValidation.fileImbalance <= 1.00) {
|
ibRoundingAdjustment = ibValidation.roundingAdjustment
|
||||||
// File-level IB is balanced — imbalance is entirely from excluded system accounts
|
|
||||||
result.warnings.push(
|
// Produce a descriptive warning explaining the source of the imbalance
|
||||||
`Exkluderade systemkonton har IB-saldon på totalt ${ibValidation.excludedAccountsTotal} SEK. ` +
|
if (Math.abs(ibValidation.excludedAccountsTotal) > 0.01 && ibValidation.fileImbalance <= 1.00) {
|
||||||
`Differensen (${ibValidation.roundingAdjustment} SEK) bokförs på konto 2099.`
|
// File-level IB is balanced — imbalance is entirely from excluded system accounts
|
||||||
)
|
ibExplanation = 'excluded_accounts'
|
||||||
} else if (ibValidation.fileImbalance > 1.00) {
|
result.warnings.push(
|
||||||
// File-level IB doesn't balance — likely unallocated årets resultat from previous year
|
`Exkluderade systemkonton har IB-saldon på totalt ${ibValidation.excludedAccountsTotal} SEK. ` +
|
||||||
result.warnings.push(
|
`Differensen (${ibValidation.roundingAdjustment} SEK) bokförs på konto 2099.`
|
||||||
`Ingående balanser obalanserade med ${ibValidation.roundingAdjustment} SEK ` +
|
)
|
||||||
`(troligen ej allokerat årets resultat från föregående räkenskapsår). ` +
|
} else if (ibValidation.fileImbalance > 1.00) {
|
||||||
`Differensen bokförs på konto 2099 (Årets resultat).`
|
// File-level IB doesn't balance — likely unallocated årets resultat from previous year
|
||||||
)
|
ibExplanation = 'unallocated_result'
|
||||||
} else {
|
result.warnings.push(
|
||||||
// Small rounding
|
`Ingående balanser obalanserade med ${ibValidation.roundingAdjustment} SEK ` +
|
||||||
result.warnings.push(
|
`(troligen ej allokerat årets resultat från föregående räkenskapsår). ` +
|
||||||
`Avrundningsdifferens vid SIE-import: ${ibValidation.roundingAdjustment} SEK bokförd på konto 2099`
|
`Differensen bokförs på konto 2099 (Årets resultat).`
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
// Small rounding
|
||||||
|
ibExplanation = 'rounding'
|
||||||
|
result.warnings.push(
|
||||||
|
`Avrundningsdifferens vid SIE-import: ${ibValidation.roundingAdjustment} SEK bokförd på konto 2099`
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
result.openingBalanceEntryId = await createOpeningBalanceEntry(
|
result.openingBalanceEntryId = await createOpeningBalanceEntry(
|
||||||
supabase,
|
supabase,
|
||||||
userId,
|
userId,
|
||||||
result.fiscalPeriodId,
|
result.fiscalPeriodId,
|
||||||
parsed,
|
parsed,
|
||||||
accountMap,
|
accountMap,
|
||||||
ibRoundingAdjustment
|
ibRoundingAdjustment
|
||||||
)
|
)
|
||||||
|
|
||||||
if (result.openingBalanceEntryId) {
|
if (result.openingBalanceEntryId) {
|
||||||
result.journalEntriesCreated++
|
result.journalEntriesCreated++
|
||||||
result.journalEntryIds.push(result.openingBalanceEntryId)
|
result.journalEntryIds.push(result.openingBalanceEntryId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1216,6 +1370,10 @@ export async function executeSIEImport(
|
|||||||
result.journalEntryIds.push(...voucherResults.ids)
|
result.journalEntryIds.push(...voucherResults.ids)
|
||||||
result.errors.push(...voucherResults.errors)
|
result.errors.push(...voucherResults.errors)
|
||||||
voucherNumberMapping = voucherResults.voucherNumberMapping
|
voucherNumberMapping = voucherResults.voucherNumberMapping
|
||||||
|
voucherRetryStats = {
|
||||||
|
retriedBatches: voucherResults.retriedBatches,
|
||||||
|
failedBatches: voucherResults.failedBatches,
|
||||||
|
}
|
||||||
|
|
||||||
// Update stats for documentation
|
// Update stats for documentation
|
||||||
voucherStats = {
|
voucherStats = {
|
||||||
@@ -1287,10 +1445,15 @@ export async function executeSIEImport(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save account mappings for future use
|
// Save account mappings for future use (non-fatal — import data is already committed)
|
||||||
await saveMappings(supabase, userId, mappings)
|
try {
|
||||||
|
await saveMappings(supabase, userId, mappings)
|
||||||
|
} catch (mappingError) {
|
||||||
|
console.error('[sie-import] Failed to save mappings (non-fatal):', mappingError)
|
||||||
|
result.warnings.push('Kunde inte spara kontomappningar — påverkar inte importerade data')
|
||||||
|
}
|
||||||
|
|
||||||
// Fix 6: Generate systemdokumentation (MigrationDocumentation)
|
// Generate systemdokumentation (MigrationDocumentation)
|
||||||
const mappingStats = getMappingStats(mappings)
|
const mappingStats = getMappingStats(mappings)
|
||||||
const documentation: MigrationDocumentation = {
|
const documentation: MigrationDocumentation = {
|
||||||
sourceSystem: parsed.header.program,
|
sourceSystem: parsed.header.program,
|
||||||
@@ -1323,17 +1486,43 @@ export async function executeSIEImport(
|
|||||||
voucherNumberMapping,
|
voucherNumberMapping,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set success before recording so recordImport() sees correct status
|
// Populate structured details for the UI
|
||||||
|
const totalSkippedForDetails = voucherStats.skippedUnbalanced + voucherStats.skippedUnmapped +
|
||||||
|
voucherStats.skippedSingleLine + voucherStats.skippedEmpty
|
||||||
|
result.details = {
|
||||||
|
fiscalYear: fiscalYearStart && fiscalYearEnd
|
||||||
|
? { start: formatDate(fiscalYearStart), end: formatDate(fiscalYearEnd) }
|
||||||
|
: undefined,
|
||||||
|
skippedVouchers: totalSkippedForDetails > 0 ? {
|
||||||
|
unbalanced: voucherStats.skippedUnbalanced,
|
||||||
|
unmapped: voucherStats.skippedUnmapped,
|
||||||
|
singleLine: voucherStats.skippedSingleLine,
|
||||||
|
empty: voucherStats.skippedEmpty,
|
||||||
|
total: totalSkippedForDetails,
|
||||||
|
} : undefined,
|
||||||
|
openingBalance: ibRoundingAdjustment !== 0 ? {
|
||||||
|
imbalance: ibRoundingAdjustment,
|
||||||
|
explanation: ibExplanation,
|
||||||
|
bookedToAccount: '2099',
|
||||||
|
} : undefined,
|
||||||
|
migrationAdjustment: migrationAdjustmentInfo.created ? {
|
||||||
|
created: true,
|
||||||
|
accountsAdjusted: migrationAdjustmentInfo.deltaAccounts,
|
||||||
|
} : undefined,
|
||||||
|
retriedBatches: voucherRetryStats.retriedBatches,
|
||||||
|
failedBatches: voucherRetryStats.failedBatches,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set success before finalizing
|
||||||
result.success = result.errors.length === 0
|
result.success = result.errors.length === 0
|
||||||
|
|
||||||
// Record the import with documentation
|
// Finalize the import record with results and documentation
|
||||||
result.importId = await recordImport(
|
await finalizeImportRecord(
|
||||||
supabase,
|
supabase,
|
||||||
|
result.importId,
|
||||||
userId,
|
userId,
|
||||||
parsed,
|
|
||||||
options.fileContent,
|
|
||||||
options.filename,
|
|
||||||
result,
|
result,
|
||||||
|
options.fileContent,
|
||||||
documentation
|
documentation
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1348,6 +1537,21 @@ export async function executeSIEImport(
|
|||||||
result.errors.push(
|
result.errors.push(
|
||||||
`Import failed: ${error instanceof Error ? error.message : 'Unknown error'}`
|
`Import failed: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Mark the pending import as failed if we created one
|
||||||
|
if (result.importId) {
|
||||||
|
try {
|
||||||
|
await finalizeImportRecord(
|
||||||
|
supabase,
|
||||||
|
result.importId,
|
||||||
|
userId,
|
||||||
|
result,
|
||||||
|
options.fileContent
|
||||||
|
)
|
||||||
|
} catch (finalizeError) {
|
||||||
|
console.error('[sie-import] Failed to finalize import record on error:', finalizeError)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -140,15 +140,6 @@ export function detectEncoding(buffer: ArrayBuffer): SIEEncoding {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// CP437 Swedish chars live in 0x80-0x9F
|
|
||||||
if (byte >= 0x80 && byte <= 0x9f && CP437_MAP[byte]) {
|
|
||||||
cp437Count++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Windows-1252 Swedish chars live in 0xC0-0xFF
|
|
||||||
if (WIN1252_SWEDISH_BYTES.has(byte)) {
|
|
||||||
win1252Count++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (utf8Count > cp437Count && utf8Count > win1252Count) return 'utf8'
|
if (utf8Count > cp437Count && utf8Count > win1252Count) return 'utf8'
|
||||||
|
|||||||
@@ -191,6 +191,7 @@ export interface SIEImport {
|
|||||||
opening_balance_entry_id: string | null
|
opening_balance_entry_id: string | null
|
||||||
imported_at: string | null
|
imported_at: string | null
|
||||||
migration_documentation: MigrationDocumentation | null
|
migration_documentation: MigrationDocumentation | null
|
||||||
|
file_storage_path: string | null
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
@@ -233,6 +234,47 @@ export interface ImportOptions {
|
|||||||
voucherSeries?: string
|
voucherSeries?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Structured import details for UI display.
|
||||||
|
* Provides machine-readable data so the UI can render proper explanations
|
||||||
|
* instead of parsing warning strings.
|
||||||
|
*/
|
||||||
|
export interface ImportResultDetails {
|
||||||
|
/** Fiscal year this import covers */
|
||||||
|
fiscalYear?: { start: string; end: string }
|
||||||
|
|
||||||
|
/** Breakdown of skipped vouchers by reason */
|
||||||
|
skippedVouchers?: {
|
||||||
|
unbalanced: number
|
||||||
|
unmapped: number
|
||||||
|
singleLine: number
|
||||||
|
empty: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opening balance imbalance info */
|
||||||
|
openingBalance?: {
|
||||||
|
/** SEK amount of the imbalance (0 if balanced) */
|
||||||
|
imbalance: number
|
||||||
|
/** Why the imbalance exists */
|
||||||
|
explanation: 'unallocated_result' | 'excluded_accounts' | 'rounding' | null
|
||||||
|
/** Account the difference was booked to */
|
||||||
|
bookedToAccount: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Migration adjustment entry info */
|
||||||
|
migrationAdjustment?: {
|
||||||
|
created: boolean
|
||||||
|
accountsAdjusted: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Number of batches that needed retries (0 = clean run) */
|
||||||
|
retriedBatches: number
|
||||||
|
|
||||||
|
/** Number of batches that still failed after all retries */
|
||||||
|
failedBatches: number
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Result of executing an import
|
* Result of executing an import
|
||||||
*/
|
*/
|
||||||
@@ -249,6 +291,9 @@ export interface ImportResult {
|
|||||||
// Issues
|
// Issues
|
||||||
errors: string[]
|
errors: string[]
|
||||||
warnings: string[]
|
warnings: string[]
|
||||||
|
|
||||||
|
// Structured details for UI (populated alongside warnings for backwards compat)
|
||||||
|
details?: ImportResultDetails
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -112,6 +112,12 @@ function makeMappingResult(overrides: Record<string, unknown> = {}) {
|
|||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Tests
|
// Tests
|
||||||
|
//
|
||||||
|
// Queue order after batch dedup refactor:
|
||||||
|
// 1. Booked transaction map query
|
||||||
|
// 2. Supplier invoices fetch
|
||||||
|
// 3. Batch external_id dedup query (returns matching external_ids)
|
||||||
|
// 4. Per-transaction: insert, updates, etc.
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
describe('ingestTransactions', () => {
|
describe('ingestTransactions', () => {
|
||||||
@@ -134,8 +140,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch (no unpaid invoices)
|
// Supplier invoices fetch (no unpaid invoices)
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup check returns null (no existing row)
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert returns the new transaction
|
// Insert returns the new transaction
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
// evaluateMappingRules will be called but we want low confidence
|
// evaluateMappingRules will be called but we want low confidence
|
||||||
@@ -160,8 +166,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup check returns an existing record
|
// Batch external_id dedup query — returns matching external_id
|
||||||
enqueue({ data: { id: 'existing-tx-1' }, error: null })
|
enqueue({ data: [{ external_id: raw.external_id }], error: null })
|
||||||
|
|
||||||
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
|
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
|
||||||
|
|
||||||
@@ -181,8 +187,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup check: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert fails
|
// Insert fails
|
||||||
enqueue({ data: null, error: { message: 'DB constraint violation' } })
|
enqueue({ data: null, error: { message: 'DB constraint violation' } })
|
||||||
|
|
||||||
@@ -209,8 +215,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert returns the new transaction
|
// Insert returns the new transaction
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
// Invoice match update (supabase.from('transactions').update(...))
|
// Invoice match update (supabase.from('transactions').update(...))
|
||||||
@@ -252,8 +258,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
@@ -283,8 +289,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
// Update after journal entry creation
|
// Update after journal entry creation
|
||||||
@@ -322,8 +328,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
@@ -353,8 +359,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
@@ -383,11 +389,11 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Transaction 1: dedup (no match), insert OK
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
|
// Transaction 1: insert OK
|
||||||
enqueue({ data: inserted1, error: null })
|
enqueue({ data: inserted1, error: null })
|
||||||
// Transaction 2: dedup (no match), insert OK
|
// Transaction 2: insert OK
|
||||||
enqueue({ data: null, error: null })
|
|
||||||
enqueue({ data: inserted2, error: null })
|
enqueue({ data: inserted2, error: null })
|
||||||
|
|
||||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||||
@@ -422,19 +428,16 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Transaction rawNew: dedup (no match), insert OK
|
// Batch external_id dedup query — ext-dup already exists
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [{ external_id: 'ext-dup' }], error: null })
|
||||||
|
// Transaction rawNew: insert OK
|
||||||
enqueue({ data: insertedNew, error: null })
|
enqueue({ data: insertedNew, error: null })
|
||||||
// Invoice match update for income transaction
|
// Invoice match update for income transaction
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: null, error: null })
|
||||||
// Auto-categorization update
|
// Auto-categorization update
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: null, error: null })
|
||||||
|
// rawDup: skipped (in Set) — no queue entry needed
|
||||||
// Transaction rawDup: dedup returns existing record
|
// Transaction rawErr: insert fails
|
||||||
enqueue({ data: { id: 'existing-dup' }, error: null })
|
|
||||||
|
|
||||||
// Transaction rawErr: dedup (no match), insert fails
|
|
||||||
enqueue({ data: null, error: null })
|
|
||||||
enqueue({ data: null, error: { message: 'Insert failed' } })
|
enqueue({ data: null, error: { message: 'Insert failed' } })
|
||||||
|
|
||||||
// Income transaction gets an invoice match
|
// Income transaction gets an invoice match
|
||||||
@@ -496,7 +499,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
enqueue({ data: null, error: null })
|
// Batch external_id dedup query (no matches)
|
||||||
|
enqueue({ data: [], error: null })
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
mockGetBestInvoiceMatch.mockRejectedValue(new Error('Network error'))
|
mockGetBestInvoiceMatch.mockRejectedValue(new Error('Network error'))
|
||||||
@@ -522,7 +526,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
enqueue({ data: null, error: null })
|
// Batch external_id dedup query (no matches)
|
||||||
|
enqueue({ data: [], error: null })
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
mockEvaluateMappingRules.mockRejectedValue(new Error('Mapping error'))
|
mockEvaluateMappingRules.mockRejectedValue(new Error('Mapping error'))
|
||||||
@@ -574,8 +579,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
// Reconciliation update
|
// Reconciliation update
|
||||||
@@ -618,8 +623,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
@@ -647,8 +652,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Dedup: no duplicate
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
@@ -679,8 +684,8 @@ describe('ingestTransactions', () => {
|
|||||||
})
|
})
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// external_id dedup: no match (different source)
|
// Batch external_id dedup query (no match by external_id)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
|
|
||||||
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
|
const result = await ingestTransactions(supabase as never, USER_ID, [raw])
|
||||||
|
|
||||||
@@ -704,8 +709,8 @@ describe('ingestTransactions', () => {
|
|||||||
})
|
})
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// external_id dedup: no match
|
// Batch external_id dedup query (no match)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
@@ -738,13 +743,12 @@ describe('ingestTransactions', () => {
|
|||||||
})
|
})
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
|
// Batch external_id dedup query (no matches for any)
|
||||||
|
enqueue({ data: [], error: null })
|
||||||
|
|
||||||
// raw1: external_id dedup (no match) -> content dedup matches (bookedCount=2 -> 1)
|
// raw1: not in external_id set → content dedup matches (bookedCount=2 -> 1)
|
||||||
enqueue({ data: null, error: null })
|
// raw2: not in external_id set → content dedup matches (bookedCount=1 -> 0)
|
||||||
// raw2: external_id dedup (no match) -> content dedup matches (bookedCount=1 -> 0)
|
// raw3: not in external_id set → content dedup exhausted → insert
|
||||||
enqueue({ data: null, error: null })
|
|
||||||
// raw3: external_id dedup (no match) -> content dedup exhausted -> insert
|
|
||||||
enqueue({ data: null, error: null })
|
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
mockEvaluateMappingRules.mockResolvedValue(makeMappingResult({ confidence: 0.5 }))
|
||||||
@@ -764,8 +768,8 @@ describe('ingestTransactions', () => {
|
|||||||
enqueue({ error: { message: 'Query failed' } })
|
enqueue({ error: { message: 'Query failed' } })
|
||||||
// Supplier invoices fetch
|
// Supplier invoices fetch
|
||||||
enqueue({ data: [], error: null })
|
enqueue({ data: [], error: null })
|
||||||
// external_id dedup: no match
|
// Batch external_id dedup query (no matches)
|
||||||
enqueue({ data: null, error: null })
|
enqueue({ data: [], error: null })
|
||||||
// Insert
|
// Insert
|
||||||
enqueue({ data: inserted, error: null })
|
enqueue({ data: inserted, error: null })
|
||||||
|
|
||||||
|
|||||||
@@ -124,16 +124,22 @@ export async function ingestTransactions(
|
|||||||
// Non-critical — amount_sek fields will stay null
|
// Non-critical — amount_sek fields will stay null
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const raw of rawTransactions) {
|
// Pre-fetch existing external_ids in batches for dedup (avoids N+1 queries)
|
||||||
// 1. Check for duplicates via external_id
|
const existingExternalIds = new Set<string>()
|
||||||
const { data: existing } = await supabase
|
const externalIds = rawTransactions.map(t => t.external_id)
|
||||||
|
for (let i = 0; i < externalIds.length; i += 500) {
|
||||||
|
const chunk = externalIds.slice(i, i + 500)
|
||||||
|
const { data } = await supabase
|
||||||
.from('transactions')
|
.from('transactions')
|
||||||
.select('id')
|
.select('external_id')
|
||||||
.eq('user_id', userId)
|
.eq('user_id', userId)
|
||||||
.eq('external_id', raw.external_id)
|
.in('external_id', chunk)
|
||||||
.single()
|
data?.forEach(r => existingExternalIds.add(r.external_id))
|
||||||
|
}
|
||||||
|
|
||||||
if (existing) {
|
for (const raw of rawTransactions) {
|
||||||
|
// 1. Check for duplicates via external_id (batch pre-fetched)
|
||||||
|
if (existingExternalIds.has(raw.external_id)) {
|
||||||
result.duplicates++
|
result.duplicates++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
-- Add oauth_state for CSRF protection during OAuth callback
|
||||||
|
ALTER TABLE public.bank_connections
|
||||||
|
ADD COLUMN IF NOT EXISTS oauth_state text;
|
||||||
|
|
||||||
|
-- Add last_expiry_notification_at for consent expiry notification tracking
|
||||||
|
ALTER TABLE public.bank_connections
|
||||||
|
ADD COLUMN IF NOT EXISTS last_expiry_notification_at timestamptz;
|
||||||
|
|
||||||
|
-- Index on oauth_state for fast lookup during callback (partial — only non-null)
|
||||||
|
CREATE INDEX idx_bank_connections_oauth_state
|
||||||
|
ON public.bank_connections (oauth_state)
|
||||||
|
WHERE oauth_state IS NOT NULL;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- SIE Import Fixes
|
||||||
|
-- 1. Add missing columns to sie_imports
|
||||||
|
-- 2. Add reserve_voucher_range RPC for batch voucher number reservation
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- 1. Add missing columns
|
||||||
|
-- =============================================================================
|
||||||
|
ALTER TABLE public.sie_imports
|
||||||
|
ADD COLUMN IF NOT EXISTS migration_documentation jsonb,
|
||||||
|
ADD COLUMN IF NOT EXISTS file_storage_path text;
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- 2. reserve_voucher_range: advance voucher sequence to at least p_highest_used
|
||||||
|
-- Used by SIE import to reserve a contiguous block of voucher numbers.
|
||||||
|
-- =============================================================================
|
||||||
|
CREATE OR REPLACE FUNCTION public.reserve_voucher_range(
|
||||||
|
p_user_id uuid,
|
||||||
|
p_fiscal_period_id uuid,
|
||||||
|
p_series text,
|
||||||
|
p_highest_used integer
|
||||||
|
)
|
||||||
|
RETURNS void
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
SECURITY DEFINER
|
||||||
|
SET search_path = public
|
||||||
|
AS $$
|
||||||
|
BEGIN
|
||||||
|
INSERT INTO public.voucher_sequences (user_id, fiscal_period_id, voucher_series, last_number)
|
||||||
|
VALUES (p_user_id, p_fiscal_period_id, p_series, p_highest_used)
|
||||||
|
ON CONFLICT (user_id, fiscal_period_id, voucher_series)
|
||||||
|
DO UPDATE SET
|
||||||
|
last_number = GREATEST(public.voucher_sequences.last_number, EXCLUDED.last_number),
|
||||||
|
updated_at = now();
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
GRANT EXECUTE ON FUNCTION public.reserve_voucher_range(uuid, uuid, text, integer) TO authenticated;
|
||||||
@@ -1017,6 +1017,7 @@ export interface OnboardingProgress {
|
|||||||
hasCustomers: boolean
|
hasCustomers: boolean
|
||||||
hasInvoices: boolean
|
hasInvoices: boolean
|
||||||
hasBankConnected: boolean
|
hasBankConnected: boolean
|
||||||
|
hasSIEImport: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
// Onboarding step data
|
// Onboarding step data
|
||||||
|
|||||||
Reference in New Issue
Block a user