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"); function readData() { try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { items: [], log: [] }; } } function writeData(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]; res.setHeader("Content-Type", "application/json; charset=utf-8"); // API: все карточки кандидата if (req.method === "GET" && url === "/api/cards") { const d = readData(); res.end(JSON.stringify(d.items || [])); return; } // API: получить одну карточку if (req.method === "GET" && url.startsWith("/api/cards/")) { const id = url.split("/").pop(); const d = readData(); const card = (d.items || []).find((x) => String(x.id) === String(id)); if (!card) { res.writeHead(404); res.end(JSON.stringify({ error: "not found" })); return; } res.end(JSON.stringify(card)); return; } // API: создать новую карточку if (req.method === "POST" && url === "/api/cards") { const b = await body(req); const d = readData(); const card = { id: Date.now(), name: b.name || "", post: b.post || "", submitted: new Date().toISOString().slice(0, 10), stage: "uploaded", files: [], analysisStatus: "idle", violations: [], checks: {}, text: "", sentAt: null, returned: null, approvedAt: null, createdAt: new Date().toISOString() }; d.items.push(card); d.log = d.log || []; d.log.push({ when: new Date().toISOString(), what: "Создана карточка «" + card.name + "»" }); writeData(d); res.end(JSON.stringify(card)); return; } // API: обновить карточку if (req.method === "PUT" && url.startsWith("/api/cards/")) { const id = url.split("/").pop(); const b = await body(req); const d = readData(); const idx = (d.items || []).findIndex((x) => String(x.id) === String(id)); if (idx === -1) { res.writeHead(404); res.end(JSON.stringify({ error: "not found" })); return; } d.items[idx] = Object.assign(d.items[idx], b, { id }); d.log = d.log || []; d.log.push({ when: new Date().toISOString(), what: "Обновлена карточка «" + d.items[idx].name + "»" }); writeData(d); res.end(JSON.stringify(d.items[idx])); return; } // Статика 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" : "text/html"; res.writeHead(200, { "Content-Type": type + "; charset=utf-8" }); res.end(fs.readFileSync(full)); return; } res.writeHead(404); res.end("Not found"); }).listen(PORT, () => console.log("Сервер на порту " + PORT));