fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import type { ExtensionCategory } from '@/lib/extensions/types'
|
||||
|
||||
const CATEGORY_LABEL_KEY: Record<ExtensionCategory, string> = {
|
||||
accounting: 'category_accounting',
|
||||
reports: 'category_reports',
|
||||
import: 'category_import',
|
||||
operations: 'category_operations',
|
||||
}
|
||||
|
||||
export default function CategoryBadge({ category }: { category: ExtensionCategory }) {
|
||||
const t = useTranslations('extensions')
|
||||
return (
|
||||
<Badge variant="outline" className="text-[10px] font-medium">
|
||||
{t(CATEGORY_LABEL_KEY[category])}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import { extensionNameKey, extensionDescriptionKey } from '@/lib/extensions/i18n'
|
||||
import type { ExtensionDefinition } from '@/lib/extensions/types'
|
||||
import CategoryBadge from './CategoryBadge'
|
||||
import Link from 'next/link'
|
||||
|
||||
export default async function ExtensionCard({ extension }: { extension: ExtensionDefinition }) {
|
||||
const t = await getTranslations('extensions')
|
||||
|
||||
const nameKey = extensionNameKey(extension.slug)
|
||||
const descriptionKey = extensionDescriptionKey(extension.slug)
|
||||
const name = nameKey ? t(nameKey) : extension.name
|
||||
const description = descriptionKey ? t(descriptionKey) : extension.description
|
||||
|
||||
const Icon = resolveIcon(extension.icon)
|
||||
|
||||
return (
|
||||
<Card className="group relative">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-3 min-w-0">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary flex-shrink-0">
|
||||
<Icon className="h-5 w-5 text-foreground" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<Link
|
||||
href={`/extensions/${extension.sector}/${extension.slug}`}
|
||||
className="text-sm font-medium hover:underline"
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
|
||||
{description}
|
||||
</p>
|
||||
<div className="mt-2">
|
||||
<CategoryBadge category={extension.category} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
|
||||
interface ExtensionSandboxLockStateProps {
|
||||
iconName?: string
|
||||
title: string
|
||||
/** One line on what the workspace actually does, so a locked page still explains itself. */
|
||||
description: string
|
||||
/** Why it is locked here and what unlocks it. */
|
||||
note: string
|
||||
ctaLabel: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Sandbox lock for an extension workspace whose value is an external service
|
||||
* (invoice-inbox: AI field extraction plus the forwarding mail address). The
|
||||
* sandbox blocks those services outright (lib/sandbox/guard.ts), so an
|
||||
* unlocked workspace looks functional and then quietly does nothing.
|
||||
*
|
||||
* Deliberately not ExtensionUpsellState: an anonymous demo user has no billing
|
||||
* to upgrade, they need an account. The CTA signs the anonymous session out
|
||||
* first, mirroring SandboxBanner: /register on top of a live anonymous session
|
||||
* registers into the sandbox instead of leaving it.
|
||||
*
|
||||
* Same RSC constraint as ExtensionUpsellState: every prop stays a plain string
|
||||
* and the icon is resolved client-side from its name, because passing a
|
||||
* resolved component across the server/client boundary 500s the page.
|
||||
*/
|
||||
export function ExtensionSandboxLockState({
|
||||
iconName,
|
||||
title,
|
||||
description,
|
||||
note,
|
||||
ctaLabel,
|
||||
}: ExtensionSandboxLockStateProps) {
|
||||
const [isLeaving, setIsLeaving] = useState(false)
|
||||
const router = useRouter()
|
||||
const t = useTranslations('extensions')
|
||||
const { toast } = useToast()
|
||||
|
||||
async function handleCreateAccount() {
|
||||
setIsLeaving(true)
|
||||
const supabase = createClient()
|
||||
const { error } = await supabase.auth.signOut()
|
||||
if (error) {
|
||||
// Navigating anyway would land on /register with the anonymous session
|
||||
// still live, which registers INTO the sandbox: the exact outcome the
|
||||
// sign-out exists to prevent. Stay put and let the user retry.
|
||||
toast({
|
||||
title: t('sandbox_locked_signout_error_title'),
|
||||
description: t('sandbox_locked_signout_error_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLeaving(false)
|
||||
return
|
||||
}
|
||||
router.push('/register')
|
||||
}
|
||||
|
||||
const Icon = iconName ? resolveIcon(iconName) : undefined
|
||||
|
||||
return (
|
||||
<EmptyState icon={Icon} title={title} description={description}>
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<p className="max-w-sm text-sm text-muted-foreground text-balance">{note}</p>
|
||||
<Button onClick={handleCreateAccount} disabled={isLeaving}>
|
||||
{ctaLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</EmptyState>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
|
||||
interface ExtensionUpsellStateProps {
|
||||
iconName?: string
|
||||
title: string
|
||||
description: string
|
||||
ctaLabel: string
|
||||
ctaHref: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Paywall state for a gated extension workspace, rendered when the active
|
||||
* company lacks the required capability.
|
||||
*
|
||||
* This is a client component on purpose: the server page cannot pass a
|
||||
* resolved icon component into the 'use client' EmptyState (React cannot
|
||||
* serialize a component across the RSC boundary; doing so 500s the page).
|
||||
* The page passes the icon NAME as a plain string and this wrapper resolves
|
||||
* it client-side, same as DashboardNav and the command palette do.
|
||||
* Every prop here must stay plain-serializable (strings only).
|
||||
*/
|
||||
export function ExtensionUpsellState({
|
||||
iconName,
|
||||
title,
|
||||
description,
|
||||
ctaLabel,
|
||||
ctaHref,
|
||||
}: ExtensionUpsellStateProps) {
|
||||
const Icon = iconName ? resolveIcon(iconName) : undefined
|
||||
return (
|
||||
<EmptyState icon={Icon} title={title} description={description}>
|
||||
<Link href={ctaHref}>
|
||||
<Button>{ctaLabel}</Button>
|
||||
</Link>
|
||||
</EmptyState>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client'
|
||||
|
||||
import type { ExtensionDefinition } from '@/lib/extensions/types'
|
||||
import { getWorkspaceComponent } from '@/lib/extensions/workspace-registry'
|
||||
import ExtensionWorkspaceShell from './ExtensionWorkspaceShell'
|
||||
import EmptyExtensionState from './shared/EmptyExtensionState'
|
||||
|
||||
// Full-screen workspaces render their own chrome (top bar, title) and opt
|
||||
// out of the shared ExtensionWorkspaceShell header.
|
||||
const FULLSCREEN_WORKSPACES = new Set(['general/invoice-inbox'])
|
||||
|
||||
export default function ExtensionWorkspaceLoader({
|
||||
sector,
|
||||
slug,
|
||||
definition,
|
||||
userId,
|
||||
}: {
|
||||
sector: string
|
||||
slug: string
|
||||
definition: ExtensionDefinition
|
||||
userId: string
|
||||
}) {
|
||||
const WorkspaceComponent = getWorkspaceComponent(sector, slug)
|
||||
const isFullScreen = FULLSCREEN_WORKSPACES.has(`${sector}/${slug}`)
|
||||
|
||||
if (isFullScreen && WorkspaceComponent) {
|
||||
return <WorkspaceComponent userId={userId} />
|
||||
}
|
||||
|
||||
return (
|
||||
<ExtensionWorkspaceShell definition={definition}>
|
||||
{WorkspaceComponent ? (
|
||||
<WorkspaceComponent userId={userId} />
|
||||
) : (
|
||||
<EmptyExtensionState
|
||||
title="Bakgrundstjänst"
|
||||
description={`${definition.name} körs i bakgrunden och har ingen egen vy. Du kan hantera inställningar under Inställningar.`}
|
||||
/>
|
||||
)}
|
||||
</ExtensionWorkspaceShell>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
'use client'
|
||||
|
||||
import type { ExtensionDefinition } from '@/lib/extensions/types'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
|
||||
export default function ExtensionWorkspaceShell({
|
||||
definition,
|
||||
children,
|
||||
}: {
|
||||
definition: ExtensionDefinition
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10 space-y-8">
|
||||
<PageHeader title={definition.name} />
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Link from 'next/link'
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import { sectorNameKey, sectorDescriptionKey } from '@/lib/extensions/i18n'
|
||||
import type { Sector } from '@/lib/extensions/types'
|
||||
|
||||
export default async function SectorCard({ sector }: { sector: Sector }) {
|
||||
const t = await getTranslations('extensions')
|
||||
|
||||
const nameKey = sectorNameKey(sector.slug)
|
||||
const descriptionKey = sectorDescriptionKey(sector.slug)
|
||||
const name = nameKey ? t(nameKey) : sector.name
|
||||
const description = descriptionKey ? t(descriptionKey) : sector.description
|
||||
|
||||
const Icon = resolveIcon(sector.icon)
|
||||
|
||||
return (
|
||||
<Link href={`/extensions/${sector.slug}`} className="h-full">
|
||||
<Card className="group h-full cursor-pointer transition-colors duration-150 hover:bg-secondary/60">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary flex-shrink-0">
|
||||
<Icon className="h-5 w-5 text-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm">
|
||||
{name}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{description}</p>
|
||||
<p className="text-xs text-muted-foreground mt-1.5">
|
||||
{t('extension_count', { count: sector.extensions.length })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import TheaterCanvas, { type TheaterCanvasHandle } from '@/components/import/TheaterCanvas'
|
||||
import type { TheaterModel } from '@/lib/import/theater-model'
|
||||
|
||||
/**
|
||||
* The migration wizard's version of the import theater. Unlike /import
|
||||
* (a fixed narration script paced against one opaque server call), the
|
||||
* wizard KNOWS what the server is doing: phase 1 posts one SIE file at a
|
||||
* time and phase 2 streams the orchestrator's real progress events. The
|
||||
* narration is therefore simply those real step labels, printed once each
|
||||
* as they arrive; the canvas reacts to the same events. Nothing here
|
||||
* invents progress.
|
||||
*
|
||||
* The graph itself is built from the client-parsed SIE data, so drawing it
|
||||
* while the server writes is honest: it shows what the data contains, the
|
||||
* narration shows how far the import has come.
|
||||
*/
|
||||
|
||||
interface ArcimMigrationTheaterProps {
|
||||
model: TheaterModel
|
||||
/** The wizard's real current step label (SIE per-file, then streamed). */
|
||||
currentStep: string
|
||||
/** The wizard's real progress bar value, 0-100. */
|
||||
progress: number
|
||||
}
|
||||
|
||||
interface LogLine {
|
||||
id: number
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Keep the printed log short enough to never overflow the card. */
|
||||
const MAX_LOG_LINES = 6
|
||||
|
||||
export default function ArcimMigrationTheater({
|
||||
model,
|
||||
currentStep,
|
||||
progress,
|
||||
}: ArcimMigrationTheaterProps) {
|
||||
const canvasRef = useRef<TheaterCanvasHandle | null>(null)
|
||||
const [log, setLog] = useState<LogLine[]>([])
|
||||
const [elapsed, setElapsed] = useState(0)
|
||||
|
||||
const reduced =
|
||||
typeof window !== 'undefined' &&
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
// Visible elapsed counter: a multi-minute migration must never look frozen.
|
||||
useEffect(() => {
|
||||
const started = Date.now()
|
||||
const id = window.setInterval(
|
||||
() => setElapsed(Math.floor((Date.now() - started) / 1000)),
|
||||
1000,
|
||||
)
|
||||
return () => window.clearInterval(id)
|
||||
}, [])
|
||||
|
||||
// Account waves (TheaterCanvas assigns account nodes wave = i % 4) are
|
||||
// rationed through one gate shared by the timer schedule and the
|
||||
// step-label reactions below. The floor between births matters: the
|
||||
// wizard emits three step labels within the first second ("Startar",
|
||||
// "Importerar bokföringsdata", "fil 1 av N"), and ungated spawns would
|
||||
// collapse the whole build back into the opening two seconds: the exact
|
||||
// "nothing left to perform" failure this pacing exists to fix.
|
||||
const accWaveRef = useRef(0)
|
||||
const nextWaveAtRef = useRef(0)
|
||||
const spawnNextAccountWave = useCallback(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas || accWaveRef.current >= 4) return
|
||||
const now = Date.now()
|
||||
if (now < nextWaveAtRef.current) return
|
||||
canvas.spawn('account', accWaveRef.current)
|
||||
accWaveRef.current += 1
|
||||
nextWaveAtRef.current = now + 1800
|
||||
}, [])
|
||||
|
||||
// Opening beat: the GL skeleton (year rings, buckets, account waves)
|
||||
// builds while phase 1 writes the journal. The account waves are spread
|
||||
// across ~10s instead of the first two: a multi-year migration runs for
|
||||
// minutes and the canvas must still be performing when file 2 starts.
|
||||
// Real step labels can pull waves forward through the shared gate; these
|
||||
// timers are the ceiling that guarantees a full build by ~10s even if
|
||||
// phase 1 hangs on one file. Reduced motion renders the settled graph
|
||||
// instead (via the settled prop below).
|
||||
useEffect(() => {
|
||||
if (reduced) return
|
||||
const canvas = () => canvasRef.current
|
||||
const timers: number[] = []
|
||||
const at = (ms: number, fn: () => void) => timers.push(window.setTimeout(fn, ms))
|
||||
at(300, () => canvas()?.spawn('ring'))
|
||||
at(1200, () => {
|
||||
canvas()?.spawn('bucket')
|
||||
canvas()?.feed(2100)
|
||||
})
|
||||
// Floor slightly below the first timer so its own spawn never loses to
|
||||
// setTimeout jitter.
|
||||
nextWaveAtRef.current = Date.now() + 2300
|
||||
;[2400, 5000, 7600, 10200].forEach((ms) => at(ms, spawnNextAccountWave))
|
||||
return () => timers.forEach((id) => window.clearTimeout(id))
|
||||
}, [reduced, spawnNextAccountWave])
|
||||
|
||||
// Real-event narration: append each distinct step label once, and let the
|
||||
// canvas mark the milestone. The entity phase (bar past its 55% handoff)
|
||||
// attaches counterparties: that is literally what the orchestrator is
|
||||
// importing then. Reconciliation (95+) gets the pulse.
|
||||
const lastStepRef = useRef('')
|
||||
const idRef = useRef(0)
|
||||
const cpWaveRef = useRef(0)
|
||||
useEffect(() => {
|
||||
if (!currentStep || currentStep === lastStepRef.current) return
|
||||
lastStepRef.current = currentStep
|
||||
idRef.current += 1
|
||||
const line = { id: idRef.current, text: currentStep }
|
||||
setLog((prev) => [...prev, line].slice(-MAX_LOG_LINES))
|
||||
if (reduced) return
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
// SIE phase (bar at or below its 55% handoff): each real step, one per
|
||||
// posted file, also births the next account wave through the rationing
|
||||
// gate, so a long phase 1 keeps building the graph between the timer
|
||||
// beats. Only canvas pacing reacts here: labels and progress stay the
|
||||
// wizard's real values.
|
||||
if (progress <= 55) spawnNextAccountWave()
|
||||
if (progress > 55 && cpWaveRef.current < 3) {
|
||||
canvas.spawn('counterparty', cpWaveRef.current)
|
||||
cpWaveRef.current += 1
|
||||
}
|
||||
canvas.feed(900)
|
||||
if (progress >= 95) canvas.pulse()
|
||||
}, [currentStep, progress, reduced, spawnNextAccountWave])
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="grid gap-6 md:grid-cols-[280px_1fr]">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Migrering pågår</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
Vi hämtar och importerar din bokföringsdata. Det kan ta några minuter.
|
||||
</p>
|
||||
{/* The live region covers only the step labels: the per-second
|
||||
timer below would drown them out in a screen reader. */}
|
||||
<ol className="mt-4 space-y-0" role="status" aria-live="polite">
|
||||
{log.map((line, i) => {
|
||||
const active = i === log.length - 1
|
||||
return (
|
||||
<li
|
||||
key={line.id}
|
||||
className="border-b border-border/60 py-2.5 last:border-b-0"
|
||||
>
|
||||
<p className={`text-sm ${active ? '' : 'text-muted-foreground'}`}>
|
||||
{line.text}
|
||||
</p>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
<div className="mt-4 space-y-1">
|
||||
<div
|
||||
className="flex justify-between text-xs text-muted-foreground tabular-nums"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span>{elapsed}s</span>
|
||||
<span>{progress}%</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative min-h-[340px] md:min-h-[420px]">
|
||||
<TheaterCanvas ref={canvasRef} model={model} settled={reduced} />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,308 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState, useEffect } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { InfoTooltip } from '@/components/ui/info-tooltip'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { InvoiceExtractionResult, VatTreatment } from '@/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { summarizeUnderlagTotals } from './bulk-book-inbox-totals'
|
||||
|
||||
// Minimal shape the dialog needs from the workspace's inbox items.
|
||||
interface BulkBookInboxItem {
|
||||
id: string
|
||||
matched_transaction_id: string | null
|
||||
created_journal_entry_id: string | null
|
||||
created_supplier_invoice_id: string | null
|
||||
// Server-derived: the verifikat anchoring an already-booked matched
|
||||
// transaction (see InvoiceInboxWorkspace's InboxItem).
|
||||
matched_transaction_journal_entry_id?: string | null
|
||||
extracted_data: InvoiceExtractionResult | null
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean
|
||||
onOpenChange: (v: boolean) => void
|
||||
// The user's full checkbox selection. Non-bookable items are filtered out
|
||||
// and surfaced as a "skipped" count so the user understands the outcome.
|
||||
items: BulkBookInboxItem[]
|
||||
onSuccess: () => void | Promise<void>
|
||||
}
|
||||
|
||||
// Swedish category labels: mirrors lib/bookkeeping/category-mapping.ts
|
||||
// (categoryLabels), ordered expenses-first since underlag are overwhelmingly
|
||||
// costs. Values match TransactionCategorySchema in lib/api/schemas.ts.
|
||||
const CATEGORY_OPTIONS: { value: string; label: string }[] = [
|
||||
{ value: 'expense_software', label: 'Programvara/IT-tjänster' },
|
||||
{ value: 'expense_office', label: 'Kontorskostnad' },
|
||||
{ value: 'expense_consumables', label: 'Förbrukningsvaror' },
|
||||
{ value: 'expense_equipment', label: 'Förbrukningsinventarier' },
|
||||
{ value: 'expense_telecom', label: 'Telefon & internet' },
|
||||
{ value: 'expense_travel', label: 'Resekostnad' },
|
||||
{ value: 'expense_marketing', label: 'Marknadsföring' },
|
||||
{ value: 'expense_professional_services', label: 'Konsulttjänst' },
|
||||
{ value: 'expense_education', label: 'Utbildning' },
|
||||
{ value: 'expense_representation', label: 'Representation' },
|
||||
{ value: 'expense_vehicle', label: 'Bil & drivmedel' },
|
||||
{ value: 'expense_bank_fees', label: 'Bankavgift' },
|
||||
{ value: 'expense_card_fees', label: 'Kortavgift' },
|
||||
{ value: 'expense_currency_exchange', label: 'Valutaväxling' },
|
||||
{ value: 'expense_other', label: 'Övrig kostnad' },
|
||||
{ value: 'income_services', label: 'Tjänsteförsäljning' },
|
||||
{ value: 'income_products', label: 'Varuförsäljning' },
|
||||
{ value: 'income_other', label: 'Övrig intäkt' },
|
||||
{ value: 'private', label: 'Privat' },
|
||||
]
|
||||
|
||||
// VAT treatment options. `value` is typed as `VatTreatment` (types/index.ts)
|
||||
// so this list can never drift from what the backend accepts: the bulk-book
|
||||
// route feeds the value straight into buildMappingResultFromCategory, which
|
||||
// only recognises these six. The 12% and 6% reduced rates are ALREADY covered
|
||||
// here by `reduced_12` / `reduced_6`: there is deliberately no `standard_12` /
|
||||
// `standard_6` (no such treatment exists; the backend would reject it). Keep
|
||||
// this list in sync with the union, not with rate labels.
|
||||
const VAT_OPTIONS: { value: VatTreatment | 'auto'; label: string }[] = [
|
||||
// 'auto' sends no explicit treatment: the bulk-book route derives the
|
||||
// default from the picked category (exempt for bank/card fees, 12%
|
||||
// representation, else 25%). Reverse charge is never derived; see below.
|
||||
{ value: 'auto', label: 'Enligt kategori' },
|
||||
{ value: 'standard_25', label: 'Moms 25%' },
|
||||
{ value: 'reduced_12', label: 'Moms 12%' },
|
||||
{ value: 'reduced_6', label: 'Moms 6%' },
|
||||
{ value: 'reverse_charge', label: 'Omvänd skattskyldighet (EU/utland)' },
|
||||
{ value: 'export', label: 'Export (0%)' },
|
||||
{ value: 'exempt', label: 'Momsfri' },
|
||||
]
|
||||
|
||||
function isBookable(it: BulkBookInboxItem): boolean {
|
||||
return (
|
||||
Boolean(it.matched_transaction_id) &&
|
||||
!it.created_journal_entry_id &&
|
||||
!it.created_supplier_invoice_id &&
|
||||
// A matched transaction that is already booked has nothing left to book:
|
||||
// the server would only skip it as already_booked_or_duplicate.
|
||||
!it.matched_transaction_journal_entry_id
|
||||
)
|
||||
}
|
||||
|
||||
export default function BulkBookInboxDialog({ open, onOpenChange, items, onSuccess }: Props) {
|
||||
const { toast } = useToast()
|
||||
const t = useTranslations('inbox_bulk_book')
|
||||
const [category, setCategory] = useState<string>('')
|
||||
const [vatTreatment, setVatTreatment] = useState<VatTreatment | 'auto'>('auto')
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const bookable = useMemo(() => items.filter(isBookable), [items])
|
||||
const notMatched = useMemo(
|
||||
() => items.filter((it) => !it.matched_transaction_id && !it.created_journal_entry_id && !it.created_supplier_invoice_id).length,
|
||||
[items],
|
||||
)
|
||||
const alreadyBooked = useMemo(
|
||||
() =>
|
||||
items.filter(
|
||||
(it) =>
|
||||
it.created_journal_entry_id ||
|
||||
it.created_supplier_invoice_id ||
|
||||
it.matched_transaction_journal_entry_id,
|
||||
).length,
|
||||
[items],
|
||||
)
|
||||
|
||||
// Reset to the category-derived default each time the dialog opens.
|
||||
// Currency is deliberately NOT used to preselect omvänd skattskyldighet: a
|
||||
// foreign currency does not imply a foreign seller: a Swedish supplier can
|
||||
// invoice in EUR and still debit 25% moms. Reverse charge is a property of
|
||||
// the seller (utländsk, utan svenskt momsnr), never of the currency, and the
|
||||
// server-side derivation never produces it either, so it is only ever an
|
||||
// explicit user choice. The advisory rendered under the Moms picker spells
|
||||
// this out to the user.
|
||||
useEffect(() => {
|
||||
if (open) setVatTreatment('auto')
|
||||
}, [open])
|
||||
|
||||
// Underlag subtotals, split per currency. This used to be a single scalar
|
||||
// named `totalSek` that summed `totals.total` across the selection and was
|
||||
// rendered with formatCurrency()'s SEK default, so a mixed batch added 100
|
||||
// EUR to 100 SEK and stamped "kr" on the result: a figure the user approved
|
||||
// against that matched no belopp at all (BFL 5 kap 7 §). The split is honest
|
||||
// in both directions: a homogeneous EUR batch now reads in EUR too.
|
||||
//
|
||||
// Deliberately NOT a submit gate, unlike the mixed-currency dead end in
|
||||
// components/transactions/BulkBookDialog.tsx. That dialog builds ONE
|
||||
// samlingsverifikation, which must sit in a single redovisningsvaluta (BFL 4
|
||||
// kap 6 §). This route books one verifikat PER underlag off its matched bank
|
||||
// transaction's own settled amount (see lib/transactions/categorize-core.ts),
|
||||
// so a EUR invoice paid by a SEK bank line is booked correctly and a mixed
|
||||
// selection yields a set of individually correct verifikat. Blocking it would
|
||||
// refuse a legal everyday batch. See bulk-book-inbox-totals.ts.
|
||||
const underlagTotals = useMemo(() => summarizeUnderlagTotals(bookable), [bookable])
|
||||
const isMixedCurrency = underlagTotals.length > 1
|
||||
|
||||
const submit = async () => {
|
||||
if (!category || bookable.length === 0) return
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/invoice-inbox/items/bulk-book', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
item_ids: bookable.map((it) => it.id),
|
||||
category,
|
||||
...(vatTreatment !== 'auto' ? { vat_treatment: vatTreatment } : {}),
|
||||
}),
|
||||
})
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
throw new Error(json.error ?? `HTTP ${res.status}`)
|
||||
}
|
||||
const bookedCount: number = json.data?.booked_count ?? 0
|
||||
const skippedCount: number = json.data?.skipped_count ?? 0
|
||||
const parts: string[] = []
|
||||
if (bookedCount > 0) parts.push(`${bookedCount} bokförda`)
|
||||
if (skippedCount > 0) parts.push(`${skippedCount} överhoppade`)
|
||||
toast({
|
||||
title: 'Bulkbokföring klar',
|
||||
description: parts.join(' · ') || 'Inga underlag bokfördes',
|
||||
variant: bookedCount === 0 ? 'destructive' : 'default',
|
||||
})
|
||||
onOpenChange(false)
|
||||
await onSuccess()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Bokföringen misslyckades',
|
||||
description: err instanceof Error ? getUserErrorMessage(err) : 'Okänt fel',
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const skippedNote: string | null = useMemo(() => {
|
||||
const bits: string[] = []
|
||||
if (notMatched > 0) bits.push(`${notMatched} saknar matchad transaktion`)
|
||||
if (alreadyBooked > 0) bits.push(`${alreadyBooked} redan bokförda`)
|
||||
return bits.length > 0 ? bits.join(' · ') : null
|
||||
}, [notMatched, alreadyBooked])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Bokför {bookable.length} underlag</DialogTitle>
|
||||
<DialogDescription>
|
||||
Varje underlag bokförs mot sin matchade banktransaktion med samma kategori och momsbehandling.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="bulk-category">Kategori</Label>
|
||||
<Select value={category} onValueChange={setCategory}>
|
||||
<SelectTrigger id="bulk-category">
|
||||
<SelectValue placeholder="Välj kategori" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CATEGORY_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<Label htmlFor="bulk-vat">Moms</Label>
|
||||
<InfoTooltip
|
||||
content={
|
||||
<>
|
||||
Välj <strong>Omvänd skattskyldighet</strong> för köp från en utländsk säljare utan
|
||||
svenskt momsnummer (t.ex. EU-tjänster som moln/mjukvara). Svenska fakturor med moms:
|
||||
välj den sats kvittot visar: valutan avgör inte.
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Select value={vatTreatment} onValueChange={(v) => setVatTreatment(v as VatTreatment | 'auto')}>
|
||||
<SelectTrigger id="bulk-vat">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VAT_OPTIONS.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{vatTreatment === 'reverse_charge' && (
|
||||
<div className="rounded-lg border border-border bg-secondary/40 p-3 text-xs text-muted-foreground">
|
||||
<strong className="font-medium text-foreground">Kontrollera säljaren.</strong>{' '}
|
||||
Omvänd skattskyldighet gäller bara köp från en <strong className="font-medium text-foreground">utländsk
|
||||
säljare utan svenskt momsregistreringsnummer</strong>: t.ex. EU-tjänster, EU-varor,
|
||||
byggtjänster eller viss elektronik. Valutan avgör inte: en svensk säljare kan fakturera i
|
||||
EUR och ändå debitera 25% moms. Är säljaren svensk och momsen står på kvittot, välj i
|
||||
stället rätt momssats ovan.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isMixedCurrency && underlagTotals.length === 1 && (
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{t('total_label', {
|
||||
amount: formatCurrency(underlagTotals[0]!.total, underlagTotals[0]!.currency),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{isMixedCurrency && (
|
||||
<div className="rounded-lg border border-border bg-secondary/40 p-3 text-xs text-muted-foreground">
|
||||
<p className="font-medium text-foreground">{t('mixed_currency_totals_label')}</p>
|
||||
<ul className="mt-2 space-y-1">
|
||||
{underlagTotals.map(({ currency, total }) => (
|
||||
<li key={currency} className="flex items-center justify-between tabular-nums">
|
||||
<span className="font-mono">{currency}</span>
|
||||
<span className="text-foreground">{formatCurrency(total, currency)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-2">{t('mixed_currency_note')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{skippedNote && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Hoppas över: {skippedNote}.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={isSubmitting || !category || bookable.length === 0}>
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Bokför {bookable.length} underlag
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { guardBrowserWrite } from '@/lib/company/tab-guard'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { PaymentCalendar } from '@/extensions/general/calendar/components/PaymentCalendar'
|
||||
import type { DeadlineFormValues } from '@/components/deadlines/DeadlineForm'
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
import type { Invoice, Deadline } from '@/types'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
export default function CalendarWorkspace({ userId }: WorkspaceComponentProps) {
|
||||
const [invoices, setInvoices] = useState<Invoice[]>([])
|
||||
const [deadlines, setDeadlines] = useState<Deadline[]>([])
|
||||
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const { data: invoicesData, error: invoicesError } = await supabase
|
||||
.from('invoices')
|
||||
.select('*, customer:customers(name)')
|
||||
.order('due_date', { ascending: true })
|
||||
|
||||
if (invoicesError) throw invoicesError
|
||||
|
||||
const { data: deadlinesData, error: deadlinesError } = await supabase
|
||||
.from('deadlines')
|
||||
.select('*, customer:customers(name)')
|
||||
.is('dismissed_at', null)
|
||||
.order('due_date', { ascending: true })
|
||||
|
||||
if (deadlinesError) throw deadlinesError
|
||||
|
||||
const { data: customersData, error: customersError } = await supabase
|
||||
.from('customers')
|
||||
.select('id, name')
|
||||
.is('archived_at', null)
|
||||
.order('name', { ascending: true })
|
||||
|
||||
if (customersError) throw customersError
|
||||
|
||||
setInvoices(invoicesData || [])
|
||||
setDeadlines(deadlinesData || [])
|
||||
setCustomers(customersData || [])
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte hämta data',
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [supabase, toast])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const handleDeadlineCreate = async (data: DeadlineFormValues) => {
|
||||
// Cross-tab guard (WL-09): browser-direct Supabase write, outside the
|
||||
// patched-fetch seam. The blocking dialog is the user feedback.
|
||||
if (!guardBrowserWrite()) return
|
||||
try {
|
||||
const { error } = await supabase.from('deadlines').insert([data])
|
||||
|
||||
if (error) throw error
|
||||
|
||||
toast({
|
||||
title: 'Deadline skapad',
|
||||
description: 'Din deadline har sparats',
|
||||
})
|
||||
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte skapa deadline',
|
||||
variant: 'destructive',
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeadlineToggle = async (deadline: Deadline) => {
|
||||
if (!guardBrowserWrite()) return
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('deadlines')
|
||||
.update({
|
||||
is_completed: !deadline.is_completed,
|
||||
completed_at: !deadline.is_completed ? new Date().toISOString() : null,
|
||||
})
|
||||
.eq('id', deadline.id)
|
||||
|
||||
if (error) throw error
|
||||
|
||||
toast({
|
||||
title: deadline.is_completed ? 'Markerad som ej klar' : 'Markerad som klar',
|
||||
})
|
||||
|
||||
fetchData()
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte uppdatera deadline',
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-10 w-48" />
|
||||
<Skeleton className="h-96 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PaymentCalendar
|
||||
invoices={invoices}
|
||||
deadlines={deadlines}
|
||||
customers={customers}
|
||||
onDeadlineCreate={handleDeadlineCreate}
|
||||
onDeadlineToggle={handleDeadlineToggle}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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 text-foreground">Molnsynkronisering</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 max-w-md">
|
||||
Koppla ditt Google Drive- eller Dropbox-konto under Importera/Exportera för att
|
||||
synka arkiv till din egen molnlagring.
|
||||
</p>
|
||||
<Button asChild variant="outline" className="mt-4">
|
||||
<Link href="/import#cloud-backup">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Gå till säkerhetskopiering
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Change everything about a proposed kontering, in one place.
|
||||
*
|
||||
* The rail used to offer three overlapping ways to alter a booking, none of
|
||||
* which said what it covered: an "Ändra" beside the date, an "Ändra kontering"
|
||||
* at the bottom, and a "Bokför som verifikat" entry in a menu that in practice
|
||||
* did what the primary button already did. This is the one control, and its
|
||||
* scope is the whole verifikat: date, series, description, every line.
|
||||
*
|
||||
* It is a dialog rather than an inline editor because a 340px rail cannot hold
|
||||
* an account picker, two money columns and a delete control per row without
|
||||
* something being clipped, and because the document has to stay readable while
|
||||
* the numbers are being changed. That is the same shape TransactionBookingDialog
|
||||
* already uses, for the same reason.
|
||||
*
|
||||
* The form is JournalEntryForm, unchanged. It already carries the series
|
||||
* picker, per-line descriptions, dimensions, currency, the balance check and
|
||||
* the confirm-before-post step, and it posts through the sanctioned route. The
|
||||
* alternative was extending BookDirectlyDialog, whose lines are seeded by three
|
||||
* effects that fight anything injected into them, and whose FormLine has no
|
||||
* room for line text, dimensions or tax codes.
|
||||
*/
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import JournalEntryForm from '@/components/bookkeeping/JournalEntryForm'
|
||||
import DocumentViewerPane from '@/components/bookkeeping/DocumentViewerPane'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
|
||||
export interface ProposedLine {
|
||||
account_number: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
description: string
|
||||
}
|
||||
|
||||
export default function EditKonteringDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
itemId,
|
||||
documentId,
|
||||
documentMime,
|
||||
documentUrl,
|
||||
fileName,
|
||||
transactionId,
|
||||
entryDate,
|
||||
description,
|
||||
lines,
|
||||
matchedTransaction = null,
|
||||
onBooked,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
itemId: string
|
||||
documentId: string | null
|
||||
documentMime: string | null
|
||||
documentUrl: string | null
|
||||
fileName: string | null
|
||||
transactionId: string | null
|
||||
entryDate: string
|
||||
description: string
|
||||
lines: ProposedLine[]
|
||||
/** SEK amount and date of the matched bank row, when there is one. Shown
|
||||
beside the title so the kronor figure stays visible even if the user
|
||||
clears the rows: on a foreign-currency invoice this is the only place
|
||||
the SEK amount exists at all. */
|
||||
matchedTransaction?: { amount_sek: number; date: string } | null
|
||||
onBooked: (entryId: string) => void
|
||||
}) {
|
||||
const t = useTranslations('inbox_workspace')
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Ändra kontering</DialogTitle>
|
||||
{matchedTransaction && (
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{t('dialog_matched_transaction')}: {formatCurrency(matchedTransaction.amount_sek)} ·{' '}
|
||||
{formatDate(matchedTransaction.date)}
|
||||
</p>
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,480px)]">
|
||||
<div className="min-w-0">
|
||||
<JournalEntryForm
|
||||
// Remount per item so a second underlag never inherits the
|
||||
// first one's draft: the form seeds its state from the initial
|
||||
// props once, by design.
|
||||
key={itemId}
|
||||
embedded
|
||||
// An unknown supplier has no proposal, and passing [] here is
|
||||
// not the same as passing nothing: the form seeds two blank rows
|
||||
// only when this is undefined, so an empty array opened the
|
||||
// dialog with no rows at all and a "lägg till rad" between the
|
||||
// user and typing anything.
|
||||
initialLines={
|
||||
lines.length > 0
|
||||
? lines.map((l) => ({
|
||||
account_number: l.account_number,
|
||||
debit_amount: l.debit_amount ? String(l.debit_amount) : '',
|
||||
credit_amount: l.credit_amount ? String(l.credit_amount) : '',
|
||||
line_description: l.description,
|
||||
}))
|
||||
: undefined
|
||||
}
|
||||
initialDate={entryDate}
|
||||
initialDescription={description}
|
||||
submitUrl={`/api/extensions/ext/invoice-inbox/items/${itemId}/book-direct`}
|
||||
sourceType={transactionId ? 'bank_transaction' : 'manual'}
|
||||
sourceId={transactionId ?? undefined}
|
||||
// source_id is metadata the schema strips. The route needs
|
||||
// transaction_id to book the underlag against its bank line;
|
||||
// without it the verifikat posts standalone, the transaction
|
||||
// stays unbooked and the match is cleared.
|
||||
extraBody={transactionId ? { transaction_id: transactionId } : undefined}
|
||||
onEntryCreated={onBooked}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* The document stays readable while the numbers change: checking a
|
||||
VAT rate against the paper is the reason to open this at all. */}
|
||||
<aside className="min-w-0">
|
||||
{documentId ? (
|
||||
<DocumentViewerPane
|
||||
documentId={documentId}
|
||||
mime={documentMime}
|
||||
downloadUrl={documentUrl}
|
||||
fileName={fileName}
|
||||
className="h-[60vh]"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-[60vh] grid place-items-center rounded-lg border text-xs text-muted-foreground">
|
||||
{t('dialog_no_document')}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
'use client'
|
||||
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Landmark, Settings } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
|
||||
export default function EnableBankingWorkspace({ userId }: WorkspaceComponentProps) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||
<Landmark className="h-12 w-12 text-muted-foreground/40 mb-4" />
|
||||
<h3 className="text-lg text-foreground">Bankintegration (PSD2)</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 max-w-md">
|
||||
Koppla ditt bankkonto under Inställningar för att synka transaktioner automatiskt.
|
||||
</p>
|
||||
<Button asChild variant="outline" className="mt-4">
|
||||
<Link href="/settings/banking">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Gå till bankinställningar
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { AlertTriangle, Check, Copy, Loader2, RefreshCw, Trash2 } from 'lucide-react'
|
||||
import type { CompanyInboundDomain, InboundDomainDnsRecord } from '@/types'
|
||||
import { getErrorMessage as getUserErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { useFormat } from '@/lib/hooks/use-format'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { copyToClipboard } from '@/lib/browser/copy-to-clipboard'
|
||||
import { useBranding } from '@/lib/branding/brand-context'
|
||||
|
||||
const BASE = '/api/extensions/ext/invoice-inbox/inbox/domain'
|
||||
|
||||
const STATUS_VARIANT: Record<
|
||||
CompanyInboundDomain['status'],
|
||||
'secondary' | 'success' | 'destructive'
|
||||
> = {
|
||||
pending: 'secondary',
|
||||
verified: 'success',
|
||||
failed: 'destructive',
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
// Settings dialog for a company's own inbound domain. Claims the domain via
|
||||
// the extension API, renders the DNS records the user must publish, and
|
||||
// re-checks verification on demand. Everything mail-routing happens
|
||||
// server-side: this surface only manages the claim lifecycle.
|
||||
export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
|
||||
const { toast } = useToast()
|
||||
const { appName } = useBranding()
|
||||
const t = useTranslations('inbox_custom_domain')
|
||||
const { locale, formatDateLong } = useFormat()
|
||||
const errorLocale = locale as ErrorLocale
|
||||
const { role } = useCompany()
|
||||
const canManage = role === 'owner' || role === 'admin'
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [domain, setDomain] = useState<CompanyInboundDomain | null>(null)
|
||||
const [domainInput, setDomainInput] = useState('')
|
||||
const [isClaiming, setIsClaiming] = useState(false)
|
||||
const [isChecking, setIsChecking] = useState(false)
|
||||
const [isRemoving, setIsRemoving] = useState(false)
|
||||
|
||||
const fetchDomain = useCallback(async () => {
|
||||
setIsLoading(true)
|
||||
setLoadFailed(false)
|
||||
try {
|
||||
const res = await fetch(BASE)
|
||||
if (!res.ok) {
|
||||
setLoadFailed(true)
|
||||
return
|
||||
}
|
||||
const json = await res.json()
|
||||
setDomain(json.data ?? null)
|
||||
} catch {
|
||||
setLoadFailed(true)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (open) fetchDomain()
|
||||
}, [open, fetchDomain])
|
||||
|
||||
const handleClaim = useCallback(async () => {
|
||||
if (!domainInput.trim()) return
|
||||
setIsClaiming(true)
|
||||
try {
|
||||
const res = await fetch(BASE, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ domain: domainInput }),
|
||||
})
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? t('claim_error_title'))
|
||||
setDomain(json.data)
|
||||
setDomainInput('')
|
||||
toast({
|
||||
title: t('claim_success_title'),
|
||||
description: t('claim_success_description'),
|
||||
})
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('claim_error_title'),
|
||||
description: err instanceof Error ? getUserErrorMessage(err, { locale: errorLocale }) : t('try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsClaiming(false)
|
||||
}
|
||||
}, [domainInput, errorLocale, t, toast])
|
||||
|
||||
const handleVerify = useCallback(async () => {
|
||||
setIsChecking(true)
|
||||
try {
|
||||
const res = await fetch(`${BASE}/verify`, { method: 'POST' })
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? t('verify_error_title'))
|
||||
setDomain(json.data)
|
||||
toast(
|
||||
json.data.status === 'verified'
|
||||
? { title: t('verify_success_title'), description: t('verify_success_description') }
|
||||
: { title: t('verify_pending_title'), description: t('verify_pending_description') }
|
||||
)
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('verify_error_title'),
|
||||
description: err instanceof Error ? getUserErrorMessage(err, { locale: errorLocale }) : t('try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsChecking(false)
|
||||
}
|
||||
}, [errorLocale, t, toast])
|
||||
|
||||
const handleRemove = useCallback(async () => {
|
||||
if (!domain) return
|
||||
if (!confirm(t('remove_confirm', { domain: domain.domain, appName }))) return
|
||||
setIsRemoving(true)
|
||||
try {
|
||||
const res = await fetch(BASE, { method: 'DELETE' })
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error ?? t('remove_error_title'))
|
||||
setDomain(null)
|
||||
toast({ title: t('remove_success_title') })
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('remove_error_title'),
|
||||
description: err instanceof Error ? getUserErrorMessage(err, { locale: errorLocale }) : t('try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsRemoving(false)
|
||||
}
|
||||
}, [domain, errorLocale, t, toast, appName])
|
||||
|
||||
const handleCopy = useCallback(
|
||||
async (value: string) => {
|
||||
const result = await copyToClipboard(value)
|
||||
toast(
|
||||
result === 'copied'
|
||||
? { title: t('copied') }
|
||||
: {
|
||||
title: t('copy_failed_title'),
|
||||
description: t('copy_failed_description'),
|
||||
variant: 'destructive',
|
||||
}
|
||||
)
|
||||
},
|
||||
[t, toast]
|
||||
)
|
||||
|
||||
const records: InboundDomainDnsRecord[] = domain?.dns_records ?? []
|
||||
const statusLabels: Record<CompanyInboundDomain['status'], string> = {
|
||||
pending: t('status_pending'),
|
||||
verified: t('status_verified'),
|
||||
failed: t('status_failed'),
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-24 w-full" />
|
||||
</div>
|
||||
) : loadFailed ? (
|
||||
<div role="status" className="flex items-center justify-between gap-4 text-sm">
|
||||
<p className="text-muted-foreground">{t('load_error')}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void fetchDomain()
|
||||
}}
|
||||
>
|
||||
{t('retry')}
|
||||
</Button>
|
||||
</div>
|
||||
) : !domain ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border p-4 text-sm">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 mt-0.5 text-muted-foreground" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">{t('warning_title')}</p>
|
||||
<p className="text-muted-foreground">
|
||||
{t('warning_before_subdomain', { appName })}{' '}
|
||||
<code className="font-mono text-xs">faktura.dittbolag.se</code>{' '}
|
||||
{t('warning_after_subdomain')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canManage ? (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={domainInput}
|
||||
onChange={(e) => setDomainInput(e.target.value)}
|
||||
placeholder="faktura.dittbolag.se"
|
||||
aria-label={t('domain_input_aria')}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') handleClaim()
|
||||
}}
|
||||
/>
|
||||
<Button onClick={handleClaim} disabled={isClaiming || !domainInput.trim()}>
|
||||
{isClaiming ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : null}
|
||||
{t('add_button')}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">{t('manage_permission')}</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<code className="font-mono text-sm truncate">{domain.domain}</code>
|
||||
<Badge variant={STATUS_VARIANT[domain.status]}>
|
||||
{statusLabels[domain.status]}
|
||||
</Badge>
|
||||
</div>
|
||||
{canManage ? (
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleVerify}
|
||||
disabled={isChecking}
|
||||
>
|
||||
{isChecking ? (
|
||||
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3.5 w-3.5 mr-1.5" />
|
||||
)}
|
||||
{t('check_again')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleRemove}
|
||||
disabled={isRemoving}
|
||||
aria-label={t('remove_aria')}
|
||||
>
|
||||
{isRemoving ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{domain.status === 'verified' ? (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border p-4 text-sm">
|
||||
<Check className="h-4 w-4 shrink-0 mt-0.5 text-muted-foreground" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">
|
||||
{t('verified_title')}{' '}
|
||||
<code className="font-mono text-xs">faktura@{domain.domain}</code>
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
{domain.verified_at
|
||||
? t('verified_description_with_date', {
|
||||
date: formatDateLong(domain.verified_at),
|
||||
})
|
||||
: t('verified_description')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('dns_instructions')}
|
||||
</p>
|
||||
{records.length > 0 ? (
|
||||
<div className="rounded-lg border border-border overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_type')}</th>
|
||||
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_name')}</th>
|
||||
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_value')}</th>
|
||||
<th className="px-3 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_priority')}</th>
|
||||
<th className="px-3 py-2" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{records.map((r, i) => (
|
||||
<tr key={`${r.type}-${r.name}-${i}`} className="border-b border-border last:border-0">
|
||||
<td className="px-3 py-2 font-mono text-xs">{r.type}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs break-all">{r.name}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs break-all">{r.value}</td>
|
||||
<td className="px-3 py-2 font-mono text-xs text-right tabular-nums">
|
||||
{r.priority ?? '-'}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
void handleCopy(r.value)
|
||||
}}
|
||||
aria-label={t('copy_record_aria', { type: r.type })}
|
||||
>
|
||||
<Copy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('dns_empty')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
// Single source of truth for the Dokumentinkorg loading silhouette, rendered
|
||||
// by both the route-level loading.tsx and the workspace's own client-fetch
|
||||
// state so the route fallback, the fetch shell, and the loaded UI are one
|
||||
// shape with no reflow. Mirrors the live layout: full-bleed top bar +
|
||||
// 3-pane grid, list pane with search + filter-dropdown trigger (PR #1524
|
||||
// replaced the old filter-pill row with a single full-width dropdown).
|
||||
export default function InvoiceInboxSkeleton() {
|
||||
return (
|
||||
<div className="h-[calc(100vh-1px)] md:h-full">
|
||||
<div className="h-full flex flex-col overflow-hidden">
|
||||
<header className="flex items-center justify-between gap-4 border-b px-4 py-2.5">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Skeleton className="h-4 w-4 shrink-0" />
|
||||
<Skeleton className="h-4 w-32 shrink-0" />
|
||||
<Skeleton className="hidden md:block h-3 w-56" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-28 shrink-0" />
|
||||
</header>
|
||||
<div className="flex-1 grid grid-cols-1 xl:grid-cols-[280px_minmax(0,1fr)_340px] min-h-0">
|
||||
<aside className="border-b xl:border-b-0 xl:border-r overflow-hidden bg-muted/20 pt-3">
|
||||
<div className="px-3 pb-3 space-y-2 border-b">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
<ul>
|
||||
{Array.from({ length: 7 }).map((_, i) => (
|
||||
<li key={i} className="border-b px-3 py-2 flex flex-col gap-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-3 w-3 shrink-0" />
|
||||
<Skeleton className="h-3.5 flex-1 max-w-[180px]" />
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Skeleton className="h-3 w-16" />
|
||||
<Skeleton className="h-3 w-12" />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</aside>
|
||||
<main className="overflow-hidden bg-muted/10 hidden xl:block" />
|
||||
<aside className="border-l overflow-hidden hidden xl:block" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,216 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
|
||||
import { GoogleMark, MicrosoftMark } from '@/components/ui/provider-marks'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
|
||||
interface MailConnection {
|
||||
id: string
|
||||
provider: 'gmail' | 'microsoft'
|
||||
emailAddress: string
|
||||
scopeLabel: string | null
|
||||
status: 'active' | 'needs_reconsent' | 'revoked'
|
||||
lastSearchedAt: string | null
|
||||
lastErrorCode: string | null
|
||||
}
|
||||
|
||||
import { useReceiptHunt } from '@/components/extensions/general/use-receipt-hunt'
|
||||
|
||||
const BASE = '/api/extensions/ext/mail'
|
||||
|
||||
export function MailConnectionsPanel() {
|
||||
const t = useTranslations('mail')
|
||||
const [connections, setConnections] = useState<MailConnection[]>([])
|
||||
const [configured, setConfigured] = useState(true)
|
||||
// False while Google's scope review keeps new consents withheld on hosted:
|
||||
// the connect button is simply absent, existing mailboxes stay listed.
|
||||
const [connectEnabled, setConnectEnabled] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [connecting, setConnecting] = useState(false)
|
||||
const [pendingDisconnect, setPendingDisconnect] = useState<MailConnection | null>(null)
|
||||
const { hunt, stop: stopHunt, hunting, progress, result: huntResult } = useReceiptHunt(() => void load())
|
||||
// Read inside the loop, so pressing Stop takes effect on the current pass
|
||||
// rather than after every remaining pass has run.
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${BASE}/connections`)
|
||||
if (!response.ok) return
|
||||
const body = (await response.json()) as {
|
||||
data: { connections: MailConnection[]; configured: boolean; connectEnabled?: boolean }
|
||||
}
|
||||
setConnections(body.data.connections)
|
||||
setConfigured(body.data.configured)
|
||||
setConnectEnabled(body.data.connectEnabled === true)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
async function connect() {
|
||||
setConnecting(true)
|
||||
try {
|
||||
// The consent screen must open from the user's own gesture, so the tab is
|
||||
// opened first and its location set once the URL is known: opening it
|
||||
// after the await is what popup blockers stop.
|
||||
const tab = window.open('', '_blank')
|
||||
const response = await fetch(`${BASE}/oauth/start`, { method: 'POST' })
|
||||
if (!response.ok) {
|
||||
tab?.close()
|
||||
return
|
||||
}
|
||||
const body = (await response.json()) as { url: string }
|
||||
if (tab) tab.location.href = body.url
|
||||
else window.location.href = body.url
|
||||
} finally {
|
||||
setConnecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One bounded pass, on request.
|
||||
*
|
||||
* Deliberately not a background job: a sweep of a real mailbox runs longer
|
||||
* than a serverless function may live, so the honest shape is a pass that
|
||||
* ends, says what it found and what is left, and can be pressed again.
|
||||
*/
|
||||
/**
|
||||
* Keep asking until the mailboxes stop yielding.
|
||||
*
|
||||
* Each request is a bounded pass, because fetching a receipt means
|
||||
* downloading it and having a model read the PDF, which is far too slow to
|
||||
* finish a backlog inside one serverless invocation. The loop lives here
|
||||
* rather than in a queue drained by cron: the finest schedule this app runs
|
||||
* is hourly, so a queue would mean pressing a button and waiting an hour.
|
||||
*
|
||||
* It stops when a pass finds nothing new, which is the honest signal that
|
||||
* the mailboxes hold nothing more for the purchases still open. The cap is a
|
||||
* backstop against a pass that keeps reporting work it cannot finish.
|
||||
*/
|
||||
|
||||
async function disconnect(connection: MailConnection) {
|
||||
await fetch(`${BASE}/connections?id=${encodeURIComponent(connection.id)}`, { method: 'DELETE' })
|
||||
setPendingDisconnect(null)
|
||||
void load()
|
||||
}
|
||||
|
||||
if (loading) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<SettingsGroup label={t('connected')} help={t('help')}>
|
||||
{connections.length === 0 ? (
|
||||
<SettingsRow label={t('none_label')} borderless>
|
||||
<SettingsRowNote>{t('none')}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
) : (
|
||||
connections.map((connection) => (
|
||||
<SettingsRow
|
||||
key={connection.id}
|
||||
label={
|
||||
<span className="flex items-center gap-2">
|
||||
{connection.provider === 'gmail' ? (
|
||||
<GoogleMark className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<MicrosoftMark className="h-3.5 w-3.5" />
|
||||
)}
|
||||
{connection.provider === 'gmail' ? 'Gmail' : 'Microsoft 365'}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate">{connection.emailAddress}</span>
|
||||
{connection.status === 'needs_reconsent' ? (
|
||||
<Badge variant="warning">{t('needs_reconsent')}</Badge>
|
||||
) : null}
|
||||
<SettingsRowEnd>
|
||||
{connection.lastSearchedAt ? (
|
||||
<SettingsRowNote>
|
||||
{t('last_searched', { date: formatDateLong(connection.lastSearchedAt, 'sv') })}
|
||||
</SettingsRowNote>
|
||||
) : null}
|
||||
<Button variant="ghost" size="sm" onClick={() => setPendingDisconnect(connection)}>
|
||||
{t('disconnect')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
))
|
||||
)}
|
||||
</SettingsGroup>
|
||||
|
||||
{connections.length > 0 ? (
|
||||
<SettingsGroup label={t('hunt_title')} help={t('hunt_help')}>
|
||||
<SettingsRow label={t('hunt_row')} borderless>
|
||||
<SettingsRowEnd>
|
||||
{huntResult ? (
|
||||
<SettingsRowNote>
|
||||
{huntResult.failed
|
||||
? t('hunt_failed')
|
||||
: huntResult.fetched > 0
|
||||
? t('hunt_found', { count: huntResult.fetched, left: huntResult.remaining })
|
||||
: t('hunt_none', { left: huntResult.remaining })}
|
||||
</SettingsRowNote>
|
||||
) : null}
|
||||
{hunting ? (
|
||||
<Button variant="ghost" size="sm" onClick={stopHunt}>
|
||||
{t('hunt_stop')}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="secondary" size="sm" onClick={hunt} disabled={hunting}>
|
||||
{hunting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
{hunting
|
||||
? progress
|
||||
? t('hunt_progress', { fetched: progress.fetched })
|
||||
: t('hunt_running')
|
||||
: t('hunt_action')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
) : null}
|
||||
|
||||
{connectEnabled ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={connect} disabled={connecting || !configured}>
|
||||
{connecting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<GoogleMark className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('connect')}
|
||||
</Button>
|
||||
{!configured ? <SettingsRowNote>{t('not_configured')}</SettingsRowNote> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{connectEnabled || connections.length > 0 ? (
|
||||
<p className="max-w-[62ch] text-xs text-muted-foreground">{t('promise')}</p>
|
||||
) : null}
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingDisconnect !== null}
|
||||
onOpenChange={(open) => !open && setPendingDisconnect(null)}
|
||||
title={t('disconnect_title')}
|
||||
description={t('disconnect_body', { address: pendingDisconnect?.emailAddress ?? '' })}
|
||||
confirmLabel={t('disconnect')}
|
||||
onConfirm={async () => {
|
||||
if (pendingDisconnect) await disconnect(pendingDisconnect)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
'use client'
|
||||
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
import EmptyExtensionState from '@/components/extensions/shared/EmptyExtensionState'
|
||||
import { Bell } from 'lucide-react'
|
||||
|
||||
export default function PushNotificationsWorkspace({ userId }: WorkspaceComponentProps) {
|
||||
return (
|
||||
<EmptyExtensionState
|
||||
title="Push-notiser"
|
||||
description="Konfigurera push-notiser under Inställningar. Notiser skickas automatiskt vid viktiga händelser."
|
||||
icon={<Bell className="h-12 w-12 text-muted-foreground/40 mb-4" />}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import { ExpenseClaimantFields } from '@/components/expenses/ExpenseClaimantFields'
|
||||
import { useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
import { useAccounts } from '@/lib/reference-data/hooks'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { ACCOUNT_NUMBER_RE, ISO_DATE_RE } from '@/lib/invariants'
|
||||
import { OWNER_FALLBACK_NAME, resolveExpenseLiabilityAccount, type ExpensePayer } from '@/lib/expenses/payer'
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
|
||||
// Who paid for the underlag out of their own pocket. The account rule (2893
|
||||
// AB owner / 2018 EF owner / 2820 employee) lives in lib/expenses/payer.ts,
|
||||
// shared with the supplier-invoice form.
|
||||
export type { ExpensePayer }
|
||||
|
||||
interface InboxItemLike {
|
||||
id: string
|
||||
document_id: string | null
|
||||
extracted_data: InvoiceExtractionResult | null
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
item: InboxItemLike
|
||||
payer: ExpensePayer
|
||||
/** Re-read the item after the claim posted its verifikat. */
|
||||
onSuccess: () => void | Promise<void>
|
||||
}
|
||||
|
||||
function todayIso(): string {
|
||||
// Local calendar date: toISOString() is UTC and would date a receipt booked
|
||||
// after midnight CEST to the previous day (wrong period, wrong FX rate).
|
||||
const now = new Date()
|
||||
const mm = String(now.getMonth() + 1).padStart(2, '0')
|
||||
const dd = String(now.getDate()).padStart(2, '0')
|
||||
return `${now.getFullYear()}-${mm}-${dd}`
|
||||
}
|
||||
|
||||
function parseAmount(raw: string): number {
|
||||
const n = parseFloat(raw.replace(/\s/g, '').replace(',', '.'))
|
||||
return Number.isFinite(n) ? n : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterExpenseDialog: the confirm step behind "Vem betalade? Jag, privat /
|
||||
* En anställd" in the Underlag pane. One screen, prefilled from the
|
||||
* extraction: who, cost account, amount and VAT, then the outcome spelled out
|
||||
* before anything posts (design convention 10). Posts through
|
||||
* POST /api/expense-claims, which books cost + moms against the person's
|
||||
* liability account and stamps the inbox item as booked.
|
||||
*/
|
||||
export default function RegisterExpenseDialog({ open, onOpenChange, item, payer, onSuccess }: Props) {
|
||||
const t = useTranslations('inbox_workspace')
|
||||
const { toast } = useToast()
|
||||
const { accounts } = useAccounts()
|
||||
const entityType = useCompanyOptional()?.company?.entity_type ?? null
|
||||
const liabilityAccount = resolveExpenseLiabilityAccount(entityType, payer)
|
||||
|
||||
const data = item.extracted_data
|
||||
const [description, setDescription] = useState('')
|
||||
const [expenseDate, setExpenseDate] = useState(todayIso())
|
||||
const [amountInput, setAmountInput] = useState('')
|
||||
const [vatInput, setVatInput] = useState('')
|
||||
const [expenseAccount, setExpenseAccount] = useState('')
|
||||
const [ownerName, setOwnerName] = useState('')
|
||||
const [employeeId, setEmployeeId] = useState('')
|
||||
const [employeeName, setEmployeeName] = useState('')
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const currency = (data?.invoice?.currency ?? 'SEK').toUpperCase()
|
||||
// A foreign receipt carries VAT the company cannot deduct on 2641: the whole
|
||||
// amount is cost. The wizard asked for the seller's country; here the
|
||||
// currency is the signal, and the note under the preview says so.
|
||||
const isForeign = currency !== 'SEK'
|
||||
const isEf = entityType === 'enskild_firma'
|
||||
|
||||
// Reset per open so a previous underlag's numbers never carry over.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setDescription(data?.supplier?.name?.trim() || '')
|
||||
setExpenseDate(data?.invoice?.invoiceDate || todayIso())
|
||||
const total = data?.totals?.total
|
||||
const vat = data?.totals?.vatAmount
|
||||
setAmountInput(total != null && total > 0 ? String(roundOre(total)).replace('.', ',') : '')
|
||||
setVatInput(!isForeign && vat != null && vat > 0 ? String(roundOre(vat)).replace('.', ',') : '0')
|
||||
setExpenseAccount('')
|
||||
setEmployeeId('')
|
||||
setEmployeeName('')
|
||||
}, [open, item.id, data, isForeign])
|
||||
|
||||
const amount = parseAmount(amountInput)
|
||||
// Foreign VAT is never deductible here: the field is locked and 0 is what
|
||||
// gets submitted, whatever the extraction said.
|
||||
const vatAmount = isForeign ? 0 : parseAmount(vatInput)
|
||||
const net = roundOre(amount - vatAmount)
|
||||
const claimantName = payer === 'owner' ? ownerName.trim() || OWNER_FALLBACK_NAME : employeeName
|
||||
|
||||
const canSubmit =
|
||||
!isSubmitting &&
|
||||
description.trim().length > 0 &&
|
||||
ISO_DATE_RE.test(expenseDate) &&
|
||||
amount > 0 &&
|
||||
vatAmount >= 0 &&
|
||||
vatAmount < amount &&
|
||||
ACCOUNT_NUMBER_RE.test(expenseAccount) &&
|
||||
/^[4-8]/.test(expenseAccount) &&
|
||||
(payer === 'owner' || !!employeeId)
|
||||
|
||||
const accountName = useMemo(
|
||||
() => accounts.find((a) => a.account_number === expenseAccount)?.account_name ?? '',
|
||||
[accounts, expenseAccount],
|
||||
)
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!canSubmit) return
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const body: Record<string, unknown> = {
|
||||
description: description.trim(),
|
||||
expense_date: expenseDate,
|
||||
amount,
|
||||
vat_amount: vatAmount,
|
||||
currency,
|
||||
expense_account: expenseAccount,
|
||||
inbox_item_id: item.id,
|
||||
document_id: item.document_id ?? undefined,
|
||||
}
|
||||
if (payer === 'owner') body.claimant_name = claimantName
|
||||
else body.employee_id = employeeId
|
||||
const res = await fetch('/api/expense-claims', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const json = (await res.json().catch(() => ({}))) as {
|
||||
data?: { journal_entry_id?: string | null }
|
||||
error?: unknown
|
||||
}
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: t('expense_failed_title'),
|
||||
description: getErrorMessage(json, { context: 'journal_entry', statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: t('expense_booked_title'),
|
||||
description: t('expense_booked_description', { name: claimantName }),
|
||||
})
|
||||
await onSuccess()
|
||||
onOpenChange(false)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}, [
|
||||
canSubmit,
|
||||
description,
|
||||
expenseDate,
|
||||
amount,
|
||||
vatAmount,
|
||||
currency,
|
||||
expenseAccount,
|
||||
item.id,
|
||||
item.document_id,
|
||||
payer,
|
||||
claimantName,
|
||||
employeeId,
|
||||
toast,
|
||||
t,
|
||||
onSuccess,
|
||||
onOpenChange,
|
||||
])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => !isSubmitting && onOpenChange(next)}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('expense_dialog_title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{payer === 'owner'
|
||||
? isEf
|
||||
? t('expense_dialog_help_owner_ef')
|
||||
: t('expense_dialog_help_owner', { account: liabilityAccount })
|
||||
: t('expense_dialog_help_employee')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<ExpenseClaimantFields
|
||||
payer={payer}
|
||||
ownerName={ownerName}
|
||||
onOwnerNameChange={setOwnerName}
|
||||
employeeId={employeeId}
|
||||
onEmployeeChange={(id, name) => {
|
||||
setEmployeeId(id)
|
||||
setEmployeeName(name)
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
idPrefix="re"
|
||||
/>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="re-description">{t('expense_description')}</Label>
|
||||
<Input
|
||||
id="re-description"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="re-date">{t('expense_date')}</Label>
|
||||
<Input
|
||||
id="re-date"
|
||||
type="date"
|
||||
value={expenseDate}
|
||||
onChange={(e) => setExpenseDate(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="re-amount">{t('expense_amount', { currency })}</Label>
|
||||
<Input
|
||||
id="re-amount"
|
||||
inputMode="decimal"
|
||||
value={amountInput}
|
||||
onChange={(e) => setAmountInput(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="re-vat">{t('expense_vat')}</Label>
|
||||
<Input
|
||||
id="re-vat"
|
||||
inputMode="decimal"
|
||||
value={isForeign ? '0' : vatInput}
|
||||
onChange={(e) => setVatInput(e.target.value)}
|
||||
disabled={isSubmitting || isForeign}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t('expense_account')}</Label>
|
||||
<AccountCombobox
|
||||
value={expenseAccount}
|
||||
accounts={accounts}
|
||||
onChange={setExpenseAccount}
|
||||
disabled={isSubmitting}
|
||||
selectedName={accountName}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{amount > 0 && vatAmount < amount && (
|
||||
<div className="rounded-lg border border-border px-4 py-3 text-xs text-muted-foreground space-y-1">
|
||||
<p className="tabular-nums">
|
||||
{expenseAccount || '____'} D {formatCurrency(net, currency)}
|
||||
{vatAmount > 0 ? ` · 2641 D ${formatCurrency(vatAmount, currency)}` : ''}
|
||||
{` · ${liabilityAccount} K ${formatCurrency(amount, currency)}`}
|
||||
</p>
|
||||
{payer === 'owner' && isEf ? (
|
||||
<p>{t('expense_outcome_ef')}</p>
|
||||
) : (
|
||||
claimantName && <p>{t('expense_outcome_att_gora', { name: claimantName })}</p>
|
||||
)}
|
||||
{isForeign && <p>{t('expense_fx_note')}</p>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
|
||||
{t('expense_cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={!canSubmit}>
|
||||
{isSubmitting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
{t('expense_confirm')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,321 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Settings panel for the whatsapp-inbox extension (Inställningar -> WhatsApp).
|
||||
*
|
||||
* Unlinked: mint a one-time code (10 min TTL) + wa.me deep link; the user
|
||||
* sends the code from their phone and the webhook binds the number.
|
||||
* Linked: masked phone, default-company select (multi-company routing),
|
||||
* revoke. Muted (user sent *stopp* in chat) can be lifted here (or with
|
||||
* *start* in the chat); no proactive confirmation is possible afterwards
|
||||
* (24h service window, v1 sends no templates), so the hint says to just
|
||||
* send the next receipt. A nonzero 7-day failure count from the health
|
||||
* object renders as one attention line.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2, ExternalLink } from 'lucide-react'
|
||||
import { WhatsAppMark } from '@/components/extensions/general/WhatsAppMark'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useFormat } from '@/lib/hooks/use-format'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowNote,
|
||||
SettingsSelect,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
|
||||
const BASE = '/api/extensions/ext/whatsapp-inbox'
|
||||
|
||||
/** Closed enum from the server (lib/last-event.ts); translated here. */
|
||||
const LAST_EVENT_KINDS = new Set([
|
||||
'filed',
|
||||
'handled',
|
||||
'processing',
|
||||
'awaiting_company',
|
||||
'duplicate',
|
||||
'rate_limited',
|
||||
'unsupported',
|
||||
'muted',
|
||||
'declined',
|
||||
'failed',
|
||||
])
|
||||
|
||||
interface LinkStatus {
|
||||
linked: boolean
|
||||
phoneMasked?: string
|
||||
defaultCompanyId?: string | null
|
||||
muted?: boolean
|
||||
lastInboundAt?: string | null
|
||||
lastInboundEvent?: string | null
|
||||
lastReplyFailed?: boolean
|
||||
health?: {
|
||||
outboundFailed7d: number
|
||||
parkedInbound7d: number
|
||||
} | null
|
||||
}
|
||||
|
||||
interface MintedCode {
|
||||
code: string
|
||||
expiresAt: string
|
||||
waLink: string | null
|
||||
}
|
||||
|
||||
export function WhatsAppLinkPanel() {
|
||||
const t = useTranslations('settings_whatsapp')
|
||||
const { toast } = useToast()
|
||||
const { companies } = useCompany()
|
||||
const { locale, formatDateLong } = useFormat()
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [status, setStatus] = useState<LinkStatus | null>(null)
|
||||
const [minted, setMinted] = useState<MintedCode | null>(null)
|
||||
const [isMinting, setIsMinting] = useState(false)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [minutesLeft, setMinutesLeft] = useState<number | null>(null)
|
||||
|
||||
const fetchStatus = useCallback(async () => {
|
||||
setIsLoading(true)
|
||||
setLoadFailed(false)
|
||||
try {
|
||||
const response = await fetch(`${BASE}/link`)
|
||||
if (!response.ok) throw new Error('load failed')
|
||||
const { data } = (await response.json()) as { data: LinkStatus }
|
||||
setStatus(data)
|
||||
} catch {
|
||||
setLoadFailed(true)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchStatus()
|
||||
}, [fetchStatus])
|
||||
|
||||
// Countdown hint for the minted code (10 min TTL server-side).
|
||||
useEffect(() => {
|
||||
if (!minted) {
|
||||
setMinutesLeft(null)
|
||||
return
|
||||
}
|
||||
const tick = () => {
|
||||
const msLeft = new Date(minted.expiresAt).getTime() - Date.now()
|
||||
setMinutesLeft(msLeft > 0 ? Math.ceil(msLeft / 60_000) : 0)
|
||||
}
|
||||
tick()
|
||||
const interval = setInterval(tick, 15_000)
|
||||
return () => clearInterval(interval)
|
||||
}, [minted])
|
||||
|
||||
const startLinking = async () => {
|
||||
setIsMinting(true)
|
||||
try {
|
||||
const response = await fetch(`${BASE}/link/start`, { method: 'POST' })
|
||||
if (!response.ok) throw new Error('mint failed')
|
||||
const { data } = (await response.json()) as { data: MintedCode }
|
||||
setMinted(data)
|
||||
} catch {
|
||||
toast({ title: t('mint_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsMinting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const saveDefaultCompany = async (companyId: string) => {
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const response = await fetch(`${BASE}/link/default-company`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ companyId: companyId || null }),
|
||||
})
|
||||
if (!response.ok) throw new Error('save failed')
|
||||
setStatus((prev) => (prev ? { ...prev, defaultCompanyId: companyId || null } : prev))
|
||||
toast({ title: t('default_company_saved') })
|
||||
} catch {
|
||||
toast({ title: t('default_company_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const revoke = async () => {
|
||||
if (!window.confirm(t('revoke_confirm'))) return
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const response = await fetch(`${BASE}/link/revoke`, { method: 'POST' })
|
||||
if (!response.ok) throw new Error('revoke failed')
|
||||
setStatus({ linked: false })
|
||||
setMinted(null)
|
||||
toast({ title: t('revoked_toast') })
|
||||
} catch {
|
||||
toast({ title: t('revoke_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const unmute = async () => {
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const response = await fetch(`${BASE}/link/unmute`, { method: 'POST' })
|
||||
if (!response.ok) throw new Error('unmute failed')
|
||||
toast({ title: t('unmuted_toast') })
|
||||
await fetchStatus()
|
||||
} catch {
|
||||
toast({ title: t('unmute_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-1 py-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
{t('loading')}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (loadFailed) {
|
||||
return (
|
||||
<div className="px-1 py-6 text-sm text-muted-foreground">
|
||||
{t('load_failed')}{' '}
|
||||
<button type="button" className="underline" onClick={() => void fetchStatus()}>
|
||||
{t('retry')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const healthIssues =
|
||||
(status?.health?.outboundFailed7d ?? 0) + (status?.health?.parkedInbound7d ?? 0)
|
||||
|
||||
if (status?.linked) {
|
||||
return (
|
||||
<SettingsGroup label={t('group_label')}>
|
||||
{healthIssues > 0 ? (
|
||||
<div className="px-1 pt-3">
|
||||
<AttnLine>{t('health_warning', { count: healthIssues })}</AttnLine>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<SettingsRow label={t('linked_number_label')}>
|
||||
<span className="font-mono text-sm">{status.phoneMasked}</span>
|
||||
</SettingsRow>
|
||||
|
||||
{status.muted ? (
|
||||
<SettingsRow label={t('muted_label')}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={isSaving}
|
||||
onClick={() => void unmute()}
|
||||
>
|
||||
{t('unmute_button')}
|
||||
</Button>
|
||||
<SettingsRowNote>{t('muted_hint')}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
|
||||
{status.lastInboundAt ? (
|
||||
<SettingsRow label={t('last_event_label')}>
|
||||
<div className="space-y-1">
|
||||
<span className="text-sm">
|
||||
{formatDateLong(status.lastInboundAt)}{' '}
|
||||
{new Date(status.lastInboundAt).toLocaleTimeString(
|
||||
locale === 'en' ? 'en-GB' : 'sv-SE',
|
||||
{ hour: '2-digit', minute: '2-digit' },
|
||||
)}
|
||||
{' · '}
|
||||
{t(
|
||||
status.lastInboundEvent && LAST_EVENT_KINDS.has(status.lastInboundEvent)
|
||||
? `last_event_${status.lastInboundEvent}`
|
||||
: 'last_event_handled',
|
||||
)}
|
||||
</span>
|
||||
{status.lastReplyFailed ? <AttnLine>{t('last_reply_failed')}</AttnLine> : null}
|
||||
</div>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
|
||||
<SettingsRow label={t('default_company_label')} help={t('default_company_help')}>
|
||||
<SettingsSelect
|
||||
aria-label={t('default_company_label')}
|
||||
value={status.defaultCompanyId ?? ''}
|
||||
disabled={isSaving}
|
||||
onChange={(event) => void saveDefaultCompany(event.target.value)}
|
||||
>
|
||||
<option value="">{t('default_company_none')}</option>
|
||||
{companies.map(({ company }) => (
|
||||
<option key={company.id} value={company.id}>
|
||||
{company.name}
|
||||
</option>
|
||||
))}
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow label={t('disconnect_label')} borderless>
|
||||
<Button type="button" variant="outline" size="sm" disabled={isSaving} onClick={() => void revoke()}>
|
||||
{t('revoke_button')}
|
||||
</Button>
|
||||
<SettingsRowNote>{t('revoke_note')}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('group_label')}>
|
||||
<div className="space-y-4 px-1 py-4">
|
||||
<p className="max-w-prose text-sm text-muted-foreground">{t('unlinked_intro')}</p>
|
||||
|
||||
{minted ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="rounded-sm border border-border bg-muted/50 px-3 py-1.5 font-mono text-base tracking-wider">
|
||||
{minted.code}
|
||||
</span>
|
||||
{minted.waLink ? (
|
||||
<Button asChild type="button" size="sm">
|
||||
<a href={minted.waLink} target="_blank" rel="noreferrer">
|
||||
<WhatsAppMark size={16} className="mr-1.5" />
|
||||
{t('open_whatsapp')}
|
||||
<ExternalLink className="ml-1.5 h-3.5 w-3.5" aria-hidden="true" />
|
||||
</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<ol className="ml-4 list-decimal space-y-1 text-sm text-muted-foreground">
|
||||
<li>{t('step_open')}</li>
|
||||
<li>{t('step_send_code')}</li>
|
||||
<li>{t('step_confirm')}</li>
|
||||
</ol>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{minutesLeft != null && minutesLeft > 0
|
||||
? t('expires_in', { minutes: minutesLeft })
|
||||
: minutesLeft === 0
|
||||
? t('code_expired')
|
||||
: t('expires_hint')}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<Button type="button" disabled={isMinting} onClick={() => void startLinking()}>
|
||||
{isMinting ? <Loader2 className="mr-1.5 h-4 w-4 animate-spin" aria-hidden="true" /> : null}
|
||||
{t('connect_button')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export default WhatsAppLinkPanel
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* WhatsApp brand mark.
|
||||
*
|
||||
* Inline SVG rather than a bundled asset: it scales, needs no network
|
||||
* request, and survives the CSP. The green (#25D366) is WhatsApp's own and
|
||||
* is deliberately the one place in settings where a brand colour appears:
|
||||
* this marks a third-party channel, so it is identity, not chrome (see
|
||||
* .claude/rules/design.md on colour belonging to actors).
|
||||
*
|
||||
* Decorative by default. Pass a `title` when the mark carries meaning that
|
||||
* the surrounding text does not already state.
|
||||
*/
|
||||
|
||||
interface WhatsAppMarkProps {
|
||||
/** Edge length in px of the rounded tile. */
|
||||
size?: number
|
||||
/** Accessible name. Omit when adjacent text already says "WhatsApp". */
|
||||
title?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function WhatsAppMark({ size = 28, title, className }: WhatsAppMarkProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 48 48"
|
||||
className={className}
|
||||
role={title ? 'img' : undefined}
|
||||
aria-hidden={title ? undefined : true}
|
||||
aria-label={title}
|
||||
>
|
||||
{title ? <title>{title}</title> : null}
|
||||
<rect width="48" height="48" rx="10" fill="#25D366" />
|
||||
<path
|
||||
fill="#FFFFFF"
|
||||
d="M32.9 26.8c-.5-.3-3-1.5-3.4-1.6-.5-.2-.8-.3-1.1.2-.3.5-1.3 1.6-1.6 2-.3.3-.6.4-1.1.1-.5-.3-2.1-.8-4-2.5-1.5-1.3-2.5-3-2.8-3.5-.3-.5 0-.8.2-1 .2-.2.5-.6.8-.9.2-.3.3-.5.5-.8.2-.3.1-.6 0-.9-.1-.3-1.1-2.7-1.5-3.7-.4-1-.8-.8-1.1-.9h-1c-.3 0-.9.1-1.3.6-.5.5-1.7 1.7-1.7 4.2 0 2.4 1.8 4.8 2 5.1.2.3 3.5 5.4 8.6 7.6 1.2.5 2.1.8 2.9 1.1 1.2.4 2.3.3 3.2.2 1-.1 3-1.2 3.4-2.4.4-1.2.4-2.2.3-2.4-.1-.2-.5-.3-1-.6z"
|
||||
/>
|
||||
<path
|
||||
fill="#FFFFFF"
|
||||
d="M24.1 8h-.1c-8.8 0-16 7.2-16 16 0 2.8.7 5.6 2.1 8L8 40l8.2-2.1c2.3 1.3 5 1.9 7.8 1.9h.1c8.8 0 16-7.2 16-16s-7.1-15.8-16-15.8zm9.4 25.2c-2.5 2.5-5.9 3.9-9.4 3.9-2.4 0-4.7-.6-6.7-1.9l-.5-.3-5 1.3 1.3-4.9-.3-.5c-1.4-2.2-2.1-4.7-2.1-7.3 0-7.4 6-13.4 13.4-13.4 3.6 0 6.9 1.4 9.4 3.9 2.5 2.5 3.9 5.9 3.9 9.5.1 3.6-1.4 6.9-3.9 9.4z"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
ARCIM_DOCUMENT_IMPORT_STALLED,
|
||||
ARCIM_DOCUMENT_OAUTH_RESUME_KEY,
|
||||
INITIAL_ARCIM_DOCUMENT_IMPORT_STATE,
|
||||
PROVIDER_DOCUMENT_SCOPES_REQUIRED,
|
||||
PROVIDER_DOCUMENT_SCOPES_UNAVAILABLE,
|
||||
ArcimDocumentImportRequestError,
|
||||
arcimDocumentImportReducer,
|
||||
documentOAuthProblemFromReason,
|
||||
parseArcimDocumentOAuthResume,
|
||||
mergeArcimDocumentImportResults,
|
||||
requestArcimDocumentImport,
|
||||
resolveArcimDocumentFollowUpProvider,
|
||||
runArcimDocumentImportToCompletion,
|
||||
watchArcimOAuthPopup,
|
||||
type ArcimDocumentImportResult,
|
||||
} from '../arcim-document-import-flow'
|
||||
|
||||
function result(
|
||||
overrides: Partial<ArcimDocumentImportResult> = {},
|
||||
): ArcimDocumentImportResult {
|
||||
return {
|
||||
provider: 'fortnox',
|
||||
scanned: 7,
|
||||
linked: 5,
|
||||
skipped: 0,
|
||||
unmatched: 2,
|
||||
failed: 0,
|
||||
dryRun: true,
|
||||
unmatchedSamples: [],
|
||||
total: 7,
|
||||
partial: false,
|
||||
nextCursor: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Fortnox document follow-up state', () => {
|
||||
it('offers the prompt after a successful Fortnox migration using the honest found count', () => {
|
||||
const discovering = arcimDocumentImportReducer(
|
||||
INITIAL_ARCIM_DOCUMENT_IMPORT_STATE,
|
||||
{ type: 'discovery-started', provider: 'fortnox', migrationSucceeded: true },
|
||||
)
|
||||
const offered = arcimDocumentImportReducer(discovering, {
|
||||
type: 'discovery-succeeded',
|
||||
result: result({ scanned: 7, linked: 5, unmatched: 2 }),
|
||||
})
|
||||
|
||||
expect(offered.phase).toBe('offered')
|
||||
expect(offered.found).toBe(7)
|
||||
})
|
||||
|
||||
it('does not start discovery for a non-Fortnox migration', () => {
|
||||
expect(
|
||||
arcimDocumentImportReducer(INITIAL_ARCIM_DOCUMENT_IMPORT_STATE, {
|
||||
type: 'discovery-started',
|
||||
provider: 'bokio',
|
||||
migrationSucceeded: true,
|
||||
}),
|
||||
).toEqual(INITIAL_ARCIM_DOCUMENT_IMPORT_STATE)
|
||||
})
|
||||
|
||||
it('keeps the document step visible when Fortnox has no attachments', () => {
|
||||
const discovering = arcimDocumentImportReducer(
|
||||
INITIAL_ARCIM_DOCUMENT_IMPORT_STATE,
|
||||
{ type: 'discovery-started', provider: 'fortnox', migrationSucceeded: true },
|
||||
)
|
||||
const empty = arcimDocumentImportReducer(discovering, {
|
||||
type: 'discovery-succeeded',
|
||||
result: result({ scanned: 0, linked: 0, unmatched: 0 }),
|
||||
})
|
||||
|
||||
expect(empty.phase).toBe('empty')
|
||||
expect(empty.result?.scanned).toBe(0)
|
||||
})
|
||||
|
||||
it('uses the completed preview provider before transient selection state', () => {
|
||||
expect(resolveArcimDocumentFollowUpProvider('fortnox', null)).toBe('fortnox')
|
||||
expect(resolveArcimDocumentFollowUpProvider('fortnox', 'bokio')).toBe('fortnox')
|
||||
expect(resolveArcimDocumentFollowUpProvider(undefined, 'fortnox')).toBe('fortnox')
|
||||
expect(resolveArcimDocumentFollowUpProvider('bokio', 'fortnox')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps a dry-run failure in a retryable document state, separate from migration success', () => {
|
||||
const problem = { code: 'TRANSIENT_ERROR', requestId: 'req_test', reconnectRequired: false }
|
||||
const state = arcimDocumentImportReducer(
|
||||
{ phase: 'discovering', found: 0, result: null, problem: null },
|
||||
{ type: 'discovery-failed', problem },
|
||||
)
|
||||
|
||||
expect(state).toEqual({
|
||||
phase: 'discovery-error',
|
||||
found: 0,
|
||||
result: null,
|
||||
problem,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps all outcome counts after a successful import', () => {
|
||||
const imported = result({
|
||||
dryRun: false,
|
||||
scanned: 7,
|
||||
linked: 3,
|
||||
skipped: 2,
|
||||
unmatched: 1,
|
||||
failed: 1,
|
||||
})
|
||||
const state = arcimDocumentImportReducer(
|
||||
{ phase: 'importing', found: 7, result: null, problem: null },
|
||||
{ type: 'import-succeeded', result: imported },
|
||||
)
|
||||
|
||||
expect(state.phase).toBe('complete')
|
||||
expect(state.result).toMatchObject({
|
||||
linked: 3,
|
||||
skipped: 2,
|
||||
unmatched: 1,
|
||||
failed: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the dry-run result offered until the user explicitly starts import', () => {
|
||||
const offered = arcimDocumentImportReducer(
|
||||
{ phase: 'discovering', found: 0, result: null, problem: null },
|
||||
{ type: 'discovery-succeeded', result: result({ dryRun: true }) },
|
||||
)
|
||||
|
||||
expect(offered).toMatchObject({ phase: 'offered', result: { dryRun: true } })
|
||||
expect(
|
||||
arcimDocumentImportReducer(offered, { type: 'import-started' }),
|
||||
).toMatchObject({ phase: 'importing' })
|
||||
})
|
||||
|
||||
it('allows OAuth success to replace an earlier popup-close failure', () => {
|
||||
const problem = { code: null, requestId: null, reconnectRequired: true }
|
||||
const failed = arcimDocumentImportReducer(
|
||||
{ phase: 'reconnecting', found: 7, result: result(), problem },
|
||||
{ type: 'import-failed', problem },
|
||||
)
|
||||
const importing = arcimDocumentImportReducer(failed, { type: 'import-started' })
|
||||
const complete = arcimDocumentImportReducer(importing, {
|
||||
type: 'import-succeeded',
|
||||
result: result({ dryRun: false, linked: 7, unmatched: 0 }),
|
||||
})
|
||||
|
||||
expect(failed.phase).toBe('import-error')
|
||||
expect(complete).toMatchObject({ phase: 'complete', result: { linked: 7 } })
|
||||
})
|
||||
|
||||
it('marks the archive/connectfile scope error as reconnect-required', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
code: PROVIDER_DOCUMENT_SCOPES_REQUIRED,
|
||||
message: 'scope required',
|
||||
requestId: 'req_scope',
|
||||
},
|
||||
}),
|
||||
{ status: 403, headers: { 'Content-Type': 'application/json' } },
|
||||
),
|
||||
)
|
||||
|
||||
const error = await requestArcimDocumentImport(
|
||||
'consent-1',
|
||||
true,
|
||||
fetcher,
|
||||
).catch((caught) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(ArcimDocumentImportRequestError)
|
||||
expect(error.problem).toEqual({
|
||||
code: PROVIDER_DOCUMENT_SCOPES_REQUIRED,
|
||||
requestId: 'req_scope',
|
||||
reconnectRequired: true,
|
||||
})
|
||||
})
|
||||
|
||||
// The scopes are missing from the connect request itself, so offering a
|
||||
// reconnect would loop the user forever (Klura AB, 2026-08-20).
|
||||
it('never offers a reconnect when the scopes are unavailable to the integration', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
code: PROVIDER_DOCUMENT_SCOPES_UNAVAILABLE,
|
||||
message: 'scopes unavailable',
|
||||
requestId: 'req_unavailable',
|
||||
},
|
||||
}),
|
||||
{ status: 403, headers: { 'Content-Type': 'application/json' } },
|
||||
),
|
||||
)
|
||||
|
||||
const error = await requestArcimDocumentImport(
|
||||
'consent-1',
|
||||
true,
|
||||
fetcher,
|
||||
).catch((caught) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(ArcimDocumentImportRequestError)
|
||||
expect(error.problem).toEqual({
|
||||
code: PROVIDER_DOCUMENT_SCOPES_UNAVAILABLE,
|
||||
requestId: 'req_unavailable',
|
||||
reconnectRequired: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('document import endpoint request', () => {
|
||||
it('uses POST dry-run discovery without downloading automatically', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ success: true, result: result() }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
|
||||
await requestArcimDocumentImport('consent-1', true, fetcher)
|
||||
|
||||
expect(fetcher).toHaveBeenCalledWith(
|
||||
'/api/extensions/ext/arcim-migration/import-documents',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ consentId: 'consent-1', dryRun: true }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a success payload without unmatched samples', async () => {
|
||||
const invalid = result()
|
||||
const { unmatchedSamples: _unmatchedSamples, ...withoutSamples } = invalid
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ success: true, result: withoutSamples }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
|
||||
await expect(
|
||||
requestArcimDocumentImport('consent-1', true, fetcher),
|
||||
).rejects.toBeInstanceOf(ArcimDocumentImportRequestError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('document scope OAuth recovery', () => {
|
||||
it('round-trips the full-page redirect resume action and rejects malformed state', () => {
|
||||
expect(ARCIM_DOCUMENT_OAUTH_RESUME_KEY).toBe('arcim-document-oauth-resume')
|
||||
expect(parseArcimDocumentOAuthResume('import')).toEqual({
|
||||
action: 'import',
|
||||
})
|
||||
expect(parseArcimDocumentOAuthResume('unknown')).toBeNull()
|
||||
})
|
||||
|
||||
it('only treats scope and consent failures as reconnectable', () => {
|
||||
expect(
|
||||
documentOAuthProblemFromReason('Tredjepartsappen saknar rätt behörigheter'),
|
||||
).toMatchObject({
|
||||
code: PROVIDER_DOCUMENT_SCOPES_REQUIRED,
|
||||
reconnectRequired: true,
|
||||
})
|
||||
expect(documentOAuthProblemFromReason('Du avbröt anslutningen')).toMatchObject({
|
||||
code: null,
|
||||
reconnectRequired: true,
|
||||
})
|
||||
expect(documentOAuthProblemFromReason('Leverantören är tillfälligt nere')).toEqual({
|
||||
code: null,
|
||||
requestId: null,
|
||||
reconnectRequired: false,
|
||||
message: 'Leverantören är tillfälligt nere',
|
||||
})
|
||||
})
|
||||
|
||||
it('restores retry controls when the OAuth popup is closed', () => {
|
||||
vi.useFakeTimers()
|
||||
const popup = { closed: false }
|
||||
const onClosed = vi.fn()
|
||||
const stopWatching = watchArcimOAuthPopup(popup, onClosed, 10, 20)
|
||||
|
||||
vi.advanceTimersByTime(20)
|
||||
expect(onClosed).not.toHaveBeenCalled()
|
||||
|
||||
popup.closed = true
|
||||
vi.advanceTimersByTime(10)
|
||||
expect(onClosed).not.toHaveBeenCalled()
|
||||
vi.advanceTimersByTime(20)
|
||||
expect(onClosed).toHaveBeenCalledOnce()
|
||||
|
||||
stopWatching()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('lets a queued OAuth success cancel the popup-close grace period', () => {
|
||||
vi.useFakeTimers()
|
||||
const popup = { closed: true }
|
||||
const onClosed = vi.fn()
|
||||
const stopWatching = watchArcimOAuthPopup(popup, onClosed, 10, 20)
|
||||
|
||||
vi.advanceTimersByTime(10)
|
||||
stopWatching()
|
||||
vi.advanceTimersByTime(20)
|
||||
|
||||
expect(onClosed).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resumable import (one server slice per call)', () => {
|
||||
it('accepts an older server answer without resume fields as one complete slice', async () => {
|
||||
const { total: _t, partial: _p, nextCursor: _c, ...legacy } = result({ scanned: 9 })
|
||||
const fetcher = vi.fn().mockResolvedValue(jsonResponse({ success: true, result: legacy }))
|
||||
|
||||
const normalized = await requestArcimDocumentImport('consent-1', true, fetcher)
|
||||
|
||||
expect(normalized).toMatchObject({ total: 9, partial: false, nextCursor: null })
|
||||
expect(JSON.parse((fetcher.mock.calls[0][1] as RequestInit).body as string)).toEqual({
|
||||
consentId: 'consent-1',
|
||||
dryRun: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('sends the cursor only when resuming', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(jsonResponse({ success: true, result: result() }))
|
||||
|
||||
await requestArcimDocumentImport('consent-1', false, fetcher, 'file-42')
|
||||
|
||||
expect(JSON.parse((fetcher.mock.calls[0][1] as RequestInit).body as string)).toEqual({
|
||||
consentId: 'consent-1',
|
||||
dryRun: false,
|
||||
cursor: 'file-42',
|
||||
})
|
||||
})
|
||||
|
||||
it('sums every slice and keeps the latest total', () => {
|
||||
const merged = mergeArcimDocumentImportResults(
|
||||
result({ scanned: 17, linked: 15, skipped: 1, unmatched: 1, failed: 0, total: 113, unmatchedSamples: [{ uploadId: 'u1', voucher: 'A1', date: '2026-01-01' }] }),
|
||||
result({ scanned: 20, linked: 18, skipped: 0, unmatched: 1, failed: 1, total: 113, partial: true, nextCursor: 'file-37', unmatchedSamples: [{ uploadId: 'u2', voucher: 'A2', date: '2026-01-02' }] }),
|
||||
)
|
||||
|
||||
expect(merged).toMatchObject({
|
||||
scanned: 37,
|
||||
linked: 33,
|
||||
skipped: 1,
|
||||
unmatched: 2,
|
||||
failed: 1,
|
||||
total: 113,
|
||||
partial: true,
|
||||
nextCursor: 'file-37',
|
||||
})
|
||||
expect(merged.unmatchedSamples).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('loops until the server reports the end, passing the cursor back and reporting running totals', async () => {
|
||||
const fetcher = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ success: true, result: result({ dryRun: false, scanned: 17, linked: 17, total: 40, partial: true, nextCursor: 'file-17' }) }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ success: true, result: result({ dryRun: false, scanned: 17, linked: 16, skipped: 1, total: 40, partial: true, nextCursor: 'file-34' }) }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ success: true, result: result({ dryRun: false, scanned: 6, linked: 6, total: 40 }) }),
|
||||
)
|
||||
const onProgress = vi.fn()
|
||||
|
||||
const final = await runArcimDocumentImportToCompletion('consent-1', { fetcher, onProgress })
|
||||
|
||||
expect(fetcher).toHaveBeenCalledTimes(3)
|
||||
const bodies = fetcher.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))
|
||||
expect(bodies).toEqual([
|
||||
{ consentId: 'consent-1', dryRun: false },
|
||||
{ consentId: 'consent-1', dryRun: false, cursor: 'file-17' },
|
||||
{ consentId: 'consent-1', dryRun: false, cursor: 'file-34' },
|
||||
])
|
||||
expect(onProgress).toHaveBeenCalledTimes(2)
|
||||
expect(onProgress.mock.calls[1][0]).toMatchObject({ scanned: 34, linked: 33, skipped: 1, total: 40 })
|
||||
expect(final).toMatchObject({ scanned: 40, linked: 39, skipped: 1, total: 40, partial: false, nextCursor: null })
|
||||
})
|
||||
|
||||
it('fails (does not report completion) when a server hands back a cursor that does not advance', async () => {
|
||||
const fetcher = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, result: result({ dryRun: false, scanned: 5, total: 10, partial: true, nextCursor: 'file-5' }) }))
|
||||
.mockResolvedValueOnce(jsonResponse({ success: true, result: result({ dryRun: false, scanned: 0, total: 10, partial: true, nextCursor: 'file-5' }) }))
|
||||
const onProgress = vi.fn()
|
||||
|
||||
await expect(
|
||||
runArcimDocumentImportToCompletion('consent-1', { fetcher, onProgress }),
|
||||
).rejects.toMatchObject({ problem: { code: ARCIM_DOCUMENT_IMPORT_STALLED } })
|
||||
|
||||
expect(fetcher).toHaveBeenCalledTimes(2)
|
||||
// The slice that did land was reported, so the UI keeps honest totals.
|
||||
expect(onProgress).toHaveBeenCalledTimes(1)
|
||||
expect(onProgress.mock.calls[0][0]).toMatchObject({ scanned: 5, total: 10 })
|
||||
})
|
||||
|
||||
it('fails when a partial answer carries no cursor at all', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(
|
||||
jsonResponse({ success: true, result: result({ dryRun: false, scanned: 5, total: 10, partial: true, nextCursor: null }) }),
|
||||
)
|
||||
|
||||
await expect(runArcimDocumentImportToCompletion('consent-1', { fetcher })).rejects.toMatchObject({
|
||||
problem: { code: ARCIM_DOCUMENT_IMPORT_STALLED },
|
||||
})
|
||||
expect(fetcher).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the import phase while recording running totals, then completes with the honest total', () => {
|
||||
const importing = arcimDocumentImportReducer(
|
||||
{ phase: 'offered', found: 40, result: result({ dryRun: true, total: 40 }), problem: null },
|
||||
{ type: 'import-started' },
|
||||
)
|
||||
const progressed = arcimDocumentImportReducer(importing, {
|
||||
type: 'import-progress',
|
||||
result: result({ dryRun: false, scanned: 17, linked: 17, total: 40, partial: true, nextCursor: 'file-17' }),
|
||||
})
|
||||
expect(progressed).toMatchObject({ phase: 'importing', result: { scanned: 17, total: 40 } })
|
||||
|
||||
const complete = arcimDocumentImportReducer(progressed, {
|
||||
type: 'import-succeeded',
|
||||
result: result({ dryRun: false, scanned: 40, linked: 39, skipped: 1, total: 40 }),
|
||||
})
|
||||
expect(complete).toMatchObject({ phase: 'complete', found: 40, result: { linked: 39, skipped: 1 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Coverage for the per-currency totalling behind the "Bokför valda" underlag
|
||||
* dialog. The dialog itself is never rendered here (Vitest runs in the `node`
|
||||
* environment, no component tests in this repo), which is exactly why the rule
|
||||
* was extracted into a pure module.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
normalizeUnderlagCurrency,
|
||||
summarizeUnderlagTotals,
|
||||
type UnderlagTotalsItem,
|
||||
} from '../bulk-book-inbox-totals'
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
|
||||
/** Minimal extraction shaped like the real one; only the read fields matter. */
|
||||
function item(total: number | null, currency?: string | null): UnderlagTotalsItem {
|
||||
return {
|
||||
extracted_data: {
|
||||
supplier: { name: null, orgNumber: null, vatNumber: null, address: null, bankgiro: null, plusgiro: null },
|
||||
// `currency` is typed non-nullable on InvoiceExtractionResult, but rows
|
||||
// written before the field existed really do arrive without it, so the
|
||||
// cast reproduces the shape the dialog actually receives at runtime.
|
||||
invoice: {
|
||||
invoiceNumber: null,
|
||||
invoiceDate: null,
|
||||
dueDate: null,
|
||||
paymentReference: null,
|
||||
currency: currency as string,
|
||||
},
|
||||
lineItems: [],
|
||||
totals: { subtotal: null, vatAmount: null, total },
|
||||
vatBreakdown: [],
|
||||
confidence: 1,
|
||||
} as InvoiceExtractionResult,
|
||||
}
|
||||
}
|
||||
|
||||
describe('normalizeUnderlagCurrency', () => {
|
||||
it('passes through a well-formed code, uppercased', () => {
|
||||
expect(normalizeUnderlagCurrency('EUR')).toBe('EUR')
|
||||
expect(normalizeUnderlagCurrency('eur')).toBe('EUR')
|
||||
expect(normalizeUnderlagCurrency(' usd ')).toBe('USD')
|
||||
})
|
||||
|
||||
it('treats a missing currency as SEK (legacy extractions predate the field)', () => {
|
||||
expect(normalizeUnderlagCurrency(null)).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency(undefined)).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency('')).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency(' ')).toBe('SEK')
|
||||
})
|
||||
|
||||
it('falls back to SEK on a malformed code rather than letting Intl throw', () => {
|
||||
// formatCurrency() -> Intl.NumberFormat raises RangeError on these, and the
|
||||
// value comes from AI extraction of a PDF, so it is not trustworthy input.
|
||||
expect(normalizeUnderlagCurrency('Euro')).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency('kr')).toBe('SEK')
|
||||
expect(normalizeUnderlagCurrency('12')).toBe('SEK')
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: single-currency selections still work', () => {
|
||||
it('sums a plain SEK selection into one entry', () => {
|
||||
const totals = summarizeUnderlagTotals([
|
||||
item(1000, 'SEK'),
|
||||
item(250.5, 'SEK'),
|
||||
item(99.25, 'SEK'),
|
||||
])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 1349.75 }])
|
||||
})
|
||||
|
||||
it('keeps a homogeneous foreign selection in its own currency, not SEK', () => {
|
||||
// The old code rendered this through formatCurrency() with the SEK
|
||||
// default, so 3 000 EUR read as "3 000 kr".
|
||||
const totals = summarizeUnderlagTotals([item(1000, 'EUR'), item(2000, 'EUR')])
|
||||
expect(totals).toEqual([{ currency: 'EUR', total: 3000 }])
|
||||
})
|
||||
|
||||
it('rounds to öre with Math.round(x * 100) / 100, never toFixed', () => {
|
||||
const totals = summarizeUnderlagTotals([item(0.1, 'SEK'), item(0.2, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 0.3 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: a legacy NULL + SEK batch is NOT a currency mix', () => {
|
||||
it('groups a missing currency with SEK instead of reporting two currencies', () => {
|
||||
const totals = summarizeUnderlagTotals([
|
||||
item(500, null),
|
||||
item(300, 'SEK'),
|
||||
item(200, undefined),
|
||||
item(100, ''),
|
||||
])
|
||||
expect(totals).toHaveLength(1)
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 1100 }])
|
||||
})
|
||||
|
||||
it('does not split lowercase sek away from SEK', () => {
|
||||
const totals = summarizeUnderlagTotals([item(10, 'sek'), item(20, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 30 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: mixed selections report per-currency subtotals', () => {
|
||||
it('never collapses two currencies into one scalar', () => {
|
||||
const totals = summarizeUnderlagTotals([
|
||||
item(100, 'SEK'),
|
||||
item(100, 'EUR'),
|
||||
item(50, 'SEK'),
|
||||
])
|
||||
expect(totals).toEqual([
|
||||
{ currency: 'EUR', total: 100 },
|
||||
{ currency: 'SEK', total: 150 },
|
||||
])
|
||||
// The old scalar would have been 250, a number denominated in nothing.
|
||||
expect(totals.reduce((s, t) => s + t.total, 0)).not.toBe(totals[0]!.total)
|
||||
})
|
||||
|
||||
it('sorts by currency code so the list is stable across renders', () => {
|
||||
const totals = summarizeUnderlagTotals([item(1, 'USD'), item(1, 'EUR'), item(1, 'SEK')])
|
||||
expect(totals.map((t) => t.currency)).toEqual(['EUR', 'SEK', 'USD'])
|
||||
})
|
||||
|
||||
it('separates a legacy NULL (SEK) from a genuine foreign underlag', () => {
|
||||
const totals = summarizeUnderlagTotals([item(400, null), item(600, 'EUR')])
|
||||
expect(totals).toEqual([
|
||||
{ currency: 'EUR', total: 600 },
|
||||
{ currency: 'SEK', total: 400 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('summarizeUnderlagTotals: items without an extracted amount', () => {
|
||||
it('returns an empty list when nothing was extracted', () => {
|
||||
expect(summarizeUnderlagTotals([])).toEqual([])
|
||||
expect(summarizeUnderlagTotals([{ extracted_data: null }])).toEqual([])
|
||||
expect(summarizeUnderlagTotals([item(null, 'SEK')])).toEqual([])
|
||||
})
|
||||
|
||||
it('skips a null total instead of counting it as zero in that currency', () => {
|
||||
const totals = summarizeUnderlagTotals([item(null, 'EUR'), item(100, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 100 }])
|
||||
})
|
||||
|
||||
it('ignores a non-finite total rather than poisoning the subtotal with NaN', () => {
|
||||
const totals = summarizeUnderlagTotals([item(Number.NaN, 'SEK'), item(100, 'SEK')])
|
||||
expect(totals).toEqual([{ currency: 'SEK', total: 100 }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { copyInboxAddress } from '@/components/extensions/general/inbox-address-copy'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('copyInboxAddress', () => {
|
||||
it('reports copied and forwards the exact address on success', async () => {
|
||||
const writeText = vi.fn(async () => undefined)
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } })
|
||||
|
||||
await expect(copyInboxAddress('[email protected]')).resolves.toBe('copied')
|
||||
expect(writeText).toHaveBeenCalledWith('[email protected]')
|
||||
})
|
||||
|
||||
it('reports failed when the write is rejected, never copied', async () => {
|
||||
// The regression guard. The old handler swallowed this rejection in an empty
|
||||
// catch and then showed "Adress kopierad" anyway, so the user walked away
|
||||
// believing they had the inbox address and waited for invoices at an address
|
||||
// they never captured.
|
||||
vi.stubGlobal('navigator', {
|
||||
clipboard: {
|
||||
writeText: vi.fn(async () => {
|
||||
throw new DOMException('Write permission denied.', 'NotAllowedError')
|
||||
}),
|
||||
},
|
||||
})
|
||||
|
||||
const state = await copyInboxAddress('[email protected]')
|
||||
expect(state).toBe('failed')
|
||||
expect(state).not.toBe('copied')
|
||||
})
|
||||
|
||||
it('reports failed on a non-Error rejection', async () => {
|
||||
vi.stubGlobal('navigator', {
|
||||
clipboard: { writeText: vi.fn(() => Promise.reject('nope')) },
|
||||
})
|
||||
|
||||
await expect(copyInboxAddress('[email protected]')).resolves.toBe('failed')
|
||||
})
|
||||
|
||||
it('reports failed when the Clipboard API is missing (insecure context)', async () => {
|
||||
// No API means no programmatic fallback either: the header must keep the
|
||||
// address visible and selectable instead of claiming a copy.
|
||||
vi.stubGlobal('navigator', {})
|
||||
|
||||
const state = await copyInboxAddress('[email protected]')
|
||||
expect(state).toBe('failed')
|
||||
expect(state).not.toBe('copied')
|
||||
})
|
||||
|
||||
it('reports failed when clipboard exists but writeText does not', async () => {
|
||||
vi.stubGlobal('navigator', { clipboard: { read: vi.fn() } })
|
||||
|
||||
await expect(copyInboxAddress('[email protected]')).resolves.toBe('failed')
|
||||
})
|
||||
|
||||
it('does not throw when there is no navigator at all', async () => {
|
||||
vi.stubGlobal('navigator', undefined)
|
||||
|
||||
await expect(copyInboxAddress('[email protected]')).resolves.toBe('failed')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,400 @@
|
||||
export const ARCIM_DOCUMENT_IMPORT_ENDPOINT =
|
||||
'/api/extensions/ext/arcim-migration/import-documents'
|
||||
|
||||
export const PROVIDER_DOCUMENT_SCOPES_REQUIRED =
|
||||
'PROVIDER_DOCUMENT_SCOPES_REQUIRED'
|
||||
|
||||
/**
|
||||
* The connect request does not ask Fortnox for Arkiv and Koppla fil at all,
|
||||
* so no reconnect can grant them: the error offers no action, only the truth.
|
||||
*/
|
||||
export const PROVIDER_DOCUMENT_SCOPES_UNAVAILABLE =
|
||||
'PROVIDER_DOCUMENT_SCOPES_UNAVAILABLE'
|
||||
|
||||
export const ARCIM_DOCUMENT_OAUTH_RESUME_KEY =
|
||||
'arcim-document-oauth-resume'
|
||||
|
||||
export type ArcimDocumentOAuthResumeAction = 'discover' | 'import'
|
||||
|
||||
export interface ArcimDocumentOAuthResume {
|
||||
action: ArcimDocumentOAuthResumeAction
|
||||
}
|
||||
|
||||
export function parseArcimDocumentOAuthResume(
|
||||
value: string | null,
|
||||
): ArcimDocumentOAuthResume | null {
|
||||
if (value !== 'discover' && value !== 'import') return null
|
||||
return { action: value }
|
||||
}
|
||||
|
||||
/** Poll a provider popup so closing it cannot leave the UI reconnecting forever. */
|
||||
export function watchArcimOAuthPopup(
|
||||
popup: { closed: boolean },
|
||||
onClosed: () => void,
|
||||
intervalMs: number = 500,
|
||||
graceMs: number = 500,
|
||||
): () => void {
|
||||
let active = true
|
||||
let graceTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
const interval = globalThis.setInterval(() => {
|
||||
if (!popup.closed || !active) return
|
||||
globalThis.clearInterval(interval)
|
||||
graceTimeout = globalThis.setTimeout(() => {
|
||||
if (!active) return
|
||||
active = false
|
||||
onClosed()
|
||||
}, graceMs)
|
||||
}, intervalMs)
|
||||
|
||||
return () => {
|
||||
if (!active) return
|
||||
active = false
|
||||
globalThis.clearInterval(interval)
|
||||
if (graceTimeout) globalThis.clearTimeout(graceTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
export interface ArcimDocumentImportResult {
|
||||
provider: string
|
||||
scanned: number
|
||||
linked: number
|
||||
skipped: number
|
||||
unmatched: number
|
||||
failed: number
|
||||
dryRun: boolean
|
||||
unmatchedSamples: { uploadId: string; voucher: string; date: string }[]
|
||||
/** Attachments in the provider's whole list (not just this call). */
|
||||
total: number
|
||||
/** The server stopped at its time budget; continue after nextCursor. */
|
||||
partial: boolean
|
||||
/** Provider id of the last handled attachment, or null when complete. */
|
||||
nextCursor: string | null
|
||||
}
|
||||
|
||||
const MAX_UNMATCHED_SAMPLES = 20
|
||||
|
||||
/**
|
||||
* Fold one server call into the running totals of a multi-call import. The
|
||||
* route processes a slice per call (hosted function limit), so the numbers
|
||||
* the user sees must be the sum of every slice, not the last one.
|
||||
*/
|
||||
export function mergeArcimDocumentImportResults(
|
||||
accumulated: ArcimDocumentImportResult | null,
|
||||
next: ArcimDocumentImportResult,
|
||||
): ArcimDocumentImportResult {
|
||||
if (!accumulated) return next
|
||||
return {
|
||||
provider: next.provider,
|
||||
dryRun: next.dryRun,
|
||||
scanned: accumulated.scanned + next.scanned,
|
||||
linked: accumulated.linked + next.linked,
|
||||
skipped: accumulated.skipped + next.skipped,
|
||||
unmatched: accumulated.unmatched + next.unmatched,
|
||||
failed: accumulated.failed + next.failed,
|
||||
unmatchedSamples: [...accumulated.unmatchedSamples, ...next.unmatchedSamples].slice(
|
||||
0,
|
||||
MAX_UNMATCHED_SAMPLES,
|
||||
),
|
||||
total: next.total,
|
||||
partial: next.partial,
|
||||
nextCursor: next.nextCursor,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ArcimDocumentImportProblem {
|
||||
code: string | null
|
||||
requestId: string | null
|
||||
reconnectRequired: boolean
|
||||
message?: string
|
||||
/** What the source system (Fortnox/Bokio) itself answered, when known. */
|
||||
providerMessage?: string
|
||||
}
|
||||
|
||||
export function documentOAuthProblemFromReason(
|
||||
reason: string,
|
||||
): ArcimDocumentImportProblem {
|
||||
const normalized = reason.toLowerCase()
|
||||
const scopeFailure =
|
||||
normalized.includes('invalid_scope') ||
|
||||
normalized.includes('scope') ||
|
||||
normalized.includes('behörighet')
|
||||
const consentDenied =
|
||||
normalized.includes('access_denied') ||
|
||||
normalized.includes('denied') ||
|
||||
normalized.includes('nekad') ||
|
||||
normalized.includes('avbröt')
|
||||
|
||||
return {
|
||||
code: scopeFailure ? PROVIDER_DOCUMENT_SCOPES_REQUIRED : null,
|
||||
requestId: null,
|
||||
reconnectRequired: scopeFailure || consentDenied,
|
||||
message: reason,
|
||||
}
|
||||
}
|
||||
|
||||
export type ArcimDocumentImportPhase =
|
||||
| 'hidden'
|
||||
| 'discovering'
|
||||
| 'offered'
|
||||
| 'empty'
|
||||
| 'dismissed'
|
||||
| 'discovery-error'
|
||||
| 'importing'
|
||||
| 'complete'
|
||||
| 'import-error'
|
||||
| 'reconnecting'
|
||||
|
||||
export interface ArcimDocumentImportState {
|
||||
phase: ArcimDocumentImportPhase
|
||||
found: number
|
||||
result: ArcimDocumentImportResult | null
|
||||
problem: ArcimDocumentImportProblem | null
|
||||
}
|
||||
|
||||
export const INITIAL_ARCIM_DOCUMENT_IMPORT_STATE: ArcimDocumentImportState = {
|
||||
phase: 'hidden',
|
||||
found: 0,
|
||||
result: null,
|
||||
problem: null,
|
||||
}
|
||||
|
||||
export type ArcimDocumentImportAction =
|
||||
| { type: 'reset' }
|
||||
| {
|
||||
type: 'discovery-started'
|
||||
provider: string | null
|
||||
migrationSucceeded: boolean
|
||||
}
|
||||
| { type: 'discovery-succeeded'; result: ArcimDocumentImportResult }
|
||||
| { type: 'discovery-failed'; problem: ArcimDocumentImportProblem }
|
||||
| { type: 'dismissed' }
|
||||
| { type: 'import-started' }
|
||||
| { type: 'import-progress'; result: ArcimDocumentImportResult }
|
||||
| { type: 'import-succeeded'; result: ArcimDocumentImportResult }
|
||||
| { type: 'import-failed'; problem: ArcimDocumentImportProblem }
|
||||
| { type: 'reconnect-started' }
|
||||
|
||||
/**
|
||||
* The completed preview is the authoritative provider source. The selected
|
||||
* provider is only a fallback for older flows that do not retain preview data.
|
||||
*/
|
||||
export function resolveArcimDocumentFollowUpProvider(
|
||||
previewProvider: string | null | undefined,
|
||||
selectedProvider: string | null | undefined,
|
||||
): 'fortnox' | null {
|
||||
const provider = previewProvider ?? selectedProvider
|
||||
return provider === 'fortnox' ? provider : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the optional document step separate from the completed migration.
|
||||
* A discovery or import failure can therefore never replace the migration's
|
||||
* own success result with a failure state.
|
||||
*/
|
||||
export function arcimDocumentImportReducer(
|
||||
state: ArcimDocumentImportState,
|
||||
action: ArcimDocumentImportAction,
|
||||
): ArcimDocumentImportState {
|
||||
switch (action.type) {
|
||||
case 'reset':
|
||||
return INITIAL_ARCIM_DOCUMENT_IMPORT_STATE
|
||||
case 'discovery-started':
|
||||
if (action.provider !== 'fortnox' || !action.migrationSucceeded) {
|
||||
return INITIAL_ARCIM_DOCUMENT_IMPORT_STATE
|
||||
}
|
||||
return { phase: 'discovering', found: 0, result: null, problem: null }
|
||||
case 'discovery-succeeded':
|
||||
if (action.result.provider !== 'fortnox') {
|
||||
return INITIAL_ARCIM_DOCUMENT_IMPORT_STATE
|
||||
}
|
||||
if (action.result.scanned <= 0) {
|
||||
return {
|
||||
phase: 'empty',
|
||||
found: 0,
|
||||
result: action.result,
|
||||
problem: null,
|
||||
}
|
||||
}
|
||||
return {
|
||||
phase: 'offered',
|
||||
found: action.result.scanned,
|
||||
result: action.result,
|
||||
problem: null,
|
||||
}
|
||||
case 'discovery-failed':
|
||||
return {
|
||||
phase: 'discovery-error',
|
||||
found: 0,
|
||||
result: null,
|
||||
problem: action.problem,
|
||||
}
|
||||
case 'dismissed':
|
||||
return { ...state, phase: 'dismissed', problem: null }
|
||||
case 'import-started':
|
||||
return { ...state, phase: 'importing', problem: null }
|
||||
case 'import-progress':
|
||||
// Running totals after each server slice; the phase stays 'importing'
|
||||
// so the UI keeps its spinner and shows "x av y".
|
||||
return { ...state, phase: 'importing', result: action.result, problem: null }
|
||||
case 'import-succeeded':
|
||||
return {
|
||||
phase: 'complete',
|
||||
found: state.found || action.result.total || action.result.scanned,
|
||||
result: action.result,
|
||||
problem: null,
|
||||
}
|
||||
case 'import-failed':
|
||||
return { ...state, phase: 'import-error', problem: action.problem }
|
||||
case 'reconnect-started':
|
||||
return { ...state, phase: 'reconnecting' }
|
||||
}
|
||||
}
|
||||
|
||||
export class ArcimDocumentImportRequestError extends Error {
|
||||
constructor(readonly problem: ArcimDocumentImportProblem) {
|
||||
super(problem.code ?? 'ARCIM_DOCUMENT_IMPORT_FAILED')
|
||||
this.name = 'ArcimDocumentImportRequestError'
|
||||
}
|
||||
}
|
||||
|
||||
function problemFromPayload(payload: unknown): ArcimDocumentImportProblem {
|
||||
const error = (payload as { error?: unknown } | null)?.error
|
||||
const structured =
|
||||
error && typeof error === 'object'
|
||||
? (error as { code?: unknown; requestId?: unknown; details?: unknown })
|
||||
: null
|
||||
const code = typeof structured?.code === 'string' ? structured.code : null
|
||||
const requestId =
|
||||
typeof structured?.requestId === 'string' ? structured.requestId : null
|
||||
const details =
|
||||
structured?.details && typeof structured.details === 'object'
|
||||
? (structured.details as { providerMessage?: unknown })
|
||||
: null
|
||||
const providerMessage =
|
||||
typeof details?.providerMessage === 'string' && details.providerMessage.trim()
|
||||
? details.providerMessage.trim()
|
||||
: null
|
||||
|
||||
return {
|
||||
code,
|
||||
requestId,
|
||||
reconnectRequired: code === PROVIDER_DOCUMENT_SCOPES_REQUIRED,
|
||||
...(providerMessage ? { providerMessage } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
type WireDocumentImportResult = Omit<
|
||||
ArcimDocumentImportResult,
|
||||
'total' | 'partial' | 'nextCursor'
|
||||
> &
|
||||
Partial<Pick<ArcimDocumentImportResult, 'total' | 'partial' | 'nextCursor'>>
|
||||
|
||||
function isDocumentImportResult(value: unknown): value is WireDocumentImportResult {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
const result = value as Partial<ArcimDocumentImportResult>
|
||||
return (
|
||||
typeof result.provider === 'string' &&
|
||||
typeof result.scanned === 'number' &&
|
||||
typeof result.linked === 'number' &&
|
||||
typeof result.skipped === 'number' &&
|
||||
typeof result.unmatched === 'number' &&
|
||||
typeof result.failed === 'number' &&
|
||||
typeof result.dryRun === 'boolean' &&
|
||||
Array.isArray(result.unmatchedSamples)
|
||||
)
|
||||
}
|
||||
|
||||
/** Older servers answer without the resume fields: a single complete slice. */
|
||||
function normalizeDocumentImportResult(
|
||||
result: WireDocumentImportResult,
|
||||
): ArcimDocumentImportResult {
|
||||
return {
|
||||
...result,
|
||||
total: typeof result.total === 'number' ? result.total : result.scanned,
|
||||
partial: result.partial === true,
|
||||
nextCursor:
|
||||
typeof result.nextCursor === 'string' && result.nextCursor.length > 0 && result.partial === true
|
||||
? result.nextCursor
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call the existing POST route for both discovery and the actual import.
|
||||
* `cursor` resumes a partial import; omit it for discovery and the first slice.
|
||||
*/
|
||||
export async function requestArcimDocumentImport(
|
||||
consentId: string,
|
||||
dryRun: boolean,
|
||||
fetcher: typeof fetch = fetch,
|
||||
cursor?: string,
|
||||
): Promise<ArcimDocumentImportResult> {
|
||||
const response = await fetcher(ARCIM_DOCUMENT_IMPORT_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(
|
||||
cursor === undefined ? { consentId, dryRun } : { consentId, dryRun, cursor },
|
||||
),
|
||||
})
|
||||
const payload = await response.json().catch(() => null)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ArcimDocumentImportRequestError(problemFromPayload(payload))
|
||||
}
|
||||
|
||||
const result = (payload as { result?: unknown } | null)?.result
|
||||
if (!isDocumentImportResult(result)) {
|
||||
throw new ArcimDocumentImportRequestError({
|
||||
code: null,
|
||||
requestId: null,
|
||||
reconnectRequired: false,
|
||||
})
|
||||
}
|
||||
|
||||
return normalizeDocumentImportResult(result)
|
||||
}
|
||||
|
||||
/** Far above any real list: a guard against a server that never completes. */
|
||||
const MAX_IMPORT_ROUNDS = 500
|
||||
|
||||
export const ARCIM_DOCUMENT_IMPORT_STALLED = 'ARCIM_DOCUMENT_IMPORT_STALLED'
|
||||
|
||||
/**
|
||||
* Run the real import to completion: the route works through one time-budgeted
|
||||
* slice per call and hands back a cursor, so this loops until the server says
|
||||
* it reached the end, reporting running totals after every slice. A thrown
|
||||
* request error aborts the loop; the slices already archived stay linked and
|
||||
* the next attempt skips them by hash. A server that keeps answering "partial"
|
||||
* without advancing (or past the round guard) is reported as a failure, never
|
||||
* as a completed import: the retry button resumes safely.
|
||||
*/
|
||||
export async function runArcimDocumentImportToCompletion(
|
||||
consentId: string,
|
||||
options: {
|
||||
fetcher?: typeof fetch
|
||||
onProgress?: (accumulated: ArcimDocumentImportResult) => void
|
||||
} = {},
|
||||
): Promise<ArcimDocumentImportResult> {
|
||||
const fetcher = options.fetcher ?? fetch
|
||||
let accumulated: ArcimDocumentImportResult | null = null
|
||||
let cursor: string | undefined
|
||||
|
||||
for (let round = 0; round < MAX_IMPORT_ROUNDS; round++) {
|
||||
const slice = await requestArcimDocumentImport(consentId, false, fetcher, cursor)
|
||||
accumulated = mergeArcimDocumentImportResults(accumulated, slice)
|
||||
if (!slice.partial) {
|
||||
return { ...accumulated, partial: false, nextCursor: null }
|
||||
}
|
||||
if (slice.nextCursor === null || (cursor !== undefined && slice.nextCursor <= cursor)) {
|
||||
break
|
||||
}
|
||||
cursor = slice.nextCursor
|
||||
options.onProgress?.(accumulated)
|
||||
}
|
||||
|
||||
throw new ArcimDocumentImportRequestError({
|
||||
code: ARCIM_DOCUMENT_IMPORT_STALLED,
|
||||
requestId: null,
|
||||
reconnectRequired: false,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Pure per-currency totalling for the "Bokför valda" underlag dialog.
|
||||
*
|
||||
* Lives outside BulkBookInboxDialog.tsx (a `'use client'` component) so the
|
||||
* rule below can be unit tested: this repo runs Vitest in the `node`
|
||||
* environment and never renders components, so logic embedded in JSX is
|
||||
* unverifiable by construction.
|
||||
*
|
||||
* # Why this exists
|
||||
*
|
||||
* The dialog used to reduce the whole selection to ONE scalar
|
||||
* (`bookable.reduce((s, it) => s + (it.extracted_data?.totals?.total ?? 0), 0)`)
|
||||
* and render it through `formatCurrency()`, which defaults to SEK. Both halves
|
||||
* of that are wrong the moment the underlag are not all SEK:
|
||||
*
|
||||
* 1. It adds 100 EUR to 100 SEK as if they were one unit, so the figure the
|
||||
* user approves against corresponds to no real belopp (BFL 5 kap 7 §
|
||||
* requires a verifikation to state the belopp of the affärshändelse; a
|
||||
* cross-currency sum is not one).
|
||||
* 2. Even for a homogeneous non-SEK selection it stamped "kr" on a total
|
||||
* denominated in something else, so three 1 000 EUR invoices read as
|
||||
* "3 000 kr".
|
||||
*
|
||||
* # Why this is a display fix and NOT a submit block
|
||||
*
|
||||
* Unlike `components/transactions/BulkBookDialog.tsx`, this dialog does not
|
||||
* build a samlingsverifikation. `POST /items/bulk-book` runs
|
||||
* `bulkBookMatchedInboxItems`, which loops the selection and calls
|
||||
* `categorizeMatchedTransaction` per item: ONE verifikat per underlag, and the
|
||||
* booked belopp is read off that item's matched bank transaction, never off
|
||||
* `extracted_data.totals.total` (see the header of
|
||||
* `lib/transactions/categorize-core.ts`: "Booking is always in SEK off the bank
|
||||
* transaction's own amount"). A EUR invoice settled by the bank in SEK is
|
||||
* therefore booked correctly and legally, and a selection mixing SEK and EUR
|
||||
* underlag produces a set of individually correct SEK verifikat.
|
||||
*
|
||||
* So there is no BFL 4 kap 6 § redovisningsvaluta conflict to refuse here, and
|
||||
* blocking the submit would break a legitimate everyday flow (a batch of
|
||||
* receipts where some suppliers invoice in EUR). The honest fix is to stop
|
||||
* presenting the misleading scalar and show what is actually true: a subtotal
|
||||
* per currency, plus a note that the booking follows the bank amount.
|
||||
*/
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
|
||||
/** The subset of an inbox item this module needs. */
|
||||
export interface UnderlagTotalsItem {
|
||||
extracted_data: InvoiceExtractionResult | null
|
||||
}
|
||||
|
||||
export interface UnderlagCurrencyTotal {
|
||||
/** ISO 4217 code, uppercased. */
|
||||
currency: string
|
||||
total: number
|
||||
}
|
||||
|
||||
function round2(n: number): number {
|
||||
return Math.round(n * 100) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve an underlag's currency to a code that is safe to both group by and
|
||||
* hand to `Intl.NumberFormat`.
|
||||
*
|
||||
* A missing/blank currency normalizes to 'SEK'. This matters for correctness,
|
||||
* not just tidiness: `extracted_data.invoice.currency` is produced by document
|
||||
* extraction and older rows predate the field, so an un-normalized
|
||||
* `new Set(items.map(i => i.extracted_data?.invoice?.currency))` would split a
|
||||
* legacy `null`/`undefined` underlag away from its SEK siblings and report a
|
||||
* currency mix that does not exist. `pickCurrency()` in
|
||||
* InvoiceInboxWorkspace.tsx and `emptyExtraction()` both already read a missing
|
||||
* currency as SEK, so this keeps the dialog consistent with the list behind it.
|
||||
*
|
||||
* Anything that is not a plausible 3-letter code also falls back to 'SEK':
|
||||
* `formatCurrency` throws a RangeError on a malformed code, and this value
|
||||
* comes from AI extraction of a PDF, so it cannot be trusted to be well formed.
|
||||
* Crashing the approval dialog on a junk code would be strictly worse than
|
||||
* grouping it with the default.
|
||||
*/
|
||||
export function normalizeUnderlagCurrency(currency: string | null | undefined): string {
|
||||
const code = currency?.trim().toUpperCase()
|
||||
return code && /^[A-Z]{3}$/.test(code) ? code : 'SEK'
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtotal the selection per currency, sorted by currency code.
|
||||
*
|
||||
* Items whose extraction produced no total contribute nothing (they are not
|
||||
* counted as a 0 in some currency), so a selection with no extracted amounts
|
||||
* yields an empty array and the caller renders nothing: the same "no figure to
|
||||
* show" outcome the old `totalSek > 0` gate produced.
|
||||
*
|
||||
* A result of length > 1 means the selection genuinely spans currencies and
|
||||
* the caller must not render a combined scalar.
|
||||
*/
|
||||
export function summarizeUnderlagTotals(items: UnderlagTotalsItem[]): UnderlagCurrencyTotal[] {
|
||||
const byCurrency = new Map<string, number>()
|
||||
for (const item of items) {
|
||||
const total = item.extracted_data?.totals?.total
|
||||
if (total == null || !Number.isFinite(total)) continue
|
||||
const currency = normalizeUnderlagCurrency(item.extracted_data?.invoice?.currency)
|
||||
byCurrency.set(currency, round2((byCurrency.get(currency) ?? 0) + total))
|
||||
}
|
||||
return Array.from(byCurrency.entries())
|
||||
.map(([currency, total]) => ({ currency, total }))
|
||||
.sort((a, b) => a.currency.localeCompare(b.currency))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { copyToClipboard } from '@/lib/browser/copy-to-clipboard'
|
||||
|
||||
/**
|
||||
* Copy state for the inbox address in the workspace header.
|
||||
*
|
||||
* `idle` claims nothing, `copied` is only reachable after the clipboard write
|
||||
* resolved, and `failed` means the address is NOT on the clipboard.
|
||||
*/
|
||||
export type AddressCopyState = 'idle' | 'copied' | 'failed'
|
||||
|
||||
/**
|
||||
* Copy the document-inbox address and report which state the header must show.
|
||||
*
|
||||
* Why this exists as its own function: the previous handler fired
|
||||
* `navigator.clipboard.writeText(...).catch(() => {})` and then showed
|
||||
* "Adress kopierad" unconditionally, so an insecure context, a blocking
|
||||
* Permissions-Policy or a document that had lost focus produced a success
|
||||
* message with an empty clipboard. The user then waits for supplier invoices at
|
||||
* an address they never captured, and nothing in the UI ever contradicts that.
|
||||
*
|
||||
* `unavailable` (no Clipboard API at all) and `failed` (the write was rejected)
|
||||
* collapse into one UI state on purpose: from the user's side both mean the
|
||||
* address is not on the clipboard and manual selection is the only way to get
|
||||
* it. The distinction only matters for logging, which this surface does not do.
|
||||
*
|
||||
* Call this as the first `await` in the click handler: a clipboard write issued
|
||||
* after another await runs outside the click's transient user activation and is
|
||||
* rejected on that ground alone.
|
||||
*/
|
||||
export async function copyInboxAddress(
|
||||
address: string,
|
||||
): Promise<Exclude<AddressCopyState, 'idle'>> {
|
||||
const result = await copyToClipboard(address)
|
||||
return result === 'copied' ? 'copied' : 'failed'
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user