Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,33 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

---

## [1.16.7] — 2026-11-02

### Transactions, Budget, Savings buckets, Debt tracker
- **Linked transactions no longer move to another budget, bucket or debt when one is deleted.** A transaction can be linked to one in its edit drawer ("Link to a budget, bucket or debt").
- **What went wrong:** the link stored the item's position in its list (`txOverrides[id].link = { type, idx }`). Deleting an item moved the ones after it up a place, so their links pointed at the next item, or past the end of the list. With three budgets, deleting the first moved the second's link to the third, and the third's link showed the second (the drawer's first option).
- **Fix:** each budget, bucket and debt now has an `id`. It's given when the item is created and kept when it's edited. Links store it: `{ type, id }`.
- **Deleting a budget, bucket or debt removes the links to it.** Before, they stayed and pointed at whatever moved into its place. The transaction's other edits stay.
- **A link to an item that no longer exists shows as None** in the drawer; saving drops it.
- **The bucket drawer's Linked transactions** finds them by id (`linkedTransactions()`).

### Settings → Data & reset
- **Clear budgets, Clear buckets and Clear debts also remove the transaction links to them** (saved as transaction edits). Other edits on those transactions are kept.

### Technical
- **Ids:** `newPlanId()` and `PLAN_LINK_TYPES` in `core.js`. An id is `bud_`, `bkt_` or `dbt_` plus 10 random base-36 characters. `saveBudget()`, `seedBudgets()` (Use starter budget), `addBucket()`, `saveBucket()` and `saveDebt()` (including a debt started from a card) give one; every edit keeps it.
- **`ui.js`:** `planItem()`, `linkedTransactions()`, `unlinkPlanItems()` and `ensurePlanIds()`. `deleteBudget()`, `deleteBucket()` and `deleteDebt()` remove the links to the deleted item. **`views-main.js`:** `showTxDrawer()` lists items by id and saves `{ type, id }`. **`views-cleanup.js`:** `clearPlan()` removes the links. **`views-db.js`:** the schema note says `{type,id}`.
- **Migration** (`IdMigration.migratePlanLinks()` in `migrate.js`). Data saved before v1.16.7 is rewritten in the same places as the account codes: at boot, when `finlens-state.json` loads, and on JSON import (all through `migrateState()`).
- **Items without an id** get `<prefix>_m<n>`, n being their position. The same old data gets the same ids wherever it's migrated.
- **Each `{ type, idx }` link** becomes `{ type, id }` of the item it pointed at, so no link changes target. A link past the end of its list is dropped.
- **At boot,** `storePlanLinks()` writes State's budgets, buckets, debts and transaction edits back to localStorage and IndexedDB `app_state`, and the normal save rewrites the state file. Running it again changes nothing.
- **The AI summary is unchanged.** `buildFinancialSummary()` reads neither links nor ids. On `samples/`, with and without budgets, buckets, debts and links, its output is byte-identical to v1.16.0's, and so is the AI Eval's sample summary. `docs/EVAL.md` stays valid.

### Docs
- **CLAUDE.md** §4.1 (the `id` fields, TxOverride and its `link`), §8, §9, §20 (clears remove links) and §22 (the migration).

---

## [1.16.6] — 2026-11-02

### Fixed
Expand Down
61 changes: 53 additions & 8 deletions CLAUDE.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> A zero-install, browser-native finance dashboard. Drop in your bank CSVs, get instant clarity on your money.

**Version:** v1.16.6 &nbsp;·&nbsp; **Stack:** Vanilla JS, HTML, CSS &nbsp;·&nbsp; **Install:** None
**Version:** v1.16.7 &nbsp;·&nbsp; **Stack:** Vanilla JS, HTML, CSS &nbsp;·&nbsp; **Install:** None

---

Expand Down Expand Up @@ -261,4 +261,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history.

---

