136 lines
7.6 KiB
TypeScript
136 lines
7.6 KiB
TypeScript
// PEP-198: «Фабрика решила за вас». The analyst takes the product decisions of a story itself
|
|
// (PEP-94: it asks nobody) — they are not hidden in the description any more but listed on the
|
|
// story page with «Подходит» / «Нужно иначе». Each decision has a status: by default (nobody
|
|
// looked), confirmed, changed (with what it was and who changed it). The split of a request into
|
|
// parts is a decision as well («Разделила на N задач»). The «Допущения» section of the story's
|
|
// description is built from the list. State lives in `settings` (`task.decisions:<taskId>`,
|
|
// `task.split-of:<partId>`): no schema change. What a change sets in motion is runner/decisions.ts.
|
|
import { m as tr } from "@peppa/shared/i18n";
|
|
import { settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
|
import { and, eq, inArray, like } from "drizzle-orm";
|
|
import { logEvent } from "./audit.ts";
|
|
import { PeppaError } from "./errors.ts";
|
|
import { notify } from "./notify.ts";
|
|
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
|
|
|
export type DecisionStatus = "default" | "confirmed" | "changed";
|
|
|
|
export interface Decision {
|
|
id: number;
|
|
text: string;
|
|
status: DecisionStatus;
|
|
/** `split` — the request was split into parts (`parts`: their task ids). */
|
|
kind: "plain" | "split";
|
|
/** Login of who confirmed or changed it. */
|
|
by: string | null;
|
|
at: string | null;
|
|
/** The text before the change. */
|
|
was: string | null;
|
|
parts?: number[];
|
|
/** `split`: what the analyst postponed (goes back to the description on «Не делить»). */
|
|
deferred?: string[];
|
|
}
|
|
|
|
export const DECISION_STATUS_LABEL: Record<DecisionStatus, string> = {
|
|
default: tr("по умолчанию"),
|
|
confirmed: tr("подтверждено"),
|
|
changed: tr("изменено"),
|
|
};
|
|
|
|
const key = (taskId: number) => `task.decisions:${taskId}`;
|
|
const splitOfKey = (partId: number) => `task.split-of:${partId}`;
|
|
const SPLIT_OF_PREFIX = "task.split-of:";
|
|
|
|
export async function getDecisions(db: Db, taskId: number): Promise<Decision[]> {
|
|
return (await getSetting<Decision[]>(db, key(taskId))) ?? [];
|
|
}
|
|
|
|
async function save(db: Db, taskId: number, list: Decision[]): Promise<void> {
|
|
await setSetting(db, key(taskId), list);
|
|
await notify(db, { type: "task_updated", taskId });
|
|
}
|
|
|
|
/** The analyst's decisions after intake (replaces what it decided before; the owner's answers stay). */
|
|
export async function setDecisions(db: Db, taskId: number, texts: string[], split?: { text: string; parts: number[]; deferred: string[] }): Promise<Decision[]> {
|
|
const kept = (await getDecisions(db, taskId)).filter((d) => d.status !== "default");
|
|
let id = kept.reduce((n, d) => Math.max(n, d.id), 0);
|
|
const fresh: Decision[] = texts
|
|
.map((t) => t.trim())
|
|
.filter((t) => t && !kept.some((d) => d.text === t))
|
|
.map((text) => ({ id: ++id, text, status: "default", kind: "plain", by: null, at: null, was: null }));
|
|
if (split && split.parts.length) fresh.push({ id: ++id, text: split.text, status: "default", kind: "split", by: null, at: null, was: null, parts: split.parts, deferred: split.deferred });
|
|
const list = [...kept, ...fresh];
|
|
await save(db, taskId, list);
|
|
return list;
|
|
}
|
|
|
|
/** Decisions nobody has looked at yet («Фабрика решила за вас N пунктов — проверьте»). */
|
|
export const openDecisions = (list: Decision[]) => list.filter((d) => d.status === "default").length;
|
|
|
|
function find(list: Decision[], id: number): Decision {
|
|
const d = list.find((x) => x.id === id);
|
|
if (!d) throw new PeppaError(tr("Этого решения уже нет. Обновите страницу."));
|
|
return d;
|
|
}
|
|
|
|
/** «Подходит»: only the status changes, nothing is set in motion. */
|
|
export async function confirmDecision(db: Db, task: { id: number; projectId: number }, id: number, by: string): Promise<Decision> {
|
|
const list = await getDecisions(db, task.id);
|
|
const d = find(list, id);
|
|
if (d.status === "default") Object.assign(d, { status: "confirmed", by, at: new Date().toISOString() });
|
|
await save(db, task.id, list);
|
|
await logEvent(db, { projectId: task.projectId, taskId: task.id, type: "decision_confirmed", payload: { id, text: d.text, login: by } });
|
|
return d;
|
|
}
|
|
|
|
/** «Нужно иначе»: the decision becomes the owner's words; returns the decision with `was`. */
|
|
export async function changeDecision(db: Db, task: { id: number; projectId: number }, id: number, how: string, by: string): Promise<Decision> {
|
|
const text = how.trim();
|
|
if (!text) throw new PeppaError(tr("Напишите, как нужно."));
|
|
const list = await getDecisions(db, task.id);
|
|
const d = find(list, id);
|
|
Object.assign(d, { was: d.status === "changed" ? d.was : d.text, text, status: "changed", by, at: new Date().toISOString() });
|
|
await save(db, task.id, list);
|
|
await logEvent(db, { projectId: task.projectId, taskId: task.id, type: "decision_changed", payload: { id, was: d.was, text, login: by } });
|
|
return d;
|
|
}
|
|
|
|
/** Lines of the «Допущения» section for the developer. */
|
|
export function decisionsAssumptions(list: Decision[]): string[] {
|
|
return list.filter((d) => d.kind === "plain").map((d) => (d.status === "changed" ? `${d.text} (решение владельца; было: ${d.was ?? "—"})` : d.text));
|
|
}
|
|
|
|
/** The description with its «Допущения» section rebuilt from the decisions. */
|
|
export function withAssumptions(description: string, list: Decision[]): string {
|
|
const lines = decisionsAssumptions(list);
|
|
const section = lines.length ? `## Допущения\n${lines.map((l) => `- ${l}`).join("\n")}\n` : "";
|
|
if (/^## Допущения\n/m.test(description)) return description.replace(/^## Допущения\n(?:- .*\n?)*\n?/m, section ? `${section}\n` : "");
|
|
if (!section) return description;
|
|
// Before «Исходный запрос» when there is one, else at the end.
|
|
return /^## Исходный запрос$/m.test(description) ? description.replace(/^## Исходный запрос$/m, `${section}\n## Исходный запрос`) : `${description.trimEnd()}\n\n${section}`;
|
|
}
|
|
|
|
// ── parts of a split ───────────────────────────────────────────────────────────
|
|
|
|
export async function markSplitPart(db: Db, partId: number, parentId: number): Promise<void> {
|
|
await setSetting(db, splitOfKey(partId), parentId);
|
|
}
|
|
export const splitParent = (db: Db, partId: number) => getSetting<number>(db, splitOfKey(partId));
|
|
export const clearSplitPart = (db: Db, partId: number) => deleteSetting(db, splitOfKey(partId));
|
|
|
|
/** Parts of a split whose first story is not accepted yet: the dispatcher does not take them (4.1). */
|
|
export async function splitWaiting(db: Db, projectId: number): Promise<Set<number>> {
|
|
const rows = await db.select().from(settings).where(keyPrefix(settings.key, `${SPLIT_OF_PREFIX}`));
|
|
if (!rows.length) return new Set();
|
|
const pairs = rows.map((r) => ({ part: Number(r.key.slice(SPLIT_OF_PREFIX.length)), parent: Number(r.value) })).filter((p) => p.part && p.parent);
|
|
const ids = [...new Set(pairs.flatMap((p) => [p.part, p.parent]))];
|
|
const found = await db.select({ id: tasks.id, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(and(inArray(tasks.id, ids), eq(tasks.projectId, projectId)));
|
|
const byId = new Map(found.map((t) => [t.id, t]));
|
|
const out = new Set<number>();
|
|
for (const p of pairs) {
|
|
const parent = byId.get(p.parent);
|
|
if (byId.has(p.part) && parent && parent.status !== "done" && !parent.archivedAt) out.add(p.part);
|
|
}
|
|
return out;
|
|
}
|