Skip to content

A local-first personal finance app

[Goals]: Add a long term goal template (#3012)

youngcw511f677ae4d7
diff --git a/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx
index ca816832c4..ccaf49d17c 100644
--- a/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx
+++ b/packages/desktop-client/src/components/budget/BalanceWithCarryover.tsx
@@ -23,6 +23,7 @@ type BalanceWithCarryoverProps = Omit<
balance: Binding;
goal: Binding;
budgeted: Binding;
+ longGoal: Binding;
disabled?: boolean;
carryoverIndicator?: ({ style }: CarryoverIndicatorProps) => JSX.Element;
};
@@ -54,6 +55,7 @@ export function BalanceWithCarryover({
balance,
goal,
budgeted,
+ longGoal,
disabled,
carryoverIndicator = DefaultCarryoverIndicator,
...props
@@ -62,11 +64,12 @@ export function BalanceWithCarryover({
const balanceValue = useSheetValue(balance);
const goalValue = useSheetValue(goal);
const budgetedValue = useSheetValue(budgeted);
+ const longGoalValue = useSheetValue(longGoal);
const isGoalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');
const valueStyle = makeBalanceAmountStyle(
balanceValue,
isGoalTemplatesEnabled ? goalValue : null,
- budgetedValue,
+ longGoalValue === 1 ? balanceValue : budgetedValue,
);
return (
@@ -86,7 +89,7 @@ export function BalanceWithCarryover({
makeBalanceAmountStyle(
value,
isGoalTemplatesEnabled ? goalValue : null,
- budgetedValue,
+ longGoalValue === 1 ? balanceValue : budgetedValue,
)
}
style={{
diff --git a/packages/desktop-client/src/components/budget/report/ReportComponents.tsx b/packages/desktop-client/src/components/budget/report/ReportComponents.tsx
index 5a9fd4b9e6..5cd9480f82 100644
--- a/packages/desktop-client/src/components/budget/report/ReportComponents.tsx
+++ b/packages/desktop-client/src/components/budget/report/ReportComponents.tsx
@@ -339,6 +339,7 @@ export const CategoryMonth = memo(function CategoryMonth({
balance={reportBudget.catBalance(category.id)}
goal={reportBudget.catGoal(category.id)}
budgeted={reportBudget.catBudgeted(category.id)}
+ longGoal={reportBudget.catLongGoal(category.id)}
style={{
':hover': { textDecoration: 'underline' },
}}
diff --git a/packages/desktop-client/src/components/budget/rollover/RolloverComponents.tsx b/packages/desktop-client/src/components/budget/rollover/RolloverComponents.tsx
index 7c4a9ff8cf..597e137e9c 100644
--- a/packages/desktop-client/src/components/budget/rollover/RolloverComponents.tsx
+++ b/packages/desktop-client/src/components/budget/rollover/RolloverComponents.tsx
@@ -327,6 +327,7 @@ export const ExpenseCategoryMonth = memo(function ExpenseCategoryMonth({
balance={rolloverBudget.catBalance(category.id)}
goal={rolloverBudget.catGoal(category.id)}
budgeted={rolloverBudget.catBudgeted(category.id)}
+ longGoal={rolloverBudget.catLongGoal(category.id)}
style={{
':hover': { textDecoration: 'underline' },
}}
diff --git a/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx b/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx
index 4bac2bee7a..5a520cd7a1 100644
--- a/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx
+++ b/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx
@@ -326,6 +326,7 @@ const ExpenseCategory = memo(function ExpenseCategory({
category,
isHidden,
goal,
+ longGoal,
budgeted,
spent,
balance,
@@ -345,8 +346,6 @@ const ExpenseCategory = memo(function ExpenseCategory({
const isGoalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');
const goalTemp = useSheetValue(goal);
const goalValue = isGoalTemplatesEnabled ? goalTemp : null;
- const budgetedTemp = useSheetValue(budgeted);
- const budgetedValue = isGoalTemplatesEnabled ? budgetedTemp : null;
const [budgetType = 'rollover'] = useLocalPref('budgetType');
const dispatch = useDispatch();
@@ -364,6 +363,14 @@ const ExpenseCategory = memo(function ExpenseCategory({
? rolloverBudget.catBalance(category.id)
: reportBudget.catBalance(category.id),
);
+ const budgetedtmp = useSheetValue(budgeted);
+ const balancetmp = useSheetValue(balance);
+ const isLongGoal = useSheetValue(longGoal) === 1;
+ const budgetedValue = isGoalTemplatesEnabled
+ ? isLongGoal
+ ? balancetmp
+ : budgetedtmp
+ : null;
const onTransfer = () => {
dispatch(
@@ -587,6 +594,7 @@ const ExpenseCategory = memo(function ExpenseCategory({
balance={balance}
goal={goal}
budgeted={budgeted}
+ longGoal={longGoal}
formatter={value => (
<Button
type="bare"
@@ -1381,6 +1389,11 @@ const ExpenseGroup = memo(function ExpenseGroup({
? reportBudget.catGoal(category.id)
: rolloverBudget.catGoal(category.id)
}
+ longGoal={
+ type === 'report'
+ ? reportBudget.catLongGoal(category.id)
+ : rolloverBudget.catLongGoal(category.id)
+ }
budgeted={
type === 'report'
? reportBudget.catBudgeted(category.id)
diff --git a/packages/desktop-client/src/components/modals/ReportBalanceMenuModal.tsx b/packages/desktop-client/src/components/modals/ReportBalanceMenuModal.tsx
index 01808eea13..40a18a6e7f 100644
--- a/packages/desktop-client/src/components/modals/ReportBalanceMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/ReportBalanceMenuModal.tsx
@@ -70,6 +70,7 @@ export function ReportBalanceMenuModal({
balance={reportBudget.catBalance(categoryId)}
goal={reportBudget.catGoal(categoryId)}
budgeted={reportBudget.catBudgeted(categoryId)}
+ longGoal={reportBudget.catLongGoal(categoryId)}
carryoverIndicator={({ style }) =>
DefaultCarryoverIndicator({
style: {
diff --git a/packages/desktop-client/src/components/modals/RolloverBalanceMenuModal.tsx b/packages/desktop-client/src/components/modals/RolloverBalanceMenuModal.tsx
index c35073f262..564bef773f 100644
--- a/packages/desktop-client/src/components/modals/RolloverBalanceMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/RolloverBalanceMenuModal.tsx
@@ -74,6 +74,7 @@ export function RolloverBalanceMenuModal({
balance={rolloverBudget.catBalance(categoryId)}
goal={rolloverBudget.catGoal(categoryId)}
budgeted={rolloverBudget.catBudgeted(categoryId)}
+ longGoal={rolloverBudget.catLongGoal(categoryId)}
carryoverIndicator={({ style }) =>
DefaultCarryoverIndicator({
style: {
diff --git a/packages/loot-core/migrations/1720665000000_goal_context.sql b/packages/loot-core/migrations/1720665000000_goal_context.sql
new file mode 100644
index 0000000000..ef9b9be6e3
--- /dev/null
+++ b/packages/loot-core/migrations/1720665000000_goal_context.sql
@@ -0,0 +1,6 @@
+BEGIN TRANSACTION;
+
+ALTER TABLE zero_budgets ADD COLUMN long_goal INTEGER DEFAULT null;
+ALTER TABLE reflect_budgets ADD COLUMN long_goal INTEGER DEFAULT null;
+
+COMMIT;
\ No newline at end of file
diff --git a/packages/loot-core/src/client/queries.ts b/packages/loot-core/src/client/queries.ts
index d4320ee52b..06279fd336 100644
--- a/packages/loot-core/src/client/queries.ts
+++ b/packages/loot-core/src/client/queries.ts
@@ -240,6 +240,7 @@ export const rolloverBudget = {
catBalance: id => `leftover-${id}`,
catCarryover: id => `carryover-${id}`,
catGoal: id => `goal-${id}`,
+ catLongGoal: id => `long-goal-${id}`,
};
export const reportBudget = {
@@ -263,4 +264,5 @@ export const reportBudget = {
catBalance: id => `leftover-${id}`,
catCarryover: id => `carryover-${id}`,
catGoal: id => `goal-${id}`,
+ catLongGoal: id => `long-goal-${id}`,
};
diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.ts
index 5fa4f519aa..05cf0968bb 100644
--- a/packages/loot-core/src/server/aql/schema/index.ts
+++ b/packages/loot-core/src/server/aql/schema/index.ts
@@ -160,6 +160,7 @@ export const schema = {
amount: f('integer'),
carryover: f('integer'),
goal: f('integer'),
+ long_goal: f('integer'),
},
zero_budgets: {
id: f('id'),
@@ -168,6 +169,7 @@ export const schema = {
amount: f('integer'),
carryover: f('integer'),
goal: f('integer'),
+ long_goal: f('integer'),
},
};
diff --git a/packages/loot-core/src/server/budget/actions.ts b/packages/loot-core/src/server/budget/actions.ts
index ce388edd4b..88ef2f47f4 100644
--- a/packages/loot-core/src/server/budget/actions.ts
+++ b/packages/loot-core/src/server/budget/actions.ts
@@ -114,7 +114,7 @@ export function setBudget({
});
}
-export function setGoal({ month, category, goal }): Promise<void> {
+export function setGoal({ month, category, goal, long_goal }): Promise<void> {
const table = getBudgetTable();
const existing = db.firstSync(
`SELECT id FROM ${table} WHERE month = ? AND category = ?`,
@@ -124,6 +124,7 @@ export function setGoal({ month, category, goal }): Promise<void> {
return db.update(table, {
id: existing.id,
goal,
+ long_goal,
});
}
return db.insert(table, {
@@ -131,6 +132,7 @@ export function setGoal({ month, category, goal }): Promise<void> {
month: dbMonth(month),
category,
goal,
+ long_goal,
});
}
diff --git a/packages/loot-core/src/server/budget/base.ts b/packages/loot-core/src/server/budget/base.ts
index a09a1eb314..dc6a5c9b26 100644
--- a/packages/loot-core/src/server/budget/base.ts
+++ b/packages/loot-core/src/server/budget/base.ts
@@ -320,6 +320,9 @@ function handleBudgetChange(budget) {
budget.carryover === 1 ? true : false,
);
sheet.get().set(`${sheetName}!goal-${budget.category}`, budget.goal);
+ sheet
+ .get()
+ .set(`${sheetName}!long-goal-${budget.category}`, budget.long_goal);
}
}
diff --git a/packages/loot-core/src/server/budget/cleanup-template.ts b/packages/loot-core/src/server/budget/cleanup-template.ts
index a9f7ca96a4..b284e34a00 100644
--- a/packages/loot-core/src/server/budget/cleanup-template.ts
+++ b/packages/loot-core/src/server/budget/cleanup-template.ts
@@ -214,6 +214,7 @@ async function processCleanup(month: string): Promise<Notification> {
category: category.id,
month,
goal: budgeted - balance,
+ long_goal: 0,
});
num_sources += 1;
} else {
diff --git a/packages/loot-core/src/server/budget/goal-template.pegjs b/packages/loot-core/src/server/budget/goal-template.pegjs
index 635efced04..dbe2dd3f16 100644
--- a/packages/loot-core/src/server/budget/goal-template.pegjs
+++ b/packages/loot-core/src/server/budget/goal-template.pegjs
@@ -1,29 +1,30 @@
// https://peggyjs.org
expr
- = priority: priority? _? percentOf:percentOf category: name
- { return { type: 'percentage', percent: +percentOf.percent, previous: percentOf.prev, category, priority: +priority }}
- / priority: priority? _? amount: amount _ repeatEvery _ weeks: weekCount _ starting _ starting: date limit: limit?
- { return { type: 'week', amount, weeks, starting, limit, priority: +priority }}
- / priority: priority? _? amount: amount _ by _ month: month from: spendFrom? repeat: (_ repeatEvery _ repeat)?
+ = template: template _ percentOf:percentOf category: name
+ { return { type: 'percentage', percent: +percentOf.percent, previous: percentOf.prev, category, priority: template.priority, directive: template.directive }}
+ / template: template _ amount: amount _ repeatEvery _ weeks: weekCount _ starting _ starting: date limit: limit?
+ { return { type: 'week', amount, weeks, starting, limit, priority: template.priority, directive: template.directive }}
+ / template: template _ amount: amount _ by _ month: month from: spendFrom? repeat: (_ repeatEvery _ repeat)?
{ return {
type: from ? 'spend' : 'by',
amount,
month,
...(repeat ? repeat[3] : {}),
from,
- priority: +priority
+ priority: template.priority, directive: template.directive
} }
- / priority: priority? _? monthly: amount limit: limit?
- { return { type: 'simple', monthly, limit, priority: +priority } }
- / priority: priority? _? limit: limit
- { return { type: 'simple', limit , priority: +priority } }
- / priority: priority? _? schedule _ full:full? name: name
- { return { type: 'schedule', name, priority: +priority, full } }
- / priority: priority? _? remainder: remainder
- { return { type: 'remainder', priority: null, weight: remainder } }
- / priority: priority? _? 'average'i _ amount: positive _ 'months'i?
- { return { type: 'average', amount: +amount, priority: +priority }}
+ / template: template _ monthly: amount limit: limit?
+ { return { type: 'simple', monthly, limit, priority: template.priority, directive: template.directive } }
+ / template: template _ limit: limit
+ { return { type: 'simple', limit , priority: template.priority, directive: template.directive } }
+ / template: template _ schedule _ full:full? name: name
+ { return { type: 'schedule', name, priority: template.priority, directive: template.directive, full } }
+ / template: template _ remainder: remainder limit: limit?
+ { return { type: 'remainder', priority: null, directive: template.directive, weight: remainder, limit } }
+ / template: template _ 'average'i _ amount: positive _ 'months'i?
+ { return { type: 'average', amount: +amount, priority: template.priority, directive: template.directive }}
+ / goal: goal amount: amount { return {type: 'simple', amount: amount, priority: null, directive: 'goal' }}
repeat 'repeat interval'
@@ -53,8 +54,10 @@ starting = 'starting'i
upTo = 'up'i _ 'to'i
schedule = 'schedule'i
full = 'full'i _ {return true}
-priority = '-'i number: number _ {return number}
+priority = '-'i number: number {return number}
remainder = 'remainder'i _? weight: positive? { return +weight || 1 }
+template = '#template' priority: priority? {return {priority: +priority, directive: 'template'}}
+goal = '#goal'
_ 'space' = ' '+
d 'digit' = [0-9]
diff --git a/packages/loot-core/src/server/budget/goaltemplates.ts b/packages/loot-core/src/server/budget/goaltemplates.ts
index 65fa4685ea..e5e2d9e7b8 100644
--- a/packages/loot-core/src/server/budget/goaltemplates.ts
+++ b/packages/loot-core/src/server/budget/goaltemplates.ts
@@ -1,7 +1,7 @@
// @ts-strict-ignore
import { Notification } from '../../client/state-types/notifications';
import * as monthUtils from '../../shared/months';
-import { integerToAmount } from '../../shared/util';
+import { integerToAmount, amountToInteger } from '../../shared/util';
import * as db from '../db';
import { batchMessages } from '../sync';
@@ -16,16 +16,25 @@ import { goalsSimple } from './goals/goalsSimple';
import { goalsSpend } from './goals/goalsSpend';
import { goalsWeek } from './goals/goalsWeek';
+const TEMPLATE_PREFIX = '#template';
+const GOAL_PREFIX = '#goal';
+
export async function applyTemplate({ month }) {
await storeTemplates();
- const category_templates = await getTemplates(null);
- return processTemplate(month, false, category_templates);
+ const category_templates = await getTemplates(null, 'template');
+ const category_goals = await getTemplates(null, 'goal');
+ const ret = await processTemplate(month, false, category_templates);
+ await processGoals(category_goals, month);
+ return ret;
}
export async function overwriteTemplate({ month }) {
await storeTemplates();
- const category_templates = await getTemplates(null);
- return processTemplate(month, true, category_templates);
+ const category_templates = await getTemplates(null, 'template');
+ const category_goals = await getTemplates(null, 'goal');
+ const ret = await processTemplate(month, true, category_templates);
+ await processGoals(category_goals, month);
+ return ret;
}
export async function applySingleCategoryTemplate({ month, category }) {
@@ -33,8 +42,16 @@ export async function applySingleCategoryTemplate({ month, category }) {
category,
]);
await storeTemplates();
- const category_templates = await getTemplates(categories[0]);
- return processTemplate(month, true, category_templates, categories[0]);
+ const category_templates = await getTemplates(categories[0], 'template');
+ const category_goals = await getTemplates(categories[0], 'goal');
+ const ret = await processTemplate(
+ month,
+ true,
+ category_templates,
+ categories[0],
+ );
+ await processGoals(category_goals, month, categories[0]);
+ return ret;
}
export function runCheckTemplates() {
@@ -83,6 +100,7 @@ async function setCategoryTargets({ month, idealTemplate }) {
category: element.category,
goal: element.amount,
month,
+ long_goal: 0,
});
});
});
@@ -101,6 +119,7 @@ async function resetCategoryTargets(month, category) {
category: categories[i].id,
goal: null,
month,
+ long_goal: null,
});
}
});
@@ -127,7 +146,7 @@ async function storeTemplates() {
}
}
-async function getTemplates(category) {
+async function getTemplates(category, directive: string) {
//retrieves template definitions from the database
const goal_def = await db.all(
'SELECT * FROM categories WHERE goal_def IS NOT NULL',
@@ -138,13 +157,26 @@ async function getTemplates(category) {
templates[goal_def[ll].id] = JSON.parse(goal_def[ll].goal_def);
}
if (category) {
- const singleCategoryTemplate = {};
+ const singleCategoryTemplate = [];
if (templates[category.id] !== undefined) {
- singleCategoryTemplate[category.id] = templates[category.id];
+ singleCategoryTemplate[category.id] = templates[category.id].filter(
+ t => t.directive === directive,
+ );
+ return singleCategoryTemplate;
}
+ singleCategoryTemplate[category.id] = undefined;
return singleCategoryTemplate;
} else {
- return templates;
+ const categories = await getCategories();
+ const ret = [];
+ for (let cc = 0; cc < categories.length; cc++) {
+ const id = categories[cc].id;
+ if (templates[id]) {
+ ret[id] = templates[id];
+ ret[id] = ret[id].filter(t => t.directive === directive);
+ }
+ }
+ return ret;
}
}
@@ -190,13 +222,12 @@ async function processTemplate(
// save index of category to remove
categories_remove.push(c);
} else {
- // if we are overwritting add this category to list to zero
- setToZero.push({
- category: category.id,
- amount: 0,
- isIncome: category.is_income,
- isTemplate: template ? true : false,
- });
+ // add all categories with a template to the list to unset budget
+ if (template?.length > 0) {
+ setToZero.push({
+ category: category.id,
+ });
+ }
}
}
}
@@ -211,7 +242,7 @@ async function processTemplate(
// zero out budget and goal from categories that need it
await setGoalBudget({
month,
- templateBudget: setToZero.filter(f => f.isTemplate === true),
+ templateBudget: setToZero,
});
await resetCategoryTargets(month, categories);
@@ -358,6 +389,7 @@ async function processTemplate(
await setGoalBudget({ month, templateBudget });
}
await setCategoryTargets({ month, idealTemplate });
+
if (num_applied === 0) {
if (errors.length) {
return {
@@ -386,12 +418,35 @@ async function processTemplate(
}
}
-const TEMPLATE_PREFIX = '#template';
+async function processGoals(goals, month, category?) {
+ let categories = [];
+ if (category) {
+ categories[0] = category;
+ } else {
+ categories = await getCategories();
+ }
+ for (let c = 0; c < categories.length; c++) {
+ const cat_id = categories[c].id;
+ const goal_lines = goals[cat_id];
+ if (goal_lines?.length > 0) {
+ await setGoal({
+ month,
+ category: cat_id,
+ goal: amountToInteger(goal_lines[0].amount),
+ long_goal: 1,
+ });
+ }
+ }
+}
async function getCategoryTemplates(category) {
const templates = {};
let notes = await db.all(
- `SELECT * FROM notes WHERE lower(note) like '%${TEMPLATE_PREFIX}%'`,
+ `
+ SELECT * FROM notes
+ WHERE lower(note) like '%${TEMPLATE_PREFIX}%'
+ OR lower(note) like '%${GOAL_PREFIX}%'
+ `,
);
if (category) notes = notes.filter(n => n.id === category.id);
@@ -400,10 +455,14 @@ async function getCategoryTemplates(category) {
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);
+ if (
+ !line.toLowerCase().startsWith(TEMPLATE_PREFIX) &&
+ !line.toLowerCase().startsWith(GOAL_PREFIX)
+ ) {
+ continue;
+ }
try {
- const parsed = parse(expression);
+ const parsed = parse(line);
template_lines.push(parsed);
} catch (e) {
template_lines.push({ type: 'error', line, error: e });
diff --git a/packages/loot-core/src/server/sheet.ts b/packages/loot-core/src/server/sheet.ts
index 3ac4b6e7b1..cad83f701c 100644
--- a/packages/loot-core/src/server/sheet.ts
+++ b/packages/loot-core/src/server/sheet.ts
@@ -217,6 +217,7 @@ export async function loadUserBudgets(db): Promise<void> {
budget.carryover === 1 ? true : false,
);
sheet.set(`${sheetName}!goal-${budget.category}`, budget.goal);
+ sheet.set(`${sheetName}!long-goal-${budget.category}`, budget.long_goal);
}
}
diff --git a/upcoming-release-notes/3012.md b/upcoming-release-notes/3012.md
new file mode 100644
index 0000000000..dcd3471eb8
--- /dev/null
+++ b/upcoming-release-notes/3012.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [youngcw]
+---
+
+Add long term goal type template