* refactor: remove unnecessary secondary action from EmptyInvoices component

* feat: add direct provider layer and provider_consents migration

Replace Arcim Sync gateway dependency with direct provider clients
for Fortnox, Visma, Briox, Bokio, and Björn Lundén. Adds OAuth
config, rate limiting, retry logic, data fetching, and consent
storage via new provider_consents/tokens/otc tables.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* refactor: migrate arcim extension to direct provider APIs

Replace Arcim Sync gateway calls with direct provider API access.
Use FortnoxClient.getText() for SIE endpoints that return plain text
instead of JSON. OAuth callback now returns HTML with postMessage
to communicate with the opener window instead of redirecting.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: use OAuth popup window instead of new tab

Open provider login in a centered popup that auto-closes on
completion via postMessage, keeping the user on a single tab.
Falls back to redirect flow if popup is blocked.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat: add connection status, consent reuse, and SIE duplicate detection

- Add listConsents() to query active consents by company
- Add GET /status route returning consents, SIE import history, and
  entity counts
- /connect reuses existing accepted consent instead of creating
  duplicates, and cleans up abandoned (status 0) consents
- /status only returns accepted (status 1) consents
- /sie-data checks each file's SHA-256 hash against sie_imports to
  report per-file import status (alreadyImported, importedAt)
- /sie-data blocks on SIE validation failure (mirrors manual upload)
- /import-sie validates unmapped accounts and auto-activates missing
  BAS accounts in chart_of_accounts (mirrors manual upload)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat: show active connections, SIE file status, and smart re-sync UI

- ProviderStep shows active connections with last import date, entity
  counts, "Synka igen" button, and disconnect option
- Already-connected providers greyed out in selection grid
- OptionsStep shows per-fiscal-year import status (imported vs new)
- SIE toggle disabled with explanation when all files already imported
- handleStartMigration skips already-imported SIE files
- Auto-skip mapping step and disable SIE on re-sync when up to date
- Result step hides empty "0 importerade" rows and shows
  "Allt är uppdaterat" when nothing new was fetched
- OptionRow supports disabled state

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: adjust COMING_SOON_PROVIDERS based on NODE_ENV for development and production

* Removed duplicate

* Removed duplicate

* refactor: redesign reports page navigation from grid boxes to bordered card layout

Replace the 4-column grid of uneven TabsList boxes with a CSS grid card
using auto-sized columns separated by 1px border dividers. All sections
now share equal height via items-stretch, with clear visual separation
between groups.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* chore: trigger Vercel deployment

* Update supabase/migrations/20260402010000_provider_consents.sql

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

* Update lib/providers/rate-limiter.ts

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

