From 8322830f464b78f6cc38b964a2de8e615340c824 Mon Sep 17 00:00:00 2001 From: Mattsson <111893710+mattssonn@users.noreply.github.com> Date: Tue, 16 Jun 2026 10:42:37 +0200 Subject: [PATCH] Add/issue in absurdum (#739) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(assets): allow editing fixed asset fields before depreciation The fixed asset register only offered a "Dispose" action, so correcting a mis-entered acquisition date/cost/category meant running the disposal flow — which posts a real divestment voucher plus a Ch. 8a VAT adjustment. Disproportionate and wrong for a data-entry fix. Add an Edit action that allows correcting those fields directly, gated for correctness: - service: extend updateAsset() with category/acquisition_date/ acquisition_cost; block the change once the asset is disposed or has posted depreciation (AssetCorrectionBlockedError) where it would desync posted vouchers from the register; realign the BAS triple on category change. Name, useful life, and method stay editable. - api: extend the PATCH schema; annotate GET /api/assets with has_posted_depreciation so the UI can lock basis fields proactively. - ui: EditAssetDialog + pencil action; disables date/cost/category when depreciation has been booked, with an inline explanation. - errors: register ASSET_CORRECTION_BLOCKED (409). - tests: unit tests for the guard; pg test for pre-disposal editability. Co-Authored-By: Claude Opus 4.8 (1M context) * feat(assets): also block basis edits when depreciation was hand-posted The correction guard only consulted depreciation_schedules, so an avskrivning booked as a manual journal entry (no schedule row) slipped through and a basis correction was wrongly allowed. Add a ledger scan: any posted credit to the asset's ackumulerade- avskrivningar account (12x9) counts as depreciation. Entries that depreciation_schedules attributes to a *different* asset are excluded, so a sibling's engine avskrivning on a shared 12x9 account doesn't produce a false block. What remains is depreciation tied to this asset (engine or manual); a basis correction is blocked there and must go through storno. Adds two unit tests: blocks on a hand-posted credit, allows when the only 12x9 credit belongs to a sibling's engine entry. Co-Authored-By: Claude Opus 4.8 (1M context) * fix(invoices): allow negative unit prices for discount lines The invoice creation form rejected negative unit prices via a frontend superRefine check, blocking valid discount lines (e.g. "Rabatt -100"). The unit_price error was never rendered inline, so submission failed silently. The backend schema already allows negative unit prices (see CreateInvoiceItemSchema test), so the form was simply out of sync. Remove the non-negative constraint; empty/NaN prices are still rejected by the base z.number() type. Drop the now-unused validation_price_positive translation key from both locale files. Co-Authored-By: Claude Opus 4.8 (1M context) * feat(invoices): allow editing draft invoices Drafts could be saved but not edited — the only way to change a draft's lines, customer, dates or amounts was to delete and recreate it. Add a "Redigera" action on draft invoices that opens the invoice editor pre-filled with the draft and saves changes in place. A verifikat is only created when an invoice is sent (or paid, under kontantmetoden), so every status=draft invoice is uncommitted and safe to edit; sent/paid invoices stay immutable and still require a credit note. - Extract buildInvoiceWriteData() with the shared validation + computation (VAT rules, ROT/RUT, accruals, totals, currency, item rows); POST now uses it too, behaviour unchanged. - Add UpdateInvoiceSchema and PATCH /api/invoices/[id], guarded to drafts (status=draft, no journal entry, not self-billed); number and status are preserved and no invoice.created is emitted. - Extract the invoice creator into a shared InvoiceEditor with create / edit modes; /invoices/new is now a thin wrapper and /invoices/[id]/edit is the new edit page. - Add a "Redigera" button on draft invoice detail pages + sv/en strings. - Tests for the builder, UpdateInvoiceSchema and the PATCH route. Co-Authored-By: Claude Opus 4.8 (1M context) * feat(reports): make Huvudbok findable via account/saldo search terms Searching the command palette for natural phrases like 'saldo per konto', 'kontoutdrag', 'kontoanalys' or 'transaktioner per konto' returned nothing, so users couldn't find the general ledger. Enrich the Huvudbok entry's keywords with those synonyms, and let Saldobalans and Balansrapport match 'saldo per konto' too since they are genuinely per-account balance views. Companion change — the clearer Huvudbok report description ('Saldo och alla transaktioner per konto') — already landed in d5f474cb. Co-Authored-By: Claude Opus 4.8 (1M context) * feat(settings): let users edit their personal name Add an editable Namn field to /settings/account that updates profiles.full_name and best-effort syncs auth user_metadata. Previously the personal name was only ever set from BankID's legal name at signup with no way to correct it, so users whose tilltalsnamn isn't their first given name were greeted by the wrong name (and email/password users had no name at all). New POST /api/user/profile route (requireAuth, RLS-scoped update) mirrors /api/user/locale. sv/en strings added. Co-Authored-By: Claude Opus 4.8 * feat(invoices): per-invoice öresavrundning override Add a display-only öresavrundning flag per invoice that wins over the company-wide setting. Resolution order in getDisplayTotal: per-invoice override -> company setting -> default-on. The stored total and the booked verifikat keep the exact öre; only the rendered total changes. Supplier invoices gain the same flag but resolve a null to off (they never had rounding historically), exposed via a toggle on the new-invoice form and a rounding row on the detail page. Co-Authored-By: Claude Opus 4.8 * feat(transactions): warn on possible duplicate before booking Before committing a transaction (via book or categorize), detect an already-booked sibling with the same date and amount and return a 409 TRANSACTION_BOOK_POSSIBLE_DUPLICATE instead of silently double-booking. The user can override with force=true, which must be bound to the reviewed sibling via expected_duplicate_transaction_id; the candidate is re-detected server-side, so a stale or guessed id is rejected with TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH. Detection is fail-open on the non-force path and fail-closed under force. Co-Authored-By: Claude Opus 4.8 * feat(transactions): shadow-mode scope-drift dedup counter in bank ingest Count rows that an enforcing same-feed scope-drift rule WOULD treat as re-imports (the IBAN-drift re-imports the external_id check misses) and surface it as IngestResult.shadow_scope_drift_candidates. Nothing is blocked yet -- the counter only measures how often the rule would fire so it can be validated against real data before enforcement. Also gitignore scripts/delete-duplicate-transactions.ts: a destructive, hand-run cleanup tool kept out of the repo so it can't run in CI/cron or be mistaken for a supported feature. Co-Authored-By: Claude Opus 4.8 * fix(bokslut): base bolagsskatt on post-disposition result Bokslutsdispositioner are booked as source_type='year_end', which the income statement excludes, so net_result alone overstates resultat före skatt and the booked tax ignored the periodiseringsfond avsättning (too-high tax, ÅR/INK2 mismatch). calculateBolagsskatt now accepts resultBeforeTaxOverride. The preview builder mirrors each proposal's P&L effect (+återföring, -avsättning, -SLP) onto the pre-disposition result; the commit path sums the already-posted dispositions via the new sumPostedYearEndDispositions (class 88 + 7533) since bolagsskatt is committed last. Co-Authored-By: Claude Opus 4.8 * feat(settings): fiscal years manager Add a FiscalYearsManager to the bookkeeping settings that lists fiscal periods with their status (closed > locked > open) and creates the next year via CreatePeriodDialog, seeded to chain forward from the latest period end. Co-Authored-By: Claude Opus 4.8 * fix(api): return 400 when locking a period with unbooked transactions lockPeriod() refuses to lock a period that still has uncategorized business transactions. Detect that message in the lock route and surface it as a clear PERIOD_HAS_UNBOOKED_TRANSACTIONS (400) instead of a generic 500. Co-Authored-By: Claude Opus 4.8 * feat(invoices): implement isEditableInvoiceDraft utility and apply it across invoice edit routes feat(transactions): log duplicate dismissal events in behandlingshistorik test(invoices): add tests for isEditableInvoiceDraft function test(transactions): enhance tests to verify behandlingshistorik logging refactor(bokslut): update tax calculation test descriptions for clarity --------- Co-authored-by: Claude Opus 4.8 (1M context) --- .gitignore | 5 + app/(dashboard)/assets/page.tsx | 46 +- app/(dashboard)/invoices/[id]/edit/page.tsx | 87 + app/(dashboard)/invoices/[id]/page.tsx | 14 + app/(dashboard)/invoices/new/page.tsx | 1945 +-------------- app/(dashboard)/invoices/page.tsx | 4 +- app/(dashboard)/page.tsx | 4 +- .../supplier-invoices/[id]/page.tsx | 18 +- .../supplier-invoices/new/page.tsx | 23 + app/api/assets/[id]/route.ts | 22 +- app/api/assets/route.ts | 28 +- .../[id]/bokslutsdispositioner/route.ts | 21 +- .../[id]/lock/__tests__/route.test.ts | 78 + .../fiscal-periods/[id]/lock/route.ts | 9 + app/api/invoices/[id]/__tests__/patch.test.ts | 201 ++ app/api/invoices/[id]/route.ts | 159 +- app/api/invoices/route.ts | 333 +-- app/api/supplier-invoices/route.ts | 2 + .../[id]/book/__tests__/route.test.ts | 126 + app/api/transactions/[id]/book/route.ts | 77 +- .../[id]/categorize/__tests__/route.test.ts | 96 + app/api/transactions/[id]/categorize/route.ts | 71 + app/api/user/profile/route.ts | 66 + .../bookkeeping/assets/EditAssetDialog.tsx | 359 +++ components/common/CommandPalette.tsx | 6 +- components/invoices/InvoiceEditor.tsx | 2112 +++++++++++++++++ components/settings/FiscalYearsManager.tsx | 124 + .../sections/AccountSettingsContent.tsx | 82 +- .../sections/BookkeepingSettingsContent.tsx | 6 + lib/api/__tests__/schemas.test.ts | 28 + lib/api/schemas.ts | 64 +- lib/bokslut/__tests__/asset-service.test.ts | 187 +- .../__tests__/bolagsskatt-calculator.test.ts | 50 + .../k3-framework-dispositions.test.ts | 25 + lib/bokslut/assets/asset-service.ts | 213 +- lib/bokslut/dispositions-proposal-builder.ts | 14 + .../tax-provision/bolagsskatt-calculator.ts | 63 +- lib/errors/structured-errors.ts | 25 + .../__tests__/build-invoice-write.test.ts | 133 ++ .../__tests__/is-editable-draft.test.ts | 32 + lib/invoices/__tests__/rounding.test.ts | 24 + lib/invoices/build-invoice-write.ts | 432 ++++ lib/invoices/is-editable-draft.ts | 20 + lib/invoices/rounding.ts | 30 +- .../booking-duplicate-detection.test.ts | 128 + lib/transactions/__tests__/ingest.test.ts | 262 +- .../booking-duplicate-detection.ts | 134 ++ lib/transactions/ingest.ts | 292 ++- messages/en.json | 32 +- messages/sv.json | 32 +- ...624130000_invoices_ore_rounding_toggle.sql | 29 + ...ssing_history_book_duplicate_dismissed.sql | 19 + tests/helpers.ts | 2 + tests/pg/assets.pg.test.ts | 14 +- types/index.ts | 17 + 55 files changed, 6049 insertions(+), 2376 deletions(-) create mode 100644 app/(dashboard)/invoices/[id]/edit/page.tsx create mode 100644 app/api/bookkeeping/fiscal-periods/[id]/lock/__tests__/route.test.ts create mode 100644 app/api/invoices/[id]/__tests__/patch.test.ts create mode 100644 app/api/user/profile/route.ts create mode 100644 components/bookkeeping/assets/EditAssetDialog.tsx create mode 100644 components/invoices/InvoiceEditor.tsx create mode 100644 components/settings/FiscalYearsManager.tsx create mode 100644 lib/invoices/__tests__/build-invoice-write.test.ts create mode 100644 lib/invoices/__tests__/is-editable-draft.test.ts create mode 100644 lib/invoices/build-invoice-write.ts create mode 100644 lib/invoices/is-editable-draft.ts create mode 100644 lib/transactions/__tests__/booking-duplicate-detection.test.ts create mode 100644 lib/transactions/booking-duplicate-detection.ts create mode 100644 supabase/migrations/20260624130000_invoices_ore_rounding_toggle.sql create mode 100644 supabase/migrations/20260626120000_processing_history_book_duplicate_dismissed.sql diff --git a/.gitignore b/.gitignore index b6e739ad..7a285ea9 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,11 @@ supabase/.branches/ # Local-only SIE test fixtures — may contain real/scrubbed company data, never commit tests/fixtures/sie/ +# Local-only DESTRUCTIVE duplicate-cleanup tooling — one-off, run by hand against +# real räkenskapsinformation. Deliberately NOT committed so it can never run in +# CI/cron and so its logic isn't mistaken for a supported product feature. +scripts/delete-duplicate-transactions.ts + # Diagnostic/cleanup tooling under /scripts is tracked, but the DATA those # scripts read or emit (ledger dumps, reconciliation exports) is real customer # räkenskapsinformation — never commit it. Keep the .ts/.sql tooling, ignore the data. diff --git a/app/(dashboard)/assets/page.tsx b/app/(dashboard)/assets/page.tsx index e204c223..9c2ae7de 100644 --- a/app/(dashboard)/assets/page.tsx +++ b/app/(dashboard)/assets/page.tsx @@ -10,7 +10,7 @@ import { Badge } from '@/components/ui/badge' import { PageHeader } from '@/components/ui/page-header' import { EmptyState } from '@/components/ui/empty-state' import { Skeleton } from '@/components/ui/skeleton' -import { Package, Plus } from 'lucide-react' +import { Package, Pencil, Plus } from 'lucide-react' import { Table, TableBody, @@ -22,6 +22,10 @@ import { import { formatCurrency, formatDate } from '@/lib/utils' import type { Asset, AssetCategory } from '@/types' import { CreateAssetDialog } from '@/components/bookkeeping/assets/CreateAssetDialog' +import { EditAssetDialog } from '@/components/bookkeeping/assets/EditAssetDialog' + +/** GET /api/assets annotates each row with whether depreciation has posted. */ +type AssetRow = Asset & { has_posted_depreciation?: boolean } const CATEGORY_LABEL_KEYS: Record = { immaterial: 'category_immaterial', @@ -36,9 +40,10 @@ const CATEGORY_LABEL_KEYS: Record = { export default function AssetsPage() { const t = useTranslations('assets') - const [assets, setAssets] = useState(null) + const [assets, setAssets] = useState(null) const [error, setError] = useState(null) const [dialogOpen, setDialogOpen] = useState(false) + const [editing, setEditing] = useState(null) const [reloadKey, setReloadKey] = useState(0) @@ -51,7 +56,7 @@ export default function AssetsPage() { setError(t('load_failed')) return } - const { data } = (await res.json()) as { data: Asset[] } + const { data } = (await res.json()) as { data: AssetRow[] } if (cancelled) return setError(null) setAssets(data) @@ -69,6 +74,11 @@ export default function AssetsPage() { setReloadKey((k) => k + 1) }, []) + const handleSaved = useCallback(() => { + setEditing(null) + setReloadKey((k) => k + 1) + }, []) + return (
{!asset.disposed_at && ( - - - + + + +
)} @@ -167,6 +187,18 @@ export default function AssetsPage() { )} + + {editing && ( + { + if (!open) setEditing(null) + }} + onSaved={handleSaved} + /> + )} ) } diff --git a/app/(dashboard)/invoices/[id]/edit/page.tsx b/app/(dashboard)/invoices/[id]/edit/page.tsx new file mode 100644 index 00000000..00cc5e2e --- /dev/null +++ b/app/(dashboard)/invoices/[id]/edit/page.tsx @@ -0,0 +1,87 @@ +'use client' + +import { useEffect, useState, use } from 'react' +import { useRouter } from 'next/navigation' +import { useTranslations } from 'next-intl' +import { createClient } from '@/lib/supabase/client' +import { useToast } from '@/components/ui/use-toast' +import { Loader2 } from 'lucide-react' +import InvoiceEditor, { type InvoiceForEdit } from '@/components/invoices/InvoiceEditor' +import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft' +import type { InvoiceItem } from '@/types' + +/** + * Edit an existing DRAFT invoice. Loads the invoice + items, guards that it is + * still an editable draft (no committed verifikat, not sent, not self-billed), + * then hands it to the shared in edit mode. The PATCH route + * enforces the same guard server-side; this just avoids opening a dead form. + */ +export default function EditInvoicePage({ params }: { params: Promise<{ id: string }> }) { + const { id } = use(params) + const router = useRouter() + const { toast } = useToast() + const supabase = createClient() + const t = useTranslations('invoice_detail') + + const [invoice, setInvoice] = useState(null) + const [isLoading, setIsLoading] = useState(true) + + useEffect(() => { + let cancelled = false + ;(async () => { + const { data, error } = await supabase + .from('invoices') + .select('*, customer:customers(*), items:invoice_items(*)') + .eq('id', id) + .single() + + if (cancelled) return + + if (error || !data) { + toast({ + title: t('load_failed_title'), + description: t('load_failed_description'), + variant: 'destructive', + }) + router.replace('/invoices') + return + } + + // Only drafts (no committed verifikat, not sent, not a received + // self-billing document) may be edited — shared predicate, the same one + // the PATCH route enforces server-side. + const editable = isEditableInvoiceDraft(data) + if (!editable) { + toast({ + title: t('edit_not_allowed_title'), + description: t('edit_not_allowed_description'), + variant: 'destructive', + }) + router.replace(`/invoices/${id}`) + return + } + + // The editor's field array expects items in display order. + if (Array.isArray(data.items)) { + data.items.sort((a: InvoiceItem, b: InvoiceItem) => a.sort_order - b.sort_order) + } + + setInvoice(data as InvoiceForEdit) + setIsLoading(false) + })() + return () => { + cancelled = true + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [id]) + + if (isLoading || !invoice) { + return ( +
+ +
+ ) + } + + return +} diff --git a/app/(dashboard)/invoices/[id]/page.tsx b/app/(dashboard)/invoices/[id]/page.tsx index bb246a67..a66cd1b2 100644 --- a/app/(dashboard)/invoices/[id]/page.tsx +++ b/app/(dashboard)/invoices/[id]/page.tsx @@ -14,6 +14,7 @@ import { formatCurrency, formatDate, cn } from '@/lib/utils' import { getVatTreatmentLabel } from '@/lib/invoices/vat-rules' import { invoiceDisplayNumber } from '@/lib/invoices/display' import { getDisplayTotal } from '@/lib/invoices/rounding' +import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft' import { Loader2, ArrowLeft, @@ -31,6 +32,7 @@ import { Trash2, Lock, CalendarClock, + Pencil, } from 'lucide-react' import { useCanWrite } from '@/lib/hooks/use-can-write' import PaymentBookingDialog from '@/components/invoices/PaymentBookingDialog' @@ -519,6 +521,10 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st // Self-billing invoices we received: the document is the counterparty's, so // there is no own PDF to render and no send step — it arrives already booked. const isSelfBilled = !!invoice.is_self_billed + // A draft (no committed verifikat, not sent, not self-billed) can be edited + // in place — header + lines — via /invoices/{id}/edit. Sent/paid invoices are + // immutable (BFL); they are corrected with a credit note instead. + const isEditableDraft = isEditableInvoiceDraft(invoice) const hasAccruedItems = invoice.items.some(itemHasAccrual) return (
@@ -559,6 +565,14 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st {/* Actions */}
+ {isEditableDraft && canWrite && ( + + + + )} {isProforma && invoice.status !== 'cancelled' && ( -
-

- {titleText} - {numberPreview && !isSelfBilled && ( - - ({numberPreview}) - - )} -

-

{subtitleText}

-
- -
- - setMode(v as 'invoice' | 'self_billed')}> - - {t('mode_invoice')} - {t('mode_self_billed')} - - - - {hasBankDetails === false && !isSelfBilled && ( -
- -

{t('bank_missing_warning')}

- -
- )} - -
-
- {/* Main content */} -
- {/* Customer selection */} - - - {isSelfBilled ? <>{ts('customer_label')} : <>{t('customer_card_title')}} - {isSelfBilled ? ts('issuer_card_description') : t('customer_card_description')} - - - ( - - )} - /> - - {errors.customer_id && ( -

{errors.customer_id.message}

- )} - - {isSelfBilled && ( -
-
- - - {errors.external_invoice_number && ( -

{errors.external_invoice_number.message}

- )} -
-
- - -
-
- )} - -
-
- - {/* Invoice items */} - - - {t('items_card_title')} - {t('items_card_description')} - - -
- - {fields.map((field, index) => { - const isTextRow = watchItems[index]?.line_type === 'text' - const lineTotal = (watchItems[index]?.quantity || 0) * (watchItems[index]?.unit_price || 0) - const lineVat = vatRegistered && !isTextRow - ? Math.round(lineTotal * (watchItems[index]?.vat_rate ?? 25) / 100 * 100) / 100 - : 0 - // Free-text / blank row: just a description field (may be left - // empty for a spacer) and a delete button. - if (isTextRow) { - return ( - -
-
-
- - -
- -
-
-
- ) - } - // Per-row action button. On real invoices it's a ⋮ menu that - // holds both the ROT/RUT skattereduktion choice and delete; - // proformas/delivery notes have no deduction model, so they - // keep a plain trash button (a one-item menu would be noise). - const renderRowActions = (triggerClassName: string) => - isInvoiceDoc ? ( - - - - - - {t('deduction_menu_label')} - { - const next = v === 'none' ? null : (v as 'rot' | 'rut') - setValue(`items.${index}.deduction_type`, next, { shouldDirty: true }) - if (next === null) { - setValue(`items.${index}.work_type`, null) - setValue(`items.${index}.labor_hours`, null) - setValue(`items.${index}.housing_designation`, null) - setValue(`items.${index}.apartment_number`, null) - } else if (watchItems[index]?.accrual_balance_account != null) { - // ROT/RUT och periodisering kombineras aldrig - // på samma rad — avdraget vinner. - setValue(`items.${index}.accrual_period_start`, null) - setValue(`items.${index}.accrual_period_end`, null) - setValue(`items.${index}.accrual_balance_account`, null) - } - }} - > - {t('deduction_none')} - {t('deduction_rot')} - {t('deduction_rut')} - - {canUseAccrual && !watchItems[index]?.deduction_type && ( - <> - - toggleAccrual(index)} className="py-2"> - - {watchItems[index]?.accrual_balance_account != null - ? ta('row_menu_remove') - : ta('row_menu_add')} - - - )} - - remove(index)} - > - - {t('remove_row')} - - - - ) : ( - - ) - return ( - -
- {/* Article picker (artikelregister). Optional — leave on - "Egen rad" to type a free-text line. Selecting an - article pre-fills description, unit, price, VAT and any - revenue-account override. */} -
-
- - ( - - )} - /> -
- {canWrite && ( - - )} -
- - {/* Description + mobile delete button */} -
-
- - - {errors.items?.[index]?.description && ( -

- {errors.items[index].description?.message} -

- )} -
- {renderRowActions('shrink-0 min-h-[44px] min-w-[44px] -mr-2 -mt-1 md:hidden')} -
- - {/* Antal, Enhet, à-pris */} -
-
- - -
-
- - ( - - )} - /> -
-
- - -
-
- - {/* Moms — hidden entirely when the company is not - momsregistrerad (no VAT may be charged). */} - {vatRegistered && ( -
- - ( - - )} - /> -
- )} - - {/* Desktop row actions (⋮ menu or trash). An invisible - label spacer mirrors the field columns (same Label + - space-y-2), so the button sits on the input row — not - high against the labels, nor low at the row bottom. */} -
- -
- {renderRowActions('')} -
-
- - {/* ROT/RUT-avdrag strip — only when a deduction is active - on this row (chosen via the ⋮ menu). A leading tag shows - which reduction applies; the work-type + hours are - required for the Skatteverket claim. Rows with no - deduction render nothing here and stay clean. */} - {isInvoiceDoc && watchItems[index]?.deduction_type && ( -
-
- - {watchItems[index]?.deduction_type === 'rot' ? 'ROT(30)' : 'RUT(50)'} - - { - 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. */} -
- -

{t('deduction_labor_only_warning')}

-
-
- )} - - {/* Periodisering (förutbetald intäkt) — activated via the - row's ⋮ menu. Intäkten krediteras 29xx vid bokning och - löses upp månadsvis över perioden; momsen påverkas inte. */} - {canUseAccrual && watchItems[index]?.accrual_balance_account != null && ( -
- { - setValue(`items.${index}.accrual_period_start`, next.start, { shouldDirty: true }) - setValue(`items.${index}.accrual_period_end`, next.end, { shouldDirty: true }) - setValue(`items.${index}.accrual_balance_account`, next.balanceAccount, { shouldDirty: true }) - }} - onRemove={() => toggleAccrual(index)} - /> - {errors.items?.[index]?.accrual_period_end && ( -

- {errors.items[index].accrual_period_end?.message} -

- )} -
- )} - - {/* Mobile summary row */} -
- {t('row_label', { index: index + 1 })} - {formatCurrency(lineTotal + lineVat, watchCurrency)} -
-
-
- ) - })} -
- -
- - {/* Free-text / blank row — explanatory text under an item, or - an empty spacer. Carries no amounts and never books. Not - offered for a received självfaktura: that is a faithful - revenue-only transcription, and the self-billed endpoint - (SelfBillingInvoiceItemSchema) has no line_type and rejects - zero-amount rows. */} - {!isSelfBilled && ( - - )} -
-
-
-
- - {/* 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 && ( - - - {t('deduction_card_title')} - {t('deduction_card_description')} - - -
- - -

- {t('deduction_personnummer_hint')} -

-
- {hasAnyRotLine && ( -
- - -

- {t('deduction_housing_hint')} -

-
- )} - {(deductionByKind.rot > ROT_MAX || deductionByKind.rut > RUT_MAX) && ( -
- {t('deduction_cap_over')} - {deductionByKind.rot > ROT_MAX && ` (ROT ${ROT_MAX.toLocaleString('sv-SE')} kr)`} - {deductionByKind.rut > RUT_MAX && ` (RUT ${RUT_MAX.toLocaleString('sv-SE')} kr)`} - {'. '} - {t('deduction_cap_check')} -
- )} -
-
- )} - - {/* Notes */} - - - {t('notes_card_title')} - {t('notes_card_description')} - - -