Отчёты по сотрудникам: To-do report и Employee Activity, события JobTread в data_collector
All checks were successful
ci / test (push) Successful in 23s
ci / deploy (push) Successful in 1m41s

Новый package employee_reports (порт 8091): To-do report перенесён идейно из
khbuild_tests на зеркало Supabase (Stale Days, выбор снимка, Excel-выгрузка) и
дополнен показателем «любая активность в инфополе»; Employee Activity - у каждого
менеджера встроенный график по дням с цветом дня (зелёный - Daily Log, жёлтый -
активность не меньше порога, тёмно-красный - меньше порога) и итоговый график
зелёных и жёлтых людей внизу.

data_collector: модуль events (jt_event, POST /events/sync) - загрузка ленты
событий JobTread; миграция 009; методология docs/activity_methodology.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-15 14:38:00 +03:00
parent 96b53c5487
commit 715546bdae
46 changed files with 3261 additions and 7 deletions

View File

@@ -0,0 +1,117 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
import { classifyEvent, fetchEvents, syncEvents, toRow, type RawEvent } from "./jt-events.js";
// Формы событий - с реальных данных JobTread (organization.events)
const todoClosed: RawEvent = {
id: "e1", type: "taskUpdated", createdAt: "2026-10-14T15:38:53.424Z", createdByUser: { id: "u1", name: "Arthur Atanoff" },
data: { next: { progress: 1 }, previous: { progress: null } },
task: { id: "t1", isToDo: true, taskType: null, job: { id: "j1" } },
};
const todoCreated: RawEvent = {
id: "e2", type: "taskCreated", createdAt: "2026-10-11T20:34:53.453Z", createdByUser: { id: "u2", name: "Yuri" },
data: { next: { id: "t2", name: "todo", jobId: "j2", isToDo: true, endDate: "2026-10-12", progress: null, accountId: "a" } },
task: { id: "t2", isToDo: true, taskType: null, job: { id: "j2" } },
};
const milestoneClosed: RawEvent = {
id: "e3", type: "taskUpdated", createdAt: "2026-10-12T10:00:00Z", createdByUser: { id: "u3", name: "Walter Walker" },
data: { next: { progress: 1 }, previous: { progress: 0.4 } },
task: { id: "t3", isToDo: false, taskType: { name: "Milestone" }, job: { id: "j3" } },
};
const milestoneMoved: RawEvent = {
id: "e4", type: "taskUpdated", createdAt: "2026-10-12T11:00:00Z", createdByUser: { id: "u3", name: "Walter Walker" },
data: { next: { endDate: "2026-10-20", startDate: "2026-10-13" }, previous: { endDate: "2026-10-16", startDate: "2026-10-12" } },
task: { id: "t3", isToDo: false, taskType: { name: "test-Milestone" }, job: { id: "j3" } },
};
const dailyLog: RawEvent = {
id: "e5", type: "dailyLogCreated", createdAt: "2026-10-13T15:12:33.857Z", createdByUser: { id: "u4", name: "Zachary Gange" },
data: { next: { id: "dl1", date: "2026-10-13", jobId: "j4", notes: "очень длинные заметки, которые не должны попадать в payload" } },
dailyLog: { id: "dl1", date: "2026-10-13" },
};
describe("classifyEvent", () => {
it("закрытие to-do, создание to-do, закрытие и перенос вехи, daily log", () => {
expect(classifyEvent(todoClosed)).toBe("todo_closed");
expect(classifyEvent(todoCreated)).toBe("todo_created");
expect(classifyEvent(milestoneClosed)).toBe("milestone_closed");
expect(classifyEvent(milestoneMoved)).toBe("milestone_moved");
expect(classifyEvent(dailyLog)).toBe("daily_log_created");
});
it("остальное активностью не считается", () => {
const base = { createdByUser: { name: "X" } };
// закрытие обычной работы графика (не to-do, не веха)
expect(classifyEvent({ id: "a", type: "taskUpdated", createdAt: "2026-10-01T00:00:00Z", ...base, data: { next: { progress: 1 }, previous: { progress: 0 } }, task: { isToDo: false, taskType: { name: "Permitting" } } })).toBeNull();
// перенос обычной работы и перенос to-do
expect(classifyEvent({ id: "b", type: "taskUpdated", createdAt: "2026-10-01T00:00:00Z", ...base, data: { next: { endDate: "2026-10-02" } }, task: { isToDo: false, taskType: { name: "Site Mobilization" } } })).toBeNull();
expect(classifyEvent({ id: "c", type: "taskUpdated", createdAt: "2026-10-01T00:00:00Z", ...base, data: { next: { endDate: "2026-10-02" } }, task: { isToDo: true, taskType: null } })).toBeNull();
// смена типа и имени вехи, создание обычной задачи, повторное закрытие
expect(classifyEvent({ id: "d", type: "taskUpdated", createdAt: "2026-10-01T00:00:00Z", ...base, data: { next: { taskTypeId: "x" } }, task: { isToDo: false, taskType: { name: "test-Milestone" } } })).toBeNull();
expect(classifyEvent({ id: "e", type: "taskCreated", createdAt: "2026-10-01T00:00:00Z", ...base, data: { next: { isToDo: false } }, task: { isToDo: false } })).toBeNull();
expect(classifyEvent({ id: "f", type: "taskUpdated", createdAt: "2026-10-01T00:00:00Z", ...base, data: { next: { progress: 1 }, previous: { progress: 1 } }, task: { isToDo: true } })).toBeNull();
});
it("закрытие вехи приоритетнее переноса", () => {
const both: RawEvent = { ...milestoneClosed, data: { next: { progress: 1, endDate: "2026-10-12" }, previous: { progress: 0 } } };
expect(classifyEvent(both)).toBe("milestone_closed");
});
});
describe("toRow", () => {
it("раскладывает поля, payload урезан до нужных ключей", () => {
const r = toRow(dailyLog);
expect(r).toMatchObject({ id: "e5", user_name: "Zachary Gange", daily_log_id: "dl1", job_id: "j4", kind: "daily_log_created" });
expect(JSON.stringify(r.payload)).not.toContain("заметки");
const t = toRow(todoClosed);
expect(t).toMatchObject({ task_id: "t1", task_is_todo: true, job_id: "j1", kind: "todo_closed", payload: { previous: { progress: null }, next: { progress: 1 } } });
expect(toRow(todoCreated).payload).toEqual({ next: { id: "t2", name: "todo", jobId: "j2", isToDo: true, endDate: "2026-10-12", progress: null } });
});
});
describe("fetchEvents", () => {
it("запрашивает три типа событий не раньше since, от новых к старым", async () => {
const calls: Array<{ field: string; args: Record<string, unknown> }> = [];
const pave = { pageAll: async (field: string, args: Record<string, unknown>) => { calls.push({ field, args }); return [todoClosed] as never; } };
const out = await fetchEvents(pave as never, new Date("2026-10-01T00:00:00Z"));
expect(out).toHaveLength(1);
expect(calls[0]!.field).toBe("events");
expect(JSON.stringify(calls[0]!.args)).toContain('["createdAt",">=","2026-10-01T00:00:00.000Z"]');
for (const t of ["taskCreated", "taskUpdated", "dailyLogCreated"]) expect(JSON.stringify(calls[0]!.args)).toContain(`["type","=","${t}"]`);
expect(JSON.stringify(calls[0]!.args)).toContain('"order":"desc"');
});
});
const url = testDatabaseUrl();
(url ? describe : describe.skip)("syncEvents (временная БД)", () => {
let db: TestDb;
beforeAll(async () => { db = await createTestDb(url!); });
afterAll(async () => { await db?.drop(); });
const paveWith = (events: RawEvent[]) => ({ pageAll: async () => events as never });
it("первая загрузка берёт backfill, повторная идемпотентна, состояние записывается", async () => {
const now = new Date("2026-10-15T12:00:00Z");
const r1 = await syncEvents(db.pool, paveWith([todoClosed, todoCreated, milestoneClosed, dailyLog]), { now, backfillDays: 30 });
expect(r1).toMatchObject({ fetched: 4, inserted: 4, since: "2026-09-15T12:00:00.000Z" });
const r2 = await syncEvents(db.pool, paveWith([todoClosed, dailyLog, milestoneMoved]), { now });
expect(r2).toMatchObject({ fetched: 3, inserted: 1 }); // новое только перенесение вехи
// вторая загрузка стартует от последнего события минус запас 2 часа
expect(r2.since).toBe(new Date(new Date(todoClosed.createdAt).getTime() - 120 * 60_000).toISOString());
const { rows } = await db.pool.query("select count(*)::int n, count(kind)::int classified from jt_event");
expect(rows[0]).toEqual({ n: 5, classified: 5 });
const st = (await db.pool.query("select * from activity_sync_state where source = 'events'")).rows[0];
expect(st.last_error).toBeNull();
expect(st.last_loaded).toBe(1);
expect(st.last_success_at).not.toBeNull();
});
it("ошибка источника записывается в состояние и пробрасывается", async () => {
const bad = { pageAll: async () => { throw new Error("JobTread недоступен"); } };
await expect(syncEvents(db.pool, bad as never, {})).rejects.toThrow("недоступен");
const st = (await db.pool.query("select last_error from activity_sync_state where source = 'events'")).rows[0];
expect(st.last_error).toContain("недоступен");
});
it("миграция: у новых таблиц включён RLS, отчёт видит список учёта (может быть пуст на чистой БД)", async () => {
const { rows } = await db.pool.query("select relname from pg_class where relname in ('jt_event','activity_tracked_person','activity_sync_state') and relrowsecurity");
expect(rows.map((r) => r.relname).sort()).toEqual(["activity_sync_state", "activity_tracked_person", "jt_event"]);
});
});

