brendmanager/src/server.js

327 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { createBot, createBotStore, mockTranscriber } from "./bot.js";
import { createPublisher } from "./publisher.js";
import { runDue, sendSummary } from "./summary-schedule.js";
import { createJobs } from "./jobs.js";
import { createHandlers, failureNotifier } from "./agent.js";
import { createLetters, letterView } from "./letters.js";
import { createOwner } from "./owner.js";
import { mockDraftWriter } from "./mock-draft-writer.js";
import { createMarketStore, KINDS, coverage, view } from "./market.js";
import { REPORT_RECORDS } from "./market-seed.js";
import { listChannels } from "./channels.js";
import { decide, publish, submit, touchedByEdit, withApproval } from "./approval.js";
import { brief, createAssetStore, KINDS as ASSET_KINDS, LINK_FILTERS } from "./assets.js";
import { docPage, homePage, sampleFile, pageHtml } from "./site.js";
import { createDeployStatus, tokenOk } from "./deploy-status.js";
import { TEXTS, pickLang, t } from "./i18n.js";
import { DEFAULT_SETTINGS, addDays, buildState, isDate, validateIdea } from "./plan.js";
// BRM-36: страницы без текста в разметке — сервер подставляет подписи при отдаче.
const PAGES = ["/plan.html", "/opportunities.html", "/summary.html", "/market.html", "/channels.html"];
const ROOT = path.dirname(fileURLToPath(import.meta.url));
export function createApp({ file, oppsFile, metricsFile, telegram = createTelegram(), draftWriter = mockDraftWriter, ownerCode = process.env.OWNER_CODE, deploySecret = process.env.DEPLOY_STATUS_SECRET, webhookSecret = process.env.TELEGRAM_WEBHOOK_SECRET, transcriber = mockTranscriber() }) {
const deploy = createDeployStatus(path.join(path.dirname(file), "deploy-status.json"));
const letters = createLetters(path.join(path.dirname(file), "letters.json"));
const owner = createOwner(path.join(path.dirname(file), "owner.json"), ownerCode);
const metrics = createMetricsStore(metricsFile ?? path.join(path.dirname(file), "metrics.json"));
const pub = createPublisher({ file: path.join(path.dirname(file), "publish-state.json"), channels: { telegram } });
const jobs = createJobs({ file: path.join(path.dirname(file), "jobs.json") });
const handlers = createHandlers({ pub });
const notify = failureNotifier(telegram);
const opps = createStore(oppsFile ?? path.join(path.dirname(file), "opportunities.json"));
const market = createMarketStore(path.join(path.dirname(file), "market.json"));
market.importReport(REPORT_RECORDS);
const assets = createAssetStore(path.join(path.dirname(file), "assets.json"));
const today = () => new Date().toISOString().slice(0, 10);
let plan;
try {
plan = JSON.parse(fs.readFileSync(file, "utf8"));
plan.ideas = plan.ideas.map(withApproval);
plan.publications ??= [];
} catch {
plan = { start: addDays(today(), 1), nextId: 1, ideas: [], publications: [], settings: structuredClone(DEFAULT_SETTINGS) };
}
const save = () => {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, JSON.stringify(plan, null, 2));
};
// BRM-52: бот владельца. Распознавание речи — мок, пока нет ключа сервиса.
const bot = createBot({ store: createBotStore(path.join(path.dirname(file), "bot.json")), telegram, pub, owner, getPlan: () => plan, savePlan: save, transcriber });
// Состояние плана с материалами; идея с датой без материалов помечается noAssets.
const state = () => {
const s = buildState(plan);
const dec = (i) => ({ ...i, assets: assets.forIdea(i.id).map(brief), noAssets: !!i.date && !assets.forIdea(i.id).length });
return { ...s, ideas: s.ideas.map(dec), unscheduled: s.unscheduled.map(dec), calendar: s.calendar.map((d) => ({ ...d, ideas: d.ideas.map(dec) })) };
};
const usage = (a) => a.ideaIds.map((id) => plan.ideas.find((i) => i.id === id)).filter(Boolean).map((i) => ({ id: i.id, title: i.title, date: i.date }));
const assetView = (a) => ({ id: a.id, kind: a.kind, title: a.title, addedAt: a.addedAt, url: a.url ?? null, content: a.content ?? null, preview: brief(a).preview, uses: usage(a) });
async function handleAssets(method, url, body, query, lang) {
const fail = (code, key, extra = {}) => [code, { error: t(lang, key), ...extra }];
if (url === "/api/assets/meta" && method === "GET") return [200, { kinds: ASSET_KINDS, links: LINK_FILTERS }];
const m = url.match(/^\/api\/assets(?:\/(\d+)(?:\/(attach|detach|file))?)?$/);
if (!m) return [404, { error: "not found" }];
const id = m[1] ? Number(m[1]) : null;
if (!id) {
if (method === "GET") {
const q = new URLSearchParams(query);
const kind = q.get("kind") || "", link = q.get("link") || "";
if ((kind && !ASSET_KINDS.includes(kind)) || (link && !LINK_FILTERS.includes(link))) return fail(400, "err.asset.filter");
return [200, { items: assets.list({ q: q.get("q") || "", kind, link }).map(assetView) }];
}
if (method === "POST") {
const r = assets.create(body, new Date().toISOString());
return r.err ? fail(400, r.err, { limitKb: 2048 }) : [201, assetView(r.asset)];
}
return [405, { error: "method" }];
}
const a = assets.get(id);
if (!a) return fail(404, "err.asset.notFound");
if (m[2] === "file" && method === "GET") { const f = assets.readFile(id); return f ? [200, f] : fail(404, "err.asset.notFound"); }
if (m[2] && method === "POST") {
const ideaId = Number(body.ideaId);
if (!plan.ideas.some((i) => i.id === ideaId)) return fail(404, "err.ideaNotFound");
return [200, assetView(m[2] === "attach" ? assets.attach(id, ideaId) : assets.detach(id, ideaId))];
}
if (!m[2] && method === "GET") return [200, assetView(a)];
if (!m[2] && method === "DELETE") {
const uses = usage(a);
if (uses.some((u) => u.date) && new URLSearchParams(query).get("confirm") !== "1") return fail(409, "err.asset.confirm", { uses });
assets.remove(id); return [200, { ok: true }];
}
return [405, { error: "method" }];
}
const pick = (b) => ({
title: typeof b.title === "string" ? b.title.trim() : b.title,
description: String(b.description ?? ""),
rubric: b.rubric,
date: b.date || null,
});
// Письмо организатору (BRM-20). BRM его не отправляет: только черновик, одобрение и отметка.
async function handleLetter(method, id, action, body, lang) {
const fail = (code, key, extra = {}) => [code, { error: t(lang, key), ...extra }];
const card = opps.get(id);
if (!card) return fail(404, "err.cardNotFound");
const out = (r) => (r.err ? fail(r.code, r.err) : [200, { letter: letterView(r.letter), codeSet: owner.isSet() }]);
const now = new Date().toISOString();
if (!action && method === "GET") return [200, { letter: letterView(letters.get(id)), codeSet: owner.isSet() }];
if (!action && method === "POST") {
const existing = letters.get(id);
if (existing) return out({ letter: existing });
const missing = ["organizer", "email"].filter((k) => !card[k]);
if (missing.length) return fail(400, missing.length === 2 ? "err.missing.both" : "err.missing." + missing[0], { missing });
const draft = await draftWriter.write(card);
return out({ letter: letters.create(id, { to: card.email, ...draft }, now) });
}
if (!action && method === "PUT") return out(letters.saveText(id, body));
if ((action === "approve" || action === "sent") && method === "POST") {
const l = letters.get(id);
if (!l) return fail(404, "err.letterNotFound");
if (action === "sent" && l.status === "draft") return fail(409, "err.notApproved");
const v = owner.verify(body.code);
if (v !== "ok") return fail(v === "short" ? 400 : 403, v === "short" ? "err.shortCode" : "err.wrongCode");
return out(action === "approve" ? letters.approve(id, body, now) : letters.markSent(id, now));
}
return [405, { error: "method" }];
}
async function handle(method, url, body, query = "", lang = "ru", token = "") {
if (url === "/api/texts" && method === "GET") return [200, { lang, texts: TEXTS[lang] }];
const lm = url.match(/^\/api\/opportunities\/(\d+)\/letter(?:\/(approve|sent))?$/);
if (lm) return handleLetter(method, Number(lm[1]), lm[2], body, lang);
if (url.startsWith("/api/assets")) return handleAssets(method, url, body, query, lang);
if (url === "/healthz") return [200, { ok: true }];
if (url === "/api/deploy-status" && method === "GET") return [200, deploy.view()];
if (url === "/api/deploy-status" && method === "POST") {
if (!tokenOk(token, deploySecret)) return [403, { error: t(lang, "err.deploy.denied") }];
const r = deploy.record(body);
return r.err ? [400, { error: t(lang, r.err) }] : [200, deploy.view()];
}
if (url === "/api/state" && method === "GET") return [200, state()];
if (url === "/api/publications" && method === "GET") return [200, { items: plan.publications }];
if (url === "/api/ideas" && method === "POST") {
const idea = pick(body);
const err = validateIdea(idea, plan);
if (err) return [400, { error: err }];
plan.ideas.push(withApproval({ id: plan.nextId++, ...idea }));
save();
return [201, state()];
}
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/jobs" && method === "GET") return [200, { items: jobs.list(), failed: jobs.failed() }];
if (url === "/api/jobs" && method === "POST") {
const r = jobs.add(body ?? {});
return r.err ? [400, { error: r.err }] : [r.duplicate ? 200 : 201, r];
}
const jm = url.match(/^\/api\/jobs\/(\d+)\/retry$/);
if (jm && method === "POST") { const j = jobs.retry(Number(jm[1])); return j ? [200, j] : [404, { error: "Задачи нет в списке ошибок" }]; }
if (url === "/api/summary/settings" && method === "GET") return [200, metrics.settings()];
if (url === "/api/summary/settings" && method === "PUT") { const r = metrics.setSettings(body); return r.err ? [400, { error: r.err }] : [200, r.settings]; }
if (url === "/api/summary/sections" && method === "GET") return [200, metrics.sections()];
if (url === "/api/summary/sections" && method === "PUT") return [200, metrics.setSections(body)];
if (url === "/api/summary/status" && method === "GET") return [200, { telegram: telegram.connected() }];
if (url === "/api/summary/log" && method === "GET") return [200, pub.log().filter((e) => e.channel === "telegram")];
if ((url === "/api/summary/stop" || url === "/api/summary/resume") && method === "POST") {
if (url.endsWith("stop")) pub.stop("telegram", "pm"); else pub.resume("telegram", "pm");
return [200, pub.status()];
}
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 sections = body.sections ?? metrics.sections();
if (url.endsWith("preview")) return [200, { text: buildSummary({ metrics: metrics.list(), period: body.period, asOf, sections }) }];
const { text, entry } = await sendSummary({ pub, metrics, period: body.period, asOf, sections });
if (entry.result === "published") return [200, { ok: true, text }];
const why = entry.reason === "stopped" ? "отправка остановлена" : entry.reason === "limit" ? "достигнут дневной лимит сообщений" : "Telegram недоступен";
return [502, { error: `Не удалось отправить: ${why}. Текст сводки сохранён ниже и в журнале.`, text }];
}
if (url === "/api/channels" && method === "GET") return [200, { items: listChannels() }];
if (url.startsWith("/api/market") && method === "GET") {
const mm = url.match(/^\/api\/market(?:\/([\w-]+))?$/);
if (!mm) return [404, { error: "not found" }];
if (mm[1]) { const r = market.get(mm[1]); return r ? [200, view(r)] : [404, { error: "Запись не найдена" }]; }
const kind = new URLSearchParams(query).get("type") || "";
if (kind && !KINDS.includes(kind)) return [400, { error: "Неизвестный тип записи" }];
return [200, { items: market.list(kind).map(view), coverage: coverage(market.list()) }];
}
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") || "") }];
const msg = (e) => (e.startsWith("err.") ? t(lang, e) : e);
if (!id && method === "POST") { const r = opps.create(body); return r.err ? [400, { error: msg(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);
if (r.item) letters.syncRecipient(id, r.item.email);
return r.notFound ? [404, { error: "Карточка не найдена" }] : r.err ? [400, { error: msg(r.err) }] : [200, r.item];
}
if (id && method === "DELETE") return opps.remove(id) && (letters.remove(id), true) ? [200, { ok: true }] : [404, { error: "Карточка не найдена" }];
return [405, { error: "method" }];
}
const am = url.match(/^\/api\/ideas\/(\d+)\/(submit|decision|publish)$/);
if (am && method === "POST") {
const idea = plan.ideas.find((x) => x.id === Number(am[1]));
if (!idea) return [404, { error: t(lang, "err.ideaNotFound") }];
const now = new Date().toISOString();
const r = am[2] === "submit" ? submit(idea, body, now) : am[2] === "decision" ? decide(idea, body, now) : publish(idea, plan.publications, body, now);
if (r.err) return [r.err === "err.notApproved" ? 409 : 400, { error: t(lang, r.err) }];
save();
return [200, state()];
}
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);
assets.dropIdea(Number(m[1]));
} else if (method === "PUT") {
const idea = pick({ ...plan.ideas[i], ...body });
const err = validateIdea(idea, plan);
if (err) return [400, { error: err }];
const old = plan.ideas[i];
const changed = ["title", "description", "rubric", "date"].some((k) => old[k] !== idea[k]);
plan.ideas[i] = { ...old, ...idea };
if (changed) touchedByEdit(plan.ideas[i], new Date().toISOString());
} else return [405, { error: "method" }];
save();
return [200, state()];
}
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, state()];
}
return [404, { error: "not found" }];
}
const server = 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("?");
const pageLang = pickLang(new URLSearchParams(query).get("lang"), req.headers["x-lang"]);
// BRM-39: «Рынок» по умолчанию русский, другой язык — только по ?lang=
const marketLang = pickLang(new URLSearchParams(query).get("lang"));
if (req.method === "GET" && (url === "/" || url === "/index.html"))
return send(200, homePage(pickLang(new URLSearchParams(query).get("lang"), req.headers["x-lang"]), undefined, deploy.view()), "text/html");
const sm = url.match(/^\/design\/brand-visual\/([\w.-]+)$/);
if (req.method === "GET" && sm) {
const f = sampleFile(sm[1]);
if (!f) return send(404, t(pageLang, "doc.notfound"), "text/plain");
res.writeHead(200, { "content-type": f.mime, "cache-control": "public, max-age=3600" });
return res.end(f.buf);
}
if (req.method === "GET" && PAGES.includes(url))
return send(200, pageHtml(url.slice(1), url === "/market.html" ? marketLang : pageLang), "text/html");
const dm = url.match(/^\/docs\/([\w-]+)$/);
if (req.method === "GET" && dm) {
const page = docPage(dm[1], pageLang);
return page ? send(200, page, "text/html") : send(404, t(pageLang, "doc.notfound"), "text/plain");
}
if (req.method === "GET" && url === "/assets.html")
return send(200, fs.readFileSync(path.join(ROOT, "../public/assets.html"), "utf8"), "text/html");
let body = {};
if (req.method === "POST" && url === "/api/telegram/webhook") {
let raw = "";
for await (const c of req) raw += c;
if (!webhookSecret || !tokenOk(req.headers["x-telegram-bot-api-secret-token"], webhookSecret)) return send(403, { error: "denied" });
try { return send(200, await bot.handleUpdate(JSON.parse(raw))); } catch { return send(200, { ok: false }); }
}
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 lang = pickLang(new URLSearchParams(query).get("lang"), req.headers["x-lang"]);
const [code, data] = await handle(req.method, url, body, query, lang, req.headers["x-deploy-token"]);
if (data?.buf) { res.writeHead(code, { "content-type": data.mime }); return res.end(data.buf); }
send(code, data);
} catch (e) {
send(500, { error: "internal" });
}
});
server.runDue = (now) => runDue({ jobs, handlers, notify, pub, metrics, opps, now });
server.jobs = jobs;
server.tickJobs = () => jobs.tick(handlers, { notify });
return server;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const port = Number(process.env.PORT ?? 3000);
const app = createApp({ file: process.env.DATA_FILE ?? "data/plan.json" });
setInterval(() => app.runDue().catch(() => {}), 60e3).unref(); // и очередь задач: повторы, срок, зависимости
app.listen(port, () => console.log(`listening on ${port}`));
}