From 32d9978f1be21b6d2877d866177146433081b326 Mon Sep 17 00:00:00 2001 From: Mattsson <111893710+mattssonn@users.noreply.github.com> Date: Tue, 26 May 2026 22:29:41 +0200 Subject: [PATCH] Fix/chrome pdf preview csp (#572) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add option to exclude year-end closing entries in SIE export and related reports * delete docs * fix: allow Chrome's PDF viewer in verifikat document preview The /api/documents/:id/inline route shipped with `object-src 'none'` in its CSP, which blocked Chrome's built-in PDF viewer (it renders inline PDFs via an internal ). Users on Chrome saw "Det här innehållet har blockerats" when expanding a PDF attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own viewer) were unaffected, and JPGs worked because isn't subject to object-src. Drops the CSP for this route to the minimum needed for embeddability: `frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the fixed Content-Type from the handler already block MIME confusion; X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking. Co-Authored-By: Claude Opus 4.7 (1M context) * feat(auth): add webmail deep link to email confirmation screens Mirrors Stripe's signup UX: after asking the user to verify their email, detect their webmail provider from the domain and show a button that opens the inbox in a new tab. Gmail gets a from: search pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly. Unknown / custom domains fall back to the existing copy. Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM (default noreply@gnubok.se) so white-label installs can match their Supabase Auth SMTP config. Co-Authored-By: Claude Opus 4.7 (1M context) * fix(auth): unblock first-time password set for BankID users with MFA Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session is required" whenever a TOTP factor is enrolled. BankID magic-link logins produce AAL1, and middleware skips MFA enforcement for bankid_linked users, so they had no path to AAL2 — leaving them unable to set a backup password or disable MFA without going through the email-recovery escape hatch. - /api/account/password: branch on app_metadata.has_password. First-time set writes via service.auth.admin.updateUserById (no existing credential to protect, AAL2 guard does not apply). Change-password keeps the user-session updateUser so AAL2 still fires for credential rotation. - /mfa/verify: accept a safeReturnTo query param and route there after successful verify, so step-up flows can land back where they came from. - SecuritySettings: detect the AAL2 error from both change-password and mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account instead of toasting a dead-end error. Co-Authored-By: Claude Opus 4.7 (1M context) * Add tests and rounding utility for öre precision in bokslut calculations - Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations. - Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries. - Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency. - Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies. - Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios. * fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility * fix: enhance security by rejecting data URIs in safeReturnTo function tests * fix: improve rounding logic in roundOre function and add customer_type migration * fix: add customer_type column to customers and enforce CHECK constraint --------- Co-authored-by: Claude Opus 4.7 (1M context) --- WHITELABEL.md | 1 + app/(auth)/login/page.tsx | 39 +- app/(auth)/mfa/verify/page.tsx | 22 +- app/(auth)/register/page.tsx | 29 +- app/(dashboard)/assets/[id]/dispose/page.tsx | 574 ++++++++++ app/(dashboard)/assets/page.tsx | 18 +- app/(dashboard)/bookkeeping/[id]/page.tsx | 11 +- app/(dashboard)/bookkeeping/page.tsx | 3 +- .../year-end/arsredovisning/page.tsx | 60 +- .../year-end/periodisering/page.tsx | 997 ++++++++++++++++++ app/(dashboard)/import/page.tsx | 2 +- app/(dashboard)/invoices/new/page.tsx | 286 ++++- app/(dashboard)/invoices/page.tsx | 8 +- app/(dashboard)/layout.tsx | 2 +- app/(dashboard)/pending/page.tsx | 43 +- .../KassaflodesanalysClient.tsx | 326 ++++++ .../reports/kassaflodesanalys/page.tsx | 10 + app/(dashboard)/reports/page.tsx | 608 +++++++++-- .../runs/[id]/employees/[employeeId]/page.tsx | 6 + app/(dashboard)/settings/bookkeeping/page.tsx | 39 +- app/(dashboard)/settings/layout.tsx | 1 + app/(dashboard)/skattekonto/page.tsx | 10 +- app/(public)/invoice-action/[token]/page.tsx | 49 +- .../account/password/__tests__/route.test.ts | 264 ++++- app/api/account/password/route.ts | 48 +- app/api/assets/[id]/dispose/route.ts | 90 +- app/api/assets/[id]/route.ts | 119 ++- app/api/assets/route.ts | 117 +- .../[id]/accruals/__tests__/route.test.ts | 104 ++ .../fiscal-periods/[id]/accruals/route.ts | 92 +- .../[id]/arsredovisning/pdf/route.ts | 11 +- .../[id]/bokslutsdispositioner/route.ts | 22 +- app/api/bookkeeping/journal-entries/route.ts | 22 +- app/api/company/current/route.ts | 157 ++- .../documents/[id]/__tests__/route.test.ts | 154 +++ app/api/documents/[id]/route.ts | 44 + app/api/import/sie/[id]/replace/route.ts | 6 +- .../[id]/mark-sent/__tests__/route.test.ts | 1 + app/api/invoices/[id]/mark-sent/route.ts | 6 +- app/api/invoices/[id]/pdf/route.ts | 3 + .../[id]/send/__tests__/route.test.ts | 1 + app/api/invoices/[id]/send/route.ts | 8 +- app/api/invoices/next-number/route.ts | 2 +- app/api/invoices/preview-pdf/route.ts | 3 + app/api/invoices/reminders/action/route.ts | 21 +- app/api/invoices/route.ts | 93 +- .../invoices/__tests__/route.test.ts | 156 +++ .../customer/[customerId]/invoices/route.ts | 152 +++ app/api/reports/ar-ledger/xlsx/route.ts | 163 +++ app/api/reports/balance-sheet/xlsx/route.ts | 153 +++ app/api/reports/balansrapport/xlsx/route.ts | 117 ++ app/api/reports/general-ledger/xlsx/route.ts | 144 +++ .../reports/income-statement/xlsx/route.ts | 156 +++ .../reports/journal-register/xlsx/route.ts | 119 +++ .../reports/kassaflodesanalys/pdf/route.ts | 80 ++ app/api/reports/kassaflodesanalys/route.ts | 32 + app/api/reports/kpi/xlsx/route.ts | 256 +++++ .../reports/monthly-breakdown/xlsx/route.ts | 77 ++ app/api/reports/resultatrapport/xlsx/route.ts | 111 ++ app/api/reports/salary-journal/xlsx/route.ts | 113 ++ .../invoices/__tests__/route.test.ts | 151 +++ .../supplier/[supplierId]/invoices/route.ts | 143 +++ app/api/reports/supplier-ledger/xlsx/route.ts | 96 ++ .../sources/__tests__/route.test.ts | 163 +++ .../account/[accountNumber]/sources/route.ts | 138 +++ app/api/reports/trial-balance/xlsx/route.ts | 94 ++ .../[ruta]/sources/__tests__/route.test.ts | 120 +++ .../ruta/[ruta]/sources/route.ts | 167 +++ app/api/reports/vat-declaration/xlsx/route.ts | 116 ++ .../invoices/[id]/pdf/__tests__/route.test.ts | 1 + .../[companyId]/invoices/[id]/pdf/route.ts | 3 + .../[id]/send/__tests__/route.test.ts | 1 + .../[companyId]/invoices/[id]/send/route.ts | 5 + .../bookkeeping/AttachmentPreviewSheet.tsx | 230 +++- components/bookkeeping/CorrectionChain.tsx | 3 +- .../bookkeeping/CorrectionEntryDialog.tsx | 3 +- .../bookkeeping/JournalEntryAttachments.tsx | 286 +++-- components/bookkeeping/JournalEntryForm.tsx | 20 +- components/bookkeeping/JournalEntryList.tsx | 27 +- .../bookkeeping/JournalEntryStatusBadge.tsx | 1 + .../bookkeeping/assets/CreateAssetDialog.tsx | 367 ++++++- .../bookkeeping/year-end/DispositionsStep.tsx | 4 + .../year-end/EfDeclarationSection.tsx | 297 ++++-- .../bookkeeping/year-end/ResultStep.tsx | 216 +++- .../general/ArcimMigrationWorkspace.tsx | 6 +- .../extensions/general/BookDirectlyDialog.tsx | 3 +- components/reports/BankReconciliationView.tsx | 7 +- components/reports/ReportRowExpansion.tsx | 307 ++++++ components/reports/ReportsNav.tsx | 2 + .../settings/AccountingFrameworkForm.tsx | 179 ++++ components/settings/PdfPrintSettings.tsx | 124 ++- .../PeriodiseringAutoDetectToggle.tsx | 108 ++ components/settings/SecuritySettings.tsx | 17 + components/settings/SettingsSidebar.tsx | 1 + .../VoucherSeriesPerSourceTypeForm.tsx | 168 +++ .../skattekonto/SkattekontoMatchDialog.tsx | 5 +- .../transactions/SkattekontoInboxCard.tsx | 6 +- .../__tests__/receipt-matcher.test.ts | 1 + lib/api/schemas.ts | 202 +++- lib/auth/__tests__/safe-return-to.test.ts | 5 + lib/auth/__tests__/webmail-search.test.ts | 78 ++ lib/auth/webmail-search.ts | 129 +++ .../__tests__/accrual-detector.test.ts | 68 ++ lib/bokslut/__tests__/asset-service.test.ts | 7 + .../__tests__/depreciation-engine.test.ts | 184 ++++ .../k3-framework-dispositions.test.ts | 257 +++++ .../__tests__/latent-tax-calculator.test.ts | 96 ++ lib/bokslut/__tests__/rounding.test.ts | 65 ++ .../accruals/__tests__/auto-detect.test.ts | 244 +++++ .../__tests__/date-range-parser.test.ts | 133 +++ lib/bokslut/accruals/accrual-detector.ts | 116 ++ lib/bokslut/accruals/auto-detect.ts | 254 +++++ lib/bokslut/accruals/date-range-parser.ts | 177 ++++ lib/bokslut/accruals/templates.ts | 163 +++ lib/bokslut/accruals/types.ts | 3 + .../__tests__/arsredovisning-k3-pdf.test.ts | 185 ++++ .../__tests__/arsredovisning-k3.test.ts | 390 +++++++ .../__tests__/k3-noter-builder.test.ts | 385 +++++++ .../arsredovisning/arsredovisning-k3-pdf.tsx | 530 ++++++++++ lib/bokslut/arsredovisning/build-data.ts | 397 ++++++- .../arsredovisning/k3-noter-builder.ts | 344 ++++++ lib/bokslut/arsredovisning/types.ts | 59 ++ .../assets/__tests__/dispose-vat.test.ts | 436 ++++++++ lib/bokslut/assets/__tests__/jamkning.test.ts | 205 ++++ .../assets/__tests__/k3-components.test.ts | 393 +++++++ lib/bokslut/assets/asset-service.ts | 348 +++++- lib/bokslut/assets/depreciation-engine.ts | 195 +++- lib/bokslut/assets/jamkning.ts | 190 ++++ lib/bokslut/assets/k3-components.ts | 99 ++ lib/bokslut/dispositions-proposal-builder.ts | 121 +++ lib/bokslut/readiness-aggregator.ts | 26 +- lib/bokslut/rounding.ts | 45 + .../tax-provision/latent-tax-calculator.ts | 118 +++ lib/bokslut/types.ts | 1 + .../__tests__/invoice-entries.test.ts | 250 +++++ .../__tests__/reminder-fee-entries.test.ts | 122 +++ .../voucher-series-defaults.pg.test.ts | 92 ++ .../__tests__/voucher-series-resolver.test.ts | 145 +++ lib/bookkeeping/engine.ts | 41 +- lib/bookkeeping/invoice-entries.ts | 90 +- lib/bookkeeping/reminder-fee-entries.ts | 115 ++ lib/bookkeeping/voucher-series-resolver.ts | 100 ++ lib/branding/__tests__/service.test.ts | 4 + lib/branding/service.ts | 7 + .../__tests__/year-end-invariants.pg.test.ts | 156 +++ .../__tests__/year-end-service.test.ts | 1 + lib/core/bookkeeping/year-end-service.ts | 131 ++- lib/core/documents/document-service.ts | 79 ++ .../__tests__/reminder-templates.test.ts | 105 ++ lib/email/invoice-templates.ts | 27 +- lib/email/reminder-templates.ts | 100 +- lib/errors/structured-errors.ts | 60 ++ lib/events/handlers/event-log-handler.ts | 1 + lib/events/types.ts | 1 + .../__tests__/sie-import.replace.pg.test.ts | 268 ++++- lib/import/sie-import.ts | 54 +- lib/import/types.ts | 4 +- lib/invoices/__tests__/contrast-check.test.ts | 85 ++ .../__tests__/late-payment-interest.test.ts | 153 +++ .../__tests__/pdf-template-branding.test.ts | 82 ++ lib/invoices/__tests__/rot-rut-rules.test.ts | 194 ++++ lib/invoices/contrast-check.ts | 80 ++ lib/invoices/late-payment-interest.ts | 155 +++ lib/invoices/pdf-render-helpers.ts | 17 + lib/invoices/pdf-template.tsx | 807 +++++++++----- lib/invoices/recurring-schedule-service.ts | 6 +- lib/invoices/reminder-processor.ts | 87 +- lib/invoices/rot-rut-rules.ts | 189 ++++ lib/pending-operations/commit.ts | 7 +- .../__tests__/continuity-check.test.ts | 4 +- .../__tests__/kassaflodesanalys.test.ts | 390 +++++++ lib/reports/__tests__/source-lines.test.ts | 146 +++ lib/reports/__tests__/xlsx-export.test.ts | 235 +++++ lib/reports/continuity-check.ts | 20 +- .../kassaflodesanalys-pdf-template.tsx | 393 +++++++ lib/reports/kassaflodesanalys.ts | 347 ++++++ lib/reports/source-lines.ts | 93 ++ lib/reports/xlsx-export.ts | 250 +++++ .../__tests__/calculation-engine.test.ts | 60 ++ .../__tests__/shift-premium-engine.test.ts | 417 ++++++++ lib/salary/account-mapping.ts | 8 + lib/salary/calculation-engine.ts | 12 +- lib/salary/run-calculation.ts | 150 ++- lib/salary/shift-premium-engine.ts | 319 ++++++ lib/tax/swedish-holidays.ts | 12 + messages/en.json | 316 +++++- messages/sv.json | 316 +++++- next.config.ts | 28 +- .../20260522110000_add_customer_type.sql | 24 + ...22110100_add_invoice_items_vat_columns.sql | 23 + ...000_fix_replace_sie_import_hard_delete.sql | 173 +++ .../20260526120100_restvardeavskrivning.sql | 62 ++ .../20260526120200_invoice_branding.sql | 41 + ...0526120300_asset_disposal_vat_jamkning.sql | 59 ++ ...120400_drojsmalsranta_paminnelseavgift.sql | 90 ++ ...20260526120700_voucher_series_defaults.sql | 42 + .../20260526120900_ob_overtime_premiums.sql | 116 ++ .../20260526121500_k3_framework.sql | 26 + .../migrations/20260526121600_latent_tax.sql | 22 + .../20260526121700_rot_rut_avdrag.sql | 64 ++ ...260526122000_k3_component_depreciation.sql | 36 + .../20260526182000_cap_reminder_fee_at_60.sql | 21 + .../20260526190000_swish_default_off.sql | 20 + tests/helpers.ts | 32 + tests/pg/assets.pg.test.ts | 105 ++ tests/pg/rot-rut-avdrag.pg.test.ts | 180 ++++ types/index.ts | 177 +++- 207 files changed, 24187 insertions(+), 1052 deletions(-) create mode 100644 app/(dashboard)/assets/[id]/dispose/page.tsx create mode 100644 app/(dashboard)/bookkeeping/year-end/periodisering/page.tsx create mode 100644 app/(dashboard)/reports/kassaflodesanalys/KassaflodesanalysClient.tsx create mode 100644 app/(dashboard)/reports/kassaflodesanalys/page.tsx create mode 100644 app/api/bookkeeping/fiscal-periods/[id]/accruals/__tests__/route.test.ts create mode 100644 app/api/documents/[id]/__tests__/route.test.ts create mode 100644 app/api/reports/ar-ledger/customer/[customerId]/invoices/__tests__/route.test.ts create mode 100644 app/api/reports/ar-ledger/customer/[customerId]/invoices/route.ts create mode 100644 app/api/reports/ar-ledger/xlsx/route.ts create mode 100644 app/api/reports/balance-sheet/xlsx/route.ts create mode 100644 app/api/reports/balansrapport/xlsx/route.ts create mode 100644 app/api/reports/general-ledger/xlsx/route.ts create mode 100644 app/api/reports/income-statement/xlsx/route.ts create mode 100644 app/api/reports/journal-register/xlsx/route.ts create mode 100644 app/api/reports/kassaflodesanalys/pdf/route.ts create mode 100644 app/api/reports/kassaflodesanalys/route.ts create mode 100644 app/api/reports/kpi/xlsx/route.ts create mode 100644 app/api/reports/monthly-breakdown/xlsx/route.ts create mode 100644 app/api/reports/resultatrapport/xlsx/route.ts create mode 100644 app/api/reports/salary-journal/xlsx/route.ts create mode 100644 app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/__tests__/route.test.ts create mode 100644 app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/route.ts create mode 100644 app/api/reports/supplier-ledger/xlsx/route.ts create mode 100644 app/api/reports/trial-balance/account/[accountNumber]/sources/__tests__/route.test.ts create mode 100644 app/api/reports/trial-balance/account/[accountNumber]/sources/route.ts create mode 100644 app/api/reports/trial-balance/xlsx/route.ts create mode 100644 app/api/reports/vat-declaration/ruta/[ruta]/sources/__tests__/route.test.ts create mode 100644 app/api/reports/vat-declaration/ruta/[ruta]/sources/route.ts create mode 100644 app/api/reports/vat-declaration/xlsx/route.ts create mode 100644 components/reports/ReportRowExpansion.tsx create mode 100644 components/settings/AccountingFrameworkForm.tsx create mode 100644 components/settings/PeriodiseringAutoDetectToggle.tsx create mode 100644 components/settings/VoucherSeriesPerSourceTypeForm.tsx create mode 100644 lib/auth/__tests__/webmail-search.test.ts create mode 100644 lib/auth/webmail-search.ts create mode 100644 lib/bokslut/__tests__/k3-framework-dispositions.test.ts create mode 100644 lib/bokslut/__tests__/latent-tax-calculator.test.ts create mode 100644 lib/bokslut/__tests__/rounding.test.ts create mode 100644 lib/bokslut/accruals/__tests__/auto-detect.test.ts create mode 100644 lib/bokslut/accruals/__tests__/date-range-parser.test.ts create mode 100644 lib/bokslut/accruals/auto-detect.ts create mode 100644 lib/bokslut/accruals/date-range-parser.ts create mode 100644 lib/bokslut/accruals/templates.ts create mode 100644 lib/bokslut/arsredovisning/__tests__/arsredovisning-k3-pdf.test.ts create mode 100644 lib/bokslut/arsredovisning/__tests__/arsredovisning-k3.test.ts create mode 100644 lib/bokslut/arsredovisning/__tests__/k3-noter-builder.test.ts create mode 100644 lib/bokslut/arsredovisning/arsredovisning-k3-pdf.tsx create mode 100644 lib/bokslut/arsredovisning/k3-noter-builder.ts create mode 100644 lib/bokslut/assets/__tests__/dispose-vat.test.ts create mode 100644 lib/bokslut/assets/__tests__/jamkning.test.ts create mode 100644 lib/bokslut/assets/__tests__/k3-components.test.ts create mode 100644 lib/bokslut/assets/jamkning.ts create mode 100644 lib/bokslut/assets/k3-components.ts create mode 100644 lib/bokslut/rounding.ts create mode 100644 lib/bokslut/tax-provision/latent-tax-calculator.ts create mode 100644 lib/bookkeeping/__tests__/reminder-fee-entries.test.ts create mode 100644 lib/bookkeeping/__tests__/voucher-series-defaults.pg.test.ts create mode 100644 lib/bookkeeping/__tests__/voucher-series-resolver.test.ts create mode 100644 lib/bookkeeping/reminder-fee-entries.ts create mode 100644 lib/bookkeeping/voucher-series-resolver.ts create mode 100644 lib/core/bookkeeping/__tests__/year-end-invariants.pg.test.ts create mode 100644 lib/email/__tests__/reminder-templates.test.ts create mode 100644 lib/invoices/__tests__/contrast-check.test.ts create mode 100644 lib/invoices/__tests__/late-payment-interest.test.ts create mode 100644 lib/invoices/__tests__/pdf-template-branding.test.ts create mode 100644 lib/invoices/__tests__/rot-rut-rules.test.ts create mode 100644 lib/invoices/contrast-check.ts create mode 100644 lib/invoices/late-payment-interest.ts create mode 100644 lib/invoices/pdf-render-helpers.ts create mode 100644 lib/invoices/rot-rut-rules.ts create mode 100644 lib/reports/__tests__/kassaflodesanalys.test.ts create mode 100644 lib/reports/__tests__/source-lines.test.ts create mode 100644 lib/reports/__tests__/xlsx-export.test.ts create mode 100644 lib/reports/kassaflodesanalys-pdf-template.tsx create mode 100644 lib/reports/kassaflodesanalys.ts create mode 100644 lib/reports/source-lines.ts create mode 100644 lib/reports/xlsx-export.ts create mode 100644 lib/salary/__tests__/shift-premium-engine.test.ts create mode 100644 lib/salary/shift-premium-engine.ts create mode 100644 supabase/migrations/20260522110000_add_customer_type.sql create mode 100644 supabase/migrations/20260522110100_add_invoice_items_vat_columns.sql create mode 100644 supabase/migrations/20260526120000_fix_replace_sie_import_hard_delete.sql create mode 100644 supabase/migrations/20260526120100_restvardeavskrivning.sql create mode 100644 supabase/migrations/20260526120200_invoice_branding.sql create mode 100644 supabase/migrations/20260526120300_asset_disposal_vat_jamkning.sql create mode 100644 supabase/migrations/20260526120400_drojsmalsranta_paminnelseavgift.sql create mode 100644 supabase/migrations/20260526120700_voucher_series_defaults.sql create mode 100644 supabase/migrations/20260526120900_ob_overtime_premiums.sql create mode 100644 supabase/migrations/20260526121500_k3_framework.sql create mode 100644 supabase/migrations/20260526121600_latent_tax.sql create mode 100644 supabase/migrations/20260526121700_rot_rut_avdrag.sql create mode 100644 supabase/migrations/20260526122000_k3_component_depreciation.sql create mode 100644 supabase/migrations/20260526182000_cap_reminder_fee_at_60.sql create mode 100644 supabase/migrations/20260526190000_swish_default_off.sql create mode 100644 tests/pg/rot-rut-avdrag.pg.test.ts diff --git a/WHITELABEL.md b/WHITELABEL.md index 6d5adc12..a745e087 100644 --- a/WHITELABEL.md +++ b/WHITELABEL.md @@ -39,6 +39,7 @@ All branding can be set via env vars. Public ones use `NEXT_PUBLIC_BRANDING_*` ( | `BRANDING_SUPPORT_EMAIL` | `supportEmail` | `support@gnubok.se` | | `BRANDING_PRIVACY_EMAIL` | `privacyEmail` | `privacy@gnubok.se` | | `BRANDING_SECURITY_EMAIL` | `securityEmail` | `security@arcim.io` | +| `NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM` | `authEmailFrom` — From address Supabase Auth sends verification / reset emails from. Used to pre-populate the `from:` query on the "open in Gmail" button after signup. Set to whatever you configured in your Supabase Auth SMTP. | `noreply@gnubok.se` | | `NEXT_PUBLIC_APP_URL` | `appUrl` | `https://app.gnubok.se` | | `NEXT_PUBLIC_BRANDING_LOGO_PATH` | `logoPath` | `/gnubokiceon-removebg-preview.png` | | `NEXT_PUBLIC_BRANDING_FAVICON_PATH` | `faviconPath` | `/favicon.ico` | diff --git a/app/(auth)/login/page.tsx b/app/(auth)/login/page.tsx index 37864143..629a1b76 100644 --- a/app/(auth)/login/page.tsx +++ b/app/(auth)/login/page.tsx @@ -9,12 +9,13 @@ import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { useToast } from '@/components/ui/use-toast' -import { Loader2, Mail, ArrowLeft, KeyRound } from 'lucide-react' +import { Loader2, Mail, ArrowLeft, KeyRound, ExternalLink } from 'lucide-react' import Image from 'next/image' import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message' import { isBankIdEnabled } from '@/lib/auth/bankid' import { BankIdAuth } from '@/components/auth/BankIdAuth' import { getBranding } from '@/lib/branding/service' +import { detectWebmailHint } from '@/lib/auth/webmail-search' const branding = getBranding() import type { BankIdResult } from '@/components/auth/BankIdAuth' @@ -249,6 +250,8 @@ function LoginPageContent() { // Email sent confirmation screen if (isEmailSent) { + const webmailHint = detectWebmailHint(email, branding.authEmailFrom) + return (
@@ -279,17 +282,29 @@ function LoginPageContent() {

- +
+ {webmailHint && ( + + )} + +
) diff --git a/app/(auth)/mfa/verify/page.tsx b/app/(auth)/mfa/verify/page.tsx index 6fa1ea07..82391cfe 100644 --- a/app/(auth)/mfa/verify/page.tsx +++ b/app/(auth)/mfa/verify/page.tsx @@ -1,7 +1,7 @@ 'use client' -import { useState, useEffect, useRef } from 'react' -import { useRouter } from 'next/navigation' +import { useState, useEffect, useRef, Suspense } from 'react' +import { useRouter, useSearchParams } from 'next/navigation' import { useTranslations } from 'next-intl' import { createClient } from '@/lib/supabase/client' import { Button } from '@/components/ui/button' @@ -10,8 +10,17 @@ import { Label } from '@/components/ui/label' import { useToast } from '@/components/ui/use-toast' import { Loader2, ShieldCheck, LogOut } from 'lucide-react' import { SupportLink } from '@/components/ui/support-link' +import { safeReturnTo } from '@/lib/auth/safe-return-to' export default function MfaVerifyPage() { + return ( + + + + ) +} + +function MfaVerifyContent() { const t = useTranslations('mfa') const tCommon = useTranslations('common') const [code, setCode] = useState('') @@ -23,8 +32,15 @@ export default function MfaVerifyPage() { const inputRef = useRef(null) const { toast } = useToast() const router = useRouter() + const searchParams = useSearchParams() const supabase = createClient() + // Step-up landing target. Set by callers that need AAL2 to do something + // sensitive (set/change password, unenroll MFA, etc.) — /api/account/password + // and SecuritySettings redirect here when GoTrue rejects with "AAL2 session + // is required". Falls back to the dashboard for direct visits. + const returnTo = safeReturnTo(searchParams.get('returnTo'), '/') + useEffect(() => { async function loadFactor() { const { data } = await supabase.auth.mfa.listFactors() @@ -122,7 +138,7 @@ export default function MfaVerifyPage() { document.cookie = 'gnubok-invite-token=; path=/; max-age=0' } - router.push('/') + router.push(returnTo) router.refresh() } catch { toast({ diff --git a/app/(auth)/register/page.tsx b/app/(auth)/register/page.tsx index 1c595ff8..c1473f0d 100644 --- a/app/(auth)/register/page.tsx +++ b/app/(auth)/register/page.tsx @@ -9,13 +9,14 @@ import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { useToast } from '@/components/ui/use-toast' -import { Loader2, Mail, ArrowLeft } from 'lucide-react' +import { Loader2, Mail, ArrowLeft, ExternalLink } from 'lucide-react' import Image from 'next/image' import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message' import { isBankIdEnabled } from '@/lib/auth/bankid' import { BankIdAuth } from '@/components/auth/BankIdAuth' import type { BankIdResult } from '@/components/auth/BankIdAuth' import { getBranding } from '@/lib/branding/service' +import { detectWebmailHint } from '@/lib/auth/webmail-search' const branding = getBranding() @@ -355,6 +356,8 @@ function RegisterPageContent() { } if (isRegistered) { + const webmailHint = detectWebmailHint(email, branding.authEmailFrom) + return (
@@ -380,12 +383,24 @@ function RegisterPageContent() {

- +
) diff --git a/app/(dashboard)/assets/[id]/dispose/page.tsx b/app/(dashboard)/assets/[id]/dispose/page.tsx new file mode 100644 index 00000000..6db1d047 --- /dev/null +++ b/app/(dashboard)/assets/[id]/dispose/page.tsx @@ -0,0 +1,574 @@ +'use client' + +import { use, useCallback, useEffect, useMemo, useState } from 'react' +import { useRouter } from 'next/navigation' +import Link from 'next/link' +import { ArrowLeft, Loader2, Lock } from 'lucide-react' + +import { Button } from '@/components/ui/button' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { PageHeader } from '@/components/ui/page-header' +import { Switch } from '@/components/ui/switch' +import { Skeleton } from '@/components/ui/skeleton' +import { Badge } from '@/components/ui/badge' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { useToast } from '@/components/ui/use-toast' +import { useCanWrite } from '@/lib/hooks/use-can-write' +import { formatCurrency, formatDate } from '@/lib/utils' +import { getErrorMessage } from '@/lib/errors/get-error-message' +import { + assessJamkningEligibility, + computeJamkningAmount, +} from '@/lib/bokslut/assets/jamkning' +import type { Asset, FiscalPeriod, VatTreatment } from '@/types' + +interface PeriodOption { + id: string + name: string + period_start: string + period_end: string + is_closed: boolean + locked_at: string | null +} + +const VAT_TREATMENT_OPTIONS: { value: VatTreatment; label: string; rate: number | null }[] = [ + { value: 'standard_25', label: 'Standard 25 %', rate: 0.25 }, + { value: 'reduced_12', label: 'Reducerad 12 %', rate: 0.12 }, + { value: 'reduced_6', label: 'Reducerad 6 %', rate: 0.06 }, + { value: 'reverse_charge', label: 'Omvänd skattskyldighet', rate: null }, + { value: 'export', label: 'Export (utanför EU)', rate: null }, + { value: 'exempt', label: 'Momsfri', rate: null }, +] + +function round2(n: number): number { + return Math.round(n * 100) / 100 +} + +export default function DisposeAssetPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = use(params) + const router = useRouter() + const { toast } = useToast() + const { canWrite } = useCanWrite() + + const [asset, setAsset] = useState(null) + const [periods, setPeriods] = useState([]) + const [loading, setLoading] = useState(true) + const [submitting, setSubmitting] = useState(false) + + // Form state + const [disposalDate, setDisposalDate] = useState(() => new Date().toISOString().slice(0, 10)) + const [proceeds, setProceeds] = useState('') + const [vatTreatment, setVatTreatment] = useState('standard_25') + const [vatAmount, setVatAmount] = useState('') + const [vatAutoCalc, setVatAutoCalc] = useState(true) + const [periodId, setPeriodId] = useState('') + const [proceedsAccount, setProceedsAccount] = useState('1930') + + // Jämkning state + const [jamkningEnabled, setJamkningEnabled] = useState(false) + const [originalInputVat, setOriginalInputVat] = useState('') + + // Load asset + periods + useEffect(() => { + let cancelled = false + Promise.all([ + fetch(`/api/assets`).then((r) => r.json()), + fetch('/api/bookkeeping/fiscal-periods').then((r) => r.json()), + ]) + .then(([assetsRes, periodsRes]) => { + if (cancelled) return + const assets: Asset[] = assetsRes.data ?? [] + const found = assets.find((a) => a.id === id) ?? null + setAsset(found) + const periodList: PeriodOption[] = (periodsRes.data ?? []).map((p: FiscalPeriod) => ({ + id: p.id, + name: p.name, + period_start: p.period_start, + period_end: p.period_end, + is_closed: p.is_closed, + locked_at: p.locked_at, + })) + setPeriods(periodList) + setLoading(false) + }) + .catch(() => { + if (!cancelled) { + toast({ + title: 'Kunde inte ladda', + description: 'Försök igen.', + variant: 'destructive', + }) + setLoading(false) + } + }) + return () => { + cancelled = true + } + }, [id, toast]) + + // Auto-select matching fiscal period when disposalDate changes. + useEffect(() => { + if (!disposalDate || periods.length === 0) return + const match = periods.find( + (p) => disposalDate >= p.period_start && disposalDate <= p.period_end, + ) + if (match && match.id !== periodId) setPeriodId(match.id) + }, [disposalDate, periods, periodId]) + + // Derived: VAT rate from treatment + const selectedVatOpt = VAT_TREATMENT_OPTIONS.find((o) => o.value === vatTreatment) + const proceedsNum = Number(proceeds) || 0 + const computedVat = useMemo(() => { + if (!selectedVatOpt || selectedVatOpt.rate === null) return 0 + // Standard convention: proceeds is GROSS (incl VAT). + // vat = gross × rate / (1 + rate) + return round2((proceedsNum * selectedVatOpt.rate) / (1 + selectedVatOpt.rate)) + }, [proceedsNum, selectedVatOpt]) + + // Auto-fill VAT amount when auto-calc is on. + useEffect(() => { + if (vatAutoCalc) { + if (selectedVatOpt && selectedVatOpt.rate !== null) { + setVatAmount(String(computedVat)) + } else { + setVatAmount('0') + } + } + }, [computedVat, selectedVatOpt, vatAutoCalc]) + + // Jämkning eligibility — derived from asset + disposal date. + const eligibility = useMemo(() => { + if (!asset) return null + return assessJamkningEligibility({ + basAssetAccount: asset.bas_asset_account, + basExpenseAccount: asset.bas_expense_account, + category: asset.category, + acquisitionDate: asset.acquisition_date, + disposalDate, + }) + }, [asset, disposalDate]) + + // Auto-enable jämkning toggle when disposal falls within the correction period. + useEffect(() => { + if (eligibility?.withinCorrectionPeriod && !jamkningEnabled) { + setJamkningEnabled(true) + } + }, [eligibility?.withinCorrectionPeriod, jamkningEnabled]) + + const originalInputVatNum = Number(originalInputVat) || 0 + const jamkningAmount = useMemo(() => { + if (!jamkningEnabled || !eligibility) return 0 + return computeJamkningAmount({ + originalInputVat: originalInputVatNum, + totalCorrectionMonths: eligibility.totalCorrectionMonths, + remainingMonths: eligibility.remainingMonths, + disposalEvent: 'triggers_jamkning', + }) + }, [jamkningEnabled, eligibility, originalInputVatNum]) + + const handleSubmit = useCallback(async () => { + if (!asset || !periodId) return + setSubmitting(true) + const vatNum = Number(vatAmount) || 0 + const body: Record = { + disposed_at: disposalDate, + disposed_proceeds: proceedsNum, + fiscal_period_id: periodId, + proceeds_account: proceedsAccount, + } + if (vatNum > 0) { + body.proceeds_vat = vatNum + body.vat_treatment = vatTreatment + } + if (jamkningEnabled && jamkningAmount > 0 && eligibility) { + body.jamkning_amount = jamkningAmount + body.jamkning_remaining_months = eligibility.remainingMonths + body.jamkning_total_months = eligibility.totalCorrectionMonths + body.jamkning_original_input_vat = originalInputVatNum + } + + try { + const res = await fetch(`/api/assets/${id}/dispose`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) + const json = await res.json() + if (!res.ok) { + toast({ + title: 'Avyttring misslyckades', + description: getErrorMessage(json?.error ?? json) || 'Försök igen.', + variant: 'destructive', + }) + return + } + toast({ + title: 'Tillgång avyttrad', + description: 'Verifikat skapat.', + }) + router.push('/assets') + } catch (err) { + toast({ + title: 'Avyttring misslyckades', + description: getErrorMessage(err), + variant: 'destructive', + }) + } finally { + setSubmitting(false) + } + }, [ + asset, + disposalDate, + eligibility, + id, + jamkningAmount, + jamkningEnabled, + originalInputVatNum, + periodId, + proceedsAccount, + proceedsNum, + router, + toast, + vatAmount, + vatTreatment, + ]) + + if (loading) { + return ( +
+ + + + + + + + +
+ ) + } + + if (!asset) { + return ( +
+ + + +

Tillgången kunde inte hittas.

+
+ + + +
+
+
+
+ ) + } + + if (asset.disposed_at) { + return ( +
+ + + +

+ Tillgången är redan avyttrad ({formatDate(asset.disposed_at)}). +

+ + + +
+
+
+ ) + } + + const netProceeds = round2(proceedsNum - (Number(vatAmount) || 0)) + const isVatLineTreatment = selectedVatOpt?.rate !== null + const selectedPeriod = periods.find((p) => p.id === periodId) + const periodLocked = selectedPeriod + ? selectedPeriod.is_closed || selectedPeriod.locked_at !== null + : false + + return ( +
+ + + + } + /> + + + + {asset.name} + + +
+ Anskaffningsvärde + {formatCurrency(Number(asset.acquisition_cost))} +
+
+ Anskaffat + {formatDate(asset.acquisition_date)} +
+
+ Konton (BAS) + + {asset.bas_asset_account} / {asset.bas_accumulated_account} / {asset.bas_expense_account} + +
+
+
+ + + + Avyttringsuppgifter + + +
+
+ + setDisposalDate(e.target.value)} + className="tabular-nums" + /> +
+ +
+ + + {periodLocked && ( +

+ Vald period är låst eller stängd — välj en öppen period. +

+ )} +
+ +
+ + setProceeds(e.target.value)} + placeholder="0,00" + className="tabular-nums" + /> +
+ +
+ + setProceedsAccount(e.target.value)} + placeholder="1930" + className="tabular-nums" + /> +
+
+
+
+ + + + Moms vid avyttring (ML 3 kap 3 §) + + +
+
+ + +
+ +
+ + { + setVatAutoCalc(false) + setVatAmount(e.target.value) + }} + placeholder="0,00" + disabled={!isVatLineTreatment} + className="tabular-nums" + /> + {isVatLineTreatment && ( +
+ + Räkna ut moms automatiskt +
+ )} +
+
+ +
+
+ Brutto + {formatCurrency(proceedsNum)} +
+
+ Moms + {formatCurrency(Number(vatAmount) || 0)} +
+
+ Netto + {formatCurrency(netProceeds)} +
+
+
+
+ + + + Jämkning av ingående moms (ML 8a kap) + + + {eligibility?.withinCorrectionPeriod ? ( + + Inom korrigeringstid ({eligibility.remainingMonths} mån kvar av{' '} + {eligibility.totalCorrectionMonths}) + + ) : ( + Utanför korrigeringstid — ingen jämkning behövs + )} + +
+ + +
+ + {jamkningEnabled && eligibility?.withinCorrectionPeriod && ( +
+
+
+ + setOriginalInputVat(e.target.value)} + placeholder="0,00" + className="tabular-nums" + /> +
+
+ +
+ {eligibility.totalCorrectionMonths} mån +
+
+
+ +
+ {eligibility.remainingMonths} mån +
+
+
+ +
+ {formatCurrency(jamkningAmount)} +
+
+
+

+ Jämkningen bokförs som kredit på 2641 (återförd ingående moms) och debet på + förlustkontot för tillgångsklassen. +

+
+ )} +
+
+ +
+ + + + +
+
+ ) +} diff --git a/app/(dashboard)/assets/page.tsx b/app/(dashboard)/assets/page.tsx index 11b6d568..e204c223 100644 --- a/app/(dashboard)/assets/page.tsx +++ b/app/(dashboard)/assets/page.tsx @@ -1,6 +1,7 @@ 'use client' import { useCallback, useEffect, useState } from 'react' +import Link from 'next/link' import { useTranslations } from 'next-intl' import { Card, CardContent } from '@/components/ui/card' @@ -116,6 +117,7 @@ export default function AssetsPage() { {t('th_acquisition_cost')} {t('th_useful_life')} {t('th_status')} + {t('th_actions')} @@ -136,11 +138,25 @@ export default function AssetsPage() { {asset.disposed_at ? ( - {t('status_disposed')} +
+ {t('status_disposed')} + + {formatDate(asset.disposed_at)} + +
) : ( {t('status_active')} )}
+ + {!asset.disposed_at && ( + + + + )} + ) })} diff --git a/app/(dashboard)/bookkeeping/[id]/page.tsx b/app/(dashboard)/bookkeeping/[id]/page.tsx index 81843510..dff942a4 100644 --- a/app/(dashboard)/bookkeeping/[id]/page.tsx +++ b/app/(dashboard)/bookkeeping/[id]/page.tsx @@ -11,6 +11,7 @@ import { Textarea } from '@/components/ui/textarea' import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Pencil, Check, X, Copy } from 'lucide-react' import { useCanWrite } from '@/lib/hooks/use-can-write' import { formatDate } from '@/lib/utils' +import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver' import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments' import JournalEntryStatusBadge, { useSourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge' import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog' @@ -92,7 +93,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i const posted = result.data toast({ title: t('toast_posted_title'), - description: t('toast_posted_description', { voucher: `${posted?.voucher_series ?? ''}${posted?.voucher_number ?? ''}` }), + description: t('toast_posted_description', { voucher: formatVoucher(posted ?? {}) }), }) await fetchData() } else { @@ -116,7 +117,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i title: wasDraft ? t('toast_delete_draft_title') : t('toast_delete_entry_title'), description: wasDraft ? t('toast_delete_draft_description') - : t('toast_delete_entry_description', { voucher: `${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''}` }), + : t('toast_delete_entry_description', { voucher: formatVoucher(result.data ?? {}) }), }) router.push('/bookkeeping') } else { @@ -201,7 +202,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i

- {entry.voucher_series}{entry.voucher_number} + {formatVoucher(entry)}

@@ -290,7 +291,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
{t('field_source_voucher')} - {entry.source_voucher_series}{entry.source_voucher_number} + {formatVoucher({ voucher_series: entry.source_voucher_series, voucher_number: entry.source_voucher_number })}
)} @@ -587,7 +588,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i warningText={ entry?.status === 'draft' ? t('delete_warning_draft') - : t('delete_warning_entry', { voucher: `${entry?.voucher_series ?? ''}${entry?.voucher_number ?? ''}` }) + : t('delete_warning_entry', { voucher: entry ? formatVoucher(entry) : '' }) } confirmLabel={t('delete_confirm_label')} > diff --git a/app/(dashboard)/bookkeeping/page.tsx b/app/(dashboard)/bookkeeping/page.tsx index b30ca1ad..300f9fdb 100644 --- a/app/(dashboard)/bookkeeping/page.tsx +++ b/app/(dashboard)/bookkeeping/page.tsx @@ -13,6 +13,7 @@ import { FiscalYearSelector } from '@/components/common/FiscalYearSelector' import { useToast } from '@/components/ui/use-toast' import { Lock, Loader2, Copy } from 'lucide-react' import { PageHeader } from '@/components/ui/page-header' +import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver' import type { JournalEntry, JournalEntryLine } from '@/types' interface CopyPrefill { @@ -87,7 +88,7 @@ export default function BookkeepingPage() { }) setCopyPrefill({ sourceId: copyFromId, - sourceVoucherLabel: `${data.voucher_series ?? ''}${data.voucher_number ?? ''}`, + sourceVoucherLabel: formatVoucher(data), lines, description: data.description || '', notes: data.notes || '', diff --git a/app/(dashboard)/bookkeeping/year-end/arsredovisning/page.tsx b/app/(dashboard)/bookkeeping/year-end/arsredovisning/page.tsx index 19c35f27..996189a8 100644 --- a/app/(dashboard)/bookkeeping/year-end/arsredovisning/page.tsx +++ b/app/(dashboard)/bookkeeping/year-end/arsredovisning/page.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from 'react' import Link from 'next/link' -import { useSearchParams } from 'next/navigation' +import { useRouter, useSearchParams } from 'next/navigation' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' @@ -13,10 +13,12 @@ import { Textarea } from '@/components/ui/textarea' import { PageHeader } from '@/components/ui/page-header' import { ArrowLeft, FileDown, Plus, ExternalLink, Loader2, Save, CheckCircle2 } from 'lucide-react' import { useToast } from '@/components/ui/use-toast' +import { FiscalYearSelector } from '@/components/common/FiscalYearSelector' import type { ArsredovisningData } from '@/lib/bokslut/arsredovisning/types' import type { SignatureRequest } from '@/lib/bokslut/arsredovisning/signature-service' export default function ArsredovisningPage() { + const router = useRouter() const searchParams = useSearchParams() const periodId = searchParams.get('period') const { toast } = useToast() @@ -205,14 +207,33 @@ export default function ArsredovisningPage() { if (!periodId) { return (
- + - - Saknar periodparameter. Öppna sidan från bokslutet via{' '} - - /bookkeeping/year-end - - . + + Välj räkenskapsår +

+ Välj det räkenskapsår du vill se årsredovisningen för. Du kan + förhandsgranska och ladda ner PDF-utkastet utan att stänga året — det + fullständiga bokslutet görs sedan via{' '} + + Bokslut + + . +

+
+ + { + if (id) router.replace(`/bookkeeping/year-end/arsredovisning?period=${id}`) + }} + includeAllOption={false} + hideFuturePeriods + label={null} + />
@@ -254,7 +275,11 @@ export default function ArsredovisningPage() {
@@ -264,12 +289,25 @@ export default function ArsredovisningPage() { } /> + {data.accounting_framework === 'k3' && ( + + +

Årsredovisning enligt K3 (BFNAR 2012:1)

+

+ Dokumentet innehåller kassaflödesanalys, förändring av eget kapital och + utökade noter (uppskjuten skatt, redovisningsprinciper, materiella + anläggningstillgångar) — krav som följer K3 men inte K2. +

+
+
+ )} + Förvaltningsberättelse — narrativ

- Texten nedan visas i PDF:en. Förändringar är lokala till denna sida tills - vidare; en framtida version kommer att spara dem mellan sessioner. + Texten nedan visas i PDF:en. Klicka på Spara texten nedan + för att behålla ändringarna mellan sessioner.

diff --git a/app/(dashboard)/bookkeeping/year-end/periodisering/page.tsx b/app/(dashboard)/bookkeeping/year-end/periodisering/page.tsx new file mode 100644 index 00000000..c7151a86 --- /dev/null +++ b/app/(dashboard)/bookkeeping/year-end/periodisering/page.tsx @@ -0,0 +1,997 @@ +'use client' + +import { useCallback, useEffect, useMemo, useState } from 'react' +import Link from 'next/link' +import { useSearchParams } from 'next/navigation' +import { ArrowLeft, ArrowRight, Loader2, Lock, Plus, Trash2 } from 'lucide-react' +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { Badge } from '@/components/ui/badge' +import { Checkbox } from '@/components/ui/checkbox' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Progress } from '@/components/ui/progress' +import { Skeleton } from '@/components/ui/skeleton' +import { EmptyState } from '@/components/ui/empty-state' +import { useToast } from '@/components/ui/use-toast' +import { useCanWrite } from '@/lib/hooks/use-can-write' +import { cn, formatCurrency } from '@/lib/utils' +import { + PERIODISERING_TEMPLATES, + type PeriodiseringTemplate, +} from '@/lib/bokslut/accruals/templates' +import type { AccrualsProposal } from '@/lib/bokslut/accruals/types' +import type { + PeriodiseringSuggestion, + PeriodiseringConfidence, +} from '@/lib/bokslut/accruals/auto-detect' +import type { FiscalPeriod } from '@/types' + +type Step = 'vacation' | 'audit' | 'auto' | 'manual' | 'review' + +const STEP_ORDER: Step[] = ['vacation', 'audit', 'auto', 'manual', 'review'] +const STEP_LABELS: Record = { + vacation: 'Semester', + audit: 'Revisionsarvode', + auto: 'Auto-detektering', + manual: 'Manuella tillägg', + review: 'Granska & posta', +} + +interface PeriodOption { + id: string + name: string + period_start: string + period_end: string +} + +type ProposalResponse = AccrualsProposal & { autoDetected: PeriodiseringSuggestion[] } + +interface AuditState { + enabled: boolean + amount: string + liabilityAccount: '2991' | '2992' +} + +interface AutoState { + /** key = source_invoice_id + '|' + source_type, value = accepted */ + selections: Record +} + +interface ManualEntry { + id: string + templateKind: PeriodiseringTemplate['kind'] + amount: string + description: string + /** Editable accounts (pre-filled from template). */ + primaryAccount: string + secondaryAccount: string +} + +function uid() { + return Math.random().toString(36).slice(2, 10) +} + +function suggestionKey(s: PeriodiseringSuggestion): string { + return `${s.source_invoice_id}|${s.source_type}` +} + +function confidenceVariant(c: PeriodiseringConfidence): 'success' | 'secondary' | 'outline' { + if (c === 'high') return 'success' + if (c === 'medium') return 'secondary' + return 'outline' +} + +function confidenceLabel(c: PeriodiseringConfidence): string { + if (c === 'high') return 'Hög säkerhet' + if (c === 'medium') return 'Medel säkerhet' + return 'Låg säkerhet' +} + +export default function PeriodiseringWizardPage() { + const searchParams = useSearchParams() + const { toast } = useToast() + const { canWrite } = useCanWrite() + + const [periods, setPeriods] = useState(null) + const [periodsError, setPeriodsError] = useState(null) + const [selectedPeriodId, setSelectedPeriodId] = useState( + searchParams.get('period') ?? null, + ) + + const [step, setStep] = useState('vacation') + const [proposal, setProposal] = useState(null) + const [loadError, setLoadError] = useState(null) + const [loading, setLoading] = useState(false) + + const [vacationAccepted, setVacationAccepted] = useState(true) + const [auditState, setAuditState] = useState({ + enabled: false, + amount: '', + liabilityAccount: '2992', + }) + const [autoState, setAutoState] = useState({ selections: {} }) + const [manualEntries, setManualEntries] = useState([]) + + const [posting, setPosting] = useState(false) + const [postError, setPostError] = useState(null) + const [postSummary, setPostSummary] = useState<{ created: number; skipped: number } | null>(null) + + // ---- Load eligible periods ---- + useEffect(() => { + let cancelled = false + const load = async () => { + try { + const res = await fetch('/api/bookkeeping/fiscal-periods') + if (!res.ok) { + if (!cancelled) setPeriodsError('Kunde inte hämta perioder') + return + } + const { data } = (await res.json()) as { data: FiscalPeriod[] } + const today = new Date().toISOString().split('T')[0] + const eligible = (data ?? []).filter( + (p) => !p.is_closed && !p.closing_entry_id && p.period_end <= today, + ) + eligible.sort((a, b) => a.period_start.localeCompare(b.period_start)) + if (cancelled) return + setPeriods(eligible) + if (!selectedPeriodId && eligible.length > 0) { + setSelectedPeriodId(eligible[0].id) + } + } catch { + if (!cancelled) setPeriodsError('Kunde inte hämta perioder') + } + } + void load() + return () => { + cancelled = true + } + }, [selectedPeriodId]) + + // ---- Fetch accruals snapshot once period chosen ---- + useEffect(() => { + if (!selectedPeriodId) return + let cancelled = false + setLoading(true) + setLoadError(null) + setProposal(null) + fetch(`/api/bookkeeping/fiscal-periods/${selectedPeriodId}/accruals`) + .then(async (res) => { + const body = await res.json() + if (cancelled) return + if (!res.ok) { + setLoadError(body?.error?.message ?? 'Kunde inte ladda periodiseringar') + return + } + const data = body.data as ProposalResponse + setProposal(data) + // Default-check all high-confidence suggestions. + const initial: Record = {} + for (const s of data.autoDetected ?? []) { + initial[suggestionKey(s)] = s.confidence === 'high' + } + setAutoState({ selections: initial }) + }) + .catch(() => { + if (!cancelled) setLoadError('Kunde inte ladda periodiseringar') + }) + .finally(() => { + if (!cancelled) setLoading(false) + }) + return () => { + cancelled = true + } + }, [selectedPeriodId]) + + const vacationProposal = useMemo( + () => proposal?.proposals.find((p) => p.kind === 'vacation_liability_change') ?? null, + [proposal], + ) + + const currentStepIndex = STEP_ORDER.indexOf(step) + const progressValue = ((currentStepIndex + 1) / STEP_ORDER.length) * 100 + const showWizard = selectedPeriodId !== null && (periods?.length ?? 0) > 0 && !loading && !loadError + + // ---- Manual entry editing helpers ---- + const addManualFromTemplate = useCallback((template: PeriodiseringTemplate) => { + const primary = + template.prepaid_account ?? template.deferred_account ?? template.accrued_account ?? '' + const secondary = + template.expense_account ?? template.revenue_account ?? '' + setManualEntries((prev) => [ + ...prev, + { + id: uid(), + templateKind: template.kind, + amount: '', + description: '', + primaryAccount: primary, + secondaryAccount: secondary, + }, + ]) + }, []) + + const updateManual = useCallback((id: string, patch: Partial) => { + setManualEntries((prev) => prev.map((m) => (m.id === id ? { ...m, ...patch } : m))) + }, []) + + const removeManual = useCallback((id: string) => { + setManualEntries((prev) => prev.filter((m) => m.id !== id)) + }, []) + + // ---- Final post ---- + const handlePost = useCallback(async () => { + if (!selectedPeriodId) return + setPosting(true) + setPostError(null) + try { + const items: unknown[] = [] + if (vacationProposal && vacationAccepted) { + items.push({ kind: 'vacation_liability_change' }) + } + if (auditState.enabled) { + const amount = parseFloat(auditState.amount) + if (Number.isFinite(amount) && amount > 0) { + items.push({ + kind: 'audit_fee', + amount, + liability_account: auditState.liabilityAccount, + }) + } + } + for (const s of proposal?.autoDetected ?? []) { + if (!autoState.selections[suggestionKey(s)]) continue + if (s.source_type === 'supplier_invoice') { + items.push({ + kind: 'manual_prepaid_expense', + amount: s.periodisering_amount, + expense_account: '5800', // safe fallback; user can override in manual list + prepaid_account: s.suggested_prepaid_account ?? '1710', + description: s.source_label, + }) + } else { + items.push({ + kind: 'deferred_revenue', + amount: s.periodisering_amount, + revenue_account: '3001', + deferred_account: s.suggested_deferred_account ?? '2970', + description: s.source_label, + }) + } + } + for (const m of manualEntries) { + const amount = parseFloat(m.amount) + if (!Number.isFinite(amount) || amount <= 0) continue + if (!m.description.trim()) continue + const tpl = PERIODISERING_TEMPLATES.find((t) => t.kind === m.templateKind) + if (!tpl) continue + switch (tpl.side) { + case 'prepaid': + items.push({ + kind: 'manual_prepaid_expense', + amount, + expense_account: m.secondaryAccount, + prepaid_account: m.primaryAccount, + description: m.description, + }) + break + case 'accrued': + items.push({ + kind: 'manual_accrued_expense', + amount, + expense_account: m.secondaryAccount, + accrued_account: m.primaryAccount, + description: m.description, + }) + break + case 'deferred_revenue': + items.push({ + kind: 'deferred_revenue', + amount, + revenue_account: m.secondaryAccount, + deferred_account: m.primaryAccount, + description: m.description, + }) + break + case 'accrued_interest': + items.push({ + kind: 'accrued_interest', + amount, + expense_account: m.secondaryAccount, + accrued_account: m.primaryAccount, + description: m.description, + }) + break + case 'accrued_utility': + items.push({ + kind: 'accrued_utility', + amount, + expense_account: m.secondaryAccount, + accrued_account: m.primaryAccount, + description: m.description, + }) + break + } + } + + if (items.length === 0) { + toast({ + title: 'Inga periodiseringar att bokföra', + description: 'Markera minst en post innan du postar.', + }) + return + } + + const res = await fetch(`/api/bookkeeping/fiscal-periods/${selectedPeriodId}/accruals`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ items }), + }) + const body = await res.json() + if (!res.ok) { + setPostError(body?.error?.message ?? 'Kunde inte bokföra periodiseringarna') + return + } + const created = body.data?.created?.length ?? 0 + const skipped = body.data?.skipped?.length ?? 0 + setPostSummary({ created, skipped }) + toast({ + title: `${created} verifikation${created === 1 ? '' : 'er'} bokförd${created === 1 ? '' : 'a'}`, + description: skipped > 0 ? `${skipped} hoppades över (redan postade).` : undefined, + }) + } catch (err) { + setPostError(err instanceof Error ? err.message : 'Okänt fel') + } finally { + setPosting(false) + } + }, [ + selectedPeriodId, + vacationProposal, + vacationAccepted, + auditState, + autoState, + manualEntries, + proposal, + toast, + ]) + + const closingYear = useMemo(() => { + if (!proposal) return null + return proposal.fiscalPeriod.period_end.slice(0, 4) + }, [proposal]) + + return ( +
+
+

+ {closingYear ? `Periodisering — Bokslut ${closingYear}` : 'Periodisering'} +

+ +
+ + {periods === null && !periodsError && ( + + + + + + + )} + + {periodsError && ( + + {periodsError} + + )} + + {periods !== null && periods.length === 0 && ( + + )} + + {loadError && ( + + {loadError} + + )} + + {loading && ( + + + + + + + )} + + {showWizard && proposal && ( + <> + + +
+ + Steg {currentStepIndex + 1}/{STEP_ORDER.length}: {STEP_LABELS[step]} + + {STEP_ORDER.map((s, i) => ( + + {STEP_LABELS[s]} + + ))} +
+ +
+
+ + {step === 'vacation' && ( + setStep('audit')} + /> + )} + {step === 'audit' && ( + setStep('vacation')} + onNext={() => setStep('auto')} + /> + )} + {step === 'auto' && ( + + setAutoState({ selections: { ...autoState.selections, [key]: val } }) + } + onBack={() => setStep('audit')} + onNext={() => setStep('manual')} + /> + )} + {step === 'manual' && ( + setStep('auto')} + onNext={() => setStep('review')} + /> + )} + {step === 'review' && ( + setStep('manual')} + onPost={handlePost} + /> + )} + + )} +
+ ) +} + +// ============================================================ +// Step components +// ============================================================ + +function VacationStep({ + proposal, + accepted, + onChange, + onNext, +}: { + proposal: AccrualsProposal['proposals'][number] | null + accepted: boolean + onChange: (v: boolean) => void + onNext: () => void +}) { + return ( +
+ + + Steg 1: Semesterlöneskuld +

