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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

* 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) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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
+9 -9
View File
@@ -19,11 +19,11 @@ export interface AuditLogFilters {
}
/**
* Get paginated audit log entries for a user
* Get paginated audit log entries for a company
*/
export async function getAuditLog(
supabase: SupabaseClient,
userId: string,
companyId: string,
filters: AuditLogFilters = {}
): Promise<{ data: AuditLogEntry[]; count: number }> {
const page = filters.page ?? 1
@@ -33,7 +33,7 @@ export async function getAuditLog(
let query = supabase
.from('audit_log')
.select('*', { count: 'exact' })
.eq('company_id', userId)
.eq('company_id', companyId)
.order('created_at', { ascending: false })
.range(offset, offset + pageSize - 1)
@@ -70,7 +70,7 @@ export async function getAuditLog(
*/
export async function getEntityHistory(
supabase: SupabaseClient,
userId: string,
companyId: string,
tableName: string,
recordId: string
): Promise<AuditLogEntry[]> {
@@ -78,7 +78,7 @@ export async function getEntityHistory(
const { data, error } = await supabase
.from('audit_log')
.select('*')
.eq('company_id', userId)
.eq('company_id', companyId)
.eq('table_name', tableName)
.eq('record_id', recordId)
.order('created_at', { ascending: true })
@@ -96,7 +96,7 @@ export async function getEntityHistory(
*/
export async function getCorrectionChain(
supabase: SupabaseClient,
userId: string,
companyId: string,
journalEntryId: string
): Promise<AuditLogEntry[]> {
@@ -105,7 +105,7 @@ export async function getCorrectionChain(
.from('journal_entries')
.select('id, reverses_id, reversed_by_id, correction_of_id')
.eq('id', journalEntryId)
.eq('company_id', userId)
.eq('company_id', companyId)
.single()
if (entryError || !entry) {
@@ -122,7 +122,7 @@ export async function getCorrectionChain(
const { data: referencing } = await supabase
.from('journal_entries')
.select('id')
.eq('company_id', userId)
.eq('company_id', companyId)
.or(`reverses_id.eq.${journalEntryId},reversed_by_id.eq.${journalEntryId},correction_of_id.eq.${journalEntryId}`)
for (const ref of referencing || []) {
@@ -133,7 +133,7 @@ export async function getCorrectionChain(
const { data, error } = await supabase
.from('audit_log')
.select('*')
.eq('company_id', userId)
.eq('company_id', companyId)
.eq('table_name', 'journal_entries')
.in('record_id', Array.from(relatedIds))
.order('created_at', { ascending: true })
+3 -3
View File
@@ -48,8 +48,8 @@ describe('sectors registry', () => {
expect(SECTORS.length).toBe(1)
})
it('should have 9 total extensions', () => {
expect(getAllExtensions().length).toBe(9)
it('should have 10 total extensions', () => {
expect(getAllExtensions().length).toBe(10)
})
it('should have unique slugs within each sector', () => {
@@ -94,7 +94,7 @@ describe('sectors registry', () => {
it('getExtensionsBySector returns extensions for a sector', () => {
const extensions = getExtensionsBySector('general')
expect(extensions.length).toBe(9)
expect(extensions.length).toBe(10)
})
it('all extensions have required fields', () => {
@@ -6,4 +6,5 @@ export const ENABLED_EXTENSION_IDS: ReadonlySet<string> = new Set([
'arcim-migration',
'tic',
'mcp-server',
'cloud-backup',
])
@@ -5,6 +5,7 @@ import { emailExtension } from '@/extensions/general/email'
import { arcimMigrationExtension } from '@/extensions/general/arcim-migration'
import { ticExtension } from '@/extensions/general/tic'
import { mcpServerExtension } from '@/extensions/general/mcp-server'
import { cloudBackupExtension } from '@/extensions/general/cloud-backup'
export const FIRST_PARTY_EXTENSIONS: Extension[] = [
enableBankingExtension,
@@ -12,4 +13,5 @@ export const FIRST_PARTY_EXTENSIONS: Extension[] = [
arcimMigrationExtension,
ticExtension,
mcpServerExtension,
cloudBackupExtension,
]
@@ -68,5 +68,17 @@ export const EXTENSION_DEFINITIONS: Record<string, ExtensionDefinition[]> = {
"description": "Gör bokföring via Claude, Cursor eller annan MCP-klient",
"longDescription": "Exponerar gnuboks bokföringsmotor som MCP-verktyg (Model Context Protocol). Koppla din MCP-klient med en API-nyckel och gör bokföring genom konversation: visa okategoriserade transaktioner, bokför dem, skapa fakturor."
},
{
"slug": "cloud-backup",
"name": "Molnsynkronisering",
"sector": "general",
"category": "operations",
"icon": "Cloud",
"dataPattern": "manual",
"description": "Synka säkerhetsbackup till din egen molnlagring",
"longDescription": "Koppla ditt Google Drive-konto och ladda upp en fullständig säkerhetsbackup med ett klick. Gnubok skapar en ZIP med SIE-filer, kvitton och behandlingshistorik och laddar upp till en egen mapp i din Drive. Perfekt för att uppfylla egna krav på redundans.",
"hasOwnData": true,
"subscriptionNotice": "Kräver ett Google-konto. Uppladdningar sker direkt till din Drive — ingen data lagras hos tredje part utöver Google."
},
],
}
@@ -7,4 +7,5 @@ export const WORKSPACES: Record<string, ComponentType<WorkspaceComponentProps>>
'general/enable-banking': dynamic(() => import('@/components/extensions/general/EnableBankingWorkspace')),
'general/arcim-migration': dynamic(() => import('@/components/extensions/general/ArcimMigrationWorkspace')),
'general/tic': dynamic(() => import('@/components/extensions/general/TicWorkspace')),
'general/cloud-backup': dynamic(() => import('@/components/extensions/general/CloudBackupWorkspace')),
}
@@ -13,6 +13,9 @@ const SETTINGS_PANELS: Record<string, ComponentType> = {
'enable-banking': dynamic(
() => import('@/extensions/general/enable-banking/components/BankingSettingsPanel')
),
'cloud-backup': dynamic(
() => import('@/extensions/general/cloud-backup/components/CloudBackupCard')
),
}
/**
+265 -147
View File
@@ -1,8 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect, vi, beforeEach } from 'vitest'
import JSZip from 'jszip'
import { generateFullArchive } from '../full-archive-export'
import { generateFullArchive, estimateArchiveSize } from '../full-archive-export'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { getAuditLog } from '@/lib/core/audit/audit-service'
vi.mock('../sie-export', () => ({
generateSIEExport: vi.fn().mockResolvedValue('#FLAGGA 0\n#PROGRAM "ERPBase"'),
@@ -62,10 +63,257 @@ vi.mock('@/lib/core/audit/audit-service', () => ({
getAuditLog: vi.fn().mockResolvedValue({ data: [], count: 0 }),
}))
const mockGetAuditLog = vi.mocked(getAuditLog)
const COMPANY_ROW = {
company_name: 'Test AB',
trade_name: null,
org_number: '5566778899',
moms_period: 'quarterly',
}
const PERIOD_2024 = {
id: 'period-2024',
period_start: '2024-01-01',
period_end: '2024-12-31',
opening_balance_entry_id: null,
}
const PERIOD_2023 = {
id: 'period-2023',
period_start: '2023-01-01',
period_end: '2023-12-31',
opening_balance_entry_id: null,
}
describe('generateFullArchive', () => {
let supabase: ReturnType<typeof createQueuedMockSupabase>['supabase']
let enqueueMany: ReturnType<typeof createQueuedMockSupabase>['enqueueMany']
beforeEach(() => {
vi.clearAllMocks()
mockGetAuditLog.mockResolvedValue({ data: [], count: 0 })
const mock = createQueuedMockSupabase()
supabase = mock.supabase
enqueueMany = mock.enqueueMany
})
describe('scope: period', () => {
it('generates a ZIP with expected file structure', async () => {
enqueueMany([
{ data: COMPANY_ROW }, // company_settings
{ data: PERIOD_2024 }, // fiscal_periods (single)
{ data: [] }, // document_attachments
])
const buffer = await generateFullArchive(supabase as any, 'company-1', {
scope: 'period',
period_id: PERIOD_2024.id,
})
const zip = await JSZip.loadAsync(buffer)
expect(zip.file('bokforing.se')).not.toBeNull()
expect(zip.file('rapporter/saldobalans.json')).not.toBeNull()
expect(zip.file('rapporter/resultatrakning.json')).not.toBeNull()
expect(zip.file('rapporter/balansrakning.json')).not.toBeNull()
expect(zip.file('rapporter/huvudbok.json')).not.toBeNull()
expect(zip.file('rapporter/grundbok.json')).not.toBeNull()
expect(zip.file('rapporter/momsdeklaration.json')).not.toBeNull()
expect(zip.file('dokument/manifest.json')).not.toBeNull()
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
expect(zip.file('revision/systemdokumentation.json')).not.toBeNull()
})
it('handles missing documents gracefully', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: PERIOD_2024 },
{
data: [
{
id: 'doc-1',
file_name: 'receipt.pdf',
storage_path: 'documents/user-1/receipt.pdf',
journal_entry_id: 'entry-1',
},
],
},
{ data: [{ id: 'entry-1', fiscal_period_id: PERIOD_2024.id }] },
])
supabase.storage.from = vi.fn().mockReturnValue({
download: vi.fn().mockResolvedValue({
data: null,
error: { message: 'File not found' },
}),
})
const buffer = await generateFullArchive(supabase as any, 'company-1', {
scope: 'period',
period_id: PERIOD_2024.id,
})
const zip = await JSZip.loadAsync(buffer)
const manifestFile = zip.file('dokument/manifest.json')
expect(manifestFile).not.toBeNull()
const manifest = JSON.parse(await manifestFile!.async('text'))
expect(manifest).toHaveLength(1)
expect(manifest[0].status).toBe('error')
expect(manifest[0].error).toBe('File not found')
expect(manifest[0].fiscal_period_id).toBe(PERIOD_2024.id)
})
it('skips documents when include_documents is false', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: PERIOD_2024 },
])
const buffer = await generateFullArchive(supabase as any, 'company-1', {
scope: 'period',
period_id: PERIOD_2024.id,
include_documents: false,
})
const zip = await JSZip.loadAsync(buffer)
expect(zip.file('dokument/manifest.json')).toBeNull()
expect(zip.file('bokforing.se')).not.toBeNull()
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
})
it('throws when fiscal period not found', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: null },
])
await expect(
generateFullArchive(supabase as any, 'company-1', {
scope: 'period',
period_id: 'nonexistent',
})
).rejects.toThrow('Fiscal period not found')
})
it('filters audit trail by period dates', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: PERIOD_2024 },
{ data: [] },
])
await generateFullArchive(supabase as any, 'company-1', {
scope: 'period',
period_id: PERIOD_2024.id,
})
expect(mockGetAuditLog).toHaveBeenCalledWith(
expect.anything(),
'company-1',
expect.objectContaining({
from_date: PERIOD_2024.period_start,
to_date: `${PERIOD_2024.period_end}T23:59:59.999Z`,
})
)
})
})
describe('scope: all', () => {
it('generates per-period SIE files and report subfolders', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: [PERIOD_2023, PERIOD_2024] }, // fiscal_periods (list for fetchAllPeriods)
{ data: [] }, // document_attachments
])
const buffer = await generateFullArchive(supabase as any, 'company-1', {
scope: 'all',
})
const zip = await JSZip.loadAsync(buffer)
expect(zip.file('sie/2023-01-01_2023-12-31.se')).not.toBeNull()
expect(zip.file('sie/2024-01-01_2024-12-31.se')).not.toBeNull()
expect(zip.file('rapporter/2023-01-01_2023-12-31/saldobalans.json')).not.toBeNull()
expect(zip.file('rapporter/2024-01-01_2024-12-31/saldobalans.json')).not.toBeNull()
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
expect(zip.file('revision/systemdokumentation.json')).not.toBeNull()
// No root bokforing.se in all-mode
expect(zip.file('bokforing.se')).toBeNull()
})
it('does not filter audit trail by date in all-mode', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: [PERIOD_2024] },
{ data: [] },
])
await generateFullArchive(supabase as any, 'company-1', { scope: 'all' })
const call = mockGetAuditLog.mock.calls[0]
expect(call[2]).not.toHaveProperty('from_date')
expect(call[2]).not.toHaveProperty('to_date')
})
it('tags each document with its fiscal_period_id across periods', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: [PERIOD_2023, PERIOD_2024] },
{
data: [
{ id: 'doc-2023', file_name: 'r23.pdf', storage_path: 'p/r23.pdf', journal_entry_id: 'e-2023' },
{ id: 'doc-2024', file_name: 'r24.pdf', storage_path: 'p/r24.pdf', journal_entry_id: 'e-2024' },
],
},
{
data: [
{ id: 'e-2023', fiscal_period_id: PERIOD_2023.id },
{ id: 'e-2024', fiscal_period_id: PERIOD_2024.id },
],
},
])
const buffer = await generateFullArchive(supabase as any, 'company-1', {
scope: 'all',
})
const zip = await JSZip.loadAsync(buffer)
const manifestFile = zip.file('dokument/manifest.json')
expect(manifestFile).not.toBeNull()
const manifest = JSON.parse(await manifestFile!.async('text'))
expect(manifest).toHaveLength(2)
const byId = Object.fromEntries(
(manifest as Array<{ document_id: string; fiscal_period_id: string | null }>).map((m) => [
m.document_id,
m.fiscal_period_id,
])
)
expect(byId['doc-2023']).toBe(PERIOD_2023.id)
expect(byId['doc-2024']).toBe(PERIOD_2024.id)
})
it('throws when no fiscal periods exist', async () => {
enqueueMany([
{ data: COMPANY_ROW },
{ data: [] },
])
await expect(
generateFullArchive(supabase as any, 'company-1', { scope: 'all' })
).rejects.toThrow('No fiscal periods found')
})
})
})
describe('estimateArchiveSize', () => {
let supabase: ReturnType<typeof createQueuedMockSupabase>['supabase']
let enqueueMany: ReturnType<typeof createQueuedMockSupabase>['enqueueMany']
beforeEach(() => {
vi.clearAllMocks()
const mock = createQueuedMockSupabase()
@@ -73,165 +321,35 @@ describe('generateFullArchive', () => {
enqueueMany = mock.enqueueMany
})
function enqueueStandardResponses(opts?: { includeDocuments?: boolean }) {
// 1. fiscal_periods query
it('sums document file_size_bytes in all-mode plus overhead', async () => {
enqueueMany([
{
data: {
id: 'period-1',
period_start: '2024-01-01',
period_end: '2024-12-31',
user_id: 'user-1',
},
},
// 2. company_settings query
{
data: {
company_name: 'Test AB',
org_number: '5566778899',
moms_period: 'quarterly',
},
},
])
if (opts?.includeDocuments !== false) {
enqueueMany([
// 3. document_attachments query
{ data: [] },
])
}
}
it('generates a ZIP with expected file structure', async () => {
enqueueStandardResponses()
const buffer = await generateFullArchive(supabase as any, 'company-1', {
period_id: 'period-1',
})
const zip = await JSZip.loadAsync(buffer)
expect(zip.file('bokforing.se')).not.toBeNull()
expect(zip.file('rapporter/saldobalans.json')).not.toBeNull()
expect(zip.file('rapporter/resultatrakning.json')).not.toBeNull()
expect(zip.file('rapporter/balansrakning.json')).not.toBeNull()
expect(zip.file('rapporter/huvudbok.json')).not.toBeNull()
expect(zip.file('rapporter/grundbok.json')).not.toBeNull()
expect(zip.file('rapporter/momsdeklaration.json')).not.toBeNull()
expect(zip.file('dokument/manifest.json')).not.toBeNull()
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
})
it('handles missing documents gracefully', async () => {
const mock = createQueuedMockSupabase()
supabase = mock.supabase
enqueueMany = mock.enqueueMany
enqueueMany([
// fiscal_periods
{
data: {
id: 'period-1',
period_start: '2024-01-01',
period_end: '2024-12-31',
user_id: 'user-1',
},
},
// company_settings
{
data: {
company_name: 'Test AB',
org_number: '5566778899',
moms_period: 'quarterly',
},
},
// document_attachments — one document
{
data: [
{
id: 'doc-1',
file_name: 'receipt.pdf',
storage_path: 'documents/user-1/receipt.pdf',
journal_entry_id: 'entry-1',
},
{ file_size_bytes: 1_000_000, journal_entry_id: 'e1' },
{ file_size_bytes: 2_500_000, journal_entry_id: 'e2' },
],
},
// journal_entries in period
{
data: [{ id: 'entry-1' }],
count: 2,
},
])
// Mock storage download to fail
supabase.storage.from = vi.fn().mockReturnValue({
download: vi.fn().mockResolvedValue({
data: null,
error: { message: 'File not found' },
}),
})
const result = await estimateArchiveSize(supabase as any, 'company-1', 'all')
const buffer = await generateFullArchive(supabase as any, 'company-1', {
period_id: 'period-1',
})
const zip = await JSZip.loadAsync(buffer)
const manifestFile = zip.file('dokument/manifest.json')
expect(manifestFile).not.toBeNull()
const manifest = JSON.parse(await manifestFile!.async('text'))
expect(manifest).toHaveLength(1)
expect(manifest[0].status).toBe('error')
expect(manifest[0].error).toBe('File not found')
expect(result.document_bytes).toBe(3_500_000)
expect(result.document_count).toBe(2)
// overhead is +5 MB
expect(result.total_bytes).toBe(3_500_000 + 5 * 1024 * 1024)
})
it('skips documents when include_documents is false', async () => {
const mock = createQueuedMockSupabase()
supabase = mock.supabase
enqueueMany = mock.enqueueMany
it('returns overhead only when no documents in scope', async () => {
enqueueMany([
// fiscal_periods
{
data: {
id: 'period-1',
period_start: '2024-01-01',
period_end: '2024-12-31',
user_id: 'user-1',
},
},
// company_settings
{
data: {
company_name: 'Test AB',
org_number: '5566778899',
moms_period: 'quarterly',
},
},
{ data: [], count: 0 }, // journal_entries for periodEntryIds
{ data: [], count: 0 }, // document_attachments
])
const buffer = await generateFullArchive(supabase as any, 'company-1', {
period_id: 'period-1',
include_documents: false,
})
const result = await estimateArchiveSize(supabase as any, 'company-1', 'period', 'p-1')
const zip = await JSZip.loadAsync(buffer)
// Should not have dokument folder
expect(zip.file('dokument/manifest.json')).toBeNull()
// Should still have other files
expect(zip.file('bokforing.se')).not.toBeNull()
expect(zip.file('revision/behandlingshistorik.json')).not.toBeNull()
})
it('throws when fiscal period not found', async () => {
const mock = createQueuedMockSupabase()
supabase = mock.supabase
enqueueMany = mock.enqueueMany
enqueueMany([{ data: null }])
await expect(
generateFullArchive(supabase as any, 'company-1', { period_id: 'nonexistent' })
).rejects.toThrow('Fiscal period not found')
expect(result.document_bytes).toBe(0)
expect(result.document_count).toBe(0)
expect(result.total_bytes).toBe(5 * 1024 * 1024)
})
})
File diff suppressed because it is too large Load Diff