160 lines
7.1 KiB
JavaScript
160 lines
7.1 KiB
JavaScript
const http = require("http");
|
||
const fs = require("fs");
|
||
const path = require("path");
|
||
|
||
const PORT = process.env.PORT || 3000;
|
||
const DATA = path.join(__dirname, "data.json");
|
||
const EMPTY = { purchases: [], clean: [], points: [], log: [] };
|
||
|
||
function load() {
|
||
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { ...EMPTY }; }
|
||
}
|
||
function save(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({}); } });
|
||
});
|
||
}
|
||
|
||
http.createServer(async (req, res) => {
|
||
const url = req.url.split("?")[0];
|
||
|
||
if (req.method === "GET" && url === "/api/purchases") {
|
||
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
||
return res.end(JSON.stringify(load().purchases));
|
||
}
|
||
|
||
if (req.method === "POST" && url === "/api/purchases") {
|
||
const p = await body(req);
|
||
if (!p.name) { res.writeHead(400, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ error: "name required" })); }
|
||
const d = load();
|
||
const rec = {
|
||
id: Date.now(),
|
||
name: String(p.name).slice(0, 120),
|
||
qty: p.qty ? String(p.qty).slice(0, 40) : "",
|
||
bought: p.bought || new Date().toISOString().slice(0, 10),
|
||
shelf: p.shelf || new Date().toISOString().slice(0, 10),
|
||
meal: p.meal || "",
|
||
price: p.price ? String(p.price).slice(0, 20) : "",
|
||
note: p.note ? String(p.note).slice(0, 200) : ""
|
||
};
|
||
d.purchases.push(rec);
|
||
d.log.push({ when: new Date().toISOString(), what: "покупок: " + rec.name + " " + rec.qty + " → меню: " + rec.meal, who: "юзер" });
|
||
save(d);
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ ok: true, item: rec }));
|
||
}
|
||
|
||
if (req.method === "POST" && /^\/api\/purchases\/\d+\/consumed$/.test(url)) {
|
||
const id = Number(url.split("/")[3]);
|
||
const d = load();
|
||
const rec = d.purchases.find((x) => x.id === id);
|
||
if (!rec) { res.writeHead(404, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ error: "not found" })); }
|
||
rec.consumed = new Date().toISOString().slice(0, 10);
|
||
d.log.push({ when: new Date().toISOString(), what: "израсходовано: " + rec.name, who: "юзер" });
|
||
save(d);
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ ok: true }));
|
||
}
|
||
|
||
if (req.method === "POST" && /^\/api\/purchases\/\d+$/.test(url)) {
|
||
const id = Number(url.split("/")[3]);
|
||
const d = load();
|
||
const rec = d.purchases.find((x) => x.id === id);
|
||
if (!rec) { res.writeHead(404, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ error: "not found" })); }
|
||
d.purchases = d.purchases.filter((x) => x.id !== id);
|
||
d.log.push({ when: new Date().toISOString(), what: "удалено: " + rec.name, who: "юзер" });
|
||
save(d);
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ ok: true }));
|
||
}
|
||
|
||
if (req.method === "GET" && url === "/api/clean") {
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify(load().clean || []));
|
||
}
|
||
|
||
if (req.method === "POST" && url === "/api/clean/toggle") {
|
||
const p = await body(req);
|
||
const when = new Date().toISOString();
|
||
const date = when.slice(0, 10);
|
||
const zone = String(p.zone || "").slice(0, 30);
|
||
if (!zone) { res.writeHead(400, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ error: "zone required" })); }
|
||
const d = load();
|
||
if (!Array.isArray(d.clean)) d.clean = [];
|
||
const rec = d.clean.find((x) => x.zone === zone && x.date === date);
|
||
if (rec) { rec.done = !rec.done; } else { d.clean.push({ zone, date, done: true }); }
|
||
d.log.push({ when, what: "уборка: " + zone + (rec && !rec.done ? " — сняли отметку" : " — исполнено"), who: "юзер" });
|
||
save(d);
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ ok: true }));
|
||
}
|
||
|
||
if (req.method === "GET" && url === "/api/points") {
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify(load().points || []));
|
||
}
|
||
|
||
if (req.method === "POST" && /^\/api\/purchases\/\d+\/vote$/.test(url)) {
|
||
const id = Number(url.split("/")[3]);
|
||
const p = await body(req);
|
||
const vote = String(p.vote || "");
|
||
const who = String(p.who || "").slice(0, 30);
|
||
if (!vote || !who || (vote !== "y" && vote !== "n")) {
|
||
res.writeHead(400, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ error: "vote y|n and who required" }));
|
||
}
|
||
const d = load();
|
||
const rec = d.purchases.find((x) => x.id === id);
|
||
if (!rec) { res.writeHead(404, { "Content-Type": "application/json" }); return res.end(JSON.stringify({ error: "not found" })); }
|
||
if (!rec.meals || typeof rec.meals !== "object") rec.meals = { y: [], n: [] };
|
||
const arr = rec.meals[vote];
|
||
if (arr.indexOf(who) === -1) arr.push(who);
|
||
d.log.push({ when: new Date().toISOString(), what: "отметка " + (vote === "y" ? "вкусно" : "невкусно") + ": " + rec.name + " (" + who + ")", who: "юзер" });
|
||
save(d);
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ ok: true }));
|
||
}
|
||
|
||
if (req.method === "POST" && url === "/api/points") {
|
||
const p = await body(req);
|
||
const when = new Date().toISOString();
|
||
const who = String(p.who || "").slice(0, 40);
|
||
const kind = String(p.kind || "").slice(0, 40);
|
||
const amount = Math.round(Number(p.amount) || 0);
|
||
const note = String(p.note || "").slice(0, 120);
|
||
if (!who || !kind || amount === 0) {
|
||
res.writeHead(400, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ error: "who, kind and non-zero amount required" }));
|
||
}
|
||
const d = load();
|
||
if (!Array.isArray(d.points)) d.points = [];
|
||
const rec = {
|
||
id: Date.now(),
|
||
who,
|
||
kind,
|
||
amount,
|
||
note,
|
||
when
|
||
};
|
||
d.points.push(rec);
|
||
const verb = amount > 0 ? "получил(а)" : "вернул(а)";
|
||
d.log.push({ when, what: "баллы: " + who + " " + verb + " " + Math.abs(amount) + (amount < 0 ? " (вернуло " + note + ")" : " за " + kind), who: "юзер" });
|
||
save(d);
|
||
res.writeHead(200, { "Content-Type": "application/json" });
|
||
return res.end(JSON.stringify({ ok: true, item: rec }));
|
||
}
|
||
|
||
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 type = ext === ".css" ? "text/css" : ext === ".js" ? "application/javascript" : ext === ".svg" ? "image/svg+xml" : ext === ".json" ? "application/json" : "text/html";
|
||
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
|
||
return res.end(fs.readFileSync(full));
|
||
}
|
||
res.writeHead(404); res.end("Not found");
|
||
}).listen(PORT, () => console.log("Сервер на порту " + PORT));
|