Psu type configuration (#248)

* feat: implement salary module with personnummer encryption, salary entries, tax tables, and AGI tracking

- Added personnummer encryption and decryption functions for secure storage.
- Created salary entries handling for journal entries including gross salary, tax withholding, and employer contributions.
- Implemented tax table lookup functionality for calculating tax amounts based on monthly income.
- Developed SQL migration for salary module including tables for payroll configuration, tax rates, employees, salary runs, salary run employees, salary line items, and AGI declarations.
- Established row-level security policies for all new tables to ensure company-scoped access.

* feat: add salary calculation modules for 2026

- Implemented engångsskatt calculation for one-time payments with tax brackets.
- Added löneväxling functionality for salary sacrifice to pension, including employer savings and warnings.
- Created pain.001 generator for salary batch payments in compliance with Swedish banking standards.
- Developed PDF template for payslips, including detailed breakdowns and employer costs.
- Generated seed data for Swedish tax tables for 2026, including SQL insert statements.
- Implemented traktamente calculations for per diem and mileage allowances, adhering to Skatteverket regulations.
- Added seed script for populating tax tables in the database.

* feat: Update meal reduction percentages in traktamente calculation

fix: Remove obsolete seed script for 2026 tax tables

feat: Extend SalaryRunStatus type to include 'corrected' status

feat: Implement KU10 XML generation endpoint for annual employee income statements

feat: Add endpoint for creating corrections to booked salary runs

feat: Implement endpoint for sending payslip PDFs to employees

feat: Create KU10 XML generator for annual reporting

feat: Add salary transaction matcher for auto-linking bank transactions to salary entries

chore: Add database migration for salary correction support

* feat: replace select elements with custom Select component for employment and salary types

* feat: enhance salary calculations with pension entry and avgifter category support

* feat: enhance banking settings with PSU type detection and error handling

* fix: improve error handling for bank connection and update access denial message
This commit is contained in:
Mattsson
2026-04-15 13:48:08 +02:00
committed by GitHub
parent 04dbb31d7e
commit d484c341a4
6 changed files with 114 additions and 17 deletions
+18 -2
View File
@@ -17,6 +17,8 @@ export default function BankingSettingsPage() {
const router = useRouter()
const { toast } = useToast()
const [bankConnectionError, setBankConnectionError] = useState<string | null>(null)
const [failedBankName, setFailedBankName] = useState<string | null>(null)
const [isAccessDenied, setIsAccessDenied] = useState(false)
const syncInitiatedRef = useRef(false)
const abortControllerRef = useRef<AbortController | null>(null)
const unmountedRef = useRef(false)
@@ -93,13 +95,18 @@ export default function BankingSettingsPage() {
}
if (bankError) {
const errorMsg = decodeURIComponent(bankError)
let errorMsg: string
try { errorMsg = decodeURIComponent(bankError) } catch { errorMsg = bankError }
const bankName = searchParams.get('bank_name')
const errorCode = searchParams.get('bank_error_code')
toast({
title: 'Anslutning misslyckades',
description: errorMsg,
variant: 'destructive',
})
setBankConnectionError(errorMsg)
if (bankName) setFailedBankName(bankName)
if (errorCode === 'access_denied') setIsAccessDenied(true)
router.replace('/settings/banking')
}
}, [searchParams, router, toast])
@@ -111,12 +118,21 @@ export default function BankingSettingsPage() {
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-destructive" />
<div className="flex-1">
<p className="text-sm font-medium text-destructive">{bankConnectionError}</p>
{isAccessDenied && failedBankName && (
<p className="mt-1 text-sm text-muted-foreground">
{failedBankName} nekade åtkomst. Om du använder ett privatkonto kan du prova att ansluta med kontotypen &quot;Privatkonto&quot; i bankväljaren nedan.
</p>
)}
<p className="mt-1 text-sm text-muted-foreground">
Du kan också <Link href="/import?mode=bank" className="underline hover:text-foreground">importera transaktioner via bankfil</Link> istället.
</p>
</div>
<button
onClick={() => setBankConnectionError(null)}
onClick={() => {
setBankConnectionError(null)
setFailedBankName(null)
setIsAccessDenied(false)
}}
className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground"
aria-label="Stäng"
>
@@ -54,6 +54,14 @@ export async function GET(request: Request) {
.from('bank_connections')
.update({ status: 'error', error_message: errorMessage, oauth_state: null })
.eq('id', pendingConn.id)
// Include bank name and error code in redirect so the UI can offer PSU type retry
const params = new URLSearchParams({
bank_error: errorMessage,
...(pendingConn.bank_name ? { bank_name: pendingConn.bank_name } : {}),
...(error === 'access_denied' ? { bank_error_code: error } : {}),
})
return NextResponse.redirect(`${baseUrl}/settings/banking?${params.toString()}`)
}
} catch (cleanupError) {
console.error('[enable-banking] Failed to clean up pending bank connection:', cleanupError)
@@ -20,6 +20,7 @@ const POPULAR_SWEDISH_BANKS = [
interface BankSelectorProps {
onConnect: (bank: Bank) => void
onPsuTypeDetected?: (psuType: 'personal' | 'business') => void
isConnecting?: boolean
connectingBankName?: string | null
className?: string
@@ -89,6 +90,7 @@ function BankCard({ bank, isConnecting, connectingBankName, onConnect }: {
export function BankSelector({
onConnect,
onPsuTypeDetected,
isConnecting = false,
connectingBankName = null,
className,
@@ -111,6 +113,9 @@ export function BankSelector({
if (data.sandbox !== undefined) {
setIsSandbox(data.sandbox)
}
if (data.psu_type && onPsuTypeDetected) {
onPsuTypeDetected(data.psu_type)
}
} catch {
setError('Kunde inte ladda banker')
} finally {
@@ -118,7 +123,8 @@ export function BankSelector({
}
}
fetchBanks()
}, [])
// eslint-disable-next-line react-hooks/exhaustive-deps -- onPsuTypeDetected is a stable setter, only run on mount
}, [onPsuTypeDetected])
const filteredBanks = banks.filter((bank) =>
bank.name.toLowerCase().includes(searchQuery.toLowerCase())
@@ -7,6 +7,7 @@ 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 { cn } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
import { useCompany } from '@/contexts/CompanyContext'
import { BankSelector, type Bank } from './BankSelector'
@@ -31,6 +32,7 @@ export default function BankingSettingsPanel() {
const connectingRef = useRef(false)
const [isLoading, setIsLoading] = useState(true)
const [showCsvFallback, setShowCsvFallback] = useState(false)
const [psuType, setPsuType] = useState<'personal' | 'business'>('business')
useEffect(() => {
fetchConnections()
@@ -52,7 +54,7 @@ export default function BankingSettingsPanel() {
setIsLoading(false)
}
async function handleConnectBank(bank: Bank) {
async function handleConnectBank(bank: Bank, psuTypeOverride?: 'personal' | 'business') {
if (connectingRef.current) return
connectingRef.current = true
setIsConnecting(true)
@@ -62,12 +64,16 @@ export default function BankingSettingsPanel() {
console.log('[enable-banking] Initiating bank connection', {
bankName: bank.name,
bankCountry: bank.country,
psuTypeOverride,
})
const body: Record<string, string> = { aspsp_name: bank.name, aspsp_country: bank.country }
if (psuTypeOverride) body.psu_type = psuTypeOverride
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 }),
body: JSON.stringify(body),
})
const data = await response.json()
@@ -288,9 +294,45 @@ export default function BankingSettingsPanel() {
Välj din bank nedan för att koppla ditt konto via PSD2.
</CardDescription>
</CardHeader>
<CardContent>
<CardContent className="space-y-4">
{/* Account type selector */}
<div className="flex items-center gap-3">
<span className="text-sm text-muted-foreground">Kontotyp:</span>
<div className="inline-flex rounded-lg border border-border p-0.5">
<button
type="button"
onClick={() => setPsuType('business')}
className={cn(
'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
psuType === 'business'
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:text-foreground'
)}
>
Företagskonto
</button>
<button
type="button"
onClick={() => setPsuType('personal')}
className={cn(
'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
psuType === 'personal'
? 'bg-primary text-primary-foreground'
: 'text-muted-foreground hover:text-foreground'
)}
>
Privatkonto
</button>
</div>
</div>
{psuType === 'personal' && (
<p className="text-xs text-muted-foreground">
Välj Privatkonto om du använder ditt personliga bankkonto för din verksamhet (vanligt för enskild firma).
</p>
)}
<BankSelector
onConnect={handleConnectBank}
onConnect={(bank) => handleConnectBank(bank, psuType)}
onPsuTypeDetected={setPsuType}
isConnecting={isConnecting}
connectingBankName={connectingBankName}
/>
+31 -6
View File
@@ -40,14 +40,27 @@ export const enableBankingExtension: Extension = {
handler: async (_request: Request, ctx?: ExtensionContext) => {
const log = ctx?.log ?? console
try {
const aspsps = await getASPSPs('SE')
// Detect PSU type from company entity_type
let psuType: 'personal' | 'business' = 'business'
if (ctx?.companyId && ctx?.supabase) {
const { data: company } = await ctx.supabase
.from('companies')
.select('entity_type')
.eq('id', ctx.companyId)
.single()
if (company?.entity_type === 'enskild_firma') {
psuType = 'personal'
}
}
const aspsps = await getASPSPs('SE', psuType)
const banks = aspsps.map((aspsp: ASPSP) => ({
name: aspsp.name,
country: aspsp.country,
logo: aspsp.logo,
bic: aspsp.bic,
}))
return NextResponse.json({ banks, sandbox: isSandboxMode() })
return NextResponse.json({ banks, psu_type: psuType, sandbox: isSandboxMode() })
} catch (error) {
log.error('Error fetching banks:', error)
return NextResponse.json({
@@ -74,7 +87,7 @@ export const enableBankingExtension: Extension = {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { aspsp_name, aspsp_country } = await request.json()
const { aspsp_name, aspsp_country, psu_type: explicitPsuType } = await request.json()
if (!aspsp_name || !aspsp_country) {
return NextResponse.json(
@@ -84,9 +97,21 @@ export const enableBankingExtension: Extension = {
}
try {
// Always use 'business' PSU type — gnubok is accounting software,
// users connect business accounts regardless of entity type (AB or EF)
const psuType = 'business'
// Detect PSU type: explicit override > company entity_type > default 'business'
let psuType: 'personal' | 'business' = 'business'
if (explicitPsuType === 'personal' || explicitPsuType === 'business') {
psuType = explicitPsuType
} else {
const companyId = ctx?.companyId ?? user.id
const { data: company } = await supabase
.from('companies')
.select('entity_type')
.eq('id', companyId)
.single()
if (company?.entity_type === 'enskild_firma') {
psuType = 'personal'
}
}
log.info('[enable-banking] Starting bank connection', {
user_id: user.id,
@@ -221,13 +221,13 @@ async function authenticatedFetchWithRetry(
/**
* Get list of supported banks (ASPSPs) for a country
*/
export async function getASPSPs(country: string = 'SE'): Promise<ASPSP[]> {
const psuType = process.env.ENABLE_BANKING_PSU_TYPE || 'business'
export async function getASPSPs(country: string = 'SE', psuType?: 'personal' | 'business'): Promise<ASPSP[]> {
const resolvedPsuType = psuType || process.env.ENABLE_BANKING_PSU_TYPE || 'business'
const isSandbox = ENABLE_BANKING_API_URL.includes('tilisy')
const params = new URLSearchParams({
country,
sandbox: String(isSandbox),
psu_type: psuType,
psu_type: resolvedPsuType,
})
const response = await authenticatedFetchWithRetry(`/aspsps?${params.toString()}`)
@@ -238,7 +238,7 @@ export async function getASPSPs(country: string = 'SE'): Promise<ASPSP[]> {
statusText: response.statusText,
body,
country,
psuType,
psuType: resolvedPsuType,
sandbox: isSandbox,
apiUrl: ENABLE_BANKING_API_URL,
})