Files
khb_microservices/packages/employee_reports/src/charts.ts
2026-10-15 22:09:47 +03:00

121 lines
9.1 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, type WeekBar } 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 CHAT_SHARE_COLOR = "#cfd4dc";
export const COLORS: Record<DayStatus, string> = { green: "#2e7d32", yellow: "#e6b800", red: "#7f1d1d", off: "#d5d9e0", black: "#000000" };
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 chatH = h && d.counts.chat > 0 ? Math.max(1, Math.round((h * d.counts.chat) / d.total)) : 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"/>` +
(chatH ? `<rect x="${i * CELL + 3.4}" y="${CHART_H - chatH - 0.4}" width="${CELL - 6.8}" height="${chatH}" fill="${CHAT_SHARE_COLOR}"/>` : "")
: "";
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; black: 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, black: 0 };
for (const s of series) t[s[i]!.status]++;
return t;
});
}
/**
* Итоговый график под всеми людьми («Всего»): те же правила, что у строки «Понедельно», но для одного дня. Колонка всегда высотой во всех людей:
* зелёные внизу, над ними жёлтые, затем красные; нерабочие дни без активности (серые) и чёрные недели добавляются выше, поэтому сумма равна числу людей.
*/
export function renderTotalChart(totals: DayTotal[], people: number): string {
const blackDay = (t: DayTotal) => people > 0 && t.black >= people; // неделя без активности у всех людей
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 tip = `${t.date} (${weekday(t.date)}): зелёных ${t.green}, жёлтых ${t.yellow}, красных ${t.red}${t.off ? `, без учёта (нерабочий день) ${t.off}` : ""}${t.black ? `, чёрных ${t.black}` : ""}`;
let y = TOTAL_H;
const seg = (n: number, color: string): string => {
if (!n) return "";
const h = n * unit;
y -= h;
return `<rect x="${i * CELL + 2}" y="${y}" width="${CELL - 4}" height="${h}" fill="${color}"/>`;
};
const layers = seg(t.green, COLORS.green) + seg(t.yellow, COLORS.yellow) + seg(t.red, COLORS.red) + seg(t.off, COLORS.off) + seg(t.black, COLORS.black);
return `<g><title>${esc(blackDay(t) ? `${t.date} (${weekday(t.date)}): неделя без единой активности` : tip)}</title>${layers}</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>`;
}
/**
* Строка «Понедельно»: один широкий столбец на неделю под её днями. Высота столбца всегда равна числу людей (3 для трёх менеджеров),
* соотношение меняется: зелёные (внизу), жёлтые, красные (вверху) - в среднем за рабочий день недели. Неделя без единой активности - чёрный столбец.
*/
export function renderWeeklyChart(weeks: WeekBar[], people: number, dates: string[]): string {
const w = dates.length * CELL;
const unit = (TOTAL_H - 8) / Math.max(1, people);
const full = people * unit;
const top = TOTAL_H - full;
const idx = (d: string) => dates.indexOf(d);
const bars = weeks
.map((wk) => {
const x = idx(wk.dates[0]!) * CELL + 2;
const bw = wk.dates.length * CELL - 4;
const range = `${ddmm(wk.weekStart)}-${ddmm(wk.dates.at(-1)!)}`;
if (wk.black) return `<g><title>${esc(`Неделя ${range}: ни одной активности`)}</title><rect x="${x}" y="${top}" width="${bw}" height="${full}" fill="${COLORS.black}"/></g>`;
const gH = wk.green * unit;
const yH = wk.yellow * unit;
const rH = Math.max(0, full - gH - yH);
const tip = `Неделя ${range} (рабочих дней ${wk.workdays}): в среднем за день зелёных ${wk.green.toFixed(2)}, жёлтых ${wk.yellow.toFixed(2)}, красных ${wk.red.toFixed(2)}`;
return `<g><title>${esc(tip)}</title>` +
(wk.workdays ? "" : `<rect x="${x}" y="${top}" width="${bw}" height="${full}" fill="${COLORS.off}"/>`) +
(gH ? `<rect x="${x}" y="${TOTAL_H - gH}" width="${bw}" height="${gH}" fill="${COLORS.green}"/>` : "") +
(yH ? `<rect x="${x}" y="${TOTAL_H - gH - yH}" width="${bw}" height="${yH}" fill="${COLORS.yellow}"/>` : "") +
(wk.workdays && rH > 0.5 ? `<rect x="${x}" y="${top}" width="${bw}" height="${rH}" fill="${COLORS.red}"/>` : "") +
`</g>`;
})
.join("");
const labels = weeks.map((wk) => `<text x="${idx(wk.dates[0]!) * CELL + 4}" y="${TOTAL_H + 12}" font-size="9" fill="#667085">${ddmm(wk.weekStart)}</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="По неделям: средние зелёные, жёлтые и красные дни">${bars}${labels}</svg>`;
}