fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
isEditableTarget,
|
||||
isOverlayBlocking,
|
||||
resolveArrowKeyAction,
|
||||
type ArrowKeyEventLike,
|
||||
type OverlayProbeDocument,
|
||||
} from '@/lib/hooks/detail-pager-guards'
|
||||
|
||||
/**
|
||||
* Minimal fake DOM for the node test environment: elements are attribute
|
||||
* bags with an optional parent, and the matcher supports exactly the two
|
||||
* selector shapes the guard uses: compound attribute selectors
|
||||
* ([role="dialog"][data-state="open"]) and one-level descendant chains
|
||||
* ([data-radix-popper-content-wrapper] [data-state="open"]), comma-separated.
|
||||
*/
|
||||
interface FakeEl {
|
||||
attrs: Record<string, string>
|
||||
parent?: FakeEl
|
||||
}
|
||||
|
||||
function matchesCompound(el: FakeEl, compound: string): boolean {
|
||||
const attrRe = /\[([a-zA-Z-]+)(?:="([^"]*)")?\]/g
|
||||
let m: RegExpExecArray | null
|
||||
let sawAny = false
|
||||
while ((m = attrRe.exec(compound))) {
|
||||
sawAny = true
|
||||
const [, name, value] = m
|
||||
if (!(name in el.attrs)) return false
|
||||
if (value !== undefined && el.attrs[name] !== value) return false
|
||||
}
|
||||
return sawAny
|
||||
}
|
||||
|
||||
function matchesSelector(el: FakeEl, selector: string): boolean {
|
||||
const parts = selector.trim().split(/\s+/)
|
||||
if (!matchesCompound(el, parts[parts.length - 1])) return false
|
||||
let ancestor = el.parent
|
||||
for (let i = parts.length - 2; i >= 0; i--) {
|
||||
let match: FakeEl | undefined
|
||||
while (ancestor) {
|
||||
if (matchesCompound(ancestor, parts[i])) {
|
||||
match = ancestor
|
||||
break
|
||||
}
|
||||
ancestor = ancestor.parent
|
||||
}
|
||||
if (!match) return false
|
||||
ancestor = match.parent
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function matchesAny(el: FakeEl, selectors: string): boolean {
|
||||
return selectors.split(',').some((s) => matchesSelector(el, s))
|
||||
}
|
||||
|
||||
function makeDoc(elements: FakeEl[], activeElement: FakeEl | null = null): OverlayProbeDocument {
|
||||
return {
|
||||
querySelector: (selectors: string) =>
|
||||
elements.find((el) => matchesAny(el, selectors)) ?? null,
|
||||
activeElement: activeElement
|
||||
? {
|
||||
closest: (selectors: string) => {
|
||||
let node: FakeEl | undefined = activeElement
|
||||
while (node) {
|
||||
if (matchesAny(node, selectors)) return node
|
||||
node = node.parent
|
||||
}
|
||||
return null
|
||||
},
|
||||
}
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
function arrowEvent(overrides: Partial<ArrowKeyEventLike> = {}): ArrowKeyEventLike {
|
||||
return {
|
||||
key: 'ArrowRight',
|
||||
defaultPrevented: false,
|
||||
isComposing: false,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target: { tagName: 'BODY' },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const emptyDoc = () => makeDoc([])
|
||||
|
||||
describe('isOverlayBlocking', () => {
|
||||
it('does not block on an empty page', () => {
|
||||
expect(isOverlayBlocking(emptyDoc())).toBe(false)
|
||||
})
|
||||
|
||||
it('does NOT block on a mounted-but-closed dialog (agent sheet hidden with display:none)', () => {
|
||||
// AgentSheet renders role="dialog" and stays in the DOM once opened; a
|
||||
// bare [role="dialog"] query would block paging forever.
|
||||
const hiddenSheet: FakeEl = { attrs: { role: 'dialog' } }
|
||||
expect(isOverlayBlocking(makeDoc([hiddenSheet]))).toBe(false)
|
||||
})
|
||||
|
||||
it('blocks on an open dialog', () => {
|
||||
const openDialog: FakeEl = { attrs: { role: 'dialog', 'data-state': 'open' } }
|
||||
expect(isOverlayBlocking(makeDoc([openDialog]))).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks on an open alertdialog', () => {
|
||||
const el: FakeEl = { attrs: { role: 'alertdialog', 'data-state': 'open' } }
|
||||
expect(isOverlayBlocking(makeDoc([el]))).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks on an open radix dropdown menu (no dialog role)', () => {
|
||||
const menuContent: FakeEl = {
|
||||
attrs: { 'data-radix-menu-content': '', 'data-state': 'open' },
|
||||
}
|
||||
expect(isOverlayBlocking(makeDoc([menuContent]))).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks on open popper content (select/menu inside the popper wrapper)', () => {
|
||||
const wrapper: FakeEl = { attrs: { 'data-radix-popper-content-wrapper': '' } }
|
||||
const content: FakeEl = { attrs: { 'data-state': 'open' }, parent: wrapper }
|
||||
expect(isOverlayBlocking(makeDoc([content]))).toBe(true)
|
||||
})
|
||||
|
||||
it('does not block on a closed, force-mounted popper', () => {
|
||||
const wrapper: FakeEl = { attrs: { 'data-radix-popper-content-wrapper': '' } }
|
||||
const content: FakeEl = { attrs: { 'data-state': 'closed' }, parent: wrapper }
|
||||
expect(isOverlayBlocking(makeDoc([content]))).toBe(false)
|
||||
})
|
||||
|
||||
it('blocks while focus sits inside a dialog/menu/listbox container', () => {
|
||||
for (const role of ['dialog', 'menu', 'listbox']) {
|
||||
const container: FakeEl = { attrs: { role } }
|
||||
const focused: FakeEl = { attrs: { tabindex: '0' }, parent: container }
|
||||
expect(isOverlayBlocking(makeDoc([], focused))).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not block while focus sits in the plain page', () => {
|
||||
const focused: FakeEl = { attrs: { tabindex: '0' } }
|
||||
expect(isOverlayBlocking(makeDoc([], focused))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isEditableTarget', () => {
|
||||
it('claims text fields, selects and contentEditable', () => {
|
||||
expect(isEditableTarget({ tagName: 'INPUT' })).toBe(true)
|
||||
expect(isEditableTarget({ tagName: 'TEXTAREA' })).toBe(true)
|
||||
expect(isEditableTarget({ tagName: 'SELECT' })).toBe(true)
|
||||
expect(isEditableTarget({ tagName: 'DIV', isContentEditable: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('passes on everything else', () => {
|
||||
expect(isEditableTarget({ tagName: 'BODY' })).toBe(false)
|
||||
expect(isEditableTarget({ tagName: 'BUTTON' })).toBe(false)
|
||||
expect(isEditableTarget(null)).toBe(false)
|
||||
expect(isEditableTarget(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveArrowKeyAction', () => {
|
||||
it('maps plain arrows to paging actions', () => {
|
||||
expect(resolveArrowKeyAction(arrowEvent({ key: 'ArrowLeft' }), emptyDoc())).toBe('prev')
|
||||
expect(resolveArrowKeyAction(arrowEvent({ key: 'ArrowRight' }), emptyDoc())).toBe('next')
|
||||
})
|
||||
|
||||
it('ignores other keys', () => {
|
||||
expect(resolveArrowKeyAction(arrowEvent({ key: 'ArrowUp' }), emptyDoc())).toBeNull()
|
||||
expect(resolveArrowKeyAction(arrowEvent({ key: 'a' }), emptyDoc())).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores handled or composing events', () => {
|
||||
expect(resolveArrowKeyAction(arrowEvent({ defaultPrevented: true }), emptyDoc())).toBeNull()
|
||||
expect(resolveArrowKeyAction(arrowEvent({ isComposing: true }), emptyDoc())).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores modified arrows (browser/OS shortcuts)', () => {
|
||||
expect(resolveArrowKeyAction(arrowEvent({ metaKey: true }), emptyDoc())).toBeNull()
|
||||
expect(resolveArrowKeyAction(arrowEvent({ ctrlKey: true }), emptyDoc())).toBeNull()
|
||||
expect(resolveArrowKeyAction(arrowEvent({ altKey: true }), emptyDoc())).toBeNull()
|
||||
expect(resolveArrowKeyAction(arrowEvent({ shiftKey: true }), emptyDoc())).toBeNull()
|
||||
})
|
||||
|
||||
it('never steals arrows from a focused text field', () => {
|
||||
const e = arrowEvent({ target: { tagName: 'TEXTAREA' } })
|
||||
expect(resolveArrowKeyAction(e, emptyDoc())).toBeNull()
|
||||
})
|
||||
|
||||
it('yields to an open dropdown menu but not to a hidden mounted dialog', () => {
|
||||
const openMenu = makeDoc([{ attrs: { 'data-radix-menu-content': '', 'data-state': 'open' } }])
|
||||
expect(resolveArrowKeyAction(arrowEvent(), openMenu)).toBeNull()
|
||||
|
||||
const hiddenSheet = makeDoc([{ attrs: { role: 'dialog' } }])
|
||||
expect(resolveArrowKeyAction(arrowEvent(), hiddenSheet)).toBe('next')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { applyRangeSelection } from '@/lib/hooks/use-range-select'
|
||||
|
||||
const VISIBLE = ['a', 'b', 'c', 'd', 'e']
|
||||
|
||||
function sorted(ids: Set<string>): string[] {
|
||||
return [...ids].sort()
|
||||
}
|
||||
|
||||
describe('applyRangeSelection', () => {
|
||||
it('toggles a single row when not extending', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: null,
|
||||
targetId: 'b',
|
||||
extend: false,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['b'])
|
||||
})
|
||||
|
||||
it('unselects a selected row when not extending', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['b']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'b',
|
||||
targetId: 'b',
|
||||
extend: false,
|
||||
})
|
||||
expect(sorted(next)).toEqual([])
|
||||
})
|
||||
|
||||
it('selects the range downwards from the anchor', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['b']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'b',
|
||||
targetId: 'd',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['b', 'c', 'd'])
|
||||
})
|
||||
|
||||
it('selects the range upwards from the anchor', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['d']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'd',
|
||||
targetId: 'b',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['b', 'c', 'd'])
|
||||
})
|
||||
|
||||
it('unselects the whole range when the target was selected', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['a', 'b', 'c', 'd']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'a',
|
||||
targetId: 'c',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['d'])
|
||||
})
|
||||
|
||||
it('keeps selections outside the range untouched', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['a', 'b']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'b',
|
||||
targetId: 'd',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['a', 'b', 'c', 'd'])
|
||||
})
|
||||
|
||||
it('degrades to a plain toggle when there is no anchor yet', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: null,
|
||||
targetId: 'd',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['d'])
|
||||
})
|
||||
|
||||
it('degrades to a plain toggle when the selection was cleared', () => {
|
||||
// The anchor row is still on screen, but the user cleared the selection
|
||||
// (clear button, filter change, finished bulk action). Extending from it
|
||||
// would sweep in rows they never picked.
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'a',
|
||||
targetId: 'e',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['e'])
|
||||
})
|
||||
|
||||
it('degrades to a plain toggle when the anchor is no longer visible', () => {
|
||||
// The anchor row was filtered away or is on another page.
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['z']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'z',
|
||||
targetId: 'c',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['c', 'z'])
|
||||
})
|
||||
|
||||
it('follows the rendered order, not the id order', () => {
|
||||
// The anchor is always a row the user just clicked, so it is selected.
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['e']),
|
||||
visibleIds: ['e', 'd', 'c', 'b', 'a'],
|
||||
anchorId: 'e',
|
||||
targetId: 'c',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual(['c', 'd', 'e'])
|
||||
})
|
||||
|
||||
it('unselects just the row when anchor and target are the same', () => {
|
||||
const next = applyRangeSelection({
|
||||
selectedIds: new Set(['c']),
|
||||
visibleIds: VISIBLE,
|
||||
anchorId: 'c',
|
||||
targetId: 'c',
|
||||
extend: true,
|
||||
})
|
||||
expect(sorted(next)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Pure keyboard-guard rules for useDetailPager, extracted from the hook so
|
||||
* they are testable in the node test environment (the hook itself needs a
|
||||
* browser to render). Only structural types: the hook passes the real
|
||||
* document, tests pass plain objects.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Overlays that are actually open. Mirrors the Esc guard selector in
|
||||
* components/agent/AgentSheet.tsx: match on data-state="open", never on the
|
||||
* container alone. The agent sheet renders role="dialog" and stays mounted
|
||||
* with display:none once it has been opened, so keying off a bare
|
||||
* [role="dialog"] would kill arrow paging for the rest of the tab session;
|
||||
* conversely open dropdown menus (Radix menu/select/listbox content) carry
|
||||
* no dialog role and must still block.
|
||||
*/
|
||||
const OPEN_OVERLAY_SELECTOR = [
|
||||
'[data-radix-popper-content-wrapper] [data-state="open"]',
|
||||
'[role="dialog"][data-state="open"]',
|
||||
'[role="alertdialog"][data-state="open"]',
|
||||
'[role="listbox"][data-state="open"]',
|
||||
'[data-radix-menu-content][data-state="open"]',
|
||||
'[data-radix-select-content][data-state="open"]',
|
||||
].join(', ')
|
||||
|
||||
/**
|
||||
* Containers whose focused content owns the arrow keys regardless of
|
||||
* data-state, for overlays that do not mark themselves the Radix way.
|
||||
* A display:none container can never hold focus, so a mounted-but-hidden
|
||||
* sheet does not block through this path either.
|
||||
*/
|
||||
const FOCUS_CONTAINER_SELECTOR =
|
||||
'[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]'
|
||||
|
||||
export interface OverlayProbeElement {
|
||||
closest(selectors: string): unknown
|
||||
}
|
||||
|
||||
export interface OverlayProbeDocument {
|
||||
querySelector(selectors: string): unknown
|
||||
readonly activeElement: OverlayProbeElement | null
|
||||
}
|
||||
|
||||
/** True while an overlay that should own the keyboard is open or focused. */
|
||||
export function isOverlayBlocking(doc: OverlayProbeDocument): boolean {
|
||||
if (doc.querySelector(OPEN_OVERLAY_SELECTOR)) return true
|
||||
const active = doc.activeElement
|
||||
return Boolean(active?.closest(FOCUS_CONTAINER_SELECTOR))
|
||||
}
|
||||
|
||||
/**
|
||||
* True for targets that own arrow keys: text fields, selects, contentEditable.
|
||||
* Duck-typed on tagName/isContentEditable instead of instanceof HTMLElement so
|
||||
* the rule works without DOM globals (tests, SSR); the semantics are the same
|
||||
* for real elements.
|
||||
*/
|
||||
export function isEditableTarget(target: unknown): boolean {
|
||||
if (target === null || typeof target !== 'object') return false
|
||||
const el = target as { tagName?: unknown; isContentEditable?: unknown }
|
||||
if (el.isContentEditable === true) return true
|
||||
return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT'
|
||||
}
|
||||
|
||||
export interface ArrowKeyEventLike {
|
||||
key: string
|
||||
defaultPrevented: boolean
|
||||
isComposing: boolean
|
||||
metaKey: boolean
|
||||
ctrlKey: boolean
|
||||
altKey: boolean
|
||||
shiftKey: boolean
|
||||
target: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* The full keydown decision: which paging action, if any, a keydown event
|
||||
* should trigger. Returns null whenever anything nearer the user owns the key.
|
||||
*/
|
||||
export function resolveArrowKeyAction(
|
||||
e: ArrowKeyEventLike,
|
||||
doc: OverlayProbeDocument,
|
||||
): 'prev' | 'next' | null {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return null
|
||||
if (e.defaultPrevented || e.isComposing) return null
|
||||
// Plain arrows only: modified arrows are browser/OS shortcuts
|
||||
// (cmd+arrow is history navigation on macOS).
|
||||
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return null
|
||||
// Never steal arrows from text editing (e.g. the notes textarea on the
|
||||
// verifikat page).
|
||||
if (isEditableTarget(e.target)) return null
|
||||
if (isOverlayBlocking(doc)) return null
|
||||
return e.key === 'ArrowLeft' ? 'prev' : 'next'
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import { useFetch } from './use-fetch'
|
||||
import type { AgiSubmissionState } from '@/lib/salary/agi-submission-state'
|
||||
|
||||
/**
|
||||
* Fetches the Skatteverket extension's per-period AGI submission record
|
||||
* (`agi_submission_{period}`, period = YYYYMM) so the run page, progress
|
||||
* rail, and salary hero can render the real filing state machine
|
||||
* (underlag submitted / awaiting BankID signature / signed).
|
||||
*
|
||||
* Returns `submission: null` when the extension is disabled (503, e.g.
|
||||
* self-hosted), the user isn't connected, or nothing has been submitted
|
||||
* yet: callers fall back to the run row's own agi_* timestamps. Pass a
|
||||
* null period to skip fetching entirely (e.g. a run that isn't booked).
|
||||
*
|
||||
* Refetches when the tab regains focus: the user typically signs in
|
||||
* Skatteverket's Mina Sidor in another tab (or on their phone) and comes
|
||||
* back here expecting the state to have caught up.
|
||||
*/
|
||||
export function useAgiSubmission(period: string | null): {
|
||||
submission: AgiSubmissionState | null
|
||||
refresh: () => void
|
||||
} {
|
||||
const { data, refetch } = useFetch<
|
||||
{ data?: AgiSubmissionState | null },
|
||||
AgiSubmissionState | null
|
||||
>(period ? `/api/extensions/ext/skatteverket/agi/status?period=${period}` : null, {
|
||||
select: body => body?.data ?? null,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
function onVisible() {
|
||||
if (document.visibilityState === 'visible') refetch()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
return () => document.removeEventListener('visibilitychange', onVisible)
|
||||
}, [refetch])
|
||||
|
||||
return { submission: data, refresh: refetch }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
'use client'
|
||||
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
|
||||
/**
|
||||
* Returns whether the current user can perform write actions in the
|
||||
* active company. Viewers (role === 'viewer') get `canWrite = false`;
|
||||
* owner / admin / member all get `canWrite = true`. Users with no active
|
||||
* company (null role) also get `canWrite = false`.
|
||||
*
|
||||
* Used by every write-action button (create / edit / delete / send /
|
||||
* approve / etc.) across the dashboard to render the button in a
|
||||
* disabled state with a lock icon and tooltip.
|
||||
*
|
||||
* This is the UI layer of the viewer role enforcement. The API layer
|
||||
* (`requireWritePermission()`) and RLS layer (`current_user_can_write()`)
|
||||
* remain the security-critical backstops: this hook only controls what
|
||||
* the user sees and can click.
|
||||
*/
|
||||
export function useCanWrite(): { canWrite: boolean } {
|
||||
const { role } = useCompany()
|
||||
return { canWrite: role !== null && role !== 'viewer' }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
computeNeighbors,
|
||||
readListContext,
|
||||
type ListContext,
|
||||
} from '@/lib/navigation/list-context'
|
||||
import { resolveArrowKeyAction } from '@/lib/hooks/detail-pager-guards'
|
||||
|
||||
export interface DetailPager {
|
||||
prevId: string | null
|
||||
nextId: string | null
|
||||
/** 1-based position, null when no list context exists (deep link/new tab). */
|
||||
index: number | null
|
||||
total: number | null
|
||||
goPrev: () => void
|
||||
goNext: () => void
|
||||
}
|
||||
|
||||
export interface DetailPagerOptions {
|
||||
/**
|
||||
* Set false to suspend the ArrowLeft/ArrowRight bindings entirely, e.g.
|
||||
* while an inline editor with unsaved state is open (paging unmounts the
|
||||
* page and would destroy the draft). Buttons stay active.
|
||||
*/
|
||||
keyboard?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Prev/next record navigation for detail pages, backed by the list context
|
||||
* the originating list page wrote to sessionStorage (lib/navigation/
|
||||
* list-context.ts). Also binds ArrowLeft/ArrowRight while no text field or
|
||||
* open overlay (dialog, menu, listbox) owns the keys; see
|
||||
* lib/hooks/detail-pager-guards.ts for the exact rules. When no context
|
||||
* exists everything is null and the pager UI hides; the detail page degrades
|
||||
* gracefully.
|
||||
*/
|
||||
export function useDetailPager(
|
||||
contextKey: string,
|
||||
basePath: string,
|
||||
currentId: string,
|
||||
options?: DetailPagerOptions,
|
||||
): DetailPager {
|
||||
const keyboard = options?.keyboard ?? true
|
||||
const router = useRouter()
|
||||
const [context, setContext] = useState<ListContext | null>(null)
|
||||
|
||||
// Read in an effect, not during render: sessionStorage does not exist on
|
||||
// the server and reading it pre-hydration would mismatch the SSR HTML.
|
||||
useEffect(() => {
|
||||
setContext(readListContext(contextKey))
|
||||
}, [contextKey])
|
||||
|
||||
const neighbors = useMemo(
|
||||
() => (context ? computeNeighbors(context.ids, currentId) : null),
|
||||
[context, currentId],
|
||||
)
|
||||
const prevId = neighbors?.prevId ?? null
|
||||
const nextId = neighbors?.nextId ?? null
|
||||
|
||||
// router.replace, deliberately not push: stepping through records is one
|
||||
// browsing act, so "tillbaka" returns to the list in a single step instead
|
||||
// of walking back through every viewed record.
|
||||
const goPrev = useCallback(() => {
|
||||
if (prevId) router.replace(`${basePath}/${prevId}`)
|
||||
}, [basePath, prevId, router])
|
||||
|
||||
const goNext = useCallback(() => {
|
||||
if (nextId) router.replace(`${basePath}/${nextId}`)
|
||||
}, [basePath, nextId, router])
|
||||
|
||||
useEffect(() => {
|
||||
if (!neighbors || !keyboard) return
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
const action = resolveArrowKeyAction(e, document)
|
||||
if (action === 'prev') goPrev()
|
||||
else if (action === 'next') goNext()
|
||||
}
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
return () => window.removeEventListener('keydown', onKeyDown)
|
||||
}, [neighbors, keyboard, goPrev, goNext])
|
||||
|
||||
return {
|
||||
prevId,
|
||||
nextId,
|
||||
index: neighbors?.index ?? null,
|
||||
total: neighbors?.total ?? null,
|
||||
goPrev,
|
||||
goNext,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
// Polls GET /api/documents/:id/extraction-status until the AI extraction
|
||||
// pipeline completes, fails, or times out. Returns the derived status the
|
||||
// upload UI binds to.
|
||||
//
|
||||
// "Disabled" semantics: the server answers 'disabled' as soon as it knows
|
||||
// no extraction will happen (AI not configured on this deployment, company
|
||||
// not entitled, self-generated document: see the route), so the UI can
|
||||
// quietly fall back ("Uppladdat" without an AI hint) on the first poll: no
|
||||
// scary error for a feature the customer didn't pay for, and no 30 s hang
|
||||
// on a self-host without an AI key. The client-side timeout stays as the
|
||||
// last resort for the one case the server cannot see: the
|
||||
// document-extraction extension switched off entirely (the column stays
|
||||
// NULL forever).
|
||||
//
|
||||
// Reasonable timeout: typical extraction takes 2-8s on Sonnet via Bedrock.
|
||||
// 30s is generous and keeps the UX responsive on flaky links.
|
||||
|
||||
const POLL_INTERVAL_MS = 1500
|
||||
const EXTRACTION_TIMEOUT_MS = 30_000
|
||||
|
||||
export type ExtractionStatus =
|
||||
| 'idle'
|
||||
| 'running'
|
||||
| 'succeeded'
|
||||
| 'failed'
|
||||
| 'unsupported'
|
||||
| 'disabled'
|
||||
|
||||
interface State {
|
||||
status: ExtractionStatus
|
||||
// Hint to consumers: how long we've been polling. Lets the UI swap the
|
||||
// copy after a few seconds ("Läser fakturan…" → "Tar lite längre än
|
||||
// vanligt…") without re-rendering.
|
||||
elapsedMs: number
|
||||
}
|
||||
|
||||
export function useDocumentExtraction(documentId: string | null | undefined): State {
|
||||
const [state, setState] = useState<State>({ status: 'idle', elapsedMs: 0 })
|
||||
|
||||
useEffect(() => {
|
||||
if (!documentId) {
|
||||
setState({ status: 'idle', elapsedMs: 0 })
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
const startedAt = Date.now()
|
||||
setState({ status: 'running', elapsedMs: 0 })
|
||||
|
||||
async function tick(): Promise<void> {
|
||||
if (cancelled) return
|
||||
const elapsedMs = Date.now() - startedAt
|
||||
|
||||
if (elapsedMs > EXTRACTION_TIMEOUT_MS) {
|
||||
setState({ status: 'disabled', elapsedMs })
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/documents/${documentId}/extraction-status`)
|
||||
if (cancelled) return
|
||||
if (res.ok) {
|
||||
const json = (await res.json()) as {
|
||||
data: { status: ExtractionStatus }
|
||||
}
|
||||
const status = json.data.status
|
||||
if (status !== 'running') {
|
||||
setState({ status, elapsedMs })
|
||||
return
|
||||
}
|
||||
setState({ status: 'running', elapsedMs })
|
||||
}
|
||||
// Non-ok responses fall through to retry; transient 5xx shouldn't
|
||||
// collapse the UI to "failed".
|
||||
} catch {
|
||||
// Network blip: keep polling.
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (!cancelled) void tick()
|
||||
}, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
void tick()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [documentId])
|
||||
|
||||
return state
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Client-side helper that turns a fetch failure into a Swedish toast with
|
||||
* remediation hint and the X-Request-Id for support reference.
|
||||
*
|
||||
* Accepts:
|
||||
* - the `{ error: {...} }` envelope produced by the route wrapper
|
||||
* - a Response object (the helper reads it for you)
|
||||
* - a raw Error / string (falls back to getErrorMessage)
|
||||
*
|
||||
* Usage:
|
||||
* const showError = useErrorToast()
|
||||
* const res = await fetch('/api/invoices/123/send', { method: 'POST' })
|
||||
* if (!res.ok) {
|
||||
* await showError(res, { context: 'invoice' })
|
||||
* return
|
||||
* }
|
||||
*/
|
||||
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { ErrorEnvelope } from '@/lib/errors/get-structured-error'
|
||||
|
||||
type ErrorContext =
|
||||
| 'invoice'
|
||||
| 'supplier_invoice'
|
||||
| 'customer'
|
||||
| 'supplier'
|
||||
| 'transaction'
|
||||
| 'journal_entry'
|
||||
| 'settings'
|
||||
| 'auth'
|
||||
| 'salary'
|
||||
|
||||
interface ShowErrorOptions {
|
||||
context?: ErrorContext
|
||||
/** Override the toast title (Swedish summary). Defaults to envelope.message. */
|
||||
title?: string
|
||||
}
|
||||
|
||||
interface NormalizedError {
|
||||
message: string
|
||||
remediation?: string
|
||||
requestId?: string
|
||||
code?: string
|
||||
}
|
||||
|
||||
async function normalize(input: unknown): Promise<NormalizedError> {
|
||||
// Response: try to read JSON body and X-Request-Id header
|
||||
if (input instanceof Response) {
|
||||
const requestId = input.headers.get('X-Request-Id') ?? undefined
|
||||
let body: unknown = null
|
||||
try {
|
||||
body = await input.json()
|
||||
} catch {
|
||||
// ignore: body might be empty
|
||||
}
|
||||
const fromBody = readEnvelope(body)
|
||||
return {
|
||||
message: fromBody.message ?? getErrorMessage(body, { statusCode: input.status }),
|
||||
remediation: fromBody.remediation,
|
||||
requestId: fromBody.requestId ?? requestId,
|
||||
code: fromBody.code,
|
||||
}
|
||||
}
|
||||
|
||||
const fromBody = readEnvelope(input)
|
||||
if (fromBody.message) {
|
||||
return fromBody
|
||||
}
|
||||
return { message: getErrorMessage(input) }
|
||||
}
|
||||
|
||||
function readEnvelope(input: unknown): NormalizedError {
|
||||
if (!input || typeof input !== 'object') return { message: '' }
|
||||
const obj = input as Record<string, unknown>
|
||||
const errObj = obj.error
|
||||
if (errObj && typeof errObj === 'object') {
|
||||
const e = errObj as Partial<ErrorEnvelope['error']>
|
||||
return {
|
||||
message: typeof e.message === 'string' ? e.message : '',
|
||||
remediation:
|
||||
e.remediation && typeof e.remediation === 'object'
|
||||
? (e.remediation as { description?: string }).description
|
||||
: undefined,
|
||||
requestId: typeof e.requestId === 'string' ? e.requestId : undefined,
|
||||
code: typeof e.code === 'string' ? e.code : undefined,
|
||||
}
|
||||
}
|
||||
return { message: '' }
|
||||
}
|
||||
|
||||
export function useErrorToast() {
|
||||
const { toast } = useToast()
|
||||
|
||||
return async function showError(input: unknown, options: ShowErrorOptions = {}) {
|
||||
const norm = await normalize(input)
|
||||
const title = options.title ?? norm.message ?? getErrorMessage(input, { context: options.context })
|
||||
|
||||
const descriptionParts: string[] = []
|
||||
if (norm.remediation) descriptionParts.push(norm.remediation)
|
||||
if (norm.requestId) descriptionParts.push(`Felreferens: ${norm.requestId}`)
|
||||
if (process.env.NODE_ENV !== 'production' && norm.code) {
|
||||
descriptionParts.push(`Kod: ${norm.code}`)
|
||||
}
|
||||
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title,
|
||||
description: descriptionParts.length > 0 ? descriptionParts.join(' · ') : undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useLocale } from 'next-intl'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* Canonical client data-fetching hook.
|
||||
*
|
||||
* Replaces the hand-rolled `useState(loading)` + `useState(error)` + `useEffect`
|
||||
* + bare `fetch()` block repeated across ~85 components. Gives every caller the
|
||||
* same behaviour for free:
|
||||
*
|
||||
* - cancels the in-flight request on unmount / url change (AbortController), so
|
||||
* a slow response can't land after the component moved on (no stale state,
|
||||
* no "set state on unmounted component" races);
|
||||
* - routes errors through the bilingual `getErrorMessage()` using the active
|
||||
* UI locale, so error copy is consistent and localized;
|
||||
* - exposes `refetch()` for retry / post-mutation refresh.
|
||||
*
|
||||
* Behaviour notes (intentional):
|
||||
* - `data` is NOT cleared on `refetch()` or url change: it keeps the previous
|
||||
* result while the new request is in flight (keep-previous-data), so lists
|
||||
* don't blank out on refresh. Read `loading` to show a pending indicator.
|
||||
* - When `url`/`enabled` start inactive and later become active, `loading`
|
||||
* flips true on the effect tick, not synchronously on the activating render.
|
||||
* Branch on `loading` first to avoid a flash.
|
||||
|
||||
*
|
||||
* Response convention: the JSON body is returned as-is, typed as `T`. Most
|
||||
* Accounted routes wrap payloads as `{ data: ... }`, so the common usage is
|
||||
* `useFetch<{ data: Account[] }>(...)` then read `result.data?.data`. Pass
|
||||
* `select` to unwrap/transform at the hook boundary instead.
|
||||
*
|
||||
* @example
|
||||
* const { data, loading, error, refetch } = useFetch<Account[]>(
|
||||
* '/api/bookkeeping/accounts',
|
||||
* { select: (body) => body.data ?? [] },
|
||||
* )
|
||||
*/
|
||||
export interface UseFetchOptions<T, R> {
|
||||
/** Skip the request until true (e.g. waiting on a dependency). Default true. */
|
||||
enabled?: boolean
|
||||
/** Transform/unwrap the parsed JSON body before it reaches `data`. */
|
||||
select?: (body: T) => R
|
||||
/** Extra `fetch` init (headers, etc.). The AbortController signal is merged in. */
|
||||
init?: Omit<RequestInit, 'signal'>
|
||||
}
|
||||
|
||||
export interface UseFetchResult<R> {
|
||||
data: R | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
/** Re-run the request. Safe to call from event handlers. */
|
||||
refetch: () => void
|
||||
}
|
||||
|
||||
export function useFetch<T = unknown, R = T>(
|
||||
url: string | null,
|
||||
options: UseFetchOptions<T, R> = {},
|
||||
): UseFetchResult<R> {
|
||||
const { enabled = true, select, init } = options
|
||||
const locale = useLocale() as ErrorLocale
|
||||
|
||||
// Keep select/init out of the effect deps without re-running on every render.
|
||||
const selectRef = useRef(select)
|
||||
selectRef.current = select
|
||||
const initRef = useRef(init)
|
||||
initRef.current = init
|
||||
|
||||
const active = enabled && url != null
|
||||
const [data, setData] = useState<R | null>(null)
|
||||
const [loading, setLoading] = useState<boolean>(active)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [nonce, setNonce] = useState(0)
|
||||
|
||||
const refetch = useCallback(() => setNonce((n) => n + 1), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || url == null) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch(url, { ...initRef.current, signal: controller.signal })
|
||||
const body = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
getErrorMessage(body ?? { error: res.statusText }, { locale, statusCode: res.status }),
|
||||
)
|
||||
}
|
||||
if (controller.signal.aborted) return
|
||||
const transform = selectRef.current
|
||||
setData((transform ? transform(body as T) : (body as unknown as R)))
|
||||
} catch (err) {
|
||||
if (controller.signal.aborted || (err as Error)?.name === 'AbortError') return
|
||||
setError(getErrorMessage(err, { locale }))
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => controller.abort()
|
||||
}, [url, active, nonce, locale])
|
||||
|
||||
return { data, loading, error, refetch }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
'use client'
|
||||
|
||||
import { useLocale } from 'next-intl'
|
||||
import { formatDateLong as formatDateLongRaw } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* Client-side hook returning locale-aware formatters.
|
||||
*
|
||||
* Currency stays SEK with sv-SE conventions (1 234,56 kr) regardless of UI
|
||||
* language: that's the Swedish accounting standard, not a UI string.
|
||||
* formatDate (ISO yyyy-MM-dd) is locale-independent and exported directly
|
||||
* from lib/utils.
|
||||
*/
|
||||
export function useFormat() {
|
||||
const locale = useLocale()
|
||||
return {
|
||||
locale,
|
||||
formatDateLong: (date: Date | string) => formatDateLongRaw(date, locale),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useRef } from 'react'
|
||||
|
||||
/**
|
||||
* Gmail-style shift-click range selection for list rows.
|
||||
*
|
||||
* Plain click toggles one row and becomes the anchor. Shift-click applies the
|
||||
* clicked row's NEW state to every row between the anchor and the target, in
|
||||
* the order the rows are currently rendered (so the range follows what the
|
||||
* user sees after filtering, sorting and paging, not the underlying data
|
||||
* order).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Pure range rule, extracted from the hook so it is testable without a
|
||||
* browser. Returns the next selection.
|
||||
*
|
||||
* `visibleIds` must be the rendered order. When the anchor is missing (first
|
||||
* click, or the anchor scrolled out of the current filter/page) a shift-click
|
||||
* degrades to a plain toggle, which is what every mail client does.
|
||||
*
|
||||
* An EMPTY selection also counts as having no anchor: every list clears the
|
||||
* selection from several places (a clear button, a filter change, a finished
|
||||
* bulk action), and a range measured from a row the user can no longer see
|
||||
* selected would sweep in dozens of rows they never picked. Anchoring on the
|
||||
* selection rather than on the clear call sites keeps that true for clear
|
||||
* paths nobody remembered to wire up.
|
||||
*/
|
||||
export function applyRangeSelection({
|
||||
selectedIds,
|
||||
visibleIds,
|
||||
anchorId,
|
||||
targetId,
|
||||
extend,
|
||||
}: {
|
||||
selectedIds: Set<string>
|
||||
visibleIds: string[]
|
||||
anchorId: string | null
|
||||
targetId: string
|
||||
extend: boolean
|
||||
}): Set<string> {
|
||||
const next = new Set(selectedIds)
|
||||
const shouldSelect = !selectedIds.has(targetId)
|
||||
|
||||
const anchorIndex =
|
||||
anchorId === null || selectedIds.size === 0 ? -1 : visibleIds.indexOf(anchorId)
|
||||
const targetIndex = visibleIds.indexOf(targetId)
|
||||
|
||||
if (!extend || anchorIndex === -1 || targetIndex === -1) {
|
||||
if (shouldSelect) next.add(targetId)
|
||||
else next.delete(targetId)
|
||||
return next
|
||||
}
|
||||
|
||||
const from = Math.min(anchorIndex, targetIndex)
|
||||
const to = Math.max(anchorIndex, targetIndex)
|
||||
for (let i = from; i <= to; i++) {
|
||||
if (shouldSelect) next.add(visibleIds[i])
|
||||
else next.delete(visibleIds[i])
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
export interface UseRangeSelectOptions {
|
||||
/** Row ids in the order they are rendered right now. */
|
||||
visibleIds: string[]
|
||||
selectedIds: Set<string>
|
||||
setSelectedIds: (next: Set<string>) => void
|
||||
}
|
||||
|
||||
export interface UseRangeSelect {
|
||||
/** Toggle one row; pass shiftKey from the click event to extend the range. */
|
||||
toggle: (id: string, extend?: boolean) => void
|
||||
/** Drop the anchor, e.g. after select-all or clear. */
|
||||
resetAnchor: () => void
|
||||
}
|
||||
|
||||
export function useRangeSelect({
|
||||
visibleIds,
|
||||
selectedIds,
|
||||
setSelectedIds,
|
||||
}: UseRangeSelectOptions): UseRangeSelect {
|
||||
const anchorRef = useRef<string | null>(null)
|
||||
|
||||
const toggle = useCallback(
|
||||
(id: string, extend = false) => {
|
||||
setSelectedIds(
|
||||
applyRangeSelection({
|
||||
selectedIds,
|
||||
visibleIds,
|
||||
anchorId: anchorRef.current,
|
||||
targetId: id,
|
||||
extend,
|
||||
}),
|
||||
)
|
||||
anchorRef.current = id
|
||||
},
|
||||
[selectedIds, visibleIds, setSelectedIds],
|
||||
)
|
||||
|
||||
const resetAnchor = useCallback(() => {
|
||||
anchorRef.current = null
|
||||
}, [])
|
||||
|
||||
return { toggle, resetAnchor }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
|
||||
/**
|
||||
* Stable browser Supabase client for realtime-enabled client components.
|
||||
*
|
||||
* The browser client itself is shared with normal data fetching; this hook
|
||||
* lazily creates the instance once so components can wire subscriptions
|
||||
* without recreating the client on every render.
|
||||
*/
|
||||
export function useRealtimeSupabase(): SupabaseClient {
|
||||
const [supabase] = useState(() => createClient())
|
||||
return supabase
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useState } from 'react'
|
||||
|
||||
/**
|
||||
* Wraps an async submit function so that responses of the form
|
||||
* `{ error: { code: 'ACCOUNTS_NOT_IN_CHART', account_numbers } }` trigger a
|
||||
* dialog-and-retry flow instead of surfacing as a generic error.
|
||||
*
|
||||
* The consumer renders <ActivateAccountsDialog> bound to `dialog.open`,
|
||||
* `dialog.accountNumbers`, `confirm`, and `cancel`. On confirm the missing
|
||||
* accounts are activated and the original submit runs again automatically.
|
||||
*
|
||||
* The submit fn should throw with a cause object containing the parsed
|
||||
* response body so we can read the structured error. Convention:
|
||||
* throw Object.assign(new Error(body.error.message), { body, status })
|
||||
*/
|
||||
|
||||
interface DialogState {
|
||||
open: boolean
|
||||
accountNumbers: string[]
|
||||
}
|
||||
|
||||
interface StructuredError {
|
||||
code?: string
|
||||
account_numbers?: string[]
|
||||
message?: string
|
||||
}
|
||||
|
||||
function extractAccountsNotInChart(err: unknown): string[] | null {
|
||||
if (typeof err !== 'object' || err === null) return null
|
||||
const anyErr = err as { body?: { error?: StructuredError } }
|
||||
const structured = anyErr.body?.error
|
||||
if (structured?.code === 'ACCOUNTS_NOT_IN_CHART' && Array.isArray(structured.account_numbers)) {
|
||||
return structured.account_numbers
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function useSubmitWithAccountActivation<T>(
|
||||
submit: () => Promise<T>
|
||||
) {
|
||||
const [dialog, setDialog] = useState<DialogState>({ open: false, accountNumbers: [] })
|
||||
const [pendingResolve, setPendingResolve] = useState<null | ((value: T | null) => void)>(null)
|
||||
const [pendingReject, setPendingReject] = useState<null | ((err: unknown) => void)>(null)
|
||||
|
||||
const runSubmit = useCallback(async (): Promise<T> => {
|
||||
try {
|
||||
return await submit()
|
||||
} catch (err) {
|
||||
const missing = extractAccountsNotInChart(err)
|
||||
if (!missing) throw err
|
||||
|
||||
// Open dialog and wait for the user to confirm or cancel.
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
setPendingResolve(() => (value: T | null) => {
|
||||
if (value === null) reject(new Error('cancelled'))
|
||||
else resolve(value)
|
||||
})
|
||||
setPendingReject(() => reject)
|
||||
setDialog({ open: true, accountNumbers: missing })
|
||||
})
|
||||
}
|
||||
}, [submit])
|
||||
|
||||
const confirm = useCallback(async () => {
|
||||
const numbers = dialog.accountNumbers
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/accounts/activate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ account_numbers: numbers }),
|
||||
})
|
||||
const body = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
throw Object.assign(new Error('Kunde inte aktivera konton'), { body, status: res.status })
|
||||
}
|
||||
// Retry the original submit
|
||||
const result = await submit()
|
||||
setDialog({ open: false, accountNumbers: [] })
|
||||
pendingResolve?.(result as T | null)
|
||||
setPendingResolve(null)
|
||||
setPendingReject(null)
|
||||
} catch (err) {
|
||||
setDialog({ open: false, accountNumbers: [] })
|
||||
pendingReject?.(err)
|
||||
setPendingResolve(null)
|
||||
setPendingReject(null)
|
||||
}
|
||||
}, [dialog.accountNumbers, submit, pendingResolve, pendingReject])
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
setDialog({ open: false, accountNumbers: [] })
|
||||
pendingReject?.(new Error('cancelled'))
|
||||
setPendingResolve(null)
|
||||
setPendingReject(null)
|
||||
}, [pendingReject])
|
||||
|
||||
return { runSubmit, dialog, confirm, cancel }
|
||||
}
|
||||
|
||||
/**
|
||||
* Small helper: parse a Response and throw a shaped error that
|
||||
* useSubmitWithAccountActivation can recognize. Callers use this inside
|
||||
* their submit fn so the hook can pick up ACCOUNTS_NOT_IN_CHART.
|
||||
*/
|
||||
export async function throwOnStructuredError(response: Response): Promise<unknown> {
|
||||
const body = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
throw Object.assign(new Error(extractMessage(body) || `HTTP ${response.status}`), {
|
||||
body,
|
||||
status: response.status,
|
||||
})
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
function extractMessage(body: unknown): string | null {
|
||||
if (typeof body !== 'object' || body === null) return null
|
||||
const obj = body as { error?: unknown }
|
||||
if (typeof obj.error === 'string') return obj.error
|
||||
if (typeof obj.error === 'object' && obj.error !== null) {
|
||||
const e = obj.error as { message?: unknown }
|
||||
if (typeof e.message === 'string') return e.message
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
'use client'
|
||||
|
||||
import useSWR from 'swr'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import type { UserUiState } from '@/types'
|
||||
|
||||
/**
|
||||
* Client-side read of user_preferences.ui_state (nav folds, split-button
|
||||
* last-used modes). RLS scopes the select to the caller's own row. Pages
|
||||
* use this to seed SplitButton's initial mode; writes go through
|
||||
* lib/ui-state/client (POST /api/user/ui-state).
|
||||
*
|
||||
* Errors (including a not-yet-migrated ui_state column) degrade to an
|
||||
* empty state: the UI falls back to its defaults.
|
||||
*/
|
||||
export function useUiState() {
|
||||
const { data } = useSWR<UserUiState>('user-ui-state', async () => {
|
||||
const supabase = createClient()
|
||||
const { data: row } = await supabase
|
||||
.from('user_preferences')
|
||||
.select('ui_state')
|
||||
.maybeSingle()
|
||||
return (row?.ui_state as UserUiState) ?? {}
|
||||
})
|
||||
|
||||
return { uiState: data, loaded: data !== undefined }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
|
||||
/**
|
||||
* Attaches a `beforeunload` event listener when the form has unsaved changes.
|
||||
* This guards against browser close, tab close, and page refresh.
|
||||
*
|
||||
* Does NOT guard in-app Next.js navigation (App Router has no supported mechanism).
|
||||
*/
|
||||
export function useUnsavedChanges(isDirty: boolean) {
|
||||
useEffect(() => {
|
||||
if (!isDirty) return
|
||||
|
||||
const handler = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', handler)
|
||||
return () => window.removeEventListener('beforeunload', handler)
|
||||
}, [isDirty])
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
'use client'
|
||||
|
||||
import useSWR from 'swr'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
|
||||
export interface WorklistBadges {
|
||||
/**
|
||||
* Rows waiting in the Transaktioner inbox: unbooked bank transactions
|
||||
* (lib/worklist countUnbookedTransactions) plus unbooked skattekonto rows
|
||||
* (countUnbookedSkattekontoRows). The badge sits on /transactions, which
|
||||
* lists both, so the number must cover both (#2180).
|
||||
*/
|
||||
uncategorized: number
|
||||
/** Agent-staged operations awaiting review: same predicate as countPendingOperations. */
|
||||
pendingOperations: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side nav badge counts. These used to be fetched by the dashboard
|
||||
* layout on the critical path of every server navigation; two head-count
|
||||
* queries nobody needs before first paint. Now they load (and revalidate)
|
||||
* after mount, and SWR dedupes the realtime-triggered refreshes that
|
||||
* previously stampeded during bulk operations.
|
||||
*
|
||||
* The predicates deliberately mirror lib/worklist/categories.ts so the badge
|
||||
* shows the same number as every other "att göra" surface; RLS scopes both
|
||||
* tables, and the explicit company_id filter is defense in depth.
|
||||
*/
|
||||
export function useWorklistBadges(companyId: string | null | undefined) {
|
||||
const { data, mutate } = useSWR<WorklistBadges>(
|
||||
companyId ? ['worklist-badges', companyId] : null,
|
||||
async ([, id]: [string, string]) => {
|
||||
const supabase = createClient()
|
||||
const [tx, skv, ops] = await Promise.all([
|
||||
supabase
|
||||
.from('transactions')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', id)
|
||||
.is('is_business', null)
|
||||
.eq('is_ignored', false),
|
||||
supabase
|
||||
.from('skattekonto_transactions')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', id)
|
||||
.eq('status', 'booked')
|
||||
.is('journal_entry_id', null)
|
||||
.eq('is_ignored', false),
|
||||
supabase
|
||||
.from('pending_operations')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', id)
|
||||
.eq('status', 'pending'),
|
||||
])
|
||||
return {
|
||||
uncategorized: (tx.error ? 0 : (tx.count ?? 0)) + (skv.error ? 0 : (skv.count ?? 0)),
|
||||
pendingOperations: ops.error ? 0 : (ops.count ?? 0),
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
uncategorized: data?.uncategorized ?? 0,
|
||||
pendingOperations: data?.pendingOperations ?? 0,
|
||||
// SWR's bound mutate is referentially stable, so consumers can list it in
|
||||
// effect deps without re-subscribing on every render.
|
||||
refresh: mutate,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user