Files
accounted/components/settings/sections/BillingSettingsContent.tsx
T
MattssonandClaude Opus 5 d54b43f80f Bug/resend and invoices (#1192)
* fix(invoices): anchor the PDF logo to the top-left of its header cell

The logo box is always the full 240x80pt reserved area (any larger logo is
clamped to exactly that), so objectFit: 'contain' placed the image inside it
with the default 50% 50% centering. A wide banner logo fills the width and
lands on the left margin, but a near-square logo scaled down to the 80pt
height cap is only ~117pt wide and got pushed ~60pt in from the margin, which
reads as a misaligned logo and forced companies to reshape their artwork.

Anchor the image top-left so every aspect ratio starts at the margin.

Covered by a test that renders the real PDF and reads the image placement
matrix out of the content stream, for both a wide and a near-square logo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(invoices): show the real delivery outcome in the send history

"Skickad" only meant the email provider accepted the message, so a bounced
invoice looked identical to one that arrived. Resend reports the outcome
asynchronously; that report now lands on the delivery row and drives the
history: green is reserved for a confirmed delivery, bounce/blocked reads
red, delayed and spam-marked read amber, and an accepted-but-unconfirmed
send is neutral instead of falsely green.

The report arrives on a signed webhook and may only touch the three new
provider status columns of an already sent, unredacted row: the WORM trigger
proves nothing else changed, and a lower ranked or older report can never
downgrade an observed failure. The provider reason text can quote the failing
address, so it is masked on read and cleared by the daily PII redaction job.

Timestamps also formatted in Europe/Stockholm instead of falling back to the
runtime zone, which rendered a 14:05 send as 12:05 on Vercel.

Delivery reports are per message, never per recipient: Resend sends one event
for the whole message, so splitting a send per recipient would be the only way
to get finer granularity, at the cost of CC.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(stripe): make the integration feed-only

Stripe sync now only imports balance transactions into the transactions
inbox, like any bank feed; nothing auto-books. The event/settlement sync
(lib/sync.ts, lib/payouts.ts) stays in the repo but is no longer wired to
any route or cron: the 15-min sync cron is removed from vercel.json.
Payment links on invoice send are unchanged; their payments arrive as
feed rows and are matched manually.

- /sync runs only syncStripeBalanceTransactions; response is { success,
  transactions }
- connecting via OAuth enables the nightly feed by default (toggle stays
  as opt-out)
- panel: needs-review section and plumbing removed, copy rewritten to
  transactions-first (sv + en), toast reports fetched/imported/linked
  and calls out an empty result instead of silent all-zeros

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

* fix(api): return the article currency from the v1 article list

The dashboard, importer, export and MCP article surfaces all learned to
carry a non-SEK article price (#1166, #1183, #1184), but the v1
projection still omitted currency. An API or agent caller therefore read
price_excl_vat with nothing marking it as EUR and would copy the number
straight onto a SEK invoice line, at a nine-to-one error.

Adds currency to the projection, the response shape and the example, plus
a pitfall stating the price is not always SEK and that this endpoint does
no FX conversion.

Additive field only; no migration (articles.currency already exists).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(settings): replace the settings modal with a routed panel sheet

Settings now renders as a sheet that fills the main panel, sliding up over the
page the user came from and back down on close, with the sidebar and frame left
visible and usable. Behind it sits one shared master-detail surface: underline
search across every section and subsection, the grouped section rail, and the
active section as a direct-editing accordion. All 11 sections are decomposed
into subsections, and the legacy *SettingsContent components compose the same
pieces so the stacked and accordion layouts cannot drift.

The sheet is the only presentation, on every entry path. The intercepting route
handles in-app navigation and closes by popping the history entry, landing back
on the page underneath. @settingsModal/default.tsx handles cold loads (refresh,
deep link, new tab), where interception never fires; nothing is mounted
underneath there, so it closes to the dashboard. Both branch on one shared
predicate, isSheetSection, together with the settings layout, which must render
nothing for those sections or the surface would stack twice behind the sheet
and run every section's fetches twice.

Closing is deliberate rather than incidental: the X, Esc, or navigating away.
The dialog is non-modal so the sidebar's account popover and company switcher
keep working with settings up, and an outside click no longer dismisses it.
Sections land fully collapsed, and the scroll position of the page behind
survives opening and closing the sheet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat: enhance article management and settings UI

- Add PATCH test for toggling article active state without other fields.
- Remove unused MessageCircle icon from DashboardContent.
- Refactor AccountingFrameworkForm to use SettingsFieldRow for better help text display.
- Update CompanyInfoForm, DimensionsToggle, and various settings forms to replace description with help text.
- Remove redundant headings and intros in several settings components to streamline UI.
- Improve help text for various settings in English and Swedish translations.
- Update structured error messages for better clarity on article deletion.

* refactor(ArticleDetailPage): remove unused imports and duplicate state variable

* fix(settings): own deep-linked settings routes by route list, not nav visibility

Review fixes from the settings panel sheet work:
* isSheetSection reads the full settings route list so a hidden-but-deep-linked
  section (assistant before BankID, banking in sandbox, api without MCP) is
  claimed by the sheet instead of rendering the legacy shell around an empty panel
* keep 503 on the Resend delivery webhook when the signing secret is unset, with
  a test pinning the behaviour
* stripe callback route test coverage

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: update salary, tax, and templates settings components

- Refactored SalarySettingsContent to use a form wrapper and improved payment settings UI.
- Enhanced TaxSettingsContent with new signals for EU sales, KU obligations, and ROT/RUT deductions.
- Updated TemplatesSettingsContent to remove legacy comments and improve readability.
- Simplified navigation items by removing unnecessary constants and directly using hrefs.
- Cleaned up translation files by removing deprecated keys and adding new descriptions for clarity.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-25 22:56:17 +02:00

249 lines
8.9 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Check } from 'lucide-react'
import { AttnLine } from '@/components/ui/attn-line'
import { Skeleton } from '@/components/ui/skeleton'
import {
SettingsGroup,
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
SettingsSectionHeader,
} from '@/components/settings/SettingsRows'
import { formatDateLong } from '@/lib/utils'
import { BillingActions } from '@/components/settings/BillingActions'
// What the paid tier unlocks (mirrors lib/entitlements PAID_CAPABILITIES).
const INCLUDED = [
'AI-assistent: chatt, kategorisering och dokumenttolkning',
'Bankkoppling och automatisk synk (PSD2)',
'Skatteverket: moms- och AGI-inlämning',
'E-postutskick av fakturor, påminnelser och lönebesked',
]
// What stays free forever (freeze-and-retain, nothing is taken away). Shown
// as the second column of the flat feature list so the paid tier reads
// strongest right next to it. Mirrors the old ALWAYS_FREE copy.
const ALWAYS_FREE = [
'Bokföring och rapporter',
'Fakturering',
'SIE-export',
'Org.nr-uppslag och momsnummerkontroll',
]
// Mirrors the checkout route's deferred-first-charge condition (Stripe's 48h
// trial_end floor plus clock margin). Above this, checkout collects the card
// but the first charge lands when the trial ends.
const DEFER_THRESHOLD_MS = 49 * 3600 * 1000
interface BillingView {
isPaying: boolean
configured: boolean
trialEndsAt: string | null
daysLeft: number | null
chargeDeferred: boolean
paidJustNow: boolean
isDemo: boolean
}
function FeatureList({ heading, items }: { heading: string; items: string[] }) {
return (
<div>
<p className="text-xs font-medium text-muted-foreground">{heading}</p>
<ul className="mt-2 space-y-2">
{items.map((item) => (
<li key={item} className="flex items-start gap-2 text-sm">
<Check aria-hidden="true" className="mt-1 h-3.5 w-3.5 shrink-0 text-foreground" />
<span>{item}</span>
</li>
))}
</ul>
</div>
)
}
/**
* Settings → Abonnemang. Rendered both as the full page (thin wrapper) and
* inside the settings modal (via SETTINGS_SECTIONS), so it's a client component
* that reads its state from GET /api/billing/status.
*/
export function BillingSettingsContent() {
const tNav = useTranslations('settings_nav')
const tIntro = useTranslations('settings_intro')
const [view, setView] = useState<BillingView | null>(null)
useEffect(() => {
let active = true
fetch('/api/billing/status')
.then((r) => r.json())
.then((d: { isPaying: boolean; configured: boolean; trialEndsAt: string | null; isDemo?: boolean }) => {
if (!active) return
// Compute time-derived state here (effect), not during render, to keep render pure.
const msLeft = d.trialEndsAt ? new Date(d.trialEndsAt).getTime() - Date.now() : null
const daysLeft = msLeft !== null ? Math.max(0, Math.ceil(msLeft / 86_400_000)) : null
const chargeDeferred = msLeft !== null && msLeft > DEFER_THRESHOLD_MS
// Set by the checkout success redirect. Provisioning happens via the
// Stripe webhook, so isPaying can lag the redirect by a few seconds.
const paidJustNow = new URLSearchParams(window.location.search).get('success') === '1'
setView({ ...d, daysLeft, chargeDeferred, paidJustNow, isDemo: d.isDemo ?? false })
})
.catch(() => {
if (active)
setView({
isPaying: false,
configured: false,
trialEndsAt: null,
daysLeft: null,
chargeDeferred: false,
paidJustNow: false,
isDemo: false,
})
})
return () => { active = false }
}, [])
const header = <SettingsSectionHeader title={tNav('billing')} intro={tIntro('billing')} />
if (!view) {
return (
<div>
{header}
<div className="mt-6 space-y-4">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-64 w-full" />
</div>
</div>
)
}
// Demo / sandbox account → can't check out. Show the value prop but point
// them to creating a real account instead of a pay button that would 403.
if (view.isDemo) {
return (
<div>
{header}
<SettingsGroup label="Ditt abonnemang">
<SettingsRow label="Status" borderless>
<span>Demo</span>
<SettingsRowNote>
Du provkör Accounted i en demo. Skapa ett riktigt konto för att aktivera
abonnemang, AI-assistent, bankkoppling och inlämning till Skatteverket.
</SettingsRowNote>
</SettingsRow>
</SettingsGroup>
<SettingsGroup label="I abonnemanget">
<ul className="space-y-2 px-1 pt-3">
{INCLUDED.map((item) => (
<li key={item} className="flex items-start gap-2 text-sm">
<Check aria-hidden="true" className="mt-1 h-3.5 w-3.5 shrink-0 text-foreground" />
<span>{item}</span>
</li>
))}
</ul>
</SettingsGroup>
</div>
)
}
// Paying company → manage view.
if (view.isPaying) {
return (
<div>
{header}
<SettingsGroup label="Ditt abonnemang">
<SettingsRow label="Status" borderless>
<span>Aktivt</span>
<SettingsRowNote>Du kan hantera eller avsluta det när som helst.</SettingsRowNote>
<SettingsRowEnd>
<BillingActions isPaying configured={view.configured} />
</SettingsRowEnd>
</SettingsRow>
</SettingsGroup>
</div>
)
}
// Just returned from checkout but the webhook hasn't flipped isPaying yet →
// confirm instead of re-showing the sell pitch to someone who already paid.
if (view.paidJustNow) {
return (
<div>
{header}
<SettingsGroup label="Ditt abonnemang">
<SettingsRow label="Status" borderless>
<span className="flex items-start gap-2">
<Check aria-hidden="true" className="mt-1 h-3.5 w-3.5 shrink-0 text-foreground" />
<span>Klart! Ditt abonnemang är aktiverat och alla funktioner låses upp inom någon minut.</span>
</span>
<SettingsRowNote>Ladda om sidan om du inte ser ändringen.</SettingsRowNote>
</SettingsRow>
</SettingsGroup>
</div>
)
}
// Trialing / expired → sell view.
const { trialEndsAt, daysLeft } = view
const deferredTo = view.chargeDeferred ? trialEndsAt : null
return (
<div>
{header}
{/* Consequential trial countdown: one attn-tone sentence, not a banner. */}
{daysLeft !== null && (
<AttnLine className="mt-3">
{daysLeft > 0
? `Din provperiod löper ut om ${daysLeft} ${daysLeft === 1 ? 'dag' : 'dagar'}${
trialEndsAt ? ` (${formatDateLong(trialEndsAt)})` : ''
}. ${
deferredTo
? 'Lägg till ditt kort nu: inget dras förrän provperioden är slut.'
: 'Lägg till betalning nu så fortsätter allt utan avbrott.'
}`
: 'Din provperiod har löpt ut. Aktivera abonnemanget för att få tillbaka AI, bankkoppling och inlämning.'}
</AttnLine>
)}
<SettingsGroup
label="Allt du behöver för att sköta bokföringen själv"
help="Ingen bindningstid · Avsluta när du vill · Säker betalning via Stripe"
>
<div className="px-1 pt-3">
<BillingActions isPaying={false} configured={view.configured} firstChargeAt={deferredTo} />
</div>
</SettingsGroup>
{deferredTo && (
<SettingsGroup label="Så funkar det">
<SettingsRow label="Idag">
<span>Du lägger till ditt kort. Inget dras nu.</span>
</SettingsRow>
<SettingsRow label={<span className="tabular-nums">{formatDateLong(deferredTo)}</span>}>
<span>Provperioden slutar och den första debiteringen sker.</span>
</SettingsRow>
<SettingsRow label="När som helst" borderless>
<span>
Avsluta direkt via Stripe. Före {formatDateLong(deferredTo)} kostar det ingenting.
</span>
</SettingsRow>
</SettingsGroup>
)}
<SettingsGroup
label="Funktioner"
// The 7-year retention reassurance moved behind the "?": long legal
// copy stays out of the page flow.
help="Utan abonnemang behåller du bokföringen, fakturorna, rapporterna och all din data utan kostnad. Ingenting raderas: räkenskapsinformation bevaras i sju år enligt bokföringslagen, oavsett abonnemang."
>
<div className="grid gap-6 px-1 pt-3 sm:grid-cols-2">
<FeatureList heading="I abonnemanget" items={INCLUDED} />
<FeatureList heading="Alltid gratis" items={ALWAYS_FREE} />
</div>
</SettingsGroup>
</div>
)
}