fix: unlink Balance transfers from the window and the import history (#522)

Linked transactions now show first in "Link transfers", checked, with no
date bound; a save diffs the selection and calls unlinkTransfer for the
unchecked ones. A delete of the import history refused for linked
transfers keeps a structured state instead of the English error text:
the panel names the accounts, counts the transfers with a COUNT(*), links
to the account's window when the edition opens the Balance sheet
(/balance?linkTransfers=<id>), and offers "Unlink and delete" in every
edition, one SQL transaction, the Journal line carrying numbers only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-08 20:05:12 -05:00
commit ff33bfa57e
16 changed files with 1582 additions and 62 deletions

View file

@ -0,0 +1,270 @@
/**
* 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", 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]);
const summary = await getLinkedTransfersSummary({ kind: "all" });
expect(summary.transferCount).toBe(3);
expect(summary.accounts.map((x) => x.account_name)).toEqual(["CELI", "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);
});
});

View file

@ -16,6 +16,8 @@ vi.mock("../../services/transactionService", () => ({
}));
vi.mock("../../services/balance.service", () => ({
linkTransfer: vi.fn(),
unlinkTransfer: vi.fn(),
listAccountTransfers: vi.fn(async () => []),
suggestTransferDirection: vi.fn(() => "in"),
BalanceServiceError: class extends Error {},
}));

View file

@ -10,9 +10,16 @@
// (auto-proposed via `suggestTransferDirection` from the signed amount,
// can be flipped per row), and a checkbox.
//
// On submit, calls `linkTransfer` for every selected row in sequence and
// reports any failures (most likely `transfer_already_linked` if the user
// double-clicked or another tab linked them already).
// The transactions already linked to the account (#522) are loaded once, with
// no date bound, and listed first, checked, whatever the filters: unchecking
// one and saving unlinks it. Their direction stays as stored (to change it:
// uncheck, save, check again). The filtered rows follow, without duplicates.
//
// On submit, the selection is diffed against the loaded links: a newly checked
// row is linked (`linkTransfer`), an unchecked linked row is unlinked
// (`unlinkTransfer`), in sequence, and any failure is reported (most likely
// `transfer_already_linked` when another tab linked it already). A row that is
// already unlinked (`transfer_not_linked`) counts as done.
import { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
@ -21,12 +28,13 @@ import { X, Loader2, AlertCircle } from "lucide-react";
import { getTransactionPage } from "../../services/transactionService";
import {
linkTransfer,
unlinkTransfer,
listAccountTransfers,
suggestTransferDirection,
BalanceServiceError,
} from "../../services/balance.service";
import type {
Category,
TransactionRow,
BalanceTransferDirection,
} from "../../shared/types";
import CategoryCombobox from "../shared/CategoryCombobox";
@ -46,6 +54,24 @@ function localISO(d: Date): string {
return `${yy}-${mm}-${dd}`;
}
/** One row of the window: a transaction, already linked or not. */
interface ModalRow {
id: number;
date: string;
description: string;
amount: number;
}
/** The changes a save would make: rows to link (with their direction), rows to unlink. */
export function diffTransferSelection(
linked: ReadonlyMap<number, BalanceTransferDirection>,
selection: ReadonlyMap<number, BalanceTransferDirection>
): { toLink: Array<[number, BalanceTransferDirection]>; toUnlink: number[] } {
const toLink = [...selection.entries()].filter(([id]) => !linked.has(id));
const toUnlink = [...linked.keys()].filter((id) => !selection.has(id));
return { toLink, toUnlink };
}
export interface LinkTransfersModalProps {
/** Account that the selected transfers will be attached to. */
accountId: number;
@ -56,8 +82,8 @@ export interface LinkTransfersModalProps {
initialFrom?: string;
initialTo?: string;
onClose: () => void;
/** Fired after at least one transfer was linked (parent typically reloads). */
onLinked?: (linkedCount: number) => void;
/** Fired after at least one transfer was linked or unlinked (parent reloads). */
onChanged?: (counts: { linked: number; unlinked: number }) => void;
}
export default function LinkTransfersModal({
@ -67,7 +93,7 @@ export default function LinkTransfersModal({
initialFrom,
initialTo,
onClose,
onLinked,
onChanged,
}: LinkTransfersModalProps) {
const { t, i18n } = useTranslation();
@ -76,10 +102,16 @@ export default function LinkTransfersModal({
const [categoryId, setCategoryId] = useState<number | null>(null);
const [search, setSearch] = useState("");
const [rows, setRows] = useState<TransactionRow[]>([]);
const [rows, setRows] = useState<ModalRow[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Transfers already linked to this account (#522): transaction id → stored
// direction, and their rows, listed first. null until loaded.
const [linked, setLinked] = useState<Map<number, BalanceTransferDirection> | null>(null);
const [linkedRows, setLinkedRows] = useState<ModalRow[]>([]);
const [linkedError, setLinkedError] = useState<string | null>(null);
// Selection state: id → direction. Presence in the map = selected.
const [selection, setSelection] = useState<
Map<number, BalanceTransferDirection>
@ -104,6 +136,36 @@ export default function LinkTransfersModal({
[t]
);
// Load the account's links once, with no date bound: a link older than the
// filtered period must still show, checked, so it can be unlinked.
useEffect(() => {
let cancelled = false;
async function run() {
try {
const transfers = await listAccountTransfers(accountId);
if (cancelled) return;
const map = new Map<number, BalanceTransferDirection>();
for (const tr of transfers) map.set(tr.transaction_id, tr.direction);
setLinked(map);
setLinkedRows(
transfers.map((tr) => ({
id: tr.transaction_id,
date: tr.transaction_date,
description: tr.transaction_description,
amount: tr.transaction_amount,
}))
);
setSelection(new Map(map));
} catch (e) {
if (!cancelled) setLinkedError(e instanceof Error ? e.message : String(e));
}
}
void run();
return () => {
cancelled = true;
};
}, [accountId]);
// Re-fetch whenever the filters change. Debounced via React's render cycle
// — typing in the search box re-runs the SQL but at < 500 rows that's fine.
useEffect(() => {
@ -144,19 +206,21 @@ export default function LinkTransfersModal({
};
}, [from, to, categoryId, search]);
function toggleRow(row: TransactionRow) {
function toggleRow(row: ModalRow) {
setSelection((prev) => {
const next = new Map(prev);
if (next.has(row.id)) {
next.delete(row.id);
} else {
next.set(row.id, suggestTransferDirection(row.amount));
// A linked row checked again keeps its stored direction.
next.set(row.id, linked?.get(row.id) ?? suggestTransferDirection(row.amount));
}
return next;
});
}
function flipDirection(rowId: number) {
if (linked?.has(rowId)) return;
setSelection((prev) => {
const next = new Map(prev);
const current = next.get(rowId);
@ -166,39 +230,70 @@ export default function LinkTransfersModal({
});
}
const { toLink, toUnlink } = diffTransferSelection(linked ?? new Map(), selection);
const changeCount = toLink.length + toUnlink.length;
function describeFailure(transactionId: number, e: unknown): string {
if (e instanceof BalanceServiceError) {
return `${transactionId}: ${t(`balance.transfers.errors.${e.code}`, { defaultValue: e.message })}`;
}
return `${transactionId}: ${e instanceof Error ? e.message : String(e)}`;
}
async function handleSubmit() {
if (selection.size === 0) return;
if (linked === null || changeCount === 0) return;
setSubmitting(true);
setSubmitError(null);
let linked = 0;
let linkedCount = 0;
let unlinkedCount = 0;
const failures: string[] = [];
for (const [transactionId, direction] of selection.entries()) {
for (const transactionId of toUnlink) {
try {
await unlinkTransfer(accountId, transactionId);
unlinkedCount += 1;
} catch (e) {
// Already unlinked elsewhere: the wanted state is reached.
if (e instanceof BalanceServiceError && e.code === "transfer_not_linked") {
unlinkedCount += 1;
} else {
failures.push(describeFailure(transactionId, e));
}
}
}
for (const [transactionId, direction] of toLink) {
try {
await linkTransfer(accountId, transactionId, direction);
linked += 1;
linkedCount += 1;
} catch (e) {
if (e instanceof BalanceServiceError) {
failures.push(`${transactionId}: ${t(`balance.transfers.errors.${e.code}`, { defaultValue: e.message })}`);
} else {
failures.push(`${transactionId}: ${e instanceof Error ? e.message : String(e)}`);
}
failures.push(describeFailure(transactionId, e));
}
}
setSubmitting(false);
if (failures.length > 0) {
setSubmitError(
`${t("balance.transfers.modal.partialFailure", { linked, total: selection.size })} — ${failures.join("; ")}`
`${t("balance.transfers.modal.partialFailure", {
done: linkedCount + unlinkedCount,
total: changeCount,
linked: linkedCount,
unlinked: unlinkedCount,
})} — ${failures.join("; ")}`
);
}
if (linked > 0) {
onLinked?.(linked);
if (failures.length === 0) {
onClose();
}
if (linkedCount + unlinkedCount > 0) {
onChanged?.({ linked: linkedCount, unlinked: unlinkedCount });
}
if (failures.length === 0) {
onClose();
}
}
const allFiltered = rows.length;
// Linked rows first, then the filtered rows that are not linked.
const displayRows = useMemo(() => {
const linkedIds = new Set(linkedRows.map((r) => r.id));
return [...linkedRows, ...rows.filter((r) => !linkedIds.has(r.id))];
}, [linkedRows, rows]);
const allShown = displayRows.length;
const selectedCount = selection.size;
return createPortal(
@ -290,17 +385,17 @@ export default function LinkTransfersModal({
</div>
<div className="flex-1 overflow-auto">
{isLoading ? (
{(isLoading || linked === null) && !error && !linkedError ? (
<div className="p-8 text-center text-[var(--muted-foreground)] flex items-center justify-center gap-2">
<Loader2 className="animate-spin" size={16} />
{t("balance.transfers.modal.loading")}
</div>
) : error ? (
) : error || linkedError ? (
<div className="p-8 text-center text-[var(--negative)] flex items-center justify-center gap-2">
<AlertCircle size={16} />
{error}
{error ?? linkedError}
</div>
) : rows.length === 0 ? (
) : displayRows.length === 0 ? (
<div className="p-8 text-center text-[var(--muted-foreground)] italic">
{t("balance.transfers.modal.noTransactions")}
</div>
@ -324,9 +419,12 @@ export default function LinkTransfersModal({
</tr>
</thead>
<tbody>
{rows.map((row) => {
{displayRows.map((row) => {
const isSelected = selection.has(row.id);
const direction = selection.get(row.id) ?? suggestTransferDirection(row.amount);
const storedDirection = linked?.get(row.id);
const isLinked = storedDirection !== undefined;
const direction =
selection.get(row.id) ?? storedDirection ?? suggestTransferDirection(row.amount);
return (
<tr
key={row.id}
@ -342,6 +440,11 @@ export default function LinkTransfersModal({
</td>
<td className="px-3 py-2 whitespace-nowrap">{row.date}</td>
<td className="px-3 py-2 max-w-md truncate" title={row.description}>
{isLinked && (
<span className="mr-2 px-1.5 py-0.5 text-[10px] rounded bg-[var(--primary)]/15 text-[var(--primary)] font-medium">
{t("balance.transfers.modal.linkedBadge")}
</span>
)}
{row.description}
</td>
<td
@ -350,7 +453,7 @@ export default function LinkTransfersModal({
{fmt.format(row.amount)}
</td>
<td className="px-3 py-2 text-center">
{isSelected ? (
{isSelected && !isLinked ? (
<button
type="button"
onClick={() => flipDirection(row.id)}
@ -364,7 +467,10 @@ export default function LinkTransfersModal({
{t(`balance.transfers.direction.${direction}`)}
</button>
) : (
<span className="text-xs text-[var(--muted-foreground)]">
<span
className="text-xs text-[var(--muted-foreground)]"
title={isLinked ? t("balance.transfers.modal.directionFixed") : undefined}
>
{t(`balance.transfers.direction.${direction}`)}
</span>
)}
@ -387,8 +493,17 @@ export default function LinkTransfersModal({
<div className="text-xs text-[var(--muted-foreground)]">
{t("balance.transfers.modal.summary", {
selected: selectedCount,
total: allFiltered,
total: allShown,
})}
{changeCount > 0 && (
<>
{" — "}
{t("balance.transfers.modal.changes", {
link: toLink.length,
unlink: toUnlink.length,
})}
</>
)}
</div>
<div className="flex gap-2">
<button
@ -401,7 +516,7 @@ export default function LinkTransfersModal({
<button
type="button"
onClick={handleSubmit}
disabled={submitting || selectedCount === 0}
disabled={submitting || linked === null || changeCount === 0}
className="px-3 py-1.5 text-sm rounded bg-[var(--primary)] text-white disabled:opacity-50 disabled:cursor-not-allowed"
>
{submitting ? (
@ -410,7 +525,7 @@ export default function LinkTransfersModal({
{t("balance.transfers.modal.linking")}
</span>
) : (
t("balance.transfers.modal.linkSelection", { count: selectedCount })
t("balance.transfers.modal.save")
)}
</button>
</div>

View file

@ -0,0 +1,220 @@
// LinkTransfersModal — unlinking from the window (#522).
//
// `unlinkTransfer` had no caller: the window listed the filtered transactions
// unchecked, a linked one included, and only linked the checked rows. Now the
// account's links load once, with no date bound, and come first, checked; a
// save diffs the selection against them. Same harness as the wiring test of
// the category filter (src/test/hookHarness.ts): the window runs as a plain
// function, `commit()` runs its effects, the test clicks through the props of
// the elements it finds.
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
import type { ReactNode } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock());
vi.mock("react-dom", async (orig) => ({
...(await orig<typeof import("react-dom")>()),
createPortal: (children: ReactNode) => children,
}));
const svc = vi.hoisted(() => {
class BalanceServiceError extends Error {
constructor(
readonly code: string,
message: string,
) {
super(message);
}
}
return {
getTransactionPage: vi.fn(),
listAccountTransfers: vi.fn(),
linkTransfer: vi.fn(),
unlinkTransfer: vi.fn(),
BalanceServiceError,
};
});
vi.mock("../../services/transactionService", () => ({ getTransactionPage: svc.getTransactionPage }));
vi.mock("../../services/balance.service", () => ({
linkTransfer: svc.linkTransfer,
unlinkTransfer: svc.unlinkTransfer,
listAccountTransfers: svc.listAccountTransfers,
suggestTransferDirection: (amount: number) => (amount < 0 ? "in" : "out"),
BalanceServiceError: svc.BalanceServiceError,
}));
import { hookHarness } from "../../test/hookHarness";
import { find, texts, type TreeProps } from "../../test/elementTree";
import LinkTransfersModal, { diffTransferSelection } from "./LinkTransfersModal";
const harness = hookHarness();
/** Linked in March, outside the window's period (July to September). */
const OLD_LINK = {
id: 90,
account_id: 1,
transaction_id: 501,
direction: "out" as const,
notes: null,
created_at: "",
transaction_date: "2026-03-02",
transaction_description: "Dépôt CELI mars",
transaction_amount: -500,
account_name: "CELI",
};
const FILTERED = [
{ id: 600, date: "2026-08-01", description: "Virement août", amount: -200 },
// The same transaction, also in the period: listed once, among the links.
{ id: 501, date: "2026-03-02", description: "Dépôt CELI mars", amount: -500 },
];
const onClose = vi.fn();
const onChanged = vi.fn();
const PROPS = {
accountId: 1,
accountName: "CELI",
categories: [],
initialFrom: "2026-07-01",
initialTo: "2026-09-30",
onClose,
onChanged,
};
const render = () => harness.render(() => LinkTransfersModal(PROPS));
const flush = async () => {
for (let i = 0; i < 10; i++) await Promise.resolve();
};
/** Mounts the window and lets both loads settle. */
async function mount() {
render();
harness.commit();
await flush();
return render();
}
const checkboxes = (tree: ReturnType<typeof render>) =>
find(tree, (el) => el.type === "input" && (el.props as TreeProps).type === "checkbox").map(
(el) => el.props as TreeProps & { checked: boolean; onChange: () => void; "aria-label": string },
);
const saveButton = (tree: ReturnType<typeof render>) => {
const buttons = find(tree, (el) => el.type === "button" && texts(el).includes("t(balance.transfers.modal.save)"));
expect(buttons).toHaveLength(1);
return buttons[0].props as TreeProps & { disabled: boolean; onClick: () => Promise<void> };
};
beforeAll(() => {
vi.stubGlobal("document", { body: {} });
});
afterAll(() => {
vi.unstubAllGlobals();
});
beforeEach(() => {
harness.clear();
for (const fn of [svc.getTransactionPage, svc.listAccountTransfers, svc.linkTransfer, svc.unlinkTransfer]) {
fn.mockReset();
}
onClose.mockReset();
onChanged.mockReset();
svc.getTransactionPage.mockResolvedValue({ rows: FILTERED, total: FILTERED.length });
svc.listAccountTransfers.mockResolvedValue([OLD_LINK]);
svc.linkTransfer.mockResolvedValue(1);
svc.unlinkTransfer.mockResolvedValue(undefined);
});
describe("LinkTransfersModal — linked transactions (#522)", () => {
it("loads the account's links with no date bound", async () => {
await mount();
expect(svc.listAccountTransfers).toHaveBeenCalledWith(1);
});
it("lists a link outside the filtered period first, checked, once, then the other rows unchecked", async () => {
const boxes = checkboxes(await mount());
expect(boxes.map((b) => [b["aria-label"], b.checked])).toEqual([
["select-501", true],
["select-600", false],
]);
});
it("marks the linked row and keeps its stored direction, with no flip button", async () => {
const tree = await mount();
const all = texts(tree);
expect(all).toContain("t(balance.transfers.modal.linkedBadge)");
expect(all.filter((s) => s === "t(balance.transfers.modal.linkedBadge)")).toHaveLength(1);
// Stored "out" although the negative amount would suggest "in".
expect(all).toContain("t(balance.transfers.direction.out)");
expect(find(tree, (el) => el.type === "button" && (el.props as TreeProps).title === "t(balance.transfers.modal.toggleDirection)")).toHaveLength(0);
});
it("keeps the save disabled while nothing changed", async () => {
expect(saveButton(await mount()).disabled).toBe(true);
});
it("unchecking a linked row and saving unlinks it, links nothing, reports the change and closes", async () => {
checkboxes(await mount())[0].onChange();
const save = saveButton(render());
expect(save.disabled).toBe(false);
await save.onClick();
expect(svc.unlinkTransfer).toHaveBeenCalledTimes(1);
expect(svc.unlinkTransfer).toHaveBeenCalledWith(1, 501);
expect(svc.linkTransfer).not.toHaveBeenCalled();
expect(onChanged).toHaveBeenCalledWith({ linked: 0, unlinked: 1 });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("checking a new row links it with its suggested direction, and leaves the linked one alone", async () => {
checkboxes(await mount())[1].onChange();
await saveButton(render()).onClick();
expect(svc.linkTransfer).toHaveBeenCalledTimes(1);
expect(svc.linkTransfer).toHaveBeenCalledWith(1, 600, "in");
expect(svc.unlinkTransfer).not.toHaveBeenCalled();
expect(onChanged).toHaveBeenCalledWith({ linked: 1, unlinked: 0 });
});
it("unchecked then checked again: no change, nothing saved", async () => {
checkboxes(await mount())[0].onChange();
checkboxes(render())[0].onChange();
expect(saveButton(render()).disabled).toBe(true);
});
it("counts a row already unlinked elsewhere as done", async () => {
svc.unlinkTransfer.mockRejectedValue(new svc.BalanceServiceError("transfer_not_linked", "gone"));
checkboxes(await mount())[0].onChange();
await saveButton(render()).onClick();
expect(onChanged).toHaveBeenCalledWith({ linked: 0, unlinked: 1 });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("reports a failed unlink with both counts and stays open", async () => {
svc.unlinkTransfer.mockRejectedValue(new Error("database is locked"));
const boxes = checkboxes(await mount());
boxes[0].onChange();
boxes[1].onChange();
await saveButton(render()).onClick();
expect(onChanged).toHaveBeenCalledWith({ linked: 1, unlinked: 0 });
expect(onClose).not.toHaveBeenCalled();
const message = texts(render()).find((s) => s.includes("partialFailure"));
expect(message).toContain("t(balance.transfers.modal.partialFailure[done=1,total=2,linked=1,unlinked=0])");
expect(message).toContain("501: database is locked");
});
});
describe("diffTransferSelection (#522)", () => {
it("links the new rows and unlinks the linked rows left out", () => {
const linked = new Map([
[1, "in" as const],
[2, "out" as const],
]);
const selection = new Map([
[2, "out" as const],
[3, "in" as const],
]);
expect(diffTransferSelection(linked, selection)).toEqual({ toLink: [[3, "in"]], toUnlink: [1] });
});
});

View file

@ -19,6 +19,8 @@ const { getTransactionPage } = vi.hoisted(() => ({ getTransactionPage: vi.fn() }
vi.mock("../../services/transactionService", () => ({ getTransactionPage }));
vi.mock("../../services/balance.service", () => ({
linkTransfer: vi.fn(),
unlinkTransfer: vi.fn(),
listAccountTransfers: vi.fn(async () => []),
suggestTransferDirection: vi.fn(() => "in"),
BalanceServiceError: class extends Error {},
}));

View file

@ -2,6 +2,8 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Trash2, Inbox, AlertTriangle } from "lucide-react";
import { useImportHistory } from "../../hooks/useImportHistory";
import { useEntitlement } from "../../hooks/useEntitlement";
import LinkedTransfersNotice, { UnlinkAndDeleteConfirm } from "./LinkedTransfersNotice";
interface ImportHistoryPanelProps {
onChanged?: () => void;
@ -11,9 +13,19 @@ export default function ImportHistoryPanel({
onChanged,
}: ImportHistoryPanelProps) {
const { t } = useTranslation();
const { state, handleDelete, handleDeleteAll } = useImportHistory(onChanged);
const { state, handleDelete, handleDeleteAll, handleUnlinkAndDelete, dismissBlocked } =
useImportHistory(onChanged);
const { allowed: balanceAllowed } = useEntitlement("balance");
const [confirmDelete, setConfirmDelete] = useState<{ id: number; filename: string; rowCount: number } | null>(null);
const [confirmDeleteAll, setConfirmDeleteAll] = useState(false);
const [confirmUnlink, setConfirmUnlink] = useState(false);
// #522 — the file a refused one-import delete targets, for the confirmation.
const blockedScope = state.blocked?.scope;
const blockedFilename =
blockedScope?.kind === "file"
? (state.files.find((f) => f.id === blockedScope.fileId)?.filename ?? null)
: null;
return (
<div className="mt-8">
@ -36,6 +48,17 @@ export default function ImportHistoryPanel({
<p className="text-sm text-[var(--negative)] mb-2">{state.error}</p>
)}
{state.blocked && (
<LinkedTransfersNotice
blocked={state.blocked}
balanceAllowed={balanceAllowed}
failed={state.unlinkFailed}
disabled={state.isDeleting}
onUnlinkAndDelete={() => setConfirmUnlink(true)}
onDismiss={dismissBlocked}
/>
)}
{state.isLoading ? (
<p className="text-sm text-[var(--muted-foreground)]">
{t("common.loading")}
@ -187,6 +210,19 @@ export default function ImportHistoryPanel({
</div>
</div>
)}
{/* Confirm unlink and delete (#522) */}
{confirmUnlink && state.blocked && (
<UnlinkAndDeleteConfirm
blocked={state.blocked}
filename={blockedFilename}
onCancel={() => setConfirmUnlink(false)}
onConfirm={() => {
setConfirmUnlink(false);
void handleUnlinkAndDelete();
}}
/>
)}
</div>
);
}

View file

@ -0,0 +1,166 @@
// LinkedTransfersNotice (#522) through the REAL locales: the history used to
// show the English text of `TransactionLinkedToBalanceError` in both
// languages. The plural forms, the "and N others" of the account list and the
// link to "Lier transferts" only exist in fr.json and en.json.
import { describe, it, expect, afterAll } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import i18n from "../../i18n/config";
import LinkedTransfersNotice, { UnlinkAndDeleteConfirm } from "./LinkedTransfersNotice";
import type { BlockedDeletion } from "../../hooks/useImportHistory";
const account = (account_id: number, account_name: string, transfer_count = 1, is_active = true) => ({
account_id,
account_name,
is_active,
transfer_count,
});
const ONE: BlockedDeletion = {
scope: { kind: "file", fileId: 8 },
summary: { transferCount: 1, accounts: [account(2, "CELI")] },
};
const MANY: BlockedDeletion = {
scope: { kind: "all" },
summary: {
transferCount: 64,
accounts: [
account(9, "Compte chèque"),
account(2, "CELI", 2),
account(3, "REER", 58, false),
account(5, "Ledger"),
account(6, "Wealthsimple", 2),
],
},
};
const UNKNOWN: BlockedDeletion = { scope: { kind: "file", fileId: 8 }, summary: null };
const RAW = "Transaction is linked to one or more balance accounts";
const notice = (blocked: BlockedDeletion, balanceAllowed: boolean) =>
renderToStaticMarkup(
<MemoryRouter>
<LinkedTransfersNotice
blocked={blocked}
balanceAllowed={balanceAllowed}
failed={false}
disabled={false}
onUnlinkAndDelete={() => undefined}
onDismiss={() => undefined}
/>
</MemoryRouter>,
);
const confirm = (blocked: BlockedDeletion, filename: string | null = "releve.csv") =>
renderToStaticMarkup(
<UnlinkAndDeleteConfirm blocked={blocked} filename={filename} onCancel={() => undefined} onConfirm={() => undefined} />,
);
const text = (html: string) =>
html
.replace(/<[^>]+>/g, " ")
.replace(/&#x27;/g, "'")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.replace(/\s+/g, " ")
.trim();
const links = (html: string) => [...html.matchAll(/<a [^>]*href="([^"]+)"[^>]*>([^<]*)<\/a>/g)].map((m) => [m[1], m[2]]);
afterAll(async () => {
await i18n.changeLanguage("fr");
});
describe("LinkedTransfersNotice — French (#522)", () => {
it("one import, one transfer: names the account and counts it", async () => {
await i18n.changeLanguage("fr");
const t = text(notice(ONE, true));
expect(t).toContain(
"Cet import ne peut pas être supprimé tel quel : 1 transfert du Bilan s'appuie sur ses transactions, dans CELI.",
);
expect(t).toContain("Déliez-les dans « Lier transferts » du compte, ou déliez-les et supprimez en une fois.");
expect(t).toContain("Délier et supprimer");
expect(t).not.toContain(RAW);
});
it("the whole history: three names then « et 2 autres », the real count", async () => {
await i18n.changeLanguage("fr");
expect(text(notice(MANY, true))).toContain(
"Les imports ne peuvent pas être supprimés tels quels : 64 transferts du Bilan s'appuient sur leurs transactions, dans Compte chèque, CELI, REER et 2 autres.",
);
});
it("Premium: one link per named active account to its « Lier transferts », none for an archived one", async () => {
await i18n.changeLanguage("fr");
expect(links(notice(MANY, true))).toEqual([
["/balance?linkTransfers=9", "Lier transferts : Compte chèque"],
["/balance?linkTransfers=2", "Lier transferts : CELI"],
]);
});
it("Free: no link, the unlink-and-delete stays offered, and the hint says so", async () => {
await i18n.changeLanguage("fr");
const html = notice(MANY, false);
expect(links(html)).toEqual([]);
expect(text(html)).toContain("Délier et supprimer");
expect(text(html)).toContain("Vous pouvez les délier et supprimer en une fois ; ces transferts seront perdus.");
});
it("the count failed: a translated message without names", async () => {
await i18n.changeLanguage("fr");
const t = text(notice(UNKNOWN, true));
expect(t).toContain("La suppression est refusée : des transactions sont liées à des comptes du Bilan.");
expect(t).not.toContain(RAW);
});
it("the confirmation states the exact count, lost for good, the accounts and the import", async () => {
await i18n.changeLanguage("fr");
const t = text(confirm({ ...MANY, scope: { kind: "file", fileId: 8 } }));
expect(t).toContain("64 transferts du Bilan seront déliés sans retour, même avec une clé.");
expect(t).toContain("Comptes touchés : Compte chèque, CELI, REER et 2 autres.");
expect(t).toContain("Puis l'import « releve.csv » et ses transactions seront supprimés.");
});
it("the confirmation, singular, for the whole history", async () => {
await i18n.changeLanguage("fr");
const t = text(confirm({ ...ONE, scope: { kind: "all" } }));
expect(t).toContain("1 transfert du Bilan sera délié sans retour, même avec une clé.");
expect(t).toContain("Puis tous les imports et leurs transactions seront supprimés.");
});
it("Cancel comes first and holds the focus; the destructive button is the second", async () => {
await i18n.changeLanguage("fr");
const buttons = [...confirm(ONE).matchAll(/<button([^>]*)>([^<]*)<\/button>/g)].map((m) => [m[1], m[2]]);
expect(buttons.map((b) => b[1])).toEqual(["Annuler", "Délier et supprimer"]);
expect(buttons[0][0]).toContain("autofocus");
expect(buttons[1][0]).not.toContain("autofocus");
});
});
describe("LinkedTransfersNotice — English (#522)", () => {
it("one import, one transfer", async () => {
await i18n.changeLanguage("en");
const t = text(notice(ONE, true));
expect(t).toContain("This import cannot be deleted as is: 1 Balance transfer relies on its transactions, in CELI.");
expect(t).toContain("Unlink and delete");
expect(t).not.toContain(RAW);
});
it("the whole history, « and 2 others », and the links", async () => {
await i18n.changeLanguage("en");
const html = notice(MANY, true);
expect(text(html)).toContain(
"The imports cannot be deleted as is: 64 Balance transfers rely on their transactions, in Compte chèque, CELI, REER and 2 others.",
);
expect(links(html)).toEqual([
["/balance?linkTransfers=9", "Link transfers: Compte chèque"],
["/balance?linkTransfers=2", "Link transfers: CELI"],
]);
});
it("the confirmation", async () => {
await i18n.changeLanguage("en");
const t = text(confirm(MANY));
expect(t).toContain("64 Balance transfers will be unlinked for good, even with a key.");
expect(t).toContain("Then every import and its transactions will be deleted.");
});
});

View file

@ -0,0 +1,195 @@
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { AlertTriangle, X } from "lucide-react";
import type { BlockedDeletion } from "../../hooks/useImportHistory";
import type { LinkedTransfersSummary } from "../../services/importedFileService";
import { formatRootFiles } from "../../utils/rootFiles";
import { linkTransfersHref } from "../../utils/balanceLinkParam";
/** Accounts a message names before counting the rest (#522). */
export const NAMED_ACCOUNTS = 3;
/** "CELI, REER, Compte chèque et 2 autres": three names, then the count of the rest. */
export function useAccountList() {
const { t } = useTranslation();
return (summary: LinkedTransfersSummary): string => {
const { shown, more } = formatRootFiles(
summary.accounts.map((a) => a.account_name),
NAMED_ACCOUNTS
);
return (
shown.join(", ") + (more > 0 ? ` ${t("import.history.linked.more", { count: more })}` : "")
);
};
}
export interface LinkedTransfersNoticeProps {
blocked: BlockedDeletion;
/** The Balance sheet is open in this edition: offer the link to "Lier transferts". */
balanceAllowed: boolean;
/** The unlink-and-delete failed: nothing was changed. */
failed: boolean;
disabled: boolean;
onUnlinkAndDelete: () => void;
onDismiss: () => void;
}
/**
* The import history's delete refused because some transactions are linked to
* the Balance sheet (#522, ADR 0010): names the accounts (three, then the
* count of the rest), counts the transfers, links to each named active
* account's "Lier transferts" when the edition opens the Balance sheet, and
* offers "Unlink and delete" in every edition. Never the error's English text.
*/
export default function LinkedTransfersNotice({
blocked,
balanceAllowed,
failed,
disabled,
onUnlinkAndDelete,
onDismiss,
}: LinkedTransfersNoticeProps) {
const { t } = useTranslation();
const accountList = useAccountList();
const { summary, scope } = blocked;
const message =
summary && summary.transferCount > 0
? t(
scope.kind === "file"
? "import.history.linked.messageFile"
: "import.history.linked.messageAll",
{ count: summary.transferCount, accounts: accountList(summary) }
)
: t("import.history.linked.messageUnknown");
const linkable =
balanceAllowed && summary
? summary.accounts.slice(0, NAMED_ACCOUNTS).filter((a) => a.is_active)
: [];
return (
<div
role="alert"
className="mb-4 p-3 rounded-xl bg-[var(--card)] border-2 border-[var(--negative)]/40 flex items-start gap-2"
>
<AlertTriangle size={16} aria-hidden="true" className="text-[var(--negative)] shrink-0 mt-0.5" />
<div className="flex-1 text-sm space-y-2">
<p className="text-[var(--foreground)]">{message}</p>
<p className="text-[var(--muted-foreground)]">
{t(
balanceAllowed
? "import.history.linked.hintBalance"
: "import.history.linked.hintNoBalance"
)}
</p>
{failed && (
<p className="text-[var(--negative)]">{t("import.history.linked.failed")}</p>
)}
<div className="flex flex-wrap items-center gap-2">
{linkable.map((a) => (
<Link
key={a.account_id}
to={linkTransfersHref(a.account_id)}
className="px-3 py-1.5 text-sm rounded-lg border border-[var(--border)] hover:bg-[var(--muted)]"
>
{t("import.history.linked.openAccount", { account: a.account_name })}
</Link>
))}
<button
type="button"
onClick={onUnlinkAndDelete}
disabled={disabled}
className="px-3 py-1.5 text-sm rounded-lg bg-[var(--negative)] text-white hover:opacity-90 disabled:opacity-50"
>
{t("import.history.linked.unlinkAndDelete")}
</button>
</div>
</div>
<button
type="button"
onClick={onDismiss}
className="p-1 rounded hover:bg-[var(--muted)]"
aria-label={t("common.close")}
>
<X size={16} />
</button>
</div>
);
}
export interface UnlinkAndDeleteConfirmProps {
blocked: BlockedDeletion;
/** The file name, for one import's delete. */
filename: string | null;
onCancel: () => void;
onConfirm: () => void;
}
/**
* Confirmation of "Unlink and delete": how many Balance sheet transfers are
* lost for good, even with a key, and which accounts; Cancel has the focus.
*/
export function UnlinkAndDeleteConfirm({
blocked,
filename,
onCancel,
onConfirm,
}: UnlinkAndDeleteConfirmProps) {
const { t } = useTranslation();
const accountList = useAccountList();
const { summary, scope } = blocked;
const known = summary !== null && summary.transferCount > 0;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="unlink-and-delete-title"
className="bg-[var(--card)] rounded-xl border border-[var(--border)] shadow-lg p-6 max-w-md w-full mx-4"
>
<div className="flex items-center gap-3 mb-4">
<div className="p-2 rounded-full bg-[var(--negative)]/10">
<AlertTriangle size={20} className="text-[var(--negative)]" />
</div>
<h2 id="unlink-and-delete-title" className="text-lg font-semibold">
{t("import.history.linked.unlinkAndDelete")}
</h2>
</div>
<p className="text-sm text-[var(--foreground)] mb-2">
{known
? t("import.history.linked.confirmBody", { count: summary.transferCount })
: t("import.history.linked.confirmBodyUnknown")}
</p>
{known && (
<p className="text-sm text-[var(--muted-foreground)] mb-2">
{t("import.history.linked.confirmAccounts", { accounts: accountList(summary) })}
</p>
)}
<p className="text-sm text-[var(--muted-foreground)] mb-6">
{scope.kind === "file"
? t("import.history.linked.confirmFile", { filename: filename ?? "" })
: t("import.history.linked.confirmAll")}
</p>
<div className="flex justify-end gap-3">
<button
type="button"
autoFocus
onClick={onCancel}
className="px-4 py-2 text-sm rounded-lg border border-[var(--border)] hover:bg-[var(--muted)] transition-colors"
>
{t("common.cancel")}
</button>
<button
type="button"
onClick={onConfirm}
className="px-4 py-2 text-sm rounded-lg bg-[var(--negative)] text-white hover:opacity-90 transition-opacity"
>
{t("import.history.linked.unlinkAndDelete")}
</button>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,143 @@
// useImportHistory — a delete refused for linked Balance transfers (#522).
//
// The hook used to keep `String(err)`: the English text of
// `TransactionLinkedToBalanceError`, shown as is in both languages. It now
// keeps a structured refusal (scope, accounts, real count), and "Unlink and
// delete" runs the service of that scope. Under the shared hook harness
// (src/test/hookHarness.ts): the hook runs as a plain function, `commit()`
// runs its load effect.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const svc = vi.hoisted(() => ({
getAllImportedFiles: vi.fn(),
deleteImportWithTransactions: vi.fn(),
deleteAllImportsWithTransactions: vi.fn(),
getLinkedTransfersSummary: vi.fn(),
unlinkAndDeleteImport: vi.fn(),
unlinkAndDeleteAllImports: vi.fn(),
}));
vi.mock("../services/importedFileService", () => svc);
vi.mock("../services/transactionService", () => ({
TransactionLinkedToBalanceError: class TransactionLinkedToBalanceError extends Error {
constructor() {
super("Transaction is linked to one or more balance accounts; unlink before deleting");
}
},
}));
import { hookHarness } from "../test/hookHarness";
import { TransactionLinkedToBalanceError } from "../services/transactionService";
import { useImportHistory } from "./useImportHistory";
const harness = hookHarness();
const onChanged = vi.fn();
const render = () => harness.render(() => useImportHistory(onChanged));
const SUMMARY = {
transferCount: 61,
accounts: [
{ account_id: 2, account_name: "CELI", is_active: true, transfer_count: 1 },
{ account_id: 3, account_name: "REER", is_active: true, transfer_count: 60 },
],
};
const refusal = () => new (TransactionLinkedToBalanceError as unknown as new () => Error)();
beforeEach(() => {
harness.clear();
for (const fn of Object.values(svc)) fn.mockReset();
onChanged.mockReset();
svc.getAllImportedFiles.mockResolvedValue([]);
svc.getLinkedTransfersSummary.mockResolvedValue(SUMMARY);
svc.unlinkAndDeleteImport.mockResolvedValue({ unlinked: 61, deleted: 70 });
svc.unlinkAndDeleteAllImports.mockResolvedValue({ unlinked: 61, deleted: 70 });
});
describe("useImportHistory — refused delete (#522)", () => {
it("keeps a structured refusal for one import, with the real count, and never the error's text", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
const { state } = render();
expect(svc.getLinkedTransfersSummary).toHaveBeenCalledWith({ kind: "file", fileId: 8 });
expect(state.blocked).toEqual({ scope: { kind: "file", fileId: 8 }, summary: SUMMARY });
expect(state.error).toBeNull();
expect(onChanged).not.toHaveBeenCalled();
});
it("does the same for the whole history", async () => {
svc.deleteAllImportsWithTransactions.mockRejectedValue(refusal());
await render().handleDeleteAll();
expect(svc.getLinkedTransfersSummary).toHaveBeenCalledWith({ kind: "all" });
expect(render().state.blocked).toEqual({ scope: { kind: "all" }, summary: SUMMARY });
});
it("keeps the refusal without a summary when the count fails", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
svc.getLinkedTransfersSummary.mockRejectedValue(new Error("database is locked"));
await render().handleDelete(8);
expect(render().state.blocked).toEqual({ scope: { kind: "file", fileId: 8 }, summary: null });
expect(render().state.error).toBeNull();
});
it("keeps any other error as text", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(new Error("disk full"));
await render().handleDelete(8);
expect(render().state.error).toBe("Error: disk full");
expect(render().state.blocked).toBeNull();
});
it("unlinks and deletes the refused import, clears the refusal, reloads and announces", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
svc.getAllImportedFiles.mockClear();
await render().handleUnlinkAndDelete();
expect(svc.unlinkAndDeleteImport).toHaveBeenCalledWith(8);
expect(svc.unlinkAndDeleteAllImports).not.toHaveBeenCalled();
expect(render().state.blocked).toBeNull();
expect(svc.getAllImportedFiles).toHaveBeenCalledTimes(1);
expect(onChanged).toHaveBeenCalledTimes(1);
});
it("unlinks and deletes everything for a refused delete-all", async () => {
svc.deleteAllImportsWithTransactions.mockRejectedValue(refusal());
await render().handleDeleteAll();
await render().handleUnlinkAndDelete();
expect(svc.unlinkAndDeleteAllImports).toHaveBeenCalledTimes(1);
expect(svc.unlinkAndDeleteImport).not.toHaveBeenCalled();
});
it("a failed unlink-and-delete keeps the refusal and flags the failure, with no raw text", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
svc.unlinkAndDeleteImport.mockRejectedValue(new Error("FOREIGN KEY constraint failed"));
await render().handleUnlinkAndDelete();
const { state } = render();
expect(state.blocked).toEqual({ scope: { kind: "file", fileId: 8 }, summary: SUMMARY });
expect(state.unlinkFailed).toBe(true);
expect(state.error).toBeNull();
expect(onChanged).not.toHaveBeenCalled();
});
it("a new delete clears an earlier refusal", async () => {
svc.deleteImportWithTransactions.mockRejectedValueOnce(refusal()).mockResolvedValueOnce(3);
await render().handleDelete(8);
await render().handleDelete(9);
expect(render().state.blocked).toBeNull();
});
it("dismissing clears the refusal", async () => {
svc.deleteImportWithTransactions.mockRejectedValue(refusal());
await render().handleDelete(8);
render().dismissBlocked();
expect(render().state.blocked).toBeNull();
});
});

View file

@ -4,26 +4,50 @@ import {
getAllImportedFiles,
deleteImportWithTransactions,
deleteAllImportsWithTransactions,
getLinkedTransfersSummary,
unlinkAndDeleteImport,
unlinkAndDeleteAllImports,
type ImportDeletionScope,
type LinkedTransfersSummary,
} from "../services/importedFileService";
import { TransactionLinkedToBalanceError } from "../services/transactionService";
/**
* A delete refused because transactions of the import are linked to the
* Balance sheet (#522). Kept structured, never as the error's English text:
* the panel names the accounts, counts the transfers and offers "Unlink and
* delete". `summary` is null when the count itself failed (generic message).
*/
export interface BlockedDeletion {
scope: ImportDeletionScope;
summary: LinkedTransfersSummary | null;
}
interface ImportHistoryState {
files: ImportedFileWithSource[];
isLoading: boolean;
isDeleting: boolean;
error: string | null;
blocked: BlockedDeletion | null;
/** The unlink-and-delete itself failed: a translated message, nothing moved. */
unlinkFailed: boolean;
}
type ImportHistoryAction =
| { type: "SET_LOADING"; payload: boolean }
| { type: "SET_DELETING"; payload: boolean }
| { type: "SET_ERROR"; payload: string | null }
| { type: "SET_FILES"; payload: ImportedFileWithSource[] };
| { type: "SET_FILES"; payload: ImportedFileWithSource[] }
| { type: "SET_BLOCKED"; payload: BlockedDeletion | null }
| { type: "SET_UNLINK_FAILED"; payload: boolean };
const initialState: ImportHistoryState = {
files: [],
isLoading: false,
isDeleting: false,
error: null,
blocked: null,
unlinkFailed: false,
};
function reducer(
@ -39,6 +63,10 @@ function reducer(
return { ...state, error: action.payload };
case "SET_FILES":
return { ...state, files: action.payload };
case "SET_BLOCKED":
return { ...state, blocked: action.payload, unlinkFailed: false };
case "SET_UNLINK_FAILED":
return { ...state, unlinkFailed: action.payload };
default:
return state;
}
@ -66,15 +94,28 @@ export function useImportHistory(onChanged?: () => void) {
}
}, []);
const handleDelete = useCallback(
async (fileId: number) => {
/** Runs one delete; a refusal for linked transfers becomes `blocked`. */
const runDelete = useCallback(
async (scope: ImportDeletionScope, remove: () => Promise<unknown>) => {
dispatch({ type: "SET_DELETING", payload: true });
dispatch({ type: "SET_ERROR", payload: null });
dispatch({ type: "SET_BLOCKED", payload: null });
try {
await deleteImportWithTransactions(fileId);
await remove();
await loadHistory();
onChanged?.();
} catch (err) {
dispatch({ type: "SET_ERROR", payload: String(err) });
if (err instanceof TransactionLinkedToBalanceError) {
let summary: LinkedTransfersSummary | null = null;
try {
summary = await getLinkedTransfersSummary(scope);
} catch {
// The panel falls back to a message without names nor count.
}
dispatch({ type: "SET_BLOCKED", payload: { scope, summary } });
} else {
dispatch({ type: "SET_ERROR", payload: String(err) });
}
} finally {
dispatch({ type: "SET_DELETING", payload: false });
}
@ -82,18 +123,46 @@ export function useImportHistory(onChanged?: () => void) {
[loadHistory, onChanged]
);
const handleDeleteAll = useCallback(async () => {
const handleDelete = useCallback(
(fileId: number) =>
runDelete({ kind: "file", fileId }, () => deleteImportWithTransactions(fileId)),
[runDelete]
);
const handleDeleteAll = useCallback(
() => runDelete({ kind: "all" }, () => deleteAllImportsWithTransactions()),
[runDelete]
);
/**
* "Unlink and delete" the refused scope, after the panel's confirmation. On
* failure nothing moved (one SQL transaction): the notice stays, with a
* translated failure line.
*/
const handleUnlinkAndDelete = useCallback(async () => {
const blocked = state.blocked;
if (!blocked) return;
dispatch({ type: "SET_DELETING", payload: true });
dispatch({ type: "SET_UNLINK_FAILED", payload: false });
try {
await deleteAllImportsWithTransactions();
if (blocked.scope.kind === "file") {
await unlinkAndDeleteImport(blocked.scope.fileId);
} else {
await unlinkAndDeleteAllImports();
}
dispatch({ type: "SET_BLOCKED", payload: null });
await loadHistory();
onChanged?.();
} catch (err) {
dispatch({ type: "SET_ERROR", payload: String(err) });
} catch {
dispatch({ type: "SET_UNLINK_FAILED", payload: true });
} finally {
dispatch({ type: "SET_DELETING", payload: false });
}
}, [loadHistory, onChanged]);
}, [state.blocked, loadHistory, onChanged]);
const dismissBlocked = useCallback(() => {
dispatch({ type: "SET_BLOCKED", payload: null });
}, []);
useEffect(() => {
loadHistory();
@ -104,5 +173,7 @@ export function useImportHistory(onChanged?: () => void) {
loadHistory,
handleDelete,
handleDeleteAll,
handleUnlinkAndDelete,
dismissBlocked,
};
}

View file

@ -278,7 +278,27 @@
"filename": "File",
"date": "Date",
"rows": "Rows",
"status": "Status"
"status": "Status",
"linked": {
"messageFile_one": "This import cannot be deleted as is: {{count}} Balance transfer relies on its transactions, in {{accounts}}.",
"messageFile_other": "This import cannot be deleted as is: {{count}} Balance transfers rely on its transactions, in {{accounts}}.",
"messageAll_one": "The imports cannot be deleted as is: {{count}} Balance transfer relies on their transactions, in {{accounts}}.",
"messageAll_other": "The imports cannot be deleted as is: {{count}} Balance transfers rely on their transactions, in {{accounts}}.",
"messageUnknown": "The delete was refused: some transactions are linked to Balance accounts.",
"more_one": "and {{count}} other",
"more_other": "and {{count}} others",
"hintBalance": "Unlink them in the account's \"Link transfers\", or unlink and delete in one go.",
"hintNoBalance": "You can unlink and delete in one go; these transfers will be lost.",
"openAccount": "Link transfers: {{account}}",
"unlinkAndDelete": "Unlink and delete",
"confirmBody_one": "{{count}} Balance transfer will be unlinked for good, even with a key.",
"confirmBody_other": "{{count}} Balance transfers will be unlinked for good, even with a key.",
"confirmBodyUnknown": "The Balance transfers of these transactions will be unlinked for good, even with a key.",
"confirmAccounts": "Accounts affected: {{accounts}}.",
"confirmFile": "Then the import \"{{filename}}\" and its transactions will be deleted.",
"confirmAll": "Then every import and its transactions will be deleted.",
"failed": "The delete failed; nothing was changed."
}
},
"wizard": {
"back": "Back",
@ -1355,7 +1375,7 @@
"Take snapshots on a regular cadence (monthly or quarterly) — return quality depends on regularity",
"The unadjusted return on the right shows \"account value\" vs \"true performance\": the difference comes from contributions, not from performance",
"Vertical chart markers help you read value jumps: a jump followed by a green marker isn't \"performance\", it's a deposit",
"If you try to delete a transaction linked to a balance account, the app asks you to unlink it first — this friction preserves the reproducibility of past returns",
"A transaction linked to a balance account is listed first in \"Link transfers\", checked: uncheck it and save to unlink it. An import that holds one cannot be deleted as is: the import history names the accounts, links to \"Link transfers\" and offers, in every edition, \"Unlink and delete\", which loses those transfers for good — this friction preserves the reproducibility of past returns",
"The \"balance out of date\" warning appears if your latest snapshot is more than 60 days old",
"Unrealized gain ≠ return: the unrealized gain (value − cost basis) measures your gain since purchase, while the Modified Dietz return measures performance accounting for the timing of your contributions — both show on a detailed account. Adjust the cost basis after a buy/sell, otherwise the unrealized gain drifts",
"(Coming in Phase 5) Automatic price fetching for Stocks/Crypto via a private proxy (premium-only) that anonymizes your request — manual entry remains always available",
@ -2365,7 +2385,7 @@
},
"modal": {
"title": "Link transfers to {{account}}",
"subtitle": "Select transactions to attribute to this balance account. The direction is suggested based on the amount sign.",
"subtitle": "Check the transactions to attribute to this balance account; transactions already linked are listed first, checked, and unchecking them unlinks them. The direction is suggested from the sign of the amount.",
"from": "From",
"to": "To",
"category": "Category",
@ -2377,9 +2397,12 @@
"direction": "Direction",
"toggleDirection": "Click to flip direction",
"summary": "{{selected}} selected of {{total}} shown",
"linkSelection": "Link {{count}} transaction(s)",
"linking": "Linking…",
"partialFailure": "{{linked}}/{{total}} linked successfully"
"linking": "Saving…",
"partialFailure": "{{done}}/{{total}} changes saved ({{linked}} linked, {{unlinked}} unlinked)",
"linkedBadge": "Linked",
"save": "Save",
"changes": "{{link}} to link · {{unlink}} to unlink",
"directionFixed": "Direction fixed: uncheck, save, then check again to change it"
},
"errors": {
"transfer_direction_invalid": "Invalid transfer direction (expected in/out).",

View file

@ -278,7 +278,27 @@
"filename": "Fichier",
"date": "Date",
"rows": "Lignes",
"status": "Statut"
"status": "Statut",
"linked": {
"messageFile_one": "Cet import ne peut pas être supprimé tel quel : {{count}} transfert du Bilan s'appuie sur ses transactions, dans {{accounts}}.",
"messageFile_other": "Cet import ne peut pas être supprimé tel quel : {{count}} transferts du Bilan s'appuient sur ses transactions, dans {{accounts}}.",
"messageAll_one": "Les imports ne peuvent pas être supprimés tels quels : {{count}} transfert du Bilan s'appuie sur leurs transactions, dans {{accounts}}.",
"messageAll_other": "Les imports ne peuvent pas être supprimés tels quels : {{count}} transferts du Bilan s'appuient sur leurs transactions, dans {{accounts}}.",
"messageUnknown": "La suppression est refusée : des transactions sont liées à des comptes du Bilan.",
"more_one": "et {{count}} autre",
"more_other": "et {{count}} autres",
"hintBalance": "Déliez-les dans « Lier transferts » du compte, ou déliez-les et supprimez en une fois.",
"hintNoBalance": "Vous pouvez les délier et supprimer en une fois ; ces transferts seront perdus.",
"openAccount": "Lier transferts : {{account}}",
"unlinkAndDelete": "Délier et supprimer",
"confirmBody_one": "{{count}} transfert du Bilan sera délié sans retour, même avec une clé.",
"confirmBody_other": "{{count}} transferts du Bilan seront déliés sans retour, même avec une clé.",
"confirmBodyUnknown": "Les transferts du Bilan de ces transactions seront déliés sans retour, même avec une clé.",
"confirmAccounts": "Comptes touchés : {{accounts}}.",
"confirmFile": "Puis l'import « {{filename}} » et ses transactions seront supprimés.",
"confirmAll": "Puis tous les imports et leurs transactions seront supprimés.",
"failed": "La suppression a échoué ; rien n'a été modifié."
}
},
"wizard": {
"back": "Retour",
@ -1355,7 +1375,7 @@
"Saisissez vos snapshots à un rythme régulier (mensuel ou trimestriel) — la qualité des rendements dépend de la régularité",
"Le rendement non-ajusté à droite vous permet de voir « valeur du compte » vs « vraie performance » : la différence vient des apports, pas de la performance",
"Les marqueurs verticaux du graphique aident à lire les sauts de valeur : un saut suivi d'un marqueur vert n'est pas une « performance », c'est un dépôt",
"Si vous tentez de supprimer une transaction liée à un compte de bilan, l'app vous demande de la délier d'abord — cette friction préserve la reproductibilité de vos rendements passés",
"Une transaction liée à un compte de bilan s'affiche cochée en tête de « Lier transferts » : décochez-la puis enregistrez pour la délier. Un import qui en contient une ne se supprime pas tel quel : l'historique d'import nomme les comptes, offre le lien vers « Lier transferts » et, dans toute édition, « Délier et supprimer », qui perd ces transferts sans retour — cette friction préserve la reproductibilité de vos rendements passés",
"L'avertissement « bilan pas à jour » apparaît si votre dernier snapshot remonte à plus de 60 jours",
"Gain latent ≠ rendement : le gain latent (valeur − coût d'acquisition) mesure votre plus-value depuis l'achat, le rendement Modified Dietz mesure la performance en tenant compte du timing de vos apports — les deux s'affichent sur un compte détaillé. Ajustez le coût d'acquisition après un achat/vente, sinon le gain latent dérive",
"(À venir Phase 5) Récupération automatique des prix pour Actions/Crypto via un proxy privé (premium-only) qui anonymise votre requête — la saisie manuelle reste toujours disponible",
@ -2365,7 +2385,7 @@
},
"modal": {
"title": "Lier des transferts à {{account}}",
"subtitle": "Sélectionnez les transactions à attribuer à ce compte de bilan. La direction est proposée d'après le signe du montant.",
"subtitle": "Cochez les transactions à attribuer à ce compte de bilan ; les transactions déjà liées s'affichent en tête, cochées, et les décocher les délie. La direction est proposée d'après le signe du montant.",
"from": "Du",
"to": "Au",
"category": "Catégorie",
@ -2377,9 +2397,12 @@
"direction": "Sens",
"toggleDirection": "Cliquer pour inverser le sens",
"summary": "{{selected}} sélectionnée(s) sur {{total}} affichée(s)",
"linkSelection": "Lier {{count}} transaction(s)",
"linking": "Liaison…",
"partialFailure": "{{linked}}/{{total}} liées avec succès"
"linking": "Enregistrement…",
"partialFailure": "{{done}}/{{total}} changements enregistrés ({{linked}} liée(s), {{unlinked}} déliée(s))",
"linkedBadge": "Liée",
"save": "Enregistrer",
"changes": "{{link}} à lier · {{unlink}} à délier",
"directionFixed": "Sens fixé : décochez, enregistrez, puis recochez pour le changer"
},
"errors": {
"transfer_direction_invalid": "Direction de transfert invalide (in/out attendu).",

View file

@ -11,8 +11,9 @@
// (Modified Dietz) are deferred to Issue #142 — the accounts table reserves
// columns with a TODO comment.
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { Wallet, FilePlus } from "lucide-react";
import {
useBalanceOverview,
@ -41,6 +42,7 @@ import HubReportNavCard, {
import { deriveLandingState } from "../components/balance/balanceLanding";
import { getPreference, setPreference } from "../services/userPreferenceService";
import { renderCategoryLabelFromAccount } from "../utils/renderCategoryLabel";
import { LINK_TRANSFERS_PARAM, takeLinkTransfersTarget } from "../utils/balanceLinkParam";
const STARTER_PREF_KEY = "balance_starter_proposed";
@ -69,6 +71,29 @@ export default function BalancePage() {
void getAllCategories().then(setCategories).catch(() => setCategories([]));
}, []);
// #522 — `/balance?linkTransfers=<id>`, from the import history's refused
// delete: open that account's "Lier transferts" once the accounts are
// loaded, then drop the parameter (replace), so going back never reopens
// it. An unknown or archived account drops it without opening anything.
const [searchParams, setSearchParams] = useSearchParams();
const linkParam = searchParams.get(LINK_TRANSFERS_PARAM);
// The accounts list starts empty: read the parameter only once a load ran.
const sawLoadRef = useRef(false);
if (state.isLoading) sawLoadRef.current = true;
useEffect(() => {
if (linkParam === null || state.isLoading || !sawLoadRef.current) return;
const target = takeLinkTransfersTarget(linkParam, state.accountsLatest);
if (target) setLinkTarget(target);
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.delete(LINK_TRANSFERS_PARAM);
return next;
},
{ replace: true }
);
}, [linkParam, state.isLoading, state.accountsLatest, setSearchParams]);
// Issue #179 — one-shot starter-accounts modal for existing profiles. The
// pref `balance_starter_proposed` is written once (confirmed or dismissed),
// so the modal never re-appears. New profiles get both the 4 starters AND
@ -417,7 +442,8 @@ export default function BalancePage() {
accountName={linkTarget.account_name}
categories={categories}
onClose={() => setLinkTarget(null)}
onLinked={() => {
onChanged={() => {
// Linked or unlinked: the chart markers and returns move (#522).
void reload();
}}
/>

View file

@ -1,5 +1,7 @@
import { getDb } from "./db";
import type Database from "@tauri-apps/plugin-sql";
import { getDb, withTransaction } from "./db";
import { notifyDataChanged } from "./dataEvents";
import { logInfo } from "./logService";
import { isLinkedTransactionFkError } from "./balance.service";
import { TransactionLinkedToBalanceError } from "./transactionService";
import type { ImportedFile, ImportedFileWithSource } from "../shared/types";
@ -188,3 +190,175 @@ export async function deleteAllImportsWithTransactions(): Promise<number> {
notifyDataChanged();
return result.rowsAffected;
}
// ---------------------------------------------------------------------------
// Imports that hold transactions linked to the Balance sheet (#522).
//
// Both delete paths above refuse when a transaction of the import is linked to
// a balance account (`ON DELETE RESTRICT`, ADR 0010). The history panel then
// names the accounts and counts the transfers (`getLinkedTransfersSummary`),
// and offers, in every edition, to unlink them and delete in one go
// (`unlinkAndDeleteImport`, `unlinkAndDeleteAllImports`).
// ---------------------------------------------------------------------------
/**
* The transactions one import's delete removes: its own rows, and the split
* children that the parent's `ON DELETE CASCADE` takes with them even when
* they do not carry the import's `file_id` (an older or restored profile).
*/
const FILE_TRANSACTIONS = `SELECT id FROM transactions
WHERE file_id = $1
OR parent_transaction_id IN (SELECT id FROM transactions WHERE file_id = $1)`;
/** What a delete of the import history targets: one import, or all of them. */
export type ImportDeletionScope = { kind: "file"; fileId: number } | { kind: "all" };
/** A balance account that holds transfers of the targeted transactions. */
export interface LinkedTransferAccount {
account_id: number;
account_name: string;
/** False for an archived account: the Balance page no longer lists it. */
is_active: boolean;
transfer_count: number;
}
/** The Balance sheet transfers a delete would lose, counted in full. */
export interface LinkedTransfersSummary {
transferCount: number;
/** Sorted by name. */
accounts: LinkedTransferAccount[];
}
/**
* Counts the transfers of the targeted transactions, per balance account. A
* `COUNT(*)`, not the pre-flight list of `deleteAllImportsWithTransactions`
* (`LIMIT 50`): the confirmation states the real number.
*/
export async function getLinkedTransfersSummary(
scope: ImportDeletionScope
): Promise<LinkedTransfersSummary> {
const db = await getDb();
const where = scope.kind === "file" ? `WHERE bat.transaction_id IN (${FILE_TRANSACTIONS})` : "";
const params = scope.kind === "file" ? [scope.fileId] : [];
const rows = await db.select<
Array<{ account_id: number; account_name: string; is_active: number; transfer_count: number }>
>(
`SELECT a.id AS account_id,
a.name AS account_name,
(a.is_active = 1 AND a.archived_at IS NULL) AS is_active,
COUNT(*) AS transfer_count
FROM balance_account_transfers bat
JOIN transactions t ON t.id = bat.transaction_id
JOIN balance_accounts a ON a.id = bat.account_id
${where}
GROUP BY a.id, a.name, a.is_active, a.archived_at
ORDER BY a.name COLLATE NOCASE, a.id`,
params
);
const accounts = rows.map((r) => ({
account_id: r.account_id,
account_name: r.account_name,
is_active: Number(r.is_active) === 1,
transfer_count: Number(r.transfer_count),
}));
return {
transferCount: accounts.reduce((sum, a) => sum + a.transfer_count, 0),
accounts,
};
}
/** What an unlink-and-delete did, counted inside its transaction. */
export interface UnlinkAndDeleteOutcome {
/** Balance sheet transfers removed: links, one per (transaction, account) pair, as counted by `transferCount`. */
unlinked: number;
/** Transactions removed. */
deleted: number;
}
/**
* Runs `body` between BEGIN and COMMIT on the transaction handle, ROLLBACK on
* any failure (the original error is rethrown). `withTransaction` holds the
* single DB lock for the whole section (`db.ts`); `body` must only use the
* handle it receives.
*/
async function inTransaction<T>(body: (db: Database) => Promise<T>): Promise<T> {
return withTransaction(async (db) => {
await db.execute("BEGIN");
let open = true;
try {
const value = await body(db);
await db.execute("COMMIT");
open = false;
return value;
} catch (e) {
if (open) {
try {
await db.execute("ROLLBACK");
} catch {
// Keep the original error: it is the one that explains the failure.
}
}
throw e;
}
});
}
/** Journal line of an unlink-and-delete: numbers only (REVIEW.md § Vie privée). */
function logUnlinkAndDelete(scope: ImportDeletionScope["kind"], outcome: UnlinkAndDeleteOutcome) {
logInfo(
`Import history: ${scope === "file" ? "one import" : "all imports"} deleted, ${outcome.unlinked} Balance transfer(s) unlinked, ${outcome.deleted} transaction(s) deleted`
);
}
/**
* Unlinks the Balance sheet transfers of one import's transactions, then
* deletes those transactions, the import and its source when no other import
* uses it: one SQL transaction, so a failing step leaves everything in place.
* The transfers are lost for good (#522, decision of 2026-11-07).
*/
export async function unlinkAndDeleteImport(fileId: number): Promise<UnlinkAndDeleteOutcome> {
const outcome = await inTransaction(async (db) => {
const files = await db.select<Array<{ source_id: number }>>(
"SELECT source_id FROM imported_files WHERE id = $1",
[fileId]
);
const sourceId = files.length > 0 ? files[0].source_id : null;
const unlinked = await db.execute(
`DELETE FROM balance_account_transfers WHERE transaction_id IN (${FILE_TRANSACTIONS})`,
[fileId]
);
const deleted = await db.execute("DELETE FROM transactions WHERE file_id = $1", [fileId]);
await db.execute("DELETE FROM imported_files WHERE id = $1", [fileId]);
if (sourceId !== null) {
const remaining = await db.select<Array<{ cnt: number }>>(
"SELECT COUNT(*) AS cnt FROM imported_files WHERE source_id = $1",
[sourceId]
);
if (Number(remaining[0]?.cnt) === 0) {
await db.execute("DELETE FROM import_sources WHERE id = $1", [sourceId]);
}
}
return { unlinked: unlinked.rowsAffected, deleted: deleted.rowsAffected };
});
logUnlinkAndDelete("file", outcome);
// Announced once, after the COMMIT and out of the DB lock (ADR 0022).
notifyDataChanged();
return outcome;
}
/**
* Unlinks every Balance sheet transfer, then deletes every transaction, import
* and source: the "delete all" of the history, in one SQL transaction.
*/
export async function unlinkAndDeleteAllImports(): Promise<UnlinkAndDeleteOutcome> {
const outcome = await inTransaction(async (db) => {
const unlinked = await db.execute("DELETE FROM balance_account_transfers");
const deleted = await db.execute("DELETE FROM transactions");
await db.execute("DELETE FROM imported_files");
await db.execute("DELETE FROM import_sources");
return { unlinked: unlinked.rowsAffected, deleted: deleted.rowsAffected };
});
logUnlinkAndDelete("all", outcome);
notifyDataChanged();
return outcome;
}

View file

@ -0,0 +1,28 @@
import { describe, it, expect } from "vitest";
import { linkTransfersHref, takeLinkTransfersTarget } from "./balanceLinkParam";
const ACCOUNTS = [
{ account_id: 2, account_name: "CELI" },
{ account_id: 13, account_name: "REER" },
];
describe("balanceLinkParam (#522)", () => {
it("builds the Balance URL that opens an account's window", () => {
expect(linkTransfersHref(13)).toBe("/balance?linkTransfers=13");
});
it("finds the loaded account the value names", () => {
expect(takeLinkTransfersTarget("13", ACCOUNTS)).toEqual(ACCOUNTS[1]);
});
it("opens nothing for an account the page does not list", () => {
expect(takeLinkTransfersTarget("7", ACCOUNTS)).toBeNull();
expect(takeLinkTransfersTarget("2", [])).toBeNull();
});
it("opens nothing for a value that is not a positive integer", () => {
for (const v of ["", "0", "-2", "2.0", "2abc", " 2", "1e1"]) {
expect(takeLinkTransfersTarget(v, ACCOUNTS)).toBeNull();
}
});
});

View file

@ -0,0 +1,26 @@
/**
* `/balance?linkTransfers=<id>` (#522): the import history's refused delete
* links to the "Lier transferts" window of a balance account. The Balance
* page reads the parameter once its accounts are loaded, opens the window of
* the matching active account, and drops the parameter.
*/
export const LINK_TRANSFERS_PARAM = "linkTransfers";
/** The URL of the Balance page that opens `accountId`'s "Lier transferts". */
export function linkTransfersHref(accountId: number): string {
return `/balance?${LINK_TRANSFERS_PARAM}=${accountId}`;
}
/**
* The account a parameter value names among the loaded (active) accounts, or
* null: a value that is not a positive integer, or an account the page does
* not list (archived, deleted), opens nothing.
*/
export function takeLinkTransfersTarget<T extends { account_id: number }>(
value: string,
accounts: readonly T[]
): T | null {
if (!/^[1-9][0-9]*$/.test(value)) return null;
const id = Number(value);
return accounts.find((a) => a.account_id === id) ?? null;
}