brendmanager/src/server.js

418 lines
28 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 { createLinkedIn } from "./linkedin.js";
import { createBot, createBotStore, mockTranscriber } from "./bot.js";
import { createPublisher } from "./publisher.js";
import { createStrategy } from "./strategy.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, AGREED } from "./market.js";
import { REPORT_RECORDS } from "./market-seed.js";
import { listChannels } from "./channels.js";
import { createFactsStore, factView, caseView, BUCKETS, LEVELS, STAGES as FACT_STAGES, CASE_FIELDS } from "./facts.js";
import { SEED_FACTS, SEED_CASES, SEED_QUESTIONS } from "./facts-seed.js";
import { STATUSES as IDEA_STATUSES, decide, publish, submit, touchedByEdit, withApproval } from "./approval.js";
import { brief, createAssetStore, KINDS as ASSET_KINDS, LINK_FILTERS } from "./assets.js";
import { botPage, botView } from "./bot-page.js";
import { docPage, homePage, sampleFile, pageHtml, regionsBox, fillSelect, metricsTable, marketSamples } 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", "/strategy.html", "/facts.html"];
const ROOT = path.dirname(fileURLToPath(import.meta.url));
export function createApp({ file, oppsFile, metricsFile, telegram = createTelegram(), linkedin = createLinkedIn(), 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 strategy = createStrategy(path.join(path.dirname(file), "strategy.json"));
const pub = createPublisher({ file: path.join(path.dirname(file), "publish-state.json"), channels: { telegram }, gate: (r) => strategy.gate(r) });
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.map((r) => ({ ...r, sample: true })));
const facts = createFactsStore(path.join(path.dirname(file), "facts.json"));
for (const f of SEED_FACTS) facts.upsert(f, { seed: true });
SEED_CASES.forEach((c) => facts.seedCase(c));
SEED_QUESTIONS.forEach((q) => facts.seedQuestion(q));
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" }];
}
// Стратегия и правила автономности (BRM-53)
function handleStrategy(method, url, body, lang) {
const now = new Date().toISOString();
const out = (r, code = 200) => (r.err ? [r.err === "err.strategy.notDecider" ? 403 : 400, { error: t(lang, r.err), ...(r.missing ? { missing: r.missing } : {}) }] : [code, r]);
if (url === "/api/strategy" && method === "GET")
return [200, { current: strategy.current(), versions: strategy.versions(), rules: strategy.rules(), tasks: strategy.tasks(), approved: strategy.isApproved(), ...strategy.meta() }];
if (url === "/api/strategy/edit" && method === "POST") return out(strategy.edit(body.sections, body.by, now));
if (url === "/api/strategy/decision" && method === "POST") return out(strategy.decide(body, now));
if (url === "/api/strategy/rules" && method === "PUT") return out(strategy.setRule(body));
if (url === "/api/strategy/consent" && method === "POST") return out(strategy.grant(body, now));
return [404, { error: "not found" }];
}
function handleFacts(method, url, body, query, lang) {
const out = (r, view) => (r.err ? [400, { error: t(lang, r.err) }] : [200, view(r.record)]);
const same = (x) => x;
if (url === "/api/facts/meta" && method === "GET") return [200, { buckets: BUCKETS, levels: LEVELS, stages: FACT_STAGES, caseFields: CASE_FIELDS }];
if (url === "/api/questions" && method === "GET") return [200, { items: facts.nextQuestions(new URLSearchParams(query).get("n")), open: facts.questions().filter((q) => !q.answer).length, total: facts.questions().length }];
let m = url.match(/^\/api\/questions\/(\d+)\/answer$/);
if (m && method === "POST") return out(facts.answer(m[1], body.answer), same);
if (url === "/api/cases" && method === "GET") return [200, { items: facts.cases().map(caseView) }];
if (url === "/api/cases" && method === "POST") return out(facts.upsertCase(body), caseView);
if (url === "/api/facts" && method === "GET") {
const bucket = new URLSearchParams(query).get("bucket") || "";
if (bucket && !BUCKETS.includes(bucket)) return [400, { error: t(lang, "err.facts.bucket") }];
return [200, { items: facts.list(bucket).map(factView) }];
}
if (url === "/api/facts" && method === "POST") return out(facts.upsert(body), factView);
m = url.match(/^\/api\/facts\/([\w-]+)(?:\/(revoke|restore))?$/);
if (m && method === "GET" && !m[2]) { const f = facts.get(m[1]); return f ? [200, factView(f)] : [404, { error: t(lang, "err.facts.notfound") }]; }
if (m && method === "POST" && m[2] === "revoke") return out(facts.revoke(m[1], body.reason), factView);
if (m && method === "POST" && m[2] === "restore") return out(facts.restore(m[1]), factView);
return [404, { error: "not found" }];
}
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/facts") || url.startsWith("/api/cases") || url.startsWith("/api/questions")) return handleFacts(method, url, body, query, 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/bot/status" && method === "GET") return [200, botView({ pub, jobs, metrics, telegram })];
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.startsWith("/api/strategy")) return handleStrategy(method, url, body, lang);
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(), missing: telegram.missing?.() ?? null, paused: Boolean(pub.status().channels.telegram?.stopped) }];
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 }];
if (entry.off) return [409, { error: t(lang, "err.sum.off"), off: true, text }];
return [502, { error: t(lang, "err.sum." + (["stopped", "limit"].includes(entry.reason) ? entry.reason : "failed")), 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()), agreed: AGREED }];
}
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" }];
}
// BRM-73: где сейчас есть записи-образцы — главная называет только эти разделы.
const sampleSections = () => [
["plan", plan.ideas.some((i) => i.sample)],
["opps", opps.list(today()).some((o) => o.sample)],
["metrics", metrics.list().some((m) => m.sample)],
["market", market.list().some((r) => r.sample)],
].filter(([, has]) => has).map(([k]) => k);
const server = http.createServer(async (req, res) => {
const send = (code, data, type = "application/json") => {
// BRM-73: страницы не кэшируем — иначе браузер показывает старый блок обновления.
res.writeHead(code, { "content-type": type + "; charset=utf-8", ...(type === "text/html" ? { "cache-control": "no-store" } : {}) });
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(), sampleSections(), { telegram: telegram.missing?.() ?? null, linkedin: linkedin.missing() }, { approved: strategy.isApproved(), date: (strategy.current()?.approvedAt ?? "").slice(0, 10) }), "text/html");
// BRM-74: раздел «Бот и отчёты»; кнопки — формы, после нажатия возвращаемся в раздел.
const langQ = new URLSearchParams(query).get("lang") ? `?lang=${pageLang}` : "";
if (req.method === "GET" && url === "/bot.html")
return send(200, botPage(pageLang, botView({ pub, jobs, metrics, telegram }), langQ, deploy.view()), "text/html");
if (req.method === "POST" && (url === "/bot/pause" || url === "/bot/resume")) {
if (url.endsWith("pause")) pub.stop(undefined, "pm"); else pub.resume(undefined, "pm");
res.writeHead(303, { location: "/bot.html" + langQ });
return res.end();
}
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))
{
let page = pageHtml(url.slice(1), url === "/market.html" ? marketLang : pageLang);
if (url === "/summary.html") {
const off = Boolean(pub.status().channels.telegram?.stopped);
page = page.replace('<p id="sched" class="hint" role="status"></p>', `<p id="sched" class="hint" role="status">${t(pageLang, off ? "ui.sum.schedOff" : telegram.connected() ? "ui.sum.schedOn" : "ui.sum.schedOnNoTg")}</p>`);
page = page.replace("<table id=\"list\"></table>", metricsTable(pageLang, metrics.list()));
for (const [id, offNow, why] of [["stop", off, "ui.sum.s.stopWhy"], ["resume", !off, "ui.sum.s.resumeWhy"]]) {
if (!offNow) continue;
page = page.replace(`<button id="${id}" `, `<button id="${id}" class="off" aria-disabled="true" `).replace(`<small id="${id}why"></small>`, `<small id="${id}why">${t(pageLang, why)}</small>`);
}
if (!telegram.connected()) page = page.replace('<small id="sendwhy"></small>', `<small id="sendwhy">${t(pageLang, telegram.missing?.() ? "why.tg.short." + telegram.missing() : "ui.sum.sendWhy")}</small>`);
}
if (url === "/market.html") page = page.replace("<!--regions-->", regionsBox(marketLang, coverage(market.list())));
if (url === "/market.html") page = page.replace(/<div id="out"([^>]*)>/, (m0) => m0 + marketSamples(marketLang, market.list()));
if (url === "/plan.html") {
page = fillSelect(page, "rubric", plan.settings.rubrics.map((r) => [r.id, r.name]));
page = fillSelect(page, "filter", [["", t(pageLang, "ap.all")], ...IDEA_STATUSES.map((s) => [s, t(pageLang, "ap.status." + s)])]);
}
if (url === "/opportunities.html") {
const stages = STAGES.map((s, i) => [s, t(pageLang, "ui.opp.stage." + i)]);
page = page.replace('<p id="lcodehint"></p>', `<p id="lcodehint">${t(pageLang, owner.isSet() ? "letter.codeHint" : "letter.codeHintNew")}</p>`);
page = fillSelect(page, "filter", [["", t(pageLang, "ui.opp.all")], ...stages]);
page = fillSelect(page, "stage", stages);
page = fillSelect(page, "type", [["", t(pageLang, "ui.opp.typeNone")], ...TYPES.filter(Boolean).map((s, i) => [s, t(pageLang, "ui.opp.type." + i)])]);
}
return send(200, page, "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}`));
}