BRM-103: страница «Стратегия и правила» — замечание и выбор режимов #99

Merged
peppa-bot merged 1 commits from task/brm-103 into main 2026-11-17 22:28:25 +05:00
12 changed files with 89 additions and 5 deletions
Showing only changes of commit c254ef3f81 - Show all commits

View File

@ -26,6 +26,7 @@
- BRM-99: строка «Что вошло в эту версию» в deployBox (locales deploy.note.*), номер задачи там намеренно; test/contact.test.js её вырезает.
- BRM-100: подсказку #lcodehint на opportunities.html подставляет сервер (owner.isSet()); #lmsg стоит под полем слова.
- BRM-102: пояснение у «Одобрить» — #lapprn на opportunities.html (пусто→btnWhy.pick, есть правки→btnWhy.save, иначе скрыто).
- BRM-103: на strategy.html режим выбирается из списков (options в /api/strategy: каналы/рубрики/действия, канал подставляет сервер); замечание Татьяны — POST /api/strategy/feedback, статус версии не меняет.
## Команды
- BRM-13: Node без зависимостей; `npm test` (сбросить NODE_TEST_CONTEXT, иначе node:test не стартует); lint = node --check src/*.js; dist/ не трогать.

View File

@ -548,6 +548,10 @@
"ui.sum.s.resumeWhy": "Sending is already running.",
"ui.str.hVersions": "Strategy versions",
"ui.str.noPublishNote": "Nothing is published until the strategy is approved.",
"ui.str.fbLabel": "Comment on this version",
"ui.str.fbSend": "Send comment",
"ui.str.fbSendTip": "The comment goes to the agent, who will revise the version.",
"ui.str.fbSent": "The comment was sent to the agent.",
"ui.str.feedbackHint": "Tatyana's comment goes to the agent, who reworks the version; it then has to be approved again.",
"ui.str.sentToAgent": "sent to the agent",
"ui.str.tasksHint": "Once approved, tasks from the 90-day plan appear here, one per plan line.",

View File

@ -548,6 +548,10 @@
"ui.sum.s.resumeWhy": "Жіберу әлдеқашан жүріп жатыр.",
"ui.str.hVersions": "Стратегия нұсқалары",
"ui.str.noPublishNote": "Стратегия бекітілгенге дейін ештеңе жарияланбайды.",
"ui.str.fbLabel": "Нұсқаға ескерту",
"ui.str.fbSend": "Ескертуді жіберу",
"ui.str.fbSendTip": "Ескерту агентке барады, ол нұсқаны жақсартады.",
"ui.str.fbSent": "Ескерту агентке жіберілді.",
"ui.str.feedbackHint": "Татьянаның ескертуі агентке жіберіледі: ол нұсқаны өңдейді, содан кейін оны қайта бекіту керек.",
"ui.str.sentToAgent": "агентке жіберілді",
"ui.str.tasksHint": "Бекітілгеннен кейін мұнда 90 күндік жоспардың міндеттері пайда болады — жоспардың әр жолына біреуден.",

View File

@ -548,6 +548,10 @@
"ui.sum.s.resumeWhy": "Рассылка уже идёт.",
"ui.str.hVersions": "Версии стратегии",
"ui.str.noPublishNote": "До утверждения стратегии ничего не публикуется.",
"ui.str.fbLabel": "Замечание к версии",
"ui.str.fbSend": "Отправить замечание",
"ui.str.fbSendTip": "Замечание уйдёт агенту, он доработает версию.",
"ui.str.fbSent": "Замечание отправлено агенту.",
"ui.str.feedbackHint": "Замечание Татьяны уходит агенту: он перерабатывает версию, после чего её снова нужно утвердить.",
"ui.str.sentToAgent": "передано агенту",
"ui.str.tasksHint": "После утверждения здесь появятся задачи из плана на 90 дней — по одной на строку плана.",

View File

@ -0,0 +1,3 @@
## Решения
- Замечание — POST /api/strategy/feedback, статус версии не меняет.
- Варианты правил отдаёт сервер (options в /api/strategy), канал в разметке подставляется сервером.

View File

@ -0,0 +1,7 @@
## Why
Страница «Стратегия и правила» не закрывала приёмку: замечание Татьяны можно было отправить только вместе с возвратом версии, а режим для канала, рубрики и действия вводился вручную.
## What Changes
- Отдельное поле «Замечание к версии» с пометкой «передано агенту».
- Режим выбирается из списков каналов, рубрик и действий; видно режим каждого пункта.
## Impact
src/strategy.js, src/server.js, public/strategy.html, locales.

View File

@ -0,0 +1,13 @@
## ADDED Requirements
### Requirement: Замечание и выбор режимов на странице стратегии
Страница SHALL позволять отправить замечание к версии и выбрать режим из списков.
#### Scenario: Замечание отправлено
- **GIVEN** есть версия стратегии
- **WHEN** Татьяна отправляет замечание «Добавить Instagram»
- **THEN** в списке замечаний видно «передано агенту»
#### Scenario: Пустое замечание
- **GIVEN** есть версия стратегии
- **WHEN** Татьяна отправляет пустое замечание
- **THEN** видна ошибка с просьбой написать замечание

View File

@ -0,0 +1,4 @@
## 1. Реализация
- [x] 1.1 Поле замечания и API
- [x] 1.2 Выбор канала, рубрики, действия из списков
- [x] 1.3 Тесты

View File

@ -0,0 +1,19 @@
# strategy Specification
## Purpose
TBD - created by archiving change brm-103-strategy-page-gaps. Update Purpose after archive.
## Requirements
### Requirement: Замечание и выбор режимов на странице стратегии
Страница SHALL позволять отправить замечание к версии и выбрать режим из списков.
#### Scenario: Замечание отправлено
- **GIVEN** есть версия стратегии
- **WHEN** Татьяна отправляет замечание «Добавить Instagram»
- **THEN** в списке замечаний видно «передано агенту»
#### Scenario: Пустое замечание
- **GIVEN** есть версия стратегии
- **WHEN** Татьяна отправляет пустое замечание
- **THEN** видна ошибка с просьбой написать замечание

View File

@ -24,11 +24,13 @@ input,select,textarea,button{font:inherit}#err{color:#b00}#ok{color:#070}.hint{f
<button id="back" data-t="ui.str.return" data-tip="ui.str.returnTip"></button></div>
<p id="err"></p><p id="ok"></p>
<h2 data-t="ui.str.hFeedback"></h2><p class="hint" data-t="ui.str.feedbackHint"></p><ul id="feedback"><li class="none" data-t="ui.str.noFeedback"></li></ul>
<div class="row"><label><span data-t="ui.str.fbLabel"></span><textarea id="fb" rows="3"></textarea></label>
<button id="fbsend" data-t="ui.str.fbSend" data-tip="ui.str.fbSendTip"></button></div>
<h2 data-t="ui.str.hRules"></h2>
<p class="hint" data-t="ui.str.rulesHint"></p>
<div class="row">
<label><span data-t="ui.str.rule.kind"></span><select id="kind"><option value="channel" data-t="ui.str.kind.channel"></option><option value="rubric" data-t="ui.str.kind.rubric"></option><option value="action" data-t="ui.str.kind.action"></option></select></label>
<label><span data-t="ui.str.rule.key"></span><input id="key" data-ph="ui.str.rule.keyPh"></label>
<label><span data-t="ui.str.rule.key"></span><select id="key"></select></label>
<label><span data-t="ui.str.rule.mode"></span><select id="mode"><option value="draft" data-t="ui.str.mode.draft"></option><option value="each" data-t="ui.str.mode.each"></option><option value="auto" data-t="ui.str.mode.auto"></option></select></label>
<button id="rule" data-t="ui.str.rule.save" data-tip="ui.str.rule.saveTip"></button></div>
<ul id="rules"></ul>
@ -46,19 +48,24 @@ const WANT=new URLSearchParams(location.search).get("lang")||"ru";
async function api(m,u,b){const r=await fetch(u,{method:m,headers:{"content-type":"application/json","x-lang":WANT},body:b&&JSON.stringify(b)});return[r.ok,await r.json()]}
const list=(el,items,k)=>{el.innerHTML=items.length?items.map(i=>`<li>${i}</li>`).join(""):`<li class="none">${esc(t(k))}</li>`};
let D=null;
const fillKey=()=>{const k=$("kind").value;$("key").innerHTML=((D&&D.options&&D.options[k])||[]).map(([v,l])=>`<option value="${esc(v)}">${esc(l)}</option>`).join("")};
$("kind").onchange=fillKey;
async function load(){const[,d]=await api("GET","/api/strategy");D=d;const v=d.current;
$("state").textContent=v?t("ui.str.v")+" "+v.n+": "+t("ui.str.st."+v.status)+(d.approved?"":" — "+t("ui.str.noPublish")):t("ui.str.none");$("state").classList.toggle("on",d.approved);
if(!$("fields").children.length)$("fields").innerHTML=d.sections.map(s=>`<label><span>${esc(t("ui.str.sec."+s))}</span><textarea id="f_${s}" rows="3"></textarea></label>`).join("");
for(const s of d.sections){const e=$("f_"+s);if(document.activeElement!==e)e.value=v?v.sections[s]:""}
list($("versions"),d.versions.slice().reverse().map(x=>esc(t("ui.str.v"))+" "+x.n+" — "+esc(t("ui.str.st."+x.status))+(x.approvedAt?" ("+esc(String(x.approvedAt).slice(0,10))+")":"")),"ui.str.none");
list($("feedback"),v?v.comments.map(c=>esc(c.by)+": "+esc(c.text)+" — "+esc(t("ui.str.sentToAgent"))):[],"ui.str.noFeedback");
list($("rules"),d.rules.map(r=>esc(t("ui.str.kind."+r.kind))+" «"+esc(r.key)+"» — "+esc(t("ui.str.mode."+r.mode))),"ui.str.noRules");
const keep=$("key").value;fillKey();if(keep)$("key").value=keep;
const nm=(k,key)=>((d.options[k]||[]).find(o=>o[0]===String(key))||[0,key])[1];
list($("rules"),["channel","rubric","action"].flatMap(k=>d.options[k].map(([key,name])=>{const r=d.rules.find(x=>x.kind===k&&x.key===key);return esc(t("ui.str.kind."+k))+" «"+esc(name)+"» — "+esc(t("ui.str.mode."+(r?r.mode:"draft")))})),"ui.str.noRules");
list($("must"),d.mustConsent.map(k=>esc(t("ui.str.act."+k))),"ui.str.noRules");
list($("tasks"),d.tasks.map(x=>esc(x.title)),"ui.str.noTasks")}
const done=(ok,d,m)=>{$("err").textContent=ok?"":d.error+(d.missing?" ("+d.missing.map(s=>t("ui.str.sec."+s)).join(", ")+")":"");$("ok").textContent=ok?t(m):"";if(ok)load()};
$("save").onclick=async()=>{const sections=Object.fromEntries(D.sections.map(s=>[s,$("f_"+s).value]));const[ok,d]=await api("POST","/api/strategy/edit",{sections,by:$("by").value});done(ok,d,"ui.str.saved")};
$("approve").onclick=async()=>{const[ok,d]=await api("POST","/api/strategy/decision",{action:"approve",by:$("by").value});done(ok,d,"ui.str.approved")};
$("back").onclick=async()=>{const[ok,d]=await api("POST","/api/strategy/decision",{action:"return",comment:$("comment").value,by:$("by").value});done(ok,d,"ui.str.returned")};
$("fbsend").onclick=async()=>{const[ok,d]=await api("POST","/api/strategy/feedback",{text:$("fb").value,by:$("by").value});if(ok)$("fb").value="";done(ok,d,"ui.str.fbSent")};
$("rule").onclick=async()=>{const[ok,d]=await api("PUT","/api/strategy/rules",{kind:$("kind").value,key:$("key").value,mode:$("mode").value});done(ok,d,"ui.str.ruleSaved")};
$("grant").onclick=async()=>{const[ok,d]=await api("POST","/api/strategy/consent",{text:$("ctext").value,by:$("by").value});done(ok,d,"ui.str.granted")};
api("GET","/api/texts").then(([,d])=>{T=d.texts;document.title=t("ui.str.title");document.documentElement.lang=d.lang;

View File

@ -144,14 +144,20 @@ export function createApp({ file, oppsFile, metricsFile, telegram = createTelegr
return [405, { error: "method" }];
}
// Стратегия и правила автономности (BRM-53)
// Стратегия и правила автономности (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() }];
return [200, { current: strategy.current(), versions: strategy.versions(), rules: strategy.rules(), tasks: strategy.tasks(), approved: strategy.isApproved(), ...strategy.meta(), options: ruleOptions(lang) }];
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/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" }];
@ -361,6 +367,7 @@ export function createApp({ file, oppsFile, metricsFile, telegram = createTelegr
}
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 === "/strategy.html") page = fillSelect(page, "key", ruleOptions(pageLang).channel);
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") {

View File

@ -59,6 +59,17 @@ export function createStrategy(file) {
return { err: "err.action" };
}
// Замечание Татьяны к текущей версии: уходит агенту, статус версии не меняет.
function comment({ text, by }, now) {
const v = cur();
if (!v) return { err: "err.strategy.nothingToDecide" };
const body = String(text ?? "").trim();
if (!body) return { err: "err.strategy.commentRequired" };
v.comments.push({ text: body, by: by || "", at: now });
save();
return { ok: true, version: view(v) };
}
function setRule({ kind, key, mode }) {
if (!KINDS.includes(kind) || !String(key ?? "").trim()) return { err: "err.strategy.rule" };
if (!MODES.includes(mode)) return { err: "err.strategy.mode" };
@ -92,7 +103,7 @@ export function createStrategy(file) {
}
return {
edit, decide, setRule, grant, gate, isApproved,
edit, decide, comment, setRule, grant, gate, isApproved,
current: () => view(cur()),
versions: () => st.versions.map(view),
rules: () => st.rules.slice(),