import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { createTestDb, testDatabaseUrl, type TestDb } from "khb_common"; import { createRepo, type ReportsRepo, type TrackedPerson } from "./repo.js"; const url = testDatabaseUrl(); const d = url ? describe : describe.skip; const TS1 = "2026-10-12T15:40:00Z"; // пн 11:40 NY (в истории) const TS2B = "2026-10-13T09:50:00Z"; // вт 05:50 NY (в истории): тот же день, что и TS2 const TS2 = "2026-10-13T15:40:00Z"; // вт 11:40 NY (в истории) const TS3 = "2026-10-14T15:40:00Z"; // ср 11:40 NY (текущий) d("отчёты по сотрудникам: SQL на временной БД", () => { let db: TestDb; let repo: ReportsRepo; beforeAll(async () => { db = await createTestDb(url!); repo = createRepo(db.pool); const q = (sql: string, params: unknown[] = []) => db.pool.query(sql, params); for (const ts of [TS1, TS2B, TS2, TS3]) await q("insert into sync_snapshot (started_at, source_prefix, requested_tables) values ($1, 'jt', '{}')", [ts]); await q("insert into jt_membership (id, user_name, role, snapshot_ts) values ('m1','Greg Paris','Admin',$1), ('m2','Alena Danylova','Admin',$1), ('m3','','Vendor',$1)", [TS3]); await q("insert into jt_job (id, number, name, snapshot_ts) values ('j1','1001','Дом Иванова',$1)", [TS3]); // to-do на текущем снимке (TS3) const todo = (id: string, endDate: string | null, progress: number | null, extra = "") => q(`insert into jt_task (id, job_id, name, end_date, progress, is_todo, is_deleted, snapshot_ts) values ($1,'j1',$2,$3,$4,true,${extra || "false"},$5)`, [id, `todo ${id}`, endDate, progress, TS3]); await todo("t1", null, null); // без срока await todo("t2", "2026-10-13", 0.5); // просрочен await todo("t3", "2026-10-20", null); // срок впереди: не в отчёте await todo("t4", "2026-10-01", 1); // закрыт await todo("t6", "2026-10-01", null); // просрочен, у Alena await todo("t7", "2026-10-01", null, "true"); // удалён await q("insert into jt_task (id, job_id, name, end_date, is_todo, snapshot_ts) values ('w1','j1','работа графика','2026-10-01',false,$1)", [TS3]); for (const [t, m] of [["t1", "m1"], ["t2", "m1"], ["t3", "m1"], ["t4", "m1"], ["t6", "m2"], ["t7", "m1"], ["t6", "m3"]] as const) await q("insert into jt_task_assignment (task_id, membership_id, snapshot_ts) values ($1,$2,$3)", [t, m, TS3]); // история снимков: t1 был открыт в 3 снимках двух дней (+ сегодня = 3 разных дня), t2 - в одном дне истории const hist = (id: string, ts: string) => q("insert into jt_task_hist (id, job_id, name, end_date, progress, is_todo, is_group, is_deleted, snapshot_ts) values ($1,'j1',$2,null,null,true,false,false,$3)", [id, `todo ${id}`, ts]); await hist("t1", TS1); await hist("t1", TS2B); await hist("t1", TS2); await hist("t2", TS2); await q("insert into jt_task_assignment_hist (task_id, membership_id, snapshot_ts) values ('t1','m1',$1), ('t1','m1',$2)", [TS1, TS2]); // люди, чат, события, календарь await q("insert into person (id, display_name, email, jt_membership_id, slack_user_id) values ('11111111-1111-1111-1111-111111111111','Greg Paris','greg@khbuild.pro','m1','U1'), ('22222222-2222-2222-2222-222222222222','Walter Walker','walter@khbuild.pro','m9','U2')"); await q("insert into construction_manager (person_id, timezone) values ('11111111-1111-1111-1111-111111111111','America/New_York'), ('22222222-2222-2222-2222-222222222222','America/New_York')"); await q("insert into activity_tracked_person (person_id) values ('11111111-1111-1111-1111-111111111111') on conflict do nothing"); await q("insert into activity_tracked_person (person_id, is_enabled) values ('22222222-2222-2222-2222-222222222222', false) on conflict (person_id) do update set is_enabled = false"); const ev = (id: string, at: string, user: string, kind: string | null) => q("insert into jt_event (id, type, created_at, user_name, kind, is_manual) values ($1,'taskUpdated',$2,$3,$4,true)", [id, at, user, kind]); await ev("e1", "2026-10-14T03:30:00Z", "Greg Paris", "todo_closed"); // 23:30 NY 13 октября await q("insert into jt_event (id, type, created_at, user_name, kind, is_manual) values ('e2','dailyLogCreated','2026-10-14T04:30:00Z','Greg Paris','daily_log_created',true)"); // 00:30 NY 14 октября await ev("e3", "2026-10-14T20:00:00Z", "Greg Paris", "milestone_moved"); await ev("e4", "2026-10-14T21:00:00Z", "Greg Paris", null); // не активность // перенос работ графика: серия из 5 событий за 8 секунд = одно действие, через полминуты ещё одно, автоматизация (агент) не считается for (let i = 0; i < 5; i++) await q("insert into jt_event (id, type, created_at, user_name, kind, is_manual) values ($1,'taskUpdated',$2,'Greg Paris','schedule_moved',true)", [`s${i}`, `2026-10-14T14:00:0${i * 2}Z`]); await q("insert into jt_event (id, type, created_at, user_name, kind, is_manual) values ('s5','taskUpdated','2026-10-14T14:00:40Z','Greg Paris','schedule_moved',true)"); await q("insert into jt_event (id, type, created_at, user_name, kind, is_manual) values ('s6','taskUpdated','2026-10-14T14:05:00Z','Greg Paris','schedule_moved',false)"); await ev("e5", "2026-10-14T16:00:00Z", "Alena Danylova", "todo_closed"); // чужое событие await ev("e6", "2026-10-16T05:00:00Z", "Greg Paris", "todo_created"); // 01:00 NY 16 октября - вне диапазона await q("insert into jt_event (id, type, created_at, user_name, kind) values ('e7','taskUpdated','2026-10-14T18:00:00Z','Greg Paris','todo_closed')"); // происхождение неизвестно (is_manual null) - не считается const chat = (ts: string, sender: string | null, at: string) => q("insert into slack_message_log (channel_id, message_ts, manager_person_id, status, received_at, sender_slack_user_id) values ('C1',$1,'11111111-1111-1111-1111-111111111111','done',$2,$3)", [ts, at, sender]); await chat("1.1", "U1", "2026-10-14T13:00:00Z"); await chat("1.2", null, "2026-10-14T14:00:00Z"); // до миграции 008 автор не записывался - писал менеджер await chat("1.3", "U9", "2026-10-14T15:00:00Z"); // написал другой участник канала - не активность менеджера await q("insert into calendar_day (day, is_workday, source) values ('2026-10-10', false, 'manual'), ('2026-10-11', false, 'manual'), ('2026-10-12', true, 'manual')"); await q("insert into activity_sync_state (source, last_success_at, last_loaded) values ('events', '2026-10-15T09:50:00Z', 7)"); }); afterAll(async () => { await db?.drop(); }); it("списки дней снимков: последний снимок каждого дня Нью-Йорка", async () => { expect(await repo.listSnapshotDays()).toEqual([ { day: "2026-10-14", snapshotTs: "2026-10-14T15:40:00.000Z" }, { day: "2026-10-13", snapshotTs: "2026-10-13T15:40:00.000Z" }, { day: "2026-10-12", snapshotTs: "2026-10-12T15:40:00.000Z" }, ]); }); it("To-do report: просроченные и без срока, Stale Days по различным дням истории, пустые имена и закрытые не считаются", async () => { expect(await repo.todoReport("2026-10-14T15:40:00.000Z")).toEqual([ { employee_name: "Greg Paris", task_count: 2, stale_days: 5 }, // t1: дни 12, 13 и 14 октября (два снимка 13-го - один день) = 3; t2: 13 и 14 октября = 2 { employee_name: "Alena Danylova", task_count: 1, stale_days: 1 }, ]); }); it("исходные строки: все открытые to-do снимка, фильтр по сотруднику, признак просрочки", async () => { const all = await repo.todoSource("2026-10-14T15:40:00.000Z"); expect(all.map((r) => r.id)).toEqual(["t1", "t2", "t3", "t6"]); expect(all.find((r) => r.id === "t3")!.overdue_or_undated).toBe(false); expect(all.find((r) => r.id === "t1")).toMatchObject({ overdue_or_undated: true, stale_days: 3, assignees: "Greg Paris", job_number: "1001", job_name: "Дом Иванова" }); expect(all.find((r) => r.id === "t6")!.assignees).toBe("Alena Danylova"); // пустое имя участника не попадает в список const greg = await repo.todoSource("2026-10-14T15:40:00.000Z", "Greg Paris"); expect(greg.map((r) => r.id)).toEqual(["t1", "t2", "t3"]); }); it("на учёт ставятся только включённые люди; чат и JobTread сопоставляются по person", async () => { const t = await repo.listTracked(); expect(t).toEqual([ { personId: "11111111-1111-1111-1111-111111111111", name: "Greg Paris", tz: "America/New_York", slackUserId: "U1", jtUserName: "Greg Paris" }, ]); }); it("счётчики по дням: день по часовому поясу сотрудника, события без kind и чужое не считаются, чат только от менеджера", async () => { const [p] = await repo.listTracked(); const m = await repo.dailyCounts(p!, "2026-10-12", "2026-10-15"); const nonZero = Object.fromEntries([...m].map(([day, c]) => [day, Object.fromEntries(Object.entries(c).filter(([, v]) => v))])); expect(nonZero).toEqual({ "2026-10-13": { todo_closed: 1 }, // событие 03:30 UTC = 23:30 по Нью-Йорку предыдущего дня "2026-10-14": { daily_log_created: 1, milestone_moved: 1, schedule_moved: 2, chat: 2 }, // 00:30 NY - уже следующий день; чат: U1 и legacy без автора, но не U9 }); // событие 01:00 NY 16 октября вне запрошенного диапазона (до 15 октября включительно) expect(m.has("2026-10-16")).toBe(false); expect(m.has("2026-10-15")).toBe(false); }); it("активность по пользователям JobTread по дням (для To-do report): события + чат", async () => { const a = await repo.activityByUserDays("2026-10-12", "2026-10-14", "America/New_York"); expect(a.get("Greg Paris")!.get("2026-10-13")).toEqual({ total: 1, dailyLogs: 0 }); // 23:30 NY expect(a.get("Greg Paris")!.get("2026-10-14")).toEqual({ total: 6, dailyLogs: 1 }); // log + moved + 2 действия переноса работ + 2 сообщения expect(a.get("Alena Danylova")!.get("2026-10-14")).toEqual({ total: 1, dailyLogs: 0 }); expect(a.has("Walter Walker")).toBe(false); }); it("нерабочие дни и состояние синхронизации", async () => { expect([...(await repo.nonWorkdays("2026-10-09", "2026-10-13"))].sort()).toEqual(["2026-10-10", "2026-10-11"]); expect(await repo.syncState()).toEqual({ lastSuccessAt: "2026-10-15T09:50:00.000Z", lastError: null, lastLoaded: 7 }); }); });