Files
accounted/lib/tax/expense-warnings.ts
T
Jakob Wennberg 629069e281 feat(whatsapp-inbox): conversation layer with clarifying questions (#1340)
PR4 of the WhatsApp intake track: turns the per-message PR3 pipeline into a
conversation. Media replies are burst-debounced into ONE combined ack (M4
single / M5 numbered list) sent by the single winner of the atomic
pending_ack claim; losers stay silent. Multi-company senders get the company
question (reply buttons <=3, list 4-10, numbered text >10) with an 8h
sliding pin ('byt' clears it); their receipts park as staged message rows
until the answer and then run through the normal intake path.

Clarifying questions are evaluated per receipt after extraction, max one per
receipt, priority unreadable > representation > partial, keyed on the
Phase-0 classification (legibility/documentKind/merchantCategory) with
heuristic fallbacks (compressed-chat-photo signal, extended meal regex).
Budgets: <=2 content questions per burst, <=6 per sender per Stockholm day;
over budget acks only and flags the item moved_to_app. Questions expire
after 48h (sweep, silent hand-off) and are asked exactly once.

Free-text answers route through the ONE new LLM call
(lib/interpret-answer.ts): Sonnet via Bedrock, max_tokens 600, no thinking,
forced tool call validated by Zod with hard caps, gated by
checkAgentRateLimit, reply framed as untrusted data. Any failure degrades to
storing the raw text as a note; exact 'nej' short-circuits without the LLM.
Answers land in invoice_inbox_items.channel_context
(representation/user_note/quality) with ChannelQuestionAsked/Answered
processing-history events. Late answers match by quoted wamid or the most
recent open question within 7 days.

New per-minute sweep cron (registry-gated physical route, 503
EXTENSION_DISABLED when off) re-claims stuck rows (max 3 attempts), rescues
crashed burst acks, expires questions and pins. One new migration
(20260802210000) adds whatsapp_messages.acked_at, the relational burst-
membership marker, with pg-real coverage for the single-winner claim.

Verified: full vitest suite (12270), pg-real against a migrated
supabase/postgres 15 (977), lint 0 errors, tsc at the 405 baseline,
check:guards green, crontabs regenerated. Mutation-checked the debounce
claim and the daily budget gate.

Co-authored-by: Jakob Wennberg <jakob.wennberg@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:27:00 +02:00

169 lines
5.4 KiB
TypeScript

/**
* Expense warnings for non-deductible or partially deductible items
* Based on Swedish tax law and Kammarrätten rulings
*/
export interface ExpenseWarning {
category: string
warningLevel: 'info' | 'warning' | 'danger'
message: string
legalBasis?: string
}
/**
* Meal/representation keyword pattern. Exported so channel intake (the
* WhatsApp representation-question trigger) reuses the exact same base
* heuristic instead of drifting its own copy.
*/
export const MEAL_PATTERN = /restaurang|lunch|middag|dinner|café|fika/i
const warningPatterns: {
pattern: RegExp
warning: ExpenseWarning
}[] = [
{
pattern: /kläder|clothes|mode|fashion|outfit/i,
warning: {
category: 'Kläder',
warningLevel: 'danger',
message: 'Kläder är normalt inte avdragsgilla, även om de används i arbetet',
legalBasis: 'RÅ 1988 ref. 35',
},
},
{
pattern: /kosmetika|smink|makeup|hudvård|skincare|beauty/i,
warning: {
category: 'Kosmetika',
warningLevel: 'warning',
message: 'Kosmetika är normalt inte avdragsgillt. Undantag kan gälla för professionella artister.',
legalBasis: 'Skatteverkets ställningstagande',
},
},
{
pattern: /gym|träning|fitness|sport/i,
warning: {
category: 'Träning',
warningLevel: 'danger',
message: 'Gymkort och träningsavgifter är inte avdragsgilla som personlig kostnad',
legalBasis: 'IL 9 kap 2§',
},
},
{
pattern: /frisör|hår|salon|barber/i,
warning: {
category: 'Frisör',
warningLevel: 'warning',
message: 'Frisörbesök är normalt privata kostnader och inte avdragsgilla',
},
},
{
pattern: MEAL_PATTERN,
warning: {
category: 'Representation',
warningLevel: 'warning',
message: 'Måltider kan vara avdragsgilla som representation. Inkomstskatteavdraget togs bort 2017, men momsen är avdragsgill på upp till 300 kr/person (exkl. moms) enligt ML 13 kap 24-25 §§.',
legalBasis: 'IL 16 kap 2 §, ML 13 kap 24-25 §§',
},
},
{
pattern: /resa|flyg|flight|tåg|train|hotel|hotell/i,
warning: {
category: 'Resor',
warningLevel: 'info',
message: 'Resor kan vara avdragsgilla om de är nödvändiga för verksamheten. Dokumentera syftet!',
},
},
{
pattern: /presenter|gift|gåva/i,
warning: {
category: 'Gåvor',
warningLevel: 'warning',
message: 'Reklamgåvor är avdragsgilla upp till 300 kr per mottagare. Representationsgåvor max 180 kr.',
legalBasis: 'IL 16 kap 2§',
},
},
{
pattern: /mobil|telefon|phone|iphone|samsung/i,
warning: {
category: 'Telefon',
warningLevel: 'info',
message: 'Arbetstelefon är avdragsgillt. Vid blandad användning, endast den yrkesmässiga delen.',
},
},
{
pattern: /dator|laptop|computer|mac|ipad/i,
warning: {
category: 'Dator',
warningLevel: 'info',
message: 'Datorer för yrkesmässig användning är avdragsgilla. Vid blandad användning ska fördelning göras.',
},
},
]
/**
* Check if an expense description triggers any warnings
*/
export function checkExpenseWarnings(description: string): ExpenseWarning[] {
const warnings: ExpenseWarning[] = []
for (const { pattern, warning } of warningPatterns) {
if (pattern.test(description)) {
warnings.push(warning)
}
}
return warnings
}
/**
* Get category suggestions based on description
*/
export function suggestCategory(description: string): string | null {
const categoryPatterns: { pattern: RegExp; category: string }[] = [
{ pattern: /spotify|netflix|adobe|software|app store/i, category: 'expense_software' },
{ pattern: /kamera|camera|ljud|mikrofon|ring light|studio/i, category: 'expense_equipment' },
{ pattern: /flyg|tåg|hotel|taxi|uber/i, category: 'expense_travel' },
{ pattern: /facebook ads|google ads|instagram|marknadsföring|marketing/i, category: 'expense_marketing' },
{ pattern: /revisor|advokat|konsult|accountant|lawyer/i, category: 'expense_professional_services' },
{ pattern: /kurs|utbildning|course|workshop/i, category: 'expense_education' },
{ pattern: /kontor|office|skriv|hyra/i, category: 'expense_office' },
{ pattern: /bankavgift|bankfee|monthly fee|kontoavgift|serviceavgift/i, category: 'expense_bank_fees' },
{ pattern: /kortavgift|card fee|annual fee/i, category: 'expense_card_fees' },
{ pattern: /valutaväxling|currency|exchange|FX fee/i, category: 'expense_currency_exchange' },
]
for (const { pattern, category } of categoryPatterns) {
if (pattern.test(description)) {
return category
}
}
return null
}
/**
* Get display name for category
*/
export function getCategoryDisplayName(category: string): string {
const names: Record<string, string> = {
income_services: 'Tjänster',
income_products: 'Produkter',
income_other: 'Övriga intäkter',
expense_equipment: 'Utrustning',
expense_software: 'Programvara',
expense_travel: 'Resor',
expense_office: 'Kontor',
expense_marketing: 'Marknadsföring',
expense_professional_services: 'Konsulter',
expense_education: 'Utbildning',
expense_bank_fees: 'Bankavgift',
expense_card_fees: 'Kortavgift',
expense_currency_exchange: 'Valutaväxling',
expense_other: 'Övriga kostnader',
private: 'Privat',
uncategorized: 'Ej bokförd',
}
return names[category] || category
}