Files
accounted/components/settings/InvoiceEmailTextsSettings.tsx
T
Mattsson 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

214 lines
7.3 KiB
TypeScript

'use client'
import { useCallback, useRef, useState } from 'react'
import { useTranslations } from 'next-intl'
import { useToast } from '@/components/ui/use-toast'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import {
SettingsGroup,
SettingsInput,
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
SettingsSeg,
SettingsTextarea,
} from '@/components/settings/SettingsRows'
import {
INVOICE_EMAIL_DEFAULT_TEXTS,
INVOICE_EMAIL_PLACEHOLDER_KEYS,
} from '@/lib/email/invoice-templates'
import type { CompanySettings, InvoiceEmailTextOverrides, InvoiceEmailTexts } from '@/types'
interface InvoiceEmailTextsSettingsProps {
settings: CompanySettings
onUpdate: (updates: Partial<CompanySettings>) => void
}
type Lang = 'sv' | 'en'
type Field = keyof InvoiceEmailTextOverrides
const LANGS: Lang[] = ['sv', 'en']
const FIELD_CONFIG: Array<{ field: Field; labelKey: string; multiline?: boolean }> = [
{ field: 'subject', labelKey: 'subject_label' },
{ field: 'greeting', labelKey: 'greeting_label' },
{ field: 'body', labelKey: 'body_label', multiline: true },
{ field: 'signoff', labelKey: 'signoff_label' },
]
// The editor always shows the EFFECTIVE text (override or standard), never an
// empty field: users see and edit the mail that actually goes out.
type DisplayTexts = Record<Lang, Record<Field, string>>
function buildDisplay(stored: InvoiceEmailTexts | null | undefined): DisplayTexts {
const result = {} as DisplayTexts
for (const lang of LANGS) {
result[lang] = {} as Record<Field, string>
for (const { field } of FIELD_CONFIG) {
const value = stored?.[lang]?.[field]
result[lang][field] =
typeof value === 'string' && value.trim() !== ''
? value
: INVOICE_EMAIL_DEFAULT_TEXTS[lang][field]
}
}
return result
}
// Cleared fields have no meaning of their own: snap them back to standard.
function normalize(display: DisplayTexts): DisplayTexts {
const result = {} as DisplayTexts
for (const lang of LANGS) {
result[lang] = {} as Record<Field, string>
for (const { field } of FIELD_CONFIG) {
const value = display[lang][field]
result[lang][field] =
value.trim() === '' ? INVOICE_EMAIL_DEFAULT_TEXTS[lang][field] : value
}
}
return result
}
// Store only changes: a field equal to the standard text is NOT an override,
// so future improvements to the standard wording reach every company that
// hasn't customized. Empty result → null (column reads "all defaults").
function toOverrides(display: DisplayTexts): InvoiceEmailTexts | null {
const result: InvoiceEmailTexts = {}
for (const lang of LANGS) {
const langOverrides: InvoiceEmailTextOverrides = {}
for (const { field } of FIELD_CONFIG) {
const value = display[lang][field].trim()
if (value !== '' && value !== INVOICE_EMAIL_DEFAULT_TEXTS[lang][field]) {
langOverrides[field] = value
}
}
if (Object.keys(langOverrides).length > 0) result[lang] = langOverrides
}
return Object.keys(result).length > 0 ? result : null
}
export function InvoiceEmailTextsSettings({ settings, onUpdate }: InvoiceEmailTextsSettingsProps) {
const t = useTranslations('settings_email_texts')
const { toast } = useToast()
const { canWrite } = useCanWrite()
const [lang, setLang] = useState<Lang>('sv')
const [texts, setTexts] = useState<DisplayTexts>(() => buildDisplay(settings.invoice_email_texts))
// Serialized last-persisted overrides: skips no-op PUTs on blur without
// edits. toOverrides() builds keys in a fixed order, so comparison is stable.
const lastSavedRef = useRef<string>(
JSON.stringify(toOverrides(buildDisplay(settings.invoice_email_texts))),
)
const setField = (lang: Lang, field: Field, value: string) => {
setTexts((prev) => ({ ...prev, [lang]: { ...prev[lang], [field]: value } }))
}
// Whole-object save: a JSONB column update replaces the stored value, and
// the inactive language's fields are unmounted (conditional render below),
// so per-field PATCHes can't work.
const persist = useCallback(async (display: DisplayTexts) => {
const overrides = toOverrides(display)
const serialized = JSON.stringify(overrides)
if (serialized === lastSavedRef.current) return
try {
const response = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ invoice_email_texts: overrides }),
})
if (!response.ok) throw new Error()
lastSavedRef.current = serialized
onUpdate({ invoice_email_texts: overrides })
} catch {
toast({ title: t('toast_save_failed'), variant: 'destructive' })
}
}, [onUpdate, toast, t])
const handleBlur = () => {
const normalized = normalize(texts)
setTexts(normalized)
void persist(normalized)
}
const resetField = (lang: Lang, field: Field) => {
const next = {
...texts,
[lang]: { ...texts[lang], [field]: INVOICE_EMAIL_DEFAULT_TEXTS[lang][field] },
}
setTexts(next)
void persist(next)
}
return (
<SettingsGroup
label={t('heading')}
help={
<div className="space-y-2">
<p>{t('description')}</p>
{/* Legend is rendered from code, not messages/*.json: ICU message
syntax treats literal braces as interpolation. */}
<p>
{t('placeholders_help')}{' '}
{INVOICE_EMAIL_PLACEHOLDER_KEYS.map((key) => (
<code key={key} className="mr-1 rounded bg-muted px-1 text-xs">{`{${key}}`}</code>
))}
</p>
<p>{t('firstname_note')}</p>
</div>
}
>
<div className="flex flex-wrap items-center gap-3 border-b border-border px-1 py-3">
<SettingsSeg
value={lang}
onChange={setLang}
options={[
{ value: 'sv', label: t('tab_sv') },
{ value: 'en', label: t('tab_en') },
]}
aria-label={t('heading')}
/>
{lang === 'en' && <SettingsRowNote>{t('en_tab_hint')}</SettingsRowNote>}
</div>
{FIELD_CONFIG.map(({ field, labelKey, multiline }) => {
const id = `invoice-email-${field}-${lang}`
const modified =
texts[lang][field].trim() !== INVOICE_EMAIL_DEFAULT_TEXTS[lang][field]
const common = {
id,
value: texts[lang][field],
onBlur: handleBlur,
disabled: !canWrite,
}
return (
<SettingsRow key={`${lang}-${field}`} label={t(labelKey)} htmlFor={id} align="baseline">
{multiline ? (
<SettingsTextarea
{...common}
rows={4}
onChange={(e) => setField(lang, field, e.target.value)}
/>
) : (
<SettingsInput
{...common}
onChange={(e) => setField(lang, field, e.target.value)}
/>
)}
{modified && canWrite && (
<SettingsRowEnd>
<button
type="button"
onClick={() => resetField(lang, field)}
className="text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
{t('reset_label')}
</button>
</SettingsRowEnd>
)}
</SettingsRow>
)
})}
</SettingsGroup>
)
}