feat(white-label): byra white-label infrastructure: brands, cockpit, home domains, branded email (#1956)

* feat(white-label): brand and team-kind foundation

- brands table: one white-label identity per byra team (unique mutable
  domain, row presence = live, email sender identity, hex color CHECKs)
- teams.kind ('personal'|'byra'): ops-only kind changes, deterministic
  ensure_user_team (personal team only), AFTER UPDATE role re-sync so a
  demoted consultant loses admin in client books immediately
- resolveBrandByHost/resolveBrandForCompany with 60s TTL cache, derived
  chrome tone and WCAG contrast gate; no brand row = default appearance

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): per-request brand theming, wordmark slot and source footer

- root layout resolves the brand from the Host header and injects a
  server-rendered style block (light + dark), font pair classes and a
  BrandProvider/useBranding context; default hosts render byte-identically
- BrandWordmark logo slot, host-aware manifest and favicon,
  images.remotePatterns for Supabase Storage logos
- curated font menu mechanism (font_key -> variable pair, preload:false
  for non-default entries)
- AGPL source-code footer link on login and public pages, both brands

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): byra team invites, member management and team billing

- team invites unfrozen behind a kind gate (byra teams only, owner/admin
  invite); members route handles multi-team membership; members/[id]
  unfrozen with last-owner protection; invite management UI in settings
- billing/status learns team-scoped grants and the settings page shows a
  read-only "part of the byra agreement" state instead of the upgrade pitch
- 30-day trial suppressed for companies created under a byra team

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): brand-aware outbound mail, auth email hook and public invoice branding

- every outbound mail is sent in the brand of the company it concerns:
  getSenderForCompany/getBaseUrlForCompany chain (verified brand domain,
  "via Accounted" fallback, canonical default) wired into invites,
  payslips, invoice deliveries and reminders
- Supabase Send Email hook endpoint (signature-verified with node:crypto,
  dormant until configured) renders auth mail per brand via redirect origin
- public invoice pages carry the company's brand mark
- snapshot suite per template class guards against wrong-brand mail

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): byra cockpit, home-domain rule and tab guard

- Klienter route: five urgency-sorted columns (company, unbooked, inbox,
  next deadline via the status engine, last booked) for byra team members,
  who land there after login on their home domain
- soft switch straight into a client and back; blocking two-exit tab
  guard against writes to the wrong active company
- client company creation admin-gated at the DB level (a created company
  is +1 on the byra invoice), bound to the byra team, no trial
- home-domain rule in the UI: switcher partitions companies by host,
  signpost page for companies homed elsewhere

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): brand-aware app name across UI strings

- 24 message keys per locale converted to the {appName} ICU parameter,
  27 call sites pass the active brand name (useBranding client-side,
  getRequestAppName server-side)
- 6 hardcoded JSX literals swept; statutory filing and API identity
  surfaces deliberately keep the Accounted name
- 34 new i18n keys for the cockpit, team invites, billing state, tab
  guard, signpost and source footer (sv/en parity verified)

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(white-label): domain glossary and decision log entries

- CONTEXT.md: the white-label ubiquitous language (brand, byra team,
  home domain, signpost, umbrella subdomain, brand color, cockpit)
- DECISIONS.md entries from the build waves

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): lean byra cockpit sidebar with company-mode back link

Byra team members now get a two-mode sidebar: on cockpit routes (/clients
and the new /byra pages) only Hem, Klienter, Automationer and Nyckeltal
show; entering a client company brings back the full company sidebar with
a pinned back-to-clients link (expanded, rail and mobile). New pages: /byra
home with client count, needs-action count and per-client urgent deadlines
reusing the fetchClientOverview aggregation, plus designed empty states for
/byra/automations and /byra/kpi. Signpost gate allows the byra routes;
non-byra users are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): cockpit shows no active company and keeps lean sidebar under settings

