49 lines
2.7 KiB
TypeScript
49 lines
2.7 KiB
TypeScript
// PEP-294: messages of the factory itself (a failure, a launch, a release — `kind = attention`,
|
|
// no `msg_type`) close by themselves once their reason is gone: at once when their task is closed,
|
|
// archived or its project deleted; after 72 h when nothing in them waits for a decision (no
|
|
// options). A message with options is a decision of a person and stays; so does the old untyped
|
|
// «готово» card of a task in review. Agents' questions and done cards (`msg_type` set) are not touched.
|
|
import { m } from "@peppa/shared/i18n";
|
|
import { projects, questions, tasks, type Db } from "@peppa/db";
|
|
import { and, eq, isNull } from "drizzle-orm";
|
|
import { notify } from "./notify.ts";
|
|
|
|
export const FACTORY_MESSAGE_CLOSED_TASK = m("(неактуально: задача закрыта)");
|
|
export const FACTORY_MESSAGE_EXPIRED = m("(неактуально: прошло больше трёх дней)");
|
|
|
|
/** Hours an option-less factory message stays open (PEPPA_FACTORY_MESSAGE_HOURS, default 72; 0 — never closed by age). */
|
|
export function factoryMessageHours(): number {
|
|
const v = process.env.PEPPA_FACTORY_MESSAGE_HOURS;
|
|
const n = v == null || v.trim() === "" ? NaN : Number(v);
|
|
return Number.isFinite(n) && n >= 0 ? n : 72;
|
|
}
|
|
|
|
/** Closes factory messages whose reason has passed; returns how many were closed. The watchdog calls it hourly. */
|
|
export async function expireFactoryMessages(db: Db, o: { now?: Date } = {}): Promise<number> {
|
|
const now = o.now ?? new Date();
|
|
const rows = await db
|
|
.select({ id: questions.id, options: questions.options, createdAt: questions.createdAt, status: tasks.status, archivedAt: tasks.archivedAt, deletedAt: projects.deletedAt })
|
|
.from(questions)
|
|
.innerJoin(projects, eq(projects.id, questions.projectId))
|
|
.leftJoin(tasks, eq(tasks.id, questions.taskId))
|
|
.where(and(isNull(questions.answeredAt), eq(questions.kind, "attention"), isNull(questions.msgType)));
|
|
const hours = factoryMessageHours();
|
|
const cut = now.getTime() - hours * 3_600_000;
|
|
let closed = 0;
|
|
for (const r of rows) {
|
|
let reason: string | null = null;
|
|
if (r.deletedAt || r.archivedAt || r.status === "done") reason = FACTORY_MESSAGE_CLOSED_TASK;
|
|
else if (hours > 0 && !r.options?.length && r.status !== "review" && r.createdAt.getTime() < cut) reason = FACTORY_MESSAGE_EXPIRED;
|
|
if (!reason) continue;
|
|
const [row] = await db
|
|
.update(questions)
|
|
.set({ answer: reason, answeredVia: "system", answeredAt: now, awaitingHook: false })
|
|
.where(and(eq(questions.id, r.id), isNull(questions.answeredAt)))
|
|
.returning({ id: questions.id });
|
|
if (!row) continue;
|
|
closed++;
|
|
await notify(db, { type: "question_answered", questionId: row.id });
|
|
}
|
|
return closed;
|
|
}
|