Add/stripe skv (#1004)

* fix(salary): align pain.001 salary file with the Swedish domestic bank dialect

Verified against the Swedish Common Interpretation of ISO 20022
(Bankforeningen, Common Payment Types in Sweden, Appendix 1 Example 4:
Salaries) and Nordea Corporate Access pain.001 examples v2.6 (2026-06-22),
and XSD-validated against the official pain.001.001.03 schema:

- drop SvcLvl SEPA (SEPA credit transfers are EUR-only; omitting SvcLvl
  gets the domestic NURG default)
- drop RmtInf (not allowed for SALA salary payments; the beneficiary
  statement text comes from the Dataclearing LON code)
- address employees domestically: clearing as CdtrAgt ClrSysMmbId SESBA,
  account WITHOUT clearing as CdtrAcct Othr with SchmeNm BBAN
- share the clearing/account split (Swedbank 5-digit shift, Nordea
  personkonto prefix dedup) between the LB and pain.001 generators via
  splitDomesticBankAccount, fixing pain.001 duplicating the personkonto
  clearing
- clamp MsgId/PmtInfId/InstrId/EndToEndId to Max35Text with the per-tx
  counter surviving truncation; carry the org number on Dbtr
- return 400 from the pain001 route on an invalid clearing instead of
  emitting a broken file

Also includes two unrelated decision-log lines from the parallel
revisor-review session (DECISIONS.md is a shared append-only log).

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

* feat(nav): surface the year-end chain in the sidebar

Add Periodiseringar, Arsredovisning (aktiebolag only) and
Inkomstdeklaration (INK2 for AB, NE-bilaga for EF) to the Skatt &
bokslut group, in workflow order. Entity gating via a new entityOnly
flag on NavItem; isActive carve-outs extended so exactly one row
lights up for the new routes. Driven by an external revisor review
that concluded these features did not exist because none of them
were reachable from the nav.

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

* feat(stripe): Stripe Connect integration behind config gate

Connect OAuth per company (only the acct_ id is stored), automatic
single-use Payment Links on invoice send, deterministic payment
settlement against 1686 (BAS moved acquirer receivables 1580 -> 1686),
payout booking with reverse-charge fees (6570 + 4535/4598 + 2645/2614),
and a 15-minute sync cron. Non-deterministic events land as
needs_review, never guessed at.

Fully dark without STRIPE_CONNECT_CLIENT_ID: connect returns 503, the
send hook and cron no-op, and the settings page shows 'Kommer snart'
(hosted) until the Connect platform is verified. Self-hosted keeps the
honest not-configured message.

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

* fix(deadlines): add shared completeTaxDeadline and fix dead AGI deadline auto-complete

generate-declaration.ts has updated non-existent columns (type/period/
status) since inception, so the arbetsgivardeklaration deadline was
never auto-completed. Replace with a shared helper targeting the real
schema (tax_deadline_type/tax_period/is_completed), also used by the
kvittens crons and moms handlers in the follow-up commit.

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

* feat(rot-rut): import Skatteverket beslutsfil and record decisions on payout requests

Parse the beslutsfil JSON from Skatteverkets rot/rut e-tjanst and record
godkant belopp on the matching begaran: matched by stored
skv_referensnummer first, then exact name among active undecided
requests; arenden by fakturanummer then personnummer, exactly-one or the
beslut errors (all-or-nothing). Never auto-settles: recording the beslut
and booking the payout are separate acts. Exposed as an API route and
the gnubok_import_rot_rut_beslut MCP tool.

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

* feat(skatteverket): system auth for background reads, one-click VAT submit, kvittens notifications

Hybrid auth program: system CCG (org certificate) for background reads
while personal BankID stays for interactive submissions, since SKV
per-flow refresh tokens live 65 min and crons structurally cannot run
on them. All system-auth code sits behind SKATTEVERKET_SYSTEM_AUTH_MODE
(default off) with a stub transport until the Expisoft cert and CCG
avtal land; auth resolution is centralized in resolve-auth.ts.

Also in this change:
- One-click VAT submit chaining kontrollera -> utkast -> las
  server-side with a stage discriminator; step-by-step buttons demoted
  to the overflow menu.
- Kvittens crons (AGI + new VAT schedule) with email-only
  notifications, deduped in notification_log under the new
  skv_kvittens type.
- Ombud grant probe + verification UI in the connect panel, and a
  dashboard promo card for unconnected companies.
- skatteverket_company_connections table with pg-real coverage.

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

* feat(salary): auto-settle AGI tax payment from skattekonto and surface SKV reconnect on the tax card

The "Skatt att betala" card only cleared via the manual mark-paid button
on the run detail page; the promised automatic flip from the Skattekonto
sync was never implemented, so paid periods stayed red.

- settleAgiTaxPayments: during every skattekonto sync, a booked
  "Arbetsgivardeklaration YYYYMM" debit row settles the matching
  agi_declarations.tax_paid_at, but only when the amount equals the
  declared total to the ore and the account is not in deficit
  (deterministic; drift or deficit falls back to manual).
- Salary overview card: reconnect hint when the SKV token needs
  re-consent (link to /settings/tax, silent when the extension is off),
  plus an inline "Markera som betald" button reusing the existing
  endpoint and salary_payments strings.

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

* Add cloud backup scheduling and alerting features

- Implement unit tests for scheduling logic in `schedule.test.ts`, covering various scenarios for determining if a backup schedule is due.
- Create a new module `backup-alert.ts` to handle failure alerts for cloud backup auto-sync, including email notifications for reauthentication and repeated failures.
- Introduce `schedule.ts` to manage scheduling logic, including handling local time zones and converting between local and UTC hours.
- Add CSV report generation functions in `archive-csv.ts` for trial balance, income statement, balance sheet, and general ledger, ensuring compatibility with Swedish Excel formats.
- Create a README generator for the archive structure in `archive-readme.ts`, providing clear documentation for users accessing backup files.
- Implement tests for CSV report generation in `archive-csv.test.ts`, ensuring correct formatting and content.
- Establish a full-archive coverage contract test in `full-archive-coverage.pg.test.ts` to ensure all company-scoped tables are properly classified for backup.

* fix(stripe): correct invoice clearing reference and improve type safety in sync logic

* fix(invoices): narrow accountingMethod before resolveInvoicePaymentSourceType

settleInvoicePayment takes accountingMethod as a raw settings string, but
resolveInvoicePaymentSourceType requires the 'accrual' | 'cash' union.
Normalize at the call site (anything but 'cash' books as accrual), matching
the existing useCashEntry semantics.

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

* fix: address CodeRabbit review findings and nitpicks on PR #1004

Review findings:
- backup settings redirect: always force view=export over incoming params
- AGI/VAT kvittens crons: isolate best-effort post-submit calls, check the
  signed-state persist error, guard recovery calls in catch blocks so one
  company cannot abort the rest; surface grant_revoked in the run summary
- kvittens notifications: atomic claim-first dedup with a partial unique
  index; map non-uuid reference keys to deterministic uuids
- grant probe: record the actual 2xx status; mTLS transport: handle
  response-stream errors
- stripe: amount-aware idempotency keys for payment links; emit
  stripe.disconnected on upstream revocations
- ROT/RUT beslut import: mutate in-memory request state after apply, move
  item + header writes into an atomic apply_rot_rut_beslut RPC, add
  rot_rut_payout to JournalEntrySourceTypeSchema
- migrations: use NOT VALID + VALIDATE CONSTRAINT for CHECK constraints on
  journal_entries, notification_log and rot_rut_payout_requests
- cloud backup: hour_utc-only schedule updates clear stale hour_local

Nitpicks:
- stripe sync: enforce the cron time budget inside per-connection event
  processing with idempotent cursor progress; maybeSingle for settings;
  honest partial-customer DTO shared with the settlement boundary
- shared applyPaymentLinkToInvoice helper for both invoice send routes,
  v1 docblock documents step 6b and PAYMENT_LINK_FAILED
- settings panel: drop redundant decodeURIComponent
- cloud backup: document worst-case archive memory headroom

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-12 19:14:12 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent ee3c33c7a4
commit 98d0c7f2d0
136 changed files with 15312 additions and 1133 deletions
@@ -0,0 +1,66 @@
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { AlertTriangle } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
// Local mirror of the cloud-backup status shape: core must not import from
// @/extensions/, so the fields we read are declared here.
interface BackupStatus {
connected: boolean
needs_reauth: boolean
schedule: { last_auto_sync_status: 'success' | 'error' | null } | null
}
/**
* Warning shown on the dashboard ONLY when the Google Drive backup is failing
* (dead token or errored auto-sync). A backup that silently stops is worse
* than none; this makes the failure visible where the user actually is.
* Renders nothing when the extension is off, disconnected, or healthy.
*/
export default function BackupHealthBanner() {
const t = useTranslations('extensions')
const [status, setStatus] = useState<BackupStatus | null>(null)
useEffect(() => {
if (!ENABLED_EXTENSION_IDS.has('cloud-backup')) return
let cancelled = false
fetch('/api/extensions/ext/cloud-backup/status')
.then((res) => (res.ok ? res.json() : null))
.then((body) => {
if (!cancelled && body?.data) setStatus(body.data as BackupStatus)
})
.catch(() => {
// Fail silent: the dashboard must not degrade over a status probe.
})
return () => {
cancelled = true
}
}, [])
if (!status?.connected) return null
const failing =
status.needs_reauth || status.schedule?.last_auto_sync_status === 'error'
if (!failing) return null
return (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 p-4">
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-warning" />
<div className="flex-1 text-sm">
<p className="font-medium">
{status.needs_reauth
? t('ext_cloud_backup_banner_reauth')
: t('ext_cloud_backup_banner_failing')}
</p>
<Link
href="/import#cloud-backup"
className="mt-1 inline-block text-muted-foreground underline underline-offset-4 hover:text-foreground"
>
{t('ext_cloud_backup_banner_action')}
</Link>
</div>
</div>
)
}
+13
View File
@@ -12,6 +12,8 @@ import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import NewUserChecklist from '@/components/onboarding/NewUserChecklist'
import AttGoraSection from '@/components/dashboard/AttGoraSection'
import BackupHealthBanner from '@/components/dashboard/BackupHealthBanner'
import { SkatteverketPromoCard } from '@/components/dashboard/SkatteverketPromoCard'
import {
ChevronRight,
CheckCircle2,
@@ -121,6 +123,7 @@ export default function DashboardContent({ companyId, summary, worklist, suggest
return (
<div className="stagger-enter space-y-8">
<BackupHealthBanner />
{/* Build-assistant hero: shown only until the company has a verified
agent_profile, so existing/migrated users get a clear prompt instead
of a full-screen onboarding takeover. Once the assistant is built the
@@ -240,6 +243,16 @@ export default function DashboardContent({ companyId, summary, worklist, suggest
</div>
</section>
{/* Connect-Skatteverket nudge for existing companies. Gated on
agentBuilt so it never stacks under the build-assistant hero:
one CTA surface at a time. */}
{agentBuilt && (
<SkatteverketPromoCard
companyId={companyId}
connected={!!onboardingProgress?.hasSkatteverketConnected}
/>
)}
{/* Att göra: the unified worklist. One section, every actionable item,
same counts as the sidebar badges (lib/worklist). */}
<AttGoraSection
+43 -9
View File
@@ -38,7 +38,10 @@ import {
Percent,
Landmark,
CalendarClock,
CalendarRange,
FileCheck,
FileSpreadsheet,
ScrollText,
} from 'lucide-react'
import { getBranding } from '@/lib/branding/service'
import { ENABLED_EXTENSION_IDS as _ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
@@ -115,7 +118,10 @@ type NavLabelKey =
| 'vat_declaration'
| 'skattekonto'
| 'deadlines'
| 'periodiseringar'
| 'year_end'
| 'annual_report'
| 'income_declaration'
| 'help'
| 'settings'
@@ -153,6 +159,9 @@ interface NavItem {
// capability. Cosmetic only, the page and API gates are the real
// enforcement; this just keeps the sidebar honest for non-payers.
requiredCapability?: CapabilityKey
// Statutory surfaces that only exist for one company form (INK2 vs
// NE-bilaga, årsredovisning): hidden for the other entity type.
entityOnly?: EntityType
hidden?: boolean
comingSoon?: boolean
devBadge?: boolean
@@ -166,7 +175,6 @@ const navItems: NavItem[] = [
// Arbeta: everything the user produces. The bookkeeping funnel leads
// (Bokföring · Underlag · Transaktioner · Granskning: kept as separate
// rows until the unified workspace lands), then the transactional flows.
// Löner: "Beta" badge while we validate the end-to-end salary + AGI flow.
// employerOnly: shown to aktiebolag and to any employer (pays_salaries), so an
// enskild firma that hires staff gets payroll. Owner self-payroll stays
// blocked at the engine/DB layer (EF owner takes egna uttag, not lön). #782
@@ -176,7 +184,7 @@ const navItems: NavItem[] = [
{ href: '/pending', labelKey: 'review', icon: ClipboardCheck, group: 'arbeta' },
{ href: '/invoices', labelKey: 'invoices', icon: ReceiptText, group: 'arbeta' },
{ href: '/supplier-invoices', labelKey: 'supplier_invoices', icon: Wallet, group: 'arbeta' },
{ href: '/salary', labelKey: 'salary', icon: HandCoins, group: 'arbeta', employerOnly: true, betaBadge: true },
{ href: '/salary', labelKey: 'salary', icon: HandCoins, group: 'arbeta', employerOnly: true },
// Analys: read the numbers. KPI stays a separate row until the fused
// Rapporter surface (nav_ia_redesign §F) is built.
{ href: '/kpi', labelKey: 'kpi', icon: TrendingUp, group: 'analys' },
@@ -187,18 +195,26 @@ const navItems: NavItem[] = [
{ href: '/customers', labelKey: 'customers', icon: Users, group: 'data' },
{ href: '/suppliers', labelKey: 'suppliers', icon: Building2, group: 'data' },
{ href: '/articles', labelKey: 'articles', icon: Tag, group: 'data' },
{ href: '/salary/employees', labelKey: 'employees', icon: Users, group: 'data', employerOnly: true, betaBadge: true },
{ href: '/salary/employees', labelKey: 'employees', icon: Users, group: 'data', employerOnly: true },
{ href: '/assets', labelKey: 'assets', icon: Package, group: 'data' },
{ href: '/chart-of-accounts', labelKey: 'chart_of_accounts', icon: ListTree, group: 'data' },
{ href: '/dimensions', labelKey: 'dimensions', icon: Tags, group: 'data', requiresDimensions: true },
{ href: '/import', labelKey: 'import', icon: Upload, group: 'data' },
// Skatt & bokslut: everything submitted to the state. Rescues the
// previously nav-orphaned /skattekonto and /deadlines, and promotes the
// VAT declaration out of the report catalog.
// VAT declaration out of the report catalog. The year-end chain
// (periodiseringar → bokslut → årsredovisning → inkomstdeklaration) is
// listed in workflow order; the last two are entity-gated because the
// surfaces only exist for one company form (ÅR + INK2 for aktiebolag,
// NE-bilaga for enskild firma).
{ href: '/reports/vat-declaration', labelKey: 'vat_declaration', icon: Percent, group: 'skatt' },
{ href: '/skattekonto', labelKey: 'skattekonto', icon: Landmark, group: 'skatt' },
{ href: '/deadlines', labelKey: 'deadlines', icon: CalendarClock, group: 'skatt' },
{ href: '/bookkeeping/periodiseringar', labelKey: 'periodiseringar', icon: CalendarRange, group: 'skatt' },
{ href: '/bookkeeping/year-end', labelKey: 'year_end', icon: FileCheck, group: 'skatt' },
{ href: '/bookkeeping/year-end/arsredovisning', labelKey: 'annual_report', icon: ScrollText, group: 'skatt', entityOnly: 'aktiebolag' },
{ href: '/reports/ink2-declaration', labelKey: 'income_declaration', icon: FileSpreadsheet, group: 'skatt', entityOnly: 'aktiebolag' },
{ href: '/reports/ne-declaration', labelKey: 'income_declaration', icon: FileSpreadsheet, group: 'skatt', entityOnly: 'enskild_firma' },
]
// Map known extension hrefs to nav translation keys so sidebar labels translate.
@@ -306,14 +322,29 @@ export default function DashboardNav({ companyName: _companyName, entityType, pa
if (href === '/salary') {
return pathname === '/salary' || pathname.startsWith('/salary/runs')
}
// Bokslut (/bookkeeping/year-end) and Moms (/reports/vat-declaration)
// have their own rows under Skatt & bokslut: carve them out of their
// parent routes so exactly one row lights up.
// Routes with their own rows under Skatt & bokslut (Bokslut, Moms,
// Periodiseringar, Årsredovisning, Inkomstdeklaration) are carved out
// of their parent routes so exactly one row lights up.
if (href === '/bookkeeping') {
return pathname.startsWith('/bookkeeping') && !pathname.startsWith('/bookkeeping/year-end')
return (
pathname.startsWith('/bookkeeping') &&
!pathname.startsWith('/bookkeeping/year-end') &&
!pathname.startsWith('/bookkeeping/periodiseringar')
)
}
if (href === '/bookkeeping/year-end') {
return (
pathname.startsWith('/bookkeeping/year-end') &&
!pathname.startsWith('/bookkeeping/year-end/arsredovisning')
)
}
if (href === '/reports') {
return pathname.startsWith('/reports') && !pathname.startsWith('/reports/vat-declaration')
return (
pathname.startsWith('/reports') &&
!pathname.startsWith('/reports/vat-declaration') &&
!pathname.startsWith('/reports/ink2-declaration') &&
!pathname.startsWith('/reports/ne-declaration')
)
}
return pathname.startsWith(href)
}
@@ -427,6 +458,9 @@ export default function DashboardNav({ companyName: _companyName, entityType, pa
// the active company holds the capability. The page + API gates enforce
// the paywall; this keeps the sidebar from advertising a dead workspace.
if (item.requiredCapability && !capabilities.includes(item.requiredCapability)) return false
// Entity-gated statutory surfaces: INK2/ÅR for aktiebolag, NE for
// enskild firma; the page for the other form doesn't exist.
if (item.entityOnly && item.entityOnly !== entityType) return false
// Hide the Assistent (/chat) tab until the agent is built: mirrors the
// floating AgentTrigger and avoids a nav entry that only bounces to the
// home checklist (chat/layout redirects unverified users to /).
@@ -0,0 +1,91 @@
'use client'
import { useCallback, useSyncExternalStore } from 'react'
import { useTranslations } from 'next-intl'
import { ArrowRight, FileCheck, X } from 'lucide-react'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
const dismissKey = (companyId: string) => `erp_skv_promo_dismissed:${companyId}`
// storage events only fire in OTHER tabs; this custom event covers the
// same-tab dismissal so useSyncExternalStore re-reads localStorage.
const DISMISS_EVENT = 'erp-skv-promo-dismissed'
function subscribeToDismissal(onStoreChange: () => void) {
window.addEventListener('storage', onStoreChange)
window.addEventListener(DISMISS_EVENT, onStoreChange)
return () => {
window.removeEventListener('storage', onStoreChange)
window.removeEventListener(DISMISS_EVENT, onStoreChange)
}
}
interface SkatteverketPromoCardProps {
companyId: string
/** True when the active user already has a Skatteverket token. */
connected: boolean
}
/**
* Dismissible dashboard nudge for companies that have never connected
* Skatteverket. New companies meet the connect step in NewUserChecklist;
* this card is the equivalent surface for existing companies, which
* otherwise only discover the integration deep inside the VAT/AGI flows.
* Capability-less users never see it: the paywall upsell lives where the
* intent is (SkatteverketPanel, AGIPanel), not on the dashboard.
*/
export function SkatteverketPromoCard({ companyId, connected }: SkatteverketPromoCardProps) {
const t = useTranslations('dashboard')
const extensionEnabled = ENABLED_EXTENSION_IDS.has('skatteverket')
const hasCapability = useCapability(CAPABILITY.skatteverket)
// Server snapshot says dismissed: the card appears only after hydration,
// when localStorage is readable, so server and client never disagree.
const dismissed = useSyncExternalStore(
subscribeToDismissal,
() => localStorage.getItem(dismissKey(companyId)) === 'true',
() => true
)
const dismiss = useCallback(() => {
localStorage.setItem(dismissKey(companyId), 'true')
window.dispatchEvent(new Event(DISMISS_EVENT))
}, [companyId])
if (!extensionEnabled || !hasCapability || connected || dismissed) return null
return (
<section>
<Card>
<CardContent className="p-6 flex items-center gap-4">
<div className="flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center bg-secondary">
<FileCheck className="h-5 w-5" />
</div>
<div className="flex-1 min-w-0">
<p className="font-display text-xl leading-tight">{t('skv_promo_title')}</p>
<p className="text-sm text-muted-foreground mt-1">{t('skv_promo_description')}</p>
</div>
<Button variant="outline" asChild className="flex-shrink-0">
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- /api route, not a Next page; the authorize endpoint 302s to Skatteverket, which the client router cannot follow */}
<a href="/api/extensions/ext/skatteverket/authorize?return_to=/">
{t('skv_promo_cta')}
<ArrowRight className="ml-1.5 h-4 w-4" />
</a>
</Button>
<Button
variant="ghost"
size="icon"
className="flex-shrink-0"
aria-label={t('skv_promo_dismiss')}
onClick={dismiss}
>
<X className="h-4 w-4" />
</Button>
</CardContent>
</Card>
</section>
)
}
@@ -11,13 +11,13 @@ export default function CloudBackupWorkspace(_props: WorkspaceComponentProps) {
<Cloud className="h-12 w-12 text-muted-foreground/40 mb-4" />
<h3 className="text-lg font-medium text-foreground">Molnsynkronisering</h3>
<p className="text-sm text-muted-foreground mt-1 max-w-md">
Koppla ditt Google Drive-konto under Säkerhetsbackup för att synka arkiv till din
egen molnlagring.
Koppla ditt Google Drive-konto under Importera/Exportera för att synka arkiv till
din egen molnlagring.
</p>
<Button asChild variant="outline" className="mt-4">
<Link href="/settings/backup">
<Link href="/import#cloud-backup">
<Settings className="mr-2 h-4 w-4" />
Gå till säkerhetsbackup
Gå till säkerhetskopiering
</Link>
</Button>
</div>
+42 -1
View File
@@ -46,6 +46,7 @@ import { BankDetailsSetupDialog } from '@/components/invoices/BankDetailsSetupDi
import { FirstInvoiceLogoPrompt } from '@/components/invoices/FirstInvoiceLogoPrompt'
import { useCompany, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import AgentSparkleButton from '@/components/agent/AgentSparkleButton'
import {
ROT_WORK_TYPES,
@@ -120,6 +121,22 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// self-billing invoice we received (mottagen självfaktura, ML 17 kap 15§).
// Self-billing is never available when editing an existing draft.
const [mode, setMode] = useState<'invoice' | 'self_billed'>('invoice')
// Active Stripe connection: drives the "auto payment link" toggle in the
// payment link section. Absent extension or no connection → toggle hidden.
const [stripeConnected, setStripeConnected] = useState(false)
useEffect(() => {
if (!ENABLED_EXTENSION_IDS.has('stripe')) return
let cancelled = false
fetch('/api/extensions/ext/stripe/status')
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (!cancelled && data?.connection?.status === 'active') setStripeConnected(true)
})
.catch(() => {})
return () => {
cancelled = true
}
}, [])
const schema = useMemo(() => {
const itemSchema = z.object({
@@ -213,6 +230,9 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
},
{ message: t('validation_payment_link_https') },
),
// Opt-out for the automatic Stripe payment link on send (only rendered
// when the company has an active Stripe connection).
payment_link_auto: z.boolean().optional(),
// Self-billing received (mottagen självfaktura). Present in the form for
// both modes; required only in self_billed mode: enforced in onSubmit.
external_invoice_number: z.string().optional(),
@@ -315,6 +335,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
our_reference: initial.our_reference ?? '',
notes: initial.notes ?? '',
payment_link_url: initial.payment_link_url ?? '',
payment_link_auto: initial.payment_link_auto ?? true,
external_invoice_number: '',
self_billing_agreement_ref: '',
received_date: '',
@@ -348,6 +369,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
currency: 'SEK',
document_type: 'invoice' as InvoiceDocumentType,
payment_link_url: '',
payment_link_auto: true,
external_invoice_number: '',
self_billing_agreement_ref: '',
received_date: '',
@@ -2126,7 +2148,26 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
{errors.payment_link_url ? (
<p className="text-sm text-destructive">{errors.payment_link_url.message}</p>
) : (
<p className="text-xs text-muted-foreground">{t('payment_link_hint')}</p>
<p className="text-xs text-muted-foreground">
{stripeConnected ? t('payment_link_hint_auto') : t('payment_link_hint')}
</p>
)}
{stripeConnected && !watch('payment_link_url')?.trim() && (
<div className="flex items-center gap-2 pt-1">
<Switch
id="payment_link_auto"
checked={watch('payment_link_auto') ?? true}
onCheckedChange={(v) =>
setValue('payment_link_auto', v, { shouldDirty: true })
}
/>
<Label
htmlFor="payment_link_auto"
className="text-sm font-normal text-muted-foreground"
>
{t('payment_link_auto_label')}
</Label>
</div>
)}
</div>
)}
+146 -39
View File
@@ -27,7 +27,6 @@ import {
Info,
Link2,
Loader2,
Lock,
MoreHorizontal,
Send,
ShieldAlert,
@@ -37,6 +36,7 @@ import { formatRedovisare, formatRedovisningsperiod } from '@/lib/skatteverket/f
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { UpgradeNote } from '@/components/billing/UpgradeNote'
import { InfoTooltip } from '@/components/ui/info-tooltip'
interface SkatteverketStatus {
connected: boolean
@@ -113,6 +113,9 @@ function isOrgNumberMissing(err: unknown): boolean {
* so a slow SKV round-trip is never silent.
*/
const ACTION_IN_FLIGHT_LABELS: Record<string, string> = {
validate: 'Validerar deklarationen...',
draft: 'Sparar utkast...',
lock: 'Låser utkastet...',
fetchDraft: 'Hämtar utkast...',
check: 'Kontrollerar inlämning...',
fetchDecided: 'Hämtar beslut...',
@@ -389,6 +392,84 @@ function SkatteverketPanelInner({
}
}
/**
* One-click filing: the server chains kontrollera -> utkast -> lås and
* returns the signing link. Stage-aware failures come back with a `stage`
* discriminator: `validation` stopped before anything was written at SKV,
* `lock` with `draft_saved` means the draft survives in Eget utrymme and
* only the lock step needs a retry (available under Fler åtgärder).
*/
const handleSubmit = async () => {
if (localBlocked) {
setNotice({
kind: 'error',
text:
'Åtgärda felen under Kontroll av underlaget högst upp på sidan innan ' +
'du skickar till Skatteverket.',
})
return
}
setActionLoading('submit')
setNotice(null)
setKontroller([])
try {
const res = await fetch('/api/extensions/ext/skatteverket/declaration/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ periodType, year, period }),
})
const result = await res.json()
if (res.ok && result.data?.signeringsLank) {
const controls: KontrollResult[] = result.data?.kontrollResultat?.resultat || []
setKontroller(controls)
setSigneringslank(result.data.signeringsLank)
setNotice({
kind: 'success',
text:
'Deklarationen är kontrollerad, sparad och låst. Öppna signeringslänken ' +
'för att signera med BankID.',
})
return
}
if (result.stage) {
const controls: KontrollResult[] = result.kontrollResultat?.resultat || []
if (controls.length > 0) setKontroller(controls)
if (result.stage === 'validation') {
setNotice({
kind: 'error',
text: result.error || 'Skatteverket hittade valideringsfel i deklarationen.',
})
} else if (result.stage === 'lock' && result.draft_saved) {
setNotice({
kind: 'error',
text:
'Utkastet är sparat hos Skatteverket men kunde inte låsas för signering. ' +
'Försök igen med "Lås och signera" under Fler åtgärder.',
})
} else {
setNotice({
kind: 'error',
text: result.error || 'Kunde inte skicka deklarationen till Skatteverket',
})
}
return
}
if (!applyApiError(result)) {
setNotice({
kind: 'error',
text: 'Kunde inte skicka deklarationen till Skatteverket',
})
}
} catch {
setNotice({ kind: 'error', text: 'Kunde inte skicka deklarationen till Skatteverket' })
} finally {
setActionLoading(null)
}
}
const handleUnlock = async () => {
setActionLoading('unlock')
setNotice(null)
@@ -426,10 +507,12 @@ function SkatteverketPanelInner({
setActionLoading('check')
setNotice(null)
try {
// periodType/year/period let the server complete the period's moms
// deadline when the filing is confirmed.
const res = await fetch(
`/api/extensions/ext/skatteverket/declaration/submitted?redovisare=${encodeURIComponent(
await getRedovisare()
)}&redovisningsperiod=${getRedovisningsperiod()}`
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${year}&period=${period}`
)
const result = await res.json()
if (applyApiError(result)) {
@@ -449,7 +532,7 @@ function SkatteverketPanelInner({
} finally {
setActionLoading(null)
}
}, [applyApiError, getRedovisare, getRedovisningsperiod])
}, [applyApiError, getRedovisare, getRedovisningsperiod, periodType, year, period])
// While a signing link is outstanding, re-check submission status when the
// user returns to this tab: signing happens on Skatteverket's site, so the
@@ -534,7 +617,7 @@ function SkatteverketPanelInner({
const res = await fetch(
`/api/extensions/ext/skatteverket/declaration/decided?redovisare=${encodeURIComponent(
await getRedovisare()
)}&redovisningsperiod=${getRedovisningsperiod()}`
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${year}&period=${period}`
)
const result = await res.json()
if (applyApiError(result)) {
@@ -691,6 +774,45 @@ function SkatteverketPanelInner({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-72">
{/* The demoted step-by-step actions: the visible surface is
the one-click "Skicka till Skatteverket" button; these
remain for partial retries (e.g. lock-only after a lock
failure) and for users who want to inspect each step. */}
<DropdownMenuLabel>Steg för steg</DropdownMenuLabel>
<DropdownMenuItem
disabled={!hasData || localBlocked || actionLoading !== null}
onSelect={() => handleValidate()}
>
<div>
<p>Validera</p>
<p className="text-xs text-muted-foreground">
Kontrollera deklarationen hos Skatteverket utan att spara
</p>
</div>
</DropdownMenuItem>
<DropdownMenuItem
disabled={!hasData || localBlocked || actionLoading !== null}
onSelect={() => handleSaveDraft()}
>
<div>
<p>Spara utkast</p>
<p className="text-xs text-muted-foreground">
Spara deklarationen som utkast i Eget utrymme
</p>
</div>
</DropdownMenuItem>
<DropdownMenuItem
disabled={!hasData || actionLoading !== null}
onSelect={() => handleLock()}
>
<div>
<p>Lås och signera</p>
<p className="text-xs text-muted-foreground">
Lås det sparade utkastet och hämta signeringslänken
</p>
</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>Status hos Skatteverket</DropdownMenuLabel>
<DropdownMenuItem
disabled={actionLoading !== null}
@@ -889,61 +1011,46 @@ function SkatteverketPanelInner({
</div>
)}
{/* Forward lifecycle: the only always-visible action row. */}
<div className="flex flex-wrap gap-2 pt-1">
{/* Forward lifecycle: one primary action. The individual steps live
in the overflow menu under "Steg för steg". */}
<div className="flex flex-wrap items-center gap-2 pt-1">
<Button
variant="outline"
onClick={handleValidate}
onClick={handleSubmit}
disabled={!hasData || localBlocked || actionLoading !== null}
className="gap-2"
>
{actionLoading === 'validate' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<FileCheck className="h-4 w-4" />
)}
Validera
</Button>
<Button
variant="outline"
onClick={handleSaveDraft}
disabled={!hasData || localBlocked || actionLoading !== null}
className="gap-2"
>
{actionLoading === 'draft' ? (
{actionLoading === 'submit' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
Spara utkast
</Button>
<Button
onClick={handleLock}
disabled={!hasData || hasErrors || actionLoading !== null}
className="gap-2"
>
{actionLoading === 'lock' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Lock className="h-4 w-4" />
)}
Lås och signera
Skicka till Skatteverket
</Button>
</div>
<p className="text-xs text-muted-foreground">
Deklarationen kontrolleras, sparas som utkast i{' '}
<InfoTooltip
variant="help"
content="Ditt företags privata yta hos Skatteverket. Utkast som sparas där räknas inte som inlämnade förrän de har signerats med BankID."
>
<span>Eget utrymme</span>
</InfoTooltip>{' '}
och låses för signering med BankID hos Skatteverket. Inget lämnas in
förrän du har signerat.
</p>
{/* Visible disabled-state explanations: title attributes never show
on disabled buttons. */}
{localBlocked && (
<p className="text-sm text-destructive">
Åtgärda felen under Kontroll av underlaget högst upp på sidan innan du
validerar eller skickar in.
skickar in.
</p>
)}
{hasErrors && !localBlocked && (
<p className="text-sm text-muted-foreground">
Valideringsfelen ovan måste åtgärdas innan utkastet kan låsas.
Valideringsfelen ovan måste åtgärdas innan deklarationen kan lämnas in.
</p>
)}
</CardContent>
+8 -13
View File
@@ -18,6 +18,8 @@ import {
import { useTranslations } from 'next-intl'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { InfoTooltip } from '@/components/ui/info-tooltip'
import { UpgradeNote } from '@/components/billing/UpgradeNote'
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
@@ -785,7 +787,11 @@ export function AGIPanel(props: AGIPanelProps) {
BankID signing is even possible. */}
{submission?.signeringslank && awaitingSigning && !draftIsStale && (
<div className="rounded-md border border-border bg-muted/30 p-3">
<p className="text-sm font-medium">{t('draft_locked_title')}</p>
<p className="text-sm font-medium">
<InfoTooltip variant="help" content={t('granskningsunderlag_gloss')}>
{t('draft_locked_title')}
</InfoTooltip>
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{t('draft_locked_description')}
</p>
@@ -920,11 +926,6 @@ export function AGIPanel(props: AGIPanelProps) {
variant="outline"
onClick={handleSubmit}
disabled={actionLoading === 'submit' || !hasSkatteverket}
title={
!hasSkatteverket
? t('submit_upgrade_title')
: undefined
}
>
{actionLoading === 'submit' ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
@@ -977,13 +978,7 @@ export function AGIPanel(props: AGIPanelProps) {
)}
{!readOnly && !isSigned && !hasSkatteverket && (
<p className="text-xs text-muted-foreground">
{t('upgrade_hint_before')}{' '}
<a href="/settings/billing" className="font-medium underline hover:no-underline">
{t('upgrade_hint_link')}
</a>{' '}
{t('upgrade_hint_after')}
</p>
<UpgradeNote>{t('upgrade_note')}</UpgradeNote>
)}
</CardContent>
</Card>
@@ -28,6 +28,15 @@ type Status =
}
export function SkatteverketConnectPanel() {
return (
<div className="space-y-4">
<SkatteverketPersonalConnectionCard />
<SkatteverketSystemConnectionCard />
</div>
)
}
function SkatteverketPersonalConnectionCard() {
const t = useTranslations('settings_skatteverket_connect')
const { toast } = useToast()
const hasSkatteverket = useCapability(CAPABILITY.skatteverket)
@@ -250,6 +259,151 @@ export function SkatteverketConnectPanel() {
)
}
type GrantStatus = 'unknown' | 'granted' | 'denied' | 'error'
interface SystemConnectionState {
available: boolean
mode?: string
environment?: string
ombud_org_number?: string | null
grant_url?: string
cert?: { notAfter: string; daysUntilExpiry: number; expiresSoon: boolean } | null
connection?: {
status: string
lasombud_status: GrantStatus
moms_ombud_status: GrantStatus
verified_at: string | null
last_probe_at: string | null
} | null
}
/**
* The system (ombud + organization certificate) connection: the one-time
* grant that lets background syncs run without a personal BankID session.
* Renders nothing until SKATTEVERKET_SYSTEM_AUTH_MODE is switched on
* server-side, so the whole section is invisible during Phase 1.
*/
function SkatteverketSystemConnectionCard() {
const t = useTranslations('settings_skatteverket_connect')
const { toast } = useToast()
const [state, setState] = useState<SystemConnectionState | null>(null)
const [verifying, setVerifying] = useState(false)
async function loadState() {
try {
const res = await fetch('/api/extensions/ext/skatteverket/system-connection')
if (!res.ok) {
setState({ available: false })
return
}
setState((await res.json()) as SystemConnectionState)
} catch {
setState({ available: false })
}
}
useEffect(() => {
loadState()
}, [])
async function verify() {
setVerifying(true)
try {
const res = await fetch('/api/extensions/ext/skatteverket/system-connection/verify', {
method: 'POST',
})
const body = await res.json().catch(() => ({}))
if (res.status === 429) {
toast({ title: t('system_verify_rate_limited') })
return
}
if (!res.ok) {
toast({
title: t('system_verify_failed'),
description: typeof body?.error === 'string' ? body.error : undefined,
variant: 'destructive',
})
return
}
await loadState()
} catch {
toast({ title: t('system_verify_failed'), variant: 'destructive' })
} finally {
setVerifying(false)
}
}
if (!state?.available) return null
const grantBadge = (status: GrantStatus | undefined) => {
switch (status) {
case 'granted':
return (
<Badge variant="success">
<CheckCircle2 className="mr-1 h-3 w-3" />
{t('system_status_granted')}
</Badge>
)
case 'denied':
return <Badge variant="destructive">{t('system_status_denied')}</Badge>
case 'error':
return <Badge variant="warning">{t('system_status_error')}</Badge>
default:
return <Badge variant="outline">{t('system_status_unknown')}</Badge>
}
}
return (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('system_title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">{t('system_intro')}</p>
{state.ombud_org_number && (
<div className="rounded-md border border-border bg-secondary/40 p-3 text-sm">
<p className="text-muted-foreground">{t('system_org_label')}</p>
<p className="font-mono font-medium tabular-nums">{state.ombud_org_number}</p>
</div>
)}
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
<div className="flex items-center justify-between gap-2 rounded-md border border-border p-3">
<span>{t('system_behorighet_lasombud')}</span>
{grantBadge(state.connection?.lasombud_status)}
</div>
<div className="flex items-center justify-between gap-2 rounded-md border border-border p-3">
<span>{t('system_behorighet_moms')}</span>
{grantBadge(state.connection?.moms_ombud_status)}
</div>
</div>
{state.cert?.expiresSoon && (
<div className="flex gap-2 rounded-md border border-border bg-secondary/40 p-3 text-sm text-foreground">
<ShieldAlert className="h-4 w-4 mt-0.5 shrink-0" />
<p>{t('system_cert_expires_soon', { days: state.cert.daysUntilExpiry })}</p>
</div>
)}
<div className="flex flex-wrap gap-2 pt-1">
{state.grant_url && (
<Button variant="outline" asChild>
<a href={state.grant_url} target="_blank" rel="noopener noreferrer">
<ExternalLink className="mr-2 h-4 w-4" />
{t('system_open_ombud')}
</a>
</Button>
)}
<Button onClick={verify} disabled={verifying}>
{verifying ? t('system_verifying') : t('system_verify')}
</Button>
</div>
</CardContent>
</Card>
)
}
function EnvironmentBadge({ environment, disabled }: { environment?: Environment; disabled?: boolean }) {
const t = useTranslations('settings_skatteverket_connect')
if (disabled) {
@@ -0,0 +1,42 @@
'use client'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { EmptyState } from '@/components/ui/empty-state'
import { CreditCard, ExternalLink } from 'lucide-react'
import { getSettingsPanel } from '@/lib/extensions/settings-panel-registry'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
const StripePanel = getSettingsPanel('stripe')
export function PaymentsSettingsContent() {
const t = useTranslations('settings_payments')
const hasStripeExtension = ENABLED_EXTENSION_IDS.has('stripe')
return (
<div className="space-y-8">
{hasStripeExtension && StripePanel ? (
<StripePanel />
) : (
<Card>
<CardContent className="p-0">
<EmptyState
icon={CreditCard}
title={t('not_enabled_title')}
description={t('not_enabled_description')}
>
<Button variant="outline" asChild>
<Link href="/extensions">
<ExternalLink className="mr-2 h-4 w-4" />
{t('go_to_extensions')}
</Link>
</Button>
</EmptyState>
</CardContent>
</Card>
)}
</div>
)
}
+2
View File
@@ -6,6 +6,7 @@ import { TaxSettingsContent } from './TaxSettingsContent'
import { SalarySettingsContent } from './SalarySettingsContent'
import { InvoicingSettingsContent } from './InvoicingSettingsContent'
import { TemplatesSettingsContent } from './TemplatesSettingsContent'
import { PaymentsSettingsContent } from './PaymentsSettingsContent'
import { BankingSettingsContent } from './BankingSettingsContent'
import { AssistantSettingsContent } from './AssistantSettingsContent'
import { ApiSettingsContent } from './ApiSettingsContent'
@@ -26,6 +27,7 @@ export const SETTINGS_SECTIONS: Record<string, ComponentType> = {
salary: SalarySettingsContent,
invoicing: InvoicingSettingsContent,
templates: TemplatesSettingsContent,
payments: PaymentsSettingsContent,
banking: BankingSettingsContent,
assistant: AssistantSettingsContent,
api: ApiSettingsContent,
@@ -41,6 +41,7 @@ export function useSettingsNavItems(): { items: SettingsNavItem[]; groups: Setti
const hasCompany = !!company
const hasBankingExtension = ENABLED_EXTENSION_IDS.has('enable-banking')
const hasMcpExtension = ENABLED_EXTENSION_IDS.has('mcp-server')
const hasStripeExtension = ENABLED_EXTENSION_IDS.has('stripe')
// Företagsprofil (TIC-snapshot) lives under Företag; Skatteverket under Skatt;
// assistentens minne + kunskap under Assistenten; säkerhetsbackup under
@@ -56,6 +57,7 @@ export function useSettingsNavItems(): { items: SettingsNavItem[]; groups: Setti
// with staff. #782
{ id: 'salary', href: '/settings/salary', label: t('salary'), group: 'accounting', show: hasCompany && (company?.entity_type === 'aktiebolag' || !!company?.pays_salaries) },
{ id: 'invoicing', href: '/settings/invoicing', label: t('invoicing'), group: 'sales', show: hasCompany },
{ id: 'payments', href: '/settings/payments', label: t('payments'), group: 'sales', show: hasCompany && !isSandbox && hasStripeExtension },
{ id: 'templates', href: '/settings/templates', label: t('templates'), group: 'sales', show: hasCompany },
{ id: 'banking', href: '/settings/banking', label: t('banking'), group: 'tools', show: hasCompany && !isSandbox && hasBankingExtension },
{ id: 'assistant', href: '/settings/assistant', label: t('assistant'), group: 'tools', show: hasCompany && identity.isVerified },