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>
537 lines
20 KiB
TypeScript
537 lines
20 KiB
TypeScript
// LinkTransfersModal — multi-select transactions and link them to a balance
|
|
// account in one shot. Issue #142 / Bilan #4.
|
|
//
|
|
// Filters available:
|
|
// - Period (from / to ISO dates) — default: last 90 days.
|
|
// - Category combobox, "any category" first (#429).
|
|
// - Free-text search on description.
|
|
//
|
|
// Each row shows: date, description, amount, suggested direction
|
|
// (auto-proposed via `suggestTransferDirection` from the signed amount,
|
|
// can be flipped per row), and a checkbox.
|
|
//
|
|
// 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";
|
|
import { useTranslation } from "react-i18next";
|
|
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,
|
|
BalanceTransferDirection,
|
|
} from "../../shared/types";
|
|
import CategoryCombobox from "../shared/CategoryCombobox";
|
|
|
|
const DEFAULT_PAGE_SIZE = 100;
|
|
|
|
function isoDaysAgo(days: number): string {
|
|
const d = new Date();
|
|
d.setDate(d.getDate() - days);
|
|
return localISO(d);
|
|
}
|
|
|
|
function localISO(d: Date): string {
|
|
const yy = d.getFullYear();
|
|
const mm = String(d.getMonth() + 1).padStart(2, "0");
|
|
const dd = String(d.getDate()).padStart(2, "0");
|
|
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;
|
|
accountName: string;
|
|
/** Categories offered by the filter combobox. */
|
|
categories: Category[];
|
|
/** Optional pre-fill date bounds (defaults to last 90 days). */
|
|
initialFrom?: string;
|
|
initialTo?: string;
|
|
onClose: () => void;
|
|
/** Fired after at least one transfer was linked or unlinked (parent reloads). */
|
|
onChanged?: (counts: { linked: number; unlinked: number }) => void;
|
|
}
|
|
|
|
export default function LinkTransfersModal({
|
|
accountId,
|
|
accountName,
|
|
categories,
|
|
initialFrom,
|
|
initialTo,
|
|
onClose,
|
|
onChanged,
|
|
}: LinkTransfersModalProps) {
|
|
const { t, i18n } = useTranslation();
|
|
|
|
const [from, setFrom] = useState(initialFrom ?? isoDaysAgo(90));
|
|
const [to, setTo] = useState(initialTo ?? localISO(new Date()));
|
|
const [categoryId, setCategoryId] = useState<number | null>(null);
|
|
const [search, setSearch] = useState("");
|
|
|
|
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>
|
|
>(new Map());
|
|
const [submitting, setSubmitting] = useState(false);
|
|
const [submitError, setSubmitError] = useState<string | null>(null);
|
|
|
|
const fmt = useMemo(
|
|
() =>
|
|
new Intl.NumberFormat(i18n.language === "fr" ? "fr-CA" : "en-CA", {
|
|
style: "currency",
|
|
currency: "CAD",
|
|
maximumFractionDigits: 2,
|
|
}),
|
|
[i18n.language]
|
|
);
|
|
|
|
// "Any category" first: the filter's empty value (null), as on the
|
|
// Transactions page's filter bar.
|
|
const categoryExtras = useMemo(
|
|
() => [{ value: "", label: t("balance.transfers.modal.anyCategory") }],
|
|
[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(() => {
|
|
let cancelled = false;
|
|
async function run() {
|
|
setIsLoading(true);
|
|
setError(null);
|
|
try {
|
|
const result = await getTransactionPage(
|
|
{
|
|
search: search.trim(),
|
|
categoryId,
|
|
sourceId: null,
|
|
dateFrom: from || null,
|
|
dateTo: to || null,
|
|
uncategorizedOnly: false,
|
|
},
|
|
{ column: "date", direction: "desc" },
|
|
1,
|
|
DEFAULT_PAGE_SIZE
|
|
);
|
|
if (!cancelled) {
|
|
setRows(result.rows);
|
|
}
|
|
} catch (e) {
|
|
if (!cancelled) {
|
|
setError(e instanceof Error ? e.message : String(e));
|
|
}
|
|
} finally {
|
|
if (!cancelled) {
|
|
setIsLoading(false);
|
|
}
|
|
}
|
|
}
|
|
void run();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [from, to, categoryId, search]);
|
|
|
|
function toggleRow(row: ModalRow) {
|
|
setSelection((prev) => {
|
|
const next = new Map(prev);
|
|
if (next.has(row.id)) {
|
|
next.delete(row.id);
|
|
} else {
|
|
// 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);
|
|
if (current === undefined) return prev;
|
|
next.set(rowId, current === "in" ? "out" : "in");
|
|
return next;
|
|
});
|
|
}
|
|
|
|
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 (linked === null || changeCount === 0) return;
|
|
setSubmitting(true);
|
|
setSubmitError(null);
|
|
let linkedCount = 0;
|
|
let unlinkedCount = 0;
|
|
const failures: string[] = [];
|
|
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);
|
|
linkedCount += 1;
|
|
} catch (e) {
|
|
failures.push(describeFailure(transactionId, e));
|
|
}
|
|
}
|
|
setSubmitting(false);
|
|
if (failures.length > 0) {
|
|
setSubmitError(
|
|
`${t("balance.transfers.modal.partialFailure", {
|
|
done: linkedCount + unlinkedCount,
|
|
total: changeCount,
|
|
linked: linkedCount,
|
|
unlinked: unlinkedCount,
|
|
})} — ${failures.join("; ")}`
|
|
);
|
|
}
|
|
if (linkedCount + unlinkedCount > 0) {
|
|
onChanged?.({ linked: linkedCount, unlinked: unlinkedCount });
|
|
}
|
|
if (failures.length === 0) {
|
|
onClose();
|
|
}
|
|
}
|
|
|
|
// 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(
|
|
<div
|
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
|
|
onClick={onClose}
|
|
>
|
|
<div
|
|
className="bg-[var(--card)] border border-[var(--border)] rounded-xl shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col"
|
|
onClick={(e) => e.stopPropagation()}
|
|
>
|
|
<div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
|
|
<div>
|
|
<h2 className="text-lg font-semibold">
|
|
{t("balance.transfers.modal.title", { account: accountName })}
|
|
</h2>
|
|
<p className="text-xs text-[var(--muted-foreground)] mt-0.5">
|
|
{t("balance.transfers.modal.subtitle")}
|
|
</p>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
className="p-1 rounded hover:bg-[var(--muted)]/40"
|
|
aria-label={t("common.close")}
|
|
>
|
|
<X size={18} />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="px-5 py-3 border-b border-[var(--border)] grid grid-cols-1 md:grid-cols-4 gap-3">
|
|
<label className="text-xs">
|
|
<span className="block text-[var(--muted-foreground)] mb-1">
|
|
{t("balance.transfers.modal.from")}
|
|
</span>
|
|
<input
|
|
type="date"
|
|
value={from}
|
|
onChange={(e) => {
|
|
setFrom(e.target.value);
|
|
// Close native date popup on WebKitGTK (#177)
|
|
e.currentTarget.blur();
|
|
}}
|
|
className="w-full px-2 py-1.5 bg-[var(--background)] border border-[var(--border)] rounded text-sm"
|
|
/>
|
|
</label>
|
|
<label className="text-xs">
|
|
<span className="block text-[var(--muted-foreground)] mb-1">
|
|
{t("balance.transfers.modal.to")}
|
|
</span>
|
|
<input
|
|
type="date"
|
|
value={to}
|
|
onChange={(e) => {
|
|
setTo(e.target.value);
|
|
// Close native date popup on WebKitGTK (#177)
|
|
e.currentTarget.blur();
|
|
}}
|
|
className="w-full px-2 py-1.5 bg-[var(--background)] border border-[var(--border)] rounded text-sm"
|
|
/>
|
|
</label>
|
|
<label className="text-xs">
|
|
<span className="block text-[var(--muted-foreground)] mb-1">
|
|
{t("balance.transfers.modal.category")}
|
|
</span>
|
|
<CategoryCombobox
|
|
categories={categories}
|
|
value={categoryId}
|
|
onChange={(id) => setCategoryId(id)}
|
|
compact
|
|
ariaLabel={t("balance.transfers.modal.category")}
|
|
extraOptions={categoryExtras}
|
|
activeExtra={categoryId === null ? "" : null}
|
|
onExtraSelect={() => setCategoryId(null)}
|
|
/>
|
|
</label>
|
|
<label className="text-xs">
|
|
<span className="block text-[var(--muted-foreground)] mb-1">
|
|
{t("balance.transfers.modal.search")}
|
|
</span>
|
|
<input
|
|
type="text"
|
|
value={search}
|
|
onChange={(e) => setSearch(e.target.value)}
|
|
placeholder={t("balance.transfers.modal.searchPlaceholder")}
|
|
className="w-full px-2 py-1.5 bg-[var(--background)] border border-[var(--border)] rounded text-sm"
|
|
/>
|
|
</label>
|
|
</div>
|
|
|
|
<div className="flex-1 overflow-auto">
|
|
{(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 || linkedError ? (
|
|
<div className="p-8 text-center text-[var(--negative)] flex items-center justify-center gap-2">
|
|
<AlertCircle size={16} />
|
|
{error ?? linkedError}
|
|
</div>
|
|
) : displayRows.length === 0 ? (
|
|
<div className="p-8 text-center text-[var(--muted-foreground)] italic">
|
|
{t("balance.transfers.modal.noTransactions")}
|
|
</div>
|
|
) : (
|
|
<table className="w-full text-sm">
|
|
<thead className="bg-[var(--muted)]/30 sticky top-0">
|
|
<tr>
|
|
<th className="w-10 px-3 py-2"></th>
|
|
<th className="text-left px-3 py-2 font-medium">
|
|
{t("transactions.date")}
|
|
</th>
|
|
<th className="text-left px-3 py-2 font-medium">
|
|
{t("transactions.description")}
|
|
</th>
|
|
<th className="text-right px-3 py-2 font-medium">
|
|
{t("transactions.amount")}
|
|
</th>
|
|
<th className="text-center px-3 py-2 font-medium">
|
|
{t("balance.transfers.modal.direction")}
|
|
</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{displayRows.map((row) => {
|
|
const isSelected = selection.has(row.id);
|
|
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}
|
|
className="border-t border-[var(--border)] hover:bg-[var(--muted)]/10"
|
|
>
|
|
<td className="px-3 py-2 text-center">
|
|
<input
|
|
type="checkbox"
|
|
checked={isSelected}
|
|
onChange={() => toggleRow(row)}
|
|
aria-label={`select-${row.id}`}
|
|
/>
|
|
</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
|
|
className={`px-3 py-2 text-right font-mono ${row.amount >= 0 ? "text-[var(--positive)]" : "text-[var(--negative)]"}`}
|
|
>
|
|
{fmt.format(row.amount)}
|
|
</td>
|
|
<td className="px-3 py-2 text-center">
|
|
{isSelected && !isLinked ? (
|
|
<button
|
|
type="button"
|
|
onClick={() => flipDirection(row.id)}
|
|
className={`px-2 py-0.5 text-xs rounded font-medium ${
|
|
direction === "in"
|
|
? "bg-[var(--positive)]/15 text-[var(--positive)]"
|
|
: "bg-[var(--negative)]/15 text-[var(--negative)]"
|
|
}`}
|
|
title={t("balance.transfers.modal.toggleDirection")}
|
|
>
|
|
{t(`balance.transfers.direction.${direction}`)}
|
|
</button>
|
|
) : (
|
|
<span
|
|
className="text-xs text-[var(--muted-foreground)]"
|
|
title={isLinked ? t("balance.transfers.modal.directionFixed") : undefined}
|
|
>
|
|
{t(`balance.transfers.direction.${direction}`)}
|
|
</span>
|
|
)}
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
)}
|
|
</div>
|
|
|
|
{submitError && (
|
|
<div className="px-5 py-2 border-t border-[var(--border)] text-xs text-[var(--negative)]">
|
|
{submitError}
|
|
</div>
|
|
)}
|
|
|
|
<div className="px-5 py-3 border-t border-[var(--border)] flex items-center justify-between">
|
|
<div className="text-xs text-[var(--muted-foreground)]">
|
|
{t("balance.transfers.modal.summary", {
|
|
selected: selectedCount,
|
|
total: allShown,
|
|
})}
|
|
{changeCount > 0 && (
|
|
<>
|
|
{" — "}
|
|
{t("balance.transfers.modal.changes", {
|
|
link: toLink.length,
|
|
unlink: toUnlink.length,
|
|
})}
|
|
</>
|
|
)}
|
|
</div>
|
|
<div className="flex gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={onClose}
|
|
className="px-3 py-1.5 text-sm rounded border border-[var(--border)] hover:bg-[var(--muted)]/30"
|
|
>
|
|
{t("common.cancel")}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleSubmit}
|
|
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 ? (
|
|
<span className="flex items-center gap-1.5">
|
|
<Loader2 className="animate-spin" size={14} />
|
|
{t("balance.transfers.modal.linking")}
|
|
</span>
|
|
) : (
|
|
t("balance.transfers.modal.save")
|
|
)}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>,
|
|
document.body
|
|
);
|
|
}
|