Fix/cus fee 28 (#820)
* feat(invoices): add Plusgiro input to bank details settings Plusgiro was already persisted, validated by the API schema, rendered on the invoice PDF and toggleable via "Visa plusgiro" — but the settings UI had no field to enter the number, so plusgiro-only users could not fill it in. Add the input next to Bankgiro with Luhn validation and hyphen formatting, include it in the save payload (normalised on save so raw digits still match the dashed schema format), and add sv/en strings. Adds validatePlusgiroNumber/formatPlusgiroNumber helpers + tests. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(invoices): respect non-VAT-registered seller in PDF preview + portal tooltips Two user-reported bugs: - PDF preview (/api/invoices/preview-pdf) ignored company.vat_registered and fell back to the customer-driven 25% rate, so a non-momsregistrerad seller saw VAT in the review step even though the created invoice books none. Mirror the server-side write gate (build-invoice-write.ts): force 0% when vat_registered is false (delivery notes excepted). - InfoTooltip rendered TooltipContent without a Portal, so tooltips were clipped by the scrollable DialogContent (overflow-y-auto) in the send-invoice journal-entry review. Wrap in TooltipPrimitive.Portal. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(transactions): book library mall from its literal lines, not a lossy fallback Booking a bank transaction with a user-created booking-template (mall) via the convertible "QuickReview" fast path reduced the template to a single category + one account_override, silently discarding the chosen debit/credit. A kundinbetalning mall (D 1930 / K 1510) booked as a generic cost (D 6991 / K 1930), or with a VAT line as D 1930 / K 1930 / K 2611 — and the result flipped with the direction inferred from the business/settlement line tags, so visually-identical templates produced different verifikationer. Route every library template through the journal-entry editor (applyTemplate -> /book), which posts the literal lines, regardless of convertibility. Add regression tests locking the contract. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): make the booking-time duplicate guard bypassable TRANSACTION_BOOK_POSSIBLE_DUPLICATE told users they could "book anyway" but the UI dead-ended on a toast with no way to do so. Add a shared DuplicateBookingDialog that surfaces the already-booked sibling and lets the user review it or book anyway (force bound to the reviewed candidate, which the server re-detects so a stale id cannot wave the guard away). - Wire the dialog into the /transactions categorize flow and the manual booking dialog (JournalEntryForm -> /api/transactions/[id]/book) - Bind the override to expected_duplicate_transaction_id OR expected_duplicate_journal_entry_id so ledger-only vouchers (paid invoice, salary run) can be confirmed too - Extend the guard to the pending-operations commit path and the MCP server - Tests for book/categorize routes, detection, and the commit guard Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): log duplicate-guard bypass to behandlingshistorik in the agent commit path The web /book and /categorize routes append a durable BankTransactionDuplicateDismissed event when a user books over a detected possible double-booking. The agent commit path (commitCategorizeTransaction, commitMarkInvoicePaid) skipped the guard silently on allow_duplicate=true, leaving no behandlingshistorik — an auditor could not reconstruct why the duplicate was allowed (BFNAR 2013:2 kap 8). When allow_duplicate=true, re-detect the candidate and append the dismissal event (BankTransactionDuplicateDismissed for the bank-line path, InvoiceDuplicatePaymentDismissed for mark-paid). Best-effort — a logging failure never blocks a legitimate booking. Payloads stay PII-safe (ids, amounts, dates only — no customer or merchant name). Also fix the misleading DuplicateBookingDialog JSDoc: the retry binds expected_duplicate_journal_entry_id, not candidate.transaction_id, so the systemdokumentation matches the actual control (BFL 7 kap). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(mcp-server): stub booking-duplicate guard in receipt-matcher categorize tests The gnubok_categorize_transaction tool runs the booking-time duplicate guard before staging; its detection queries consumed the queued supabase mock results, so the staging assertions saw a thrown duplicate error instead of a staged op. Mock detectBookingDuplicate to "no duplicate" since these tests don't exercise that path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(transactions): use roundOre for duplicate-guard öre rounding Replace naive Math.round(x*100)/100 with roundOre() from @/lib/money in the booking-time duplicate guard (detection lib, commit executor, MCP categorize tool), satisfying the no-new-antipatterns ratchet guard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(sie-export): paginate journal entries and lines to prevent truncation * fix(bookkeeping): keep the Verifikat/Utkast toggle reachable on an empty list The journal entry list early-returned a pristine empty card whenever the visible list was empty and no filter was active, returning before the Verifikat/Utkast toggle rendered. This stranded users with only drafts (no posted entries) and users who emptied the drafts list, who then had to use the main menu to get back to posted entries. Narrow the early return to a genuinely empty ledger (committed view, no drafts, no filters); make the in-list empty placeholder context-aware (no drafts / no filter matches / no posted entries yet); resolve the draft count before clearing loading on an empty committed list to avoid a toggle flicker. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(enable-banking): persist psu_type and reuse it on reconnect Reconnecting a bank connection re-derived psu_type from the company entity_type every time (aktiebolag -> 'business'), silently overriding the type the user actually authorized with. A connection that only signs as 'personal' — common for AB owners who use a personal Mobile BankID, notably at Handelsbanken — flipped back to 'business' on every consent renewal and failed at the bank's signing step. - Add nullable bank_connections.psu_type column (idempotent migration) - Persist psu_type on connect; on reconnect reuse the stored value (explicit client override still wins) - Let users switch account type (Företag/Privat) from the reconnect button - Tests for persistence, reuse, and override Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(import): set maxDuration=300 on bank-file execute to prevent timeout A full-year bank file (300+ rows) runs a sequential per-row ingest that takes ~85s of server time. The execute route set no maxDuration, so it inherited the platform default and was killed mid-run — the import "spins then aborts" for the user. Match the SIE import route and give it a 5-minute budget. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(transactions): add assistant entry point on transaction rows The agent ("Lena") could only be reached from Dokumentinkorgen, and only once an underlag was matched to a transaction. Transaktioner is the most common starting point for booking, so users could not start a booking with the assistant from there at all. Add a per-row "Fråga [namn]" button on unbooked transaction rows that opens the existing transaction.categorization intent with the row's transaction_id. The intent already reads any linked underlag, so it works whether or not a receipt is attached. No new logic — only the missing entry point. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): enable Swish payment QR on invoices Flip SHOW_SWISH_ON_INVOICE on so the Swish row and payment QR render on the invoice PDF, and make the "Visa Swish" settings toggle live (it was hardcoded disabled). The preview-pdf route now builds the QR too, so it shows in forhandsvisning. Position the QR in the top-right of the payment box. No Swish API integration -- the QR is generated offline and prefills the customer Swish app; reconciliation stays via bank matching. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): scope verifikat list to current year, add storno action, clarify correction preview Three UI fixes from user feedback; no engine logic changed. - List defaults to the current räkenskapsår instead of all years. Voucher numbers run per fiscal year (one A42/year), so showing every year at once made them look like duplicates. New resolveCurrentPeriodId helper. - Add 'Återför (storno)' action on the entry detail page and list row, wiring the existing reverseEntry — a pure reversal (BFL 5 kap 5§) with no replacement, distinct from 'Rätta'. - Correction 'Effekt per konto' preview now labels a removed account 'tas bort' (vs a bare dash) and warns when the proposal is unbalanced; dialog explains the rows are the full new verifikat. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bank_connections): add psu_type column to persist chosen authorization type * feat(errors): add CannotReverseStornoError for handling reversal of storno or correction entries --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
4f0a7b1db0
commit
60e33c4b51
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { validateBalance, getSwedishLocalDate, createDraftEntry, reverseEntry } from '../engine'
|
||||
import { BookkeepingDatabaseError, AccountsNotInChartError } from '../errors'
|
||||
import { BookkeepingDatabaseError, AccountsNotInChartError, CannotReverseStornoError } from '../errors'
|
||||
import type { CreateJournalEntryLineInput, JournalEntryStatus } from '@/types'
|
||||
|
||||
// Mock Supabase client for createDraftEntry/reverseEntry tests
|
||||
@@ -612,6 +612,55 @@ describe('reverseEntry — entry_date defaults to original entry date', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('reverseEntry — rejects reversing a storno or correction', () => {
|
||||
// BFL 5 kap 5§: a storno-of-a-storno makes the original verifikat's
|
||||
// cancellation chain ambiguous. The UI hides "Återför" for these source
|
||||
// types; the engine is the server-side backstop against a direct API call.
|
||||
function supabaseReturningOriginal(original: Record<string, unknown>) {
|
||||
return {
|
||||
rpc: vi.fn(),
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'journal_entries') {
|
||||
const b: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'in', 'update', 'insert']) b[m] = vi.fn().mockReturnValue(b)
|
||||
b.single = vi.fn().mockResolvedValue({ data: original, error: null })
|
||||
return b
|
||||
}
|
||||
return createMockChain()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
for (const sourceType of ['storno', 'correction'] as const) {
|
||||
it(`throws CannotReverseStornoError for source_type '${sourceType}'`, async () => {
|
||||
const original = {
|
||||
id: 'entry-1',
|
||||
company_id: 'company-1',
|
||||
status: 'posted',
|
||||
fiscal_period_id: 'period-1',
|
||||
voucher_series: 'A',
|
||||
voucher_number: 3,
|
||||
entry_date: '2024-11-15',
|
||||
description: 'Makulering: Hyra november',
|
||||
source_type: sourceType,
|
||||
source_id: null,
|
||||
lines: [
|
||||
{ account_number: '1930', debit_amount: 10000, credit_amount: 0 },
|
||||
{ account_number: '5010', debit_amount: 0, credit_amount: 10000 },
|
||||
],
|
||||
}
|
||||
const supabase = supabaseReturningOriginal(original)
|
||||
|
||||
await expect(
|
||||
reverseEntry(supabase as never, 'company-1', 'user-1', 'entry-1'),
|
||||
).rejects.toBeInstanceOf(CannotReverseStornoError)
|
||||
|
||||
// No reversal was written — the guard fires before any voucher number is drawn.
|
||||
expect(supabase.rpc).not.toHaveBeenCalled()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('reverseEntry — bank transaction unlink', () => {
|
||||
// After a reversal the booked bank transaction must return to "Att bokföra"
|
||||
// (journal_entry_id cleared) so the user can book it again. The agent paths
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { computeSuggestedPeriod, suggestSeedDate } from '../suggest-fiscal-period'
|
||||
import {
|
||||
computeSuggestedPeriod,
|
||||
suggestSeedDate,
|
||||
resolveCurrentPeriodId,
|
||||
} from '../suggest-fiscal-period'
|
||||
|
||||
type Range = { period_start: string; period_end: string }
|
||||
|
||||
@@ -71,3 +75,30 @@ describe('suggestSeedDate', () => {
|
||||
expect(suggestSeedDate([FY2024], today)).toBe('2025-01-01')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveCurrentPeriodId', () => {
|
||||
const P2024 = { id: 'p2024', period_start: '2024-01-01', period_end: '2024-12-31' }
|
||||
const P2025 = { id: 'p2025', period_start: '2025-01-01', period_end: '2025-12-31' }
|
||||
const P2026 = { id: 'p2026', period_start: '2026-01-01', period_end: '2026-12-31' }
|
||||
|
||||
it('returns null when there are no periods', () => {
|
||||
expect(resolveCurrentPeriodId([], '2026-06-29')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the period that contains today', () => {
|
||||
expect(resolveCurrentPeriodId([P2024, P2025, P2026], '2026-06-29')).toBe('p2026')
|
||||
})
|
||||
|
||||
it('is order-independent', () => {
|
||||
expect(resolveCurrentPeriodId([P2026, P2024, P2025], '2025-03-01')).toBe('p2025')
|
||||
})
|
||||
|
||||
it('falls back to the most recent started period when today sits in a gap after the last year', () => {
|
||||
// Today is in 2027 but only periods up to 2026 exist (next year not created yet).
|
||||
expect(resolveCurrentPeriodId([P2024, P2025, P2026], '2027-02-15')).toBe('p2026')
|
||||
})
|
||||
|
||||
it('falls back to the earliest period when every period is still upcoming', () => {
|
||||
expect(resolveCurrentPeriodId([P2025, P2026], '2024-06-01')).toBe('p2025')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
BookkeepingDatabaseError,
|
||||
CannotEditNonDraftError,
|
||||
CannotReverseNonPostedError,
|
||||
CannotReverseStornoError,
|
||||
EntryAlreadyReversedError,
|
||||
EntryDateOutsideFiscalPeriodError,
|
||||
FiscalPeriodNotFoundError,
|
||||
@@ -639,6 +640,14 @@ export async function reverseEntry(
|
||||
throw new CannotReverseNonPostedError(original.status)
|
||||
}
|
||||
|
||||
// A storno or correction entry must never itself be reversed: a
|
||||
// storno-of-a-storno makes the original verifikat's cancellation chain
|
||||
// ambiguous (BFL 5 kap 5§). The UI hides "Återför" for these source types;
|
||||
// this is the server-side backstop against a direct API call.
|
||||
if (original.source_type === 'storno' || original.source_type === 'correction') {
|
||||
throw new CannotReverseStornoError(original.source_type)
|
||||
}
|
||||
|
||||
const lines = (original.lines as JournalEntryLine[]) || []
|
||||
|
||||
// Create reversed lines (swap debit and credit, preserve dimensions)
|
||||
|
||||
@@ -10,6 +10,7 @@ export const FISCAL_PERIOD_NOT_FOUND = 'FISCAL_PERIOD_NOT_FOUND' as const
|
||||
export const ENTRY_DATE_OUTSIDE_FISCAL_PERIOD = 'ENTRY_DATE_OUTSIDE_FISCAL_PERIOD' as const
|
||||
export const JOURNAL_ENTRY_NOT_FOUND = 'JOURNAL_ENTRY_NOT_FOUND' as const
|
||||
export const CANNOT_REVERSE_NON_POSTED = 'CANNOT_REVERSE_NON_POSTED' as const
|
||||
export const CANNOT_REVERSE_STORNO = 'CANNOT_REVERSE_STORNO' as const
|
||||
export const CANNOT_CORRECT_NON_POSTED = 'CANNOT_CORRECT_NON_POSTED' as const
|
||||
export const CANNOT_EDIT_NON_DRAFT = 'CANNOT_EDIT_NON_DRAFT' as const
|
||||
export const ENTRY_ALREADY_REVERSED = 'ENTRY_ALREADY_REVERSED' as const
|
||||
@@ -119,6 +120,22 @@ export class CannotReverseNonPostedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Raised when a storno (reversal) is attempted on an entry that is itself a
|
||||
* storno or a correction. Reversing such an entry would produce a
|
||||
* storno-of-a-storno and make the original verifikat's cancellation chain
|
||||
* ambiguous, violating the traceable-correction requirement of BFL 5 kap 5§.
|
||||
* The UI hides the "Återför" action for these source types; this is the
|
||||
* server-side backstop so a direct API call cannot bypass it.
|
||||
*/
|
||||
export class CannotReverseStornoError extends Error {
|
||||
readonly code = CANNOT_REVERSE_STORNO
|
||||
constructor(public readonly sourceType: string) {
|
||||
super('Cannot reverse a storno or correction entry')
|
||||
this.name = 'CannotReverseStornoError'
|
||||
}
|
||||
}
|
||||
|
||||
export class CannotCorrectNonPostedError extends Error {
|
||||
readonly code = CANNOT_CORRECT_NON_POSTED
|
||||
constructor(public readonly currentStatus: string) {
|
||||
@@ -283,6 +300,7 @@ export function isBookkeepingError(err: unknown): boolean {
|
||||
err instanceof EntryDateOutsideFiscalPeriodError ||
|
||||
err instanceof JournalEntryNotFoundError ||
|
||||
err instanceof CannotReverseNonPostedError ||
|
||||
err instanceof CannotReverseStornoError ||
|
||||
err instanceof CannotCorrectNonPostedError ||
|
||||
err instanceof CannotEditNonDraftError ||
|
||||
err instanceof EntryAlreadyReversedError ||
|
||||
@@ -399,6 +417,19 @@ export function bookkeepingErrorResponse(err: unknown): NextResponse | null {
|
||||
)
|
||||
}
|
||||
|
||||
if (err instanceof CannotReverseStornoError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
details: { sourceType: err.sourceType },
|
||||
},
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (err instanceof CannotCorrectNonPostedError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
|
||||
@@ -14,6 +14,9 @@ import type { FiscalPeriod } from '@/types'
|
||||
/** Minimal shape needed for the date math — `FiscalPeriod` satisfies it. */
|
||||
type PeriodRange = Pick<FiscalPeriod, 'period_start' | 'period_end'>
|
||||
|
||||
/** A period plus its id, for resolving which räkenskapsår a view scopes to. */
|
||||
type IdentifiablePeriod = Pick<FiscalPeriod, 'id' | 'period_start' | 'period_end'>
|
||||
|
||||
export interface SuggestedPeriod {
|
||||
name: string
|
||||
period_start: string
|
||||
@@ -121,3 +124,36 @@ export function suggestSeedDate(periods: PeriodRange[], today: string): string {
|
||||
|
||||
return addDays(sorted[sorted.length - 1].period_end, 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which fiscal period a period-scoped view (e.g. the verifikat list)
|
||||
* should default to: the räkenskapsår the user is currently in.
|
||||
*
|
||||
* Verifikationsnummer run as an unbroken series *per räkenskapsår* (BFL 5 kap
|
||||
* 7§), so the same number (e.g. A42) legitimately recurs once per year. Showing
|
||||
* every year at once makes those look like duplicates and makes a bare "A42"
|
||||
* reference ambiguous — a period-oriented view should land on a single year.
|
||||
*
|
||||
* Resolution, given `today` (YYYY-MM-DD):
|
||||
* 1. The period that contains today.
|
||||
* 2. Else the most recent period that has already started (period_start ≤ today)
|
||||
* — covers a gap after the last year before the next one is created.
|
||||
* 3. Else the earliest period (a company whose only/first year is still upcoming).
|
||||
* 4. Else null (no periods at all → caller falls back to "all years").
|
||||
*/
|
||||
export function resolveCurrentPeriodId(
|
||||
periods: IdentifiablePeriod[],
|
||||
today: string,
|
||||
): string | null {
|
||||
if (periods.length === 0) return null
|
||||
|
||||
const containing = periods.find((p) => p.period_start <= today && today <= p.period_end)
|
||||
if (containing) return containing.id
|
||||
|
||||
const started = periods
|
||||
.filter((p) => p.period_start <= today)
|
||||
.sort((a, b) => b.period_start.localeCompare(a.period_start))
|
||||
if (started.length > 0) return started[0].id
|
||||
|
||||
return [...periods].sort((a, b) => a.period_start.localeCompare(b.period_start))[0].id
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
BookkeepingDatabaseError,
|
||||
CannotCorrectNonPostedError,
|
||||
CannotReverseNonPostedError,
|
||||
CannotReverseStornoError,
|
||||
EntryAlreadyReversedError,
|
||||
EntryDateOutsideFiscalPeriodError,
|
||||
FiscalPeriodNotFoundError,
|
||||
@@ -348,6 +349,9 @@ function extractBookkeepingDetails(err: unknown): { code: string; details?: unkn
|
||||
if (err instanceof CannotReverseNonPostedError) {
|
||||
return { code: err.code, details: { currentStatus: err.currentStatus } }
|
||||
}
|
||||
if (err instanceof CannotReverseStornoError) {
|
||||
return { code: err.code, details: { sourceType: err.sourceType } }
|
||||
}
|
||||
if (err instanceof CannotCorrectNonPostedError) {
|
||||
return { code: err.code, details: { currentStatus: err.currentStatus } }
|
||||
}
|
||||
|
||||
@@ -180,6 +180,11 @@ const BOOKKEEPING: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Endast bokförda verifikationer kan stornas.',
|
||||
message_en: 'Only posted entries can be reversed.',
|
||||
},
|
||||
CANNOT_REVERSE_STORNO: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'En stornering eller rättelse kan inte stornas.',
|
||||
message_en: 'A storno or correction entry cannot be reversed.',
|
||||
},
|
||||
CANNOT_CORRECT_NON_POSTED: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Endast bokförda verifikationer kan rättas.',
|
||||
|
||||
@@ -159,10 +159,9 @@ const LABELS = {
|
||||
},
|
||||
} as const
|
||||
|
||||
// Swish on invoices (the number row + the payment QR) is "coming soon" — gated
|
||||
// off until the QR flow is finished. Flip to true to re-enable both at once;
|
||||
// the settings "Visa Swish" toggle is disabled while this is false.
|
||||
export const SHOW_SWISH_ON_INVOICE = false
|
||||
// Swish on invoices (the number row + the payment QR). When true, the Swish row
|
||||
// and QR render on the invoice PDF and the settings "Visa Swish" toggle is live.
|
||||
export const SHOW_SWISH_ON_INVOICE = true
|
||||
|
||||
// Labor-only disclaimer for the ROT/RUT block. Kept Swedish-only in both
|
||||
// locales — references Skatteverket's fakturamodell directly, which is a
|
||||
@@ -395,6 +394,7 @@ function createStyles(branding?: InvoiceBranding) {
|
||||
padding: 15,
|
||||
backgroundColor: '#f8f9fa',
|
||||
borderRadius: 4,
|
||||
position: 'relative',
|
||||
},
|
||||
paymentTitle: {
|
||||
fontSize: 11,
|
||||
@@ -1086,9 +1086,9 @@ export function InvoicePDF({ invoice, customer, items, company, originalInvoiceN
|
||||
</View>
|
||||
)}
|
||||
{swishQrDataUrl && (
|
||||
<View style={{ marginTop: 10, alignItems: 'center' }}>
|
||||
<View style={{ position: 'absolute', top: 15, right: 15, width: 96, alignItems: 'center' }}>
|
||||
<Image src={swishQrDataUrl} style={{ width: 96, height: 96 }} />
|
||||
<Text style={[styles.paymentLabel, { marginTop: 2 }]}>{L.swishQrCaption}</Text>
|
||||
<Text style={[styles.paymentLabel, { width: 'auto', marginTop: 2, textAlign: 'center' }]}>{L.swishQrCaption}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
@@ -9,7 +9,7 @@ let results: Array<{ data?: unknown; error?: unknown }>
|
||||
|
||||
function makeBuilder() {
|
||||
const b: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'in', 'order', 'range', 'lt', 'lte', 'gte', 'gt', 'limit']) {
|
||||
for (const m of ['select', 'eq', 'in', 'order', 'range', 'lt', 'lte', 'gte', 'gt', 'limit', 'neq']) {
|
||||
b[m] = vi.fn().mockReturnValue(b)
|
||||
}
|
||||
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
|
||||
@@ -46,6 +46,16 @@ const baseOptions = {
|
||||
program_name: 'ERPBase',
|
||||
}
|
||||
|
||||
// Queue consumption order after the pagination fix:
|
||||
// 0: fiscal_periods.single()
|
||||
// 1: previous fiscal period .single() (#RAR -1)
|
||||
// 2: chart_of_accounts (fetchAllRows)
|
||||
// 3: journal_entries (fetchAllRows)
|
||||
// 4: journal_entry_lines (fetchAllRows) ← split out from the entries query
|
||||
// 5: cost_centers
|
||||
// 6: projects
|
||||
// 7: opening balances (RPC fallback or journal_entry_lines page)
|
||||
|
||||
describe('generateSIEExport', () => {
|
||||
it('throws when fiscal period not found', async () => {
|
||||
results = [
|
||||
@@ -59,20 +69,14 @@ describe('generateSIEExport', () => {
|
||||
|
||||
it('generates correct header format', async () => {
|
||||
results = [
|
||||
// 0: fiscal_periods
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
// 1: previous fiscal period (#RAR -1)
|
||||
{ data: null, error: null },
|
||||
// 2: chart_of_accounts (empty)
|
||||
{ data: [], error: null },
|
||||
// 3: journal_entries (empty)
|
||||
{ data: [], error: null },
|
||||
// 4: cost_centers (empty)
|
||||
{ data: [], error: null },
|
||||
// 5: projects (empty)
|
||||
{ data: [], error: null },
|
||||
// 6: compute_prior_opening_balances RPC (empty — no IB)
|
||||
{ data: [], error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // opening balances RPC
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
@@ -92,10 +96,11 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -118,9 +123,10 @@ describe('generateSIEExport', () => {
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -139,20 +145,18 @@ describe('generateSIEExport', () => {
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{
|
||||
// journal_entries (no embedded lines — those come from the next slot)
|
||||
data: [
|
||||
{
|
||||
id: 'e1',
|
||||
entry_date: '2024-03-15',
|
||||
voucher_number: 1,
|
||||
voucher_series: 'A',
|
||||
description: 'Sale invoice',
|
||||
status: 'posted',
|
||||
lines: [
|
||||
{ account_number: '1510', debit_amount: 1250, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ account_number: '3001', debit_amount: 0, credit_amount: 1000, line_description: 'Revenue', cost_center: null, project: null },
|
||||
{ account_number: '2611', debit_amount: 0, credit_amount: 250, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
},
|
||||
{ id: 'e1', entry_date: '2024-03-15', voucher_number: 1, voucher_series: 'A', description: 'Sale invoice', status: 'posted' },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
// journal_entry_lines — each carries journal_entry_id for grouping
|
||||
data: [
|
||||
{ journal_entry_id: 'e1', account_number: '1510', debit_amount: 1250, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ journal_entry_id: 'e1', account_number: '3001', debit_amount: 0, credit_amount: 1000, line_description: 'Revenue', cost_center: null, project: null },
|
||||
{ journal_entry_id: 'e1', account_number: '2611', debit_amount: 0, credit_amount: 250, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
@@ -175,8 +179,9 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{
|
||||
data: [
|
||||
{ code: 'CC1', name: 'Avdelning 1', is_active: true },
|
||||
@@ -204,21 +209,17 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 'e1',
|
||||
entry_date: '2024-03-15',
|
||||
voucher_number: 1,
|
||||
voucher_series: 'A',
|
||||
description: 'With dimensions',
|
||||
status: 'posted',
|
||||
lines: [
|
||||
{ account_number: '5010', debit_amount: 8000, credit_amount: 0, line_description: null, cost_center: 'CC1', project: 'P001' },
|
||||
{ account_number: '1930', debit_amount: 0, credit_amount: 8000, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
},
|
||||
{ id: 'e1', entry_date: '2024-03-15', voucher_number: 1, voucher_series: 'A', description: 'With dimensions', status: 'posted' },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
data: [
|
||||
{ journal_entry_id: 'e1', account_number: '5010', debit_amount: 8000, credit_amount: 0, line_description: null, cost_center: 'CC1', project: 'P001' },
|
||||
{ journal_entry_id: 'e1', account_number: '1930', debit_amount: 0, credit_amount: 8000, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
@@ -237,27 +238,23 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 'e1',
|
||||
entry_date: '2024-01-15',
|
||||
voucher_number: 1,
|
||||
voucher_series: 'A',
|
||||
description: 'Sale',
|
||||
status: 'posted',
|
||||
lines: [
|
||||
{ account_number: '1510', debit_amount: 1250, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ account_number: '3001', debit_amount: 0, credit_amount: 1000, line_description: null, cost_center: null, project: null },
|
||||
{ account_number: '2611', debit_amount: 0, credit_amount: 250, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
},
|
||||
{ id: 'e1', entry_date: '2024-01-15', voucher_number: 1, voucher_series: 'A', description: 'Sale', status: 'posted' },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{
|
||||
data: [
|
||||
{ journal_entry_id: 'e1', account_number: '1510', debit_amount: 1250, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ journal_entry_id: 'e1', account_number: '3001', debit_amount: 0, credit_amount: 1000, line_description: null, cost_center: null, project: null },
|
||||
{ journal_entry_id: 'e1', account_number: '2611', debit_amount: 0, credit_amount: 250, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -275,26 +272,22 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 'e1',
|
||||
entry_date: '2024-01-15',
|
||||
voucher_number: 1,
|
||||
voucher_series: 'A',
|
||||
description: 'Invoice for "consulting"',
|
||||
status: 'posted',
|
||||
lines: [
|
||||
{ account_number: '1930', debit_amount: 100, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ account_number: '3001', debit_amount: 0, credit_amount: 100, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
},
|
||||
{ id: 'e1', entry_date: '2024-01-15', voucher_number: 1, voucher_series: 'A', description: 'Invoice for "consulting"', status: 'posted' },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{
|
||||
data: [
|
||||
{ journal_entry_id: 'e1', account_number: '1930', debit_amount: 100, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ journal_entry_id: 'e1', account_number: '3001', debit_amount: 0, credit_amount: 100, line_description: null, cost_center: null, project: null },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -307,10 +300,11 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -331,10 +325,11 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -348,10 +343,11 @@ describe('generateSIEExport', () => {
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null },
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
@@ -361,6 +357,68 @@ describe('generateSIEExport', () => {
|
||||
expect(output).not.toContain('#OBJEKT')
|
||||
})
|
||||
|
||||
it('does not truncate large periods — every voucher and its lines are exported', async () => {
|
||||
// Regression test for the user-reported bug: the previous nested
|
||||
// `select('*, lines:journal_entry_lines(*)')` query hit PostgREST's
|
||||
// embedded-resource row ceiling and silently truncated to ~30 vouchers.
|
||||
// The pagination fix fetches entries and lines as separate paginated
|
||||
// queries, so a period far larger than any single page round-trips fully.
|
||||
const ENTRY_COUNT = 2500 // well past the 1000-row PostgREST page size
|
||||
|
||||
const entries = Array.from({ length: ENTRY_COUNT }, (_, i) => ({
|
||||
id: `e${i + 1}`,
|
||||
entry_date: '2024-06-01',
|
||||
voucher_number: i + 1,
|
||||
voucher_series: 'A',
|
||||
description: `Voucher ${i + 1}`,
|
||||
status: 'posted',
|
||||
}))
|
||||
|
||||
const lines = entries.flatMap((e) => [
|
||||
{ journal_entry_id: e.id, account_number: '1510', debit_amount: 100, credit_amount: 0, line_description: null, cost_center: null, project: null },
|
||||
{ journal_entry_id: e.id, account_number: '3001', debit_amount: 0, credit_amount: 100, line_description: null, cost_center: null, project: null },
|
||||
])
|
||||
|
||||
// fetchAllRows paginates at PAGE_SIZE = 1000; chunk the mock data so the
|
||||
// queue mimics real multi-page round-trips and the loop stops on a short page.
|
||||
function paginate<T>(rows: T[]): Array<{ data: T[]; error: null }> {
|
||||
const PAGE = 1000
|
||||
const pages: Array<{ data: T[]; error: null }> = []
|
||||
for (let i = 0; i < rows.length; i += PAGE) {
|
||||
pages.push({ data: rows.slice(i, i + PAGE), error: null })
|
||||
}
|
||||
// Ensure a final short page so fetchAllRows terminates when the data is
|
||||
// an exact multiple of PAGE_SIZE.
|
||||
if (rows.length % PAGE === 0) pages.push({ data: [], error: null })
|
||||
return pages
|
||||
}
|
||||
|
||||
results = [
|
||||
{ data: { id: 'period-1', period_start: '2024-01-01', period_end: '2024-12-31' }, error: null },
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
...paginate(entries), // journal_entries — 3 pages (1000 + 1000 + 500)
|
||||
...paginate(lines), // journal_entry_lines — 5000 rows → 5 pages
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
{ data: [], error: null }, // RPC fallback
|
||||
]
|
||||
|
||||
const output = await generateSIEExport(supabase, 'company-1', baseOptions)
|
||||
|
||||
// Every voucher present — including the first, last, and a middle one
|
||||
// that the old ~30-row cap would have dropped.
|
||||
const verCount = (output.match(/#VER /g) || []).length
|
||||
expect(verCount).toBe(ENTRY_COUNT)
|
||||
expect(output).toContain('#VER "A" 1 20240601 "Voucher 1"')
|
||||
expect(output).toContain(`#VER "A" 1500 20240601 "Voucher 1500"`)
|
||||
expect(output).toContain(`#VER "A" ${ENTRY_COUNT} 20240601 "Voucher ${ENTRY_COUNT}"`)
|
||||
|
||||
// Lines were stitched onto their entries (two #TRANS per voucher)
|
||||
const transCount = (output.match(/#TRANS /g) || []).length
|
||||
expect(transCount).toBe(ENTRY_COUNT * 2)
|
||||
})
|
||||
|
||||
it('emits #IB from compute_prior_opening_balances RPC fallback when opening_balance_entry_id is null', async () => {
|
||||
// Reproduces the user-reported bug: after a multi-year SIE import the
|
||||
// continuation-import guard intentionally leaves opening_balance_entry_id
|
||||
@@ -374,6 +432,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries (no movements this period)
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
// RPC fallback returns prior IBs derived from historical journal lines
|
||||
@@ -404,6 +463,7 @@ describe('generateSIEExport', () => {
|
||||
{ data: null, error: null }, // prevPeriod
|
||||
{ data: [], error: null }, // accounts
|
||||
{ data: [], error: null }, // journal_entries
|
||||
{ data: [], error: null }, // journal_entry_lines
|
||||
{ data: [], error: null }, // cost_centers
|
||||
{ data: [], error: null }, // projects
|
||||
// fetchAllRows page 1 — explicit OB entry lines
|
||||
|
||||
+50
-11
@@ -56,20 +56,59 @@ export async function generateSIEExport(
|
||||
.range(from, to)
|
||||
)
|
||||
|
||||
// Fetch all posted journal entries with lines
|
||||
let entriesQuery = supabase
|
||||
.from('journal_entries')
|
||||
.select('*, lines:journal_entry_lines(*)')
|
||||
.eq('company_id', companyId)
|
||||
.eq('fiscal_period_id', options.fiscal_period_id)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
.order('voucher_number')
|
||||
// Fetch all posted journal entries — paginated to avoid truncation.
|
||||
// The previous nested `select('*, lines:journal_entry_lines(*)')` hit
|
||||
// PostgREST's response-row ceiling on the embedded resource and silently
|
||||
// truncated large periods (~30 vouchers). Fetch entries and lines as two
|
||||
// separate paginated queries and stitch them together in memory, mirroring
|
||||
// journal-register.ts.
|
||||
const entries = await fetchAllRows<JournalEntry>(({ from, to }) => {
|
||||
let q = supabase
|
||||
.from('journal_entries')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.eq('fiscal_period_id', options.fiscal_period_id)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
if (options.exclude_year_end_closing) {
|
||||
entriesQuery = entriesQuery.neq('source_type', 'year_end')
|
||||
if (options.exclude_year_end_closing) {
|
||||
q = q.neq('source_type', 'year_end')
|
||||
}
|
||||
|
||||
return q.order('voucher_number').range(from, to)
|
||||
})
|
||||
|
||||
// Fetch all lines for those entries, filtered server-side via an inner join
|
||||
// so the same company/period/status (and year-end exclusion) constraints
|
||||
// apply, then group by journal_entry_id.
|
||||
const allLines = await fetchAllRows<JournalEntryLine & { journal_entry_id: string }>(({ from, to }) => {
|
||||
let q = supabase
|
||||
.from('journal_entry_lines')
|
||||
.select('*, journal_entries!inner(company_id, fiscal_period_id, status, source_type)')
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.eq('journal_entries.fiscal_period_id', options.fiscal_period_id)
|
||||
.in('journal_entries.status', ['posted', 'reversed'])
|
||||
|
||||
if (options.exclude_year_end_closing) {
|
||||
q = q.neq('journal_entries.source_type', 'year_end')
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return q.range(from, to) as any
|
||||
})
|
||||
|
||||
const linesByEntryId = new Map<string, JournalEntryLine[]>()
|
||||
for (const line of allLines) {
|
||||
const list = linesByEntryId.get(line.journal_entry_id)
|
||||
if (list) {
|
||||
list.push(line)
|
||||
} else {
|
||||
linesByEntryId.set(line.journal_entry_id, [line])
|
||||
}
|
||||
}
|
||||
|
||||
const { data: entries } = await entriesQuery
|
||||
for (const entry of entries) {
|
||||
entry.lines = linesByEntryId.get(entry.id) || []
|
||||
}
|
||||
|
||||
// Fetch cost centers and projects for dimension records
|
||||
const { data: costCenters } = await supabase
|
||||
|
||||
Reference in New Issue
Block a user