feat: arcim migration wizard UX, import fixes, Sentry setup (#22)
* 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]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
82ad630448
commit
2ad8731dc9
@@ -5,7 +5,7 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/com
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ArrowLeftRight, FileText, ArrowLeft, Landmark, Loader2 } from 'lucide-react'
|
||||
import { ArrowLeftRight, ArrowRightLeft, FileText, ArrowLeft, Landmark, Loader2 } from 'lucide-react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { BankSelector, type Bank } from '@/extensions/general/enable-banking/components/BankSelector'
|
||||
import { BankConnectionStatus } from '@/extensions/general/enable-banking/components/BankConnectionStatus'
|
||||
@@ -39,6 +39,12 @@ import type {
|
||||
} from '@/lib/import/types'
|
||||
import type { BASAccount } from '@/types'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const MigrationWizard = dynamic(
|
||||
() => import('@/components/extensions/general/ArcimMigrationWorkspace'),
|
||||
{ ssr: false, loading: () => <div className="flex items-center gap-3 text-muted-foreground p-6"><Loader2 className="h-5 w-5 animate-spin" />Laddar migreringsverktyg...</div> }
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// Bank File Import Wizard Steps
|
||||
@@ -730,16 +736,36 @@ function PSD2ConnectWizard() {
|
||||
// Import Page with Selection Cards
|
||||
// ============================================================
|
||||
|
||||
type ImportMode = null | 'psd2' | 'bank' | 'sie'
|
||||
type ImportMode = null | 'psd2' | 'bank' | 'sie' | 'migration'
|
||||
|
||||
export default function ImportPage() {
|
||||
const [mode, setMode] = useState<ImportMode>(null)
|
||||
const [userId, setUserId] = useState('')
|
||||
|
||||
// Fetch authenticated user ID for migration wizard
|
||||
useEffect(() => {
|
||||
const supabase = createClient()
|
||||
supabase.auth.getUser().then(({ data: { user } }) => {
|
||||
if (user) setUserId(user.id)
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Auto-detect OAuth callback from migration extension
|
||||
useEffect(() => {
|
||||
if (new URLSearchParams(window.location.search).get('migration')) {
|
||||
setMode('migration')
|
||||
}
|
||||
}, [])
|
||||
// If extension isn't compiled in, we know synchronously it's unavailable
|
||||
const bankingCompiledIn = ENABLED_EXTENSION_IDS.has('enable-banking')
|
||||
const [hasBankingExtension, setHasBankingExtension] = useState<boolean | null>(
|
||||
bankingCompiledIn ? null : false
|
||||
)
|
||||
|
||||
// Migration extension: show card when compiled in (no DB toggle needed,
|
||||
// since the extensions marketplace is not exposed in the UI)
|
||||
const hasMigrationExtension = ENABLED_EXTENSION_IDS.has('arcim-migration')
|
||||
|
||||
useEffect(() => {
|
||||
if (!bankingCompiledIn) return
|
||||
fetch('/api/extensions/toggles/general/enable-banking')
|
||||
@@ -761,7 +787,7 @@ export default function ImportPage() {
|
||||
</div>
|
||||
|
||||
{mode === null && (
|
||||
<div className={`grid gap-4 ${hasBankingExtension !== false ? 'md:grid-cols-3' : 'md:grid-cols-2'}`}>
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{hasBankingExtension === null && (
|
||||
<Card className="animate-pulse">
|
||||
<CardContent className="pt-6 pb-6 flex flex-col items-center text-center space-y-3">
|
||||
@@ -844,6 +870,31 @@ export default function ImportPage() {
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{hasMigrationExtension === true && (
|
||||
<Card
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="cursor-pointer hover:border-primary/50 active:scale-[0.98] transition-all"
|
||||
onClick={() => setMode('migration')}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setMode('migration') } }}
|
||||
>
|
||||
<CardContent className="pt-6 pb-6 flex flex-col items-center text-center space-y-3">
|
||||
<div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
|
||||
<ArrowRightLeft className="h-6 w-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">Migrera från annat system</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Flytta bokföring, kunder, leverantörer och fakturor från Fortnox, Visma, Bokio, Björn Lundén eller Briox.
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
SIE-data, kunder, leverantörer, fakturor
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -857,6 +908,7 @@ export default function ImportPage() {
|
||||
{mode === 'psd2' && <PSD2ConnectWizard />}
|
||||
{mode === 'bank' && <BankFileImportWizard />}
|
||||
{mode === 'sie' && <SIEImportWizard />}
|
||||
{mode === 'migration' && <MigrationWizard userId={userId} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { redirect } from 'next/navigation'
|
||||
import DashboardNav from '@/components/dashboard/DashboardNav'
|
||||
import { RecaptIdentify } from '@/components/RecaptIdentify'
|
||||
import { SentryIdentify } from '@/components/SentryIdentify'
|
||||
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
|
||||
import type { EntityType } from '@/types'
|
||||
|
||||
@@ -60,6 +61,7 @@ export default async function DashboardLayout({
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
<SentryIdentify userId={user.id} email={user.email} />
|
||||
{!isSandbox && (
|
||||
<RecaptIdentify
|
||||
userId={user.id}
|
||||
|
||||
@@ -81,7 +81,6 @@ export default async function DashboardPage() {
|
||||
const onboardingProgress: OnboardingProgress = {
|
||||
hasCustomers: (customerCount || 0) > 0,
|
||||
hasInvoices: (invoiceCount || 0) > 0,
|
||||
hasReceipts: (receiptCount || 0) > 0,
|
||||
hasBankConnected: (transactionCount || 0) > 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,12 @@ export async function GET(
|
||||
|
||||
/**
|
||||
* DELETE /api/import/sie/[id]
|
||||
* Delete an import record (does not delete created journal entries)
|
||||
* Delete an import record.
|
||||
*
|
||||
* Only failed or pending imports can be deleted. Completed imports have created
|
||||
* journal entries that are part of räkenskapsinformation — deleting the metadata
|
||||
* without reversing entries would leave orphaned bookkeeping data, and deleting
|
||||
* both is prohibited under BFL 7 kap (7-year retention).
|
||||
*/
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
@@ -57,6 +62,24 @@ export async function DELETE(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Check current status before deleting
|
||||
const { data: importRecord } = await supabase
|
||||
.from('sie_imports')
|
||||
.select('status')
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (!importRecord) {
|
||||
return NextResponse.json({ error: 'Import not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (importRecord.status === 'completed') {
|
||||
return NextResponse.json({
|
||||
error: 'Slutförd import kan inte raderas. Importerade verifikationer ingår i räkenskapsinformationen (BFL 7 kap).',
|
||||
}, { status: 403 })
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from('sie_imports')
|
||||
.delete()
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
decodeBuffer,
|
||||
calculateFileHash,
|
||||
} from '@/lib/import/sie-parser'
|
||||
import { suggestMappings, getMappingStats } from '@/lib/import/account-mapper'
|
||||
import { suggestMappings, getMappingStats, isSystemAccount } from '@/lib/import/account-mapper'
|
||||
import { generateImportPreview, checkDuplicateImport } from '@/lib/import/sie-import'
|
||||
import { BAS_REFERENCE } from '@/lib/bookkeeping/bas-data'
|
||||
import type { SIEAccountMappingRecord } from '@/lib/import/types'
|
||||
@@ -78,6 +78,15 @@ export async function POST(request: Request) {
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
// Separate source-system internal accounts (e.g. Fortnox 0099) from
|
||||
// real bookkeeping accounts. System accounts have no BAS equivalent and
|
||||
// should not appear in the mapping step.
|
||||
const excludedSystemAccounts = parsed.accounts
|
||||
.filter((a) => isSystemAccount(a.number))
|
||||
.map((a) => ({ number: a.number, name: a.name }))
|
||||
const bookkeepingAccounts = parsed.accounts
|
||||
.filter((a) => !isSystemAccount(a.number))
|
||||
|
||||
// Fetch stored mappings from database
|
||||
const { data: storedMappings } = await supabase
|
||||
.from('sie_account_mappings')
|
||||
@@ -88,13 +97,15 @@ export async function POST(request: Request) {
|
||||
// the user's active chart (~40 accounts). Accounts that match will be
|
||||
// auto-activated during the execute step.
|
||||
const mappings = suggestMappings(
|
||||
parsed.accounts,
|
||||
bookkeepingAccounts,
|
||||
BAS_REFERENCE,
|
||||
(storedMappings as SIEAccountMappingRecord[]) || undefined
|
||||
)
|
||||
|
||||
// Generate preview
|
||||
const preview = generateImportPreview(parsed, mappings)
|
||||
preview.excludedSystemAccounts = excludedSystemAccounts
|
||||
preview.accountCount = bookkeepingAccounts.length
|
||||
|
||||
// Calculate file hash for storage
|
||||
const fileHash = await calculateFileHash(content)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function GlobalError({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
Sentry.captureException(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<html lang="sv">
|
||||
<body>
|
||||
<div className="flex min-h-screen items-center justify-center p-8">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-xl font-semibold">Något gick fel</h2>
|
||||
<p className="text-muted-foreground">
|
||||
Ett oväntat fel inträffade. Försök igen.
|
||||
</p>
|
||||
<button
|
||||
onClick={reset}
|
||||
className="rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
Försök igen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
|
||||
export default function SentryExamplePage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center p-8">
|
||||
<div className="text-center space-y-4">
|
||||
<h1 className="text-xl font-semibold">Sentry Test</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Click the button to send a test error to Sentry.
|
||||
</p>
|
||||
<button
|
||||
className="rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground hover:bg-primary/90"
|
||||
onClick={() => {
|
||||
Sentry.captureException(
|
||||
new Error("Sentry test error from gnubok")
|
||||
);
|
||||
alert("Test error sent to Sentry!");
|
||||
}}
|
||||
>
|
||||
Throw Test Error
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export function SentryIdentify({
|
||||
userId,
|
||||
email,
|
||||
}: {
|
||||
userId: string;
|
||||
email?: string;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
Sentry.setUser({ id: userId, email });
|
||||
return () => {
|
||||
Sentry.setUser(null);
|
||||
};
|
||||
}, [userId, email]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -252,7 +252,6 @@ export default function DashboardContent({ firstName, settings, summary, onboard
|
||||
hasCustomers={onboardingProgress.hasCustomers}
|
||||
hasInvoices={onboardingProgress.hasInvoices}
|
||||
hasBankConnected={onboardingProgress.hasBankConnected}
|
||||
hasReceipts={onboardingProgress.hasReceipts}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@ import {
|
||||
XCircle,
|
||||
ArrowRight,
|
||||
BarChart3,
|
||||
Info,
|
||||
} from 'lucide-react'
|
||||
import type { ImportPreview, ParseIssue } from '@/lib/import/types'
|
||||
|
||||
@@ -226,6 +227,16 @@ export default function SIEPreviewStep({
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Excluded system accounts info */}
|
||||
{preview.excludedSystemAccounts.length > 0 && (
|
||||
<div className="flex items-start gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>
|
||||
{preview.excludedSystemAccounts.length} internt systemkonto från källsystemet exkluderades ({preview.excludedSystemAccounts.map((a) => a.number).join(', ')}) — inte bokföringskonton
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create missing accounts */}
|
||||
{missingAccounts.length > 0 && (
|
||||
<Card className="border-primary/50">
|
||||
|
||||
@@ -25,7 +25,6 @@ interface NewUserChecklistProps {
|
||||
hasCustomers: boolean
|
||||
hasInvoices: boolean
|
||||
hasBankConnected: boolean
|
||||
hasReceipts: boolean
|
||||
onDismiss?: () => void
|
||||
className?: string
|
||||
}
|
||||
@@ -36,7 +35,6 @@ export default function NewUserChecklist({
|
||||
hasCustomers,
|
||||
hasInvoices,
|
||||
hasBankConnected,
|
||||
hasReceipts,
|
||||
onDismiss,
|
||||
className,
|
||||
}: NewUserChecklistProps) {
|
||||
@@ -78,13 +76,6 @@ export default function NewUserChecklist({
|
||||
href: '/import',
|
||||
completed: hasBankConnected,
|
||||
},
|
||||
{
|
||||
id: 'receipt',
|
||||
label: 'Skanna ditt första kvitto',
|
||||
description: 'Fotografera för automatisk bokföring',
|
||||
href: '/receipts/scan',
|
||||
completed: hasReceipts,
|
||||
},
|
||||
]
|
||||
|
||||
const completedCount = items.filter((item) => item.completed).length
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"$schema":"./extensions.schema.json","extensions":["enable-banking","email"]}
|
||||
{"$schema":"./extensions.schema.json","extensions":["enable-banking","email","arcim-migration"]}
|
||||
|
||||
@@ -23,7 +23,8 @@
|
||||
"invoice-inbox",
|
||||
"calendar",
|
||||
"enable-banking",
|
||||
"email"
|
||||
"email",
|
||||
"arcim-migration"
|
||||
]
|
||||
},
|
||||
"description": "Extension IDs to enable. Each ID must match a manifest.json in the extensions/ directory."
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* HTTP client for the Arcim Sync gateway API.
|
||||
*
|
||||
* Targets the consent-based resource API (/api/v1/consents/...) which
|
||||
* provides typed, normalized access to any Swedish accounting provider.
|
||||
*/
|
||||
|
||||
import type {
|
||||
ArcimProvider,
|
||||
ConsentRecord,
|
||||
OtcResponse,
|
||||
PaginatedResponse,
|
||||
CompanyInformationDto,
|
||||
CustomerDto,
|
||||
SupplierDto,
|
||||
SalesInvoiceDto,
|
||||
SupplierInvoiceDto,
|
||||
} from '../types'
|
||||
|
||||
function getBaseUrl(): string {
|
||||
const url = process.env.ARCIM_SYNC_GATEWAY_URL
|
||||
if (!url) throw new Error('ARCIM_SYNC_GATEWAY_URL is not configured')
|
||||
return url.replace(/\/$/, '')
|
||||
}
|
||||
|
||||
function getApiKey(): string {
|
||||
const key = process.env.ARCIM_SYNC_API_KEY
|
||||
if (!key) throw new Error('ARCIM_SYNC_API_KEY is not configured')
|
||||
return key
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const url = `${getBaseUrl()}${path}`
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${getApiKey()}`,
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => '')
|
||||
throw new Error(`Arcim API ${response.status}: ${body || response.statusText}`)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
// ── Consent lifecycle ───────────────────────────────────────────────
|
||||
|
||||
export async function createConsent(
|
||||
provider: ArcimProvider,
|
||||
name: string,
|
||||
orgNumber?: string,
|
||||
companyName?: string
|
||||
): Promise<ConsentRecord> {
|
||||
return request<ConsentRecord>('/api/v1/consents', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, provider, orgNumber, companyName }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getConsent(consentId: string): Promise<ConsentRecord> {
|
||||
return request<ConsentRecord>(`/api/v1/consents/${consentId}`)
|
||||
}
|
||||
|
||||
export async function generateOtc(
|
||||
consentId: string,
|
||||
expiresInMinutes: number = 60
|
||||
): Promise<OtcResponse> {
|
||||
return request<OtcResponse>(`/api/v1/consents/${consentId}/otc`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ expiresInMinutes }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteConsent(consentId: string): Promise<void> {
|
||||
await request(`/api/v1/consents/${consentId}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
// ── OAuth helpers ───────────────────────────────────────────────────
|
||||
|
||||
export async function getAuthUrl(
|
||||
provider: ArcimProvider,
|
||||
state?: string
|
||||
): Promise<{ url: string }> {
|
||||
const params = new URLSearchParams()
|
||||
if (state) params.set('state', state)
|
||||
const qs = params.toString()
|
||||
return request<{ url: string }>(`/api/v1/auth/${provider}/url${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
|
||||
export async function exchangeAuthToken(
|
||||
consentId: string,
|
||||
provider: ArcimProvider,
|
||||
otcCode: string,
|
||||
oauthCode: string
|
||||
): Promise<{ success: boolean; consentId: string }> {
|
||||
return request(`/api/v1/auth/${provider}/callback`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
code: oauthCode,
|
||||
consentId,
|
||||
otcCode,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// ── Token-based auth (Bokio, Björn Lundén, Briox) ──────────────────
|
||||
|
||||
export async function submitProviderToken(
|
||||
consentId: string,
|
||||
provider: ArcimProvider,
|
||||
apiToken: string,
|
||||
companyId?: string
|
||||
): Promise<{ success: boolean; consentId: string }> {
|
||||
return request(`/api/v1/auth/${provider}/callback`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
code: apiToken,
|
||||
consentId,
|
||||
...(companyId ? { companyId } : {}),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// ── Resource fetching (paginated) ───────────────────────────────────
|
||||
|
||||
async function fetchAllPages<T>(
|
||||
consentId: string,
|
||||
resource: string,
|
||||
params?: Record<string, string>,
|
||||
pageSize: number = 100
|
||||
): Promise<T[]> {
|
||||
const all: T[] = []
|
||||
let page = 1
|
||||
|
||||
while (true) {
|
||||
const query = new URLSearchParams({
|
||||
page: String(page),
|
||||
pageSize: String(pageSize),
|
||||
...params,
|
||||
})
|
||||
const result = await request<PaginatedResponse<T>>(
|
||||
`/api/v1/consents/${consentId}/${resource}?${query}`
|
||||
)
|
||||
all.push(...result.data)
|
||||
|
||||
if (!result.hasMore || result.data.length === 0) break
|
||||
page++
|
||||
}
|
||||
|
||||
return all
|
||||
}
|
||||
|
||||
// ── Typed resource accessors ────────────────────────────────────────
|
||||
|
||||
export async function fetchCompanyInfo(
|
||||
consentId: string
|
||||
): Promise<CompanyInformationDto | null> {
|
||||
// CompanyInformation is a singleton resource — gateway returns { data: object }
|
||||
const result = await request<{ data: CompanyInformationDto }>(
|
||||
`/api/v1/consents/${consentId}/companyinformation`
|
||||
)
|
||||
return result.data ?? null
|
||||
}
|
||||
|
||||
export async function fetchCustomers(consentId: string): Promise<CustomerDto[]> {
|
||||
return fetchAllPages<CustomerDto>(consentId, 'customers')
|
||||
}
|
||||
|
||||
export async function fetchSuppliers(consentId: string): Promise<SupplierDto[]> {
|
||||
return fetchAllPages<SupplierDto>(consentId, 'suppliers')
|
||||
}
|
||||
|
||||
export async function fetchSalesInvoices(
|
||||
consentId: string,
|
||||
params?: Record<string, string>
|
||||
): Promise<SalesInvoiceDto[]> {
|
||||
return fetchAllPages<SalesInvoiceDto>(consentId, 'salesinvoices', params)
|
||||
}
|
||||
|
||||
export async function fetchSupplierInvoices(
|
||||
consentId: string,
|
||||
params?: Record<string, string>
|
||||
): Promise<SupplierInvoiceDto[]> {
|
||||
return fetchAllPages<SupplierInvoiceDto>(consentId, 'supplierinvoices', params)
|
||||
}
|
||||
|
||||
// ── SIE export ────────────────────────────────────────────────────
|
||||
|
||||
export interface SIEExportFile {
|
||||
fiscalYear: number
|
||||
sieType: number
|
||||
rawContent: string
|
||||
accountCount: number
|
||||
transactionCount: number
|
||||
}
|
||||
|
||||
export async function fetchSIEExport(
|
||||
consentId: string,
|
||||
sieType?: number
|
||||
): Promise<{ files: SIEExportFile[] }> {
|
||||
const params = new URLSearchParams()
|
||||
if (sieType) params.set('sieType', String(sieType))
|
||||
const qs = params.toString()
|
||||
return request<{ files: SIEExportFile[] }>(
|
||||
`/api/v1/consents/${consentId}/sie/export${qs ? `?${qs}` : ''}`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
/**
|
||||
* Maps Arcim Sync canonical DTOs to gnubok internal types.
|
||||
*
|
||||
* These mappers transform the normalized data from any Swedish accounting
|
||||
* provider into the exact shapes gnubok expects for database insertion.
|
||||
*/
|
||||
|
||||
import type { CustomerType, SupplierType, VatTreatment } from '@/types'
|
||||
import type {
|
||||
CustomerDto,
|
||||
SupplierDto,
|
||||
SalesInvoiceDto,
|
||||
SalesInvoiceLineDto,
|
||||
SupplierInvoiceDto,
|
||||
SupplierInvoiceLineDto,
|
||||
CompanyInformationDto,
|
||||
PostalAddress,
|
||||
PartyDto,
|
||||
} from '../types'
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
function round2(n: number): number {
|
||||
return Math.round(n * 100) / 100
|
||||
}
|
||||
|
||||
function formatAddress(addr?: PostalAddress): {
|
||||
address_line1: string | null
|
||||
address_line2: string | null
|
||||
postal_code: string | null
|
||||
city: string | null
|
||||
country: string | null
|
||||
} {
|
||||
if (!addr) {
|
||||
return { address_line1: null, address_line2: null, postal_code: null, city: null, country: null }
|
||||
}
|
||||
const line1 = [addr.streetName, addr.buildingNumber].filter(Boolean).join(' ') || null
|
||||
return {
|
||||
address_line1: line1,
|
||||
address_line2: addr.additionalStreetName || null,
|
||||
postal_code: addr.postalZone || null,
|
||||
city: addr.cityName || null,
|
||||
country: addr.countryCode || null,
|
||||
}
|
||||
}
|
||||
|
||||
function getOrgNumber(party: PartyDto): string | null {
|
||||
// Look for SE:ORGNR scheme first, then companyId in legalEntity
|
||||
const seOrg = party.identifications?.find(i => i.schemeId === 'SE:ORGNR')
|
||||
if (seOrg) return seOrg.id
|
||||
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']
|
||||
|
||||
function inferTypeFromVatOrCountry(
|
||||
vatNumber: string | undefined,
|
||||
countryCode: string | undefined
|
||||
): 'swedish_business' | 'eu_business' | 'non_eu_business' {
|
||||
// 1. VAT number prefix is the strongest signal
|
||||
if (vatNumber) {
|
||||
const prefix = vatNumber.substring(0, 2).toUpperCase()
|
||||
if (prefix === 'SE') return 'swedish_business'
|
||||
if (EU_COUNTRIES.includes(prefix)) return 'eu_business'
|
||||
return 'non_eu_business'
|
||||
}
|
||||
|
||||
// 2. Fall back to address country
|
||||
const country = countryCode?.toUpperCase()
|
||||
if (!country || country === 'SE') return 'swedish_business'
|
||||
if (EU_COUNTRIES.includes(country)) return 'eu_business'
|
||||
return 'non_eu_business'
|
||||
}
|
||||
|
||||
function inferCustomerType(dto: CustomerDto): CustomerType {
|
||||
if (dto.type === 'private') return 'individual'
|
||||
return inferTypeFromVatOrCountry(dto.vatNumber, dto.party.postalAddress?.countryCode)
|
||||
}
|
||||
|
||||
function inferSupplierType(dto: SupplierDto): SupplierType {
|
||||
return inferTypeFromVatOrCountry(dto.vatNumber, dto.party.postalAddress?.countryCode)
|
||||
}
|
||||
|
||||
function inferVatTreatment(taxPercent?: number, currencyCode?: string): VatTreatment {
|
||||
if (taxPercent === 25) return 'standard_25'
|
||||
if (taxPercent === 12) return 'reduced_12'
|
||||
if (taxPercent === 6) return 'reduced_6'
|
||||
if (taxPercent === 0 && currencyCode && currencyCode !== 'SEK') return 'export'
|
||||
return 'standard_25'
|
||||
}
|
||||
|
||||
function inferVatRate(taxPercent?: number): number {
|
||||
if (taxPercent === 25 || taxPercent === 12 || taxPercent === 6) return taxPercent
|
||||
if (taxPercent === 0) return 0
|
||||
return 25 // Default to standard rate
|
||||
}
|
||||
|
||||
// ── Public mappers ──────────────────────────────────────────────────
|
||||
|
||||
export function mapCustomer(dto: CustomerDto, userId: string): Record<string, unknown> {
|
||||
const addr = formatAddress(dto.party.postalAddress)
|
||||
return {
|
||||
user_id: userId,
|
||||
name: dto.party.name,
|
||||
customer_type: inferCustomerType(dto),
|
||||
email: dto.party.contact?.email || null,
|
||||
phone: dto.party.contact?.telephone || null,
|
||||
...addr,
|
||||
org_number: getOrgNumber(dto.party),
|
||||
vat_number: dto.vatNumber || null,
|
||||
vat_number_validated: false,
|
||||
default_payment_terms: dto.defaultPaymentTermsDays || 30,
|
||||
notes: dto.note || null,
|
||||
}
|
||||
}
|
||||
|
||||
export function mapSupplier(dto: SupplierDto, userId: string): Record<string, unknown> {
|
||||
const addr = formatAddress(dto.party.postalAddress)
|
||||
return {
|
||||
user_id: userId,
|
||||
name: dto.party.name,
|
||||
supplier_type: inferSupplierType(dto),
|
||||
email: dto.party.contact?.email || null,
|
||||
phone: dto.party.contact?.telephone || null,
|
||||
...addr,
|
||||
org_number: getOrgNumber(dto.party),
|
||||
vat_number: dto.vatNumber || null,
|
||||
bankgiro: dto.bankGiro || null,
|
||||
plusgiro: dto.plusGiro || null,
|
||||
bank_account: dto.bankAccount || null,
|
||||
iban: null,
|
||||
bic: null,
|
||||
default_expense_account: null,
|
||||
default_payment_terms: dto.defaultPaymentTermsDays || 30,
|
||||
default_currency: 'SEK',
|
||||
notes: dto.note || null,
|
||||
}
|
||||
}
|
||||
|
||||
export function mapSalesInvoice(
|
||||
dto: SalesInvoiceDto,
|
||||
userId: string,
|
||||
customerId: string
|
||||
): { invoice: Record<string, unknown>; items: Record<string, unknown>[] } {
|
||||
const subtotal = round2(dto.legalMonetaryTotal.lineExtensionAmount.value)
|
||||
const total = round2(dto.legalMonetaryTotal.payableAmount.value)
|
||||
const vatAmount = round2(dto.taxTotal?.taxAmount.value ?? (total - subtotal))
|
||||
|
||||
// Determine primary VAT treatment from first line with tax
|
||||
const primaryTaxPercent = dto.lines.find(l => l.taxPercent != null)?.taxPercent
|
||||
const vatTreatment = inferVatTreatment(primaryTaxPercent, dto.currencyCode)
|
||||
|
||||
// Map Arcim status to gnubok status
|
||||
const statusMap: Record<string, string> = {
|
||||
draft: 'draft',
|
||||
sent: 'sent',
|
||||
booked: 'sent', // gnubok has no 'booked' status — treat as sent
|
||||
paid: 'paid',
|
||||
overdue: 'overdue',
|
||||
cancelled: 'cancelled',
|
||||
credited: 'credited',
|
||||
}
|
||||
|
||||
const isCreditNote = dto.invoiceTypeCode === '381'
|
||||
|
||||
const invoice: Record<string, unknown> = {
|
||||
user_id: userId,
|
||||
customer_id: customerId,
|
||||
invoice_number: dto.invoiceNumber,
|
||||
invoice_date: dto.issueDate,
|
||||
due_date: dto.dueDate || dto.issueDate,
|
||||
status: statusMap[dto.status] || 'sent',
|
||||
currency: dto.currencyCode || 'SEK',
|
||||
exchange_rate: dto.currencyCode === 'SEK' ? null : null,
|
||||
subtotal,
|
||||
subtotal_sek: dto.currencyCode === 'SEK' ? subtotal : null,
|
||||
vat_amount: vatAmount,
|
||||
vat_amount_sek: dto.currencyCode === 'SEK' ? vatAmount : null,
|
||||
total,
|
||||
total_sek: dto.currencyCode === 'SEK' ? total : null,
|
||||
vat_treatment: vatTreatment,
|
||||
vat_rate: inferVatRate(primaryTaxPercent),
|
||||
your_reference: null,
|
||||
our_reference: null,
|
||||
notes: dto.note || null,
|
||||
document_type: isCreditNote ? 'invoice' : 'invoice',
|
||||
paid_at: dto.paymentStatus.paid ? dto.paymentStatus.lastPaymentDate || dto.issueDate : null,
|
||||
paid_amount: dto.paymentStatus.paid ? total : round2(total - dto.paymentStatus.balance.value),
|
||||
}
|
||||
|
||||
const items = dto.lines.map((line, idx) => mapSalesInvoiceLine(line, idx))
|
||||
|
||||
return { invoice, items }
|
||||
}
|
||||
|
||||
function mapSalesInvoiceLine(line: SalesInvoiceLineDto, index: number): Record<string, unknown> {
|
||||
return {
|
||||
sort_order: index + 1,
|
||||
description: line.description || line.itemName || '',
|
||||
quantity: line.quantity || 1,
|
||||
unit: line.unitCode || 'st',
|
||||
unit_price: round2(line.unitPrice?.value ?? line.lineExtensionAmount.value),
|
||||
line_total: round2(line.lineExtensionAmount.value),
|
||||
vat_rate: inferVatRate(line.taxPercent),
|
||||
vat_amount: round2(line.taxAmount?.value ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
export function mapSupplierInvoice(
|
||||
dto: SupplierInvoiceDto,
|
||||
userId: string,
|
||||
supplierId: string
|
||||
): { invoice: Record<string, unknown>; items: Record<string, unknown>[] } {
|
||||
const subtotal = round2(dto.legalMonetaryTotal.lineExtensionAmount.value)
|
||||
const total = round2(dto.legalMonetaryTotal.payableAmount.value)
|
||||
const vatAmount = round2(dto.taxTotal?.taxAmount.value ?? (total - subtotal))
|
||||
|
||||
const primaryTaxPercent = dto.lines.find(l => l.taxPercent != null)?.taxPercent
|
||||
const vatTreatment = inferVatTreatment(primaryTaxPercent, dto.currencyCode)
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
draft: 'registered',
|
||||
sent: 'registered',
|
||||
booked: 'registered',
|
||||
paid: 'paid',
|
||||
overdue: 'overdue',
|
||||
cancelled: 'credited',
|
||||
credited: 'credited',
|
||||
}
|
||||
|
||||
const isCreditNote = dto.invoiceTypeCode === '381'
|
||||
|
||||
const invoice: Record<string, unknown> = {
|
||||
user_id: userId,
|
||||
supplier_id: supplierId,
|
||||
supplier_invoice_number: dto.invoiceNumber,
|
||||
invoice_date: dto.issueDate,
|
||||
due_date: dto.dueDate || dto.issueDate,
|
||||
received_date: dto.issueDate,
|
||||
delivery_date: dto.deliveryDate || null,
|
||||
status: statusMap[dto.status] || 'registered',
|
||||
currency: dto.currencyCode || 'SEK',
|
||||
exchange_rate: dto.currencyCode === 'SEK' ? null : null,
|
||||
subtotal,
|
||||
subtotal_sek: dto.currencyCode === 'SEK' ? subtotal : null,
|
||||
vat_amount: vatAmount,
|
||||
vat_amount_sek: dto.currencyCode === 'SEK' ? vatAmount : null,
|
||||
total,
|
||||
total_sek: dto.currencyCode === 'SEK' ? total : null,
|
||||
vat_treatment: vatTreatment,
|
||||
reverse_charge: vatTreatment === 'reverse_charge',
|
||||
payment_reference: dto.ocrNumber || null,
|
||||
paid_at: dto.paymentStatus.paid ? dto.paymentStatus.lastPaymentDate || dto.issueDate : null,
|
||||
paid_amount: dto.paymentStatus.paid ? total : round2(total - dto.paymentStatus.balance.value),
|
||||
remaining_amount: round2(dto.paymentStatus.balance.value),
|
||||
is_credit_note: isCreditNote,
|
||||
notes: dto.note || null,
|
||||
}
|
||||
|
||||
const items = dto.lines.map((line, idx) => mapSupplierInvoiceLine(line, idx))
|
||||
|
||||
return { invoice, items }
|
||||
}
|
||||
|
||||
function mapSupplierInvoiceLine(line: SupplierInvoiceLineDto, index: number): Record<string, unknown> {
|
||||
return {
|
||||
sort_order: index + 1,
|
||||
description: line.description || line.itemName || '',
|
||||
quantity: line.quantity || 1,
|
||||
unit: line.unitCode || 'st',
|
||||
unit_price: round2(line.unitPrice?.value ?? line.lineExtensionAmount.value),
|
||||
line_total: round2(line.lineExtensionAmount.value),
|
||||
account_number: line.accountNumber || '4000', // Default to purchases
|
||||
vat_rate: inferVatRate(line.taxPercent),
|
||||
vat_amount: round2(line.taxAmount?.value ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
export function mapCompanyInfo(dto: CompanyInformationDto): {
|
||||
company_name: string | null
|
||||
org_number: string | null
|
||||
vat_number: string | null
|
||||
fiscal_year_start_month: number
|
||||
address_line1: string | null
|
||||
postal_code: string | null
|
||||
city: string | null
|
||||
phone: string | null
|
||||
email: string | null
|
||||
} {
|
||||
const addr = formatAddress(dto.address)
|
||||
// Parse fiscal year start month from "MM-DD" format
|
||||
let fiscalYearStartMonth = 1
|
||||
if (dto.fiscalYearStart) {
|
||||
const month = parseInt(dto.fiscalYearStart.split('-')[0], 10)
|
||||
if (month >= 1 && month <= 12) fiscalYearStartMonth = month
|
||||
}
|
||||
|
||||
return {
|
||||
company_name: dto.companyName || null,
|
||||
org_number: dto.organizationNumber || null,
|
||||
vat_number: dto.vatNumber || null,
|
||||
fiscal_year_start_month: fiscalYearStartMonth,
|
||||
address_line1: addr.address_line1,
|
||||
postal_code: addr.postal_code,
|
||||
city: addr.city,
|
||||
phone: dto.contact?.telephone || null,
|
||||
email: dto.contact?.email || null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
/**
|
||||
* Migration orchestrator — coordinates the data migration from
|
||||
* an external accounting system via Arcim Sync into gnubok.
|
||||
*
|
||||
* Bookkeeping data (accounts, balances, vouchers) is now imported
|
||||
* via SIE files through the core SIE import engine. This orchestrator
|
||||
* handles only entity-level imports:
|
||||
* 1. Company info → pre-fill company_settings
|
||||
* 2. Customers → needed before sales invoices
|
||||
* 3. Suppliers → needed before supplier invoices
|
||||
* 4. Sales invoices (open only)
|
||||
* 5. Supplier invoices (open only)
|
||||
*/
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { MigrationProgress, MigrationResults } from '../types'
|
||||
import {
|
||||
fetchCompanyInfo,
|
||||
fetchCustomers,
|
||||
fetchSuppliers,
|
||||
fetchSalesInvoices,
|
||||
fetchSupplierInvoices,
|
||||
} from './arcim-client'
|
||||
import {
|
||||
mapCustomer,
|
||||
mapSupplier,
|
||||
mapSalesInvoice,
|
||||
mapSupplierInvoice,
|
||||
mapCompanyInfo,
|
||||
} from './entity-mapper'
|
||||
|
||||
export interface MigrationOptions {
|
||||
consentId: string
|
||||
userId: string
|
||||
supabase: SupabaseClient
|
||||
importCompanyInfo?: boolean
|
||||
importCustomers?: boolean
|
||||
importSuppliers?: boolean
|
||||
importSalesInvoices?: boolean
|
||||
importSupplierInvoices?: boolean
|
||||
onProgress?: (progress: MigrationProgress) => void
|
||||
}
|
||||
|
||||
function emitProgress(options: MigrationOptions, progress: MigrationProgress) {
|
||||
options.onProgress?.(progress)
|
||||
}
|
||||
|
||||
// ── Main orchestrator ─────────────────────────────────────────────
|
||||
|
||||
export async function executeMigration(options: MigrationOptions): Promise<MigrationResults> {
|
||||
const { consentId, userId, supabase } = options
|
||||
const results: MigrationResults = {}
|
||||
|
||||
try {
|
||||
// ── Step 1: Company information ───────────────────────────────
|
||||
if (options.importCompanyInfo !== false) {
|
||||
emitProgress(options, { status: 'fetching', currentStep: 'Hämtar företagsinformation...', progress: 5 })
|
||||
try {
|
||||
const companyInfo = await fetchCompanyInfo(consentId)
|
||||
if (companyInfo) {
|
||||
const mapped = mapCompanyInfo(companyInfo)
|
||||
const { data: existing } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name, org_number, vat_number')
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
|
||||
const updates: Record<string, unknown> = {}
|
||||
if (!existing?.company_name && mapped.company_name) updates.company_name = mapped.company_name
|
||||
if (!existing?.org_number && mapped.org_number) updates.org_number = mapped.org_number
|
||||
if (!existing?.vat_number && mapped.vat_number) {
|
||||
updates.vat_number = mapped.vat_number
|
||||
updates.vat_registered = true
|
||||
}
|
||||
if (mapped.fiscal_year_start_month !== 1) {
|
||||
updates.fiscal_year_start_month = mapped.fiscal_year_start_month
|
||||
}
|
||||
if (mapped.address_line1) updates.address_line1 = mapped.address_line1
|
||||
if (mapped.postal_code) updates.postal_code = mapped.postal_code
|
||||
if (mapped.city) updates.city = mapped.city
|
||||
if (mapped.phone) updates.phone = mapped.phone
|
||||
if (mapped.email) updates.email = mapped.email
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await supabase.from('company_settings').update(updates).eq('user_id', userId)
|
||||
}
|
||||
results.companyInfo = { imported: true }
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to import company info:', err)
|
||||
results.companyInfo = { imported: false }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Step 2: Customers ─────────────────────────────────────────
|
||||
const customerIdMap = new Map<string, string>()
|
||||
|
||||
if (options.importCustomers !== false) {
|
||||
emitProgress(options, { status: 'importing', currentStep: 'Importerar kunder...', progress: 20 })
|
||||
try {
|
||||
const customers = await fetchCustomers(consentId)
|
||||
let imported = 0
|
||||
let skipped = 0
|
||||
|
||||
for (const customer of customers) {
|
||||
if (!customer.active) {
|
||||
console.log(`[migration] Customer skipped (inactive): ${customer.party.name}`)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const orgNumber = customer.party.legalEntity?.companyId ||
|
||||
customer.party.identifications?.find(i => i.schemeId === 'SE:ORGNR')?.id
|
||||
if (orgNumber) {
|
||||
const { data: existing } = await supabase
|
||||
.from('customers')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('org_number', orgNumber)
|
||||
.limit(1)
|
||||
|
||||
if (existing && existing.length > 0) {
|
||||
console.log(`[migration] Customer skipped (duplicate org_number ${orgNumber}): ${customer.party.name}`)
|
||||
customerIdMap.set(customer.id, existing[0].id)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const mapped = mapCustomer(customer, userId)
|
||||
const { data: inserted, error } = await supabase
|
||||
.from('customers')
|
||||
.insert(mapped)
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (error || !inserted) {
|
||||
console.error(`[migration] Customer insert failed: ${customer.party.name}`, error?.message)
|
||||
skipped++
|
||||
} else {
|
||||
customerIdMap.set(customer.id, inserted.id)
|
||||
imported++
|
||||
}
|
||||
}
|
||||
|
||||
results.customers = { total: customers.length, imported, skipped }
|
||||
} catch (err) {
|
||||
console.error('Failed to import customers:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Step 3: Suppliers ─────────────────────────────────────────
|
||||
const supplierIdMap = new Map<string, string>()
|
||||
|
||||
if (options.importSuppliers !== false) {
|
||||
emitProgress(options, { status: 'importing', currentStep: 'Importerar leverantörer...', progress: 40 })
|
||||
try {
|
||||
const suppliers = await fetchSuppliers(consentId)
|
||||
let imported = 0
|
||||
let skipped = 0
|
||||
|
||||
for (const supplier of suppliers) {
|
||||
if (!supplier.active) {
|
||||
console.log(`[migration] Supplier skipped (inactive): ${supplier.party.name}`)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const orgNumber = supplier.party.legalEntity?.companyId ||
|
||||
supplier.party.identifications?.find(i => i.schemeId === 'SE:ORGNR')?.id
|
||||
if (orgNumber) {
|
||||
const { data: existing } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('org_number', orgNumber)
|
||||
.limit(1)
|
||||
|
||||
if (existing && existing.length > 0) {
|
||||
console.log(`[migration] Supplier skipped (duplicate org_number ${orgNumber}): ${supplier.party.name}`)
|
||||
supplierIdMap.set(supplier.id, existing[0].id)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const mapped = mapSupplier(supplier, userId)
|
||||
const { data: inserted, error } = await supabase
|
||||
.from('suppliers')
|
||||
.insert(mapped)
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (error || !inserted) {
|
||||
console.error(`[migration] Supplier insert failed: ${supplier.party.name}`, error?.message)
|
||||
skipped++
|
||||
} else {
|
||||
supplierIdMap.set(supplier.id, inserted.id)
|
||||
imported++
|
||||
}
|
||||
}
|
||||
|
||||
results.suppliers = { total: suppliers.length, imported, skipped }
|
||||
} catch (err) {
|
||||
console.error('Failed to import suppliers:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Step 4: Sales invoices (open/unpaid only) ─────────────────
|
||||
if (options.importSalesInvoices !== false) {
|
||||
emitProgress(options, { status: 'importing', currentStep: 'Importerar kundfakturor...', progress: 60 })
|
||||
try {
|
||||
const invoices = await fetchSalesInvoices(consentId)
|
||||
const openInvoices = invoices.filter(i =>
|
||||
i.status === 'sent' || i.status === 'overdue' || i.status === 'booked'
|
||||
)
|
||||
console.log(`[migration] Sales invoices: ${invoices.length} total, ${openInvoices.length} open (filtered by status: sent/overdue/booked)`)
|
||||
|
||||
let imported = 0
|
||||
let skipped = 0
|
||||
|
||||
for (const inv of openInvoices) {
|
||||
const customerOrgNumber = inv.customer.legalEntity?.companyId ||
|
||||
inv.customer.identifications?.find(i => i.schemeId === 'SE:ORGNR')?.id
|
||||
|
||||
let customerId: string | null = null
|
||||
|
||||
if (customerOrgNumber) {
|
||||
const { data: match } = await supabase
|
||||
.from('customers')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('org_number', customerOrgNumber)
|
||||
.limit(1)
|
||||
if (match?.[0]) customerId = match[0].id
|
||||
}
|
||||
|
||||
if (!customerId) {
|
||||
const { data: match } = await supabase
|
||||
.from('customers')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('name', inv.customer.name)
|
||||
.limit(1)
|
||||
if (match?.[0]) customerId = match[0].id
|
||||
}
|
||||
|
||||
if (!customerId) {
|
||||
const minimalCustomer = {
|
||||
user_id: userId,
|
||||
name: inv.customer.name,
|
||||
customer_type: 'swedish_business',
|
||||
default_payment_terms: 30,
|
||||
country: 'SE',
|
||||
vat_number_validated: false,
|
||||
}
|
||||
const { data: created, error: custErr } = await supabase
|
||||
.from('customers')
|
||||
.insert(minimalCustomer)
|
||||
.select('id')
|
||||
.single()
|
||||
if (created) {
|
||||
customerId = created.id
|
||||
} else {
|
||||
console.error(`[migration] Sales invoice ${inv.invoiceNumber} skipped — could not create customer "${inv.customer.name}":`, custErr?.message)
|
||||
}
|
||||
}
|
||||
|
||||
if (!customerId) {
|
||||
console.log(`[migration] Sales invoice ${inv.invoiceNumber} skipped — no customer match for "${inv.customer.name}" (org: ${customerOrgNumber || 'n/a'})`)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const { data: existingInv } = await supabase
|
||||
.from('invoices')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('invoice_number', inv.invoiceNumber)
|
||||
.limit(1)
|
||||
|
||||
if (existingInv && existingInv.length > 0) {
|
||||
console.log(`[migration] Sales invoice ${inv.invoiceNumber} skipped — already exists`)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const { invoice: mappedInvoice, items: mappedItems } = mapSalesInvoice(inv, userId, customerId)
|
||||
|
||||
const { data: insertedInv, error: invError } = await supabase
|
||||
.from('invoices')
|
||||
.insert(mappedInvoice)
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (invError || !insertedInv) {
|
||||
console.error(`[migration] Sales invoice ${inv.invoiceNumber} insert failed:`, invError?.message)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
if (mappedItems.length > 0) {
|
||||
const itemsWithInvoiceId = mappedItems.map(item => ({
|
||||
...item,
|
||||
invoice_id: insertedInv.id,
|
||||
}))
|
||||
await supabase.from('invoice_items').insert(itemsWithInvoiceId)
|
||||
}
|
||||
|
||||
imported++
|
||||
}
|
||||
|
||||
results.salesInvoices = { total: openInvoices.length, imported, skipped }
|
||||
} catch (err) {
|
||||
console.error('Failed to import sales invoices:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Step 5: Supplier invoices (open/unpaid only) ──────────────
|
||||
if (options.importSupplierInvoices !== false) {
|
||||
emitProgress(options, { status: 'importing', currentStep: 'Importerar leverantörsfakturor...', progress: 80 })
|
||||
try {
|
||||
const invoices = await fetchSupplierInvoices(consentId)
|
||||
const openInvoices = invoices.filter(i =>
|
||||
i.status === 'sent' || i.status === 'overdue' || i.status === 'booked' || i.status === 'draft'
|
||||
)
|
||||
console.log(`[migration] Supplier invoices: ${invoices.length} total, ${openInvoices.length} open (filtered by status: sent/overdue/booked/draft)`)
|
||||
|
||||
let imported = 0
|
||||
let skipped = 0
|
||||
|
||||
for (const inv of openInvoices) {
|
||||
const supplierOrgNumber = inv.supplier.legalEntity?.companyId ||
|
||||
inv.supplier.identifications?.find(i => i.schemeId === 'SE:ORGNR')?.id
|
||||
|
||||
let supplierId: string | null = null
|
||||
|
||||
if (supplierOrgNumber) {
|
||||
const { data: match } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('org_number', supplierOrgNumber)
|
||||
.limit(1)
|
||||
if (match?.[0]) supplierId = match[0].id
|
||||
}
|
||||
|
||||
if (!supplierId) {
|
||||
const { data: match } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('name', inv.supplier.name)
|
||||
.limit(1)
|
||||
if (match?.[0]) supplierId = match[0].id
|
||||
}
|
||||
|
||||
if (!supplierId) {
|
||||
const minimalSupplier = {
|
||||
user_id: userId,
|
||||
name: inv.supplier.name,
|
||||
supplier_type: 'swedish_business',
|
||||
default_payment_terms: 30,
|
||||
default_currency: 'SEK',
|
||||
country: 'SE',
|
||||
}
|
||||
const { data: created, error: supErr } = await supabase
|
||||
.from('suppliers')
|
||||
.insert(minimalSupplier)
|
||||
.select('id')
|
||||
.single()
|
||||
if (created) {
|
||||
supplierId = created.id
|
||||
} else {
|
||||
console.error(`[migration] Supplier invoice ${inv.invoiceNumber} skipped — could not create supplier "${inv.supplier.name}":`, supErr?.message)
|
||||
}
|
||||
}
|
||||
|
||||
if (!supplierId) {
|
||||
console.log(`[migration] Supplier invoice ${inv.invoiceNumber} skipped — no supplier match for "${inv.supplier.name}" (org: ${supplierOrgNumber || 'n/a'})`)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const { data: existingInv } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select('id')
|
||||
.eq('user_id', userId)
|
||||
.eq('supplier_invoice_number', inv.invoiceNumber)
|
||||
.eq('supplier_id', supplierId)
|
||||
.limit(1)
|
||||
|
||||
if (existingInv && existingInv.length > 0) {
|
||||
console.log(`[migration] Supplier invoice ${inv.invoiceNumber} skipped — already exists for supplier "${inv.supplier.name}"`)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const { invoice: mappedInvoice, items: mappedItems } = mapSupplierInvoice(inv, userId, supplierId)
|
||||
|
||||
// Get next arrival number (ankomstnummer) — required NOT NULL column
|
||||
const { data: arrivalNum, error: arrivalError } = await supabase
|
||||
.rpc('get_next_arrival_number', { p_user_id: userId })
|
||||
|
||||
if (arrivalError || arrivalNum == null) {
|
||||
console.error(`[migration] Supplier invoice ${inv.invoiceNumber} skipped — could not get arrival number:`, arrivalError?.message)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
mappedInvoice.arrival_number = arrivalNum
|
||||
|
||||
const { data: insertedInv, error: invError } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.insert(mappedInvoice)
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (invError || !insertedInv) {
|
||||
console.error(`[migration] Supplier invoice ${inv.invoiceNumber} insert failed for "${inv.supplier.name}":`, invError?.message, JSON.stringify(mappedInvoice, null, 2))
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
if (mappedItems.length > 0) {
|
||||
const itemsWithInvoiceId = mappedItems.map(item => ({
|
||||
...item,
|
||||
supplier_invoice_id: insertedInv.id,
|
||||
}))
|
||||
await supabase.from('supplier_invoice_items').insert(itemsWithInvoiceId)
|
||||
}
|
||||
|
||||
imported++
|
||||
}
|
||||
|
||||
results.supplierInvoices = { total: openInvoices.length, imported, skipped }
|
||||
} catch (err) {
|
||||
console.error('Failed to import supplier invoices:', err)
|
||||
}
|
||||
}
|
||||
|
||||
emitProgress(options, { status: 'completed', progress: 100, results })
|
||||
return results
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Migration failed'
|
||||
emitProgress(options, { status: 'failed', progress: 0, error: message })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"id": "arcim-migration",
|
||||
"sector": "general",
|
||||
"exportName": "arcimMigrationExtension",
|
||||
"entryPoint": "@/extensions/general/arcim-migration",
|
||||
"workspace": "@/components/extensions/general/ArcimMigrationWorkspace",
|
||||
"requiredEnvVars": ["ARCIM_SYNC_GATEWAY_URL", "ARCIM_SYNC_API_KEY"],
|
||||
"optionalEnvVars": [],
|
||||
"npmDependencies": [],
|
||||
"definition": {
|
||||
"name": "Systemmigration (Arcim Sync)",
|
||||
"category": "import",
|
||||
"icon": "ArrowRightLeft",
|
||||
"dataPattern": "manual",
|
||||
"hasOwnData": false,
|
||||
"description": "Migrera bokföring från Fortnox, Visma, Bokio, Björn Lundén eller Briox",
|
||||
"longDescription": "Flytta all bokföringsdata från ditt gamla system till gnubok. Importerar kontoplan, verifikationer, kunder, leverantörer och öppna fakturor automatiskt via säker API-integration."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Types for the Arcim Sync migration extension.
|
||||
*
|
||||
* These mirror the canonical DTOs from the Arcim Sync gateway
|
||||
* (packages/core/src/types/dto/) so we don't take a runtime dependency.
|
||||
*/
|
||||
|
||||
// ── Arcim Sync canonical DTOs (subset we consume) ──────────────────
|
||||
|
||||
export interface AmountType {
|
||||
value: number
|
||||
currencyCode: string
|
||||
}
|
||||
|
||||
export interface PostalAddress {
|
||||
streetName?: string
|
||||
additionalStreetName?: string
|
||||
buildingNumber?: string
|
||||
cityName?: string
|
||||
postalZone?: string
|
||||
countrySubentity?: string
|
||||
countryCode?: string
|
||||
}
|
||||
|
||||
export interface Contact {
|
||||
name?: string
|
||||
telephone?: string
|
||||
email?: string
|
||||
website?: string
|
||||
}
|
||||
|
||||
export interface PartyIdentification {
|
||||
id: string
|
||||
schemeId?: string
|
||||
}
|
||||
|
||||
export interface PartyLegalEntity {
|
||||
registrationName: string
|
||||
companyId?: string
|
||||
companyIdSchemeId?: string
|
||||
}
|
||||
|
||||
export interface PartyDto {
|
||||
name: string
|
||||
identifications: PartyIdentification[]
|
||||
postalAddress?: PostalAddress
|
||||
legalEntity?: PartyLegalEntity
|
||||
contact?: Contact
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
page: number
|
||||
pageSize: number
|
||||
totalCount: number
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export interface TaxSubtotalDto {
|
||||
taxableAmount: AmountType
|
||||
taxAmount: AmountType
|
||||
taxCategory?: string
|
||||
percent?: number
|
||||
}
|
||||
|
||||
export interface TaxTotalDto {
|
||||
taxAmount: AmountType
|
||||
taxSubtotals?: TaxSubtotalDto[]
|
||||
}
|
||||
|
||||
export interface LegalMonetaryTotalDto {
|
||||
lineExtensionAmount: AmountType
|
||||
taxExclusiveAmount?: AmountType
|
||||
taxInclusiveAmount?: AmountType
|
||||
payableAmount: AmountType
|
||||
}
|
||||
|
||||
export interface PaymentStatusDto {
|
||||
paid: boolean
|
||||
balance: AmountType
|
||||
lastPaymentDate?: string
|
||||
}
|
||||
|
||||
// ── Company Information ─────────────────────────────────────────────
|
||||
|
||||
export interface CompanyInformationDto {
|
||||
companyName: string
|
||||
organizationNumber?: string
|
||||
legalEntity?: PartyLegalEntity
|
||||
address?: PostalAddress
|
||||
contact?: Contact
|
||||
vatNumber?: string
|
||||
fiscalYearStart?: string // MM-DD
|
||||
baseCurrency?: string
|
||||
}
|
||||
|
||||
// ── Customer ────────────────────────────────────────────────────────
|
||||
|
||||
export type ArcimCustomerType = 'company' | 'private'
|
||||
|
||||
export interface CustomerDto {
|
||||
id: string
|
||||
customerNumber: string
|
||||
type?: ArcimCustomerType
|
||||
party: PartyDto
|
||||
active: boolean
|
||||
vatNumber?: string
|
||||
defaultPaymentTermsDays?: number
|
||||
note?: string
|
||||
}
|
||||
|
||||
// ── Supplier ────────────────────────────────────────────────────────
|
||||
|
||||
export interface SupplierDto {
|
||||
id: string
|
||||
supplierNumber: string
|
||||
party: PartyDto
|
||||
active: boolean
|
||||
vatNumber?: string
|
||||
bankAccount?: string
|
||||
bankGiro?: string
|
||||
plusGiro?: string
|
||||
defaultPaymentTermsDays?: number
|
||||
note?: string
|
||||
}
|
||||
|
||||
// ── Sales Invoice ───────────────────────────────────────────────────
|
||||
|
||||
export type InvoiceStatusCode = 'draft' | 'sent' | 'booked' | 'paid' | 'overdue' | 'cancelled' | 'credited'
|
||||
|
||||
export interface SalesInvoiceLineDto {
|
||||
id: string
|
||||
description?: string
|
||||
quantity?: number
|
||||
unitCode?: string
|
||||
unitPrice?: AmountType
|
||||
lineExtensionAmount: AmountType
|
||||
taxPercent?: number
|
||||
taxAmount?: AmountType
|
||||
accountNumber?: string
|
||||
itemName?: string
|
||||
}
|
||||
|
||||
export interface SalesInvoiceDto {
|
||||
id: string
|
||||
invoiceNumber: string
|
||||
issueDate: string
|
||||
dueDate?: string
|
||||
deliveryDate?: string
|
||||
invoiceTypeCode?: string
|
||||
currencyCode: string
|
||||
status: InvoiceStatusCode
|
||||
supplier: PartyDto
|
||||
customer: PartyDto
|
||||
lines: SalesInvoiceLineDto[]
|
||||
taxTotal?: TaxTotalDto
|
||||
legalMonetaryTotal: LegalMonetaryTotalDto
|
||||
paymentStatus: PaymentStatusDto
|
||||
paymentTerms?: string
|
||||
note?: string
|
||||
}
|
||||
|
||||
// ── Supplier Invoice ────────────────────────────────────────────────
|
||||
|
||||
export interface SupplierInvoiceLineDto {
|
||||
id: string
|
||||
description?: string
|
||||
quantity?: number
|
||||
unitCode?: string
|
||||
unitPrice?: AmountType
|
||||
lineExtensionAmount: AmountType
|
||||
taxPercent?: number
|
||||
taxAmount?: AmountType
|
||||
accountNumber?: string
|
||||
itemName?: string
|
||||
}
|
||||
|
||||
export interface SupplierInvoiceDto {
|
||||
id: string
|
||||
invoiceNumber: string
|
||||
issueDate: string
|
||||
dueDate?: string
|
||||
deliveryDate?: string
|
||||
invoiceTypeCode?: string
|
||||
currencyCode: string
|
||||
status: InvoiceStatusCode
|
||||
supplier: PartyDto
|
||||
buyer: PartyDto
|
||||
lines: SupplierInvoiceLineDto[]
|
||||
taxTotal?: TaxTotalDto
|
||||
legalMonetaryTotal: LegalMonetaryTotalDto
|
||||
paymentStatus: PaymentStatusDto
|
||||
ocrNumber?: string
|
||||
note?: string
|
||||
}
|
||||
|
||||
// ── Supported providers ─────────────────────────────────────────────
|
||||
|
||||
export type ArcimProvider = 'fortnox' | 'visma' | 'briox' | 'bokio' | 'bjornlunden'
|
||||
|
||||
export const ARCIM_PROVIDERS: { id: ArcimProvider; name: string; authType: 'oauth' | 'token' }[] = [
|
||||
{ id: 'fortnox', name: 'Fortnox', authType: 'oauth' },
|
||||
{ id: 'visma', name: 'Visma eEkonomi', authType: 'oauth' },
|
||||
{ id: 'bokio', name: 'Bokio', authType: 'token' },
|
||||
{ id: 'bjornlunden', name: 'Björn Lundén', authType: 'token' },
|
||||
{ id: 'briox', name: 'Briox', authType: 'token' },
|
||||
]
|
||||
|
||||
// ── Migration state ─────────────────────────────────────────────────
|
||||
|
||||
export interface MigrationProgress {
|
||||
status: 'idle' | 'connecting' | 'fetching' | 'importing' | 'completed' | 'failed'
|
||||
currentStep?: string
|
||||
progress: number // 0-100
|
||||
results?: MigrationResults
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface MigrationResults {
|
||||
companyInfo?: { imported: boolean }
|
||||
customers?: { total: number; imported: number; skipped: number }
|
||||
suppliers?: { total: number; imported: number; skipped: number }
|
||||
salesInvoices?: { total: number; imported: number; skipped: number }
|
||||
supplierInvoices?: { total: number; imported: number; skipped: number }
|
||||
}
|
||||
|
||||
// ── Consent flow ────────────────────────────────────────────────────
|
||||
|
||||
export interface ConsentRecord {
|
||||
id: string
|
||||
name: string
|
||||
provider: ArcimProvider
|
||||
status: 0 | 1 | 2 | 3 // Created | Accepted | Revoked | Inactive
|
||||
orgNumber?: string
|
||||
companyName?: string
|
||||
etag?: string
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
export interface OtcResponse {
|
||||
code: string
|
||||
consentId: string
|
||||
expiresAt: string
|
||||
}
|
||||
@@ -49,7 +49,7 @@ describe('sectors registry', () => {
|
||||
})
|
||||
|
||||
it('should have 8 total extensions', () => {
|
||||
expect(getAllExtensions().length).toBe(8)
|
||||
expect(getAllExtensions().length).toBe(9)
|
||||
})
|
||||
|
||||
it('should have unique slugs within each sector', () => {
|
||||
@@ -94,7 +94,7 @@ describe('sectors registry', () => {
|
||||
|
||||
it('getExtensionsBySector returns extensions for a sector', () => {
|
||||
const extensions = getExtensionsBySector('general')
|
||||
expect(extensions.length).toBe(8)
|
||||
expect(extensions.length).toBe(9)
|
||||
})
|
||||
|
||||
it('all extensions have required fields', () => {
|
||||
|
||||
@@ -3,4 +3,5 @@
|
||||
export const ENABLED_EXTENSION_IDS: ReadonlySet<string> = new Set([
|
||||
'enable-banking',
|
||||
'email',
|
||||
'arcim-migration',
|
||||
])
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
import type { Extension } from '../types'
|
||||
import { enableBankingExtension } from '@/extensions/general/enable-banking'
|
||||
import { emailExtension } from '@/extensions/general/email'
|
||||
import { arcimMigrationExtension } from '@/extensions/general/arcim-migration'
|
||||
|
||||
export const FIRST_PARTY_EXTENSIONS: Extension[] = [
|
||||
enableBankingExtension,
|
||||
emailExtension,
|
||||
arcimMigrationExtension,
|
||||
]
|
||||
|
||||
@@ -30,5 +30,15 @@ export const EXTENSION_DEFINITIONS: Record<string, ExtensionDefinition[]> = {
|
||||
"company_settings"
|
||||
]
|
||||
},
|
||||
{
|
||||
"slug": "arcim-migration",
|
||||
"name": "Systemmigration (Arcim Sync)",
|
||||
"sector": "general",
|
||||
"category": "import",
|
||||
"icon": "ArrowRightLeft",
|
||||
"dataPattern": "manual",
|
||||
"description": "Migrera bokföring från Fortnox, Visma, Bokio, Björn Lundén eller Briox",
|
||||
"longDescription": "Flytta all bokföringsdata från ditt gamla system till gnubok. Importerar kontoplan, verifikationer, kunder, leverantörer och öppna fakturor automatiskt via säker API-integration."
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -5,4 +5,5 @@ import type { WorkspaceComponentProps } from '../workspace-registry'
|
||||
|
||||
export const WORKSPACES: Record<string, ComponentType<WorkspaceComponentProps>> = {
|
||||
'general/enable-banking': dynamic(() => import('@/components/extensions/general/EnableBankingWorkspace')),
|
||||
'general/arcim-migration': dynamic(() => import('@/components/extensions/general/ArcimMigrationWorkspace')),
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ const LEGACY_GENERAL_EXTENSIONS = [
|
||||
'ai-categorization',
|
||||
'ai-chat',
|
||||
'enable-banking',
|
||||
'arcim-migration',
|
||||
]
|
||||
|
||||
export async function isExtensionEnabled(
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
getMappingStats,
|
||||
applyMappingOverride,
|
||||
mappingsToMap,
|
||||
isSystemAccount,
|
||||
} from '../account-mapper'
|
||||
|
||||
// --- Helpers ---
|
||||
@@ -54,6 +55,8 @@ const basAccounts: BASAccount[] = [
|
||||
makeBASAccount('1510', 'Kundfordringar'),
|
||||
makeBASAccount('1930', 'Företagskonto'),
|
||||
makeBASAccount('2440', 'Leverantörsskulder'),
|
||||
makeBASAccount('2640', 'Ingående moms'),
|
||||
makeBASAccount('2641', 'Debiterad ingående moms'),
|
||||
makeBASAccount('3001', 'Försäljning varor 25%'),
|
||||
makeBASAccount('3002', 'Försäljning varor 12%'),
|
||||
makeBASAccount('5010', 'Lokalhyra'),
|
||||
@@ -94,7 +97,7 @@ describe('suggestMappings', () => {
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].targetAccount).toBe('3400')
|
||||
expect(result[0].targetName).toBe('Försäljning tjänster')
|
||||
expect(result[0].confidence).toBe(0.9)
|
||||
expect(result[0].confidence).toBe(0.7)
|
||||
expect(result[0].matchType).toBe('bas_range')
|
||||
})
|
||||
|
||||
@@ -105,7 +108,7 @@ describe('suggestMappings', () => {
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].targetAccount).toBe('1241')
|
||||
expect(result[0].targetName).toBe('Personbilar')
|
||||
expect(result[0].confidence).toBe(0.9)
|
||||
expect(result[0].confidence).toBe(0.7)
|
||||
expect(result[0].matchType).toBe('bas_range')
|
||||
})
|
||||
|
||||
@@ -164,9 +167,9 @@ describe('suggestMappings', () => {
|
||||
// Unmapped (confidence 0) should come first
|
||||
expect(result[0].sourceAccount).toBe('9999')
|
||||
expect(result[0].confidence).toBe(0)
|
||||
// bas_range (confidence 0.9) next
|
||||
// bas_range (confidence 0.7) next
|
||||
expect(result[1].sourceAccount).toBe('3400')
|
||||
expect(result[1].confidence).toBe(0.9)
|
||||
expect(result[1].confidence).toBe(0.7)
|
||||
// Exact matches (confidence 1.0) come last
|
||||
expect(result[2].confidence).toBe(1.0)
|
||||
expect(result[3].confidence).toBe(1.0)
|
||||
@@ -193,13 +196,33 @@ describe('suggestMappings', () => {
|
||||
expect(result).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('redirects group header account 2640 to posting account 2641', () => {
|
||||
const source = [makeSIEAccount('2640', 'Ingående moms')]
|
||||
const result = suggestMappings(source, basAccounts)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].sourceAccount).toBe('2640')
|
||||
expect(result[0].targetAccount).toBe('2641')
|
||||
expect(result[0].targetName).toBe('Debiterad ingående moms')
|
||||
expect(result[0].confidence).toBe(1.0)
|
||||
expect(result[0].matchType).toBe('exact')
|
||||
})
|
||||
|
||||
it('does not redirect 2641 (it is the posting account, not a group header)', () => {
|
||||
const source = [makeSIEAccount('2641', 'Debiterad ingående moms')]
|
||||
const result = suggestMappings(source, basAccounts)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].targetAccount).toBe('2641')
|
||||
})
|
||||
|
||||
it('handles empty BAS accounts — bas_range fallback for valid accounts', () => {
|
||||
const source = [makeSIEAccount('1510', 'Kundfordringar')]
|
||||
const result = suggestMappings(source, [])
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].targetAccount).toBe('1510')
|
||||
expect(result[0].confidence).toBe(0.9)
|
||||
expect(result[0].confidence).toBe(0.7)
|
||||
expect(result[0].matchType).toBe('bas_range')
|
||||
})
|
||||
|
||||
@@ -360,8 +383,8 @@ describe('getMappingStats', () => {
|
||||
)
|
||||
const stats = getMappingStats(mappings)
|
||||
|
||||
// Average of (1.0 + 0.9) / 2 = 0.95
|
||||
expect(stats.averageConfidence).toBe(0.95)
|
||||
// Average of (1.0 + 0.7) / 2 = 0.85
|
||||
expect(stats.averageConfidence).toBe(0.85)
|
||||
})
|
||||
|
||||
it('returns 0 average confidence when nothing is mapped', () => {
|
||||
@@ -446,3 +469,53 @@ describe('mappingsToMap', () => {
|
||||
expect(map.size).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isSystemAccount', () => {
|
||||
it('returns true for Fortnox system account 0099', () => {
|
||||
expect(isSystemAccount('0099')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true for other 0xxx accounts', () => {
|
||||
expect(isSystemAccount('0001')).toBe(true)
|
||||
expect(isSystemAccount('0500')).toBe(true)
|
||||
expect(isSystemAccount('0999')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for valid BAS accounts (1000-8999)', () => {
|
||||
expect(isSystemAccount('1000')).toBe(false)
|
||||
expect(isSystemAccount('1510')).toBe(false)
|
||||
expect(isSystemAccount('3001')).toBe(false)
|
||||
expect(isSystemAccount('8999')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for 9000+ accounts (handled separately as out-of-range)', () => {
|
||||
expect(isSystemAccount('9000')).toBe(false)
|
||||
expect(isSystemAccount('9999')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for non-4-digit numbers', () => {
|
||||
expect(isSystemAccount('099')).toBe(false)
|
||||
expect(isSystemAccount('00099')).toBe(false)
|
||||
expect(isSystemAccount('abc')).toBe(false)
|
||||
expect(isSystemAccount('')).toBe(false)
|
||||
})
|
||||
|
||||
it('allows pre-filtering system accounts before suggestMappings', () => {
|
||||
const allAccounts = [
|
||||
makeSIEAccount('0099', 'Systemkonto'),
|
||||
makeSIEAccount('1510', 'Kundfordringar'),
|
||||
makeSIEAccount('1930', 'Företagskonto'),
|
||||
]
|
||||
|
||||
const bookkeepingAccounts = allAccounts.filter((a) => !isSystemAccount(a.number))
|
||||
const excluded = allAccounts.filter((a) => isSystemAccount(a.number))
|
||||
|
||||
expect(bookkeepingAccounts).toHaveLength(2)
|
||||
expect(excluded).toHaveLength(1)
|
||||
expect(excluded[0].number).toBe('0099')
|
||||
|
||||
const mappings = suggestMappings(bookkeepingAccounts, basAccounts)
|
||||
expect(mappings).toHaveLength(2)
|
||||
expect(mappings.every((m) => m.targetAccount)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { generateImportPreview } from '../sie-import'
|
||||
import { generateImportPreview, validateIBBalance, isBalanceSheetAccount } from '../sie-import'
|
||||
import type { ParsedSIEFile, AccountMapping } from '../types'
|
||||
|
||||
// --- Helpers ---
|
||||
@@ -221,3 +221,116 @@ describe('generateImportPreview', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateIBBalance', () => {
|
||||
it('returns 0 roundingAdjustment when IB is balanced', () => {
|
||||
const parsed = makeParsedFile({
|
||||
openingBalances: [
|
||||
{ yearIndex: 0, account: '1510', amount: 50000 },
|
||||
{ yearIndex: 0, account: '2440', amount: -50000 },
|
||||
],
|
||||
})
|
||||
const accountMap = new Map([['1510', '1510'], ['2440', '2440']])
|
||||
const result = validateIBBalance(parsed, accountMap)
|
||||
|
||||
expect(result.roundingAdjustment).toBe(0)
|
||||
expect(result.fileImbalance).toBe(0)
|
||||
expect(result.excludedAccountsTotal).toBe(0)
|
||||
expect(result.lines).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('returns rounding adjustment for imbalance <= 1 SEK', () => {
|
||||
const parsed = makeParsedFile({
|
||||
openingBalances: [
|
||||
{ yearIndex: 0, account: '1510', amount: 50000.50 },
|
||||
{ yearIndex: 0, account: '2440', amount: -50000 },
|
||||
],
|
||||
})
|
||||
const accountMap = new Map([['1510', '1510'], ['2440', '2440']])
|
||||
const result = validateIBBalance(parsed, accountMap)
|
||||
|
||||
expect(result.roundingAdjustment).toBe(0.5)
|
||||
expect(result.fileImbalance).toBe(0.5)
|
||||
})
|
||||
|
||||
it('returns large adjustment for file-level imbalance (unallocated årets resultat)', () => {
|
||||
// Simulates a Fortnox export where previous year result hasn't been allocated
|
||||
// to equity — BS accounts don't balance because årets resultat is implicit
|
||||
const parsed = makeParsedFile({
|
||||
openingBalances: [
|
||||
{ yearIndex: 0, account: '1510', amount: 50100 },
|
||||
{ yearIndex: 0, account: '2440', amount: -50000 },
|
||||
],
|
||||
})
|
||||
const accountMap = new Map([['1510', '1510'], ['2440', '2440']])
|
||||
const result = validateIBBalance(parsed, accountMap)
|
||||
|
||||
// The adjustment is 100 SEK — caller should book to 2099, never reject
|
||||
expect(result.roundingAdjustment).toBe(100)
|
||||
expect(result.fileImbalance).toBe(100)
|
||||
expect(result.excludedAccountsTotal).toBe(0)
|
||||
})
|
||||
|
||||
it('tracks excluded accounts separately from file imbalance (Fortnox system accounts)', () => {
|
||||
// Simulates Fortnox 0099 carrying IB balance — file is balanced,
|
||||
// but mapped accounts are not because 0099 is excluded from mapping
|
||||
const parsed = makeParsedFile({
|
||||
openingBalances: [
|
||||
{ yearIndex: 0, account: '1510', amount: 50000 },
|
||||
{ yearIndex: 0, account: '2440', amount: -150000 },
|
||||
{ yearIndex: 0, account: '0099', amount: 100000 }, // System account, not mapped
|
||||
],
|
||||
})
|
||||
const accountMap = new Map([['1510', '1510'], ['2440', '2440']])
|
||||
const result = validateIBBalance(parsed, accountMap)
|
||||
|
||||
// File-level: 50000 + (-150000) + 100000 = 0, balanced
|
||||
expect(result.fileImbalance).toBe(0)
|
||||
// Mapped-level: 50000 debit, 150000 credit = -100000 diff
|
||||
expect(result.roundingAdjustment).toBe(-100000)
|
||||
// The excluded 0099 accounts for the entire difference
|
||||
expect(result.excludedAccountsTotal).toBe(100000)
|
||||
// Only 2 lines (0099 excluded)
|
||||
expect(result.lines).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('ignores non-current-year balances', () => {
|
||||
const parsed = makeParsedFile({
|
||||
openingBalances: [
|
||||
{ yearIndex: 0, account: '1510', amount: 50000 },
|
||||
{ yearIndex: 0, account: '2440', amount: -50000 },
|
||||
{ yearIndex: -1, account: '1510', amount: 99999 }, // Previous year — ignored
|
||||
],
|
||||
})
|
||||
const accountMap = new Map([['1510', '1510'], ['2440', '2440']])
|
||||
const result = validateIBBalance(parsed, accountMap)
|
||||
|
||||
expect(result.roundingAdjustment).toBe(0)
|
||||
expect(result.lines).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isBalanceSheetAccount', () => {
|
||||
it('returns true for class 1 (assets)', () => {
|
||||
expect(isBalanceSheetAccount('1510')).toBe(true)
|
||||
expect(isBalanceSheetAccount('1930')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true for class 2 (liabilities/equity)', () => {
|
||||
expect(isBalanceSheetAccount('2099')).toBe(true)
|
||||
expect(isBalanceSheetAccount('2440')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for class 3 (revenue)', () => {
|
||||
expect(isBalanceSheetAccount('3001')).toBe(false)
|
||||
expect(isBalanceSheetAccount('3740')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for class 4-8 (expenses)', () => {
|
||||
expect(isBalanceSheetAccount('4010')).toBe(false)
|
||||
expect(isBalanceSheetAccount('5010')).toBe(false)
|
||||
expect(isBalanceSheetAccount('6211')).toBe(false)
|
||||
expect(isBalanceSheetAccount('7210')).toBe(false)
|
||||
expect(isBalanceSheetAccount('8999')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -383,7 +383,7 @@ describe('validateSIEFile', () => {
|
||||
expect(validation.errors.some((e) => e.includes('not balanced'))).toBe(true)
|
||||
})
|
||||
|
||||
it('adds warning for undefined account references', () => {
|
||||
it('no longer warns about accounts referenced in #IB since parser auto-adds them', () => {
|
||||
const content = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
@@ -394,9 +394,12 @@ describe('validateSIEFile', () => {
|
||||
].join('\n')
|
||||
|
||||
const parsed = parseSIEFile(content)
|
||||
const validation = validateSIEFile(parsed)
|
||||
// Parser now auto-adds 9999 to accounts list from #IB data
|
||||
expect(parsed.accounts.map((a) => a.number)).toContain('9999')
|
||||
|
||||
expect(validation.warnings.some((w) => w.includes('9999') && w.includes('not defined'))).toBe(true)
|
||||
const validation = validateSIEFile(parsed)
|
||||
// No warning since account was auto-added by the parser
|
||||
expect(validation.warnings.some((w) => w.includes('9999') && w.includes('not defined'))).toBe(false)
|
||||
})
|
||||
|
||||
it('adds error for missing #RAR', () => {
|
||||
@@ -436,6 +439,60 @@ describe('validateSIEFile', () => {
|
||||
|
||||
// --- Fix 2: Windows-1252 encoding detection and decoding ---
|
||||
|
||||
describe('detectEncoding — #FORMAT PC8 detection', () => {
|
||||
it('returns cp437 when #FORMAT PC8 is present in the first 500 bytes', () => {
|
||||
const text = '#FLAGGA 0\n#FORMAT PC8\n#SIETYP 4\n'
|
||||
const encoder = new TextEncoder()
|
||||
const buf = encoder.encode(text)
|
||||
const encoding = detectEncoding(buf.buffer)
|
||||
expect(encoding).toBe('cp437')
|
||||
})
|
||||
|
||||
it('returns cp437 even when Win-1252 bytes follow #FORMAT PC8', () => {
|
||||
// #FORMAT PC8 header should take priority over any byte analysis
|
||||
const prefix = new TextEncoder().encode('#FORMAT PC8\n#FNAMN F')
|
||||
const buf = new Uint8Array(prefix.length + 3)
|
||||
buf.set(prefix)
|
||||
buf[prefix.length] = 0xf6 // ö in Win-1252
|
||||
buf[prefix.length + 1] = 0xe4 // ä in Win-1252
|
||||
buf[prefix.length + 2] = 0xe5 // å in Win-1252
|
||||
const encoding = detectEncoding(buf.buffer)
|
||||
expect(encoding).toBe('cp437')
|
||||
})
|
||||
})
|
||||
|
||||
describe('detectEncoding — range-based discrimination', () => {
|
||||
it('detects CP437 when bytes are in 0x80-0x9F range only', () => {
|
||||
// 0x84=ä, 0x86=å, 0x94=ö in CP437 — all in 0x80-0x9F
|
||||
const buf = new Uint8Array([0x23, 0x84, 0x86, 0x94, 0x84, 0x86])
|
||||
const encoding = detectEncoding(buf.buffer)
|
||||
expect(encoding).toBe('cp437')
|
||||
})
|
||||
|
||||
it('detects Win-1252 when bytes are in 0xC0-0xFF range only', () => {
|
||||
// 0xE4=ä, 0xE5=å, 0xF6=ö in Win-1252 — all in 0xC0-0xFF
|
||||
const buf = new Uint8Array([0x23, 0xe4, 0xe5, 0xf6, 0xe4, 0xe5])
|
||||
const encoding = detectEncoding(buf.buffer)
|
||||
expect(encoding).toBe('windows1252')
|
||||
})
|
||||
|
||||
it('does not double-count UTF-8 continuation bytes as CP437', () => {
|
||||
// UTF-8: ä = C3 A4, å = C3 A5, ö = C3 B6
|
||||
// Without skipping, 0xA4/0xA5/0xB6 are NOT in CP437 map so no false count,
|
||||
// but 0x84/0x85 ARE in CP437 map — test that C3 84 (Ä in UTF-8) is not
|
||||
// counted as CP437 0x84 (ä)
|
||||
const buf = new Uint8Array([
|
||||
0x23, // #
|
||||
0xc3, 0x84, // Ä in UTF-8
|
||||
0xc3, 0x85, // Å in UTF-8
|
||||
0xc3, 0x96, // Ö in UTF-8
|
||||
0xc3, 0xa4, // ä in UTF-8
|
||||
0xc3, 0xa5, // å in UTF-8
|
||||
])
|
||||
const encoding = detectEncoding(buf.buffer)
|
||||
expect(encoding).toBe('utf8')
|
||||
})
|
||||
})
|
||||
describe('detectEncoding — Windows-1252', () => {
|
||||
it('detects Windows-1252 when Swedish chars use Win-1252 byte values', () => {
|
||||
// Build a buffer with Windows-1252 encoded Swedish text: "#FNAMN Företag"
|
||||
@@ -662,3 +719,82 @@ describe('parseSIEFile — missing amount handling', () => {
|
||||
expect(result.openingBalances[0].amount).toBe(100000)
|
||||
})
|
||||
})
|
||||
|
||||
// --- Fix B4: Account collection from transaction data ---
|
||||
|
||||
describe('parseSIEFile — account collection from transaction data', () => {
|
||||
it('adds accounts from #TRANS that are missing from #KONTO', () => {
|
||||
const content = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Test"',
|
||||
'#RAR 0 20240101 20241231',
|
||||
'#KONTO 1510 "Kundfordringar"',
|
||||
// 3001 is NOT defined in #KONTO but used in #TRANS
|
||||
'#VER A 1 20240115 "Test"',
|
||||
'{',
|
||||
'#TRANS 1510 {} 10000.00',
|
||||
'#TRANS 3001 {} -10000.00',
|
||||
'}',
|
||||
].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
// Should have both 1510 (from #KONTO) and 3001 (from #TRANS)
|
||||
expect(result.accounts.map((a) => a.number)).toContain('1510')
|
||||
expect(result.accounts.map((a) => a.number)).toContain('3001')
|
||||
// The auto-added account should have empty name
|
||||
const added = result.accounts.find((a) => a.number === '3001')
|
||||
expect(added?.name).toBe('')
|
||||
})
|
||||
|
||||
it('adds accounts from #IB that are missing from #KONTO', () => {
|
||||
const content = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Test"',
|
||||
'#RAR 0 20240101 20241231',
|
||||
'#KONTO 1510 "Kundfordringar"',
|
||||
'#IB 0 1510 50000.00',
|
||||
'#IB 0 2440 -50000.00', // 2440 not in #KONTO
|
||||
].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.accounts.map((a) => a.number)).toContain('2440')
|
||||
})
|
||||
|
||||
it('does not duplicate accounts already in #KONTO', () => {
|
||||
const content = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Test"',
|
||||
'#RAR 0 20240101 20241231',
|
||||
'#KONTO 1510 "Kundfordringar"',
|
||||
'#KONTO 3001 "Försäljning"',
|
||||
'#VER A 1 20240115 "Test"',
|
||||
'{',
|
||||
'#TRANS 1510 {} 10000.00',
|
||||
'#TRANS 3001 {} -10000.00',
|
||||
'}',
|
||||
].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
const count1510 = result.accounts.filter((a) => a.number === '1510').length
|
||||
expect(count1510).toBe(1)
|
||||
})
|
||||
|
||||
it('adds accounts from #UB and #RES that are missing from #KONTO', () => {
|
||||
const content = [
|
||||
'#FLAGGA 0',
|
||||
'#SIETYP 4',
|
||||
'#FNAMN "Test"',
|
||||
'#RAR 0 20240101 20241231',
|
||||
'#KONTO 1510 "Kundfordringar"',
|
||||
'#UB 0 1930 100000.00', // 1930 not in #KONTO
|
||||
'#RES 0 3001 -50000.00', // 3001 not in #KONTO
|
||||
].join('\n')
|
||||
|
||||
const result = parseSIEFile(content)
|
||||
expect(result.accounts.map((a) => a.number)).toContain('1930')
|
||||
expect(result.accounts.map((a) => a.number)).toContain('3001')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -25,6 +25,25 @@ export type MappableAccount = {
|
||||
account_name: string
|
||||
}
|
||||
|
||||
// Group header accounts that should redirect to their posting sub-account.
|
||||
// These are BAS group headers not meant for direct posting.
|
||||
const GROUP_HEADER_REDIRECTS: Record<string, string> = {
|
||||
'2640': '2641', // Ingående moms → Debiterad ingående moms
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an account is a source-system internal account that should be
|
||||
* excluded from import. BAS accounts use classes 1-8 (1000-8999). Account
|
||||
* numbers starting with 0 (e.g. Fortnox 0099) are internal system accounts
|
||||
* with no BAS equivalent — they should be silently filtered out rather than
|
||||
* forcing the user to map them.
|
||||
*/
|
||||
export function isSystemAccount(accountNumber: string): boolean {
|
||||
if (!/^\d{4}$/.test(accountNumber)) return false
|
||||
const num = parseInt(accountNumber, 10)
|
||||
return num < 1000
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an account number is in the valid BAS range (1000-8999).
|
||||
* Standard Swedish BAS accounts are 4-digit numbers in classes 1-8.
|
||||
@@ -60,6 +79,23 @@ function findBestMatch(
|
||||
)
|
||||
|
||||
if (exactMatch) {
|
||||
// Redirect group header accounts to their posting sub-account
|
||||
const redirect = GROUP_HEADER_REDIRECTS[exactMatch.account_number]
|
||||
if (redirect) {
|
||||
const redirectTarget = basAccounts.find((a) => a.account_number === redirect)
|
||||
if (redirectTarget) {
|
||||
return {
|
||||
sourceAccount: source.number,
|
||||
sourceName: source.name,
|
||||
targetAccount: redirectTarget.account_number,
|
||||
targetName: redirectTarget.account_name,
|
||||
confidence: 1.0,
|
||||
matchType: 'exact',
|
||||
isOverride: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sourceAccount: source.number,
|
||||
sourceName: source.name,
|
||||
@@ -80,7 +116,7 @@ function findBestMatch(
|
||||
sourceName: source.name,
|
||||
targetAccount: source.number,
|
||||
targetName: source.name,
|
||||
confidence: 0.9,
|
||||
confidence: 0.7,
|
||||
matchType: 'bas_range',
|
||||
isOverride: false,
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user