+ Justering av 2920 mot 7090 plus 31,42 % sociala avgifter (2940 / 7519). + Saldot rullas vidare till nästa år. +

+
+ + {proposal ? ( +
+
+

{proposal.label}

+

{proposal.description}

+
+ onChange(Boolean(c))} + /> + +
+
+

+ {formatCurrency(proposal.amount)} +

+
+ ) : ( +

+ Ingen justering behövs — semesterlöneskulden ligger redan rätt. +

+ )} +
+
+
+ +
+
+ ) +} + +function AuditStep({ + state, + onChange, + onBack, + onNext, +}: { + state: AuditState + onChange: (s: AuditState) => void + onBack: () => void + onNext: () => void +}) { + return ( +
+ + + Steg 2: Revisions- / bokslutsarvode +

+ Periodisera arvode för revision (2992) eller bokslut (2991). Posten + vänds första dagen i nästa räkenskapsår när fakturan kommer. +

+
+ +
+ onChange({ ...state, enabled: Boolean(c) })} + /> + +
+ {state.enabled && ( +
+
+ + onChange({ ...state, amount: e.target.value })} + className="tabular-nums h-9" + /> +
+
+ + +
+
+ )} +
+
+
+ + +
+
+ ) +} + +function AutoStep({ + suggestions, + selections, + onToggle, + onBack, + onNext, +}: { + suggestions: PeriodiseringSuggestion[] + selections: Record + onToggle: (key: string, val: boolean) => void + onBack: () => void + onNext: () => void +}) { + return ( +
+ + + Steg 3: Auto-detekterade periodiseringar +

+ Fakturor (kund och leverantör) i den stängda perioden vars beskrivning + innehåller en datumintervall som sträcker sig in i nästa räkenskapsår. + Granska och bekräfta — högst säkra förslag är förvalda. +

+
+ + {suggestions.length === 0 && ( +

+ Inga fakturor med tydlig datumintervall hittades. Du kan ändå lägga + till manuella periodiseringar i nästa steg. +

+ )} + {suggestions.map((s) => { + const key = suggestionKey(s) + return ( +
+ onToggle(key, Boolean(c))} + className="mt-1" + /> +
+
+ + + {confidenceLabel(s.confidence)} + +
+

{s.reason}

+
+ + {s.source_type === 'supplier_invoice' + ? 'Förutbetald kostnad → 1710' + : 'Förutbetald intäkt → 2970'} + + + {formatCurrency(s.periodisering_amount)} + +
+
+
+ ) + })} +
+
+
+ + +
+
+ ) +} + +function ManualStep({ + entries, + onAdd, + onUpdate, + onRemove, + onBack, + onNext, +}: { + entries: ManualEntry[] + onAdd: (t: PeriodiseringTemplate) => void + onUpdate: (id: string, patch: Partial) => void + onRemove: (id: string) => void + onBack: () => void + onNext: () => void +}) { + return ( +
+ + + Steg 4: Manuella periodiseringar +

+ Använd mallarna nedan för vanliga fall, eller hoppa direkt till granskning. +

+
+ +
+ {PERIODISERING_TEMPLATES.map((t) => ( + + ))} +
+ + {entries.length > 0 && ( +
+ {entries.map((entry) => ( + onUpdate(entry.id, patch)} + onRemove={() => onRemove(entry.id)} + /> + ))} +
+ )} +
+
+
+ + +
+
+ ) +} + +function ManualEntryEditor({ + entry, + onChange, + onRemove, +}: { + entry: ManualEntry + onChange: (patch: Partial) => void + onRemove: () => void +}) { + const template = PERIODISERING_TEMPLATES.find((t) => t.kind === entry.templateKind) + if (!template) return null + const primaryLabel = + template.side === 'prepaid' + ? '17xx-konto' + : template.side === 'deferred_revenue' + ? '29xx-konto (deferred)' + : '29xx-konto' + const secondaryLabel = + template.side === 'deferred_revenue' ? 'Intäktskonto' : 'Kostnadskonto' + + return ( +
+
+

{template.name}

+ +
+
+
+ + onChange({ amount: e.target.value })} + className="tabular-nums h-8" + /> +
+
+ + onChange({ primaryAccount: e.target.value })} + className="tabular-nums h-8" + /> +
+
+ + onChange({ secondaryAccount: e.target.value })} + className="tabular-nums h-8" + /> +
+
+ + onChange({ description: e.target.value })} + placeholder="t.ex. Försäkring 2026" + className="h-8" + /> +
+
+
+ ) +} + +function ReviewStep({ + vacationProposal, + vacationAccepted, + auditState, + suggestions, + selections, + manualEntries, + postError, + postSummary, + posting, + canWrite, + onBack, + onPost, +}: { + vacationProposal: AccrualsProposal['proposals'][number] | null + vacationAccepted: boolean + auditState: AuditState + suggestions: PeriodiseringSuggestion[] + selections: Record + manualEntries: ManualEntry[] + postError: string | null + postSummary: { created: number; skipped: number } | null + posting: boolean + canWrite: boolean + onBack: () => void + onPost: () => void +}) { + const auditAmount = parseFloat(auditState.amount) + const auditValid = auditState.enabled && Number.isFinite(auditAmount) && auditAmount > 0 + const selectedSuggestions = suggestions.filter((s) => selections[suggestionKey(s)]) + const validManual = manualEntries.filter( + (m) => Number.isFinite(parseFloat(m.amount)) && parseFloat(m.amount) > 0 && m.description.trim(), + ) + + const totalCount = + (vacationProposal && vacationAccepted ? 1 : 0) + + (auditValid ? 1 : 0) + + selectedSuggestions.length + + validManual.length + + return ( +
+ + + Steg 5: Granska & posta +

+ {totalCount === 0 + ? 'Inga periodiseringar valda. Gå tillbaka och välj minst en.' + : `${totalCount} periodisering${totalCount === 1 ? '' : 'ar'} kommer att bokföras som separata verifikationer.`} +

+
+ + {vacationProposal && vacationAccepted && ( + + )} + {auditValid && ( + + )} + {selectedSuggestions.map((s) => ( + + ))} + {validManual.map((m) => { + const tpl = PERIODISERING_TEMPLATES.find((t) => t.kind === m.templateKind) + return ( + + ) + })} + +
+ + {postError && ( + + {postError} + + )} + + {postSummary && ( + + + {postSummary.created} verifikation{postSummary.created === 1 ? '' : 'er'} bokförd + {postSummary.created === 1 ? '' : 'a'}. + {postSummary.skipped > 0 && ` ${postSummary.skipped} hoppades över (redan postade).`} + + + )} + +
+ + +
+
+ ) +} + +function ReviewLine({ label, amount, note }: { label: string; amount: number; note?: string }) { + return ( +
+
+

{label}

+ {note &&

{note}

} +
+

{formatCurrency(amount)}

+
+ ) +} diff --git a/app/(dashboard)/import/page.tsx b/app/(dashboard)/import/page.tsx index 76d0b841..6f5bebc8 100644 --- a/app/(dashboard)/import/page.tsx +++ b/app/(dashboard)/import/page.tsx @@ -477,7 +477,7 @@ function SIEImportWizard() { toast({ title: 'Import ersatt', - description: `${data.cancelledEntries} verifikation${data.cancelledEntries === 1 ? '' : 'er'} makulerades. Importerar ny fil...`, + description: `${data.deletedEntries} verifikation${data.deletedEntries === 1 ? '' : 'er'} raderades. Importerar ny fil...`, }) // Clear error state and re-trigger the file upload diff --git a/app/(dashboard)/invoices/new/page.tsx b/app/(dashboard)/invoices/new/page.tsx index d159f4e3..7440cc0c 100644 --- a/app/(dashboard)/invoices/new/page.tsx +++ b/app/(dashboard)/invoices/new/page.tsx @@ -20,7 +20,7 @@ import { useToast } from '@/components/ui/use-toast' import { formatCurrency } from '@/lib/utils' import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog' -import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock } from 'lucide-react' +import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock, AlertTriangle } from 'lucide-react' import { useCanWrite } from '@/lib/hooks/use-can-write' import { ConfirmationDialog } from '@/components/ui/confirmation-dialog' import { InvoiceReviewContent } from '@/components/invoices/InvoiceReviewContent' @@ -30,6 +30,13 @@ import CustomerForm from '@/components/customers/CustomerForm' import { BankDetailsSetupDialog } from '@/components/invoices/BankDetailsSetupDialog' import { FirstInvoiceLogoPrompt } from '@/components/invoices/FirstInvoiceLogoPrompt' import { useCompany } from '@/contexts/CompanyContext' +import { + ROT_WORK_TYPES, + RUT_WORK_TYPES, + ROT_MAX, + RUT_MAX, + computeDeduction, +} from '@/lib/invoices/rot-rut-rules' import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType } from '@/types' const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK'] @@ -54,6 +61,12 @@ export default function NewInvoicePage() { unit: z.string().min(1, t('validation_unit_required')), unit_price: z.number().min(0, t('validation_price_positive')), vat_rate: z.number().min(0).max(25), + // ROT/RUT-avdrag per line. Optional — null means "no deduction". + deduction_type: z.enum(['rot', 'rut']).nullable().optional(), + labor_hours: z.number().nonnegative().nullable().optional(), + work_type: z.string().nullable().optional(), + housing_designation: z.string().nullable().optional(), + apartment_number: z.string().nullable().optional(), }) return z.object({ customer_id: z.string().min(1, t('validation_customer_required')), @@ -65,6 +78,10 @@ export default function NewInvoicePage() { your_reference: z.string().optional(), our_reference: z.string().optional(), notes: z.string().optional(), + // Invoice-level ROT/RUT claim info. Personnummer is plaintext on + // the wire; the API encrypts it before storage. + deduction_personnummer: z.string().optional(), + deduction_housing_designation: z.string().optional(), items: z.array(itemSchema).min(1, t('validation_min_one_row')), }) }, [t]) @@ -112,7 +129,18 @@ export default function NewInvoicePage() { due_date: '', currency: 'SEK', document_type: 'invoice' as InvoiceDocumentType, - items: [{ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: 25 }], + items: [{ + description: '', + quantity: 1, + unit: 'st', + unit_price: 0, + vat_rate: 25, + deduction_type: null, + labor_hours: null, + work_type: null, + housing_designation: null, + apartment_number: null, + }], }, }) @@ -320,10 +348,33 @@ export default function NewInvoicePage() { } const total = subtotal + vatAmount + // ROT/RUT-avdrag live preview. Computed client-side for instant feedback; + // the API recomputes server-side as the source of truth. Skipped for + // non-invoice document types (proformas and delivery notes don't book + // a deduction). + const isInvoiceDoc = watchDocumentType === 'invoice' + const deductionByKind = { rot: 0, rut: 0 } + if (isInvoiceDoc) { + for (const item of watchItems) { + if (!item.deduction_type) continue + const amount = computeDeduction({ + unit_price: item.unit_price || 0, + quantity: item.quantity || 0, + deduction_type: item.deduction_type, + }) + if (item.deduction_type === 'rot') deductionByKind.rot += amount + else deductionByKind.rut += amount + } + } + const deductionTotal = Math.round((deductionByKind.rot + deductionByKind.rut) * 100) / 100 + const hasAnyDeduction = deductionTotal > 0 + const hasAnyRotLine = isInvoiceDoc && watchItems.some((i) => i.deduction_type === 'rot') + const toPay = Math.round((total - deductionTotal) * 100) / 100 + async function onSubmit(data: FormData) { setPendingData(data) // Re-fetch the preview right before review so the displayed number - // reflects any concurrent invoice creations. + // reflects any concurrent invoice creations. Skip for delivery notes. if (data.document_type !== 'delivery_note') { try { const r = await fetch(`/api/invoices/next-number?document_type=${encodeURIComponent(data.document_type)}`) @@ -370,11 +421,37 @@ export default function NewInvoicePage() { if (!pendingData) return setIsSubmitting(true) + // Privacy by default: ROT/RUT line fields and the invoice-level + // personnummer / housing designation are only sent to the API when the + // user actually claims a deduction. Defaults are pre-instantiated as + // null in the form state, but null personal-data fields shouldn't ride + // along on every regular invoice. + const anyDeduction = pendingData.items.some((i) => i.deduction_type) + const sanitizedItems = pendingData.items.map((item) => { + if (item.deduction_type) return item + const { + deduction_type: _dt, + labor_hours: _lh, + work_type: _wt, + housing_designation: _hd, + apartment_number: _an, + ...rest + } = item + return rest + }) + const sanitizedPayload: CreateInvoiceInput = { + ...(pendingData as CreateInvoiceInput), + items: sanitizedItems as CreateInvoiceInput['items'], + ...(anyDeduction + ? {} + : { deduction_personnummer: undefined, deduction_housing_designation: undefined }), + } + try { const response = await fetch('/api/invoices', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(pendingData as CreateInvoiceInput), + body: JSON.stringify(sanitizedPayload), }) const result = await response.json() @@ -707,6 +784,117 @@ export default function NewInvoicePage() {
+ {/* ROT/RUT-avdrag per-row controls. Only shown on real + invoices — proformas and delivery notes have no + deduction model. Collapsed to a tiny segmented + toggle by default; selecting ROT or RUT reveals the + work-type picker. */} + {isInvoiceDoc && ( +
+ { + const value = field.value ?? 'none' + return ( +
+ Skattereduktion: + + {watchItems[index]?.deduction_type && ( + <> + { + const opts = + watchItems[index]?.deduction_type === 'rot' + ? ROT_WORK_TYPES + : RUT_WORK_TYPES + return ( + + ) + }} + /> + + v === '' || Number.isNaN(v) ? null : Number(v), + })} + /> + {(() => { + const amt = computeDeduction({ + unit_price: watchItems[index]?.unit_price || 0, + quantity: watchItems[index]?.quantity || 0, + deduction_type: watchItems[index]?.deduction_type, + }) + return amt > 0 ? ( + + −{formatCurrency(amt, watchCurrency)} + + ) : null + })()} + + )} +
+ ) + }} + /> + {/* Labor-only disclosure (Skatteverket fakturamodellen). + 30%/50% applies to the full line total — the seller + must ensure the line is 100% labor; material has + to be invoiced separately. */} + {watchItems[index]?.deduction_type && ( +
+ +

+ Skatteverket kräver att endast arbetskostnad ingår i ROT/RUT-grundlaget. Material ska faktureras separat. Sätt endast skattereduktion på rader som är 100% arbete. +

+
+ )} +
+ )} + {/* Mobile summary row */}
{t('row_label', { index: index + 1 })} @@ -721,7 +909,18 @@ export default function NewInvoicePage() { variant="outline" className="w-full md:w-auto" onClick={() => - append({ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: availableRates[0]?.rate ?? 25 }) + append({ + description: '', + quantity: 1, + unit: 'st', + unit_price: 0, + vat_rate: availableRates[0]?.rate ?? 25, + deduction_type: null, + labor_hours: null, + work_type: null, + housing_designation: null, + apartment_number: null, + }) } > @@ -731,6 +930,59 @@ export default function NewInvoicePage() { + {/* ROT/RUT-avdrag claim info. Surfaces only when any item has + a deduction_type set — keeps the form quiet for the 90%+ + of users who don't sell ROT/RUT-eligible services. */} + {isInvoiceDoc && hasAnyDeduction && ( + + + Underlag för skattereduktion + + ROT/RUT-avdrag begärs hos Skatteverket via fakturamodellen. Kunden behöver godkänna utbetalningen, så uppgifterna måste matcha köparen exakt. + + + +
+ + +

+ Krypteras innan lagring. Endast de fyra sista siffrorna visas på fakturan. +

+
+ {hasAnyRotLine && ( +
+ + +

+ Krävs för ROT-avdrag (RUT behöver inte detta fält). +

+
+ )} + {(deductionByKind.rot > ROT_MAX || deductionByKind.rut > RUT_MAX) && ( +
+ Fakturans avdrag överstiger årstaket + {deductionByKind.rot > ROT_MAX && ` (ROT ${ROT_MAX.toLocaleString('sv-SE')} kr)`} + {deductionByKind.rut > RUT_MAX && ` (RUT ${RUT_MAX.toLocaleString('sv-SE')} kr)`} + . Kunden behöver kontrollera sitt återstående utrymme själv. +
+ )} +
+
+ )} + {/* Notes */} @@ -881,11 +1133,23 @@ export default function NewInvoicePage() { {formatCurrency(0, watchCurrency)}
)} + {hasAnyDeduction && ( +
+ Skattereduktion ROT/RUT + −{formatCurrency(deductionTotal, watchCurrency)} +
+ )}
- {t('total_label')} - {formatCurrency(total, watchCurrency)} + {hasAnyDeduction ? 'Att betala' : t('total_label')} + {formatCurrency(hasAnyDeduction ? toPay : total, watchCurrency)}
+ {hasAnyDeduction && ( +
+ Totalt inkl. moms + {formatCurrency(total, watchCurrency)} +
+ )} @@ -907,8 +1171,12 @@ export default function NewInvoicePage() {
-

{t('total_label')}

-

{formatCurrency(total, watchCurrency)}

+

+ {hasAnyDeduction ? 'Att betala' : t('total_label')} +

+

+ {formatCurrency(hasAnyDeduction ? toPay : total, watchCurrency)} +

+ + + + + + + + + Snart tillgänglig + + +
+
+ +

+ Indirekt metod enligt BFNAR 2012:1 kap 7. Totalsumman ska överensstämma + med förändringen i likvida medel (kontoklass 19) under perioden. +

+ + {isLoadingPeriods ? ( +
+ + + +
+ ) : !selectedPeriod ? ( + + ) : isLoadingReport ? ( +
+ + + +
+ ) : error ? ( + + {error} + + ) : report ? ( +
+

+ Period: {formatDate(report.period_start)} – {formatDate(report.period_end)} +

+ + {/* Section 1: Löpande verksamhet */} + + +

+ Den löpande verksamheten +

+ + Kassaflöde från löpande verksamhet + +
+ + + + + + + + + + +
+ + {/* Section 2: Investeringsverksamhet */} + + +

+ Investeringsverksamheten +

+ + Kassaflöde från investeringsverksamhet + +
+ + + + + +
+ + {/* Section 3: Finansieringsverksamhet */} + + +

+ Finansieringsverksamheten +

+ + Kassaflöde från finansieringsverksamhet + +
+ + + + + + +
+ + {/* Total */} + + +
+ Årets kassaflöde + + {formatAmount(report.total_cash_flow)} + +
+
+
+ + {/* Reconciliation banner */} + + +
+ {report.reconciliation.is_reconciled ? ( + + ) : ( + + )} + + {report.reconciliation.is_reconciled + ? 'Avstämning OK — kassaflödet stämmer med 19xx' + : 'Avstämning misslyckades — kontrollera bokföringen'} + +
+
+ + + + + {!report.reconciliation.is_reconciled && ( +
+ Avvikelse + + {formatAmount(report.reconciliation.mismatch_amount)} + +
+ )} +
+
+
+
+ ) : null} +
+ ) +} diff --git a/app/(dashboard)/reports/kassaflodesanalys/page.tsx b/app/(dashboard)/reports/kassaflodesanalys/page.tsx new file mode 100644 index 00000000..717a8dbe --- /dev/null +++ b/app/(dashboard)/reports/kassaflodesanalys/page.tsx @@ -0,0 +1,10 @@ +import { KassaflodesanalysClient } from './KassaflodesanalysClient' + +// NOTE: The xlsx download button on this page is intentionally disabled. +// Plan item #4 (Excel export for all reports) introduces a shared +// `reportToWorkbook` helper and adds `/api/reports/kassaflodesanalys/xlsx`. +// Once that helper lands, enable the button and point it at that endpoint. + +export default function KassaflodesanalysPage() { + return +} diff --git a/app/(dashboard)/reports/page.tsx b/app/(dashboard)/reports/page.tsx index 19d92d0b..59c74787 100644 --- a/app/(dashboard)/reports/page.tsx +++ b/app/(dashboard)/reports/page.tsx @@ -2,14 +2,16 @@ import React, { useState, useEffect, useCallback } from 'react' import Link from 'next/link' +import { useRouter } from 'next/navigation' import { useTranslations } from 'next-intl' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Skeleton } from "@/components/ui/skeleton" import { Button } from '@/components/ui/button' import { Label } from '@/components/ui/label' import { Badge } from '@/components/ui/badge' -import { Download, AlertCircle, ChevronDown, ChevronRight, ArrowRight } from 'lucide-react' +import { Download, FileSpreadsheet, AlertCircle, ChevronDown, ChevronRight, ArrowRight } from 'lucide-react' import { formatDate } from '@/lib/utils' +import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver' import { AccountNumber } from '@/components/ui/account-number' import { useCompany } from '@/contexts/CompanyContext' import { FiscalYearSelector } from '@/components/common/FiscalYearSelector' @@ -22,6 +24,11 @@ import { TrialBalanceChart } from '@/components/reports/TrialBalanceChart' import { VatCompositionChart } from '@/components/reports/VatCompositionChart' import { SkatteverketPanel } from '@/components/reports/SkatteverketPanel' import { IncomeExpenseChart } from '@/components/reports/IncomeExpenseChart' +import { useReportRowExpansion } from '@/components/reports/ReportRowExpansion' +import type { + ReportSourceLine, + ReportSourceFetcher, +} from '@/lib/reports/source-lines' import type { MonthlyDataPoint } from '@/components/reports/IncomeExpenseChart' import type { TrialBalanceRow, @@ -54,6 +61,7 @@ const TAB_LABEL_KEYS: Record = { } export default function ReportsPage() { + const router = useRouter() const [selectedPeriod, setSelectedPeriod] = useState('') const [activeTab, setActiveTab] = useState('resultatrapport') const [isLoadingInit, setIsLoadingInit] = useState(true) @@ -74,11 +82,27 @@ export default function ReportsPage() { }, [activeTab, t]) const handleTabChange = useCallback((tab: string) => { + // Kassaflödesanalys lives on its own route; route there instead of swapping tabs. + if (tab === 'kassaflodesanalys') { + router.push('/reports/kassaflodesanalys') + return + } + // Årsredovisning is an editable document (narrative + signatures) and lives + // on its own route under the year-end flow. Forward the active period so + // the page opens directly on the right fiscal year. + if (tab === 'arsredovisning') { + router.push( + selectedPeriod + ? `/bookkeeping/year-end/arsredovisning?period=${selectedPeriod}` + : '/bookkeeping/year-end/arsredovisning', + ) + return + } // Manual tab change clears drill-down state setActiveTab(tab) setGlAccountFilter(null) setDrillDownTrail([]) - }, []) + }, [router, selectedPeriod]) const navigateBack = useCallback((stepIndex: number) => { const step = drillDownTrail[stepIndex] @@ -300,6 +324,16 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string; return (
+
+ +
@@ -342,6 +376,7 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string; + @@ -350,38 +385,23 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string; - {data.rows.map((row) => { - const ob = getNetBalance(row, 'opening') - const ch = getNetBalance(row, 'period') - const cb = getNetBalance(row, 'closing') - return ( - onNavigateToAccount(row.account_number)} - > - - - - - - - ) - })} + {data.rows.map((row) => ( + + ))}
Konto Namn Ingående saldo
- - {row.account_name} - {formatSigned(ob)} - - {formatSigned(ch)} - - {formatSigned(cb)} -
) : ( + @@ -392,32 +412,17 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string; {data.rows.map((row) => ( - onNavigateToAccount(row.account_number)} - > - - - - - - - + row={row} + periodId={periodId} + onNavigateToAccount={onNavigateToAccount} + /> ))} + + + + + + + + + + + ) +} + +function TrialBalanceDetailedRow({ + row, + periodId, + onNavigateToAccount, +}: { + row: TrialBalanceRow + periodId: string + onNavigateToAccount: (account: string) => void +}) { + const fetcher = React.useMemo( + () => makeTrialBalanceFetcher(row.account_number, periodId), + [row.account_number, periodId] + ) + const { Toggle, Panel } = useReportRowExpansion(fetcher, `tb-det-${row.account_number}`) + + return ( + <> + + + + + + + + + + + + ) +} function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) { const t = useTranslations('reports') const [data, setData] = useState(null) @@ -515,7 +641,7 @@ function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: stri return (
-
+
+
{!monthlyLoading && monthlyData.length > 0 && ( @@ -661,7 +795,7 @@ function BalanceSheetView({ periodId, onNavigateToAccount }: { periodId: string; return (
-
+
+
{/* Assets */} @@ -783,10 +925,11 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri } const hasPrior = data.prior_period !== null + const colCount = 4 return (
-
+
+
@@ -813,7 +964,7 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri {data.groups.map((group) => (
- @@ -852,7 +1003,7 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri -
+
Beräknat resultat = 0 ? 'text-success' : 'text-destructive'}`}> {formatAmount(data.net_result_current)} kr @@ -925,7 +1076,7 @@ function BalansrapportView({ periodId, onNavigateToAccount }: { periodId: string return (
-
+
+
@@ -1149,6 +1308,16 @@ function VatDeclarationView() { return (
+
+ +
{/* Period selection */} @@ -1250,31 +1419,42 @@ function VatDeclarationView() {
Konto Namn Period debet
- - {row.account_name} - {row.period_debit > 0 ? formatAmount(row.period_debit) : ''} - - {row.period_credit > 0 ? formatAmount(row.period_credit) : ''} - - {row.closing_debit > 0 ? formatAmount(row.closing_debit) : ''} - - {row.closing_credit > 0 ? formatAmount(row.closing_credit) : ''} -
Summa {formatAmount(data.rows.reduce((s, r) => s + r.period_debit, 0))} @@ -441,6 +446,127 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string; ) } + +// Lazy fetcher for a TB account's source lines. Memoised at the row level so +// repeated toggling never refetches. +function makeTrialBalanceFetcher(accountNumber: string, periodId: string): ReportSourceFetcher { + return async () => { + const res = await fetch( + `/api/reports/trial-balance/account/${encodeURIComponent(accountNumber)}/sources?fiscal_period_id=${encodeURIComponent(periodId)}` + ) + const json = await res.json() + if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat') + const lines: ReportSourceLine[] = json.data?.lines || [] + return { lines, next_cursor: json.data?.next_cursor ?? null } + } +} + +function TrialBalanceSimplifiedRow({ + row, + periodId, + onNavigateToAccount, + getNetBalance, + formatSigned, +}: { + row: TrialBalanceRow + periodId: string + onNavigateToAccount: (account: string) => void + getNetBalance: (row: TrialBalanceRow, type: 'opening' | 'period' | 'closing') => number + formatSigned: (amount: number) => string +}) { + const fetcher = React.useMemo( + () => makeTrialBalanceFetcher(row.account_number, periodId), + [row.account_number, periodId] + ) + const { Toggle, Panel } = useReportRowExpansion(fetcher, `tb-${row.account_number}`) + + const ob = getNetBalance(row, 'opening') + const ch = getNetBalance(row, 'period') + const cb = getNetBalance(row, 'closing') + + return ( + <> +
e.stopPropagation()}> + + onNavigateToAccount(row.account_number)} + > + + onNavigateToAccount(row.account_number)} + > + {row.account_name} + + {formatSigned(ob)} + + {formatSigned(ch)} + + {formatSigned(cb)} +
e.stopPropagation()}> + + onNavigateToAccount(row.account_number)} + > + + onNavigateToAccount(row.account_number)} + > + {row.account_name} + + {row.period_debit > 0 ? formatAmount(row.period_debit) : ''} + + {row.period_credit > 0 ? formatAmount(row.period_credit) : ''} + + {row.closing_debit > 0 ? formatAmount(row.closing_debit) : ''} + + {row.closing_credit > 0 ? formatAmount(row.closing_credit) : ''} +
+ {group.class_label}
{data.rutor.ruta05 > 0 && ( - - - - + )} @@ -1311,14 +1497,14 @@ function VatDeclarationView() {

Omvänd skattskyldighet (inköp)

- 05 - Momspliktig försäljning - {formatAmount(data.rutor.ruta05)} kr
- - - - - - - - + + + + + + + +
@@ -1330,13 +1516,15 @@ function VatDeclarationView() {

Ingående moms (avdragsgill)

- - - - + {data.breakdown.transactions.ruta48 > 0 && ( @@ -1411,19 +1599,49 @@ function VatDeclarationView() { ) } +function makeVatFetcher(ruta: string, periodType: VatPeriodType, year: number, period: number): ReportSourceFetcher { + return async () => { + const res = await fetch( + `/api/reports/vat-declaration/ruta/${encodeURIComponent(ruta)}/sources?periodType=${periodType}&year=${year}&period=${period}` + ) + const json = await res.json() + if (!res.ok) throw new Error(json.error || 'Kunde inte hämta verifikat') + const lines: ReportSourceLine[] = json.data?.lines || [] + return { lines, next_cursor: json.data?.next_cursor ?? null } + } +} + function VatRutaRow({ ruta, label, amount, baseAmount, noVat, + periodType, + year, + period, }: { ruta: string label: string amount: number baseAmount: number noVat?: boolean + periodType?: VatPeriodType + year?: number + period?: number }) { + const canDrill = periodType !== undefined && year !== undefined && period !== undefined + const fetcher = React.useMemo( + () => (canDrill ? makeVatFetcher(ruta, periodType!, year!, period!) : null), + [canDrill, ruta, periodType, year, period] + ) + // Hooks must be called unconditionally — provide a noop fetcher when drill + // is disabled. The early-return for zero rows lives below the hooks. + const expansion = useReportRowExpansion( + fetcher ?? (async () => ({ lines: [], next_cursor: null })), + `vat-${ruta}` + ) + // Don't show rows with zero values if (baseAmount === 0 && amount === 0) return null @@ -1431,17 +1649,23 @@ function VatRutaRow({ <> - + {!noVat && baseAmount > 0 && ( - + )} + {canDrill && } ) } @@ -1535,6 +1759,16 @@ function SupplierLedgerView({ periodId }: { periodId: string }) { return (
+
+ +
{/* Summary cards */}
@@ -1579,6 +1813,7 @@ function SupplierLedgerView({ periodId }: { periodId: string }) {
- 48 - Ingående moms att dra av - {formatAmount(data.rutor.ruta48)} kr
- från transaktioner
+ {canDrill && ( + + + + )} {ruta} {label} {noVat ? `${formatAmount(baseAmount)} kr` : `${formatAmount(amount)} kr`}{noVat ? `${formatAmount(baseAmount)} kr` : `${formatAmount(amount)} kr`}
Underlag{formatAmount(baseAmount)} kr{formatAmount(baseAmount)} kr
+ @@ -1590,19 +1825,12 @@ function SupplierLedgerView({ periodId }: { periodId: string }) { {ledger.entries.map((entry) => ( - - - - - - - - - + ))} + @@ -1659,6 +1887,54 @@ function SupplierLedgerView({ periodId }: { periodId: string }) { ) } +function makeSupplierFetcher(supplierId: string): ReportSourceFetcher { + return async () => { + const res = await fetch( + `/api/reports/supplier-ledger/supplier/${encodeURIComponent(supplierId)}/invoices` + ) + const json = await res.json() + if (!res.ok) throw new Error(json.error || 'Kunde inte hämta leverantörsfakturor') + const lines: ReportSourceLine[] = json.data?.lines || [] + return { lines, next_cursor: json.data?.next_cursor ?? null } + } +} + +function SupplierLedgerRow({ + entry, +}: { + entry: { + supplier_id: string + supplier_name: string + current: number + days_1_30: number + days_31_60: number + days_61_90: number + days_90_plus: number + total_outstanding: number + } +}) { + const fetcher = React.useMemo( + () => makeSupplierFetcher(entry.supplier_id), + [entry.supplier_id] + ) + const { Toggle, Panel } = useReportRowExpansion(fetcher, `sup-${entry.supplier_id}`) + return ( + <> + + + + + + + + + + + + + ) +} + // --- General Ledger (Huvudbok) --- interface GeneralLedgerData { @@ -1758,6 +2034,16 @@ function GeneralLedgerView({ periodId, initialAccountFilter }: { periodId: strin return (
+
+ +
{/* Account range filter */} @@ -1827,7 +2113,7 @@ function GeneralLedgerView({ periodId, initialAccountFilter }: { periodId: strin href={`/bookkeeping/${line.journal_entry_id}`} className="text-foreground underline underline-offset-4 decoration-muted-foreground/40 hover:decoration-foreground transition-colors" > - {line.voucher_series}{line.voucher_number} + {formatVoucher(line)}
@@ -1957,6 +2243,16 @@ function JournalRegisterView({ periodId }: { periodId: string }) { return (
+
+ +
{data.period.start && (

Period: {data.period.start} — {data.period.end} | {data.total_entries} verifikationer @@ -1999,7 +2295,7 @@ function JournalRegisterView({ periodId }: { periodId: string }) { )}

+ + + + + + + + ) + })} + {loading && ( + + + + + )} + + ) +} + function ARLedgerView({ periodId }: { periodId: string }) { const [data, setData] = useState(null) const [loading, setLoading] = useState(false) @@ -2161,6 +2553,16 @@ function ARLedgerView({ periodId }: { periodId: string }) { return (
+
+ +
{/* Summary cards */}
@@ -2239,26 +2641,12 @@ function ARLedgerView({ periodId }: { periodId: string }) {
- {isExpanded && entry.invoices.map((inv) => ( - - - - - - - - - ))} + {isExpanded && ( + + )} ) })} diff --git a/app/(dashboard)/salary/runs/[id]/employees/[employeeId]/page.tsx b/app/(dashboard)/salary/runs/[id]/employees/[employeeId]/page.tsx index 758ff6af..2ca047c1 100644 --- a/app/(dashboard)/salary/runs/[id]/employees/[employeeId]/page.tsx +++ b/app/(dashboard)/salary/runs/[id]/employees/[employeeId]/page.tsx @@ -13,6 +13,12 @@ const LINE_ITEM_TYPE_LABELS: Record = { monthly_salary: 'Månadslön', hourly_salary: 'Timlön', overtime: 'Övertid', + overtime_50: 'Övertid 50 %', + overtime_100: 'Övertid 100 %', + ob_weekday_evening: 'OB vardag kväll', + ob_weekend: 'OB helg', + ob_night: 'OB natt', + ob_holiday: 'OB helgdag', bonus: 'Bonus', commission: 'Provision', gross_deduction_pension: 'Bruttoavdrag — pension', diff --git a/app/(dashboard)/settings/bookkeeping/page.tsx b/app/(dashboard)/settings/bookkeeping/page.tsx index c887b4b6..41cd37a9 100644 --- a/app/(dashboard)/settings/bookkeeping/page.tsx +++ b/app/(dashboard)/settings/bookkeeping/page.tsx @@ -1,21 +1,34 @@ 'use client' import Link from 'next/link' +import { useState } from 'react' import { useTranslations } from 'next-intl' import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper' import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton' import { PeriodLockingSettings } from '@/components/settings/PeriodLockingSettings' import { VoucherSeriesManager } from '@/components/settings/VoucherSeriesManager' +import { VoucherSeriesPerSourceTypeForm } from '@/components/settings/VoucherSeriesPerSourceTypeForm' +import { PeriodiseringAutoDetectToggle } from '@/components/settings/PeriodiseringAutoDetectToggle' +import { AccountingFrameworkForm } from '@/components/settings/AccountingFrameworkForm' import { useSettings } from '@/components/settings/useSettings' +import { useCompany } from '@/contexts/CompanyContext' import { Label } from '@/components/ui/label' import { ExternalLink } from 'lucide-react' -import type { CompanySettings } from '@/types' +import type { AccountingFramework, CompanySettings } from '@/types' const SERIES_OPTIONS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('') export default function BookkeepingSettingsPage() { const t = useTranslations('settings_bookkeeping') const { settings, isLoading, updateSettings } = useSettings() + const { company } = useCompany() + // Local mirror of the company-level accounting_framework so the K2/K3 + // selector can reflect its own saves without waiting for the layout to + // re-render through the server. Falls back to k2 (matches the column + // default) until the company row is loaded. + const [framework, setFramework] = useState( + company?.accounting_framework ?? 'k2', + ) if (isLoading || !settings) return @@ -39,8 +52,19 @@ export default function BookkeepingSettingsPage() { } } + // K2/K3 selector is only meaningful for AB. EF stays on EF rules and never + // picks a framework. Use the company row (source of truth) since + // company_settings.entity_type can be stale on legacy data. + const isAktiebolag = company?.entity_type === 'aktiebolag' + return (
+ {isAktiebolag && ( + setFramework(next)} + /> + )} {/* Accounting method */}
@@ -95,11 +119,24 @@ export default function BookkeepingSettingsPage() {
+ {/* Voucher series — per-source-type mapping */} +
+ +
+ {/* Voucher series — read-only display */}
+ {/* Periodisering auto-detect toggle */} +
+ +
+ {/* Cross-links */}

diff --git a/app/(dashboard)/settings/layout.tsx b/app/(dashboard)/settings/layout.tsx index a145e22f..21a88cc3 100644 --- a/app/(dashboard)/settings/layout.tsx +++ b/app/(dashboard)/settings/layout.tsx @@ -14,6 +14,7 @@ const TAB_TO_ROUTE: Record = { team: '/settings/team', banking: '/settings/banking', templates: '/settings/templates', + 'approval-rules': '/settings/approval-rules', account: '/settings/account', api: '/settings/api', } diff --git a/app/(dashboard)/skattekonto/page.tsx b/app/(dashboard)/skattekonto/page.tsx index 1fdf69d0..cced4501 100644 --- a/app/(dashboard)/skattekonto/page.tsx +++ b/app/(dashboard)/skattekonto/page.tsx @@ -17,6 +17,7 @@ import { } from '@/components/ui/dialog' import { useToast } from '@/components/ui/use-toast' import { formatCurrency } from '@/lib/utils' +import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver' import { Copy, ExternalLink, @@ -517,7 +518,10 @@ function TransactionTable({

Möjlig dublett av{' '} {row.match_suggestion.voucher_series && row.match_suggestion.voucher_number - ? `${row.match_suggestion.voucher_series}${row.match_suggestion.voucher_number}` + ? formatVoucher({ + voucher_series: row.match_suggestion.voucher_series, + voucher_number: row.match_suggestion.voucher_number, + }) : 'utkast'}{' '} ({row.match_suggestion.entry_date})

@@ -647,9 +651,7 @@ function MatchDialog({ {c.entry_date} - {c.voucher_series && c.voucher_number - ? `${c.voucher_series}${c.voucher_number}` - : '–'} + {formatVoucher(c)} {c.description} diff --git a/app/(public)/invoice-action/[token]/page.tsx b/app/(public)/invoice-action/[token]/page.tsx index 0ab618ed..10293488 100644 --- a/app/(public)/invoice-action/[token]/page.tsx +++ b/app/(public)/invoice-action/[token]/page.tsx @@ -22,6 +22,14 @@ interface InvoiceData { reminderLevel: number alreadyResponded: boolean previousResponse: 'marked_paid' | 'disputed' | null + // Dröjsmålsränta + lagstadgad påminnelseavgift (Räntelagen §6, Lag 1981:739). + // Default to 0 for older reminders sent before the surcharge feature shipped. + interestAmount: number + interestRate: number + interestFromDate: string | null + interestDays: number | null + reminderFee: number + totalDue: number } export default function InvoiceActionPage({ params }: { params: Promise<{ token: string }> }) { @@ -179,13 +187,46 @@ export default function InvoiceActionPage({ params }: { params: Promise<{ token:

-
-

+

+

Förfallen med {daysOverdue} dagar

-

- {formatCurrency(invoice.total, invoice.currency)} + + {(invoice.interestAmount > 0 || invoice.reminderFee > 0) && ( +

+
+ Ursprungligt belopp + {formatCurrency(invoice.total, invoice.currency)} +
+ {invoice.interestAmount > 0 && ( +
+ + Dröjsmålsränta + {invoice.interestRate > 0 && invoice.interestDays != null + ? ` (${(invoice.interestRate * 100).toLocaleString('sv-SE', { maximumFractionDigits: 2 })}% per år, ${invoice.interestDays} dagar)` + : ''} + + {formatCurrency(invoice.interestAmount, invoice.currency)} +
+ )} + {invoice.reminderFee > 0 && ( +
+ Påminnelseavgift + {formatCurrency(invoice.reminderFee, invoice.currency)} +
+ )} +
+
+ )} + +

+ {formatCurrency(invoice.totalDue || invoice.total, invoice.currency)}

+ {(invoice.interestAmount > 0 || invoice.reminderFee > 0) && ( +

+ Att betala (inkl. dröjsmålsränta och påminnelseavgift) +

+ )}
{error && ( diff --git a/app/api/account/password/__tests__/route.test.ts b/app/api/account/password/__tests__/route.test.ts index 9dca9705..bbd8fbe5 100644 --- a/app/api/account/password/__tests__/route.test.ts +++ b/app/api/account/password/__tests__/route.test.ts @@ -12,8 +12,10 @@ import { POST } from '../route' const mockCreateClient = vi.mocked(createClient) const mockCreateServiceClient = vi.mocked(createServiceClient) +type AuthMetadata = Record + function mockUserClient(opts: { - user: { id: string } | null + user: { id: string; app_metadata?: AuthMetadata } | null updateUserError?: { message: string; status?: number; code?: string } | null }) { const updateUser = vi.fn().mockResolvedValue({ @@ -33,12 +35,24 @@ function mockUserClient(opts: { } function mockService(opts: { - priorAppMetadata?: Record - updateUserByIdError?: Error | null + priorAppMetadata?: AuthMetadata + // Returned-error from admin.updateUserById when called with { password } + passwordSetError?: { message: string; status?: number; code?: string } | null + // Thrown error from admin.updateUserById when called with { app_metadata } + flagFlipError?: Error | null }) { - const updateUserById = opts.updateUserByIdError - ? vi.fn().mockRejectedValue(opts.updateUserByIdError) - : vi.fn().mockResolvedValue({ data: {}, error: null }) + const updateUserById = vi + .fn() + .mockImplementation((_id: string, args: Record) => { + if ('password' in args) { + return Promise.resolve({ + data: {}, + error: opts.passwordSetError ?? null, + }) + } + if (opts.flagFlipError) return Promise.reject(opts.flagFlipError) + return Promise.resolve({ data: {}, error: null }) + }) const getUserById = vi.fn().mockResolvedValue({ data: { user: { app_metadata: opts.priorAppMetadata ?? {} } }, @@ -54,6 +68,18 @@ function mockService(opts: { const STRONG_PASSWORD = 'StrongP@ssword1' +function flagFlipCall(updateUserById: ReturnType) { + return updateUserById.mock.calls.find( + ([, args]) => args && typeof args === 'object' && 'app_metadata' in args, + ) +} + +function passwordSetCall(updateUserById: ReturnType) { + return updateUserById.mock.calls.find( + ([, args]) => args && typeof args === 'object' && 'password' in args, + ) +} + beforeEach(() => { vi.clearAllMocks() }) @@ -72,8 +98,8 @@ describe('POST /api/account/password', () => { }) it('returns 400 when password is too weak', async () => { - mockUserClient({ user: { id: 'user-1' } }) - mockService({}) + mockUserClient({ user: { id: 'user-1', app_metadata: { has_password: true } } }) + mockService({ priorAppMetadata: { has_password: true } }) const req = createMockRequest('/api/account/password', { method: 'POST', @@ -83,65 +109,187 @@ describe('POST /api/account/password', () => { expect(status).toBe(400) }) - it('returns 400 when Supabase rejects the password update', async () => { - const { updateUser } = mockUserClient({ - user: { id: 'user-1' }, - updateUserError: { message: 'Password too similar to old', status: 400 }, - }) - const { updateUserById } = mockService({}) + describe('first-time set (has_password !== true)', () => { + it('writes the password via admin API and flips the flag', async () => { + const { updateUser } = mockUserClient({ + user: { + id: 'user-1', + app_metadata: { has_password: false, bankid_linked: true }, + }, + }) + const { updateUserById } = mockService({ + priorAppMetadata: { has_password: false, bankid_linked: true }, + }) - const req = createMockRequest('/api/account/password', { - method: 'POST', - body: { password: STRONG_PASSWORD }, - }) - const { status, body } = await parseJsonResponse<{ error?: string }>( - await POST(req), - ) - expect(status).toBe(400) - expect(body.error).toContain('Password too similar') - expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD }) - // Flag should NOT be flipped on a failed password update - expect(updateUserById).not.toHaveBeenCalled() - }) + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status, body } = await parseJsonResponse<{ + data?: { ok: boolean } + }>(await POST(req)) - it('flips app_metadata.has_password to true on success and preserves siblings', async () => { - const { updateUser } = mockUserClient({ user: { id: 'user-1' } }) - const { getUserById, updateUserById } = mockService({ - priorAppMetadata: { bankid_linked: true, provider: 'email' }, + expect(status).toBe(200) + expect(body.data?.ok).toBe(true) + // Did NOT go through the user session — that path would fail with AAL2. + expect(updateUser).not.toHaveBeenCalled() + // Password set via admin + expect(passwordSetCall(updateUserById)).toEqual([ + 'user-1', + { password: STRONG_PASSWORD }, + ]) + // Flag flipped, siblings preserved + expect(flagFlipCall(updateUserById)).toEqual([ + 'user-1', + { + app_metadata: { + has_password: true, + bankid_linked: true, + }, + }, + ]) }) - const req = createMockRequest('/api/account/password', { - method: 'POST', - body: { password: STRONG_PASSWORD }, + it('treats unset has_password as first-time set', async () => { + const { updateUser } = mockUserClient({ + user: { id: 'user-1' /* no app_metadata */ }, + }) + const { updateUserById } = mockService({}) + + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status } = await parseJsonResponse(await POST(req)) + + expect(status).toBe(200) + expect(updateUser).not.toHaveBeenCalled() + expect(passwordSetCall(updateUserById)).toBeDefined() }) - const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>( - await POST(req), - ) - expect(status).toBe(200) - expect(body.data?.ok).toBe(true) - expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD }) - expect(getUserById).toHaveBeenCalledWith('user-1') - expect(updateUserById).toHaveBeenCalledWith('user-1', { - app_metadata: { - bankid_linked: true, - provider: 'email', - has_password: true, - }, + + it('returns 400 and skips flag flip when the admin password set fails', async () => { + const { updateUser } = mockUserClient({ + user: { id: 'user-1', app_metadata: { has_password: false } }, + }) + const { updateUserById } = mockService({ + priorAppMetadata: { has_password: false }, + passwordSetError: { message: 'Password too weak', status: 400 }, + }) + + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status, body } = await parseJsonResponse<{ error?: string }>( + await POST(req), + ) + + expect(status).toBe(400) + expect(body.error).toContain('Password too weak') + expect(updateUser).not.toHaveBeenCalled() + expect(flagFlipCall(updateUserById)).toBeUndefined() + }) + + it('still returns success when the flag flip fails after admin password set', async () => { + mockUserClient({ + user: { id: 'user-1', app_metadata: { has_password: false } }, + }) + mockService({ + priorAppMetadata: { has_password: false }, + flagFlipError: new Error('admin down'), + }) + + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status, body } = await parseJsonResponse<{ + data?: { ok: boolean } + }>(await POST(req)) + + expect(status).toBe(200) + expect(body.data?.ok).toBe(true) }) }) - it('still returns success when the flag flip fails (password is set; logged)', async () => { - mockUserClient({ user: { id: 'user-1' } }) - mockService({ updateUserByIdError: new Error('admin down') }) + describe('change-password (has_password === true)', () => { + it('writes via the user session so Supabase enforces AAL2', async () => { + const { updateUser } = mockUserClient({ + user: { id: 'user-1', app_metadata: { has_password: true } }, + }) + const { updateUserById } = mockService({ + priorAppMetadata: { has_password: true, provider: 'email' }, + }) - const req = createMockRequest('/api/account/password', { - method: 'POST', - body: { password: STRONG_PASSWORD }, + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status, body } = await parseJsonResponse<{ + data?: { ok: boolean } + }>(await POST(req)) + + expect(status).toBe(200) + expect(body.data?.ok).toBe(true) + // Used user session, NOT admin API for the password itself + expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD }) + expect(passwordSetCall(updateUserById)).toBeUndefined() + // Flag is still flipped (idempotent) with siblings preserved + expect(flagFlipCall(updateUserById)).toEqual([ + 'user-1', + { + app_metadata: { + has_password: true, + provider: 'email', + }, + }, + ]) + }) + + it('returns 400 and skips flag flip when Supabase rejects the password update', async () => { + const { updateUser } = mockUserClient({ + user: { id: 'user-1', app_metadata: { has_password: true } }, + updateUserError: { message: 'Password too similar to old', status: 400 }, + }) + const { updateUserById } = mockService({ + priorAppMetadata: { has_password: true }, + }) + + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status, body } = await parseJsonResponse<{ error?: string }>( + await POST(req), + ) + + expect(status).toBe(400) + expect(body.error).toContain('Password too similar') + expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD }) + expect(flagFlipCall(updateUserById)).toBeUndefined() + }) + + it('surfaces the AAL2 error verbatim so the client can step up via /mfa/verify', async () => { + mockUserClient({ + user: { id: 'user-1', app_metadata: { has_password: true } }, + updateUserError: { + message: + 'AAL2 session is required to update email or password when MFA is enabled', + status: 422, + }, + }) + mockService({ priorAppMetadata: { has_password: true } }) + + const req = createMockRequest('/api/account/password', { + method: 'POST', + body: { password: STRONG_PASSWORD }, + }) + const { status, body } = await parseJsonResponse<{ error?: string }>( + await POST(req), + ) + + expect(status).toBe(400) + expect(body.error).toContain('AAL2') }) - const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>( - await POST(req), - ) - expect(status).toBe(200) - expect(body.data?.ok).toBe(true) }) }) diff --git a/app/api/account/password/route.ts b/app/api/account/password/route.ts index 602b311a..cd258e06 100644 --- a/app/api/account/password/route.ts +++ b/app/api/account/password/route.ts @@ -23,12 +23,25 @@ const SetPasswordSchema = z.object({ /** * POST /api/account/password * - * Server-routed password set/change. Wraps `supabase.auth.updateUser({ password })` - * on the user's own session, then flips `app_metadata.has_password = true` via the - * service client (clients can't write app_metadata). + * Server-routed password set/change, then flips `app_metadata.has_password = + * true` via the service client (clients can't write app_metadata). + * + * Two paths depending on whether the user already has a real password: + * + * - First-time set (`app_metadata.has_password !== true`): write via the + * admin API. BankID-only users — and legacy users whose `has_password` + * flag was set to false by the backfill — sit at AAL1 with a TOTP factor + * enrolled, and `updateUser` on the user session would be rejected with + * "AAL2 session is required to update email or password when MFA is + * enabled". Setting an initial password has no existing credential to + * protect, so bypassing AAL2 is safe. + * + * - Change-password (`app_metadata.has_password === true`): write via the + * user session so Supabase's AAL2 guard still fires. A stolen AAL1 + * cookie must not be able to rotate a known password. * * This route is the single write path for setting a password. SecuritySettings, - * the reset-password page, and the new /account/set-password page all funnel + * the reset-password page, and the /account/set-password page all funnel * through here so the flag stays in sync — see lib/auth/has-password.ts. * * If the password update succeeds but the flag write fails, we log and still @@ -49,11 +62,29 @@ export async function POST(request: Request) { if (!result.success) return result.response const { password } = result.data - const { error: updateError } = await supabase.auth.updateUser({ password }) + const isFirstTimeSet = user.app_metadata?.has_password !== true + const service = createServiceClient() + + let updateError: + | { message?: string; status?: number; code?: string } + | null + | undefined = null + + if (isFirstTimeSet) { + const { error } = await service.auth.admin.updateUserById(user.id, { + password, + }) + updateError = error + } else { + const { error } = await supabase.auth.updateUser({ password }) + updateError = error + } + if (updateError) { - log.warn('updateUser({password}) failed', { + log.warn('password update failed', { userId: user.id, - code: (updateError as { code?: string }).code, + isFirstTimeSet, + code: updateError.code, status: updateError.status, }) return NextResponse.json( @@ -69,7 +100,6 @@ export async function POST(request: Request) { // Read-merge-write so we don't wipe sibling app_metadata keys. // updateUserById replaces app_metadata wholesale (see lib/auth/has-password.ts // and the comment in app/api/account/delete/route.ts). - const service = createServiceClient() let flagWriteOk = false try { const { data: u } = await service.auth.admin.getUserById(user.id) @@ -87,7 +117,7 @@ export async function POST(request: Request) { // banner will show once more and a retry will succeed. } - log.info('password set', { userId: user.id, flagWriteOk }) + log.info('password set', { userId: user.id, isFirstTimeSet, flagWriteOk }) return NextResponse.json({ data: { ok: true } }) } diff --git a/app/api/assets/[id]/dispose/route.ts b/app/api/assets/[id]/dispose/route.ts index 9442f98e..3891be02 100644 --- a/app/api/assets/[id]/dispose/route.ts +++ b/app/api/assets/[id]/dispose/route.ts @@ -5,15 +5,87 @@ import { errorResponse } from '@/lib/errors/get-structured-error' import { validateBody } from '@/lib/api/validate' import { disposeAsset } from '@/lib/bokslut/assets/asset-service' -const DisposeAssetSchema = z.object({ - disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), - disposed_proceeds: z.number().nonnegative(), - proceeds_account: z.string().regex(/^\d{4}$/).optional(), - fiscal_period_id: z.string().uuid(), - // accumulated_depreciation is intentionally NOT accepted from the client — - // disposeAsset sums depreciation_schedules server-side so callers cannot - // inflate the book-value calculation. -}) +const VAT_TREATMENTS = [ + 'standard_25', + 'reduced_12', + 'reduced_6', + 'reverse_charge', + 'export', + 'exempt', +] as const + +const DisposeAssetSchema = z + .object({ + disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + /** Gross proceeds (INCL VAT when applicable). */ + disposed_proceeds: z.number().nonnegative(), + proceeds_account: z.string().regex(/^\d{4}$/).optional(), + fiscal_period_id: z.string().uuid(), + /** Output VAT on the proceeds. Defaults to 0 (sale was momsfri). */ + proceeds_vat: z.number().nonnegative().optional(), + /** Required when proceeds_vat > 0 so the engine can resolve a 26xx account. */ + vat_treatment: z.enum(VAT_TREATMENTS).optional(), + /** Precomputed jämkning amount (ML 8a kap 7 §). Caller supplies; engine + * books a 2641 credit + loss-account debit. */ + jamkning_amount: z.number().nonnegative().optional(), + /** Audit metadata. */ + jamkning_remaining_months: z.number().int().nonnegative().optional(), + jamkning_total_months: z.number().int().positive().optional(), + jamkning_original_input_vat: z.number().nonnegative().optional(), + // accumulated_depreciation is intentionally NOT accepted from the client — + // disposeAsset sums depreciation_schedules server-side so callers cannot + // inflate the book-value calculation. + }) + .superRefine((value, ctx) => { + // VAT consistency: if a treatment that produces a VAT line is selected, + // the VAT amount must equal 25%/12%/6% of the net proceeds. Tolerance is + // ±0.50 kr to handle rounding on item prices. + if (value.proceeds_vat && value.proceeds_vat > 0) { + if (!value.vat_treatment) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['vat_treatment'], + message: 'vat_treatment krävs när proceeds_vat > 0.', + }) + return + } + const rate = vatRateFromTreatment(value.vat_treatment) + if (rate === null) { + // Treatments without a VAT line must carry 0 VAT. + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['proceeds_vat'], + message: `proceeds_vat måste vara 0 för momsbehandling "${value.vat_treatment}".`, + }) + return + } + // Expected: proceeds_gross = net × (1 + rate), so net = gross / (1 + rate) + // and vat = gross - net = gross × rate / (1 + rate). + const expectedVat = (value.disposed_proceeds * rate) / (1 + rate) + if (Math.abs(expectedVat - value.proceeds_vat) > 0.5) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['proceeds_vat'], + message: `proceeds_vat ska vara ~${Math.round(expectedVat * 100) / 100} kr för momsbehandling "${value.vat_treatment}" på ${value.disposed_proceeds} kr brutto.`, + }) + } + } + }) + +function vatRateFromTreatment(t: (typeof VAT_TREATMENTS)[number]): number | null { + switch (t) { + case 'standard_25': + return 0.25 + case 'reduced_12': + return 0.12 + case 'reduced_6': + return 0.06 + case 'reverse_charge': + case 'export': + case 'exempt': + return null + } +} export const POST = withRouteContext( 'assets.dispose', diff --git a/app/api/assets/[id]/route.ts b/app/api/assets/[id]/route.ts index 8309c575..1bfa7035 100644 --- a/app/api/assets/[id]/route.ts +++ b/app/api/assets/[id]/route.ts @@ -3,40 +3,66 @@ import { z } from 'zod' import { withRouteContext } from '@/lib/api/with-route-context' import { errorResponse } from '@/lib/errors/get-structured-error' import { validateBody } from '@/lib/api/validate' +import { K3ComponentSchema } from '@/lib/api/schemas' import { getAsset, updateAsset } from '@/lib/bokslut/assets/asset-service' +import { validateComponents } from '@/lib/bokslut/assets/k3-components' import type { DepreciationMethod } from '@/types' const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [ 'linear', 'declining_balance_30', 'declining_balance_20', + 'restvardesavskrivning_25', ] as const -// Engine only implements linear today — reject declining_balance methods on -// both create and update until the engine grows them. The DB enum keeps the -// other methods reserved for a future phase. -const SUPPORTED_DEPRECIATION_METHODS: readonly DepreciationMethod[] = ['linear'] as const +const UpdateAssetSchema = z + .object({ + name: z.string().min(1).optional(), + notes: z.string().nullable().optional(), + salvage_value: z.number().nonnegative().optional(), + useful_life_months: z.number().int().positive().optional(), + depreciation_method: z + .enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]]) + .optional(), + restvarde_target: z.number().nonnegative().nullable().optional(), + bas_asset_account: z.string().regex(/^\d{4}$/).optional(), + bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(), + bas_expense_account: z.string().regex(/^\d{4}$/).optional(), + // K3 component depreciation. Accepting `null` lets the caller clear an + // existing breakdown (the engine then falls back to depreciation_method). + // Per-component validation runs whenever the field is set to a non-null + // value; the cross-sum check needs acquisition_cost so it's deferred to + // updateAsset() which can read the existing row. + k3_components: z.array(K3ComponentSchema).nullable().optional(), + }) + .superRefine((value, ctx) => { + // Enforce the method/target biconditional when EITHER field is supplied. + // We can't see the existing row from a zod refinement, so the + // application-level updateAsset() carries the cross-row check; here we + // only catch the obviously inconsistent combinations within a single + // PATCH body. + const hasMethod = value.depreciation_method !== undefined + const hasTarget = value.restvarde_target !== undefined + if (!hasMethod && !hasTarget) return -const UpdateAssetSchema = z.object({ - name: z.string().min(1).optional(), - notes: z.string().nullable().optional(), - salvage_value: z.number().nonnegative().optional(), - useful_life_months: z.number().int().positive().optional(), - depreciation_method: z - .enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]]) - .optional() - .refine( - (m) => m === undefined || (SUPPORTED_DEPRECIATION_METHODS as readonly string[]).includes(m), - { - message: - 'Only "linear" depreciation is supported by the engine today. ' + - 'Declining-balance methods are reserved for a future phase.', - }, - ), - bas_asset_account: z.string().regex(/^\d{4}$/).optional(), - bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(), - bas_expense_account: z.string().regex(/^\d{4}$/).optional(), -}) + const isRestvarde = value.depreciation_method === 'restvardesavskrivning_25' + const targetIsSet = value.restvarde_target !== null && value.restvarde_target !== undefined + + if (hasMethod && isRestvarde && hasTarget && !targetIsSet) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['restvarde_target'], + message: 'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).', + }) + } + if (hasMethod && !isRestvarde && hasTarget && targetIsSet) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['restvarde_target'], + message: 'restvarde_target får bara anges för restvärdeavskrivning (25 %).', + }) + } + }) export const GET = withRouteContext( 'assets.get', @@ -62,6 +88,51 @@ export const PATCH = withRouteContext( const { supabase, companyId, log, requestId } = ctx const validation = await validateBody(request, UpdateAssetSchema) if (!validation.success) return validation.response + + // K3 component depreciation gating + cross-sum check. + // The Zod refinement cannot see the existing asset's acquisition_cost, + // so we do both the framework check and the sum validation here at + // route level before delegating to updateAsset(). + if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) { + const [{ data: company }, existing] = await Promise.all([ + supabase + .from('companies') + .select('accounting_framework') + .eq('id', companyId) + .single(), + getAsset(supabase, companyId, id), + ]) + if (!company || company.accounting_framework !== 'k3') { + return NextResponse.json( + { + error: { + code: 'K3_REQUIRED_FOR_COMPONENTS', + message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).', + }, + }, + { status: 422 }, + ) + } + if (!existing) { + return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 }) + } + const { errors } = validateComponents({ + acquisition_cost: Number(existing.acquisition_cost), + k3_components: validation.data.k3_components, + }) + if (errors.length > 0) { + return NextResponse.json( + { + error: { + code: 'INVALID_K3_COMPONENTS', + message: errors.join(' '), + }, + }, + { status: 400 }, + ) + } + } + try { const asset = await updateAsset(supabase, companyId, id, validation.data) return NextResponse.json({ data: asset }) diff --git a/app/api/assets/route.ts b/app/api/assets/route.ts index 2b961813..43046f3d 100644 --- a/app/api/assets/route.ts +++ b/app/api/assets/route.ts @@ -3,7 +3,9 @@ import { z } from 'zod' import { withRouteContext } from '@/lib/api/with-route-context' import { errorResponse } from '@/lib/errors/get-structured-error' import { validateBody } from '@/lib/api/validate' +import { K3ComponentSchema } from '@/lib/api/schemas' import { createAsset, listAssets } from '@/lib/bokslut/assets/asset-service' +import { validateComponents } from '@/lib/bokslut/assets/k3-components' import type { AssetCategory, DepreciationMethod } from '@/types' const ASSET_CATEGORIES: readonly AssetCategory[] = [ @@ -17,18 +19,16 @@ const ASSET_CATEGORIES: readonly AssetCategory[] = [ 'other_tangible', ] as const -// The DB enum keeps all three methods so future phases can add support -// without a migration, but the engine only implements linear today. Reject -// the unsupported methods at create to avoid silently producing wrong -// (linear) numbers under a misleading method label. +// All four depreciation methods are now implemented by the engine. The DB +// CHECK constraint mirrors this list (see +// 20260526120100_restvardeavskrivning.sql). const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [ 'linear', 'declining_balance_30', 'declining_balance_20', + 'restvardesavskrivning_25', ] as const -const SUPPORTED_DEPRECIATION_METHODS: readonly DepreciationMethod[] = ['linear'] as const - const CreateAssetSchema = z .object({ name: z.string().min(1), @@ -41,18 +41,21 @@ const CreateAssetSchema = z useful_life_months: z.number().int().positive(), depreciation_method: z .enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]]) - .optional() - .refine( - (m) => m === undefined || (SUPPORTED_DEPRECIATION_METHODS as readonly string[]).includes(m), - { - message: - 'Only "linear" depreciation is supported by the engine today. ' + - 'Declining-balance methods are reserved for a future phase.', - }, - ), + .optional(), + // Restvärde-target floor for restvärdeavskrivning. Required iff + // depreciation_method = 'restvardesavskrivning_25'. The DB CHECK enforces + // the same biconditional; we mirror it in the API for an early, Swedish + // error message rather than a Postgres check_violation surfacing. + restvarde_target: z.number().nonnegative().nullable().optional(), bas_asset_account: z.string().regex(/^\d{4}$/).optional(), bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(), bas_expense_account: z.string().regex(/^\d{4}$/).optional(), + // K3 component depreciation (BFNAR 2012:1 ch.17.4). Only meaningful for + // companies with accounting_framework='k3' — the route handler rejects + // K3_REQUIRED_FOR_COMPONENTS for K2 companies. When present, the engine + // dispatches to per-component linear depreciation instead of the + // asset-level depreciation_method. + k3_components: z.array(K3ComponentSchema).nullable().optional(), notes: z.string().optional(), }) .superRefine((value, ctx) => { @@ -60,8 +63,70 @@ const CreateAssetSchema = z // outside the legitimate range for the asset category so the chart stays // BAS-aligned and INK2R mappings continue to work. validateBasOverrides(value, ctx) + validateRestvardeTarget(value, ctx) + validateK3Components(value, ctx) }) +function validateK3Components( + value: { + acquisition_cost: number + k3_components?: { name: string; cost: number; useful_life_months: number; salvage_value?: number }[] | null + }, + ctx: z.RefinementCtx, +): void { + if (value.k3_components === undefined || value.k3_components === null) return + const { errors } = validateComponents({ + acquisition_cost: value.acquisition_cost, + k3_components: value.k3_components, + }) + for (const message of errors) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['k3_components'], + message, + }) + } +} + +function validateRestvardeTarget( + value: { + depreciation_method?: DepreciationMethod + restvarde_target?: number | null + acquisition_cost?: number + }, + ctx: z.RefinementCtx, +): void { + const isRestvarde = value.depreciation_method === 'restvardesavskrivning_25' + const hasTarget = value.restvarde_target !== undefined && value.restvarde_target !== null + if (isRestvarde && !hasTarget) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['restvarde_target'], + message: 'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).', + }) + } + if (!isRestvarde && hasTarget) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['restvarde_target'], + message: 'restvarde_target får bara anges för restvärdeavskrivning (25 %).', + }) + } + if ( + isRestvarde && + hasTarget && + value.acquisition_cost !== undefined && + (value.restvarde_target as number) >= value.acquisition_cost + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['restvarde_target'], + message: + 'restvarde_target måste vara lägre än anskaffningsvärdet — annars finns inget kvar att skriva av.', + }) + } +} + function validateBasOverrides( value: { category: AssetCategory @@ -151,6 +216,28 @@ export const POST = withRouteContext( const { user, supabase, companyId, log, requestId } = ctx const validation = await validateBody(request, CreateAssetSchema) if (!validation.success) return validation.response + // K3_REQUIRED_FOR_COMPONENTS: K3 component depreciation is only + // meaningful when the company applies the K3 framework. Reject the + // write with 422 (Unprocessable Entity) rather than silently dropping + // the field so the user knows their input was discarded. + if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) { + const { data: company } = await supabase + .from('companies') + .select('accounting_framework') + .eq('id', companyId) + .single() + if (!company || company.accounting_framework !== 'k3') { + return NextResponse.json( + { + error: { + code: 'K3_REQUIRED_FOR_COMPONENTS', + message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).', + }, + }, + { status: 422 }, + ) + } + } try { const asset = await createAsset(supabase, companyId, user.id, validation.data) return NextResponse.json({ data: asset }) diff --git a/app/api/bookkeeping/fiscal-periods/[id]/accruals/__tests__/route.test.ts b/app/api/bookkeeping/fiscal-periods/[id]/accruals/__tests__/route.test.ts new file mode 100644 index 00000000..146a9891 --- /dev/null +++ b/app/api/bookkeeping/fiscal-periods/[id]/accruals/__tests__/route.test.ts @@ -0,0 +1,104 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers' + +const mockCreateClient = vi.fn() +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => mockCreateClient(), +})) + +vi.mock('@/lib/init', () => ({ + ensureInitialized: vi.fn(), +})) + +vi.mock('@/lib/company/context', () => ({ + requireCompanyId: vi.fn().mockResolvedValue('company-1'), + getActiveCompanyId: vi.fn().mockResolvedValue('company-1'), +})) + +vi.mock('@/lib/auth/require-write', () => ({ + requireWritePermission: vi.fn().mockResolvedValue({ ok: true }), +})) + +const mockBuildAccrualsProposal = vi.fn() +const mockDetectPeriodisering = vi.fn() +vi.mock('@/lib/bokslut/accruals/accrual-detector', async () => { + const actual = + (await vi.importActual('@/lib/bokslut/accruals/accrual-detector')) as Record + return { + ...actual, + buildAccrualsProposal: (...args: unknown[]) => mockBuildAccrualsProposal(...args), + } +}) + +vi.mock('@/lib/bokslut/accruals/auto-detect', () => ({ + detectPeriodisering: (...args: unknown[]) => mockDetectPeriodisering(...args), +})) + +const mockUser = { id: 'user-1', email: 'test@test.se' } + +beforeEach(() => { + vi.clearAllMocks() + mockCreateClient.mockResolvedValue({ + auth: { getUser: vi.fn().mockResolvedValue({ data: { user: mockUser } }) }, + }) +}) + +describe('GET /api/bookkeeping/fiscal-periods/[id]/accruals', () => { + it('returns 401 when unauthenticated', async () => { + mockCreateClient.mockResolvedValue({ + auth: { getUser: vi.fn().mockResolvedValue({ data: { user: null } }) }, + }) + const { GET } = await import('../route') + const res = await GET( + createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'), + createMockRouteParams({ id: 'period-1' }), + ) + expect(res.status).toBe(401) + }) + + it('returns the snapshot plus autoDetected suggestions', async () => { + mockBuildAccrualsProposal.mockResolvedValue({ + fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' }, + proposals: [], + }) + mockDetectPeriodisering.mockResolvedValue([ + { + source_invoice_id: 'sup-1', + source_type: 'supplier_invoice', + original_amount: 12000, + periodisering_amount: 6000, + parsed_start: '2025-07-01', + parsed_end: '2026-06-30', + confidence: 'high', + reason: 'Mock reason', + source_label: 'Test Supplier', + suggested_prepaid_account: '1710', + suggested_deferred_account: null, + }, + ]) + const { GET } = await import('../route') + const res = await GET( + createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'), + createMockRouteParams({ id: 'period-1' }), + ) + const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res) + expect(status).toBe(200) + expect(body.data.autoDetected).toHaveLength(1) + }) + + it('still returns the snapshot when auto-detect throws', async () => { + mockBuildAccrualsProposal.mockResolvedValue({ + fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' }, + proposals: [], + }) + mockDetectPeriodisering.mockRejectedValue(new Error('boom')) + const { GET } = await import('../route') + const res = await GET( + createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'), + createMockRouteParams({ id: 'period-1' }), + ) + const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res) + expect(status).toBe(200) + expect(body.data.autoDetected).toEqual([]) + }) +}) diff --git a/app/api/bookkeeping/fiscal-periods/[id]/accruals/route.ts b/app/api/bookkeeping/fiscal-periods/[id]/accruals/route.ts index 10d4217a..b055df4f 100644 --- a/app/api/bookkeeping/fiscal-periods/[id]/accruals/route.ts +++ b/app/api/bookkeeping/fiscal-periods/[id]/accruals/route.ts @@ -6,11 +6,15 @@ import { validateBody } from '@/lib/api/validate' import { createJournalEntry } from '@/lib/bookkeeping/engine' import { buildAccrualsProposal, + proposeAccruedInterest, + proposeAccruedUtility, proposeAuditFee, proposeManualAccrued, proposeManualPrepaid, + proposeRevenueDeferral, proposeVacationLiabilityChange, } from '@/lib/bokslut/accruals/accrual-detector' +import { detectPeriodisering } from '@/lib/bokslut/accruals/auto-detect' import type { AccrualProposal } from '@/lib/bokslut/accruals/types' import type { JournalEntry } from '@/types' @@ -20,8 +24,18 @@ export const GET = withRouteContext( const { id } = await params const { supabase, companyId, log, requestId } = ctx try { - const proposal = await buildAccrualsProposal(supabase, companyId, id) - return NextResponse.json({ data: proposal }) + // Run the two independent scans in parallel so the wizard's first + // paint isn't gated on the slower auto-detect query. + const [proposal, autoDetected] = await Promise.all([ + buildAccrualsProposal(supabase, companyId, id), + detectPeriodisering(supabase, companyId, id).catch((err) => { + // Auto-detect is best-effort — a malformed invoice description + // shouldn't break the rest of the preflight. Log + return empty. + log.warn('auto-detect failed', { error: (err as Error)?.message }) + return [] + }), + ]) + return NextResponse.json({ data: { ...proposal, autoDetected } }) } catch (err) { const message = err instanceof Error ? err.message : '' if (/not found/i.test(message)) { @@ -32,6 +46,19 @@ export const GET = withRouteContext( }, ) +// Defense-in-depth on caller-supplied account numbers. The wizard sends +// accounts from a closed template list, but the API accepts them as plain +// strings so we constrain the BAS class per accrual kind: +// - cost accounts (5xxx-8xxx) for expense legs +// - revenue accounts (3xxx) for revenue legs +// - 17xx for förutbetalda kostnader (prepaid) +// - 29xx for upplupna poster (accrued / deferred) +// Anything outside these ranges is rejected with 400 before reaching the +// engine — keeps a compromised browser session from posting arbitrary +// balance-sheet hits. +const EXPENSE_ACCOUNT_RE = /^[5-8]\d{3}$/ +const REVENUE_ACCOUNT_RE = /^3\d{3}$/ + const PostItemSchema = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('vacation_liability_change') }), z.object({ @@ -42,14 +69,35 @@ const PostItemSchema = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('manual_prepaid_expense'), amount: z.number().positive(), - expense_account: z.string().regex(/^\d{4}$/), + expense_account: z.string().regex(EXPENSE_ACCOUNT_RE), prepaid_account: z.string().regex(/^17\d{2}$/), description: z.string().min(1), }), z.object({ kind: z.literal('manual_accrued_expense'), amount: z.number().positive(), - expense_account: z.string().regex(/^\d{4}$/), + expense_account: z.string().regex(EXPENSE_ACCOUNT_RE), + accrued_account: z.string().regex(/^29\d{2}$/), + description: z.string().min(1), + }), + z.object({ + kind: z.literal('deferred_revenue'), + amount: z.number().positive(), + revenue_account: z.string().regex(REVENUE_ACCOUNT_RE), + deferred_account: z.string().regex(/^29\d{2}$/), + description: z.string().min(1), + }), + z.object({ + kind: z.literal('accrued_interest'), + amount: z.number().positive(), + expense_account: z.string().regex(EXPENSE_ACCOUNT_RE), + accrued_account: z.string().regex(/^29\d{2}$/), + description: z.string().min(1), + }), + z.object({ + kind: z.literal('accrued_utility'), + amount: z.number().positive(), + expense_account: z.string().regex(EXPENSE_ACCOUNT_RE), accrued_account: z.string().regex(/^29\d{2}$/), description: z.string().min(1), }), @@ -132,6 +180,33 @@ export const POST = withRouteContext( closingDate: period.period_end, }) break + case 'deferred_revenue': + proposal = proposeRevenueDeferral({ + amount: item.amount, + revenueAccount: item.revenue_account, + deferredAccount: item.deferred_account, + description: item.description, + closingDate: period.period_end, + }) + break + case 'accrued_interest': + proposal = proposeAccruedInterest({ + amount: item.amount, + expenseAccount: item.expense_account, + accruedAccount: item.accrued_account, + description: item.description, + closingDate: period.period_end, + }) + break + case 'accrued_utility': + proposal = proposeAccruedUtility({ + amount: item.amount, + expenseAccount: item.expense_account, + accruedAccount: item.accrued_account, + description: item.description, + closingDate: period.period_end, + }) + break } if (!proposal) continue @@ -199,6 +274,15 @@ async function findExistingAccrualEntry( case 'manual_accrued_expense': pattern = `Periodisering: Upplupen kostnad: ${escapeLike(item.description)}%` break + case 'deferred_revenue': + pattern = `Periodisering: Förutbetald intäkt: ${escapeLike(item.description)}%` + break + case 'accrued_interest': + pattern = `Periodisering: Upplupen ränta: ${escapeLike(item.description)}%` + break + case 'accrued_utility': + pattern = `Periodisering: Upplupen förbrukning: ${escapeLike(item.description)}%` + break } const { data } = await supabase diff --git a/app/api/bookkeeping/fiscal-periods/[id]/arsredovisning/pdf/route.ts b/app/api/bookkeeping/fiscal-periods/[id]/arsredovisning/pdf/route.ts index 0b7856ec..de23f741 100644 --- a/app/api/bookkeeping/fiscal-periods/[id]/arsredovisning/pdf/route.ts +++ b/app/api/bookkeeping/fiscal-periods/[id]/arsredovisning/pdf/route.ts @@ -3,6 +3,7 @@ import { withRouteContext } from '@/lib/api/with-route-context' import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error' import { buildArsredovisningData } from '@/lib/bokslut/arsredovisning/build-data' import { ArsredovisningPDF } from '@/lib/bokslut/arsredovisning/arsredovisning-pdf' +import { ArsredovisningK3PDF } from '@/lib/bokslut/arsredovisning/arsredovisning-k3-pdf' export const GET = withRouteContext( 'period.arsredovisning_pdf', @@ -14,7 +15,15 @@ export const GET = withRouteContext( // inside buildArsredovisningData. The URL stays clean — no narrative // text in query params, access logs, or browser history. const data = await buildArsredovisningData(supabase, companyId, id) - const pdfBuffer = await renderToBuffer(ArsredovisningPDF({ data })) + // Dispatch on the framework recorded in the data. K3 documents need + // the additional kassaflöde + equity-changes pages + richer noter + // that ArsredovisningK3PDF renders. K2 (the default) keeps the + // existing template byte-for-byte unchanged. + const PdfComponent = + data.accounting_framework === 'k3' + ? ArsredovisningK3PDF + : ArsredovisningPDF + const pdfBuffer = await renderToBuffer(PdfComponent({ data })) // "-utkast" suffix mirrors the existing PDF routes; the file becomes // "fastställd" only after the signature flow records all signatures. // Sanitize the dynamic segment so a stray quote / newline in the date diff --git a/app/api/bookkeeping/fiscal-periods/[id]/bokslutsdispositioner/route.ts b/app/api/bookkeeping/fiscal-periods/[id]/bokslutsdispositioner/route.ts index 69284c02..3d92ea1e 100644 --- a/app/api/bookkeeping/fiscal-periods/[id]/bokslutsdispositioner/route.ts +++ b/app/api/bookkeeping/fiscal-periods/[id]/bokslutsdispositioner/route.ts @@ -13,7 +13,10 @@ import { } from '@/lib/bokslut/reserves/periodiseringsfond-service' import { proposeOveravskrivningar } from '@/lib/bokslut/reserves/overavskrivningar-service' import { generateIncomeStatement } from '@/lib/reports/income-statement' -import { buildDispositionsProposal } from '@/lib/bokslut/dispositions-proposal-builder' +import { + buildDispositionsProposal, + buildLatentTaxProposal, +} from '@/lib/bokslut/dispositions-proposal-builder' import type { ProposedDisposition } from '@/lib/bokslut/types' import type { JournalEntry } from '@/types' @@ -45,6 +48,9 @@ const DISPOSITION_ORDER: Record = { periodiseringsfond_avsattning: 2, sarskild_loneskatt: 3, bolagsskatt: 4, + // K3 only — posts last because it depends on the closing 21xx balance, + // which only stabilises once avsättning / återföring have been applied. + uppskjuten_skatt: 5, } // ============================================================ @@ -112,6 +118,11 @@ const ItemSchema = z.discriminatedUnion('kind', [ .enum(['machinery_equipment', 'building', 'immaterial', 'group']) .optional(), }), + // K3 only — uppskjuten skatt provision. Server recomputes the amount from + // current 2240 + 21xx state so the client cannot override it. + z.object({ + kind: z.literal('uppskjuten_skatt'), + }), ]) const PostBodySchema = z.object({ @@ -260,6 +271,15 @@ async function computeProposal( additionalAmount: item.additionalAmount, category: item.category, }) + case 'uppskjuten_skatt': + // Server-only: recompute from current TB (which already reflects any + // 21xx postings that committed earlier in this batch). The client + // sends no amount — the calculator owns the K3 split. + return buildLatentTaxProposal({ + supabase, + companyId, + fiscalPeriodId, + }) } } diff --git a/app/api/bookkeeping/journal-entries/route.ts b/app/api/bookkeeping/journal-entries/route.ts index da207be1..b806575e 100644 --- a/app/api/bookkeeping/journal-entries/route.ts +++ b/app/api/bookkeeping/journal-entries/route.ts @@ -28,6 +28,10 @@ export async function GET(request: Request) { const dateFrom = searchParams.get('date_from') const dateTo = searchParams.get('date_to') const sortDate = searchParams.get('sort_date') // 'asc' | 'desc' + // 'series' optional filter — single uppercase letter A–Z. Ignored if any + // other value is passed (defense against trivial injection / typos). + const seriesRaw = searchParams.get('series') + const seriesFilter = seriesRaw && /^[A-Z]$/.test(seriesRaw) ? seriesRaw : null // 'date_desc' (default) | 'date_asc' | 'voucher_asc' | 'voucher_desc' // sort_by overrides sort_date when present. sort_date is kept for backwards // compatibility with older clients. @@ -69,8 +73,18 @@ export async function GET(request: Request) { } const rows = data ?? [] - const entries = rows.map((r: { entry: unknown }) => r.entry) - const count = rows.length > 0 ? Number((rows[0] as { total_count: number | string }).total_count) : 0 + let entries = rows.map((r: { entry: unknown }) => r.entry) as Array<{ voucher_series?: string }> + let count = rows.length > 0 ? Number((rows[0] as { total_count: number | string }).total_count) : 0 + + // The list_fiscal_period_entries_with_related RPC doesn't accept a series + // filter, so post-filter here. Recompute count from the filtered set so + // the paginator stays consistent; consequence: when a series filter is + // applied, the cross-period follow-up surfacing is still on but the + // visible total drops to the matching subset. + if (seriesFilter) { + entries = entries.filter((e) => (e?.voucher_series ?? 'A') === seriesFilter) + count = entries.length + } return NextResponse.json({ data: entries, count }) } @@ -115,6 +129,10 @@ export async function GET(request: Request) { query = query.lte('entry_date', dateTo) } + if (seriesFilter) { + query = query.eq('voucher_series', seriesFilter) + } + const { data, error, count } = await query if (error) { diff --git a/app/api/company/current/route.ts b/app/api/company/current/route.ts index 8f10f4d6..b4334132 100644 --- a/app/api/company/current/route.ts +++ b/app/api/company/current/route.ts @@ -1,6 +1,21 @@ import { createClient } from '@/lib/supabase/server' -import { getActiveCompanyId } from '@/lib/company/context' +import { getActiveCompanyId, requireCompanyId } from '@/lib/company/context' +import { requireWritePermission } from '@/lib/auth/require-write' +import { validateBody } from '@/lib/api/validate' +import { AccountingFrameworkSchema } from '@/lib/api/schemas' +import { getBASReference } from '@/lib/bookkeeping/bas-reference' +import { createLogger } from '@/lib/logger' import { NextResponse } from 'next/server' +import { z } from 'zod' + +const log = createLogger('api/company/current') + +// BAS 2026 accounts required for K3's uppskjuten skatt (latent tax) entries. +// Both rows carry k2_excluded=true in lib/bookkeeping/bas-data so they are +// NOT seeded by seed_chart_of_accounts() for K2 companies. When a company +// opts into K3 we backfill them here so the engine can resolve them by +// account_number when the first latent-tax entry is posted. +const K3_LATENT_TAX_ACCOUNTS = ['2240', '8940'] as const /** * GET /api/company/current @@ -34,3 +49,143 @@ export async function GET() { { headers: { 'Cache-Control': 'private, no-store' } }, ) } + +/** + * Body shape for PATCH /api/company/current. + * + * Currently only carries `accounting_framework` (K2 / K3). Adding more + * companies-level fields here is fine but anything that belongs on + * company_settings should go to /api/settings instead. + */ +const PatchBodySchema = z.object({ + accounting_framework: AccountingFrameworkSchema.optional(), +}) + +/** + * PATCH /api/company/current + * + * Updates company-level fields (in the `companies` table) for the active + * company. Separate from /api/settings (which writes to `company_settings`) + * because the columns live on different tables. + * + * Currently scoped to `accounting_framework` (K2 / K3) — only meaningful for + * entity_type='aktiebolag'. The handler rejects K3 for non-AB to prevent + * impossible chart-of-accounts states downstream. + */ +export async function PATCH(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const writeCheck = await requireWritePermission(supabase, user.id) + if (!writeCheck.ok) return writeCheck.response + + const companyId = await requireCompanyId(supabase, user.id) + + const validation = await validateBody(request, PatchBodySchema) + if (!validation.success) return validation.response + + const updates: Record = {} + + if (validation.data.accounting_framework !== undefined) { + // Only AB can opt in to K3 — EF stays on the simpler EF rules and never + // touches K2/K3. Fetch the entity_type before applying. + const { data: company } = await supabase + .from('companies') + .select('entity_type') + .eq('id', companyId) + .single() + if (!company) { + return NextResponse.json( + { error: 'Företaget kunde inte hittas' }, + { status: 404 }, + ) + } + if ( + validation.data.accounting_framework === 'k3' + && company.entity_type !== 'aktiebolag' + ) { + return NextResponse.json( + { error: 'K3 (BFNAR 2012:1) gäller endast aktiebolag.' }, + { status: 400 }, + ) + } + updates.accounting_framework = validation.data.accounting_framework + } + + if (Object.keys(updates).length === 0) { + // Nothing to write — surface the current row so the client can refresh + // its local state without a no-op write. + const { data } = await supabase + .from('companies') + .select('id, accounting_framework, entity_type') + .eq('id', companyId) + .single() + return NextResponse.json({ data }) + } + + const { data, error } = await supabase + .from('companies') + .update(updates) + .eq('id', companyId) + .select('id, accounting_framework, entity_type') + .single() + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + // When opting in to K3, ensure the two latent-tax (uppskjuten skatt) + // accounts exist in the company's chart of accounts. The base seed skips + // them for K2 companies via k2_excluded=true, so without this backfill + // the engine cannot resolve account_id for the first latent-tax post. + // Wrapped in try/catch so a CoA insert failure does not block the + // framework update — the user can still re-trigger the seed later. + // The reverse switch (K3 → K2) intentionally keeps the rows for audit + // history; the legal record of past K3 postings must remain intact. + if (data.accounting_framework === 'k3') { + try { + const rows = K3_LATENT_TAX_ACCOUNTS.map(accountNumber => { + const basRef = getBASReference(accountNumber) + if (!basRef) return null + return { + user_id: user.id, + company_id: companyId, + account_number: basRef.account_number, + account_name: basRef.account_name, + account_class: basRef.account_class, + account_group: basRef.account_group, + account_type: basRef.account_type, + normal_balance: basRef.normal_balance, + sru_code: basRef.sru_code, + k2_excluded: basRef.k2_excluded, + plan_type: 'full_bas', + is_active: true, + is_system_account: true, + description: basRef.description, + } + }).filter((row): row is NonNullable => row !== null) + + if (rows.length > 0) { + const { error: seedError } = await supabase + .from('chart_of_accounts') + .upsert(rows, { onConflict: 'company_id,account_number', ignoreDuplicates: true }) + if (seedError) { + log.error('Failed to seed K3 latent-tax accounts', { + companyId, + error: seedError.message, + }) + } + } + } catch (err) { + log.error('Unexpected error seeding K3 latent-tax accounts', { + companyId, + error: err instanceof Error ? err.message : String(err), + }) + } + } + + return NextResponse.json({ data }) +} diff --git a/app/api/documents/[id]/__tests__/route.test.ts b/app/api/documents/[id]/__tests__/route.test.ts new file mode 100644 index 00000000..6924eda3 --- /dev/null +++ b/app/api/documents/[id]/__tests__/route.test.ts @@ -0,0 +1,154 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { eventBus } from '@/lib/events/bus' +import { + parseJsonResponse, + createMockRouteParams, + createQueuedMockSupabase, +} from '@/tests/helpers' + +const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase() +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => Promise.resolve(mockSupabase), +})) + +vi.mock('@/lib/company/context', () => ({ + requireCompanyId: vi.fn().mockResolvedValue('company-1'), + getActiveCompanyId: vi.fn().mockResolvedValue('company-1'), +})) + +vi.mock('@/lib/auth/require-write', () => ({ + requireWritePermission: vi.fn().mockResolvedValue({ ok: true }), +})) + +vi.mock('@/lib/init', () => ({ + ensureInitialized: vi.fn(), +})) + +import { DELETE } from '../route' +import { requireWritePermission } from '@/lib/auth/require-write' +import { NextResponse } from 'next/server' + +const mockUser = { id: 'user-1', email: 'test@test.se' } + +beforeEach(() => { + vi.clearAllMocks() + reset() + eventBus.clear() + mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } }) + // Reset write-permission mock to default ok + vi.mocked(requireWritePermission).mockResolvedValue({ ok: true }) +}) + +function makeReq() { + return new Request('http://localhost/api/documents/doc-1', { method: 'DELETE' }) +} + +describe('DELETE /api/documents/[id]', () => { + it('returns 401 when not authenticated', async () => { + mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } }) + const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' })) + const { status, body } = await parseJsonResponse(res) + expect(status).toBe(401) + expect(body).toEqual({ error: 'Unauthorized' }) + }) + + it('returns 403 when caller has read-only role', async () => { + vi.mocked(requireWritePermission).mockResolvedValue({ + ok: false, + response: NextResponse.json( + { error: 'Du har endast läsbehörighet i detta företag.' }, + { status: 403 }, + ), + }) + const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' })) + const { status } = await parseJsonResponse(res) + expect(status).toBe(403) + }) + + it('returns 404 when document not found in company', async () => { + enqueue({ data: null, error: null }) // doc lookup + const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' })) + const { status, body } = await parseJsonResponse<{ error: string }>(res) + expect(status).toBe(404) + expect(body.error).toContain('hittades inte') + }) + + it('returns 409 with BFL message when doc is linked to a journal entry', async () => { + enqueue({ + data: { + id: 'doc-1', + file_name: 'kvitto.pdf', + storage_path: 'documents/user-1/kvitto.pdf', + journal_entry_id: 'je-99', + user_id: 'user-1', + }, + error: null, + }) + const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' })) + const { status, body } = await parseJsonResponse<{ error: string }>(res) + expect(status).toBe(409) + expect(body.error).toContain('Bokföringslagen') + expect(body.error).toContain('7 kap') + }) + + it('deletes the row, removes Storage file, and emits document.deleted on unlinked doc', async () => { + enqueue({ + data: { + id: 'doc-1', + file_name: 'kvitto.pdf', + storage_path: 'documents/user-1/kvitto.pdf', + journal_entry_id: null, + user_id: 'user-1', + }, + error: null, + }) + enqueue({ data: null, error: null }) // delete + + const handler = vi.fn() + eventBus.on('document.deleted', handler) + + const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' })) + const { status, body } = await parseJsonResponse<{ data: { id: string; deleted: boolean } }>(res) + + expect(status).toBe(200) + expect(body.data).toEqual({ id: 'doc-1', deleted: true }) + + expect(mockSupabase.storage.from).toHaveBeenCalledWith('documents') + const storageBucket = mockSupabase.storage.from.mock.results[0]?.value + expect(storageBucket.remove).toHaveBeenCalledWith(['documents/user-1/kvitto.pdf']) + + expect(handler).toHaveBeenCalledOnce() + expect(handler).toHaveBeenCalledWith( + expect.objectContaining({ + document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }), + userId: 'user-1', + companyId: 'company-1', + }), + ) + }) + + it('returns 409 with BFL message when DB trigger blocks deletion (defense-in-depth)', async () => { + // Caller bypasses the application-layer check (e.g. race condition). + // The block_document_deletion() trigger raises with "Bokföringslagen" in the + // message; the service maps it to a 409. + enqueue({ + data: { + id: 'doc-1', + file_name: 'kvitto.pdf', + storage_path: 'documents/user-1/kvitto.pdf', + journal_entry_id: null, + user_id: 'user-1', + }, + error: null, + }) + enqueue({ + data: null, + error: { message: 'Cannot delete document linked to a posted journal entry (Bokföringslagen)' }, + }) + + const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' })) + const { status, body } = await parseJsonResponse<{ error: string }>(res) + expect(status).toBe(409) + expect(body.error).toContain('Bokföringslagen') + }) +}) diff --git a/app/api/documents/[id]/route.ts b/app/api/documents/[id]/route.ts index dca1e9eb..4e38c362 100644 --- a/app/api/documents/[id]/route.ts +++ b/app/api/documents/[id]/route.ts @@ -2,6 +2,8 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' import { ensureInitialized } from '@/lib/init' import { requireCompanyId } from '@/lib/company/context' +import { requireWritePermission } from '@/lib/auth/require-write' +import { deleteDocument } from '@/lib/core/documents/document-service' import { eventBus } from '@/lib/events' ensureInitialized() @@ -66,3 +68,45 @@ export async function GET( }, }) } + +/** + * DELETE /api/documents/:id + * Remove an uploaded document. Only permitted when the document is not yet + * linked to a journal entry — once linked, it is räkenskapsinformation under + * BFL 7 kap 2§ and must be retained for 7 years. For linked docs the caller + * should use POST /api/documents/:id/versions to supersede via a new version. + */ +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ id: string }> } +) { + const supabase = await createClient() + + const { data: { user } } = await supabase.auth.getUser() + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const writeCheck = await requireWritePermission(supabase, user.id) + if (!writeCheck.ok) return writeCheck.response + + const companyId = await requireCompanyId(supabase, user.id) + + const { id } = await params + + try { + const result = await deleteDocument(supabase, companyId, id) + + if (!result.ok) { + return NextResponse.json({ error: result.message }, { status: result.status }) + } + + return NextResponse.json({ data: { id: result.document.id, deleted: true } }) + } catch (error) { + console.error('[documents/DELETE] Failed to delete document:', error) + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Failed to delete document' }, + { status: 500 } + ) + } +} diff --git a/app/api/import/sie/[id]/replace/route.ts b/app/api/import/sie/[id]/replace/route.ts index fa7e0ad2..a50e63ae 100644 --- a/app/api/import/sie/[id]/replace/route.ts +++ b/app/api/import/sie/[id]/replace/route.ts @@ -6,8 +6,8 @@ import { errorResponseFromCode } from '@/lib/errors/get-structured-error' /** * POST /api/import/sie/[id]/replace * - * Replace a completed SIE import by cancelling its entries, allowing the user - * to re-import corrected data for the same fiscal period. + * Replace a completed SIE import by hard-deleting its entries, allowing the + * user to re-import corrected data for the same fiscal period. */ export const POST = withRouteContext( 'sie_import.replace', @@ -25,7 +25,7 @@ export const POST = withRouteContext( }) } - return NextResponse.json({ success: true, cancelledEntries: result.cancelledEntries }) + return NextResponse.json({ success: true, deletedEntries: result.deletedEntries }) }, { requireWrite: true }, ) diff --git a/app/api/invoices/[id]/mark-sent/__tests__/route.test.ts b/app/api/invoices/[id]/mark-sent/__tests__/route.test.ts index 3dfee258..6cd47091 100644 --- a/app/api/invoices/[id]/mark-sent/__tests__/route.test.ts +++ b/app/api/invoices/[id]/mark-sent/__tests__/route.test.ts @@ -39,6 +39,7 @@ vi.mock('@react-pdf/renderer', () => ({ vi.mock('@/lib/invoices/pdf-template', () => ({ InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'), + brandingFromCompanySettings: vi.fn().mockReturnValue({}), })) import { InvoicePDF } from '@/lib/invoices/pdf-template' diff --git a/app/api/invoices/[id]/mark-sent/route.ts b/app/api/invoices/[id]/mark-sent/route.ts index ff95c8eb..c2c177b1 100644 --- a/app/api/invoices/[id]/mark-sent/route.ts +++ b/app/api/invoices/[id]/mark-sent/route.ts @@ -5,6 +5,7 @@ import { createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries' import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number' import { ensureInitialized } from '@/lib/init' import { InvoicePDF } from '@/lib/invoices/pdf-template' +import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers' import { uploadDocument } from '@/lib/core/documents/document-service' import { requireCompanyId } from '@/lib/company/context' import { requireWritePermission } from '@/lib/auth/require-write' @@ -134,13 +135,16 @@ export async function POST( // The DB status flip already happened above, but the in-memory `invoice` // is stale and still reads 'draft' — override here so the archived // underlag isn't stamped "UTKAST – inte en giltig faktura". + const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const } + const { branding } = prepareInvoicePdfRender(settings as CompanySettings) const pdfBuffer = await renderToBuffer( InvoicePDF({ - invoice: { ...(invoice as Invoice), status: 'sent' as const }, + invoice: renderableInvoice, customer: invoice.customer as Customer, items, company: settings as CompanySettings, originalInvoiceNumber, + branding, }) ) diff --git a/app/api/invoices/[id]/pdf/route.ts b/app/api/invoices/[id]/pdf/route.ts index 077bea5c..9befa4d2 100644 --- a/app/api/invoices/[id]/pdf/route.ts +++ b/app/api/invoices/[id]/pdf/route.ts @@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' import { renderToBuffer } from '@react-pdf/renderer' import { InvoicePDF } from '@/lib/invoices/pdf-template' +import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers' import { requireCompanyId } from '@/lib/company/context' import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types' @@ -66,6 +67,7 @@ export async function GET( try { // Generate PDF + const { branding } = prepareInvoicePdfRender(company as CompanySettings) const pdfBuffer = await renderToBuffer( InvoicePDF({ invoice: invoice as Invoice, @@ -73,6 +75,7 @@ export async function GET( items, company: company as CompanySettings, originalInvoiceNumber, + branding, }) ) diff --git a/app/api/invoices/[id]/send/__tests__/route.test.ts b/app/api/invoices/[id]/send/__tests__/route.test.ts index 05c4067e..adac2750 100644 --- a/app/api/invoices/[id]/send/__tests__/route.test.ts +++ b/app/api/invoices/[id]/send/__tests__/route.test.ts @@ -40,6 +40,7 @@ vi.mock('@react-pdf/renderer', () => ({ vi.mock('@/lib/invoices/pdf-template', () => ({ InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'), + brandingFromCompanySettings: vi.fn().mockReturnValue({}), })) import { InvoicePDF } from '@/lib/invoices/pdf-template' diff --git a/app/api/invoices/[id]/send/route.ts b/app/api/invoices/[id]/send/route.ts index fd46a782..28b6a70f 100644 --- a/app/api/invoices/[id]/send/route.ts +++ b/app/api/invoices/[id]/send/route.ts @@ -3,6 +3,7 @@ import { eventBus } from '@/lib/events' import { ensureInitialized } from '@/lib/init' import { renderToBuffer } from '@react-pdf/renderer' import { InvoicePDF } from '@/lib/invoices/pdf-template' +import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers' import { getEmailService } from '@/lib/email/service' import { generateInvoiceEmailHtml, @@ -93,6 +94,7 @@ export const POST = withRouteContext( const isFreshAllocation = !invoice.invoice_number if (isFreshAllocation) { try { + const preflight = prepareInvoicePdfRender(company as CompanySettings) await renderToBuffer( InvoicePDF({ invoice: { ...(invoice as Invoice), invoice_number: 'F-PREVIEW' }, @@ -100,6 +102,7 @@ export const POST = withRouteContext( items, company: company as CompanySettings, originalInvoiceNumber, + branding: preflight.branding, }), ) } catch (err) { @@ -121,13 +124,16 @@ export const POST = withRouteContext( // the in-memory copy: the DB flip happens after email delivery (line // ~185), but if we render with the stale 'draft' status the customer // receives a PDF stamped "UTKAST – inte en giltig faktura". + const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const } + const { branding } = prepareInvoicePdfRender(company as CompanySettings) const pdfBuffer = await renderToBuffer( InvoicePDF({ - invoice: { ...(invoice as Invoice), status: 'sent' as const }, + invoice: renderableInvoice, customer, items, company: company as CompanySettings, originalInvoiceNumber, + branding, }), ) diff --git a/app/api/invoices/next-number/route.ts b/app/api/invoices/next-number/route.ts index 0b28169d..457fba81 100644 --- a/app/api/invoices/next-number/route.ts +++ b/app/api/invoices/next-number/route.ts @@ -9,7 +9,7 @@ export const GET = withRouteContext( const url = new URL(request.url) const documentType = url.searchParams.get('document_type') ?? 'invoice' - if (!['invoice', 'proforma', 'delivery_note'].includes(documentType)) { + if (!['invoice', 'proforma', 'delivery_note', 'quote'].includes(documentType)) { return NextResponse.json( { error: 'invalid document_type', requestId }, { status: 400 }, diff --git a/app/api/invoices/preview-pdf/route.ts b/app/api/invoices/preview-pdf/route.ts index ef2ff7d2..80739e5d 100644 --- a/app/api/invoices/preview-pdf/route.ts +++ b/app/api/invoices/preview-pdf/route.ts @@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' import { renderToBuffer } from '@react-pdf/renderer' import { InvoicePDF } from '@/lib/invoices/pdf-template' +import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers' import { getVatRules } from '@/lib/invoices/vat-rules' import { requireCompanyId } from '@/lib/company/context' import type { Invoice, InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types' @@ -167,6 +168,7 @@ export async function POST(request: Request) { } as Invoice try { + const { branding } = prepareInvoicePdfRender(company as CompanySettings) const pdfBuffer = await renderToBuffer( InvoicePDF({ invoice: previewInvoice, @@ -174,6 +176,7 @@ export async function POST(request: Request) { items: invoiceItems, company: company as CompanySettings, isPreview: true, + branding, }) ) diff --git a/app/api/invoices/reminders/action/route.ts b/app/api/invoices/reminders/action/route.ts index 448a0ba2..431eb6ef 100644 --- a/app/api/invoices/reminders/action/route.ts +++ b/app/api/invoices/reminders/action/route.ts @@ -120,6 +120,11 @@ export async function GET(request: Request) { sent_at, response_type, action_token_used, + interest_amount, + interest_rate, + interest_from_date, + interest_days, + reminder_fee, invoice:invoices( id, invoice_number, @@ -159,6 +164,11 @@ export async function GET(request: Request) { const customerData = invoice.customer const customer = Array.isArray(customerData) ? customerData[0] : customerData + const interestAmount = Number(reminder.interest_amount ?? 0) + const reminderFee = Number(reminder.reminder_fee ?? 0) + const totalDue = + Math.round((Number(invoice.total) + interestAmount + reminderFee) * 100) / 100 + return NextResponse.json({ invoiceNumber: invoice.invoice_number, invoiceDate: invoice.invoice_date, @@ -168,6 +178,15 @@ export async function GET(request: Request) { customerName: customer?.name, reminderLevel: reminder.reminder_level, alreadyResponded: reminder.action_token_used, - previousResponse: reminder.response_type + previousResponse: reminder.response_type, + // Dröjsmålsränta + lagstadgad påminnelseavgift surfaced to the + // customer-facing action page. Numeric defaults preserve back-compat + // for old reminders sent before the surcharge feature shipped. + interestAmount, + interestRate: reminder.interest_rate !== null ? Number(reminder.interest_rate) : 0, + interestFromDate: reminder.interest_from_date, + interestDays: reminder.interest_days, + reminderFee, + totalDue, }) } diff --git a/app/api/invoices/route.ts b/app/api/invoices/route.ts index 0296cb66..c6316742 100644 --- a/app/api/invoices/route.ts +++ b/app/api/invoices/route.ts @@ -8,6 +8,16 @@ import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules' import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken' import { createCreditNoteJournalEntry } from '@/lib/bookkeeping/invoice-entries' import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number' +import { + computeDeduction, + computeInvoiceDeductionTotal, + validateInvoice as validateRotRut, +} from '@/lib/invoices/rot-rut-rules' +import { + encryptPersonnummer, + extractLast4, + validatePersonnummer, +} from '@/lib/salary/personnummer' import { withRouteContext } from '@/lib/api/with-route-context' import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error' import type { Logger } from '@/lib/logger' @@ -135,6 +145,51 @@ export const POST = withRouteContext( } const total = documentType === 'delivery_note' ? 0 : subtotal + vatAmount + // ROT/RUT-avdrag: validate prerequisites and compute the per-item + + // invoice-level deduction. Computed server-side (never trusted from + // the client) so a tampered request can't expand the 1513 receivable. + // Skipped entirely for proformas, delivery notes, and quotes — those + // documents don't post journal entries and have no deduction model. + let deductionTotal = 0 + let deductionPersonnummerEncrypted: string | null = null + let deductionPersonnummerLast4: string | null = null + if (documentType === 'invoice') { + const housingProvided = !!invoiceInput.deduction_housing_designation?.trim() + const personnummerRaw = invoiceInput.deduction_personnummer?.trim() || '' + const personnummerProvided = personnummerRaw.length > 0 + + const validateInput = invoiceInput.items.map((item) => ({ + unit_price: item.unit_price, + quantity: item.quantity, + deduction_type: item.deduction_type ?? null, + labor_hours: item.labor_hours ?? null, + housing_designation: item.housing_designation ?? null, + })) + const validation = validateRotRut(validateInput, personnummerProvided, housingProvided) + if (validation.errors.length > 0) { + return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_VALIDATION', log, { + requestId, + details: { errors: validation.errors, warnings: validation.warnings }, + }) + } + + // Compute and (when present) encrypt the personnummer. The plaintext + // value never touches the DB — only the AES-256-GCM ciphertext + the + // last four digits go into invoices columns. + deductionTotal = computeInvoiceDeductionTotal(validateInput) + if (personnummerProvided) { + const pnValid = validatePersonnummer(personnummerRaw) + if (!pnValid.valid) { + return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_PERSONNUMMER_INVALID', log, { + requestId, + details: { error: pnValid.error }, + }) + } + deductionPersonnummerEncrypted = encryptPersonnummer(personnummerRaw) + deductionPersonnummerLast4 = extractLast4(personnummerRaw) + } + } + const uniqueRates = new Set(invoiceInput.items.map((item) => item.vat_rate ?? vatRules.rate)) const isMixedRate = uniqueRates.size > 1 @@ -182,13 +237,14 @@ export const POST = withRouteContext( vat_amount_sek: documentType === 'delivery_note' ? null : vatAmountSek, total, total_sek: documentType === 'delivery_note' ? null : totalSek, - // Initialize remaining_amount to total for real invoices so the open- - // invoice queries (InvoicePicker, AR ledger, supplier matching) treat - // newly-created invoices as fully unpaid. The DB default is 0 — without - // this, brand-new fakturor look settled and disappear from match - // candidate lists. Proformas and delivery notes have no payment - // obligation, so they keep the 0 default. - remaining_amount: documentType === 'invoice' ? total : 0, + // Initialize remaining_amount to total - deduction for real invoices + // so the open-invoice queries (InvoicePicker, AR ledger, supplier + // matching) treat newly-created invoices as fully unpaid for the + // CUSTOMER's share — the Skatteverket portion is on 1513 and will be + // cleared when the agency pays out, not by the customer payment. + // Proformas, delivery notes and quotes have no payment obligation, + // so they keep the 0 default. + remaining_amount: documentType === 'invoice' ? total - deductionTotal : 0, vat_treatment: vatRules.treatment, vat_rate: documentType === 'delivery_note' ? 0 : (isMixedRate ? null : (uniqueRates.values().next().value ?? vatRules.rate)), moms_ruta: vatRules.momsRuta, @@ -197,6 +253,9 @@ export const POST = withRouteContext( our_reference: invoiceInput.our_reference, notes: invoiceInput.notes, document_type: documentType, + deduction_total: deductionTotal, + deduction_personnummer_encrypted: deductionPersonnummerEncrypted, + deduction_personnummer_last4: deductionPersonnummerLast4, }) .select() .single() @@ -213,6 +272,18 @@ export const POST = withRouteContext( const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate const lineTotal = item.quantity * item.unit_price const itemVat = documentType === 'delivery_note' ? 0 : Math.round(lineTotal * itemRate / 100 * 100) / 100 + // ROT/RUT deduction is recomputed server-side so a tampered client + // can't expand the 1513 receivable beyond the rules. Non-invoice + // document types never carry deduction_type (rules above strip them + // implicitly because validateRotRut isn't invoked). + const deductionType = documentType === 'invoice' ? (item.deduction_type ?? null) : null + const deductionAmount = deductionType + ? computeDeduction({ + unit_price: item.unit_price, + quantity: item.quantity, + deduction_type: deductionType, + }) + : 0 return { invoice_id: invoice.id, sort_order: index, @@ -223,6 +294,12 @@ export const POST = withRouteContext( line_total: lineTotal, vat_rate: itemRate, vat_amount: itemVat, + deduction_type: deductionType, + deduction_amount: deductionAmount, + labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null, + work_type: documentType === 'invoice' ? (item.work_type ?? null) : null, + housing_designation: documentType === 'invoice' ? (item.housing_designation ?? null) : null, + apartment_number: documentType === 'invoice' ? (item.apartment_number ?? null) : null, } }) @@ -296,7 +373,7 @@ export const POST = withRouteContext( .eq('id', invoice.id) .single() - // Emit event only for real invoices (proformas / delivery notes are informational). + // Emit event only for real invoices (proformas / delivery notes / quotes are informational). if (completeInvoice && documentType === 'invoice') { await eventBus.emit({ type: 'invoice.created', diff --git a/app/api/reports/ar-ledger/customer/[customerId]/invoices/__tests__/route.test.ts b/app/api/reports/ar-ledger/customer/[customerId]/invoices/__tests__/route.test.ts new file mode 100644 index 00000000..f3af3850 --- /dev/null +++ b/app/api/reports/ar-ledger/customer/[customerId]/invoices/__tests__/route.test.ts @@ -0,0 +1,156 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMockRequest, createMockRouteParams } from '@/tests/helpers' + +vi.mock('@/lib/supabase/server', () => ({ + createClient: vi.fn(), +})) + +vi.mock('@/lib/company/context', () => ({ + requireCompanyId: vi.fn().mockResolvedValue('company-1'), +})) + +vi.mock('@/lib/bookkeeping/currency-utils', () => ({ + resolveSekAmount: vi.fn((amount: number) => amount), +})) + +import { createClient } from '@/lib/supabase/server' +import { GET } from '../route' + +const mockCreateClient = vi.mocked(createClient) + +interface QueryResult { + data: unknown + error: unknown +} + +function buildSupabase( + user: { id: string } | null, + customer: { id: string; name: string } | null, + invoicesResult: QueryResult, + entriesResult: QueryResult +) { + let invoiceCallNum = 0 + let entryCallNum = 0 + return { + auth: { + getUser: vi.fn().mockResolvedValue({ data: { user } }), + }, + from: vi.fn().mockImplementation((table: string) => { + if (table === 'customers') { + return { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + maybeSingle: vi.fn().mockResolvedValue({ data: customer, error: null }), + } + } + if (table === 'invoices') { + invoiceCallNum += 1 + return { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + in: vi.fn().mockReturnThis(), + order: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + then: (resolve: (v: QueryResult) => void) => resolve(invoicesResult), + } + } + // journal_entries + entryCallNum += 1 + return { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + in: vi.fn().mockReturnThis(), + then: (resolve: (v: QueryResult) => void) => resolve(entriesResult), + } + }), + _stats: () => ({ invoiceCallNum, entryCallNum }), + } +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('GET /api/reports/ar-ledger/customer/[customerId]/invoices', () => { + it('returns 401 when not authenticated', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase(null, null, { data: [], error: null }, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/ar-ledger/customer/cust-1/invoices' + ) + const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' })) + expect(res.status).toBe(401) + }) + + it('returns 404 when customer is unknown', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, null, { data: [], error: null }, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/ar-ledger/customer/cust-1/invoices' + ) + const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' })) + expect(res.status).toBe(404) + }) + + it('happy path: returns invoices with linked journal entries', async () => { + const invoices = [ + { + id: 'inv-1', + invoice_number: '2026-001', + invoice_date: '2026-05-01', + due_date: '2026-06-01', + total: 1250, + paid_amount: 0, + currency: 'SEK', + exchange_rate: null, + remaining_amount: 1250, + notes: null, + }, + ] + const entries = [ + { + id: 'je-1', + voucher_number: 22, + voucher_series: 'A', + description: 'Faktura 2026-001', + source_id: 'inv-1', + }, + ] + mockCreateClient.mockResolvedValue( + buildSupabase( + { id: 'user-1' }, + { id: 'cust-1', name: 'Acme AB' }, + { data: invoices, error: null }, + { data: entries, error: null } + ) as never + ) + const req = createMockRequest( + '/api/reports/ar-ledger/customer/cust-1/invoices' + ) + const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' })) + expect(res.status).toBe(200) + + const body = (await res.json()) as { + data: { + customer_id: string + customer_name: string + lines: Array<{ + invoice_id: string + voucher_number: number + journal_entry_id: string + outstanding: number + }> + } + } + + expect(body.data.customer_id).toBe('cust-1') + expect(body.data.customer_name).toBe('Acme AB') + expect(body.data.lines).toHaveLength(1) + expect(body.data.lines[0].invoice_id).toBe('inv-1') + expect(body.data.lines[0].journal_entry_id).toBe('je-1') + expect(body.data.lines[0].voucher_number).toBe(22) + expect(body.data.lines[0].outstanding).toBe(1250) + }) +}) diff --git a/app/api/reports/ar-ledger/customer/[customerId]/invoices/route.ts b/app/api/reports/ar-ledger/customer/[customerId]/invoices/route.ts new file mode 100644 index 00000000..ccb166a2 --- /dev/null +++ b/app/api/reports/ar-ledger/customer/[customerId]/invoices/route.ts @@ -0,0 +1,152 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { requireCompanyId } from '@/lib/company/context' +import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils' +import type { ReportSourceLine } from '@/lib/reports/source-lines' + +/** + * GET /api/reports/ar-ledger/customer/[customerId]/invoices + * + * Returns the invoices that contribute to a customer's outstanding balance. + * Each row exposes the registration journal entry (if any) via + * `journal_entry_id`, so the UI can link directly to `/bookkeeping/[id]`. + * + * If an invoice has no posted registration entry yet (still draft), the + * `journal_entry_id` is null and the UI must fall back to `/invoices/[id]`. + */ +const PAGE_LIMIT = 500 + +export async function GET( + request: Request, + { params }: { params: Promise<{ customerId: string }> } +) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + const { customerId } = await params + + // Verify customer belongs to the company. + const { data: customer } = await supabase + .from('customers') + .select('id, name') + .eq('id', customerId) + .eq('company_id', companyId) + .maybeSingle() + + if (!customer) { + return NextResponse.json({ error: 'Kund saknas' }, { status: 404 }) + } + + // Pull this customer's outstanding invoices. Mirrors the filter in + // `generateARLedger` so the UI sees the same set the aggregate is built + // from. + const { data, error } = await supabase + .from('invoices') + .select(` + id, + invoice_number, + invoice_date, + due_date, + total, + paid_amount, + currency, + exchange_rate, + remaining_amount, + notes + `) + .eq('company_id', companyId) + .eq('customer_id', customerId) + .in('status', ['sent', 'overdue', 'credited']) + .order('invoice_date', { ascending: true }) + .limit(PAGE_LIMIT) + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + // For each invoice, find the registration journal entry (source_type = + // 'invoice_created', source_id = invoice.id). We batch them to keep this + // a single DB roundtrip. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const invoices = (data || []) as any[] + const ids = invoices.map((i) => i.id) + const entryMap = new Map< + string, + { id: string; voucher_number: number; voucher_series: string; description: string | null } + >() + + if (ids.length > 0) { + const { data: entries } = await supabase + .from('journal_entries') + .select('id, voucher_number, voucher_series, description, source_id') + .eq('company_id', companyId) + .eq('source_type', 'invoice_created') + .in('source_id', ids) + .in('status', ['posted', 'reversed']) + + for (const e of entries || []) { + entryMap.set(e.source_id, { + id: e.id, + voucher_number: e.voucher_number, + voucher_series: e.voucher_series || 'A', + description: e.description, + }) + } + } + + // Shape each invoice as a ReportSourceLine. The "debit" column carries + // the outstanding SEK amount (it's a receivable on 1510); "credit" is 0 + // unless the invoice is fully a credit note. + const lines: (ReportSourceLine & { + invoice_id: string + invoice_number: string | null + outstanding: number + outstanding_sek: number | null + currency: string + paid_amount: number + due_date: string + })[] = invoices.map((inv) => { + const entry = entryMap.get(inv.id) + const paidAmount = Number(inv.paid_amount) || 0 + const total = Number(inv.total) || 0 + const outstanding = Math.round((total - paidAmount) * 100) / 100 + const isFx = inv.currency && inv.currency !== 'SEK' + const hasRate = inv.exchange_rate != null && Number(inv.exchange_rate) > 0 + const outstandingSek = + isFx && !hasRate + ? null + : resolveSekAmount(outstanding, null, inv.currency, inv.exchange_rate) + + return { + journal_entry_id: entry?.id ?? '', + voucher_number: entry?.voucher_number ?? 0, + voucher_series: entry?.voucher_series ?? 'A', + date: inv.invoice_date || '', + description: + entry?.description ?? `Faktura ${inv.invoice_number || '(utkast)'}`, + debit: outstandingSek ?? outstanding, + credit: 0, + invoice_id: inv.id, + invoice_number: inv.invoice_number, + outstanding, + outstanding_sek: outstandingSek, + currency: inv.currency || 'SEK', + paid_amount: paidAmount, + due_date: inv.due_date, + } + }) + + return NextResponse.json({ + data: { + customer_id: customer.id, + customer_name: customer.name, + lines, + next_cursor: null, + }, + }) +} diff --git a/app/api/reports/ar-ledger/xlsx/route.ts b/app/api/reports/ar-ledger/xlsx/route.ts new file mode 100644 index 00000000..49f67a24 --- /dev/null +++ b/app/api/reports/ar-ledger/xlsx/route.ts @@ -0,0 +1,163 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateARLedger } from '@/lib/reports/ar-ledger' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + dateColumn, + integerColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface AgingRow { + customer_name: string + current: number + days_1_30: number + days_31_60: number + days_61_90: number + days_90_plus: number + total_outstanding: number +} + +interface InvoiceRow { + customer_name: string + invoice_number: string + invoice_date: Date | string + due_date: Date | string + total: number + paid_amount: number + outstanding: number + outstanding_sek: number | null + days_overdue: number + currency: string +} + +function toDate(s: string): Date | null { + if (!s) return null + const d = new Date(s) + return isNaN(d.getTime()) ? null : d +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const asOfDate = searchParams.get('as_of_date') || undefined + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const ledger = await generateARLedger(supabase, companyId, asOfDate) + + const agingRows: AgingRow[] = ledger.entries.map((e) => ({ + customer_name: e.customer_name, + current: e.current, + days_1_30: e.days_1_30, + days_31_60: e.days_31_60, + days_61_90: e.days_61_90, + days_90_plus: e.days_90_plus, + total_outstanding: e.total_outstanding, + })) + + const invoiceRows: InvoiceRow[] = [] + for (const e of ledger.entries) { + for (const inv of e.invoices) { + invoiceRows.push({ + customer_name: e.customer_name, + invoice_number: inv.invoice_number, + invoice_date: toDate(inv.invoice_date) ?? inv.invoice_date, + due_date: toDate(inv.due_date) ?? inv.due_date, + total: inv.total, + paid_amount: inv.paid_amount, + outstanding: inv.outstanding, + outstanding_sek: inv.outstanding_sek, + days_overdue: inv.days_overdue, + currency: inv.currency, + }) + } + } + + const buffer = reportToWorkbook([ + { + name: 'Åldersfördelning', + columns: [ + textColumn('Kund'), + currencyColumn('Ej förfallet'), + currencyColumn('1-30 dagar'), + currencyColumn('31-60 dagar'), + currencyColumn('61-90 dagar'), + currencyColumn('90+ dagar'), + currencyColumn('Totalt utestående'), + ], + rows: agingRows, + mapRow: (r) => [ + r.customer_name, + r.current, + r.days_1_30, + r.days_31_60, + r.days_61_90, + r.days_90_plus, + r.total_outstanding, + ], + }, + { + name: 'Fakturor', + columns: [ + textColumn('Kund'), + textColumn('Fakturanr'), + dateColumn('Fakturadatum'), + dateColumn('Förfallodatum'), + currencyColumn('Totalt'), + currencyColumn('Betalt'), + currencyColumn('Utestående'), + currencyColumn('Utestående (SEK)'), + integerColumn('Dagar förfallet'), + textColumn('Valuta'), + ], + rows: invoiceRows, + mapRow: (r) => [ + r.customer_name, + r.invoice_number, + r.invoice_date instanceof Date ? r.invoice_date : null, + r.due_date instanceof Date ? r.due_date : null, + r.total, + r.paid_amount, + r.outstanding, + r.outstanding_sek, + r.days_overdue, + r.currency, + ], + }, + ]) + + const filename = xlsxFilename( + 'kundreskontra', + companyRow?.company_name ?? '', + asOfDate ?? new Date().toISOString().slice(0, 10), + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera kundreskontra' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/balance-sheet/xlsx/route.ts b/app/api/reports/balance-sheet/xlsx/route.ts new file mode 100644 index 00000000..1ed0f11e --- /dev/null +++ b/app/api/reports/balance-sheet/xlsx/route.ts @@ -0,0 +1,153 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateBalanceSheet } from '@/lib/reports/balance-sheet' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface FlatRow { + section: string + account_number: string + account_name: string + amount: number + isSubtotal: boolean +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const [{ data: period }, { data: companyRow }] = await Promise.all([ + supabase + .from('fiscal_periods') + .select('period_start, period_end') + .eq('id', periodId) + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single(), + ]) + + if (!period) { + return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 }) + } + + try { + const report = await generateBalanceSheet(supabase, companyId, periodId) + + // Flatten nested sections into a single tabular view, mirroring how the + // PDF lays them out: each section's rows followed by a subtotal line, with + // grand totals at the end. The "Sektion" column keeps the grouping queryable. + const assetRows: FlatRow[] = [] + for (const s of report.asset_sections) { + for (const r of s.rows) { + assetRows.push({ + section: s.title, + account_number: r.account_number, + account_name: r.account_name, + amount: r.amount, + isSubtotal: false, + }) + } + assetRows.push({ + section: s.title, + account_number: '', + account_name: `Summa ${s.title}`, + amount: s.subtotal, + isSubtotal: true, + }) + } + assetRows.push({ + section: 'Tillgångar', + account_number: '', + account_name: 'Summa tillgångar', + amount: report.total_assets, + isSubtotal: true, + }) + + const equityRows: FlatRow[] = [] + for (const s of report.equity_liability_sections) { + for (const r of s.rows) { + equityRows.push({ + section: s.title, + account_number: r.account_number, + account_name: r.account_name, + amount: r.amount, + isSubtotal: false, + }) + } + equityRows.push({ + section: s.title, + account_number: '', + account_name: `Summa ${s.title}`, + amount: s.subtotal, + isSubtotal: true, + }) + } + equityRows.push({ + section: 'Eget kapital och skulder', + account_number: '', + account_name: 'Summa eget kapital och skulder', + amount: report.total_equity_liabilities, + isSubtotal: true, + }) + + const buffer = reportToWorkbook([ + { + name: 'Tillgångar', + columns: [ + textColumn('Sektion'), + textColumn('Konto'), + textColumn('Kontonamn'), + currencyColumn('Belopp'), + ], + rows: assetRows, + mapRow: (r) => [r.section, r.account_number, r.account_name, r.amount], + }, + { + name: 'Eget kapital och skulder', + columns: [ + textColumn('Sektion'), + textColumn('Konto'), + textColumn('Kontonamn'), + currencyColumn('Belopp'), + ], + rows: equityRows, + mapRow: (r) => [r.section, r.account_number, r.account_name, r.amount], + }, + ]) + + const filename = xlsxFilename('balansrakning', companyRow?.company_name ?? '', period.period_end) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera balansräkning' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/balansrapport/xlsx/route.ts b/app/api/reports/balansrapport/xlsx/route.ts new file mode 100644 index 00000000..86e2a6cf --- /dev/null +++ b/app/api/reports/balansrapport/xlsx/route.ts @@ -0,0 +1,117 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateBalansrapport } from '@/lib/reports/balansrapport' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface FlatRow { + group: string + account_number: string + account_name: string + ib: number + period_change: number + ub: number +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const report = await generateBalansrapport(supabase, companyId, periodId) + + const rows: FlatRow[] = [] + for (const g of report.groups) { + for (const r of g.rows) { + rows.push({ + group: g.class_label, + account_number: r.account_number, + account_name: r.account_name, + ib: r.ib, + period_change: r.period_change, + ub: r.ub, + }) + } + rows.push({ + group: g.class_label, + account_number: '', + account_name: `Summa ${g.class_label}`, + ib: g.subtotal_ib, + period_change: Math.round((g.subtotal_ub - g.subtotal_ib) * 100) / 100, + ub: g.subtotal_ub, + }) + } + rows.push({ + group: 'Beräknat resultat', + account_number: '', + account_name: 'Beräknat resultat', + ib: 0, + period_change: report.beraknat_resultat, + ub: report.beraknat_resultat, + }) + + const buffer = reportToWorkbook([ + { + name: 'Balansrapport', + columns: [ + textColumn('Grupp'), + textColumn('Konto'), + textColumn('Kontonamn'), + currencyColumn('IB'), + currencyColumn('Periodförändring'), + currencyColumn('UB'), + ], + rows, + mapRow: (r) => [ + r.group, + r.account_number, + r.account_name, + r.ib, + r.period_change, + r.ub, + ], + }, + ]) + + const filename = xlsxFilename( + 'balansrapport', + companyRow?.company_name ?? '', + report.period.end, + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera balansrapport' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/general-ledger/xlsx/route.ts b/app/api/reports/general-ledger/xlsx/route.ts new file mode 100644 index 00000000..9ba4dc69 --- /dev/null +++ b/app/api/reports/general-ledger/xlsx/route.ts @@ -0,0 +1,144 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateGeneralLedger } from '@/lib/reports/general-ledger' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + dateColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface FlatRow { + account_number: string + account_name: string + date: Date | string + voucher: string + description: string + source_type: string + debit: number + credit: number + balance: number +} + +function toDate(s: string): Date | string { + // Preserve original ISO string in the cell if parsing fails (avoids NaN + // dates polluting the workbook). + const d = new Date(s) + return isNaN(d.getTime()) ? s : d +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + const accountFrom = searchParams.get('account_from') || undefined + const accountTo = searchParams.get('account_to') || undefined + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const report = await generateGeneralLedger(supabase, companyId, periodId, accountFrom, accountTo) + + // Flatten accounts + their lines into a single sheet. Each account contributes + // an opening-balance row, its lines (with running balance), and a closing + // row — matching how huvudbok is read in Fortnox/Visma. + const rows: FlatRow[] = [] + for (const acc of report.accounts) { + rows.push({ + account_number: acc.account_number, + account_name: acc.account_name, + date: '', + voucher: '', + description: 'Ingående balans', + source_type: '', + debit: 0, + credit: 0, + balance: acc.opening_balance, + }) + for (const line of acc.lines) { + rows.push({ + account_number: acc.account_number, + account_name: acc.account_name, + date: toDate(line.date), + voucher: `${line.voucher_series}${line.voucher_number}`, + description: line.description, + source_type: line.source_type, + debit: line.debit, + credit: line.credit, + balance: line.balance, + }) + } + rows.push({ + account_number: acc.account_number, + account_name: acc.account_name, + date: '', + voucher: '', + description: 'Utgående balans', + source_type: '', + debit: acc.total_debit, + credit: acc.total_credit, + balance: acc.closing_balance, + }) + } + + const buffer = reportToWorkbook([ + { + name: 'Huvudbok', + columns: [ + textColumn('Konto'), + textColumn('Kontonamn'), + dateColumn('Datum'), + textColumn('Verifikat'), + textColumn('Beskrivning'), + textColumn('Källa'), + currencyColumn('Debet'), + currencyColumn('Kredit'), + currencyColumn('Saldo'), + ], + rows, + mapRow: (r) => [ + r.account_number, + r.account_name, + r.date instanceof Date ? r.date : null, + r.voucher, + r.description, + r.source_type, + r.debit, + r.credit, + r.balance, + ], + }, + ]) + + const filename = xlsxFilename('huvudbok', companyRow?.company_name ?? '', report.period.end) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera huvudbok' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/income-statement/xlsx/route.ts b/app/api/reports/income-statement/xlsx/route.ts new file mode 100644 index 00000000..bb3bde40 --- /dev/null +++ b/app/api/reports/income-statement/xlsx/route.ts @@ -0,0 +1,156 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateIncomeStatement } from '@/lib/reports/income-statement' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' +import type { IncomeStatementSection } from '@/types' + +interface FlatRow { + section: string + account_number: string + account_name: string + amount: number +} + +function flatten( + sections: IncomeStatementSection[], + groupLabel: string, + groupTotalLabel: string, + groupTotal: number, +): FlatRow[] { + const rows: FlatRow[] = [] + for (const s of sections) { + for (const r of s.rows) { + rows.push({ + section: s.title, + account_number: r.account_number, + account_name: r.account_name, + amount: r.amount, + }) + } + rows.push({ + section: s.title, + account_number: '', + account_name: `Summa ${s.title}`, + amount: s.subtotal, + }) + } + rows.push({ + section: groupLabel, + account_number: '', + account_name: groupTotalLabel, + amount: groupTotal, + }) + return rows +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const [{ data: period }, { data: companyRow }] = await Promise.all([ + supabase + .from('fiscal_periods') + .select('period_start, period_end') + .eq('id', periodId) + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single(), + ]) + + if (!period) { + return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 }) + } + + try { + const report = await generateIncomeStatement(supabase, companyId, periodId) + + const revenueRows = flatten( + report.revenue_sections, + 'Rörelseintäkter', + 'Summa rörelseintäkter', + report.total_revenue, + ) + const expenseRows = flatten( + report.expense_sections, + 'Rörelsekostnader', + 'Summa rörelsekostnader', + report.total_expenses, + ) + const financialRows = flatten( + report.financial_sections, + 'Finansiella poster', + 'Summa finansiella poster', + report.total_financial, + ) + + const summaryRows: FlatRow[] = [ + { + section: 'Sammanfattning', + account_number: '', + account_name: 'Rörelseresultat', + amount: Math.round((report.total_revenue - report.total_expenses) * 100) / 100, + }, + { + section: 'Sammanfattning', + account_number: '', + account_name: 'Årets resultat', + amount: report.net_result, + }, + ] + + const columns = [ + textColumn('Sektion'), + textColumn('Konto'), + textColumn('Kontonamn'), + currencyColumn('Belopp'), + ] + const mapRow = (r: FlatRow) => [r.section, r.account_number, r.account_name, r.amount] + + const buffer = reportToWorkbook([ + { name: 'Intäkter', columns, rows: revenueRows, mapRow }, + { name: 'Kostnader', columns, rows: expenseRows, mapRow }, + { name: 'Finansiella poster', columns, rows: financialRows, mapRow }, + { name: 'Sammanfattning', columns, rows: summaryRows, mapRow }, + ]) + + const filename = xlsxFilename( + 'resultatrakning', + companyRow?.company_name ?? '', + period.period_end, + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera resultaträkning' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/journal-register/xlsx/route.ts b/app/api/reports/journal-register/xlsx/route.ts new file mode 100644 index 00000000..be62bbec --- /dev/null +++ b/app/api/reports/journal-register/xlsx/route.ts @@ -0,0 +1,119 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateJournalRegister } from '@/lib/reports/journal-register' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + dateColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface FlatRow { + voucher: string + date: Date | null + description: string + source_type: string + status: string + account_number: string + account_name: string + debit: number + credit: number +} + +function toDate(s: string): Date | null { + if (!s) return null + const d = new Date(s) + return isNaN(d.getTime()) ? null : d +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const report = await generateJournalRegister(supabase, companyId, periodId) + + // Flatten: one row per (entry, line). Voucher metadata repeats so the + // file is filterable in Excel without losing context. + const rows: FlatRow[] = [] + for (const entry of report.entries) { + const voucherLabel = `${entry.voucher_series}${entry.voucher_number}` + for (const line of entry.lines) { + rows.push({ + voucher: voucherLabel, + date: toDate(entry.date), + description: entry.description, + source_type: entry.source_type, + status: entry.status, + account_number: line.account_number, + account_name: line.account_name, + debit: line.debit, + credit: line.credit, + }) + } + } + + const buffer = reportToWorkbook([ + { + name: 'Grundbok', + columns: [ + textColumn('Verifikat'), + dateColumn('Datum'), + textColumn('Beskrivning'), + textColumn('Källa'), + textColumn('Status'), + textColumn('Konto'), + textColumn('Kontonamn'), + currencyColumn('Debet'), + currencyColumn('Kredit'), + ], + rows, + mapRow: (r) => [ + r.voucher, + r.date, + r.description, + r.source_type, + r.status, + r.account_number, + r.account_name, + r.debit, + r.credit, + ], + }, + ]) + + const filename = xlsxFilename('grundbok', companyRow?.company_name ?? '', report.period.end) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera grundbok' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/kassaflodesanalys/pdf/route.ts b/app/api/reports/kassaflodesanalys/pdf/route.ts new file mode 100644 index 00000000..cc861860 --- /dev/null +++ b/app/api/reports/kassaflodesanalys/pdf/route.ts @@ -0,0 +1,80 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { renderToBuffer } from '@react-pdf/renderer' +import { generateKassaflodesanalys } from '@/lib/reports/kassaflodesanalys' +import { KassaflodesanalysPDF } from '@/lib/reports/kassaflodesanalys-pdf-template' +import { requireCompanyId } from '@/lib/company/context' +import type { CompanySettings } from '@/types' + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const [{ data: period }, { data: companyRow }] = await Promise.all([ + supabase + .from('fiscal_periods') + .select('period_start, period_end') + .eq('id', periodId) + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('*') + .eq('company_id', companyId) + .single(), + ]) + + if (!companyRow) { + return NextResponse.json({ error: 'Företagsinställningar saknas' }, { status: 404 }) + } + // An identifiable period is part of räkenskapsinformation (BFL 7 kap). Refuse + // to render a PDF that can't be archived with the period it refers to. + if (!period) { + return NextResponse.json( + { + error: + 'Räkenskapsperioden kunde inte läsas. Välj en befintlig period innan du genererar PDF.', + }, + { status: 400 } + ) + } + + try { + const report = await generateKassaflodesanalys(supabase, companyId, periodId) + + const pdfBuffer = await renderToBuffer( + KassaflodesanalysPDF({ + report, + company: companyRow as CompanySettings, + generatedAt: new Date().toISOString(), + }) + ) + + const filename = `kassaflodesanalys-${report.period_start}.pdf` + + return new Response(new Uint8Array(pdfBuffer), { + headers: { + 'Content-Type': 'application/pdf', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera kassaflödesanalys' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/kassaflodesanalys/route.ts b/app/api/reports/kassaflodesanalys/route.ts new file mode 100644 index 00000000..cdc07c99 --- /dev/null +++ b/app/api/reports/kassaflodesanalys/route.ts @@ -0,0 +1,32 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateKassaflodesanalys } from '@/lib/reports/kassaflodesanalys' +import { requireCompanyId } from '@/lib/company/context' + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + try { + const result = await generateKassaflodesanalys(supabase, companyId, periodId) + return NextResponse.json({ data: result }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Failed to generate kassaflödesanalys' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/kpi/xlsx/route.ts b/app/api/reports/kpi/xlsx/route.ts new file mode 100644 index 00000000..efae6718 --- /dev/null +++ b/app/api/reports/kpi/xlsx/route.ts @@ -0,0 +1,256 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateIncomeStatement } from '@/lib/reports/income-statement' +import { generateTrialBalance } from '@/lib/reports/trial-balance' +import { generateARLedger } from '@/lib/reports/ar-ledger' +import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown' +import { + calculateCashPosition, + calculateGrossMargin, + calculateExpenseRatio, + calculateAvgPaymentDays, +} from '@/lib/reports/kpi' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + percentColumn, + integerColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface KpiKv { + label: string + value: number | null +} + +interface MonthRow { + label: string + income: number + expenses: number + net: number +} + +interface CompositionRow { + klass: string + amount: number +} + +interface SupplierRow { + supplier_name: string + total: number +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const [{ data: period }, { data: companyRow }] = await Promise.all([ + supabase + .from('fiscal_periods') + .select('period_start, period_end, is_closed') + .eq('id', periodId) + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single(), + ]) + + if (!period) { + return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 }) + } + + try { + const [ + incomeStatement, + trialBalanceResult, + arLedger, + monthlyBreakdown, + paidInvoicesResult, + topSuppliersResult, + ] = await Promise.all([ + generateIncomeStatement(supabase, companyId, periodId), + generateTrialBalance(supabase, companyId, periodId), + generateARLedger(supabase, companyId), + generateMonthlyBreakdown(supabase, companyId, periodId), + supabase + .from('invoices') + .select('invoice_date, paid_at') + .eq('company_id', companyId) + .eq('status', 'paid') + .not('paid_at', 'is', null), + supabase + .from('supplier_invoices') + .select('supplier_id, total_sek, total, supplier:suppliers(id, name)') + .eq('company_id', companyId) + .gte('invoice_date', period.period_start) + .lte('invoice_date', period.period_end) + .neq('status', 'credited'), + ]) + + const cashPosition = calculateCashPosition(trialBalanceResult.rows) + const vatOutputAccounts = ['2611', '2621', '2631'] + const vatInputAccounts = ['2641', '2645'] + const outputVat = trialBalanceResult.rows + .filter((r) => vatOutputAccounts.includes(r.account_number)) + .reduce((sum, r) => sum + (r.closing_credit - r.closing_debit), 0) + const inputVat = trialBalanceResult.rows + .filter((r) => vatInputAccounts.includes(r.account_number)) + .reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0) + const vatLiability = Math.round((outputVat - inputVat) * 100) / 100 + + const paidInvoices = (paidInvoicesResult.data ?? []).map((inv) => ({ + invoice_date: inv.invoice_date as string, + paid_at: inv.paid_at as string, + })) + + // Expense composition by BAS class (mirrors KPI JSON route logic). + const expenseComposition = trialBalanceResult.rows.reduce( + (acc, r) => { + if (r.account_class < 4 || r.account_class > 7) return acc + const amount = r.closing_debit - r.closing_credit + if (amount <= 0) return acc + if (r.account_class === 4) acc.class4 += amount + else if (r.account_class === 5) acc.class5 += amount + else if (r.account_class === 6) acc.class6 += amount + else if (r.account_class === 7) acc.class7 += amount + return acc + }, + { class4: 0, class5: 0, class6: 0, class7: 0 }, + ) + + type SupplierInvoiceRow = { + supplier_id: string | null + total_sek: number | null + total: number | null + supplier: { id: string; name: string } | { id: string; name: string }[] | null + } + const supplierTotals = new Map() + for (const row of (topSuppliersResult.data ?? []) as SupplierInvoiceRow[]) { + if (!row.supplier_id) continue + const supplier = Array.isArray(row.supplier) ? row.supplier[0] : row.supplier + if (!supplier?.name) continue + const amount = row.total_sek ?? null + if (amount == null) continue + const existing = supplierTotals.get(row.supplier_id) + if (existing) existing.total += amount + else supplierTotals.set(row.supplier_id, { name: supplier.name, total: amount }) + } + const topSuppliers = Array.from(supplierTotals.values()) + .map((v) => ({ + supplier_name: v.name, + total: Math.round(v.total * 100) / 100, + })) + .sort((a, b) => b.total - a.total) + .slice(0, 7) + + // Sheet 1: scalar KPIs, label + value. Currency by default; percent rows + // are split into a separate sheet so the formatting is unambiguous. + const currencyKpis: KpiKv[] = [ + { label: 'Årets resultat', value: incomeStatement.net_result }, + { label: 'Likvida medel', value: cashPosition }, + { label: 'Utestående kundfordringar', value: arLedger.total_outstanding }, + { label: 'Förfallna kundfordringar', value: arLedger.total_overdue }, + { label: 'Momsskuld (ruta 49)', value: vatLiability }, + { label: 'Totala intäkter', value: incomeStatement.total_revenue }, + { label: 'Totala kostnader', value: incomeStatement.total_expenses }, + ] + + const percentKpis: KpiKv[] = [ + // calculateGrossMargin returns percentage as `25.5` (i.e. percent units). + // The xlsx percent format expects fractional values (0.255 → 25.50%). + // Divide by 100 so the displayed value matches the in-app KPI tile. + { label: 'Bruttomarginal', value: scaleToFraction(calculateGrossMargin(incomeStatement)) }, + { label: 'Kostnadsandel', value: scaleToFraction(calculateExpenseRatio(incomeStatement)) }, + ] + + const integerKpis: KpiKv[] = [ + { label: 'Genomsnittliga betaldagar', value: calculateAvgPaymentDays(paidInvoices) }, + ] + + const monthRows: MonthRow[] = monthlyBreakdown.months + + const compositionRows: CompositionRow[] = [ + { klass: '4 — Material/varor', amount: Math.round(expenseComposition.class4 * 100) / 100 }, + { klass: '5 — Externa kostnader', amount: Math.round(expenseComposition.class5 * 100) / 100 }, + { klass: '6 — Externa kostnader', amount: Math.round(expenseComposition.class6 * 100) / 100 }, + { klass: '7 — Personalkostnader', amount: Math.round(expenseComposition.class7 * 100) / 100 }, + ] + + const supplierRows: SupplierRow[] = topSuppliers + + const buffer = reportToWorkbook([ + { + name: 'Nyckeltal (kr)', + columns: [textColumn('Nyckeltal'), currencyColumn('Värde')], + rows: currencyKpis, + mapRow: (r) => [r.label, r.value], + }, + { + name: 'Nyckeltal (%)', + columns: [textColumn('Nyckeltal'), percentColumn('Värde')], + rows: percentKpis, + mapRow: (r) => [r.label, r.value], + }, + { + name: 'Nyckeltal (övrigt)', + columns: [textColumn('Nyckeltal'), integerColumn('Värde')], + rows: integerKpis, + mapRow: (r) => [r.label, r.value], + }, + { + name: 'Månadsbrytning', + columns: [ + textColumn('Månad'), + currencyColumn('Intäkter'), + currencyColumn('Kostnader'), + currencyColumn('Netto'), + ], + rows: monthRows, + mapRow: (m) => [m.label, m.income, m.expenses, m.net], + }, + { + name: 'Kostnadssammansättning', + columns: [textColumn('Kontoklass'), currencyColumn('Belopp')], + rows: compositionRows, + mapRow: (r) => [r.klass, r.amount], + }, + { + name: 'Topp leverantörer', + columns: [textColumn('Leverantör'), currencyColumn('Totalt')], + rows: supplierRows, + mapRow: (r) => [r.supplier_name, r.total], + }, + ]) + + const filename = xlsxFilename('nyckeltal', companyRow?.company_name ?? '', period.period_end) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera nyckeltalsrapport' }, + { status: 500 } + ) + } +} + +function scaleToFraction(value: number | null): number | null { + return value === null ? null : Math.round(value) / 100 +} diff --git a/app/api/reports/monthly-breakdown/xlsx/route.ts b/app/api/reports/monthly-breakdown/xlsx/route.ts new file mode 100644 index 00000000..89618a15 --- /dev/null +++ b/app/api/reports/monthly-breakdown/xlsx/route.ts @@ -0,0 +1,77 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const [{ data: period }, { data: companyRow }] = await Promise.all([ + supabase + .from('fiscal_periods') + .select('period_start, period_end') + .eq('id', periodId) + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single(), + ]) + + try { + const breakdown = await generateMonthlyBreakdown(supabase, companyId, periodId) + + const buffer = reportToWorkbook([ + { + name: 'Månadsbrytning', + columns: [ + textColumn('Månad'), + currencyColumn('Intäkter'), + currencyColumn('Kostnader'), + currencyColumn('Netto'), + ], + rows: breakdown.months, + mapRow: (m) => [m.label, m.income, m.expenses, m.net], + }, + ]) + + const filename = xlsxFilename( + 'manadsbrytning', + companyRow?.company_name ?? '', + period?.period_end ?? new Date().toISOString().slice(0, 10), + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera månadsbrytning' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/resultatrapport/xlsx/route.ts b/app/api/reports/resultatrapport/xlsx/route.ts new file mode 100644 index 00000000..5c9a31b3 --- /dev/null +++ b/app/api/reports/resultatrapport/xlsx/route.ts @@ -0,0 +1,111 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateResultatrapport } from '@/lib/reports/resultatrapport' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface FlatRow { + group: string + account_number: string + account_name: string + current_period: number + prior_period: number +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const report = await generateResultatrapport(supabase, companyId, periodId) + + const rows: FlatRow[] = [] + for (const g of report.groups) { + for (const r of g.rows) { + rows.push({ + group: g.class_label, + account_number: r.account_number, + account_name: r.account_name, + current_period: r.current_period, + prior_period: r.prior_period, + }) + } + rows.push({ + group: g.class_label, + account_number: '', + account_name: `Summa ${g.class_label}`, + current_period: g.subtotal_current, + prior_period: g.subtotal_prior, + }) + } + rows.push({ + group: 'Resultat', + account_number: '', + account_name: 'Årets resultat', + current_period: report.net_result_current, + prior_period: report.net_result_prior, + }) + + const buffer = reportToWorkbook([ + { + name: 'Resultatrapport', + columns: [ + textColumn('Grupp'), + textColumn('Konto'), + textColumn('Kontonamn'), + currencyColumn('Aktuell period'), + currencyColumn('Föregående period'), + ], + rows, + mapRow: (r) => [ + r.group, + r.account_number, + r.account_name, + r.current_period, + r.prior_period, + ], + }, + ]) + + const filename = xlsxFilename( + 'resultatrapport', + companyRow?.company_name ?? '', + report.period.end, + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera resultatrapport' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/salary-journal/xlsx/route.ts b/app/api/reports/salary-journal/xlsx/route.ts new file mode 100644 index 00000000..95775c6d --- /dev/null +++ b/app/api/reports/salary-journal/xlsx/route.ts @@ -0,0 +1,113 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { requireCompanyId } from '@/lib/company/context' +import { generateSalaryJournal } from '@/lib/reports/salary-journal' +import { + reportToWorkbook, + textColumn, + currencyColumn, + dateColumn, + integerColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +function toDate(s: string): Date | null { + if (!s) return null + const d = new Date(s) + return isNaN(d.getTime()) ? null : d +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const year = parseInt(searchParams.get('year') || new Date().getFullYear().toString()) + const monthFrom = searchParams.get('month_from') ? parseInt(searchParams.get('month_from')!) : undefined + const monthTo = searchParams.get('month_to') ? parseInt(searchParams.get('month_to')!) : undefined + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const report = await generateSalaryJournal(supabase, companyId, year, monthFrom, monthTo) + + const buffer = reportToWorkbook([ + { + name: 'Lönejournal', + columns: [ + textColumn('Anställd'), + textColumn('Personnr (4)'), + textColumn('Anställning'), + integerColumn('År'), + integerColumn('Månad'), + dateColumn('Utbetalningsdatum'), + currencyColumn('Bruttolön'), + currencyColumn('Skatt'), + currencyColumn('Nettolön'), + currencyColumn('Arbetsgivaravgifter'), + currencyColumn('Semesterlönereservation'), + currencyColumn('Semesterskuld avgifter'), + currencyColumn('Total arbetsgivarkostnad'), + integerColumn('Sjukdagar'), + integerColumn('VAB-dagar'), + integerColumn('Föräldradagar'), + integerColumn('Semesterdagar uttagna'), + textColumn('Status'), + ], + rows: report.rows, + mapRow: (r) => [ + r.employeeName, + r.personnummerLast4, + r.employmentType, + r.periodYear, + r.periodMonth, + toDate(r.paymentDate), + r.grossSalary, + r.taxWithheld, + r.netSalary, + r.avgifterAmount, + r.vacationAccrual, + r.vacationAccrualAvgifter, + r.totalEmployerCost, + r.sickDays, + r.vabDays, + r.parentalDays, + r.vacationDaysTaken, + r.salaryRunStatus, + ], + }, + ]) + + // Use the period's last month-end as the filename anchor. For full-year + // reports this is `YYYY-12-31`; for narrowed month ranges we approximate + // with the end month's last day (good enough for filename ordering). + const endMonth = monthTo ?? 12 + const periodAnchor = `${year}-${String(endMonth).padStart(2, '0')}-31` + const filename = xlsxFilename( + 'lonejournal', + companyRow?.company_name ?? '', + periodAnchor, + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera lönejournal' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/__tests__/route.test.ts b/app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/__tests__/route.test.ts new file mode 100644 index 00000000..d985dc04 --- /dev/null +++ b/app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/__tests__/route.test.ts @@ -0,0 +1,151 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMockRequest, createMockRouteParams } from '@/tests/helpers' + +vi.mock('@/lib/supabase/server', () => ({ + createClient: vi.fn(), +})) + +vi.mock('@/lib/company/context', () => ({ + requireCompanyId: vi.fn().mockResolvedValue('company-1'), +})) + +vi.mock('@/lib/bookkeeping/currency-utils', () => ({ + resolveSekAmount: vi.fn((amount: number) => amount), +})) + +import { createClient } from '@/lib/supabase/server' +import { GET } from '../route' + +const mockCreateClient = vi.mocked(createClient) + +interface QueryResult { + data: unknown + error: unknown +} + +function buildSupabase( + user: { id: string } | null, + supplier: { id: string; name: string } | null, + invoicesResult: QueryResult, + entriesResult: QueryResult +) { + return { + auth: { + getUser: vi.fn().mockResolvedValue({ data: { user } }), + }, + from: vi.fn().mockImplementation((table: string) => { + if (table === 'suppliers') { + return { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + maybeSingle: vi.fn().mockResolvedValue({ data: supplier, error: null }), + } + } + if (table === 'supplier_invoices') { + return { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + in: vi.fn().mockReturnThis(), + order: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + then: (resolve: (v: QueryResult) => void) => resolve(invoicesResult), + } + } + // journal_entries + return { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + in: vi.fn().mockReturnThis(), + then: (resolve: (v: QueryResult) => void) => resolve(entriesResult), + } + }), + } +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('GET /api/reports/supplier-ledger/supplier/[supplierId]/invoices', () => { + it('returns 401 when not authenticated', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase(null, null, { data: [], error: null }, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/supplier-ledger/supplier/sup-1/invoices' + ) + const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' })) + expect(res.status).toBe(401) + }) + + it('returns 404 when supplier is unknown', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, null, { data: [], error: null }, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/supplier-ledger/supplier/sup-1/invoices' + ) + const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' })) + expect(res.status).toBe(404) + }) + + it('happy path: returns supplier invoices with journal entries', async () => { + const invoices = [ + { + id: 'si-1', + supplier_invoice_number: 'INV-7', + invoice_date: '2026-05-10', + due_date: '2026-06-10', + total: 2500, + paid_amount: 0, + remaining_amount: 2500, + currency: 'SEK', + exchange_rate: null, + registration_journal_entry_id: 'je-3', + }, + ] + const entries = [ + { + id: 'je-3', + voucher_number: 33, + voucher_series: 'B', + description: 'Leverantörsfaktura INV-7', + entry_date: '2026-05-10', + }, + ] + mockCreateClient.mockResolvedValue( + buildSupabase( + { id: 'user-1' }, + { id: 'sup-1', name: 'Office Supply AB' }, + { data: invoices, error: null }, + { data: entries, error: null } + ) as never + ) + const req = createMockRequest( + '/api/reports/supplier-ledger/supplier/sup-1/invoices' + ) + const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' })) + expect(res.status).toBe(200) + + const body = (await res.json()) as { + data: { + supplier_id: string + supplier_name: string + lines: Array<{ + supplier_invoice_id: string + journal_entry_id: string + voucher_number: number + credit: number + }> + } + } + + expect(body.data.supplier_id).toBe('sup-1') + expect(body.data.supplier_name).toBe('Office Supply AB') + expect(body.data.lines).toHaveLength(1) + expect(body.data.lines[0].supplier_invoice_id).toBe('si-1') + expect(body.data.lines[0].journal_entry_id).toBe('je-3') + expect(body.data.lines[0].voucher_number).toBe(33) + expect(body.data.lines[0].credit).toBe(2500) + }) +}) diff --git a/app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/route.ts b/app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/route.ts new file mode 100644 index 00000000..62e898a5 --- /dev/null +++ b/app/api/reports/supplier-ledger/supplier/[supplierId]/invoices/route.ts @@ -0,0 +1,143 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { requireCompanyId } from '@/lib/company/context' +import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils' +import type { ReportSourceLine } from '@/lib/reports/source-lines' + +/** + * GET /api/reports/supplier-ledger/supplier/[supplierId]/invoices + * + * Returns the supplier invoices behind a supplier's outstanding balance. + * Each row's `journal_entry_id` points at the registration journal entry + * (when posted) so the UI can link to `/bookkeeping/[id]`. + */ +const PAGE_LIMIT = 500 + +export async function GET( + request: Request, + { params }: { params: Promise<{ supplierId: string }> } +) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + const { supplierId } = await params + + const { data: supplier } = await supabase + .from('suppliers') + .select('id, name') + .eq('id', supplierId) + .eq('company_id', companyId) + .maybeSingle() + + if (!supplier) { + return NextResponse.json({ error: 'Leverantör saknas' }, { status: 404 }) + } + + // Mirror `generateSupplierLedger`'s filter: registered/approved/partially + // paid/overdue invoices that still have an outstanding balance. + const { data, error } = await supabase + .from('supplier_invoices') + .select(` + id, + supplier_invoice_number, + invoice_date, + due_date, + total, + paid_amount, + remaining_amount, + currency, + exchange_rate, + registration_journal_entry_id + `) + .eq('company_id', companyId) + .eq('supplier_id', supplierId) + .in('status', ['registered', 'approved', 'partially_paid', 'overdue']) + .order('invoice_date', { ascending: true }) + .limit(PAGE_LIMIT) + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const invoices = (data || []) as any[] + + // Pull the registration entries in one batch to get voucher numbers. + const entryIds = invoices + .map((i) => i.registration_journal_entry_id) + .filter((id): id is string => !!id) + const entryMap = new Map< + string, + { voucher_number: number; voucher_series: string; description: string | null; entry_date: string } + >() + if (entryIds.length > 0) { + const { data: entries } = await supabase + .from('journal_entries') + .select('id, voucher_number, voucher_series, description, entry_date') + .eq('company_id', companyId) + .in('id', entryIds) + .in('status', ['posted', 'reversed']) + for (const e of entries || []) { + entryMap.set(e.id, { + voucher_number: e.voucher_number, + voucher_series: e.voucher_series || 'A', + description: e.description, + entry_date: e.entry_date, + }) + } + } + + const lines: (ReportSourceLine & { + supplier_invoice_id: string + supplier_invoice_number: string + remaining_sek: number | null + currency: string + paid_amount: number + due_date: string + })[] = invoices.map((inv) => { + const entry = inv.registration_journal_entry_id + ? entryMap.get(inv.registration_journal_entry_id) + : undefined + + const remaining = Number(inv.remaining_amount) || 0 + const isFx = inv.currency && inv.currency !== 'SEK' + const hasRate = inv.exchange_rate != null && Number(inv.exchange_rate) > 0 + const remainingSek = + isFx && !hasRate + ? null + : resolveSekAmount(remaining, null, inv.currency, inv.exchange_rate) + + return { + journal_entry_id: inv.registration_journal_entry_id || '', + voucher_number: entry?.voucher_number ?? 0, + voucher_series: entry?.voucher_series ?? 'A', + date: inv.invoice_date || entry?.entry_date || '', + description: + entry?.description ?? + `Leverantörsfaktura ${inv.supplier_invoice_number || ''}`, + debit: 0, + // For an unpaid AP entry, the open balance is a credit on 2440. + credit: remainingSek ?? remaining, + supplier_invoice_id: inv.id, + supplier_invoice_number: inv.supplier_invoice_number || '', + remaining_sek: remainingSek, + currency: inv.currency || 'SEK', + paid_amount: Number(inv.paid_amount) || 0, + due_date: inv.due_date, + } + }) + + return NextResponse.json({ + data: { + supplier_id: supplier.id, + supplier_name: supplier.name, + lines, + next_cursor: null, + }, + }) +} diff --git a/app/api/reports/supplier-ledger/xlsx/route.ts b/app/api/reports/supplier-ledger/xlsx/route.ts new file mode 100644 index 00000000..dc7df499 --- /dev/null +++ b/app/api/reports/supplier-ledger/xlsx/route.ts @@ -0,0 +1,96 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateSupplierLedger } from '@/lib/reports/supplier-ledger' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' + +interface AgingRow { + supplier_name: string + current: number + days_1_30: number + days_31_60: number + days_61_90: number + days_90_plus: number + total_outstanding: number +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const asOfDate = searchParams.get('as_of_date') || undefined + + const { data: companyRow } = await supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single() + + try { + const ledger = await generateSupplierLedger(supabase, companyId, asOfDate) + + const rows: AgingRow[] = ledger.entries.map((e) => ({ + supplier_name: e.supplier_name, + current: e.current, + days_1_30: e.days_1_30, + days_31_60: e.days_31_60, + days_61_90: e.days_61_90, + days_90_plus: e.days_90_plus, + total_outstanding: e.total_outstanding, + })) + + const buffer = reportToWorkbook([ + { + name: 'Leverantörsreskontra', + columns: [ + textColumn('Leverantör'), + currencyColumn('Ej förfallet'), + currencyColumn('1-30 dagar'), + currencyColumn('31-60 dagar'), + currencyColumn('61-90 dagar'), + currencyColumn('90+ dagar'), + currencyColumn('Totalt utestående'), + ], + rows, + mapRow: (r) => [ + r.supplier_name, + r.current, + r.days_1_30, + r.days_31_60, + r.days_61_90, + r.days_90_plus, + r.total_outstanding, + ], + }, + ]) + + const filename = xlsxFilename( + 'leverantorsreskontra', + companyRow?.company_name ?? '', + asOfDate ?? new Date().toISOString().slice(0, 10), + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera leverantörsreskontra' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/trial-balance/account/[accountNumber]/sources/__tests__/route.test.ts b/app/api/reports/trial-balance/account/[accountNumber]/sources/__tests__/route.test.ts new file mode 100644 index 00000000..48b45cc1 --- /dev/null +++ b/app/api/reports/trial-balance/account/[accountNumber]/sources/__tests__/route.test.ts @@ -0,0 +1,163 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMockRequest, createMockRouteParams } from '@/tests/helpers' + +vi.mock('@/lib/supabase/server', () => ({ + createClient: vi.fn(), +})) + +vi.mock('@/lib/company/context', () => ({ + requireCompanyId: vi.fn().mockResolvedValue('company-1'), +})) + +import { createClient } from '@/lib/supabase/server' +import { GET } from '../route' + +const mockCreateClient = vi.mocked(createClient) + +interface AuthShape { + auth: { getUser: ReturnType } + from: ReturnType +} + +function buildSupabase( + user: { id: string } | null, + account: { account_number: string; account_name: string } | null, + linesResult: { data: unknown; error: unknown } +): AuthShape { + return { + auth: { + getUser: vi.fn().mockResolvedValue({ data: { user } }), + }, + from: vi.fn().mockImplementation((table: string) => { + if (table === 'chart_of_accounts') { + const chain = { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + maybeSingle: vi.fn().mockResolvedValue({ data: account, error: null }), + } + return chain + } + // journal_entry_lines + const chain = { + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + in: vi.fn().mockReturnThis(), + gte: vi.fn().mockReturnThis(), + lte: vi.fn().mockReturnThis(), + order: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + or: vi.fn().mockReturnThis(), + then: (resolve: (v: unknown) => void) => resolve(linesResult), + } + return chain + }), + } +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('GET /api/reports/trial-balance/account/[accountNumber]/sources', () => { + it('returns 401 when not authenticated', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase(null, null, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/trial-balance/account/1930/sources', + { searchParams: { fiscal_period_id: 'period-1' } } + ) + const res = await GET(req, createMockRouteParams({ accountNumber: '1930' })) + expect(res.status).toBe(401) + }) + + it('returns 400 when fiscal_period_id is missing', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, null, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/trial-balance/account/1930/sources' + ) + const res = await GET(req, createMockRouteParams({ accountNumber: '1930' })) + expect(res.status).toBe(400) + }) + + it('returns 404 when account is unknown for the company', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, null, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/trial-balance/account/9999/sources', + { searchParams: { fiscal_period_id: 'period-1' } } + ) + const res = await GET(req, createMockRouteParams({ accountNumber: '9999' })) + expect(res.status).toBe(404) + }) + + it('happy path: returns mapped lines for an account', async () => { + const linesData = [ + { + debit_amount: 1250, + credit_amount: 0, + journal_entry_id: 'je-1', + journal_entries: { + id: 'je-1', + voucher_number: 7, + voucher_series: 'A', + entry_date: '2026-05-02', + description: 'Provision', + status: 'posted', + company_id: 'company-1', + fiscal_period_id: 'period-1', + }, + }, + { + debit_amount: 0, + credit_amount: 700, + journal_entry_id: 'je-2', + journal_entries: { + id: 'je-2', + voucher_number: 8, + voucher_series: 'A', + entry_date: '2026-05-03', + description: 'Återbet', + status: 'posted', + company_id: 'company-1', + fiscal_period_id: 'period-1', + }, + }, + ] + mockCreateClient.mockResolvedValue( + buildSupabase( + { id: 'user-1' }, + { account_number: '1930', account_name: 'Företagskonto' }, + { data: linesData, error: null } + ) as never + ) + + const req = createMockRequest( + '/api/reports/trial-balance/account/1930/sources', + { searchParams: { fiscal_period_id: 'period-1' } } + ) + const res = await GET(req, createMockRouteParams({ accountNumber: '1930' })) + expect(res.status).toBe(200) + + const body = (await res.json()) as { + data: { + account_number: string + account_name: string + lines: Array<{ voucher_number: number; debit: number; credit: number; journal_entry_id: string }> + next_cursor: string | null + } + } + + expect(body.data.account_number).toBe('1930') + expect(body.data.account_name).toBe('Företagskonto') + expect(body.data.lines).toHaveLength(2) + expect(body.data.lines[0].voucher_number).toBe(7) + expect(body.data.lines[0].debit).toBe(1250) + expect(body.data.lines[0].journal_entry_id).toBe('je-1') + expect(body.data.lines[1].credit).toBe(700) + expect(body.data.next_cursor).toBeNull() + }) +}) diff --git a/app/api/reports/trial-balance/account/[accountNumber]/sources/route.ts b/app/api/reports/trial-balance/account/[accountNumber]/sources/route.ts new file mode 100644 index 00000000..ba261117 --- /dev/null +++ b/app/api/reports/trial-balance/account/[accountNumber]/sources/route.ts @@ -0,0 +1,138 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { requireCompanyId } from '@/lib/company/context' +import type { ReportSourceLine } from '@/lib/reports/source-lines' + +/** + * GET /api/reports/trial-balance/account/[accountNumber]/sources + * + * Returns the journal entry lines for one account in a fiscal period, + * ordered by entry date then voucher number ASC. Used by the trial balance + * drilldown UI to show the verifikat behind an aggregated row. + * + * Pagination uses an opaque cursor of `|` for + * the last seen row; pass it back as `cursor` to continue. + */ +const PAGE_LIMIT = 500 + +export async function GET( + request: Request, + { params }: { params: Promise<{ accountNumber: string }> } +) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + const { accountNumber } = await params + + const { searchParams } = new URL(request.url) + const fiscalPeriodId = searchParams.get('fiscal_period_id') + const cursor = searchParams.get('cursor') + + if (!fiscalPeriodId) { + return NextResponse.json( + { error: 'fiscal_period_id is required' }, + { status: 400 } + ) + } + + // Look up account name (and verify account belongs to the company) + const { data: account } = await supabase + .from('chart_of_accounts') + .select('account_number, account_name') + .eq('company_id', companyId) + .eq('account_number', accountNumber) + .maybeSingle() + + if (!account) { + return NextResponse.json( + { error: 'Konto saknas' }, + { status: 404 } + ) + } + + // Pull all lines on this account in this period. We rely on the same + // join+filter pattern as `generateTrialBalance`. Pagination is server-side + // via cursor so even an account with tens of thousands of rows stays cheap. + let query = supabase + .from('journal_entry_lines') + .select(` + debit_amount, + credit_amount, + journal_entry_id, + journal_entries!inner( + id, + voucher_number, + voucher_series, + entry_date, + description, + status, + company_id, + fiscal_period_id + ) + `) + .eq('account_number', accountNumber) + .eq('journal_entries.company_id', companyId) + .eq('journal_entries.fiscal_period_id', fiscalPeriodId) + .in('journal_entries.status', ['posted', 'reversed']) + .order('entry_date', { foreignTable: 'journal_entries', ascending: true }) + .order('voucher_number', { foreignTable: 'journal_entries', ascending: true }) + .limit(PAGE_LIMIT + 1) + + if (cursor) { + // Cursor format: | + const [cursorDate, cursorVoucher] = cursor.split('|') + const cursorVoucherNum = parseInt(cursorVoucher, 10) + if (!cursorDate || isNaN(cursorVoucherNum)) { + return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 }) + } + // Filter for rows strictly after the cursor (date>cur OR same date & voucher>cur). + // Supabase doesn't expose tuple compare, so use an `or()` clause. + query = query.or( + `entry_date.gt.${cursorDate},and(entry_date.eq.${cursorDate},voucher_number.gt.${cursorVoucherNum})`, + { foreignTable: 'journal_entries' } + ) + } + + const { data, error } = await query + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows = (data || []) as any[] + + const lines: ReportSourceLine[] = rows + .slice(0, PAGE_LIMIT) + .map((row) => ({ + journal_entry_id: row.journal_entries.id, + voucher_number: row.journal_entries.voucher_number, + voucher_series: row.journal_entries.voucher_series || 'A', + date: row.journal_entries.entry_date, + description: row.journal_entries.description || '', + debit: Math.round((Number(row.debit_amount) || 0) * 100) / 100, + credit: Math.round((Number(row.credit_amount) || 0) * 100) / 100, + })) + + // If we got more than PAGE_LIMIT rows back, the next cursor points at the + // last delivered row so the next call resumes from after it. + let next_cursor: string | null = null + if (rows.length > PAGE_LIMIT && lines.length > 0) { + const last = lines[lines.length - 1] + next_cursor = `${last.date}|${last.voucher_number}` + } + + return NextResponse.json({ + data: { + account_number: account.account_number, + account_name: account.account_name, + lines, + next_cursor, + }, + }) +} diff --git a/app/api/reports/trial-balance/xlsx/route.ts b/app/api/reports/trial-balance/xlsx/route.ts new file mode 100644 index 00000000..d12bd758 --- /dev/null +++ b/app/api/reports/trial-balance/xlsx/route.ts @@ -0,0 +1,94 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { generateTrialBalance } from '@/lib/reports/trial-balance' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + integerColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' +import type { TrialBalanceRow } from '@/types' + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodId = searchParams.get('period_id') + + if (!periodId) { + return NextResponse.json({ error: 'period_id is required' }, { status: 400 }) + } + + const [{ data: period }, { data: companyRow }] = await Promise.all([ + supabase + .from('fiscal_periods') + .select('period_start, period_end') + .eq('id', periodId) + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single(), + ]) + + if (!period) { + return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 }) + } + + try { + const report = await generateTrialBalance(supabase, companyId, periodId) + + const buffer = reportToWorkbook([ + { + name: 'Saldobalans', + columns: [ + textColumn('Konto'), + textColumn('Kontonamn'), + integerColumn('Klass'), + currencyColumn('IB Debet'), + currencyColumn('IB Kredit'), + currencyColumn('Period Debet'), + currencyColumn('Period Kredit'), + currencyColumn('UB Debet'), + currencyColumn('UB Kredit'), + ], + rows: report.rows, + mapRow: (r) => [ + r.account_number, + r.account_name, + r.account_class, + r.opening_debit, + r.opening_credit, + r.period_debit, + r.period_credit, + r.closing_debit, + r.closing_credit, + ], + }, + ]) + + const filename = xlsxFilename('saldobalans', companyRow?.company_name ?? '', period.period_end) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera saldobalans' }, + { status: 500 } + ) + } +} diff --git a/app/api/reports/vat-declaration/ruta/[ruta]/sources/__tests__/route.test.ts b/app/api/reports/vat-declaration/ruta/[ruta]/sources/__tests__/route.test.ts new file mode 100644 index 00000000..640ade60 --- /dev/null +++ b/app/api/reports/vat-declaration/ruta/[ruta]/sources/__tests__/route.test.ts @@ -0,0 +1,120 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMockRequest, createMockRouteParams } from '@/tests/helpers' + +vi.mock('@/lib/supabase/server', () => ({ + createClient: vi.fn(), +})) + +vi.mock('@/lib/company/context', () => ({ + requireCompanyId: vi.fn().mockResolvedValue('company-1'), +})) + +import { createClient } from '@/lib/supabase/server' +import { GET } from '../route' + +const mockCreateClient = vi.mocked(createClient) + +function buildSupabase( + user: { id: string } | null, + linesResult: { data: unknown; error: unknown } +) { + return { + auth: { + getUser: vi.fn().mockResolvedValue({ data: { user } }), + }, + from: vi.fn().mockImplementation(() => ({ + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + in: vi.fn().mockReturnThis(), + gte: vi.fn().mockReturnThis(), + lte: vi.fn().mockReturnThis(), + order: vi.fn().mockReturnThis(), + limit: vi.fn().mockReturnThis(), + or: vi.fn().mockReturnThis(), + maybeSingle: vi.fn().mockResolvedValue({ data: null, error: null }), + then: (resolve: (v: unknown) => void) => resolve(linesResult), + })), + } +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('GET /api/reports/vat-declaration/ruta/[ruta]/sources', () => { + it('returns 401 when not authenticated', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase(null, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/vat-declaration/ruta/10/sources', + { searchParams: { periodType: 'monthly', year: '2026', period: '5' } } + ) + const res = await GET(req, createMockRouteParams({ ruta: '10' })) + expect(res.status).toBe(401) + }) + + it('returns 400 when period params are missing', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/vat-declaration/ruta/10/sources' + ) + const res = await GET(req, createMockRouteParams({ ruta: '10' })) + expect(res.status).toBe(400) + }) + + it('returns 404 when ruta has no underlying BAS accounts', async () => { + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, { data: [], error: null }) as never + ) + const req = createMockRequest( + '/api/reports/vat-declaration/ruta/99/sources', + { searchParams: { periodType: 'monthly', year: '2026', period: '5' } } + ) + const res = await GET(req, createMockRouteParams({ ruta: '99' })) + expect(res.status).toBe(404) + }) + + it('happy path: returns mapped lines for ruta10', async () => { + const linesData = [ + { + account_number: '2611', + debit_amount: 0, + credit_amount: 250, + journal_entries: { + id: 'je-1', + voucher_number: 12, + voucher_series: 'A', + entry_date: '2026-05-12', + description: 'Faktura 1001', + status: 'posted', + company_id: 'company-1', + }, + }, + ] + mockCreateClient.mockResolvedValue( + buildSupabase({ id: 'user-1' }, { data: linesData, error: null }) as never + ) + + const req = createMockRequest( + '/api/reports/vat-declaration/ruta/10/sources', + { searchParams: { periodType: 'monthly', year: '2026', period: '5' } } + ) + const res = await GET(req, createMockRouteParams({ ruta: '10' })) + expect(res.status).toBe(200) + + const body = (await res.json()) as { + data: { + ruta: string + lines: Array<{ voucher_number: number; credit: number }> + } + } + + expect(body.data.ruta).toBe('ruta10') + expect(body.data.lines).toHaveLength(1) + expect(body.data.lines[0].voucher_number).toBe(12) + expect(body.data.lines[0].credit).toBe(250) + }) +}) diff --git a/app/api/reports/vat-declaration/ruta/[ruta]/sources/route.ts b/app/api/reports/vat-declaration/ruta/[ruta]/sources/route.ts new file mode 100644 index 00000000..984dc29e --- /dev/null +++ b/app/api/reports/vat-declaration/ruta/[ruta]/sources/route.ts @@ -0,0 +1,167 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { requireCompanyId } from '@/lib/company/context' +import { + ACCOUNT_RUTA, + calculatePeriodDates, +} from '@/lib/reports/vat-declaration' +import type { ReportSourceLine } from '@/lib/reports/source-lines' +import type { VatDeclarationRutor, VatPeriodType } from '@/types' + +/** + * GET /api/reports/vat-declaration/ruta/[ruta]/sources + * + * Returns the journal entry lines that contribute to a single ruta on the + * VAT declaration. The mapping ruta → BAS accounts is the inverse of + * `ACCOUNT_RUTA` in `lib/reports/vat-declaration.ts`. + * + * Period can be specified either via: + * ?periodType=monthly|quarterly|yearly&year=2026&period=5 + * ?fiscal_period_id= + * + * The periodType form mirrors the way the main VAT report is fetched. + */ +const PAGE_LIMIT = 500 + +export async function GET( + request: Request, + { params }: { params: Promise<{ ruta: string }> } +) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + const { ruta: rutaParam } = await params + + const { searchParams } = new URL(request.url) + const cursor = searchParams.get('cursor') + + // Normalise ruta param to the keyof VatDeclarationRutor (`ruta10`, `ruta48`). + const rutaKey = ( + rutaParam.startsWith('ruta') ? rutaParam : `ruta${rutaParam}` + ) as keyof VatDeclarationRutor + + // Invert ACCOUNT_RUTA: which BAS accounts feed this ruta? + const accountsForRuta = Object.entries(ACCOUNT_RUTA) + .filter(([, m]) => m.box === rutaKey) + .map(([acc]) => acc) + + if (accountsForRuta.length === 0) { + return NextResponse.json( + { error: `Ruta ${rutaParam} har inga underliggande konton` }, + { status: 404 } + ) + } + + // Resolve the period — either by fiscal_period_id or periodType/year/period. + let start: string | null = null + let end: string | null = null + const fiscalPeriodId = searchParams.get('fiscal_period_id') + if (fiscalPeriodId) { + const { data: period } = await supabase + .from('fiscal_periods') + .select('period_start, period_end') + .eq('id', fiscalPeriodId) + .eq('company_id', companyId) + .maybeSingle() + if (!period) { + return NextResponse.json({ error: 'Period saknas' }, { status: 404 }) + } + start = period.period_start + end = period.period_end + } else { + const periodType = searchParams.get('periodType') as VatPeriodType | null + const yearStr = searchParams.get('year') + const periodStr = searchParams.get('period') + if (!periodType || !yearStr || !periodStr) { + return NextResponse.json( + { error: 'periodType/year/period or fiscal_period_id is required' }, + { status: 400 } + ) + } + const year = parseInt(yearStr, 10) + const periodNum = parseInt(periodStr, 10) + if (isNaN(year) || isNaN(periodNum)) { + return NextResponse.json({ error: 'Invalid period' }, { status: 400 }) + } + const dates = calculatePeriodDates(periodType, year, periodNum) + start = dates.start + end = dates.end + } + + let query = supabase + .from('journal_entry_lines') + .select(` + account_number, + debit_amount, + credit_amount, + journal_entries!inner( + id, + voucher_number, + voucher_series, + entry_date, + description, + status, + company_id + ) + `) + .in('account_number', accountsForRuta) + .eq('journal_entries.company_id', companyId) + .in('journal_entries.status', ['posted', 'reversed']) + .gte('journal_entries.entry_date', start) + .lte('journal_entries.entry_date', end) + .order('entry_date', { foreignTable: 'journal_entries', ascending: true }) + .order('voucher_number', { foreignTable: 'journal_entries', ascending: true }) + .limit(PAGE_LIMIT + 1) + + if (cursor) { + const [cursorDate, cursorVoucher] = cursor.split('|') + const cursorVoucherNum = parseInt(cursorVoucher, 10) + if (!cursorDate || isNaN(cursorVoucherNum)) { + return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 }) + } + query = query.or( + `entry_date.gt.${cursorDate},and(entry_date.eq.${cursorDate},voucher_number.gt.${cursorVoucherNum})`, + { foreignTable: 'journal_entries' } + ) + } + + const { data, error } = await query + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows = (data || []) as any[] + + const lines: ReportSourceLine[] = rows + .slice(0, PAGE_LIMIT) + .map((row) => ({ + journal_entry_id: row.journal_entries.id, + voucher_number: row.journal_entries.voucher_number, + voucher_series: row.journal_entries.voucher_series || 'A', + date: row.journal_entries.entry_date, + description: row.journal_entries.description || '', + debit: Math.round((Number(row.debit_amount) || 0) * 100) / 100, + credit: Math.round((Number(row.credit_amount) || 0) * 100) / 100, + })) + + let next_cursor: string | null = null + if (rows.length > PAGE_LIMIT && lines.length > 0) { + const last = lines[lines.length - 1] + next_cursor = `${last.date}|${last.voucher_number}` + } + + return NextResponse.json({ + data: { + ruta: rutaKey, + lines, + next_cursor, + }, + }) +} diff --git a/app/api/reports/vat-declaration/xlsx/route.ts b/app/api/reports/vat-declaration/xlsx/route.ts new file mode 100644 index 00000000..3910c94e --- /dev/null +++ b/app/api/reports/vat-declaration/xlsx/route.ts @@ -0,0 +1,116 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' +import { + calculateVatDeclaration, + formatPeriodLabel, +} from '@/lib/reports/vat-declaration' +import { requireCompanyId } from '@/lib/company/context' +import { + reportToWorkbook, + textColumn, + currencyColumn, + xlsxFilename, +} from '@/lib/reports/xlsx-export' +import { + VAT_RUTA_LABELS, + type VatPeriodType, + type VatDeclarationRutor, + type AccountingMethod, +} from '@/types' + +interface RutaRow { + ruta: string + label: string + amount: number +} + +export async function GET(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const companyId = await requireCompanyId(supabase, user.id) + + const { searchParams } = new URL(request.url) + const periodType = searchParams.get('periodType') as VatPeriodType | null + const yearStr = searchParams.get('year') + const periodStr = searchParams.get('period') + + if (!periodType || !yearStr || !periodStr) { + return NextResponse.json( + { error: 'periodType, year, and period are required' }, + { status: 400 } + ) + } + if (!['monthly', 'quarterly', 'yearly'].includes(periodType)) { + return NextResponse.json({ error: 'Invalid periodType' }, { status: 400 }) + } + + const year = parseInt(yearStr, 10) + const period = parseInt(periodStr, 10) + if (isNaN(year) || isNaN(period)) { + return NextResponse.json({ error: 'Invalid year or period' }, { status: 400 }) + } + + const [{ data: settings }, { data: companyRow }] = await Promise.all([ + supabase + .from('company_settings') + .select('accounting_method') + .eq('company_id', companyId) + .single(), + supabase + .from('company_settings') + .select('company_name') + .eq('company_id', companyId) + .single(), + ]) + + const accountingMethod = (settings?.accounting_method as AccountingMethod) || 'accrual' + + try { + const declaration = await calculateVatDeclaration( + supabase, companyId, periodType, year, period, accountingMethod, + ) + + const rows: RutaRow[] = (Object.keys(declaration.rutor) as (keyof VatDeclarationRutor)[]).map( + (key) => ({ + ruta: key.replace(/^ruta/, 'Ruta '), + label: VAT_RUTA_LABELS[key], + amount: declaration.rutor[key], + }), + ) + + const buffer = reportToWorkbook([ + { + name: `Moms ${formatPeriodLabel(periodType, year, period)}`, + columns: [ + textColumn('Ruta'), + textColumn('Beskrivning'), + currencyColumn('Belopp'), + ], + rows, + mapRow: (r) => [r.ruta, r.label, r.amount], + }, + ]) + + const filename = xlsxFilename( + 'momsdeklaration', + companyRow?.company_name ?? '', + declaration.period.end, + ) + return new NextResponse(new Uint8Array(buffer), { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename="${filename}"`, + }, + }) + } catch (err) { + return NextResponse.json( + { error: err instanceof Error ? err.message : 'Kunde inte generera momsdeklaration' }, + { status: 500 } + ) + } +} diff --git a/app/api/v1/companies/[companyId]/invoices/[id]/pdf/__tests__/route.test.ts b/app/api/v1/companies/[companyId]/invoices/[id]/pdf/__tests__/route.test.ts index 6a85e9f4..d402d924 100644 --- a/app/api/v1/companies/[companyId]/invoices/[id]/pdf/__tests__/route.test.ts +++ b/app/api/v1/companies/[companyId]/invoices/[id]/pdf/__tests__/route.test.ts @@ -39,6 +39,7 @@ vi.mock('@react-pdf/renderer', () => ({ })) vi.mock('@/lib/invoices/pdf-template', () => ({ InvoicePDF: vi.fn().mockReturnValue({}), + brandingFromCompanySettings: vi.fn().mockReturnValue({}), })) import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys' diff --git a/app/api/v1/companies/[companyId]/invoices/[id]/pdf/route.ts b/app/api/v1/companies/[companyId]/invoices/[id]/pdf/route.ts index b24cca8a..4178e121 100644 --- a/app/api/v1/companies/[companyId]/invoices/[id]/pdf/route.ts +++ b/app/api/v1/companies/[companyId]/invoices/[id]/pdf/route.ts @@ -20,6 +20,7 @@ import { z } from 'zod' import { renderToBuffer } from '@react-pdf/renderer' import { InvoicePDF } from '@/lib/invoices/pdf-template' +import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers' import { registerEndpoint } from '@/lib/api/v1/registry' import { withApiV1 } from '@/lib/api/v1/with-api-v1' import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' @@ -148,6 +149,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string } let pdfBuffer: Buffer try { + const { branding } = prepareInvoicePdfRender(company as CompanySettings) pdfBuffer = await renderToBuffer( InvoicePDF({ invoice: typed as Invoice, @@ -155,6 +157,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string } items, company: company as CompanySettings, originalInvoiceNumber, + branding, }), ) } catch (err) { diff --git a/app/api/v1/companies/[companyId]/invoices/[id]/send/__tests__/route.test.ts b/app/api/v1/companies/[companyId]/invoices/[id]/send/__tests__/route.test.ts index 85fe35c7..364d0013 100644 --- a/app/api/v1/companies/[companyId]/invoices/[id]/send/__tests__/route.test.ts +++ b/app/api/v1/companies/[companyId]/invoices/[id]/send/__tests__/route.test.ts @@ -71,6 +71,7 @@ vi.mock('@/lib/email/invoice-templates', () => ({ vi.mock('@/lib/invoices/pdf-template', () => ({ InvoicePDF: vi.fn().mockReturnValue({}), + brandingFromCompanySettings: vi.fn().mockReturnValue({}), })) import { InvoicePDF } from '@/lib/invoices/pdf-template' diff --git a/app/api/v1/companies/[companyId]/invoices/[id]/send/route.ts b/app/api/v1/companies/[companyId]/invoices/[id]/send/route.ts index 5f5cacea..eb58fa4b 100644 --- a/app/api/v1/companies/[companyId]/invoices/[id]/send/route.ts +++ b/app/api/v1/companies/[companyId]/invoices/[id]/send/route.ts @@ -43,6 +43,7 @@ import { registerEndpoint } from '@/lib/api/v1/registry' import { withApiV1 } from '@/lib/api/v1/with-api-v1' import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors' import { InvoicePDF } from '@/lib/invoices/pdf-template' +import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers' import { getEmailService } from '@/lib/email/service' import { generateInvoiceEmailHtml, @@ -264,6 +265,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string const isFreshAllocation = !typed.invoice_number if (isFreshAllocation) { try { + const preflight = prepareInvoicePdfRender(settings) await renderToBuffer( InvoicePDF({ invoice: { ...(typed as Invoice), invoice_number: 'F-PREVIEW' }, @@ -271,6 +273,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string items, company: settings, originalInvoiceNumber, + branding: preflight.branding, }), ) } catch (err) { @@ -352,6 +355,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string let pdfBuffer: Buffer try { + const { branding } = prepareInvoicePdfRender(settings) pdfBuffer = await renderToBuffer( InvoicePDF({ invoice: renderableInvoice, @@ -359,6 +363,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string items, company: settings, originalInvoiceNumber, + branding, }), ) } catch (err) { diff --git a/components/bookkeeping/AttachmentPreviewSheet.tsx b/components/bookkeeping/AttachmentPreviewSheet.tsx index 7ee6fe75..7b472c63 100644 --- a/components/bookkeeping/AttachmentPreviewSheet.tsx +++ b/components/bookkeeping/AttachmentPreviewSheet.tsx @@ -1,14 +1,28 @@ 'use client' -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { useTranslations } from 'next-intl' -import { ExternalLink, FileText, ImageIcon, Paperclip } from 'lucide-react' import { - Sheet, - SheetContent, - SheetHeader, - SheetTitle, -} from '@/components/ui/sheet' + AlertTriangle, + ExternalLink, + FileText, + ImageIcon, + Loader2, + Lock, + Paperclip, + RefreshCw, + Trash2, +} from 'lucide-react' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { useToast } from '@/components/ui/use-toast' import { Skeleton } from '@/components/ui/skeleton' interface DocumentRecord { @@ -47,9 +61,16 @@ export default function AttachmentPreviewSheet({ onOpenChange, }: AttachmentPreviewSheetProps) { const t = useTranslations('attachment_preview_sheet') + const tj = useTranslations('journal_attachments') + const { toast } = useToast() const [documents, setDocuments] = useState([]) const [loading, setLoading] = useState(false) + const [blockedDoc, setBlockedDoc] = useState(null) + const [replacingDocId, setReplacingDocId] = useState(null) + const replaceFileInputRef = useRef(null) + const replaceTargetIdRef = useRef(null) + const fetchAttachments = useCallback(async (id: string) => { setLoading(true) try { @@ -87,20 +108,64 @@ export default function AttachmentPreviewSheet({ if (open && entryId) { fetchAttachments(entryId) } else if (!open) { - // Reset state when closed so the next open starts fresh setDocuments([]) + setBlockedDoc(null) } }, [open, entryId, fetchAttachments]) + const handleOpenReplacePicker = (docId: string) => { + replaceTargetIdRef.current = docId + replaceFileInputRef.current?.click() + } + + const handleReplaceFileSelected = async (file: File | null) => { + const docId = replaceTargetIdRef.current + replaceTargetIdRef.current = null + if (replaceFileInputRef.current) { + replaceFileInputRef.current.value = '' + } + if (!file || !docId || !entryId) return + + setReplacingDocId(docId) + try { + const fd = new FormData() + fd.append('file', file) + const res = await fetch(`/api/documents/${docId}/versions`, { + method: 'POST', + body: fd, + }) + if (!res.ok) { + const { error } = await res.json().catch(() => ({ error: undefined })) + toast({ + title: tj('replace_failed'), + description: error || undefined, + variant: 'destructive', + }) + } else { + await fetchAttachments(entryId) + setBlockedDoc(null) + } + } catch { + toast({ title: tj('replace_failed'), variant: 'destructive' }) + } finally { + setReplacingDocId(null) + } + } + return ( - - - - {t('title')} - + + + + {t('title')} + + + handleReplaceFileSelected(e.target.files?.[0] ?? null)} + /> {loading ? (
@@ -119,6 +184,7 @@ export default function AttachmentPreviewSheet({ {documents.map((doc) => { const inlineSrc = `/api/documents/${doc.id}/inline` const previewable = isImageType(doc.mime_type) || isPdfType(doc.mime_type) + const isReplacing = replacingDocId === doc.id return (
@@ -137,25 +203,76 @@ export default function AttachmentPreviewSheet({

- {doc.download_url && ( - + + + {doc.download_url && ( + + + {t('open_in_new_tab')} + + )} +
{isPdfType(doc.mime_type) && ( -
Leverantör Ej förfallet 1-30 dagar
{entry.supplier_name}{entry.current > 0 ? formatAmount(entry.current) : ''}{entry.days_1_30 > 0 ? formatAmount(entry.days_1_30) : ''}{entry.days_31_60 > 0 ? formatAmount(entry.days_31_60) : ''}{entry.days_61_90 > 0 ? formatAmount(entry.days_61_90) : ''}{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}{formatAmount(entry.total_outstanding)}
Summa {formatAmount(ledger.entries.reduce((s, e) => s + e.current, 0))} {formatAmount(ledger.entries.reduce((s, e) => s + e.days_1_30, 0))}
{entry.supplier_name}{entry.current > 0 ? formatAmount(entry.current) : ''}{entry.days_1_30 > 0 ? formatAmount(entry.days_1_30) : ''}{entry.days_31_60 > 0 ? formatAmount(entry.days_31_60) : ''}{entry.days_61_90 > 0 ? formatAmount(entry.days_61_90) : ''}{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''}{formatAmount(entry.total_outstanding)}
{line.date} - {entry.voucher_series}{entry.voucher_number} + {formatVoucher(entry)} {entry.date} @@ -2086,6 +2382,102 @@ interface ARLedgerData { } | null } +// Inner expansion row component for AR ledger. +// Fetches per-customer invoices (with journal_entry_id) and renders each as a +// link to /bookkeeping/[id] when posted, /invoices/[id] when still draft. +function ARCustomerInvoiceRows({ + customerId, + invoices, +}: { + customerId: string + invoices: { + invoice_id: string + invoice_number: string + invoice_date: string + due_date: string + total: number + paid_amount: number + outstanding: number + outstanding_sek: number | null + days_overdue: number + currency: string + }[] +}) { + // ARCustomerInvoiceRows is mounted lazily — only when a customer is + // expanded, so initial state matches "still loading" and resets on + // unmount. No synchronous setState in the effect is needed. + const [enriched, setEnriched] = useState>({}) + const [loaded, setLoaded] = useState(false) + + useEffect(() => { + let cancelled = false + fetch(`/api/reports/ar-ledger/customer/${encodeURIComponent(customerId)}/invoices`) + .then((r) => r.json()) + .then((json) => { + if (cancelled) return + const map: typeof enriched = {} + for (const line of json.data?.lines || []) { + if (line.invoice_id && line.journal_entry_id) { + map[line.invoice_id] = { + journal_entry_id: line.journal_entry_id, + voucher_series: line.voucher_series, + voucher_number: line.voucher_number, + } + } + } + setEnriched(map) + }) + .catch(() => { /* fail silently; rows still render without verifikat link */ }) + .finally(() => { if (!cancelled) setLoaded(true) }) + return () => { cancelled = true } + }, [customerId]) + const loading = !loaded + + return ( + <> + {invoices.map((inv) => { + const entry = enriched[inv.invoice_id] + const targetHref = entry?.journal_entry_id + ? `/bookkeeping/${entry.journal_entry_id}` + : `/invoices/${inv.invoice_id}` + return ( +
+ + {inv.invoice_number || '(utkast)'} + + {entry && ( + + {formatVoucher(entry)} + + )} + {formatDate(inv.invoice_date)} + förfaller {formatDate(inv.due_date)} + + {inv.days_overdue > 0 ? `${inv.days_overdue} dagar förfallen` : 'Ej förfallen'} + + {inv.paid_amount > 0 ? `Betalt: ${formatAmount(inv.paid_amount)}` : ''} + + {formatAmount(inv.outstanding)} {inv.currency} +
Letar verifikat…
{entry.days_90_plus > 0 ? formatAmount(entry.days_90_plus) : ''} {formatAmount(entry.total_outstanding)}
- {inv.invoice_number} - {formatDate(inv.invoice_date)} - förfaller {formatDate(inv.due_date)} - - {inv.days_overdue > 0 ? `${inv.days_overdue} dagar förfallen` : 'Ej förfallen'} - - {inv.paid_amount > 0 ? `Betalt: ${formatAmount(inv.paid_amount)}` : ''} - - {formatAmount(inv.outstanding)} {inv.currency} -