Skip to content

A local-first personal finance app

Add types to budget template files and some cleanup (#4986)

Joel Jeremy Marquez83f6706020c1
diff --git a/packages/loot-core/src/server/budget/app.ts b/packages/loot-core/src/server/budget/app.ts
index fdfe7d46f9..9081308228 100644
--- a/packages/loot-core/src/server/budget/app.ts
+++ b/packages/loot-core/src/server/budget/app.ts
@@ -15,7 +15,7 @@ import { undoable } from '../undo';
import * as actions from './actions';
import * as budget from './base';
import * as cleanupActions from './cleanup-template';
-import * as goalActions from './goaltemplates';
+import * as goalActions from './goal-template';
export interface BudgetHandlers {
'budget/budget-amount': typeof actions.setBudget;
diff --git a/packages/loot-core/src/server/budget/categoryTemplate.test.ts b/packages/loot-core/src/server/budget/category-template-context.test.ts
similarity index 87%
rename from packages/loot-core/src/server/budget/categoryTemplate.test.ts
rename to packages/loot-core/src/server/budget/category-template-context.test.ts
index 797d5fbbea..f0c79ef3ee 100644
--- a/packages/loot-core/src/server/budget/categoryTemplate.test.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.test.ts
@@ -5,7 +5,7 @@ import { type CategoryEntity } from '../../types/models';
import * as db from '../db';
import * as actions from './actions';
-import { CategoryTemplate } from './categoryTemplate';
+import { CategoryTemplateContext } from './category-template-context';
import { type Template } from './types/templates';
// Mock getSheetValue and getCategories
@@ -19,7 +19,7 @@ vi.mock('../db', () => ({
}));
// Test helper class to access constructor and methods
-class TestCategoryTemplate extends CategoryTemplate {
+class TestCategoryTemplateContext extends CategoryTemplateContext {
public constructor(
templates: Template[],
category: CategoryEntity,
@@ -31,7 +31,7 @@ class TestCategoryTemplate extends CategoryTemplate {
}
}
-describe('CategoryTemplate', () => {
+describe('CategoryTemplateContext', () => {
describe('runSimple', () => {
it('should return monthly amount when provided', () => {
const template: Template = {
@@ -42,7 +42,7 @@ describe('CategoryTemplate', () => {
};
const limit = 0;
- const result = CategoryTemplate.runSimple(template, limit);
+ const result = CategoryTemplateContext.runSimple(template, limit);
expect(result).toBe(amountToInteger(100));
});
@@ -54,7 +54,7 @@ describe('CategoryTemplate', () => {
priority: 1,
};
- const result = CategoryTemplate.runSimple(template, 500);
+ const result = CategoryTemplateContext.runSimple(template, 500);
expect(result).toBe(500);
});
@@ -76,7 +76,7 @@ describe('CategoryTemplate', () => {
directive: 'template',
priority: 1,
};
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
[template],
category,
'2024-01',
@@ -100,7 +100,7 @@ describe('CategoryTemplate', () => {
directive: 'template',
priority: 1,
};
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
[template],
category,
'2024-01',
@@ -113,7 +113,7 @@ describe('CategoryTemplate', () => {
});
describe('runCopy', () => {
- let instance: TestCategoryTemplate;
+ let instance: TestCategoryTemplateContext;
beforeEach(() => {
const category: CategoryEntity = {
@@ -122,7 +122,7 @@ describe('CategoryTemplate', () => {
group: 'test-group',
is_income: false,
};
- instance = new TestCategoryTemplate([], category, '2024-01', 0, 0);
+ instance = new TestCategoryTemplateContext([], category, '2024-01', 0, 0);
vi.clearAllMocks();
});
@@ -136,7 +136,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetValue).mockResolvedValue(100);
- const result = await CategoryTemplate.runCopy(template, instance);
+ const result = await CategoryTemplateContext.runCopy(template, instance);
expect(result).toBe(100);
});
@@ -150,7 +150,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetValue).mockResolvedValue(200);
- const result = await CategoryTemplate.runCopy(template, instance);
+ const result = await CategoryTemplateContext.runCopy(template, instance);
expect(result).toBe(200);
});
@@ -164,13 +164,13 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetValue).mockResolvedValue(0);
- const result = await CategoryTemplate.runCopy(template, instance);
+ const result = await CategoryTemplateContext.runCopy(template, instance);
expect(result).toBe(0);
});
});
describe('runWeek', () => {
- let instance: TestCategoryTemplate;
+ let instance: TestCategoryTemplateContext;
beforeEach(() => {
const category: CategoryEntity = {
@@ -179,7 +179,7 @@ describe('CategoryTemplate', () => {
group: 'test-group',
is_income: false,
};
- instance = new TestCategoryTemplate([], category, '2024-01', 0, 0);
+ instance = new TestCategoryTemplateContext([], category, '2024-01', 0, 0);
});
//5 mondays in January 2024
@@ -193,7 +193,7 @@ describe('CategoryTemplate', () => {
priority: 1,
};
- const result = CategoryTemplate.runWeek(template, instance);
+ const result = CategoryTemplateContext.runWeek(template, instance);
expect(result).toBe(amountToInteger(500));
});
@@ -207,7 +207,7 @@ describe('CategoryTemplate', () => {
priority: 1,
};
- const result = CategoryTemplate.runWeek(template, instance);
+ const result = CategoryTemplateContext.runWeek(template, instance);
expect(result).toBe(amountToInteger(300));
});
@@ -221,13 +221,13 @@ describe('CategoryTemplate', () => {
priority: 1,
};
- const result = CategoryTemplate.runWeek(template, instance);
+ const result = CategoryTemplateContext.runWeek(template, instance);
expect(result).toBe(amountToInteger(100));
});
});
describe('runSpend', () => {
- let instance: TestCategoryTemplate;
+ let instance: TestCategoryTemplateContext;
beforeEach(() => {
const category: CategoryEntity = {
@@ -236,7 +236,7 @@ describe('CategoryTemplate', () => {
group: 'test-group',
is_income: false,
};
- instance = new TestCategoryTemplate([], category, '2024-01', 0, 0);
+ instance = new TestCategoryTemplateContext([], category, '2024-01', 0, 0);
vi.clearAllMocks();
});
@@ -255,7 +255,7 @@ describe('CategoryTemplate', () => {
.mockResolvedValueOnce(20000) // leftover in Nov
.mockResolvedValueOnce(10000); // budgeted in Dec
- const result = await CategoryTemplate.runSpend(template, instance);
+ const result = await CategoryTemplateContext.runSpend(template, instance);
expect(result).toBe(60000);
});
@@ -276,7 +276,7 @@ describe('CategoryTemplate', () => {
.mockResolvedValueOnce(20000)
.mockResolvedValueOnce(10000);
- const result = await CategoryTemplate.runSpend(template, instance);
+ const result = await CategoryTemplateContext.runSpend(template, instance);
expect(result).toBe(33333);
});
@@ -290,13 +290,13 @@ describe('CategoryTemplate', () => {
priority: 1,
};
- const result = await CategoryTemplate.runSpend(template, instance);
+ const result = await CategoryTemplateContext.runSpend(template, instance);
expect(result).toBe(0);
});
});
describe('runPercentage', () => {
- let instance: TestCategoryTemplate;
+ let instance: TestCategoryTemplateContext;
beforeEach(() => {
const category: CategoryEntity = {
@@ -305,7 +305,7 @@ describe('CategoryTemplate', () => {
group: 'test-group',
is_income: false,
};
- instance = new TestCategoryTemplate([], category, '2024-01', 0, 0);
+ instance = new TestCategoryTemplateContext([], category, '2024-01', 0, 0);
vi.clearAllMocks();
});
@@ -321,7 +321,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetValue).mockResolvedValue(10000);
- const result = await CategoryTemplate.runPercentage(
+ const result = await CategoryTemplateContext.runPercentage(
template,
0,
instance,
@@ -339,7 +339,7 @@ describe('CategoryTemplate', () => {
priority: 1,
};
- const result = await CategoryTemplate.runPercentage(
+ const result = await CategoryTemplateContext.runPercentage(
template,
500,
instance,
@@ -370,7 +370,7 @@ describe('CategoryTemplate', () => {
]);
vi.mocked(actions.getSheetValue).mockResolvedValue(2000);
- const result = await CategoryTemplate.runPercentage(
+ const result = await CategoryTemplateContext.runPercentage(
template,
0,
instance,
@@ -390,7 +390,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetValue).mockResolvedValue(10000);
- const result = await CategoryTemplate.runPercentage(
+ const result = await CategoryTemplateContext.runPercentage(
template,
0,
instance,
@@ -404,7 +404,7 @@ describe('CategoryTemplate', () => {
});
describe('runAverage', () => {
- let instance: TestCategoryTemplate;
+ let instance: TestCategoryTemplateContext;
beforeEach(() => {
const category: CategoryEntity = {
@@ -413,7 +413,7 @@ describe('CategoryTemplate', () => {
group: 'test-group',
is_income: false,
};
- instance = new TestCategoryTemplate([], category, '2024-01', 0, 0);
+ instance = new TestCategoryTemplateContext([], category, '2024-01', 0, 0);
vi.clearAllMocks();
});
@@ -430,7 +430,10 @@ describe('CategoryTemplate', () => {
.mockResolvedValueOnce(-200) // Nov 2023
.mockResolvedValueOnce(-300); // Oct 2023
- const result = await CategoryTemplate.runAverage(template, instance);
+ const result = await CategoryTemplateContext.runAverage(
+ template,
+ instance,
+ );
expect(result).toBe(200); // Average of -100, -200, -300
});
@@ -447,7 +450,10 @@ describe('CategoryTemplate', () => {
.mockResolvedValueOnce(0)
.mockResolvedValueOnce(-300);
- const result = await CategoryTemplate.runAverage(template, instance);
+ const result = await CategoryTemplateContext.runAverage(
+ template,
+ instance,
+ );
expect(result).toBe(100);
});
@@ -464,13 +470,16 @@ describe('CategoryTemplate', () => {
.mockResolvedValueOnce(200)
.mockResolvedValueOnce(-300);
- const result = await CategoryTemplate.runAverage(template, instance);
+ const result = await CategoryTemplateContext.runAverage(
+ template,
+ instance,
+ );
expect(result).toBe(67); // Average of -100, 200, -300
});
});
describe('runBy', () => {
- let instance: TestCategoryTemplate;
+ let instance: TestCategoryTemplateContext;
beforeEach(() => {
const category: CategoryEntity = {
@@ -479,7 +488,7 @@ describe('CategoryTemplate', () => {
group: 'test-group',
is_income: false,
};
- instance = new TestCategoryTemplate(
+ instance = new TestCategoryTemplateContext(
[
{
type: 'by',
@@ -504,12 +513,12 @@ describe('CategoryTemplate', () => {
});
it('should calculate monthly amount needed for multiple targets', () => {
- const result = CategoryTemplate.runBy(instance);
+ const result = CategoryTemplateContext.runBy(instance);
expect(result).toBe(66667);
});
it('should handle repeating targets', () => {
- instance = new TestCategoryTemplate(
+ instance = new TestCategoryTemplateContext(
[
{
type: 'by',
@@ -534,12 +543,12 @@ describe('CategoryTemplate', () => {
0,
);
- const result = CategoryTemplate.runBy(instance);
+ const result = CategoryTemplateContext.runBy(instance);
expect(result).toBe(83333);
});
it('should handle existing balance', () => {
- instance = new TestCategoryTemplate(
+ instance = new TestCategoryTemplateContext(
[
{
type: 'by',
@@ -562,7 +571,7 @@ describe('CategoryTemplate', () => {
0,
);
- const result = CategoryTemplate.runBy(instance);
+ const result = CategoryTemplateContext.runBy(instance);
expect(result).toBe(66500); // (1000 + 2000 - 5) / 3
});
});
@@ -589,7 +598,7 @@ describe('CategoryTemplate', () => {
priority: 1,
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -618,7 +627,7 @@ describe('CategoryTemplate', () => {
priority: 1,
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -645,7 +654,7 @@ describe('CategoryTemplate', () => {
priority: 1,
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -672,7 +681,7 @@ describe('CategoryTemplate', () => {
priority: 1,
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -699,7 +708,7 @@ describe('CategoryTemplate', () => {
directive: 'template',
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -724,7 +733,7 @@ describe('CategoryTemplate', () => {
directive: 'template',
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -749,7 +758,7 @@ describe('CategoryTemplate', () => {
directive: 'template',
},
];
- const instance = new TestCategoryTemplate(
+ const instance = new TestCategoryTemplateContext(
templates,
category,
'2024-01',
@@ -794,7 +803,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
// Initialize the template
- const instance = await CategoryTemplate.init(
+ const instance = await CategoryTemplateContext.init(
templates,
category,
'2024-01',
@@ -857,7 +866,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
// Initialize the template
- const instance = await CategoryTemplate.init(
+ const instance = await CategoryTemplateContext.init(
templates,
category,
'2024-01',
@@ -909,7 +918,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
// Initialize the template
- const instance = await CategoryTemplate.init(
+ const instance = await CategoryTemplateContext.init(
templates,
category,
'2024-01',
@@ -967,7 +976,7 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
// Initialize the template
- const instance = await CategoryTemplate.init(
+ const instance = await CategoryTemplateContext.init(
templates,
category,
'2024-01',
@@ -985,7 +994,7 @@ describe('CategoryTemplate', () => {
expect(values.budgeted).toBe(30000); // Should match the result
expect(values.goal).toBe(100000); // Should be the goal amount
expect(values.longGoal).toBe(true); // Should have a long goal
- expect(instance.getGoalOnly()).toBe(false); // Should not be goal only
+ expect(instance.isGoalOnly()).toBe(false); // Should not be goal only
});
it('should handle goal-only template through the entire process', async () => {
@@ -1008,14 +1017,14 @@ describe('CategoryTemplate', () => {
vi.mocked(actions.getSheetBoolean).mockResolvedValueOnce(false); // carryover
// Initialize the template
- const instance = await CategoryTemplate.init(
+ const instance = await CategoryTemplateContext.init(
templates,
category,
'2024-01',
10000,
);
- expect(instance.getGoalOnly()).toBe(true); // Should be goal only
+ expect(instance.isGoalOnly()).toBe(true); // Should be goal only
// Get the final values
const values = instance.getValues();
diff --git a/packages/loot-core/src/server/budget/categoryTemplate.ts b/packages/loot-core/src/server/budget/category-template-context.ts
similarity index 76%
rename from packages/loot-core/src/server/budget/categoryTemplate.ts
rename to packages/loot-core/src/server/budget/category-template-context.ts
index fd90b632ac..48791fd15c 100644
--- a/packages/loot-core/src/server/budget/categoryTemplate.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.ts
@@ -6,11 +6,22 @@ import { CategoryEntity } from '../../types/models';
import * as db from '../db';
import { getSheetValue, getSheetBoolean } from './actions';
-import { goalsSchedule } from './goalsSchedule';
+import { runSchedule } from './schedule-template';
import { getActiveSchedules } from './statements';
-import { Template } from './types/templates';
-
-export class CategoryTemplate {
+import {
+ AverageTemplate,
+ ByTemplate,
+ CopyTemplate,
+ GoalTemplate,
+ PercentageTemplate,
+ RemainderTemplate,
+ SimpleTemplate,
+ SpendTemplate,
+ Template,
+ WeekTemplate,
+} from './types/templates';
+
+export class CategoryTemplateContext {
/*----------------------------------------------------------------------------
* Using This Class:
* 1. instantiate via `await categoryTemplate.init(templates, categoryID, month)`;
@@ -33,7 +44,7 @@ export class CategoryTemplate {
static async init(
templates: Template[],
category: CategoryEntity,
- month,
+ month: string,
budgeted: number,
) {
// get all the needed setup values
@@ -58,10 +69,10 @@ export class CategoryTemplate {
fromLastMonth = lastMonthBalance;
}
// run all checks
- await CategoryTemplate.checkByAndScheduleAndSpend(templates, month);
- await CategoryTemplate.checkPercentage(templates);
+ await CategoryTemplateContext.checkByAndScheduleAndSpend(templates, month);
+ await CategoryTemplateContext.checkPercentage(templates);
// call the private constructor
- return new CategoryTemplate(
+ return new CategoryTemplateContext(
templates,
category,
month,
@@ -70,7 +81,7 @@ export class CategoryTemplate {
);
}
- getGoalOnly(): boolean {
+ isGoalOnly(): boolean {
// if there is only a goal
return (
this.templates.length === 0 &&
@@ -116,28 +127,31 @@ export class CategoryTemplate {
let remainder = 0;
let scheduleFlag = false;
// switch on template type and calculate the amount for the line
- for (let i = 0; i < t.length; i++) {
+ for (const template of t) {
let newBudget = 0;
- switch (t[i].type) {
+ switch (template.type) {
case 'simple': {
- newBudget = CategoryTemplate.runSimple(t[i], this.limitAmount);
+ newBudget = CategoryTemplateContext.runSimple(
+ template,
+ this.limitAmount,
+ );
break;
}
case 'copy': {
- newBudget = await CategoryTemplate.runCopy(t[i], this);
+ newBudget = await CategoryTemplateContext.runCopy(template, this);
break;
}
case 'week': {
- newBudget = CategoryTemplate.runWeek(t[i], this);
+ newBudget = CategoryTemplateContext.runWeek(template, this);
break;
}
case 'spend': {
- newBudget = await CategoryTemplate.runSpend(t[i], this);
+ newBudget = await CategoryTemplateContext.runSpend(template, this);
break;
}
case 'percentage': {
- newBudget = await CategoryTemplate.runPercentage(
- t[i],
+ newBudget = await CategoryTemplateContext.runPercentage(
+ template,
availStart,
this,
);
@@ -146,7 +160,7 @@ export class CategoryTemplate {
case 'by': {
// all by's get run at once
if (!byFlag) {
- newBudget = CategoryTemplate.runBy(this);
+ newBudget = CategoryTemplateContext.runBy(this);
} else {
newBudget = 0;
}
@@ -154,27 +168,28 @@ export class CategoryTemplate {
break;
}
case 'schedule': {
- const budgeted = this.fromLastMonth + toBudget;
- const ret = await goalsSchedule(
- scheduleFlag,
- t,
- this.month,
- budgeted,
- remainder,
- this.fromLastMonth,
- toBudget,
- [],
- this.category,
- );
- // Schedules assume that its to budget value is the whole thing so this
- // needs to remove the previous funds so they aren't double counted
- newBudget = ret.to_budget - toBudget;
- remainder = ret.remainder;
- scheduleFlag = ret.scheduleFlag;
+ if (!scheduleFlag) {
+ const budgeted = this.fromLastMonth + toBudget;
+ const ret = await runSchedule(
+ t,
+ this.month,
+ budgeted,
+ remainder,
+ this.fromLastMonth,
+ toBudget,
+ [],
+ this.category,
+ );
+ // Schedules assume that its to budget value is the whole thing so this
+ // needs to remove the previous funds so they aren't double counted
+ newBudget = ret.to_budget - toBudget;
+ remainder = ret.remainder;
+ scheduleFlag = true;
+ }
break;
}
case 'average': {
- newBudget = await CategoryTemplate.runAverage(t[i], this);
+ newBudget = await CategoryTemplateContext.runAverage(template, this);
break;
}
}
@@ -226,7 +241,7 @@ export class CategoryTemplate {
}
}
- getValues(): { budgeted; goal; longGoal } {
+ getValues() {
this.runGoal();
return {
budgeted: this.toBudgetAmount,
@@ -239,9 +254,9 @@ export class CategoryTemplate {
// Implementation
readonly category: CategoryEntity; //readonly so we can double check the category this is using
private month: string;
- private templates = [];
- private remainder = [];
- private goals = [];
+ private templates: Template[] = [];
+ private remainder: RemainderTemplate[] = [];
+ private goals: GoalTemplate[] = [];
private priorities: number[] = [];
private remainderWeight: number = 0;
private toBudgetAmount: number = 0; // amount that will be budgeted by the templates
@@ -280,7 +295,7 @@ export class CategoryTemplate {
}
});
templates.forEach(t => {
- if (t.directive === 'goal') this.goals.push(t);
+ if (t.directive === 'goal' && t.type === 'goal') this.goals.push(t);
});
}
// check limits here since it needs to save states inside the object
@@ -312,7 +327,7 @@ export class CategoryTemplate {
private runGoal() {
if (this.goals.length > 0) {
- if (this.getGoalOnly()) this.toBudgetAmount = this.previouslyBudgeted;
+ if (this.isGoalOnly()) this.toBudgetAmount = this.previouslyBudgeted;
this.isLongGoal = true;
this.goalAmount = amountToInteger(this.goals[0].amount);
return;
@@ -322,7 +337,10 @@ export class CategoryTemplate {
//-----------------------------------------------------------------------------
// Template Validation
- static async checkByAndScheduleAndSpend(templates, month) {
+ static async checkByAndScheduleAndSpend(
+ templates: Template[],
+ month: string,
+ ) {
if (
templates.filter(t => t.type === 'schedule' || t.type === 'by').length ===
0
@@ -352,7 +370,7 @@ export class CategoryTemplate {
.forEach(t => {
if (t.priority !== lowestPriority) {
throw new Error(
- `Schedule and By templates must be the same priority level. Fix by setting all Schedule and By templates to priority level ${lowestPriority}`,
+ `Schedule and By templates must be the same priority level. Fix by setting all Schedule and By templates to priority level ${lowestPriority}`,
);
//t.priority = lowestPriority;
}
@@ -373,7 +391,7 @@ export class CategoryTemplate {
});
}
- static async checkPercentage(templates) {
+ static async checkPercentage(templates: Template[]) {
const pt = templates.filter(t => t.type === 'percentage');
if (pt.length === 0) return;
const reqCategories = pt.map(t => t.category.toLowerCase());
@@ -395,35 +413,38 @@ export class CategoryTemplate {
}
private checkLimit() {
- for (const t of this.templates) {
- if (!t.limit) continue;
+ for (const template of this.templates
+ .filter(
+ t => t.type === 'simple' || t.type === 'week' || t.type === 'remainder',
+ )
+ .filter(t => t.limit)) {
if (this.limitCheck) {
throw new Error('Only one `up to` allowed per category');
}
- if (t.limit.period === 'daily') {
+ if (template.limit.period === 'daily') {
const numDays = monthUtils.differenceInCalendarDays(
monthUtils.addMonths(this.month, 1),
this.month,
);
- this.limitAmount += amountToInteger(t.limit.amount) * numDays;
- } else if (t.limit.period === 'weekly') {
+ this.limitAmount += amountToInteger(template.limit.amount) * numDays;
+ } else if (template.limit.period === 'weekly') {
const nextMonth = monthUtils.nextMonth(this.month);
- let week = t.limit.start;
- const baseLimit = amountToInteger(t.limit.amount);
+ let week = template.limit.start;
+ const baseLimit = amountToInteger(template.limit.amount);
while (week < nextMonth) {
if (week >= this.month) {
this.limitAmount += baseLimit;
}
week = monthUtils.addWeeks(week, 1);
}
- } else if (t.limit.period === 'monthly') {
- this.limitAmount = amountToInteger(t.limit.amount);
+ } else if (template.limit.period === 'monthly') {
+ this.limitAmount = amountToInteger(template.limit.amount);
} else {
throw new Error('Invalid limit period. Check template syntax');
}
//amount is good save the rest
this.limitCheck = true;
- this.limitHold = t.limit.hold ? true : false;
+ this.limitHold = template.limit.hold ? true : false;
// check if the limit is already met and save the excess
if (this.fromLastMonth >= this.limitAmount) {
this.limitMet = true;
@@ -456,7 +477,7 @@ export class CategoryTemplate {
//-----------------------------------------------------------------------------
// Processor Functions
- static runSimple(template, limit): number {
+ static runSimple(template: SimpleTemplate, limit: number): number {
if (template.monthly != null) {
return amountToInteger(template.monthly);
} else {
@@ -464,22 +485,31 @@ export class CategoryTemplate {
}
}
- static async runCopy(template, catObj: CategoryTemplate): Promise<number> {
+ static async runCopy(
+ template: CopyTemplate,
+ templateContext: CategoryTemplateContext,
+ ): Promise<number> {
const sheetName = monthUtils.sheetForMonth(
- monthUtils.subMonths(catObj.month, template.lookBack),
+ monthUtils.subMonths(templateContext.month, template.lookBack),
+ );
+ return await getSheetValue(
+ sheetName,
+ `budget-${templateContext.category.id}`,
);
- return await getSheetValue(sheetName, `budget-${catObj.category.id}`);
}
- static runWeek(template, catObj: CategoryTemplate): number {
+ static runWeek(
+ template: WeekTemplate,
+ templateContext: CategoryTemplateContext,
+ ): number {
let toBudget = 0;
const amount = amountToInteger(template.amount);
const weeks = template.weeks != null ? Math.round(template.weeks) : 1;
let w = template.starting;
- const nextMonth = monthUtils.addMonths(catObj.month, 1);
+ const nextMonth = monthUtils.addMonths(templateContext.month, 1);
while (w < nextMonth) {
- if (w >= catObj.month) {
+ if (w >= templateContext.month) {
toBudget += amount;
}
w = monthUtils.addWeeks(w, weeks);
@@ -487,28 +517,37 @@ export class CategoryTemplate {
return toBudget;
}
- static async runSpend(template, catObj: CategoryTemplate): Promise<number> {
+ static async runSpend(
+ template: SpendTemplate,
+ templateContext: CategoryTemplateContext,
+ ): Promise<number> {
let fromMonth = `${template.from}`;
let toMonth = `${template.month}`;
- let alreadyBudgeted = catObj.fromLastMonth;
+ let alreadyBudgeted = templateContext.fromLastMonth;
let firstMonth = true;
//update months if needed
const repeat = template.annual
? (template.repeat || 1) * 12
: template.repeat;
- let m = monthUtils.differenceInCalendarMonths(toMonth, catObj.month);
+ let m = monthUtils.differenceInCalendarMonths(
+ toMonth,
+ templateContext.month,
+ );
if (repeat && m < 0) {
while (m < 0) {
toMonth = monthUtils.addMonths(toMonth, repeat);
fromMonth = monthUtils.addMonths(fromMonth, repeat);
- m = monthUtils.differenceInCalendarMonths(toMonth, catObj.month);
+ m = monthUtils.differenceInCalendarMonths(
+ toMonth,
+ templateContext.month,
+ );
}
}
for (
let m = fromMonth;
- monthUtils.differenceInCalendarMonths(catObj.month, m) > 0;
+ monthUtils.differenceInCalendarMonths(templateContext.month, m) > 0;
m = monthUtils.addMonths(m, 1)
) {
const sheetName = monthUtils.sheetForMonth(m);
@@ -516,25 +555,25 @@ export class CategoryTemplate {
//TODO figure out if I already found these values and can pass them in
const spent = await getSheetValue(
sheetName,
- `sum-amount-${catObj.category.id}`,
+ `sum-amount-${templateContext.category.id}`,
);
const balance = await getSheetValue(
sheetName,
- `leftover-${catObj.category.id}`,
+ `leftover-${templateContext.category.id}`,
);
alreadyBudgeted = balance - spent;
firstMonth = false;
} else {
alreadyBudgeted += await getSheetValue(
sheetName,
- `budget-${catObj.category.id}`,
+ `budget-${templateContext.category.id}`,
);
}
}
const numMonths = monthUtils.differenceInCalendarMonths(
toMonth,
- catObj.month,
+ templateContext.month,
);
const target = amountToInteger(template.amount);
if (numMonths < 0) {
@@ -545,9 +584,9 @@ export class CategoryTemplate {
}
static async runPercentage(
- template,
- availableFunds,
- catObj: CategoryTemplate,
+ template: PercentageTemplate,
+ availableFunds: number,
+ templateContext: CategoryTemplateContext,
): Promise<number> {
const percent = template.percent;
const cat = template.category.toLowerCase();
@@ -558,10 +597,10 @@ export class CategoryTemplate {
//choose the sheet to find income for
if (prev) {
sheetName = monthUtils.sheetForMonth(
- monthUtils.subMonths(catObj.month, 1),
+ monthUtils.subMonths(templateContext.month, 1),
);
} else {
- sheetName = monthUtils.sheetForMonth(catObj.month);
+ sheetName = monthUtils.sheetForMonth(templateContext.month);
}
if (cat === 'all income') {
monthlyIncome = await getSheetValue(sheetName, `total-income`);
@@ -580,19 +619,27 @@ export class CategoryTemplate {
return Math.max(0, Math.round(monthlyIncome * (percent / 100)));
}
- static async runAverage(template, catObj: CategoryTemplate): Promise<number> {
+ static async runAverage(
+ template: AverageTemplate,
+ templateContext: CategoryTemplateContext,
+ ): Promise<number> {
let sum = 0;
for (let i = 1; i <= template.numMonths; i++) {
const sheetName = monthUtils.sheetForMonth(
- monthUtils.subMonths(catObj.month, i),
+ monthUtils.subMonths(templateContext.month, i),
+ );
+ sum += await getSheetValue(
+ sheetName,
+ `sum-amount-${templateContext.category.id}`,
);
- sum += await getSheetValue(sheetName, `sum-amount-${catObj.category.id}`);
}
return -Math.round(sum / template.numMonths);
}
- static runBy(catObj: CategoryTemplate): number {
- const byTemplates = catObj.templates.filter(t => t.type === 'by');
+ static runBy(templateContext: CategoryTemplateContext): number {
+ const byTemplates: ByTemplate[] = templateContext.templates.filter(
+ t => t.type === 'by',
+ );
const savedInfo = [];
let totalNeeded = 0;
let shortNumMonths;
@@ -607,13 +654,13 @@ export class CategoryTemplate {
: null;
let numMonths = monthUtils.differenceInCalendarMonths(
targetMonth,
- catObj.month,
+ templateContext.month,
);
while (numMonths < 0 && period) {
targetMonth = monthUtils.addMonths(targetMonth, period);
numMonths = monthUtils.differenceInCalendarMonths(
targetMonth,
- catObj.month,
+ templateContext.month,
);
}
savedInfo.push({ numMonths, period });
@@ -646,7 +693,7 @@ export class CategoryTemplate {
totalNeeded += amount;
}
return Math.round(
- (totalNeeded - catObj.fromLastMonth) / (shortNumMonths + 1),
+ (totalNeeded - templateContext.fromLastMonth) / (shortNumMonths + 1),
);
}
}
diff --git a/packages/loot-core/src/server/budget/goal-template.ts b/packages/loot-core/src/server/budget/goal-template.ts
new file mode 100644
index 0000000000..0ae11ecc88
--- /dev/null
+++ b/packages/loot-core/src/server/budget/goal-template.ts
@@ -0,0 +1,280 @@
+// @ts-strict-ignore
+import * as monthUtils from '../../shared/months';
+import { q } from '../../shared/query';
+import { CategoryEntity, CategoryGroupEntity } from '../../types/models';
+import { aqlQuery } from '../aql';
+import { batchMessages } from '../sync';
+
+import { isReflectBudget, getSheetValue, setGoal, setBudget } from './actions';
+import { CategoryTemplateContext } from './category-template-context';
+import { checkTemplates, storeTemplates } from './template-notes';
+import { Template } from './types/templates';
+
+type Notification = {
+ type?: 'message' | 'error' | 'warning' | undefined;
+ pre?: string | undefined;
+ title?: string | undefined;
+ message: string;
+ sticky?: boolean | undefined;
+};
+
+export async function applyTemplate({
+ month,
+}: {
+ month: string;
+}): Promise<Notification> {
+ await storeTemplates();
+ const categoryTemplates = await getTemplates();
+ const ret = await processTemplate(month, false, categoryTemplates);
+ return ret;
+}
+
+export async function overwriteTemplate({
+ month,
+}: {
+ month: string;
+}): Promise<Notification> {
+ await storeTemplates();
+ const categoryTemplates = await getTemplates();
+ const ret = await processTemplate(month, true, categoryTemplates);
+ return ret;
+}
+
+export async function applyMultipleCategoryTemplates({
+ month,
+ categoryIds,
+}: {
+ month: string;
+ categoryIds: Array<CategoryEntity['id']>;
+}) {
+ const { data: categoryData }: { data: CategoryEntity[] } = await aqlQuery(
+ q('categories').filter({ $oneof: categoryIds }).select('*'),
+ );
+ await storeTemplates();
+ const categoryTemplates = await getTemplates(c => categoryIds.includes(c.id));
+ const ret = await processTemplate(
+ month,
+ true,
+ categoryTemplates,
+ categoryData,
+ );
+ return ret;
+}
+
+export async function applySingleCategoryTemplate({
+ month,
+ category,
+}: {
+ month: string;
+ category: CategoryEntity['id'];
+}) {
+ const { data: categoryData }: { data: CategoryEntity[] } = await aqlQuery(
+ q('categories').filter({ id: category }).select('*'),
+ );
+ await storeTemplates();
+ const categoryTemplates = await getTemplates(c => c.id === category);
+ const ret = await processTemplate(
+ month,
+ true,
+ categoryTemplates,
+ categoryData,
+ );
+ return ret;
+}
+
+export function runCheckTemplates() {
+ return checkTemplates();
+}
+
+async function getCategories(): Promise<CategoryEntity[]> {
+ const { data: categoryGroups }: { data: CategoryGroupEntity[] } =
+ await aqlQuery(q('category_groups').filter({ hidden: false }).select('*'));
+
+ return categoryGroups.flatMap(g => g.categories || []).filter(c => !c.hidden);
+}
+
+async function getTemplates(
+ filter: (category: CategoryEntity) => boolean = () => true,
+): Promise<Record<CategoryEntity['id'], Template[]>> {
+ //retrieves template definitions from the database
+ const { data: categoriesWithGoalDef }: { data: CategoryEntity[] } =
+ await aqlQuery(
+ q('categories')
+ .filter({ goal_def: { $ne: null } })
+ .select('*'),
+ );
+
+ const categoryTemplates: Record<CategoryEntity['id'], Template[]> = {};
+ for (const categoryWithGoalDef of categoriesWithGoalDef.filter(filter)) {
+ categoryTemplates[categoryWithGoalDef.id] = JSON.parse(
+ categoryWithGoalDef.goal_def,
+ );
+ }
+ return categoryTemplates;
+}
+
+type TemplateBudget = {
+ category: CategoryEntity['id'];
+ budgeted: number;
+};
+
+async function setBudgets(month: string, templateBudget: TemplateBudget[]) {
+ await batchMessages(async () => {
+ templateBudget.forEach(element => {
+ setBudget({
+ category: element.category,
+ month,
+ amount: element.budgeted,
+ });
+ });
+ });
+}
+
+type TemplateGoal = {
+ category: CategoryEntity['id'];
+ goal: number | null;
+ longGoal: number | null;
+};
+
+async function setGoals(month: string, templateGoal: TemplateGoal[]) {
+ await batchMessages(async () => {
+ templateGoal.forEach(element => {
+ setGoal({
+ month,
+ category: element.category,
+ goal: element.goal,
+ long_goal: element.longGoal,
+ });
+ });
+ });
+}
+
+async function processTemplate(
+ month: string,
+ force: boolean,
+ categoryTemplates: Record<CategoryEntity['id'], Template[]>,
+ categories: CategoryEntity[] = [],
+): Promise<Notification> {
+ // setup categories
+ if (!categories.length) {
+ const isReflect = isReflectBudget();
+ categories = (await getCategories()).filter(c => isReflect || !c.is_income);
+ }
+
+ // setup categories to process
+ const templateContexts: CategoryTemplateContext[] = [];
+ let availBudget = await getSheetValue(
+ monthUtils.sheetForMonth(month),
+ `to-budget`,
+ );
+ let priorities: number[] = [];
+ let remainderWeight = 0;
+ const errors: string[] = [];
+ const budgetList: TemplateBudget[] = [];
+ const goalList: TemplateGoal[] = [];
+ for (const category of categories) {
+ const { id } = category;
+ const sheetName = monthUtils.sheetForMonth(month);
+ const templates = categoryTemplates[id];
+ const budgeted = await getSheetValue(sheetName, `budget-${id}`);
+ const existingGoal = await getSheetValue(sheetName, `goal-${id}`);
+
+ // only run categories that are unbudgeted or if we are forcing it
+ if ((budgeted === 0 || force) && templates) {
+ // add to available budget
+ // gather needed priorities
+ // gather remainder weights
+ try {
+ const templateContext = await CategoryTemplateContext.init(
+ templates,
+ category,
+ month,
+ budgeted,
+ );
+ // don't use the funds that are not from templates
+ if (!templateContext.isGoalOnly()) {
+ availBudget += budgeted;
+ }
+ availBudget += templateContext.getLimitExcess();
+ priorities = [...priorities, ...templateContext.getPriorities()];
+ remainderWeight += templateContext.getRemainderWeight();
+ templateContexts.push(templateContext);
+ } catch (e) {
+ errors.push(`${category.name}: ${e.message}`);
+ }
+
+ // do a reset of the goals that are orphaned
+ } else if (existingGoal !== null && !templates) {
+ goalList.push({
+ category: id,
+ goal: null,
+ longGoal: null,
+ });
+ }
+ }
+
+ //break early if nothing to do, or there are errors
+ if (templateContexts.length === 0 && errors.length === 0) {
+ if (goalList.length > 0) {
+ setGoals(month, goalList);
+ }
+ return {
+ type: 'message',
+ message: 'Everything is up to date',
+ };
+ }
+ if (errors.length > 0) {
+ return {
+ sticky: true,
+ message: 'There were errors interpreting some templates:',
+ pre: errors.join(`\n\n`),
+ };
+ }
+
+ //compress to needed, sorted priorities
+ priorities = priorities
+ .sort((a, b) => {
+ return a - b;
+ })
+ .filter((item, idx, curr) => curr.indexOf(item) === idx);
+
+ // run each priority level
+ for (const priority of priorities) {
+ const availStart = availBudget;
+ for (const templateContext of templateContexts) {
+ const budget = await templateContext.runTemplatesForPriority(
+ priority,
+ availBudget,
+ availStart,
+ );
+ availBudget -= budget;
+ }
+ }
+ // run remainder
+ if (availBudget > 0 && remainderWeight) {
+ const perWeight = availBudget / remainderWeight;
+ templateContexts.forEach(context => {
+ availBudget -= context.runRemainder(availBudget, perWeight);
+ });
+ }
+ // finish
+ templateContexts.forEach(context => {
+ const values = context.getValues();
+ budgetList.push({
+ category: context.category.id,
+ budgeted: values.budgeted,
+ });
+ goalList.push({
+ category: context.category.id,
+ goal: values.goal,
+ longGoal: values.longGoal ? 1 : null,
+ });
+ });
+ await setBudgets(month, budgetList);
+ await setGoals(month, goalList);
+
+ return {
+ type: 'message',
+ message: `Successfully applied templates to ${templateContexts.length} categories`,
+ };
+}
diff --git a/packages/loot-core/src/server/budget/goaltemplates.ts b/packages/loot-core/src/server/budget/goaltemplates.ts
deleted file mode 100644
index 291fb26676..0000000000
--- a/packages/loot-core/src/server/budget/goaltemplates.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-// @ts-strict-ignore
-import * as monthUtils from '../../shared/months';
-import * as db from '../db';
-import { batchMessages } from '../sync';
-
-import { isReflectBudget, getSheetValue, setGoal, setBudget } from './actions';
-import { CategoryTemplate } from './categoryTemplate';
-import { checkTemplates, storeTemplates } from './template-notes';
-
-type Notification = {
- type?: 'message' | 'error' | 'warning' | undefined;
- pre?: string | undefined;
- title?: string | undefined;
- message: string;
- sticky?: boolean | undefined;
-};
-
-export async function applyTemplate({ month }): Promise<Notification> {
- await storeTemplates();
- const categoryTemplates = await getTemplates(null);
- const ret = await processTemplate(month, false, categoryTemplates, null);
- return ret;
-}
-
-export async function overwriteTemplate({ month }): Promise<Notification> {
- await storeTemplates();
- const categoryTemplates = await getTemplates(null);
- const ret = await processTemplate(month, true, categoryTemplates, null);
- return ret;
-}
-
-export async function applyMultipleCategoryTemplates({ month, categoryIds }) {
- const placeholders = categoryIds.map(() => '?').join(', ');
- const query = `SELECT * FROM v_categories WHERE id IN (${placeholders})`;
- const categories = await db.all<db.DbViewCategory>(query, categoryIds);
- await storeTemplates();
- const categoryTemplates = await getTemplates(categories);
- const ret = await processTemplate(month, true, categoryTemplates, categories);
- return ret;
-}
-
-export async function applySingleCategoryTemplate({ month, category }) {
- const categories = await db.all<db.DbViewCategory>(
- `SELECT * FROM v_categories WHERE id = ?`,
- [category],
- );
- await storeTemplates();
- const categoryTemplates = await getTemplates(categories[0]);
- const ret = await processTemplate(month, true, categoryTemplates, categories);
- return ret;
-}
-
-export function runCheckTemplates() {
- return checkTemplates();
-}
-
-async function getCategories(): Promise<db.DbCategory[]> {
- return await db.all<db.DbCategory>(
- `
- SELECT categories.* FROM categories
- INNER JOIN category_groups on categories.cat_group = category_groups.id
- WHERE categories.tombstone = 0 AND categories.hidden = 0
- AND category_groups.hidden = 0
- `,
- );
-}
-
-async function getTemplates(category) {
- //retrieves template definitions from the database
- const goalDef = await db.all<db.DbCategory>(
- 'SELECT * FROM categories WHERE goal_def IS NOT NULL',
- );
-
- const templates = [];
- for (let ll = 0; ll < goalDef.length; ll++) {
- templates[goalDef[ll].id] = JSON.parse(goalDef[ll].goal_def);
- }
- if (Array.isArray(category)) {
- const multipleCategoryTemplates = [];
- for (let dd = 0; dd < category.length; dd++) {
- const categoryId = category[dd].id;
- if (templates[categoryId] !== undefined) {
- multipleCategoryTemplates[categoryId] = templates[categoryId];
- }
- }
- return multipleCategoryTemplates;
- } else if (category) {
- const ret = [];
- ret[category.id] = templates[category.id];
- return ret;
- } else {
- 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];
- }
- }
- return ret;
- }
-}
-
-async function setBudgets(month, templateBudget) {
- await batchMessages(async () => {
- templateBudget.forEach(element => {
- setBudget({
- category: element.category,
- month,
- amount: element.budgeted,
- });
- });
- });
-}
-
-async function setGoals(month, idealTemplate) {
- await batchMessages(async () => {
- idealTemplate.forEach(element => {
- setGoal({
- month,
- category: element.category,
- goal: element.goal,
- long_goal: element.longGoal,
- });
- });
- });
-}
-
-async function processTemplate(
- month,
- force: boolean,
- categoryTemplates,
- categoriesIn?,
-): Promise<Notification> {
- // setup categories
- let categories = [];
- if (!categoriesIn) {
- const isReflect = isReflectBudget();
- const categoriesLong = await getCategories();
- categoriesLong.forEach(c => {
- if (isReflect || !c.is_income) {
- categories.push(c);
- }
- });
- } else {
- categories = categoriesIn;
- }
-
- // setup categories to process
- const catObjects: CategoryTemplate[] = [];
- let availBudget = await getSheetValue(
- monthUtils.sheetForMonth(month),
- `to-budget`,
- );
- let priorities = [];
- let remainderWeight = 0;
- const errors = [];
- const budgetList = [];
- const goalList = [];
- for (let i = 0; i < categories.length; i++) {
- const category = categories[i];
- const { id } = category;
- const sheetName = monthUtils.sheetForMonth(month);
- const templates = categoryTemplates[id];
- const budgeted = await getSheetValue(sheetName, `budget-${id}`);
- const existingGoal = await getSheetValue(sheetName, `goal-${id}`);
-
- // only run categories that are unbudgeted or if we are forcing it
- if ((budgeted === 0 || force) && templates) {
- // add to available budget
- // gather needed priorities
- // gather remainder weights
- try {
- const obj = await CategoryTemplate.init(
- templates,
- category,
- month,
- budgeted,
- );
- // don't use the funds that are not from templates
- if (!obj.getGoalOnly()) {
- availBudget += budgeted;
- }
- availBudget += obj.getLimitExcess();
- const p = obj.getPriorities();
- p.forEach(pr => priorities.push(pr));
- remainderWeight += obj.getRemainderWeight();
- catObjects.push(obj);
- } catch (e) {
- errors.push(`${categories[i].name}: ${e.message}`);
- }
-
- // do a reset of the goals that are orphaned
- } else if (existingGoal !== null && !templates) {
- goalList.push({
- category: id,
- goal: null,
- longGoal: null,
- });
- }
- }
-
- //break early if nothing to do, or there are errors
- if (catObjects.length === 0 && errors.length === 0) {
- if (goalList.length > 0) {
- setGoals(month, goalList);
- }
- return {
- type: 'message',
- message: 'Everything is up to date',
- };
- }
- if (errors.length > 0) {
- return {
- sticky: true,
- message: 'There were errors interpreting some templates:',
- pre: errors.join(`\n\n`),
- };
- }
-
- //compress to needed, sorted priorities
- priorities = priorities
- .sort((a, b) => {
- return a - b;
- })
- .filter((item, idx, curr) => curr.indexOf(item) === idx);
-
- // run each priority level
- for (let pi = 0; pi < priorities.length; pi++) {
- const availStart = availBudget;
- const p = priorities[pi];
- for (let i = 0; i < catObjects.length; i++) {
- const ret = await catObjects[i].runTemplatesForPriority(
- p,
- availBudget,
- availStart,
- );
- availBudget -= ret;
- }
- }
- // run remainder
- if (availBudget > 0 && remainderWeight) {
- const perWeight = availBudget / remainderWeight;
- catObjects.forEach(o => {
- availBudget -= o.runRemainder(availBudget, perWeight);
- });
- }
- // finish
- catObjects.forEach(o => {
- const ret = o.getValues();
- budgetList.push({ category: o.category.id, budgeted: ret.budgeted });
- goalList.push({
- category: o.category.id,
- goal: ret.goal,
- longGoal: ret.longGoal ? 1 : null,
- });
- });
- await setBudgets(month, budgetList);
- await setGoals(month, goalList);
-
- return {
- type: 'message',
- message: `Successfully applied templates to ${catObjects.length} categories`,
- };
-}
diff --git a/packages/loot-core/src/server/budget/goalsSchedule.test.ts b/packages/loot-core/src/server/budget/schedule-template.test.ts
similarity index 91%
rename from packages/loot-core/src/server/budget/goalsSchedule.test.ts
rename to packages/loot-core/src/server/budget/schedule-template.test.ts
index cd51008ab4..2ae52536ce 100644
--- a/packages/loot-core/src/server/budget/goalsSchedule.test.ts
+++ b/packages/loot-core/src/server/budget/schedule-template.test.ts
@@ -4,7 +4,7 @@ import { Rule } from '../rules';
import { getRuleForSchedule } from '../schedules/app';
import { isReflectBudget } from './actions';
-import { goalsSchedule } from './goalsSchedule';
+import { runSchedule } from './schedule-template';
vi.mock('../db');
vi.mock('./actions');
@@ -16,14 +16,13 @@ vi.mock('../schedules/app', async () => {
};
});
-describe('goalsSchedule', () => {
+describe('runSchedule', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should return correct budget when recurring schedule set', async () => {
// Given
- const scheduleFlag = false;
const template_lines = [
{
type: 'schedule',
@@ -75,8 +74,7 @@ describe('goalsSchedule', () => {
vi.mocked(isReflectBudget).mockReturnValue(false);
// When
- const result = await goalsSchedule(
- scheduleFlag,
+ const result = await runSchedule(
template_lines,
current_month,
balance,
@@ -91,12 +89,10 @@ describe('goalsSchedule', () => {
expect(result.to_budget).toBe(10000);
expect(result.errors).toHaveLength(0);
expect(result.remainder).toBe(0);
- expect(result.scheduleFlag).toBe(true);
});
it('should return correct budget when yearly recurring schedule set and balance is greater than target', async () => {
// Given
- const scheduleFlag = false;
const template_lines = [
{
type: 'schedule',
@@ -148,8 +144,7 @@ describe('goalsSchedule', () => {
vi.mocked(isReflectBudget).mockReturnValue(false);
// When
- const result = await goalsSchedule(
- scheduleFlag,
+ const result = await runSchedule(
template_lines,
current_month,
balance,
@@ -164,6 +159,5 @@ describe('goalsSchedule', () => {
expect(result.to_budget).toBe(1000);
expect(result.errors).toHaveLength(0);
expect(result.remainder).toBe(0);
- expect(result.scheduleFlag).toBe(true);
});
});
diff --git a/packages/loot-core/src/server/budget/goalsSchedule.ts b/packages/loot-core/src/server/budget/schedule-template.ts
similarity index 62%
rename from packages/loot-core/src/server/budget/goalsSchedule.ts
rename to packages/loot-core/src/server/budget/schedule-template.ts
index 57b2027bfc..f1881aa64a 100644
--- a/packages/loot-core/src/server/budget/goalsSchedule.ts
+++ b/packages/loot-core/src/server/budget/schedule-template.ts
@@ -12,20 +12,32 @@ import { getRuleForSchedule } from '../schedules/app';
import { isReflectBudget } from './actions';
import { ScheduleTemplate, Template } from './types/templates';
+type ScheduleTemplateTarget = {
+ name: string;
+ target: number;
+ next_date_string: string;
+ target_interval: number;
+ target_frequency: string;
+ num_months: number;
+ completed: number;
+ full: boolean;
+ repeat: boolean;
+};
+
async function createScheduleList(
- template: ScheduleTemplate[],
+ templates: ScheduleTemplate[],
current_month: string,
category: CategoryEntity,
) {
- const t = [];
- const errors = [];
+ const t: Array<ScheduleTemplateTarget> = [];
+ const errors: string[] = [];
- for (let ll = 0; ll < template.length; ll++) {
- const { id: sid, completed: complete } = await db.first<
+ for (const template of templates) {
+ const { id: sid, completed } = await db.first<
Pick<db.DbSchedule, 'id' | 'completed'>
>(
'SELECT id, completed FROM schedules WHERE TRIM(name) = ? AND tombstone = 0',
- [template[ll].name.trim()],
+ [template.name],
);
const rule = await getRuleForSchedule(sid);
const conditions = rule.serialize().conditions;
@@ -37,8 +49,8 @@ async function createScheduleList(
2
: amountCondition.value;
// Apply adjustment percentage if specified
- if (template[ll].adjustment) {
- const adjustmentFactor = 1 + template[ll].adjustment / 100;
+ if (template.adjustment) {
+ const adjustmentFactor = 1 + template.adjustment / 100;
scheduleAmount = Math.round(scheduleAmount * adjustmentFactor);
}
const { amount: postRuleAmount, subtransactions } = rule.execActions({
@@ -75,7 +87,7 @@ async function createScheduleList(
);
if (num_months < 0) {
//non-repeating schedules could be negative
- errors.push(`Schedule ${template[ll].name} is in the Past.`);
+ errors.push(`Schedule ${template.name} is in the Past.`);
} else {
t.push({
target,
@@ -83,13 +95,13 @@ async function createScheduleList(
target_interval,
target_frequency,
num_months,
- completed: complete,
+ completed,
//started,
- full: template[ll].full === null ? false : template[ll].full,
+ full: template.full === null ? false : template.full,
repeat: isRepeating,
- name: template[ll].name,
+ name: template.name,
});
- if (!complete) {
+ if (!completed) {
if (isRepeating) {
let monthlyTarget = 0;
const nextMonth = monthUtils.addMonths(
@@ -139,7 +151,7 @@ async function createScheduleList(
}
} else {
errors.push(
- `Schedule ${t[ll].name} is not active during the month in question.`,
+ `Schedule ${template.name} is not active during the month in question.`,
);
}
}
@@ -147,22 +159,28 @@ async function createScheduleList(
return { t: t.filter(c => c.completed === 0), errors };
}
-async function getPayMonthOfTotal(t) {
+async function getPayMonthOfTotal(t: ScheduleTemplateTarget[]) {
//return the contribution amounts of full or every month type schedules
let total = 0;
const schedules = t.filter(c => c.num_months === 0);
- for (let ll = 0; ll < schedules.length; ll++) {
- total += schedules[ll].target;
+ for (const schedule of schedules) {
+ total += schedule.target;
}
return total;
}
-async function getSinkingContributionTotal(t, remainder, last_month_balance) {
+async function getSinkingContributionTotal(
+ t: ScheduleTemplateTarget[],
+ remainder: number,
+ last_month_balance: number,
+) {
//return the contribution amount if there is a balance carried in the category
let total = 0;
- for (let ll = 0; ll < t.length; ll++) {
+ for (const [index, schedule] of t.entries()) {
remainder =
- ll === 0 ? t[ll].target - last_month_balance : t[ll].target - remainder;
+ index === 0
+ ? schedule.target - last_month_balance
+ : schedule.target - remainder;
let tg = 0;
if (remainder >= 0) {
tg = remainder;
@@ -171,17 +189,17 @@ async function getSinkingContributionTotal(t, remainder, last_month_balance) {
tg = 0;
remainder = Math.abs(remainder);
}
- total += tg / (t[ll].num_months + 1);
+ total += tg / (schedule.num_months + 1);
}
return total;
}
-async function getSinkingBaseContributionTotal(t) {
+async function getSinkingBaseContributionTotal(t: ScheduleTemplateTarget[]) {
//return only the base contribution of each schedule
let total = 0;
- for (let ll = 0; ll < t.length; ll++) {
- let monthlyAmount = t[ll].target / t[ll].target_interval;
- if (t[ll].target_frequency === 'yearly') {
+ for (const schedule of t) {
+ let monthlyAmount = schedule.target / schedule.target_interval;
+ if (schedule.target_frequency === 'yearly') {
monthlyAmount /= 12;
}
total += monthlyAmount;
@@ -189,17 +207,16 @@ async function getSinkingBaseContributionTotal(t) {
return total;
}
-async function getSinkingTotal(t) {
+async function getSinkingTotal(t: ScheduleTemplateTarget[]) {
//sum the total of all upcoming schedules
let total = 0;
- for (let ll = 0; ll < t.length; ll++) {
- total += t[ll].target;
+ for (const schedule of t) {
+ total += schedule.target;
}
return total;
}
-export async function goalsSchedule(
- scheduleFlag: boolean,
+export async function runSchedule(
template_lines: Template[],
current_month: string,
balance: number,
@@ -209,54 +226,51 @@ export async function goalsSchedule(
errors: string[],
category: CategoryEntity,
) {
- if (!scheduleFlag) {
- scheduleFlag = true;
- const scheduleTemplates = template_lines.filter(t => t.type === 'schedule');
- //in the case of multiple templates per category, schedules may have wrong priority level
+ const scheduleTemplates = template_lines.filter(t => t.type === 'schedule');
+ //in the case of multiple templates per category, schedules may have wrong priority level
- const t = await createScheduleList(
- scheduleTemplates,
- current_month,
- category,
- );
- errors = errors.concat(t.errors);
+ const t = await createScheduleList(
+ scheduleTemplates,
+ current_month,
+ category,
+ );
+ errors = errors.concat(t.errors);
- const isPayMonthOf = c =>
- c.full ||
- (c.target_frequency === 'monthly' &&
- c.target_interval === 1 &&
- c.num_months === 0) ||
- (c.target_frequency === 'weekly' &&
- c.target_interval >= 0 &&
- c.num_months === 0) ||
- c.target_frequency === 'daily' ||
- isReflectBudget();
+ const isPayMonthOf = c =>
+ c.full ||
+ (c.target_frequency === 'monthly' &&
+ c.target_interval === 1 &&
+ c.num_months === 0) ||
+ (c.target_frequency === 'weekly' &&
+ c.target_interval >= 0 &&
+ c.num_months === 0) ||
+ c.target_frequency === 'daily' ||
+ isReflectBudget();
- const t_payMonthOf = t.t.filter(isPayMonthOf);
- const t_sinking = t.t
- .filter(c => !isPayMonthOf(c))
- .sort((a, b) => a.next_date_string.localeCompare(b.next_date_string));
- const totalPayMonthOf = await getPayMonthOfTotal(t_payMonthOf);
- const totalSinking = await getSinkingTotal(t_sinking);
- const totalSinkingBaseContribution =
- await getSinkingBaseContributionTotal(t_sinking);
+ const t_payMonthOf = t.t.filter(isPayMonthOf);
+ const t_sinking = t.t
+ .filter(c => !isPayMonthOf(c))
+ .sort((a, b) => a.next_date_string.localeCompare(b.next_date_string));
+ const totalPayMonthOf = await getPayMonthOfTotal(t_payMonthOf);
+ const totalSinking = await getSinkingTotal(t_sinking);
+ const totalSinkingBaseContribution =
+ await getSinkingBaseContributionTotal(t_sinking);
- if (balance >= totalSinking + totalPayMonthOf) {
- to_budget += Math.round(totalPayMonthOf + totalSinkingBaseContribution);
+ if (balance >= totalSinking + totalPayMonthOf) {
+ to_budget += Math.round(totalPayMonthOf + totalSinkingBaseContribution);
+ } else {
+ const totalSinkingContribution = await getSinkingContributionTotal(
+ t_sinking,
+ remainder,
+ last_month_balance,
+ );
+ if (t_sinking.length === 0) {
+ to_budget +=
+ Math.round(totalPayMonthOf + totalSinkingContribution) -
+ last_month_balance;
} else {
- const totalSinkingContribution = await getSinkingContributionTotal(
- t_sinking,
- remainder,
- last_month_balance,
- );
- if (t_sinking.length === 0) {
- to_budget +=
- Math.round(totalPayMonthOf + totalSinkingContribution) -
- last_month_balance;
- } else {
- to_budget += Math.round(totalPayMonthOf + totalSinkingContribution);
- }
+ to_budget += Math.round(totalPayMonthOf + totalSinkingContribution);
}
}
- return { to_budget, errors, remainder, scheduleFlag };
+ return { to_budget, errors, remainder };
}
diff --git a/packages/loot-core/src/server/budget/types/templates.d.ts b/packages/loot-core/src/server/budget/types/templates.d.ts
index 50ba2ea7c5..8cfeddfbc3 100644
--- a/packages/loot-core/src/server/budget/types/templates.d.ts
+++ b/packages/loot-core/src/server/budget/types/templates.d.ts
@@ -38,7 +38,8 @@ interface SpendTemplate extends BaseTemplate {
amount: number;
month: string;
from: string;
- repeat?: { annual: boolean; repeat?: number };
+ annual?: boolean;
+ repeat?: number;
}
interface SimpleTemplate extends BaseTemplate {
diff --git a/upcoming-release-notes/4986.md b/upcoming-release-notes/4986.md
new file mode 100644
index 0000000000..3f0228d5c6
--- /dev/null
+++ b/upcoming-release-notes/4986.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [joel-jeremy]
+---
+
+Add types to budget template files and some cleanup