diff --git a/DECISIONS.md b/DECISIONS.md index 558749b5..e7db64a3 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -869,4 +869,6 @@ One line per decision: `[YYYY-MM-DD] : `. Appended by agents and [2026-08-11] suggest-booking derives the proposed kontering on demand rather than storing it on the inbox row or computing it in the receipt hunt: a stored proposal goes stale against a corrected amount, a re-matched transaction or a template the company taught itself since, and the nightly hunt is already at its 300 s ceiling for a proposal most rows never open. It composes the existing evaluateMappingRules -> buildTransactionEntryLines chain rather than a second one, so the shown lines cannot drift from the posted lines. It withholds the proposal entirely on a foreign-currency row that matched via the mapping_rules branch: mapping-engine.ts buildResult computes VAT from the transaction's own currency while every other line is SEK (its own NOTE tracks this), which understates ingaende moms by the exchange rate and still balances, so nothing downstream catches it. Guarding the surface was chosen over fixing buildResult in this PR because that changes posted VAT amounts across every caller; the counterparty and static-template paths already convert correctly and are not withheld. [2026-08-11] Agent skills for the API ship as generated artifacts, not authored docs: skills/accounted-api/ is CI-checked output (apiskill:check) of scripts/api-skill/generate.ts, rendered from the same lib/api/v1 registry that serves the API and its OpenAPI spec, so the installable skill cannot drift from the server. Edit scripts/api-skill/overlays/ or the registry, never the output. The per-operation renderer is the portable tool inside skills/openapi-to-skill/ (the generic spec-to-skill generator): our own skill dogfoods it. Skills live in top-level skills/ because that is the directory `npx skills add erp-mafia/accounted` scans; the OpenAPI generator was extended to emit requestBody + path parameters (previously response-only) rather than teaching the skill generator to read Zod directly, so every spec consumer benefits, not just the skill. [2026-08-11] Gmail search fans out with a bounded pool (5 per connection) instead of Promise.all over every message id: Gmail enforces a per-user CONCURRENCY ceiling, not just a daily quota, and answers 429 "Too many concurrent requests for user" well below this app's volume. A real two-connection run returned mails=25 documents=0 purely from 429s. The catch in searchOne turned every refusal into an empty result, which is indistinguishable from an empty mailbox, and the manual hunt loop stops on fetched===0 as its "nothing left to find" signal, so the user was told their receipts do not exist by a search that never ran. searchFailureCount() now separates "could not look" from "nothing there", the run route returns it, and the loop treats a pass with failures as failed rather than finished. +[2026-08-11] Anthropic, Vercel and Supabase removed from the portal directory: all three email their invoices to European customers, so listing them told the user to go and log in for a document already in their inbox. The directory's bar is "does not send the invoice", not "also has a portal", and the poll it was seeded from asked which portals people log into, which people answered with where an invoice can ALSO be found. The same objection may reach further down the list; an entry is a claim that the invoice cannot be had any other way and is worth checking per vendor. +[2026-08-11] Portal URLs are swept by scripts/check-portal-urls.mts rather than trusted: the directory shipped with 18 hand-written paths, none opened, the file said so and shipped anyway, and a founder then hit a 404 on Google Workspace (/ac/billing/history). A sweep found GitHub's /settings/billing 404 too. Rule now is the shallowest URL that certainly resolves: landing one click short of the invoice costs little, landing on an error page spends the trust the feature runs on. Google, OpenAI and Hetzner refuse automated requests, so they cannot be swept and are kept shallow deliberately; only a genuine 404 fails the script, since failing on an unreachable host would train people to ignore it. Trygg Hansa removed: neither candidate URL could be reached at all. [2026-08-11] Credit-note deduction fields (deduction_total, per-item deduction_amount) stay POSITIVE magnitudes, unlike every other amount on a credit note: both columns carry CHECK (>= 0) in the DB, and negating them made every ROT/RUT credit fail at insert (prod support case 2026-08-11). Verified inert: the reversing verifikat recomputes the ROT/RUT split from quantity/unit_price (generateRotRutLines), the PDF hides the deduction section for credit notes, getAmountToPay skips deductions when credited_invoice_id is set, and ROT payout candidates require status='paid', which invoices_credit_note_not_paid makes impossible for credit notes. Any future reader summing these fields across invoice + credit note must special-case credit notes. diff --git a/components/bookkeeping/JournalEntryForm.tsx b/components/bookkeeping/JournalEntryForm.tsx index bb289c39..ae4c8d46 100644 --- a/components/bookkeeping/JournalEntryForm.tsx +++ b/components/bookkeeping/JournalEntryForm.tsx @@ -103,6 +103,13 @@ interface Props { /** The bank transaction being booked (set by TransactionBookingDialog). * Enables the duplicate guard's "Matcha mot verifikatet" action for * ledger-only voucher candidates. */ + /** + * Extra keys for the submit body, for endpoints that need something this + * form does not model. The invoice-inbox book-direct route needs + * transaction_id to book the underlag against its bank line; without it the + * entry posts standalone and the match is cleared. + */ + extraBody?: Record duplicateMatchTransaction?: DuplicateMatchTransaction /** Fired after the duplicate guard's match action links the transaction to * the existing voucher (no new entry was created). */ @@ -129,6 +136,7 @@ export default function JournalEntryForm({ initialExchangeRate, initialForeignAmount, onUpdated, + extraBody, duplicateMatchTransaction, onDuplicateMatched, }: Props) { @@ -974,10 +982,14 @@ export default function JournalEntryForm({ // handleBookAnyway). Stripped by schemas that don't declare it, so a // stray value never reaches the manual journal-entry endpoint. ...(forceDuplicateRef.current ?? {}), + // Fields only the caller's endpoint knows about. Same safety as above: + // a schema that does not declare a key strips it, so this cannot leak + // into the manual journal-entry route. + ...(extraBody ?? {}), }), }) return (await throwOnStructuredError(res)) as { data?: { id?: string; voucher_series?: string; voucher_number?: number }; journal_entry_id?: string } - }, [lines, rate, entryCurrency, computedForeignAmount, t, submitUrl, editEntryId, selectedPeriod, entryDate, description, effectiveSourceType, sourceId, voucherSeries, notes]) + }, [lines, rate, entryCurrency, computedForeignAmount, t, submitUrl, editEntryId, selectedPeriod, entryDate, description, effectiveSourceType, sourceId, voucherSeries, notes, extraBody]) const { runSubmit, dialog: activationDialog, confirm: confirmActivation, cancel: cancelActivation } = useSubmitWithAccountActivation(postJournalEntry) diff --git a/components/extensions/general/EditKonteringDialog.tsx b/components/extensions/general/EditKonteringDialog.tsx new file mode 100644 index 00000000..9d1c4fd8 --- /dev/null +++ b/components/extensions/general/EditKonteringDialog.tsx @@ -0,0 +1,131 @@ +'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 JournalEntryForm from '@/components/bookkeeping/JournalEntryForm' +import DocumentViewerPane from '@/components/bookkeeping/DocumentViewerPane' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, +} 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, + 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[] + onBooked: (entryId: string) => void +}) { + const t = useTranslations('inbox_workspace') + + return ( + + + + Ändra kontering + + Förslaget är en utgångspunkt. Ändra konto, belopp, datum eller serie innan du bokför. + + + +
+
+ ({ + 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, + }))} + 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} + /> +
+ + {/* The document stays readable while the numbers change: checking a + VAT rate against the paper is the reason to open this at all. */} + +
+
+
+ ) +} diff --git a/components/extensions/general/InvoiceInboxWorkspace.tsx b/components/extensions/general/InvoiceInboxWorkspace.tsx index 157be173..9c6bba9f 100644 --- a/components/extensions/general/InvoiceInboxWorkspace.tsx +++ b/components/extensions/general/InvoiceInboxWorkspace.tsx @@ -42,12 +42,16 @@ import { Circle, X, ChevronDown, + ChevronRight, Sparkles, MessageCircle, Maximize2, } from 'lucide-react' import Link from 'next/link' -import { cn, formatCurrency, formatDate } from '@/lib/utils' +import { cn, formatCurrency, formatDate, formatDateLong } from '@/lib/utils' +import { GoogleMark, MicrosoftMark } from '@/components/ui/provider-marks' +import EditKonteringDialog from '@/components/extensions/general/EditKonteringDialog' +import { WhatsAppMark } from '@/components/extensions/general/WhatsAppMark' import { useReceiptHunt } from '@/components/extensions/general/use-receipt-hunt' import { createClient } from '@/lib/supabase/client' import { fetchWithTimeout } from '@/lib/http/fetch-with-timeout' @@ -171,6 +175,37 @@ function hasAnyExtractedField(data: InvoiceExtractionResult | null): boolean { ) } +/** + * The fields the extraction is scored against, in the order a person reads + * them. Deliberately the same list hasAnyExtractedField checks, so the summary + * cannot claim a field the "is anything here at all" test does not count. + */ +const EXTRACTED_FIELD_ACCESSORS: ((d: InvoiceExtractionResult) => unknown)[] = [ + (d) => d.supplier?.name, + (d) => d.supplier?.orgNumber, + (d) => d.supplier?.vatNumber, + (d) => d.supplier?.bankgiro, + (d) => d.supplier?.plusgiro, + (d) => d.invoice?.invoiceNumber, + (d) => d.invoice?.invoiceDate, + (d) => d.invoice?.dueDate, + (d) => d.invoice?.paymentReference, + (d) => d.totals?.subtotal, + (d) => d.totals?.vatAmount, + (d) => d.totals?.total, +] + +export const EXTRACTED_FIELD_COUNT = EXTRACTED_FIELD_ACCESSORS.length + +/** How many of them the extraction actually filled in. */ +function countExtractedFields(data: InvoiceExtractionResult | null): number { + if (!data) return 0 + return EXTRACTED_FIELD_ACCESSORS.reduce( + (n, get) => n + (get(data) != null && get(data) !== '' ? 1 : 0), + 0, + ) +} + // Lifecycle stage of an inbox item. Single source of truth shared by the list // filter, the count pills, and the row icons so they never drift apart. // @@ -246,6 +281,8 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { const { toast } = useToast() const t = useTranslations('inbox_workspace') const fileInputRef = useRef(null) + // Its own input: sharing the header's would upload without the purchase. + const purchaseFileInputRef = useRef(null) const { openAgentSheet, identity } = useAgentSheet() const [items, setItems] = useState([]) @@ -261,7 +298,9 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { // ones stay visible. // 'missing' is the odd one out: it lists bank purchases, not inbox items, so // the list and both panes branch on it. - const [filter, setFilter] = useState<'todo' | 'linked' | 'booked' | 'error' | 'all' | 'missing'>('todo') + const [filter, setFilter] = useState< + 'todo' | 'linked' | 'booked' | 'error' | 'all' | 'missing' | 'portal' + >('todo') const [searchTerm, setSearchTerm] = useState('') // Bulk selection. Items linked to a supplier invoice are skipped at delete // time (server returns 409); we still allow them to be selected so the @@ -456,27 +495,55 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { const [purchases, setPurchases] = useState([]) const [selectedPurchaseId, setSelectedPurchaseId] = useState(null) - // Whether any mailbox can actually be searched. Counting rows would not - // answer that: a revoked or expired connection is still a row, and the hunt - // skips it, so the button would promise a search that returns nothing every - // pass. A dead mailbox looking healthy is the exact failure this feature - // exists to surface, so it must not start by doing it in its own header. - const [mailConnected, setMailConnected] = useState(false) + // Where underlag come from. Three routes in, and the page should say so: + // the mailboxes we search, WhatsApp for photographed receipts, and the + // forwarding address that works with nothing connected at all. + const [mailConnections, setMailConnections] = useState([]) + const [whatsapp, setWhatsapp] = useState<{ linked: boolean; phoneMasked?: string; verifiedAt?: string | null } | null>(null) + const [sourcesOpen, setSourcesOpen] = useState(false) + useEffect(() => { void (async () => { try { const res = await fetch('/api/extensions/ext/mail/connections') if (!res.ok) return - const json = (await res.json()) as { - data?: { connections?: { status?: string }[] } - } - setMailConnected((json.data?.connections ?? []).some((c) => c.status === 'active')) + const json = (await res.json()) as { data?: { connections?: InboxMailConnection[] } } + setMailConnections(json.data?.connections ?? []) } catch { // The extension may not be enabled at all; stay quiet. } })() + void (async () => { + try { + const res = await fetch('/api/extensions/ext/whatsapp-inbox/link') + if (!res.ok) return + // The route answers in camelCase (phoneMasked / verifiedAt); reading + // snake_case here silently rendered a linked number as "–". + const json = (await res.json()) as { + data?: { linked: boolean; phoneMasked?: string; verifiedAt?: string | null } + } + if (json.data) setWhatsapp(json.data) + } catch { + // Same: not every company has it. + } + })() }, []) + // Counting rows would not answer whether anything is searchable: a revoked + // or expired connection is still a row, and the hunt skips it, so the button + // would promise a search that returns nothing every pass. A dead mailbox + // looking healthy is the exact failure this feature exists to surface, so it + // must not start by doing it in its own header. + const mailConnected = useMemo( + () => mailConnections.some((c) => c.status === 'active'), + [mailConnections], + ) + const ailingMailbox = useMemo( + () => mailConnections.find((c) => c.status !== 'active') ?? null, + [mailConnections], + ) + const sourceCount = mailConnections.length + (whatsapp?.linked ? 1 : 0) + (inboxAddress ? 1 : 0) + const fetchPurchases = useCallback(async () => { try { const res = await fetch('/api/extensions/ext/invoice-inbox/purchases') @@ -499,6 +566,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { stop: stopHunt, hunting, progress: huntProgress, + result: huntResult, } = useReceiptHunt(() => { void fetchItems() void fetchPurchases() @@ -509,6 +577,9 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { [purchases, selectedPurchaseId], ) + const portalPurchases = useMemo(() => purchases.filter((p) => p.portal), [purchases]) + const otherPurchases = useMemo(() => purchases.filter((p) => !p.portal), [purchases]) + // Per-status counts for the filter pills. Computed once over the full list. const statusCounts = useMemo(() => { const counts = { todo: 0, linked: 0, booked: 0, error: 0, all: items.length } @@ -530,29 +601,37 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { { key: 'linked', label: 'Kopplade', count: statusCounts.linked }, { key: 'booked', label: 'Bokförda', count: statusCounts.booked }, ] - // Only worth a pill when there is something behind it: a company that - // keeps every receipt should not be shown a permanent empty accusation. - if (purchases.length > 0 || filter === 'missing') { - list.push({ key: 'missing', label: 'Saknar underlag', count: purchases.length }) + // Two lists, because they are two different jobs. A purchase whose + // supplier keeps invoices behind a login is one you can settle now by + // going there; one with nothing known needs somebody to be asked. Mixing + // them buries the twelve you can act on among the hundred you cannot. + if (portalPurchases.length > 0 || filter === 'portal') { + list.push({ key: 'portal', label: t('filter_portal'), count: portalPurchases.length }) + } + if (otherPurchases.length > 0 || filter === 'missing') { + list.push({ key: 'missing', label: t('filter_missing'), count: otherPurchases.length }) } if (statusCounts.error > 0 || filter === 'error') { list.push({ key: 'error', label: 'Fel', count: statusCounts.error }) } list.push({ key: 'all', label: 'Alla', count: statusCounts.all }) return list - }, [statusCounts, filter, purchases.length]) + }, [statusCounts, filter, portalPurchases.length, otherPurchases.length]) + + const activePill = useMemo(() => pills.find((p) => p.key === filter), [pills, filter]) const filteredPurchases = useMemo(() => { + const base = filter === 'portal' ? portalPurchases : otherPurchases const term = searchTerm.trim().toLowerCase() - if (term === '') return purchases - return purchases.filter((p) => + if (term === '') return base + return base.filter((p) => [p.merchant_name, p.description].some((v) => v?.toLowerCase().includes(term)), ) - }, [purchases, searchTerm]) + }, [portalPurchases, otherPurchases, filter, searchTerm]) const filteredItems = useMemo(() => { const term = searchTerm.trim().toLowerCase() - if (filter === 'missing') return [] + if (filter === 'missing' || filter === 'portal') return [] return items.filter((item) => { // Status filter. "todo" is the active inbox: everything except booked. const status = deriveInboxStatus(item) @@ -721,6 +800,7 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { if (options.autoSelect && json.data?.inbox_item_id) { await handleSelect(json.data.inbox_item_id) } + return json.data?.inbox_item_id as string | undefined } catch (err) { setItems((prev) => prev.filter((it) => it.id !== tempId)) if (options.autoSelect) { @@ -740,6 +820,54 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { // Sequential queue: running multiple extractions concurrently would // hammer pdfjs on slow boxes. Per-file placeholder rows + the queue // counter on the upload button surface progress. + /** + * Upload a file and make it the underlag for one specific purchase. + * + * The generic upload only carries the file, so a document dropped while a + * purchase was selected landed in the inbox unmatched: the pane showed that + * purchase's amount and date under the drop zone and then quietly did not + * use either. Matching afterwards through the endpoint that already exists + * keeps the promise the copy makes. + */ + const uploadForPurchase = useCallback(async (files: File[], transactionId: string) => { + const [file, ...rest] = files + if (!file) return + const itemId = await uploadFile(file, { autoSelect: false }) + // A receipt scanned as two images, or an invoice with its specification, + // arrives as one drop. Taking the first and discarding the rest in silence + // left the purchase looking resolved with half its paperwork gone. They + // cannot all be the underlag for one purchase, so the extras are filed in + // the inbox rather than dropped on the floor. + for (const extra of rest) await uploadFile(extra, { autoSelect: false }) + if (!itemId) return + try { + const res = await fetch( + `/api/extensions/ext/invoice-inbox/items/${itemId}/match-transaction`, + { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ transaction_id: transactionId }), + }, + ) + if (!res.ok) throw new Error(String(res.status)) + toast({ + title: 'Underlag kopplat', + description: rest.length ? `${file.name}. ${rest.length} till lades i inkorgen.` : file.name, + }) + setSelectedPurchaseId(null) + await Promise.all([fetchItems(), fetchPurchases()]) + } catch { + // The document is safely filed either way; only the link failed, and + // the user can still make it by hand from the inbox. + toast({ + title: 'Uppladdat, men inte kopplat', + description: 'Dokumentet ligger i inkorgen. Koppla det till köpet därifrån.', + variant: 'destructive', + }) + await fetchItems() + } + }, [uploadFile, toast, fetchItems, fetchPurchases]) + const uploadFiles = useCallback(async (files: File[]) => { if (files.length === 0) return if (files.length === 1) { @@ -769,8 +897,17 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { e.preventDefault() setIsDragging(false) const files = Array.from(e.dataTransfer.files ?? []) - if (files.length > 0) await uploadFiles(files) - }, [uploadFiles]) + if (files.length === 0) return + // Dropping while a purchase is selected means "this is that purchase's + // receipt", wherever on the page it landed. Ignoring the selection would + // file it loose and leave the user to match by hand what they had already + // told us. + if (selectedPurchaseId) { + await uploadForPurchase(files, selectedPurchaseId) + return + } + await uploadFiles(files) + }, [uploadFiles, uploadForPurchase, selectedPurchaseId]) // ── Delete ───────────────────────────────────────────────── @@ -928,12 +1065,33 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {

