Files
accounted/app/api/extensions/cloud-backup/auto-sync/cron/route.ts
T
Mattsson 98d0c7f2d0 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>
2026-07-12 19:14:12 +02:00

295 lines
9.8 KiB
TypeScript

import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import {
performSync,
CONNECTION_KEY,
SCHEDULE_KEY,
saveExtensionData,
} from '@/extensions/general/cloud-backup/lib/sync'
import { isScheduleDue } from '@/extensions/general/cloud-backup/lib/schedule'
import {
sendBackupFailureAlert,
shouldSendBackupAlert,
type BackupAlertKind,
} from '@/extensions/general/cloud-backup/lib/backup-alert'
import type {
GoogleDriveConnection,
GoogleDriveSchedule,
} from '@/extensions/general/cloud-backup/types'
/**
* GET /api/extensions/cloud-backup/auto-sync/cron
*
* Runs hourly. Finds all companies whose auto-sync is due (daily slot has
* passed and no attempt has run since it: see `isScheduleDue`) and triggers a
* full Drive backup for each via the shared `performSync()` helper. Companies
* left over when a run hits its time budget stay due and are picked up by the
* next hourly run instead of losing the day.
*
* Failures increment `consecutive_failures` on the schedule; alert emails go
* out on dead tokens (once per incident) and repeated failures (threshold in
* `backup-alert.ts`), throttled per company.
*
* Uses the service role client: no user session, no RLS. Each row in
* `extension_data` carries its own `user_id` (the user who configured the
* schedule), which we use as the "actor" when writing back the sync result.
*/
export const GET = withCronContext('cron.cloud_backup_auto_sync', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
const now = new Date()
const origin = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
const { data: rows, error } = await supabase
.from('extension_data')
.select('company_id, user_id, value')
.eq('extension_id', 'cloud-backup')
.eq('key', SCHEDULE_KEY)
if (error) {
ctx.log.error('failed to fetch schedules', error, {
message: error.message,
code: error.code,
})
return errorResponse(error, ctx.log, { requestId: ctx.requestId })
}
if (!rows || rows.length === 0) {
return NextResponse.json({ message: 'No schedules configured', processed: 0 })
}
const candidates = rows.filter((r) =>
isScheduleDue(r.value as GoogleDriveSchedule | null, now)
)
if (candidates.length === 0) {
return NextResponse.json({
message: 'No companies due this hour',
checked: rows.length,
processed: 0,
})
}
// Connections flagged needs_reauth carry a permanently dead refresh token
// (Google returned 400 invalid_grant): skip them instead of retrying every
// night. They stay visible in the UI until the user reconnects.
const { data: connectionRows, error: connectionError } = await supabase
.from('extension_data')
.select('company_id, value')
.eq('extension_id', 'cloud-backup')
.eq('key', CONNECTION_KEY)
.in(
'company_id',
candidates.map((r) => r.company_id as string)
)
if (connectionError) {
// Fail open: without connection data we cannot tell who needs reauth,
// so fall back to attempting everyone (performSync re-flags dead tokens).
ctx.log.warn('failed to fetch connections for reauth check', {
message: connectionError.message,
})
}
const connectionByCompany = new Map<string, GoogleDriveConnection>()
for (const r of connectionRows ?? []) {
const value = r.value as GoogleDriveConnection | null
if (value) connectionByCompany.set(r.company_id as string, value)
}
const startTime = Date.now()
const TIME_BUDGET_MS = 250_000 // 4m10s: leaves 50s margin below Vercel's 300s Pro limit
const results: {
companyId: string
status: 'success' | 'error' | 'skipped'
error?: string
}[] = []
/**
* Send a failure alert if warranted and return the new last_alert_at.
* Best-effort: alert failures are logged inside sendBackupFailureAlert.
*/
const maybeAlert = async (params: {
companyId: string
userId: string
kind: BackupAlertKind
consecutiveFailures: number
errorMessage: string | null
lastAlertAt: string | null | undefined
}): Promise<string | null> => {
const prior = params.lastAlertAt ?? null
if (
!shouldSendBackupAlert({
kind: params.kind,
consecutiveFailures: params.consecutiveFailures,
lastAlertAt: prior,
now: new Date(),
})
) {
return prior
}
const sent = await sendBackupFailureAlert(supabase, {
companyId: params.companyId,
userId: params.userId,
kind: params.kind,
consecutiveFailures: params.consecutiveFailures,
errorMessage: params.errorMessage,
origin,
})
return sent.sent ? new Date().toISOString() : prior
}
for (const row of candidates) {
if (Date.now() - startTime > TIME_BUDGET_MS) {
ctx.log.info('time budget reached', {
processedSoFar: results.length,
skipped: candidates.length - results.length,
})
break
}
const companyId = row.company_id as string
const userId = row.user_id as string
const schedule = row.value as GoogleDriveSchedule
const connection = connectionByCompany.get(companyId)
if (connection?.status === 'needs_reauth') {
// Do not touch last_auto_sync_* here: the schedule keeps showing the
// failure from the night the dead token was detected. But make sure the
// incident has been alerted once: a token can go dead via a manual sync
// (which never emails) and would otherwise stay silent forever.
const alertedSinceIncident =
schedule.last_alert_at &&
connection.needs_reauth_at &&
new Date(schedule.last_alert_at).getTime() >=
new Date(connection.needs_reauth_at).getTime()
if (!alertedSinceIncident) {
const lastAlertAt = await maybeAlert({
companyId,
userId,
kind: 'needs_reauth',
consecutiveFailures: schedule.consecutive_failures ?? 0,
errorMessage: null,
lastAlertAt: schedule.last_alert_at,
})
if (lastAlertAt !== (schedule.last_alert_at ?? null)) {
await saveExtensionData(supabase, companyId, userId, SCHEDULE_KEY, {
...schedule,
last_alert_at: lastAlertAt,
}).catch((persistErr) => {
ctx.log.error('failed to persist alert state', persistErr as Error, { companyId })
})
}
}
results.push({ companyId, status: 'skipped', error: 'needs_reauth' })
continue
}
try {
const syncResult = await performSync({
supabase,
companyId,
userId,
origin,
includeDocuments: true,
allowDocumentFallback: true,
})
const consecutiveFailures = syncResult.ok
? 0
: (schedule.consecutive_failures ?? 0) + 1
let lastAlertAt = schedule.last_alert_at ?? null
if (!syncResult.ok) {
lastAlertAt = await maybeAlert({
companyId,
userId,
kind: syncResult.reason === 'needs_reauth' ? 'needs_reauth' : 'repeated_failures',
consecutiveFailures,
errorMessage: syncResult.message,
lastAlertAt,
})
}
const updated: GoogleDriveSchedule = {
...schedule,
last_auto_sync_at: new Date().toISOString(),
last_auto_sync_status: syncResult.ok ? 'success' : 'error',
last_auto_sync_error: syncResult.ok ? null : syncResult.message,
consecutive_failures: consecutiveFailures,
last_alert_at: lastAlertAt,
}
await saveExtensionData(supabase, companyId, userId, SCHEDULE_KEY, updated)
results.push({
companyId,
status: syncResult.ok ? 'success' : 'error',
error: syncResult.ok ? undefined : syncResult.message,
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
ctx.log.error('cloud backup sync failed for company', err as Error, {
companyId,
})
const consecutiveFailures = (schedule.consecutive_failures ?? 0) + 1
const lastAlertAt = await maybeAlert({
companyId,
userId,
kind: 'repeated_failures',
consecutiveFailures,
errorMessage: message.slice(0, 200),
lastAlertAt: schedule.last_alert_at,
})
const updated: GoogleDriveSchedule = {
...schedule,
last_auto_sync_at: new Date().toISOString(),
last_auto_sync_status: 'error',
last_auto_sync_error: message.slice(0, 200),
consecutive_failures: consecutiveFailures,
last_alert_at: lastAlertAt,
}
await saveExtensionData(supabase, companyId, userId, SCHEDULE_KEY, updated).catch(
(persistErr) => {
ctx.log.error('failed to persist failure state', persistErr as Error, { companyId })
},
)
results.push({ companyId, status: 'error', error: message })
}
}
const successCount = results.filter((r) => r.status === 'success').length
const errorCount = results.filter((r) => r.status === 'error').length
const skippedCount = results.filter((r) => r.status === 'skipped').length
ctx.log.info('cloud backup cron summary', {
processed: results.length,
succeeded: successCount,
failed: errorCount,
skipped: skippedCount,
})
return NextResponse.json({
checked: rows.length,
candidates: candidates.length,
processed: results.length,
successes: successCount,
errors: errorCount,
skipped: skippedCount,
results,
})
})