137 lines
7.1 KiB
JavaScript
137 lines
7.1 KiB
JavaScript
import http from "node:http";
|
||
import fs from "node:fs";
|
||
import path from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { STAGES, TYPES, createStore } from "./opportunities.js";
|
||
import { PERIODS, buildSummary, createMetricsStore, isDate as isDay } from "./metrics.js";
|
||
import { createTelegram } from "./telegram.js";
|
||
import { DEFAULT_SETTINGS, addDays, buildState, isDate, validateIdea } from "./plan.js";
|
||
|
||
const ROOT = path.dirname(fileURLToPath(import.meta.url));
|
||
|
||
export function createApp({ file, oppsFile, metricsFile, telegram = createTelegram() }) {
|
||
const metrics = createMetricsStore(metricsFile ?? path.join(path.dirname(file), "metrics.json"));
|
||
const opps = createStore(oppsFile ?? path.join(path.dirname(file), "opportunities.json"));
|
||
const today = () => new Date().toISOString().slice(0, 10);
|
||
let plan;
|
||
try {
|
||
plan = JSON.parse(fs.readFileSync(file, "utf8"));
|
||
} catch {
|
||
plan = { start: addDays(today(), 1), nextId: 1, ideas: [], settings: structuredClone(DEFAULT_SETTINGS) };
|
||
}
|
||
const save = () => {
|
||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||
fs.writeFileSync(file, JSON.stringify(plan, null, 2));
|
||
};
|
||
const pick = (b) => ({
|
||
title: typeof b.title === "string" ? b.title.trim() : b.title,
|
||
description: String(b.description ?? ""),
|
||
rubric: b.rubric,
|
||
date: b.date || null,
|
||
});
|
||
|
||
async function handle(method, url, body, query = "") {
|
||
if (url === "/healthz") return [200, { ok: true }];
|
||
if (url === "/api/state" && method === "GET") return [200, buildState(plan)];
|
||
if (url === "/api/ideas" && method === "POST") {
|
||
const idea = pick(body);
|
||
const err = validateIdea(idea, plan);
|
||
if (err) return [400, { error: err }];
|
||
plan.ideas.push({ id: plan.nextId++, ...idea });
|
||
save();
|
||
return [201, buildState(plan)];
|
||
}
|
||
if (url === "/api/metrics" && method === "GET") return [200, { metrics: metrics.list() }];
|
||
if (url === "/api/metrics" && method === "POST") { const r = metrics.set(body); return r.err ? [400, { error: r.err }] : [200, r]; }
|
||
if ((url === "/api/summary/preview" || url === "/api/summary/send") && method === "POST") {
|
||
if (!PERIODS[body.period]) return [400, { error: "Период: day или week" }];
|
||
const asOf = body.date || today();
|
||
if (!isDay(asOf)) return [400, { error: "Дата в формате ГГГГ-ММ-ДД" }];
|
||
const text = buildSummary({ metrics: metrics.list(), period: body.period, asOf, sections: body.sections });
|
||
if (url.endsWith("preview")) return [200, { text }];
|
||
if (!telegram.connected()) return [502, { error: "Не удалось отправить: Telegram не подключён. Текст сводки сохранён ниже.", text }];
|
||
try { await telegram.send(text); return [200, { ok: true, text }]; }
|
||
catch (e) { return [502, { error: "Не удалось отправить в Telegram. Текст сводки сохранён ниже.", text }]; }
|
||
}
|
||
if (url === "/api/opportunities/meta" && method === "GET") return [200, { stages: STAGES, types: TYPES.filter(Boolean) }];
|
||
if (url.startsWith("/api/opportunities")) {
|
||
const mm = url.match(/^\/api\/opportunities(?:\/(\d+))?$/);
|
||
if (!mm) return [404, { error: "not found" }];
|
||
const id = mm[1] ? Number(mm[1]) : null;
|
||
if (!id && method === "GET") return [200, { items: opps.list(today(), new URLSearchParams(query).get("stage") || "") }];
|
||
if (!id && method === "POST") { const r = opps.create(body); return r.err ? [400, { error: r.err }] : [201, r.item]; }
|
||
if (id && method === "GET") { const o = opps.get(id); return o ? [200, o] : [404, { error: "Карточка не найдена" }]; }
|
||
if (id && method === "PUT") { const r = opps.update(id, body); return r.notFound ? [404, { error: "Карточка не найдена" }] : r.err ? [400, { error: r.err }] : [200, r.item]; }
|
||
if (id && method === "DELETE") return opps.remove(id) ? [200, { ok: true }] : [404, { error: "Карточка не найдена" }];
|
||
return [405, { error: "method" }];
|
||
}
|
||
const m = url.match(/^\/api\/ideas\/(\d+)$/);
|
||
if (m) {
|
||
const i = plan.ideas.findIndex((x) => x.id === Number(m[1]));
|
||
if (i < 0) return [404, { error: "Идея не найдена" }];
|
||
if (method === "DELETE") {
|
||
plan.ideas.splice(i, 1);
|
||
} else if (method === "PUT") {
|
||
const idea = pick({ ...plan.ideas[i], ...body });
|
||
const err = validateIdea(idea, plan);
|
||
if (err) return [400, { error: err }];
|
||
plan.ideas[i] = { id: plan.ideas[i].id, ...idea };
|
||
} else return [405, { error: "method" }];
|
||
save();
|
||
return [200, buildState(plan)];
|
||
}
|
||
if (url === "/api/settings" && method === "PUT") {
|
||
if (body.start !== undefined) {
|
||
if (!isDate(body.start)) return [400, { error: "Дата старта в формате ГГГГ-ММ-ДД" }];
|
||
plan.start = body.start;
|
||
}
|
||
if (body.threshold !== undefined) {
|
||
if (!(Number(body.threshold) >= 0)) return [400, { error: "Порог — неотрицательное число" }];
|
||
plan.settings.threshold = Number(body.threshold);
|
||
}
|
||
if (Array.isArray(body.rubrics)) {
|
||
for (const r of body.rubrics) {
|
||
const cur = plan.settings.rubrics.find((x) => x.id === r.id);
|
||
if (!cur || !String(r.name ?? "").trim()) return [400, { error: "Некорректная рубрика" }];
|
||
cur.name = String(r.name).trim();
|
||
if (r.share !== undefined) cur.share = Number(r.share);
|
||
}
|
||
}
|
||
save();
|
||
return [200, buildState(plan)];
|
||
}
|
||
return [404, { error: "not found" }];
|
||
}
|
||
|
||
return http.createServer(async (req, res) => {
|
||
const send = (code, data, type = "application/json") => {
|
||
res.writeHead(code, { "content-type": type + "; charset=utf-8" });
|
||
res.end(type === "application/json" ? JSON.stringify(data) : data);
|
||
};
|
||
try {
|
||
const [url, query = ""] = req.url.split("?");
|
||
if (req.method === "GET" && (url === "/" || url === "/index.html"))
|
||
return send(200, fs.readFileSync(path.join(ROOT, "../public/index.html"), "utf8"), "text/html");
|
||
if (req.method === "GET" && url === "/opportunities.html")
|
||
return send(200, fs.readFileSync(path.join(ROOT, "../public/opportunities.html"), "utf8"), "text/html");
|
||
if (req.method === "GET" && url === "/summary.html")
|
||
return send(200, fs.readFileSync(path.join(ROOT, "../public/summary.html"), "utf8"), "text/html");
|
||
let body = {};
|
||
if (req.method === "POST" || req.method === "PUT") {
|
||
let raw = "";
|
||
for await (const c of req) raw += c;
|
||
try { body = raw ? JSON.parse(raw) : {}; } catch { return send(400, { error: "Некорректный JSON" }); }
|
||
}
|
||
const [code, data] = await handle(req.method, url, body, query);
|
||
send(code, data);
|
||
} catch (e) {
|
||
send(500, { error: "internal" });
|
||
}
|
||
});
|
||
}
|
||
|
||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||
const port = Number(process.env.PORT ?? 3000);
|
||
createApp({ file: process.env.DATA_FILE ?? "data/plan.json" }).listen(port, () => console.log(`listening on ${port}`));
|
||
}
|