Simpl-Resultat/src/__integration__/unlink-and-delete-import.test.ts
le king fu fc077d49a7
All checks were successful
PR Check — Frontend / frontend (pull_request) Successful in 3m25s
test: count a manual transaction's link in the whole-history summary (#522)
Review 32761: excluding transactions without a file_id from the
delete-all count stayed green, while unlinkAndDeleteAllImports removes
those links for good.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:24:53 -05:00

277 lines
12 KiB
TypeScript

/**
* An import whose transactions are linked to the Balance sheet (#522).
*
* Deleting such an import is refused (`ON DELETE RESTRICT`, ADR 0010), and the
* history used to print the raw English error with no way out. The panel now
* counts the transfers it would lose (`getLinkedTransfersSummary`, a real
* `COUNT(*)`, not the 50-row pre-flight) and offers to unlink them and delete
* in one SQL transaction (`unlinkAndDeleteImport`, `unlinkAndDeleteAllImports`).
*
* Every case runs on a real SQLite database with foreign keys on
* (`src/test/sqliteHarness.ts`), with the four starter balance accounts of a
* new profile (Compte chèque, CELI, REER, Compte non-enregistré).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { DatabaseSync } from "node:sqlite";
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
const { logInfo } = vi.hoisted(() => ({ logInfo: vi.fn() }));
vi.mock("../services/logService", () => ({ logInfo, logWarn: vi.fn(), logError: vi.fn() }));
import { openProfileDb, useDb } from "../test/sqliteHarness";
import { subscribeDataChanged } from "../services/dataEvents";
import { TransactionLinkedToBalanceError } from "../services/transactionService";
import {
deleteImportWithTransactions,
getLinkedTransfersSummary,
unlinkAndDeleteAllImports,
unlinkAndDeleteImport,
} from "../services/importedFileService";
let db: DatabaseSync;
let notifications = 0;
let unsubscribe: () => void = () => undefined;
const count = (sql: string, ...params: (number | string)[]) =>
Number((db.prepare(sql).get(...params) as { n: number }).n);
const accountId = (name: string) =>
Number((db.prepare("SELECT id FROM balance_accounts WHERE name = ?").get(name) as { id: number }).id);
/** A source with one imported file of `rows` transactions; returns their ids. */
function seedImport(sourceName: string, rows: number): { sourceId: number; fileId: number; txIds: number[] } {
const sourceId = Number(
db.prepare("INSERT INTO import_sources (name, column_mapping) VALUES (?, '{}')").run(sourceName)
.lastInsertRowid,
);
const fileId = Number(
db
.prepare("INSERT INTO imported_files (source_id, filename, file_hash, row_count) VALUES (?, ?, ?, ?)")
.run(sourceId, `${sourceName}.csv`, `hash-${sourceName}`, rows).lastInsertRowid,
);
const insert = db.prepare(
"INSERT INTO transactions (date, description, amount, source_id, file_id) VALUES (?, ?, ?, ?, ?)",
);
const txIds: number[] = [];
for (let i = 0; i < rows; i++) {
const day = String((i % 28) + 1).padStart(2, "0");
txIds.push(Number(insert.run(`2026-01-${day}`, `Virement ${i}`, -100 - i, sourceId, fileId).lastInsertRowid));
}
return { sourceId, fileId, txIds };
}
function link(account: string, transactionId: number, direction: "in" | "out" = "in") {
db.prepare("INSERT INTO balance_account_transfers (account_id, transaction_id, direction) VALUES (?, ?, ?)").run(
accountId(account),
transactionId,
direction,
);
}
beforeEach(() => {
db = useDb(openProfileDb());
notifications = 0;
unsubscribe = subscribeDataChanged(() => {
notifications += 1;
});
logInfo.mockClear();
});
afterEach(() => {
unsubscribe();
db.close();
});
describe("getLinkedTransfersSummary (#522)", () => {
it("counts every transfer of one import, beyond the 50 rows of the pre-flight, per account sorted by name", async () => {
const { fileId, txIds } = seedImport("Desjardins", 70);
for (const id of txIds.slice(0, 60)) link("REER", id);
link("CELI", txIds[60]);
const other = seedImport("Tangerine", 2);
link("CELI", other.txIds[0]);
const summary = await getLinkedTransfersSummary({ kind: "file", fileId });
expect(summary.transferCount).toBe(61);
expect(summary.accounts.map((a) => [a.account_name, a.transfer_count, a.is_active])).toEqual([
["CELI", 1, true],
["REER", 60, true],
]);
});
it("counts every transfer of the profile for the whole history, a manual transaction's link included", async () => {
const a = seedImport("Desjardins", 3);
const b = seedImport("Tangerine", 3);
link("CELI", a.txIds[0]);
link("REER", a.txIds[0]);
link("CELI", b.txIds[2]);
// Entered by hand, no import: "delete all" removes it and its link too.
const manual = Number(
db
.prepare("INSERT INTO transactions (date, description, amount) VALUES ('2026-02-01', 'Manuelle', -10)")
.run().lastInsertRowid,
);
link("Compte non-enregistré", manual);
const summary = await getLinkedTransfersSummary({ kind: "all" });
expect(summary.transferCount).toBe(4);
expect(summary.accounts.map((x) => x.account_name)).toEqual(["CELI", "Compte non-enregistré", "REER"]);
});
it("marks an archived account as inactive", async () => {
const { fileId, txIds } = seedImport("Desjardins", 1);
link("REER", txIds[0]);
db.prepare("UPDATE balance_accounts SET is_active = 0, archived_at = CURRENT_TIMESTAMP WHERE name = 'REER'").run();
const summary = await getLinkedTransfersSummary({ kind: "file", fileId });
expect(summary.accounts).toEqual([
{ account_id: accountId("REER"), account_name: "REER", is_active: false, transfer_count: 1 },
]);
});
it("counts a linked split child that does not carry the import's file_id", async () => {
const { fileId, sourceId, txIds } = seedImport("Desjardins", 1);
const child = Number(
db
.prepare(
"INSERT INTO transactions (date, description, amount, source_id, file_id, parent_transaction_id) VALUES ('2026-01-01', 'Part', -50, ?, NULL, ?)",
)
.run(sourceId, txIds[0]).lastInsertRowid,
);
link("CELI", child);
expect((await getLinkedTransfersSummary({ kind: "file", fileId })).transferCount).toBe(1);
});
});
describe("unlinkAndDeleteImport (#522)", () => {
it("the plain delete is still refused while a transfer is linked", async () => {
const { fileId, txIds } = seedImport("Desjardins", 2);
link("CELI", txIds[0]);
await expect(deleteImportWithTransactions(fileId)).rejects.toBeInstanceOf(TransactionLinkedToBalanceError);
});
it("removes the import's transfers, transactions, file and orphaned source together; another import keeps its own", async () => {
const target = seedImport("Desjardins", 70);
for (const id of target.txIds.slice(0, 55)) link("REER", id);
const kept = seedImport("Tangerine", 2);
link("CELI", kept.txIds[1], "out");
const outcome = await unlinkAndDeleteImport(target.fileId);
expect(outcome).toEqual({ unlinked: 55, deleted: 70 });
expect(count("SELECT COUNT(*) AS n FROM transactions WHERE file_id = ?", target.fileId)).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM imported_files WHERE id = ?", target.fileId)).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM import_sources WHERE id = ?", target.sourceId)).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers WHERE transaction_id = ?", kept.txIds[1])).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM transactions WHERE file_id = ?", kept.fileId)).toBe(2);
// The balance accounts themselves stay.
expect(count("SELECT COUNT(*) AS n FROM balance_accounts WHERE name = 'REER'")).toBe(1);
expect(notifications).toBe(1);
});
it("keeps the source when another import still uses it", async () => {
const first = seedImport("Desjardins", 1);
const second = Number(
db
.prepare("INSERT INTO imported_files (source_id, filename, file_hash) VALUES (?, 'b.csv', 'hash-b')")
.run(first.sourceId).lastInsertRowid,
);
link("CELI", first.txIds[0]);
await unlinkAndDeleteImport(first.fileId);
expect(count("SELECT COUNT(*) AS n FROM import_sources WHERE id = ?", first.sourceId)).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM imported_files WHERE id = ?", second)).toBe(1);
});
it("unlinks a split child the parent's cascade removes, instead of failing on its link", async () => {
const { fileId, sourceId, txIds } = seedImport("Desjardins", 1);
const child = Number(
db
.prepare(
"INSERT INTO transactions (date, description, amount, source_id, file_id, parent_transaction_id) VALUES ('2026-01-01', 'Part', -50, ?, NULL, ?)",
)
.run(sourceId, txIds[0]).lastInsertRowid,
);
link("CELI", child);
await expect(unlinkAndDeleteImport(fileId)).resolves.toEqual({ unlinked: 1, deleted: 1 });
expect(count("SELECT COUNT(*) AS n FROM transactions")).toBe(0);
});
it("leaves everything in place when a step fails, and announces nothing", async () => {
const { fileId, sourceId, txIds } = seedImport("Desjardins", 3);
link("CELI", txIds[0]);
link("REER", txIds[1]);
db.exec(
"CREATE TRIGGER refuse_file_delete BEFORE DELETE ON imported_files BEGIN SELECT RAISE(ABORT, 'refused by test'); END;",
);
await expect(unlinkAndDeleteImport(fileId)).rejects.toThrow("refused by test");
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(2);
expect(count("SELECT COUNT(*) AS n FROM transactions WHERE file_id = ?", fileId)).toBe(3);
expect(count("SELECT COUNT(*) AS n FROM imported_files WHERE id = ?", fileId)).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM import_sources WHERE id = ?", sourceId)).toBe(1);
expect(notifications).toBe(0);
expect(logInfo).not.toHaveBeenCalled();
});
it("writes one Journal line that carries the numbers and no account name", async () => {
const { fileId, txIds } = seedImport("Desjardins", 4);
link("CELI", txIds[0]);
link("Compte non-enregistré", txIds[1]);
await unlinkAndDeleteImport(fileId);
expect(logInfo).toHaveBeenCalledTimes(1);
const line = logInfo.mock.calls[0].map(String).join(" ");
expect(line).toContain("2 Balance transfer(s) unlinked");
expect(line).toContain("4 transaction(s) deleted");
for (const name of ["CELI", "REER", "Compte", "Desjardins"]) expect(line).not.toContain(name);
});
});
describe("unlinkAndDeleteAllImports (#522)", () => {
it("removes every transfer, transaction, import and source, a manual transaction's link included", async () => {
const a = seedImport("Desjardins", 2);
const b = seedImport("Tangerine", 2);
link("CELI", a.txIds[0]);
link("REER", b.txIds[1]);
const manual = Number(
db
.prepare("INSERT INTO transactions (date, description, amount) VALUES ('2026-02-01', 'Manuelle', -10)")
.run().lastInsertRowid,
);
link("CELI", manual);
await expect(unlinkAndDeleteAllImports()).resolves.toEqual({ unlinked: 3, deleted: 5 });
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM transactions")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM imported_files")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM import_sources")).toBe(0);
expect(count("SELECT COUNT(*) AS n FROM balance_accounts")).toBe(4);
expect(notifications).toBe(1);
expect(logInfo).toHaveBeenCalledTimes(1);
});
it("leaves everything in place when a step fails", async () => {
const a = seedImport("Desjardins", 2);
link("CELI", a.txIds[0]);
db.exec(
"CREATE TRIGGER refuse_source_delete BEFORE DELETE ON import_sources BEGIN SELECT RAISE(ABORT, 'refused by test'); END;",
);
await expect(unlinkAndDeleteAllImports()).rejects.toThrow("refused by test");
expect(count("SELECT COUNT(*) AS n FROM balance_account_transfers")).toBe(1);
expect(count("SELECT COUNT(*) AS n FROM transactions")).toBe(2);
expect(count("SELECT COUNT(*) AS n FROM imported_files")).toBe(1);
expect(notifications).toBe(0);
});
});