docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
-85
View File
@@ -1,85 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
vi.mock('../categories', () => ({
countUnbookedTransactions: vi.fn().mockResolvedValue(4),
countUnbookedSkattekontoRows: vi.fn().mockResolvedValue(7),
countInboxDocuments: vi.fn().mockResolvedValue(6),
countSuggestedMatches: vi.fn().mockResolvedValue(2),
countSupplierInvoicesAwaitingApproval: vi.fn().mockResolvedValue(1),
countVerifikatMissingDocument: vi.fn().mockResolvedValue(3),
countOverdueInvoices: vi.fn().mockResolvedValue(5),
countDeadlinesNeedingAction: vi.fn().mockResolvedValue(1),
countPendingOperations: vi.fn().mockResolvedValue(2),
countReconciliationDue: vi.fn().mockResolvedValue(1),
countExpensePayoutsDue: vi.fn().mockResolvedValue(2),
countSkattekontoPaymentDue: vi.fn().mockResolvedValue(1),
}))
import { getWorklistCounts } from '../aggregate'
const supabase = {} as SupabaseClient
beforeEach(() => {
vi.clearAllMocks()
})
describe('getWorklistCounts', () => {
it('aggregates every category', async () => {
const { counts } = await getWorklistCounts(supabase, 'company-1')
expect(counts).toEqual({
book_transaction: 4,
book_skattekonto: 7,
inbox_document: 6,
suggested_match: 2,
supplier_invoice_approval: 1,
verifikat_missing_document: 3,
overdue_invoice: 5,
deadline_action: 1,
pending_operations: 2,
reconciliation_due: 1,
expense_payout: 2,
skattekonto_payment_due: 1,
})
})
it('takes the suggested-match count from a caller-supplied list instead of rescanning', async () => {
const { countSuggestedMatches } = await import('../categories')
const matches = [{ transactionId: 't1' }, { transactionId: 't2' }, { transactionId: 't3' }] as never[]
const { counts } = await getWorklistCounts(supabase, 'company-1', {
suggestedMatches: Promise.resolve(matches),
})
expect(counts.suggested_match).toBe(3)
expect(countSuggestedMatches).not.toHaveBeenCalled()
})
it('takes the expense-payout count from a caller-supplied list instead of rescanning', async () => {
const { countExpensePayoutsDue } = await import('../categories')
const people = [{ key: 'owner:Anna' }, { key: 'emp-1' }, { key: 'emp-2' }] as never[]
const { counts } = await getWorklistCounts(supabase, 'company-1', {
expensePayoutsDue: Promise.resolve(people),
})
expect(counts.expense_payout).toBe(3)
expect(countExpensePayoutsDue).not.toHaveBeenCalled()
})
it('takes the skattekonto payment count from a caller-supplied value instead of rescanning', async () => {
const { countSkattekontoPaymentDue } = await import('../categories')
const due = { due: '2026-09-12', amount: 1000 } as never
const withDue = await getWorklistCounts(supabase, 'company-1', {
skattekontoPaymentDue: Promise.resolve(due),
})
expect(withDue.counts.skattekonto_payment_due).toBe(1)
// null is a value ("nothing to pay in"), not an absent option.
const without = await getWorklistCounts(supabase, 'company-1', { skattekontoPaymentDue: null })
expect(without.counts.skattekonto_payment_due).toBe(0)
expect(countSkattekontoPaymentDue).not.toHaveBeenCalled()
})
it('excludes suggested_match from the total (subset of book_transaction)', async () => {
const { total } = await getWorklistCounts(supabase, 'company-1')
// 4 + 7 + 6 + 1 + 3 + 5 + 1 + 2 + 1 + 2 (people owed for utlägg) + 1
// (skattekonto payment), without the 2 suggested matches.
expect(total).toBe(33)
})
})
File diff suppressed because it is too large Load Diff
-83
View File
@@ -1,83 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
mergeResumeItems,
isSalaryRunLate,
RESUME_MAX_ROWS,
type ResumeItem,
} from '../resume'
function item(overrides: Partial<ResumeItem>): ResumeItem {
return {
kind: 'journal_draft',
ref: `journal:${Math.abs(overrides.updated_at?.length ?? 1)}`,
href: '/bookkeeping/x',
context: null,
updated_at: '2026-07-01T10:00:00Z',
...overrides,
}
}
describe('mergeResumeItems', () => {
it('orders by updated_at desc', () => {
const merged = mergeResumeItems([
item({ ref: 'a', updated_at: '2026-07-01T10:00:00Z' }),
item({ ref: 'b', updated_at: '2026-07-03T10:00:00Z' }),
item({ ref: 'c', updated_at: '2026-07-02T10:00:00Z' }),
])
expect(merged.map((i) => i.ref)).toEqual(['b', 'c', 'a'])
})
it('boosts late items above newer non-late items', () => {
const merged = mergeResumeItems([
item({ ref: 'fresh', updated_at: '2026-07-20T10:00:00Z' }),
item({ ref: 'late-old', late: true, updated_at: '2026-05-01T10:00:00Z' }),
])
expect(merged[0].ref).toBe('late-old')
})
it('caps at RESUME_MAX_ROWS', () => {
const many = Array.from({ length: 7 }, (_, i) =>
item({ ref: `r${i}`, updated_at: `2026-07-0${i + 1}T10:00:00Z` }),
)
expect(mergeResumeItems(many)).toHaveLength(RESUME_MAX_ROWS)
})
it('keeps late-first ordering stable within groups', () => {
const merged = mergeResumeItems([
item({ ref: 'late-new', late: true, updated_at: '2026-07-10T10:00:00Z' }),
item({ ref: 'late-old', late: true, updated_at: '2026-06-10T10:00:00Z' }),
item({ ref: 'plain', updated_at: '2026-07-22T10:00:00Z' }),
])
expect(merged.map((i) => i.ref)).toEqual(['late-new', 'late-old', 'plain'])
})
it('does not mutate the input array', () => {
const input = [
item({ ref: 'a', updated_at: '2026-07-01T10:00:00Z' }),
item({ ref: 'b', updated_at: '2026-07-02T10:00:00Z' }),
]
const before = [...input]
mergeResumeItems(input)
expect(input).toEqual(before)
})
})
describe('isSalaryRunLate', () => {
const now = new Date('2026-07-23T12:00:00Z')
it('flags a run two months past its period', () => {
expect(isSalaryRunLate(2026, 5, now)).toBe(true)
})
it('does not flag last month', () => {
expect(isSalaryRunLate(2026, 6, now)).toBe(false)
})
it('does not flag the current period', () => {
expect(isSalaryRunLate(2026, 7, now)).toBe(false)
})
it('handles year boundaries', () => {
expect(isSalaryRunLate(2025, 12, now)).toBe(true)
})
})
@@ -1,27 +0,0 @@
import { describe, it, expect } from 'vitest'
import { visibleWorklistTotal, visibleWorklistTotalFrom } from '../visible-total'
import type { WorklistCounts } from '../types'
describe('visibleWorklistTotal', () => {
it('subtracts inbox documents for non-payers so the count matches the hidden row', () => {
expect(visibleWorklistTotal({ total: 5, inboxDocumentCount: 3, hasAi: false })).toBe(2)
})
it('keeps inbox documents for payers (the row is shown)', () => {
expect(visibleWorklistTotal({ total: 5, inboxDocumentCount: 3, hasAi: true })).toBe(5)
})
it('adds dashboard-only extras (expiring bank connections)', () => {
expect(visibleWorklistTotal({ total: 5, inboxDocumentCount: 3, hasAi: false, extra: 2 })).toBe(4)
})
it('clamps to 0 rather than rendering a negative count on a count skew', () => {
expect(visibleWorklistTotal({ total: 1, inboxDocumentCount: 3, hasAi: false })).toBe(0)
})
it('from() reads total + inbox_document off the worklist object', () => {
const worklist = { total: 4, counts: { inbox_document: 1 } } as unknown as WorklistCounts
expect(visibleWorklistTotalFrom(worklist, false, 1)).toBe(4) // 4 + 1 - 1
expect(visibleWorklistTotalFrom(worklist, true, 1)).toBe(5) // 4 + 1 - 0
})
})
-118
View File
@@ -1,118 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { ExpensePayoutDue, SkattekontoPaymentDue, SuggestedMatch } from './types'
import type { WorklistCounts } from './types'
import {
countDeadlinesNeedingAction,
countExpensePayoutsDue,
countInboxDocuments,
countOverdueInvoices,
countPendingOperations,
countReconciliationDue,
countSkattekontoPaymentDue,
countSuggestedMatches,
countSupplierInvoicesAwaitingApproval,
countUnbookedSkattekontoRows,
countUnbookedTransactions,
countVerifikatMissingDocument,
} from './categories'
/**
* All worklist counts in one round-trip burst. Each count is a bounded query
* (mostly head-only; suggested_match revalidates its candidates, see
* categories.ts) and individually soft-fails to 0, so this is safe to call
* from layouts and server components on every render.
*
* `total` is the number of distinct actionable items: suggested_match is a
* fast path over transactions already counted in book_transaction, so it is
* excluded to avoid double-counting (see lib/worklist/types.ts).
*/
export interface GetWorklistCountsOptions {
/**
* Suggested matches the caller is already fetching (Hem renders them in
* the Att göra pane): the count is taken from this list instead of a
* second scan of the same rows. A promise is accepted so it can run in
* parallel with the other counts.
*/
suggestedMatches?: SuggestedMatch[] | Promise<SuggestedMatch[]>
/**
* People owed for unpaid utlägg the caller is already fetching (Hem
* renders one row per person): the count is the list's length instead of
* a second scan of expense_claims.
*/
expensePayoutsDue?: ExpensePayoutDue[] | Promise<ExpensePayoutDue[]>
/**
* The next uncovered skattekonto charge the caller is already fetching
* (Hem renders it as one Betala row): the count is 1 or 0 from that value
* instead of a second scan. Pass null for "nothing to pay in".
*/
skattekontoPaymentDue?: SkattekontoPaymentDue | null | Promise<SkattekontoPaymentDue | null>
}
export async function getWorklistCounts(
supabase: SupabaseClient,
companyId: string,
options: GetWorklistCountsOptions = {},
): Promise<WorklistCounts> {
const [
bookTransaction,
bookSkattekonto,
inboxDocument,
suggestedMatch,
supplierInvoiceApproval,
verifikatMissingDocument,
overdueInvoice,
deadlineAction,
pendingOperations,
reconciliationDue,
expensePayout,
skattekontoPaymentDue,
] = await Promise.all([
countUnbookedTransactions(supabase, companyId),
countUnbookedSkattekontoRows(supabase, companyId),
countInboxDocuments(supabase, companyId),
options.suggestedMatches
? Promise.resolve(options.suggestedMatches).then((m) => m.length)
: countSuggestedMatches(supabase, companyId),
countSupplierInvoicesAwaitingApproval(supabase, companyId),
countVerifikatMissingDocument(supabase, companyId),
countOverdueInvoices(supabase, companyId),
countDeadlinesNeedingAction(supabase, companyId),
countPendingOperations(supabase, companyId),
countReconciliationDue(supabase, companyId),
options.expensePayoutsDue
? Promise.resolve(options.expensePayoutsDue).then((p) => p.length)
: countExpensePayoutsDue(supabase, companyId),
options.skattekontoPaymentDue !== undefined
? Promise.resolve(options.skattekontoPaymentDue).then((p) => (p ? 1 : 0))
: countSkattekontoPaymentDue(supabase, companyId),
])
return {
counts: {
book_transaction: bookTransaction,
book_skattekonto: bookSkattekonto,
inbox_document: inboxDocument,
suggested_match: suggestedMatch,
supplier_invoice_approval: supplierInvoiceApproval,
verifikat_missing_document: verifikatMissingDocument,
overdue_invoice: overdueInvoice,
deadline_action: deadlineAction,
pending_operations: pendingOperations,
reconciliation_due: reconciliationDue,
expense_payout: expensePayout,
skattekonto_payment_due: skattekontoPaymentDue,
},
total:
bookTransaction +
bookSkattekonto +
inboxDocument +
supplierInvoiceApproval +
verifikatMissingDocument +
overdueInvoice +
deadlineAction +
pendingOperations +
reconciliationDue +
expensePayout +
skattekontoPaymentDue,
}
}
File diff suppressed because it is too large Load Diff
-4
View File
@@ -1,4 +0,0 @@
export * from './types'
export * from './categories'
export * from './aggregate'
export * from './visible-total'
-164
View File
@@ -1,164 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
/**
* Resume list ("Fortsätt") for the homepage: in-progress work derived purely
* from draft/mid-lifecycle state (dev_docs/last_session_resume.md §6).
* No event log, no presence table: a completed flow can never render here
* because only draft-state rows are ever fetched (the reliability invariant).
*
* Lives in lib/worklist (owns pending-work predicates) but is deliberately
* NOT part of WorklistCounts.total: Att göra = obligations the system
* imposes; Fortsätt = work the user started and left. An item renders in
* exactly one surface.
*/
export type ResumeItemKind =
| 'journal_draft'
| 'invoice_draft'
| 'invoice_unsent'
| 'salary_run'
export type ResumeSalaryStatus = 'draft' | 'review' | 'approved' | 'paid'
export interface ResumeItem {
kind: ResumeItemKind
/** Stable reference, e.g. 'invoice:<uuid>'. */
ref: string
href: string
/** Free-text context: verifikat description, customer name, or period. */
context: string | null
/** Invoice number (unsent invoices). */
number?: string | null
amount?: number | null
currency?: string | null
salaryStatus?: ResumeSalaryStatus
/** Deadline boost: unsent invoices and stale salary runs outrank newer
* trivial drafts (Iqbal & Horvitz: deadline-tied tasks matter more). */
late?: boolean
updated_at: string
}
export const RESUME_MAX_ROWS = 3
/** A salary run whose period lies >= this many months back is "late". */
const SALARY_LATE_MONTHS = 2
export function isSalaryRunLate(
periodYear: number,
periodMonth: number,
now: Date,
): boolean {
const monthsBehind =
(now.getFullYear() - periodYear) * 12 + (now.getMonth() + 1 - periodMonth)
return monthsBehind >= SALARY_LATE_MONTHS
}
/**
* Pure ordering + cap: late items first (deadline boost), then most recently
* touched. Deterministic and explainable: no scoring, no ML.
*/
export function mergeResumeItems(items: ResumeItem[]): ResumeItem[] {
return [...items]
.sort((a, b) => {
if (Boolean(a.late) !== Boolean(b.late)) return a.late ? -1 : 1
return b.updated_at.localeCompare(a.updated_at)
})
.slice(0, RESUME_MAX_ROWS)
}
/**
* Fetch resume candidates for a company. Every query soft-fails to empty:
* the worst case is a missing pane, never a broken homepage.
*/
export async function listResumeItems(
supabase: SupabaseClient,
companyId: string,
now: Date = new Date(),
): Promise<ResumeItem[]> {
const [journalRes, invoiceRes, salaryRes] = await Promise.all([
supabase
.from('journal_entries')
.select('id, description, updated_at')
.eq('company_id', companyId)
.eq('status', 'draft')
.order('updated_at', { ascending: false })
.limit(RESUME_MAX_ROWS + 1)
.then((r) => r, () => ({ data: null })),
supabase
.from('invoices')
.select('id, invoice_number, total, currency, updated_at, customer:customers(name)')
.eq('company_id', companyId)
.eq('status', 'draft')
.order('updated_at', { ascending: false })
.limit(RESUME_MAX_ROWS + 1)
.then((r) => r, () => ({ data: null })),
supabase
.from('salary_runs')
.select('id, period_year, period_month, status, updated_at')
.eq('company_id', companyId)
// Enumerated on purpose: `!= 'booked'` would resurface 'corrected'.
.in('status', ['draft', 'review', 'approved', 'paid'])
.order('updated_at', { ascending: false })
.limit(RESUME_MAX_ROWS + 1)
.then((r) => r, () => ({ data: null })),
])
const items: ResumeItem[] = []
for (const row of (journalRes.data ?? []) as Array<{
id: string
description: string | null
updated_at: string
}>) {
items.push({
kind: 'journal_draft',
ref: `journal:${row.id}`,
href: `/bookkeeping/${row.id}`,
context: row.description,
updated_at: row.updated_at,
})
}
for (const row of (invoiceRes.data ?? []) as Array<{
id: string
invoice_number: string | null
total: number | null
currency: string | null
updated_at: string
customer: { name: string } | { name: string }[] | null
}>) {
const customer = Array.isArray(row.customer) ? row.customer[0] : row.customer
const unsent = !!row.invoice_number
items.push({
kind: unsent ? 'invoice_unsent' : 'invoice_draft',
ref: `invoice:${row.id}`,
href: `/invoices/${row.id}`,
context: customer?.name ?? null,
number: row.invoice_number,
amount: row.total,
currency: row.currency,
late: unsent,
updated_at: row.updated_at,
})
}
for (const row of (salaryRes.data ?? []) as Array<{
id: string
period_year: number
period_month: number
status: ResumeSalaryStatus
updated_at: string
}>) {
items.push({
kind: 'salary_run',
ref: `salary:${row.id}`,
href: `/salary/runs/${row.id}`,
context: `${row.period_year}-${String(row.period_month).padStart(2, '0')}`,
salaryStatus: row.status,
late: isSalaryRunLate(row.period_year, row.period_month, now),
updated_at: row.updated_at,
})
}
return mergeResumeItems(items)
}
-243
View File
@@ -1,243 +0,0 @@
/**
* Worklist: the unified "Att göra" pending-work model.
*
* One source of truth for what the user still has to do, shared by the
* dashboard "Att göra" section, the sidebar badges, and (eventually) the
* MCP list tools. Every surface that shows a pending-work count MUST read
* it from lib/worklist so the numbers can never diverge: divergent counts
* are exactly the "vampire transactions" problem this module exists to fix.
*
* Each category documents its "done" condition: the status field or link
* whose write makes an item drop out of the count, everywhere, at once.
*/
export const WORKLIST_CATEGORIES = [
/**
* Unbooked bank transactions ("N st att bokföra").
* Pending: is_business IS NULL AND is_ignored = false.
* Done: any booking flow (categorize, match-invoice, bulk-book RPC,
* manual booking) sets is_business = true: including the
* multi-tx flows, whose RPCs set is_business on every linked tx:
* or the user ignores the transaction (is_ignored = true).
* This is the canonical "unbooked" predicate. Do NOT count bare
* journal_entry_id IS NULL: multi-allocation and bulk-booked transactions
* keep journal_entry_id NULL (see lib/transactions/is-booked.ts).
*/
'book_transaction',
/**
* Unbooked skattekonto rows ("N st skattekontohändelser att bokföra").
* Pending: skattekonto_transactions with status = 'booked' (Skatteverket's
* "tidigare": the event has happened on the tax account),
* journal_entry_id IS NULL and is_ignored = false. Rows with
* status = 'upcoming' are future charges with nothing to book
* yet and never reach the Transaktioner inbox, so they are not
* pending work either.
* Done: the skattekonto booking flows set journal_entry_id (here it IS
* the booked marker, unlike bank transactions), or the user
* ignores the row (is_ignored = true). Same predicate as the
* Transaktioner inbox's Skatteverket rows.
*/
'book_skattekonto',
/**
* Unconsumed documents in the inbox ("N st underlag att hantera").
* Pending: invoice_inbox_items with a document and no
* created_supplier_invoice_id / created_journal_entry_id /
* matched_transaction_id, whose document is still unlinked.
* Done: any of those three columns gets stamped (match, book-direct,
* supplier-invoice conversion) or the document is linked to a
* journal entry. Mirrors /api/documents/inbox-available.
*/
'inbox_document',
/**
* Suggested transaction↔invoice matches awaiting one-click confirm.
* Pending: unbooked transactions (see book_transaction) carrying a
* potential_invoice_id or potential_supplier_invoice_id hint.
* Done: the match is confirmed (booking clears is_business) or the
* hint column is cleared. NOTE: a subset of book_transaction:
* excluded from `total` to avoid double-counting.
*/
'suggested_match',
/**
* Supplier invoices awaiting approval ("attestera").
* Pending: supplier_invoices.status = 'registered' and not a credit note
* (a credit note is a reversal, never a payable).
* Done: status moves to approved/paid/credited/….
*/
'supplier_invoice_approval',
/**
* Posted verifikat without underlag (BFL 5 kap 7§ documentation gap).
* Pending: posted journal_entries of document-requiring source types with
* no current-version document_attachments row and no
* journal_entry_no_doc_required exemption.
* Done: a document is linked or an exemption is recorded.
*/
'verifikat_missing_document',
/**
* Overdue customer invoices ("förfallna kundfakturor").
* Pending: invoices.status = 'overdue', not credited.
* Done: paid/credited (status leaves 'overdue').
*/
'overdue_invoice',
/**
* Tax/VAT deadlines needing attention.
* Pending: deadlines.is_completed = false AND status IN
* ('action_needed', 'overdue'): same predicate as
* lib/deadlines/status-engine.ts getDeadlinesNeedingAttention().
* Done: submitted/confirmed (is_completed or status transition).
*/
'deadline_action',
/**
* Agent-staged operations awaiting review ("Granskning").
* Pending: pending_operations.status = 'pending'.
* Done: committed or rejected.
*/
'pending_operations',
/**
* Accounts not signed off through the end of the previous month
* ("N konton att stämma av"), only for companies that have adopted the
* sign-off ritual (at least one account_reconciliations row ever).
* Pending: an enabled cash account (deduplicated per IBAN + currency) or a
* configured skattekonto whose latest ACTIVE sign-off has
* through_date before the last day of the previous month.
* Done: a sign-off through that date or later (POST .../signoff), or
* the account stops being reconcilable (disabled cash account).
* Zero for companies with no sign-off at all: the nudge is for those who
* reconcile monthly, not a new chore for everyone.
*/
'reconciliation_due',
/**
* People the company owes for out-of-pocket purchases ("Betala ut utlägg
* till Anna"), one item per person.
* Pending: expense_claims.status = 'registered' (booked as cost against a
* person-liability account 2893/2820/2018, nothing paid out yet),
* grouped by employee_id, or by claimant_name for the owner.
* Done: every claim of that person is marked 'paid' (a payout batch
* posted the 1930 leg), or the claim is deleted (storno).
* Counts PEOPLE, not receipts: the action is one transfer per person.
*/
'expense_payout',
/**
* The next skattekonto charge the balance does not cover ("Betala in till
* Skatteverket"), one item at most.
* Pending: skattekonto_transactions with status = 'upcoming' (Skatteverket's
* "kommande": a charge it will draw on forfallodatum), grouped on
* the earliest due date on or after today, whose sum exceeds the
* last synced saldo (extension_data skattekonto_balance_snapshot).
* Ignored rows take part: Skatteverket draws regardless of our
* flag. With no snapshot the whole charge is the amount to pay in.
* Done: the saldo covers the charge (the payment reached Skatteverket
* and the next sync or file import shows it), or the due date
* passes and the charge becomes a booked event, which is then
* book_skattekonto's work, not this row's.
* Never counts with book_skattekonto: that one is a verifikat to write for
* a settled event; this one is money that has to move before a date.
*/
'skattekonto_payment_due',
] as const
export type WorklistCategory = (typeof WORKLIST_CATEGORIES)[number]
/**
* One person the company owes for registered, unpaid utlägg: the Att göra
* row "Betala ut utlägg till {name}". Grouped server-side by employee_id
* (or claimant_name for the owner, who has no employee row).
*/
export interface ExpensePayoutDue {
/** employee_id, or `owner:<claimant_name trimmed and lower-cased>` for claims without one. */
key: string
employee_id: string | null
claimant_name: string
/** 2893 (AB owner), 2018 (EF owner) or 2820 (employee). */
liability_account: string
claim_count: number
/** The registered claims behind the total, in expense_date order. */
claim_ids: string[]
total_sek: number
/** ISO date of the oldest unpaid claim. */
oldest_expense_date: string
}
/**
* The next charge Skatteverket will draw that the skattekonto balance does
* not cover: the Att göra row "Betala in till Skatteverket". Same math as the
* /skattekonto page's Nästa dragning line and its payment dialog.
*/
export interface SkattekontoPaymentDue {
/** ISO due date of the charge (forfallodatum, else transaktionsdatum). */
due: string
/** Everything Skatteverket draws on `due`, as a positive amount. */
charge: number
/** Last synced saldo; null when no balance snapshot exists. */
balance: number | null
/** What has to be paid in: charge minus balance (never below 0), or the full charge when the balance is unknown. */
amount: number
/** Number of skattekonto rows drawn on `due`. */
count: number
/** OCR reference for the payment; null when the company's org number cannot produce one. */
ocr: string | null
/** Bankgiro for every skattekonto payment (5050-1055). */
bankgiro: string
}
export interface WorklistCounts {
counts: Record<WorklistCategory, number>
/**
* Distinct actionable items. Excludes suggested_match, which is a fast
* path over transactions already counted in book_transaction.
*/
total: number
}
/** A transaction↔invoice match suggestion, ready for one-click confirm. */
export interface SuggestedMatch {
transaction_id: string
transaction_date: string
transaction_description: string
transaction_amount: number
transaction_currency: string
/**
* Which match endpoint confirms it: match-invoice, match-supplier-invoice,
* match-rot-rut-payout (Skatteverkets utbetalning for an open begäran;
* candidate_number is then the request name), or match-expense-payout (a
* transfer repaying one person's registered utlägg; candidate_id is the
* person key and claim_ids carries the claims the transfer covers).
*/
kind: 'invoice' | 'supplier_invoice' | 'rot_rut_payout' | 'expense_payout'
candidate_id: string
candidate_number: string | null
counterparty_name: string | null
candidate_total: number | null
/**
* rot_rut_payout only: every begäran the transfer settles. Absent for a
* persisted 1:1 hint (candidate_id is the request); several when
* Skatteverket paid a bundle of beslut in one transfer (#2239), in which
* case candidate_number joins their names.
*/
request_ids?: string[]
/** expense_payout only: the registered claims this transfer pays. */
claim_ids?: string[]
}
/**
* Journal-entry source types that require underlag (BFL 5 kap 7 §). Source
* types representing system-generated entries (VAT settlement, year-end,
* currency revaluation, ...) are exempt by omission.
*
* Single source of truth for EVERY TS surface (worklist counts, journal-list
* chip/waiver UI, no-doc-required batch route, push notifications); the SQL
* mirror lives in the verifikat_without_documents RPC, pinned by
* tests/pg/document-surfaces-unification.pg.test.ts. Lives here (not in
* categories.ts) because this module is dependency-free and safe to import
* from client components.
*/
export const NEEDS_DOC_SOURCE_TYPES = [
'manual',
'bank_transaction',
'supplier_invoice_registered',
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
'import',
// Webshop order bookings rest on the generated orderunderlag (#1881); an
// entry whose underlag failed to attach must surface here.
'webshop_order',
] as const
-39
View File
@@ -1,39 +0,0 @@
import type { WorklistCounts } from './types'
/**
* The "Att göra" total as the user actually sees it. The raw worklist total
* counts inbox_document, but the Dokumentinkorg is a paid (AI) surface hidden
* from non-payers, so its documents must not inflate the count either, else the
* dashboard tile shows "N att göra" over a section that renders no such row.
*
* Single source for the KPI tile (DashboardContent) and the section header
* (AttGoraSection): both must agree, and a mismatch here was a real bug. `extra`
* carries dashboard-only additions (expiring bank connections) that are not a
* lib/worklist category.
*/
export function visibleWorklistTotal(params: {
total: number
inboxDocumentCount: number
hasAi: boolean
extra?: number
}): number {
const { total, inboxDocumentCount, hasAi, extra = 0 } = params
// total already includes inbox_document, so the subtraction is >= 0 in normal
// operation; clamp anyway so a transient count skew can never render a
// nonsense negative "N att gora" on the dashboard tile.
return Math.max(0, total + extra - (hasAi ? 0 : inboxDocumentCount))
}
/** Convenience overload taking the whole counts object. */
export function visibleWorklistTotalFrom(
worklist: WorklistCounts,
hasAi: boolean,
extra = 0,
): number {
return visibleWorklistTotal({
total: worklist.total,
inboxDocumentCount: worklist.counts.inbox_document,
hasAi,
extra,
})
}