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 { createStrategyCard, strategyBox } from "./strategy-card.js"; import { SEED_KEY, SEED_SECTIONS, SEED_QUESTIONS as STRATEGY_QUESTIONS } from "./strategy-seed.js"; import { runDue, sendSummary } from "./summary-schedule.js"; import { createJobs } from "./jobs.js"; import { createBotIdentity, webhookUrl, webhookSecret as deriveWebhookSecret } from "./bot-identity.js"; import { createTestRun, CHANNEL as TEST_CHANNEL, NEED_UPDATES } from "./test-run.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 { pickIdea, planCard } from "./plan-card.js"; import { docPage, homePage, sampleFile, pageHtml, regionsBox, competitorsBox, 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 = deriveWebhookSecret(process.env.BRAND_BOT_TOKEN), webhook = webhookUrl(), siteUrl = process.env.PUBLIC_HOST ? "https://" + process.env.PUBLIC_HOST : "", 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 botStore = createBotStore(path.join(path.dirname(file), "bot.json")); // BRM-143: проверочный путь до закрытого тестового канала; материалы и память бренда создаются ниже — берём их при вызове. const testRun = createTestRun({ file: path.join(path.dirname(file), "test-run.json"), telegram, getOwnerChat: () => botStore.chatId(), getPlan: () => plan, savePlan: () => save(), facts: { get: (k) => facts.get(k) }, assets: { forIdea: (id) => assets.forIdea(id), readFile: (id) => assets.readFile(id) }, strategy, pub: () => pub, }); const pub = createPublisher({ file: path.join(path.dirname(file), "publish-state.json"), channels: { telegram, [TEST_CHANNEL]: testRun.adapter }, 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: бот владельца. Распознавание речи — мок, пока нет ключа сервиса. // BRM-165: карточка стратегии Татьяне — отправляет только версия, которая получает сообщения бота. const strategyCard = createStrategyCard({ file: path.join(path.dirname(file), "strategy-card.json"), telegram, strategy, getOwnerChat: () => botStore.chatId(), testRun, enabled: Boolean(webhook), siteUrl, questions: STRATEGY_QUESTIONS }); const strategyElsewhere = !webhook && siteUrl && /-(pr\d+|prod)\./.test(siteUrl) ? siteUrl.replace(/-(pr\d+|prod)\./, "-staging.") + "/strategy.html" : null; const bot = createBot({ store: botStore, telegram, pub, owner, getPlan: () => plan, savePlan: save, transcriber, testRun, strategyCard, siteUrl }); // BRM-150: какой бот подключён и получает ли сообщения; вебхук ставит только версия-владелец (webhook задан). const identity = createBotIdentity({ telegram, url: webhook, secret: webhookSecret }); const botPageView = () => ({ ...botView({ pub, jobs, metrics, telegram, testRun }), bot: identity.view(), bound: botStore.owner(), wordSet: owner.isSet(), // BRM-155: слово задаётся только там, где бот получает сообщения (версия для проверки) и оно не зашито в окружение. wordSetup: Boolean(webhook) && !owner.fixed(), wordWhere: !webhook && /-pr\d+\./.test(siteUrl) ? siteUrl.replace(/-pr\d+\./, "-staging.") + "/bot.html" : null }); // Состояние плана с материалами; идея с датой без материалов помечается 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, rights: a.rights ?? "unknown", 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|rights))?)?$/); 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] === "rights" && method === "POST") { const r = assets.setRights(id, String(body.rights ?? "")); return r ? [200, assetView(r)] : fail(400, "err.asset.rights"); } 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): что можно выбрать в правилах (BRM-103) const ruleOptions = (lang) => ({ channel: listChannels().map((c) => [c.id, t(lang, "ui.ch.name." + c.id)]), rubric: plan.settings.rubrics.map((r) => [String(r.id), r.name]), action: strategy.meta().mustConsent.map((k) => [k, t(lang, "ui.str.act." + k)]), }); 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(), options: ruleOptions(lang), card: strategyCard.view() }]; if (url === "/api/strategy/edit" && method === "POST") return out(strategy.edit(body.sections, body.by, now)); if (url === "/api/strategy/decision" && method === "POST") { const r = strategy.decide(body, now); if (!r.err && body.action === "approve") testRun.arm(Date.parse(now)); // утверждение запускает проверочный путь return out(r); } if (url === "/api/strategy/feedback" && method === "POST") return out(strategy.comment(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/test-run" && method === "GET") return [200, testRun.view()]; if (url === "/api/test-run/check" && method === "POST") { const d = await testRun.diagnose(); return [200, { ok: d.ok, problems: d.problems, view: testRun.view() }]; } if (url === "/api/bot/status" && method === "GET") return [200, botPageView()]; 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()]; } // BRM-158: владелица забыла слово — команда сбрасывает его служебным ключом; после привязки сброса нет. if (url === "/api/owner/reset" && method === "POST") { if (!tokenOk(token, deploySecret)) return [403, { error: t(lang, "err.deploy.denied") }]; if (botStore.owner()) return [409, { error: t(lang, "botp.tg.word.bound") }]; return owner.clear() === "ok" ? [200, { ok: true, wordSet: owner.isSet() }] : [409, { error: t(lang, "botp.tg.word.fixed") }]; } 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 && m.entries?.length)], ["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") { await identity.refresh().catch(() => null); return send(200, botPage(pageLang, { ...botPageView(), wordMsg: ["saved", "short", "mismatch", "bound", "env", "fixed", "notOwner"].find((w) => w === new URLSearchParams(query).get("word")) ?? null, checkMsg: ["ok", "wrong", "none"].find((w) => w === new URLSearchParams(query).get("check")) ?? null, cardMsg: ["done", "wrong", "noWord", "closed"].find((w) => w === new URLSearchParams(query).get("card")) ?? null }, langQ, deploy.view()), "text/html"); } if (req.method === "POST" && url === "/bot/test-check") { // BRM-143: проверить доступ проверочного пути сейчас await testRun.diagnose().catch(() => null); res.writeHead(303, { location: "/bot.html" + langQ }); return res.end(); } // BRM-147: решение по карточке проверочной публикации со страницы — то же, что кнопка в боте, // только со словом для одобрения (на сайте нет входа). Пока слово не задано, решение не принимается. if (req.method === "POST" && url === "/bot/test-card") { let raw = ""; for await (const c of req) raw += c; const f = new URLSearchParams(raw); const card = testRun.view().cards.find((c) => String(c.id) === f.get("id")); let r = !owner.isSet() ? "noWord" : owner.verify(f.get("word") ?? "") !== "ok" ? "wrong" : null; if (!r) { if (!card || card.status !== "waiting" || !["approve", "rework", "reject"].includes(f.get("action"))) r = "closed"; else { await testRun.onButton(f.get("action"), card.id, f.get("h") ?? ""); r = ["approved", "sent", "rework", "rejected"].includes(testRun.view().cards.find((c) => c.id === card.id)?.status) ? "done" : "closed"; } } // BRM-163: решение из карточки записи на «Плане и банке идей» — вернуть к этой записи. if (f.get("back") === "plan") res.writeHead(303, { location: "/plan.html" + langQ + (langQ ? "&" : "?") + "id=" + encodeURIComponent(card?.ideaId ?? "") + "&card=" + r + "#apcard" }); else res.writeHead(303, { location: "/bot.html" + langQ + (langQ ? "&" : "?") + "card=" + r + "#trcards" }); return res.end(); } // BRM-150/155: новое слово для одобрения — пока бот не привязан и только в версии, которая получает сообщения бота. // Слово не попадает ни в адрес, ни в журнал: наружу уходит только код результата. if (req.method === "POST" && url === "/bot/owner-word") { let raw = ""; for await (const c of req) raw += c; const f = new URLSearchParams(raw); const v = botPageView(); const r = v.bound ? "bound" : !webhook ? "env" : owner.reset(f.get("word") ?? "", f.get("confirm") ?? "", f.get("current") ?? ""); res.writeHead(303, { location: "/bot.html" + langQ + (langQ ? "&" : "?") + "word=" + (r === "ok" ? "saved" : r) + "#tgbot" }); return res.end(); } // BRM-155: проверить слово на странице — та же проверка, что у бота. if (req.method === "POST" && url === "/bot/word-check") { let raw = ""; for await (const c of req) raw += c; const r = owner.check(new URLSearchParams(raw).get("word") ?? ""); res.writeHead(303, { location: "/bot.html" + langQ + (langQ ? "&" : "?") + "check=" + r + "#tgbot" }); return res.end(); } 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('

', `

${t(pageLang, off ? "ui.sum.schedOff" : telegram.connected() ? "ui.sum.schedOn" : "ui.sum.schedOnNoTg")}

`); page = page.replace("
", metricsTable(pageLang, metrics.list())); for (const [id, offNow, why] of [["stop", off, "ui.sum.s.stopWhy"], ["resume", !off, telegram.connected() ? "ui.sum.s.resumeWhy" : "ui.sum.s.resumeWhyNoTg"]]) { if (!offNow) continue; page = page.replace(`