Files
accounted/components/common/FyPicker.tsx
T
Jakob Wennberg c0a106e591 feat(ux): Bucket A defaults pass: remove choices the system already knows the answer to (#1443)
* feat(booking): batch VAT seeds from category default, period derives from entry date

BatchCategorySelector and BulkBookInboxDialog hardcoded standard_25 as the
initial VAT treatment, overriding the server's per-category derivation and
claiming 25% moms on VAT-exempt bank fees. Both now default to an explicit
'Enligt kategori' option that omits vat_treatment so the server derives it
(exempt bank/card fees, 12% representation). Reverse charge is never derived.

The embedded JournalEntryForm period Select is replaced by the same derived
read-only text the standalone variant already uses: the period is a total
function of the entry date, and the Select allowed picking a period that
disagreed with it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(booking): prefill cost account from counterparty history; period text in Bokfor direkt

BookDirectlyDialog and the supplier-invoice form left the cost account
deliberately blank even when the company's own confirmed history for the
counterparty (categorization_templates) or supplier.default_expense_account
knew the answer. Both now prefill from a counterparty-template hit (new
?counterparty= single-match mode on the settings route, same tiered matcher
as the booking flows), only into still-empty fields, only from expense-shaped
templates, with a provenance line. No generic fallback: a miss leaves the
field blank exactly as before.

Bokfor direkt's period Select is replaced by text derived from the entry
date; the silent periods[0] fallback becomes a blocking explanation, since
borrowing an arbitrary period could book into the wrong one.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(ux): single-company login skips the picker; filing surfaces default to filable periods

/select-company auto-forwards when the user is a member of exactly one
company with nothing else to decide (no new TIC engagements, no pending
invite, enrichment fresh); the in-app 'Lagg till foretag' links pass
?choose=1 to keep the picker deliberately reachable. Byra/multi-company
users are untouched.

The VAT declaration now opens on the most recently ENDED month/quarter
(lib/vat/period-defaults, tested) instead of the current one, which can
never be filed and forced a step-back click on every filing visit; the
periodicity switch resets the same way. Helarsmoms FyPicker gains
preferLatestEnded and opens on the latest ended rakenskapsar instead of
the newest started one.

The 'momsperiod saknas' dead end now collects the answer inline through
the same PUT /api/settings validation instead of bouncing to settings:
until the period exists the deadline engine generates zero VAT deadlines,
silently, so every extra hop kept a compliance hole open.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(granskning): approve pill commits directly for low and medium risk

The Godkann pill on /pending only opened a ConfirmationDialog demanding a
second Godkann, regardless of tier. The review row already states source,
title and risk and offers Detaljer, so for low/medium the pill now commits
directly; high risk keeps the dialog, whose warning sentence carries
information the row does not. Chat-side bulk approve is deferred: it needs
ApprovalCard's state lifted (assistant-redesign seam 8.8), see DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reports): map inline momsperiod save errors through getErrorMessage

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): repair the dead login auto-forward and nine review findings

The big one: setActiveCompany ends with a cookie write that throws during
Server Component render (sealed cookie store), so the /select-company
auto-forward silently never fired; the write is now best-effort since the
cookie is write-only compat and the DB write is already verified.

Also: supplier-switch un-plants history-prefilled accounts so the new
supplier's own default applies; prefill routes through handleAccountChange
so konto default moms rides along; batch 'Ingen moms' books exempt instead
of the derived 25%; monthly VAT default tracks the actual 12th/17th filing
deadline (over-40M stays M-1); inline momsperiod setup uses EmptyState,
gates on vat_number (the PUT would 400 without it), keeps keyboard focus
and announces errors; cost-account shape guard tightened to P&L accounts;
attn tone on the new warning lines.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger workflows; the Actions outage swallowed the rebase push event

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger after outage (events dropped, not delayed)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger after GitHub Actions recovery

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): address CodeRabbit and compliance-bot findings

Direct commit now prunes the op from the bulk selection (a stale id kept
inflating the bulk bar and rode into bulk-commit) and the detail-panel
Godkann gets the same risk gate as the row pill. The automatic account
fill in the supplier-invoice form is requested, not applied inline: the
applying effect waits for both the BAS chart and the request with fresh
closures, so a fill can no longer land before the chart and leave a
VAT-free konto on the 25% row default. Test dates use local-time
constructors (ISO strings parse as UTC midnight and shift a day in
negative-offset timezones). Stale ML 11 kap citation dropped from a
comment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger; push event dropped again

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 10:16:23 +02:00