*FinLens v1.16.6 — Built for one person's finances, designed to be useful for anyone's.*
*FinLens v1.16.7 — Built for one person's finances, designed to be useful for anyone's.*
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1164,7 +1164,7 @@
<div class="folder-banner-wrap" id="folderBanner" hidden></div>
<div class="content" id="content"></div>
</main>
<footer class="appfoot">v1.16.6 · FinLens</footer>
<footer class="appfoot">v1.16.7 · FinLens</footer>

<!-- side drawer: transaction detail, bill and plan forms (ui.js openDrawer) -->
<div class="drawer-scrim" id="drawerScrim" onclick="closeDrawer()" hidden></div>
Expand Down
32 changes: 28 additions & 4 deletions js/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,27 @@ const hash = (s) => {
for (let i=0;i<s.length;i++){h=((h<<5)-h)+s.charCodeAt(i);h|=0;}
return 'tx'+Math.abs(h).toString(36);
};
/* ---------- Plan item ids (v1.16.7) ---------- */
// Budgets, buckets and debts each have a stable `id`, and a transaction's link to one
// (State.txOverrides[txId].link) is { type, id }. Up to v1.16.6 the link held the item's
// list position ({ type, idx }), so deleting an item left the links of the items after it
// pointing at the wrong one. migrate.js rewrites data saved that way (CLAUDE.md §22).
// Link type → [State key, id prefix]
const PLAN_LINK_TYPES = { budget: ['budgets', 'bud'], bucket: ['buckets', 'bkt'], debt: ['debts', 'dbt'] };
// A new id for an item of `type`: its prefix and 10 random base-36 characters
// ('bud_k3x9q0m2zp'), never one already in `list` (default: the State list). An id is a
// name, not a position: once given it never changes.
function newPlanId(type, list) {
const [key, prefix] = PLAN_LINK_TYPES[type];
const taken = new Set((list || State[key] || []).map(x => x && x.id));
for (;;) {
let s = '';
try { s = Array.from(crypto.getRandomValues(new Uint8Array(10)), b => (b % 36).toString(36)).join(''); }
catch (e) { while (s.length < 10) s += Math.random().toString(36).slice(2); s = s.slice(0, 10); }
const id = prefix + '_' + s;
if (!taken.has(id)) return id;
}
}
const lsGet = (k, def) => {
try { const v=localStorage.getItem('finlens_'+k); return v?JSON.parse(v):def; }
catch(e){ return def; }
Expand Down Expand Up @@ -155,9 +176,12 @@ async function loadStateFromFile() {
.filter(t => !isNaN(t.date))
.sort((a, b) => b.date - a.date);
}
// A file written before v1.12.0 (or an old backup) uses the old account codes:
// rewrite them (migrate.js) and save the file again once it's loaded.
if (IdMigration.migrateState(loaded).changed.length) _saveStateDebounced(State);
// A file written before v1.12.0 (or an old backup) uses the old account codes, and one
// written before v1.16.7 links transactions to plan items by position: rewrite them
// (migrate.js) and save the file again once it's loaded.
const migrated = IdMigration.migrateState(loaded);
if (migrated.changed.length) _saveStateDebounced(State);
IdMigration.logPlanLinks(migrated.plan, 'finlens-state.json');
console.log('[FinLens] State loaded from finlens-state.json');
return loaded;
} catch(e) {
Expand Down Expand Up @@ -368,7 +392,7 @@ const State = {
debts: lsGet('debts', []),
bills: lsGet('bills', []),
recurringConfirmed: lsGet(storageKey('recurringConfirmed'), {}), // stored as 'recurring'
txOverrides: lsGet('txOverrides', {}), // id -> { description, categories, notes, isBill, isRecurring, isSubscription, type, accountOverride }
txOverrides: lsGet('txOverrides', {}), // id -> { description, categories, notes, isBill, isRecurring, isSubscription, type, accountOverride, link: { type, id } }
manualBalances: lsGet('manualBalances', {}), // id -> amount; id+'_limit' -> limit; id+'_initial' -> initial balance
categoryRules: lsGet(storageKey('categoryRules'), []), // stored as 'catRules'
categories: lsGet('categories', null) || [
Expand Down
120 changes: 115 additions & 5 deletions js/migrate.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
// change too. The stored transaction lacks two of the hash inputs (the bank's time or
// the post date), but the hash is linear enough to swap the account part of an existing
// id without them: see _rekey().
//
// v1.16.7: budgets, buckets and debts get ids, and transaction links point at them by id
// instead of list position (migratePlanLinks(), further down).
const IdMigration = {
// Account kinds and BANK_SCHEMAS ids
KINDS: { ally_checking: 'bank_checking', ally_savings: 'bank_savings', chase: 'credit_card' },
Expand Down Expand Up @@ -204,12 +207,14 @@ const IdMigration = {
// Rewrites a state object in place: State, a parsed finlens-state.json (transactions
// already rebuilt with reconstituteTx()), or a JSON export. Safe to run on data that's
// already new: nothing matches, nothing changes.
// Returns { changed: [keys], idMap: Map(old tx id → new), kept: count of transactions
// whose id couldn't be traced and so kept their old id }.
// Returns { changed: [keys], codes: [keys the account codes changed], idMap: Map(old tx
// id → new), kept: count of transactions whose id couldn't be traced and so kept their
// old id, plan: migratePlanLinks() result }.
// Also gives plan items their ids and rewrites old transaction links (v1.16.7, below).
migrateState(s) {
const changed = [], idMap = new Map();
let kept = 0;
if (!s || typeof s !== 'object') return { changed, idMap, kept };
if (!s || typeof s !== 'object') return { changed, codes: [], idMap, kept, plan: this.migratePlanLinks(null) };

const txs = Array.isArray(s.transactions) ? s.transactions.filter((t) => t && typeof t === 'object') : [];
const oldAccounts = [...new Set([...Object.keys(s.accounts || {}), ...txs.map((t) => t.account)])]
Expand Down Expand Up @@ -243,7 +248,101 @@ const IdMigration = {
if (Array.isArray(s.fileMeta)) {
s.fileMeta = s.fileMeta.map((f) => (f && this.KINDS[f.kind]) ? { ...f, kind: this.kind(f.kind), account: this.accountName(f.account) } : f);
}
return { changed, idMap, kept };

// v1.16.7: plan item ids and transaction links (below)
const codes = changed.slice();
const plan = this.migratePlanLinks(s);
plan.changed.forEach((k) => { if (!changed.includes(k)) changed.push(k); });
return { changed, codes, idMap, kept, plan };
},

/* ---------- v1.16.7: plan item ids and transaction links ---------- */
// Up to v1.16.6 a transaction's link to a budget, bucket or debt (txOverrides[id].link)
// was { type, idx }: the item's position in its list. Deleting an item moved the ones
// after it up a place, so their links pointed at the wrong item. Items now have a stable
// `id` and a link is { type, id } (PLAN_LINK_TYPES and newPlanId() in core.js).
//
// An item without an id gets `<prefix>_m<n>`, n being its position when this runs. The id
// depends only on the position, so the same old data gets the same ids wherever it's
// migrated (browser storage, finlens-state.json, an export), and running it again
// changes nothing. A link { type, idx } becomes { type, id: list[idx].id }: the item it
// pointed at, so no link changes target. A link past the end of its list pointed at
// nothing and is dropped.
PLAN_KEYS: ['budgets', 'buckets', 'debts', 'txOverrides'],

_isOldLink(l) {
return !!(l && typeof l === 'object' && PLAN_LINK_TYPES[l.type] && !(typeof l.id === 'string' && l.id));
},

// Gives each item of `list` without an id (or with one an earlier item already has) its
// `<prefix>_m<n>` id, in place. Returns how many it gave.
_assignPlanIds(type, list) {
const prefix = PLAN_LINK_TYPES[type][1];
const seen = new Set(), need = [];
list.forEach((it, i) => {
if (!it || typeof it !== 'object') return;
if (typeof it.id === 'string' && it.id && !seen.has(it.id)) seen.add(it.id);
else need.push(i);
});
for (const i of need) {
let id = `${prefix}_m${i}`;
for (let k = 2; seen.has(id); k++) id = `${prefix}_m${i}_${k}`;
list[i].id = id;
seen.add(id);
}
return need.length;
},

// Rewrites s.budgets, s.buckets, s.debts and the links in s.txOverrides, in place. A link
// whose list isn't in `s` (an export without it) is left for the boot step to resolve.
// An edit left with nothing in it once its link is dropped is removed.
// Returns { changed: [keys], ids, links, dropped }.
migratePlanLinks(s) {
const out = { changed: [], ids: 0, links: 0, dropped: 0 };
if (!s || typeof s !== 'object') return out;
for (const [type, [key]] of Object.entries(PLAN_LINK_TYPES)) {
if (!Array.isArray(s[key])) continue;
const n = this._assignPlanIds(type, s[key]);
if (n) { out.ids += n; out.changed.push(key); }
}
const ovs = s.txOverrides;
if (!ovs || typeof ovs !== 'object' || Array.isArray(ovs)) return out;
let touched = false;
for (const [txId, ov] of Object.entries(ovs)) {
const l = ov && ov.link;
if (!this._isOldLink(l)) continue;
const list = s[PLAN_LINK_TYPES[l.type][0]];
if (!Array.isArray(list)) continue;
const item = Number.isInteger(l.idx) && l.idx >= 0 ? list[l.idx] : null;
if (item && typeof item === 'object' && item.id) { ov.link = { type: l.type, id: item.id }; out.links++; }
else { delete ov.link; if (!Object.keys(ov).length) delete ovs[txId]; out.dropped++; }
touched = true;
}
if (touched) out.changed.push('txOverrides');
return out;
},

// Boot: browser storage (localStorage + IndexedDB app_state, through lsSet, which also
// schedules the state-file save) gets State's budgets, buckets, debts and txOverrides
// when the migration changed them, or when a copy there still needs it (State came from
// finlens-state.json, which loadStateFromFile() had already migrated). The four are
// written together, so a copy's links always come with the lists they point into.
async storePlanLinks(plan) {
const needs = (copy) => this.migratePlanLinks(JSON.parse(JSON.stringify(copy))).changed.length > 0;
let stale = !!(plan && plan.changed.length);
if (!stale) {
const ls = {};
for (const k of this.PLAN_KEYS) ls[k] = lsGet(k, null);
stale = needs(ls);
}
if (!stale && typeof DB !== 'undefined' && DB._db) {
const idb = {};
for (const k of this.PLAN_KEYS) idb[k] = await DB.getState(k, null);
stale = needs(idb);
}
if (!stale) return false;
for (const k of this.PLAN_KEYS) if (State[k] !== undefined) lsSet(k, State[k]);
return true;
},

/* ---------- browser storage (IndexedDB finlens_db + localStorage) ---------- */
Expand Down Expand Up @@ -346,11 +445,22 @@ const IdMigration = {
const mem = this.migrateState(State);
const store = await this.migrateStores(new Map(mem.idMap));
if (mem.changed.length) _saveStateDebounced(State);
if (mem.changed.length || store.transactions) {
if (mem.codes.length || store.transactions) {
const kept = Math.max(mem.kept, store.kept);
console.log(`[FinLens] Renamed old account codes; ${store.idMap.size} transaction ids updated` +
(kept ? `, ${kept} kept their old id (couldn't be traced)` : ''));
}
// After migrateStores(), so State's txOverrides (account codes already renamed) is
// what browser storage keeps.
await this.storePlanLinks(mem.plan);
this.logPlanLinks(mem.plan, 'browser storage');
},

// One log line when the plan-link step changed something (boot and loadStateFromFile()).
logPlanLinks(p, where) {
if (!p || !p.changed.length) return;
console.log(`[FinLens] Plan links: ${p.ids} budget, bucket or debt ids added, ${p.links} links rewritten, ` +
`${p.dropped} dropped (pointed past the end of the list), in ${where}`);
},

// Edits saved under a transaction's old id (an export from an older version, or edits
Expand Down
Loading