* feat: multi-tenant company refactor (GNU-19) Introduce companies table, company_members, and user_preferences to support multiple companies per user. All data scoping changes from user_id to company_id across the entire codebase. Key changes: - Database migration: new tables, company_id on 40+ tables, backfill, RLS rewrite from user_id to company-member-based, updated RPCs - Types: Company, CompanyMember, CompanyRole, UserPreferences types; company_id added to all entity interfaces; companyId on all events - Engine: all 7 core functions take companyId; storno, period, year-end services updated; 16 report generators updated - Middleware: company context resolution (cookie → prefs → first company) - API routes: ~120 routes updated with requireCompanyId() - Frontend: CompanyProvider context, layout/dashboard/onboarding updated - Extensions: context factory, 9 extensions, all lib files updated - Tests: 1880 tests passing, all helpers updated with company_id defaults Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add database migrations for multi-tenant company and team system (GNU-19) Adds company_invitations, company creation RPC, team_members, account deletion RPC, and teams table refactor migrations. Updates base multi-tenant migration with cascading FKs and onboarding_step column. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add team types and update core infrastructure for multi-tenancy (GNU-19) Adds TeamRole, MemberSource, and Team types. Refactors Supabase service client to be stateless, updates middleware for team-aware routing, extends CompanyContext with team/role fields, and updates extension service types to accept companyId. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: thread company_id through business logic functions (GNU-19) Replaces user_id scoping with company_id across all lib modules: bookkeeping, documents, transactions, invoices, reconciliation, tax, deadlines, and import. Updates corresponding tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: thread company_id through API routes and extensions (GNU-19) Updates all existing API routes to extract and pass companyId. Updates enable-banking and arcim-migration extensions for company-scoped transaction ingestion and sync. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add company and team management API routes (GNU-19) Adds CRUD endpoints for company members, company invitations, team members, and team invitations. Includes invite token utilities, email templates, and company switch server action. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add team/company UI components, pages, and dashboard updates (GNU-19) Adds CompanySwitcher, ConsultantEmptyState, Step0RoleChoice, company members and team management panels. Updates dashboard layout for team-aware routing, onboarding for multi-step role choice, and auth callback for team invite acceptance. Ignores supabase/.branches/. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add null guards for company in import page (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move appUrl declaration to outer scope in invite route (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add optional chaining for company.name in members section (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add optional chaining for second company.name in members section (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add null guards for company in extension components (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: pass companyId to executeSIEImport in arcim-migration extension (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update tests to use companyId instead of userId and improve type handling --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
320 lines
10 KiB
TypeScript
320 lines
10 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useRef } from 'react'
|
|
import Link from 'next/link'
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Button } from '@/components/ui/button'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
|
import { Loader2, Upload } from 'lucide-react'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { useCompany } from '@/contexts/CompanyContext'
|
|
import { BankSelector, type Bank } from './BankSelector'
|
|
import { BankConnectionStatus } from './BankConnectionStatus'
|
|
import type { BankConnection } from '@/types'
|
|
|
|
/**
|
|
* Self-contained banking settings panel for the enable-banking extension.
|
|
* Loaded dynamically by the settings panel registry.
|
|
*/
|
|
export default function BankingSettingsPanel() {
|
|
const { toast } = useToast()
|
|
const supabase = createClient()
|
|
|
|
const { dialogProps, confirm } = useDestructiveConfirm()
|
|
const { company } = useCompany()
|
|
|
|
const [bankConnections, setBankConnections] = useState<BankConnection[]>([])
|
|
const [syncingConnectionId, setSyncingConnectionId] = useState<string | null>(null)
|
|
const [isConnecting, setIsConnecting] = useState(false)
|
|
const [connectingBankName, setConnectingBankName] = useState<string | null>(null)
|
|
const connectingRef = useRef(false)
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
const [showCsvFallback, setShowCsvFallback] = useState(false)
|
|
|
|
useEffect(() => {
|
|
fetchConnections()
|
|
}, [])
|
|
|
|
async function fetchConnections() {
|
|
setIsLoading(true)
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) return
|
|
if (!company) return
|
|
|
|
const { data: connections } = await supabase
|
|
.from('bank_connections')
|
|
.select('*')
|
|
.eq('company_id', company.id)
|
|
.order('created_at', { ascending: false })
|
|
|
|
setBankConnections(connections || [])
|
|
setIsLoading(false)
|
|
}
|
|
|
|
async function handleConnectBank(bank: Bank) {
|
|
if (connectingRef.current) return
|
|
connectingRef.current = true
|
|
setIsConnecting(true)
|
|
setConnectingBankName(bank.name)
|
|
|
|
try {
|
|
console.log('[enable-banking] Initiating bank connection', {
|
|
bankName: bank.name,
|
|
bankCountry: bank.country,
|
|
})
|
|
|
|
const response = await fetch('/api/extensions/ext/enable-banking/connect', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ aspsp_name: bank.name, aspsp_country: bank.country }),
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
if (!response.ok) {
|
|
console.error('[enable-banking] Connect request failed', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
error: data.error,
|
|
bankName: bank.name,
|
|
})
|
|
throw new Error(data.error)
|
|
}
|
|
|
|
console.log('[enable-banking] Redirecting to bank authorization', {
|
|
connectionId: data.connection_id,
|
|
hasAuthUrl: !!data.authorization_url,
|
|
})
|
|
window.location.href = data.authorization_url
|
|
} catch (error) {
|
|
console.error('[enable-banking] Connect flow failed', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
bankName: bank.name,
|
|
})
|
|
toast({
|
|
title: 'Fel',
|
|
description: error instanceof Error ? error.message : 'Kunde inte ansluta bank',
|
|
variant: 'destructive',
|
|
})
|
|
connectingRef.current = false
|
|
setIsConnecting(false)
|
|
setConnectingBankName(null)
|
|
setShowCsvFallback(true)
|
|
}
|
|
}
|
|
|
|
async function handleSyncTransactions(connectionId: string) {
|
|
setSyncingConnectionId(connectionId)
|
|
|
|
try {
|
|
console.log('[enable-banking] Starting sync', { connectionId })
|
|
|
|
const response = await fetch('/api/extensions/ext/enable-banking/sync', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ connection_id: connectionId }),
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
if (!response.ok) {
|
|
console.error('[enable-banking] Sync request failed', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
error: data.error,
|
|
connectionId,
|
|
})
|
|
throw new Error(data.error)
|
|
}
|
|
|
|
console.log('[enable-banking] Sync completed', {
|
|
connectionId,
|
|
imported: data.imported,
|
|
duplicates: data.duplicates,
|
|
})
|
|
|
|
toast({
|
|
title: 'Synkronisering klar',
|
|
description: `${data.imported} nya transaktioner importerade`,
|
|
})
|
|
|
|
setShowCsvFallback(false)
|
|
fetchConnections()
|
|
} catch (error) {
|
|
console.error('[enable-banking] Sync flow failed', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
connectionId,
|
|
})
|
|
toast({
|
|
title: 'Fel',
|
|
description: error instanceof Error ? error.message : 'Synkronisering misslyckades',
|
|
variant: 'destructive',
|
|
})
|
|
setShowCsvFallback(true)
|
|
}
|
|
|
|
setSyncingConnectionId(null)
|
|
}
|
|
|
|
async function handleDisconnectBank(connectionId: string) {
|
|
const ok = await confirm({
|
|
title: 'Koppla bort bank?',
|
|
description: 'PSD2-samtycket kommer återkallas. Befintliga transaktioner påverkas inte.',
|
|
confirmLabel: 'Koppla bort',
|
|
variant: 'warning',
|
|
})
|
|
if (!ok) return
|
|
|
|
try {
|
|
console.log('[enable-banking] Disconnecting bank', { connectionId })
|
|
|
|
const response = await fetch('/api/extensions/ext/enable-banking/disconnect', {
|
|
method: 'DELETE',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ connection_id: connectionId }),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const data = await response.json()
|
|
console.error('[enable-banking] Disconnect request failed', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
error: data.error,
|
|
connectionId,
|
|
})
|
|
throw new Error(data.error || 'Disconnect failed')
|
|
}
|
|
|
|
console.log('[enable-banking] Bank disconnected', { connectionId })
|
|
toast({
|
|
title: 'Bank bortkopplad',
|
|
description: 'Bankanslutningen och PSD2-samtycket har återkallats',
|
|
})
|
|
fetchConnections()
|
|
} catch (error) {
|
|
console.error('[enable-banking] Disconnect flow failed', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
connectionId,
|
|
})
|
|
toast({
|
|
title: 'Fel',
|
|
description: error instanceof Error ? error.message : 'Kunde inte koppla bort bank',
|
|
variant: 'destructive',
|
|
})
|
|
}
|
|
}
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="flex items-center justify-center h-32">
|
|
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
|
</div>
|
|
)
|
|
}
|
|
|
|
const activeConnections = bankConnections.filter((c) => c.status === 'active')
|
|
const actionRequiredConnections = bankConnections.filter((c) => ['expired', 'error'].includes(c.status))
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<DestructiveConfirmDialog {...dialogProps} />
|
|
|
|
{/* Persistent CSV fallback after connection/sync failure */}
|
|
{showCsvFallback && (
|
|
<div className="flex items-center gap-3 rounded-lg border border-border bg-muted/50 p-4">
|
|
<Upload className="h-5 w-5 shrink-0 text-muted-foreground" />
|
|
<p className="flex-1 text-sm text-muted-foreground">
|
|
Har du problem med bankanslutningen? Du kan importera transaktioner manuellt via bankfil.
|
|
</p>
|
|
<Button variant="outline" size="sm" asChild>
|
|
<Link href="/import?mode=bank">Importera bankfil</Link>
|
|
</Button>
|
|
</div>
|
|
)}
|
|
|
|
{/* Action required — expired/error connections */}
|
|
{actionRequiredConnections.length > 0 && (
|
|
<Card className="border-warning/30">
|
|
<CardHeader>
|
|
<CardTitle>Åtgärd krävs</CardTitle>
|
|
<CardDescription>
|
|
Dessa anslutningar behöver uppmärksamhet.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
{actionRequiredConnections.map((connection) => (
|
|
<BankConnectionStatus
|
|
key={connection.id}
|
|
connection={connection}
|
|
onSync={handleSyncTransactions}
|
|
onDisconnect={handleDisconnectBank}
|
|
onReconnect={handleConnectBank}
|
|
isSyncing={syncingConnectionId === connection.id}
|
|
/>
|
|
))}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Connected banks */}
|
|
{activeConnections.length > 0 && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Anslutna banker</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
{activeConnections.map((connection) => (
|
|
<BankConnectionStatus
|
|
key={connection.id}
|
|
connection={connection}
|
|
onSync={handleSyncTransactions}
|
|
onDisconnect={handleDisconnectBank}
|
|
isSyncing={syncingConnectionId === connection.id}
|
|
/>
|
|
))}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Connect new bank */}
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Anslut ny bank</CardTitle>
|
|
<CardDescription>
|
|
Välj din bank nedan för att koppla ditt konto via PSD2.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<BankSelector
|
|
onConnect={handleConnectBank}
|
|
isConnecting={isConnecting}
|
|
connectingBankName={connectingBankName}
|
|
/>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
{/* Info about PSD2 */}
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Om bankintegration (PSD2)</CardTitle>
|
|
<CardDescription>
|
|
Automatisk import av transaktioner via PSD2 open banking.
|
|
Samtycket gäller i 90 dagar och behöver sedan förnyas.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<p className="text-sm text-muted-foreground">
|
|
Vi använder säker bankintegration (PSD2). Vi kan endast läsa transaktioner,
|
|
aldrig flytta pengar. Du kan också importera transaktioner manuellt via
|
|
bankfiler på importsidan.
|
|
</p>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
)
|
|
}
|