44 lines
1.4 KiB
JavaScript
44 lines
1.4 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
const ExcelJS = require("exceljs");
|
|
|
|
function exportXlsx(userId, entries) {
|
|
const wb = new ExcelJS.Workbook();
|
|
const ws = wb.addWorksheet("Операции");
|
|
ws.columns = [
|
|
{ header: "Дата", key: "date", width: 18 },
|
|
{ header: "Время", key: "time", width: 8 },
|
|
{ header: "Тип", key: "type", width: 12 },
|
|
{ header: "Сумма", key: "amount", width: 14 },
|
|
{ header: "Категория", key: "note", width: 30 },
|
|
{ header: "Остаток", key: "balance", width: 16 }
|
|
];
|
|
let bal = 0;
|
|
for (const e of entries) {
|
|
if (e.type === "income") bal += e.amount;
|
|
else bal -= e.amount;
|
|
const d = new Date(e.createdAt);
|
|
ws.addRow({
|
|
date: d.toLocaleDateString("ru-RU"),
|
|
time: d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }),
|
|
type: e.type === "income" ? "Доход" : "Расход",
|
|
amount: e.amount,
|
|
note: e.note || "",
|
|
balance: bal
|
|
});
|
|
}
|
|
return wb.xlsx
|
|
.writeBuffer()
|
|
.then((buf) => Buffer.from(buf));
|
|
}
|
|
|
|
async function saveTemp(userId, buf, name) {
|
|
const dir = path.join(__dirname, "exports");
|
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
const file = path.join(dir, `export_${userId}_${Date.now()}.xlsx`);
|
|
await fs.promises.writeFile(file, buf);
|
|
return file;
|
|
}
|
|
|
|
module.exports = { exportXlsx, saveTemp };
|