From b6332e9ff4f3e90c4095dbab07ca689c8edd945f Mon Sep 17 00:00:00 2001 From: Mattsson <111893710+mattssonn@users.noreply.github.com> Date: Mon, 13 Jul 2026 22:54:33 +0200 Subject: [PATCH] Fix/skv connection flow (#1015) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(salary): one-click AGI submission with filing state machine and success feedback The AGI panel required users to know that "Ladda ner AGI-fil" was the generate step, then click submit, signing link, and kvittens manually. A nollkorning filing stalled on "AGI-XML saknas" pointing at a UI path that does not exist. - New primary button "Lamna in till Skatteverket" chains the existing endpoints client-side: generate XML if missing, POST underlag, poll kontrollresultat, create signing link, open Mina Sidor in a tab opened synchronously at click (popup-blocker safe). Inline stepper shows each step; the four old buttons become collapsed advanced/recovery actions, auto-expanded in stale-draft and rejected states. XML download stays visible and free for manual filing. - deriveAgiFilingState() + useAgiSubmission() lift the per-period submission record to the run page: the progress rail and salary hero now render the real state machine (generated, underlag inskickat, vantar pa BankID-signatur, inlamnad med kvittensnummer) instead of telling users to "lamna in" an already-submitted declaration. - Success card with kvittensnummer and signature metadata once signed, plus a toast when a poll flips the state while the page is open. - AGI kvittens cron every 15 min instead of every 2 h so filings signed on another device get stamped and emailed promptly. - Advanced submit also auto-generates, and the stale "Lon -> AGI -> Generera" error text now points at the real buttons. Co-Authored-By: Claude Fable 5 * fix(enable-banking): instant OAuth callback feedback and dead-attempt cleanup The bank redirect landed on a blank page for the several seconds the callback spent exchanging the PSD2 session and mirroring accounts, and every failed connect attempt left a status='error' row that rendered forever as an "Atgard kravs" card next to a successful retry, showing duplicate connections to the same bank. - Stream a branded "Slutfor bankanslutningen" progress page from the callback: the shell flushes before the session exchange starts and a script/meta redirect follows when the work completes, with a 30s slow-work escape hatch. Fast outcomes (denial, bad params, unknown state) keep their plain redirects. - Delete never-activated connection rows (no session_id, no accounts_data) on denial or exchange failure, and sweep leftovers for the same bank on the next connect. Established connections keep their "Atgard krävs" card via the accounts_data guard; FKs are ON DELETE SET NULL so deletion has no dependents. - Show "Banken ar ansluten: hamtar dina konton" while the settings panel loads after the callback instead of an anonymous spinner. Co-Authored-By: Claude Fable 5 * fix(invoices): reject re-send of issued invoices and gate bookkeeping on the sent flip A direct POST to /api/invoices/[id]/send against an already-issued invoice re-emailed the customer and posted a second revenue verifikat (createInvoiceJournalEntry has no dedup), overwriting journal_entry_id and orphaning the first entry. Only the UI hid the button; the v1 route and the MCP commit executor already rejected non-drafts. - Non-draft invoices now return 409 INVOICE_ALREADY_SENT. - The draft to sent status flip is an optimistic lock (status guard plus row-count check); journal entry, accrual schedules, PDF archival and the invoice.sent event only run for the request that won the flip. - On a flip failure the journal entry is deferred: the row stays draft and a retry re-runs the pipeline, ending with exactly one verifikat. Co-Authored-By: Claude Fable 5 * fix(invoices): payment links, failure visibility and sandbox guard for recurring auto-send - sendInvoiceFromSchedule now auto-creates an online payment link via applyPaymentLinkToInvoice before rendering and passes the payment link QR to the PDF: parity with the dashboard and v1 send routes, which recurring invoices silently lacked. - The recurring cron persists last_run_warning both when a claimed run throws (hourly retries stay visible on the schedule) and when a stale schedule is rolled forward, so a deterministic failure can no longer skip a month silently. - Auto-send is blocked for sandbox companies at the email chokepoint (freeze-and-retain: the invoice is still generated as a draft), covering both the cron and the run-now route with one guard. Co-Authored-By: Claude Fable 5 * feat(salary): close the Fortnox payroll API gaps (phases 1-4) Payroll now runs end-to-end through the open API, including onboarding a client from another payroll system, with every write staged for approval. - v1: per-employee payslips (list/detail/PDF), payslip line writes, run roster attach/remove, absence ranges (per-day storage), jamkning fields, cutover opening balances (single + atomic bulk PUT), vacation balance + vacation-year-close. PUT added to the wrapper's idempotency/ test-key set (test keys could otherwise write through PUT). - MCP: 10 new tools (get_employee/get_payslip/list_absence/ get_vacation_balance reads + staged update_payslip_line, register_absence, create_employee, update_employee, set_employee_opening_balances, close_vacation_year), executors, risk tiers, op-type CHECK expansions. create_employee encrypts personnummer at staging: pending_operations never holds plaintext. - Scope-map audit retrofit: 11 formerly unmapped tools now scoped; BREAKING for keys that relied on the 4 default-allow writes. - Cutover: employee_opening_balances (derived lock trigger, self-unlocks on run correction), engine YTD/karens/liability integration, Ingaende saldon section in the employee editor. - Arbetsschema-lite: employees.hours_per_week/workdays_per_week drive the hourly/daily divisors; legacy 173/21 preserved exactly at defaults so existing pay math is byte-identical. - Vacation ledger + semesterberedning/arsavslut: recomputed per-year day balances (synced on book/correct, non-fatal), year-close with the min-20 floor, 5-year sparade-dagar expiry to forced payout, and a 2920/2940 drift adjustment via the bookkeeping engine; Semester dashboard card with preview-then-confirm dialog. - Fix: Zod 4 defaults leak through .partial(), which made every sparse employee PATCH fail validation and reset defaulted columns. Migrations 20260713100000/101000/110000/121000/122000 (applied to staging with version rows; prod via merge). vacation_ledger renamed from 20260713120000 to avoid colliding with vat_declaration_totals_rpc. Co-Authored-By: Claude Fable 5 * perf: cut dashboard page-load latency (region, round trips, caching, VAT RPC) The dominant cost was infrastructure: Vercel functions ran in iad1 (Washington D.C.) while Supabase (DB + auth) lives in eu-north-1 (Stockholm), so every request paid 4-5 transatlantic round trips of auth + company resolution before doing any real work (measured 530-1900ms for single-query GETs in prod logs). Pin functions to arn1 and cut the redundant work on top: - vercel.json: functions to arn1, same city as the database - getActiveCompanyId: preference + first-membership queries run in parallel; the fallback result doubles as validation in the common single-company case (one round trip instead of two sequential) - withRouteContext: Server-Timing header and authMs/companyMs/handlerMs in the op-completed log, so latency is attributable per phase - dashboard layout: nav badge counts off the critical path; DashboardNav loads them client-side via the new use-worklist-badges SWR hook with debounced realtime revalidation - swr (new dependency, approved): global provider; useCompanySettings shares one cache entry across consumers and renders from cache on back-navigation instead of re-showing skeletons - /pending: realtime refetch debounced; bulk operations previously fired 4 requests per row-change event - VAT declaration: new get_vat_declaration_totals RPC returns per-account totals, settlement-shape detection (#984) and source_type counts in ONE round trip instead of paging every entry+line through PostgREST. Account lists stay TS-side parameters so ACCOUNT_RUTA remains the single source of truth. Shape-exclusion coverage moved to tests/pg/vat-declaration-totals-rpc.pg.test.ts; DDL already applied to staging. - bundle: CommandPalette lazy-mounts on first Ctrl/Cmd+K, AgentChat dynamic-imports the markdown parser, @vercel/speed-insights (new dependency, approved) added for real-user timings The /salary fetch-waterfall fix from the same effort already landed inside 2084a756. Co-Authored-By: Claude Fable 5 * fix(invoices): settle öre-rounded payments from the mark-paid flow An invoice with öresavrundning shows a rounded "Att betala" on the PDF; the customer pays that amount (up to 50 öre off the stored öre total) and the invoice-page mark-paid flow rejected it with MATCH_AMOUNT_EXCEEDS_REMAINING: a dead end, while the bank-transaction match flow already absorbed the residual to 3740. - PaymentBookingDialog now proposes the rounded bank leg plus the 3740 residual line (credit when rounded up, debit when rounded down), resolved via getDisplayTotal from the per-invoice override and company_settings.ore_rounding. - settleInvoicePayment and the v1 mark-paid route absorb the sub-krona residual, gated by planInvoicePaymentForLines: absorption applies ONLY when the caller lines carry the exact residual on 3740; otherwise the strict plan applies (sub-krona partials stay partial, no-3740 overshoots keep the 400), so the GL can never diverge from the AR sub-ledger. - planInvoicePayment absorb-band boundary tightened to >= 1 kr: an exactly-1-kr overshoot used to slip past both the guard and the absorb branch and silently over-record paid_amount (pre-existing on the bank-match path). Co-Authored-By: Claude Fable 5 * fix(security): resolve all 7 PR compliance findings - ASVS V3.3: per-request CSP nonce on the enable-banking finalize page (mirrors the mcp-oauth consent page); inline scripts are nonce-bound - ASVS V16: decouple callback finalize work from the response stream (eager promise + next/server after()) so a client disconnect cannot drop session persistence or the consent_granted audit emit - ISO 27001 A.8.15: failed audit-event emits log through the structured logger with a stable message for log-based alerting - ASVS V2.3: recurring-invoice cron and run-now routes resolve isSandboxCompany themselves and pass an explicit suppressAutoSend flag (defence in depth around the email chokepoint, freeze-and-retain kept) - ISO 27001 A.8.11: stagePendingOperation rejects plaintext personnummer-bearing keys in params/preview_data (key-based guard; EF org numbers make value-matching unsafe) - ASVS V4.5: employee PATCH body is truly sparse; cleared number fields are omitted instead of resetting DB values to hardcoded fallbacks - ASVS V8.2.1: route-level tests pin the v1 cross-company deny (404 by convention, not 403) on the payslip PDF endpoint Co-Authored-By: Claude Fable 5 * feat: implement vacation-year basis change validation and error handling - Added tests to block vacation-year basis changes when open balances exist. - Implemented error handling for open-balances guard query failures in the settings route. - Enhanced absence route to reject reversed date ranges with a validation error. - Updated absence handling to use atomic upserts instead of delete+insert for better performance and reliability. - Refactored salary calculation logic to correctly handle age-based avgifter rates according to Skatteverket's rules. - Improved error messaging for vacation year closure adjustments. - Adjusted employee opening balances handling to preserve audit information during upserts. * feat(settings): add validation to block vacation-year basis change with open balances feat(absence): reject reversed date ranges in absence queries fix(absence): update absence handling to use atomic upserts instead of delete+insert fix(employee): improve validation for jamkning dates in employee updates fix(opening-balances): ensure created_by field is preserved during upserts test(absence): enhance tests for absence range and date validations test(calculation): add tests for age-based avgifter rates and edge cases test(semesterberedning): validate vacation year closure adjustments and error handling test(employee-opening-balances): update tests to reflect changes in salary_run_employees schema * fix(migrations): implement NOT VALID constraints for pending_operations and add validation migration --------- Co-authored-by: Claude Fable 5 --- DECISIONS.md | 35 + app/(dashboard)/layout.tsx | 22 +- app/(dashboard)/pending/page.tsx | 12 +- .../salary/employees/[id]/page.tsx | 25 +- app/(dashboard)/salary/page.tsx | 108 ++- app/(dashboard)/salary/runs/[id]/page.tsx | 20 + app/(dashboard)/settings/banking/page.tsx | 10 +- .../callback/__tests__/route.test.ts | 182 +++- .../enable-banking/callback/finalize-page.ts | 185 ++++ .../enable-banking/callback/route.ts | 629 ++++++++----- .../[id]/mark-paid/__tests__/route.test.ts | 45 + .../[id]/send/__tests__/route.test.ts | 92 +- app/api/invoices/[id]/send/route.ts | 58 +- app/api/invoices/recurring/[id]/run/route.ts | 11 +- .../recurring/cron/__tests__/route.test.ts | 93 ++ app/api/invoices/recurring/cron/route.ts | 33 +- .../[id]/absence/__tests__/route.test.ts | 3 +- .../salary/employees/[id]/absence/route.ts | 131 +-- .../employees/[id]/opening-balances/route.ts | 56 ++ app/api/salary/employees/route.ts | 5 + app/api/salary/runs/[id]/book/route.ts | 22 + app/api/salary/runs/[id]/correct/route.ts | 15 +- .../runs/[id]/employees/[employeeId]/route.ts | 33 +- app/api/salary/runs/[id]/employees/route.ts | 102 +- .../lines/[lineId]/__tests__/route.test.ts | 5 + .../salary/runs/[id]/lines/[lineId]/route.ts | 74 +- app/api/salary/runs/[id]/lines/route.ts | 71 +- app/api/salary/vacation-balances/route.ts | 49 + app/api/salary/vacation-year-close/route.ts | 76 ++ app/api/settings/__tests__/route.test.ts | 44 + app/api/settings/route.ts | 31 +- .../[id]/absence/__tests__/route.test.ts | 405 ++++++++ .../employees/[id]/absence/route.ts | 362 +++++++ .../opening-balances/__tests__/route.test.ts | 518 ++++++++++ .../employees/[id]/opening-balances/route.ts | 213 +++++ .../[companyId]/employees/[id]/route.ts | 57 +- .../vacation-balance/__tests__/route.test.ts | 179 ++++ .../employees/[id]/vacation-balance/route.ts | 174 ++++ .../employees/__tests__/route.test.ts | 156 +++ .../employees/opening-balances/route.ts | 126 +++ .../companies/[companyId]/employees/route.ts | 5 + .../[id]/mark-paid/__tests__/route.test.ts | 44 + .../invoices/[id]/mark-paid/route.ts | 15 +- .../salary-runs/[id]/book/route.ts | 12 + .../employees/[employeeId]/lines/route.ts | 150 +++ .../[id]/employees/[employeeId]/route.ts | 301 ++++++ .../[id]/employees/__tests__/route.test.ts | 550 +++++++++++ .../salary-runs/[id]/employees/route.ts | 355 +++++++ .../salary-runs/[id]/lines/[lineId]/route.ts | 227 +++++ .../[id]/lines/__tests__/route.test.ts | 439 +++++++++ .../[employeeId]/pdf/__tests__/route.test.ts | 133 +++ .../[id]/payslips/[employeeId]/pdf/route.ts | 153 +++ .../[id]/payslips/__tests__/pdf.route.test.ts | 279 ++++++ .../[companyId]/salary-runs/[id]/route.ts | 2 +- .../__tests__/route.test.ts | 242 +++++ .../salary/vacation-year-close/route.ts | 146 +++ app/layout.tsx | 13 +- components/agent/AgentChat.tsx | 15 +- components/agent/MarkdownMessage.tsx | 14 + components/common/CommandPalette.tsx | 7 +- components/common/LazyCommandPalette.tsx | 31 + components/dashboard/DashboardNav.tsx | 103 +- components/invoices/PaymentBookingDialog.tsx | 5 +- components/providers/SWRProvider.tsx | 29 + components/salary/AGIPanel.tsx | 642 +++++++++---- components/salary/NewEmployeeDialog.tsx | 8 + components/salary/OpeningBalancesPanel.tsx | 271 ++++++ components/salary/VacationBalanceCard.tsx | 238 +++++ components/salary/run/RunProgressBar.tsx | 32 +- components/settings/useSettings.ts | 87 +- .../__tests__/connect-cleanup.test.ts | 199 ++++ .../__tests__/session-expired.test.ts | 5 + .../components/BankingSettingsPanel.tsx | 28 +- extensions/general/enable-banking/index.ts | 35 +- .../__tests__/payload-size.bench.test.ts | 15 +- .../__tests__/payroll-read-tools.test.ts | 261 +++++ .../__tests__/payroll-staged-tools.test.ts | 430 +++++++++ .../__tests__/staging-pii-guard.test.ts | 80 ++ extensions/general/mcp-server/server.ts | 788 ++++++++++++++++ .../general/mcp-server/staging-pii-guard.ts | 76 ++ .../skatteverket/lib/declaration-prep.ts | 2 +- lib/api/schemas.ts | 165 +++- .../__snapshots__/spec-snapshot.test.ts.snap | 18 +- lib/api/v1/load-routes.ts | 20 + lib/api/v1/with-api-v1.ts | 6 +- lib/api/with-route-context.ts | 19 + lib/auth/api-keys.ts | 34 + lib/auth/scopes.ts | 24 + .../__tests__/propose-payment-lines.test.ts | 112 +++ lib/bookkeeping/propose-payment-lines.ts | 55 +- lib/company/__tests__/context.test.ts | 81 +- lib/company/context.ts | 49 +- .../content/cookbook/run-payroll-and-agi.ts | 4 +- lib/errors/structured-errors.ts | 60 ++ lib/hooks/use-agi-submission.ts | 42 + lib/hooks/use-worklist-badges.ts | 56 ++ .../__tests__/apply-invoice-payment.test.ts | 181 ++++ .../recurring-schedule-service.test.ts | 260 ++++- .../__tests__/settle-invoice-payment.test.ts | 147 +++ lib/invoices/apply-invoice-payment.ts | 61 +- lib/invoices/recurring-schedule-service.ts | 64 +- lib/invoices/settle-invoice-payment.ts | 16 +- .../__tests__/payroll-executors.test.ts | 437 +++++++++ lib/pending-operations/commit.ts | 264 ++++++ lib/pending-operations/risk-tiers.ts | 21 + .../vacation-liability-opening.test.ts | 179 ++++ lib/reports/__tests__/vat-declaration.test.ts | 888 ++++++------------ lib/reports/__tests__/vat-settlement.test.ts | 181 ++-- lib/reports/full-archive-export.ts | 8 + lib/reports/vacation-liability.ts | 106 ++- lib/reports/vat-declaration.ts | 117 +-- lib/salary/__tests__/absence.test.ts | 243 +++++ .../__tests__/agi-submission-state.test.ts | 48 + .../__tests__/calculation-engine.test.ts | 45 +- .../derive-absence-line-items.test.ts | 55 ++ lib/salary/__tests__/payslip-lines.test.ts | 264 ++++++ lib/salary/__tests__/personnummer.test.ts | 14 +- lib/salary/__tests__/run-employees.test.ts | 219 +++++ .../__tests__/semesterberedning.test.ts | 353 +++++++ lib/salary/__tests__/vacation-ledger.test.ts | 181 ++++ .../__tests__/work-schedule-threading.test.ts | 104 ++ lib/salary/__tests__/work-schedule.test.ts | 47 + lib/salary/absence-calculator.ts | 21 +- lib/salary/absence.ts | 301 ++++++ lib/salary/agi-submission-state.ts | 57 ++ lib/salary/calculation-engine.ts | 19 +- lib/salary/derive-absence-line-items.ts | 30 +- lib/salary/employee-commands.ts | 297 ++++++ lib/salary/opening-balances.ts | 314 +++++++ lib/salary/payslip-lines.ts | 281 ++++++ lib/salary/personnummer.ts | 13 +- lib/salary/run-calculation.ts | 101 +- lib/salary/run-employees.ts | 231 +++++ lib/salary/semesterberedning.ts | 564 +++++++++++ lib/salary/vacation-ledger.ts | 243 +++++ lib/salary/vacation-year.ts | 42 + lib/salary/work-schedule.ts | 44 + messages/en.json | 82 +- messages/sv.json | 80 +- package-lock.json | 53 ++ package.json | 2 + scripts/checks/antipatterns-baseline.json | 2 +- ...operations_add_payroll_gap_closure_ops.sql | 83 ++ ...260713101000_employee_opening_balances.sql | 121 +++ ...20260713110000_employees_work_schedule.sql | 26 + ...60713120000_vat_declaration_totals_rpc.sql | 125 +++ ...ing_operations_add_vacation_year_close.sql | 73 ++ .../20260713122000_vacation_ledger.sql | 102 ++ ...idate_pending_operations_op_type_check.sql | 14 + tests/pg/employee-opening-balances.pg.test.ts | 202 ++++ .../pg/employee-vacation-balances.pg.test.ts | 180 ++++ .../pg/vat-declaration-totals-rpc.pg.test.ts | 327 +++++++ types/index.ts | 16 + vercel.json | 3 +- 154 files changed, 18364 insertions(+), 1867 deletions(-) create mode 100644 app/api/extensions/enable-banking/callback/finalize-page.ts create mode 100644 app/api/salary/employees/[id]/opening-balances/route.ts create mode 100644 app/api/salary/vacation-balances/route.ts create mode 100644 app/api/salary/vacation-year-close/route.ts create mode 100644 app/api/v1/companies/[companyId]/employees/[id]/absence/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/employees/[id]/absence/route.ts create mode 100644 app/api/v1/companies/[companyId]/employees/[id]/opening-balances/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/employees/[id]/opening-balances/route.ts create mode 100644 app/api/v1/companies/[companyId]/employees/[id]/vacation-balance/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/employees/[id]/vacation-balance/route.ts create mode 100644 app/api/v1/companies/[companyId]/employees/opening-balances/route.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/employees/[employeeId]/lines/route.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/employees/[employeeId]/route.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/employees/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/employees/route.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/lines/[lineId]/route.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/lines/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/payslips/[employeeId]/pdf/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/payslips/[employeeId]/pdf/route.ts create mode 100644 app/api/v1/companies/[companyId]/salary-runs/[id]/payslips/__tests__/pdf.route.test.ts create mode 100644 app/api/v1/companies/[companyId]/salary/vacation-year-close/__tests__/route.test.ts create mode 100644 app/api/v1/companies/[companyId]/salary/vacation-year-close/route.ts create mode 100644 components/agent/MarkdownMessage.tsx create mode 100644 components/common/LazyCommandPalette.tsx create mode 100644 components/providers/SWRProvider.tsx create mode 100644 components/salary/OpeningBalancesPanel.tsx create mode 100644 components/salary/VacationBalanceCard.tsx create mode 100644 extensions/general/enable-banking/__tests__/connect-cleanup.test.ts create mode 100644 extensions/general/mcp-server/__tests__/payroll-read-tools.test.ts create mode 100644 extensions/general/mcp-server/__tests__/payroll-staged-tools.test.ts create mode 100644 extensions/general/mcp-server/__tests__/staging-pii-guard.test.ts create mode 100644 extensions/general/mcp-server/staging-pii-guard.ts create mode 100644 lib/hooks/use-agi-submission.ts create mode 100644 lib/hooks/use-worklist-badges.ts create mode 100644 lib/pending-operations/__tests__/payroll-executors.test.ts create mode 100644 lib/reports/__tests__/vacation-liability-opening.test.ts create mode 100644 lib/salary/__tests__/absence.test.ts create mode 100644 lib/salary/__tests__/agi-submission-state.test.ts create mode 100644 lib/salary/__tests__/payslip-lines.test.ts create mode 100644 lib/salary/__tests__/run-employees.test.ts create mode 100644 lib/salary/__tests__/semesterberedning.test.ts create mode 100644 lib/salary/__tests__/vacation-ledger.test.ts create mode 100644 lib/salary/__tests__/work-schedule-threading.test.ts create mode 100644 lib/salary/__tests__/work-schedule.test.ts create mode 100644 lib/salary/absence.ts create mode 100644 lib/salary/agi-submission-state.ts create mode 100644 lib/salary/employee-commands.ts create mode 100644 lib/salary/opening-balances.ts create mode 100644 lib/salary/payslip-lines.ts create mode 100644 lib/salary/run-employees.ts create mode 100644 lib/salary/semesterberedning.ts create mode 100644 lib/salary/vacation-ledger.ts create mode 100644 lib/salary/vacation-year.ts create mode 100644 lib/salary/work-schedule.ts create mode 100644 supabase/migrations/20260713100000_pending_operations_add_payroll_gap_closure_ops.sql create mode 100644 supabase/migrations/20260713101000_employee_opening_balances.sql create mode 100644 supabase/migrations/20260713110000_employees_work_schedule.sql create mode 100644 supabase/migrations/20260713120000_vat_declaration_totals_rpc.sql create mode 100644 supabase/migrations/20260713121000_pending_operations_add_vacation_year_close.sql create mode 100644 supabase/migrations/20260713122000_vacation_ledger.sql create mode 100644 supabase/migrations/20260713123000_validate_pending_operations_op_type_check.sql create mode 100644 tests/pg/employee-opening-balances.pg.test.ts create mode 100644 tests/pg/employee-vacation-balances.pg.test.ts create mode 100644 tests/pg/vat-declaration-totals-rpc.pg.test.ts diff --git a/DECISIONS.md b/DECISIONS.md index 2024a601..2666f50f 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -115,3 +115,38 @@ One line per decision: `[YYYY-MM-DD] : `. Appended by agents and [2026-07-13] postMessage hardening uses event.source identity (popup handle in a ref) plus a verified rebroadcast CustomEvent ('skatteverket-connection-updated') instead of the nonce the SOC2 finding suggested: a window reference cannot be forged by same-origin scripts, so the source check is strictly stronger than a nonce threaded through the OAuth flow, and pages that never open the popup (salary dashboard) consume the rebroadcast from the component that did verify it. [2026-07-13] Kvittens cron HTTP response drops companyId per row (GDPR minimization) but keeps declarationId: it is an opaque UUID useless without DB access, the endpoint is cron-secret gated + Cache-Control: no-store, and losing it would make per-run ops debugging blind. The extension_data delete race flagged by the swarm is documented-and-accepted: the agi_submission_ key is period-scoped by design and agi_declarations is UNIQUE per company+period, so no two declarations share a key. [2026-07-13] signeradAv (personnummer in agi_declarations.response_data) is documented in .compliance/ropa.yaml under the existing agi.submit entry (Art.6(1)(c), BFL 7 kap 2 par retention) rather than moved to a dedicated column with column-level grants: it is part of the SKV kvittens payload preserved verbatim as rakenskapsinformation, and submitted_by is now explicitly documented as the technical submitter with response_data.signeradAv as the authoritative legal signatory. +[2026-07-13] One-click AGI submission ("Lamna in till Skatteverket") orchestrates the existing panel endpoints client-side (xml -> submit -> kontrollresultat -> granskningsunderlag) instead of reusing the server-side commitSubmitAgi chain: the MCP commit path carries pending-operation semantics (audit rows, monotonic flips, recoverable codes) that the interactive UI does not want to re-plumb, and the client chain preserves the panel's existing per-step error surfaces. Signing tab is opened synchronously at click (placeholder) and navigated on success to dodge popup blockers. +[2026-07-13] Dashboard invoice send route rejects non-drafts (409 INVOICE_ALREADY_SENT) and gates JE/archive/event on winning an optimistic-locked draft->sent flip; on a flip DB error the JE is now DEFERRED (previously posted anyway, and v1 still posts): with the row left in draft, a retry re-runs the pipeline and ends with exactly one verifikat, whereas booking on a failed flip sets up a duplicate JE on retry. Cost: a duplicate customer email on retry, judged cheaper than duplicate revenue. +[2026-07-13] Enable Banking OAuth callback streams an interim "Slutfor bankanslutningen" HTML page (shell first, work, then script/meta redirect) instead of redirecting to settings and finalizing via a client-called endpoint: keeps the one-time authorization code server-side in a single round trip, needs no new endpoint or polling, and the global CSP already permits inline script. The blank-tab gap during createSession + cash-account mirroring was the reported "no loading state after redirect". +[2026-07-13] Failed bank-connect attempts that never activated (status pending/error, no session_id, no accounts_data) are DELETED, not parked as status=error: parked rows rendered forever as "Atgard kravs" cards next to a successful retry, showing duplicate connections to the same bank. Deletion is safe (transactions/cash_accounts FKs are ON DELETE SET NULL; never-activated rows have no dependents) and the stale-pending cron already deletes such rows. Established connections keep the error/expired card via the accounts_data guard. +[2026-07-13] Recurring auto-send sandbox enforcement lives inside sendInvoiceFromSchedule (isSandboxCompany at the email chokepoint, freeze-and-retain: invoice still created as draft) instead of route-level guardSandbox on run-now/create: run-now legitimately generates invoices in the sandbox, only the outbound email is forbidden, and one guard at the chokepoint covers both cron and run-now. Cron failure warnings overwrite (not append to) last_run_warning; the stale roll-forward message wins over the per-attempt failure detail because it carries the actionable state (skipped date + next run + "Skapa faktura nu" hint). +[2026-07-13] Payroll gap-closure: personnummer stays MASKED on the v1 payslip detail endpoint (deviation from the "full value on detail" convention): a payslip is a pay document, not an identity record; the employee master GET remains the only full-pnr drill-in. On MCP, personnummer is masked on EVERY tool (LLM context is a leak surface), incl. encrypt-at-staging for create_employee so pending_operations.params never persists plaintext. +[2026-07-13] Absence v1 API is range-in/per-day-storage: PUT expands [from,to] server-side (weekends skipped by default, 92-day cap) onto the (employee,date,type) natural key. Per-day rows are non-negotiable (karens/aterinsjuknande/hogriskskydd + AGI Franvarouppgift derive from dates); the range payload is pure ergonomics. PUT added to the v1 wrapper's REQUIRES_IDEMPOTENCY set: without it test keys would write through PUT for real. +[2026-07-13] UpdateEmployeeSchema rebuilt on a defaults-stripped base (EmployeeSchemaPatchBase): Zod 4 applies .default() through .partial(), so any sparse PATCH body materialized salary_type='monthly' and failed the byte-till-loneform refinement (latent bug: first surfaced by jamkning-only patches), and routes spreading the parsed body silently reset defaulted columns. +[2026-07-13] Scope-map audit retrofit ships accept-the-break (Emil 2026-07-13): 4 previously unmapped write tools (link_invoice_to_voucher, undo_sie_import, post_annual_depreciation, import_rot_rut_beslut) now require their scopes; keys relying on the default-allow hole lose access. No grandfathering migration (unlike gnubok_remember_fact): these were security holes, not granted capabilities. Release-note callout required. +[2026-07-13] employee_opening_balances lock is DERIVED (trigger checks for a booked run), not a locked_at flag: cannot drift, needs no hook in the two book routes, and self-unlocks when the only booked run is corrected, which is exactly when re-editing cutover state is legitimate. Ongoing sick cases get NO dedicated fields: imported pre-cutover salary_absence_days rows reconstruct segments exactly; only the karens-period count not covered by imports is a field (over-suppression of karens is the softer error). +[2026-07-13] Opening-balances bulk PUT is atomic all-or-nothing (validate every item, 400 with per-item errors and zero writes) rather than 207 partial: byra onboarding wants "all imported or fix the file"; partial success forces the caller to diff. Cutover YTD merges into the engine's ytdByEmployee for display/reports only: verified that AGI is per-run and youth/vaxa avgifter caps are per-month, so no calculation reads YTD. +[2026-07-13] runSalaryCalculation opening-balance merge has no dedicated unit test (no existing mock harness for the full orchestrator; building one is ~15 brittle queued queries): covered by type-check + the pure-function karens tests + vacation-liability tests; the pg-real suite and the E2E cutover smoke are the integration net. +[2026-07-13] MCP tools/list payload ceiling bumped 45.5K -> 50K for the 8 payroll tools: create/update_employee carry the full employee-config schema by design (agent-driveable onboarding is the point); descriptions trimmed to enum-only where self-evident first. +[2026-07-13] Arbetsschema-lite divisors keep the LEGACY constants (173/21) exactly at the default 40h/5d schedule and use the exact 52-week formula only for non-default schedules: switching defaults to exact formulas (173.33/21.67) would shift every running company's monthly-to-hourly derivation ~0.2% and sick/VAB daily deductions ~3% mid-year with zero schedule change. Exact-formula migration deferred to a fiscal-year boundary. Precedence: employment_degree prorates BASE SALARY, hours/workdays per week ONLY drive divisors; deliberately not reconciled. +[2026-07-13] Vacation ledger (employee_vacation_balances) is DAYS-ONLY and RECOMPUTED (never incremented) from booked runs on every book/correct, with lazy seeding from cutover opening balances or the legacy vacation_days_saved (attributed to the previous year: expires earlier, never later). SEK stays derived: persisting a parallel SEK column would create a reconciliation obligation with zero new information. Ledger sync is non-fatal in all three hooks: a ledger bug must never block a legally required booking. +[2026-07-13] Semesterberedning + arsavslut is ONE two-phase verb (dry-run report, then commit), not two: both act on the same year boundary, the review report is only judgeable with both halves, and two verbs would create half-closed states. Days roll books NOTHING (reclassifying days moves no liability); only the 2920/2940 drift adjustment posts, via createJournalEntry with source_type 'salary_payment' + source_id = closure id (no new source_type: avoids a CHECK expansion). Untaken days at/below the 20-day floor are FLAGGED, not auto-saved (Semesterlagen 18 par.); expired 5-year savings become forced_payout_days paid via a normal run. +[2026-07-13] Year-close SEK reconcile uses a day-valued computed liability (simplified BFNAR 2016:10: sammaloneregeln dagslön+tillägg, procentregeln annual basis x 12%/14.4% over entitled days, hourly via hours_per_week) against the trial-balance 2920/2940 closing balances: per-run accruals never relieve 2920 when vacation is taken, so drift accumulates BY DESIGN and the annual adjustment is the correction mechanism. Avgifter on the computed liability use flat 31.42% (per-employee reduced rates called out in the report, not silently applied). vacation_year_closures has NO DELETE policy: the frozen report is the underlag for the adjustment verifikat (BFL 7 kap); reopening is a future explicit feature. +[2026-07-13] company_settings.salary_vacation_year_basis (calendar default | statutory_apr_mar) can only change while ZERO open ledger rows exist (settings PUT guard): rows are keyed by vacation_year_start and a basis flip would orphan them. Settings UI deferred; calendar is right for the segment. +[2026-07-13] Page-load perf: root cause was Vercel functions in iad1 vs Supabase in eu-north-1 (~100ms per DB/auth round trip, measured 530-1900ms for single-query GETs); fix = "regions": ["arn1"] in vercel.json rather than any code-level caching first. Local JWT verification (getClaims + asymmetric keys) deliberately DEFERRED: the region move collapses getUser() to ~1-3ms, so changing auth semantics (revocation window) is not worth it now. +[2026-07-13] VAT declaration aggregation moved into get_vat_declaration_totals RPC (totals + settlement-shape detection + source_type counts in one round trip, SECURITY INVOKER). Account lists stay TS-side parameters (ACCOUNT_RUTA remains the single source of truth; mapping changes must never need a migration). The #984 shape-exclusion unit tests moved to tests/pg/vat-declaration-totals-rpc.pg.test.ts per repo convention (RPC behavior is pg-tested, not mocked). +[2026-07-13] Client data caching: chose SWR over TanStack Query (lighter, fetch-shaped hooks fit the codebase; MIT). Converted useCompanySettings + nav badges; pending page realtime stampede fixed with a 400ms trailing debounce instead of a full SWR rewrite of the page. +[2026-07-13] next-intl message splitting SKIPPED: ~25 of the main pages are client components, so nearly every namespace is needed client-side; pick()-based splitting would save little and risk MISSING_MESSAGE regressions. Real win would be route-level splitting, deferred until more pages are server components. +[2026-07-13] Öresavrundning in mark-paid: absorbing the sub-krona residual is gated on the caller lines actually carrying it on 3740 (planInvoicePaymentForLines); mismatch FALLS BACK to the strict plan instead of rejecting, so deliberate sub-krona partials keep working and no-3740 overshoots keep the pre-change 400. Rejecting outright would have broken the documented v1 partial-payment flow. +[2026-07-13] planInvoicePayment absorb-band boundary fixed to >= 1 kr (exactly-1-kr overshoot used to slip past both the guard and the absorb branch and over-record paid_amount). Supplier mirror planSupplierPayment deliberately NOT touched (same hole exists, reachable via match-supplier-invoice; separate change to keep this diff scoped). v1 match-invoice + MCP match paths still reject öre overshoot on bank matches (their line builders lack 3740); also deferred. +[2026-07-13] Compliance-report V8.2.1 remediation (403 on cross-company v1 access) REJECTED in favor of the existing 404: withApiV1 already enforces key-user-to-URL-company membership, and 404 deliberately avoids leaking which company ids exist. Pinned with route-level tests on the payslip PDF endpoint instead. +[2026-07-13] CSP unsafe-inline (ASVS V3.3): fixed with a per-request nonce CSP on the enable-banking finalize page (mirrors mcp-oauth consent page); removing 'unsafe-inline' from the GLOBAL next.config script-src is deferred, it requires an app-wide middleware nonce pipeline covering the Next.js bootstrap plus recapt/Enable Banking scripts and carries real breakage risk. +[2026-07-13] Recurring-invoice sandbox defence-in-depth: cron and run-now routes now resolve isSandboxCompany themselves and pass an explicit suppressAutoSend flag to executeRecurringSchedule, keeping the internal email chokepoint as the second layer. A route-level guardSandbox 403 was rejected: the cron is cross-company (no single company context) and sandbox schedules must still draft invoices (freeze-and-retain). +[2026-07-13] pending_operations PII chokepoint (ISO 27001 A.8.11): stagePendingOperation now rejects plaintext personnummer-bearing KEYS in params/preview_data. Key-based, not value-based detection: enskild firma org numbers ARE personnummer, so value-pattern matching would false-positive on legitimate counterparty data. +[2026-07-13] Enable-banking callback finalize work decoupled from the response stream (eager promise + next/server after()) so a client disconnect cannot abort session persistence or the consent_granted audit emit. A persistent outbox/dead-letter for audit events was rejected as disproportionate; failed emits now log through the structured logger for alerting (A.8.15). +[2026-07-13] Declined CodeRabbit suggestion to rewrite migration 20260713100000 (pending_operations CHECK) as NOT VALID + VALIDATE: the migration is already committed (2084a756) and applied to staging, and modifying shipped migrations is forbidden; pending_operations is small enough that the brief lock is a non-issue. +[2026-07-13] Vacation year close: 2940 target now uses per-employee age-tier avgifter (0% born <=1937, 10.21% fyllt 67 vid årets ingång at the settlement year, else 31.42%) instead of flat 31.42% (compliance-review finding): per-run accruals already credit 2940 at each employee's actual rate, so a flat target would "correct" a right booked balance to a wrong one for companies with 67+ staff. The temporary youth discount is deliberately NOT provisioned (payment-month- and cap-dependent, expires Sep 2027; the full rate is the prudent target per ÅRL försiktighetsprincipen), so youth accruals show a top-up drift at close. +[2026-07-13] calculateAgeAtYearStart is now birth-year based ((year - 1) - birth year) instead of birthday-inclusive age at Jan 1: Skatteverket applies "vid årets ingång fyllt X" rules as birth-year ranges (2026 youth cohort = born 2003-2007), and the old semantics misclassified employees born exactly on January 1 in both directions (born 2008-01-01 wrongly youth-rated, which AGI validation rejects; born 2003-01-01 wrongly standard-rated; born 1959-01-01 wrongly given the 67+ reduction a year early). +[2026-07-13] employee_opening_balances created_by preserved via read-then-upsert, not a DB trigger: a BEFORE UPDATE trigger would need a new migration for a pure audit concern; the extra select is one indexed query and the lock trigger already backstops races. +[2026-07-13] Opening balances are authoritative for pre-cutover YTD: runSalaryCalculation now excludes booked runs before the cutover month from the YTD aggregation for employees with opening balances, instead of blocking pre-cutover backdated runs (backfill of history is a supported flow). +[2026-07-13] Superseded the 2026-07-13 decline of the NOT VALID suggestion for migration 20260713100000: Emil asked to resolve the PR findings, and the migration is branch-only (verified absent from prod schema_migrations), so the never-modify-shipped-migrations rule does not apply; staging already recorded the versions, so edits only change what prod runs at merge. Implemented as ADD ... NOT VALID in 20260713100000 + 20260713121000 with VALIDATE split into 20260713123000: VALIDATE in the same transaction as ADD would be a no-op since Postgres holds the ACCESS EXCLUSIVE lock until commit; a separate migration file gets its own transaction and validates under SHARE UPDATE EXCLUSIVE. 20260713123000 applied to staging (no-op VALIDATE) and version recorded. diff --git a/app/(dashboard)/layout.tsx b/app/(dashboard)/layout.tsx index f2dfbd7a..9222e863 100644 --- a/app/(dashboard)/layout.tsx +++ b/app/(dashboard)/layout.tsx @@ -7,7 +7,7 @@ import CompanyTabSync from '@/components/dashboard/CompanyTabSync' import { RecaptIdentify } from '@/components/RecaptIdentify' import { AgentSheetProvider } from '@/components/agent/AgentSheetProvider' import AgentTrigger from '@/components/agent/AgentTrigger' -import CommandPalette from '@/components/common/CommandPalette' +import LazyCommandPalette from '@/components/common/LazyCommandPalette' import { SettingsHotkey } from '@/components/settings/SettingsHotkey' import { SandboxBanner } from '@/components/dashboard/SandboxBanner' import { getExtensionNavItems } from '@/lib/extensions/sectors' @@ -16,7 +16,6 @@ import { getActiveCompanyId } from '@/lib/company/context' import { getCompanyEntitlements } from '@/lib/entitlements/has-capability' import { getBranding } from '@/lib/branding/service' import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent' -import { countPendingOperations, countUnbookedTransactions } from '@/lib/worklist' import type { EntityType, CompanyRole, Team } from '@/types' /** @@ -99,8 +98,6 @@ export default async function DashboardLayout({ @@ -131,8 +128,6 @@ export default async function DashboardLayout({ { data: memberRow }, { data: allMemberships }, { data: settings }, - uncategorizedCount, - pendingOpsCount, { data: agentProfileIdentity }, { data: userProfile }, entitlements, @@ -146,11 +141,10 @@ export default async function DashboardLayout({ .select('company_name, onboarding_complete, entity_type, pays_salaries, is_sandbox, dimensions_enabled') .eq('company_id', companyId) .single(), - // Shared worklist predicates (lib/worklist), the badge must show the - // same number as every other "att göra" surface. Notably this excludes - // is_ignored rows, which the old inline query here did not. - countUnbookedTransactions(supabase, companyId), - countPendingOperations(supabase, companyId), + // Nav badge counts (unbooked transactions, pending operations) are NOT + // fetched here anymore: DashboardNav loads them client-side after mount + // (lib/hooks/use-worklist-badges) so two head-count queries stop blocking + // first paint on every dashboard navigation. // Agent identity, name + avatar, surfaced on the FAB and chat // surfaces. Null when no agent_profile exists yet (banner CTA path). supabase @@ -203,8 +197,6 @@ export default async function DashboardLayout({ @@ -311,8 +303,6 @@ export default async function DashboardLayout({ entityType={entityType} paysSalaries={paysSalaries} dimensionsEnabled={dimensionsEnabled} - uncategorizedTransactionCount={uncategorizedCount} - pendingOperationsCount={pendingOpsCount} isSandbox={isSandbox} extensionNavItems={getExtensionNavItems()} userName={userProfile?.full_name ?? null} @@ -322,7 +312,7 @@ export default async function DashboardLayout({ {children} - + {settingsModal} diff --git a/app/(dashboard)/pending/page.tsx b/app/(dashboard)/pending/page.tsx index 74f17df8..abc2ad0d 100644 --- a/app/(dashboard)/pending/page.tsx +++ b/app/(dashboard)/pending/page.tsx @@ -714,20 +714,28 @@ export default function PendingOperationsPage() { // in-place) so server-side filtering, sorting, and computed fields stay in // sync with whatever the API route returned. The counts endpoint isn't // pushed by the same trigger, so we also refresh counts on every change. + // Trailing debounce: bulk actions emit one event per row, which previously + // stampeded 4 requests per event (list + 3 counts); the burst now collapses + // into a single refetch after the last event. useEffect(() => { const supabase = createClient() + let debounce: ReturnType | null = null const channel = supabase .channel('pending_operations:list') .on( 'postgres_changes', { event: '*', schema: 'public', table: 'pending_operations' }, () => { - fetchOperations() - fetchAllCounts() + if (debounce) clearTimeout(debounce) + debounce = setTimeout(() => { + fetchOperations() + fetchAllCounts() + }, 400) } ) .subscribe() return () => { + if (debounce) clearTimeout(debounce) void supabase.removeChannel(channel) } }, [fetchOperations, fetchAllCounts]) diff --git a/app/(dashboard)/salary/employees/[id]/page.tsx b/app/(dashboard)/salary/employees/[id]/page.tsx index c4cc9c5f..baed7e54 100644 --- a/app/(dashboard)/salary/employees/[id]/page.tsx +++ b/app/(dashboard)/salary/employees/[id]/page.tsx @@ -24,6 +24,7 @@ import { } from '@/lib/salary/payment/bank-account' import type { Employee } from '@/types' import { EmployeeBenefitsPanel } from '@/components/salary/EmployeeBenefitsPanel' +import { OpeningBalancesPanel } from '@/components/salary/OpeningBalancesPanel' import EmployeeTaxCard, { type EmployeeTaxValue } from '@/components/salary/EmployeeTaxCard' import LineDimensionFields from '@/components/dimensions/LineDimensionFields' @@ -124,12 +125,18 @@ export default function EmployeeDetailPage({ params }: { params: Promise<{ id: s employment_type: employmentType, employment_start: form.get('employment_start') as string || undefined, employment_end: form.get('employment_end') as string || undefined, - employment_degree: parseFloat(form.get('employment_degree') as string) || 100, + // Sparse patch: an empty/cleared field is OMITTED (undefined keys are + // dropped by JSON.stringify) so the server's patch schema leaves the + // column unchanged. Hardcoded fallbacks here would silently reset real + // DB values on submit. + employment_degree: parseFloat(form.get('employment_degree') as string) || undefined, + hours_per_week: parseFloat(form.get('hours_per_week') as string) || undefined, + workdays_per_week: parseFloat(form.get('workdays_per_week') as string) || undefined, salary_type: salaryType, f_skatt_status: tax?.f_skatt_status, is_sidoinkomst: tax?.is_sidoinkomst, tax_table_number: tax?.tax_table_number ?? undefined, - tax_column: tax?.tax_column ?? 1, + tax_column: tax?.tax_column ?? undefined, tax_municipality: tax?.tax_municipality || undefined, email: form.get('email') as string || undefined, phone: form.get('phone') as string || undefined, @@ -139,7 +146,7 @@ export default function EmployeeDetailPage({ params }: { params: Promise<{ id: s clearing_number: normalizeBankNumber(clearing) || undefined, bank_account_number: normalizeBankNumber(account) || undefined, vacation_rule: vacationRule, - vacation_days_per_year: parseInt(form.get('vacation_days_per_year') as string) || 25, + vacation_days_per_year: parseInt(form.get('vacation_days_per_year') as string) || undefined, // Always sent: {} clears the employee's default dimensions. default_dimensions: dimensions, } @@ -291,6 +298,15 @@ export default function EmployeeDetailPage({ params }: { params: Promise<{ id: s +
+ + +

{t('form_work_schedule_hint')}

+
+
+ + +