74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const FILE = path.join(__dirname, "data.json");
|
|
|
|
function read() {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(FILE, "utf8"));
|
|
} catch (_) {
|
|
return { entries: [] };
|
|
}
|
|
}
|
|
|
|
function write(data) {
|
|
data.updatedAt = new Date().toISOString();
|
|
fs.writeFileSync(FILE, JSON.stringify(data, null, 2));
|
|
}
|
|
|
|
function addEntry({ userId, type, amount, note, auto }) {
|
|
const data = read();
|
|
const entry = {
|
|
id: Date.now() + "_" + Math.random().toString(36).slice(2, 7),
|
|
userId,
|
|
type, // "income" | "expense"
|
|
amount: Math.round(amount),
|
|
note: String(note || "").trim(),
|
|
isAuto: !!auto,
|
|
createdAt: new Date().toISOString()
|
|
};
|
|
data.entries.push(entry);
|
|
write(data);
|
|
return entry;
|
|
}
|
|
|
|
function getEntries(userId) {
|
|
return read().entries.filter((e) => e.userId === userId);
|
|
}
|
|
|
|
function getBalance(userId) {
|
|
const list = getEntries(userId);
|
|
return list.reduce((bal, e) => (e.type === "income" ? bal + e.amount : bal - e.amount), 0);
|
|
}
|
|
|
|
function getMonthlySummary(userId, year, month) {
|
|
const list = getEntries(userId).filter((e) => {
|
|
const d = new Date(e.createdAt);
|
|
return d.getFullYear() === year && d.getMonth() + 1 === month;
|
|
});
|
|
const income = list.filter((e) => e.type === "income").reduce((s, e) => s + e.amount, 0);
|
|
const expense = list.filter((e) => e.type === "expense").reduce((s, e) => s + e.amount, 0);
|
|
return { income, expense, net: income - expense };
|
|
}
|
|
|
|
function getPeriodSummary(userId, from, to) {
|
|
// from/to — Date
|
|
const list = getEntries(userId).filter((e) => {
|
|
const d = new Date(e.createdAt);
|
|
return d >= from && d <= to;
|
|
});
|
|
const income = list.filter((e) => e.type === "income").reduce((s, e) => s + e.amount, 0);
|
|
const expense = list.filter((e) => e.type === "expense").reduce((s, e) => s + e.amount, 0);
|
|
|
|
const byCat = {};
|
|
for (const e of list) {
|
|
const cat = e.note || "Без категории";
|
|
byCat[cat] = byCat[cat] || { income: 0, expense: 0 };
|
|
if (e.type === "income") byCat[cat].income += e.amount;
|
|
else byCat[cat].expense += e.amount;
|
|
}
|
|
return { income, expense, net: income - expense, byCat, count: list.length };
|
|
}
|
|
|
|
module.exports = { addEntry, getEntries, getBalance, getMonthlySummary, getPeriodSummary, read, write };
|