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 { createPublisher } from "./publisher.js"; import { runDue, sendSummary } from "./summary-schedule.js"; import { createLetters, letterView } from "./letters.js"; import { createOwner } from "./owner.js"; import { mockDraftWriter } from "./mock-draft-writer.js"; import { createMarketStore, KINDS } from "./market.js"; import { REPORT_RECORDS } from "./market-seed.js"; import { TEXTS, pickLang, t } from "./i18n.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(), draftWriter = mockDraftWriter, ownerCode = process.env.OWNER_CODE }) { 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 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 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, }); // Письмо организатору (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") { 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 === "/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/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/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.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, r] : [404, { error: "Запись не найдена" }]; } const kind = new URLSearchParams(query).get("type") || ""; if (kind && !KINDS.includes(kind)) return [400, { error: "Неизвестный тип записи" }]; return [200, { items: market.list(kind) }]; } 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 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" }]; } 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("?"); 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 lang = pickLang(req.headers["x-lang"], req.headers["accept-language"]); const [code, data] = await handle(req.method, url, body, query, lang); send(code, data); } catch (e) { send(500, { error: "internal" }); } }); server.runDue = (now) => runDue({ pub, metrics, now }); 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}`)); }