Compare commits

...

3 Commits

5 changed files with 117 additions and 42 deletions

View File

@ -3,52 +3,114 @@ import { format } from 'date-fns';
import { checkEnv } from './lib/env.js';
import * as actual from './lib/actual.js';
import { addFromFrequency } from './lib/dates.js';
import chalk from 'chalk';
checkEnv([
'BUDGET_INCOME_NAME',
'BUDGET_OUTCOME_NAME',
]);
const [month = format(new Date(), 'yyyy-MM')] = process.argv.slice(2);
const schedules = await actual.getSchedules();
let totalOutcome = 0;
let totalIncome = 0;
for (const s of schedules) {
// TODO: get end
if (s._date.start.slice(0, 7) > month) {
console.log(`Skipping ${s.name} cause not in range`);
continue;
}
let date = s._date.start.slice(0, 7);
while (date < month) {
date = addFromFrequency(date, s._date.frequency);
}
if (date !== month) {
console.log(`Skipping ${s.name} cause not this month`);
continue;
}
if (s._amount > 0) {
totalIncome += s._amount;
} else {
totalOutcome += Math.abs(s._amount);
}
}
console.log(`\nTotal income: +${totalIncome / 100}`);
console.log(`Total outcome: -${totalOutcome / 100}\n`);
const categories = await actual.getCategories();
const incomeCategory = categories.find(c => c.name === process.env.BUDGET_INCOME_NAME);
const outcomeCategory = categories.find(c => c.name === process.env.BUDGET_OUTCOME_NAME);
if (incomeCategory) {
actual.setBudgetAmount(month, incomeCategory.id, totalIncome);
}
if (outcomeCategory) {
actual.setBudgetAmount(month, outcomeCategory.id, totalOutcome);
console.log();
if (process.env.DRY_RUN) {
console.log(chalk.grey.bold('Running in dry run mode\n'));
}
const [month = format(new Date(), 'yyyy-MM')] = process.argv.slice(2);
const amountFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
function formatAmount(amount) {
return chalk.bold(amountFormatter.format(Math.abs(amount / 100)));
}
function formatSchedule(s, c) {
const operator = s._amountOp === 'isapprox' ? '~ ' : '';
let meta = formatAmount(s._amount);
if (s._date.frequency) {
meta += ` - ${s._date.frequency}`;
}
if (c?.name) {
meta += ` - ${c.name}`;
}
return `${chalk.underline(s.name)} (${operator}${meta})`;
}
const schedules = await actual.getSchedules();
const categoriesTotal = new Map();
let totalOutcome = 0;
let totalIncome = 0;
for (const s of schedules) {
if (s.completed) {
console.log(chalk.grey(`- ${formatSchedule(s)}: completed`));
continue;
}
const start = (typeof s._date === 'string' ? s._date : s._date.start).slice(0, 7);
if (start > month) {
console.log(chalk.grey(`- ${formatSchedule(s)}: not in range`));
continue;
}
if (s.name === "Etalis - Téléphone") {
console.log(s);
}
let date = start;
if (typeof s._date === 'object') {
let occurrences = 0;
while (date < month && occurrences <= s._date.endOccurrences) {
if (s._date.endMode !== 'never') {
occurrences += 1;
}
date = addFromFrequency(date, s._date.frequency, s._date.interval);
}
}
if (date !== month) {
console.log(chalk.grey(`- ${formatSchedule(s)}: not the specified month`));
continue;
}
const amount = Math.abs(s._amount);
let categoryId = s._actions.find((a) => a.field === 'category' && a.op === 'set')?.value;
if (!categoryId) {
console.log(chalk.yellow(` ${formatSchedule(s)}: falling back on default`));
categoryId = (s._amount > 0 ? incomeCategory?.id : outcomeCategory?.id);
}
if (!categoryId) {
console.log(chalk.red(`- ${formatSchedule(s)}: no category found`));
continue;
}
if (s._amount > 0) {
totalIncome += amount;
} else {
totalOutcome += amount;
}
categoriesTotal.set(categoryId, (categoriesTotal.get(categoryId) || 0) + amount);
console.log(chalk.green(`+ ${formatSchedule(s, categories.find((c) => c.id === categoryId))}`));
}
console.log(chalk.bgBlue(`\nTotal income: +${formatAmount(totalIncome)}\nTotal outcome: -${formatAmount(totalOutcome)}\n`));
console.log(`Budgets for ${month}: `);
for (const [id, total] of categoriesTotal) {
const category = categories.find((c) => c.id === id);
if (!category) {
console.log(chalk.red(`Category ${id} not found`));
continue;
}
if (!process.env.DRY_RUN) {
actual.setBudgetAmount(month, id, total);
}
console.log(chalk.blue(`${chalk.underline(category.name)} -> ${formatAmount(total)}`));
}
console.log();
await actual.shutdown();

View File

@ -21,7 +21,7 @@ await api.downloadBudget(process.env.ACTUAL_ID, {
export async function getSchedules(select = '*') {
return (await api.runQuery(api.q('schedules').select(select).filter({ completed: false }))).data;
return (await api.runQuery(api.q('schedules').select(select))).data;
}
export * from '@actual-app/api';

View File

@ -2,20 +2,20 @@ import { add, parse, format } from 'date-fns';
const startNow = new Date();
export function addFromFrequency(date, frequency, f = 'yyyy-MM') {
export function addFromFrequency(date, frequency, interval = 1, f = 'yyyy-MM') {
const toAdd = {};
switch (frequency) {
case 'daily':
toAdd.days = 1;
toAdd.days = interval;
break;
case 'weekly':
toAdd.weeks = 1;
toAdd.weeks = interval;
break;
case 'monthly':
toAdd.months = 1;
toAdd.months = interval;
break;
case 'yearly':
toAdd.years = 1;
toAdd.years = interval;
break;
default:

12
package-lock.json generated
View File

@ -10,6 +10,7 @@
"license": "MIT",
"dependencies": {
"@actual-app/api": "^6.8.2",
"chalk": "^5.3.0",
"date-fns": "^3.6.0",
"dotenv": "^16.4.5"
}
@ -109,6 +110,17 @@
"ieee754": "^1.1.13"
}
},
"node_modules/chalk": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",
"integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chownr": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",

View File

@ -12,6 +12,7 @@
"license": "MIT",
"dependencies": {
"@actual-app/api": "^6.8.2",
"chalk": "^5.3.0",
"date-fns": "^3.6.0",
"dotenv": "^16.4.5"
}