docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,80 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useSyncExternalStore } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
const dismissKey = (companyId: string) => `erp_agent_promo_dismissed:${companyId}`
|
||||
// storage events only fire in OTHER tabs; this custom event covers the
|
||||
// same-tab dismissal so useSyncExternalStore re-reads localStorage.
|
||||
const DISMISS_EVENT = 'erp-agent-promo-dismissed'
|
||||
|
||||
function subscribeToDismissal(onStoreChange: () => void) {
|
||||
window.addEventListener('storage', onStoreChange)
|
||||
window.addEventListener(DISMISS_EVENT, onStoreChange)
|
||||
return () => {
|
||||
window.removeEventListener('storage', onStoreChange)
|
||||
window.removeEventListener(DISMISS_EVENT, onStoreChange)
|
||||
}
|
||||
}
|
||||
|
||||
interface AgentPromoProps {
|
||||
companyId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Build-assistant nudge on Hem, shown until the company has a verified
|
||||
* agent_profile (the caller gates on that plus the first-run checklist
|
||||
* being dismissed or completed, since the checklist already carries the
|
||||
* assistant as its last step).
|
||||
* Shape: one quiet sentence with the action link at the end and the same
|
||||
* "Dölj" text control the Skatteverket promo uses, not a boxed card. It is
|
||||
* an optional offer, not an exception, so it stays muted (convention 6/12).
|
||||
* Non-payers keep seeing it (conversion surface) but it routes to billing
|
||||
* instead of a build flow that would 403.
|
||||
*/
|
||||
export function AgentPromo({ companyId }: AgentPromoProps) {
|
||||
const t = useTranslations('dashboard')
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
|
||||
// Server snapshot says dismissed: the promo appears only after hydration,
|
||||
// when localStorage is readable, so server and client never disagree.
|
||||
const dismissed = useSyncExternalStore(
|
||||
subscribeToDismissal,
|
||||
() => localStorage.getItem(dismissKey(companyId)) === 'true',
|
||||
() => true
|
||||
)
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
localStorage.setItem(dismissKey(companyId), 'true')
|
||||
window.dispatchEvent(new Event(DISMISS_EVENT))
|
||||
}, [companyId])
|
||||
|
||||
if (dismissed) return null
|
||||
|
||||
return (
|
||||
<section className="flex items-start justify-between gap-4">
|
||||
<p className="text-[12.5px] leading-5 text-muted-foreground">
|
||||
{t(hasAi ? 'agent_promo_description' : 'agent_promo_description_upgrade')}{' '}
|
||||
{/* py-3/-my-3: a 44px tap target on a link that still sits inline in
|
||||
the sentence; the negative margin keeps the line box at 20px so
|
||||
nothing shifts. */}
|
||||
<Link
|
||||
href={hasAi ? '/onboarding/agent' : '/settings/billing'}
|
||||
className="inline-block -my-3 whitespace-nowrap py-3 text-foreground underline decoration-border underline-offset-4 transition-colors hover:decoration-foreground"
|
||||
>
|
||||
{t(hasAi ? 'agent_promo_cta' : 'agent_promo_cta_upgrade')}
|
||||
</Link>
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={dismiss}
|
||||
className="-my-3 shrink-0 py-3 text-xs text-muted-foreground underline decoration-border underline-offset-4 transition-colors hover:text-foreground"
|
||||
>
|
||||
{t('agent_promo_dismiss')}
|
||||
</button>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,244 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, useEffect, useCallback } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { performCompanySwitch } from '@/lib/company/switch-client'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Check, ChevronsUpDown, Plus, Loader2, Lock } from 'lucide-react'
|
||||
|
||||
export default function CompanySwitcher() {
|
||||
const { company, companies, isSandbox, foreignCompanies = [], lockedCompanyIds = [] } = useCompany()
|
||||
const t = useTranslations('company_switcher')
|
||||
const { toast } = useToast()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [isPending, setIsPending] = useState(false)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||
const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 })
|
||||
|
||||
const updatePosition = useCallback(() => {
|
||||
if (!triggerRef.current || !dropdownRef.current) return
|
||||
const triggerRect = triggerRef.current.getBoundingClientRect()
|
||||
const dropdownRect = dropdownRef.current.getBoundingClientRect()
|
||||
const margin = 8
|
||||
|
||||
let top = triggerRect.bottom + 4
|
||||
let left = triggerRect.left
|
||||
|
||||
// Clamp right edge to viewport
|
||||
if (left + dropdownRect.width > window.innerWidth - margin) {
|
||||
left = Math.max(margin, window.innerWidth - dropdownRect.width - margin)
|
||||
}
|
||||
|
||||
// If dropdown would go below viewport, show above trigger
|
||||
if (top + dropdownRect.height > window.innerHeight - margin) {
|
||||
top = Math.max(margin, triggerRect.top - dropdownRect.height - 4)
|
||||
}
|
||||
|
||||
setDropdownPos({ top, left })
|
||||
}, [])
|
||||
|
||||
// Update position when opening (run twice: once to render, once to measure)
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const raf = requestAnimationFrame(() => updatePosition())
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [open, updatePosition])
|
||||
|
||||
// Close on outside click
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleClick(e: MouseEvent) {
|
||||
const target = e.target as Node
|
||||
if (
|
||||
(!triggerRef.current || !triggerRef.current.contains(target)) &&
|
||||
(!dropdownRef.current || !dropdownRef.current.contains(target))
|
||||
) {
|
||||
setOpen(false)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [open])
|
||||
|
||||
// Close on Escape
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') setOpen(false)
|
||||
}
|
||||
document.addEventListener('keydown', handleKey)
|
||||
return () => document.removeEventListener('keydown', handleKey)
|
||||
}, [open])
|
||||
|
||||
const handleSwitch = async (companyId: string) => {
|
||||
if (company && companyId === company.id) {
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
setIsPending(true)
|
||||
// Shared switch-and-reload mechanism (lib/company/switch-client), same
|
||||
// path as the sidebar user-menu flyout.
|
||||
const result = await performCompanySwitch(companyId)
|
||||
if (result?.error) {
|
||||
setIsPending(false)
|
||||
toast({
|
||||
title: t(
|
||||
result.error === 'not_member'
|
||||
? 'error_no_access'
|
||||
: result.error === 'company_locked'
|
||||
? 'error_locked'
|
||||
: 'error_switch_failed',
|
||||
),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Always allow opening the dropdown (to show "Lägg till företag")
|
||||
const hasMultiple = companies.length > 1
|
||||
|
||||
// No companies yet: show a direct "Lägg till företag" link instead of
|
||||
// the switcher so the user can still create one. Hidden in sandbox mode.
|
||||
if (!company && companies.length === 0) {
|
||||
if (isSandbox) return null
|
||||
return (
|
||||
<Link
|
||||
href="/select-company?choose=1"
|
||||
className="flex items-center gap-2 w-full text-left rounded-lg border border-dashed border-border/60 hover:border-foreground/30 hover:bg-muted/40 -mx-1 px-2 py-1.5 transition-colors duration-150"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
|
||||
<span className="text-[13px] text-muted-foreground truncate">{t('add_company')}</span>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
onClick={() => setOpen(!open)}
|
||||
className="flex items-center gap-1.5 w-full text-left rounded-lg border border-transparent hover:border-border/60 hover:bg-muted/40 -mx-1 px-2 py-1.5 transition-colors duration-150"
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-[10px] text-muted-foreground/60 uppercase tracking-[0.06em] leading-none mb-1">{t('company_label')}</p>
|
||||
<p className="text-[13px] font-semibold text-foreground truncate tracking-[-0.01em]">
|
||||
{company?.name || t('default_company_name')}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronsUpDown className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
</button>
|
||||
|
||||
{open && createPortal(
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="fixed min-w-56 w-max max-w-[calc(100vw-1rem)] bg-card border border-border/60 rounded-lg shadow-lg z-[60] py-1 animate-in fade-in slide-in-from-top-1 duration-150"
|
||||
style={{ top: dropdownPos.top, left: dropdownPos.left }}
|
||||
>
|
||||
{companies.length > 0 && (
|
||||
<>
|
||||
{hasMultiple && (
|
||||
<div className="px-2 py-1.5">
|
||||
<p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-[0.08em] px-1.5">
|
||||
{t('company_label')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-h-48 overflow-y-auto px-1">
|
||||
{companies.map(({ company: c, role }) =>
|
||||
lockedCompanyIds.includes(c.id) ? (
|
||||
// Multi-user seat gate: frozen for this user until the
|
||||
// company pays. Shown, not hidden: the membership exists
|
||||
// and the row explains why it cannot be entered.
|
||||
<div
|
||||
key={c.id}
|
||||
className="flex items-center gap-2 w-full px-2.5 py-2 text-left text-[13px] leading-snug text-muted-foreground/60 rounded-sm md:whitespace-nowrap"
|
||||
aria-disabled="true"
|
||||
>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block truncate">{c.name}</span>
|
||||
<span className="block truncate text-[10px]">{t('locked_note')}</span>
|
||||
</span>
|
||||
<Lock className="h-3 w-3 flex-shrink-0" aria-hidden="true" />
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => handleSwitch(c.id)}
|
||||
disabled={isPending}
|
||||
className={cn(
|
||||
'flex items-center gap-2 w-full px-2.5 py-2 text-left text-[13px] leading-snug transition-colors rounded-sm md:whitespace-nowrap',
|
||||
c.id === company?.id
|
||||
? 'text-foreground bg-muted/40'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-muted/40',
|
||||
isPending && 'opacity-50',
|
||||
)}
|
||||
role="option"
|
||||
aria-selected={c.id === company?.id}
|
||||
>
|
||||
<span className="flex-1 min-w-0">{c.name}</span>
|
||||
{role !== 'owner' && (
|
||||
<span className="text-[10px] text-muted-foreground/60 flex-shrink-0">
|
||||
{role}
|
||||
</span>
|
||||
)}
|
||||
{c.id === company?.id && (
|
||||
<Check className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
)}
|
||||
{isPending && c.id !== company?.id && (
|
||||
<Loader2 className="h-3 w-3 animate-spin text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Companies homed on another domain (home-domain rule, WL-01):
|
||||
non-clickable signposts; the company is worked in over there. */}
|
||||
{foreignCompanies.length > 0 && (
|
||||
<div className="border-t border-border/40 mt-1 pt-1 px-1">
|
||||
<p className="px-2.5 pt-1 pb-0.5 text-[10px] font-semibold text-muted-foreground/60 uppercase tracking-[0.08em]">
|
||||
{t('managed_elsewhere')}
|
||||
</p>
|
||||
{foreignCompanies.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="px-2.5 py-1.5 text-[12px] leading-snug text-muted-foreground/60"
|
||||
aria-disabled="true"
|
||||
>
|
||||
<span className="block truncate">{entry.name}</span>
|
||||
<span className="block truncate text-[10px]">
|
||||
{t('managed_via', { domain: entry.domain })}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isSandbox && (
|
||||
<div className={cn((companies.length > 0 || foreignCompanies.length > 0) && 'border-t border-border/40 mt-1 pt-1', 'px-1')}>
|
||||
<Link
|
||||
href="/select-company?choose=1"
|
||||
onClick={() => setOpen(false)}
|
||||
className="flex items-center gap-2 px-2.5 py-2 text-[13px] text-muted-foreground hover:text-foreground hover:bg-muted/40 rounded-sm transition-colors md:whitespace-nowrap"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
{t('add_company')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { performCompanySwitch } from '@/lib/company/switch-client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
TAB_SYNC_CHANNEL,
|
||||
TAB_SYNC_STORAGE_KEY,
|
||||
decodeStorageValue,
|
||||
guardStore,
|
||||
isTabMismatch,
|
||||
requestHasNextActionHeader,
|
||||
resolveObservedCompanyName,
|
||||
shouldBlockMutation,
|
||||
} from '@/lib/company/tab-guard'
|
||||
|
||||
/**
|
||||
* CompanyTabSync: the cross-tab active-company TAB GUARD (WL-09).
|
||||
*
|
||||
* The active company is one user_preferences row per user shared across
|
||||
* every tab, so a switch in one tab silently re-anchors every other tab's
|
||||
* writes to the new company. Each tab remembers the company it is rendering
|
||||
* (server-rendered active company at mount). Three detection layers:
|
||||
*
|
||||
* 1. BroadcastChannel('gnubok-company-switch'): live cross-tab signal;
|
||||
* the switch action (lib/company/switch-client) broadcasts.
|
||||
* 2. `storage` events on the gnubok-active-company key: fallback where
|
||||
* BroadcastChannel is unavailable; the switch action writes the key.
|
||||
* 3. visibilitychange + pageshow(persisted): tabs hidden/bfcache-frozen
|
||||
* during the switch verify against /api/company/current on focus.
|
||||
*
|
||||
* On mismatch the tab BLOCKS with a dialog whose only exits are switching
|
||||
* back to this tab's company or reloading as the new one. Deliberately no
|
||||
* continue-anyway: continuing would post into the wrong company's books
|
||||
* (WL-09 resolution; this is not the soft-guard pattern).
|
||||
*
|
||||
* Mutations are guarded too: window.fetch is wrapped while mounted, and a
|
||||
* mutating same-origin request from a tab that KNOWS the active company
|
||||
* changed is refused with a synthetic 409 before it leaves the tab (covers
|
||||
* autosaves and other background writes racing the dialog). Two shapes:
|
||||
*
|
||||
* - /api requests get the canonical JSON error envelope.
|
||||
* - server-action POSTs (identified by the `next-action` header; verified
|
||||
* to pass through the patched window.fetch on [email protected]) get a
|
||||
* text/plain 409, which the flight client surfaces as the thrown action
|
||||
* error. The sanctioned company-switch action passes through
|
||||
* (guardStore.companySwitchInFlight): it is both dialog exits.
|
||||
*
|
||||
* Browser-direct Supabase calls go to the Supabase origin and stay outside
|
||||
* this seam; their write sites call guardBrowserWrite() (lib/company/
|
||||
* tab-guard.ts), which consults the same guardStore.
|
||||
*
|
||||
* No-op when the user has no active company.
|
||||
*/
|
||||
|
||||
// Guard state is the shared guardStore in lib/company/tab-guard.ts so
|
||||
// browser-direct write sites can consult the same belief. Single dashboard
|
||||
// shell = single writer (this component).
|
||||
|
||||
let originalFetch: typeof window.fetch | null = null
|
||||
|
||||
function installFetchGuard(): void {
|
||||
if (typeof window === 'undefined' || originalFetch) return
|
||||
originalFetch = window.fetch.bind(window)
|
||||
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const method =
|
||||
init?.method ?? (input instanceof Request ? input.method : undefined)
|
||||
const url =
|
||||
typeof input === 'string'
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: input.url
|
||||
const isServerAction = requestHasNextActionHeader(input, init)
|
||||
if (
|
||||
shouldBlockMutation({
|
||||
method,
|
||||
url,
|
||||
pageOrigin: window.location.origin,
|
||||
tabCompanyId: guardStore.tabCompanyId,
|
||||
observedCompanyId: guardStore.observedCompanyId,
|
||||
isServerAction,
|
||||
companySwitchInFlight: guardStore.companySwitchInFlight,
|
||||
})
|
||||
) {
|
||||
guardStore.notifyBlocked?.()
|
||||
if (isServerAction) {
|
||||
// The flight client treats a non-RSC response as a failed action and
|
||||
// surfaces a text/plain >=400 body as the thrown error's message.
|
||||
return Promise.resolve(
|
||||
new Response('Aktivt företag har bytts i en annan flik.', {
|
||||
status: 409,
|
||||
headers: { 'Content-Type': 'text/plain' },
|
||||
}),
|
||||
)
|
||||
}
|
||||
return Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
code: 'ACTIVE_COMPANY_CHANGED',
|
||||
message: 'Aktivt företag har bytts i en annan flik.',
|
||||
message_en: 'The active company was switched in another tab.',
|
||||
},
|
||||
}),
|
||||
{ status: 409, headers: { 'Content-Type': 'application/json' } },
|
||||
),
|
||||
)
|
||||
}
|
||||
return originalFetch!(input as RequestInfo, init)
|
||||
}) as typeof window.fetch
|
||||
}
|
||||
|
||||
function uninstallFetchGuard(): void {
|
||||
if (typeof window === 'undefined' || !originalFetch) return
|
||||
window.fetch = originalFetch
|
||||
originalFetch = null
|
||||
}
|
||||
|
||||
export default function CompanyTabSync() {
|
||||
const { company, companies, foreignCompanies } = useCompany()
|
||||
const t = useTranslations('company_tab_guard')
|
||||
const currentCompanyId = company?.id ?? null
|
||||
const [mismatch, setMismatch] = useState(false)
|
||||
// The company the other tab switched to, so the dialog can name it: the
|
||||
// choice between "switch back" and "reload as the new one" is only obvious
|
||||
// when both sides are named. Read from the guard store at the moment the
|
||||
// dialog is raised (both the observe path and the blocked-write path set
|
||||
// observedCompanyId first).
|
||||
const [observedCompanyId, setObservedCompanyId] = useState<string | null>(null)
|
||||
const [resolving, setResolving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentCompanyId) return
|
||||
|
||||
guardStore.tabCompanyId = currentCompanyId
|
||||
guardStore.observedCompanyId = null
|
||||
guardStore.notifyBlocked = () => {
|
||||
// A self-initiated switch is hard-navigating this tab away: blocked
|
||||
// stray writes still get their 409, but the "switched in another tab"
|
||||
// dialog would just flash over the tab's own page load.
|
||||
if (!guardStore.selfSwitchTargetId) {
|
||||
setObservedCompanyId(guardStore.observedCompanyId)
|
||||
setMismatch(true)
|
||||
}
|
||||
}
|
||||
installFetchGuard()
|
||||
|
||||
const observe = (observedId: string | null | undefined) => {
|
||||
if (observedId === null || observedId === undefined) return
|
||||
guardStore.observedCompanyId = observedId
|
||||
if (observedId === guardStore.selfSwitchTargetId) return
|
||||
if (isTabMismatch(currentCompanyId, observedId)) {
|
||||
setObservedCompanyId(observedId)
|
||||
setMismatch(true)
|
||||
}
|
||||
}
|
||||
|
||||
// Layer 1: BroadcastChannel: live cross-tab sync
|
||||
let channel: BroadcastChannel | null = null
|
||||
if (typeof BroadcastChannel !== 'undefined') {
|
||||
channel = new BroadcastChannel(TAB_SYNC_CHANNEL)
|
||||
channel.onmessage = (event: MessageEvent<{ companyId: string | null }>) => {
|
||||
observe(event.data?.companyId ?? null)
|
||||
}
|
||||
}
|
||||
|
||||
// Layer 1b: storage-event fallback (fires in every OTHER tab)
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if (event.key !== TAB_SYNC_STORAGE_KEY) return
|
||||
observe(decodeStorageValue(event.newValue))
|
||||
}
|
||||
window.addEventListener('storage', handleStorage)
|
||||
|
||||
// Layer 2: on focus, verify against the server
|
||||
const checkServer = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/company/current', {
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin',
|
||||
})
|
||||
if (!res.ok) return
|
||||
const data = (await res.json()) as { companyId: string | null }
|
||||
observe(data.companyId)
|
||||
} catch {
|
||||
// Network error / offline: do nothing (don't false-positive the guard)
|
||||
}
|
||||
}
|
||||
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void checkServer()
|
||||
}
|
||||
}
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange)
|
||||
|
||||
// Layer 3: pageshow (persisted === true): bfcache restore
|
||||
const handlePageShow = (event: PageTransitionEvent) => {
|
||||
if (event.persisted) {
|
||||
// A bfcache-restored page renders the OLD company after this tab's
|
||||
// own switch (back-navigation): the self-switch marker must not keep
|
||||
// suppressing the dialog here.
|
||||
guardStore.selfSwitchTargetId = null
|
||||
void checkServer()
|
||||
}
|
||||
}
|
||||
window.addEventListener('pageshow', handlePageShow)
|
||||
|
||||
return () => {
|
||||
channel?.close()
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
window.removeEventListener('pageshow', handlePageShow)
|
||||
guardStore.tabCompanyId = null
|
||||
guardStore.observedCompanyId = null
|
||||
guardStore.notifyBlocked = null
|
||||
guardStore.selfSwitchTargetId = null
|
||||
uninstallFetchGuard()
|
||||
}
|
||||
}, [currentCompanyId])
|
||||
|
||||
if (!mismatch || !currentCompanyId) return null
|
||||
|
||||
const newCompanyName = resolveObservedCompanyName(
|
||||
observedCompanyId,
|
||||
companies,
|
||||
foreignCompanies ?? [],
|
||||
)
|
||||
|
||||
const handleSwitchBack = async () => {
|
||||
setResolving(true)
|
||||
// Re-activate THIS tab's company and reload the page we are on (same
|
||||
// company, so its data is still valid). Other tabs get the broadcast and
|
||||
// face the same dialog: the hazard is symmetric by design.
|
||||
const result = await performCompanySwitch(currentCompanyId, {
|
||||
destination: window.location.pathname + window.location.search,
|
||||
})
|
||||
if (result?.error) {
|
||||
// Membership lost or persist failure: this tab cannot win the company
|
||||
// back, so the only safe exit left is loading the new company.
|
||||
window.location.assign('/')
|
||||
}
|
||||
}
|
||||
|
||||
const handleReloadAsNew = () => {
|
||||
setResolving(true)
|
||||
// Land on the start page: the current path may not exist (or worse, mean
|
||||
// another object) under the new company.
|
||||
window.location.assign('/')
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] flex items-center justify-center p-4"
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="company-tab-guard-title"
|
||||
>
|
||||
{/* Veil: deliberately no click-to-close and no Esc: the dialog is
|
||||
blocking, its two buttons are the only exits (WL-09). */}
|
||||
<div className="absolute inset-0 bg-background/80 backdrop-blur-sm" aria-hidden="true" />
|
||||
<div className="relative w-full max-w-md rounded-lg border border-border bg-card p-6 shadow-lg">
|
||||
<h2 id="company-tab-guard-title" className="font-display text-lg leading-6">
|
||||
{t('title')}
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{newCompanyName
|
||||
? t('body_named', { company: company?.name ?? '', newCompany: newCompanyName })
|
||||
: t('body', { company: company?.name ?? '' })}
|
||||
</p>
|
||||
<div className="mt-6 flex flex-col gap-2 sm:flex-row sm:justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={resolving}
|
||||
onClick={handleReloadAsNew}
|
||||
>
|
||||
{newCompanyName
|
||||
? t('reload_as_named', { newCompany: newCompanyName })
|
||||
: t('reload_as_new')}
|
||||
</Button>
|
||||
<Button disabled={resolving} onClick={() => void handleSwitchBack()}>
|
||||
{t('switch_back', { company: company?.name ?? '' })}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { SkatteverketPromoCard } from '@/components/dashboard/SkatteverketPromoCard'
|
||||
import { AgentPromo } from '@/components/dashboard/AgentPromo'
|
||||
import type { InitialSetupState } from '@/types'
|
||||
|
||||
interface DashboardContentProps {
|
||||
companyId: string
|
||||
/** Signed-in user's first name for the greeting; null falls back to a
|
||||
* nameless greeting. */
|
||||
userFirstName?: string | null
|
||||
initialSetup: InitialSetupState
|
||||
/**
|
||||
* False until the company has a verified agent_profile. When false the hero
|
||||
* slot shows a build-assistant prompt instead of the next-best-action card,
|
||||
* so existing/migrated users are nudged to build the assistant without a
|
||||
* full-screen onboarding takeover.
|
||||
*/
|
||||
agentBuilt?: boolean
|
||||
hasSkatteverketConnected?: boolean
|
||||
/**
|
||||
* Streamed sections (server components behind Suspense in
|
||||
* app/(dashboard)/page.tsx): the notice line, the setup checklist and the
|
||||
* Att göra + Fortsätt panes. The shell renders the greeting immediately
|
||||
* and each slot fills in as its queries resolve, instead of the whole page
|
||||
* waiting for the slowest of ~30 queries.
|
||||
*/
|
||||
notices: ReactNode
|
||||
checklist: ReactNode
|
||||
panes: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Hem (concept scene 14): greeting, then the two panes side by side:
|
||||
* Att göra (obligations, lib/worklist) and Fortsätt (in-progress work,
|
||||
* lib/worklist/resume). KPI tiles, revenue/expense cards and the deadline/tax
|
||||
* widgets left the page (founder direction, dev_docs/last_session_resume.md
|
||||
* §8): the numbers live at /kpi and /reports, deadlines render as Bevaka rows.
|
||||
*/
|
||||
export default function DashboardContent({
|
||||
companyId,
|
||||
userFirstName,
|
||||
initialSetup,
|
||||
agentBuilt = true,
|
||||
hasSkatteverketConnected = false,
|
||||
notices,
|
||||
checklist,
|
||||
panes,
|
||||
}: DashboardContentProps) {
|
||||
const t = useTranslations('dashboard')
|
||||
const { company } = useCompany()
|
||||
|
||||
// Time-of-day greeting (concept: "God morgon, Jakob."). Client-side clock
|
||||
// on purpose (the user's local morning, not the server's), captured once
|
||||
// so render stays pure.
|
||||
const [greetingNow] = useState(() => new Date())
|
||||
const hour = greetingNow.getHours()
|
||||
const greeting =
|
||||
hour < 10 ? t('greeting_morning') : hour < 17 ? t('greeting_day') : t('greeting_evening')
|
||||
const dateLine = new Intl.DateTimeFormat('sv-SE', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
}).format(greetingNow)
|
||||
|
||||
return (
|
||||
<div className="stagger-enter space-y-8">
|
||||
{/* Degraded-state notices (lib/notices): one attn line, highest
|
||||
priority first, quiet "+N till" expander. The wrong-account hint
|
||||
participates in the same priority list instead of rendering its own
|
||||
unconditional line, and the old boxed BackupHealthBanner card lives
|
||||
on as the backup_failing category. */}
|
||||
{notices}
|
||||
|
||||
{/* Greeting hero (concept scene 14) */}
|
||||
<section>
|
||||
<h1 className="font-display text-2xl leading-8 tracking-tight">
|
||||
{userFirstName ? `${greeting}, ${userFirstName}.` : `${greeting}.`}
|
||||
</h1>
|
||||
<p className="mt-1.5 text-[13px] text-muted-foreground">
|
||||
{dateLine}
|
||||
{company?.name ? ` · ${company.name}` : ''}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{checklist}
|
||||
|
||||
{/* Build-assistant nudge: shown only until the company has a verified
|
||||
agent_profile, so existing/migrated users get a clear prompt instead
|
||||
of a full-screen onboarding takeover. While the stepped first-run
|
||||
checklist is visible it already carries the assistant as its last
|
||||
step, so the promo waits until that block is dismissed or completed. */}
|
||||
{!agentBuilt && (initialSetup.dismissedAt || initialSetup.completedAt) && (
|
||||
<AgentPromo companyId={companyId} />
|
||||
)}
|
||||
|
||||
{/* The two panes (concept hem-grid). When nothing is in progress the
|
||||
right pane renders null and Att göra takes the full width. */}
|
||||
{panes}
|
||||
|
||||
{/* Connect-Skatteverket nudge for existing companies. Gated on
|
||||
agentBuilt so it never stacks under the build-assistant hero:
|
||||
one CTA surface at a time. */}
|
||||
{agentBuilt && (
|
||||
<SkatteverketPromoCard companyId={companyId} connected={hasSkatteverketConnected} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,24 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import NoticeLines from '@/components/dashboard/NoticeLines'
|
||||
import type { Notice } from '@/lib/notices/types'
|
||||
|
||||
/**
|
||||
* Hem's notice line with the one action that needs client state: the
|
||||
* wrong-account hint signs the user out so they can come back in with their
|
||||
* other login (same flow as SandboxBanner). Rendered by the streamed notices
|
||||
* section, so the shell above it never waits for the notice detectors.
|
||||
*/
|
||||
export function HemNotices({ notices }: { notices: Notice[] }) {
|
||||
const router = useRouter()
|
||||
|
||||
async function handleSwitchAccount() {
|
||||
const supabase = createClient()
|
||||
await supabase.auth.signOut()
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
return <NoticeLines notices={notices} actionOverrides={{ other_account_hint: handleSwitchAccount }} />
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
/** Suspense fallback for the setup checklist block. */
|
||||
export function ChecklistSkeleton() {
|
||||
return (
|
||||
<div className="space-y-3 rounded-lg border border-border p-5" aria-busy="true">
|
||||
<Skeleton className="h-4 w-40" />
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="flex items-center gap-3">
|
||||
<Skeleton className="h-4 w-4 rounded-full" />
|
||||
<Skeleton className="h-4 w-64" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Suspense fallback for the Att göra + Fortsätt panes. */
|
||||
export function PanesSkeleton() {
|
||||
return (
|
||||
<div className="grid items-start gap-x-6 gap-y-8 md:grid-cols-2" aria-busy="true">
|
||||
{[0, 1].map((col) => (
|
||||
<div key={col}>
|
||||
<Skeleton className="mb-3 h-4 w-24" />
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<div key={i} className="flex items-center justify-between gap-4 border-b border-border px-1 py-3 last:border-b-0">
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-4 w-10" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ArrowUpRight, Loader2, Briefcase } from 'lucide-react'
|
||||
import { performCompanySwitch } from '@/lib/company/switch-client'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
|
||||
/**
|
||||
* The home-domain signpost (WL-01): shown instead of the dashboard when the
|
||||
* active company is homed on another domain. Never a silent redirect:
|
||||
* sessions are per domain, so the user must log in again over there, and the
|
||||
* signpost explains why. Companies homed HERE are offered as one-click
|
||||
* switches; companies homed elsewhere link to their home domain.
|
||||
*/
|
||||
export default function HomeDomainSignpost({
|
||||
activeCompanyName,
|
||||
homedCompanies,
|
||||
foreignCompanies,
|
||||
}: {
|
||||
activeCompanyName: string
|
||||
homedCompanies: Array<{ id: string; name: string }>
|
||||
foreignCompanies: Array<{ id: string; name: string; domain: string }>
|
||||
}) {
|
||||
const t = useTranslations('signpost')
|
||||
const { toast } = useToast()
|
||||
const [pendingId, setPendingId] = useState<string | null>(null)
|
||||
|
||||
const handleSwitch = async (companyId: string) => {
|
||||
setPendingId(companyId)
|
||||
const result = await performCompanySwitch(companyId, { destination: '/' })
|
||||
if (result?.error) {
|
||||
setPendingId(null)
|
||||
toast({ title: t('switch_failed'), variant: 'destructive' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="stagger-enter mx-auto max-w-lg pt-12">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<div className="mb-5 flex h-12 w-12 items-center justify-center rounded-xl bg-muted/60">
|
||||
<Briefcase className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
<h1 className="font-display text-2xl leading-8 tracking-tight">
|
||||
{t('title')}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-muted-foreground text-balance">
|
||||
{t('body', { company: activeCompanyName })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{foreignCompanies.length > 0 && (
|
||||
<div className="mt-8">
|
||||
<ul className="divide-y divide-border border-y border-border">
|
||||
{foreignCompanies.map((entry) => (
|
||||
<li key={entry.id}>
|
||||
<a
|
||||
href={`https://${entry.domain}`}
|
||||
className="group flex items-center gap-3 px-1 py-3 transition-colors duration-150 hover:bg-secondary/35"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] text-foreground">
|
||||
{t('managed_via', { company: entry.name, domain: entry.domain })}
|
||||
</span>
|
||||
<ArrowUpRight className="h-4 w-4 flex-shrink-0 text-muted-foreground group-hover:text-foreground" />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-2 text-xs text-muted-foreground">{t('login_hint')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{homedCompanies.length > 0 && (
|
||||
<div className="mt-10">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('homed_here')}
|
||||
</h2>
|
||||
<ul className="mt-2 divide-y divide-border border-y border-border">
|
||||
{homedCompanies.map((entry) => (
|
||||
<li key={entry.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleSwitch(entry.id)}
|
||||
disabled={pendingId !== null}
|
||||
className="flex w-full items-center gap-3 px-1 py-3 text-left transition-colors duration-150 hover:bg-secondary/35 disabled:opacity-50"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] text-foreground">
|
||||
{entry.name}
|
||||
</span>
|
||||
{pendingId === entry.id ? (
|
||||
<Loader2 className="h-4 w-4 flex-shrink-0 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">{t('open_company')}</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { useEffect } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
/**
|
||||
* Picks the dashboard chrome container based on route. Extension workspaces
|
||||
* (/e/*) and the /chat app shell want the full viewport for their own
|
||||
* multi-pane layouts; everything else gets the centered max-w-5xl card.
|
||||
*
|
||||
* Lives in a client component because the parent (dashboard) layout is
|
||||
* shared across all dashboard routes. Server-side pathname checks done in
|
||||
* the layout don't re-evaluate reliably on soft navigation between sibling
|
||||
* routes, so the wrapper class would otherwise stick on whichever branch
|
||||
* the first render picked.
|
||||
*/
|
||||
export function MainContainer({
|
||||
companyId,
|
||||
children,
|
||||
}: {
|
||||
companyId: string | null
|
||||
children: ReactNode
|
||||
}) {
|
||||
const pathname = usePathname()
|
||||
|
||||
// The panel (<main>) is its own scroll container on desktop, so Next's
|
||||
// built-in scroll-to-top on navigation (which targets the window) never
|
||||
// fires for it. Reset the panel scroll on every route change; hash-anchor
|
||||
// scrolling still works because pages call scrollIntoView themselves.
|
||||
useEffect(() => {
|
||||
document.getElementById('main-content')?.scrollTo(0, 0)
|
||||
}, [pathname])
|
||||
|
||||
// Full-bleed routes own their own padding + multi-pane layout. They
|
||||
// shouldn't sit inside max-w-5xl or any horizontal padding: that's what
|
||||
// causes a visible gap between the dashboard sidebar and the chat-sidebar
|
||||
// pane on wide viewports.
|
||||
const isFullBleed = pathname.startsWith('/e/') || pathname.startsWith('/chat')
|
||||
|
||||
// The salary run detail page drives a wide, horizontal-flow layout (progress
|
||||
// band + 5-up KPIs + full-width employee ledger) that the standard max-w-5xl
|
||||
// column squeezes. It opts into a wider canvas — a deliberate, scoped
|
||||
// exception to the locked container token. Match only /salary/runs/{id}, not
|
||||
// its nested employee sub-pages.
|
||||
const isWide = /^\/salary\/runs\/[^/]+$/.test(pathname)
|
||||
|
||||
if (isFullBleed) {
|
||||
return <div key={companyId ?? ''} className="h-full">{children}</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={companyId ?? ''}
|
||||
className={
|
||||
isWide
|
||||
? 'max-w-7xl mx-auto px-5 py-8 md:px-8 md:py-10'
|
||||
: 'max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10'
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import Link, { type LinkProps } from 'next/link'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import { useCallback, type ComponentProps } from 'react'
|
||||
import { shouldWarmNavRoute } from './nav-prefetch'
|
||||
|
||||
type Props = Omit<ComponentProps<typeof Link>, 'prefetch'> & { href: LinkProps['href'] }
|
||||
|
||||
/**
|
||||
* Sidebar / rail / mobile nav link with hover-intent prefetching.
|
||||
*
|
||||
* Why not the default viewport prefetch: the dashboard nav renders ~45
|
||||
* links, every one of which is a dynamic route with a loading boundary, so
|
||||
* Next prefetched all of them the moment the nav mounted. Each prefetch is
|
||||
* a full request through the auth proxy (Supabase Auth round trip, the
|
||||
* active-company RPC, the MFA check) whose only payload is the shared
|
||||
* loading skeleton. Prod logs showed 1,000 to 1,300 such hits per nav route
|
||||
* per day. Warming on hover/focus/touch keeps the perceived-instant click
|
||||
* for the one or two links a user is about to use and drops the other ~43.
|
||||
*
|
||||
* `prefetch={false}` also disables Link's own hover prefetch (next/link only
|
||||
* hover-prefetches when viewport prefetch is enabled), so the warm-up is an
|
||||
* explicit router.prefetch. onFocus covers keyboard users; onTouchStart
|
||||
* gives the mobile bottom nav a ~100 ms head start before the tap lands.
|
||||
*/
|
||||
export function NavLink({ href, onMouseEnter, onFocus, onTouchStart, children, ...rest }: Props) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const hrefString = typeof href === 'string' ? href : (href.pathname ?? '')
|
||||
|
||||
const warm = useCallback(() => {
|
||||
if (shouldWarmNavRoute(hrefString, pathname)) router.prefetch(hrefString)
|
||||
}, [hrefString, pathname, router])
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
prefetch={false}
|
||||
onMouseEnter={(e) => {
|
||||
warm()
|
||||
onMouseEnter?.(e)
|
||||
}}
|
||||
onFocus={(e) => {
|
||||
warm()
|
||||
onFocus?.(e)
|
||||
}}
|
||||
onTouchStart={(e) => {
|
||||
warm()
|
||||
onTouchStart?.(e)
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { useBranding } from '@/lib/branding/brand-context'
|
||||
import type { Notice, NoticeCategory } from '@/lib/notices/types'
|
||||
|
||||
interface NoticeLinesProps {
|
||||
/** Active notices in priority order (lib/notices getCompanyNotices). */
|
||||
notices: Notice[]
|
||||
/**
|
||||
* Per-category client-side action overrides: some notices need a handler
|
||||
* rather than a link (other_account_hint signs the user out).
|
||||
*/
|
||||
actionOverrides?: Partial<Record<NoticeCategory, () => void>>
|
||||
}
|
||||
|
||||
/**
|
||||
* The Hem notice slot: renders ONLY the single highest-priority active
|
||||
* notice as one AttnLine (convention 6), with a quiet "+N till" text link
|
||||
* expanding the rest inline when more are active. No boxed card, no overlay.
|
||||
*
|
||||
* Dismiss is optimistic and per user (POST /api/notices/dismiss): a failed
|
||||
* write just lets the notice reappear on the next load, which is the safe
|
||||
* direction for a health warning.
|
||||
*/
|
||||
export default function NoticeLines({ notices, actionOverrides = {} }: NoticeLinesProps) {
|
||||
const t = useTranslations('notices')
|
||||
// Brand-aware app name for messages that mention the platform (WL-12);
|
||||
// identical to the default on unbranded hosts.
|
||||
const { appName } = useBranding()
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [hiddenIds, setHiddenIds] = useState<ReadonlySet<string>>(new Set())
|
||||
|
||||
const active = notices.filter((n) => !hiddenIds.has(n.id))
|
||||
if (active.length === 0) return null
|
||||
const visible = expanded ? active : [active[0]]
|
||||
const moreCount = active.length - 1
|
||||
|
||||
function dismiss(notice: Notice) {
|
||||
setHiddenIds((prev) => new Set(prev).add(notice.id))
|
||||
// Fire-and-forget on purpose: on failure the notice simply returns on
|
||||
// the next load. Never block or error the dashboard over a dismissal.
|
||||
void fetch('/api/notices/dismiss', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notice_id: notice.id }),
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
{visible.map((notice, index) => {
|
||||
const override = actionOverrides[notice.category]
|
||||
return (
|
||||
<AttnLine
|
||||
key={notice.id}
|
||||
action={
|
||||
override
|
||||
? { label: t(notice.actionKey), onClick: override }
|
||||
: { label: t(notice.actionKey), href: notice.actionHref }
|
||||
}
|
||||
trailing={
|
||||
<>
|
||||
{index === 0 && !expanded && moreCount > 0 && (
|
||||
<>
|
||||
{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(true)}
|
||||
className="text-muted-foreground underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
{t('more_count', { count: moreCount })}
|
||||
</button>
|
||||
</>
|
||||
)}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dismiss(notice)}
|
||||
className="text-muted-foreground underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
{t('dismiss')}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{t(notice.messageKey, { appName, ...notice.messageParams })}
|
||||
</AttnLine>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { BookOpen, ChevronRight, FileText, HandCoins } from 'lucide-react'
|
||||
import type { ResumeItem } from '@/lib/worklist/resume'
|
||||
|
||||
/**
|
||||
* "Fortsätt" (concept scene 14, right pane): in-progress work you can jump
|
||||
* back into, derived purely from draft state (lib/worklist/resume). Renders
|
||||
* null when empty: never a blank-but-present card.
|
||||
*/
|
||||
export default function ResumePane({ items }: { items: ResumeItem[] }) {
|
||||
const t = useTranslations('dashboard')
|
||||
|
||||
// Captured once: render must stay pure and the labels stable per mount.
|
||||
const [nowMs] = useState(() => Date.now())
|
||||
|
||||
if (items.length === 0) return null
|
||||
|
||||
const relativeLabel = (iso: string): string => {
|
||||
const days = Math.floor((nowMs - new Date(iso).getTime()) / 86_400_000)
|
||||
if (days <= 0) return t('rel_today')
|
||||
if (days === 1) return t('rel_yesterday')
|
||||
return t('rel_days', { count: days })
|
||||
}
|
||||
|
||||
const rowFor = (item: ResumeItem) => {
|
||||
switch (item.kind) {
|
||||
case 'invoice_draft':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: t('resume_invoice_draft', { customer: item.context ?? '' }),
|
||||
sub: [
|
||||
item.amount != null ? formatCurrency(item.amount, item.currency ?? 'SEK') : null,
|
||||
t('resume_edited', { when: relativeLabel(item.updated_at) }),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
}
|
||||
case 'invoice_unsent':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: t('resume_invoice_unsent', { number: item.number ?? '' }),
|
||||
sub: [
|
||||
item.context,
|
||||
item.amount != null ? formatCurrency(item.amount, item.currency ?? 'SEK') : null,
|
||||
t('resume_edited', { when: relativeLabel(item.updated_at) }),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
}
|
||||
case 'salary_run': {
|
||||
const key =
|
||||
item.salaryStatus === 'review'
|
||||
? 'resume_salary_review'
|
||||
: item.salaryStatus === 'approved'
|
||||
? 'resume_salary_approved'
|
||||
: item.salaryStatus === 'paid'
|
||||
? 'resume_salary_paid'
|
||||
: 'resume_salary_draft'
|
||||
return {
|
||||
icon: HandCoins,
|
||||
title: t(key, { period: item.context ?? '' }),
|
||||
sub: t('resume_edited', { when: relativeLabel(item.updated_at) }),
|
||||
}
|
||||
}
|
||||
case 'journal_draft':
|
||||
default:
|
||||
return {
|
||||
icon: BookOpen,
|
||||
title: t('resume_journal_draft'),
|
||||
sub: [item.context, t('resume_edited', { when: relativeLabel(item.updated_at) })]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label={t('resume_title')}>
|
||||
{/* Pane header: Geist title over a hairline */}
|
||||
<div className="flex items-baseline justify-between border-b border-border px-1 pb-2.5">
|
||||
<h2 className="font-sans text-sm font-medium">{t('resume_title')}</h2>
|
||||
</div>
|
||||
<div>
|
||||
{items.map((item) => {
|
||||
const row = rowFor(item)
|
||||
const Icon = row.icon
|
||||
return (
|
||||
<Link
|
||||
key={item.ref}
|
||||
href={item.href}
|
||||
className="group flex w-full items-start gap-3 border-b border-border px-1 py-3.5 transition-colors duration-150 hover:bg-secondary/30"
|
||||
>
|
||||
<span className="mt-px w-[18px] shrink-0 text-muted-foreground" aria-hidden>
|
||||
<Icon className="h-[15px] w-[15px]" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13.5px]">{row.title}</span>
|
||||
{row.sub && (
|
||||
<span className="mt-0.5 block truncate text-xs text-muted-foreground">
|
||||
{row.sub}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="ml-auto flex shrink-0 items-center gap-2.5 pt-px">
|
||||
{item.late && (
|
||||
<Badge variant="warning" className="font-normal">
|
||||
{t('resume_late')}
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronRight
|
||||
className={cn(
|
||||
'h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity duration-150 group-hover:opacity-100',
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { X } from 'lucide-react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
|
||||
export function SandboxBanner() {
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
const router = useRouter()
|
||||
|
||||
if (dismissed) return null
|
||||
|
||||
async function handleCreateAccount() {
|
||||
const supabase = createClient()
|
||||
await supabase.auth.signOut()
|
||||
router.push('/register')
|
||||
}
|
||||
|
||||
// Primary-on-secondary, not a solid amber bar: the sandbox notice is
|
||||
// environment chrome, and chrome never wears the warning fill.
|
||||
return (
|
||||
<div className="relative z-50 flex items-center justify-center gap-x-3 gap-y-1 border-b border-border bg-secondary px-10 py-2 text-sm text-secondary-foreground sm:px-4 flex-wrap">
|
||||
<span className="font-medium text-center text-xs sm:text-sm">
|
||||
Sandlådemiljö: AI och externa tjänster är avstängda. Data raderas efter 24h.
|
||||
</span>
|
||||
<button
|
||||
onClick={handleCreateAccount}
|
||||
className="shrink-0 rounded-full bg-foreground/10 px-3 py-0.5 text-xs font-semibold hover:bg-foreground/15 transition-colors"
|
||||
>
|
||||
Skapa konto
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDismissed(true)}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-1 hover:bg-foreground/10 transition-colors"
|
||||
aria-label="Stäng"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useSyncExternalStore } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
import { useCapability, useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
const dismissKey = (companyId: string) => `erp_skv_promo_dismissed:${companyId}`
|
||||
// storage events only fire in OTHER tabs; this custom event covers the
|
||||
// same-tab dismissal so useSyncExternalStore re-reads localStorage.
|
||||
const DISMISS_EVENT = 'erp-skv-promo-dismissed'
|
||||
|
||||
function subscribeToDismissal(onStoreChange: () => void) {
|
||||
window.addEventListener('storage', onStoreChange)
|
||||
window.addEventListener(DISMISS_EVENT, onStoreChange)
|
||||
return () => {
|
||||
window.removeEventListener('storage', onStoreChange)
|
||||
window.removeEventListener(DISMISS_EVENT, onStoreChange)
|
||||
}
|
||||
}
|
||||
|
||||
interface SkatteverketPromoCardProps {
|
||||
companyId: string
|
||||
/** True when the active user already has a Skatteverket token. */
|
||||
connected: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Dismissible dashboard nudge for companies that have never connected
|
||||
* Skatteverket. New companies meet the connect step in NewUserChecklist;
|
||||
* this is the equivalent surface for existing companies, which otherwise
|
||||
* only discover the integration deep inside the VAT/AGI flows.
|
||||
* Shape: one quiet sentence with the connect link at the end and the same
|
||||
* "Dölj" text control the checklist uses, not a boxed card. It is an
|
||||
* optional offer, not an exception, so it stays muted rather than taking
|
||||
* the ochre .attn tone (convention 6/12: attention colour is for data and
|
||||
* real exceptions).
|
||||
* Capability-less users never see it: the paywall upsell lives where the
|
||||
* intent is (SkatteverketPanel, AGIPanel), not on the dashboard.
|
||||
* Sandbox companies never see it either: Skatteverket is one of the external
|
||||
* services the sandbox blocks outright, so the CTA would lead nowhere.
|
||||
*/
|
||||
export function SkatteverketPromoCard({ companyId, connected }: SkatteverketPromoCardProps) {
|
||||
const t = useTranslations('dashboard')
|
||||
const extensionEnabled = ENABLED_EXTENSION_IDS.has('skatteverket')
|
||||
const hasCapability = useCapability(CAPABILITY.skatteverket)
|
||||
const isSandbox = useCompanyOptional()?.isSandbox ?? false
|
||||
|
||||
// Server snapshot says dismissed: the card appears only after hydration,
|
||||
// when localStorage is readable, so server and client never disagree.
|
||||
const dismissed = useSyncExternalStore(
|
||||
subscribeToDismissal,
|
||||
() => localStorage.getItem(dismissKey(companyId)) === 'true',
|
||||
() => true
|
||||
)
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
localStorage.setItem(dismissKey(companyId), 'true')
|
||||
window.dispatchEvent(new Event(DISMISS_EVENT))
|
||||
}, [companyId])
|
||||
|
||||
if (!extensionEnabled || !hasCapability || isSandbox || connected || dismissed) return null
|
||||
|
||||
return (
|
||||
<section className="flex items-start justify-between gap-4">
|
||||
<p className="text-[12.5px] leading-5 text-muted-foreground">
|
||||
{t('skv_promo_description')}{' '}
|
||||
{/* py-3/-my-3: a 44px tap target on a link that still sits inline in
|
||||
the sentence; the negative margin keeps the line box at 20px so
|
||||
nothing shifts. */}
|
||||
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- /api route, not a Next page; the authorize endpoint 302s to Skatteverket, which the client router cannot follow */}
|
||||
<a
|
||||
href="/api/extensions/ext/skatteverket/authorize?return_to=/"
|
||||
className="inline-block -my-3 whitespace-nowrap py-3 text-foreground underline decoration-border underline-offset-4 transition-colors hover:decoration-foreground"
|
||||
>
|
||||
{t('skv_promo_cta')}
|
||||
</a>
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={dismiss}
|
||||
className="-my-3 shrink-0 py-3 text-xs text-muted-foreground underline decoration-border underline-offset-4 transition-colors hover:text-foreground"
|
||||
>
|
||||
{t('skv_promo_dismiss')}
|
||||
</button>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,91 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
dismissSystemNotice,
|
||||
isSystemNoticeDismissed,
|
||||
} from '@/components/dashboard/system-notice'
|
||||
|
||||
/**
|
||||
* setTimeout clamps anything above 2^31-1 ms to ~1 ms, so a deadline more
|
||||
* than 24.8 days out would hide the banner instantly. Wait in bounded steps
|
||||
* and re-check the clock at each step instead.
|
||||
*/
|
||||
const MAX_TIMER_MS = 2_147_483_647
|
||||
|
||||
/**
|
||||
* localStorage is a throwing property access when a browser blocks site
|
||||
* data, not just a null; read it behind a try so the dashboard never
|
||||
* crashes over a notice.
|
||||
*/
|
||||
function safeStorage(): Storage | null {
|
||||
try {
|
||||
return window.localStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Operator-set system notice, shown once per browser until the deadline.
|
||||
* Same chrome treatment as SandboxBanner: environment notice on secondary,
|
||||
* never a warning fill (status colors are data, not chrome).
|
||||
*
|
||||
* Visibility is computed in an effect so server and client markup agree at
|
||||
* hydration, and a timer hides the banner at the deadline in tabs that stay
|
||||
* open past it.
|
||||
*/
|
||||
export function SystemNoticeBanner({ until }: { until: number }) {
|
||||
const t = useTranslations('system_notice')
|
||||
const [visible, setVisible] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const tick = () => {
|
||||
if (isSystemNoticeDismissed(safeStorage(), until)) {
|
||||
setVisible(false)
|
||||
return
|
||||
}
|
||||
const msLeft = until - Date.now()
|
||||
if (msLeft <= 0) {
|
||||
setVisible(false)
|
||||
return
|
||||
}
|
||||
setVisible(true)
|
||||
timer = setTimeout(tick, Math.min(msLeft, MAX_TIMER_MS))
|
||||
}
|
||||
tick()
|
||||
return () => {
|
||||
if (timer !== undefined) clearTimeout(timer)
|
||||
}
|
||||
}, [until])
|
||||
|
||||
if (!visible) return null
|
||||
|
||||
function handleDismiss() {
|
||||
dismissSystemNotice(safeStorage(), until)
|
||||
setVisible(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="relative z-50 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-border bg-secondary py-2 pl-4 pr-12 text-sm text-secondary-foreground"
|
||||
>
|
||||
<span className="text-center text-xs font-medium sm:text-sm">{t('high_load')}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleDismiss}
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2"
|
||||
aria-label={t('dismiss')}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,33 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { shouldWarmNavRoute } from '../nav-prefetch'
|
||||
|
||||
describe('shouldWarmNavRoute', () => {
|
||||
it('warms other internal routes, ignoring query and hash', () => {
|
||||
expect(shouldWarmNavRoute('/invoices', '/transactions')).toBe(true)
|
||||
expect(shouldWarmNavRoute('/invoices?status=draft', '/transactions')).toBe(true)
|
||||
expect(shouldWarmNavRoute('/reports#top', '/transactions')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not warm the current route or non-routes', () => {
|
||||
expect(shouldWarmNavRoute('/invoices', '/invoices')).toBe(false)
|
||||
expect(shouldWarmNavRoute('/invoices?x=1', '/invoices')).toBe(false)
|
||||
expect(shouldWarmNavRoute('https://example.com', '/')).toBe(false)
|
||||
expect(shouldWarmNavRoute('//evil.example', '/')).toBe(false)
|
||||
expect(shouldWarmNavRoute('#section', '/')).toBe(false)
|
||||
})
|
||||
|
||||
it('warms when the pathname is unknown (first render)', () => {
|
||||
expect(shouldWarmNavRoute('/invoices', null)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DashboardNav uses NavLink for every link', () => {
|
||||
it('has no bare next/link usage left, so no nav link prefetches on viewport', () => {
|
||||
const source = fs.readFileSync(path.resolve(__dirname, '..', 'DashboardNav.tsx'), 'utf8')
|
||||
expect(source).not.toMatch(/from 'next\/link'/)
|
||||
expect(source).not.toMatch(/<Link[\s>]/)
|
||||
expect(source).toMatch(/<NavLink[\s>]/)
|
||||
})
|
||||
})
|
||||
@@ -1,85 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
SYSTEM_NOTICE_STORAGE_KEY,
|
||||
dismissSystemNotice,
|
||||
isSystemNoticeDismissed,
|
||||
parseSystemNoticeUntil,
|
||||
} from '../system-notice'
|
||||
|
||||
const NOW = Date.parse('2026-09-10T12:00:00+02:00')
|
||||
|
||||
function memoryStorage(initial: Record<string, string> = {}) {
|
||||
const map = new Map(Object.entries(initial))
|
||||
return {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => {
|
||||
map.set(k, v)
|
||||
},
|
||||
map,
|
||||
}
|
||||
}
|
||||
|
||||
describe('parseSystemNoticeUntil', () => {
|
||||
it('returns the deadline while it is in the future', () => {
|
||||
expect(parseSystemNoticeUntil('2026-09-10T23:00:00+02:00', NOW)).toBe(
|
||||
Date.parse('2026-09-10T23:00:00+02:00'),
|
||||
)
|
||||
expect(parseSystemNoticeUntil(' 2026-09-10T23:00:00+02:00 ', NOW)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('returns null once the deadline has passed, or at the exact instant', () => {
|
||||
expect(parseSystemNoticeUntil('2026-09-10T11:00:00+02:00', NOW)).toBeNull()
|
||||
expect(parseSystemNoticeUntil('2026-09-10T12:00:00+02:00', NOW)).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts Z and compact offsets, rejects a date-time without any offset', () => {
|
||||
expect(parseSystemNoticeUntil('2026-09-10T21:00:00Z', NOW)).toBe(
|
||||
Date.parse('2026-09-10T23:00:00+02:00'),
|
||||
)
|
||||
expect(parseSystemNoticeUntil('2026-09-10T23:00:00+0200', NOW)).toBe(
|
||||
Date.parse('2026-09-10T23:00:00+02:00'),
|
||||
)
|
||||
// Local-time parse would differ between Vercel (UTC) and a laptop.
|
||||
expect(parseSystemNoticeUntil('2026-09-10T23:00:00', NOW)).toBeNull()
|
||||
expect(parseSystemNoticeUntil('2026-09-10', NOW)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for unset, blank, or unparseable values', () => {
|
||||
expect(parseSystemNoticeUntil(undefined, NOW)).toBeNull()
|
||||
expect(parseSystemNoticeUntil(null, NOW)).toBeNull()
|
||||
expect(parseSystemNoticeUntil('', NOW)).toBeNull()
|
||||
expect(parseSystemNoticeUntil(' ', NOW)).toBeNull()
|
||||
expect(parseSystemNoticeUntil('tonight', NOW)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('dismissal', () => {
|
||||
const until = Date.parse('2026-09-10T23:00:00+02:00')
|
||||
|
||||
it('is not dismissed until the user closes it, then stays closed for that deadline', () => {
|
||||
const storage = memoryStorage()
|
||||
expect(isSystemNoticeDismissed(storage, until)).toBe(false)
|
||||
dismissSystemNotice(storage, until)
|
||||
expect(storage.map.get(SYSTEM_NOTICE_STORAGE_KEY)).toBe(String(until))
|
||||
expect(isSystemNoticeDismissed(storage, until)).toBe(true)
|
||||
})
|
||||
|
||||
it('shows a later notice again: the dismissal is keyed by deadline', () => {
|
||||
const storage = memoryStorage({ [SYSTEM_NOTICE_STORAGE_KEY]: String(until) })
|
||||
expect(isSystemNoticeDismissed(storage, until + 86_400_000)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats missing or throwing storage as not dismissed', () => {
|
||||
expect(isSystemNoticeDismissed(null, until)).toBe(false)
|
||||
const throwing = {
|
||||
getItem: () => {
|
||||
throw new Error('blocked')
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('blocked')
|
||||
},
|
||||
}
|
||||
expect(isSystemNoticeDismissed(throwing, until)).toBe(false)
|
||||
expect(() => dismissSystemNotice(throwing, until)).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -1,12 +0,0 @@
|
||||
/**
|
||||
* Whether hovering/focusing a nav link should warm its route.
|
||||
*
|
||||
* The link to the page you are already on has nothing to warm, and a
|
||||
* hash-only or external href is not a route. Pure so it can be unit tested.
|
||||
*/
|
||||
export function shouldWarmNavRoute(href: string, currentPathname: string | null): boolean {
|
||||
if (!href.startsWith('/')) return false
|
||||
if (href.startsWith('//')) return false
|
||||
const path = href.split(/[?#]/)[0]
|
||||
return path !== currentPathname
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// Strata renders for the start cards (public/startkort/*.webp). Generated
|
||||
// deterministically by strata-engine in the CRM workspace (studio/strata):
|
||||
//
|
||||
// node stratify.mjs <source> linen-clear --bg <ground> [flags] --name <out>
|
||||
//
|
||||
// Per-file source + flags, so any card can be regenerated or re-grounded:
|
||||
// venice.webp imports/venice-canal-painting/04-commons-giovanni-antonio-canal...jpg --bg #3A2118
|
||||
// sthlm.webp imports/stockholm-gamla-stan-riddarholmen-waterfront-skyline/05-web...jpg --bg #16303B
|
||||
// geese.webp imports/byt-hero/02-commons-canadiangeeseflyinginvformation-jpg.jpg --bg #2E3C58
|
||||
// stopwatch.webp imports/konsult-hero/04-flickr-stopwatch.jpg (night-clear) --bg #322416
|
||||
// ledger.webp imports/ledger/01-commons-pittsboro-merchant-business-ledger-dpla-.jpg --bg #1F2B20 --tone 0.35
|
||||
// abacus.webp imports/abacus/04-commons-abacus-of-state-department-store-jpg.jpg (right unit crop) --bg #1B2136 --tone 0.5
|
||||
//
|
||||
// The ground color is baked into the render (the gaps between bars carry it),
|
||||
// so the card background and scrims below must stay in the same hue: change
|
||||
// them together or the image edge shows a seam. Intrinsic dimensions declared
|
||||
// up front so the <img> gets width/height and avoids layout shift.
|
||||
|
||||
export const START_CARDS = {
|
||||
venice: {
|
||||
src: '/startkort/venice.webp',
|
||||
w: 2400,
|
||||
h: 1466,
|
||||
ground: '#3A2118',
|
||||
groundRgb: '58, 33, 24',
|
||||
objectPosition: 'center 42%',
|
||||
},
|
||||
sthlm: {
|
||||
src: '/startkort/sthlm.webp',
|
||||
w: 2400,
|
||||
h: 1500,
|
||||
ground: '#16303B',
|
||||
groundRgb: '22, 48, 59',
|
||||
objectPosition: 'center 32%',
|
||||
},
|
||||
geese: {
|
||||
src: '/startkort/geese.webp',
|
||||
w: 2400,
|
||||
h: 1600,
|
||||
ground: '#2E3C58',
|
||||
groundRgb: '46, 60, 88',
|
||||
objectPosition: '0 26%',
|
||||
},
|
||||
stopwatch: {
|
||||
src: '/startkort/stopwatch.webp',
|
||||
w: 2400,
|
||||
h: 1800,
|
||||
ground: '#322416',
|
||||
groundRgb: '50, 36, 22',
|
||||
objectPosition: 'center 30%',
|
||||
},
|
||||
ledger: {
|
||||
src: '/startkort/ledger.webp',
|
||||
w: 2400,
|
||||
h: 3602,
|
||||
ground: '#1F2B20',
|
||||
groundRgb: '31, 43, 32',
|
||||
objectPosition: 'center 30%',
|
||||
},
|
||||
abacus: {
|
||||
src: '/startkort/abacus.webp',
|
||||
w: 2400,
|
||||
h: 2176,
|
||||
ground: '#1B2136',
|
||||
groundRgb: '27, 33, 54',
|
||||
objectPosition: 'center 35%',
|
||||
},
|
||||
} as const
|
||||
|
||||
export type StartCardName = keyof typeof START_CARDS
|
||||
@@ -1,58 +0,0 @@
|
||||
/**
|
||||
* System notice window: a one-off, operator-set banner ("high load right
|
||||
* now") shown to every signed-in user until a fixed point in time.
|
||||
*
|
||||
* The switch is NEXT_PUBLIC_SYSTEM_NOTICE_UNTIL, an ISO timestamp with an
|
||||
* explicit offset (e.g. 2026-09-10T23:00:00+02:00). The value doubles as the
|
||||
* dismiss key: closing the banner stores the timestamp in localStorage, so a
|
||||
* later notice with a new timestamp shows once again while the old dismissal
|
||||
* stays inert. No DB read: the notice must survive the DB being unavailable.
|
||||
*/
|
||||
|
||||
export const SYSTEM_NOTICE_STORAGE_KEY = 'Accounted:system-notice-dismissed'
|
||||
|
||||
/**
|
||||
* A date-time without Z or a numeric offset is parsed as the runtime's local
|
||||
* time, which is UTC on Vercel and whatever the operator's laptop is locally.
|
||||
* Require the offset so the deadline means the same instant everywhere.
|
||||
*/
|
||||
const HAS_UTC_OFFSET = /(?:Z|[+-]\d{2}:?\d{2})$/i
|
||||
|
||||
/**
|
||||
* Parse the raw env value into an epoch ms deadline. Returns null when the
|
||||
* value is missing, has no UTC offset, is unparseable, or is already in the
|
||||
* past, so callers render nothing without a second check.
|
||||
*/
|
||||
export function parseSystemNoticeUntil(
|
||||
raw: string | undefined | null,
|
||||
now: number = Date.now(),
|
||||
): number | null {
|
||||
const trimmed = raw?.trim()
|
||||
if (!trimmed) return null
|
||||
if (!HAS_UTC_OFFSET.test(trimmed)) return null
|
||||
const until = new Date(trimmed).getTime()
|
||||
if (!Number.isFinite(until)) return null
|
||||
return until > now ? until : null
|
||||
}
|
||||
|
||||
type StorageLike = Pick<Storage, 'getItem' | 'setItem'>
|
||||
|
||||
export function isSystemNoticeDismissed(
|
||||
storage: StorageLike | null | undefined,
|
||||
until: number,
|
||||
): boolean {
|
||||
try {
|
||||
return storage?.getItem(SYSTEM_NOTICE_STORAGE_KEY) === String(until)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function dismissSystemNotice(storage: StorageLike | null | undefined, until: number): void {
|
||||
try {
|
||||
storage?.setItem(SYSTEM_NOTICE_STORAGE_KEY, String(until))
|
||||
} catch {
|
||||
// Private mode or blocked storage: the banner closes for this page
|
||||
// load and may show again next time, which is the acceptable fallback.
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user