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:
co-authored by
Claude Fable 5
parent
ee3c33c7a4
commit
98d0c7f2d0
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import {
|
||||
MASTER_DATA_DUMP_TABLES,
|
||||
ARCHIVE_COVERED_ELSEWHERE_TABLES,
|
||||
ARCHIVE_EXCLUDED_TABLES,
|
||||
} from '@/lib/reports/full-archive-export'
|
||||
|
||||
/**
|
||||
* Anti-rot guard for the full-archive backup (BFL 7-year retention).
|
||||
*
|
||||
* The säkerhetsbackup dumps company data table-by-table from an explicit list.
|
||||
* That list rotted once already: salary, assets, dimensions, articles and
|
||||
* rot/rut shipped without ever joining the dump, and three child tables were
|
||||
* queried by a company_id column they do not have (silent error stubs in every
|
||||
* backup). This test makes the schema and the dump contract converge:
|
||||
*
|
||||
* every public base table with a company_id column must be classified as
|
||||
* DUMPED, COVERED ELSEWHERE in the archive, or EXCLUDED with a reason.
|
||||
*
|
||||
* A migration adding a company-scoped table fails here until the author makes
|
||||
* an explicit call about its place in the backup.
|
||||
*/
|
||||
|
||||
interface ColumnRow {
|
||||
table_name: string
|
||||
column_name: string
|
||||
}
|
||||
|
||||
let columnsByTable: Map<string, Set<string>>
|
||||
|
||||
beforeAll(async () => {
|
||||
const { rows } = await getPool().query<ColumnRow>(`
|
||||
SELECT c.table_name, c.column_name
|
||||
FROM information_schema.columns c
|
||||
JOIN information_schema.tables t
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
||||
WHERE c.table_schema = 'public'
|
||||
AND t.table_type = 'BASE TABLE'
|
||||
`)
|
||||
columnsByTable = new Map()
|
||||
for (const row of rows) {
|
||||
let set = columnsByTable.get(row.table_name)
|
||||
if (!set) {
|
||||
set = new Set()
|
||||
columnsByTable.set(row.table_name, set)
|
||||
}
|
||||
set.add(row.column_name)
|
||||
}
|
||||
})
|
||||
|
||||
function companyScopedTables(): string[] {
|
||||
return [...columnsByTable.entries()]
|
||||
.filter(([, cols]) => cols.has('company_id'))
|
||||
.map(([name]) => name)
|
||||
.sort()
|
||||
}
|
||||
|
||||
describe('full-archive coverage contract', () => {
|
||||
it('classifies every company-scoped table (new tables must be triaged)', () => {
|
||||
const dumped = new Set(MASTER_DATA_DUMP_TABLES.map((t) => t.name))
|
||||
const covered = new Set(Object.keys(ARCHIVE_COVERED_ELSEWHERE_TABLES))
|
||||
const excluded = new Set(Object.keys(ARCHIVE_EXCLUDED_TABLES))
|
||||
|
||||
const unclassified = companyScopedTables().filter(
|
||||
(t) => !dumped.has(t) && !covered.has(t) && !excluded.has(t)
|
||||
)
|
||||
|
||||
expect(
|
||||
unclassified,
|
||||
`Company-scoped tables missing from the backup contract: ${unclassified.join(', ')}. ` +
|
||||
'Add each to MASTER_DATA_DUMP_TABLES, ARCHIVE_COVERED_ELSEWHERE_TABLES or ' +
|
||||
'ARCHIVE_EXCLUDED_TABLES in lib/reports/full-archive-export.ts (with a reason).'
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('classifies only tables that actually exist (catches renames and drops)', () => {
|
||||
const allClassified = [
|
||||
...MASTER_DATA_DUMP_TABLES.map((t) => t.name),
|
||||
...Object.keys(ARCHIVE_COVERED_ELSEWHERE_TABLES),
|
||||
...Object.keys(ARCHIVE_EXCLUDED_TABLES),
|
||||
]
|
||||
const missing = allClassified.filter((t) => !columnsByTable.has(t))
|
||||
expect(
|
||||
missing,
|
||||
`Classified tables that no longer exist in the schema: ${missing.join(', ')}`
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the three classification buckets disjoint', () => {
|
||||
const dumped = MASTER_DATA_DUMP_TABLES.map((t) => t.name)
|
||||
const covered = Object.keys(ARCHIVE_COVERED_ELSEWHERE_TABLES)
|
||||
const excluded = Object.keys(ARCHIVE_EXCLUDED_TABLES)
|
||||
const seen = new Set<string>()
|
||||
const duplicates: string[] = []
|
||||
for (const name of [...dumped, ...covered, ...excluded]) {
|
||||
if (seen.has(name)) duplicates.push(name)
|
||||
seen.add(name)
|
||||
}
|
||||
expect(duplicates).toEqual([])
|
||||
})
|
||||
|
||||
it('dumps direct tables by an existing company_id column', () => {
|
||||
const broken = MASTER_DATA_DUMP_TABLES.filter(
|
||||
(t) => !t.via && !columnsByTable.get(t.name)?.has('company_id')
|
||||
).map((t) => t.name)
|
||||
expect(
|
||||
broken,
|
||||
`Direct dump tables without a company_id column (the query would error and ` +
|
||||
`the backup would contain an error stub): ${broken.join(', ')}`
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('pages every dump table by an existing unique key', () => {
|
||||
const broken = MASTER_DATA_DUMP_TABLES.filter(
|
||||
(t) => !columnsByTable.get(t.name)?.has(t.pageKey ?? 'id')
|
||||
).map((t) => `${t.name}.${t.pageKey ?? 'id'}`)
|
||||
expect(broken, `page keys missing from schema: ${broken.join(', ')}`).toEqual([])
|
||||
})
|
||||
|
||||
it('fetches via-tables through a real parent/fk relationship', () => {
|
||||
for (const t of MASTER_DATA_DUMP_TABLES) {
|
||||
if (!t.via) continue
|
||||
const childCols = columnsByTable.get(t.name)
|
||||
expect(childCols, `via-table ${t.name} does not exist`).toBeDefined()
|
||||
expect(
|
||||
childCols!.has(t.via.fk),
|
||||
`via-table ${t.name} has no column ${t.via.fk}`
|
||||
).toBe(true)
|
||||
expect(
|
||||
childCols!.has('company_id'),
|
||||
`via-table ${t.name} HAS a company_id column: dump it directly instead`
|
||||
).toBe(false)
|
||||
expect(
|
||||
columnsByTable.get(t.via.parent)?.has('company_id'),
|
||||
`via-parent ${t.via.parent} of ${t.name} has no company_id column`
|
||||
).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('orders every dump query by columns that exist', () => {
|
||||
const broken = MASTER_DATA_DUMP_TABLES.filter(
|
||||
(t) => t.orderBy && !columnsByTable.get(t.name)?.has(t.orderBy)
|
||||
).map((t) => `${t.name}.${t.orderBy}`)
|
||||
expect(broken, `orderBy columns missing from schema: ${broken.join(', ')}`).toEqual([])
|
||||
})
|
||||
|
||||
it('writes each table to a unique file', () => {
|
||||
const files = MASTER_DATA_DUMP_TABLES.map((t) => t.file)
|
||||
expect(new Set(files).size).toBe(files.length)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* pg-real tests for apply_rot_rut_beslut (20260712112000).
|
||||
*
|
||||
* The RPC records a Skatteverket beslut atomically: every
|
||||
* rot_rut_payout_request_items.decided_amount update plus the
|
||||
* rot_rut_payout_requests header update (decided_total, decided_at,
|
||||
* skv_referensnummer, status) run in one transaction. Any missing row
|
||||
* raises, rolling the whole beslut back.
|
||||
*
|
||||
* Verifies:
|
||||
* - happy path: all items and the header are updated in one call.
|
||||
* - rollback: one missing item id leaves BOTH the valid items and the
|
||||
* header untouched.
|
||||
* - a missing request id raises.
|
||||
* - SECURITY INVOKER: RLS hides another company's request, so a foreign
|
||||
* caller gets the not-found raise instead of a write.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertCompanyMember } from './fixtures'
|
||||
|
||||
const SKV_REF = '20260000185-01'
|
||||
|
||||
async function seedInvoice(userId: string, companyId: string): Promise<string> {
|
||||
const customerId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.customers (id, user_id, company_id, name, customer_type)
|
||||
VALUES ($1, $2, $3, 'Test Cust', 'individual')`,
|
||||
[customerId, userId, companyId],
|
||||
)
|
||||
const invoiceId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.invoices
|
||||
(id, user_id, company_id, customer_id, invoice_date, due_date,
|
||||
currency, vat_treatment, vat_rate, deduction_total)
|
||||
VALUES ($1, $2, $3, $4, '2026-06-01', '2026-06-30', 'SEK', 'standard_25', 25, 3000)`,
|
||||
[invoiceId, userId, companyId, customerId],
|
||||
)
|
||||
return invoiceId
|
||||
}
|
||||
|
||||
async function seedRequestWithItems(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
itemCount?: number
|
||||
}): Promise<{ requestId: string; itemIds: string[] }> {
|
||||
const requestId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.rot_rut_payout_requests
|
||||
(id, company_id, user_id, deduction_type, name, status, requested_total, file_name)
|
||||
VALUES ($1, $2, $3, 'rot', 'ROT 2026-07-02', 'submitted', 3000, 'rot_2026-07-02.xml')`,
|
||||
[requestId, params.companyId, params.userId],
|
||||
)
|
||||
const itemIds: string[] = []
|
||||
for (let i = 0; i < (params.itemCount ?? 2); i++) {
|
||||
const invoiceId = await seedInvoice(params.userId, params.companyId)
|
||||
const itemId = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.rot_rut_payout_request_items
|
||||
(id, request_id, invoice_id, requested_amount)
|
||||
VALUES ($1, $2, $3, 1500)`,
|
||||
[itemId, requestId, invoiceId],
|
||||
)
|
||||
itemIds.push(itemId)
|
||||
}
|
||||
return { requestId, itemIds }
|
||||
}
|
||||
|
||||
function callRpc(params: {
|
||||
requestId: string
|
||||
items: Array<{ item_id: string; decided_amount: number }>
|
||||
decidedTotal: number
|
||||
status?: string
|
||||
}) {
|
||||
return getPool().query(
|
||||
`SELECT public.apply_rot_rut_beslut($1, $2::jsonb, $3, $4, $5)`,
|
||||
[
|
||||
params.requestId,
|
||||
JSON.stringify(params.items),
|
||||
params.decidedTotal,
|
||||
SKV_REF,
|
||||
params.status ?? 'submitted',
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
describe('apply_rot_rut_beslut RPC', () => {
|
||||
it('applies item decided amounts and the request header in one call', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
const { requestId, itemIds } = await seedRequestWithItems({ userId, companyId })
|
||||
|
||||
await callRpc({
|
||||
requestId,
|
||||
items: [
|
||||
{ item_id: itemIds[0], decided_amount: 1200 },
|
||||
{ item_id: itemIds[1], decided_amount: 800 },
|
||||
],
|
||||
decidedTotal: 2000,
|
||||
})
|
||||
|
||||
const items = await getPool().query<{ id: string; decided_amount: string }>(
|
||||
`SELECT id, decided_amount FROM public.rot_rut_payout_request_items
|
||||
WHERE request_id = $1 ORDER BY decided_amount DESC`,
|
||||
[requestId],
|
||||
)
|
||||
expect(items.rows.map((r) => Number(r.decided_amount))).toEqual([1200, 800])
|
||||
|
||||
const header = await getPool().query<{
|
||||
decided_total: string
|
||||
decided_at: string | null
|
||||
skv_referensnummer: string | null
|
||||
status: string
|
||||
}>(
|
||||
`SELECT decided_total, decided_at, skv_referensnummer, status
|
||||
FROM public.rot_rut_payout_requests WHERE id = $1`,
|
||||
[requestId],
|
||||
)
|
||||
expect(Number(header.rows[0].decided_total)).toBe(2000)
|
||||
expect(header.rows[0].decided_at).not.toBeNull()
|
||||
expect(header.rows[0].skv_referensnummer).toBe(SKV_REF)
|
||||
expect(header.rows[0].status).toBe('submitted')
|
||||
})
|
||||
|
||||
it('rolls back everything when one item id does not exist', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
const { requestId, itemIds } = await seedRequestWithItems({ userId, companyId })
|
||||
|
||||
await expect(
|
||||
callRpc({
|
||||
requestId,
|
||||
items: [
|
||||
{ item_id: itemIds[0], decided_amount: 1200 },
|
||||
{ item_id: randomUUID(), decided_amount: 800 },
|
||||
],
|
||||
decidedTotal: 2000,
|
||||
}),
|
||||
).rejects.toThrow(/not found on request/)
|
||||
|
||||
// The first (valid) item update must have rolled back with the rest.
|
||||
const items = await getPool().query<{ decided_amount: string | null }>(
|
||||
`SELECT decided_amount FROM public.rot_rut_payout_request_items
|
||||
WHERE request_id = $1`,
|
||||
[requestId],
|
||||
)
|
||||
expect(items.rows.every((r) => r.decided_amount === null)).toBe(true)
|
||||
|
||||
const header = await getPool().query<{
|
||||
decided_total: string | null
|
||||
decided_at: string | null
|
||||
skv_referensnummer: string | null
|
||||
status: string
|
||||
}>(
|
||||
`SELECT decided_total, decided_at, skv_referensnummer, status
|
||||
FROM public.rot_rut_payout_requests WHERE id = $1`,
|
||||
[requestId],
|
||||
)
|
||||
expect(header.rows[0].decided_total).toBeNull()
|
||||
expect(header.rows[0].decided_at).toBeNull()
|
||||
expect(header.rows[0].skv_referensnummer).toBeNull()
|
||||
expect(header.rows[0].status).toBe('submitted')
|
||||
})
|
||||
|
||||
it('raises when the request id does not exist', async () => {
|
||||
await expect(
|
||||
callRpc({ requestId: randomUUID(), items: [], decidedTotal: 0, status: 'rejected' }),
|
||||
).rejects.toThrow(/request .* not found/)
|
||||
})
|
||||
|
||||
it('rejects a non-array p_items payload', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
const { requestId } = await seedRequestWithItems({ userId, companyId, itemCount: 1 })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`SELECT public.apply_rot_rut_beslut($1, $2::jsonb, $3, $4, $5)`,
|
||||
[requestId, JSON.stringify({ item_id: 'x' }), 0, SKV_REF, 'submitted'],
|
||||
),
|
||||
).rejects.toThrow(/must be a jsonb array/)
|
||||
})
|
||||
|
||||
it('SECURITY INVOKER: RLS hides another company from the caller', async () => {
|
||||
const owner = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: owner })
|
||||
await insertCompanyMember({ companyId, userId: owner })
|
||||
const { requestId, itemIds } = await seedRequestWithItems({ userId: owner, companyId })
|
||||
|
||||
const outsider = await insertAuthUser()
|
||||
const outsiderCompany = await insertCompany({ createdBy: outsider })
|
||||
await insertCompanyMember({ companyId: outsiderCompany, userId: outsider })
|
||||
|
||||
// The outsider cannot see the request's items through RLS, so the item
|
||||
// update hits zero rows and the RPC raises instead of writing.
|
||||
await expect(
|
||||
withUserContext(outsider, (client) =>
|
||||
client.query(`SELECT public.apply_rot_rut_beslut($1, $2::jsonb, $3, $4, $5)`, [
|
||||
requestId,
|
||||
JSON.stringify([{ item_id: itemIds[0], decided_amount: 1200 }]),
|
||||
1200,
|
||||
SKV_REF,
|
||||
'submitted',
|
||||
]),
|
||||
),
|
||||
).rejects.toThrow(/not found/)
|
||||
|
||||
// The member CAN apply it through the same RLS path.
|
||||
await withUserContext(owner, (client) =>
|
||||
client.query(`SELECT public.apply_rot_rut_beslut($1, $2::jsonb, $3, $4, $5)`, [
|
||||
requestId,
|
||||
JSON.stringify([
|
||||
{ item_id: itemIds[0], decided_amount: 700 },
|
||||
{ item_id: itemIds[1], decided_amount: 500 },
|
||||
]),
|
||||
1200,
|
||||
SKV_REF,
|
||||
'submitted',
|
||||
]),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* pg-real tests for skatteverket_company_connections
|
||||
* (20260712092000_skatteverket_company_connections.sql).
|
||||
*
|
||||
* Verifies:
|
||||
* - table exists with RLS enabled and the expected CHECK constraints
|
||||
* - members can SELECT their own company's connection row
|
||||
* - cross-company SELECT returns nothing
|
||||
* - user sessions cannot INSERT/UPDATE (no policies exist: all writes go
|
||||
* through the service-role client in connection-store.ts)
|
||||
* - UNIQUE (company_id, environment)
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import { insertAuthUser, insertCompany, insertCompanyMember } from './fixtures'
|
||||
|
||||
async function seedConnection(companyId: string, createdBy: string): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.skatteverket_company_connections
|
||||
(id, company_id, environment, org_number, status, lasombud_status, created_by)
|
||||
VALUES ($1, $2, 'test', '165560000000', 'partial', 'granted', $3)`,
|
||||
[id, companyId, createdBy],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
describe('skatteverket_company_connections schema', () => {
|
||||
it('exists with RLS enabled', async () => {
|
||||
const result = await getPool().query<{ relrowsecurity: boolean }>(
|
||||
`SELECT relrowsecurity FROM pg_class WHERE relname = 'skatteverket_company_connections'`,
|
||||
)
|
||||
expect(result.rows).toHaveLength(1)
|
||||
expect(result.rows[0].relrowsecurity).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects invalid environment / status / grant values', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.skatteverket_company_connections
|
||||
(company_id, environment, org_number) VALUES ($1, 'staging', 'x')`,
|
||||
[companyId],
|
||||
),
|
||||
).rejects.toThrow()
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.skatteverket_company_connections
|
||||
(company_id, environment, org_number, status) VALUES ($1, 'test', 'x', 'weird')`,
|
||||
[companyId],
|
||||
),
|
||||
).rejects.toThrow()
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.skatteverket_company_connections
|
||||
(company_id, environment, org_number, lasombud_status) VALUES ($1, 'test', 'x', 'maybe')`,
|
||||
[companyId],
|
||||
),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('enforces UNIQUE (company_id, environment)', async () => {
|
||||
const userId = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: userId })
|
||||
await seedConnection(companyId, userId)
|
||||
|
||||
await expect(seedConnection(companyId, userId)).rejects.toThrow()
|
||||
|
||||
// A different environment for the same company is fine.
|
||||
await getPool().query(
|
||||
`INSERT INTO public.skatteverket_company_connections
|
||||
(company_id, environment, org_number) VALUES ($1, 'production', '165560000000')`,
|
||||
[companyId],
|
||||
)
|
||||
})
|
||||
|
||||
it('members can SELECT their own company connection; other companies cannot', async () => {
|
||||
const owner = await insertAuthUser()
|
||||
const outsider = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: owner })
|
||||
const otherCompanyId = await insertCompany({ createdBy: outsider })
|
||||
await insertCompanyMember({ companyId, userId: owner })
|
||||
await insertCompanyMember({ companyId: otherCompanyId, userId: outsider })
|
||||
const connectionId = await seedConnection(companyId, owner)
|
||||
|
||||
const ownRows = await withUserContext(owner, async (client) => {
|
||||
const res = await client.query(
|
||||
`SELECT id FROM public.skatteverket_company_connections WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
return res.rows
|
||||
})
|
||||
expect(ownRows).toHaveLength(1)
|
||||
expect(ownRows[0].id).toBe(connectionId)
|
||||
|
||||
const crossRows = await withUserContext(outsider, async (client) => {
|
||||
const res = await client.query(
|
||||
`SELECT id FROM public.skatteverket_company_connections WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
return res.rows
|
||||
})
|
||||
expect(crossRows).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('user sessions cannot INSERT or UPDATE (service-role writes only)', async () => {
|
||||
const owner = await insertAuthUser()
|
||||
const companyId = await insertCompany({ createdBy: owner })
|
||||
await insertCompanyMember({ companyId, userId: owner })
|
||||
await seedConnection(companyId, owner)
|
||||
|
||||
await expect(
|
||||
withUserContext(owner, async (client) => {
|
||||
await client.query(
|
||||
`INSERT INTO public.skatteverket_company_connections
|
||||
(company_id, environment, org_number) VALUES ($1, 'production', 'x')`,
|
||||
[companyId],
|
||||
)
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
// UPDATE without a policy silently affects 0 rows under RLS.
|
||||
const updated = await withUserContext(owner, async (client) => {
|
||||
const res = await client.query(
|
||||
`UPDATE public.skatteverket_company_connections
|
||||
SET status = 'verified'
|
||||
WHERE company_id = $1
|
||||
RETURNING id`,
|
||||
[companyId],
|
||||
)
|
||||
return res.rowCount
|
||||
})
|
||||
expect(updated).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getPool, withUserContext } from './setup'
|
||||
import {
|
||||
seedCompany,
|
||||
insertDraftJournalEntry,
|
||||
insertBalancedLines,
|
||||
} from './fixtures'
|
||||
|
||||
/**
|
||||
* Covers the Stripe integration migrations:
|
||||
* 20260712100000_stripe_connections
|
||||
* 20260712100200_invoice_stripe_payment_link
|
||||
* 20260712100300_stripe_payment_events
|
||||
* 20260712100400_stripe_payouts
|
||||
* 20260712100500_journal_source_type_stripe_payout
|
||||
*
|
||||
* Verified here (real Postgres, migrations replayed):
|
||||
* 1. source_type accepts 'stripe_payout' and still rejects unknown values,
|
||||
* and exactly one source_type CHECK survives the constraint swap.
|
||||
* 2. stripe_connections RLS: members read + write their own company's rows,
|
||||
* non-members see nothing.
|
||||
* 3. stripe_payment_events / stripe_payouts RLS: members can read, but the
|
||||
* ledgers are service-role write-only (member INSERT is rejected).
|
||||
* 4. invoices.payment_link_auto defaults TRUE (the automation is opt-out).
|
||||
*/
|
||||
|
||||
async function postWithSourceType(sourceType: string): Promise<string> {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertDraftJournalEntry({ userId, companyId, fiscalPeriodId })
|
||||
await insertBalancedLines(entryId)
|
||||
await getPool().query(
|
||||
`UPDATE public.journal_entries SET source_type = $2 WHERE id = $1`,
|
||||
[entryId, sourceType],
|
||||
)
|
||||
return entryId
|
||||
}
|
||||
|
||||
describe('journal_entries.source_type: stripe_payout', () => {
|
||||
it('accepts source_type=stripe_payout', async () => {
|
||||
const entryId = await postWithSourceType('stripe_payout')
|
||||
const { rows } = await getPool().query(
|
||||
`SELECT source_type FROM public.journal_entries WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
expect(rows[0]).toEqual({ source_type: 'stripe_payout' })
|
||||
})
|
||||
|
||||
it('still rejects values outside the CHECK list', async () => {
|
||||
await expect(postWithSourceType('paypal_payout')).rejects.toMatchObject({
|
||||
code: '23514', // check_violation
|
||||
})
|
||||
})
|
||||
|
||||
it('exactly one source_type CHECK constraint exists, under the canonical name', async () => {
|
||||
const { rows } = await getPool().query(
|
||||
`SELECT conname
|
||||
FROM pg_constraint
|
||||
WHERE conrelid = 'public.journal_entries'::regclass
|
||||
AND conname LIKE '%source_type%'`,
|
||||
)
|
||||
expect(rows.map((r) => r.conname)).toEqual(['journal_entries_source_type_check'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('stripe_connections RLS', () => {
|
||||
it('a member can insert and read their company connection', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await withUserContext(userId, async (client) => {
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status, oauth_state)
|
||||
VALUES ($1, $2, 'pending', gen_random_uuid()) RETURNING id`,
|
||||
[companyId, userId],
|
||||
)
|
||||
expect(inserted.rows).toHaveLength(1)
|
||||
|
||||
const read = await client.query(
|
||||
`SELECT id, status FROM public.stripe_connections WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toHaveLength(1)
|
||||
expect(read.rows[0].status).toBe('pending')
|
||||
})
|
||||
})
|
||||
|
||||
it('a non-member sees nothing and cannot insert for a foreign company', async () => {
|
||||
const { userId: ownerId, companyId } = await seedCompany()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status)
|
||||
VALUES ($1, $2, 'active')`,
|
||||
[companyId, ownerId],
|
||||
)
|
||||
const { userId: outsiderId } = await seedCompany() // member of a DIFFERENT company
|
||||
|
||||
await withUserContext(outsiderId, async (client) => {
|
||||
const read = await client.query(
|
||||
`SELECT id FROM public.stripe_connections WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(read.rows).toHaveLength(0)
|
||||
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status)
|
||||
VALUES ($1, $2, 'pending')`,
|
||||
[companyId, outsiderId],
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i)
|
||||
})
|
||||
})
|
||||
|
||||
it('only one ACTIVE connection per company is allowed', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status, stripe_account_id)
|
||||
VALUES ($1, $2, 'active', 'acct_pg_one')`,
|
||||
[companyId, userId],
|
||||
)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status, stripe_account_id)
|
||||
VALUES ($1, $2, 'active', 'acct_pg_two')`,
|
||||
[companyId, userId],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' }) // unique_violation
|
||||
})
|
||||
})
|
||||
|
||||
describe('stripe event/payout ledgers: member-read, service-write', () => {
|
||||
it('members read their company rows but cannot insert', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const { rows: connRows } = await getPool().query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status)
|
||||
VALUES ($1, $2, 'active') RETURNING id`,
|
||||
[companyId, userId],
|
||||
)
|
||||
const connectionId = connRows[0].id
|
||||
|
||||
// Service role (pool) writes a ledger row in each table.
|
||||
await getPool().query(
|
||||
`INSERT INTO public.stripe_payment_events
|
||||
(company_id, connection_id, stripe_event_id, status, reason)
|
||||
VALUES ($1, $2, 'evt_pg_1', 'needs_review', 'amount_mismatch')`,
|
||||
[companyId, connectionId],
|
||||
)
|
||||
await getPool().query(
|
||||
`INSERT INTO public.stripe_payouts
|
||||
(company_id, connection_id, payout_id, status)
|
||||
VALUES ($1, $2, 'po_pg_1', 'booked')`,
|
||||
[companyId, connectionId],
|
||||
)
|
||||
|
||||
await withUserContext(userId, async (client) => {
|
||||
const events = await client.query(
|
||||
`SELECT reason FROM public.stripe_payment_events WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(events.rows).toEqual([{ reason: 'amount_mismatch' }])
|
||||
|
||||
const payouts = await client.query(
|
||||
`SELECT payout_id FROM public.stripe_payouts WHERE company_id = $1`,
|
||||
[companyId],
|
||||
)
|
||||
expect(payouts.rows).toEqual([{ payout_id: 'po_pg_1' }])
|
||||
|
||||
// Writes are service-role only: no INSERT policy for authenticated.
|
||||
// One expected failure per context: an RLS rejection aborts the whole
|
||||
// transaction, so a second statement would only see "current
|
||||
// transaction is aborted" instead of the RLS error.
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.stripe_payment_events
|
||||
(company_id, connection_id, stripe_event_id, status)
|
||||
VALUES ($1, $2, 'evt_pg_member', 'ignored')`,
|
||||
[companyId, connectionId],
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i)
|
||||
})
|
||||
|
||||
await withUserContext(userId, async (client) => {
|
||||
await expect(
|
||||
client.query(
|
||||
`INSERT INTO public.stripe_payouts (company_id, connection_id, payout_id, status)
|
||||
VALUES ($1, $2, 'po_pg_member', 'booked')`,
|
||||
[companyId, connectionId],
|
||||
),
|
||||
).rejects.toThrow(/row-level security/i)
|
||||
})
|
||||
})
|
||||
|
||||
it('duplicate event and payout claims are rejected (idempotency keys)', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const { rows: connRows } = await getPool().query(
|
||||
`INSERT INTO public.stripe_connections (company_id, user_id, status)
|
||||
VALUES ($1, $2, 'active') RETURNING id`,
|
||||
[companyId, userId],
|
||||
)
|
||||
const connectionId = connRows[0].id
|
||||
|
||||
await getPool().query(
|
||||
`INSERT INTO public.stripe_payment_events
|
||||
(company_id, connection_id, stripe_event_id, status)
|
||||
VALUES ($1, $2, 'evt_dup', 'processing')`,
|
||||
[companyId, connectionId],
|
||||
)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.stripe_payment_events
|
||||
(company_id, connection_id, stripe_event_id, status)
|
||||
VALUES ($1, $2, 'evt_dup', 'processing')`,
|
||||
[companyId, connectionId],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' })
|
||||
|
||||
await getPool().query(
|
||||
`INSERT INTO public.stripe_payouts (company_id, connection_id, payout_id, status)
|
||||
VALUES ($1, $2, 'po_dup', 'processing')`,
|
||||
[companyId, connectionId],
|
||||
)
|
||||
await expect(
|
||||
getPool().query(
|
||||
`INSERT INTO public.stripe_payouts (company_id, connection_id, payout_id, status)
|
||||
VALUES ($1, $2, 'po_dup', 'processing')`,
|
||||
[companyId, connectionId],
|
||||
),
|
||||
).rejects.toMatchObject({ code: '23505' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('invoices.payment_link_auto', () => {
|
||||
it('defaults to TRUE (automation is opt-out)', async () => {
|
||||
const { userId, companyId } = await seedCompany()
|
||||
const { rows: customerRows } = await getPool().query(
|
||||
`INSERT INTO public.customers (company_id, user_id, name)
|
||||
VALUES ($1, $2, 'PG Test AB') RETURNING id`,
|
||||
[companyId, userId],
|
||||
)
|
||||
const { rows } = await getPool().query(
|
||||
`INSERT INTO public.invoices
|
||||
(company_id, user_id, customer_id, invoice_date, due_date, subtotal, vat_amount, total, status)
|
||||
VALUES ($1, $2, $3, '2026-07-01', '2026-07-31', 100, 25, 125, 'draft')
|
||||
RETURNING payment_link_auto, stripe_payment_link_id`,
|
||||
[companyId, userId, customerRows[0].id],
|
||||
)
|
||||
expect(rows[0]).toEqual({ payment_link_auto: true, stripe_payment_link_id: null })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user