Отчёты по сотрудникам: 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"]);
});
});