Employee Activity: итог «Всего» как «Понедельно» на одном дне, серая доля чата, действия агента засчитываются менеджеру
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,6 +8,8 @@ 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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
@@ -30,7 +32,12 @@ export function renderPersonChart(days: ActivityDay[], threshold: number, yMax:
|
||||
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 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>`;
|
||||
})
|
||||
@@ -50,7 +57,10 @@ export function buildTotals(series: ActivityDay[][]): DayTotal[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** Итоговый график под всеми людьми: за каждый день столбик из зелёных (внизу) и жёлтых (над ними) людей. */
|
||||
/**
|
||||
* Итоговый график под всеми людьми («Всего»): те же правила, что у строки «Понедельно», но для одного дня. Колонка всегда высотой во всех людей:
|
||||
* зелёные внизу, над ними жёлтые, затем красные; нерабочие дни без активности (серые) и чёрные недели добавляются выше, поэтому сумма равна числу людей.
|
||||
*/
|
||||
export function renderTotalChart(totals: DayTotal[], people: number): string {
|
||||
const blackDay = (t: DayTotal) => people > 0 && t.black >= people; // неделя без активности у всех людей
|
||||
const w = totals.length * CELL;
|
||||
@@ -61,14 +71,16 @@ export function renderTotalChart(totals: DayTotal[], people: number): string {
|
||||
}).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}` : ""}`;
|
||||
const bg = blackDay(t) ? COLORS.black : "transparent";
|
||||
return `<g><title>${esc(blackDay(t) ? `${t.date} (${weekday(t.date)}): неделя без единой активности` : tip)}</title><rect x="${i * CELL}" y="0" width="${CELL}" height="${TOTAL_H}" fill="${bg}"/>` +
|
||||
(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>`;
|
||||
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("");
|
||||
|
||||
@@ -86,6 +86,26 @@ describe("графики", () => {
|
||||
expect(svg).toContain(`fill="${COLORS.yellow}"`);
|
||||
expect(svg).toContain(`width="${2 * CELL}"`); // та же ширина дня, что у графиков людей
|
||||
});
|
||||
|
||||
it("итог за день: колонка всегда высотой во всех людей, зелёное внизу, жёлтое выше, красное сверху", () => {
|
||||
const totals = [{ date: "2026-10-12", green: 1, yellow: 1, red: 1, off: 0, black: 0 }, { date: "2026-10-13", green: 0, yellow: 0, red: 3, off: 0, black: 0 }];
|
||||
const svg = renderTotalChart(totals, 3);
|
||||
const rects = (color: string) => [...svg.matchAll(new RegExp(`<rect x="(\\d+)" y="([\\d.]+)" width="14" height="([\\d.]+)" fill="${color}"`, "g"))].map((m) => ({ x: Number(m[1]), y: Number(m[2]), h: Number(m[3]) }));
|
||||
const g = rects(COLORS.green)[0]!, y = rects(COLORS.yellow)[0]!, r = rects(COLORS.red);
|
||||
expect(g.y).toBeGreaterThan(y.y); // зелёное ниже жёлтого
|
||||
expect(y.y).toBeGreaterThan(r[0]!.y); // жёлтое ниже красного
|
||||
expect(g.h + y.h + r[0]!.h).toBeCloseTo(r[1]!.h); // первый день равен по высоте дню из одних красных
|
||||
expect(r[1]!.y).toBeCloseTo(r[0]!.y); // верх у обеих колонок один
|
||||
});
|
||||
|
||||
it("серая доля сообщений в чате внутри белого столбика", () => {
|
||||
const series = buildSeries({ from: "2026-10-12", to: "2026-10-12", counts: new Map([["2026-10-12", counts({ chat: 2, todo_closed: 2 })]]), nonWorkdays: new Set<string>(), threshold: 1 });
|
||||
const svg = renderPersonChart(series, 1, 4);
|
||||
const grey = [...svg.matchAll(/fill="#cfd4dc"/g)].length;
|
||||
expect(grey).toBe(1);
|
||||
const noChat = renderPersonChart(buildSeries({ from: "2026-10-12", to: "2026-10-12", counts: new Map([["2026-10-12", counts({ todo_closed: 2 })]]), nonWorkdays: new Set<string>(), threshold: 1 }), 1, 4);
|
||||
expect(noChat).not.toContain("#cfd4dc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("чёрная неделя и понедельные столбики", () => {
|
||||
@@ -214,7 +234,7 @@ describe("страница Employee Activity", () => {
|
||||
expect(r.body.match(/class="chart"/g)).toHaveLength(4); // два человека, итоговый график и понедельная строка
|
||||
expect(r.body).toContain("Понедельно");
|
||||
expect(r.body.indexOf("Greg Paris")).toBeLessThan(r.body.indexOf("Всего")); // итог под всеми людьми
|
||||
expect(r.body).toContain("зелёные (внизу) + жёлтые");
|
||||
expect(r.body).toContain("колонка = все люди: зелёные (внизу), жёлтые, красные (вверху)");
|
||||
expect(r.body).toContain("зелёный день: есть Daily Log");
|
||||
expect(r.body).toContain("события JobTread загружены 2026-10-15 09:50 UTC");
|
||||
expect(r.body.match(/<rect x="\d+" y="0" width="18" height="48"/g)).toHaveLength(28); // 2 человека x 14 дней
|
||||
|
||||
@@ -126,7 +126,7 @@ export function renderActivityPage(i: ActivityPageInput): string {
|
||||
.join("");
|
||||
const totals = i.persons.length ? buildTotals(i.persons.map((p) => p.days)) : [];
|
||||
const totalRow = i.persons.length
|
||||
? `<tr><td><strong>Всего</strong><br><span class="sum">людей на учёте: ${i.persons.length}<br>столбик = зелёные (внизу) + жёлтые</span></td><td class="chartc">${renderTotalChart(totals, i.persons.length)}</td><td class="sum"></td></tr>` +
|
||||
? `<tr><td><strong>Всего</strong><br><span class="sum">людей на учёте: ${i.persons.length}<br>колонка = все люди: зелёные (внизу), жёлтые, красные (вверху)</span></td><td class="chartc">${renderTotalChart(totals, i.persons.length)}</td><td class="sum"></td></tr>` +
|
||||
`<tr><td><strong>Понедельно</strong><br><span class="sum">один столбец на неделю, высота = ${i.persons.length}:<br>зелёные (внизу), жёлтые, красные (вверху) - в среднем за рабочий день недели;<br>неделя без активности - чёрная</span></td><td class="chartc">${renderWeeklyChart(i.weeks, i.persons.length, totals.map((t) => t.date))}</td><td class="sum"></td></tr>`
|
||||
: "";
|
||||
const syncText = i.sync.lastSuccessAt ? `события JobTread загружены ${esc(i.sync.lastSuccessAt.replace("T", " ").slice(0, 16))} UTC` : "события JobTread ещё не загружались";
|
||||
|
||||
@@ -76,6 +76,14 @@ d("отчёты по сотрудникам: SQL на временной БД",
|
||||
await pm("CP1", "4.4", "U1", "2026-10-14T17:15:00Z");
|
||||
await q("insert into slack_message_log (channel_id, message_ts, manager_person_id, status, received_at, sender_slack_user_id) values ('CP1','4.4','11111111-1111-1111-1111-111111111111','done','2026-10-14T17:15:01Z','U1')");
|
||||
|
||||
// действия агента Claude (коннектор claude.ai) во время запуска шага 4 приписываются менеджеру, вне запуска - нет
|
||||
await q("insert into agent_run (manager_person_id, step, status, started_at, finished_at) values ('11111111-1111-1111-1111-111111111111','step4','ok','2026-10-14T19:00:00Z','2026-10-14T19:05:00Z')");
|
||||
const agentEv = (id: string, at: string, grant: string, manual: boolean) =>
|
||||
q("insert into jt_event (id, type, created_at, user_name, kind, is_manual, grant_name) values ($1,'taskUpdated',$2,'Arthur Atanoff','todo_closed',$3,$4)", [id, at, manual, grant]);
|
||||
await agentEv("g1", "2026-10-14T19:02:00Z", "Access for claude.ai", false); // внутри запуска - считается Greg
|
||||
await agentEv("g2", "2026-10-14T19:30:00Z", "Access for claude.ai", false); // вне запуска - нет
|
||||
await agentEv("g3", "2026-10-14T19:03:00Z", "Claude", false); // другой grant (скрипты) - нет
|
||||
|
||||
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)");
|
||||
});
|
||||
@@ -119,7 +127,7 @@ d("отчёты по сотрудникам: SQL на временной БД",
|
||||
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: 4 }, // 00:30 NY - уже следующий день; чат: U1 и legacy без автора, не U9; плюс чат проекта CP1 (4.1 и 4.4, дубль журнала один раз)
|
||||
"2026-10-14": { daily_log_created: 1, milestone_moved: 1, schedule_moved: 2, chat: 4, todo_closed: 1 }, // 00:30 NY - уже следующий день; чат: U1 и legacy без автора, не U9; плюс чат проекта CP1 (4.1 и 4.4, дубль журнала один раз)
|
||||
});
|
||||
// событие 01:00 NY 16 октября вне запрошенного диапазона (до 15 октября включительно)
|
||||
expect(m.has("2026-10-16")).toBe(false);
|
||||
@@ -129,7 +137,7 @@ d("отчёты по сотрудникам: SQL на временной БД",
|
||||
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: 8, dailyLogs: 1 }); // log + moved + 2 действия переноса работ + 2 сообщения ассистенту + 2 сообщения в чате проекта
|
||||
expect(a.get("Greg Paris")!.get("2026-10-14")).toEqual({ total: 9, dailyLogs: 1 }); // log + moved + 2 действия переноса работ + 2 сообщения ассистенту + 2 сообщения в чате проекта
|
||||
expect(a.get("Alena Danylova")!.get("2026-10-14")).toEqual({ total: 1, dailyLogs: 0 });
|
||||
expect(a.has("Walter Walker")).toBe(false);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user