Отчёты по сотрудникам: 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,103 @@
import Fastify, { type FastifyInstance } from "fastify";
import { buildSeries, rangeStart, type ActivityDay } from "./activity.js";
import { buildTotals } from "./charts.js";
import { buildWorkbook } from "./export.js";
import { renderActivityPage, renderIndex, renderTodoPage, type ActivityPerson } from "./render.js";
import type { ReportsRepo, SnapshotDay } from "./repo.js";
export interface EmployeeReportsDeps {
repo: ReportsRepo;
/** порог активности за день (включительно) */
threshold: number;
defaultDays: number;
/** часовой пояс «сегодня» и дня снимка */
tz: string;
now?: () => Date;
}
/** Сегодняшняя дата YYYY-MM-DD в часовом поясе. */
export function todayIn(tz: string, now: Date): string {
return new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
}
const clampDays = (raw: unknown, fallback: number): number => {
const n = Number(raw);
return Number.isFinite(n) && n >= 7 && n <= 180 ? Math.floor(n) : fallback;
};
/**
* Отчёты по сотрудникам: To-do report и Employee Activity. Читают только Supabase (зеркало JobTread, события JobTread, журнал чата, календарь).
* Собственной авторизации нет: порт слушает 127.0.0.1, наружу сервис выставляет nginx за входом Keycloak (reports.khbuild.freeddns.org/employee/).
*/
export function buildApi(deps: EmployeeReportsDeps): FastifyInstance {
const app = Fastify();
const now = deps.now ?? (() => new Date());
const html = (reply: import("fastify").FastifyReply, body: string) => reply.header("cache-control", "no-store").type("text/html; charset=utf-8").send(body);
app.get("/healthz", async () => ({ ok: true, time: now().toISOString() }));
app.get("/", async (_req, reply) => html(reply, renderIndex()));
app.get("/todo", async (_req, reply) => reply.redirect("todo/"));
app.get("/activity", async (_req, reply) => reply.redirect("activity/"));
/** Ряды активности всех, кого поставили на учёт. */
async function activityPersons(days: number): Promise<{ persons: ActivityPerson[]; from: string; to: string }> {
const to = todayIn(deps.tz, now());
const from = rangeStart(to, days);
const tracked = await deps.repo.listTracked();
const nonWorkdays = await deps.repo.nonWorkdays(from, to);
const persons: ActivityPerson[] = [];
for (const p of tracked) {
const counts = await deps.repo.dailyCounts(p, from, to);
persons.push({ name: p.name, days: buildSeries({ from, to, counts, nonWorkdays, threshold: deps.threshold }) });
}
return { persons, from, to };
}
app.get<{ Querystring: { days?: string } }>("/activity/", async (req, reply) => {
const days = clampDays(req.query.days, deps.defaultDays);
const { persons, from, to } = await activityPersons(days);
const sync = await deps.repo.syncState();
return html(reply, renderActivityPage({ persons, from, to, days, threshold: deps.threshold, sync, today: to }));
});
app.get<{ Querystring: { days?: string } }>("/api/activity", async (req) => {
const days = clampDays(req.query.days, deps.defaultDays);
const { persons, from, to } = await activityPersons(days);
return {
from,
to,
threshold: deps.threshold,
persons: persons.map((p) => ({ name: p.name, days: p.days as ActivityDay[] })),
totals: persons.length ? buildTotals(persons.map((p) => p.days)) : [],
};
});
const pickSnapshot = (days: SnapshotDay[], date?: string): SnapshotDay | undefined => days.find((d) => d.day === date) ?? days[0];
app.get<{ Querystring: { date?: string; employee?: string } }>("/todo/", async (req, reply) => {
const snapshotDays = await deps.repo.listSnapshotDays();
const selected = pickSnapshot(snapshotDays, req.query.date);
const reportRows = selected ? await deps.repo.todoReport(selected.snapshotTs) : [];
// любая активность в инфополе: за день снимка по времени Нью-Йорка (события JobTread и чат)
const activity = selected ? await deps.repo.activityByUser(selected.day, deps.tz) : new Map();
const rows = reportRows.map((r) => {
const a = activity.get(r.employee_name) ?? { total: 0, dailyLogs: 0 };
return { ...r, activity: { total: a.total, dailyLogs: a.dailyLogs, active: a.total >= deps.threshold } };
});
const employee = rows.some((r) => r.employee_name === req.query.employee) ? req.query.employee : undefined;
const source = selected && employee ? await deps.repo.todoSource(selected.snapshotTs, employee) : [];
return html(reply, renderTodoPage({ snapshotDays, selected, rows, employee, source, threshold: deps.threshold }));
});
app.get<{ Querystring: { date?: string } }>("/todo/export", async (req, reply) => {
const selected = pickSnapshot(await deps.repo.listSnapshotDays(), req.query.date);
if (!selected) return reply.code(404).send("Нет снимков");
const buf = await buildWorkbook(await deps.repo.todoSource(selected.snapshotTs));
return reply
.header("content-disposition", `attachment; filename="jobtread_todo_${selected.day}.xlsx"`)
.type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
.send(buf);
});
return app;
}