Files
accounted/extensions/general/cloud-backup/lib/google-drive.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

316 lines
9.5 KiB
TypeScript

/**
* Minimal Google Drive v3 client: just enough to:
* - find or create a named folder,
* - revalidate a cached file/folder id,
* - upload a file (create) or update one in place, via resumable uploads.
*
* We operate on `drive.file` scope, so we can only see files we created.
* Queries by name return only app-created folders with that name.
*
* Uploads use Drive's resumable protocol in 8 MB chunks (a multiple of the
* required 256 KiB): no multipart body concatenation (which doubles memory
* for large archives), per-chunk retries on transient failures, and every
* upload is verified against the md5Checksum Drive reports. A silently
* corrupted backup is worse than a failed one.
*/
import { createHash } from 'node:crypto'
const DRIVE_API = 'https://www.googleapis.com/drive/v3'
const DRIVE_UPLOAD_API = 'https://www.googleapis.com/upload/drive/v3/files'
const FOLDER_MIME = 'application/vnd.google-apps.folder'
/** 8 MB: resumable chunks must be multiples of 256 KiB. */
const UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024
const CHUNK_MAX_ATTEMPTS = 3
const RESULT_FIELDS = 'id,name,size,webViewLink,md5Checksum'
interface DriveFile {
id: string
name: string
}
/** Thrown when an update targets a file that no longer exists (404). */
export class DriveFileGoneError extends Error {
constructor(fileId: string) {
super(`Drive file ${fileId} no longer exists`)
this.name = 'DriveFileGoneError'
}
}
async function driveFetch(
accessToken: string,
path: string,
init?: RequestInit
): Promise<Response> {
const res = await fetch(`${DRIVE_API}${path}`, {
...init,
headers: {
...(init?.headers || {}),
Authorization: `Bearer ${accessToken}`,
},
})
if (!res.ok) {
const body = await res.text()
throw new Error(`Drive API ${res.status}: ${body.slice(0, 200)}`)
}
return res
}
/**
* Find a folder by name under a parent (or root). Returns null if none exists.
* Uses q= filter; drive.file scope only sees app-created folders.
*/
async function findFolderByName(
accessToken: string,
name: string,
parentId: string | null
): Promise<DriveFile | null> {
const parentClause = parentId ? `'${parentId}' in parents` : `'root' in parents`
const q = [
`mimeType = '${FOLDER_MIME}'`,
`name = '${escapeName(name)}'`,
parentClause,
'trashed = false',
].join(' and ')
const url = `/files?q=${encodeURIComponent(q)}&fields=files(id,name)&pageSize=1`
const res = await driveFetch(accessToken, url)
const json = (await res.json()) as { files: DriveFile[] }
return json.files[0] || null
}
async function createFolder(
accessToken: string,
name: string,
parentId: string | null
): Promise<DriveFile> {
const body = {
name,
mimeType: FOLDER_MIME,
parents: parentId ? [parentId] : undefined,
}
const res = await driveFetch(accessToken, '/files?fields=id,name', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return (await res.json()) as DriveFile
}
export async function ensureFolder(
accessToken: string,
name: string,
parentId: string | null
): Promise<DriveFile> {
const existing = await findFolderByName(accessToken, name, parentId)
if (existing) return existing
return createFolder(accessToken, name, parentId)
}
export interface FileMeta {
id: string
name: string
/** True also when the file sits inside a trashed parent folder. */
trashed: boolean
}
/**
* Fetch metadata for a file/folder by id. Returns null on 404 (deleted or
* never visible to this scope). Used to revalidate cached folder ids: a file
* created inside a trashed folder is purged with it, so uploads must never
* target a trashed parent.
*/
export async function getFileMeta(
accessToken: string,
fileId: string
): Promise<FileMeta | null> {
const res = await fetch(
`${DRIVE_API}/files/${encodeURIComponent(fileId)}?fields=id,name,trashed`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
)
if (res.status === 404) return null
if (!res.ok) {
const body = await res.text()
throw new Error(`Drive API ${res.status}: ${body.slice(0, 200)}`)
}
const json = (await res.json()) as { id: string; name: string; trashed?: boolean }
return { id: json.id, name: json.name, trashed: json.trashed === true }
}
export interface UploadResult {
id: string
name: string
size_bytes: number
web_view_link: string
/** MD5 reported by Drive; present when the API returned it. */
md5_checksum?: string
}
/**
* Create a new file in a folder (resumable, md5-verified, one full retry on
* checksum mismatch).
*/
export async function uploadFile(
accessToken: string,
folderId: string,
fileName: string,
data: ArrayBuffer,
contentType = 'application/zip'
): Promise<UploadResult> {
return verifiedUpload(data, () =>
resumableUpload(accessToken, data, contentType, {
method: 'POST',
url: `${DRIVE_UPLOAD_API}?uploadType=resumable&fields=${RESULT_FIELDS}`,
metadata: { name: fileName, parents: [folderId] },
})
)
}
/**
* Replace the content of an existing file in place (resumable, md5-verified).
* Drive keeps prior versions of updated files for ~30 days, which gives the
* backup rolling history without accumulating one file per day.
* Throws DriveFileGoneError when the file id no longer exists.
*/
export async function updateFile(
accessToken: string,
fileId: string,
data: ArrayBuffer,
contentType = 'application/zip'
): Promise<UploadResult> {
return verifiedUpload(data, () =>
resumableUpload(accessToken, data, contentType, {
method: 'PATCH',
url: `${DRIVE_UPLOAD_API}/${encodeURIComponent(fileId)}?uploadType=resumable&fields=${RESULT_FIELDS}`,
fileId,
})
)
}
async function verifiedUpload(
data: ArrayBuffer,
run: () => Promise<UploadResult>
): Promise<UploadResult> {
const expectedMd5 = createHash('md5').update(Buffer.from(data)).digest('hex')
let lastError: Error | null = null
for (let attempt = 0; attempt < 2; attempt++) {
const result = await run()
if (!result.md5_checksum || result.md5_checksum === expectedMd5) {
return result
}
lastError = new Error(
`Drive upload checksum mismatch: expected ${expectedMd5}, got ${result.md5_checksum}`
)
}
throw lastError
}
interface ResumableTarget {
method: 'POST' | 'PATCH'
url: string
metadata?: Record<string, unknown>
fileId?: string
}
async function resumableUpload(
accessToken: string,
data: ArrayBuffer,
contentType: string,
target: ResumableTarget
): Promise<UploadResult> {
// 1) Initiate the session. Metadata (name/parents) rides on the initiation
// request; the byte chunks follow against the returned session URL.
const initRes = await fetch(target.url, {
method: target.method,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json; charset=UTF-8',
'X-Upload-Content-Type': contentType,
'X-Upload-Content-Length': String(data.byteLength),
},
body: target.metadata ? JSON.stringify(target.metadata) : undefined,
})
if (initRes.status === 404 && target.fileId) {
throw new DriveFileGoneError(target.fileId)
}
if (!initRes.ok) {
const body = await initRes.text()
throw new Error(`Drive upload init failed: ${initRes.status} ${body.slice(0, 200)}`)
}
const sessionUrl = initRes.headers.get('location')
if (!sessionUrl) {
throw new Error('Drive upload init returned no session URL')
}
// 2) Send the bytes in chunks. 308 = chunk accepted, keep going;
// 200/201 = upload complete with the file resource as body.
const total = data.byteLength
const buffer = Buffer.from(data)
let offset = 0
while (true) {
const end = Math.min(offset + UPLOAD_CHUNK_BYTES, total)
const chunk = buffer.subarray(offset, end)
let res: Response | null = null
let lastErr: unknown = null
for (let attempt = 0; attempt < CHUNK_MAX_ATTEMPTS; attempt++) {
try {
res = await fetch(sessionUrl, {
method: 'PUT',
headers: {
'Content-Length': String(chunk.length),
'Content-Range': `bytes ${offset}-${end - 1}/${total}`,
},
body: chunk,
})
if (res.status >= 500) {
lastErr = new Error(`Drive chunk upload ${res.status}`)
res = null
continue
}
break
} catch (err) {
lastErr = err
res = null
}
}
if (!res) {
throw lastErr instanceof Error
? lastErr
: new Error('Drive chunk upload failed after retries')
}
if (res.status === 308) {
// Advance to wherever the session says it is (defensive: usually `end`).
const range = res.headers.get('range')
const match = range?.match(/bytes=0-(\d+)/)
offset = match ? Number(match[1]) + 1 : end
continue
}
if (res.ok) {
const json = (await res.json()) as {
id: string
name: string
size?: string
webViewLink?: string
md5Checksum?: string
}
return {
id: json.id,
name: json.name,
size_bytes: json.size ? Number(json.size) : total,
web_view_link:
json.webViewLink || `https://drive.google.com/file/d/${json.id}/view`,
md5_checksum: json.md5Checksum,
}
}
const body = await res.text()
throw new Error(`Drive upload failed: ${res.status} ${body.slice(0, 200)}`)
}
}
function escapeName(name: string): string {
// Drive query string: escape single quotes and backslashes.
return name.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
}