Files
khb_microservices/packages/employee_reports/src/charts.ts
2026-10-15 14:44:12 +03:00

74 lines
5.2 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 { describeDay, type ActivityDay, type DayStatus } from "./activity.js";
/** Ширина колонки одного дня: у графика сотрудника и у итогового графика она одинаковая, дни стоят друг под другом. */
export const CELL = 18;
const CHART_H = 48;
const TOTAL_H = 84;
const AXIS_H = 18;
/** Фон дня: тёмно-красный - активности меньше порога; зелёный - есть Daily Log; жёлтый - активность выше порога, но Daily Log нет; серый - нерабочий день без активности. */
export const COLORS: Record<DayStatus, string> = { green: "#2e7d32", yellow: "#e6b800", red: "#7f1d1d", off: "#d5d9e0" };
const esc = (s: string): string => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const WEEKDAY_RU = ["вс", "пн", "вт", "ср", "чт", "пт", "сб"];
const weekday = (date: string): string => WEEKDAY_RU[new Date(`${date}T00:00:00Z`).getUTCDay()]!;
const isMonday = (date: string): boolean => new Date(`${date}T00:00:00Z`).getUTCDay() === 1;
const ddmm = (date: string): string => `${date.slice(8, 10)}.${date.slice(5, 7)}`;
/** Подписи дат под осью X: первый день и каждый понедельник. */
function axis(dates: string[], top: number): string {
return dates
.map((d, i) => (i === 0 || isMonday(d) ? `<text x="${i * CELL + CELL / 2}" y="${top + 12}" text-anchor="middle" font-size="9" fill="#667085">${ddmm(d)}</text>` : ""))
.join("");
}
/** Встроенный график сотрудника: по X даты, по Y количество активностей; фон каждого дня закрашен по статусу дня. */
export function renderPersonChart(days: ActivityDay[], threshold: number, yMax: number): string {
const w = days.length * CELL;
const cols = days
.map((d, i) => {
const h = d.total > 0 ? Math.max(3, Math.round((d.total / yMax) * (CHART_H - 14))) : 0;
const bar = h ? `<rect x="${i * CELL + 3}" y="${CHART_H - h}" width="${CELL - 6}" height="${h}" fill="#ffffff" stroke="#111827" stroke-width="0.8"/>` : "";
const num = d.total > 0 ? `<text x="${i * CELL + CELL / 2}" y="${CHART_H - h - 2}" text-anchor="middle" font-size="8" font-weight="700" fill="#111827" paint-order="stroke" stroke="#ffffff" stroke-width="2">${d.total}</text>` : "";
return `<g><title>${esc(describeDay(d, threshold))} (${weekday(d.date)})</title><rect x="${i * CELL}" y="0" width="${CELL}" height="${CHART_H}" fill="${COLORS[d.status]}" stroke="#ffffff" stroke-width="0.6"/>${bar}${num}</g>`;
})
.join("");
return `<svg xmlns="http://www.w3.org/2000/svg" class="chart" width="${w}" height="${CHART_H + AXIS_H}" viewBox="0 0 ${w} ${CHART_H + AXIS_H}" role="img" aria-label="Активность по дням">${cols}${axis(days.map((d) => d.date), CHART_H)}</svg>`;
}
export interface DayTotal { date: string; green: number; yellow: number; red: number; off: number }
/** Итоги по дням: сколько человек было зелёных, жёлтых, красных и без учёта (нерабочий день). */
export function buildTotals(series: ActivityDay[][]): DayTotal[] {
const first = series[0] ?? [];
return first.map((d, i) => {
const t: DayTotal = { date: d.date, green: 0, yellow: 0, red: 0, off: 0 };
for (const s of series) t[s[i]!.status]++;
return t;
});
}
/** Итоговый график под всеми людьми: за каждый день столбик из зелёных (внизу) и жёлтых (над ними) людей. */
export function renderTotalChart(totals: DayTotal[], people: number): string {
const w = totals.length * CELL;
const unit = (TOTAL_H - 8) / Math.max(1, people);
const grid = Array.from({ length: people + 1 }, (_, n) => {
const y = TOTAL_H - n * unit;
return `<line x1="0" y1="${y}" x2="${w}" y2="${y}" stroke="#e5e7eb" stroke-width="0.6"/>`;
}).join("");
const cols = totals
.map((t, i) => {
const gH = t.green * unit;
const yH = t.yellow * unit;
const tip = `${t.date} (${weekday(t.date)}): зелёных ${t.green}, жёлтых ${t.yellow}, красных ${t.red}${t.off ? `, без учёта (нерабочий день) ${t.off}` : ""}`;
return `<g><title>${esc(tip)}</title><rect x="${i * CELL}" y="0" width="${CELL}" height="${TOTAL_H}" fill="transparent"/>` +
(gH ? `<rect x="${i * CELL + 3}" y="${TOTAL_H - gH}" width="${CELL - 6}" height="${gH}" fill="${COLORS.green}"/>` : "") +
(yH ? `<rect x="${i * CELL + 3}" y="${TOTAL_H - gH - yH}" width="${CELL - 6}" height="${yH}" fill="${COLORS.yellow}"/>` : "") +
`</g>`;
})
.join("");
const yTicks = Array.from({ length: people + 1 }, (_, n) => `<text x="2" y="${TOTAL_H - n * unit - 2}" font-size="8" fill="#667085">${n}</text>`).join("");
return `<svg xmlns="http://www.w3.org/2000/svg" class="chart" width="${w}" height="${TOTAL_H + AXIS_H}" viewBox="0 0 ${w} ${TOTAL_H + AXIS_H}" role="img" aria-label="Итого за день: зелёные и жёлтые">${grid}${cols}${yTicks}${axis(totals.map((t) => t.date), TOTAL_H)}</svg>`;
}