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
@@ -217,6 +217,209 @@ describe('POST /items/:id/book-direct', () => {
expect(createJournalEntryMock).not.toHaveBeenCalled()
})
// ── WhatsApp channel-context notes default ──────────────────
// The chat answers (representation deltagare + syfte, sender note) reach
// the verifikat even through callers that never saw the chat: absent/empty
// request notes default server-side to the rendered channel_context.
const WA_CONTEXT = {
channel: 'whatsapp' as const,
caption: 'Kvitto lunch',
representation: {
participants: [
{ name: 'Anna Berg', company: 'Volvo' },
{ name: 'Jakob W', company: null },
],
purpose: 'uppföljning av avtal',
event_date: null,
raw_answer: 'Anna Berg Volvo och jag, uppföljning av avtal',
answered_at: '2026-08-01T12:00:00Z',
},
}
it('defaults notes to the rendered channel context when the request sends none', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
document_id: 'doc-1',
source: 'whatsapp',
channel_context: WA_CONTEXT,
}),
})
enqueue({ data: null }) // inbox item update
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: VALID_BODY, // no notes field
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(createJournalEntryMock).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({
notes: 'Representation: Anna Berg (Volvo), Jakob W · Syfte: uppföljning av avtal',
}),
)
})
it('lets caller-supplied notes win over the channel context', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
document_id: 'doc-1',
source: 'whatsapp',
channel_context: WA_CONTEXT,
}),
})
enqueue({ data: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: { ...VALID_BODY, notes: 'Min egen anteckning' },
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(createJournalEntryMock).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({ notes: 'Min egen anteckning' }),
)
})
// Regression (adversarial review): the dialog prefills the chat note, so a
// user who reads it, disagrees and DELETES it submits notes:''. Falling back
// to the rendered context on any falsy value re-attached the deleted text to
// a posted verifikat, where only a formal rättelse can remove it. Presence
// of the field, not its truthiness, decides.
it('honors an explicitly cleared notes field instead of resurrecting the chat context', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
document_id: 'doc-1',
source: 'whatsapp',
channel_context: WA_CONTEXT,
}),
})
enqueue({ data: null }) // inbox item update
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: { ...VALID_BODY, notes: '' },
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(createJournalEntryMock).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({ notes: undefined }),
)
const [, , , input] = createJournalEntryMock.mock.calls[0] as [unknown, string, string, { notes?: string }]
expect(input.notes ?? '').not.toContain('Representation')
})
// Whitespace is a cleared field too, not "no opinion".
it('treats a whitespace-only notes value as cleared', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
document_id: 'doc-1',
source: 'whatsapp',
channel_context: WA_CONTEXT,
}),
})
enqueue({ data: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: { ...VALID_BODY, notes: ' ' },
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(createJournalEntryMock).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({ notes: undefined }),
)
})
// The photo caption is unreviewed chat text: this default runs for callers
// that never saw it (MCP, API), so it must not reach the verifikat.
it('never defaults an unreviewed caption onto the verifikat', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
document_id: 'doc-1',
source: 'whatsapp',
channel_context: {
channel: 'whatsapp',
caption: 'kvittot från igår, Annas sjukbesök, hon betalade',
},
}),
})
enqueue({ data: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: VALID_BODY, // no notes field: the server default applies
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(createJournalEntryMock).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({ notes: undefined }),
)
})
it('leaves notes undefined when the item has no channel context', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: makeInvoiceInboxItem({ document_id: 'doc-1' }) })
enqueue({ data: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/book-direct', {
method: 'POST',
body: VALID_BODY,
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
expect(createJournalEntryMock).toHaveBeenCalledWith(
expect.anything(),
'company-1',
'user-1',
expect.objectContaining({ notes: undefined }),
)
})
it('books with transaction link: source_type=bank_transaction, source_id=transaction.id', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: makeInvoiceInboxItem({ document_id: 'doc-1' }) })
@@ -216,6 +216,131 @@ describe('POST /items/:id/convert', () => {
expect(body.data.inbox_item_id).toBe('item-1')
})
it('defaults the supplier invoice notes to the rendered WhatsApp channel context', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
status: 'received',
document_id: 'doc-1',
source: 'whatsapp',
channel_context: { channel: 'whatsapp', user_note: 'Serverlicens för Q3' },
}),
})
enqueue({ data: makeSupplier({ id: 'supplier-1' }) })
enqueue({ data: 42 })
enqueue({ data: { id: 'invoice-1', status: 'registered' } })
enqueue({ data: null, error: null })
enqueue({ data: makeCompanySettings({ accounting_method: 'cash' }) })
enqueue({ data: null, error: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/convert', {
method: 'POST',
body: VALID_CONVERT_BODY, // no notes field
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
const insertArgs = findCall('supplier_invoices', 'insert')
expect(insertArgs?.[0]).toMatchObject({ notes: 'Serverlicens för Q3' })
})
// Same rule as book-direct: an explicit '' is the caller clearing the field,
// not "no opinion", so the chat context must not be written back in.
it('honors an explicitly cleared notes field on convert', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
status: 'received',
source: 'whatsapp',
channel_context: { channel: 'whatsapp', user_note: 'Från chatten' },
}),
})
enqueue({ data: makeSupplier({ id: 'supplier-1' }) })
enqueue({ data: 42 })
enqueue({ data: { id: 'invoice-1', status: 'registered' } })
enqueue({ data: null, error: null })
enqueue({ data: makeCompanySettings({ accounting_method: 'cash' }) })
enqueue({ data: null, error: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/convert', {
method: 'POST',
body: { ...VALID_CONVERT_BODY, notes: '' },
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
const insertArgs = findCall('supplier_invoices', 'insert')
expect(insertArgs?.[0]).toMatchObject({ notes: null })
})
// The convert form never shows the chat context, so an unreviewed photo
// caption must not ride along onto the leverantörsfaktura either.
it('never defaults an unreviewed caption onto the supplier invoice', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
status: 'received',
source: 'whatsapp',
channel_context: { channel: 'whatsapp', caption: 'lunch med Anna, hon bjöd tillbaka' },
}),
})
enqueue({ data: makeSupplier({ id: 'supplier-1' }) })
enqueue({ data: 42 })
enqueue({ data: { id: 'invoice-1', status: 'registered' } })
enqueue({ data: null, error: null })
enqueue({ data: makeCompanySettings({ accounting_method: 'cash' }) })
enqueue({ data: null, error: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/convert', {
method: 'POST',
body: VALID_CONVERT_BODY, // no notes field
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
const insertArgs = findCall('supplier_invoices', 'insert')
expect(insertArgs?.[0]).toMatchObject({ notes: null })
})
it('keeps caller-supplied notes over the channel context on convert', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({
data: makeInvoiceInboxItem({
status: 'received',
source: 'whatsapp',
channel_context: { channel: 'whatsapp', user_note: 'Från chatten' },
}),
})
enqueue({ data: makeSupplier({ id: 'supplier-1' }) })
enqueue({ data: 42 })
enqueue({ data: { id: 'invoice-1', status: 'registered' } })
enqueue({ data: null, error: null })
enqueue({ data: makeCompanySettings({ accounting_method: 'cash' }) })
enqueue({ data: null, error: null })
const ctx = buildCtx(supabase)
const request = createMockRequest('/items/item-1/convert', {
method: 'POST',
body: { ...VALID_CONVERT_BODY, notes: 'Egen anteckning' },
searchParams: { _id: 'item-1' },
})
const res = await route.handler(request, ctx)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
const insertArgs = findCall('supplier_invoices', 'insert')
expect(insertArgs?.[0]).toMatchObject({ notes: 'Egen anteckning' })
})
it('emits supplier_invoice.registered and supplier_invoice.confirmed events', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: makeInvoiceInboxItem({ status: 'received' }) })
+37 -5
View File
@@ -50,6 +50,7 @@ import {
} from '@/lib/currency/supplier-invoice-rate'
import { roundOre } from '@/lib/money'
import { linkToJournalEntry } from '@/lib/core/documents/document-service'
import { renderChannelContextNotes } from '@/lib/documents/channel-context-notes'
import { CreateSupplierInvoiceSchema, BookInboxItemDirectlySchema, BulkBookInboxSchema } from '@/lib/api/schemas'
import { bulkBookMatchedInboxItems } from '@/lib/transactions/categorize-core'
import { hasCapability, capabilityBlockedResponse } from '@/lib/entitlements/has-capability'
@@ -57,7 +58,7 @@ import { CAPABILITY } from '@/lib/entitlements/keys'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { checkInboxUploadRateLimit } from '@/lib/rate-limits/inbox'
import { simpleParser } from 'mailparser'
import type { InvoiceExtractionResult, InvoiceInboxItem, SupplierInvoice, SupplierInvoiceItem } from '@/types'
import type { InboxChannelContext, InvoiceExtractionResult, InvoiceInboxItem, SupplierInvoice, SupplierInvoiceItem } from '@/types'
const MAX_ATTACHMENTS_PER_EMAIL = 20
@@ -275,7 +276,7 @@ export const invoiceInboxExtension: Extension = {
email_received_at, email_body_text, error_message,
created_supplier_invoice_id,
matched_transaction_id, created_journal_entry_id,
resend_email_id, extraction_skipped
resend_email_id, extraction_skipped, channel_context
`)
.eq('company_id', ctx.companyId)
.order('created_at', { ascending: false })
@@ -1772,7 +1773,20 @@ export const invoiceInboxExtension: Extension = {
total_sek: totalSek,
remaining_amount: total,
document_id: item.document_id || null,
notes: body.notes || null,
// WhatsApp-sourced items: when the request carries NO notes field
// at all, default to the rendered chat context (representation
// deltagare + syfte, sender note) so the human answers from the
// chat reach the leverantörsfaktura. Presence decides, not
// truthiness: `notes: ""` is an explicit clear and stays empty
// (same rule as book-direct, where the value lands on an
// immutable verifikat). The caption is excluded: this form never
// shows the chat context, so nobody reviewed it.
notes:
body.notes === undefined
? renderChannelContextNotes(
(item as { channel_context?: InboxChannelContext | null }).channel_context,
)
: body.notes.trim() || null,
})
.select()
.single()
@@ -2022,7 +2036,7 @@ export const invoiceInboxExtension: Extension = {
const { data: item, error: fetchError } = await ctx.supabase
.from('invoice_inbox_items')
.select('id, document_id, status, created_supplier_invoice_id, created_journal_entry_id, matched_transaction_id, correlation_id')
.select('id, document_id, status, created_supplier_invoice_id, created_journal_entry_id, matched_transaction_id, correlation_id, channel_context')
.eq('id', id)
.eq('company_id', ctx.companyId)
.maybeSingle()
@@ -2074,6 +2088,24 @@ export const invoiceInboxExtension: Extension = {
transaction = tx
}
// WhatsApp-sourced items: when the request carries NO notes field at
// all, default to the rendered chat context (representation deltagare
// + syfte, sender note) so the audit text reaches the verifikat even
// through clients that never saw the chat (MCP, older UI).
//
// Presence decides, not truthiness: `notes: ""` is the UI saying the
// user emptied the field, and resurrecting the prefill there would
// write text onto an immutable verifikat against an explicit user
// action (removable only via rättelse). So an empty string clears,
// and only an absent field defaults. The caption is excluded: this
// path can run without a human ever seeing the string.
const effectiveNotes =
body.notes === undefined
? renderChannelContextNotes(
(item as { channel_context?: InboxChannelContext | null }).channel_context,
) ?? undefined
: body.notes.trim() || undefined
// Create the journal entry via the engine. Source-tracks back to
// the inbox item so the audit trail is preserved even when no
// transaction is involved.
@@ -2085,7 +2117,7 @@ export const invoiceInboxExtension: Extension = {
description: body.description,
source_type: transaction ? 'bank_transaction' : 'inbox_item',
source_id: transaction ? transaction.id : item.id,
notes: body.notes,
notes: effectiveNotes,
lines: body.lines,
})
} catch (err) {