Files
accounted/app/api/extensions/skatteverket/agi/kvittenser/cron/route.ts
T
Jakob WennbergandClaude Opus 4.8 4f0a7b1db0 feat(entitlements): per-company capability paywall — gate, trial seeding, UI upsells, Stripe checkout (#815)
* feat(entitlements): capability-grant gate substrate (paywall + modularity)

Two-axis capability primitive behind the SaaS paywall and the per-tenant
modularity/marketplace vision:
- migration: capability_grants (entitlement axis, polymorphic company/firm
  scope), company_capability_config (enablement axis), metered_events
  (append-only), company_has_capability() RPC reusing the 20260619130100
  tenant guard; SELECT-only RLS (writes service-role only, no self-grant).
- lib/entitlements: hasCapability/requireCapability gate (mirrors guardSandbox,
  fail-closed, NEXT_PUBLIC_SELF_HOSTED bypass), capability key namespace,
  metering helper.
- unit (11) + pg-real tests (RPC/RLS/tenant-guard incl. no-self-grant).

Gate not yet wired into call sites (follow-up commit). Paid keys:
ai, bank_sync, skatteverket, email_send.

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

* feat(entitlements): enforce capability gate at paid external-service chokepoints

Wire the gate into the paid surfaces (keys: ai, email_send, bank_sync, skatteverket):
- AI routes (agent invoke/composer/onboarding stream): requireCapability(ai)
- Invoice send (web + v1): requireCapability(email_send)
- document-extraction event handler: skip Bedrock extract if ai not entitled
- enable-banking + skatteverket crons: per-company hasCapability skip in loop
- colocated send-route test mocks updated (requireCapability -> null)

Free per founder decision: TIC org lookup, VIES VAT validation, FX auto-fetch,
cloud backup, BankID login, all internal bookkeeping.

DEPLOY ORDER: fail-closed by design — do NOT deploy before trial/comp grant
seeding lands, or companies without grants lose these features. Seeding +
Stripe checkout/webhook are the next steps.

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

* feat(entitlements): seed trial + comp capability grants

Makes the fail-closed gate safely deployable — nobody is locked out at cutover:
- AFTER INSERT trigger on companies grants every NEW company a 30-day trial on
  the PAID keys (ai, bank_sync, skatteverket, email_send), on ALL creation paths
  (RPC/MCP/direct) — so a new signup can use onboarding AI immediately.
- one-time backfill for EXISTING companies: created <=2026-06-07 -> trial ends
  2026-07-07; created later -> created_at + 30 days.
- permanent comp grants for Arcim/Mattsson (matched by name, no hardcoded UUIDs).
- pg tests: clearGrants() for controlled resolver tests + trigger coverage.

Trigger fn is SECURITY DEFINER so it writes grants regardless of caller RLS
(table has no INSERT policy for authenticated — no self-grant).

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

* feat(entitlements): client capability visibility + billing page

Non-payers get a clean upsell instead of broken/empty features:
- CompanyContext gains capabilities[] + useCapability(key); resolved once
  server-side in the dashboard layout via getCompanyCapabilities (batched, 2
  queries), all three provider branches wired.
- /settings/billing upgrade page — the destination upsells point to (Stripe
  Payment Link via NEXT_PUBLIC_STRIPE_PAYMENT_LINK; degrades to 'coming soon'
  until automated checkout lands).
- ChatEmptyState: non-payer sees an Uppgradera CTA (mirrors the sandbox state).
- SendInvoiceDialog: email send disabled + upsell note when email_send missing
  (extends the existing sandbox-disable pattern).

Fast-follow: chat input/FAB + document-inbox empty state + bank/skatteverket/
AI-suggest buttons + a shared capability_blocked->toast backstop.

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

* feat(entitlements): gate remaining paid UI surfaces with upsell (fast-follow)

disable-with-upsell across the rest of the paid surfaces (keys: bank_sync, skatteverket, ai):
- BankSyncNowButton: sync/reconnect disabled + note when !bank_sync (CSV/SIE stays free)
- AGIPanel: AGI submit-to-Skatteverket disabled + note when !skatteverket
- SkatteverketConnectPanel: BankID connect/reconnect disabled + upsell
- ApprovalCard: AI re-propose (correction) gated; manual approve/reject stay free
- InvoiceInboxWorkspace: upsell when extraction empty AND !ai (deterministic parse + manual entry unaffected)
- AgentTrigger FAB: routes to /settings/billing when !ai (no dead chat)
- settings nav: 'Abonnemang'/'Subscription' link to /settings/billing (sv/en)

TaxPaymentPanel + TransactionInboxCard intentionally untouched — only local/
deterministic actions there, nothing paid+external to gate.

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

* feat(entitlements): automated Stripe subscription checkout + webhook

Self-serve revenue wired to the same capability-grant primitive:
- migration: company_subscriptions (company<->Stripe link/status) + stripe_webhook_events (idempotency)
- lib/stripe: getStripe singleton, plan->price mapping, subscription-sync (statusGrantsAccess / subscriptionToState / applySubscriptionState / handleStripeEvent). Active sub -> upsert source='stripe' grants for PAID keys (expiry = period_end + 3d grace); canceled/unpaid -> remove ONLY stripe grants (freeze-and-retain).
- routes: POST /api/billing/checkout (hosted subscription Checkout, company_id metadata), POST /api/billing/portal (Customer Portal), POST /api/stripe/webhook (raw-body signature verify, event-id dedup; handles checkout.session.completed + customer.subscription.*)
- billing page: real plan-toggle Checkout CTA / manage-subscription portal, gated on isStripeConfigured()
- adds stripe@22; unit tests for sync logic

Provisioning is webhook-driven (never trusts the success redirect). Needs env: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_MONTHLY, STRIPE_PRICE_YEARLY.

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

* fix(entitlements): validate UUIDs in capability filter + log webhook errors

Addresses PR review (Superagent Security / PR Agent):
- has-capability.ts: validate companyId/teamId as UUIDs before interpolating into the PostgREST .or() filter (fail-closed) — removes the latent injection vector flagged in the entitlement gate. Unit tests updated to use UUIDs.
- stripe/webhook: log processing failures with event id + type before the generic 500, so a failing webhook is visible to operators.

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

* fix(salary): always-free AGI XML download for manual filing; only direct API submit is paid

Per founder decision on the swedish-compliance-review finding: AGI is a mandatory statutory filing, so producing/downloading the AGI XML must never be paywalled. Adds a free 'Ladda ner AGI-fil' button (generates + downloads the XML for manual upload to Skatteverket's e-service) on all tiers; the gated 'Skicka in underlag' stays the paid convenience (direct API submission — which also requires the paid BankID connection). Upsell reworded to point to the manual path.

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

* fix(entitlements): harden comp-grant match after prod verification

Verified Arcim/Mattsson in prod (pwxtzglxptnnvjrpixpg): the name match was case-sensitive (missed the active 'Arcim technology AB' lowercase variant) and would have granted 3 archived dupes. Now match by org_number (5595386219 / 5595719864) OR case-insensitive name, active companies only — hits exactly the 3 active comp companies, excludes archived dupes and the unrelated 'Amnäs Mattsson, Emil' enskild firma.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 15:56:19 +02:00

240 lines
9.1 KiB
TypeScript

import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { verifyCronSecret } from '@/lib/auth/cron'
import { agiGetKvittenser } from '@/extensions/general/skatteverket/lib/agi-client'
import { SkatteverketAuthError } from '@/extensions/general/skatteverket/lib/api-client'
import { formatRedovisare, formatRedovisningsperiod } from '@/lib/skatteverket/format'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
ensureInitialized()
export const maxDuration = 60
/**
* GET /api/extensions/skatteverket/agi/kvittenser/cron
*
* Daily kvittens reconciliation. The user-side flow signs the AGI in
* Skatteverket's Mina Sidor; the resulting kvittens (uuidKvittens +
* signeradTid) is the canonical filing receipt. Without this cron,
* `salary_runs.agi_submitted_at` only gets stamped when the user returns
* to the panel and clicks "Hämta kvittens" or stays on the page long
* enough for the in-browser timers to fire — which is unreliable, and
* leaves the audit trail out of step with reality (BFNAR 2013:2 kap 8 +
* BFL 5 kap 5§ require the behandlingshistorik to faithfully record
* filing events).
*
* Strategy: walk every `agi_declarations` row in `pending_signature`
* status, look up its arbetsgivare/period, fetch /kvittenser via the
* extension's per-user token, and on a hit promote the row to
* `submitted` + stamp salary_runs.agi_submitted_at.
*
* Per-row errors are logged and skipped — one expired token shouldn't
* block other companies' reconciliation.
*
* Time budget: 50s (Vercel default 60s function timeout with 10s margin).
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
if (process.env.SKATTEVERKET_ENABLED !== 'true') {
return NextResponse.json({ message: 'Skatteverket extension disabled', processed: 0 })
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json({ error: 'Missing Supabase configuration' }, { status: 500 })
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
const { data: pending, error: pendingError } = await supabase
.from('agi_declarations')
.select('id, company_id, salary_run_id, period_year, period_month')
.eq('status', 'pending_signature')
.order('created_at', { ascending: true })
.limit(100)
if (pendingError) {
console.error('[agi-kvittenser-cron] Failed to fetch pending declarations', {
message: pendingError.message,
code: pendingError.code,
})
return NextResponse.json({ error: 'Failed to fetch pending declarations' }, { status: 500 })
}
if (!pending || pending.length === 0) {
return NextResponse.json({ message: 'No pending signatures', processed: 0 })
}
const startTime = Date.now()
const TIME_BUDGET_MS = 50_000
type Result = {
declarationId: string
companyId: string
period: string
status: 'signed' | 'still_pending' | 'no_token' | 'no_company_settings' | 'expired_token' | 'error'
error?: string
}
const results: Result[] = []
for (const decl of pending) {
if (Date.now() - startTime > TIME_BUDGET_MS) {
console.log(`[agi-kvittenser-cron] Time budget reached after ${results.length} declarations`)
break
}
const companyId = decl.company_id as string
const declarationId = decl.id as string
const period = formatRedovisningsperiod('monthly', decl.period_year as number, decl.period_month as number)
if (!(await hasCapability(supabase, companyId, CAPABILITY.skatteverket))) {
console.info('[agi-kvittenser-cron] skip — capability not entitled', { companyId })
continue
}
try {
// The token table is user-scoped (one BankID identity per user) but
// also carries company_id. Match on company_id so a multi-company
// operator's token is reused only for the company that owns the AGI.
const { data: token } = await supabase
.from('skatteverket_tokens')
.select('user_id')
.eq('company_id', companyId)
.maybeSingle()
if (!token?.user_id) {
results.push({ declarationId, companyId, period, status: 'no_token' })
continue
}
const { data: settings } = await supabase
.from('company_settings')
.select('org_number, entity_type')
.eq('company_id', companyId)
.single()
if (!settings?.org_number) {
results.push({ declarationId, companyId, period, status: 'no_company_settings' })
continue
}
const arbetsgivare = formatRedovisare(
settings.org_number as string,
settings.entity_type as 'enskild_firma' | 'aktiebolag',
)
const kvittRes = await agiGetKvittenser(supabase, token.user_id as string, arbetsgivare, period)
if (!kvittRes.ok) {
results.push({
declarationId, companyId, period,
status: 'error',
error: kvittRes.error,
})
continue
}
const kvittens = kvittRes.data.kvittenser?.[0]
if (!kvittens?.uuidKvittens) {
results.push({ declarationId, companyId, period, status: 'still_pending' })
continue
}
// The presence of uuidKvittens confirms SKV signed and accepted
// the AGI. signeradTid is the precise signing moment; if SKV omits
// it we fall back to reconciliation time + warn so the discrepancy
// is investigable. Leaving NULL would hide that the filing occurred
// at all, which itself misstates behandlingshistorik (BFNAR 2013:2
// kap 8 / BFL 5 kap 6§). The fallback only applies on this code
// path because we're inside the kvittens-found branch above.
const submittedAt = kvittens.signeradTid || new Date().toISOString()
if (!kvittens.signeradTid) {
console.warn('[agi-kvittenser-cron] kvittens missing signeradTid; using reconciliation time', {
declarationId, companyId, period, uuidKvittens: kvittens.uuidKvittens,
})
}
// submitted_by is the token-owning auth.users row — the human who
// connected via BankID. The legally load-bearing signer identity
// is kvittens.signeradAv (a personnummer), which the token user_id
// does NOT necessarily match (e.g. if the connected user is a
// bookkeeper but the deklarationsombud signed). We preserve the
// full kvittens in response_data so the audit trail (BFL 5 kap 6§,
// BFNAR 2013:2 kap 8) records the actual BankID signer regardless
// of who triggered the reconciliation.
await supabase
.from('agi_declarations')
.update({
status: 'submitted',
kvittensnummer: kvittens.uuidKvittens,
submitted_at: submittedAt,
submitted_by: token.user_id,
response_data: {
signeradAv: kvittens.signeradAv ?? null,
signeradTid: kvittens.signeradTid ?? null,
uuidKvittens: kvittens.uuidKvittens,
arbetsgivare: kvittens.arbetsgivare ?? null,
period: kvittens.period ?? null,
underlag: kvittens.underlag ?? null,
reconciledBy: 'cron',
},
})
.eq('id', declarationId)
if (decl.salary_run_id) {
await supabase
.from('salary_runs')
.update({ agi_submitted_at: submittedAt })
.eq('id', decl.salary_run_id)
.eq('company_id', companyId)
}
// Clear the locally-cached submission state so the panel doesn't
// pop a stale "awaiting signature" view if the user revisits.
await supabase
.from('extension_data')
.delete()
.eq('company_id', companyId)
.eq('extension_id', 'skatteverket')
.eq('key', `agi_submission_${period}`)
results.push({ declarationId, companyId, period, status: 'signed' })
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
if (
err instanceof SkatteverketAuthError &&
(err.code === 'REFRESH_EXHAUSTED' || err.code === 'SESSION_EXPIRED' || err.code === 'TOKEN_CORRUPTED' || err.code === 'MISSING_SCOPE')
) {
results.push({ declarationId, companyId, period, status: 'expired_token', error: err.code })
continue
}
console.error('[agi-kvittenser-cron] Reconciliation failed', { declarationId, companyId, period, message })
results.push({ declarationId, companyId, period, status: 'error', error: message })
}
}
const signed = results.filter(r => r.status === 'signed').length
const stillPending = results.filter(r => r.status === 'still_pending').length
const expired = results.filter(r => r.status === 'expired_token').length
const errors = results.filter(r => r.status === 'error').length
console.log(
`[agi-kvittenser-cron] Processed ${results.length}: ${signed} signed, ${stillPending} still pending, ${expired} expired, ${errors} errors`,
)
return NextResponse.json({
processed: results.length,
signed,
stillPending,
expired,
errors,
results,
})
}