View File

@@ -0,0 +1,160 @@
import type { Pool } from "khb_common";
import type { PaveClient } from "../jobtread/pave-client.js";
/** Типы событий JobTread, которые загружаются (остальные для отчёта активности не нужны). */
export const EVENT_TYPES = ["taskCreated", "taskUpdated", "dailyLogCreated"] as const;
/** Что считается активностью (методология: docs/activity_methodology.md). */
export type EventKind = "todo_closed" | "todo_created" | "milestone_closed" | "milestone_moved" | "daily_log_created";
/** Событие organization.events в том виде, как его отдаёт Pave API (union-поля task и dailyLog приходят плоскими). */
export interface RawEvent {
id: string;
type: string;
createdAt: string;
createdByUser?: { id?: string; name?: string } | null;
data?: { previous?: Record<string, unknown> | null; next?: Record<string, unknown> | null } | null;
task?: { id?: string; isToDo?: boolean; taskType?: { name?: string } | null; job?: { id?: string } | null } | null;
dailyLog?: { id?: string; date?: string } | null;
}
export interface JtEventRow {
id: string;
type: string;
created_at: string;
user_id: string | null;
user_name: string | null;
task_id: string | null;
task_is_todo: boolean | null;
task_type_name: string | null;
job_id: string | null;
daily_log_id: string | null;
kind: EventKind | null;
payload: Record<string, unknown>;
}
/** Веха - задача типа Milestone (так её называет справочник типов задач JobTread). */
const MILESTONE_RE = /milestone/i;
/** Поля, которые сохраняются в payload: достаточно, чтобы пересмотреть классификацию без повторной загрузки. */
const PAYLOAD_KEYS = ["progress", "startDate", "endDate", "isToDo", "taskTypeId", "jobId", "name", "id", "date"];
const trim = (o: Record<string, unknown> | null | undefined): Record<string, unknown> => {
const out: Record<string, unknown> = {};
for (const k of PAYLOAD_KEYS) if (o && k in o) out[k] = o[k];
return out;
};
const isClosed = (next: Record<string, unknown>, prev: Record<string, unknown>): boolean =>
"progress" in next && Number(next.progress) >= 1 && !(Number(prev.progress) >= 1);
const isMoved = (next: Record<string, unknown>): boolean => "startDate" in next || "endDate" in next;
/**
* Классификация события в «активность»:
* - dailyLogCreated -> daily_log_created;
* - taskCreated для to-do -> todo_created;
* - taskUpdated: to-do, у которого progress стал 1 -> todo_closed; веха (тип Milestone) с progress 1 -> milestone_closed,
* с изменением startDate/endDate -> milestone_moved. Закрытие приоритетнее переноса.
* Остальное (позиция, имя, тип, закрытие обычных работ графика и т.п.) активностью не считается (kind = null).
*/
export function classifyEvent(e: RawEvent): EventKind | null {
const next = e.data?.next ?? {};
const prev = e.data?.previous ?? {};
if (e.type === "dailyLogCreated") return "daily_log_created";
const isToDo = e.task?.isToDo ?? (typeof next.isToDo === "boolean" ? next.isToDo : undefined);
if (e.type === "taskCreated") return isToDo ? "todo_created" : null;
if (e.type === "taskUpdated") {
const milestone = MILESTONE_RE.test(e.task?.taskType?.name ?? "");
if (isToDo && isClosed(next, prev)) return "todo_closed";
if (milestone && isClosed(next, prev)) return "milestone_closed";
if (milestone && isMoved(next)) return "milestone_moved";
}
return null;
}
export function toRow(e: RawEvent): JtEventRow {
const next = e.data?.next ?? {};
const prev = e.data?.previous ?? {};
const created = e.type === "taskCreated" || e.type === "dailyLogCreated";
return {
id: e.id,
type: e.type,
created_at: e.createdAt,
user_id: e.createdByUser?.id ?? null,
user_name: e.createdByUser?.name ?? null,
task_id: e.task?.id ?? (typeof next.id === "string" && e.type !== "dailyLogCreated" ? next.id : null),
task_is_todo: e.task?.isToDo ?? (typeof next.isToDo === "boolean" ? next.isToDo : null),
task_type_name: e.task?.taskType?.name ?? null,
job_id: e.task?.job?.id ?? (typeof next.jobId === "string" ? next.jobId : null),
daily_log_id: e.dailyLog?.id ?? (e.type === "dailyLogCreated" && typeof next.id === "string" ? next.id : null),
kind: classifyEvent(e),
payload: created ? { next: trim(next) } : { previous: trim(prev), next: trim(next) },
};
}
const EVENT_FIELDS = {
id: {}, type: {}, createdAt: {}, createdByUser: { id: {}, name: {} }, data: {},
task: { _on_task: { id: {}, isToDo: {}, taskType: { name: {} }, job: { id: {} } } },
dailyLog: { _on_dailyLog: { id: {}, date: {} } },
};
/** Загружает события организации, созданные не раньше `since` (страницы от новых к старым). */
export async function fetchEvents(pave: Pick<PaveClient, "pageAll">, since: Date): Promise<RawEvent[]> {
return pave.pageAll<RawEvent>(
"events",
{
where: { and: [["createdAt", ">=", since.toISOString()], { or: EVENT_TYPES.map((t) => ["type", "=", t]) }] },
sortBy: [{ field: ["createdAt"], order: "desc" }],
},
EVENT_FIELDS,
100,
);
}
export interface SyncEventsOptions {
now?: Date;
/** Сколько дней истории загружать при первом запуске. */
backfillDays?: number;
/** Запас по времени назад от последнего события: защищает от событий, записанных с опозданием. */
overlapMinutes?: number;
}
export interface SyncEventsResult { since: string; fetched: number; inserted: number }
const COLS = ["id", "type", "created_at", "user_id", "user_name", "task_id", "task_is_todo", "task_type_name", "job_id", "daily_log_id", "kind", "payload"] as const;
const SOURCE = "events";
/**
* Инкрементальная синхронизация ленты событий JobTread в jt_event.
* События неизменяемы: повторная вставка тех же id игнорируется. Состояние (успех, ошибка, сколько загружено) - в activity_sync_state.
*/
export async function syncEvents(pool: Pool, pave: Pick<PaveClient, "pageAll">, opts: SyncEventsOptions = {}): Promise<SyncEventsResult> {
const now = opts.now ?? new Date();
await pool.query(
"insert into activity_sync_state (source, last_started_at) values ($1, $2) on conflict (source) do update set last_started_at = $2",
[SOURCE, now],
);
try {
const last = (await pool.query("select max(created_at) as m from jt_event")).rows[0]?.m as Date | null;
const since = last
? new Date(last.getTime() - (opts.overlapMinutes ?? 120) * 60_000)
: new Date(now.getTime() - (opts.backfillDays ?? 45) * 86_400_000);
const rows = (await fetchEvents(pave, since)).map(toRow);
let inserted = 0;
for (let i = 0; i < rows.length; i += 200) {
const chunk = rows.slice(i, i + 200);
const params: unknown[] = [];
const values = chunk.map((r, j) => {
COLS.forEach((c) => params.push(c === "payload" ? JSON.stringify(r.payload) : r[c]));
return `(${COLS.map((_, k) => `$${j * COLS.length + k + 1}`).join(", ")})`;
});
const res = await pool.query(`insert into jt_event (${COLS.join(", ")}) values ${values.join(", ")} on conflict (id) do nothing`, params);
inserted += res.rowCount ?? 0;
}
await pool.query(
"update activity_sync_state set last_success_at = $2, last_error = null, last_loaded = $3 where source = $1",
[SOURCE, new Date(), inserted],
);
return { since: since.toISOString(), fetched: rows.length, inserted };
} catch (e) {
await pool.query("update activity_sync_state set last_error = $2 where source = $1", [SOURCE, e instanceof Error ? e.message : String(e)]);
throw e;
}
}

