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 load() { try { const d = JSON.parse(fs.readFileSync(DATA, "utf8")); return { items: Array.isArray(d.items) ? d.items : [], log: Array.isArray(d.log) ? d.log : [], }; } catch (_) { return { items: [], log: [] }; } } function save(d) { fs.writeFileSync(DATA, JSON.stringify(d, null, 2)); } const DEMO = [ { id: 2026001, title: "Контрольный пункт, пр. Абая 1", direction: "ОДС", status: "active", contractNo: "Д-2026/014", amount: 1250000, requestNo: "З-1042", startDate: "01.10.2026", endDate: "31.12.2026", }, { id: 2026002, title: "ЦОД, ул. Толе би 33", direction: "ДРБ", status: "completed", contractNo: "Д-2026/009", amount: 890000, requestNo: "З-1027", startDate: "01.07.2026", endDate: "30.09.2026", }, { id: 2026003, title: "Сеть связи, мкр. Самал", direction: "ДКБ", status: "planned", contractNo: "Д-2026/031", amount: 3400000, requestNo: "З-1061", startDate: "01.12.2026", endDate: "31.03.2027", }, { id: 2026004, title: "Диспетчерская служба, ул. Байтурсынова 5", direction: "ОДС", status: "paused", contractNo: "Д-2026/018", amount: 560000, requestNo: "З-1045", startDate: "15.09.2026", endDate: "15.11.2026", }, { id: 2026005, title: "Блок резервированного питания", direction: "ДРБ", status: "active", contractNo: "Д-2025/187", amount: 2100000, requestNo: "З-0963", startDate: "01.05.2026", endDate: "30.06.2026", }, { id: 2026006, title: "Боевой расчёт, ул. Гагарина 112", direction: "ДКБ", status: "active", contractNo: "Д-2026/022", amount: 1750000, requestNo: "З-1055", startDate: "10.10.2026", endDate: "10.04.2027", }, ]; function seed() { try { fs.accessSync(DATA); return; } catch (_) {} const now = new Date().toISOString(); save({ items: DEMO, log: [ { when: now, who: "система", what: "Добавлены демонстрационные записи. Замените их своими данными кнопкой «Новый объект».", }, ], }); } function sendJson(res, code, obj) { const s = JSON.stringify(obj); res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,POST,DELETE,OPTIONS", "Access-Control-Allow-Headers": "Content-Type", }); res.end(s); } function readBody(req) { return new Promise((resolve) => { let s = ""; req.on("data", (c) => (s += c)); req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } }); }); } const MIMES = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "application/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".woff2": "font/woff2", }; const server = http.createServer(async (req, res) => { const url = req.url.split("?")[0]; if (req.method === "OPTIONS") return sendJson(res, 204, {}); if (req.method === "GET" && url === "/api/items") { return sendJson(res, 200, load()); } if (req.method === "POST" && url === "/api/items") { const b = await readBody(req); const d = load(); const item = { id: Date.now(), title: String(b.title || "").trim(), direction: b.direction || "", status: b.status || "active", contractNo: String(b.contractNo || "").trim(), amount: Number(b.amount) || 0, requestNo: String(b.requestNo || "").trim(), startDate: b.startDate || "", endDate: b.endDate || "", }; if (!item.title) return sendJson(res, 400, { error: "Укажите объект" }); if (d.items.some((x) => x.id === item.id)) return sendJson(res, 409, { error: "Объект уже изменён — обновите список" }); d.items.unshift(item); d.log.unshift({ when: new Date().toISOString(), who: String(b.who || "вы"), what: "Новый объект: " + item.title }); save(d); return sendJson(res, 200, { ok: true, item }); } if (req.method === "POST" && url === "/api/items/update") { const b = await readBody(req); const d = load(); const it = d.items.find((x) => x.id === b.id); if (!it) return sendJson(res, 404, { error: "Объект не найден" }); const before = it.status; if (b.status && b.status !== before) it.status = b.status; if (b.amount !== undefined) it.amount = Number(b.amount) || 0; if (b.title) it.title = String(b.title).trim(); if (b.contractNo !== undefined) it.contractNo = String(b.contractNo).trim(); if (b.requestNo !== undefined) it.requestNo = String(b.requestNo).trim(); if (b.startDate) it.startDate = b.startDate; if (b.endDate) it.endDate = b.endDate; const parts = ["Статус: " + STATUS_LABEL[it.status] + (before !== it.status ? " (было: " + STATUS_LABEL[before] + ")" : "")]; d.log.unshift({ when: new Date().toISOString(), who: String(b.who || "вы"), what: itemTitle(it) + " — " + parts.join(", ") }); save(d); return sendJson(res, 200, { ok: true, item: it }); } if (req.method === "DELETE" && url === "/api/items") { const u = new URL(req.url, "http://localhost"); const id = Number(u.searchParams.get("id")); const d = load(); const it = d.items.find((x) => x.id === id); if (!it) return sendJson(res, 404, { error: "Объект не найден" }); d.items = d.items.filter((x) => x.id !== id); d.log.unshift({ when: new Date().toISOString(), who: "вы", what: "Удалён объект: " + itemTitle(it) }); save(d); return sendJson(res, 200, { ok: true }); } if (req.method === "GET" && url === "/api/log") { return sendJson(res, 200, load().log.slice(0, 50)); } if (url.startsWith("/api/")) return sendJson(res, 404, { error: "Not found" }); const file = url === "/" ? "index.html" : path.join(__dirname, url); if (file.startsWith(__dirname) && fs.existsSync(file) && fs.statSync(file).isFile()) { const ext = path.extname(file).toLowerCase(); res.writeHead(200, { "Content-Type": MIMES[ext] || "application/octet-stream" }); return res.end(fs.readFileSync(file)); } res.writeHead(404); res.end("Not found"); }); const STATUS_LABEL = { active: "Активен", paused: "Приостановлен", completed: "Завершён", planned: "Запланирован", }; function itemTitle(it) { return it.title + (it.direction ? " [" + it.direction + "]" : ""); } seed(); server.listen(PORT, () => console.log("Сервер реестра объектов на порту " + PORT));