Compare commits

..
2 Commits
Author SHA1 Message Date
MangaValkandClaude Opus 5.5 0d399b77c3 Remove the donation popup and the Support broke links
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:48 +01:00
MangaValkandClaude Opus 5.5 5ef800e618 Bank feeds: a row sent again under a new id updates the saved one
ING through Enable Banking gave every row a new transaction_id after linking
again, so the 14-day re-fetch saved all of it a second time.

- before inserting, a new-looking row is paired with a saved row of the same
  provider, account, day, amount and name whose id this fetch didn't return
- the saved row takes the new id and keeps its category, name and tags
- one saved row per new row, so two identical buys on a day stay two rows;
  visible rows are used before hidden ones

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:01:47 +01:00
6 changed files with 71 additions and 64 deletions

No files matched your search

+1 -4
View File
@@ -1,12 +1,11 @@
import { ChevronRight, Sparkles } from "lucide-react"; import { ChevronRight, Sparkles } from "lucide-react";
import { DonateLink } from "@/components/Donate";
import Link from "next/link"; import Link from "next/link";
const PAGES = [ const PAGES = [
{ href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." }, { href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." },
]; ];
// What isn't in the main menu: Debt, connecting your AI and supporting broke. // What isn't in the main menu: Debt and connecting your AI.
export default function More() { export default function More() {
return ( return (
<div className="max-w-2xl space-y-4"> <div className="max-w-2xl space-y-4">
@@ -23,8 +22,6 @@ export default function More() {
<span className="flex-1 font-medium">Connect your AI</span> <span className="flex-1 font-medium">Connect your AI</span>
<ChevronRight size={18} className="text-muted shrink-0" /> <ChevronRight size={18} className="text-muted shrink-0" />
</Link> </Link>
{/* The sidebar has this link too; on a phone, More is the only place. */}
<DonateLink className="card-link flex items-center gap-3 px-6 py-4 font-medium [&_svg]:text-muted" />
</div> </div>
); );
} }
-55
View File
@@ -1,55 +0,0 @@
"use client";
import { Heart } from "lucide-react";
import { useEffect, useState } from "react";
import { Modal } from "@/components/Modal";
export const DONATE_URL = "https://buy.stripe.com/5kQ6oHgXWc1T33CbNt5Vu05";
const USED = "broke.minutesUsed", ASKED = "broke.donateAsked";
const ASK_AFTER = 120; // minutes with broke open and on screen
const read = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
const write = (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* private window: just don't count */ } };
export function DonateLink({ className = "" }: { className?: string }) {
return (
<a href={DONATE_URL} target="_blank" rel="noopener noreferrer" className={className}>
<Heart size={18} strokeWidth={1.6} className="shrink-0" />
<span className="flex-1 text-left">Support broke</span>
</a>
);
}
// Asks once, after about two hours of use: minutes count only while a broke tab is open and visible, in this browser.
export function DonatePrompt() {
const [open, setOpen] = useState(false);
useEffect(() => {
if (read(ASKED)) return;
const tick = setInterval(() => {
if (document.visibilityState !== "visible") return;
const used = Number(read(USED) ?? 0) + 1;
write(USED, String(used));
if (used < ASK_AFTER || read(ASKED)) return;
write(ASKED, new Date().toISOString());
setOpen(true);
clearInterval(tick);
}, 60_000);
return () => clearInterval(tick);
}, []);
if (!open) return null;
return (
<Modal label="Support broke" onClose={() => setOpen(false)}>
<div className="space-y-4">
<Heart size={22} strokeWidth={1.6} className="text-muted" />
<div className="space-y-1.5">
<h2 className="text-lg font-semibold">Finding broke useful?</h2>
<p className="text-sm text-muted">broke is free and open source. If it&apos;s saved you money, you can chip in to keep it going. This is the only time it asks.</p>
</div>
<div className="flex gap-3">
<a href={DONATE_URL} target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)} className="btn-primary" data-autofocus>Donate</a>
<button className="btn" onClick={() => setOpen(false)}>Not now</button>
</div>
</div>
</Modal>
);
}
-3
View File
@@ -7,7 +7,6 @@ import { usePathname, useRouter } from "next/navigation";
import { Suspense, useEffect, useState } from "react"; import { Suspense, useEffect, useState } from "react";
import { useAssistant } from "@/components/Assistant"; import { useAssistant } from "@/components/Assistant";
import { BookmarkButton, SavedList } from "@/components/Bookmarks"; import { BookmarkButton, SavedList } from "@/components/Bookmarks";
import { DonateLink, DonatePrompt } from "@/components/Donate";
// Spending holds Budgets and Recurring as tabs, Plan holds Optimize, Bonuses and Cards, More holds the rest. Every page keeps its own URL. // Spending holds Budgets and Recurring as tabs, Plan holds Optimize, Bonuses and Cards, More holds the rest. Every page keeps its own URL.
type Icon = ComponentType<{ size?: number; strokeWidth?: number }>; type Icon = ComponentType<{ size?: number; strokeWidth?: number }>;
@@ -61,10 +60,8 @@ export function Nav() {
<MessageCircle size={18} strokeWidth={1.6} /> <MessageCircle size={18} strokeWidth={1.6} />
<span className="flex-1 text-left">Ask broke ai</span> <span className="flex-1 text-left">Ask broke ai</span>
</button> </button>
<DonateLink className="flex items-center gap-3 px-3 py-2 rounded-xl text-[14px] whitespace-nowrap text-ink/70 hover:text-ink hover:bg-canvas/60" />
<Suspense><SavedList /></Suspense> <Suspense><SavedList /></Suspense>
</nav> </nav>
<DonatePrompt />
</> </>
); );
} }
+21 -1
View File
@@ -1,7 +1,7 @@
// Run: node src/lib/providers/feeds.test.ts // Run: node src/lib/providers/feeds.test.ts
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { createVerify, generateKeyPairSync } from "node:crypto"; import { createVerify, generateKeyPairSync } from "node:crypto";
import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, pemFrom, validCpf } from "./feeds.ts"; import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, matchRenamed, pemFrom, validCpf } from "./feeds.ts";
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString(); const pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
@@ -99,6 +99,26 @@ console.log("feeds: ok");
const b = ebTxn({ transaction_id: "x2", entry_reference: "ref-9", booking_date: "2026-11-02", transaction_amount: { amount: "3.50" }, credit_debit_indicator: "DBIT", status: "BOOK" }, "u1")!; const b = ebTxn({ transaction_id: "x2", entry_reference: "ref-9", booking_date: "2026-11-02", transaction_amount: { amount: "3.50" }, credit_debit_indicator: "DBIT", status: "BOOK" }, "u1")!;
assert.equal(a.plaid_transaction_id, b.plaid_transaction_id); assert.equal(a.plaid_transaction_id, b.plaid_transaction_id);
} }
// Linking again gave every row a new transaction_id: each new row takes over its saved twin instead of doubling.
{
const t = (id: string, date: string, amount: number, name: string) => ({ ...ebTxn({ transaction_id: id, booking_date: date, transaction_amount: { amount: String(amount) }, credit_debit_indicator: "DBIT", status: "BOOK", note: name }, "h")!, account_id: "acc" });
const saved = [
{ id: "s1", account_id: "acc", date: "2026-11-17", amount: "3.49", name: "Action" },
{ id: "s2", account_id: "acc", date: "2026-11-17", amount: "3.49", name: "Action" }, // two identical buys
{ id: "s3", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza" },
{ id: "s4", account_id: "other", date: "2026-11-17", amount: 14, name: "Pizza" }, // other account: never matched
];
const fresh = [t("n1", "2026-11-17", 3.49, "Action"), t("n2", "2026-11-17", 3.49, "Action"), t("n3", "2026-11-17", 3.49, "Action"), t("n4", "2026-11-17", 14, "Pizza"), t("n5", "2026-11-18", 14, "Pizza")];
const m = matchRenamed(fresh, saved);
assert.equal(m.size, 3); // two Actions and the pizza; the third Action and the next day's pizza are really new
assert.deepEqual(new Set([m.get(fresh[0].plaid_transaction_id), m.get(fresh[1].plaid_transaction_id)]), new Set(["s1", "s2"]));
assert.equal(m.get(fresh[2].plaid_transaction_id), undefined);
assert.equal(m.get(fresh[3].plaid_transaction_id), "s3");
assert.equal(m.get(fresh[4].plaid_transaction_id), undefined);
// A hidden copy is only used when the visible one is taken.
const h = matchRenamed([fresh[3]], [{ id: "hidden", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza", ignored: true }, { id: "shown", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza", ignored: false }]);
assert.equal(h.get(fresh[3].plaid_transaction_id), "shown");
}
// A key pasted on one line keeps its own label, PKCS#1 included, and still signs. // A key pasted on one line keeps its own label, PKCS#1 included, and still signs.
{ {
const { generateKeyPairSync, createPrivateKey: load } = await import("node:crypto"); const { generateKeyPairSync, createPrivateKey: load } = await import("node:crypto");
+19
View File
@@ -97,6 +97,25 @@ export function ebTxn(t: EbTxn, uid: string): FeedTxn | null {
const id = t.entry_reference || t.transaction_id || `${date}|${n}|${text}`; const id = t.entry_reference || t.transaction_id || `${date}|${n}|${text}`;
return { plaid_transaction_id: `enablebanking:${uid}:${id}`, account_ref: `enablebanking:${uid}`, date: date.slice(0, 10), amount: out ? Math.abs(n) : -Math.abs(n), name: text || other || "Transaction", merchant_name: other, logo_url: null, pending: false, plaid_category: t.bank_transaction_code?.code ?? null }; return { plaid_transaction_id: `enablebanking:${uid}:${id}`, account_ref: `enablebanking:${uid}`, date: date.slice(0, 10), amount: out ? Math.abs(n) : -Math.abs(n), name: text || other || "Transaction", merchant_name: other, logo_url: null, pending: false, plaid_category: t.bank_transaction_code?.code ?? null };
} }
/** A bank can give a row a new id on a later fetch (ING through Enable Banking does after linking again), so a row
* already saved under its old id looks new. Pairs each such "new" row with a saved row of the same account, day, amount
* and name whose id didn't come back in this fetch. One saved row per new row, so two identical coffees stay two rows.
* Returns new id -> saved row's id. Saved rows that aren't hidden are used first. */
export type SavedRow = { id: string; account_id: string; date: string; amount: number | string; name: string | null; ignored?: boolean | null };
export function matchRenamed(fresh: (FeedTxn & { account_id: string })[], unmatchedSaved: SavedRow[]) {
const key = (r: { account_id: string; date: string; amount: number | string; name: string | null }) => `${r.account_id}|${r.date.slice(0, 10)}|${Number(r.amount).toFixed(2)}|${r.name ?? ""}`;
const pool = new Map<string, SavedRow[]>();
for (const s of [...unmatchedSaved].sort((a, b) => Number(!!b.ignored) - Number(!!a.ignored))) {
const k = key(s);
pool.set(k, [...(pool.get(k) ?? []), s]); // hidden first, popped last
}
const out = new Map<string, string>();
for (const t of fresh) {
const s = pool.get(key(t))?.pop();
if (s) out.set(t.plaid_transaction_id, s.id);
}
return out;
}
async function ebFeed(env: Env, token: string, since: string, f?: Fetch, now = Date.now()) { async function ebFeed(env: Env, token: string, since: string, f?: Fetch, now = Date.now()) {
const s = JSON.parse(token) as { accounts: EbAccount[]; institution?: string; valid_until?: string | null }; const s = JSON.parse(token) as { accounts: EbAccount[]; institution?: string; valid_until?: string | null };
if (s.valid_until && Date.parse(s.valid_until) <= now) throw consentExpired(); if (s.valid_until && Date.parse(s.valid_until) <= now) throw consentExpired();
+30 -1
View File
@@ -3,7 +3,7 @@ import type { CountryCode, InvestmentTransaction, RemovedTransaction, Transactio
import { categoryKey, plaid, PLAID_COUNTRIES } from "@/lib/plaid"; import { categoryKey, plaid, PLAID_COUNTRIES } from "@/lib/plaid";
import { akahuTokens } from "@/lib/providers"; import { akahuTokens } from "@/lib/providers";
import { akahuAccounts, akahuTransactions, toAccount, toTxn } from "@/lib/providers/akahu"; import { akahuAccounts, akahuTransactions, toAccount, toTxn } from "@/lib/providers/akahu";
import { feedData, isFeed, type FeedAccount, type FeedId, type FeedTxn } from "@/lib/providers/feeds"; import { feedData, isFeed, matchRenamed, type FeedAccount, type FeedId, type FeedTxn, type SavedRow } from "@/lib/providers/feeds";
import { applyRules, RULE_COLS, type Rule } from "@/lib/rules"; import { applyRules, RULE_COLS, type Rule } from "@/lib/rules";
import { pairTransfers, findOwnTransfers, type OwnRow } from "@/lib/transfers"; import { pairTransfers, findOwnTransfers, type OwnRow } from "@/lib/transfers";
import { createAdminClient } from "@/utils/supabase/admin"; import { createAdminClient } from "@/utils/supabase/admin";
@@ -420,6 +420,32 @@ export async function linkFeed(userId: string, id: FeedId, ref: string, institut
return result; return result;
} }
/** New-looking rows that match a saved row of this provider (same account, day, amount, name) whose id this fetch didn't
* return: move the saved row to the new id. Returns the new ids that now exist. */
async function adoptRenamed(item: Item, unknown: FeedTxn[], fetched: Set<string>, accountId: Map<string, string>) {
if (!unknown.length || !item.provider) return [];
const db = createAdminClient();
const fresh = unknown.map((t) => ({ ...t, account_id: accountId.get(t.account_ref)! }));
const dates = fresh.map((t) => t.date).sort();
const saved: SavedRow[] = [];
for (let from = 0; ; from += 1000) {
const { data, error } = await db.from("transactions").select("id, plaid_transaction_id, account_id, date, amount, name, ignored")
.eq("user_id", item.user_id).in("account_id", [...new Set(fresh.map((t) => t.account_id))])
.gte("date", dates[0]).lte("date", dates[dates.length - 1]).like("plaid_transaction_id", `${item.provider}:%`)
.order("id").range(from, from + 999);
if (error) throw error;
for (const r of data ?? []) if (!fetched.has(r.plaid_transaction_id)) saved.push(r);
if ((data ?? []).length < 1000) break;
}
const moves = [...matchRenamed(fresh, saved)];
for (let i = 0; i < moves.length; i += 50)
await Promise.all(moves.slice(i, i + 50).map(async ([to, id]) => {
const { error } = await db.from("transactions").update({ plaid_transaction_id: to }).eq("id", id);
if (error) throw error;
}));
return moves.map(([to]) => to);
}
// Writes any provider's accounts and rows the same way: new rows get the user's rules, seen rows keep their edits. // Writes any provider's accounts and rows the same way: new rows get the user's rules, seen rows keep their edits.
async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof toAccount>[], feed: FeedTxn[]) { async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof toAccount>[], feed: FeedTxn[]) {
const db = createAdminClient(); const db = createAdminClient();
@@ -438,6 +464,9 @@ async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof
const { data } = await db.from("transactions").select("plaid_transaction_id").eq("user_id", item.user_id).in("plaid_transaction_id", c); const { data } = await db.from("transactions").select("plaid_transaction_id").eq("user_id", item.user_id).in("plaid_transaction_id", c);
for (const r of data ?? []) known.add(r.plaid_transaction_id); for (const r of data ?? []) known.add(r.plaid_transaction_id);
} }
// Rows the bank sent again under a new id: the saved row takes the new id, so it updates instead of doubling.
const renamed = await adoptRenamed(item, txns.filter((t) => !known.has(t.plaid_transaction_id)), new Set(txns.map((t) => t.plaid_transaction_id)), accountId);
for (const id of renamed) known.add(id);
const fresh = txns.filter((t) => !known.has(t.plaid_transaction_id)); const fresh = txns.filter((t) => !known.has(t.plaid_transaction_id));
const seen = txns.filter((t) => known.has(t.plaid_transaction_id)); const seen = txns.filter((t) => known.has(t.plaid_transaction_id));
const { data: rules } = await db.from("rules").select(RULE_COLS).eq("user_id", item.user_id).order("created_at", { ascending: false }); const { data: rules } = await db.from("rules").select(RULE_COLS).eq("user_id", item.user_id).order("created_at", { ascending: false });