feat(inbox): Underlag rebuilt to answer what is missing, where to get it, and how it would be booked (#1524)

* fix(mail): stop Gmail refusing the search, and stop calling that "hittade inget"

Pressing Leta produced mails=25, documents=0 on a real two-mailbox run.
Nothing was found because nothing was searched: every request came back
429 "Too many concurrent requests for user".

Two bugs, and the second is the one that matters.

The search fanned out with Promise.all over every message id at once, one
Gmail request per message, per connection. Gmail enforces a per-user
concurrency ceiling as well as a daily quota, and this sailed past it long
before any volume worth worrying about. It now runs through a pool of five
per connection, which is comfortably under and still finishes a page of
results in a couple of round trips.

The catch turned each refusal into an empty array, with a comment saying
one mailbox's failure must not become the company's. Right instinct, wrong
consequence: an empty array is also what an empty mailbox returns, and the
manual hunt loop stops on fetched === 0 because that is its signal for
"the mailboxes hold nothing more for what is open". So a rate-limited
search told the user their receipts do not exist, and stopped looking.

searchFailureCount() now separates "could not look" from "nothing there".
The run route reports it, and the loop treats a pass with failures as
failed rather than finished, so pressing again is the obvious next move
instead of a pointless one.

This is the failure this feature exists to catch, happening inside the
feature: silence that reads as an answer.

Restoring the unbounded fan-out fails one test; removing the failure
counter fails three.

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

* feat(inbox): segment filter as a dropdown, not three rows of pills

Five filters wrapped to three lines in a 280px column. The counts are what
people actually read, so they stay on the trigger and inside the menu
rather than being traded away for the space.

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

* feat(inbox): one chip for where underlag come from

Three routes in, and the page never said so: the forwarding address sat
inline in the header, the mailboxes lived only in Instaellningar, and
WhatsApp was invisible here entirely.

They are behind one chip now. Which mailbox and when it was last read is
what people look up when something seems wrong, not what they read every
visit, so it opens rather than occupying the header.

A mailbox that has stopped working is the exception, so it surfaces on the
chip itself rather than waiting to be found one click in. That silence is
the failure this feature exists to catch.

Configuration stays in Instaellningar; this only reports.

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

* feat(inbox): the kontering first, the evidence folded

Reading order was backwards. Nine extracted values came first and the one
thing to approve came last, so every matched item meant scrolling past the
evidence to reach the decision.

The proposed kontering is now the first thing in the rail. The fields fold
behind a summary that carries how many of the twelve the extraction
actually filled, so a thin extraction is visible without opening it.

They stay open when nothing is matched: with no proposal above them the
fields are all there is, and folding the only content on the pane would be
a hiding place rather than a hierarchy.

The counted list is the same one hasAnyExtractedField checks, so the
summary cannot claim a field the 'is anything here' test does not count.

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

* feat(inbox): one dialog that changes the whole verifikat

The rail offered three overlapping ways to alter a booking and none said
what it covered: an Aendra beside the date, an Aendra kontering at the
bottom, and a menu entry that 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 opens pre-filled with the proposal
when there is one and empty when there is not, so there is no separate
book-manually path to pick between.

A dialog rather than an inline editor: a 340px rail cannot hold an account
picker, two money columns and a delete control per row without clipping
something, and the document has to stay readable while the numbers change.
Checking a momssats against the paper is the reason to open it at all.
TransactionBookingDialog already has this shape for the same reason.

The form is JournalEntryForm unchanged. It carries the series picker, per
line descriptions, dimensions, currency, the balance check and the confirm
step, and it posts through the sanctioned route. Extending
BookDirectlyDialog was the alternative and is not viable: three effects
seed its lines and fight anything injected, and its FormLine has no room
for line text, dimensions or tax codes.

Nothing posts without the form's own review step, so a proposal stays a
draft the user commits.

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

* fix(inbox): show every unreceipted purchase, and fold the mailboxes

Three things.

The 100 kr floor was hiding 52 of one real company's 119 unreceipted
purchases: the page reported 67 and looked tidier for it. The floor was
copied from the receipt hunt, where it earns its place because every
candidate costs a mail search and a model read. This list costs a query,
and bokforingslagen wants an underlag for the 45 kr purchase exactly as
much as for the 4 500 kr one. The hunt keeps its floor; the page has none.

Mailboxes fold. When it was last searched is what you look up when a
mailbox seems to have gone quiet, not what you read on the way past. The
address stays on the row, and a connection that needs reconnecting still
says so without opening.

Dropped the line telling people to go to Instaellningar. The panel reports
where underlag come from; sending them elsewhere was the seam this work
set out to close.

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

* feat(inbox): split the portal purchases out, and say what a run found

Four things from looking at the real page beside the artifact.

Hamta fran portal is its own list again. Twelve of one company's 119
unreceipted purchases have a supplier whose invoices sit behind a login,
and that is a different job from the other 107: go there and fetch it,
versus ask somebody. Collapsing them into one list with a badge buried the
twelve you can settle now among the hundred you cannot.

A run now says what it did. Pressing Leta and being told nothing is why
the feature read as broken even on the runs where it worked: three
underlag landed and the page looked identical afterwards.

WhatsApp folds like the mailboxes and shows its number, which is the fact
worth having. Describing the channel to someone who already connected it
was not.

The forwarding address lost its subtitle, and WhatsApp rows carry the
brand mark. Emailed documents keep the generic one: nothing records which
mailbox fetched them, so claiming a provider would be a guess.

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

* fix(inbox): the WhatsApp number, three wrong portals, and somewhere to drop the file

The WhatsApp row read the response in snake_case while the route answers
camelCase, so a linked number rendered as a dash and a verified link read
as unverified. Reading phoneMasked and verifiedAt fixes both.

Anthropic, Vercel and Supabase are out of the portal directory. All three
email their invoices to European customers, so listing them told somebody
to go and log in for a document already sitting in their inbox: worse than
saying nothing, because it sends them away from the answer. The directory's
bar is 'does not send the invoice', not 'also has a portal'. The poll it
was seeded from asked which portals people log into, and people answered
with where an invoice can also be found. The same objection may reach
further down the list.

A purchase with no underlag now offers somewhere to put one. Telling
somebody a document is missing without a place to drop it is half an
answer, and the drop zone carries the amount and the date so the right
file goes to the right purchase.

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

* fix(portal): the links were never opened, and two of them were wrong

The directory shipped with eighteen hand-written paths and none had been
clicked. The file said so in its own header and shipped regardless, which
is how a founder came to land on a 404 opening Google Workspace.

A sweep of every URL found GitHub broken as well. Google Workspace now
points at the console root rather than a deep billing path: admin.google.com
refuses automated requests, so no deeper path can be verified from here,
and a link that lands one click short beats one that lands on an error
page. GitHub points at the path that actually answers. Trygg Hansa is
removed because neither candidate URL could be reached at all, and an
unverifiable link is exactly the promise this file kept warning about.

scripts/check-portal-urls.mts sweeps them, so the next wrong URL is found
by a script rather than by somebody who trusted the link. A 404 fails it;
a host that refuses automation reports as unreachable and does not, because
failing on those would train people to ignore the output.

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

* fix(inbox): the drop zone now actually attaches the file to the purchase

It did not. The generic upload sends only the file, so a document dropped
while a purchase was selected landed in the inbox unmatched, while the
pane showed that purchase's amount and date directly under the drop zone.
The copy promised a link the code never made, and the user was left to
match by hand what they had already told us.

Uploading from a selected purchase now matches the new item to that
transaction through the endpoint that already exists, and a file dropped
anywhere on the page while a purchase is selected counts as that
purchase's receipt rather than a loose upload.

When the match fails the document is still safely filed, so it says so
plainly instead of claiming a link that is not there.

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

* fix(inbox): book the underlag against its transaction, and stop claiming links

Two blockers found by review, both on the path that writes to the ledger.

"Granska och bokför" never sent transaction_id. JournalEntryForm
serialises a fixed set of keys and that is not one of them, and
BookInboxItemDirectlySchema is a non-strict z.object, so the source_id
carrying it was silently stripped. The verifikat posted standalone, the
bank transaction stayed unbooked, and matched_transaction_id was
overwritten with null: the match somebody had already made, undone, while
the rail said Bokförd over all of it.

Fixed in three places because one was not enough. JournalEntryForm takes
an extraBody passthrough, the dialog sends transaction_id through it, and
the route now falls back to the item's existing match rather than null, so
a caller that merely forgets the field cannot undo work. Removing that
fallback fails the new test.

The hunt banner said "kopplades till ett köp" about pending_operations
rows. The hunt stages proposals for approval and books nothing, so the
number was real and the word was wrong: a user would read it, believe
three purchases were done, and leave. It now says how many förslag await
granskning, and links there.

Booking also left the rail in its pre-booking state, still offering to
post, so the same underlag could be submitted twice.

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

* fix(inbox): no marker on a healthy state, no false empty state, no dropped files

Three from review.

The sources chip painted a sage dot whenever every mailbox was fine.
Convention 12 rules semantic colour out of chrome, and convention 5 rules
out a marker on a normal state: a chip every company sees always is a chip
that says nothing. What is left is the exception, which is worth an ochre
word and an icon. The pre-existing sage on matched rows is untouched; it
is not this branch's to change.

The empty state asserted "Varje köp har sitt underlag" while the trigger
directly above it still showed the unsearched count. Type a term under Att
göra, switch to Saknar underlag, and the page told you every purchase was
covered while the button beside it read 50. It now says what is true: no
matches for that term.

A drop of several files onto a selected purchase kept the first and
discarded the rest in silence, so a receipt scanned as two images left the
purchase looking resolved with half its paperwork gone. They cannot all be
one purchase's underlag, so the extras are filed in the inbox and the
toast says how many.

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

* fix(inbox): the hunt banner now says a press is not the last word

A press fetches a bounded number of receipts, so an empty result usually
means not yet rather than nothing there. The banner said 'Inget matchade
något köp' and stopped, which reads as final and sends people away from a
mailbox that still holds their receipts. It now says how many purchases
are left to search for, and to press again.

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

* fix(inbox): a count not a score, an honest failure, full-opacity borders

'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, so the denominator was measuring the document kind rather than
the reading of it. It now says how many fields are filled, and says
nothing when none are.

The failure banner told people their mailbox had not answered even when
the failure was ours, sending them to check a healthy Gmail. It now reads
searchFailures and only blames the mailbox when a mailbox actually refused.

Opacity-suffixed borders on the sources panel, which design.md forbids on
surfaces: the border token is calibrated for full opacity.

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

* feat(inbox): translate the new strings, and name the mailbox that fetched a receipt

Both of these were deferred with reasons, and one of the reasons was wrong.

57 keys in inbox_workspace, in both locales, covering every string this
branch added. The component already had 27 t() calls, so hardcoding beside
them was an inconsistency rather than a convention. The message-keys guard
caught an invented journal_form.no_document on the way, which is what it
is for.

The provider mark claimed nothing recorded which mailbox fetched a
document. It does: lib/receipt-hunt/ingest.ts writes mail_provider and
mail_mailbox into channel_context on every ingest, and GET /items already
selects that column. A hunted receipt now carries the mark of the mailbox
it came from; forwarded mail has no connection behind it and keeps the
envelope, which is the honest distinction rather than a guess.

InboxChannelContext was WhatsApp-shaped and is now a union over the two
intakes that write it.

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

* fix(agent-context): keep the clarification channel narrow

Widening InboxChannelContext.channel to cover the mail hunt broke this:
only WhatsApp asks a human anything, so only WhatsApp produces
clarifications. The mail hunt writes the same column with its own shape and
never carries answers, so the provenance field stays 'whatsapp' rather than
following the union.

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

* fix(inbox): book the transaction we preserved, and date the verifikat by the event

Three from PR review, two of them real.

Preserving matched_transaction_id without booking it was the worse half of
the bug it fixed. The transaction update was still guarded on the caller
having sent transaction_id, so an omitted field left the item looking
resolved while its bank line stayed open forever. Both the update and the
item now use the same resolved id: the one the caller named, or the one
the item was already matched to. Reverting the guard fails a test.

The verifikat date fell back to today when there was no proposal, which is
exactly the unknown-supplier case the dialog exists for. BFL 5 kap 6-7 §
asks for datum för affärshändelsen; the day somebody opened a dialog is
nobody's business event. It now falls back to the document's own date
first, and only then to today.

An en dash had crept in as a placeholder glyph, which the repo bans.

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-12 14:36:08 +02:00
committed by GitHub
co-authored by Claude Opus 5 Jakob Wennberg
parent 9dbaebcc50
commit 555a2a20ae
14 changed files with 1041 additions and 147 deletions
+2
View File
@@ -869,4 +869,6 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. 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.
+13 -1
View File
@@ -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<string, unknown>
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)
@@ -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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Ändra kontering</DialogTitle>
<DialogDescription>
Förslaget är en utgångspunkt. Ändra konto, belopp, datum eller serie innan du bokför.
</DialogDescription>
</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
initialLines={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,
}))}
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>
)
}
@@ -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<HTMLInputElement | null>(null)
// Its own input: sharing the header's would upload without the purchase.
const purchaseFileInputRef = useRef<HTMLInputElement | null>(null)
const { openAgentSheet, identity } = useAgentSheet()
const [items, setItems] = useState<InboxItem[]>([])
@@ -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<PurchaseWithoutUnderlag[]>([])
const [selectedPurchaseId, setSelectedPurchaseId] = useState<string | null>(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<InboxMailConnection[]>([])
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) {
<div className="flex items-center gap-2 min-w-0">
<Inbox className="h-4 w-4 text-muted-foreground shrink-0" />
<h1 className="font-medium text-sm shrink-0">Dokumentinkorg</h1>
{inboxAddress ? (
<InboxAddressBar
address={inboxAddress.address}
onRotate={handleRotateAddress}
isRotating={isRotating}
/>
{/* 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 ? (
<Button
variant="ghost"
size="sm"
onClick={() => setSourcesOpen((v) => !v)}
className={cn(
'h-7 px-2 text-xs font-normal shrink-0',
ailingMailbox ? 'text-warning' : 'text-muted-foreground',
)}
aria-expanded={sourcesOpen}
>
{/* No marker on the healthy state. Convention 5: a normal state
is muted text, and a chip every company sees always is a chip
that says nothing. Convention 12 rules out the sage anyway,
semantic colour being data rather than chrome. What remains is
the exception, which is the one thing worth an ochre word. */}
{ailingMailbox && <AlertTriangle className="h-3 w-3 mr-1.5" />}
{ailingMailbox
? `${ailingMailbox.emailAddress} behöver återanslutas`
: `${sourceCount} ${sourceCount === 1 ? 'källa' : 'källor'}`}
<ChevronDown className="h-3 w-3 ml-1 opacity-60" />
</Button>
) : 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) {
</div>
</header>
{huntResult && (
<div className="border-b px-4 py-2 text-xs flex items-center gap-2">
{huntResult.failed ? (
<span className="text-warning">
{/* 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.'}
</span>
) : huntResult.fetched > 0 ? (
<span>
<b className="font-medium tabular-nums">{huntResult.fetched}</b> nya underlag hämtade.{' '}
{huntResult.remaining > 0 && (
<>
<b className="font-medium tabular-nums">{huntResult.remaining}</b> 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 ? (
<>
<b className="font-medium tabular-nums">{huntResult.proposed}</b> förslag väntar på{' '}
<Link href="/pending" className="underline hover:text-foreground">
granskning
</Link>
.
</>
) : (
// 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.</>
)}
</span>
) : (
<span className="text-muted-foreground">
Inga nya underlag i brevlådorna för de köp som saknar ett.
</span>
)}
</div>
)}
{/* 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 && (
<div className="border-b bg-muted/20 text-xs">
{inboxAddress && (
<div className="flex items-center gap-3 px-4 py-2 border-b border-border">
<Mail className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
<div className="min-w-0 flex-1">
<span className="tabular-nums">{inboxAddress.address}</span>
</div>
<InboxAddressBar
address={inboxAddress.address}
onRotate={handleRotateAddress}
isRotating={isRotating}
/>
</div>
)}
{mailConnections.map((c) => (
<details key={c.id} className="group border-b border-border">
<summary className="flex items-center gap-3 px-4 py-2 cursor-pointer list-none hover:bg-secondary/40">
{c.provider === 'gmail' ? (
<GoogleMark className="h-3.5 w-3.5 shrink-0" />
) : (
<MicrosoftMark className="h-3.5 w-3.5 shrink-0" />
)}
<span className="truncate flex-1">{c.emailAddress}</span>
{c.status !== 'active' && (
<Badge variant="warning" className="text-[10px] font-normal shrink-0">
Behöver återanslutas
</Badge>
)}
<ChevronRight className="h-3 w-3 text-muted-foreground transition-transform group-open:rotate-90 shrink-0" />
</summary>
{/* 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. */}
<dl className="px-4 pb-2.5 pl-11 text-[11px] text-muted-foreground space-y-0.5">
<div className="flex gap-2">
<dt className="w-24 shrink-0">{t('source_last_searched')}</dt>
<dd className="tabular-nums">
{c.lastSearchedAt ? formatDateLong(c.lastSearchedAt) : t('source_never_searched')}
</dd>
</div>
<div className="flex gap-2">
<dt className="w-24 shrink-0">Status</dt>
<dd>
{c.status === 'active'
? t('source_searched_when_hunting')
: t('source_not_searched')}
</dd>
</div>
</dl>
</details>
))}
{whatsapp?.linked && (
<details className="group border-b border-border">
<summary className="flex items-center gap-3 px-4 py-2 cursor-pointer list-none hover:bg-secondary/40">
<WhatsAppMark className="h-3.5 w-3.5 shrink-0" />
<span className="flex-1 truncate">WhatsApp</span>
<ChevronRight className="h-3 w-3 text-muted-foreground transition-transform group-open:rotate-90 shrink-0" />
</summary>
<dl className="px-4 pb-2.5 pl-11 text-[11px] text-muted-foreground space-y-0.5">
<div className="flex gap-2">
<dt className="w-24 shrink-0">{t('source_whatsapp_number')}</dt>
<dd className="tabular-nums">{whatsapp.phoneMasked ?? '-'}</dd>
</div>
<div className="flex gap-2">
<dt className="w-24 shrink-0">Status</dt>
<dd>{whatsapp.verifiedAt ? t('source_verified') : t('source_unverified')}</dd>
</div>
</dl>
</details>
)}
</div>
)}
{/* 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"
/>
</div>
<div className="flex flex-wrap gap-1">
{pills.map((pill) => (
<button
key={pill.key}
type="button"
onClick={() => {
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') setSelectedId(null)
else setSelectedPurchaseId(null)
}}
className={cn(
'text-[11px] px-2 py-0.5 rounded-full border transition-colors',
filter === pill.key
? 'bg-primary text-primary-foreground border-primary'
: 'bg-background text-muted-foreground border-border hover:text-foreground'
)}
{/* One row instead of three. Five filters wrapped to three lines
in a 280px column, and the counts are what people actually
read, so they stay visible on the trigger and inside the menu
rather than being traded away for the space. */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
className="w-full justify-between h-8 px-2.5 text-xs font-normal"
>
{pill.label}
{pill.count > 0 && (
<span
className={cn(
'ml-1 tabular-nums',
filter === pill.key ? 'opacity-80' : 'opacity-50'
)}
>
{pill.count}
<span className="flex items-center gap-1.5 min-w-0">
<span className="truncate">{activePill?.label ?? 'Att göra'}</span>
<span className="tabular-nums text-muted-foreground">
{activePill?.count ?? 0}
</span>
)}
</button>
))}
</div>
</span>
<ChevronDown className="h-3.5 w-3.5 opacity-60 shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-[--radix-dropdown-menu-trigger-width]">
{pills.map((pill) => (
<DropdownMenuItem
key={pill.key}
onSelect={() => {
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"
>
<span className="flex items-center gap-2">
<Check
className={cn(
'h-3.5 w-3.5',
filter === pill.key ? 'opacity-100' : 'opacity-0',
)}
/>
{pill.label}
</span>
<span className="tabular-nums text-muted-foreground">{pill.count}</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
{selectedIds.size > 0 && (
@@ -1174,17 +1476,25 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
Inkorgen är tom.
</div>
)
) : (filter === 'missing' ? filteredPurchases.length : filteredItems.length) === 0 ? (
) : (filter === 'missing' || filter === 'portal' ? filteredPurchases.length : filteredItems.length) === 0 ? (
<div className="p-6 text-center text-xs text-muted-foreground">
{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.'}
</div>
) : (
<ul>
{filter === 'missing'
{filter === 'missing' || filter === 'portal'
? filteredPurchases.map((p) => (
<PurchaseRow
key={p.id}
@@ -1222,17 +1532,65 @@ export default function InvoiceInboxWorkspace(_props: WorkspaceComponentProps) {
)}
>
{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.
<div className="h-full flex items-center justify-center p-8">
<div className="text-center max-w-sm">
<div className="text-center max-w-sm w-full">
<FileQuestion className="h-6 w-6 mx-auto mb-3 text-muted-foreground opacity-60" />
<p className="text-sm">Inget underlag hittat</p>
<p className="text-sm">{t('purchase_no_document')}</p>
<p className="text-xs text-muted-foreground mt-1.5">
{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.'}
</p>
{selectedPurchase.portal && (
<Button size="sm" variant="outline" className="mt-4" asChild>
<a href={selectedPurchase.portal.url} target="_blank" rel="noopener noreferrer">
Öppna {selectedPurchase.portal.vendor}
<ExternalLink className="h-3.5 w-3.5 ml-1.5" />
</a>
</Button>
)}
<input
ref={purchaseFileInputRef}
type="file"
className="hidden"
accept="application/pdf,image/jpeg,image/png,image/heic,image/heif,image/webp"
onChange={async (e) => {
const files = Array.from(e.target.files ?? [])
if (files.length > 0) await uploadForPurchase(files, selectedPurchase.id)
if (purchaseFileInputRef.current) purchaseFileInputRef.current.value = ''
}}
/>
<button
type="button"
onClick={() => purchaseFileInputRef.current?.click()}
disabled={isUploading}
className={cn(
'mt-4 w-full rounded-lg border border-dashed px-4 py-6 text-xs transition-colors',
'text-muted-foreground hover:border-foreground hover:text-foreground',
isDragging && 'border-foreground text-foreground bg-secondary/40',
)}
>
{isUploading ? (
<span className="flex items-center justify-center gap-2">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Laddar upp…
</span>
) : (
<>
Släpp filen här, eller klicka för att välja
<span className="block mt-1 opacity-70">
{formatCurrency(Math.abs(selectedPurchase.amount), selectedPurchase.currency ?? undefined)}
{' · '}
{formatDate(selectedPurchase.date)}
</span>
</>
)}
</button>
</div>
</div>
) : 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' ? (
<Mail className="h-3 w-3 text-muted-foreground shrink-0" />
) : item.source === 'whatsapp' ? (
<MessageCircle className="h-3 w-3 text-muted-foreground shrink-0" />
<WhatsAppMark className="h-3 w-3 shrink-0" />
) : 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.
<GoogleMark className="h-3 w-3 shrink-0" />
) : item.channel_context?.mail_provider === 'microsoft' ? (
<MicrosoftMark className="h-3 w-3 shrink-0" />
) : (
<Upload className="h-3 w-3 text-muted-foreground shrink-0" />
)}
@@ -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 (
<li>
<button
@@ -1967,7 +2347,7 @@ function PurchaseRow({
>
<div className="flex items-baseline justify-between gap-2">
<span className="text-[13px] truncate">
{purchase.merchant_name || purchase.description || 'Okänt köp'}
{purchase.merchant_name || purchase.description || t('purchase_unknown')}
</span>
<span className="text-xs tabular-nums shrink-0">
{formatCurrency(Math.abs(purchase.amount), purchase.currency ?? undefined)}
@@ -1989,13 +2369,14 @@ function PurchaseRow({
}
function PurchaseRail({ purchase }: { purchase: PurchaseWithoutUnderlag }) {
const t = useTranslations('inbox_workspace')
return (
<div className="p-4 space-y-4">
<div>
<h3 className="text-sm font-medium">
{purchase.merchant_name || purchase.description || 'Okänt köp'}
{purchase.merchant_name || purchase.description || t('purchase_unknown')}
</h3>
<p className="text-xs text-muted-foreground mt-0.5">Köp utan underlag</p>
<p className="text-xs text-muted-foreground mt-0.5">{t('purchase_kind')}</p>
</div>
<dl className="space-y-1.5 text-xs">
@@ -2011,7 +2392,7 @@ function PurchaseRail({ purchase }: { purchase: PurchaseWithoutUnderlag }) {
</div>
{purchase.description && (
<div className="flex justify-between gap-3">
<dt className="text-muted-foreground shrink-0">Kontotext</dt>
<dt className="text-muted-foreground shrink-0">{t('purchase_bank_text')}</dt>
<dd className="text-muted-foreground text-right break-words">{purchase.description}</dd>
</div>
)}
@@ -2089,7 +2470,15 @@ const SUGGESTION_EMPTY_REASON: Record<string, string> = {
'Köpet är i utländsk valuta och matchades av en konteringsregel. Momsen skulle bli fel, så vi visar inget förslag.',
}
function ProposedBooking({ itemId }: { itemId: string }) {
function ProposedBooking({
itemId,
onLoaded,
}: {
itemId: string
/** Hands the loaded proposal up so the editor can open pre-filled with it. */
onLoaded?: (data: SuggestedBooking | null) => void
}) {
const t = useTranslations('inbox_workspace')
const [state, setState] = useState<'loading' | 'ready' | 'failed'>('loading')
const [data, setData] = useState<SuggestedBooking | null>(null)
@@ -2112,17 +2501,24 @@ function ProposedBooking({ itemId }: { itemId: string }) {
.then((json) => {
if (cancelled) return
setData(json.data)
onLoaded?.(json.data)
setState('ready')
})
.catch(() => {
// A suggestion that cannot be fetched is not something the user did:
// stay quiet rather than showing an error beside their document.
if (!cancelled) setState('failed')
if (!cancelled) {
onLoaded?.(null)
setState('failed')
}
})
return () => {
cancelled = true
controller.abort()
}
// onLoaded is intentionally excluded: a new identity each render
// would refetch on every parent render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [itemId])
if (state === 'loading') return <Skeleton className="h-24 w-full" />
@@ -2141,7 +2537,7 @@ function ProposedBooking({ itemId }: { itemId: string }) {
return (
<div className="space-y-2">
<div className="flex items-baseline justify-between gap-3">
<h3 className="text-xs font-medium">Föreslagen kontering</h3>
<h3 className="text-xs font-medium">{t('proposal_title')}</h3>
{data.entry_date && (
<span className="text-[11px] text-muted-foreground tabular-nums">
Bokförs {formatDate(data.entry_date)}
@@ -2188,7 +2584,7 @@ function ProposedBooking({ itemId }: { itemId: string }) {
{(SUGGESTION_SOURCE_LABEL[data.source] || data.requires_review || data.direction_mismatch) && (
<details className="text-[11px] text-muted-foreground">
<summary className="cursor-pointer hover:text-foreground">Varför så här?</summary>
<summary className="cursor-pointer hover:text-foreground">{t('proposal_why')}</summary>
<div className="pt-1.5 space-y-1">
{SUGGESTION_SOURCE_LABEL[data.source] && <p>{SUGGESTION_SOURCE_LABEL[data.source]}</p>}
{data.rule_name && <p>Regel: {data.rule_name}</p>}
@@ -2223,6 +2619,7 @@ function FieldsRail({
isDeleting,
onFieldsUpdated,
onRetryRequested,
onBookedLocally,
}: {
item: InboxItem
docMime: string | null
@@ -2235,11 +2632,22 @@ function FieldsRail({
onAskAssistant?: (transactionId: string) => void
isDeleting: boolean
onFieldsUpdated: (data: InvoiceExtractionResult) => void
/** Re-read the item after this rail posted a verifikat for it. */
onBookedLocally?: () => void
onRetryRequested: () => Promise<void>
}) {
const { toast } = useToast()
const hasAi = useCapability(CAPABILITY.ai)
const data = item.extracted_data
const [proposal, setProposal] = useState<SuggestedBooking | null>(null)
const [editOpen, setEditOpen] = useState(false)
// A proposal belongs to one item; carrying it to the next would offer the
// previous underlag's accounts for this one's money.
useEffect(() => {
setProposal(null)
setEditOpen(false)
}, [item.id])
const isProcessed = !!item.created_supplier_invoice_id
const isBookedDirectly = !isProcessed && !!item.created_journal_entry_id
// "Resolved" now means a journal entry exists: matched_transaction_id alone
@@ -2486,25 +2894,47 @@ function FieldsRail({
</div>
)}
{/* Extracted fields */}
<div className="flex-1 overflow-y-auto px-4 py-3">
<div className="flex items-center justify-between mb-3">
<h3 className="text-xs uppercase tracking-wide text-muted-foreground font-medium">
Extraherade fält
</h3>
{!item.isPlaceholder && (hasAnyExtractedField(data) || hasAi) && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 -my-2 text-muted-foreground hover:text-foreground"
onClick={() => setFieldsExpanded(true)}
aria-label={t('expand_fields')}
title={t('expand_fields')}
>
<Maximize2 className="h-3.5 w-3.5" />
</Button>
)}
</div>
<div className="flex-1 overflow-y-auto px-4 py-3 space-y-4">
{/* 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 && <ProposedBooking itemId={item.id} onLoaded={setProposal} />}
<details className="group" open={!isLinkedToTransaction}>
<summary className="flex items-center gap-1.5 cursor-pointer list-none text-xs uppercase tracking-wide text-muted-foreground font-medium hover:text-foreground">
<ChevronRight className="h-3 w-3 transition-transform group-open:rotate-90" />
<span className="flex-1">{t('fields_summary')}</span>
{/* 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 && (
<span className="tabular-nums normal-case tracking-normal">
{t('fields_filled', { count: countExtractedFields(data) })}
</span>
)}
{/* 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) && (
<span
role="button"
tabIndex={0}
onClick={(e) => { 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"
>
<Maximize2 className="h-3.5 w-3.5" />
</span>
)}
</summary>
<div className="pt-3">
{item.isPlaceholder ? (
<div className="space-y-2">
<div className="text-xs text-muted-foreground italic flex items-center gap-2 mb-2">
@@ -2541,6 +2971,8 @@ function FieldsRail({
onUpdated={onFieldsUpdated}
/>
)}
</div>
</details>
</div>
{/* Actions: hidden while AI extraction is in flight */}
@@ -2578,9 +3010,6 @@ function FieldsRail({
</Link>
</div>
{/* The answer the rail never gave: what this would be booked as.
Read-only; booking still goes through the dialog below. */}
<ProposedBooking itemId={item.id} />
{onAskAssistant && (
<Button
variant="default"
@@ -2591,13 +3020,18 @@ function FieldsRail({
Fråga assistenten
</Button>
)}
{/* One control, and its scope is the whole verifikat. It opens
pre-filled with the proposal when there is one and empty when
there is not, so there is no separate "book manually" path to
choose between. Nothing posts from here without the form's own
review step (convention 14). */}
<Button
variant="outline"
size="sm"
className="w-full"
onClick={onBookDirect}
onClick={() => setEditOpen(true)}
>
Bokför manuellt
{proposal?.lines.length ? t('review_and_book') : t('book_manually')}
</Button>
<button
type="button"
@@ -2709,12 +3143,43 @@ function FieldsRail({
</div>
)}
<EditKonteringDialog
open={editOpen}
onOpenChange={setEditOpen}
itemId={item.id}
documentId={item.document_id ?? null}
documentMime={docMime}
documentUrl={null}
fileName={item.fileName ?? null}
transactionId={item.matched_transaction_id ?? null}
// BFL 5 kap 6-7 § wants datum för affärshändelsen. The proposal's date
// is the bank's, which is the event for a matched purchase. Without one
// the document's own date is the next best truth; today is the day
// somebody opened a dialog and is nobody's business event. The field is
// editable either way, but a silent wrong default is not checked.
entryDate={
proposal?.entry_date ??
data?.invoice?.invoiceDate ??
new Date().toISOString().slice(0, 10)
}
description={data?.supplier?.name ?? item.email_subject ?? 'Underlag'}
lines={proposal?.lines ?? []}
onBooked={() => {
setEditOpen(false)
// Realtime refreshes the list, but this rail renders from the
// `selected` object the parent already fetched, so it would keep
// offering "Granska och bokför" for an underlag that now has a
// verifikat, and a second press would post a duplicate.
onBookedLocally?.()
}}
/>
{/* Expanded fields editor: same autosaving list as the rail, at a
readable size. Convention 13: centered modal. */}
<Dialog open={fieldsExpanded} onOpenChange={setFieldsExpanded}>
<DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Extraherade fält</DialogTitle>
<DialogTitle>{t('fields_summary')}</DialogTitle>
</DialogHeader>
<EditableFieldsList
itemId={item.id}
@@ -450,4 +450,46 @@ describe('POST /items/:id/book-direct', () => {
}),
)
})
it('keeps an existing match when the caller omits transaction_id', async () => {
// A caller that merely forgets the field used to unpick a match somebody
// had already made: the verifikat posted standalone, the bank line stayed
// unbooked, and nothing on screen said so. Forgetting a field must not
// undo work.
const { supabase, enqueue, calls } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({ document_id: 'doc-1', matched_transaction_id: TX_UUID }),
})
enqueue({ data: null }) // inbox item update
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: VALID_BODY, // no transaction_id
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
expect(res.status).toBe(200)
// The preserved match must also be BOOKED. Keeping the link while leaving
// the bank line open is the worse half of the bug: the item looks resolved
// and the transaction stays outstanding forever.
const txUpdate = calls.find(
(c: { method: string; args?: unknown[] }) =>
c.method === 'update' &&
typeof c.args?.[0] === 'object' &&
c.args?.[0] !== null &&
'journal_entry_id' in (c.args[0] as Record<string, unknown>),
)
expect(txUpdate, 'the preserved transaction was never booked').toBeTruthy()
const update = calls.find(
(c: { method: string; args?: unknown[] }) =>
c.method === 'update' &&
typeof c.args?.[0] === 'object' &&
c.args?.[0] !== null &&
'created_journal_entry_id' in (c.args[0] as Record<string, unknown>),
)
expect((update?.args?.[0] as Record<string, unknown>).matched_transaction_id).toBe(TX_UUID)
})
})
+14 -4
View File
@@ -2256,8 +2256,14 @@ export const invoiceInboxExtension: Extension = {
}
}
// If transaction-linked, mark the transaction as booked.
if (transaction) {
// The transaction this verifikat settles: the one the caller named, or
// the one the item was already matched to. Preserving the match without
// booking it was half a fix, and the worse half: the item then looked
// resolved while the bank line stayed open forever. The fallback needs
// no ownership check because it was read off a company-scoped item.
const bookedTransactionId = transaction?.id ?? item.matched_transaction_id ?? null
if (bookedTransactionId) {
const { error: txUpdateError } = await ctx.supabase
.from('transactions')
.update({
@@ -2265,7 +2271,7 @@ export const invoiceInboxExtension: Extension = {
is_business: true,
category: 'uncategorized',
})
.eq('id', transaction.id)
.eq('id', bookedTransactionId)
.eq('company_id', ctx.companyId)
if (txUpdateError) {
console.error('[invoice-inbox/book-direct] Transaction link failed:', txUpdateError)
@@ -2280,7 +2286,11 @@ export const invoiceInboxExtension: Extension = {
.from('invoice_inbox_items')
.update({
created_journal_entry_id: journalEntry.id,
matched_transaction_id: transaction?.id ?? null,
// Keep the existing match when the caller sent no transaction_id.
// Overwriting with null let a caller that merely forgot the field
// silently unpick a match somebody had already made, and left the
// bank line unbooked with nothing on screen saying so.
matched_transaction_id: bookedTransactionId,
})
.eq('id', id)
.eq('company_id', ctx.companyId)
+9 -2
View File
@@ -62,7 +62,14 @@ export interface ChatClarifications {
type: 'representation' | 'context' | 'resend'
status: 'open' | 'moved_to_app'
} | null
/** Where these answers were captured, for provenance in the prompt. */
/**
* Where these answers were captured, for provenance in the prompt.
*
* Only WhatsApp asks a human anything, so only WhatsApp produces
* clarifications. The mail hunt writes the same column with its own shape
* and never carries answers, which is why this stays narrow while
* InboxChannelContext.channel spans both intakes.
*/
channel: 'whatsapp'
}
@@ -112,7 +119,7 @@ export function summariseClarifications(
userNote,
contextAnswerRaw,
openQuestion,
channel: ctx.channel,
channel: 'whatsapp',
}
}
@@ -9,7 +9,6 @@ import { PORTAL_DIRECTORY, lookupPortal } from '../portal-directory'
describe('lookupPortal', () => {
it('reads a card descriptor the bank has mangled', () => {
// Real strings from a production ledger.
expect(lookupPortal('ANTHROPIC* CLAUDE SUB SAN FRANCISCO Kortköp/uttag')?.vendor).toBe('Anthropic')
expect(lookupPortal('OPENAI CHATGPT SUBSCR')?.vendor).toBe('OpenAI')
expect(lookupPortal('Kortköp 260228 HETZNER ONLINE GMBH')?.vendor).toBe('Hetzner')
})
@@ -27,6 +26,15 @@ describe('lookupPortal', () => {
expect(lookupPortal('Skatt lön Juni BG 0000050501055')).toBeNull()
})
it('says nothing about a supplier that emails its invoices', () => {
// The bar is "does not send the invoice", not "also has a portal".
// Anthropic, Vercel and Supabase all mail theirs to European customers, so
// pointing somebody at a login sends them away from the document.
expect(lookupPortal('ANTHROPIC* CLAUDE SUB SAN FRANCISCO')).toBeNull()
expect(lookupPortal('Vercel Jul Överföring via internet')).toBeNull()
expect(lookupPortal('SUPABASE PRO SUBSCRIPTION')).toBeNull()
})
it('says nothing about a supplier it does not know', () => {
expect(lookupPortal('ALVIKS KOETT OCH FISK K3667')).toBeNull()
expect(lookupPortal('RESTAURANG RIDD K3667 Kortköp/uttag')).toBeNull()
+38 -25
View File
@@ -52,14 +52,48 @@ export interface PortalEntry {
/**
* Ordered by how many companies actually pay them, measured across production
* ledgers, cross-checked against a customer poll. Google and OpenAI lead on
* both counts by a wide margin.
* ledgers, cross-checked against a customer poll.
*
* The bar is "does not send the invoice", not "also has a portal". Almost every
* vendor here has a billing page; what earns an entry is that the invoice does
* not arrive by mail, so a person has no other way to get it.
*
* Anthropic, Vercel and Supabase were removed after a founder pointed out that
* all three do email their invoices, at least to European customers. The poll
* they came from asked which portals people log into, and people answered with
* where the invoice can ALSO be found. Listing them told somebody to go and log
* in for a document already sitting in their inbox, which is worse than saying
* nothing: it sends them away from the answer.
*
* The same objection may reach further down this list. An entry is a claim that
* the invoice cannot be had any other way, and that claim is worth checking per
* vendor rather than assuming.
*
* ## The URLs were wrong, and shipped anyway
*
* Every path here was hand-written and none was opened. The file said so and
* shipped regardless, and a founder then hit a 404 on Google Workspace. A
* subsequent HTTP sweep found GitHub's billing path 404 as well. Both are
* corrected; Trygg Hansa was removed because neither of its candidate URLs
* could be reached at all, and an unverifiable link is the same promise this
* comment keeps warning about.
*
* Prefer the shallowest URL that certainly resolves. A link landing one click
* short of the invoice is a small cost; one landing on an error page spends
* the trust the whole feature runs on. Several hosts here (Google, OpenAI,
* Hetzner) refuse an automated request, so they cannot be swept: those stay
* shallow on purpose.
*/
export const PORTAL_DIRECTORY: PortalEntry[] = [
{
vendor: 'Google Workspace',
aliases: ['google workspace', 'google gsuite', 'google apps'],
url: 'https://admin.google.com/ac/billing/history',
// The console root, not a deep billing path. /ac/billing/history returned
// a 404 in a real browser, and admin.google.com blocks the checker, so no
// deeper path can be verified from here. The root certainly resolves and
// billing is one click from it; a link that lands slightly short beats one
// that lands on an error page.
url: 'https://admin.google.com',
note: 'Fakturor ligger under Fakturering i adminkonsolen.',
},
{
@@ -109,16 +143,6 @@ export const PORTAL_DIRECTORY: PortalEntry[] = [
aliases: ['atlassian', 'jira', 'confluence'],
url: 'https://admin.atlassian.com/billing',
},
{
vendor: 'Anthropic',
aliases: ['anthropic', 'claude ai', 'claude sub'],
url: 'https://console.anthropic.com/settings/billing',
},
{
vendor: 'Vercel',
aliases: ['vercel'],
url: 'https://vercel.com/account/invoices',
},
{
vendor: 'Hetzner',
aliases: ['hetzner'],
@@ -127,12 +151,7 @@ export const PORTAL_DIRECTORY: PortalEntry[] = [
{
vendor: 'GitHub',
aliases: ['github'],
url: 'https://github.com/settings/billing',
},
{
vendor: 'Supabase',
aliases: ['supabase'],
url: 'https://supabase.com/dashboard/org/_/billing',
url: 'https://github.com/settings/billing/summary',
},
{
vendor: 'Cursor',
@@ -144,12 +163,6 @@ export const PORTAL_DIRECTORY: PortalEntry[] = [
aliases: ['loopia'],
url: 'https://customerzone.loopia.se',
},
{
vendor: 'Trygg Hansa',
aliases: ['trygg hansa', 'trygghansa'],
url: 'https://mitt.trygghansa.se',
note: 'Försäkringsbrev och fakturor under Mina sidor.',
},
]
/**
+14 -6
View File
@@ -29,11 +29,19 @@ import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { isTransactionBooked } from '@/lib/transactions/is-booked'
/**
* Kept equal to the receipt hunt's own thresholds (MIN_AMOUNT_SEK,
* LOOKBACK_MONTHS in lib/receipt-hunt/hunt.ts). A page that showed purchases
* the hunt never looks for would offer a row it can never resolve on its own.
* Deliberately below the receipt hunt's own floor (MIN_AMOUNT_SEK = 100 in
* lib/receipt-hunt/hunt.ts), and the two are not meant to match.
*
* The hunt has a floor because every candidate costs a mail search and a model
* read, so chasing a 45 kr purchase is not worth the spend. This list costs a
* query. Bokföringslagen wants an underlag for the 45 kr purchase exactly as
* much as for the 4 500 kr one, and the person can always upload it by hand
* even when the hunt will not go looking.
*
* Matching the hunt's floor hid 52 of one real company's 119 unreceipted
* purchases: the page under-reported by 44% and looked tidier for it.
*/
export const MIN_PURCHASE_AMOUNT_SEK = 100
export const MIN_PURCHASE_AMOUNT_SEK = 0
export const PURCHASE_LOOKBACK_MONTHS = 12
export interface PurchaseWithoutUnderlag {
@@ -83,8 +91,8 @@ export async function fetchPurchasesWithoutUnderlag(
// "business, not yet booked". Only an explicit false means the user
// called it private, and a private purchase needs no underlag.
.not('is_business', 'is', false)
// Outflows only, and amount <= -MIN covers the floor in one filter.
.lte('amount', -minAmount)
// Outflows only. With no floor this is simply every negative row.
.lt('amount', minAmount > 0 ? -minAmount : 0)
.gte('date', sinceDate)
.order('date', { ascending: false })
.range(range.from, range.to),
+57
View File
@@ -3049,6 +3049,63 @@
"mixed_currency_note": "Documents in different currencies cannot be summed into a single amount. Each document is still booked separately, against its matched bank transaction and the amount the bank actually settled in SEK."
},
"inbox_workspace": {
"dialog_no_document": "No document",
"sources_one": "{count} source",
"sources_many": "{count} sources",
"source_needs_reconnect": "{address} needs reconnecting",
"source_last_searched": "Last searched",
"source_never_searched": "Never",
"source_status": "Status",
"source_searched_when_hunting": "Searched when you look",
"source_not_searched": "Not searched until reconnected",
"source_reconnect_badge": "Needs reconnecting",
"source_whatsapp_number": "Number",
"source_verified": "Verified",
"source_unverified": "Not verified yet",
"hunt_button": "Search the mailboxes",
"hunt_running": "Searching…",
"hunt_running_found": "Searching… {count} found",
"hunt_fetched": "{count} new documents fetched.",
"hunt_remaining": "{count} purchases left to search for: press again.",
"hunt_staged": "{count} proposals awaiting review.",
"hunt_none": "Nothing matched a purchase yet. Press again to keep looking.",
"hunt_failed_mailbox": "A mailbox did not answer. Try again shortly.",
"hunt_failed": "The search could not finish. Try again.",
"filter_missing": "Missing a document",
"filter_portal": "Fetch from portal",
"empty_no_search_hits": "No matches for “{term}”.",
"empty_all_covered": "Every purchase has its document.",
"empty_no_portal": "No purchases are waiting on a portal invoice.",
"purchase_no_document": "No document found",
"purchase_portal_hint": "{vendor} sends no file. Fetch the invoice and drop it here.",
"purchase_searched_hint": "We searched the mailboxes. Drop the receipt here, or forward it to the inbox address.",
"purchase_open_portal": "Open {vendor}",
"purchase_drop": "Drop the file here, or click to choose",
"purchase_uploading": "Uploading…",
"purchase_kind": "Purchase without a document",
"purchase_date": "Date",
"purchase_amount": "Amount",
"purchase_bank_text": "Bank text",
"purchase_unknown": "Unknown purchase",
"linked_document": "Document linked",
"linked_document_extra": "{name}. {count} more added to the inbox.",
"link_failed": "Uploaded, but not linked",
"link_failed_body": "The document is in the inbox. Link it to the purchase from there.",
"proposal_title": "Proposed entry",
"proposal_booked_on": "Books on {date}",
"proposal_why": "Why this?",
"proposal_from_counterparty": "How you usually book this supplier",
"proposal_from_template": "From a booking template",
"proposal_from_rule": "From a mapping rule",
"proposal_rule_named": "Rule: {name}",
"proposal_direction_mismatch": "The amount's direction contradicts how this supplier is usually booked. Check before booking.",
"proposal_needs_review": "The proposal is uncertain and should be reviewed before booking.",
"proposal_none_unknown": "No proposal: the supplier is unknown and no rule matches. Book it by hand once and it will be recognised next time.",
"proposal_none_currency": "The purchase is in foreign currency and matched a mapping rule. The VAT would be wrong, so no proposal is shown.",
"fields_summary": "Extracted fields",
"fields_filled": "{count} filled",
"review_and_book": "Review and book",
"book_manually": "Book manually",
"retry": "Try again",
"copy_address": "Copy address",
"copy_address_failed": "The address was not copied. Select it above and copy it manually.",
+57
View File
@@ -3049,6 +3049,63 @@
"mixed_currency_note": "Underlag i olika valutor kan inte summeras till ett belopp. Varje underlag bokförs ändå var för sig, mot sin matchade banktransaktion och det belopp banken faktiskt drog i SEK."
},
"inbox_workspace": {
"dialog_no_document": "Ingen handling",
"sources_one": "{count} källa",
"sources_many": "{count} källor",
"source_needs_reconnect": "{address} behöver återanslutas",
"source_last_searched": "Söktes senast",
"source_never_searched": "Aldrig",
"source_status": "Status",
"source_searched_when_hunting": "Söks igenom när du letar",
"source_not_searched": "Söks inte igenom förrän den återanslutits",
"source_reconnect_badge": "Behöver återanslutas",
"source_whatsapp_number": "Nummer",
"source_verified": "Verifierat",
"source_unverified": "Inte verifierat än",
"hunt_button": "Leta i mejlen",
"hunt_running": "Letar…",
"hunt_running_found": "Letar… {count} hittade",
"hunt_fetched": "{count} nya underlag hämtade.",
"hunt_remaining": "{count} köp kvar att söka för: tryck igen.",
"hunt_staged": "{count} förslag väntar på granskning.",
"hunt_none": "Inget matchade något köp än. Tryck igen för att leta vidare.",
"hunt_failed_mailbox": "En brevlåda svarade inte. Försök igen om en stund.",
"hunt_failed": "Sökningen kunde inte slutföras. Försök igen.",
"filter_missing": "Saknar underlag",
"filter_portal": "Hämta från portal",
"empty_no_search_hits": "Inga träffar på ”{term}”.",
"empty_all_covered": "Varje köp har sitt underlag.",
"empty_no_portal": "Inga köp väntar på en faktura från en portal.",
"purchase_no_document": "Inget underlag hittat",
"purchase_portal_hint": "{vendor} skickar ingen fil. Hämta fakturan och släpp den här.",
"purchase_searched_hint": "Vi har sökt i brevlådorna. Släpp kvittot här, eller vidarebefordra det till inkorgsadressen.",
"purchase_open_portal": "Öppna {vendor}",
"purchase_drop": "Släpp filen här, eller klicka för att välja",
"purchase_uploading": "Laddar upp…",
"purchase_kind": "Köp utan underlag",
"purchase_date": "Datum",
"purchase_amount": "Belopp",
"purchase_bank_text": "Kontotext",
"purchase_unknown": "Okänt köp",
"linked_document": "Underlag kopplat",
"linked_document_extra": "{name}. {count} till lades i inkorgen.",
"link_failed": "Uppladdat, men inte kopplat",
"link_failed_body": "Dokumentet ligger i inkorgen. Koppla det till köpet därifrån.",
"proposal_title": "Föreslagen kontering",
"proposal_booked_on": "Bokförs {date}",
"proposal_why": "Varför så här?",
"proposal_from_counterparty": "Så du brukar bokföra den här leverantören",
"proposal_from_template": "Från en bokföringsmall",
"proposal_from_rule": "Från en konteringsregel",
"proposal_rule_named": "Regel: {name}",
"proposal_direction_mismatch": "Beloppets riktning stämmer inte med hur leverantören brukar bokföras. Kontrollera innan du bokför.",
"proposal_needs_review": "Förslaget är osäkert och bör granskas innan du bokför.",
"proposal_none_unknown": "Vi har inget förslag: leverantören är obekant och ingen regel matchar. Bokför manuellt en gång, så känns den igen nästa gång.",
"proposal_none_currency": "Köpet är i utländsk valuta och matchades av en konteringsregel. Momsen skulle bli fel, så vi visar inget förslag.",
"fields_summary": "Extraherade fält",
"fields_filled": "{count} ifyllda",
"review_and_book": "Granska och bokför",
"book_manually": "Bokför manuellt",
"retry": "Försök igen",
"copy_address": "Kopiera adress",
"copy_address_failed": "Adressen kopierades inte. Markera den ovan och kopiera manuellt.",
+71
View File
@@ -0,0 +1,71 @@
/**
* Open every URL in the portal directory and report the ones that are wrong.
*
* The directory shipped with eighteen hand-written paths, none of them opened.
* The file warned about exactly that and shipped anyway, and a founder then hit
* a 404 on Google Workspace. A sweep found GitHub broken too. This exists so
* the next wrong URL is found by a script rather than by a person who trusted
* the link.
*
* npx tsx scripts/check-portal-urls.mts
*
* A 404 is the signal. 401/403 and a redirect to a login host both mean the
* path exists and is asking who you are, which is the expected answer for a
* billing page. Several hosts (Google, OpenAI, Hetzner) refuse automated
* requests outright and report as UNREACHABLE: that is not proof of a bad URL,
* only proof that this script cannot judge it, and those entries should be kept
* shallow enough that a human landing on them is never lost.
*/
import { PORTAL_DIRECTORY } from '../lib/receipt-hunt/portal-directory'
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
type Verdict = 'OK' | 'BROKEN' | 'UNREACHABLE'
async function check(url: string): Promise<{ verdict: Verdict; detail: string }> {
try {
const res = await fetch(url, {
redirect: 'follow',
signal: AbortSignal.timeout(15_000),
headers: { 'user-agent': UA },
})
const where = res.redirected ? ` -> ${new URL(res.url).host}` : ''
if (res.status === 404 || res.status === 410) {
return { verdict: 'BROKEN', detail: `${res.status}${where}` }
}
return { verdict: 'OK', detail: `${res.status}${where}` }
} catch (err) {
return { verdict: 'UNREACHABLE', detail: err instanceof Error ? err.message.slice(0, 44) : 'okänt fel' }
}
}
const results = await Promise.all(
PORTAL_DIRECTORY.map(async (entry) => ({ entry, ...(await check(entry.url)) })),
)
for (const r of results) {
const mark = r.verdict === 'BROKEN' ? '✗' : r.verdict === 'UNREACHABLE' ? '?' : '✓'
console.log(`${mark} ${r.entry.vendor.padEnd(22)} ${r.detail.padEnd(30)} ${r.entry.url}`)
}
const broken = results.filter((r) => r.verdict === 'BROKEN')
const unreachable = results.filter((r) => r.verdict === 'UNREACHABLE')
console.log(
`\n${results.length} länkar: ${results.length - broken.length - unreachable.length} svarade, ` +
`${unreachable.length} gick inte att nå, ${broken.length} trasiga`,
)
if (unreachable.length > 0) {
console.log(`\nGick inte att nå (kan inte bedömas härifrån, håll dem grunda):`)
for (const r of unreachable) console.log(` ${r.entry.vendor}: ${r.entry.url}`)
}
// Only a genuine 404 fails the run. An unreachable host is a limit of this
// script, not a defect in the directory, and failing on it would train people
// to ignore the output.
if (broken.length > 0) {
console.error(`\nTrasiga länkar som måste rättas:`)
for (const r of broken) console.error(` ${r.entry.vendor}: ${r.entry.url} (${r.detail})`)
process.exit(1)
}
+12 -1
View File
@@ -2867,7 +2867,18 @@ export interface InvoiceInboxItem {
// Chat-sourced context attached to an inbox item. `raw_answer` + timestamps
// double as the Skatteverket representation documentation trail.
export interface InboxChannelContext {
channel: 'whatsapp'
/**
* Which intake wrote this. 'mail_hunt' rows carry the mail_* fields below;
* everything else on this type belongs to the WhatsApp branch and is absent
* on them.
*/
channel: 'whatsapp' | 'mail_hunt'
/** Set by lib/receipt-hunt/ingest.ts: which mailbox the receipt came out of. */
mail_mailbox?: string | null
mail_provider?: 'gmail' | 'microsoft' | null
mail_subject?: string | null
mail_from?: string | null
mail_received_at?: string | null
caption?: string | null
company_selected_via?: 'button' | 'list' | 'numbered' | 'pin' | 'default' | 'single'
representation?: {