ya-hochu-sozdat-prilozhenie/server.js

414 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 {
const d = JSON.parse(fs.readFileSync(DATA, "utf8"));
if (!d.places) d.places = [];
return d;
}
catch (_) { return { transactions: [], plans: [], budgets: [], files: [], places: [] }; }
}
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;
}
// ===== Поиск мест (OpenStreetMap / Nominatim) =====
const CATEGORIES = {
all: { label: "Все", params: "" },
cafe: { label: "Кафе / кофейни", params: "amenity=cafe" },
restaurant: { label: "Рестораны", params: "amenity=restaurant" },
bar: { label: "Бары", params: "amenity=bar" },
supermarket: { label: "Супермаркеты", params: "shop=supermarket" },
convenience: { label: "Продукты", params: "shop=convenience" },
pharmacy: { label: "Аптеки", params: "amenity=pharmacy" },
bank: { label: "Банки", params: "amenity=bank" },
fuel: { label: "Заправки", params: "amenity=fuel" },
hairdresser: { label: "Салоны красоты", params: "shop=hairdresser" },
beauty: { label: "Услуги красоты", params: "shop=beauty" },
fitness: { label: "Фитнес / спорт", params: "leisure=fitness_centre" },
hotel: { label: "Гостиницы", params: "tourism=hotel" },
market: { label: "Рынки / продовольствие", params: "shop=greengrocer" },
car_service: { label: "Автосервис", params: "shop=car_repair" },
clinic: { label: "Поликлиники / медицина", params: "amenity=doctors" }
};
const NOMA_UA = "Vibe42-PersonalAssistant/1.0 (personal budget assistant)";
let lastNoma = 0;
async function nomaFetch(url) {
const r = await fetch(url, { headers: { "User-Agent": NOMA_UA, "Accept-Language": "ru" } });
if (!r.ok) throw new Error("Nominatim " + r.status);
return r.json();
}
function placesHandler(query) {
const qs = new URLSearchParams(query);
const q = (qs.get("q") || "").trim();
const city = (qs.get("city") || "").trim();
const cat = qs.get("cat") || "all";
const catDef = CATEGORIES[cat] || CATEGORIES.all;
const finish = (res, code, payload) => {
if (res.headersSent) return;
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(payload));
};
(async () => {
try {
// 1) если указан город — нашли его bbox, чтобы ограничить поиск им
let viewbox = null;
let cityLabel = "";
if (city) {
const cUrl = "https://nominatim.openstreetmap.org/search?format=jsonv2&limit=1&accept-language=ru&q=" + encodeURIComponent(city);
const cj = await nomaFetch(cUrl);
if (cj && cj.length) {
const c = cj[0];
const bb = c.boundingbox; // [s, n, w, e]
viewbox = [bb[2], bb[0], bb[3], bb[1]]; // w, s, e, n
cityLabel = c.display_name;
}
}
// 2) строим запрос с viewbox + bounded=1
const parts = ["format=jsonv2", "limit=25", "accept-language=ru", "addressdetails=1"];
if (viewbox) {
parts.push("viewbox=" + viewbox.join(","));
parts.push("bounded=1");
}
if (catDef.params) parts.push(catDef.params);
if (q) parts.push("q=" + encodeURIComponent(q));
const url = "https://nominatim.openstreetmap.org/search?" + parts.join("&");
const raw = await nomaFetch(url);
const results = (raw || []).map(p => ({
name: p.name || (p.display_name ? p.display_name.split(",")[0] : "Без названия"),
type: (p.type || p.category || "").replace(/_/g, " "),
category: (p.addresstype === "amenity" || p.addresstype === "shop" || p.addresstype === "leisure" || p.addresstype === "tourism") ? p.addresstype : (p.category || ""),
address: p.display_name || "",
lat: p.lat,
lon: p.lon,
class: p.class,
tag: p.type
}));
finish(res, 200, { ok: true, city: cityLabel, results });
} catch (e) {
finish(res, 502, { error: "Сервис поиска временно недоступен. Попробуйте ещё раз." });
}
})();
}
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: поиск мест (Nominatim) с дросселированием ===
if (req.method === "GET" && url === "/api/places") {
const now = Date.now();
const wait = Math.max(0, 1100 - (now - lastNoma));
lastNoma = Date.now();
setTimeout(() => placesHandler(req.url.split("?")[1] || ""), wait);
return;
}
// === API: сохранить место в «Мои места» ===
if (req.method === "POST" && url === "/api/myplaces") {
const item = await body(req);
if (!item.name) {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "name required" }));
}
const d = loadData();
const rec = {
id: Date.now(),
name: item.name,
type: item.type || "",
category: item.category || "",
address: item.address || "",
lat: item.lat || null,
lon: item.lon || null,
city: item.city || "",
addedAt: new Date().toISOString()
};
d.places.push(rec);
saveData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, id: rec.id }));
}
// === API: удалить место из «Мои места» ===
if (req.method === "DELETE" && url.startsWith("/api/myplaces/")) {
const id = parseInt(url.split("/").pop());
const d = loadData();
d.places = d.places.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/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: edit операцию (type, category, desc, amount, date) ===
if (req.method === "PUT" && /^\/api\/transactions\/\d+$/.test(url)) {
const id = parseInt(url.split("/")[3]);
const item = await body(req);
const d = loadData();
const t = d.transactions.find(x => x.id === id);
if (t) {
if (item.type) t.type = item.type;
if (item.category !== undefined) t.category = item.category;
if (item.desc !== undefined) t.desc = item.desc;
if (item.amount !== undefined) t.amount = item.amount;
if (item.date !== undefined) t.date = item.date;
saveData(d);
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === 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: edit план (title, date, time) ===
if (req.method === "PUT" && url.endsWith("/edit")) {
const id = parseInt(url.split("/")[3]);
const item = await body(req);
const d = loadData();
const p = d.plans.find(x => x.id === id);
if (p) {
if (item.title !== undefined) p.title = item.title;
if (item.date !== undefined) p.date = item.date;
if (item.time !== undefined) p.time = item.time;
saveData(d);
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// === API: toggle план ===
if (req.method === "PUT" && /^\/api\/plans\/\d+$/.test(url)) {
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 }));
}
// === API: удалить лимит категории ===
if (req.method === "DELETE" && url.startsWith("/api/budgets/")) {
const cat = decodeURIComponent(url.split("/api/budgets/")[1] || "");
const d = loadData();
d.budgets = d.budgets.filter(b => b.category !== cat);
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));