import type { Pool } from "khb_common"; /** Условие SQL: агент не в режиме off (passive и включённый - шаг 2 и ответы идут). */ export const NOT_OFF_SQL = (alias = "cm"): string => `(${alias}.pause_mode = 'passive' or (not ${alias}.agent_paused and (${alias}.paused_until is null or ${alias}.paused_until <= now())))`; /** Условие SQL: агент менеджера включён (не отключён бессрочно и срок отключения истёк). */ export const NOT_PAUSED_SQL = (alias = "cm"): string => `(not ${alias}.agent_paused and (${alias}.paused_until is null or ${alias}.paused_until <= now()))`; export type PauseMode = "passive" | "off"; /** Пассивное окно календаря: день недели (ISO, 1 - понедельник) и интервал в минутах от полуночи в часовом поясе окна. */ export interface PassiveWindow { id?: string; weekday: number; fromMinute: number; toMinute: number; timezone: string; note: string | null; } /** День недели (ISO) и минуты от полуночи момента `now` в часовом поясе. */ export function localWeekdayMinute(now: Date, timezone: string): { weekday: number; minute: number } { const parts = new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(now); const get = (t: string) => parts.find((x) => x.type === t)?.value ?? ""; const weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(get("weekday")) + 1; return { weekday, minute: Number(get("hour")) * 60 + Number(get("minute")) }; } export const inWindow = (w: PassiveWindow, now: Date): boolean => { const l = localWeekdayMinute(now, w.timezone); return l.weekday === w.weekday && l.minute >= w.fromMinute && l.minute < w.toMinute; }; export async function loadWindows(pool: Pool): Promise { const { rows } = await pool.query("select id, weekday, from_minute, to_minute, timezone, note from agent_passive_window where is_active order by weekday, from_minute"); return rows.map((r) => ({ id: String(r.id), weekday: Number(r.weekday), fromMinute: Number(r.from_minute), toMinute: Number(r.to_minute), timezone: String(r.timezone), note: (r.note as string | null) ?? null })); } /** Пассивное окно календаря, действующее сейчас (null - нет). */ export async function activeWindow(pool: Pool, now: Date = new Date()): Promise { return (await loadWindows(pool)).find((w) => inWindow(w, now)) ?? null; } export interface PauseState { paused: boolean; /** passive - молчит, пока ему не пишут (на сообщения отвечает как обычно); off - ничего не делает. */ mode: PauseMode; /** true - отключён до команды владельца (без срока). */ indefinite: boolean; until: Date | null; reason: string | null; by: string | null; } export async function pauseState(pool: Pool, managerId: string, now: Date = new Date()): Promise { const { rows } = await pool.query( `select (not ${NOT_PAUSED_SQL("cm")}) as paused, cm.pause_mode, cm.agent_paused, cm.paused_until, cm.pause_reason, cm.paused_by from construction_manager cm where cm.person_id = $1`, [managerId], ); const r = rows[0]; if (!r) return { paused: false, mode: "passive", indefinite: false, until: null, reason: null, by: null }; const paused = r.paused === true; if (!paused) { // календарь пассивных окон (например, вторник): агент в режиме passive у всех менеджеров const w = await activeWindow(pool, now); if (w) return { paused: true, mode: "passive", indefinite: false, until: null, reason: `календарь: ${w.note ?? "пассивное окно"}`, by: "calendar" }; } return { paused, mode: r.pause_mode === "off" ? "off" : "passive", indefinite: paused && r.agent_paused === true, until: paused && !r.agent_paused ? (r.paused_until as Date) : null, reason: paused ? (r.pause_reason as string | null) : null, by: paused ? (r.paused_by as string | null) : null }; } export interface PauseOptions { /** Срок отключения; null/не задан - до команды владельца. */ until?: Date | null; reason?: string | null; by?: string | null; /** passive (по умолчанию) - молчит, пока ему не пишут; off - вообще ничего. */ mode?: PauseMode; } const SET_PAUSE = `update construction_manager set agent_paused = $2, paused_until = $3, pause_reason = $4, paused_by = $5, paused_at = now(), pause_mode = $6`; /** Отключает агента менеджера: на время (until) или до команды (until не задан). Возвращает false, если менеджера нет. */ export async function setPause(pool: Pool, managerId: string, o: PauseOptions = {}): Promise { const r = await pool.query(`${SET_PAUSE} where person_id = $1`, [managerId, !o.until, o.until ?? null, o.reason ?? null, o.by ?? null, o.mode ?? "passive"]); return (r.rowCount ?? 0) > 0; } /** Включает агента менеджера обратно. */ export async function resumeManager(pool: Pool, managerId: string): Promise { const r = await pool.query( "update construction_manager set agent_paused = false, paused_until = null, pause_reason = null, paused_by = null, paused_at = null where person_id = $1", [managerId], ); return (r.rowCount ?? 0) > 0; } /** Отключает агентов всех активных менеджеров. Возвращает число менеджеров. */ export async function setPauseAll(pool: Pool, o: PauseOptions = {}): Promise { const r = await pool.query( "update construction_manager set agent_paused = $1, paused_until = $2, pause_reason = $3, paused_by = $4, paused_at = now(), pause_mode = $5 where is_active", [!o.until, o.until ?? null, o.reason ?? null, o.by ?? null, o.mode ?? "passive"], ); return r.rowCount ?? 0; } export async function resumeAll(pool: Pool): Promise { const r = await pool.query("update construction_manager set agent_paused = false, paused_until = null, pause_reason = null, paused_by = null, paused_at = null where agent_paused or paused_until is not null"); return r.rowCount ?? 0; }