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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
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: recentReceiptActivity },
|
||||
{ data: enabledToggles },
|
||||
{ count: sieImportCount },
|
||||
{ count: staleUncategorizedCount },
|
||||
] = await Promise.all([
|
||||
supabase.from('profiles').select('full_name').eq('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('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('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
|
||||
@@ -82,6 +86,7 @@ export default async function DashboardPage() {
|
||||
hasCustomers: (customerCount || 0) > 0,
|
||||
hasInvoices: (invoiceCount || 0) > 0,
|
||||
hasBankConnected: (transactionCount || 0) > 0,
|
||||
hasSIEImport: (sieImportCount || 0) > 0,
|
||||
}
|
||||
|
||||
// Calculate totals from journal entry lines using account classes
|
||||
@@ -215,6 +220,7 @@ export default async function DashboardPage() {
|
||||
deadlines: (deadlines || []) as Deadline[],
|
||||
receiptQueue,
|
||||
missingUnderlagCount,
|
||||
staleUncategorizedCount: staleUncategorizedCount || 0,
|
||||
}}
|
||||
onboardingProgress={onboardingProgress}
|
||||
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 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 errorDescription = searchParams.get('error_description')
|
||||
|
||||
@@ -35,8 +35,25 @@ export async function GET(request: Request) {
|
||||
const supabase = await createServiceClient()
|
||||
|
||||
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 { session_id, accounts, access, aspsp } = sessionData
|
||||
const { session_id, accounts, access } = sessionData
|
||||
const consentExpiresAt = access.valid_until
|
||||
|
||||
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')
|
||||
.select('id')
|
||||
.eq('user_id', state)
|
||||
.eq('status', 'pending')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.single()
|
||||
.update({
|
||||
session_id,
|
||||
status: 'active',
|
||||
accounts_data: accountsWithBalances,
|
||||
consent_expires: consentExpiresAt,
|
||||
last_synced_at: new Date().toISOString(),
|
||||
oauth_state: null, // Clear to prevent replay
|
||||
})
|
||||
.eq('id', pendingConnection.id)
|
||||
|
||||
let connectionId: string
|
||||
|
||||
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
|
||||
if (updateError) {
|
||||
throw new Error('Failed to update connection')
|
||||
}
|
||||
|
||||
const connectionId = pendingConnection.id
|
||||
|
||||
const { data: userSettings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('user_id', state)
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
|
||||
const redirectTarget = userSettings?.onboarding_complete
|
||||
@@ -131,8 +115,8 @@ export async function GET(request: Request) {
|
||||
try {
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({ status: 'error' })
|
||||
.eq('user_id', state)
|
||||
.update({ status: 'error', oauth_state: null })
|
||||
.eq('oauth_state', state)
|
||||
.eq('status', 'pending')
|
||||
} catch {
|
||||
// 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 { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync'
|
||||
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 type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||
|
||||
@@ -12,7 +18,7 @@ ensureInitialized()
|
||||
* Automatic daily bank transaction sync
|
||||
* 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.
|
||||
* Deduplication via external_id makes repeated runs safe.
|
||||
*/
|
||||
@@ -68,6 +74,7 @@ export async function GET(request: Request) {
|
||||
|
||||
const startTime = Date.now()
|
||||
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: {
|
||||
connectionId: string
|
||||
@@ -96,6 +103,11 @@ export async function GET(request: Request) {
|
||||
.update({ status: 'expired' })
|
||||
.eq('id', connection.id)
|
||||
|
||||
// Send expiry notification
|
||||
await sendConsentExpiryNotification(
|
||||
supabase, connection, 0, true, baseUrl
|
||||
)
|
||||
|
||||
results.push({
|
||||
connectionId: connection.id,
|
||||
userId: connection.user_id,
|
||||
@@ -111,6 +123,13 @@ export async function GET(request: Request) {
|
||||
|
||||
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 fromDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
@@ -133,11 +152,13 @@ export async function GET(request: Request) {
|
||||
const totalDuplicates = syncResults.reduce((sum, r) => sum + r.duplicates, 0)
|
||||
const totalErrors = syncResults.reduce((sum, r) => sum + r.errors, 0)
|
||||
|
||||
// Successful sync: update connection and clear any previous error state
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({
|
||||
accounts_data: accounts,
|
||||
last_synced_at: new Date().toISOString(),
|
||||
...(connection.error_message ? { error_message: null } : {}),
|
||||
})
|
||||
.eq('id', connection.id)
|
||||
|
||||
@@ -152,7 +173,15 @@ export async function GET(request: Request) {
|
||||
daysUntilExpiry: daysLeft,
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Unknown 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({
|
||||
connectionId: connection.id,
|
||||
userId: connection.user_id,
|
||||
@@ -181,3 +210,65 @@ export async function GET(request: Request) {
|
||||
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) {
|
||||
return NextResponse.json({
|
||||
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,
|
||||
}, { status: 409 })
|
||||
}
|
||||
|
||||
+3
-3
@@ -46,7 +46,7 @@ export default function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="sv" suppressHydrationWarning>
|
||||
<html lang="sv" suppressHydrationWarning className={`${geistSans.variable} ${geistMono.variable} ${fraunces.variable}`}>
|
||||
<head>
|
||||
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
|
||||
<script
|
||||
@@ -58,11 +58,11 @@ export default function RootLayout({
|
||||
/>
|
||||
</head>
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} ${fraunces.variable} antialiased`}
|
||||
className="antialiased"
|
||||
>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
defaultTheme="light"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
Landmark,
|
||||
CheckCircle2,
|
||||
FileWarning,
|
||||
Clock,
|
||||
} from 'lucide-react'
|
||||
import { getExtensionDefinition } from '@/lib/extensions/sectors'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
@@ -41,6 +42,7 @@ interface DashboardContentProps {
|
||||
deadlines: Deadline[]
|
||||
receiptQueue: ReceiptQueueSummary | null
|
||||
missingUnderlagCount: number
|
||||
staleUncategorizedCount: number
|
||||
}
|
||||
onboardingProgress?: OnboardingProgress
|
||||
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) {
|
||||
const conn = summary.expiringBankConnections[0]
|
||||
alertItems.push(
|
||||
@@ -249,6 +271,7 @@ export default function DashboardContent({ firstName, settings, summary, onboard
|
||||
hasCustomers={onboardingProgress.hasCustomers}
|
||||
hasInvoices={onboardingProgress.hasInvoices}
|
||||
hasBankConnected={onboardingProgress.hasBankConnected}
|
||||
hasSIEImport={onboardingProgress.hasSIEImport}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
import EmptyExtensionState from '@/components/extensions/shared/EmptyExtensionState'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
import { Wand } from 'lucide-react'
|
||||
|
||||
export default function AiCategorizationWorkspace({ userId }: WorkspaceComponentProps) {
|
||||
return (
|
||||
<EmptyExtensionState
|
||||
title="AI-kategorisering"
|
||||
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,
|
||||
Info,
|
||||
RotateCcw,
|
||||
AlertTriangle,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Calendar,
|
||||
XCircle,
|
||||
BookOpen,
|
||||
} from 'lucide-react'
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
|
||||
@@ -732,6 +738,213 @@ function MigratingStep({ currentStep, progress }: { currentStep: string; progres
|
||||
|
||||
// ── 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({
|
||||
results,
|
||||
sieResults,
|
||||
@@ -753,8 +966,8 @@ function ResultStep({
|
||||
<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" />
|
||||
<div>
|
||||
<p className="font-medium text-destructive">Migreringen misslyckades</p>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
<p className="text-base font-medium text-destructive">Migreringen misslyckades</p>
|
||||
<p className="mt-1 text-sm text-muted-foreground">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -773,77 +986,119 @@ function ResultStep({
|
||||
const hasResults = results || sieResults.length > 0
|
||||
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 allSieErrors = sieResults.flatMap(r => r.errors)
|
||||
const allSieWarnings = sieResults.flatMap(r => r.warnings)
|
||||
const totalErrors = sieResults.reduce((sum, r) => sum + r.errors.length, 0)
|
||||
const totalSkipped = sieResults.reduce((sum, r) => (r.details?.skippedVouchers?.total || 0) + sum, 0)
|
||||
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 (
|
||||
<div className="space-y-4">
|
||||
{/* ── Header card with overall summary ── */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CheckCircle className="h-5 w-5 text-green-600" />
|
||||
Migrering klar
|
||||
<CardTitle className="flex items-center gap-2.5">
|
||||
<StatusIcon status={overallIcon} />
|
||||
{anySieFailed ? 'Migrering delvis genomförd' :
|
||||
!allSieSucceeded ? 'Migrering klar med anmärkningar' :
|
||||
'Migrering klar'}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Din bokföringsdata har importerats till gnubok.
|
||||
<CardDescription className="text-sm">
|
||||
{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>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{/* SIE import results — combined summary */}
|
||||
{sieResults.length > 0 && (
|
||||
<ResultRow
|
||||
label="Bokföringsdata (SIE)"
|
||||
value={allSieSucceeded ? 'Importerad' : 'Delvis importerad'}
|
||||
detail={totalJournalEntries > 0
|
||||
? `${totalJournalEntries} verifikationer skapade (${sieResults.length} räkenskapsår)`
|
||||
: `${sieResults.length} räkenskapsår importerade`
|
||||
}
|
||||
errors={allSieErrors}
|
||||
warnings={allSieWarnings}
|
||||
</Card>
|
||||
|
||||
{/* ── Per-fiscal-year SIE breakdown ── */}
|
||||
{sieResults.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<Database className="h-4 w-4" />
|
||||
Bokföringsdata (SIE)
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
{sieResults.map((r, i) => (
|
||||
<FiscalYearResult key={i} result={r} index={i} />
|
||||
))}
|
||||
</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'}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* API import results */}
|
||||
{results?.companyInfo && (
|
||||
<ResultRow label="Företagsinformation" value={results.companyInfo.imported ? 'Importerad' : 'Hoppad'} />
|
||||
)}
|
||||
{results?.customers && (
|
||||
<ResultRow
|
||||
{results.customers && (
|
||||
<EntityResultRow
|
||||
icon={<Users className="h-4 w-4" />}
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
{results?.suppliers && (
|
||||
<ResultRow
|
||||
{results.suppliers && (
|
||||
<EntityResultRow
|
||||
icon={<Truck className="h-4 w-4" />}
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
{results?.salesInvoices && (
|
||||
<ResultRow
|
||||
{results.salesInvoices && (
|
||||
<EntityResultRow
|
||||
icon={<FileText className="h-4 w-4" />}
|
||||
label="Kundfakturor"
|
||||
value={`${results.salesInvoices.imported} importerade`}
|
||||
detail={results.salesInvoices.skipped > 0 ? `${results.salesInvoices.skipped} hoppade` : undefined}
|
||||
status="success"
|
||||
statusText={`${results.salesInvoices.imported} importerade`}
|
||||
detail={results.salesInvoices.skipped > 0 ? `${results.salesInvoices.skipped} hoppades över` : undefined}
|
||||
/>
|
||||
)}
|
||||
{results?.supplierInvoices && (
|
||||
<ResultRow
|
||||
{results.supplierInvoices && (
|
||||
<EntityResultRow
|
||||
icon={<FileText className="h-4 w-4" />}
|
||||
label="Leverantörsfakturor"
|
||||
value={`${results.supplierInvoices.imported} importerade`}
|
||||
detail={results.supplierInvoices.skipped > 0 ? `${results.supplierInvoices.skipped} hoppade` : undefined}
|
||||
status="success"
|
||||
statusText={`${results.supplierInvoices.imported} importerade`}
|
||||
detail={results.supplierInvoices.skipped > 0 ? `${results.supplierInvoices.skipped} hoppades över` : undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Next steps guidance */}
|
||||
{/* ── Next steps ── */}
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Nästa steg</CardTitle>
|
||||
@@ -855,7 +1110,7 @@ function ResultStep({
|
||||
</div>
|
||||
<div>
|
||||
<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 className="flex items-start gap-3">
|
||||
@@ -863,8 +1118,8 @@ function ResultStep({
|
||||
2
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Kontrollera kunder och leverantörer</p>
|
||||
<p className="text-sm text-muted-foreground">Verifiera att kontaktuppgifter och bankinfo stämmer</p>
|
||||
<p className="font-medium">Stäm av balansräkningen</p>
|
||||
<p className="text-sm text-muted-foreground">Jämför ingående balanser och saldon mot ditt tidigare system</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
@@ -872,8 +1127,8 @@ function ResultStep({
|
||||
3
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Verifiera balanserna i rapporterna</p>
|
||||
<p className="text-sm text-muted-foreground">Jämför med ditt tidigare system</p>
|
||||
<p className="font-medium">Kontrollera kunder och leverantörer</p>
|
||||
<p className="text-sm text-muted-foreground">Verifiera kontaktuppgifter, organisationsnummer och bankinfo</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -903,38 +1158,29 @@ function ResultStep({
|
||||
)
|
||||
}
|
||||
|
||||
function ResultRow({
|
||||
/** Simple row for non-SIE entity results (customers, invoices, etc.) */
|
||||
function EntityResultRow({
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
status,
|
||||
statusText,
|
||||
detail,
|
||||
errors,
|
||||
warnings,
|
||||
}: {
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
value: string
|
||||
status: 'success' | 'skipped'
|
||||
statusText: string
|
||||
detail?: string
|
||||
errors?: string[]
|
||||
warnings?: string[]
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-lg border border-border p-3">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
<p className="text-sm text-muted-foreground">{value}</p>
|
||||
{detail && <p className="text-xs text-muted-foreground">{detail}</p>}
|
||||
{warnings && warnings.length > 0 && (
|
||||
<p className="mt-1 text-xs text-warning-foreground">{warnings.join('. ')}</p>
|
||||
)}
|
||||
{errors && errors.length > 0 && (
|
||||
<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 className="flex items-center gap-3 rounded-lg border border-border p-3">
|
||||
<div className="text-muted-foreground">{icon}</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">{label}</p>
|
||||
<p className="text-sm text-muted-foreground">{statusText}</p>
|
||||
{detail && <p className="text-sm text-muted-foreground/70">{detail}</p>}
|
||||
</div>
|
||||
<StatusIcon status={status === 'success' ? 'success' : 'warning'} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,8 +8,14 @@ import { Progress } from '@/components/ui/progress'
|
||||
import {
|
||||
Check,
|
||||
Circle,
|
||||
Sparkles,
|
||||
PartyPopper,
|
||||
Rocket,
|
||||
X,
|
||||
FileUp,
|
||||
ArrowRight,
|
||||
UserPlus,
|
||||
Receipt,
|
||||
ArrowLeftRight,
|
||||
} from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -19,17 +25,20 @@ interface ChecklistItem {
|
||||
description: string
|
||||
href: string
|
||||
completed: boolean
|
||||
icon: React.ElementType
|
||||
}
|
||||
|
||||
interface NewUserChecklistProps {
|
||||
hasCustomers: boolean
|
||||
hasInvoices: boolean
|
||||
hasBankConnected: boolean
|
||||
hasSIEImport: boolean
|
||||
onDismiss?: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
const CHECKLIST_DISMISSED_KEY = 'erp_checklist_dismissed'
|
||||
const FRESH_START_KEY = 'erp_onboarding_fresh'
|
||||
|
||||
export default function NewUserChecklist({
|
||||
hasCustomers,
|
||||
@@ -38,49 +47,24 @@ export default function NewUserChecklist({
|
||||
onDismiss,
|
||||
className,
|
||||
}: NewUserChecklistProps) {
|
||||
const [isDismissed, setIsDismissed] = useState(true) // Start hidden until we check localStorage
|
||||
const [isDismissed, setIsDismissed] = useState(true)
|
||||
const [isAnimatingOut, setIsAnimatingOut] = useState(false)
|
||||
const [showChecklist, setShowChecklist] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
// Check if checklist has been dismissed
|
||||
const dismissed = localStorage.getItem(CHECKLIST_DISMISSED_KEY)
|
||||
setIsDismissed(dismissed === 'true')
|
||||
|
||||
const freshStart = localStorage.getItem(FRESH_START_KEY)
|
||||
if (freshStart === 'true') {
|
||||
setShowChecklist(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const items: ChecklistItem[] = [
|
||||
{
|
||||
id: 'account',
|
||||
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 handleFreshStart = () => {
|
||||
setShowChecklist(true)
|
||||
localStorage.setItem(FRESH_START_KEY, 'true')
|
||||
}
|
||||
|
||||
const handleDismiss = () => {
|
||||
setIsAnimatingOut(true)
|
||||
@@ -91,19 +75,49 @@ export default function NewUserChecklist({
|
||||
}, 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) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Auto-dismiss after all completed with celebration
|
||||
if (allCompleted && !isAnimatingOut) {
|
||||
// Celebration state when all checklist items done
|
||||
if (showChecklist && allCompleted && !isAnimatingOut) {
|
||||
return (
|
||||
<Card className={cn('border-success/50 bg-success/5', className)}>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<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 className="flex-1">
|
||||
<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 (
|
||||
<Card
|
||||
className={cn(
|
||||
@@ -136,21 +229,36 @@ export default function NewUserChecklist({
|
||||
{completedCount} av {items.length} steg klara
|
||||
</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 checklista</span>
|
||||
</Button>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setShowChecklist(false)
|
||||
localStorage.removeItem(FRESH_START_KEY)
|
||||
}}
|
||||
>
|
||||
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>
|
||||
<Progress value={progress} className="h-1.5 mt-3" />
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<ul className="space-y-1">
|
||||
{items.map((item) => (
|
||||
{items.map((item) => {
|
||||
const Icon = item.icon
|
||||
return (
|
||||
<li key={item.id}>
|
||||
{item.completed ? (
|
||||
<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" />
|
||||
</div>
|
||||
<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}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
@@ -180,7 +289,8 @@ export default function NewUserChecklist({
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
Check,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
Sparkles,
|
||||
Wand,
|
||||
} from 'lucide-react'
|
||||
import JournalEntryPreview from './JournalEntryPreview'
|
||||
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="min-w-0 flex-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">
|
||||
AI-förslag
|
||||
</Badge>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
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'
|
||||
|
||||
interface TransactionStatusBarProps {
|
||||
@@ -66,7 +66,7 @@ export default function TransactionStatusBar({
|
||||
onClick={onOpenSwipeView}
|
||||
disabled={isLoadingSuggestions}
|
||||
>
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
<Wand className="mr-2 h-4 w-4" />
|
||||
{isLoadingSuggestions ? 'Laddar...' : 'Gå igenom alla'}
|
||||
</Button>
|
||||
<Button
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"definition": {
|
||||
"name": "AI-kategorisering",
|
||||
"category": "operations",
|
||||
"icon": "Sparkles",
|
||||
"icon": "Wand",
|
||||
"dataPattern": "core",
|
||||
"readsCoreTables": ["transactions"],
|
||||
"description": "AI-drivna kategoriförslag för transaktioner",
|
||||
|
||||
@@ -51,11 +51,85 @@ function getOrgNumber(party: PartyDto): string | 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(
|
||||
vatNumber: string | undefined,
|
||||
countryCode: string | undefined
|
||||
countryCode: string | undefined,
|
||||
orgNumber?: string | null,
|
||||
companyName?: string
|
||||
): 'swedish_business' | 'eu_business' | 'non_eu_business' {
|
||||
// 1. VAT number prefix is the strongest signal
|
||||
if (vatNumber) {
|
||||
@@ -65,20 +139,68 @@ function inferTypeFromVatOrCountry(
|
||||
return 'non_eu_business'
|
||||
}
|
||||
|
||||
// 2. Fall back to address country
|
||||
// 2. Explicit country code
|
||||
const country = countryCode?.toUpperCase()
|
||||
if (!country || country === 'SE') return 'swedish_business'
|
||||
if (EU_COUNTRIES.includes(country)) return 'eu_business'
|
||||
return 'non_eu_business'
|
||||
if (country === 'SE') return 'swedish_business'
|
||||
if (country && EU_COUNTRIES.includes(country)) return '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 {
|
||||
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 {
|
||||
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 {
|
||||
@@ -183,7 +305,7 @@ export function mapSalesInvoice(
|
||||
your_reference: null,
|
||||
our_reference: 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_amount: dto.paymentStatus.paid ? total : round2(total - dto.paymentStatus.balance.value),
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
mapSalesInvoice,
|
||||
mapSupplierInvoice,
|
||||
mapCompanyInfo,
|
||||
inferTypeFromParty,
|
||||
} from './entity-mapper'
|
||||
|
||||
export interface MigrationOptions {
|
||||
@@ -246,12 +247,13 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
|
||||
}
|
||||
|
||||
if (!customerId) {
|
||||
const customerType = inferTypeFromParty(inv.customer)
|
||||
const minimalCustomer = {
|
||||
user_id: userId,
|
||||
name: inv.customer.name,
|
||||
customer_type: 'swedish_business',
|
||||
customer_type: customerType,
|
||||
default_payment_terms: 30,
|
||||
country: 'SE',
|
||||
country: inv.customer.postalAddress?.countryCode || (customerType === 'swedish_business' ? 'SE' : null),
|
||||
vat_number_validated: false,
|
||||
}
|
||||
const { data: created, error: custErr } = await supabase
|
||||
@@ -356,13 +358,14 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
|
||||
}
|
||||
|
||||
if (!supplierId) {
|
||||
const supplierType = inferTypeFromParty(inv.supplier)
|
||||
const minimalSupplier = {
|
||||
user_id: userId,
|
||||
name: inv.supplier.name,
|
||||
supplier_type: 'swedish_business',
|
||||
supplier_type: supplierType,
|
||||
default_payment_terms: 30,
|
||||
default_currency: 'SEK',
|
||||
country: 'SE',
|
||||
country: inv.supplier.postalAddress?.countryCode || (supplierType === 'swedish_business' ? 'SE' : null),
|
||||
}
|
||||
const { data: created, error: supErr } = await supabase
|
||||
.from('suppliers')
|
||||
|
||||
@@ -19,6 +19,7 @@ interface BankConnectionStatusProps {
|
||||
connection: BankConnection
|
||||
onSync: (connectionId: string) => void
|
||||
onDisconnect: (connectionId: string) => void
|
||||
onReconnect?: (bank: { name: string; country: string }) => void
|
||||
isSyncing?: boolean
|
||||
}
|
||||
|
||||
@@ -26,39 +27,53 @@ export function BankConnectionStatus({
|
||||
connection,
|
||||
onSync,
|
||||
onDisconnect,
|
||||
onReconnect,
|
||||
isSyncing = false,
|
||||
}: BankConnectionStatusProps) {
|
||||
const daysUntilExpiry = getDaysUntilExpiry(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: {
|
||||
icon: CheckCircle,
|
||||
color: 'text-success',
|
||||
label: 'Aktiv',
|
||||
variant: 'success' as const,
|
||||
variant: 'success',
|
||||
},
|
||||
pending: {
|
||||
icon: Loader2,
|
||||
color: 'text-warning',
|
||||
label: 'Väntar',
|
||||
variant: 'warning' as const,
|
||||
variant: 'warning',
|
||||
},
|
||||
expired: {
|
||||
icon: AlertTriangle,
|
||||
color: 'text-warning',
|
||||
label: 'Utgånget samtycke',
|
||||
variant: 'warning',
|
||||
},
|
||||
error: {
|
||||
icon: XCircle,
|
||||
color: 'text-destructive',
|
||||
label: 'Fel',
|
||||
variant: 'destructive' as const,
|
||||
variant: 'destructive',
|
||||
},
|
||||
revoked: {
|
||||
icon: XCircle,
|
||||
color: 'text-gray-600',
|
||||
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
|
||||
|
||||
// Parse accounts from connection
|
||||
@@ -81,6 +96,10 @@ export function BankConnectionStatus({
|
||||
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 (
|
||||
<div className="border rounded-lg p-4 space-y-4">
|
||||
{/* Header */}
|
||||
@@ -104,6 +123,35 @@ export function BankConnectionStatus({
|
||||
</div>
|
||||
</div>
|
||||
<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' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -128,8 +176,28 @@ export function BankConnectionStatus({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Consent expiry warning */}
|
||||
{isExpiring && daysUntilExpiry !== null && (
|
||||
{/* Error message */}
|
||||
{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">
|
||||
<AlertTriangle className="h-4 w-4 text-warning" />
|
||||
<span className="text-sm">
|
||||
|
||||
@@ -151,11 +151,36 @@ export default function BankingSettingsPanel() {
|
||||
}
|
||||
|
||||
const activeConnections = bankConnections.filter((c) => c.status === 'active')
|
||||
const actionRequiredConnections = bankConnections.filter((c) => ['expired', 'error'].includes(c.status))
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<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 */}
|
||||
{activeConnections.length > 0 && (
|
||||
<Card>
|
||||
|
||||
@@ -94,11 +94,14 @@ export const enableBankingExtension: Extension = {
|
||||
|
||||
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(
|
||||
aspsp_name,
|
||||
aspsp_country,
|
||||
redirectUrl,
|
||||
user.id,
|
||||
oauthState,
|
||||
psuType
|
||||
)
|
||||
|
||||
@@ -109,6 +112,7 @@ export const enableBankingExtension: Extension = {
|
||||
provider: `${aspsp_name.toLowerCase().replace(/\s+/g, '-')}-${aspsp_country.toLowerCase()}`,
|
||||
bank_name: aspsp_name,
|
||||
authorization_id,
|
||||
oauth_state: oauthState,
|
||||
status: 'pending',
|
||||
})
|
||||
.select()
|
||||
@@ -144,7 +148,8 @@ export const enableBankingExtension: Extension = {
|
||||
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
|
||||
.from('bank_connections')
|
||||
@@ -168,6 +173,7 @@ export const enableBankingExtension: Extension = {
|
||||
const fromDate = new Date(Date.now() - days_back * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.split('T')[0]
|
||||
const syncStartedAt = new Date().toISOString()
|
||||
|
||||
// Use ctx.services.ingestTransactions when available
|
||||
const ingestFn = ctx?.services.ingestTransactions
|
||||
@@ -202,7 +208,7 @@ export const enableBankingExtension: Extension = {
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('bank_connection_id', connection.id)
|
||||
.gte('created_at', fromDate)
|
||||
.gte('created_at', syncStartedAt)
|
||||
.order('created_at', { ascending: false })
|
||||
.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
|
||||
}
|
||||
|
||||
// Constants
|
||||
const FETCH_TIMEOUT_MS = 15_000
|
||||
const MAX_RETRIES = 2
|
||||
const RETRY_DELAY_MS = 1000
|
||||
const MAX_PAGINATION_PAGES = 100
|
||||
|
||||
// API Helper
|
||||
|
||||
async function authenticatedFetch(
|
||||
@@ -149,17 +155,53 @@ async function authenticatedFetch(
|
||||
options: RequestInit = {}
|
||||
): Promise<Response> {
|
||||
const url = `${ENABLE_BANKING_API_URL}${endpoint}`
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Authorization': getAuthorizationHeader(),
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
})
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
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
|
||||
@@ -175,7 +217,7 @@ export async function getASPSPs(country: string = 'SE'): Promise<ASPSP[]> {
|
||||
sandbox: String(isSandbox),
|
||||
psu_type: psuType,
|
||||
})
|
||||
const response = await authenticatedFetch(`/aspsps?${params.toString()}`)
|
||||
const response = await authenticatedFetchWithRetry(`/aspsps?${params.toString()}`)
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text()
|
||||
@@ -286,7 +328,7 @@ export async function createSession(code: string): Promise<SessionResponse> {
|
||||
* @param sessionId - The session ID
|
||||
*/
|
||||
export async function getSession(sessionId: string): Promise<SessionResponse> {
|
||||
const response = await authenticatedFetch(`/sessions/${sessionId}`)
|
||||
const response = await authenticatedFetchWithRetry(`/sessions/${sessionId}`)
|
||||
|
||||
if (!response.ok) {
|
||||
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)
|
||||
*/
|
||||
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) {
|
||||
throw new Error('Failed to get account balances')
|
||||
@@ -372,7 +414,7 @@ export async function getAccountTransactions(
|
||||
const queryString = params.toString()
|
||||
const endpoint = `/accounts/${accountUid}/transactions${queryString ? `?${queryString}` : ''}`
|
||||
|
||||
const response = await authenticatedFetch(endpoint)
|
||||
const response = await authenticatedFetchWithRetry(endpoint)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to get transactions')
|
||||
@@ -391,6 +433,7 @@ export async function getAllTransactions(
|
||||
): Promise<Transaction[]> {
|
||||
const allTransactions: Transaction[] = []
|
||||
let continuationKey: string | undefined
|
||||
let page = 0
|
||||
|
||||
do {
|
||||
const response = await getAccountTransactions(
|
||||
@@ -402,11 +445,63 @@ export async function getAllTransactions(
|
||||
|
||||
allTransactions.push(...response.transactions)
|
||||
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)
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
@@ -89,10 +89,29 @@ export function generateJWT(expiresInSeconds: number = 3600): string {
|
||||
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 {
|
||||
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}`
|
||||
}
|
||||
|
||||
/** @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 { 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 type { RawTransaction, IngestResult } 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.
|
||||
*
|
||||
* 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).
|
||||
* When called from an extension handler with ctx.services.ingestTransactions,
|
||||
@@ -36,13 +38,14 @@ export async function syncAccountTransactions(
|
||||
toDate: string,
|
||||
ingest: IngestFn = defaultIngest
|
||||
): Promise<SyncResult> {
|
||||
const bankTransactions = await getTransactions(
|
||||
const { transactions, rawPages } = await getAllTransactionsWithRaw(
|
||||
account.uid,
|
||||
fromDate,
|
||||
toDate,
|
||||
account.currency
|
||||
)
|
||||
|
||||
const bankTransactions = transactions.map(tx => convertTransaction(tx, account.currency))
|
||||
|
||||
// Convert Enable Banking format to generic RawTransaction
|
||||
const rawTransactions: RawTransaction[] = bankTransactions.map((tx) => ({
|
||||
date: tx.booking_date || tx.date,
|
||||
@@ -59,6 +62,21 @@ export async function syncAccountTransactions(
|
||||
|
||||
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
|
||||
try {
|
||||
const balance = await getAccountBalance(account.uid)
|
||||
|
||||
@@ -65,7 +65,7 @@ describe('BAS_REFERENCE data integrity', () => {
|
||||
})
|
||||
|
||||
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) {
|
||||
it(`${num} is not in the catalog`, () => {
|
||||
|
||||
@@ -695,27 +695,104 @@ export const CLASS_1_ACCOUNTS: BASReferenceAccount[] = [
|
||||
k2_excluded: false,
|
||||
},
|
||||
{
|
||||
account_number: '1250',
|
||||
account_name: '(Fritt konto för Inventarier, verktyg och installationer)',
|
||||
account_number: '1241',
|
||||
account_name: 'Personbilar',
|
||||
account_class: 1,
|
||||
account_group: '12',
|
||||
account_type: 'asset',
|
||||
normal_balance: 'debit',
|
||||
description: '(Fritt konto för Inventarier, verktyg och installationer)',
|
||||
description: 'Personbilar',
|
||||
sru_code: '7202',
|
||||
k2_excluded: false,
|
||||
},
|
||||
{
|
||||
account_number: '1260',
|
||||
account_name: '(Fritt konto för Inventarier, verktyg och installationer)',
|
||||
account_number: '1242',
|
||||
account_name: 'Lastbilar och andra transportmedel',
|
||||
account_class: 1,
|
||||
account_group: '12',
|
||||
account_type: 'asset',
|
||||
normal_balance: 'debit',
|
||||
description: '(Fritt konto för Inventarier, verktyg och installationer)',
|
||||
description: 'Lastbilar och andra transportmedel',
|
||||
sru_code: '7202',
|
||||
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_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' }
|
||||
|
||||
results = [
|
||||
{ data: period, error: null }, // fetch
|
||||
{ data: lockedPeriod, error: null }, // update
|
||||
{ data: period, error: null }, // fetch
|
||||
{ count: 0, data: null, error: null }, // uncategorized tx count check
|
||||
{ data: lockedPeriod, error: null }, // update
|
||||
]
|
||||
|
||||
const handler = vi.fn()
|
||||
|
||||
@@ -33,6 +33,22 @@ export async function lockPeriod(
|
||||
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
|
||||
.from('fiscal_periods')
|
||||
.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 {
|
||||
Camera,
|
||||
Sparkles,
|
||||
Wand,
|
||||
MessageSquare,
|
||||
Bell,
|
||||
Inbox,
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
|
||||
const ICON_MAP: Record<string, LucideIcon> = {
|
||||
Camera,
|
||||
Sparkles,
|
||||
Wand,
|
||||
MessageSquare,
|
||||
Bell,
|
||||
Inbox,
|
||||
|
||||
+306
-102
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user