180 lines
6.4 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { useCompany } from '@/contexts/CompanyContext'
import { ContextPicker } from '@/components/common/ContextPicker'
import {
STORAGE_KEY_PREFIX,
ALL_YEARS_VALUE,
} from '@/components/common/FiscalYearSelector'
import type { FiscalPeriod } from '@/types'
interface FyPickerProps {
/** Current selection. `null` means "all years": no filter applied. */
value: string | null
/**
* Called with the selected period id (or null for "all years") and the
* matching FiscalPeriod so callers avoid an extra fetch.
*/
onChange: (periodId: string | null, period?: FiscalPeriod | null) => void
/** Include an "Alla räkenskapsår" option that clears the filter. */
includeAllOption?: boolean
/** Only show periods that have started (Reports-style filter). */
hideFuturePeriods?: boolean
/**
* Auto-select the most recently ENDED period on load instead of restoring
* the shared per-company scope or falling back to the newest started one.
* For filing surfaces (helårsmoms): only an ended räkenskapsår can be
* declared, so the newest started period is the one default that is always
* wrong there. Manual picks still work and are still persisted.
*/
preferLatestEnded?: boolean
/** Fires once after the initial period load completes. */
onReady?: () => void
/** Server-loaded periods for the first render, scoped to initialCompanyId. */
initialPeriods?: FiscalPeriod[]
initialCompanyId?: string | null
className?: string
}
function preparePeriods(periods: FiscalPeriod[], hideFuturePeriods: boolean): FiscalPeriod[] {
const today = new Date().toISOString().split('T')[0]
return periods
.filter((p) => !hideFuturePeriods || p.period_start <= today)
.sort((a, b) => b.period_start.localeCompare(a.period_start))
}
/**
* Fiscal-year context picker (UI-migration plan PR 3): the chip-dropdown
* "Räkenskapsår 2026" with a check on the active choice and closed/locked
* years annotated. Same controlled API and per-company localStorage
* persistence as FiscalYearSelector, which it replaces page by page from
* PR 4 on.
*/
export function FyPicker({
value,
onChange,
includeAllOption = true,
hideFuturePeriods = false,
preferLatestEnded = false,
onReady,
initialPeriods,
initialCompanyId,
className,
}: FyPickerProps) {
const { company } = useCompany()
const t = useTranslations('fiscal_year')
const canUseInitial = initialCompanyId === company?.id && initialPeriods !== undefined
const [periods, setPeriods] = useState<FiscalPeriod[]>(() =>
canUseInitial ? preparePeriods(initialPeriods, hideFuturePeriods) : [],
)
const [loaded, setLoaded] = useState(canUseInitial)
useEffect(() => {
if (!company?.id) {
onReady?.()
return
}
let cancelled = false
;(async () => {
let fetched: FiscalPeriod[]
if (initialCompanyId === company.id && initialPeriods !== undefined) {
fetched = preparePeriods(initialPeriods, hideFuturePeriods)
} else {
const res = await fetch('/api/bookkeeping/fiscal-periods')
if (!res.ok) {
if (!cancelled) {
setLoaded(true)
onReady?.()
}
return
}
const { data } = await res.json()
fetched = preparePeriods(data || [], hideFuturePeriods)
}
if (cancelled) return
setPeriods(fetched)
setLoaded(true)
// Restore last selection (same key as FiscalYearSelector so pages keep
// their scope when the picker swaps in).
if (value === null && typeof window !== 'undefined') {
if (preferLatestEnded) {
// Filing surfaces: ignore the shared scope memory and open on the
// most recently ended period (fetched is sorted newest-first).
const today = new Date().toISOString().split('T')[0]
const pick = fetched.find((p) => p.period_end < today) ?? fetched[0]
if (pick) onChange(pick.id, pick)
} else {
const stored = window.localStorage.getItem(STORAGE_KEY_PREFIX + company.id)
if (stored === ALL_YEARS_VALUE) {
if (includeAllOption) onChange(null, null)
else if (fetched.length > 0) onChange(fetched[0].id, fetched[0])
} else if (stored && fetched.some((p) => p.id === stored)) {
onChange(stored, fetched.find((p) => p.id === stored) ?? null)
} else if (!includeAllOption && fetched.length > 0) {
onChange(fetched[0].id, fetched[0])
}
}
}
onReady?.()
})()
return () => {
cancelled = true
}
// onReady is a lifecycle callback: fire once per load, not on parent
// re-renders that re-create it.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [company?.id, hideFuturePeriods, includeAllOption, preferLatestEnded, initialCompanyId, initialPeriods])
const handleChange = (id: string) => {
const nextId = id === ALL_YEARS_VALUE ? null : id
if (company?.id && typeof window !== 'undefined') {
window.localStorage.setItem(STORAGE_KEY_PREFIX + company.id, nextId ?? ALL_YEARS_VALUE)
}
onChange(nextId, nextId ? periods.find((p) => p.id === nextId) ?? null : null)
}
const annotationFor = (p: FiscalPeriod) =>
p.locked_at ? t('badge_locked').toLowerCase() : p.is_closed ? t('badge_closed').toLowerCase() : undefined
const selected = value ? periods.find((p) => p.id === value) : null
// Real period names often already read "Räkenskapsår 2026"; only prefix
// the label when the name is a bare year/name so the chip never doubles up.
const chipLabel = (p: FiscalPeriod) =>
p.name.toLowerCase().includes(t('label').toLowerCase())
? p.name
: `${t('label')} ${p.name}`
const triggerLabel = selected
? chipLabel(selected)
: includeAllOption
? t('all_years')
: loaded
? t('placeholder')
: t('loading')
const items = [
...(includeAllOption ? [{ id: ALL_YEARS_VALUE, label: t('all_years') }] : []),
...periods.map((p) => ({
id: p.id,
label: p.name,
annotation: annotationFor(p),
})),
]
return (
<ContextPicker
items={items}
value={value ?? (includeAllOption ? ALL_YEARS_VALUE : null)}
onChange={handleChange}
triggerLabel={triggerLabel}
disabled={!loaded || periods.length === 0}
ariaLabel={t('label')}
className={className}
/>
)
}