Feat/cloud backup (#277)

* feat: cloud backup to Google Drive + full-archive all-scope

Adds a cloud-backup extension that uploads a full-company backup ZIP to
the user's own Google Drive via OAuth (drive.file scope only). Refresh
tokens are AES-256-GCM encrypted before being stored in extension_data.

The full-archive export gains a scope=all mode for whole-company
backups (per-period SIE under sie/, per-period rapporter/ subfolders,
flat dokument/ manifest tagged with fiscal_period_id). An 80 MB size
guard short-circuits generation before the platform response limit.

Also fixes a latent bug in lib/core/audit/audit-service.ts where the
parameter was named userId while the query filtered by company_id; the
audit-trail API route was passing user.id so audit queries returned
empty unless user and company shared a UUID.

Drive-by: scope the dashboard "fresh start" localStorage key per
companyId so dismissing the setup checklist in one company no longer
carries over to others.

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

* fix: address review comments on cloud backup + archive export

- Extend audit trail to_date to end-of-day so last-day entries aren't
  silently excluded from period-scoped archives.
- Apply 413 size-limit guard regardless of include_documents, using the
  overhead-only figure when documents are excluded.
- Use crypto.randomUUID() for Drive multipart boundary to eliminate any
  collision risk with ZIP payload bytes.

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

* fix: migrate legacy setup-gate localStorage keys on dashboard

Users who previously dismissed the setup checklist via the old global
erp_setup_fresh_start or erp_checklist_dismissed keys were re-gated after
the switch to a company-scoped key. Fall back to the legacy keys on read
and migrate them to the scoped key on first hit.

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

* fix: update customer email handling and anonymization rules in supportmail-to-ticket skill

* test: update audit trail to_date expectation for end-of-day timestamp

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:
Mattsson
2026-04-20 10:49:59 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 2ea5a72b3d
commit d708a85d4c
34 changed files with 2900 additions and 314 deletions
+15 -7
View File
@@ -24,10 +24,11 @@ import { resolveIcon } from '@/lib/extensions/icon-resolver'
import type { QuickActionDefinition } from '@/lib/extensions/types'
import type { CompanySettings, Deadline, ReceiptQueueSummary, OnboardingProgress } from '@/types'
const SETUP_FRESH_START_KEY = 'erp_setup_fresh_start'
const setupFreshStartKey = (companyId: string) => `erp_setup_fresh_start:${companyId}`
interface DashboardContentProps {
firstName?: string | null
companyId: string
settings: CompanySettings | null
summary: {
ytd: { income: number; expenses: number; net: number }
@@ -49,7 +50,7 @@ interface DashboardContentProps {
onboardingProgress?: OnboardingProgress
}
export default function DashboardContent({ firstName, settings, summary, onboardingProgress }: DashboardContentProps) {
export default function DashboardContent({ firstName, companyId, settings, summary, onboardingProgress }: DashboardContentProps) {
const [showAllAlerts, setShowAllAlerts] = useState(false)
const [showMore, setShowMore] = useState(false)
const [greeting, setGreeting] = useState('Hej')
@@ -68,16 +69,23 @@ export default function DashboardContent({ firstName, settings, summary, onboard
setSetupGateActive(false)
return
}
const freshStart = localStorage.getItem(SETUP_FRESH_START_KEY) === 'true'
const oldDismissed = localStorage.getItem('erp_checklist_dismissed') === 'true'
if (freshStart || oldDismissed) setSetupGateActive(false)
}, [needsSetup])
const scopedKey = setupFreshStartKey(companyId)
const freshStart = localStorage.getItem(scopedKey) === 'true'
const legacyFreshStart = localStorage.getItem('erp_setup_fresh_start') === 'true'
const legacyDismissed = localStorage.getItem('erp_checklist_dismissed') === 'true'
if (freshStart || legacyFreshStart || legacyDismissed) {
if (!freshStart) {
localStorage.setItem(scopedKey, 'true')
}
setSetupGateActive(false)
}
}, [needsSetup, companyId])
if (setupGateActive) {
return (
<NewUserChecklist
onFreshStart={() => {
localStorage.setItem(SETUP_FRESH_START_KEY, 'true')
localStorage.setItem(setupFreshStartKey(companyId), 'true')
setSetupGateActive(false)
}}
/>
@@ -0,0 +1,25 @@
'use client'
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
import { Button } from '@/components/ui/button'
import { Cloud, Settings } from 'lucide-react'
import Link from 'next/link'
export default function CloudBackupWorkspace(_props: WorkspaceComponentProps) {
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<Cloud className="h-12 w-12 text-muted-foreground/40 mb-4" />
<h3 className="text-lg font-medium text-foreground">Molnsynkronisering</h3>
<p className="text-sm text-muted-foreground mt-1 max-w-md">
Koppla ditt Google Drive-konto under Säkerhetsbackup för att synka arkiv till din
egen molnlagring.
</p>
<Button asChild variant="outline" className="mt-4">
<Link href="/settings/backup">
<Settings className="mr-2 h-4 w-4" />
Gå till säkerhetsbackup
</Link>
</Button>
</div>
)
}
+359
View File
@@ -0,0 +1,359 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { useToast } from '@/components/ui/use-toast'
import { useCompany } from '@/contexts/CompanyContext'
import { Cloud, Download, Info, Loader2 } from 'lucide-react'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { getSettingsPanel } from '@/lib/extensions/settings-panel-registry'
import type { FiscalPeriod } from '@/types'
const CloudBackupPanel = getSettingsPanel('cloud-backup')
const hasCloudBackup = ENABLED_EXTENSION_IDS.has('cloud-backup')
type Scope = 'all' | 'period'
interface EstimateResponse {
total_bytes: number
document_bytes: number
document_count: number
size_limit_bytes: number
within_limit: boolean
}
const LAST_DOWNLOAD_STORAGE_KEY = 'gnubok:last-backup-download'
export function BackupDownloadForm() {
const { toast } = useToast()
const { company } = useCompany()
const [scope, setScope] = useState<Scope>('all')
const [includeDocuments, setIncludeDocuments] = useState(true)
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
const [selectedPeriodId, setSelectedPeriodId] = useState<string>('')
const [estimate, setEstimate] = useState<EstimateResponse | null>(null)
const [isLoadingEstimate, setIsLoadingEstimate] = useState(false)
const [isDownloading, setIsDownloading] = useState(false)
const [lastDownloadedAt, setLastDownloadedAt] = useState<string | null>(null)
const storageKey = useMemo(
() => (company ? `${LAST_DOWNLOAD_STORAGE_KEY}:${company.id}` : null),
[company]
)
useEffect(() => {
if (!storageKey) return
setLastDownloadedAt(window.localStorage.getItem(storageKey))
}, [storageKey])
useEffect(() => {
let cancelled = false
async function loadPeriods() {
try {
const res = await fetch('/api/bookkeeping/fiscal-periods')
const { data } = await res.json()
if (cancelled) return
const sorted = (data || []) as FiscalPeriod[]
setPeriods(sorted)
if (sorted.length > 0 && !selectedPeriodId) {
setSelectedPeriodId(sorted[0].id)
}
} catch {
// silent: scope=all still works without periods loaded
}
}
loadPeriods()
return () => {
cancelled = true
}
// Intentionally run once on mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const estimateUrl = useMemo(() => {
const params = new URLSearchParams({ estimate: '1', scope })
if (scope === 'period' && selectedPeriodId) {
params.set('period_id', selectedPeriodId)
}
if (!includeDocuments) {
params.set('include_documents', 'false')
}
return `/api/reports/full-archive?${params.toString()}`
}, [scope, selectedPeriodId, includeDocuments])
useEffect(() => {
if (scope === 'period' && !selectedPeriodId) {
setEstimate(null)
return
}
let cancelled = false
setIsLoadingEstimate(true)
setEstimate(null)
;(async () => {
try {
const res = await fetch(estimateUrl)
if (!res.ok) return
const { data } = (await res.json()) as { data: EstimateResponse }
if (!cancelled) setEstimate(data)
} catch {
// leave estimate null; we still let users attempt the download
} finally {
if (!cancelled) setIsLoadingEstimate(false)
}
})()
return () => {
cancelled = true
}
}, [estimateUrl, scope, selectedPeriodId])
const downloadUrl = useMemo(() => {
const params = new URLSearchParams({ scope })
if (scope === 'period' && selectedPeriodId) {
params.set('period_id', selectedPeriodId)
}
if (!includeDocuments) {
params.set('include_documents', 'false')
}
return `/api/reports/full-archive?${params.toString()}`
}, [scope, selectedPeriodId, includeDocuments])
const handleDownload = useCallback(async () => {
if (scope === 'period' && !selectedPeriodId) return
setIsDownloading(true)
try {
const res = await fetch(downloadUrl)
if (!res.ok) {
if (res.status === 413) {
const body = await res.json().catch(() => ({}))
const sizeMb = body.size_bytes ? Math.round(body.size_bytes / (1024 * 1024)) : null
toast({
title: 'Arkivet är för stort för direktnedladdning',
description: sizeMb
? `Ditt arkiv är cirka ${sizeMb} MB. Exportera en period i taget tills vidare — automatisk molnsynkronisering kommer i senare version.`
: 'Exportera en period i taget tills vidare — automatisk molnsynkronisering kommer i senare version.',
variant: 'destructive',
})
return
}
const body = await res.json().catch(() => ({}))
throw new Error(body.error || 'Kunde inte skapa arkivet')
}
const blob = await res.blob()
const contentDisposition = res.headers.get('Content-Disposition') || ''
const match = contentDisposition.match(/filename="?([^";]+)"?/)
const filename = match?.[1] || 'arkiv.zip'
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
const now = new Date().toISOString()
if (storageKey) {
window.localStorage.setItem(storageKey, now)
setLastDownloadedAt(now)
}
toast({ title: 'Säkerhetsbackup skapad', description: filename })
} catch (err) {
toast({
title: 'Kunde inte skapa säkerhetsbackup',
description: err instanceof Error ? err.message : 'Försök igen.',
variant: 'destructive',
})
} finally {
setIsDownloading(false)
}
}, [downloadUrl, scope, selectedPeriodId, storageKey, toast])
const isOverLimit = !!estimate && !estimate.within_limit && includeDocuments
const canDownload = !isDownloading && !isOverLimit && (scope === 'all' || !!selectedPeriodId)
return (
<div className="space-y-8">
<Card>
<CardHeader>
<CardTitle>Skapa backup</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-2">
<Label>Omfattning</Label>
<div className="flex flex-col gap-2 sm:flex-row">
<ScopeRadio
checked={scope === 'all'}
onChange={() => setScope('all')}
label="Hela historiken"
description="Alla räkenskapsår och verifikationer"
recommended
/>
<ScopeRadio
checked={scope === 'period'}
onChange={() => setScope('period')}
label="En period"
description="Välj ett specifikt räkenskapsår"
/>
</div>
</div>
{scope === 'period' && (
<div className="space-y-2">
<Label htmlFor="backup-period">Räkenskapsår</Label>
<select
id="backup-period"
value={selectedPeriodId}
onChange={(e) => setSelectedPeriodId(e.target.value)}
className="flex h-10 w-full max-w-xs rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
disabled={periods.length === 0}
>
{periods.length === 0 && <option value="">Inga räkenskapsår</option>}
{periods.map((p) => (
<option key={p.id} value={p.id}>
{p.period_start} – {p.period_end}
</option>
))}
</select>
</div>
)}
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<Label htmlFor="include-documents">Inkludera kvitton och underlag</Label>
<p className="text-xs text-muted-foreground max-w-prose">
Bilagor till verifikationer (kvitton, fakturor, PDF:er) packas med i ZIP:en.
Stäng av för en mindre backup med bara bokföringsdata.
</p>
</div>
<Switch
id="include-documents"
checked={includeDocuments}
onCheckedChange={setIncludeDocuments}
/>
</div>
<div className="rounded-md border border-border/60 bg-muted/30 p-3 text-sm">
<div className="flex items-center gap-2 text-muted-foreground">
<Info className="h-3.5 w-3.5" />
{isLoadingEstimate ? (
<span>Beräknar storlek…</span>
) : estimate ? (
<span>
Uppskattad storlek: <strong className="text-foreground">{formatBytes(estimate.total_bytes)}</strong>
{' '}({estimate.document_count} {estimate.document_count === 1 ? 'bilaga' : 'bilagor'})
</span>
) : (
<span>Storlek beräknas när omfattning är vald.</span>
)}
</div>
{isOverLimit && (
<p className="mt-2 text-xs text-destructive">
Arkivet är större än {formatBytes(estimate!.size_limit_bytes)} och kan inte laddas ner
direkt. Välj en enskild period eller stäng av bilagor tills vidare —
automatisk molnsynkronisering kommer i senare version.
</p>
)}
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Button onClick={handleDownload} disabled={!canDownload}>
{isDownloading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Skapar backup…
</>
) : (
<>
<Download className="mr-2 h-4 w-4" />
Skapa och ladda ner
</>
)}
</Button>
{lastDownloadedAt && (
<p className="text-xs text-muted-foreground">
Senaste nedladdning: {formatDate(lastDownloadedAt)}
</p>
)}
</div>
</CardContent>
</Card>
{hasCloudBackup && CloudBackupPanel ? (
<CloudBackupPanel />
) : (
<Card className="border-dashed">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Cloud className="h-4 w-4 text-muted-foreground" />
Molnsynkronisering
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground max-w-prose">
Aktivera tillägget &ldquo;Molnsynkronisering&rdquo; för att koppla Google
Drive och ladda upp säkerhetsbackupen med ett klick.
</p>
</CardContent>
</Card>
)}
</div>
)
}
interface ScopeRadioProps {
checked: boolean
onChange: () => void
label: string
description: string
recommended?: boolean
}
function ScopeRadio({ checked, onChange, label, description, recommended }: ScopeRadioProps) {
return (
<button
type="button"
onClick={onChange}
className={`flex-1 rounded-lg border-2 p-3 text-left transition-colors ${
checked ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/40'
}`}
>
<div className="flex items-center gap-2">
<span className="font-medium text-sm">{label}</span>
{recommended && (
<span className="text-[10px] font-medium uppercase tracking-wider text-primary">
Rekommenderas
</span>
)}
</div>
<p className="mt-0.5 text-xs text-muted-foreground">{description}</p>
</button>
)
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
const kb = bytes / 1024
if (kb < 1024) return `${kb.toFixed(1)} kB`
const mb = kb / 1024
if (mb < 1024) return `${mb.toFixed(1)} MB`
return `${(mb / 1024).toFixed(2)} GB`
}
function formatDate(iso: string): string {
const d = new Date(iso)
return d.toLocaleString('sv-SE', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
+2 -9
View File
@@ -2,7 +2,6 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { useCompany } from '@/contexts/CompanyContext'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -16,7 +15,7 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import { RetentionNotice } from '@/components/ui/retention-notice'
import { ExternalLink, Loader2 } from 'lucide-react'
import { Loader2 } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
/**
@@ -84,13 +83,7 @@ export function CompanyDangerZone() {
<RetentionNotice variant="company" />
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Button variant="outline" className="w-full sm:w-auto" asChild>
<Link href="/reports?type=full-archive">
<ExternalLink className="mr-2 h-4 w-4" />
Exportera fullständigt arkiv
</Link>
</Button>
<div className="flex justify-end">
<Button
variant="destructive"
className="w-full sm:w-auto"
+1
View File
@@ -31,6 +31,7 @@ export function SettingsNav({ isSandbox }: { isSandbox?: boolean }) {
{ href: '/settings/banking', label: 'Bank (PSD2)', show: hasCompany && !isSandbox && hasBankingExtension },
{ href: '/settings/salary', label: 'Löner', show: hasCompany && company?.entity_type === 'aktiebolag' },
{ href: '/settings/templates', label: 'Mallar', show: hasCompany },
{ href: '/settings/backup', label: 'Säkerhetsbackup', show: hasCompany },
{ href: '/settings/account', label: 'Konto', show: true },
{ href: '/settings/api', label: 'API', show: hasCompany && hasMcpExtension },
].filter(item => item.show)
+30 -9
View File
@@ -1,5 +1,6 @@
'use client'
import Link from 'next/link'
import { AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
@@ -23,18 +24,38 @@ export function RetentionNotice({ variant, className }: RetentionNoticeProps) {
variant === 'company'
? {
title: 'Bokföringen behålls i 7 år',
body:
'Enligt bokföringslagen (BFL 7 kap. 2§) sparas räkenskapsinformation i 7 år. ' +
'När du raderar företaget döljs det i gnubok, men verifikationer, dokument och ' +
'bokföring behålls säkert tills lagkravet löpt ut.',
body: (
<>
Enligt bokföringslagen (BFL 7 kap. 2§) sparas räkenskapsinformation i 7 år.
När du raderar företaget döljs det i gnubok, men verifikationer, dokument och
bokföring behålls säkert tills lagkravet löpt ut. Du kan{' '}
<Link
href="/settings/backup"
className="underline underline-offset-2 hover:text-foreground"
>
ladda ner en säkerhetsbackup
</Link>{' '}
innan du fortsätter.
</>
),
}
: {
title: 'Kontoraderingen är permanent',
body:
'Ditt konto avidentifieras och du loggas ut från alla enheter. Räkenskaps­information ' +
'från företag du ägt behålls säkert i 7 år enligt BFL 7 kap. 2§. Du kan inte skapa ett ' +
'nytt konto med samma e-postadress — kontakta support om du vill återaktivera kontot ' +
'i framtiden. Ladda gärna ner ett fullständigt arkiv innan du fortsätter.',
body: (
<>
Ditt konto avidentifieras och du loggas ut från alla enheter.
Räkenskapsinformation från företag du ägt behålls säkert i 7 år enligt BFL 7
kap. 2§. Du kan inte skapa ett nytt konto med samma e-postadress — kontakta
support om du vill återaktivera kontot i framtiden. Ladda gärna ner en{' '}
<Link
href="/settings/backup"
className="underline underline-offset-2 hover:text-foreground"
>
säkerhetsbackup
</Link>{' '}
innan du fortsätter.
</>
),
}
return (