actual-scripts/calc-schedule-budget.js

54 lines
1.4 KiB
JavaScript

import { format } from 'date-fns';
import { checkEnv } from './lib/env.js';
import * as actual from './lib/actual.js';
import { addFromFrequency } from './lib/dates.js';
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);
}
await actual.shutdown();