ya-hochu-sozdat-prilozhenie/server.js

237 lines
8.8 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const formidable = require("formidable");
const XLSX = require("xlsx");
const PORT = process.env.PORT || 3000;
const DATA = path.join(__dirname, "data.json");
const UPLOADS = path.join(__dirname, "uploads");
if (!fs.existsSync(UPLOADS)) fs.mkdirSync(UPLOADS);
function loadData() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); }
catch (_) { return { transactions: [], plans: [], budgets: [], files: [] }; }
}
function saveData(d) { fs.writeFileSync(DATA, JSON.stringify(d, null, 2)); }
function body(req) {
return new Promise((resolve) => {
let s = "";
req.on("data", (c) => (s += c));
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
});
}
// ИИ
async function ai(text) {
if (!process.env.AI_BASE_URL || !process.env.AI_API_KEY) {
throw new Error("AI not configured");
}
const r = await fetch(process.env.AI_BASE_URL + "/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: "Bearer " + process.env.AI_API_KEY },
body: JSON.stringify({ model: process.env.AI_MODEL, messages: [{ role: "user", content: text }] })
});
if (!r.ok) throw new Error("AI error " + r.status);
const j = await r.json();
const out = j.choices && j.choices[0] && j.choices[0].message && j.choices[0].message.content;
if (!out) throw new Error("AI empty response");
return out;
}
function parseFile(filePath, originalName) {
const ext = path.extname(originalName).toLowerCase();
if (ext === ".csv") {
const wb = XLSX.read(fs.readFileSync(filePath), { type: "file" });
return XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
}
const wb = XLSX.readFile(filePath);
return XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
}
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
// === API: получить все данные ===
if (req.method === "GET" && url === "/api/data") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(loadData()));
}
// === API: добавить операцию ===
if (req.method === "POST" && url === "/api/transactions") {
const item = await body(req);
const d = loadData();
d.transactions.push({ id: Date.now(), ...item });
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, id: Date.now() }));
}
// === API: удалить операцию ===
if (req.method === "DELETE" && url.startsWith("/api/transactions/")) {
const id = parseInt(url.split("/").pop());
const d = loadData();
d.transactions = d.transactions.filter(t => t.id !== id);
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === API: добавить план ===
if (req.method === "POST" && url === "/api/plans") {
const item = await body(req);
const d = loadData();
d.plans.push({ id: Date.now(), ...item, done: false });
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, id: Date.now() }));
}
// === API: toggle план ===
if (req.method === "PUT" && url.startsWith("/api/plans/")) {
const id = parseInt(url.split("/")[3]);
const d = loadData();
const p = d.plans.find(x => x.id === id);
if (p) { p.done = !p.done; saveData(d); }
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === API: удалить план ===
if (req.method === "DELETE" && url.startsWith("/api/plans/")) {
const id = parseInt(url.split("/").pop());
const d = loadData();
d.plans = d.plans.filter(p => p.id !== id);
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === API: загрузить файл ===
if (req.method === "POST" && url === "/api/upload") {
const form = formidable({ uploadDir: UPLOADS, keepExtensions: true });
form.parse(req, async (err, fields, files) => {
if (err) {
res.writeHead(500, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: err.message }));
}
const f = files.file && files.file[0];
if (!f) {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "no file" }));
}
try {
const rows = parseFile(f.filepath, f.originalFilename);
const d = loadData();
const fileId = Date.now();
d.files.push({
id: fileId,
name: f.originalFilename,
rows: rows.length,
uploadedAt: new Date().toISOString(),
filepath: f.filepath
});
saveData(d);
// Build preview of data for context
let preview = "";
if (rows.length > 0) {
const keys = Object.keys(rows[0]);
preview = "Headers: " + keys.join(", ") + "\n";
const sample = rows.slice(0, 5);
preview += "Sample rows:\n" + sample.map(r => keys.map(k => r[k]).join(" | ")).join("\n");
preview += "\nTotal rows: " + rows.length;
}
const prompt = `You are a data analysis assistant. A user uploaded a CSV/Excel file named "${f.originalFilename}".
Here is the data structure and sample:
${preview}
Provide a concise analysis in Russian:
1. Summary of the data (how many rows, what columns)
2. Key statistics (sums, averages, min/max for numeric columns)
3. Any notable patterns or anomalies
4. 2-3 actionable insights or recommendations
Format the response as clean markdown with headers and bullet points. Be concise and specific.
`;
let analysis = "AI analysis is not available yet. File uploaded successfully with " + rows.length + " rows.";
try {
analysis = await ai(prompt);
} catch (e) {
analysis = "⚠️ AI analysis temporarily unavailable. File uploaded successfully (" + rows.length + " rows). Try again later.";
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
ok: true,
fileId: fileId,
name: f.originalFilename,
rows: rows.length,
analysis: analysis
}));
} catch (e2) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Failed to parse file: " + e2.message }));
}
});
return;
}
// === API: получить анализ файла ===
if (req.method === "GET" && url.startsWith("/api/files/")) {
const id = parseInt(url.split("/").pop());
const d = loadData();
const f = d.files.find(x => x.id === id);
if (!f) {
res.writeHead(404, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "file not found" }));
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(f));
}
// === API: удалить файл ===
if (req.method === "DELETE" && url.startsWith("/api/files/")) {
const id = parseInt(url.split("/").pop());
const d = loadData();
const f = d.files.find(x => x.id === id);
if (f && f.filepath && fs.existsSync(f.filepath)) fs.unlinkSync(f.filepath);
d.files = d.files.filter(x => x.id !== id);
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === API: обновить бюджет категории ===
if (req.method === "PUT" && url === "/api/budgets") {
const item = await body(req);
const d = loadData();
const idx = d.budgets.findIndex(b => b.category === item.category);
if (idx >= 0) {
d.budgets[idx] = { ...d.budgets[idx], ...item };
} else {
d.budgets.push({ ...item });
}
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === Статика ===
let file = url === "/" ? "/index.html" : url;
const full = path.join(__dirname, file);
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
const ext = path.extname(full);
const types = { ".css": "text/css", ".js": "application/javascript", ".html": "text/html", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2" };
const type = types[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}).listen(PORT, () => console.log("Server on port " + PORT));