proekt-po-crm/server.js

98 lines
3.4 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
const DATA_FILE = path.join(__dirname, "requests.json");
const RESPONSES_FILE = path.join(__dirname, "responses.json");
function readJson(file, def) {
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch (_) { return def; }
}
function writeJson(file, data) {
fs.writeFileSync(file, JSON.stringify(data, 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];
// API: получить все запросы и ответы
if (req.method === "GET" && url === "/api/requests") {
const requests = readJson(DATA_FILE, []);
const responses = readJson(RESPONSES_FILE, []);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ requests, responses }));
}
// API: добавить новый запрос
if (req.method === "POST" && url === "/api/request") {
const { query, preset } = await body(req);
const requests = readJson(DATA_FILE, []);
const newReq = {
id: Date.now(),
query,
preset: preset || null,
status: "pending",
created: new Date().toISOString()
};
requests.unshift(newReq);
writeJson(DATA_FILE, requests);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, request: newReq }));
}
// API: обновить ответ на запрос
if (req.method === "POST" && url === "/api/response") {
const { id, response, status } = await body(req);
const responses = readJson(RESPONSES_FILE, []);
const existing = responses.findIndex(r => r.id === id);
const respData = { id, response, status: status || "completed", updated: new Date().toISOString() };
if (existing >= 0) {
responses[existing] = respData;
} else {
responses.unshift(respData);
}
writeJson(RESPONSES_FILE, responses);
// Обновляем статус запроса
const requests = readJson(DATA_FILE, []);
const reqIdx = requests.findIndex(r => r.id === id);
if (reqIdx >= 0) {
requests[reqIdx].status = status || "completed";
writeJson(DATA_FILE, requests);
}
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// API: очистить старые данные
if (req.method === "DELETE" && url === "/api/clear") {
writeJson(DATA_FILE, []);
writeJson(RESPONSES_FILE, []);
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 type = ext === ".css" ? "text/css" : ext === ".js" ? "application/javascript" : "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("CRM Dashboard на порту " + PORT));