* 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>
407 lines
15 KiB
TypeScript
407 lines
15 KiB
TypeScript
import type { Extension, ExtensionContext } from '@/lib/extensions/types'
|
|
import { NextResponse } from 'next/server'
|
|
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
|
|
import { requireCapability } from '@/lib/entitlements/has-capability'
|
|
import { CAPABILITY } from '@/lib/entitlements/keys'
|
|
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
|
|
import {
|
|
buildAuthorizeUrl,
|
|
deauthorizeAccount,
|
|
isStripeConnectConfigured,
|
|
isLiveMode,
|
|
} from './lib/connect'
|
|
import {
|
|
createInvoicePaymentLink,
|
|
handleCreditNoteCreated,
|
|
handleInvoicePaid,
|
|
} from './lib/payment-links'
|
|
import { syncStripeConnection } from './lib/sync'
|
|
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
|
import type { StripeConnection, StripeStatusResponse } from './types'
|
|
|
|
// Per-user limits: connect/disconnect are outward-facing OAuth operations,
|
|
// sync hits the Stripe API.
|
|
const RATE_LIMIT_CONNECT = { maxRequests: 10, windowMs: 60_000 }
|
|
const RATE_LIMIT_DISCONNECT = { maxRequests: 10, windowMs: 60_000 }
|
|
const RATE_LIMIT_SYNC = { maxRequests: 10, windowMs: 60_000 }
|
|
|
|
// A pending row younger than this blocks a second connect attempt so a
|
|
// double-click cannot start two OAuth round-trips (only one state would
|
|
// survive, stranding the other at the callback).
|
|
const PENDING_FRESH_MS = 60_000
|
|
|
|
const NOT_CONFIGURED_MESSAGE =
|
|
'Stripe-integrationen är inte konfigurerad på den här installationen.'
|
|
|
|
/**
|
|
* Stripe Connect extension
|
|
*
|
|
* Connects a company's Stripe account via Connect OAuth (Standard accounts).
|
|
* Auto-creates a Stripe Payment Link when an invoice is sent, marks invoices
|
|
* paid from Stripe checkout events, and books payouts (gross/fees/net) against
|
|
* the 1686 clearing account.
|
|
*
|
|
* Required environment variables:
|
|
* - STRIPE_SECRET_KEY (the platform account key, shared with billing)
|
|
* - STRIPE_CONNECT_CLIENT_ID (ca_... from the platform's Connect settings)
|
|
*/
|
|
export const stripeExtension: Extension = {
|
|
id: 'stripe',
|
|
name: 'Stripe-betalningar',
|
|
version: '1.0.0',
|
|
|
|
settingsPanel: {
|
|
label: 'Betalningar (Stripe)',
|
|
path: '/settings/payments',
|
|
},
|
|
|
|
// Core-callable services, resolved via the extension registry (core never
|
|
// imports extension code). The send routes use this to auto-fill
|
|
// invoices.payment_link_url before the email/PDF render.
|
|
services: {
|
|
createInvoicePaymentLink,
|
|
},
|
|
|
|
eventHandlers: [
|
|
// A settled or credited invoice must stop accepting money through its link.
|
|
{ eventType: 'invoice.paid', handler: handleInvoicePaid },
|
|
{ eventType: 'credit_note.created', handler: handleCreditNoteCreated },
|
|
],
|
|
|
|
apiRoutes: [
|
|
{
|
|
method: 'GET',
|
|
path: '/status',
|
|
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
|
|
// Prefer the active connection; otherwise surface the most recent row
|
|
// so the panel can show pending/error/revoked states.
|
|
const { data: rows } = await supabase
|
|
.from('stripe_connections')
|
|
.select(
|
|
'id, status, stripe_account_id, livemode, display_name, error_message, connected_at, last_event_created_at',
|
|
)
|
|
.eq('company_id', ctx.companyId)
|
|
.order('created_at', { ascending: false })
|
|
.limit(10)
|
|
|
|
const connection =
|
|
rows?.find((r) => r.status === 'active') ?? rows?.[0] ?? null
|
|
|
|
// Events + payouts the deterministic matcher refused to auto-apply.
|
|
// Members can read both ledgers under RLS; the panel lists them for
|
|
// manual handling.
|
|
const { data: reviewRows, count: reviewCount } = await supabase
|
|
.from('stripe_payment_events')
|
|
.select('id, reason, amount, currency, invoice_id, event_created_at', {
|
|
count: 'exact',
|
|
})
|
|
.eq('company_id', ctx.companyId)
|
|
.eq('status', 'needs_review')
|
|
.order('event_created_at', { ascending: false })
|
|
.limit(5)
|
|
|
|
const { data: payoutRows, count: payoutCount } = await supabase
|
|
.from('stripe_payouts')
|
|
.select('id, reason, amount, currency, event_created_at', { count: 'exact' })
|
|
.eq('company_id', ctx.companyId)
|
|
.eq('status', 'needs_review')
|
|
.order('event_created_at', { ascending: false })
|
|
.limit(5)
|
|
|
|
const payload: StripeStatusResponse = {
|
|
configured: isStripeConnectConfigured(),
|
|
connection,
|
|
needs_review_count: (reviewCount ?? 0) + (payoutCount ?? 0),
|
|
needs_review: [
|
|
...(reviewRows ?? []),
|
|
...(payoutRows ?? []).map((p) => ({ ...p, invoice_id: null })),
|
|
],
|
|
}
|
|
return NextResponse.json(payload)
|
|
},
|
|
},
|
|
{
|
|
method: 'POST',
|
|
path: '/sync',
|
|
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
const capabilityBlocked = await requireCapability(
|
|
supabase,
|
|
companyId,
|
|
CAPABILITY.stripe_payments,
|
|
)
|
|
if (capabilityBlocked) return capabilityBlocked
|
|
|
|
const rl = await checkRateLimit({
|
|
prefix: 'stripe:sync',
|
|
identifier: user.id,
|
|
...RATE_LIMIT_SYNC,
|
|
})
|
|
if (!rl.ok) return rl.response!
|
|
|
|
// Membership-scoped lookup via the user client; the sync itself runs
|
|
// on the service client because the event ledger is service-write-only.
|
|
const { data: connection } = await supabase
|
|
.from('stripe_connections')
|
|
.select('*')
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'active')
|
|
.maybeSingle()
|
|
|
|
if (!connection) {
|
|
return NextResponse.json({ error: 'Inget anslutet Stripe-konto.' }, { status: 404 })
|
|
}
|
|
|
|
try {
|
|
const serviceClient = createServiceClientNoCookies()
|
|
const summary = await syncStripeConnection(
|
|
serviceClient,
|
|
connection as StripeConnection,
|
|
)
|
|
return NextResponse.json({ success: true, ...summary })
|
|
} catch (error) {
|
|
log.error('[stripe] Manual sync failed', {
|
|
message: error instanceof Error ? error.message : String(error),
|
|
connection_id: connection.id,
|
|
})
|
|
return NextResponse.json(
|
|
{ error: 'Synkroniseringen misslyckades. Försök igen.' },
|
|
{ status: 502 },
|
|
)
|
|
}
|
|
},
|
|
},
|
|
{
|
|
method: 'POST',
|
|
path: '/connect',
|
|
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
// Anonymous/sandbox users must never reach Stripe (same doctrine as
|
|
// billing checkout: the sandbox never talks to external services).
|
|
// The anon check is identity truth and runs first (no DB round trip).
|
|
if (user.is_anonymous) return sandboxBlockedResponse()
|
|
const sandboxBlocked = await guardSandbox(supabase, companyId)
|
|
if (sandboxBlocked) return sandboxBlocked
|
|
|
|
const capabilityBlocked = await requireCapability(
|
|
supabase,
|
|
companyId,
|
|
CAPABILITY.stripe_payments,
|
|
)
|
|
if (capabilityBlocked) return capabilityBlocked
|
|
|
|
const rl = await checkRateLimit({
|
|
prefix: 'stripe:connect',
|
|
identifier: user.id,
|
|
...RATE_LIMIT_CONNECT,
|
|
})
|
|
if (!rl.ok) return rl.response!
|
|
|
|
if (!isStripeConnectConfigured()) {
|
|
return NextResponse.json({ error: NOT_CONFIGURED_MESSAGE }, { status: 503 })
|
|
}
|
|
|
|
const { data: existing } = await supabase
|
|
.from('stripe_connections')
|
|
.select('id, status, created_at')
|
|
.eq('company_id', companyId)
|
|
.in('status', ['active', 'pending'])
|
|
.order('created_at', { ascending: false })
|
|
|
|
if (existing?.some((c) => c.status === 'active')) {
|
|
return NextResponse.json(
|
|
{ error: 'Företaget har redan ett anslutet Stripe-konto. Koppla från det först.' },
|
|
{ status: 409 },
|
|
)
|
|
}
|
|
|
|
const pending = existing?.filter((c) => c.status === 'pending') ?? []
|
|
const freshPending = pending.find(
|
|
(c) => Date.now() - new Date(c.created_at).getTime() < PENDING_FRESH_MS,
|
|
)
|
|
if (freshPending) {
|
|
return NextResponse.json(
|
|
{ error: 'En anslutning pågår redan. Vänta och försök igen.' },
|
|
{ status: 409 },
|
|
)
|
|
}
|
|
if (pending.length > 0) {
|
|
// Supersede stale pending attempts so their oauth_state can never
|
|
// complete a callback after this new round-trip starts.
|
|
await supabase
|
|
.from('stripe_connections')
|
|
.update({
|
|
status: 'error',
|
|
error_message: 'Superseded by new connection attempt',
|
|
oauth_state: null,
|
|
})
|
|
.eq('company_id', companyId)
|
|
.eq('status', 'pending')
|
|
}
|
|
|
|
// Persist the CSRF state BEFORE handing the user to Stripe: the
|
|
// callback locates the row by oauth_state alone, so the row must
|
|
// exist before Stripe can ever redirect back with that state.
|
|
const oauthState = crypto.randomUUID()
|
|
const { data: created, error: insertError } = await supabase
|
|
.from('stripe_connections')
|
|
.insert({
|
|
company_id: companyId,
|
|
user_id: user.id,
|
|
status: 'pending',
|
|
oauth_state: oauthState,
|
|
livemode: isLiveMode(),
|
|
})
|
|
.select('id')
|
|
.single()
|
|
|
|
if (insertError || !created) {
|
|
log.error('[stripe] Failed to stage pending connection', {
|
|
message: insertError?.message,
|
|
code: insertError?.code,
|
|
companyId,
|
|
})
|
|
return NextResponse.json(
|
|
{ error: 'Kunde inte starta anslutningen. Försök igen.' },
|
|
{ status: 500 },
|
|
)
|
|
}
|
|
|
|
log.info('[stripe] Starting Connect OAuth', {
|
|
connection_id: created.id,
|
|
company_id: companyId,
|
|
livemode: isLiveMode(),
|
|
})
|
|
|
|
return NextResponse.json({ url: buildAuthorizeUrl(oauthState) })
|
|
},
|
|
},
|
|
{
|
|
method: 'DELETE',
|
|
path: '/disconnect',
|
|
handler: async (request: Request, ctx?: ExtensionContext) => {
|
|
const log = ctx?.log ?? console
|
|
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
if (!ctx?.companyId) {
|
|
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
|
|
}
|
|
const companyId = ctx.companyId
|
|
|
|
const rl = await checkRateLimit({
|
|
prefix: 'stripe:disconnect',
|
|
identifier: user.id,
|
|
...RATE_LIMIT_DISCONNECT,
|
|
})
|
|
if (!rl.ok) return rl.response!
|
|
|
|
const body = (await request.json().catch(() => ({}))) as { connection_id?: string }
|
|
|
|
const base = supabase
|
|
.from('stripe_connections')
|
|
.select('id, status, stripe_account_id')
|
|
.eq('company_id', companyId)
|
|
const query = body.connection_id
|
|
? base.eq('id', body.connection_id).limit(1)
|
|
: base.neq('status', 'revoked').order('created_at', { ascending: false }).limit(1)
|
|
const { data: rows, error: findError } = await query
|
|
const connection = rows?.[0] as
|
|
| Pick<StripeConnection, 'id' | 'status' | 'stripe_account_id'>
|
|
| undefined
|
|
|
|
if (findError || !connection) {
|
|
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
|
|
}
|
|
|
|
// Best-effort revoke at Stripe: an already-severed connection throws,
|
|
// which is fine (the goal state is reached either way). Logged at WARN
|
|
// so a systematic revoke failure stays visible to monitoring.
|
|
if (connection.status === 'active' && connection.stripe_account_id) {
|
|
try {
|
|
await deauthorizeAccount(connection.stripe_account_id)
|
|
} catch (revokeError) {
|
|
log.warn('[stripe] Deauthorize skipped (likely already revoked)', {
|
|
message: revokeError instanceof Error ? revokeError.message : String(revokeError),
|
|
connection_id: connection.id,
|
|
})
|
|
}
|
|
}
|
|
|
|
const { error: updateError } = await supabase
|
|
.from('stripe_connections')
|
|
.update({
|
|
status: 'revoked',
|
|
oauth_state: null,
|
|
disconnected_at: new Date().toISOString(),
|
|
})
|
|
.eq('id', connection.id)
|
|
.eq('company_id', companyId)
|
|
|
|
if (updateError) {
|
|
log.error('[stripe] Failed to mark connection revoked', {
|
|
message: updateError.message,
|
|
connection_id: connection.id,
|
|
})
|
|
return NextResponse.json(
|
|
{ error: 'Kunde inte koppla från. Försök igen.' },
|
|
{ status: 500 },
|
|
)
|
|
}
|
|
|
|
if (ctx?.emit) {
|
|
try {
|
|
await ctx.emit({
|
|
type: 'stripe.disconnected',
|
|
payload: {
|
|
connectionId: connection.id,
|
|
stripeAccountId: connection.stripe_account_id,
|
|
reason: 'user',
|
|
userId: user.id,
|
|
companyId,
|
|
},
|
|
})
|
|
} catch {
|
|
// Audit event failure must not block the disconnect itself.
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({ success: true })
|
|
},
|
|
},
|
|
],
|
|
}
|
|
|
|
export default stripeExtension
|