Bug/template and sandbox (#589)

* Enhance booking template functionality and add sandbox extraction checks

* Implement Recapt integration for feedback submission and user identification

* Add Recapt identification component and bank sync status chip; update crontab entries

* Update .gitignore to ignore the entire scripts directory

* Refactor Recapt integration: add loader component, update privacy policy, and enhance bank sync status messages

* Fix .gitignore to correctly ignore the scripts directory
This commit is contained in:
Mattsson
2026-05-28 15:43:48 +02:00
committed by GitHub
parent 20989379bb
commit a9aff5a120
25 changed files with 927 additions and 70 deletions
@@ -1,6 +1,25 @@
import { describe, it, expect } from 'vitest'
import { applyTemplate, getTemplateScope, TEMPLATE_CATEGORY_LABELS } from '../template-library'
import type { BookingTemplateLibraryLine } from '@/types'
import { applyTemplate, convertLibraryToBookingTemplate, getTemplateScope, LIBRARY_TEMPLATE_PREFIX, TEMPLATE_CATEGORY_LABELS } from '../template-library'
import type { BookingTemplateLibrary, BookingTemplateLibraryLine } from '@/types'
function makeLibraryTemplate(lines: BookingTemplateLibraryLine[], overrides: Partial<BookingTemplateLibrary> = {}): BookingTemplateLibrary {
return {
id: 'tpl-1',
company_id: 'co-1',
team_id: null,
created_by: 'user-1',
name: 'Test template',
description: '',
category: 'other',
entity_type: 'all',
lines,
is_system: false,
is_active: true,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
...overrides,
}
}
describe('applyTemplate', () => {
it('creates simple two-line debit/credit entries', () => {
@@ -96,3 +115,89 @@ describe('TEMPLATE_CATEGORY_LABELS', () => {
expect(TEMPLATE_CATEGORY_LABELS.tax_account).toBe('Skattekonto')
})
})
describe('convertLibraryToBookingTemplate', () => {
it('converts a simple 2-line business + settlement template', () => {
const tpl = makeLibraryTemplate([
{ account: '6072', label: 'Representation', side: 'debit', type: 'business', ratio: 1 },
{ account: '1930', label: 'Företagskonto', side: 'credit', type: 'settlement', ratio: 1 },
])
const result = convertLibraryToBookingTemplate(tpl)
expect(result).not.toBeNull()
expect(result!.id).toBe(`${LIBRARY_TEMPLATE_PREFIX}tpl-1`)
expect(result!.direction).toBe('expense')
expect(result!.debit_account).toBe('6072')
expect(result!.credit_account).toBe('1930')
expect(result!.vat_treatment).toBeNull()
})
it('identifies direction "income" when business line is on credit', () => {
const tpl = makeLibraryTemplate([
{ account: '3001', label: 'Försäljning', side: 'credit', type: 'business', ratio: 1 },
{ account: '1930', label: 'Företagskonto', side: 'debit', type: 'settlement', ratio: 1 },
])
const result = convertLibraryToBookingTemplate(tpl)
expect(result).not.toBeNull()
expect(result!.direction).toBe('income')
expect(result!.debit_account).toBe('1930')
expect(result!.credit_account).toBe('3001')
})
it.each([
[0.25, 'standard_25'],
[0.12, 'reduced_12'],
[0.06, 'reduced_6'],
] as const)('extracts VAT treatment for rate %f', (rate, treatment) => {
const tpl = makeLibraryTemplate([
{ account: '4010', label: 'Varor', side: 'debit', type: 'business', ratio: 1 },
{ account: '2641', label: 'Ingående moms', side: 'debit', type: 'vat', vat_rate: rate },
{ account: '1930', label: 'Bank', side: 'credit', type: 'settlement', ratio: 1 },
])
const result = convertLibraryToBookingTemplate(tpl)
expect(result).not.toBeNull()
expect(result!.vat_treatment).toBe(treatment)
expect(result!.vat_rate).toBe(rate)
})
it('detects reverse charge via 2614 fictitious output VAT', () => {
const tpl = makeLibraryTemplate([
{ account: '4056', label: 'EU-varor', side: 'debit', type: 'business', ratio: 1 },
{ account: '2614', label: 'Utg. moms omv.', side: 'credit', type: 'vat', vat_rate: 0.25 },
{ account: '2645', label: 'Ing. moms omv.', side: 'debit', type: 'vat', vat_rate: 0.25 },
{ account: '1930', label: 'Bank', side: 'credit', type: 'settlement', ratio: 1 },
])
const result = convertLibraryToBookingTemplate(tpl)
expect(result).not.toBeNull()
expect(result!.vat_treatment).toBe('reverse_charge')
})
it('returns null when there are 2 business lines', () => {
const tpl = makeLibraryTemplate([
{ account: '6072', label: 'A', side: 'debit', type: 'business', ratio: 0.5 },
{ account: '6073', label: 'B', side: 'debit', type: 'business', ratio: 0.5 },
{ account: '1930', label: 'Bank', side: 'credit', type: 'settlement', ratio: 1 },
])
expect(convertLibraryToBookingTemplate(tpl)).toBeNull()
})
it('returns null when there is no settlement line', () => {
const tpl = makeLibraryTemplate([
{ account: '6072', label: 'A', side: 'debit', type: 'business', ratio: 1 },
{ account: '2641', label: 'Moms', side: 'debit', type: 'vat', vat_rate: 0.25 },
])
expect(convertLibraryToBookingTemplate(tpl)).toBeNull()
})
it('returns null when business and settlement are on the same side', () => {
const tpl = makeLibraryTemplate([
{ account: '6072', label: 'A', side: 'debit', type: 'business', ratio: 1 },
{ account: '1930', label: 'Bank', side: 'debit', type: 'settlement', ratio: 1 },
])
expect(convertLibraryToBookingTemplate(tpl)).toBeNull()
})
it('returns null when lines is not an array', () => {
const tpl = makeLibraryTemplate([], { lines: null as unknown as BookingTemplateLibraryLine[] })
expect(convertLibraryToBookingTemplate(tpl)).toBeNull()
})
})
+31
View File
@@ -0,0 +1,31 @@
// Recapt's identify SDK keeps the last-known uid in memory and in
// localStorage. Passing `uid: undefined` is not a documented logout
// signal — on some SDK versions it's coerced to the previous value.
// We send an explicit empty-string uid (the SDK's "anonymous" marker),
// then clear any persisted Recapt keys from localStorage so the next
// pageload doesn't re-identify the logged-out user from cache.
export function clearRecaptIdentity(): void {
if (typeof window === 'undefined') return
try {
if (typeof window.recapt === 'function') {
window.recapt('identify', {
uid: '',
email: undefined,
nickname: undefined,
})
}
// Defense-in-depth: wipe any Recapt-namespaced storage on logout so
// a shared device cannot resurrect the previous user's identity on
// the next page load.
if (typeof window.localStorage !== 'undefined') {
for (let i = window.localStorage.length - 1; i >= 0; i--) {
const key = window.localStorage.key(i)
if (key && (key.startsWith('recapt') || key.startsWith('glimt'))) {
window.localStorage.removeItem(key)
}
}
}
} catch {
// best-effort — we're already in a logout flow
}
}
+62 -14
View File
@@ -11,19 +11,30 @@ describe('submitFeedback', () => {
vi.unstubAllGlobals()
})
function stubRecapt(impl: (...args: unknown[]) => void) {
vi.stubGlobal('window', { recapt: impl })
}
function stubNoRecapt() {
vi.stubGlobal('window', {})
}
function stubFetchOk() {
const fetchSpy = vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })
vi.stubGlobal('fetch', fetchSpy)
return fetchSpy
}
it('posts subject and message to the contact endpoint', async () => {
it('sends to both Recapt and email when SDK is present', async () => {
const recapt = vi.fn()
stubRecapt(recapt)
const fetchSpy = stubFetchOk()
const result = await submitFeedback({ subject: 'Hjälpsida', message: 'Hjälp tack' })
expect(result.ok).toBe(true)
expect(result.channels).toEqual(['email'])
expect(result.channels.sort()).toEqual(['email', 'recapt'])
expect(recapt).toHaveBeenCalledWith('feedback', { message: '[Hjälpsida]\n\nHjälp tack' })
expect(fetchSpy).toHaveBeenCalledWith(
'/api/support/contact',
expect.objectContaining({
@@ -33,21 +44,57 @@ describe('submitFeedback', () => {
)
})
it('omits subject when not provided', async () => {
const fetchSpy = stubFetchOk()
it('omits subject prefix in Recapt payload when subject not provided', async () => {
const recapt = vi.fn()
stubRecapt(recapt)
stubFetchOk()
const result = await submitFeedback({ message: 'plain' })
await submitFeedback({ message: 'plain' })
expect(result.ok).toBe(true)
expect(fetchSpy).toHaveBeenCalledWith(
'/api/support/contact',
expect.objectContaining({
body: JSON.stringify({ message: 'plain' }),
})
)
expect(recapt).toHaveBeenCalledWith('feedback', { message: 'plain' })
})
it('returns failure with server error message when the endpoint rejects', async () => {
it('still reports success via email when Recapt throws', async () => {
stubRecapt(() => {
throw new Error('boom')
})
stubFetchOk()
const result = await submitFeedback({ subject: 'X', message: 'msg' })
expect(result.ok).toBe(true)
expect(result.channels).toEqual(['email'])
})
it('uses email only when Recapt SDK is absent', async () => {
stubNoRecapt()
const fetchSpy = stubFetchOk()
const result = await submitFeedback({ message: 'msg' })
expect(result.ok).toBe(true)
expect(result.channels).toEqual(['email'])
expect(fetchSpy).toHaveBeenCalledOnce()
})
it('reports success when Recapt succeeds even if email fails', async () => {
const recapt = vi.fn()
stubRecapt(recapt)
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: false, json: async () => ({ error: 'down' }) })
)
const result = await submitFeedback({ message: 'msg' })
expect(result.ok).toBe(true)
expect(result.channels).toEqual(['recapt'])
})
it('returns failure with email error when both channels fail', async () => {
stubRecapt(() => {
throw new Error('boom')
})
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
@@ -63,7 +110,8 @@ describe('submitFeedback', () => {
expect(result.error).toBe('Mailtjänsten är inte konfigurerad')
})
it('returns failure when fetch itself throws', async () => {
it('returns failure when fetch itself throws and Recapt is absent', async () => {
stubNoRecapt()
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network down')))
const result = await submitFeedback({ message: 'msg' })
+45 -10
View File
@@ -3,7 +3,7 @@ export interface SubmitFeedbackInput {
subject?: string
}
export type SupportChannel = 'email'
export type SupportChannel = 'recapt' | 'email'
export interface SubmitFeedbackResult {
ok: boolean
@@ -11,23 +11,58 @@ export interface SubmitFeedbackResult {
error?: string
}
export async function submitFeedback(input: SubmitFeedbackInput): Promise<SubmitFeedbackResult> {
function composeMessage({ message, subject }: SubmitFeedbackInput): string {
if (!subject) return message
return `[${subject}]\n\n${message}`
}
async function submitViaEmail(
{ message, subject }: SubmitFeedbackInput
): Promise<{ ok: true } | { ok: false; error: string }> {
try {
const res = await fetch('/api/support/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ subject: input.subject, message: input.message }),
body: JSON.stringify({ subject, message }),
})
if (!res.ok) {
const data = await res.json().catch(() => ({}))
return { ok: false, channels: [], error: data.error || 'Kunde inte skicka meddelandet' }
return { ok: false, error: data.error || 'Kunde inte skicka meddelandet' }
}
return { ok: true, channels: ['email'] }
return { ok: true }
} catch (err) {
return {
ok: false,
channels: [],
error: err instanceof Error ? err.message : 'Nätverksfel',
}
return { ok: false, error: err instanceof Error ? err.message : 'Nätverksfel' }
}
}
function submitViaRecapt(
input: SubmitFeedbackInput
): { ok: true } | { ok: false; error: string } | null {
const recapt = typeof window !== 'undefined' ? window.recapt : undefined
if (typeof recapt !== 'function') return null
try {
recapt('feedback', { message: composeMessage(input) })
return { ok: true }
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : 'Recapt-fel' }
}
}
export async function submitFeedback(input: SubmitFeedbackInput): Promise<SubmitFeedbackResult> {
const recaptResult = submitViaRecapt(input)
const emailResult = await submitViaEmail(input)
const channels: SupportChannel[] = []
if (recaptResult?.ok) channels.push('recapt')
if (emailResult.ok) channels.push('email')
if (channels.length > 0) {
return { ok: true, channels }
}
return {
ok: false,
channels: [],
error: emailResult.ok ? undefined : emailResult.error,
}
}