Add/issue in absurdum (#739)
* 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) <noreply@anthropic.com> * 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) <noreply@anthropic.com> * 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) <noreply@anthropic.com> * 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) <noreply@anthropic.com> * 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) <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
d95a0b6105
commit
8322830f46
@@ -0,0 +1,359 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { AlertTriangle, Loader2, Lock } from 'lucide-react'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { Asset, AssetCategory, DepreciationMethod } from '@/types'
|
||||
|
||||
/** The list route annotates each asset with whether any depreciation has been
|
||||
* posted against it. When true, the acquisition-basis fields are locked. */
|
||||
type EditableAsset = Asset & { has_posted_depreciation?: boolean }
|
||||
|
||||
interface EditAssetDialogProps {
|
||||
asset: EditableAsset
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
// Same category labels and depreciation hints as CreateAssetDialog (kept in
|
||||
// sync deliberately — this register surface is Swedish-only, like creation).
|
||||
const CATEGORY_OPTIONS: { value: AssetCategory; label: string }[] = [
|
||||
{ value: 'computer', label: 'Dator / IT-utrustning' },
|
||||
{ value: 'equipment', label: 'Inventarier' },
|
||||
{ value: 'machinery', label: 'Maskiner' },
|
||||
{ value: 'vehicle', label: 'Fordon' },
|
||||
{ value: 'building', label: 'Byggnad' },
|
||||
{ value: 'land_improvement', label: 'Markanläggning' },
|
||||
{ value: 'immaterial', label: 'Immateriell tillgång' },
|
||||
{ value: 'other_tangible', label: 'Övrig materiell tillgång' },
|
||||
]
|
||||
|
||||
const DEPRECIATION_METHOD_OPTIONS: { value: DepreciationMethod; label: string; hint: string }[] = [
|
||||
{
|
||||
value: 'linear',
|
||||
label: 'Linjär',
|
||||
hint: 'Planenlig raklinje över nyttjandeperioden (ÅRL 4 kap 4§).',
|
||||
},
|
||||
{
|
||||
value: 'declining_balance_30',
|
||||
label: 'Räkenskapsenlig 30 %',
|
||||
hint: 'Huvudregeln (IL 18 kap 13§) — 30 % degressivt på avskrivningsunderlaget.',
|
||||
},
|
||||
{
|
||||
value: 'declining_balance_20',
|
||||
label: 'Räkenskapsenlig 20 %',
|
||||
hint: 'Kompletteringsregeln (IL 18 kap 17§) — 20 % degressivt. Vanlig för byggnader.',
|
||||
},
|
||||
{
|
||||
value: 'restvardesavskrivning_25',
|
||||
label: 'Restvärdeavskrivning 25 %',
|
||||
hint: 'IL 18 kap 13§ st.3 — 25 % degressivt ner till angivet restvärde.',
|
||||
},
|
||||
]
|
||||
|
||||
export function EditAssetDialog({ asset, open, onOpenChange, onSaved }: EditAssetDialogProps) {
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
// Once depreciation has been booked, acquisition date/cost/category are
|
||||
// locked — a real change has to go through storno. The server enforces the
|
||||
// same rule (ASSET_CORRECTION_BLOCKED); this just makes it visible up front.
|
||||
const basisLocked = asset.has_posted_depreciation === true
|
||||
|
||||
const [name, setName] = useState(asset.name)
|
||||
const [category, setCategory] = useState<AssetCategory>(asset.category)
|
||||
const [acquisitionDate, setAcquisitionDate] = useState(asset.acquisition_date)
|
||||
const [acquisitionCost, setAcquisitionCost] = useState(String(asset.acquisition_cost))
|
||||
const [usefulLifeYears, setUsefulLifeYears] = useState(
|
||||
String(Math.round(asset.useful_life_months / 12)),
|
||||
)
|
||||
const [depreciationMethod, setDepreciationMethod] = useState<DepreciationMethod>(
|
||||
asset.depreciation_method,
|
||||
)
|
||||
const [restvardeTarget, setRestvardeTarget] = useState(
|
||||
asset.restvarde_target != null ? String(asset.restvarde_target) : '',
|
||||
)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const isRestvarde = depreciationMethod === 'restvardesavskrivning_25'
|
||||
const methodHint =
|
||||
DEPRECIATION_METHOD_OPTIONS.find((o) => o.value === depreciationMethod)?.hint ?? ''
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setError(null)
|
||||
const trimmedName = name.trim()
|
||||
if (!trimmedName) {
|
||||
setError('Namnet får inte vara tomt.')
|
||||
return
|
||||
}
|
||||
|
||||
// Send only what actually changed. This keeps a name-only edit on a
|
||||
// depreciated asset from tripping the acquisition-basis guard, and avoids
|
||||
// clobbering a useful_life_months value that isn't a clean multiple of 12.
|
||||
const patch: Record<string, unknown> = {}
|
||||
|
||||
if (trimmedName !== asset.name) patch.name = trimmedName
|
||||
|
||||
if (!basisLocked) {
|
||||
if (category !== asset.category) patch.category = category
|
||||
if (acquisitionDate !== asset.acquisition_date) patch.acquisition_date = acquisitionDate
|
||||
const cost = parseFloat(acquisitionCost)
|
||||
if (!Number.isFinite(cost) || cost <= 0) {
|
||||
setError('Anskaffningsvärdet måste vara större än 0.')
|
||||
return
|
||||
}
|
||||
if (cost !== Number(asset.acquisition_cost)) patch.acquisition_cost = cost
|
||||
}
|
||||
|
||||
const years = parseInt(usefulLifeYears, 10)
|
||||
if (!Number.isFinite(years) || years <= 0) {
|
||||
setError('Ange en avskrivningstid (minst 1 år).')
|
||||
return
|
||||
}
|
||||
const months = years * 12
|
||||
if (months !== asset.useful_life_months) patch.useful_life_months = months
|
||||
|
||||
if (depreciationMethod !== asset.depreciation_method) {
|
||||
patch.depreciation_method = depreciationMethod
|
||||
}
|
||||
|
||||
if (isRestvarde) {
|
||||
const target = parseFloat(restvardeTarget)
|
||||
const cost = !basisLocked ? parseFloat(acquisitionCost) : Number(asset.acquisition_cost)
|
||||
if (!Number.isFinite(target) || target < 0) {
|
||||
setError('Ange ett restvärde (0 kr eller högre).')
|
||||
return
|
||||
}
|
||||
if (Number.isFinite(cost) && target >= cost) {
|
||||
setError('Restvärdet måste vara lägre än anskaffningsvärdet.')
|
||||
return
|
||||
}
|
||||
// Send the target when switching into restvärde or when it changed, so
|
||||
// the method/target biconditional always holds.
|
||||
if (
|
||||
depreciationMethod !== asset.depreciation_method ||
|
||||
target !== Number(asset.restvarde_target)
|
||||
) {
|
||||
patch.restvarde_target = target
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(patch).length === 0) {
|
||||
toast({ title: 'Inga ändringar', description: 'Inget att spara.' })
|
||||
onOpenChange(false)
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const res = await fetch(`/api/assets/${asset.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok) {
|
||||
setError(getErrorMessage(body?.error ?? body) || 'Kunde inte spara ändringen.')
|
||||
return
|
||||
}
|
||||
toast({ title: 'Tillgång uppdaterad', description: trimmedName })
|
||||
onSaved()
|
||||
} catch (err) {
|
||||
setError(getErrorMessage(err))
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Ändra anläggningstillgång</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-name">Namn</Label>
|
||||
<Input
|
||||
id="edit-asset-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-category">Kategori</Label>
|
||||
<Select
|
||||
value={category}
|
||||
onValueChange={(v) => setCategory(v as AssetCategory)}
|
||||
disabled={basisLocked}
|
||||
>
|
||||
<SelectTrigger id="edit-asset-category">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{CATEGORY_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-date">Anskaffat</Label>
|
||||
<Input
|
||||
id="edit-asset-date"
|
||||
type="date"
|
||||
value={acquisitionDate}
|
||||
onChange={(e) => setAcquisitionDate(e.target.value)}
|
||||
disabled={basisLocked}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-cost">Anskaffningsvärde (kr)</Label>
|
||||
<Input
|
||||
id="edit-asset-cost"
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
value={acquisitionCost}
|
||||
onChange={(e) => setAcquisitionCost(e.target.value)}
|
||||
disabled={basisLocked}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{basisLocked && (
|
||||
<div className="flex items-start gap-2 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
|
||||
<Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span>
|
||||
Anskaffningsdatum, anskaffningsvärde och kategori är låsta eftersom avskrivningar
|
||||
redan har bokförts. Återför avskrivningen (storno) eller använd avyttring för att
|
||||
ändra grunduppgifterna. Namn, avskrivningstid och metod kan fortfarande justeras.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-life">Avskrivningstid (år)</Label>
|
||||
<Input
|
||||
id="edit-asset-life"
|
||||
type="number"
|
||||
min="1"
|
||||
max="50"
|
||||
step="1"
|
||||
value={usefulLifeYears}
|
||||
onChange={(e) => setUsefulLifeYears(e.target.value)}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-method">Avskrivningsmetod</Label>
|
||||
<Select
|
||||
value={depreciationMethod}
|
||||
onValueChange={(v) => setDepreciationMethod(v as DepreciationMethod)}
|
||||
>
|
||||
<SelectTrigger id="edit-asset-method">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DEPRECIATION_METHOD_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">{methodHint}</p>
|
||||
</div>
|
||||
|
||||
{basisLocked && depreciationMethod !== asset.depreciation_method && (
|
||||
<div className="flex items-start gap-2 rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
|
||||
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span>
|
||||
Byte av avskrivningsmetod efter att avskrivning påbörjats. Enligt K2
|
||||
(BFNAR 2016:10 p. 10.26) ska vald metod tillämpas konsekvent — ändra
|
||||
bara vid särskilda skäl och lämna i så fall upplysning i bokslutet.
|
||||
Ändringen gäller framåt; redan bokförda avskrivningar påverkas inte.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isRestvarde && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-asset-restvarde">Restvärde (kr)</Label>
|
||||
<Input
|
||||
id="edit-asset-restvarde"
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={restvardeTarget}
|
||||
onChange={(e) => setRestvardeTarget(e.target.value)}
|
||||
placeholder="t.ex. 5000"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Avskrivningen stannar när bokfört värde når restvärdet. Restvärdet måste vara lägre
|
||||
än anskaffningsvärdet.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!canWrite || submitting}
|
||||
title={
|
||||
!canWrite ? 'Endast användare med skrivrättigheter kan ändra tillgångar.' : undefined
|
||||
}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-1 h-4 w-4" />}
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
|
||||
</>
|
||||
) : (
|
||||
'Spara'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -50,10 +50,10 @@ const PAGE_ENTRIES: Entry[] = [
|
||||
{ id: 'anläggningstillgångar', label: 'Anläggningstillgångar', icon: Package, href: '/assets', keywords: 'tillgångar assets' },
|
||||
{ id: 'rapporter', label: 'Rapporter', icon: BarChart3, href: '/reports' },
|
||||
{ id: 'rapport-resultatrapport', label: 'Visa rapport: Resultatrapport', icon: BarChart3, href: '/reports/resultatrapport', keywords: 'rapport resultat intäkter kostnader' },
|
||||
{ id: 'rapport-balansrapport', label: 'Visa rapport: Balansrapport', icon: BarChart3, href: '/reports/balansrapport', keywords: 'rapport balans tillgångar skulder' },
|
||||
{ id: 'rapport-saldobalans', label: 'Visa rapport: Saldobalans', icon: BarChart3, href: '/reports/trial-balance', keywords: 'rapport saldobalans trial balance' },
|
||||
{ id: 'rapport-balansrapport', label: 'Visa rapport: Balansrapport', icon: BarChart3, href: '/reports/balansrapport', keywords: 'rapport balans tillgångar skulder saldo per konto' },
|
||||
{ id: 'rapport-saldobalans', label: 'Visa rapport: Saldobalans', icon: BarChart3, href: '/reports/trial-balance', keywords: 'rapport saldobalans trial balance saldo per konto' },
|
||||
{ id: 'rapport-moms', label: 'Visa rapport: Momsdeklaration', icon: BarChart3, href: '/reports/vat-declaration', keywords: 'rapport moms vat deklaration' },
|
||||
{ id: 'rapport-huvudbok', label: 'Visa rapport: Huvudbok', icon: BookOpen, href: '/reports/huvudbok', keywords: 'rapport huvudbok ledger konto' },
|
||||
{ id: 'rapport-huvudbok', label: 'Visa rapport: Huvudbok', icon: BookOpen, href: '/reports/huvudbok', keywords: 'rapport huvudbok ledger general konto saldo transaktioner per konto kontoutdrag kontoanalys kontokort kontohistorik balance account statement transactions' },
|
||||
{ id: 'rapport-kundreskontra', label: 'Visa rapport: Kundreskontra', icon: Users, href: '/reports/kundreskontra', keywords: 'rapport kundreskontra ar kundfordringar' },
|
||||
{ id: 'importera', label: 'Importera', icon: Upload, href: '/import' },
|
||||
{ id: 'granskning', label: 'Granskning', icon: ClipboardCheck, href: '/pending', keywords: 'pending review' },
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,124 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Plus } from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
|
||||
|
||||
/** Status of a fiscal period, in legal precedence: closed > locked > open. */
|
||||
function periodStatus(p: FiscalPeriod): 'closed' | 'locked' | 'open' {
|
||||
if (p.is_closed) return 'closed'
|
||||
if (p.locked_at) return 'locked'
|
||||
return 'open'
|
||||
}
|
||||
|
||||
const STATUS_VARIANT: Record<'closed' | 'locked' | 'open', 'secondary' | 'warning' | 'success'> = {
|
||||
closed: 'secondary',
|
||||
locked: 'warning',
|
||||
open: 'success',
|
||||
}
|
||||
|
||||
/** ISO date one day after the latest period ends — seeds the create dialog so
|
||||
* its suggestion chains forward onto the most recent year. UTC throughout to
|
||||
* avoid timezone-offset date drift. */
|
||||
function nextEntryDate(periods: FiscalPeriod[]): string {
|
||||
if (periods.length === 0) {
|
||||
return new Date().toISOString().split('T')[0]
|
||||
}
|
||||
const latestEnd = periods
|
||||
.map((p) => p.period_end)
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.at(-1)!
|
||||
const d = new Date(latestEnd + 'T00:00:00Z')
|
||||
d.setUTCDate(d.getUTCDate() + 1)
|
||||
return d.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
export function FiscalYearsManager() {
|
||||
const t = useTranslations('settings_bookkeeping')
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [hasError, setHasError] = useState(false)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
|
||||
const fetchPeriods = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
if (!res.ok) throw new Error('fetch failed')
|
||||
const { data } = await res.json()
|
||||
setPeriods((data as FiscalPeriod[]) || [])
|
||||
setHasError(false)
|
||||
} catch {
|
||||
setHasError(true)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { fetchPeriods() }, [fetchPeriods])
|
||||
|
||||
// Newest first — matches the API's ordering and reads most-recent-at-top.
|
||||
const sorted = [...periods].sort((a, b) => b.period_start.localeCompare(a.period_start))
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('fy_heading')}
|
||||
</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setDialogOpen(true)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_create')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">{t('fy_help')}</p>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
</div>
|
||||
) : hasError ? (
|
||||
<p className="text-sm text-muted-foreground">{t('fy_load_error')}</p>
|
||||
) : sorted.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">{t('fy_empty')}</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{sorted.map((p) => {
|
||||
const status = periodStatus(p)
|
||||
return (
|
||||
<div key={p.id} className="flex items-center justify-between gap-4 py-2">
|
||||
<div className="min-w-0">
|
||||
<span className="text-sm font-medium">{p.name}</span>
|
||||
<span className="ml-2 text-sm text-muted-foreground tabular-nums">
|
||||
{formatDate(p.period_start)} – {formatDate(p.period_end)}
|
||||
</span>
|
||||
</div>
|
||||
<Badge variant={STATUS_VARIANT[status]}>{t(`fy_status_${status}`)}</Badge>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CreatePeriodDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
entryDate={nextEntryDate(periods)}
|
||||
periods={periods}
|
||||
onCreated={fetchPeriods}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import Link from 'next/link'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Sun, Moon, Monitor, LogOut, Languages, ExternalLink } from 'lucide-react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
@@ -30,9 +32,56 @@ export function AccountSettingsContent() {
|
||||
const tCommon = useTranslations('common')
|
||||
const tSettings = useTranslations('settings')
|
||||
const [savingLocale, setSavingLocale] = useState(false)
|
||||
const [fullName, setFullName] = useState('')
|
||||
const [initialName, setInitialName] = useState('')
|
||||
const [nameLoading, setNameLoading] = useState(true)
|
||||
const [savingName, setSavingName] = useState(false)
|
||||
|
||||
useEffect(() => { setMounted(true) }, [])
|
||||
|
||||
// Pre-fill the name field from profiles.full_name. Self-contained client
|
||||
// fetch — mirrors BankIdSettings.
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
;(async () => {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) { if (active) setNameLoading(false); return }
|
||||
const { data } = await supabase
|
||||
.from('profiles')
|
||||
.select('full_name')
|
||||
.eq('id', user.id)
|
||||
.maybeSingle()
|
||||
if (!active) return
|
||||
setFullName(data?.full_name ?? '')
|
||||
setInitialName(data?.full_name ?? '')
|
||||
setNameLoading(false)
|
||||
})()
|
||||
return () => { active = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
async function handleSaveName() {
|
||||
const trimmed = fullName.trim()
|
||||
if (!trimmed || trimmed === initialName || savingName) return
|
||||
setSavingName(true)
|
||||
try {
|
||||
const res = await fetch('/api/user/profile', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ full_name: trimmed }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Could not save')
|
||||
setFullName(trimmed)
|
||||
setInitialName(trimmed)
|
||||
toast({ title: tSettings('name_saved') })
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({ title: tSettings('name_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSavingName(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
clearRecaptIdentity()
|
||||
await supabase.auth.signOut()
|
||||
@@ -68,8 +117,39 @@ export function AccountSettingsContent() {
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Appearance */}
|
||||
{/* Name */}
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{tSettings('section_name')}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground max-w-md">
|
||||
{tSettings('name_description')}
|
||||
</p>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="flex-1 space-y-2 sm:max-w-sm">
|
||||
<Label htmlFor="full_name">{tSettings('name_label')}</Label>
|
||||
<Input
|
||||
id="full_name"
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
placeholder={tSettings('name_placeholder')}
|
||||
disabled={nameLoading || savingName}
|
||||
maxLength={100}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleSaveName}
|
||||
disabled={
|
||||
nameLoading || savingName || !fullName.trim() || fullName.trim() === initialName
|
||||
}
|
||||
>
|
||||
{savingName ? tCommon('saving') : tCommon('save')}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Appearance */}
|
||||
<section className="space-y-4 border-t border-border pt-8">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{tSettings('section_appearance')}
|
||||
</h2>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { PeriodLockingSettings } from '@/components/settings/PeriodLockingSettings'
|
||||
import { FiscalYearsManager } from '@/components/settings/FiscalYearsManager'
|
||||
import { VoucherSeriesManager } from '@/components/settings/VoucherSeriesManager'
|
||||
import { VoucherSeriesPerSourceTypeForm } from '@/components/settings/VoucherSeriesPerSourceTypeForm'
|
||||
import { applyDefaultSeriesToMap } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
@@ -141,6 +142,11 @@ export function BookkeepingSettingsContent() {
|
||||
</div>
|
||||
</SettingsFormWrapper>
|
||||
|
||||
{/* Fiscal years */}
|
||||
<div className="border-t border-border pt-8">
|
||||
<FiscalYearsManager />
|
||||
</div>
|
||||
|
||||
{/* Voucher series — per-source-type mapping */}
|
||||
<div className="border-t border-border pt-8">
|
||||
<VoucherSeriesPerSourceTypeForm
|
||||
|
||||
Reference in New Issue
Block a user