View File

@@ -9,6 +9,8 @@ export interface CollectorApiDeps {
runCollect(req: CollectRequest, onStarted: (ts: Date) => void): Promise<{ status: "ok" | "error" }[]>;
runRetention(): Promise<unknown>;
importHolidays(): Promise<unknown>;
/** Синхронизирует ленту событий JobTread (jt_event) для отчётов активности. */
syncEvents(): Promise<unknown>;
}
export function buildApi(deps: CollectorApiDeps): FastifyInstance {
@@ -54,5 +56,12 @@ export function buildApi(deps: CollectorApiDeps): FastifyInstance {
app.post("/retention/run", async () => deps.runRetention());
app.post("/holidays/import", async () => deps.importHolidays());
app.post("/events/sync", async (_req, reply) => {
try {
return await deps.syncEvents();
} catch (e) {
return reply.code(502).send({ error: e instanceof Error ? e.message : String(e) });
}
});
return app;
}

View File

@@ -2,6 +2,7 @@ import { createLogger, createPool, loadServiceSettings } from "khb_common";
import { jobtreadSchema } from "khb_common";
import { collect, jobtreadLoaders } from "./collect.js";
import { buildApi } from "./http-api.js";
import { syncEvents } from "./events/jt-events.js";
import { importHolidays } from "./holidays/import.js";
import { JobtreadSource } from "./jobtread/jobtread-source.js";
import { PaveClient } from "./jobtread/pave-client.js";
@@ -18,16 +19,25 @@ const pave = new PaveClient({ grantKey: jt.grantKey, organizationId: jt.organiza
const loaders = { jt: jobtreadLoaders(new JobtreadSource(pave)) };
const tablesBySource = Object.fromEntries(Object.entries(loaders).map(([k, v]) => [k, v.map((l) => l.table)]));
const runEvents = async () => {
const r = await syncEvents(pool, pave, { backfillDays: service.events.backfillDays });
log.info(r, "events synced");
return r;
};
const app = buildApi({
pool,
token: service.http.token,
runCollect: async (req, onStarted) => {
const results = await collect(pool, loaders, { ...req, sources: req.sources ?? service.sources.map((s: string) => (s === "jobtread" ? "jt" : s)) }, onStarted);
for (const r of results) log.info({ snapshotTs: r.snapshotTs, status: r.status, tables: r.tables }, "snapshot finished");
// события JobTread для отчётов активности: сбой не должен портить результат снапшота
runEvents().catch((e) => log.error({ err: e instanceof Error ? e.message : String(e) }, "events sync failed"));
return results;
},
runRetention: () => runRetention(pool, tablesBySource, { ...DEFAULT_RETENTION, ...service.retention }),
importHolidays: () => importHolidays(pool, service.holidays),
syncEvents: runEvents,
});
await app.listen({ host: service.http.host, port: service.http.port });

View File

@@ -16,6 +16,7 @@ export const dataCollectorSchema = z.object({
failedMaxPerDay: z.number().optional(),
})
.default({}),
events: z.object({ backfillDays: z.number().default(45) }).default({}),
holidays: z.object({ country: z.string().default("US"), state: z.string().default("FL"), yearsAhead: z.number().default(2) }).default({}),
});
export type DataCollectorSettings = z.infer<typeof dataCollectorSchema>;