feat(invoice-inbox): surface WhatsApp chat context in booking flows (#1339)

* feat(invoice-inbox): surface WhatsApp chat context in booking flows

The WhatsApp intake bot writes verified human answers (photo caption,
representation deltagare + syfte, sender note, open-question state) to
invoice_inbox_items.channel_context. This makes the in-app booking flows
READ it:

- New core renderer lib/documents/channel-context-notes.ts: deterministic
  compact Swedish line ("Representation: Anna Berg (Volvo), Jakob W ·
  Syfte: uppföljning av avtal"), capped at 220 chars by dropping whole
  participant names ("… och N till"), never mid-name. Representation
  first, then user_note; caption only when nothing else exists.
- FieldsRail "Från WhatsApp" block in InvoiceInboxWorkspace: caption,
  deltagare, syfte, anteckning rows plus an ochre AttnLine when a chat
  question expired unanswered (pending_question.status = moved_to_app).
- Notes threading: book-direct and convert default their notes to the
  rendered string server-side when the request carries none (a supplied
  value always wins); BookDirectlyDialog prefills its notes input with
  the same string so the user can edit it before it lands. Bulk-book
  (categorize-core) joins the shared batch note with the per-item
  rendered context so the representation trail survives batch booking.
- Inbox list: whatsapp rows get a chat icon and a quiet "Fråga obesvarad"
  badge for moved_to_app items. No worklist count change: unresolved
  whatsapp items are already counted by countInboxDocuments.
- sv/en strings for every new key; renderer + route + bulk tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(invoice-inbox): honor cleared notes and keep unreviewed captions out of verifikat

Two adversarial-review findings on the WhatsApp surfacing flows, both about
text that lands on an immutable verifikat.

1. A cleared note was silently re-applied. BookDirectlyDialog prefills the
   rendered chat context, and the dialog sent `notes.trim() || undefined`
   while book-direct and convert defaulted from channel_context on any falsy
   value. A user who read the prefill, disagreed and deleted it therefore got
   it written back onto a posted entry, removable only through a formal
   rättelse. Both code comments claimed "an edited value always wins", which
   was false for exactly that edit. Now PRESENCE of the field decides: the
   dialog always submits `notes` (empty string included) and the routes only
   default when the field is absent from the request (MCP, older clients).
   The Zod `.optional()` carrying that distinction is documented at the
   schema so it is not "tidied" into a `.default('')` later.

2. The photo caption was auto-burned into verifikat text with no review.
   renderChannelContextNotes fell back to the raw caption, and bulk-book
   appended the result per item with no per-item notes field at all (the MCP
   approval preview deliberately shows no per-item PII either), so unreviewed
   chat text reached a WORM record nobody had seen. The renderer now takes
   { includeCaption } and leaves the caption out by DEFAULT: representation
   answers and user_note are replies to a question the bot asked, the caption
   is not. Only the Bokför direkt prefill opts in, where the user reads the
   string in an editable field before booking.

Tests: cleared-notes and whitespace-cleared on book-direct, cleared-notes on
convert, caption-never-defaulted on both routes, caption-not-threaded in
bulk-book, and the renderer's opt-in. The book-direct cleared-notes tests
were mutation-checked (restoring the truthiness fallback fails them).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reports): export the chat answers behind a verifikat in the full archive

The verifikat line caps the representation trail at 220 chars and drops whole
participant names ("… och N till"); the complete list (deltagare, syfte,
raw_answer) exists only in invoice_inbox_items.channel_context. That table was
in ARCHIVE_EXCLUDED_TABLES with a rationale predating channel_context ("inbox
workflow state"), so a company leaving Accounted and keeping the full-archive
export as its BFL 7-year record kept an incomplete deltagare documentation for
its representation deductions.

Dumped as a column PROJECTION, not the whole row: the new
MasterDataTableSpec.columns narrows the select to the underlag provenance
(document, matched transaction, created verifikat / leverantörsfaktura) plus
channel_context, so the answers are tied to what was booked from them while
the inbox workflow state (email bodies, OCR output, error messages) stays out
of the archive. The documents themselves remain in dokument/.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <jakob.wennberg@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-05 14:54:30 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 398c734b93
commit d1c411ad6f
15 changed files with 1124 additions and 20 deletions
@@ -32,13 +32,18 @@ import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
import { resolveAccount } from '@/lib/cash-accounts/resolve-account'
import type { BASAccount, BookingTemplateLibrary, CashAccount, FiscalPeriod, InvoiceExtractionResult } from '@/types'
import { renderChannelContextNotes } from '@/lib/documents/channel-context-notes'
import type { BASAccount, BookingTemplateLibrary, CashAccount, FiscalPeriod, InboxChannelContext, InvoiceExtractionResult } from '@/types'
interface InboxItem {
id: string
document_id: string | null
matched_transaction_id: string | null
extracted_data: InvoiceExtractionResult | null
// Verified human answers from the delivering chat (WhatsApp items):
// prefills the notes field so representation deltagare + syfte reach the
// verifikat. Absent for email/upload items.
channel_context?: InboxChannelContext | null
}
interface PickerTransaction {
@@ -225,7 +230,16 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, docUrl =
const supplier = item.extracted_data?.supplier?.name?.trim() || ''
const invoiceNum = item.extracted_data?.invoice?.invoiceNumber?.trim() || ''
setDescription([supplier, invoiceNum].filter(Boolean).join(' · ') || 'Bokföring från inkorg')
setNotes('')
// WhatsApp items: prefill with the rendered chat context (representation
// deltagare + syfte, sender note) so it lands on the verifikat unless the
// user edits it away. This is the one place the photo caption is included:
// the user reads it here and can change or delete it before booking, which
// no other path offers (see channel-context-notes.ts).
//
// The dialog always submits the field, empty string included, so clearing
// the prefill really clears it: the server only defaults when the field is
// absent from the request.
setNotes(renderChannelContextNotes(item.channel_context, { includeCaption: true }) ?? '')
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, item.id])
@@ -506,7 +520,11 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, docUrl =
fiscal_period_id: periodId,
entry_date: entryDate,
description: description.trim(),
notes: notes.trim() || undefined,
// Always send the field, '' included: the server treats an absent
// `notes` as "default it from the chat context" and a present one as
// the user's own value. Sending undefined for a cleared prefill would
// resurrect the text the user just deleted onto an immutable verifikat.
notes: notes.trim(),
lines: lines.map((l) => ({
account_number: l.account_number.trim(),
debit_amount: parseFloat(l.debit_amount) || 0,
@@ -35,6 +35,7 @@ import {
X,
ChevronDown,
Sparkles,
MessageCircle,
} from 'lucide-react'
import Link from 'next/link'
import { cn, formatCurrency } from '@/lib/utils'
@@ -44,7 +45,8 @@ import { copyInboxAddress, type AddressCopyState } from '@/components/extensions
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
import type { InvoiceExtractionResult } from '@/types'
import type { InboxChannelContext, InvoiceExtractionResult } from '@/types'
import { renderChannelParticipant } from '@/lib/documents/channel-context-notes'
import BookDirectlyDialog from '@/components/extensions/general/BookDirectlyDialog'
import NewSupplierInvoiceDialog from '@/components/supplier-invoices/NewSupplierInvoiceDialog'
import BulkBookInboxDialog from '@/components/extensions/general/BulkBookInboxDialog'
@@ -61,7 +63,7 @@ type AccountingMethod = 'accrual' | 'cash'
interface InboxItem {
id: string
status: 'received' | 'error'
source: 'email' | 'upload'
source: 'email' | 'upload' | 'whatsapp'
created_at: string
email_from: string | null
email_subject: string | null
@@ -84,6 +86,10 @@ interface InboxItem {
// Distinct from status='error' (extraction failed) and from extracted_data
// having empty fields (extraction ran but found nothing).
extraction_skipped: boolean
// Verified human answers from the delivering chat (source='whatsapp'):
// photo caption, representation deltagare + syfte, sender note, and the
// open-question state. Null/absent for email and upload items.
channel_context?: InboxChannelContext | null
// Set client-side only while a manual upload is in flight. Replaced by a
// real server-side row once the AI extraction completes.
isPlaceholder?: boolean
@@ -1349,6 +1355,7 @@ function InboxRow({
checkbox visible (otherwise it's hover-only on desktop). */
anyChecked: boolean
}) {
const t = useTranslations('inbox_workspace')
const amount = pickAmount(item)
const supplierName = pickSupplierName(item)
const isPlaceholder = !!item.isPlaceholder
@@ -1356,6 +1363,11 @@ function InboxRow({
const isErrored = status === 'error'
const isBooked = status === 'booked'
const isLinkedToTransaction = status === 'linked'
// A chat question the sender never answered (48h TTL hit): the missing
// info should be completed here instead. Quiet hint, not a status: the
// item still books normally. Booked items drop the reminder.
const hasUnansweredQuestion =
!isBooked && item.channel_context?.pending_question?.status === 'moved_to_app'
return (
<li
@@ -1396,6 +1408,8 @@ function InboxRow({
<Loader2 className="h-3 w-3 text-muted-foreground shrink-0 animate-spin" />
) : 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" />
) : (
<Upload className="h-3 w-3 text-muted-foreground shrink-0" />
)}
@@ -1417,9 +1431,16 @@ function InboxRow({
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
{isPlaceholder ? (
<span className="italic">Tolkar dokument med AI…</span>
) : item.extraction_skipped ? (
) : item.extraction_skipped || hasUnansweredQuestion ? (
<span className="flex items-center gap-1.5 min-w-0">
<Badge variant="outline" className="font-normal">Inte AI-tolkad</Badge>
{item.extraction_skipped && (
<Badge variant="outline" className="font-normal">Inte AI-tolkad</Badge>
)}
{hasUnansweredQuestion && (
<Badge variant="outline" className="font-normal text-attn border-attn/40">
{t('wa_question_badge')}
</Badge>
)}
<span className="truncate">{timeAgo(item.email_received_at ?? item.created_at)}</span>
</span>
) : (
@@ -1780,6 +1801,24 @@ function FieldsRail({
const [isRetrying, setIsRetrying] = useState(false)
const t = useTranslations('inbox_workspace')
// WhatsApp chat context: verified human answers captured by the intake bot
// (photo caption, representation deltagare + syfte, sender note). Rendered
// as read-only provenance above the editable fields, mirroring the email
// metadata block. `moved_to_app` means the bot asked a question in the chat
// that was never answered (48h TTL): the missing info should be completed
// here before booking.
const waCtx = item.source === 'whatsapp' ? item.channel_context ?? null : null
const waParticipants = (waCtx?.representation?.participants ?? [])
.map(renderChannelParticipant)
.filter((n) => n.length > 0)
const waPurpose = waCtx?.representation?.purpose?.trim() || null
const waCaption = waCtx?.caption?.trim() || null
const waNote = waCtx?.user_note?.trim() || null
const waUnanswered =
!isResolved && waCtx?.pending_question?.status === 'moved_to_app'
const showWaBlock =
waParticipants.length > 0 || !!waPurpose || !!waCaption || !!waNote || waUnanswered
// Surface a quiet hint when extraction caught a supplier name but no existing
// supplier matched. The actual creation flow lives on the leverantörsfaktura
// form (Skapa & välj), so we don't render a separate button here.
@@ -1841,6 +1880,42 @@ function FieldsRail({
</div>
)}
{/* WhatsApp chat context (see waCtx derivation above). */}
{showWaBlock && (
<div className="border-b px-4 py-3 text-xs space-y-1">
<h3 className="text-xs uppercase tracking-wide text-muted-foreground font-medium mb-2">
{t('wa_block_title')}
</h3>
{waCaption && (
<div className="flex gap-2">
<span className="text-muted-foreground w-20 shrink-0">{t('wa_caption_label')}</span>
<span className="break-words min-w-0">{waCaption}</span>
</div>
)}
{waParticipants.length > 0 && (
<div className="flex gap-2">
<span className="text-muted-foreground w-20 shrink-0">{t('wa_participants_label')}</span>
<span className="break-words min-w-0">{waParticipants.join(', ')}</span>
</div>
)}
{waPurpose && (
<div className="flex gap-2">
<span className="text-muted-foreground w-20 shrink-0">{t('wa_purpose_label')}</span>
<span className="break-words min-w-0">{waPurpose}</span>
</div>
)}
{waNote && (
<div className="flex gap-2">
<span className="text-muted-foreground w-20 shrink-0">{t('wa_note_label')}</span>
<span className="break-words min-w-0">{waNote}</span>
</div>
)}
{waUnanswered && (
<AttnLine className="pt-1">{t('wa_question_unanswered')}</AttnLine>
)}
</div>
)}
{/* AI classification: what kind of document this is and how it was
paid. Read-only context above the editable fields; absent for
extractions from before the fields existed. */}