In cockpit mode the bottom user widget no longer shows the active company
subline or the company-switcher flyout: the cockpit sits above the
companies and clients are entered through the Klienter list. The settings
modal previously flipped the sidebar to the full company nav behind it
because the pathname becomes /settings/*; the sidebar now keeps the mode
of the surface underneath.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): keep company picker in cockpit with nothing selected

The cockpit user menu gets the company-switcher flyout back, but neutral:
the row reads "Valj bolag", no company carries the check mark or active
styling, and picking any company (including the technically-active one)
enters it with a full navigation. Company mode is unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* chore(db): renumber white-label migrations past main and add byra settings scope

Renumber 20260801100000-120000 to 20260804110000-113000: main already
carries applied versions up to 20260803231000, and Supabase branching
refuses local migrations stamped before the remote head (the repo rule
from 5932632f5: keep new versions strictly newest). Comment references
updated in the pg tests, route docs and onboarding precheck.

Also ships the byra settings scope: settings opened from the cockpit
(?ctx=byra, honored only for byra team members) show account-level
sections only (Konto, Medlemmar och roller), hide company-scoped
sections and the company kicker, and the team section is registered in
SETTINGS_SECTIONS so Medlemmar och roller renders inside the settings
window. The cockpit user menu drops Abonnemang and carries the scope on
its links; section switches preserve it.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(byra): cross-client nyckeltal view in the cockpit

Period presets and company chips in the URL, summary tiles, merged
monthly income/expense chart and a sortable per-client KPI table.
Numbers come from the existing get_kpi_report_aggregates RPC per
client (no new migrations); calendar months are the cross-client
axis since clients can have different fiscal years.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): byra self-service brand logo and app name

New Varumarke settings section (byra scope, owner/admin): logo
upload/remove and an editable app name; domain stays read-only.
brands has no write RLS by design, so writes go through
/api/byra/brand routes with the service client behind an explicit
owner/admin team check. Files land in logos/byra/{teamId}/. The
expanded sidebar shows the brand app name beside the logo.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): route root layout through the shared brand resolver

app/layout.tsx carried a private copy of resolveRequestBrand, so it
and lib/branding/request-brand.ts could drift. The layout now uses
the shared function, which also gains a BRAND_DEV_DOMAIN override:
on literal localhost hosts only, resolve that brand so branding is
testable in local dev. Real domains are unaffected even if the
variable leaks into a deployment.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(byra): automations roadmap teaser and cockpit i18n strings

The Automationer tab now previews the planned automation set
(Monday briefing, deadline watch, rule-driven bookkeeping,
connection watch, monthly checklist, report delivery) instead of a
bare empty state. Bundles the sv/en strings for the whole cockpit
wave (nyckeltal, varumarke, automations) and the decision-log
entries.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): byra owners/admins land in the cockpit, not an auto-picked company

After login "/" resolved the first-membership fallback and opened a client
company nobody chose, and the top-left brand mark always linked back to it.
Byra owners/admins now home to /byra: the logo links there always, and "/"
redirects there unless a company was explicitly picked this browser session.

The middleware writes the fallback company back to user_preferences, so the
DB cannot tell picked from auto-picked; setActiveCompany stamps a session
cookie (gnubok-company-picked) on every explicit switch instead. The byra
check on "/" reuses the layout's team_members query via a request-cached
helper, so it costs no extra round trip. Byra members and regular users are
unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor(white-label): drop brand color theming, keep monochrome everywhere

White-label is logo + app name + domain only (founder call): the
layout no longer injects brand color CSS variables, stamps
data-brand or colors the browser chrome. buildBrandVarsCss, its
WCAG gate and the brand_color/chrome_color columns stay dormant
for a future opt-in.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(db): arm SIE RPC statement_timeout via pgrst.db_pre_request hook

ALTER FUNCTION ... SET statement_timeout (20260629160100, 20260721144311)
never re-arms the running statement's timer, so large SIE imports still
died at the role default 8s. The pre-request hook runs as its own
statement before the main query, so set_config there is what the main
statement's timer is armed with. Scoped by request path to the three SIE
RPCs; every other request keeps 8s.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(byra): drop the 'what's coming' tail from the automations intro

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): byra owners/admins with zero companies land in the empty cockpit

Both no-company gates (Edge middleware and the dashboard layout) sent
every company-less user to the onboarding wizard, which forced a fresh
byra owner to create a personal company before ever seeing the cockpit.
Byra owners/admins now pass through to cockpit routes (/byra, /clients,
/companies/new, /settings, /api) and are steered to /byra elsewhere.
Plain byra members and regular users keep the onboarding redirect.
The membership lookup runs only in the rare no-company state, so the
middleware hot path is untouched.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): auth wordmark shows the brand logo alone

Byra logos usually carry their own name, so logo + app name text on the
login/register hero read as a duplicate. Branded hosts with an uploaded
logo now render the logo only, with the app name as the image's alt
text. Hosts without a logo keep the text wordmark unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): per-brand favicon via brands.favicon_url

Branded hosts used logo_url as the tab icon, which squashes wide byra
lockups at 16px. New optional brands.favicon_url holds a square mark;
the root layout prefers it and falls back to logo_url as before.
Migration applied to staging (idempotent DDL).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(auth): wire the villkor and integritetspolicy footer links

Both auth pages shipped with href="#" placeholders. Villkor now points
at the platform terms on the marketing site (accounted.se/terms; the
terms are the platform's even on branded byra hosts) and
integritetspolicy at the in-app /privacy page, host-relative so it
resolves on every branded domain. Both open in a new tab so the auth
form state survives.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): styled popup for the team role dropdowns

The byra team panel's role pickers (member rows + invite form) were
native selects, so the opened list rendered as the unstylable OS menu.
Swapped to the Radix Select with the popup styled like every other
overlay; the trigger keeps the flat quiet SettingsSelect look.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(email): branded sender shows the brand name alone, no via-platform

Byra invite mail read "Willem via Accounted" in the From display name.
The tier-2 fallback (brand on the platform address) now renders just the
brand name; the platform stays visible in the actual From address until
the brand verifies its own sender domain (tier 1, unchanged).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): byra landing applies to every team member, not only owners/admins

An invited byra consultant (role member) still landed in an auto-picked
client company after signup. The cockpit landing rules ("/" redirect,
brand-mark home link, and both no-company gates) now key on byra team
MEMBERSHIP instead of the owner/admin role: anyone with cockpit access
homes to /byra. Regular users unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(email): branded team invite names the byra, not "ett team pa <platform>"

Subject, headline, body and text variant now read "Du har blivit
inbjuden till <Byra>" (brand casing kept) when the team has a brand.
Brandless teams keep the platform phrasing byte-identical.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): sidebar keeps cockpit mode after refresh on settings

The sidebar's cockpit/company decision on /settings/* rested on React
state remembering the surface underneath, which a hard reload wipes: a
byra user refreshing settings opened from the cockpit got the full
company nav and read it as landing in a client company. The ?ctx=byra
marker already in the URL survives reloads, so the sidebar now honors
it as the cockpit signal alongside the in-session memory.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): hide the active-company chip in byra-scoped settings

The full-page settings header (the hard-refresh fallback surface) showed
the ActiveCompanyBadge even under ?ctx=byra, so a byra user read the
auto-active client as "the company I am in". The chip now follows the
same byra-scope rule as the modal's kicker.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): tab guard no longer fires in the tab that initiated the switch

BroadcastChannel delivers the company-switch broadcast to every listener in
the same tab too, so the cockpit tab raised its own WL-09 "switched in
another tab" dialog over the hard navigation into the clicked client.
performCompanySwitch now marks the switch as self-initiated; CompanyTabSync
suppresses only the dialog for that observation (stray writes still get
their 409) and clears the marker on bfcache restore so back-navigation
regains the full guard.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(settings): styled popups for every settings dropdown

SettingsSelect rendered a native <select>, whose OS listbox cannot be
styled and clashes with the panel (same problem the team-panel role
dropdowns had). It now renders through Radix Select with the flat
dashed-underline trigger, keeping the native prop surface so all 13 call
sites work unchanged: value/defaultValue, onChange(e.target.value),
<option> children, and a hidden input that carries `name` into
SettingsFormWrapper's FormData read and raises the bubbling input event
its dirty tracking listens for. Empty-string option values map onto a
sentinel at the Radix boundary. The backup form's boxed fiscal-year
select moves to the shadcn Select with a placeholder.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): home-domain affinity redirect in middleware

Every signed-in user now homes on a domain: byra team members on their
brand's domain, everyone else on the platform app URL, except a byra's
client users, whose home is the byra domain their companies live under.
On any other product host the request redirects to the home domain's
root, where the user meets the RIGHT branded login (sessions are
per-domain by design). localhost, direct *.vercel.app hosts and IP
hosts are exempt; a 15-minute host-scoped cookie caches the "this is
home" verdict so the hot path costs zero extra queries; lookup failures
fail open. Complements the WL-01 signpost, which keeps handling
per-company homing inside a domain.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): render hero brand logo at 64px on auth pages

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(white-label): shareable invite link and re-send for byra team invites

A failed invite mail previously surfaced only as a toast description while
the invitation quietly waited for a mail that never arrived (the Arbore
case). The inviter now always has a recovery path:

- persistent share-link line after invite create/re-send: ochre attn line
  with a copy action when the mail did not go out, quiet muted line with
  the same action when it did
- POST /api/team/invite/[id] re-sends a pending invitation with a fresh
  token and expiry (same byra-only owner/admin gates as DELETE)
- brand mail sending extracted to lib/email/send-team-invite.ts, shared
  by create and re-send so the two paths cannot drift

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): sidebar shows uploaded brand logo alone, no app-name label

Byra logos usually carry their own name, so logo + text in the expanded
sidebar read as a duplicate (same founder call as BrandWordmark,
2026-08-05). The app-name label now renders only for branded hosts
without an uploaded logo.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): close the four skeptic refutations before merge

- trial seed: migration 130300 now carries the seven-key PAID body from
  20260818170000 plus the byra guard, instead of silently reverting it;
  pg test pins the full key set against PAID_CAPABILITIES
- byra gate: new migration 130600 adds the owner/admin gate to
  create_company_for_user (v1 API + MCP path), and both surfaces resolve
  the default team personal-only, so a consultant's private company can
  never attach to the byra team
- home-domain: byra staff who also have canonical-homed companies are no
  longer redirected off the platform host; the signpost handles per-company
  homing (5 new middleware tests)
- settings selects: the Radix popup renders optgroup group headers again
  (ROT/RUT work-type picker)

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(schema): re-baseline unresolvable-expression ceiling after #1954 catch-up merge

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(white-label): pg-real rollback-safe assertions and deep-link-preserving affinity redirect

The byra company-creation pg test asserted persisted rows through the pool
after withUserContext, which always rolls back its transaction; the
assertions now run inside the transaction after RESET ROLE. The home-domain
affinity redirect carries the original path and query across the domain hop
(PR Agent finding), so invite links and deep links survive the correction.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Mattsson
2026-08-26 16:56:39 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 6f0f4d1eea
commit fdb5f6f891
160 changed files with 15125 additions and 504 deletions
+44
View File
@@ -0,0 +1,44 @@
# Accounted
Swedish accounting SaaS: double-entry bookkeeping under Bokföringslagen for sole traders and limited companies, sold directly and (from 2026) resold white-label by accounting firms under their own brand.
## Language
### White label
**Brand**:
The host-resolved white-label identity: one row per partner domain carrying app name, logo, palette, font, and email sender identity. Owned by a byrå team; a request's Host header resolves to at most one brand, and no match means the default Accounted appearance.
_Avoid_: Tenant (already means company-level multi-tenancy here), theme, skin
**Byrå team**:
A team that represents an accounting firm: named, multi-member, invitable, the anchor for brand ownership, client companies, and billing.
_Avoid_: Agency, firm team
**Personal team**:
The silent auto-created team every user gets (`ensure_user_team()`); an implementation detail of company ownership, never a byrå.
**Partner**:
Prose word for the commercial relationship: a byrå with an agreement and usually a brand. Not an entity in the schema.
**Canonical domain**:
app.accounted.se (and legacy app.gnubok.se): the domains carrying the default Accounted brand, external OAuth flows, and cron entry points.
**Home domain**:
The one domain a company is opened and worked in: its byrå's brand domain if the company's team has a brand, else the canonical domain. Everywhere else the UI shows a signpost to the home domain, never the company. A navigation rule, not a security boundary: access is still governed solely by company membership and RLS.
**Signpost**:
The screen shown when a logged-in user's company lives on a different host ("Kalles Bygg AB hanteras via app.siffra.se"), with a link there. Never a silent redirect: sessions are per domain, so the user must log in again on the home domain.
**Umbrella subdomain**:
A brand domain hosted under our own zone (siffra.accounted.se): the starter shape, zero partner DNS work. A custom domain (app.siffra.se) is the upgrade; the brand model treats both as the same single hostname.
**Invoice branding**:
The per-company logo and colors printed on that company's customer invoices. Unrelated to a byrå brand; never shorten to "branding".
_Avoid_: Branding (unqualified)
**Brand color**:
The single partner-supplied color a brand is themed from: primary buttons, focus rings, links, and active nav take it directly; the chrome (frame and sidebar) is derived from it unless the partner explicitly overrides the chrome color. Semantic colors (success, warning, destructive) never follow it.
**Cockpit**:
The byrå dashboard: the read-first client overview for byrå staff, aggregating status across all client companies. Acting on a client happens inside the client after a switch (or via the agent path); the cockpit itself never writes to client books.
_Avoid_: Byrå portal, partner dashboard
+22
View File
File diff suppressed because one or more lines are too long
+29 -5
View File
@@ -25,9 +25,11 @@ import {
import { BrandWordmark } from '@/components/branding/BrandWordmark'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { isBankIdEnabled } from '@/lib/auth/bankid-flags'
import { getBranding } from '@/lib/branding/service'
import { useBranding } from '@/lib/branding/brand-context'
import { SourceCodeFooter } from '@/components/branding/SourceCodeFooter'
import { detectWebmailHint } from '@/lib/auth/webmail-search'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import { resolvePostLoginDestination } from '@/lib/company/post-login-landing'
import {
consumeInviteCookie,
INVITE_PROBLEM_MESSAGE_KEYS,
@@ -53,7 +55,6 @@ import {
type SessionTimeoutReason,
} from '@/lib/auth/session-timeout-shared'
const branding = getBranding()
import type { BankIdResult } from '@/components/auth/BankIdAuth'
const BankIdAuth = dynamic(
@@ -111,6 +112,9 @@ export function LoginClient({ initialMethod }: { initialMethod: LoginMethod | nu
const registerHref = nextPath === '/' ? '/register' : `/register?next=${encodeURIComponent(nextPath)}`
const supabase = createClient()
const bankIdEnabled = isBankIdEnabled()
// Per-request brand merged over getBranding() defaults (WL-12): identical
// values on default hosts, brand values on branded hosts.
const branding = useBranding()
const googleAuthEnabled = isGoogleAuthEnabled()
const tAuth = useTranslations('auth')
const tCommon = useTranslations('common')
@@ -330,7 +334,10 @@ export function LoginClient({ initialMethod }: { initialMethod: LoginMethod | nu
return
}
router.push('/')
// Byrå staff land in the cockpit on their byrå's home domain (WL-14);
// everyone else resolves to '/' and keeps today's flow byte-identically
// (any failure inside the helper also degrades to '/').
router.push(await resolvePostLoginDestination())
router.refresh()
} catch (error) {
setFormError({
@@ -784,15 +791,32 @@ export function LoginClient({ initialMethod }: { initialMethod: LoginMethod | nu
<p className="mt-3 text-center text-xs text-muted-foreground/80 leading-relaxed">
{tAuth('terms_prefix')}{' '}
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
{/* The platform's terms live on the marketing site; the privacy
policy is the in-app /privacy page (host-relative, so it works
on branded byrå domains too). New tab: don't lose login state. */}
<a
href="https://accounted.se/terms"
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-foreground transition-colors"
>
{tAuth('terms_link')}
</a>{' '}
{tAuth('terms_and')}{' '}
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
<a
href="/privacy"
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-foreground transition-colors"
>
{tAuth('privacy_link')}
</a>
.
</p>
{/* AGPL section 13 source offer (WL-06): renders on both default and
branded hosts; never gate this on a brand. */}
<SourceCodeFooter className="mt-4" />
</div>
</div>
)
+7 -1
View File
@@ -11,6 +11,7 @@ import { useToast } from '@/components/ui/use-toast'
import { Loader2, ShieldCheck, LogOut } from 'lucide-react'
import { SupportLink } from '@/components/ui/support-link'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import { resolvePostLoginDestination } from '@/lib/company/post-login-landing'
import {
consumeInviteCookie,
INVITE_PROBLEM_MESSAGE_KEYS,
@@ -151,7 +152,12 @@ function MfaVerifyContent() {
return
}
router.push(returnTo)
// Hosted byrå staff hit MFA before any dashboard, so the cockpit
// landing (WL-14) resolves here too: only when no explicit step-up
// destination was requested. Everyone else keeps returnTo/'/' exactly
// as before (the helper degrades to '/' on any failure). The session
// is AAL2 at this point, so the /api MFA gate passes.
router.push(returnTo === '/' ? await resolvePostLoginDestination() : returnTo)
router.refresh()
} catch {
toast({
+18 -5
View File
@@ -16,7 +16,7 @@ import { BrandWordmark } from '@/components/branding/BrandWordmark'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { isBankIdEnabled } from '@/lib/auth/bankid-flags'
import type { BankIdResult } from '@/components/auth/BankIdAuth'
import { getBranding } from '@/lib/branding/service'
import { useBranding } from '@/lib/branding/brand-context'
import { detectWebmailHint } from '@/lib/auth/webmail-search'
import {
consumeInviteCookie,
@@ -39,8 +39,6 @@ import { persistLoginMethodHint, type LoginMethod } from '@/lib/auth/login-metho
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import { cn } from '@/lib/utils'
const branding = getBranding()
const BankIdAuth = dynamic(
() => import('@/components/auth/BankIdAuth').then((module) => module.BankIdAuth),
{ ssr: false },
@@ -99,6 +97,9 @@ function RegisterPageContent() {
const router = useRouter()
const supabase = createClient()
const bankIdEnabled = isBankIdEnabled()
// Per-request brand merged over getBranding() defaults (WL-12): identical
// values on default hosts, brand values on branded hosts.
const branding = useBranding()
const googleAuthEnabled = isGoogleAuthEnabled()
const t = useTranslations('register')
const tAuth = useTranslations('auth')
@@ -861,11 +862,23 @@ function RegisterPageContent() {
<p className="mt-3 text-center text-xs text-muted-foreground/80 leading-relaxed">
{t('terms_prefix')}{' '}
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
{/* Same targets as the login page: platform terms on the marketing
site, in-app /privacy (host-relative for branded domains). */}
<a
href="https://accounted.se/terms"
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-foreground transition-colors"
>
{t('terms_link')}
</a>{' '}
{t('terms_and')}{' '}
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
<a
href="/privacy"
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-foreground transition-colors"
>
{t('privacy_link')}
</a>
.
+60
View File
@@ -0,0 +1,60 @@
import { redirect } from 'next/navigation'
import { getTranslations } from 'next-intl/server'
import { BellRing, ListChecks, Mail, PlugZap, Send, Wand2 } from 'lucide-react'
import { PageHeader } from '@/components/ui/page-header'
import { getByraMembership } from '@/lib/clients/fetch-client-overview'
import { getDashboardAuthContext } from '../../request-context'
export const dynamic = 'force-dynamic'
/**
* Byrå cockpit: Automationer. Nothing is buildable yet; instead of a bare
* empty state the page shows the planned automation set (the byrå-tools
* research shortlist) so the surface sells the roadmap. All static: no
* per-card chips (same state on every card = no chip, design rule 5), one
* intro line carries the "coming" message.
*/
const CARDS = [
{ key: 'digest', icon: Mail },
{ key: 'deadlines', icon: BellRing },
{ key: 'rules', icon: Wand2 },
{ key: 'connections', icon: PlugZap },
{ key: 'checklist', icon: ListChecks },
{ key: 'reports', icon: Send },
] as const
export default async function ByraAutomationsPage() {
const { supabase, user } = await getDashboardAuthContext()
if (!user) {
redirect('/login')
}
const membership = await getByraMembership(supabase, user.id)
if (!membership) {
redirect('/')
}
const t = await getTranslations('byra')
return (
<div className="space-y-8">
<PageHeader title={t('automations_title')} />
<p className="max-w-2xl text-sm text-muted-foreground">{t('automations_intro')}</p>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 stagger-enter">
{CARDS.map(({ key, icon: Icon }) => (
<div key={key} className="rounded-lg border border-border p-6">
<Icon className="h-4 w-4 text-muted-foreground" />
<h2 className="mt-3 text-sm font-medium">{t(`automations_card_${key}_title`)}</h2>
<p className="mt-1 text-[13px] leading-5 text-muted-foreground">
{t(`automations_card_${key}_desc`)}
</p>
</div>
))}
</div>
<p className="text-[13px] text-muted-foreground">{t('automations_footer')}</p>
</div>
)
}
+65
View File
@@ -0,0 +1,65 @@
import { redirect } from 'next/navigation'
import { getTranslations } from 'next-intl/server'
import { TrendingUp } from 'lucide-react'
import { PageHeader } from '@/components/ui/page-header'
import { EmptyState } from '@/components/ui/empty-state'
import { fetchByraKpiOverview } from '@/lib/byra/kpi-overview'
import ByraKpiView from '@/components/byra/ByraKpiView'
import { getDashboardAuthContext } from '../../request-context'
export const dynamic = 'force-dynamic'
/**
* Byrå cockpit: Nyckeltal (WL-16). Aggregated cross-client KPI view: period
* preset + company chips in the URL (shareable, server-refetched), summary
* tiles, merged monthly chart, and a sortable per-client table. Byrå team
* members only, like the rest of the cockpit.
*/
export default async function ByraKpiPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
const { supabase, user } = await getDashboardAuthContext()
if (!user) {
redirect('/login')
}
const params = await searchParams
const period = typeof params.period === 'string' ? params.period : undefined
const companiesParam = typeof params.companies === 'string' ? params.companies : undefined
const companyIds = companiesParam
? companiesParam.split(',').filter((id) => id.length > 0)
: undefined
const overview = await fetchByraKpiOverview(supabase, user.id, {
preset: period,
companyIds,
})
if (!overview) {
redirect('/')
}
const t = await getTranslations('byra')
return (
<div className="space-y-8">
<PageHeader title={t('kpi_title')} />
{overview.allClients.length === 0 ? (
<EmptyState
icon={TrendingUp}
title={t('kpi_empty_title')}
description={t('kpi_empty_description')}
/>
) : (
<ByraKpiView
preset={overview.preset}
allClients={overview.allClients}
selectedIds={overview.selectedIds}
rows={overview.rows}
months={overview.months}
/>
)}
</div>
)
}
+117
View File
@@ -0,0 +1,117 @@
import { redirect } from 'next/navigation'
import { getTranslations } from 'next-intl/server'
import { PageHeader } from '@/components/ui/page-header'
import { Badge } from '@/components/ui/badge'
import { cn, formatDate } from '@/lib/utils'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { fetchClientOverview } from '@/lib/clients/fetch-client-overview'
import { getDashboardAuthContext } from '../request-context'
export const dynamic = 'force-dynamic'
/**
* Byrå cockpit home (Hem): the general overview the lean sidebar opens on.
* Aggregates the same client-overview data as /clients into a glance:
* client count, companies needing action, and the nearest deadline per
* client. Byrå team members only, like the rest of the cockpit.
*/
export default async function ByraHomePage() {
const { supabase, user } = await getDashboardAuthContext()
if (!user) {
redirect('/login')
}
const overview = await fetchClientOverview(supabase, user.id)
if (!overview) {
redirect('/')
}
const t = await getTranslations('byra')
const tClients = await getTranslations('clients')
const clients = overview.clients
const needsAction = clients.filter((c) => c.unbookedCount > 0 || c.inboxCount > 0).length
const urgentDeadlines = clients.filter(
(c) => c.nextDeadline && c.nextDeadline.urgency !== 'upcoming',
).length
// One row per client with an open deadline, most urgent first.
const urgencyRank = { overdue: 0, action_needed: 1, upcoming: 2 } as const
const deadlineRows = clients
.filter((c) => c.nextDeadline)
.sort((a, b) => {
const rank = urgencyRank[a.nextDeadline!.urgency] - urgencyRank[b.nextDeadline!.urgency]
if (rank !== 0) return rank
return a.nextDeadline!.dueDate.localeCompare(b.nextDeadline!.dueDate)
})
.slice(0, 5)
const stats = [
{ label: t('stats_clients'), value: clients.length },
{ label: t('stats_attention'), value: needsAction },
{ label: t('stats_deadlines'), value: urgentDeadlines },
]
return (
<div className="space-y-8">
<PageHeader title={overview.team.name || t('home_title')} />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
{stats.map((stat) => (
<div key={stat.label} className="rounded-lg border border-border p-4">
<div className="text-xs text-muted-foreground">{stat.label}</div>
<div className="mt-1 font-display text-xl tabular-nums">{stat.value}</div>
</div>
))}
</div>
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('deadlines_title')}
</h2>
{deadlineRows.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('deadlines_empty')}</p>
) : (
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={TH_CLASS}>{tClients('col_company')}</th>
<th className={TH_CLASS}>{tClients('col_next_deadline')}</th>
</tr>
</thead>
<tbody className="stagger-enter">
{deadlineRows.map((row) => (
<tr key={row.companyId} className="transition-colors duration-150 hover:bg-secondary/35">
<td className={cn(TD_CLASS, 'font-medium text-foreground')}>{row.name}</td>
<td className={TD_CLASS}>
<span className="flex items-center gap-2">
{row.nextDeadline!.urgency === 'overdue' && (
<Badge variant="destructive">{tClients('deadline_overdue')}</Badge>
)}
{row.nextDeadline!.urgency === 'action_needed' && (
<Badge variant="warning">{tClients('deadline_action_needed')}</Badge>
)}
<span
className={cn(
'truncate',
row.nextDeadline!.urgency === 'upcoming' && 'text-muted-foreground',
)}
>
{row.nextDeadline!.title}
</span>
<span className="text-muted-foreground tabular-nums">
{formatDate(row.nextDeadline!.dueDate)}
</span>
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
</div>
)
}
+163
View File
@@ -0,0 +1,163 @@
'use client'
import { useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Loader2, Search } from 'lucide-react'
import { cn, formatDate } from '@/lib/utils'
import { Badge } from '@/components/ui/badge'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { useToast } from '@/components/ui/use-toast'
import { performCompanySwitch } from '@/lib/company/switch-client'
import { filterClientRows, type ClientOverviewRow } from '@/lib/clients/aggregate'
/**
* The cockpit client list (WL-14): dry-table, urgency-sorted server-side,
* free-text filter client-side. Entering a client is the WL-09 soft switch:
* sets the active company and lands DIRECTLY on that company's overview via
* performCompanySwitch (one full-page load to the target, no start-page
* bounce). The way back is the Klienter nav entry, which needs no switch.
*/
export default function ClientsTable({ clients }: { clients: ClientOverviewRow[] }) {
const t = useTranslations('clients')
const { toast } = useToast()
const [query, setQuery] = useState('')
const [pendingId, setPendingId] = useState<string | null>(null)
const rows = useMemo(() => filterClientRows(clients, query), [clients, query])
const handleEnter = async (companyId: string) => {
if (pendingId) return
setPendingId(companyId)
const result = await performCompanySwitch(companyId, { destination: '/' })
if (result?.error) {
setPendingId(null)
toast({ title: t('enter_failed'), variant: 'destructive' })
}
}
if (clients.length === 0) {
return (
<p className="text-sm text-muted-foreground">{t('empty')}</p>
)
}
return (
<div className="space-y-4">
<div className="flex items-center gap-2 max-w-xs rounded-lg border border-border px-3 py-2">
<Search className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('filter_placeholder')}
aria-label={t('filter_placeholder')}
className="w-full bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"
/>
</div>
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={TH_CLASS}>{t('col_company')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('col_unbooked')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('col_inbox')}</th>
<th className={TH_CLASS}>{t('col_next_deadline')}</th>
<th className={TH_CLASS}>{t('col_last_booked')}</th>
</tr>
</thead>
<tbody className="stagger-enter">
{rows.length === 0 && (
<tr>
<td className={cn(TD_CLASS, 'text-muted-foreground')} colSpan={5}>
{t('no_matches')}
</td>
</tr>
)}
{rows.map((row) => (
<tr
key={row.companyId}
onClick={() => void handleEnter(row.companyId)}
className={cn(
'cursor-pointer transition-colors duration-150 hover:bg-secondary/35',
pendingId && pendingId !== row.companyId && 'opacity-50',
)}
>
<td className={TD_CLASS}>
<button
type="button"
onClick={(e) => {
e.stopPropagation()
void handleEnter(row.companyId)
}}
disabled={pendingId !== null}
className="flex items-center gap-2 text-left"
>
<span className="font-medium text-foreground">{row.name}</span>
{row.orgNumber && (
<span className="text-xs text-muted-foreground tabular-nums">
{row.orgNumber}
</span>
)}
{pendingId === row.companyId && (
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
)}
</button>
</td>
<td className={cn(TD_CLASS, 'text-right tabular-nums')}>
{row.unbookedCount > 0 ? (
row.unbookedCount
) : (
<span className="text-muted-foreground">0</span>
)}
</td>
<td className={cn(TD_CLASS, 'text-right tabular-nums')}>
{row.inboxCount > 0 ? (
row.inboxCount
) : (
<span className="text-muted-foreground">0</span>
)}
</td>
<td className={TD_CLASS}>
{row.nextDeadline ? (
<span className="flex items-center gap-2">
{/* Chips mark exceptions: only overdue/action_needed
deviate; an ordinary upcoming deadline is muted text. */}
{row.nextDeadline.urgency === 'overdue' && (
<Badge variant="destructive">{t('deadline_overdue')}</Badge>
)}
{row.nextDeadline.urgency === 'action_needed' && (
<Badge variant="warning">{t('deadline_action_needed')}</Badge>
)}
<span
className={cn(
'truncate',
row.nextDeadline.urgency === 'upcoming' && 'text-muted-foreground',
)}
>
{row.nextDeadline.title}
</span>
<span className="text-muted-foreground tabular-nums">
{formatDate(row.nextDeadline.dueDate)}
</span>
</span>
) : (
<span className="text-muted-foreground">-</span>
)}
</td>
<td className={cn(TD_CLASS, 'tabular-nums')}>
{row.lastBookedDate ? (
<span className="text-muted-foreground">
{formatDate(row.lastBookedDate)}
</span>
) : (
<span className="text-muted-foreground">{t('never_booked')}</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
@@ -0,0 +1,61 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Plus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
/**
* "Nytt klientbolag" (WL-15): header primary action on the cockpit, rendered
* only for byrå owner/admin (the page checks; the create RPC enforces the
* same gate in the database). Confirm up front (design convention 10): the
* dialog states that the company is added to the byrå's agreement (+1 on the
* monthly invoice) BEFORE routing into today's company creation flow with
* the explicit byrå team binding (/companies/new-client).
*/
export default function NewClientCompanyButton() {
const t = useTranslations('clients')
const router = useRouter()
const [open, setOpen] = useState(false)
const [navigating, setNavigating] = useState(false)
return (
<>
<Button onClick={() => setOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
{t('new_client_company')}
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('new_client_company')}</DialogTitle>
<DialogDescription>{t('added_to_agreement')}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)} disabled={navigating}>
{t('cancel')}
</Button>
<Button
disabled={navigating}
onClick={() => {
setNavigating(true)
router.push('/companies/new-client')
}}
>
{t('continue')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
+42
View File
@@ -0,0 +1,42 @@
import { redirect } from 'next/navigation'
import { getTranslations } from 'next-intl/server'
import { PageHeader } from '@/components/ui/page-header'
import { fetchClientOverview } from '@/lib/clients/fetch-client-overview'
import { getDashboardAuthContext } from '../request-context'
import ClientsTable from './ClientsTable'
import NewClientCompanyButton from './NewClientCompanyButton'
export const dynamic = 'force-dynamic'
/**
* Byrå cockpit: the client list (WL-14). Five urgency-sorted columns per
* client company; byrå team members only: everyone else is redirected to the
* dashboard (the API mirrors this with 403). Read-first (WL-09): this page
* only aggregates; acting on a client happens by jumping in, which switches
* the active company.
*/
export default async function ClientsPage() {
const { supabase, user } = await getDashboardAuthContext()
if (!user) {
redirect('/login')
}
const overview = await fetchClientOverview(supabase, user.id)
if (!overview) {
// Not a byrå team member: the cockpit is byrå-exclusive in v1.
redirect('/')
}
const t = await getTranslations('clients')
const canCreate = overview.role === 'owner' || overview.role === 'admin'
return (
<div className="space-y-8">
<PageHeader
title={t('title')}
action={canCreate ? <NewClientCompanyButton /> : undefined}
/>
<ClientsTable clients={overview.clients} />
</div>
)
}
@@ -9,6 +9,7 @@ import {
sectorNameKey,
} from '@/lib/extensions/i18n'
import type { SectorSlug } from '@/lib/extensions/types'
import { getRequestAppName } from '@/lib/branding/request-brand'
import CategoryBadge from '@/components/extensions/CategoryBadge'
import { WORKSPACES } from '@/lib/extensions/_generated/workspace-map'
import { Button } from '@/components/ui/button'
@@ -27,13 +28,16 @@ export default async function ExtensionDetailPage({
const sector = getSector(sectorSlug as SectorSlug)
const t = await getTranslations('extensions')
// Some long descriptions carry the {appName} ICU parameter (WL-12 appName
// sweep); passing it unconditionally is harmless for messages without it.
const appName = await getRequestAppName()
const nameKey = extensionNameKey(definition.slug)
const descriptionKey = extensionDescriptionKey(definition.slug)
const longDescriptionKey = extensionLongDescriptionKey(definition.slug)
const extensionName = nameKey ? t(nameKey) : definition.name
const extensionDescription = descriptionKey ? t(descriptionKey) : definition.description
const extensionLongDescription = longDescriptionKey ? t(longDescriptionKey) : definition.longDescription
const extensionDescription = descriptionKey ? t(descriptionKey, { appName }) : definition.description
const extensionLongDescription = longDescriptionKey ? t(longDescriptionKey, { appName }) : definition.longDescription
const sectorLabel = (() => {
if (!sector) return sectorSlug
+14 -6
View File
@@ -6,6 +6,7 @@ import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { useLocale, useTranslations } from 'next-intl'
import { createClient } from '@/lib/supabase/client'
import { guardBrowserWrite } from '@/lib/company/tab-guard'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { DetailSection, DefRow, DefEmpty } from '@/components/ui/detail-section'
@@ -80,6 +81,9 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import type { Invoice, InvoiceItem, Customer, InvoiceStatus, InvoiceReminder, InvoiceDocumentType } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { useBranding } from '@/lib/branding/brand-context'
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
/** Minimized Peppol delivery projection from GET /api/invoices/[id]/peppol/deliveries. */
interface PeppolDeliveryView {
@@ -97,8 +101,6 @@ const PEPPOL_STATUS_KEYS = new Set([
'no_route', 'failed',
])
const PEPPOL_SENDABLE_STATUSES = new Set<InvoiceStatus>(['draft', 'sent', 'overdue'])
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
// Why the downloaded file is not the invoice the customer received. One key
// per reason: "no archived copy exists" and "the archive could not be reached"
@@ -152,6 +154,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
const { toast } = useToast()
const supabase = createClient()
const t = useTranslations('invoice_detail')
const { appName } = useBranding()
// Begäran status labels are shared with the payout dialog on the list page.
const tInvoices = useTranslations('invoices')
const tCommon = useTranslations('common')
@@ -573,6 +576,11 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
async function updateStatus(status: InvoiceStatus) {
if (!invoice) return
// Cross-tab guard (WL-09): the direct Supabase branches below bypass the
// patched window.fetch, so consult the tab guard explicitly. On a
// mismatch the blocking dialog raised by guardBrowserWrite is the user
// feedback; nothing is written.
if (!guardBrowserWrite()) return
setIsUpdating(true)
@@ -713,7 +721,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
if (caveat) {
toast({
title: t('pdf_rerender_downloaded_title'),
description: t(RERENDER_CAVEAT_KEYS[caveat]),
description: t(RERENDER_CAVEAT_KEYS[caveat], { appName }),
})
} else {
toast({
@@ -992,7 +1000,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
if (!window.open(url, '_blank', 'noopener,noreferrer')) {
toast({
title: t('pdf_preview_blocked_title'),
description: t('pdf_preview_blocked_description'),
description: t('pdf_preview_blocked_description', { appName }),
variant: 'destructive',
})
return
@@ -1002,7 +1010,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
if (caveat) {
toast({
title: t('pdf_rerender_preview_title'),
description: t(RERENDER_CAVEAT_KEYS[caveat]),
description: t(RERENDER_CAVEAT_KEYS[caveat], { appName }),
})
}
}
@@ -2315,7 +2323,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
<DialogDescription>
{pdfArchiveIssue === 'document'
? t('pdf_archive_issue_document_desc')
: t('pdf_archive_issue_history_desc')}
: t('pdf_archive_issue_history_desc', { appName })}
</DialogDescription>
</DialogHeader>
<DialogFooter>
+137 -21
View File
@@ -13,16 +13,24 @@ import { SessionTimeoutController } from '@/components/auth/SessionTimeoutContro
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
import TrialExpiredDialog from '@/components/billing/TrialExpiredDialog'
import { getExtensionNavItems } from '@/lib/extensions/sectors'
import { CompanyProvider } from '@/contexts/CompanyContext'
import { CompanyProvider, type ByraTeamRef } from '@/contexts/CompanyContext'
import { ReferenceDataSeed } from '@/components/providers/ReferenceDataSeed'
import { getCompanyEntitlements } from '@/lib/entitlements/has-capability'
import { getDashboardNavFlags } from '@/lib/dashboard/nav-flags'
import { getBranding } from '@/lib/branding/service'
import { resolveBrandByHost } from '@/lib/branding/resolve'
import { resolveBrandsForTeams } from '@/lib/branding/team-brands'
import {
partitionCompaniesByHomeDomain,
isCompanyHomedOnHost,
} from '@/lib/company/home-domain'
import HomeDomainSignpost from '@/components/dashboard/HomeDomainSignpost'
import type { AccountingFramework, EntityType, CompanyRole, Team } from '@/types'
import {
getDashboardAuthContext,
getDashboardCompanyId,
getDashboardSettings,
getDashboardTeamMemberships,
getResolvedDashboardAgentProfile,
} from './request-context'
@@ -67,16 +75,16 @@ export default async function DashboardLayout({
// `getActiveCompanyId` reads from user_preferences, matching what RLS
// sees via `current_active_company_id()`. Keeping both sides on the same
// source avoids cross-tab / cookie divergence.
// Team membership (with the team row embedded) only depends on user.id,
// so it resolves in parallel, this layout is on the critical path of
// every dashboard page, so sequential round-trips are wall-clock time.
// Team memberships come from the request-cached getDashboardTeamMemberships
// (ALL rows: multi-team is the supported shape after WL-08) so the home
// page's byrå landing redirect reuses the same single query.
// Wave 1: everything keyed on the user alone runs alongside the company
// resolution. The memberships join carries the active company's row and
// role too, so wave 2 no longer re-reads companies / company_members.
const [
companyId,
headerStore,
{ data: teamMembership },
teamMemberships,
{ data: userProfile },
{ data: userPrefs },
{ data: allMemberships },
@@ -84,12 +92,7 @@ export default async function DashboardLayout({
getDashboardCompanyId(),
// Read the pathname forwarded by middleware so we can branch on it.
headers(),
supabase
.from('team_members')
.select('team_id, role, teams:team_id(*)')
.eq('user_id', user.id)
.limit(1)
.maybeSingle(),
getDashboardTeamMemberships(),
// The signed-in user's profile, shown in the bottom-left account
// popover (full_name + initial) so it's clear which user is logged
// in, distinct from the active company shown at the top.
@@ -106,15 +109,46 @@ export default async function DashboardLayout({
pathname.startsWith(p)
)
// Team now carries `kind` directly (types/index.ts, WL-08).
const membershipRows = teamMemberships
const byraMembership = membershipRows.find((m) => m.teams?.kind === 'byra') ?? null
// Byrå team membership gates the cockpit ("Klienter" nav + /clients).
const byraTeam: ByraTeamRef | null = byraMembership?.teams
? {
id: byraMembership.teams.id,
name: byraMembership.teams.name,
role:
byraMembership.role === 'owner' || byraMembership.role === 'admin'
? byraMembership.role
: 'member',
}
: null
// Legacy single-team fields: the byrå team when present (the one consumers
// care about), else the first membership: same value as before for
// single-team users.
const team: Team | null =
(teamMembership?.teams as unknown as Team | null) ?? null
const isTeamMember = !!teamMembership
(byraMembership?.teams as Team | null) ??
(membershipRows[0]?.teams as Team | null) ??
null
const isTeamMember = membershipRows.length > 0
// No companies: redirect to onboarding, except for allowed escape-hatch
// routes (so the user can still reach /settings/account to delete their
// account after archiving their last company).
// account after archiving their last company) and byrå team members (any
// role, founder call 2026-08-05), whose home is the EMPTY cockpit (mirrors
// the middleware's byrå exception): they render the no-company shell on
// cockpit routes and are steered to /byra everywhere else, never to the
// company wizard.
if (!companyId) {
if (!isNoCompanyAllowed) {
const isByraMember = !!byraTeam
const isByraShellPath =
pathname.startsWith('/byra') ||
pathname.startsWith('/clients') ||
pathname.startsWith('/settings')
if (!isNoCompanyAllowed && !(isByraMember && isByraShellPath)) {
if (isByraMember) {
redirect('/byra')
}
redirect('/onboarding')
}
@@ -126,6 +160,8 @@ export default async function DashboardLayout({
companies: [],
isTeamMember,
team,
byraTeam,
foreignCompanies: [],
isSandbox: false,
capabilities: [],
trialEndsAt: null,
@@ -167,6 +203,14 @@ export default async function DashboardLayout({
const companyRow = (activeMembership?.companies as unknown as import('@/types').Company | null) ?? null
const memberRow = activeMembership ? { role: activeMembership.role } : null
// Home-domain rule (WL-01): which brand serves this host, and which brand
// (if any) each membership company's team owns. Both resolvers are ~60s
// cached; unknown hosts and brandless teams resolve to null/absent, so the
// canonical no-brands hot path stays byte-identical. Both only depend on
// wave-1 data, so they ride in the wave-2 batch below.
const hostHeader =
headerStore.get('x-forwarded-host') ?? headerStore.get('host') ?? ''
// Wave 2: everything keyed on the company. Nav badge counts are NOT fetched
// here: DashboardNav loads them client-side after mount
// (lib/hooks/use-worklist-badges). The four nav-visibility probes
@@ -179,6 +223,8 @@ export default async function DashboardLayout({
navFlags,
{ data: seedFiscalPeriods },
{ data: seedCashAccounts },
hostBrand,
brandByTeam,
] = await Promise.all([
getDashboardSettings(),
// Agent identity, name + avatar, surfaced on the FAB and chat
@@ -210,10 +256,24 @@ export default async function DashboardLayout({
.eq('company_id', companyId)
.order('is_primary', { ascending: false })
.order('ledger_account', { ascending: true }),
hostHeader ? resolveBrandByHost(hostHeader) : Promise.resolve(null),
resolveBrandsForTeams(
(allMemberships || []).map(
(m) => (m.companies as { team_id?: string | null } | null)?.team_id ?? null,
),
),
])
const hasWebshop = navFlags.hasWebshop
const hasMileageTrips = navFlags.hasMileageTrips
const canonicalDomain = (() => {
try {
return new URL(getBranding().appUrl).hostname
} catch {
return ''
}
})()
// company_id -> current display name for every company the user belongs to.
const nameByCompany = new Map(
(allSettingsNames || []).map((s) => [s.company_id, s.company_name as string | null]),
@@ -234,6 +294,8 @@ export default async function DashboardLayout({
}),
isTeamMember,
team,
byraTeam,
foreignCompanies: [],
isSandbox: false,
capabilities: [],
trialEndsAt: null,
@@ -304,10 +366,9 @@ export default async function DashboardLayout({
const uiState = (userPrefs?.ui_state ?? {}) as import('@/types').UserUiState
const navCollapsed = uiState.nav_collapsed === true
const companyContextValue = {
company: companyWithName,
role: memberRow.role as CompanyRole,
companies: (allMemberships || []).map((m) => {
const allCompanyEntries = (allMemberships || [])
.filter((m) => m.companies)
.map((m) => {
const c = m.companies as unknown as import('@/types').Company
// Current display name for every company (company_settings.company_name,
// falling back to the frozen companies.name) so non-active switcher rows
@@ -316,9 +377,34 @@ export default async function DashboardLayout({
company: { ...c, name: nameByCompany.get(c.id) || c.name },
role: m.role as CompanyRole,
}
}),
})
// Home-domain rule (WL-01): the switcher offers only companies homed on
// THIS host; companies homed elsewhere become "Hanteras via <domain>"
// signpost entries. With no brands anywhere both lists reduce to
// visible = everything, foreign = [] : the additive guarantee.
const homePartition = partitionCompaniesByHomeDomain({
companies: allCompanyEntries,
getTeamId: (entry) => entry.company.team_id ?? null,
brandByTeam,
hostBrandTeamId: hostBrand?.teamId ?? null,
canonicalDomain,
canonicalAppName: getBranding().appName,
})
const foreignCompanies = homePartition.foreign.map((f) => ({
id: f.item.company.id,
name: f.item.company.name,
domain: f.domain,
}))
const companyContextValue = {
company: companyWithName,
role: memberRow.role as CompanyRole,
companies: homePartition.visible,
isTeamMember,
team,
byraTeam,
foreignCompanies,
isSandbox,
capabilities: entitlements.capabilities,
trialEndsAt: entitlements.trialEndsAt,
@@ -326,6 +412,23 @@ export default async function DashboardLayout({
trialExpiredAt: entitlements.trialExpiredAt,
}
// Signpost gate (WL-01): a company is opened ONLY on its home domain. When
// the active company is homed elsewhere, the dashboard body is replaced by
// the signpost (never the wrong company's data), except on account-level
// and byrå-cockpit routes, which are not company surfaces. Navigation rule
// only: RLS/membership remain the security boundary, and middleware is
// untouched (the layout is the clean seam: brand lookups don't belong on
// the Edge hot path).
const activeCompanyHomed = isCompanyHomedOnHost({
companyTeamId: (companyRow.team_id as string | null) ?? null,
brandByTeam,
hostBrandTeamId: hostBrand?.teamId ?? null,
})
const SIGNPOST_ALLOWED_PATHS = ['/settings/account', '/clients', '/byra']
const showSignpost =
!activeCompanyHomed &&
!SIGNPOST_ALLOWED_PATHS.some((p) => pathname.startsWith(p))
return (
<CompanyProvider value={companyContextValue}>
<ReferenceDataSeed
@@ -374,7 +477,20 @@ export default async function DashboardLayout({
initialUiState={uiState}
/>
<main id="main-content" className={MAIN_PANEL_CLASS} role="main">
<MainContainer companyId={companyId}>{children}</MainContainer>
<MainContainer companyId={companyId}>
{showSignpost ? (
<HomeDomainSignpost
activeCompanyName={displayName}
homedCompanies={homePartition.visible.map((entry) => ({
id: entry.company.id,
name: entry.company.name,
}))}
foreignCompanies={foreignCompanies}
/>
) : (
children
)}
</MainContainer>
</main>
<AgentTrigger hidden={userPrefs?.hide_assistant_fab === true} />
{/* One-time expired-trial notice. Sandbox/anonymous demo users have
+22
View File
@@ -1,11 +1,14 @@
import { Suspense } from 'react'
import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'
import DashboardContent from '@/components/dashboard/DashboardContent'
import { ChecklistSkeleton, PanesSkeleton } from '@/components/dashboard/HemSkeletons'
import { COMPANY_PICKED_COOKIE } from '@/lib/company/context'
import {
getDashboardAuthContext,
getDashboardCompanyId,
getDashboardSettings,
getDashboardTeamMemberships,
getResolvedDashboardAgentProfile,
} from './request-context'
import { HemChecklistSection, HemNoticesSection, HemPanesSection } from './hem-sections'
@@ -40,6 +43,25 @@ export default async function DashboardPage() {
redirect('/onboarding')
}
// Byrå landing: every byrå team member (owner, admin AND member: widened
// from owner/admin on the founder's call 2026-08-05, so invited consultants
// land right too) homes to the cockpit, not to an auto-resolved client
// company. companyId above can be the middleware's first-membership
// fallback (which it also writes back to user_preferences, so the DB can't
// tell picked from auto-picked); the session cookie stamped by
// setActiveCompany is the explicit-choice signal. Once they enter a client
// this session, "/" is that company's Hem again. Memberships are
// request-cached and shared with the layout.
const [cookieStore, teamMemberships] = await Promise.all([
cookies(),
getDashboardTeamMemberships(),
])
if (!cookieStore.has(COMPANY_PICKED_COOKIE)) {
if (teamMemberships.some((m) => m.teams?.kind === 'byra')) {
redirect('/byra')
}
}
const now = new Date()
const [settingsRes, { data: profile }, agentProfile, { count: skatteverketTokenCount }] =
+29
View File
@@ -6,6 +6,7 @@ import { createClient } from '@/lib/supabase/server'
import { claimsPinned, userFromClaims } from '@/lib/auth/claims'
import { getActiveCompanyId } from '@/lib/company/context'
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
import type { Team } from '@/types'
/**
* Request-local dashboard auth context. React cache shares the Supabase client
@@ -48,6 +49,34 @@ export const getDashboardCompanyId = cache(async () => {
return user ? getActiveCompanyId(supabase, user.id) : null
})
export interface DashboardTeamMembership {
team_id: string
role: string
teams: Team | null
}
/**
* Request-local team memberships with the team row embedded. ALL memberships:
* multi-team membership (own personal team + byrå team) is the supported
* shape after WL-08; a `.limit(1)` would pick an arbitrary row and could hide
* a consultant's byrå membership. Shared between the dashboard layout (byrå
* cockpit gate) and the home page (byrå landing redirect), so the byrå check
* costs no extra query.
*/
export const getDashboardTeamMemberships = cache(
async (): Promise<DashboardTeamMembership[]> => {
const { supabase, user } = await getDashboardAuthContext()
if (!user) return []
const { data } = await supabase
.from('team_members')
.select('team_id, role, teams:team_id(*)')
.eq('user_id', user.id)
return (data ?? []) as unknown as DashboardTeamMembership[]
},
)
export const getDashboardSettings = cache(async () => {
const [{ supabase }, companyId] = await Promise.all([
getDashboardAuthContext(),
+7
View File
@@ -0,0 +1,7 @@
'use client'
import { BrandSettingsContent } from '@/components/settings/sections/BrandSettingsContent'
export default function BrandSettingsPage() {
return <BrandSettingsContent />
}
+5
View File
@@ -1,6 +1,7 @@
import type { Metadata } from 'next'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import Link from 'next/link'
import { SourceCodeFooter } from '@/components/branding/SourceCodeFooter'
import { getBranding } from '@/lib/branding/service'
export function generateMetadata(): Metadata {
@@ -249,6 +250,10 @@ export default function DPAPage() {
</p>
</CardContent>
</Card>
{/* AGPL section 13 source offer (WL-06): renders on both default and
branded hosts; never gate this on a brand. */}
<SourceCodeFooter className="pt-2" />
</div>
</div>
)
+34 -2
View File
@@ -38,6 +38,33 @@ interface InvoiceData {
reminderFeeCurrency?: string
totalDue: number
feeDueSeparately?: number
// White-label brand of the invoice's COMPANY (WL-13), resolved server-side
// by the action API regardless of host. Null/absent = today's page.
brand?: {
appName: string
logoUrl: string | null
brandColor: string
} | null
}
// Discreet brand mark shown when the invoice's company has a white-label
// brand: logo when one exists, else the brand name in the brand color.
function BrandMark({ brand }: { brand: NonNullable<InvoiceData['brand']> }) {
return (
<div className="flex justify-center mb-6">
{brand.logoUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={brand.logoUrl} alt={brand.appName} className="h-8 w-auto" />
) : (
<span
className="text-sm font-semibold tracking-wide"
style={{ color: brand.brandColor }}
>
{brand.appName}
</span>
)}
</div>
)
}
export default function InvoiceActionPage({ params }: { params: Promise<{ token: string }> }) {
@@ -133,7 +160,9 @@ export default function InvoiceActionPage({ params }: { params: Promise<{ token:
if (invoice.alreadyResponded || successMessage) {
return (
<div className="min-h-dvh bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-4">
<Card className="max-w-md w-full">
<div className="max-w-md w-full">
{invoice.brand && <BrandMark brand={invoice.brand} />}
<Card className="w-full">
<CardContent className="pt-6 text-center">
<CheckCircle className="h-12 w-12 text-success mx-auto mb-4" />
<h2 className="text-lg mb-2">Tack för ditt svar!</h2>
@@ -149,7 +178,8 @@ export default function InvoiceActionPage({ params }: { params: Promise<{ token:
<p className="font-medium">{invoice.invoiceNumber}</p>
</div>
</CardContent>
</Card>
</Card>
</div>
</div>
)
}
@@ -168,6 +198,8 @@ export default function InvoiceActionPage({ params }: { params: Promise<{ token:
return (
<div className="min-h-dvh bg-gradient-to-b from-slate-50 to-white py-12 px-4">
<div className="max-w-lg mx-auto">
{/* Brand chrome (WL-13): only when the invoice's company has a brand */}
{invoice.brand && <BrandMark brand={invoice.brand} />}
{/* Header */}
<div className="text-center mb-8">
<h1 className="text-2xl text-foreground mb-2">
+5
View File
@@ -1,6 +1,7 @@
import type { Metadata } from 'next'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { SourceCodeFooter } from '@/components/branding/SourceCodeFooter'
import { getBranding } from '@/lib/branding/service'
export function generateMetadata(): Metadata {
@@ -310,6 +311,10 @@ export default function PrivacyPolicyPage() {
</p>
</CardContent>
</Card>
{/* AGPL section 13 source offer (WL-06): renders on both default and
branded hosts; never gate this on a brand. */}
<SourceCodeFooter className="pt-2" />
</div>
</div>
)
@@ -0,0 +1,240 @@
/**
* Tests for POST /api/auth/email-hook (Supabase Send Email hook).
*
* Unauthenticated by design: the guard is the Standard Webhooks signature.
* Signature material is computed with node:crypto exactly like Supabase does.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createHmac, randomBytes } from 'node:crypto'
import type { Brand } from '@/lib/branding/resolve'
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const resolveBrandByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandByHost: resolveBrandByHostMock,
// Imported by lib/email/brand-sender (not called on the hook path).
resolveBrandForCompany: vi.fn(),
}))
vi.mock('@/lib/branding/service', () => ({
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
}))
const sendEmailMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/email/service', () => ({
getEmailService: () => ({ sendEmail: sendEmailMock, isConfigured: () => true }),
}))
import { POST } from '../route'
const KEY = randomBytes(24)
const SECRET = `v1,whsec_${KEY.toString('base64')}`
function makeBrand(overrides: Partial<Brand> = {}): Brand {
return {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.siffra.se',
appName: 'Siffra',
logoUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: '[email protected]',
authEmailFrom: '[email protected]',
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
...overrides,
}
}
function signedRequest(rawBody: string, opts?: { badSignature?: boolean; headers?: Record<string, string> }): Request {
const id = 'msg_1'
const timestamp = String(Math.floor(Date.now() / 1000))
const signature = createHmac('sha256', KEY)
.update(`${id}.${timestamp}.${rawBody}`)
.digest('base64')
return new Request('http://localhost:3000/api/auth/email-hook', {
method: 'POST',
body: rawBody,
headers: {
'content-type': 'application/json',
'webhook-id': id,
'webhook-timestamp': timestamp,
'webhook-signature': opts?.badSignature ? 'v1,AAAA' : `v1,${signature}`,
...opts?.headers,
},
})
}
function hookPayload(overrides?: {
user?: Record<string, unknown>
email_data?: Record<string, unknown>
}): string {
return JSON.stringify({
user: { email: '[email protected]', ...overrides?.user },
email_data: {
token: '123456',
token_hash: 'hash-1',
redirect_to: 'https://app.gnubok.se/auth/callback?next=/reset-password',
email_action_type: 'recovery',
site_url: 'https://app.gnubok.se',
...overrides?.email_data,
},
})
}
beforeEach(() => {
vi.clearAllMocks()
process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET = SECRET
resolveBrandByHostMock.mockResolvedValue(null)
sendEmailMock.mockResolvedValue({ success: true, messageId: 'msg-1' })
})
afterEach(() => {
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
})
describe('POST /api/auth/email-hook', () => {
it('returns 500 when the hook secret is not configured', async () => {
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(500)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 401 for an invalid signature', async () => {
const res = await POST(signedRequest(hookPayload(), { badSignature: true }))
expect(res.status).toBe(401)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 400 for a signed but malformed payload', async () => {
const res = await POST(signedRequest('not-json'))
expect(res.status).toBe(400)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('sends canonical recovery mail linking to the originating host (no brand)', async () => {
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({})
expect(sendEmailMock).toHaveBeenCalledTimes(1)
const options = sendEmailMock.mock.calls[0][0]
expect(options.to).toBe('[email protected]')
expect(options.subject).toBe('Återställ ditt lösenord')
expect(options.fromName).toBeUndefined()
expect(options.fromAddress).toBeUndefined()
expect(options.replyTo).toBeUndefined()
// token_hash + verifyOtp pattern on the originating host, preserving the
// existing next=/reset-password query.
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Freset-password')
expect(options.text).toContain('token_hash=hash-1')
expect(options.text).toContain('type=recovery')
})
it('brands the mail from the redirect_to host and rides the verified brand sender', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
const res = await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'signup',
redirect_to: 'https://app.siffra.se/auth/callback',
},
}),
),
)
expect(res.status).toBe(200)
expect(resolveBrandByHostMock).toHaveBeenCalledWith('app.siffra.se')
const options = sendEmailMock.mock.calls[0][0]
expect(options.fromName).toBe('Siffra')
expect(options.fromAddress).toBe('[email protected]')
expect(options.replyTo).toBe('[email protected]')
expect(options.html).toContain('Siffra')
expect(options.html).not.toMatch(/accounted/i)
expect(options.text).toContain('https://app.siffra.se/auth/callback?token_hash=hash-1')
expect(options.text).toContain('type=signup')
})
it('uses the via-fallback for a brand without a verified sender domain', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand({ senderDomainStatus: 'pending' }))
await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'magiclink',
redirect_to: 'https://app.siffra.se/auth/callback',
},
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.fromName).toBe('Siffra')
expect(options.fromAddress).toBeUndefined()
})
it('sends two mails for a secure email change', async () => {
await POST(
signedRequest(
hookPayload({
user: { email: '[email protected]', new_email: '[email protected]' },
email_data: {
email_action_type: 'email_change',
token_hash: 'hash-new-address',
token_hash_new: 'hash-current-address',
redirect_to: 'https://app.gnubok.se/auth/callback',
},
}),
),
)
expect(sendEmailMock).toHaveBeenCalledTimes(2)
const first = sendEmailMock.mock.calls[0][0]
const second = sendEmailMock.mock.calls[1][0]
// token_hash confirms at the NEW address, token_hash_new at the current.
expect(first.to).toBe('[email protected]')
expect(first.text).toContain('token_hash=hash-new-address')
expect(second.to).toBe('[email protected]')
expect(second.text).toContain('token_hash=hash-current-address')
})
it('sends the OTP code for reauthentication without a link', async () => {
await POST(
signedRequest(
hookPayload({
email_data: { email_action_type: 'reauthentication', token: '424242' },
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.subject).toBe('Din verifieringskod')
expect(options.text).toContain('424242')
expect(options.text).not.toContain('token_hash=')
})
it('builds the callback URL when redirect_to points at a plain path', async () => {
await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'magiclink',
redirect_to: 'https://app.gnubok.se/settings/account',
},
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Fsettings%2Faccount')
expect(options.text).toContain('type=magiclink')
})
it('returns 500 when the email provider fails, so Supabase retries', async () => {
sendEmailMock.mockResolvedValue({ success: false, error: 'provider down' })
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(500)
})
})
+209
View File
@@ -0,0 +1,209 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { createLogger } from '@/lib/logger'
import { getEmailService } from '@/lib/email/service'
import { getBranding } from '@/lib/branding/service'
import { resolveBrandByHost } from '@/lib/branding/resolve'
import { getSenderForBrand } from '@/lib/email/brand-sender'
import { buildAuthEmail } from '@/lib/email/auth-templates'
import { verifyStandardWebhookSignature } from '@/lib/email/standard-webhook'
// Loads the email extension so getEmailService() returns the Resend
// implementation instead of the noop default.
ensureInitialized()
const log = createLogger('auth-email-hook')
/**
* POST /api/auth/email-hook: Supabase Auth "Send Email" hook (WL-05, WL-13).
*
* When enabled in Supabase (Auth > Hooks > Send Email, pointing at this URL
* with the shared secret in SUPABASE_SEND_EMAIL_HOOK_SECRET), Supabase stops
* sending auth mail itself and this endpoint sends every auth mail (signup
* confirmation, recovery, magic link, invite, email change, reauthentication)
* through the platform email service, branded per the requesting host: the
* brand is resolved from the redirect_to origin via resolveBrandByHost, so a
* reset requested on app.partner.se is sent in the partner's brand and links
* back to app.partner.se. Unknown hosts get canonical platform mail.
*
* Unauthenticated by design (server-to-server): authenticity comes from the
* Standard Webhooks signature, not a session, exactly like the Stripe and
* Resend webhook routes. The raw body is verified byte-for-byte before
* parsing. This endpoint is availability-critical once the hook is enabled:
* any internal failure returns 500 so Supabase retries (up to 3 times within
* a 5 second budget); success returns 200 {} fast.
*
* Until the hook is switched on in Supabase this route is dormant and auth
* mail keeps flowing from Supabase unchanged.
*/
// verifyOtp types our /auth/callback confirm route accepts. Unknown action
// types fall back to the generic 'email' type rather than dropping the mail.
const VERIFY_TYPES = new Set([
'signup',
'recovery',
'magiclink',
'invite',
'email_change',
'email',
])
interface SendEmailHookPayload {
user?: {
email?: string | null
new_email?: string | null
email_new?: string | null
} | null
email_data?: {
token?: string
token_hash?: string
token_new?: string
token_hash_new?: string
redirect_to?: string
email_action_type?: string
site_url?: string
} | null
}
/**
* Build the verify URL on the ORIGINATING host using the token_hash +
* verifyOtp pattern (browser- and host-independent, per the WL-05 research):
* /auth/callback consumes token_hash + type server-side and then honors the
* `next` path. If redirect_to already points at /auth/callback (our client
* flows do), its query (e.g. next=/reset-password) is preserved.
*/
function buildActionUrl(
redirectUrl: URL | null,
tokenHash: string,
actionType: string,
): string {
const verifyType = VERIFY_TYPES.has(actionType) ? actionType : 'email'
let url: URL
if (redirectUrl && redirectUrl.pathname === '/auth/callback') {
url = new URL(redirectUrl.toString())
} else {
url = new URL('/auth/callback', redirectUrl ? redirectUrl.origin : getBranding().appUrl)
if (redirectUrl) {
const next = redirectUrl.pathname + redirectUrl.search
if (next && next !== '/') url.searchParams.set('next', next)
}
}
url.searchParams.set('token_hash', tokenHash)
url.searchParams.set('type', verifyType)
return url.toString()
}
export async function POST(request: Request) {
const secret = process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
if (!secret) {
log.error('SUPABASE_SEND_EMAIL_HOOK_SECRET is not configured', undefined)
return NextResponse.json({ error: 'Hook not configured' }, { status: 500 })
}
const rawBody = await request.text()
const verified = verifyStandardWebhookSignature({
secret,
payload: rawBody,
id: request.headers.get('webhook-id'),
timestamp: request.headers.get('webhook-timestamp'),
signature: request.headers.get('webhook-signature'),
})
if (!verified) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 })
}
let payload: SendEmailHookPayload
try {
payload = JSON.parse(rawBody) as SendEmailHookPayload
} catch {
return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })
}
const emailData = payload.email_data ?? {}
const actionType = emailData.email_action_type || ''
const recipient = payload.user?.email || null
if (!recipient) {
return NextResponse.json({ error: 'Missing recipient' }, { status: 400 })
}
// Brand from the requesting host: redirect_to carries the tenant origin.
let redirectUrl: URL | null = null
if (emailData.redirect_to) {
try {
redirectUrl = new URL(emailData.redirect_to)
} catch {
redirectUrl = null
}
}
const brand = redirectUrl ? await resolveBrandByHost(redirectUrl.hostname) : null
const sender = getSenderForBrand(brand)
const appName = brand?.appName ?? getBranding().appName
// Compose the mail(s) for this hook invocation.
const mails: Array<{ to: string; actionType: string; actionUrl?: string; otpCode?: string }> = []
if (actionType === 'reauthentication') {
if (!emailData.token) {
return NextResponse.json({ error: 'Missing token' }, { status: 400 })
}
mails.push({ to: recipient, actionType, otpCode: emailData.token })
} else if (actionType === 'email_change') {
// Secure email change sends TWO mails from one invocation. Documented
// reversal: token_hash confirms at the NEW address, token_hash_new at
// the CURRENT one.
if (!emailData.token_hash) {
return NextResponse.json({ error: 'Missing token_hash' }, { status: 400 })
}
const newEmail = payload.user?.new_email || payload.user?.email_new || recipient
mails.push({
to: newEmail,
actionType: 'email_change',
actionUrl: buildActionUrl(redirectUrl, emailData.token_hash, 'email_change'),
})
if (emailData.token_hash_new) {
mails.push({
to: recipient,
actionType: 'email_change_current',
actionUrl: buildActionUrl(redirectUrl, emailData.token_hash_new, 'email_change'),
})
}
} else {
if (!emailData.token_hash) {
return NextResponse.json({ error: 'Missing token_hash' }, { status: 400 })
}
mails.push({
to: recipient,
actionType,
actionUrl: buildActionUrl(redirectUrl, emailData.token_hash, actionType),
})
}
const emailService = getEmailService()
for (const mail of mails) {
const built = buildAuthEmail({
actionType: mail.actionType,
appName,
actionUrl: mail.actionUrl,
otpCode: mail.otpCode,
})
const result = await emailService.sendEmail({
to: mail.to,
subject: built.subject,
html: built.html,
text: built.text,
fromName: sender.fromName ?? undefined,
fromAddress: sender.fromAddress ?? undefined,
replyTo: sender.replyTo ?? undefined,
})
if (!result.success) {
// Non-2xx makes Supabase retry, which is the recovery we want: auth
// mail must not be silently dropped.
log.error('auth mail send failed', new Error(result.error ?? 'unknown'), {
actionType: mail.actionType,
})
return NextResponse.json({ error: 'Send failed' }, { status: 500 })
}
}
return NextResponse.json({})
}
+106
View File
@@ -42,12 +42,22 @@ vi.mock('@/lib/sandbox/guard', () => ({
isSandboxCompany: vi.fn().mockResolvedValue(false),
}))
// Service client for the WL-10 team-agreement lookup (end clients cannot read
// the byrå team or its grants under RLS, so the route uses the service role).
let serviceByTable: Record<string, TableResult> = {}
const createServiceClientMock = vi.fn(() => makeSupabase(serviceByTable))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => createServiceClientMock(),
createClient: vi.fn(),
}))
import { GET } from '../status/route'
interface StatusBody {
isPaying: boolean
trialEndsAt: string | null
isDemo: boolean
teamAgreement?: { teamName: string }
}
function authAs(byTable: Record<string, TableResult>) {
@@ -60,6 +70,7 @@ function authAs(byTable: Record<string, TableResult>) {
beforeEach(() => {
vi.clearAllMocks()
serviceByTable = {}
})
describe('GET /api/billing/status', () => {
@@ -108,3 +119,98 @@ describe('GET /api/billing/status', () => {
expect(body.isPaying).toBe(false)
})
})
// WL-10 billing honesty: a non-paying company under a byrå team with an
// active team-scoped manual grant gets the additive teamAgreement field.
describe('GET /api/billing/status team agreement', () => {
it('returns teamAgreement for a byrå-covered non-paying company', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: null }] },
}
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(false)
expect(body.teamAgreement).toEqual({ teamName: 'Siffran AB' })
})
it('accepts a future-dated grant expiry', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: '2099-01-01T00:00:00Z' }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.teamAgreement).toEqual({ teamName: 'Siffran AB' })
})
it('ignores an expired team grant (grace lapsed: standard paywall)', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: '2020-01-01T00:00:00Z' }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
expect(body.teamAgreement).toBeUndefined()
})
it('ignores a personal team even with a manual grant', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Personal', kind: 'personal' } },
capability_grants: { data: [{ expires_at: null }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.teamAgreement).toBeUndefined()
})
it('leaves a teamless company unchanged', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
serviceByTable = {
companies: { data: { team_id: null } },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
expect(body.trialEndsAt).toBe('2099-01-01T00:00:00Z')
expect(body.teamAgreement).toBeUndefined()
expect('teamAgreement' in (body as object)).toBe(false)
})
it('never consults the team path for a paying company', async () => {
authAs({
company_subscriptions: { data: { status: 'active' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(true)
expect(body.teamAgreement).toBeUndefined()
expect(createServiceClientMock).not.toHaveBeenCalled()
})
})
+23 -1
View File
@@ -1,14 +1,21 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { requireCompanyId } from '@/lib/company/context'
import { isStripeConfigured } from '@/lib/stripe/client'
import { isSandboxCompany } from '@/lib/sandbox/guard'
import { getTeamAgreement, type TeamAgreement } from '@/lib/entitlements/team-agreement'
/**
* Billing status for the client-rendered billing section (which lives inside the
* settings modal Dialog and can't read the DB server-side). Returns whether the
* company is paying, whether Stripe checkout is configured, and the trial expiry
* (for the days-left urgency banner). Read-only.
*
* WL-10: a non-paying company covered by its byrå team's agreement (active
* team-scoped manual grant) additionally gets `teamAgreement: { teamName }`,
* which the settings surface renders as "Ingår i <byråns namn>s avtal"
* instead of the upgrade pitch. Additive field: absent for everyone else.
*/
export async function GET() {
const { user, supabase, error } = await requireAuth()
@@ -30,6 +37,7 @@ export async function GET() {
let isPaying = false
let trialEndsAt: string | null = null
let teamAgreement: TeamAgreement | null = null
if (companyId) {
const { data: sub } = await supabase
.from('company_subscriptions')
@@ -53,7 +61,21 @@ export async function GET() {
.limit(1)
.maybeSingle()
trialEndsAt = (trial as { expires_at: string | null } | null)?.expires_at ?? null
// Team entitlement (WL-10): only consulted when the company isn't paying
// on its own subscription. Service client by necessity: end clients are
// not members of the byrå team, so RLS hides the team and its grants
// from the user's session.
if (!isPaying) {
teamAgreement = await getTeamAgreement(createServiceClient(), companyId)
}
}
return NextResponse.json({ isPaying, configured: isStripeConfigured(), trialEndsAt, isDemo })
return NextResponse.json({
isPaying,
configured: isStripeConfigured(),
trialEndsAt,
isDemo,
...(teamAgreement ? { teamAgreement } : {}),
})
}
+179
View File
@@ -0,0 +1,179 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
const getByraMembershipMock = vi.fn()
vi.mock('@/lib/clients/fetch-client-overview', () => ({
getByraMembership: (...args: unknown[]) => getByraMembershipMock(...args),
}))
const clearBrandCacheMock = vi.fn()
vi.mock('@/lib/branding/resolve', () => ({
clearBrandCache: (...args: unknown[]) => clearBrandCacheMock(...args),
}))
interface BrandRow {
domain?: string
app_name?: string
logo_url?: string | null
id?: string
}
let brandRow: BrandRow | null = null
let brandReadError: { message: string } | null = null
let updateError: { message: string } | null = null
const updateEqMock = vi.fn(async () => ({ error: updateError }))
const updateMock = vi.fn(() => ({ eq: updateEqMock }))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => ({
from: () => ({
select: () => ({
eq: () => ({
maybeSingle: async () => ({ data: brandRow, error: brandReadError }),
}),
}),
update: updateMock,
}),
}),
}))
import { GET, PATCH } from '../route'
function patchRequest(body: unknown): Request {
return new Request('http://localhost/api/byra/brand', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
function authed() {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, error: null })
}
function unauthed() {
requireAuthMock.mockResolvedValue({
user: null,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
beforeEach(() => {
vi.clearAllMocks()
brandRow = null
brandReadError = null
updateError = null
})
describe('GET /api/byra/brand', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await GET()
expect(res.status).toBe(401)
})
it('returns 403 for a user without a byrå team', async () => {
authed()
getByraMembershipMock.mockResolvedValue(null)
const res = await GET()
expect(res.status).toBe(403)
})
it('returns hasBrand false when the team has no brand row', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'owner' })
const res = await GET()
const { status, body } = await parseJsonResponse<{
data: { hasBrand: boolean; canEdit: boolean }
}>(res)
expect(status).toBe(200)
expect(body.data).toMatchObject({ hasBrand: false, canEdit: true })
})
it('returns the brand with canEdit false for a plain member', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'member' })
brandRow = { domain: 'willem.accounted.se', app_name: 'Siffra', logo_url: null }
const res = await GET()
const { status, body } = await parseJsonResponse<{
data: { hasBrand: boolean; domain: string; appName: string; logoUrl: string | null; canEdit: boolean }
}>(res)
expect(status).toBe(200)
expect(body.data).toEqual({
hasBrand: true,
domain: 'willem.accounted.se',
appName: 'Siffra',
logoUrl: null,
canEdit: false,
})
})
it('returns 500 when the brand read fails', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'admin' })
brandReadError = { message: 'boom' }
const res = await GET()
expect(res.status).toBe(500)
})
})
describe('PATCH /api/byra/brand', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await PATCH(patchRequest({ appName: 'Willem' }))
expect(res.status).toBe(401)
})
it('returns 403 for a plain member', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'member' })
const res = await PATCH(patchRequest({ appName: 'Willem' }))
expect(res.status).toBe(403)
})
it('returns 400 for an empty app name', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'owner' })
const res = await PATCH(patchRequest({ appName: ' ' }))
expect(res.status).toBe(400)
expect(updateMock).not.toHaveBeenCalled()
})
it('returns 404 when the team has no brand row', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'owner' })
brandRow = null
const res = await PATCH(patchRequest({ appName: 'Willem' }))
expect(res.status).toBe(404)
})
it('trims, updates app_name and clears the brand cache', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'admin' })
brandRow = { id: 'brand-1' }
const res = await PATCH(patchRequest({ appName: ' Willem ' }))
const { status, body } = await parseJsonResponse<{ data: { app_name: string } }>(res)
expect(status).toBe(200)
expect(body.data.app_name).toBe('Willem')
expect(updateMock).toHaveBeenCalledWith({ app_name: 'Willem' })
expect(clearBrandCacheMock).toHaveBeenCalled()
})
it('returns 500 when the update fails', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'owner' })
brandRow = { id: 'brand-1' }
updateError = { message: 'nope' }
const res = await PATCH(patchRequest({ appName: 'Willem' }))
expect(res.status).toBe(500)
expect(clearBrandCacheMock).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,180 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
const getByraMembershipMock = vi.fn()
vi.mock('@/lib/clients/fetch-client-overview', () => ({
getByraMembership: (...args: unknown[]) => getByraMembershipMock(...args),
}))
const clearBrandCacheMock = vi.fn()
vi.mock('@/lib/branding/resolve', () => ({
clearBrandCache: (...args: unknown[]) => clearBrandCacheMock(...args),
}))
let brandRow: { id: string; logo_url?: string | null } | null = null
let updateError: { message: string } | null = null
const updateEqMock = vi.fn(async () => ({ error: updateError }))
const updateMock = vi.fn(() => ({ eq: updateEqMock }))
const storageListMock = vi.fn(async () => ({ data: [{ name: 'logo-old.png' }] }))
const storageRemoveMock = vi.fn(async () => ({ error: null }))
const storageUploadMock = vi.fn(async () => ({ error: null }))
const storageGetPublicUrlMock = vi.fn(() => ({
data: { publicUrl: 'https://cdn.test/logos/byra/team-1/logo-2.png' },
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => ({
from: () => ({
select: () => ({
eq: () => ({
maybeSingle: async () => ({ data: brandRow, error: null }),
}),
}),
update: updateMock,
}),
storage: {
from: () => ({
list: storageListMock,
remove: storageRemoveMock,
upload: storageUploadMock,
getPublicUrl: storageGetPublicUrlMock,
}),
},
}),
}))
import { POST, DELETE } from '../route'
function authed() {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, error: null })
}
function unauthed() {
requireAuthMock.mockResolvedValue({
user: null,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
function ownerMembership() {
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'owner' })
}
function uploadRequest(type = 'image/png', size = 128): Request {
const file = new File([new Uint8Array(size)], 'logo.png', { type })
const formData = new FormData()
formData.append('file', file)
return new Request('http://localhost/api/byra/brand/logo', { method: 'POST', body: formData })
}
beforeEach(() => {
vi.clearAllMocks()
brandRow = { id: 'brand-1', logo_url: null }
updateError = null
})
describe('POST /api/byra/brand/logo', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await POST(uploadRequest())
expect(res.status).toBe(401)
})
it('returns 403 for a user without a byrå team', async () => {
authed()
getByraMembershipMock.mockResolvedValue(null)
const res = await POST(uploadRequest())
expect(res.status).toBe(403)
})
it('returns 403 for a plain member', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'member' })
const res = await POST(uploadRequest())
expect(res.status).toBe(403)
})
it('returns 404 when the team has no brand row', async () => {
authed()
ownerMembership()
brandRow = null
const res = await POST(uploadRequest())
expect(res.status).toBe(404)
})
it('returns 400 when no file is attached', async () => {
authed()
ownerMembership()
const formData = new FormData()
const res = await POST(
new Request('http://localhost/api/byra/brand/logo', { method: 'POST', body: formData }),
)
expect(res.status).toBe(400)
})
it('returns 400 for a disallowed file type', async () => {
authed()
ownerMembership()
const res = await POST(uploadRequest('application/pdf'))
expect(res.status).toBe(400)
})
it('uploads, purges old files, updates brands.logo_url and clears the cache', async () => {
authed()
ownerMembership()
const res = await POST(uploadRequest())
const { status, body } = await parseJsonResponse<{ data: { logo_url: string } }>(res)
expect(status).toBe(200)
expect(body.data.logo_url).toBe('https://cdn.test/logos/byra/team-1/logo-2.png')
expect(storageRemoveMock).toHaveBeenCalledWith(['byra/team-1/logo-old.png'])
expect(storageUploadMock).toHaveBeenCalledWith(
expect.stringMatching(/^byra\/team-1\/logo-\d+\.png$/),
expect.any(Buffer),
{ contentType: 'image/png', upsert: true },
)
expect(updateMock).toHaveBeenCalledWith({
logo_url: 'https://cdn.test/logos/byra/team-1/logo-2.png',
})
expect(clearBrandCacheMock).toHaveBeenCalled()
})
it('returns 500 when the brands update fails', async () => {
authed()
ownerMembership()
updateError = { message: 'nope' }
const res = await POST(uploadRequest())
expect(res.status).toBe(500)
expect(clearBrandCacheMock).not.toHaveBeenCalled()
})
})
describe('DELETE /api/byra/brand/logo', () => {
it('returns 403 for a plain member', async () => {
authed()
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'member' })
const res = await DELETE()
expect(res.status).toBe(403)
})
it('purges files, nulls logo_url and clears the cache', async () => {
authed()
ownerMembership()
brandRow = { id: 'brand-1', logo_url: 'https://cdn.test/old.png' }
const res = await DELETE()
const { status, body } = await parseJsonResponse<{ data: { logo_url: null } }>(res)
expect(status).toBe(200)
expect(body.data.logo_url).toBeNull()
expect(storageRemoveMock).toHaveBeenCalledWith(['byra/team-1/logo-old.png'])
expect(updateMock).toHaveBeenCalledWith({ logo_url: null })
expect(clearBrandCacheMock).toHaveBeenCalled()
})
})
+140
View File
@@ -0,0 +1,140 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { requireByraBrandAccess } from '@/lib/byra/brand-access'
import { clearBrandCache } from '@/lib/branding/resolve'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { LOGO_UPLOAD_MAX_BYTES, LOGO_UPLOAD_MAX_MB } from '@/lib/invoices/branding-constants'
/**
* POST/DELETE /api/byra/brand/logo
* Byrå self-service brand logo (the ONE brand field byråer edit themselves;
* domain, app name and colors stay ops-managed, see DECISIONS.md).
*
* brands has no write RLS (ops-managed rows), so writes go through the
* service client behind an explicit owner/admin check on the caller's byrå
* team: the same authorization idiom as /api/team/members. Files live in
* the public `logos` bucket under byra/{teamId}/ (company invoice logos use
* {companyId}/ top-level; the byra/ prefix keeps the namespaces apart).
*
* The timestamped filename doubles as a cache-buster; the 60s brand cache
* in lib/branding/resolve.ts means other lambda instances can serve the old
* logo_url for up to a minute after a change. clearBrandCache() covers the
* instance that handled the write.
*/
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp']
async function purgeLogoFiles(
serviceClient: ReturnType<typeof createServiceClient>,
teamId: string,
): Promise<void> {
const prefix = `byra/${teamId}`
const { data: existing } = await serviceClient.storage.from('logos').list(prefix)
if (existing && existing.length > 0) {
await serviceClient.storage
.from('logos')
.remove(existing.map((f) => `${prefix}/${f.name}`))
}
}
export async function POST(request: Request) {
const { user, error } = await requireAuth()
if (error) return error
const { teamId, serviceClient, errorResponse } = await requireByraBrandAccess(user.id)
if (errorResponse) return errorResponse
const { data: brand } = await serviceClient
.from('brands')
.select('id')
.eq('team_id', teamId)
.maybeSingle()
if (!brand) {
return NextResponse.json({ error: 'Ingen varumärkesprofil är aktiverad ännu.' }, { status: 404 })
}
const formData = await request.formData()
const file = formData.get('file') as File | null
if (!file) {
return NextResponse.json({ error: 'Ingen fil angiven' }, { status: 400 })
}
if (!ALLOWED_TYPES.includes(file.type)) {
return NextResponse.json(
{ error: 'Otillåten filtyp. Tillåtna: PNG, JPG, SVG, WebP.' },
{ status: 400 },
)
}
if (file.size > LOGO_UPLOAD_MAX_BYTES) {
return NextResponse.json(
{ error: `Filen är för stor (max ${LOGO_UPLOAD_MAX_MB} MB).` },
{ status: 400 },
)
}
const buffer = Buffer.from(await file.arrayBuffer())
const mimeToExt: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/svg+xml': 'svg',
'image/webp': 'webp',
}
const ext = mimeToExt[file.type] ?? 'png'
const storagePath = `byra/${teamId}/logo-${Date.now()}.${ext}`
await purgeLogoFiles(serviceClient, teamId)
const { error: uploadError } = await serviceClient.storage
.from('logos')
.upload(storagePath, buffer, { contentType: file.type, upsert: true })
if (uploadError) {
return NextResponse.json(
{ error: `Uppladdning misslyckades: ${getUserErrorMessage(uploadError)}` },
{ status: 500 },
)
}
const { data: urlData } = serviceClient.storage.from('logos').getPublicUrl(storagePath)
const { error: updateError } = await serviceClient
.from('brands')
.update({ logo_url: urlData.publicUrl })
.eq('team_id', teamId)
if (updateError) {
return NextResponse.json({ error: 'Kunde inte uppdatera varumärket.' }, { status: 500 })
}
clearBrandCache()
return NextResponse.json({ data: { logo_url: urlData.publicUrl } })
}
export async function DELETE() {
const { user, error } = await requireAuth()
if (error) return error
const { teamId, serviceClient, errorResponse } = await requireByraBrandAccess(user.id)
if (errorResponse) return errorResponse
const { data: brand } = await serviceClient
.from('brands')
.select('id, logo_url')
.eq('team_id', teamId)
.maybeSingle()
if (!brand) {
return NextResponse.json({ error: 'Ingen varumärkesprofil är aktiverad ännu.' }, { status: 404 })
}
await purgeLogoFiles(serviceClient, teamId)
const { error: updateError } = await serviceClient
.from('brands')
.update({ logo_url: null })
.eq('team_id', teamId)
if (updateError) {
return NextResponse.json({ error: 'Kunde inte uppdatera varumärket.' }, { status: 500 })
}
clearBrandCache()
return NextResponse.json({ data: { logo_url: null } })
}
+96
View File
@@ -0,0 +1,96 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { getByraMembership } from '@/lib/clients/fetch-client-overview'
import { requireByraBrandAccess } from '@/lib/byra/brand-access'
import { clearBrandCache } from '@/lib/branding/resolve'
import { validateBody } from '@/lib/api/validate'
import { ByraBrandUpdateSchema } from '@/lib/api/schemas'
/**
* GET /api/byra/brand
* The caller's byrå brand profile for the Varumärke settings section.
*
* Team-scoped, not company-scoped: uses requireAuth() directly (like
* /api/team/members) because the byrå cockpit has no active-company
* context. requireAuth still enforces MFA (AAL2) on hosted.
*
* Reads the brands row directly through the service client instead of the
* cached resolveBrandForTeam(): the settings form must show what is stored
* NOW, not a value up to 60s stale (lib/branding/resolve.ts cache).
*/
export async function GET() {
const { user, error } = await requireAuth()
if (error) return error
const serviceClient = createServiceClient()
const membership = await getByraMembership(serviceClient, user.id)
if (!membership) {
return NextResponse.json({ error: 'Endast för byråteam.' }, { status: 403 })
}
const { data: brand, error: brandError } = await serviceClient
.from('brands')
.select('domain, app_name, logo_url')
.eq('team_id', membership.teamId)
.maybeSingle()
if (brandError) {
return NextResponse.json({ error: 'Kunde inte hämta varumärket.' }, { status: 500 })
}
const canEdit = membership.role === 'owner' || membership.role === 'admin'
if (!brand) {
return NextResponse.json({
data: { hasBrand: false, domain: null, appName: null, logoUrl: null, canEdit },
})
}
return NextResponse.json({
data: {
hasBrand: true,
domain: brand.domain,
appName: brand.app_name,
logoUrl: brand.logo_url,
canEdit,
},
})
}
/**
* PATCH /api/byra/brand
* Byrå self-service app name (WL-17): the name shown beside the sidebar
* logo and across branded chrome. Owner/admin only; domain and colors stay
* ops-managed. Same service-client write path as the logo route.
*/
export async function PATCH(request: Request) {
const { user, error } = await requireAuth()
if (error) return error
const { teamId, serviceClient, errorResponse } = await requireByraBrandAccess(user.id)
if (errorResponse) return errorResponse
const validation = await validateBody(request, ByraBrandUpdateSchema)
if (!validation.success) return validation.response
const { data: brand } = await serviceClient
.from('brands')
.select('id')
.eq('team_id', teamId)
.maybeSingle()
if (!brand) {
return NextResponse.json({ error: 'Ingen varumärkesprofil är aktiverad ännu.' }, { status: 404 })
}
const { error: updateError } = await serviceClient
.from('brands')
.update({ app_name: validation.data.appName })
.eq('team_id', teamId)
if (updateError) {
return NextResponse.json({ error: 'Kunde inte uppdatera varumärket.' }, { status: 500 })
}
clearBrandCache()
return NextResponse.json({ data: { app_name: validation.data.appName } })
}
+201
View File
@@ -0,0 +1,201 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createQueuedMockSupabase,
createMockRequest,
parseJsonResponse,
} from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET } from '../route'
const noParams = { params: Promise.resolve({}) }
function authed() {
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
}
function unauthed() {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
function isoDaysFromNow(days: number): string {
const d = new Date()
d.setHours(0, 0, 0, 0)
d.setDate(d.getDate() + days)
// Local date parts, not toISOString(): UTC conversion would shift the day
// in timezones ahead of UTC and skew the urgency math under test.
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
beforeEach(() => {
vi.clearAllMocks()
reset()
})
describe('GET /api/clients', () => {
it('returns 401 when unauthenticated', async () => {
unauthed()
const res = await GET(createMockRequest('/api/clients'), noParams)
expect(res.status).toBe(401)
})
it('returns 403 for a user without a byrå team', async () => {
authed()
// Query 1: byrå team membership lookup: no rows.
enqueue({ data: [] })
const res = await GET(createMockRequest('/api/clients'), noParams)
const { status, body } = await parseJsonResponse<{
error: { code: string }
}>(res)
expect(status).toBe(403)
expect(body.error.code).toBe('FORBIDDEN')
})
it('aggregates one urgency-sorted row per client company', async () => {
authed()
// 1. byrå membership
enqueue({
data: [
{
team_id: 'team-1',
role: 'admin',
teams: { id: 'team-1', name: 'Siffra', kind: 'byra' },
},
],
})
// 2. client companies
enqueue({
data: [
{ id: 'c1', name: 'Alpha AB', org_number: '5560125790' },
{ id: 'c2', name: 'Beta AB', org_number: null },
],
})
// 3. company_settings (display names)
enqueue({
data: [{ company_id: 'c1', company_name: 'Alpha Redovisning AB', org_number: null }],
})
// 4. unbooked transactions (canonical predicate)
enqueue({
data: [
{ id: 't1', company_id: 'c1' },
{ id: 't2', company_id: 'c1' },
{ id: 't3', company_id: 'c1' },
{ id: 't4', company_id: 'c2' },
],
})
// 5. inbox items with a document that became nothing
enqueue({ data: [{ id: 'i1', company_id: 'c1', document_id: 'd1' }] })
// 6. document backstop: d1 still unlinked
enqueue({ data: [{ id: 'd1', company_id: 'c1' }] })
// 7. open deadlines: c2 has an overdue one
enqueue({
data: [
{
id: 'dl1',
company_id: 'c2',
title: 'Momsdeklaration',
due_date: isoDaysFromNow(-5),
tax_deadline_type: 'vat_declaration',
status: 'overdue',
},
],
})
// 8. latest posted verifikat per company (embedded)
enqueue({
data: [
{ id: 'c1', journal_entries: [{ entry_date: '2026-07-15' }] },
{ id: 'c2', journal_entries: [] },
],
})
const res = await GET(createMockRequest('/api/clients'), noParams)
const { status, body } = await parseJsonResponse<{
data: {
team: { id: string; name: string }
role: string
clients: Array<{
companyId: string
name: string
orgNumber: string | null
unbookedCount: number
inboxCount: number
nextDeadline: { urgency: string; dueDate: string } | null
lastBookedDate: string | null
}>
}
}>(res)
expect(status).toBe(200)
expect(body.data.team).toEqual({ id: 'team-1', name: 'Siffra' })
expect(body.data.role).toBe('admin')
// Urgency sort: c2 (overdue deadline) before c1 (bigger unbooked pile).
expect(body.data.clients.map((c) => c.companyId)).toEqual(['c2', 'c1'])
const [c2, c1] = body.data.clients
expect(c2).toMatchObject({
name: 'Beta AB',
unbookedCount: 1,
inboxCount: 0,
lastBookedDate: null,
})
expect(c2.nextDeadline).toMatchObject({
urgency: 'overdue',
dueDate: isoDaysFromNow(-5),
})
expect(c1).toMatchObject({
// company_settings display name wins over the frozen companies.name
name: 'Alpha Redovisning AB',
orgNumber: '5560125790',
unbookedCount: 3,
inboxCount: 1,
nextDeadline: null,
lastBookedDate: '2026-07-15',
})
})
it('returns an empty client list for a byrå without companies', async () => {
authed()
enqueue({
data: [
{
team_id: 'team-1',
role: 'member',
teams: { id: 'team-1', name: 'Siffra', kind: 'byra' },
},
],
})
enqueue({ data: [] }) // no client companies
const res = await GET(createMockRequest('/api/clients'), noParams)
const { status, body } = await parseJsonResponse<{
data: { role: string; clients: unknown[] }
}>(res)
expect(status).toBe(200)
expect(body.data.role).toBe('member')
expect(body.data.clients).toEqual([])
})
})
+40
View File
@@ -0,0 +1,40 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { resolveBrandByHost } from '@/lib/branding/resolve'
import { resolveBrandsForTeams } from '@/lib/branding/team-brands'
import { resolveLandingPath } from '@/lib/company/home-domain'
/**
* GET /api/clients/landing
*
* Post-login landing decision (WL-14): byrå staff land in the cockpit
* ('/clients') when the current host is their byrå's home domain: the byrå's
* brand domain, or the canonical domain for a byrå without white label
* (WL-01). Everyone else gets '/' so their flow stays byte-identical. Called
* by the login and MFA-verify pages when no explicit destination was
* requested; any failure degrades to '/' at the caller.
*/
export const GET = withRouteContext('clients.landing', async (request, ctx) => {
const host =
request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? ''
const hostBrand = host ? await resolveBrandByHost(host) : null
const { data: memberships } = await ctx.supabase
.from('team_members')
.select('team_id, teams:team_id!inner(kind)')
.eq('user_id', ctx.user.id)
.eq('teams.kind', 'byra')
const byraTeamIds = (memberships ?? []).map((m) => m.team_id as string)
if (byraTeamIds.length === 0) {
return NextResponse.json({ data: { destination: '/' } })
}
const brandByTeam = await resolveBrandsForTeams(byraTeamIds)
const destination = resolveLandingPath({
hostBrandTeamId: hostBrand?.teamId ?? null,
byraTeams: byraTeamIds.map((id) => ({ teamId: id, hasBrand: brandByTeam.has(id) })),
})
return NextResponse.json({ data: { destination } })
})

Some files were not shown because too many files have changed in this diff Show More