fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,499 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool, withUserContext } from '@/tests/pg/setup'
|
||||
import {
|
||||
insertAuthUser,
|
||||
insertBalancedLines,
|
||||
insertCompany,
|
||||
insertCompanyMember,
|
||||
insertDraftJournalEntry,
|
||||
seedCompany,
|
||||
} from '@/tests/pg/fixtures'
|
||||
|
||||
// BFL retention is enforced by two independent triggers on document_attachments:
|
||||
// * enforce_document_journal_entry_immutability (20260506130000): blocks
|
||||
// any change to journal_entry_id once it has been set, regardless of the
|
||||
// linked entry's status. Honors gnubok.allow_delete (20260506140000).
|
||||
// * enforce_document_metadata_immutability (extended in 20260506120000):
|
||||
// blocks metadata changes and journal_entry_line_id changes when the
|
||||
// linked entry is posted/reversed. Also honors gnubok.allow_delete.
|
||||
//
|
||||
// Both wordings: "BFL 5 kap" (entry trigger) and "BFL 7 kap" (metadata
|
||||
// trigger): are accepted; which one fires first depends on what column the
|
||||
// UPDATE touches.
|
||||
const BFL_RETENTION_ERROR = /BFL [57] kap/i
|
||||
|
||||
async function insertDocument(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
journalEntryId: string | null
|
||||
journalEntryLineId?: string | null
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.document_attachments
|
||||
(id, user_id, company_id, storage_path, file_name, file_size_bytes,
|
||||
mime_type, sha256_hash, journal_entry_id, journal_entry_line_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
[
|
||||
id,
|
||||
params.userId,
|
||||
params.companyId,
|
||||
`documents/${params.userId}/${id}.pdf`,
|
||||
'underlag.pdf',
|
||||
1024,
|
||||
'application/pdf',
|
||||
'a'.repeat(64),
|
||||
params.journalEntryId,
|
||||
params.journalEntryLineId ?? null,
|
||||
],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
// Insert a draft, balance it, and walk through the legal state-machine
|
||||
// transitions to land on the requested status. enforce_journal_entry_immutability
|
||||
// only allows draft→posted and posted→reversed, so the path matters.
|
||||
async function insertEntryAtStatus(params: {
|
||||
userId: string
|
||||
companyId: string
|
||||
fiscalPeriodId: string
|
||||
voucherNumber: number
|
||||
status?: 'posted' | 'reversed'
|
||||
}): Promise<string> {
|
||||
const entryId = await insertDraftJournalEntry({
|
||||
userId: params.userId,
|
||||
companyId: params.companyId,
|
||||
fiscalPeriodId: params.fiscalPeriodId,
|
||||
voucherNumber: params.voucherNumber,
|
||||
})
|
||||
await insertBalancedLines(entryId)
|
||||
await getPool().query(
|
||||
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
if (params.status === 'reversed') {
|
||||
await getPool().query(
|
||||
`UPDATE public.journal_entries SET status = 'reversed' WHERE id = $1`,
|
||||
[entryId],
|
||||
)
|
||||
}
|
||||
return entryId
|
||||
}
|
||||
|
||||
describe('document-immutability.pg: BFL retention bypass guards', () => {
|
||||
it('rejects unlinking (journal_entry_id → NULL) on a doc linked to a posted entry', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
})
|
||||
|
||||
it('rejects unlinking on a doc linked to a reversed entry', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1, status: 'reversed',
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
})
|
||||
|
||||
it('rejects unlinking on a doc linked to a draft entry: link is durable from first set', async () => {
|
||||
// The entry-level trigger does not consult journal_entries.status; once
|
||||
// journal_entry_id is set on a document, it cannot be cleared. This is
|
||||
// stricter than the original branch design and matches main's intent
|
||||
// that the verifikation→underlag link be durable from first set.
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const draftId = await insertDraftJournalEntry({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 0,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: draftId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
})
|
||||
|
||||
it('rejects re-pointing journal_entry_id to a different posted entry', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryA = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const entryB = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 2,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryA })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = $1 WHERE id = $2`,
|
||||
[entryB, docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
})
|
||||
|
||||
it('allows first-time linking (NULL → UUID): legitimate linkToJournalEntry path', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: null })
|
||||
|
||||
await getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = $1 WHERE id = $2`,
|
||||
[entryId, docId],
|
||||
)
|
||||
const after = await getPool().query<{ journal_entry_id: string | null }>(
|
||||
`SELECT journal_entry_id FROM public.document_attachments WHERE id = $1`,
|
||||
[docId],
|
||||
)
|
||||
expect(after.rows[0]!.journal_entry_id).toBe(entryId)
|
||||
})
|
||||
|
||||
it('rejects unlinking journal_entry_line_id on a doc linked to a posted entry', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const lineRow = await getPool().query<{ id: string }>(
|
||||
`SELECT id FROM public.journal_entry_lines WHERE journal_entry_id = $1 LIMIT 1`,
|
||||
[entryId],
|
||||
)
|
||||
const lineId = lineRow.rows[0]!.id
|
||||
const docId = await insertDocument({
|
||||
userId, companyId, journalEntryId: entryId, journalEntryLineId: lineId,
|
||||
})
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_line_id = NULL WHERE id = $1`,
|
||||
[docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
})
|
||||
|
||||
it('end-to-end: unlink-then-delete attack is blocked at the unlink step', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
|
||||
await expect(
|
||||
getPool().query(`DELETE FROM public.document_attachments WHERE id = $1`, [docId]),
|
||||
).rejects.toThrow(/Bokföringslagen/i)
|
||||
})
|
||||
|
||||
it('respects gnubok.allow_delete bypass: delete_last_voucher RPC keeps working', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
const client = await getPool().connect()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
await client.query(`SELECT set_config('gnubok.allow_delete', 'true', true)`)
|
||||
await client.query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = NULL WHERE id = $1`,
|
||||
[docId],
|
||||
)
|
||||
const after = await client.query<{ journal_entry_id: string | null }>(
|
||||
`SELECT journal_entry_id FROM public.document_attachments WHERE id = $1`,
|
||||
[docId],
|
||||
)
|
||||
expect(after.rows[0]!.journal_entry_id).toBeNull()
|
||||
await client.query('ROLLBACK')
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// The supersession flow needs to flip the OLD row from is_current_version=true
|
||||
// to false. The metadata-immutability trigger blocks that change for docs
|
||||
// linked to posted entries unless the gnubok.allow_supersede GUC is set:
|
||||
// which create_document_version sets before its UPDATE. Without this, users
|
||||
// have no way to replace a corrupt underlag (e.g. a bad PDF uploaded via the
|
||||
// MCP server before magic-byte validation).
|
||||
describe('document-immutability.pg: version supersession on posted entries', () => {
|
||||
it('allows create_document_version on a doc linked to a posted entry', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
// create_document_version is SECURITY DEFINER but enforces auth.uid()
|
||||
// matches p_user_id and that the caller is a company member, so the
|
||||
// call must run under withUserContext(userId).
|
||||
const newId = await withUserContext(userId, async (client) => {
|
||||
const result = await client.query<{ new_id: string }>(
|
||||
`SELECT public.create_document_version(
|
||||
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
|
||||
) AS new_id`,
|
||||
[
|
||||
userId,
|
||||
docId,
|
||||
`documents/${userId}/replacement.pdf`,
|
||||
'replacement.pdf',
|
||||
2048,
|
||||
'application/pdf',
|
||||
'b'.repeat(64),
|
||||
],
|
||||
)
|
||||
const id = result.rows[0]!.new_id
|
||||
// The transaction is rolled back by withUserContext, so we have to
|
||||
// assert state from within the same client/transaction.
|
||||
const oldRow = await client.query<{
|
||||
is_current_version: boolean
|
||||
superseded_by_id: string | null
|
||||
journal_entry_id: string | null
|
||||
}>(
|
||||
`SELECT is_current_version, superseded_by_id, journal_entry_id
|
||||
FROM public.document_attachments WHERE id = $1`,
|
||||
[docId],
|
||||
)
|
||||
expect(oldRow.rows[0]!.is_current_version).toBe(false)
|
||||
expect(oldRow.rows[0]!.superseded_by_id).toBe(id)
|
||||
expect(oldRow.rows[0]!.journal_entry_id).toBe(entryId)
|
||||
|
||||
const newRow = await client.query<{
|
||||
is_current_version: boolean
|
||||
version: number
|
||||
journal_entry_id: string | null
|
||||
prev_version_hash: string | null
|
||||
}>(
|
||||
`SELECT is_current_version, version, journal_entry_id, prev_version_hash
|
||||
FROM public.document_attachments WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
expect(newRow.rows[0]!.is_current_version).toBe(true)
|
||||
expect(newRow.rows[0]!.version).toBe(2)
|
||||
expect(newRow.rows[0]!.journal_entry_id).toBe(entryId)
|
||||
expect(newRow.rows[0]!.prev_version_hash).toBe('a'.repeat(64))
|
||||
|
||||
return id
|
||||
})
|
||||
|
||||
expect(newId).toBeDefined()
|
||||
})
|
||||
|
||||
it('allows create_document_version on a doc linked to a reversed entry', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1, status: 'reversed',
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
await withUserContext(userId, async (client) => {
|
||||
const result = await client.query(
|
||||
`SELECT public.create_document_version(
|
||||
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
|
||||
)`,
|
||||
[
|
||||
userId, docId,
|
||||
`documents/${userId}/replacement.pdf`,
|
||||
'replacement.pdf', 2048, 'application/pdf', 'c'.repeat(64),
|
||||
],
|
||||
)
|
||||
expect(result.rows).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
// Cross-tenant attack: a member of company A calls create_document_version
|
||||
// with a document id that belongs to company B. Before the auth+membership
|
||||
// check landed, the SECURITY DEFINER function would happily mutate the
|
||||
// foreign company's row because the GUC bypass disarmed the immutability
|
||||
// trigger. The membership guard inside the function is the only line of
|
||||
// defence: PostgREST exposes the RPC to all authenticated users.
|
||||
it('rejects create_document_version when caller is not a member of the document company', async () => {
|
||||
const { userId: aliceId, companyId: aliceCompanyId, fiscalPeriodId: aliceFp } =
|
||||
await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId: aliceId,
|
||||
companyId: aliceCompanyId,
|
||||
fiscalPeriodId: aliceFp,
|
||||
voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({
|
||||
userId: aliceId,
|
||||
companyId: aliceCompanyId,
|
||||
journalEntryId: entryId,
|
||||
})
|
||||
|
||||
// Bob has his own company; he is NOT a member of Alice's company.
|
||||
const bobId = await insertAuthUser()
|
||||
const bobCompany = await insertCompany({ createdBy: bobId })
|
||||
await insertCompanyMember({ companyId: bobCompany, userId: bobId, role: 'owner' })
|
||||
|
||||
await withUserContext(bobId, async (client) => {
|
||||
await expect(
|
||||
client.query(
|
||||
`SELECT public.create_document_version(
|
||||
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
|
||||
)`,
|
||||
[
|
||||
bobId, docId,
|
||||
`documents/${bobId}/exfil.pdf`,
|
||||
'exfil.pdf', 2048, 'application/pdf', 'd'.repeat(64),
|
||||
],
|
||||
),
|
||||
).rejects.toThrow(/not a member/i)
|
||||
})
|
||||
})
|
||||
|
||||
// Identity-spoofing attack: caller passes p_user_id ≠ auth.uid(). Allowing
|
||||
// this would let any authenticated user manufacture supersession events
|
||||
// attributed to a different user: useful for audit-log forgery even when
|
||||
// the supersession itself is legitimate.
|
||||
it('rejects create_document_version when p_user_id does not match auth.uid()', async () => {
|
||||
const { userId: aliceId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId: aliceId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({
|
||||
userId: aliceId, companyId, journalEntryId: entryId,
|
||||
})
|
||||
|
||||
// Mallory is also a member of the company: so the membership check
|
||||
// alone would not catch a spoofed p_user_id.
|
||||
const malloryId = await insertAuthUser()
|
||||
await insertCompanyMember({ companyId, userId: malloryId, role: 'member' })
|
||||
|
||||
await withUserContext(malloryId, async (client) => {
|
||||
await expect(
|
||||
client.query(
|
||||
`SELECT public.create_document_version(
|
||||
$1::uuid, $2::uuid, $3::text, $4::text, $5::bigint, $6::text, $7::text
|
||||
)`,
|
||||
[
|
||||
// Spoofing aliceId as the actor while auth.uid() is malloryId.
|
||||
aliceId, docId,
|
||||
`documents/${aliceId}/spoofed.pdf`,
|
||||
'spoofed.pdf', 2048, 'application/pdf', 'e'.repeat(64),
|
||||
],
|
||||
),
|
||||
).rejects.toThrow(/does not match authenticated user/i)
|
||||
})
|
||||
})
|
||||
|
||||
// The narrowed bypass: even with allow_supersede set, a direct UPDATE that
|
||||
// tries to change sha256_hash, journal_entry_id, or any other audit field
|
||||
// must still be blocked. Before the narrowing the GUC was a blanket
|
||||
// bypass that disarmed the entire trigger.
|
||||
it('keeps blocking sha256_hash mutation even when allow_supersede is set', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
const client = await getPool().connect()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
await client.query(`SELECT set_config('gnubok.allow_supersede', 'true', true)`)
|
||||
await expect(
|
||||
client.query(
|
||||
`UPDATE public.document_attachments SET sha256_hash = $2 WHERE id = $1`,
|
||||
[docId, 'f'.repeat(64)],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
await client.query('ROLLBACK')
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps blocking journal_entry_id mutation even when allow_supersede is set', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryA = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const entryB = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 2,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryA })
|
||||
|
||||
const client = await getPool().connect()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
await client.query(`SELECT set_config('gnubok.allow_supersede', 'true', true)`)
|
||||
await expect(
|
||||
client.query(
|
||||
`UPDATE public.document_attachments SET journal_entry_id = $1 WHERE id = $2`,
|
||||
[entryB, docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
await client.query('ROLLBACK')
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects direct UPDATE flipping is_current_version without the GUC', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.document_attachments SET is_current_version = false WHERE id = $1`,
|
||||
[docId],
|
||||
),
|
||||
).rejects.toThrow(BFL_RETENTION_ERROR)
|
||||
})
|
||||
|
||||
it('respects gnubok.allow_supersede bypass on direct UPDATE', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
const entryId = await insertEntryAtStatus({
|
||||
userId, companyId, fiscalPeriodId, voucherNumber: 1,
|
||||
})
|
||||
const docId = await insertDocument({ userId, companyId, journalEntryId: entryId })
|
||||
|
||||
const client = await getPool().connect()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
await client.query(`SELECT set_config('gnubok.allow_supersede', 'true', true)`)
|
||||
await client.query(
|
||||
`UPDATE public.document_attachments SET is_current_version = false WHERE id = $1`,
|
||||
[docId],
|
||||
)
|
||||
const after = await client.query<{ is_current_version: boolean }>(
|
||||
`SELECT is_current_version FROM public.document_attachments WHERE id = $1`,
|
||||
[docId],
|
||||
)
|
||||
expect(after.rows[0]!.is_current_version).toBe(false)
|
||||
await client.query('ROLLBACK')
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,190 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
readBodyWithCap,
|
||||
resolveUpstreamStorageUrl,
|
||||
toSameOriginStorageUrl,
|
||||
} from '../storage-proxy'
|
||||
|
||||
const SUPABASE = 'https://pwxtzglxptnnvjrpixpg.supabase.co'
|
||||
const APP = 'https://app.accounted.se'
|
||||
const UPLOAD_URL = `${SUPABASE}/storage/v1/object/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`
|
||||
const DOWNLOAD_URL = `${SUPABASE}/storage/v1/object/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig&download=`
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', SUPABASE)
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', APP)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('toSameOriginStorageUrl', () => {
|
||||
it('moves a signed upload URL onto the app origin, keeping path encoding and the token', () => {
|
||||
expect(toSameOriginStorageUrl(UPLOAD_URL)).toBe(
|
||||
`${APP}/api/storage/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`,
|
||||
)
|
||||
})
|
||||
|
||||
it('moves a signed download URL onto the app origin with every query parameter', () => {
|
||||
expect(toSameOriginStorageUrl(DOWNLOAD_URL)).toBe(
|
||||
`${APP}/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig&download=`,
|
||||
)
|
||||
})
|
||||
|
||||
it('tolerates a trailing slash on the app URL', () => {
|
||||
expect(toSameOriginStorageUrl(DOWNLOAD_URL, `${APP}/`)).toMatch(
|
||||
new RegExp(`^${APP}/api/storage/sign/`),
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves the URL alone when the app has no public URL (self-host without NEXT_PUBLIC_APP_URL)', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', '')
|
||||
expect(toSameOriginStorageUrl(UPLOAD_URL)).toBe(UPLOAD_URL)
|
||||
expect(toSameOriginStorageUrl(UPLOAD_URL, undefined)).toBe(UPLOAD_URL)
|
||||
})
|
||||
|
||||
it('leaves URLs on other hosts, other buckets, unsigned paths and token-less links alone', () => {
|
||||
expect(toSameOriginStorageUrl('https://storage.example/upload?token=signed')).toBe(
|
||||
'https://storage.example/upload?token=signed',
|
||||
)
|
||||
const otherBucket = `${SUPABASE}/storage/v1/object/sign/avatars/a.png?token=t`
|
||||
expect(toSameOriginStorageUrl(otherBucket)).toBe(otherBucket)
|
||||
const publicObject = `${SUPABASE}/storage/v1/object/public/documents/a.pdf`
|
||||
expect(toSameOriginStorageUrl(publicObject)).toBe(publicObject)
|
||||
const noToken = `${SUPABASE}/storage/v1/object/sign/documents/a.pdf`
|
||||
expect(toSameOriginStorageUrl(noToken)).toBe(noToken)
|
||||
expect(toSameOriginStorageUrl('not a url')).toBe('not a url')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveUpstreamStorageUrl', () => {
|
||||
it('rebuilds the upstream signed URL for upload and download paths', () => {
|
||||
expect(
|
||||
resolveUpstreamStorageUrl(
|
||||
'upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf',
|
||||
new URLSearchParams('token=eyJ.sig'),
|
||||
),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
url: `${SUPABASE}/storage/v1/object/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`,
|
||||
})
|
||||
expect(
|
||||
resolveUpstreamStorageUrl(
|
||||
'sign/documents/co-1/user-1/kvitto.pdf',
|
||||
new URLSearchParams('token=eyJ.sig&download='),
|
||||
),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
url: `${SUPABASE}/storage/v1/object/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig&download=`,
|
||||
})
|
||||
})
|
||||
|
||||
it('fails closed on anything that is not a signed documents-bucket object path', () => {
|
||||
const token = new URLSearchParams('token=t')
|
||||
expect(resolveUpstreamStorageUrl('public/documents/a.pdf', token)).toEqual({
|
||||
ok: false,
|
||||
reason: 'unsupported_path',
|
||||
})
|
||||
expect(resolveUpstreamStorageUrl('sign/avatars/a.png', token)).toEqual({
|
||||
ok: false,
|
||||
reason: 'unsupported_path',
|
||||
})
|
||||
expect(resolveUpstreamStorageUrl('sign/documents/', token)).toEqual({
|
||||
ok: false,
|
||||
reason: 'unsupported_path',
|
||||
})
|
||||
expect(resolveUpstreamStorageUrl('sign/documents/../bucket/x', token)).toEqual({
|
||||
ok: false,
|
||||
reason: 'unsupported_path',
|
||||
})
|
||||
expect(resolveUpstreamStorageUrl('list/documents', token)).toEqual({
|
||||
ok: false,
|
||||
reason: 'unsupported_path',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects dot segments in every spelling the URL parser would normalise away', () => {
|
||||
const token = new URLSearchParams('token=t')
|
||||
for (const evil of [
|
||||
'sign/documents/%2e%2e/avatars/x',
|
||||
'sign/documents/.%2e/avatars/x',
|
||||
'sign/documents/%2e./avatars/x',
|
||||
'sign/documents/%2E%2E/avatars/x',
|
||||
'sign/documents/a/../../avatars/x',
|
||||
'sign/documents/./x',
|
||||
'sign/documents/a//x',
|
||||
'sign/documents/a%5c..%5cavatars/x',
|
||||
'sign/documents/a\\..\\avatars/x',
|
||||
'sign/documents/a%2f..%2favatars/x',
|
||||
'sign/documents/%zz/x',
|
||||
'upload/sign/documents/%2e%2e/avatars/x',
|
||||
]) {
|
||||
expect(resolveUpstreamStorageUrl(evil, token), evil).toEqual({
|
||||
ok: false,
|
||||
reason: 'unsupported_path',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('still accepts real keys with spaces, non-ASCII and dots inside names', () => {
|
||||
const token = new URLSearchParams('token=t')
|
||||
const resolved = resolveUpstreamStorageUrl(
|
||||
'sign/documents/co-1/user-1/faktura%20maj%20%C3%A5r.2026.pdf',
|
||||
token,
|
||||
)
|
||||
expect(resolved.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('requires the signed token', () => {
|
||||
expect(resolveUpstreamStorageUrl('sign/documents/a.pdf', new URLSearchParams())).toEqual({
|
||||
ok: false,
|
||||
reason: 'missing_token',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an unconfigured Storage host instead of guessing', () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', '')
|
||||
expect(
|
||||
resolveUpstreamStorageUrl('sign/documents/a.pdf', new URLSearchParams('token=t')),
|
||||
).toEqual({ ok: false, reason: 'storage_unconfigured' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('readBodyWithCap', () => {
|
||||
function stream(chunks: Uint8Array[]): ReadableStream<Uint8Array> {
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of chunks) controller.enqueue(chunk)
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('concatenates a body under the cap', async () => {
|
||||
const out = await readBodyWithCap(
|
||||
stream([new TextEncoder().encode('%PDF'), new TextEncoder().encode('-1.4')]),
|
||||
100,
|
||||
)
|
||||
expect(out && new TextDecoder().decode(out)).toBe('%PDF-1.4')
|
||||
})
|
||||
|
||||
it('returns null as soon as the running total passes the cap, without draining the rest', async () => {
|
||||
let pulled = 0
|
||||
const endless = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
pulled++
|
||||
controller.enqueue(new Uint8Array(1024))
|
||||
},
|
||||
})
|
||||
|
||||
const out = await readBodyWithCap(endless, 4096)
|
||||
|
||||
expect(out).toBeNull()
|
||||
expect(pulled).toBeLessThan(10)
|
||||
})
|
||||
|
||||
it('treats a missing body as empty', async () => {
|
||||
expect((await readBodyWithCap(null, 10))?.byteLength).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,463 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import {
|
||||
anchorSupplierInvoiceDocument,
|
||||
reanchorOrphanedSupplierInvoiceDocuments,
|
||||
sweepFloatingSupplierInvoiceDocuments,
|
||||
} from '../supplier-invoice-underlag'
|
||||
|
||||
/**
|
||||
* anchorSupplierInvoiceDocument issues its queries in a fixed `.from()` order,
|
||||
* and the queued mock consumes one enqueued result per `.from()` call:
|
||||
* 1. supplier_invoices (the invoice + its FK verifikat)
|
||||
* 2. document_attachments (the retained document, anchor check)
|
||||
* 3. supplier_invoice_payments (partial-payment verifikat candidates)
|
||||
* 4. journal_entries (status + period of every candidate)
|
||||
* 5. document_attachments (the anchoring UPDATE)
|
||||
* Steps 3-5 are skipped when the document needs no anchoring.
|
||||
*/
|
||||
describe('anchorSupplierInvoiceDocument', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const openPeriod = { is_closed: false, locked_at: null }
|
||||
|
||||
it('anchors a floating document to the payment verifikat when registration was reversed', async () => {
|
||||
// The reported case: the invoice PDF was orphaned when the rättelse it had
|
||||
// been relinked onto was deleted, leaving the posted payment verifikat
|
||||
// warning "Underlag saknas" while the verifikat view showed the PDF.
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: 'je-pay',
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{
|
||||
data: [
|
||||
{ id: 'je-reg', status: 'reversed', fiscal_period: openPeriod },
|
||||
{ id: 'je-pay', status: 'posted', fiscal_period: openPeriod },
|
||||
],
|
||||
},
|
||||
{ data: [{ id: 'doc-1' }] },
|
||||
])
|
||||
|
||||
const anchored = await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
)
|
||||
|
||||
expect(anchored).toBe('je-pay')
|
||||
expect(supabase.from).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
|
||||
it('prefers the registration verifikat: it is the primary booking', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: 'je-pay',
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{
|
||||
data: [
|
||||
{ id: 'je-reg', status: 'posted', fiscal_period: openPeriod },
|
||||
{ id: 'je-pay', status: 'posted', fiscal_period: openPeriod },
|
||||
],
|
||||
},
|
||||
{ data: [{ id: 'doc-1' }] },
|
||||
])
|
||||
|
||||
expect(
|
||||
await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
),
|
||||
).toBe('je-reg')
|
||||
})
|
||||
|
||||
it('falls back to a partial-payment verifikat, oldest first', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: null,
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [{ journal_entry_id: 'je-p1' }, { journal_entry_id: 'je-p2' }] },
|
||||
{
|
||||
data: [
|
||||
{ id: 'je-p1', status: 'posted', fiscal_period: openPeriod },
|
||||
{ id: 'je-p2', status: 'posted', fiscal_period: openPeriod },
|
||||
],
|
||||
},
|
||||
{ data: [{ id: 'doc-1' }] },
|
||||
])
|
||||
|
||||
expect(
|
||||
await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
),
|
||||
).toBe('je-p1')
|
||||
})
|
||||
|
||||
it('never moves a document that is already anchored', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: 'je-pay',
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: 'je-reg', is_current_version: true } },
|
||||
])
|
||||
|
||||
expect(
|
||||
await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
),
|
||||
).toBeNull()
|
||||
// Stopped before the candidate lookup: no UPDATE was attempted.
|
||||
expect(supabase.from).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('leaves a superseded document alone', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: false } },
|
||||
])
|
||||
|
||||
expect(
|
||||
await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
),
|
||||
).toBeNull()
|
||||
expect(supabase.from).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('skips a candidate whose period is locked (the trigger would reject the write)', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 'je-reg',
|
||||
status: 'posted',
|
||||
fiscal_period: { is_closed: false, locked_at: '2026-07-01T00:00:00Z' },
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
expect(
|
||||
await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
),
|
||||
).toBeNull()
|
||||
// Candidates were resolved, but no UPDATE followed.
|
||||
expect(supabase.from).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('does nothing when the invoice has no retained document', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: null,
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
expect(
|
||||
await anchorSupplierInvoiceDocument(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
'si-1',
|
||||
),
|
||||
).toBeNull()
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reports a zero-row update as null: a write that never happened is not an anchor', async () => {
|
||||
// Prod case 2026-08-28 (faktura 118776): every static condition passed yet
|
||||
// the document stayed floating. The guarded update can match nothing (a
|
||||
// concurrent writer, or RLS filtering the row); claiming success then hides
|
||||
// the miss from both callers and the reconcile cron.
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: null,
|
||||
payment_journal_entry_id: 'je-pay',
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'je-pay', status: 'posted', fiscal_period: openPeriod }] },
|
||||
{ data: [] }, // UPDATE matched no rows
|
||||
])
|
||||
|
||||
await expect(
|
||||
anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1'),
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('names the foreign key in the fiscal_periods embed', async () => {
|
||||
// fiscal_periods points back at journal_entries twice (closing_entry_id,
|
||||
// opening_balance_entry_id), so the bare embed is ambiguous and PostgREST
|
||||
// answers PGRST201. The bare form shipped 2026-07-27 and this helper
|
||||
// anchored nothing in production until 2026-09-01. A mocked client resolves
|
||||
// no relationship, so asserting the string is the only thing a unit test
|
||||
// can do here; scripts/checks/ambiguous-embed.mjs is the repo-wide guard.
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'je-reg', status: 'posted', fiscal_period: openPeriod }] },
|
||||
{ data: [{ id: 'doc-1' }] },
|
||||
])
|
||||
|
||||
await anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1')
|
||||
|
||||
expect(findCall('journal_entries', 'select')?.[0]).toContain(
|
||||
'fiscal_periods!journal_entries_fiscal_period_id_fkey',
|
||||
)
|
||||
})
|
||||
|
||||
it('logs the reason when the period lock state cannot be read, and anchors nothing', async () => {
|
||||
// Failing closed is right: never anchor on a lock state we could not read.
|
||||
// Failing SILENTLY is what let the PGRST201 above sit dead for five weeks,
|
||||
// with the caller's "no verifikat can anchor it" warning as the only
|
||||
// signal, naming a cause that had nothing to do with it.
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{
|
||||
error: {
|
||||
message:
|
||||
"Could not embed because more than one relationship was found for 'journal_entries' and 'fiscal_periods'",
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
await expect(
|
||||
anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1'),
|
||||
).resolves.toBeNull()
|
||||
// Stopped at the failed read: no UPDATE was attempted.
|
||||
expect(supabase.from).toHaveBeenCalledTimes(4)
|
||||
const logged = consoleError.mock.calls.flat().join(' ')
|
||||
expect(logged).toContain('failed to resolve period lock state for supplier invoice anchoring')
|
||||
expect(logged).toContain('more than one relationship')
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('reports failure as null instead of throwing at the caller', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: 'je-reg',
|
||||
payment_journal_entry_id: null,
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'je-reg', status: 'posted', fiscal_period: openPeriod }] },
|
||||
{ error: { message: 'period locked' } },
|
||||
])
|
||||
|
||||
await expect(
|
||||
anchorSupplierInvoiceDocument(supabase as unknown as SupabaseClient, 'company-1', 'si-1'),
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('sweepFloatingSupplierInvoiceDocuments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const openPeriod = { is_closed: false, locked_at: null }
|
||||
|
||||
it('anchors every floating retained document it finds, across companies', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
// Candidate scan: two invoices with floating current-version documents.
|
||||
{
|
||||
data: [
|
||||
{ id: 'si-1', company_id: 'company-1', document: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ id: 'si-2', company_id: 'company-2', document: { id: 'doc-2', journal_entry_id: null, is_current_version: true } },
|
||||
],
|
||||
},
|
||||
// anchorSupplierInvoiceDocument for si-1 (5 queries)
|
||||
{ data: { id: 'si-1', document_id: 'doc-1', registration_journal_entry_id: null, payment_journal_entry_id: 'je-1' } },
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'je-1', status: 'posted', fiscal_period: openPeriod }] },
|
||||
{ data: [{ id: 'doc-1' }] },
|
||||
// anchorSupplierInvoiceDocument for si-2: its only verifikat is locked.
|
||||
{ data: { id: 'si-2', document_id: 'doc-2', registration_journal_entry_id: null, payment_journal_entry_id: 'je-2' } },
|
||||
{ data: { id: 'doc-2', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'je-2', status: 'posted', fiscal_period: { is_closed: true, locked_at: null } }] },
|
||||
])
|
||||
|
||||
const result = await sweepFloatingSupplierInvoiceDocuments(
|
||||
supabase as unknown as SupabaseClient,
|
||||
)
|
||||
expect(result).toEqual({ candidates: 2, anchored: 1 })
|
||||
})
|
||||
|
||||
it('returns zeros and touches nothing when no document is floating', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([{ data: [] }])
|
||||
|
||||
const result = await sweepFloatingSupplierInvoiceDocuments(
|
||||
supabase as unknown as SupabaseClient,
|
||||
)
|
||||
expect(result).toEqual({ candidates: 0, anchored: 0 })
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('survives a failed candidate scan without throwing', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([{ error: { message: 'relation walk failed' } }])
|
||||
|
||||
await expect(
|
||||
sweepFloatingSupplierInvoiceDocuments(supabase as unknown as SupabaseClient),
|
||||
).resolves.toEqual({ candidates: 0, anchored: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('reanchorOrphanedSupplierInvoiceDocuments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('re-anchors the supplier invoice whose document a deleted voucher orphaned', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([
|
||||
{ data: [{ id: 'si-1' }] }, // supplier_invoices by document_id
|
||||
{
|
||||
data: {
|
||||
id: 'si-1',
|
||||
document_id: 'doc-1',
|
||||
registration_journal_entry_id: null,
|
||||
payment_journal_entry_id: 'je-pay',
|
||||
},
|
||||
},
|
||||
{ data: { id: 'doc-1', journal_entry_id: null, is_current_version: true } },
|
||||
{ data: [] },
|
||||
{
|
||||
data: [{ id: 'je-pay', status: 'posted', fiscal_period: { is_closed: false, locked_at: null } }],
|
||||
},
|
||||
{ data: [{ id: 'doc-1' }] },
|
||||
])
|
||||
|
||||
expect(
|
||||
await reanchorOrphanedSupplierInvoiceDocuments(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
['doc-1'],
|
||||
),
|
||||
).toBe(1)
|
||||
})
|
||||
|
||||
it('leaves a plain receipt floating so it returns to the unlinked pool', async () => {
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
enqueueMany([{ data: [] }]) // no supplier invoice owns this document
|
||||
|
||||
expect(
|
||||
await reanchorOrphanedSupplierInvoiceDocuments(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
['doc-9'],
|
||||
),
|
||||
).toBe(0)
|
||||
})
|
||||
|
||||
it('short-circuits when the deleted voucher had no documents', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
expect(
|
||||
await reanchorOrphanedSupplierInvoiceDocuments(
|
||||
supabase as unknown as SupabaseClient,
|
||||
'company-1',
|
||||
[],
|
||||
),
|
||||
).toBe(0)
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user