Invoicing & account-security polish bundle (#550)

* feat: invoicing & account-security polish bundle

Five independent improvements bundled to ship together:

- BankID/password lockout fix: BankID-only users could enroll MFA and
  brick themselves (Supabase requires AAL2 to change password or unenroll
  MFA, and AAL2 needs a password sign-in). New app_metadata.has_password
  flag tracks this; middleware gates /mfa/enroll behind it, /account/set-
  password is the unlock path, SecuritySettings shows a banner, and
  /api/account/password is the single write path that flips the flag.
  Backfill script for existing users.

- Swish invoice payment method: company_settings.swish + invoice_show_swish
  columns, validation in lib/api/schemas.ts (accepts 123XXXXXXX företag or
  07XXXXXXXX mobile, strips whitespace/hyphens), rendered on invoice PDFs.

- Send-reminders kill switch: per-company company_settings.send_invoice_
  reminders toggle in PdfPrintSettings/Automatisering. Reminder processor
  also tightened: positive status allowlist (sent + overdue) so terminal
  statuses can never match; skip when customer already responded via
  reminder link; race-window re-check before send.

- First-invoice logo prompt: one-shot dialog when creating the first
  invoice without a logo (issue #520). Self-limits via head-only count.

- SIE export opening-balance fallback: route IB through getOpeningBalances
  so the compute_prior_opening_balances RPC supplies #IB after multi-year
  imports where opening_balance_entry_id is intentionally NULL. Previously
  #IB silently went to zero and #UB collapsed to current-period movements.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(account-polish): address PR review feedback

- BankID-link path (extensions/general/tic/index.ts): read-merge-write
  app_metadata instead of passing { bankid_linked: true } alone.
  updateUserById REPLACES app_metadata wholesale, so the previous code
  would have wiped has_password for any user who later linked BankID,
  causing the set-password banner to (incorrectly) reappear and blocking
  the standard MFA enrollment button. The comment is now corrected.

- Middleware (lib/supabase/middleware.ts): thread inner returnTo through
  the /mfa/enroll → /account/set-password redirect so the user lands on
  their original destination after the full chain completes, not on /.

- safeReturnTo helper (lib/auth/safe-return-to.ts): replace the
  starts-with-/-but-not-// guard on mfa/enroll and set-password pages.
  The previous guard let /\evil.com and /@evil.com through. The new
  helper parses against a synthetic base origin and verifies it matches.

- set-password page (app/(auth)/account/set-password/page.tsx): remove
  CLAUDE.md design system violations — bg-gradient-to-b on page bg,
  inline shadow-md style on the card, space-y-5, font-medium on the h1,
  rounded-xl on the card. Flat surface, hairline border, font-display
  h1 per the design tokens.

- Swish dedup (lib/payments/swish.ts): extract normaliseSwish() and
  isValidSwish() helpers and use them in lib/api/schemas.ts,
  components/settings/BankDetailsForm.tsx, and the invoicing settings
  page. Single source of truth for the regex.

- Password route (app/api/account/password/route.ts): emit a structured
  success log so the audit pipeline can detect password-set events, not
  just failures.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-05-21 16:44:09 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 2879f6ed17
commit cc351158f8
32 changed files with 1327 additions and 76 deletions
@@ -0,0 +1,67 @@
'use client'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { LogoUpload } from '@/components/settings/LogoUpload'
interface FirstInvoiceLogoPromptProps {
open: boolean
onClose: () => void
logoUrl: string | null
onLogoUpdate: (url: string | null) => void
}
/**
* One-shot dialog offered after the user creates their first invoice and has
* no logo on file. Reuses the same LogoUpload control as settings, so the
* upload, MIME validation, and preview are identical to the canonical flow.
*
* The PDF reads logo_url live at render time, so uploading now still applies
* to the just-created invoice when it is later previewed or sent.
*/
export function FirstInvoiceLogoPrompt({
open,
onClose,
logoUrl,
onLogoUpdate,
}: FirstInvoiceLogoPromptProps) {
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="font-display text-xl tracking-tight">
Lägg till en logotyp?
</DialogTitle>
<DialogDescription>
Din första faktura är skapad. Vill du ladda upp en logotyp som
visas i sidhuvudet? Du kan ändra den senare i{' '}
<a
href="/settings/company"
className="underline underline-offset-2 hover:text-foreground"
>
Inställningar
</a>
.
</DialogDescription>
</DialogHeader>
<div className="py-2">
<LogoUpload logoUrl={logoUrl} onUpdate={onLogoUpdate} />
</div>
<DialogFooter>
<Button variant={logoUrl ? 'default' : 'ghost'} onClick={onClose}>
{logoUrl ? 'Klar' : 'Hoppa över'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+48 -19
View File
@@ -5,6 +5,7 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { BankNameCombobox } from '@/components/settings/BankNameCombobox'
import { validateBankgiroNumber, formatBankgiroNumber } from '@/lib/bankgiro/luhn'
import { normaliseSwish, isValidSwish } from '@/lib/payments/swish'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import type { CompanySettings } from '@/types'
@@ -16,6 +17,7 @@ export function BankDetailsForm({ settings }: BankDetailsFormProps) {
const [bankgiroError, setBankgiroError] = useState<string | null>(null)
const [clearingError, setClearingError] = useState<string | null>(null)
const [accountNumberError, setAccountNumberError] = useState<string | null>(null)
const [swishError, setSwishError] = useState<string | null>(null)
const hasBankingExtension = ENABLED_EXTENSION_IDS.has('enable-banking')
return (
@@ -77,25 +79,48 @@ export function BankDetailsForm({ settings }: BankDetailsFormProps) {
</div>
</div>
<div className="max-w-xs space-y-2">
<Label htmlFor="bankgiro">Bankgiro</Label>
<Input
id="bankgiro"
name="bankgiro"
placeholder="XXX-XXXX"
defaultValue={settings.bankgiro || ''}
onBlur={(e) => {
const val = e.target.value.trim()
if (!val) { setBankgiroError(null); return }
if (validateBankgiroNumber(val)) {
e.target.value = formatBankgiroNumber(val)
setBankgiroError(null)
} else {
setBankgiroError('Ogiltigt bankgironummer')
}
}}
/>
{bankgiroError && <p className="text-xs text-destructive">{bankgiroError}</p>}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="bankgiro">Bankgiro</Label>
<Input
id="bankgiro"
name="bankgiro"
placeholder="XXX-XXXX"
defaultValue={settings.bankgiro || ''}
onBlur={(e) => {
const val = e.target.value.trim()
if (!val) { setBankgiroError(null); return }
if (validateBankgiroNumber(val)) {
e.target.value = formatBankgiroNumber(val)
setBankgiroError(null)
} else {
setBankgiroError('Ogiltigt bankgironummer')
}
}}
/>
{bankgiroError && <p className="text-xs text-destructive">{bankgiroError}</p>}
</div>
<div className="space-y-2">
<Label htmlFor="swish">Swish</Label>
<Input
id="swish"
name="swish"
placeholder="123 XXX XX XX eller 07X XXX XX XX"
defaultValue={settings.swish || ''}
onBlur={(e) => {
const val = normaliseSwish(e.target.value)
if (!val) { setSwishError(null); e.target.value = ''; return }
if (isValidSwish(val)) {
e.target.value = val
setSwishError(null)
} else {
setSwishError('Ogiltigt Swish-nummer (företagsnummer 123XXXXXXX eller mobilnummer 07XXXXXXXX)')
}
}}
/>
{swishError && <p className="text-xs text-destructive">{swishError}</p>}
</div>
</div>
</section>
)
@@ -107,6 +132,7 @@ export function validateBankFields(formData: FormData): { field: string; message
const clearing = (formData.get('clearing_number') as string || '').trim()
const account = (formData.get('account_number') as string || '').trim()
const bankgiro = (formData.get('bankgiro') as string || '').trim()
const swish = normaliseSwish(formData.get('swish') as string)
if (clearing && !/^\d{4,5}$/.test(clearing)) {
errors.push({ field: 'clearing_number', message: 'Clearingnummer måste vara 4-5 siffror' })
@@ -117,5 +143,8 @@ export function validateBankFields(formData: FormData): { field: string; message
if (bankgiro && !validateBankgiroNumber(bankgiro)) {
errors.push({ field: 'bankgiro', message: 'Ogiltigt bankgironummer' })
}
if (swish && !isValidSwish(swish)) {
errors.push({ field: 'swish', message: 'Ogiltigt Swish-nummer (företagsnummer 123XXXXXXX eller mobilnummer 07XXXXXXXX)' })
}
return errors
}
+30
View File
@@ -110,6 +110,17 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
/>
</div>
<div className="flex items-center justify-between">
<div>
<Label>Visa Swish</Label>
<p className="text-xs text-muted-foreground">Visa Swish-nummer på fakturautskrift</p>
</div>
<Switch
checked={settings.invoice_show_swish ?? true}
onCheckedChange={(v) => saveToggle('invoice_show_swish', v)}
/>
</div>
<div className="flex items-center justify-between">
<div>
<Label>Visa logga</Label>
@@ -190,6 +201,25 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
/>
</div>
</div>
<div className="pt-6 space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Automatisering
</h2>
<div className="flex items-center justify-between">
<div>
<Label>Skicka automatiska påminnelser</Label>
<p className="text-xs text-muted-foreground">
Skicka påminnelser till kunder för försenade fakturor enligt din inställning för påminnelseintervall.
</p>
</div>
<Switch
checked={settings.send_invoice_reminders ?? true}
onCheckedChange={(v) => saveToggle('send_invoice_reminders', v)}
/>
</div>
</div>
</section>
)
}
+68 -14
View File
@@ -12,6 +12,7 @@ import { Loader2, ShieldCheck, ShieldOff, KeyRound } from 'lucide-react'
import { isMfaRequired } from '@/lib/auth/mfa'
import { isBankIdEnabled } from '@/lib/auth/bankid'
import { BankIdSettings } from '@/components/settings/BankIdSettings'
import { userHasPassword } from '@/lib/auth/has-password'
const isSelfHosted = process.env.NEXT_PUBLIC_SELF_HOSTED === 'true'
const mfaRequired = isMfaRequired()
@@ -25,19 +26,24 @@ export function SecuritySettings() {
const [isLoadingMfa, setIsLoadingMfa] = useState(true)
const [isUnenrolling, setIsUnenrolling] = useState(false)
const [mfaFactorId, setMfaFactorId] = useState<string | null>(null)
const [hasPassword, setHasPassword] = useState<boolean | null>(null)
const { toast } = useToast()
const router = useRouter()
const supabase = createClient()
useEffect(() => {
async function loadMfaStatus() {
const { data } = await supabase.auth.mfa.listFactors()
const verifiedFactor = data?.totp?.find(f => f.status === 'verified')
async function loadStatus() {
const [{ data: factors }, { data: userData }] = await Promise.all([
supabase.auth.mfa.listFactors(),
supabase.auth.getUser(),
])
const verifiedFactor = factors?.totp?.find(f => f.status === 'verified')
setHasMfa(!!verifiedFactor)
setMfaFactorId(verifiedFactor?.id ?? null)
setHasPassword(userData?.user ? userHasPassword(userData.user) : null)
setIsLoadingMfa(false)
}
loadMfaStatus()
loadStatus()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
@@ -72,12 +78,17 @@ export function SecuritySettings() {
}
try {
const { error } = await supabase.auth.updateUser({ password: newPassword })
const res = await fetch('/api/account/password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: newPassword }),
})
if (error) {
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string }
toast({
title: 'Kunde inte uppdatera lösenord',
description: error.message,
description: body.error || 'Försök igen senare.',
variant: 'destructive',
})
return
@@ -89,6 +100,7 @@ export function SecuritySettings() {
})
setNewPassword('')
setConfirmPassword('')
setHasPassword(true)
} catch {
toast({
title: 'Något gick fel',
@@ -136,7 +148,36 @@ export function SecuritySettings() {
return (
<div className="space-y-6">
{bankIdEnabled && <BankIdSettings />}
{/* Change password */}
{/* BankID-only users with no password — banner above everything else */}
{hasPassword === false && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<KeyRound className="h-4 w-4" />
Sätt ett lösenord
</CardTitle>
<CardDescription>
Du loggade in med BankID och har inget lösenord ännu. Sätt ett
lösenord för att kunna aktivera 2FA eller logga in när BankID
inte är tillgängligt.
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={() =>
router.push('/account/set-password?returnTo=/settings/account')
}
>
Sätt lösenord
</Button>
</CardContent>
</Card>
)}
{/* Change password — hidden when the user has no password (the banner
above handles the set-initial-password flow). */}
{hasPassword !== false && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
@@ -190,6 +231,7 @@ export function SecuritySettings() {
</form>
</CardContent>
</Card>
)}
{/* MFA — hidden for self-hosted */}
{!isSelfHosted && (
@@ -257,12 +299,24 @@ export function SecuritySettings() {
</p>
</div>
</div>
<Button
onClick={() => router.push(`/mfa/enroll?returnTo=${encodeURIComponent('/settings/account')}`)}
>
<ShieldCheck className="mr-2 h-4 w-4" />
Aktivera 2FA
</Button>
{hasPassword === false ? (
<Button
onClick={() =>
router.push(
'/account/set-password?returnTo=/mfa/enroll',
)
}
>
Sätt ett lösenord först
</Button>
) : (
<Button
onClick={() => router.push(`/mfa/enroll?returnTo=${encodeURIComponent('/settings/account')}`)}
>
<ShieldCheck className="mr-2 h-4 w-4" />
Aktivera 2FA
</Button>
)}
</div>
)}
</CardContent>