Files
khb_microservices/packages/employee_reports/src/http-api.ts
Yuri Yaryshev 0014f3f091
All checks were successful
ci / test (push) Successful in 22s
ci / deploy (push) Successful in 1m41s
Активность: неизвестное происхождение не считается, чёрные недели, строка «Понедельно»
События с неизвестным источником не считаются (миграция 011). Завершённая
неделя без единой активности красится чёрным. В Employee Activity под итоговым
графиком добавлена строка «Понедельно»: один столбец на неделю, средние
зелёные, жёлтые и красные люди за рабочий день, высота равна числу людей.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 15:08:12 +03:00

114 lines
6.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Fastify, { type FastifyInstance } from "fastify";
import { buildSeries, buildWeeks, datesBetween, markBlackWeeks, rangeStart, weekStartOf, 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; weeks: ReturnType<typeof buildWeeks> }> {
const to = todayIn(deps.tz, now());
const from = rangeStart(to, days);
const fetchFrom = weekStartOf(from);
const tracked = await deps.repo.listTracked();
const nonWorkdays = await deps.repo.nonWorkdays(fetchFrom, to);
const full: ActivityDay[][] = [];
for (const p of tracked) {
const counts = await deps.repo.dailyCounts(p, fetchFrom, to);
full.push(markBlackWeeks(buildSeries({ from: fetchFrom, to, counts, nonWorkdays, threshold: deps.threshold }), to));
}
const persons: ActivityPerson[] = tracked.map((p, k) => ({ name: p.name, days: full[k]!.filter((d) => d.date >= from) }));
return { persons, from, to, weeks: buildWeeks(full, from, to) };
}
app.get<{ Querystring: { days?: string } }>("/activity/", async (req, reply) => {
const days = clampDays(req.query.days, deps.defaultDays);
const { persons, from, to, weeks } = await activityPersons(days);
const sync = await deps.repo.syncState();
return html(reply, renderActivityPage({ persons, from, to, days, weeks, 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, weeks } = await activityPersons(days);
return {
from,
to,
threshold: deps.threshold,
weeks,
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) : [];
// любая активность в инфополе: за день снимка и за 7 дней по него включительно (по времени Нью-Йорка; события JobTread и чат)
const from = rangeStart(selected?.day ?? todayIn(deps.tz, now()), 7);
const activity = selected ? await deps.repo.activityByUserDays(from, selected.day, deps.tz) : new Map();
const weekDates = selected ? datesBetween(from, selected.day) : [];
const rows = reportRows.map((r) => {
const byDay = activity.get(r.employee_name) ?? new Map();
const today = byDay.get(selected?.day ?? "") ?? { total: 0, dailyLogs: 0 };
const activeDays = weekDates.filter((d) => (byDay.get(d)?.total ?? 0) >= deps.threshold).length;
return { ...r, activity: { total: today.total, dailyLogs: today.dailyLogs, active: today.total >= deps.threshold, activeDays, windowDays: weekDates.length } };
});
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;
}