todo_service: новый сервис todo (надстройка над JobTread, REST, MCP, вебхуки, слежение Control), миграция 024, docs в proposed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
126
packages/todo_service/src/watchers.ts
Normal file
126
packages/todo_service/src/watchers.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { addDays, localDate, type Logger, type Pool } from "khb_common";
|
||||
import type { TodoCore } from "./core.js";
|
||||
import type { JtApi } from "./jt.js";
|
||||
import { isClosed } from "./rules.js";
|
||||
import type { TodoServiceSettings } from "./settings.js";
|
||||
|
||||
/**
|
||||
* Слежение (переехало из агентов): Control (исполнитель закрыл - "выполнено", срок наступил и действий нет - "просрочено"),
|
||||
* review_date. Сервис решает, ЧТО произошло, и пишет событие; агент решает, ЧТО сказать. Control todo сервис НЕ закрывает.
|
||||
*/
|
||||
export class Watchers {
|
||||
constructor(
|
||||
private readonly core: TodoCore,
|
||||
private readonly pool: Pool,
|
||||
private readonly jt: JtApi,
|
||||
private readonly settings: TodoServiceSettings,
|
||||
private readonly tz: string,
|
||||
private readonly log: Logger,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
private async item(id: string): Promise<{ progress: number | null; deleted: boolean; lastEventAt: Date | null; createdAt: Date | null; name: string; known: boolean }> {
|
||||
let r = (await this.pool.query("select progress::float8 as progress, is_deleted, last_event_at, jt_created_at, name from todo_item where task_id = $1", [id])).rows[0];
|
||||
if (!r) {
|
||||
await this.core.syncTask(id).catch(() => false);
|
||||
r = (await this.pool.query("select progress::float8 as progress, is_deleted, last_event_at, jt_created_at, name from todo_item where task_id = $1", [id])).rows[0];
|
||||
}
|
||||
if (!r) return { progress: null, deleted: false, lastEventAt: null, createdAt: null, name: "", known: false };
|
||||
return { progress: r.progress, deleted: !!r.is_deleted, lastEventAt: r.last_event_at, createdAt: r.jt_created_at, name: String(r.name), known: true };
|
||||
}
|
||||
|
||||
/** Одна проверка пар Control. Возвращает число изменений статуса. */
|
||||
async controlTick(): Promise<number> {
|
||||
const now = this.now();
|
||||
const today = localDate(now, this.tz);
|
||||
const { rows } = await this.pool.query(
|
||||
"select id, task_id, linked_task_id, controller_person_id, executor_name, to_char(control_due, 'YYYY-MM-DD') as control_due, status from todo_link where status in ('active', 'overdue') order by created_at",
|
||||
);
|
||||
let changed = 0;
|
||||
for (const l of rows) {
|
||||
const exec = await this.item(String(l.linked_task_id));
|
||||
const ctrl = await this.item(String(l.task_id));
|
||||
let next: "closed" | "done" | "overdue" | null = null;
|
||||
if (ctrl.known && (ctrl.deleted || isClosed(ctrl.progress))) next = "closed"; // закрыл контролёр: слежение снимается без сообщений
|
||||
else if (exec.known && (isClosed(exec.progress) || exec.deleted)) next = "done";
|
||||
else if (l.status === "active" && l.control_due && l.control_due <= today) {
|
||||
const quiet = addDays(today, -this.settings.control.quietDays);
|
||||
const last = exec.lastEventAt ? localDate(exec.lastEventAt, this.tz) : null;
|
||||
if (!last || last <= quiet) next = "overdue";
|
||||
}
|
||||
if (!next) continue;
|
||||
await this.pool.query("update todo_link set status = $2, updated_at = now() where id = $1", [l.id, next]);
|
||||
if (next !== "closed") {
|
||||
await this.pool.query(
|
||||
"update todo_ext set done_flag = $2, overdue_flag = $3, updated_at = now() where task_id = $1",
|
||||
[l.task_id, next === "done", next === "overdue"],
|
||||
);
|
||||
await this.reconcileControlName(String(l.task_id));
|
||||
await this.pool.query("insert into todo_event (event_type, task_id, person_id, payload) values ($1,$2,$3,$4)", [
|
||||
next === "done" ? "control_done" : "control_overdue",
|
||||
l.task_id,
|
||||
l.controller_person_id,
|
||||
{ controlTaskId: l.task_id, executorTaskId: l.linked_task_id, executorName: exec.name || l.executor_name, controlDue: l.control_due },
|
||||
]);
|
||||
}
|
||||
changed++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private async reconcileControlName(controlTaskId: string): Promise<void> {
|
||||
await this.core.reconcile(controlTaskId);
|
||||
}
|
||||
|
||||
/** review_date наступил: одно событие review_due на каждую дату, адресат - person исполнителя(ей), иначе без адресата. */
|
||||
async reviewTick(): Promise<number> {
|
||||
const today = localDate(this.now(), this.tz);
|
||||
const { rows } = await this.pool.query(
|
||||
`select e.task_id, to_char(e.review_date, 'YYYY-MM-DD') as review_date, i.name, i.assignee_ids,
|
||||
(select array_agg(p.id) from person p where p.jt_membership_id = any(i.assignee_ids)) as persons
|
||||
from todo_ext e join todo_item i on i.task_id = e.task_id
|
||||
where e.review_date <= $1::date and (e.review_notified_for is distinct from e.review_date) and not i.is_deleted and (i.progress is null or i.progress < 1)`,
|
||||
[today],
|
||||
);
|
||||
for (const r of rows) {
|
||||
const persons: (string | null)[] = (r.persons as string[] | null) ?? [null];
|
||||
for (const p of persons)
|
||||
await this.pool.query("insert into todo_event (event_type, task_id, person_id, payload) values ('review_due',$1,$2,$3)", [r.task_id, p, { name: r.name, reviewDate: r.review_date }]);
|
||||
await this.pool.query("update todo_ext set review_notified_for = review_date where task_id = $1", [r.task_id]);
|
||||
}
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
/** Доставка событий агентам (если включена): окно часов по локальному времени; режим off у получателя - не доставляется. */
|
||||
async deliverEvents(fetchFn: typeof fetch = fetch): Promise<number> {
|
||||
const n = this.settings.notify;
|
||||
if (!n.enabled || !n.url) return 0;
|
||||
const hour = Number(new Intl.DateTimeFormat("en-US", { timeZone: this.tz, hour: "numeric", hourCycle: "h23" }).format(this.now()));
|
||||
if (hour < n.fromHour || hour >= n.toHour) return 0;
|
||||
const { rows } = await this.pool.query(
|
||||
`select ev.id, ev.event_type, ev.task_id, ev.person_id, ev.payload
|
||||
from todo_event ev left join construction_manager cm on cm.person_id = ev.person_id
|
||||
where ev.delivered_at is null and ev.person_id is not null and not (coalesce(cm.agent_paused, false) and cm.pause_mode = 'off')
|
||||
order by ev.id limit 100`,
|
||||
);
|
||||
const byPerson = new Map<string, typeof rows>();
|
||||
for (const r of rows) byPerson.set(String(r.person_id), [...(byPerson.get(String(r.person_id)) ?? []), r]);
|
||||
let sent = 0;
|
||||
for (const [personId, list] of byPerson) {
|
||||
try {
|
||||
const res = await fetchFn(n.url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...(n.token ? { authorization: `Bearer ${n.token}` } : {}) },
|
||||
body: JSON.stringify({ kind: "todo_events", personId, events: list.map((e) => ({ id: Number(e.id), type: e.event_type, taskId: e.task_id, payload: e.payload })) }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
await this.pool.query("update todo_event set delivered_at = now(), delivery_error = null where id = any($1::bigint[])", [list.map((e) => e.id)]);
|
||||
sent += list.length;
|
||||
} catch (e) {
|
||||
await this.pool.query("update todo_event set delivery_error = $2 where id = any($1::bigint[])", [list.map((x) => x.id), String(e)]);
|
||||
this.log.warn({ personId, err: String(e) }, "доставка событий агенту не удалась");
|
||||
}
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user