A local-first personal finance app
persist cleanup templates in the DB (#7794)
Matt Fiddamand015858e4a32
diff --git a/packages/loot-core/migrations/1778510362740_add_cleanup_groups_and_def.sql b/packages/loot-core/migrations/1778510362740_add_cleanup_groups_and_def.sqlnew file mode 100644index 0000000000..6d59815d20--- /dev/null+++ b/packages/loot-core/migrations/1778510362740_add_cleanup_groups_and_def.sql@@ -0,0 +1,10 @@+BEGIN TRANSACTION;++ALTER TABLE categories ADD COLUMN cleanup_def TEXT DEFAULT NULL;++CREATE TABLE cleanup_groups+ (id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ tombstone INTEGER DEFAULT 0);++COMMIT;diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.tsindex d8da6c4513..7a10b21ab9 100644--- a/packages/loot-core/src/server/aql/schema/index.ts+++ b/packages/loot-core/src/server/aql/schema/index.ts@@ -85,6 +85,7 @@ export const schema = {hidden: f('boolean'),group: f('id', { ref: 'category_groups' }),goal_def: f('string'),+ cleanup_def: f('string'),template_settings: f('json', { default: { source: 'notes' } }),sort_order: f('float'),tombstone: f('boolean'),@@ -97,6 +98,11 @@ export const schema = {sort_order: f('float'),tombstone: f('boolean'),},+ cleanup_groups: {+ id: f('id'),+ name: f('string'),+ tombstone: f('boolean'),+ },schedules: {id: f('id'),name: f('string'),diff --git a/packages/loot-core/src/server/budget/cleanup-template-notes.test.ts b/packages/loot-core/src/server/budget/cleanup-template-notes.test.tsnew file mode 100644index 0000000000..e4497d0f8a--- /dev/null+++ b/packages/loot-core/src/server/budget/cleanup-template-notes.test.ts@@ -0,0 +1,172 @@+import { vi } from 'vitest';++import * as db from '#server/db';++import { storeNoteCleanups } from './cleanup-template-notes';++vi.mock('#server/db');++type CategoryRow = {+ id: string;+ note: string | null;+};++type GroupRow = {+ id: string;+ name: string;+ tombstone: 0 | 1;+};++function setupDb(initial: { categories: CategoryRow[]; groups?: GroupRow[] }) {+ const groups = new Map<string, GroupRow>(+ (initial.groups ?? []).map(g => [g.id, { ...g }]),+ );+ const categoryDefs = new Map<string, string | null>();++ vi.mocked(db.all).mockImplementation(async (sql: string) => {+ if (sql.includes('FROM categories c')) {+ return initial.categories as never;+ }+ return [] as never;+ });++ vi.mocked(db.first).mockImplementation(async (sql: string, params) => {+ if (sql.includes('FROM cleanup_groups')) {+ const key = (params as string[])[0];+ const match = Array.from(groups.values()).find(+ g => g.name.toLowerCase() === key,+ );+ return (match ?? null) as never;+ }+ return null as never;+ });++ vi.mocked(db.insertWithSchema).mockImplementation(async (table, row) => {+ if (table === 'cleanup_groups') {+ const r = row as GroupRow;+ groups.set(r.id, { ...r, tombstone: 0 });+ }+ return row.id as never;+ });++ vi.mocked(db.update).mockImplementation(async (table, params) => {+ if (table === 'cleanup_groups') {+ const r = params as Partial<GroupRow> & { id: string };+ const existing = groups.get(r.id);+ if (existing) groups.set(r.id, { ...existing, ...r } as GroupRow);+ }+ return undefined as never;+ });++ vi.mocked(db.updateWithSchema).mockImplementation(async (table, fields) => {+ if (table === 'categories') {+ const r = fields as { id: string; cleanup_def: string | null };+ categoryDefs.set(r.id, r.cleanup_def);+ }+ return undefined as never;+ });++ vi.mocked(db.run).mockImplementation(async (sql: string) => {+ // tombstoneOrphanCleanupGroups: scan written cleanup_defs for referenced ids+ if (sql.includes('UPDATE cleanup_groups')) {+ const referenced = new Set<string>();+ for (const def of categoryDefs.values()) {+ if (!def) continue;+ const arr = JSON.parse(def) as Array<{ groupId?: string | null }>;+ for (const row of arr) {+ if (row.groupId) referenced.add(row.groupId);+ }+ }+ for (const [id, g] of groups) {+ if (g.tombstone === 0 && !referenced.has(id)) {+ groups.set(id, { ...g, tombstone: 1 });+ }+ }+ }+ return undefined as never;+ });++ return { groups, categoryDefs };+}++describe('storeNoteCleanups', () => {+ beforeEach(() => vi.clearAllMocks());++ it('persists global source/sink lines as cleanup_def with null groupId', async () => {+ const state = setupDb({+ categories: [+ { id: 'cat-1', note: '#cleanup source' },+ { id: 'cat-2', note: '#cleanup sink 2' },+ ],+ });++ await storeNoteCleanups();++ expect(JSON.parse(state.categoryDefs.get('cat-1')!)).toEqual([+ { role: 'source', groupId: null },+ ]);+ expect(JSON.parse(state.categoryDefs.get('cat-2')!)).toEqual([+ { role: 'sink', groupId: null, weight: 2 },+ ]);+ });++ it('resolves shared group names to a single group id, case-insensitively', async () => {+ const state = setupDb({+ categories: [+ { id: 'cat-1', note: '#cleanup Vacations source' },+ { id: 'cat-2', note: '#cleanup vacations sink' },+ { id: 'cat-3', note: '#cleanup VACATIONS' },+ ],+ });++ await storeNoteCleanups();++ const def1 = JSON.parse(state.categoryDefs.get('cat-1')!);+ const def2 = JSON.parse(state.categoryDefs.get('cat-2')!);+ const def3 = JSON.parse(state.categoryDefs.get('cat-3')!);+ expect(def1[0].groupId).toBe(def2[0].groupId);+ expect(def2[0].groupId).toBe(def3[0].groupId);++ // One group exists.+ const liveGroups = Array.from(state.groups.values()).filter(+ g => g.tombstone === 0,+ );+ expect(liveGroups).toHaveLength(1);+ // Name preserves the casing of whichever line was seen first.+ expect(liveGroups[0].name).toBe('Vacations');+ });++ it('clears cleanup_def for categories whose notes no longer carry cleanup', async () => {+ const state = setupDb({+ categories: [{ id: 'cat-1', note: 'totally unrelated note text' }],+ });++ await storeNoteCleanups();++ expect(state.categoryDefs.get('cat-1')).toBeNull();+ });++ it('tombstones groups that no longer have any live members', async () => {+ const state = setupDb({+ categories: [{ id: 'cat-1', note: 'no cleanup here' }],+ groups: [{ id: 'g-orphan', name: 'OldGroup', tombstone: 0 }],+ });++ await storeNoteCleanups();++ expect(state.groups.get('g-orphan')!.tombstone).toBe(1);+ });++ it('resurrects a tombstoned group when a fresh note references its name', async () => {+ const state = setupDb({+ categories: [{ id: 'cat-1', note: '#cleanup Reborn source' }],+ groups: [{ id: 'g-existing', name: 'Reborn', tombstone: 1 }],+ });++ await storeNoteCleanups();++ expect(state.groups.get('g-existing')!.tombstone).toBe(0);+ const def = JSON.parse(state.categoryDefs.get('cat-1')!);+ expect(def[0].groupId).toBe('g-existing');+ });+});diff --git a/packages/loot-core/src/server/budget/cleanup-template-notes.ts b/packages/loot-core/src/server/budget/cleanup-template-notes.tsnew file mode 100644index 0000000000..f7c5e68c6b--- /dev/null+++ b/packages/loot-core/src/server/budget/cleanup-template-notes.ts@@ -0,0 +1,182 @@+import { v4 as uuidv4 } from 'uuid';++import * as db from '#server/db';+import type { CleanupTemplate } from '#types/models/cleanup-templates';++import { parse } from './cleanup-template.pegjs';++export const CLEANUP_PREFIX = '#cleanup ';++// The grammar emits `type: null` for the bare `<group>` line; we re-key+// that to `'overspend'` so the discriminator is a non-null literal.+type ParsedCleanupRow =+ | { type: 'source'; group: string | null }+ | { type: 'sink'; group: string | null; weight: number }+ | { type: 'overspend'; group: string };++type CategoryWithCleanupNote = {+ id: string;+ note: string | null;+};++export async function storeNoteCleanups(categoryIds?: string[]): Promise<void> {+ const candidates = await getCategoriesWithCleanupNotes(categoryIds);++ const parsedByCategory = new Map<string, ParsedCleanupRow[]>();+ const allGroupNames = new Set<string>();+ for (const { id, note } of candidates) {+ if (!note) continue;+ const rows = parseCleanupNote(note);+ if (rows.length === 0) continue;+ parsedByCategory.set(id, rows);+ for (const r of rows) {+ if (r.group != null) allGroupNames.add(r.group);+ }+ }++ const nameToId = await resolveCleanupGroups(allGroupNames);++ for (const { id } of candidates) {+ const parsed = parsedByCategory.get(id);+ if (!parsed) {+ await db.updateWithSchema('categories', { id, cleanup_def: null });+ continue;+ }+ const cleanupDef: CleanupTemplate[] = parsed.map(row =>+ toCleanupTemplate(row, nameToId),+ );+ await db.updateWithSchema('categories', {+ id,+ cleanup_def: JSON.stringify(cleanupDef),+ });+ }++ await tombstoneOrphanCleanupGroups();+}++function parseCleanupNote(note: string): ParsedCleanupRow[] {+ const rows: ParsedCleanupRow[] = [];+ for (const line of note.split('\n')) {+ const trimmed = line.trim();+ if (!trimmed.toLowerCase().startsWith(CLEANUP_PREFIX)) continue;+ try {+ const raw = parse(trimmed) as {+ type: 'source' | 'sink' | null;+ group: string | null;+ weight?: number;+ };+ const row: ParsedCleanupRow =+ raw.type === 'source'+ ? { type: 'source', group: raw.group }+ : raw.type === 'sink'+ ? { type: 'sink', group: raw.group, weight: raw.weight ?? 1 }+ : { type: 'overspend', group: raw.group ?? '' };+ // The grammar should guarantee a non-null group for `overspend`, but+ // guard so a malformed parse can't write a blank-group row.+ if (row.type === 'overspend' && row.group === '') continue;+ rows.push(row);+ } catch {+ // Match the legacy engine: silently skip unparseable lines.+ }+ }+ return rows;+}++function toCleanupTemplate(+ row: ParsedCleanupRow,+ nameToId: Map<string, string>,+): CleanupTemplate {+ switch (row.type) {+ case 'source':+ return { role: 'source', groupId: resolveGroup(row.group, nameToId) };+ case 'sink':+ return {+ role: 'sink',+ groupId: resolveGroup(row.group, nameToId),+ weight: row.weight,+ };+ case 'overspend': {+ const groupId = nameToId.get(row.group.toLowerCase());+ if (groupId == null) {+ throw new Error(+ `Unresolved cleanup group for overspend row: ${row.group}`,+ );+ }+ return { role: 'overspend', groupId };+ }+ default:+ throw new Error(`Unknown cleanup row type: ${String(row)}`);+ }+}++function resolveGroup(+ name: string | null,+ nameToId: Map<string, string>,+): string | null {+ return name != null ? (nameToId.get(name.toLowerCase()) ?? null) : null;+}++async function resolveCleanupGroups(+ names: ReadonlySet<string>,+): Promise<Map<string, string>> {+ const map = new Map<string, string>();+ for (const name of names) {+ const key = name.toLowerCase();+ const existing = await db.first<{ id: string; tombstone: 0 | 1 }>(+ `SELECT id, tombstone FROM cleanup_groups WHERE lower(name) = ? LIMIT 1`,+ [key],+ );+ if (existing) {+ // Resurrect a tombstoned row so the id stays stable across edits.+ if (existing.tombstone === 1) {+ await db.update('cleanup_groups', { id: existing.id, tombstone: 0 });+ }+ map.set(key, existing.id);+ continue;+ }+ const id = uuidv4();+ await db.insertWithSchema('cleanup_groups', { id, name, tombstone: 0 });+ map.set(key, id);+ }+ return map;+}++async function tombstoneOrphanCleanupGroups(): Promise<void> {+ await db.run(+ `+ UPDATE cleanup_groups+ SET tombstone = 1+ WHERE tombstone = 0+ AND id NOT IN (+ SELECT json_extract(je.value, '$.groupId') AS group_id+ FROM categories c, json_each(c.cleanup_def) je+ WHERE c.tombstone = 0+ AND c.cleanup_def IS NOT NULL+ AND json_extract(je.value, '$.groupId') IS NOT NULL+ )+ `,+ );+}++// Scoped to non-ui-managed categories so a migrated category is not+// overwritten by stale note text.+async function getCategoriesWithCleanupNotes(+ categoryIds?: string[],+): Promise<CategoryWithCleanupNote[]> {+ const baseQuery = `+ SELECT c.id AS id, n.note AS note+ FROM categories c+ LEFT JOIN notes n ON n.id = c.id+ WHERE c.tombstone = 0+ AND COALESCE(JSON_EXTRACT(c.template_settings, '$.source'), 'notes') <> 'ui'+ `;+ if (!categoryIds) {+ return db.all<CategoryWithCleanupNote>(baseQuery);+ }+ if (categoryIds.length === 0) return [];+ const placeholders = categoryIds.map(() => '?').join(',');+ return db.all<CategoryWithCleanupNote>(+ `${baseQuery} AND c.id IN (${placeholders})`,+ categoryIds,+ );+}diff --git a/packages/loot-core/src/server/budget/cleanup-template.pegjs b/packages/loot-core/src/server/budget/cleanup-template.pegjsindex b01e097c71..179eeb09ef 100644--- a/packages/loot-core/src/server/budget/cleanup-template.pegjs+++ b/packages/loot-core/src/server/budget/cleanup-template.pegjs@@ -1,6 +1,9 @@// https://peggyjs.orgexpr+ = '#cleanup' _ inner: inner { return inner }++inner= source{ return { group: null, type: 'source' }}/@@ -8,9 +11,9 @@ expr{ return { type: 'sink', weight: +weight || 1, group: null } }/group: sourcegroup _? source- {return {group: group || null, type: 'source'}}+ {return {group: group || null, type: 'source'}}/- group: sinkgroup? _? sink _? weight: weight?+ group: sinkgroup? _? sink _? weight: weight?{ return { type: 'sink', weight: +weight || 1, group: group || null } }/group: sourcegroupdiff --git a/packages/loot-core/src/server/budget/cleanup-template.ts b/packages/loot-core/src/server/budget/cleanup-template.tsindex 76cddc8e92..130ea0f0c3 100644--- a/packages/loot-core/src/server/budget/cleanup-template.ts+++ b/packages/loot-core/src/server/budget/cleanup-template.ts@@ -1,9 +1,10 @@import * as db from '#server/db';// @ts-strict-ignoreimport * as monthUtils from '#shared/months';+import type { CleanupTemplate } from '#types/models/cleanup-templates';import { getSheetValue, setBudget, setGoal } from './actions';-import { parse } from './cleanup-template.pegjs';+import { storeNoteCleanups } from './cleanup-template-notes';type Notification = {type?: 'message' | 'error' | 'warning' | undefined;@@ -13,15 +14,21 @@ type Notification = {sticky?: boolean | undefined;};-export function cleanupTemplate({ month }: { month: string }) {+export async function cleanupTemplate({ month }: { month: string }) {+ await storeNoteCleanups();return processCleanup(month);}+type GroupSourceRow = { category: string; groupId: string };+type GroupSinkRow = { category: string; groupId: string; weight: number };+type GroupOverspendRow = { category: string; groupId: string };+async function applyGroupCleanups(month: string,- sourceGroups,- sinkGroups,- generalGroups,+ sourceGroups: GroupSourceRow[],+ sinkGroups: GroupSinkRow[],+ overspendGroups: GroupOverspendRow[],+ groupNamesById: Map<string, string>,) {const sheetName = monthUtils.sheetForMonth(month);const warnings = [];@@ -29,16 +36,16 @@ async function applyGroupCleanups(let groupLength = sourceGroups.length;while (groupLength > 0) {//function for each unique group- const groupName = sourceGroups[0].group;- const tempSourceGroups = sourceGroups.filter(c => c.group === groupName);- const sinkGroup = sinkGroups.filter(c => c.group === groupName);- const generalGroup = generalGroups.filter(c => c.group === groupName);+ const groupId = sourceGroups[0].groupId;+ const tempSourceGroups = sourceGroups.filter(c => c.groupId === groupId);+ const sinkGroup = sinkGroups.filter(c => c.groupId === groupId);+ const overspendGroup = overspendGroups.filter(c => c.groupId === groupId);let total_weight = 0;// We track how mouch amount was produced by all group sinks and only// distribute this instead of the "to-budget" amount.let available_amount = 0;- if (sinkGroup.length > 0 || generalGroup.length > 0) {+ if (sinkGroup.length > 0 || overspendGroup.length > 0) {//only return group source funds to To Budget if there are corresponding sinking groups or underfunded included groupsfor (let ii = 0; ii < tempSourceGroups.length; ii++) {const balance = await getSheetValue(@@ -63,17 +70,21 @@ async function applyGroupCleanups(}//fill underfunded categories within the group first- for (let ii = 0; ii < generalGroup.length && available_amount > 0; ii++) {+ for (+ let ii = 0;+ ii < overspendGroup.length && available_amount > 0;+ ii+++ ) {const balance = await getSheetValue(sheetName,- `leftover-${generalGroup[ii].category}`,+ `leftover-${overspendGroup[ii].category}`,);const budgeted = await getSheetValue(sheetName,- `budget-${generalGroup[ii].category}`,+ `budget-${overspendGroup[ii].category}`,);const to_budget = budgeted + Math.abs(balance);- const categoryId = generalGroup[ii].category;+ const categoryId = overspendGroup[ii].category;let carryover = await db.first<Pick<db.DbZeroBudget, 'carryover'>>(`SELECT carryover FROM zero_budgets WHERE month = ? and category = ?`,[db_month, categoryId],@@ -87,11 +98,10 @@ async function applyGroupCleanups(// We have enough to fully cover the overspent.balance < 0 &&Math.abs(balance) <= available_amount &&- !generalGroup[ii].category.is_income &&carryover.carryover === 0) {await setBudget({- category: generalGroup[ii].category,+ category: categoryId,month,amount: to_budget,});@@ -99,12 +109,11 @@ async function applyGroupCleanups(} else if (// We can only cover this category partially.balance < 0 &&- !generalGroup[ii].category.is_income &&carryover.carryover === 0 &&Math.abs(balance) > available_amount) {await setBudget({- category: generalGroup[ii].category,+ category: categoryId,month,amount: budgeted + available_amount,});@@ -126,9 +135,12 @@ async function applyGroupCleanups(});}} else {- warnings.push(groupName + ' has no matching sink categories.');+ const groupName = groupNamesById.get(groupId) ?? groupId;+ warnings.push(+ `Cleanup group "${groupName}" has no matching sink categories.`,+ );}- sourceGroups = sourceGroups.filter(c => c.group !== groupName);+ sourceGroups = sourceGroups.filter(c => c.groupId !== groupId);groupLength = sourceGroups.length;}return warnings;@@ -140,123 +152,93 @@ async function processCleanup(month: string): Promise<Notification> {let total_weight = 0;const errors = [];const warnings = [];- const sinkCategory = [];- const sourceWithRollover = [];+ type SinkCategoryRow = {+ cat: db.DbViewCategory;+ weight: number;+ };+ const sinkCategory: SinkCategoryRow[] = [];const db_month = parseInt(month.replace('-', ''));- const category_templates = await getCategoryTemplates();const categories = await db.all<db.DbViewCategory>('SELECT * FROM v_categories WHERE tombstone = 0',);const sheetName = monthUtils.sheetForMonth(month);- const groupSource = [];- const groupSink = [];- const groupGeneral = [];+ const groupSource: GroupSourceRow[] = [];+ const groupSink: GroupSinkRow[] = [];+ const groupOverspend: GroupOverspendRow[] = [];- //filter out category groups- for (let c = 0; c < categories.length; c++) {- const category = categories[c];- const template = category_templates[category.id];+ for (const category of categories) {+ const def = parseCleanupDef(category.cleanup_def);+ if (!def) continue;- //filter out source and sink groups for processing- if (template) {- if (- template.filter(t => t.type === 'source' && t.group !== null).length > 0- ) {- groupSource.push({- category: category.id,- group: template.filter(- t => t.type === 'source' && t.group !== null,- )[0].group,- });- }- if (- template.filter(t => t.type === 'sink' && t.group !== null).length > 0- ) {- //only supports 1 sink reference per category. Need more?+ for (const row of def) {+ if (row.role === 'source' && row.groupId !== null) {+ groupSource.push({ category: category.id, groupId: row.groupId });+ } else if (row.role === 'sink' && row.groupId !== null) {groupSink.push({category: category.id,- group: template.filter(t => t.type === 'sink' && t.group !== null)[0]- .group,- weight: template.filter(t => t.type === 'sink' && t.group !== null)[0]- .weight,+ groupId: row.groupId,+ weight: row.weight,});- }- if (- template.filter(t => t.type === null && t.group !== null).length > 0- ) {- groupGeneral.push({ category: category.id, group: template[0].group });+ } else if (row.role === 'overspend') {+ groupOverspend.push({ category: category.id, groupId: row.groupId });}}}++ const groupRows = await db.all<{ id: string; name: string }>(+ 'SELECT id, name FROM cleanup_groups WHERE tombstone = 0',+ );+ const groupNamesById = new Map(groupRows.map(g => [g.id, g.name]));+//run category groupsconst newWarnings = await applyGroupCleanups(month,groupSource,groupSink,- groupGeneral,+ groupOverspend,+ groupNamesById,);warnings.splice(1, 0, ...newWarnings);- for (let c = 0; c < categories.length; c++) {- const category = categories[c];- const template = category_templates[category.id];- if (template) {- if (- template.filter(t => t.type === 'source' && t.group === null).length > 0- ) {- const balance = await getSheetValue(- sheetName,- `leftover-${category.id}`,- );- const budgeted = await getSheetValue(- sheetName,- `budget-${category.id}`,- );- if (balance >= 0) {- // const spent = await getSheetValue(- // sheetName,- // `sum-amount-${category.id}`,- // );- await setBudget({- category: category.id,- month,- amount: budgeted - balance,- });- await setGoal({- category: category.id,- month,- goal: budgeted - balance,- long_goal: 0,- });- num_sources += 1;- } else {- warnings.push(category.name + ' does not have available funds.');- }- const carryover = await db.first<Pick<db.DbZeroBudget, 'carryover'>>(- `SELECT carryover FROM zero_budgets WHERE month = ? and category = ?`,- [db_month, category.id],- );- if (carryover !== null) {- //keep track of source categories with rollover enabled- if (carryover.carryover === 1) {- sourceWithRollover.push({ cat: category, temp: template });- }- }- }- if (- template.filter(t => t.type === 'sink' && t.group === null).length > 0- ) {- sinkCategory.push({ cat: category, temp: template });- num_sinks += 1;- total_weight += template.filter(w => w.type === 'sink')[0].weight;+ for (const category of categories) {+ const def = parseCleanupDef(category.cleanup_def);+ if (!def) continue;++ const globalSource = def.find(+ r => r.role === 'source' && r.groupId === null,+ );+ if (globalSource) {+ const balance = await getSheetValue(sheetName, `leftover-${category.id}`);+ const budgeted = await getSheetValue(sheetName, `budget-${category.id}`);+ if (balance >= 0) {+ await setBudget({+ category: category.id,+ month,+ amount: budgeted - balance,+ });+ await setGoal({+ category: category.id,+ month,+ goal: budgeted - balance,+ long_goal: 0,+ });+ num_sources += 1;+ } else {+ warnings.push(category.name + ' does not have available funds.');}}++ const globalSink = def.find(r => r.role === 'sink' && r.groupId === null);+ if (globalSink && globalSink.role === 'sink') {+ sinkCategory.push({ cat: category, weight: globalSink.weight });+ num_sinks += 1;+ total_weight += globalSink.weight;+ }}//funds all underfunded categories first unless the overspending rollover is checked- for (let c = 0; c < categories.length; c++) {- const category = categories[c];+ for (const category of categories) {const budgetAvailable = await getSheetValue(sheetName, `to-budget`);const balance = await getSheetValue(sheetName, `leftover-${category.id}`);const budgeted = await getSheetValue(sheetName, `budget-${category.id}`);@@ -303,13 +285,8 @@ async function processCleanup(month: string): Promise<Notification> {//fill sinking categoriesfor (let c = 0; c < sinkCategory.length; c++) {- const budgeted = await getSheetValue(- sheetName,- `budget-${sinkCategory[c].cat.id}`,- );- const categoryId = sinkCategory[c].cat.id;- const weight = sinkCategory[c].temp.filter(w => w.type === 'sink')[0]- .weight;+ const { cat, weight } = sinkCategory[c];+ const budgeted = await getSheetValue(sheetName, `budget-${cat.id}`);let to_budget =budgeted + Math.round((weight / total_weight) * budgetAvailable);if (c === sinkCategory.length - 1) {@@ -322,7 +299,7 @@ async function processCleanup(month: string): Promise<Notification> {}}await setBudget({- category: categoryId,+ category: cat.id,month,amount: to_budget,});@@ -378,31 +355,14 @@ async function processCleanup(month: string): Promise<Notification> {}}-const TEMPLATE_PREFIX = '#cleanup ';-async function getCategoryTemplates() {- const templates = {};-- const notes = await db.all<db.DbNote>(- `SELECT * FROM notes WHERE lower(note) like '%${TEMPLATE_PREFIX}%'`,- );-- for (let n = 0; n < notes.length; n++) {- const lines = notes[n].note.split('\n');- const template_lines = [];- for (let l = 0; l < lines.length; l++) {- const line = lines[l].trim();- if (!line.toLowerCase().startsWith(TEMPLATE_PREFIX)) continue;- const expression = line.slice(TEMPLATE_PREFIX.length);- try {- const parsed = parse(expression);- template_lines.push(parsed);- } catch (e) {- template_lines.push({ type: 'error', line, error: e });- }- }- if (template_lines.length) {- templates[notes[n].id] = template_lines;- }+function parseCleanupDef(+ raw: string | null | undefined,+): CleanupTemplate[] | null {+ if (!raw) return null;+ try {+ const parsed = JSON.parse(raw) as CleanupTemplate[];+ return Array.isArray(parsed) && parsed.length > 0 ? parsed : null;+ } catch {+ return null;}- return templates;}diff --git a/packages/loot-core/src/server/budget/goal-template.ts b/packages/loot-core/src/server/budget/goal-template.tsindex 0feadd9a76..f9ffd87f34 100644--- a/packages/loot-core/src/server/budget/goal-template.ts+++ b/packages/loot-core/src/server/budget/goal-template.ts@@ -9,6 +9,7 @@ import type { Template } from '#types/models/templates';import { getSheetValue, isTrackingBudget, setBudget, setGoal } from './actions';import { CategoryTemplateContext } from './category-template-context';+import { storeNoteCleanups } from './cleanup-template-notes';import { checkTemplateNotes, storeNoteTemplates } from './template-notes';export function distributeRemainder(@@ -50,6 +51,7 @@ export async function storeTemplates({}[];source: 'notes' | 'ui';}): Promise<void> {+ await storeNoteCleanups(categoriesWithTemplates.map(c => c.id));await batchMessages(async () => {for (const { id, templates } of categoriesWithTemplates) {const goalDefs = templates.length > 0 ? JSON.stringify(templates) : null;diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.tsindex 4b66e4c1dc..8f537941ad 100644--- a/packages/loot-core/src/server/budget/template-notes.test.ts+++ b/packages/loot-core/src/server/budget/template-notes.test.ts@@ -34,6 +34,7 @@ function mockDbUpdate() {describe('storeNoteTemplates', () => {beforeEach(() => {vi.clearAllMocks();+ vi.mocked(db.all).mockResolvedValue([]);});const testCases = [diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.tsindex 4254b022aa..42e789555f 100644--- a/packages/loot-core/src/server/db/types/index.ts+++ b/packages/loot-core/src/server/db/types/index.ts@@ -41,6 +41,7 @@ export type DbCategory = {sort_order: number;hidden: 1 | 0;goal_def?: JsonString | null;+ cleanup_def?: JsonString | null;template_settings?: { source: 'notes' | 'ui' };tombstone: 1 | 0;};@@ -54,6 +55,12 @@ export type DbCategoryGroup = {tombstone: 1 | 0;};+export type DbCleanupGroup = {+ id: string;+ name: string;+ tombstone: 1 | 0;+};+export type DbCategoryMapping = {id: DbCategory['id'];transferId: DbCategory['id'];@@ -293,6 +300,7 @@ export type DbViewCategory = {group: DbCategoryGroup['id'];sort_order: DbCategory['sort_order'];tombstone: DbCategory['tombstone'];+ cleanup_def?: DbCategory['cleanup_def'];};export type DbViewCategoryWithGroupHidden = {diff --git a/packages/loot-core/src/types/models/category.ts b/packages/loot-core/src/types/models/category.tsindex 69d2f74324..9d978e7fc3 100644--- a/packages/loot-core/src/types/models/category.ts+++ b/packages/loot-core/src/types/models/category.ts@@ -6,6 +6,7 @@ export type CategoryEntity = {is_income?: boolean;group: CategoryGroupEntity['id'];goal_def?: string;+ cleanup_def?: string;template_settings?: { source: 'notes' | 'ui' };sort_order?: number;tombstone?: boolean;diff --git a/packages/loot-core/src/types/models/cleanup-templates.ts b/packages/loot-core/src/types/models/cleanup-templates.tsnew file mode 100644index 0000000000..b8987aba66--- /dev/null+++ b/packages/loot-core/src/types/models/cleanup-templates.ts@@ -0,0 +1,4 @@+export type CleanupTemplate =+ | { role: 'source'; groupId: string | null }+ | { role: 'sink'; groupId: string | null; weight: number }+ | { role: 'overspend'; groupId: string };diff --git a/upcoming-release-notes/7794.md b/upcoming-release-notes/7794.mdnew file mode 100644index 0000000000..35df2d8a5d--- /dev/null+++ b/upcoming-release-notes/7794.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [matt-fidd]+---++Persist end-of-month cleanup templates in the database