Dokumentinkorg

- {inboxAddress ? ( - + {/* Where the page's contents come from, behind one chip. The detail + (which mailbox, when it was last read) is a thing people look up + when something seems wrong, not something they read every visit. + A mailbox that has stopped working is the exception, so that + surfaces on the chip itself. */} + {sourceCount > 0 ? ( + ) : addressLoadFailed ? ( // We do not know whether an address exists, so we offer a retry // rather than an activate button that would rotate a live address. @@ -1010,6 +1168,136 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
+ {huntResult && ( +
+ {huntResult.failed ? ( + + {/* searchFailures counts mailboxes that refused; without it the + failure was ours, and telling somebody to go check a healthy + Gmail sends them after the wrong thing. */} + {(huntResult.searchFailures ?? 0) > 0 + ? 'En brevlåda svarade inte. Försök igen om en stund.' + : 'Sökningen kunde inte slutföras. Försök igen.'} + + ) : huntResult.fetched > 0 ? ( + + {huntResult.fetched} nya underlag hämtade.{' '} + {huntResult.remaining > 0 && ( + <> + {huntResult.remaining} köp kvar att söka + för: tryck igen.{' '} + + )} + {/* "proposed" counts pending_operations rows, not links. The hunt + stages attach_document_to_transaction for a human to approve + and books nothing, so calling them kopplade would send the + user away believing purchases were done. */} + {huntResult.proposed > 0 ? ( + <> + {huntResult.proposed} förslag väntar på{' '} + + granskning + + . + + ) : ( + // A press fetches a bounded number of receipts, so an empty + // result usually means "not yet", not "nothing there". Saying + // only the first sends people away from a mailbox that still + // has their receipts in it. + <>Inget matchade något köp än. Tryck igen för att leta vidare. + )} + + ) : ( + + Inga nya underlag i brevlådorna för de köp som saknar ett. + + )} +
+ )} + + {/* Opened from the chip. Three ways in, each with the one fact that + matters about it: an address you can forward to, mailboxes we search, + and the number receipts arrive from. Nothing here is configuration; + that still lives in Inställningar. */} + {sourcesOpen && ( +
+ {inboxAddress && ( +
+ +
+ {inboxAddress.address} +
+ +
+ )} + + {mailConnections.map((c) => ( +
+ + {c.provider === 'gmail' ? ( + + ) : ( + + )} + {c.emailAddress} + {c.status !== 'active' && ( + + Behöver återanslutas + + )} + + + {/* One level down, because this is what you look up when a + mailbox seems to have gone quiet, not what you read on the + way past. */} +
+
+
{t('source_last_searched')}
+
+ {c.lastSearchedAt ? formatDateLong(c.lastSearchedAt) : t('source_never_searched')} +
+
+
+
Status
+
+ {c.status === 'active' + ? t('source_searched_when_hunting') + : t('source_not_searched')} +
+
+
+
+ ))} + + {whatsapp?.linked && ( +
+ + + WhatsApp + + +
+
+
{t('source_whatsapp_number')}
+
{whatsapp.phoneMasked ?? '-'}
+
+
+
Status
+
{whatsapp.verifiedAt ? t('source_verified') : t('source_unverified')}
+
+
+
+ )} + +
+ )} + + {/* Three-section body. Below xl (iPad portrait/landscape + phone) the sections stack vertically as a single scrollable feed. With the app sidebar eating ~256px, even iPad landscape (1024-1180px viewport) @@ -1029,39 +1317,53 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { className="pl-8 h-8 text-xs" /> -
- {pills.map((pill) => ( - - ))} -
+ + + + + + {pills.map((pill) => ( + { + setFilter(pill.key) + // The panes show one kind of row at a time; a stale + // selection from the other kind would outlive its list. + if (pill.key === 'missing' || pill.key === 'portal') setSelectedId(null) + else setSelectedPurchaseId(null) + }} + className="justify-between text-xs" + > + + + {pill.label} + + {pill.count} + + ))} + + )} {selectedIds.size > 0 && ( @@ -1174,17 +1476,25 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { Inkorgen är tom. ) - ) : (filter === 'missing' ? filteredPurchases.length : filteredItems.length) === 0 ? ( + ) : (filter === 'missing' || filter === 'portal' ? filteredPurchases.length : filteredItems.length) === 0 ? (
- {filter === 'todo' - ? 'Inget att åtgärda; allt är bearbetat.' - : filter === 'missing' - ? 'Varje köp har sitt underlag.' - : 'Inga poster matchar filtret.'} + {/* A leftover search term makes every one of these false: the + trigger above still shows the unsearched count, so the page + would claim every purchase has its underlag while the button + beside it reads 50. */} + {searchTerm.trim() !== '' + ? `Inga träffar på ”${searchTerm.trim()}”.` + : filter === 'todo' + ? 'Inget att åtgärda; allt är bearbetat.' + : filter === 'portal' + ? 'Inga köp väntar på en faktura från en portal.' + : filter === 'missing' + ? 'Varje köp har sitt underlag.' + : 'Inga poster matchar filtret.'}
) : (
    - {filter === 'missing' + {filter === 'missing' || filter === 'portal' ? filteredPurchases.map((p) => ( {selectedPurchase ? ( - // There is no file to show, so the pane says why instead of - // rendering an empty frame. + // There is no file to show, so the pane says why and then offers + // the one thing that resolves it. Telling somebody a document is + // missing without a place to put it is half an answer.
    -
    +
    -

    Inget underlag hittat

    +

    {t('purchase_no_document')}

    {selectedPurchase.portal - ? `${selectedPurchase.portal.vendor} skickar ingen fil. Hämta fakturan och ladda upp den här, så kopplas den till köpet.` - : 'Vi har sökt i brevlådorna och i portalkatalogen. Ladda upp kvittot här, eller vidarebefordra det till inkorgsadressen.'} + ? `${selectedPurchase.portal.vendor} skickar ingen fil. Hämta fakturan och släpp den här.` + : 'Vi har sökt i brevlådorna. Släpp kvittot här, eller vidarebefordra det till inkorgsadressen.'}

    + + {selectedPurchase.portal && ( + + )} + + { + const files = Array.from(e.target.files ?? []) + if (files.length > 0) await uploadForPurchase(files, selectedPurchase.id) + if (purchaseFileInputRef.current) purchaseFileInputRef.current.value = '' + }} + /> +
    ) : selected ? ( @@ -1325,6 +1683,12 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) { onRetryRequested={async () => { await Promise.all([fetchItems(), handleSelect(selected.id)]) }} + onBookedLocally={async () => { + // Re-read the item so the rail sees created_journal_entry_id + // and switches to the booked state; without it the same + // underlag can be posted twice. + await Promise.all([fetchItems(), fetchPurchases(), handleSelect(selected.id)]) + }} onFieldsUpdated={(nextData) => { // Guard against stale closure: if the user navigated to a // different item between sending the PATCH and the response @@ -1562,7 +1926,14 @@ function InboxRow({ ) : item.source === 'email' ? ( ) : item.source === 'whatsapp' ? ( - + + ) : item.channel_context?.mail_provider === 'gmail' ? ( + // The hunt records which mailbox it pulled a receipt from, so the + // brand is known rather than guessed. Mail that arrived by + // forwarding has no connection behind it and keeps the envelope. + + ) : item.channel_context?.mail_provider === 'microsoft' ? ( + ) : ( )} @@ -1925,6 +2296,14 @@ function EmptyPreview({ ) } +interface InboxMailConnection { + id: string + provider: 'gmail' | 'microsoft' + emailAddress: string + status: 'active' | 'needs_reconsent' | 'revoked' + lastSearchedAt: string | null +} + // ── Purchases with no underlag ─────────────────────────────── /** @@ -1955,6 +2334,7 @@ function PurchaseRow({ selected: boolean onClick: () => void }) { + const t = useTranslations('inbox_workspace') return (
  • - )} -
  • +
    + {/* The proposed kontering comes first: it is the decision. The fields + are the evidence you check when the decision looks wrong, so they + fold. Reading order used to be the other way round, which meant + scrolling past nine values to reach the one thing to approve. */} + {isLinkedToTransaction && } + +
    + + + {t('fields_summary')} + {/* A count, not a score. "5 av 12" read as a bad extraction even + when a kvitto had given up everything a kvitto has: half those + twelve fields only exist on an invoice. */} + {!item.isPlaceholder && countExtractedFields(data) > 0 && ( + + {t('fields_filled', { count: countExtractedFields(data) })} + + )} + {/* Kept from main: the fields are readable at rail width but not + comfortable, so the expand still earns its place inside the + fold. stopPropagation, or the summary would toggle under it. */} + {!item.isPlaceholder && (hasAnyExtractedField(data) || hasAi) && ( + { e.preventDefault(); e.stopPropagation(); setFieldsExpanded(true) }} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); e.stopPropagation(); setFieldsExpanded(true) + } + }} + aria-label={t('expand_fields')} + title={t('expand_fields')} + className="p-1 -m-1 hover:text-foreground" + > + + + )} + +
    {item.isPlaceholder ? (
    @@ -2541,6 +2971,8 @@ function FieldsRail({ onUpdated={onFieldsUpdated} /> )} +
    +
    {/* Actions: hidden while AI extraction is in flight */} @@ -2578,9 +3010,6 @@ function FieldsRail({ - {/* The answer the rail never gave: what this would be booked as. - Read-only; booking still goes through the dialog below. */} - {onAskAssistant && (