Files
accounted/lib/documents/channel-context-notes.ts
T
Jakob Wennberg d1c411ad6f 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>
2026-08-05 14:54:30 +02:00

120 lines
4.7 KiB
TypeScript

/**
* Render the verified human answers captured on a chat-sourced inbox item
* (invoice_inbox_items.channel_context, written by the WhatsApp intake bot)
* as ONE compact Swedish line for the booking notes path.
*
* The rendered string travels through the existing `notes` parameters
* (book-direct, convert, bulk-book via categorize-core) and ends up appended
* to the verifikat description, which caps at 500 chars in
* lib/bookkeeping/transaction-entries.ts. This renderer therefore stays well
* under that: at most CHANNEL_CONTEXT_NOTES_MAX chars, truncating the
* participant list by WHOLE names ("… och 3 till"), never mid-name.
*
* Precedence: representation answers first (Skatteverket's dokumentationskrav
* for representation: deltagare + syfte belong on the verifikat), then the
* sender's explicit note. Both are answers a human typed to a question the bot
* asked, having been told they reach the bookkeeping. The photo caption is the
* weakest signal: nobody was asked for it and nobody reviewed it, so it is
* OFF by default and only renders where a human sees the result before it is
* posted (see ChannelContextNotesOptions.includeCaption).
*
* Core lib: must not import from @/extensions. Deliberately Swedish-only
* output: the verifikat description is a regulatory surface (see
* .claude/rules/i18n.md), not UI chrome.
*/
import type { InboxChannelContext } from '@/types'
/**
* Cap on the rendered line. 220 leaves the description's 500-char cap plenty
* of room for the bank text / supplier prefix it is appended to.
*/
export const CHANNEL_CONTEXT_NOTES_MAX = 220
/** "Anna Berg (Volvo)" with a company, bare "Jakob W" without (the sender
* themselves usually answers without naming their own company). */
export function renderChannelParticipant(p: {
name: string
company: string | null
}): string {
const name = (p.name ?? '').trim()
if (!name) return ''
const company = (p.company ?? '').trim()
return company ? `${name} (${company})` : name
}
function buildLine(
names: string[],
droppedCount: number,
purpose: string | null,
userNote: string | null,
): string {
const parts: string[] = []
if (names.length > 0) {
const suffix = droppedCount > 0 ? ` … och ${droppedCount} till` : ''
parts.push(`Representation: ${names.join(', ')}${suffix}`)
}
if (purpose) parts.push(`Syfte: ${purpose}`)
if (userNote) parts.push(userNote)
return parts.join(' · ')
}
/** Last-resort cap for free text (purpose/note/caption): the whole-name rule
* above governs the participant list; a runaway free-text field is cut with
* an ellipsis instead. Result is always <= CHANNEL_CONTEXT_NOTES_MAX. */
function capFreeText(line: string): string {
if (line.length <= CHANNEL_CONTEXT_NOTES_MAX) return line
return `${line.slice(0, CHANNEL_CONTEXT_NOTES_MAX - 1).trimEnd()}…`
}
export interface ChannelContextNotesOptions {
/**
* Render the raw photo caption when there is neither a representation
* answer nor a sender note. Default false.
*
* Off by default on purpose. The representation answer and the note are
* replies to a question the bot asked, so the sender knew they were writing
* bookkeeping text; the caption is whatever happened to be typed next to a
* photo and nobody reviewed it. Every unattended path (bulk-book, the
* server-side note defaults used by MCP and API callers) writes straight
* into a posted verifikat, which BFL 5 kap 5 § only lets you change through
* a formal rättelse. Pass true only where a human sees the string and can
* edit or delete it before booking: today that is the Bokför direkt dialog
* prefill.
*/
includeCaption?: boolean
}
export function renderChannelContextNotes(
ctx: InboxChannelContext | null | undefined,
options: ChannelContextNotesOptions = {},
): string | null {
if (!ctx) return null
const names = (ctx.representation?.participants ?? [])
.map(renderChannelParticipant)
.filter((n) => n.length > 0)
const purpose = ctx.representation?.purpose?.trim() || null
const userNote = ctx.user_note?.trim() || null
const caption = options.includeCaption ? ctx.caption?.trim() || null : null
// Caption (when allowed) only if there is neither a representation answer
// nor a note.
if (names.length === 0 && !purpose && !userNote) {
return caption ? capFreeText(caption) : null
}
// Full participant list first; drop whole names from the end until the
// line fits. Keeps at least one name so the representation trail never
// degrades to a bare count.
let keep = names.length
for (;;) {
const line = buildLine(names.slice(0, keep), names.length - keep, purpose, userNote)
if (line.length <= CHANNEL_CONTEXT_NOTES_MAX) return line
if (keep > 1) {
keep--
continue
}
return capFreeText(line)
}
}