* chore: re-trigger checks after migration sync

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
This commit is contained in:
Mattsson
2026-04-07 10:30:20 +02:00
committed by GitHub
co-authored by Claude Opus 4.6 greptile-apps[bot]
parent e2d9c8bb85
commit e42da5c32b
41 changed files with 5219 additions and 488 deletions
File diff suppressed because it is too large Load Diff
@@ -16,7 +16,7 @@ import type {
CompanyInformationDto,
PostalAddress,
PartyDto,
} from '../types'
} from '@/lib/providers/dto'
// ── Helpers ─────────────────────────────────────────────────────────
@@ -1,8 +1,8 @@
/**
* Migration orchestrator — coordinates the data migration from
* an external accounting system via Arcim Sync into gnubok.
* an external accounting system directly via provider APIs into gnubok.
*
* Bookkeeping data (accounts, balances, vouchers) is now imported
* Bookkeeping data (accounts, balances, vouchers) is imported
* via SIE files through the core SIE import engine. This orchestrator
* handles only entity-level imports:
* 1. Company info → pre-fill company_settings
@@ -14,13 +14,15 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { MigrationProgress, MigrationResults } from '../types'
import type { ProviderName } from '@/lib/providers/types'
import { resolveConsent } from '@/lib/providers/resolve-consent'
import {
fetchCompanyInfo,
fetchCustomers,
fetchSuppliers,
fetchSalesInvoices,
fetchSupplierInvoices,
} from './arcim-client'
fetchCompanyInfoDirect,
fetchCustomersDirect,
fetchSuppliersDirect,
fetchSalesInvoicesDirect,
fetchSupplierInvoicesDirect,
} from '@/lib/providers/provider-data-fetcher'
import {
mapCustomer,
mapSupplier,
@@ -32,8 +34,8 @@ import {
export interface MigrationOptions {
consentId: string
userId: string
companyId: string
userId: string
supabase: SupabaseClient
importCompanyInfo?: boolean
importCustomers?: boolean
@@ -50,15 +52,21 @@ function emitProgress(options: MigrationOptions, progress: MigrationProgress) {
// ── Main orchestrator ─────────────────────────────────────────────
export async function executeMigration(options: MigrationOptions): Promise<MigrationResults> {
const { consentId, userId, companyId, supabase } = options
const { consentId, companyId, userId, supabase } = options
const results: MigrationResults = {}
// Resolve consent to get access token and provider
const resolved = await resolveConsent(companyId, consentId)
const provider = resolved.consent.provider as ProviderName
const accessToken = resolved.accessToken
const providerCompanyId = resolved.providerCompanyId
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)
const companyInfo = await fetchCompanyInfoDirect(provider, accessToken, providerCompanyId)
if (companyInfo) {
const mapped = mapCompanyInfo(companyInfo)
const { data: existing } = await supabase
@@ -100,7 +108,7 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
if (options.importCustomers !== false) {
emitProgress(options, { status: 'importing', currentStep: 'Importerar kunder...', progress: 20 })
try {
const customers = await fetchCustomers(consentId)
const customers = await fetchCustomersDirect(provider, accessToken, providerCompanyId)
let imported = 0
let skipped = 0
@@ -157,7 +165,7 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
if (options.importSuppliers !== false) {
emitProgress(options, { status: 'importing', currentStep: 'Importerar leverantörer...', progress: 40 })
try {
const suppliers = await fetchSuppliers(consentId)
const suppliers = await fetchSuppliersDirect(provider, accessToken, providerCompanyId)
let imported = 0
let skipped = 0
@@ -212,7 +220,7 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
if (options.importSalesInvoices !== false) {
emitProgress(options, { status: 'importing', currentStep: 'Importerar kundfakturor...', progress: 60 })
try {
const invoices = await fetchSalesInvoices(consentId)
const invoices = await fetchSalesInvoicesDirect(provider, accessToken, providerCompanyId)
const openInvoices = invoices.filter(i =>
i.status === 'sent' || i.status === 'overdue' || i.status === 'booked'
)
@@ -324,7 +332,7 @@ export async function executeMigration(options: MigrationOptions): Promise<Migra
if (options.importSupplierInvoices !== false) {
emitProgress(options, { status: 'importing', currentStep: 'Importerar leverantörsfakturor...', progress: 80 })
try {
const invoices = await fetchSupplierInvoices(consentId)
const invoices = await fetchSupplierInvoicesDirect(provider, accessToken, providerCompanyId)
const openInvoices = invoices.filter(i =>
i.status === 'sent' || i.status === 'overdue' || i.status === 'booked' || i.status === 'draft'
)
@@ -0,0 +1,262 @@
/**
* Direct provider client — replaces arcim-client.ts.
*
* Instead of making HTTP calls to the Arcim Sync gateway, this module
* performs consent/OTC operations directly against Supabase and delegates
* data fetching to the provider clients in lib/providers/.
*/
import { createServiceClient } from '@/lib/supabase/server'
import type { ProviderName } from '@/lib/providers/types'
import { getOAuthConfig } from '@/lib/providers/oauth-config'
import { buildFortnoxAuthUrl } from '@/lib/providers/fortnox/oauth'
import { exchangeFortnoxCode } from '@/lib/providers/fortnox/oauth'
import { buildVismaAuthUrl, exchangeVismaCode } from '@/lib/providers/visma/oauth'
import { refreshBjornLundenToken } from '@/lib/providers/bjornlunden/oauth'
import type { ConsentRecord, OtcResponse } from '../types'
// Re-export data fetching functions from the provider layer
export { resolveConsent } from '@/lib/providers/resolve-consent'
export {
fetchCompanyInfoDirect,
fetchCustomersDirect,
fetchSuppliersDirect,
fetchSalesInvoicesDirect,
fetchSupplierInvoicesDirect,
} from '@/lib/providers/provider-data-fetcher'
// ── Consent lifecycle (direct Supabase) ─────────────────────────────
export async function createConsent(
companyId: string,
provider: ProviderName,
name: string,
orgNumber?: string,
companyName?: string,
): Promise<ConsentRecord> {
const supabase = createServiceClient()
const { data, error } = await supabase
.from('provider_consents')
.insert({
company_id: companyId,
name,
provider,
org_number: orgNumber,
company_name: companyName,
status: 0, // Created
})
.select('*')
.single()
if (error || !data) {
throw new Error(`Failed to create consent: ${error?.message}`)
}
return {
id: data.id,
name: data.name,
provider: data.provider as ProviderName,
status: data.status,
orgNumber: data.org_number,
companyName: data.company_name,
}
}
export async function listConsents(companyId: string): Promise<ConsentRecord[]> {
const supabase = createServiceClient()
const { data, error } = await supabase
.from('provider_consents')
.select('*')
.eq('company_id', companyId)
.in('status', [0, 1]) // Created or Accepted
.order('created_at', { ascending: false })
if (error) {
throw new Error(`Failed to list consents: ${error.message}`)
}
return (data ?? []).map(d => ({
id: d.id,
name: d.name,
provider: d.provider as ProviderName,
status: d.status,
orgNumber: d.org_number,
companyName: d.company_name,
createdAt: d.created_at,
updatedAt: d.updated_at,
}))
}
export async function getConsent(consentId: string): Promise<ConsentRecord> {
const supabase = createServiceClient()
const { data, error } = await supabase
.from('provider_consents')
.select('*')
.eq('id', consentId)
.single()
if (error || !data) {
throw new Error(`Consent not found: ${error?.message}`)
}
return {
id: data.id,
name: data.name,
provider: data.provider as ProviderName,
status: data.status,
orgNumber: data.org_number,
companyName: data.company_name,
}
}
export async function deleteConsent(consentId: string): Promise<void> {
const supabase = createServiceClient()
// Delete tokens first (cascade should handle this, but be explicit)
await supabase.from('provider_consent_tokens').delete().eq('consent_id', consentId)
await supabase.from('provider_otc').delete().eq('consent_id', consentId)
const { error } = await supabase
.from('provider_consents')
.delete()
.eq('id', consentId)
if (error) {
throw new Error(`Failed to delete consent: ${error.message}`)
}
}
export async function generateOtc(
consentId: string,
expiresInMinutes: number = 60,
): Promise<OtcResponse> {
const supabase = createServiceClient()
const code = crypto.randomUUID().replace(/-/g, '').slice(0, 16)
const expiresAt = new Date(Date.now() + expiresInMinutes * 60 * 1000).toISOString()
const { error } = await supabase
.from('provider_otc')
.insert({
code,
consent_id: consentId,
expires_at: expiresAt,
})
if (error) {
throw new Error(`Failed to generate OTC: ${error.message}`)
}
return { code, consentId, expiresAt }
}
// ── OAuth helpers (direct provider calls) ───────────────────────────
export async function getAuthUrl(
provider: ProviderName,
state?: string,
redirectUri?: string,
): Promise<{ url: string }> {
const config = getOAuthConfig(provider)
// Override redirect URI if provided (extension callback URL)
const effectiveConfig = redirectUri
? { ...config, redirectUri }
: config
if (provider === 'fortnox') {
const url = buildFortnoxAuthUrl(effectiveConfig, { state })
return { url }
}
if (provider === 'visma') {
const url = buildVismaAuthUrl(effectiveConfig, { state })
return { url }
}
throw new Error(`OAuth is not supported for provider: ${provider}`)
}
export async function exchangeAuthToken(
consentId: string,
provider: ProviderName,
code: string,
redirectUri?: string,
): Promise<{ success: boolean; consentId: string }> {
const config = getOAuthConfig(provider)
const effectiveConfig = redirectUri ? { ...config, redirectUri } : config
const supabase = createServiceClient()
let tokenResponse: { access_token: string; refresh_token: string; expires_in: number }
if (provider === 'fortnox') {
tokenResponse = await exchangeFortnoxCode(effectiveConfig, code)
} else if (provider === 'visma') {
tokenResponse = await exchangeVismaCode(effectiveConfig, code)
} else {
throw new Error(`OAuth exchange not supported for provider: ${provider}`)
}
const expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString()
// Store tokens
await supabase
.from('provider_consent_tokens')
.upsert({
consent_id: consentId,
provider,
access_token: tokenResponse.access_token,
refresh_token: tokenResponse.refresh_token,
token_expires_at: expiresAt,
})
// Mark consent as accepted
await supabase
.from('provider_consents')
.update({ status: 1 })
.eq('id', consentId)
return { success: true, consentId }
}
export async function submitProviderToken(
consentId: string,
provider: ProviderName,
apiToken: string,
companyId?: string,
): Promise<{ success: boolean; consentId: string }> {
const supabase = createServiceClient()
let accessToken = apiToken
let tokenExpiresAt: string | null = null
// BL uses client credentials — get a real token
if (provider === 'bjornlunden') {
const tokenResponse = await refreshBjornLundenToken()
accessToken = tokenResponse.access_token
tokenExpiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString()
}
// Store tokens
await supabase
.from('provider_consent_tokens')
.upsert({
consent_id: consentId,
provider,
access_token: accessToken,
refresh_token: null,
token_expires_at: tokenExpiresAt,
provider_company_id: companyId,
})
// Mark consent as accepted
await supabase
.from('provider_consents')
.update({ status: 1 })
.eq('id', consentId)
return { success: true, consentId }
}
@@ -4,16 +4,28 @@
"exportName": "arcimMigrationExtension",
"entryPoint": "@/extensions/general/arcim-migration",
"workspace": "@/components/extensions/general/ArcimMigrationWorkspace",
"requiredEnvVars": ["ARCIM_SYNC_GATEWAY_URL", "ARCIM_SYNC_API_KEY"],
"optionalEnvVars": [],
"npmDependencies": [],
"requiredEnvVars": [],
"optionalEnvVars": [
"FORTNOX_CLIENT_ID",
"FORTNOX_CLIENT_SECRET",
"FORTNOX_REDIRECT_URI",
"VISMA_CLIENT_ID",
"VISMA_CLIENT_SECRET",
"VISMA_REDIRECT_URI",
"BRIOX_CLIENT_ID",
"BJORN_LUNDEN_CLIENT_ID",
"BJORN_LUNDEN_CLIENT_SECRET",
"UPSTASH_REDIS_REST_URL",
"UPSTASH_REDIS_REST_TOKEN"
],
"npmDependencies": ["@upstash/redis", "@upstash/ratelimit"],
"definition": {
"name": "Systemmigration (Arcim Sync)",
"name": "Systemmigration",
"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."
"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 direkt med leverantören."
}
}
+26 -190
View File
@@ -1,198 +1,34 @@
/**
* Types for the Arcim Sync migration extension.
* Types for the provider 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.
* DTO types are now imported from the canonical source at lib/providers/dto.ts
* instead of being duplicated here.
*/
// ── Arcim Sync canonical DTOs (subset we consume) ──────────────────
// Re-export canonical DTOs used by entity-mapper and migration-orchestrator
export type {
AmountType,
PostalAddress,
Contact,
PartyIdentification,
PartyLegalEntity,
PartyDto,
PaginatedResponse,
TaxSubtotalDto,
TaxTotalDto,
LegalMonetaryTotalDto,
PaymentStatusDto,
CompanyInformationDto,
CustomerDto,
SupplierDto,
InvoiceStatusCode,
SalesInvoiceLineDto,
SalesInvoiceDto,
SupplierInvoiceLineDto,
SupplierInvoiceDto,
} from '@/lib/providers/dto'
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
}
export type { CustomerType as ArcimCustomerType } from '@/lib/providers/dto'
// ── Supported providers ─────────────────────────────────────────────