Files
khb_microservices/packages/employee_reports/src/repo.ts
2026-10-15 20:59:43 +03:00

270 lines
13 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 type { Queryable } from "khb_common";
import { emptyCounts, type DayCounts } from "./activity.js";
/** Кого ставим на учёт (activity_tracked_person) и как его узнать в чате и в JobTread. */
export interface TrackedPerson {
personId: string;
name: string;
/** часовой поясу сотрудника (construction_manager.timezone) - по нему считается «день» */
tz: string;
slackUserId: string | null;
/** имя пользователя JobTread (jt_membership.user_name) */
jtUserName: string | null;
}
export interface SnapshotDay { day: string; snapshotTs: string }
export interface TodoReportRow {
employee_name: string;
task_count: number;
stale_days: number;
}
export interface TodoSourceRow {
snapshot_ts: string;
id: string;
job_number: string | null;
job_name: string | null;
name: string;
description: string | null;
start_date: string | null;
end_date: string | null;
progress: number | null;
stale_days: number;
assignees: string;
overdue_or_undated: boolean;
}
export interface UserActivity { total: number; dailyLogs: number }
/** Активность пользователей JobTread: имя -> день -> счётчик. */
export type UserActivityByDay = Map<string, Map<string, UserActivity>>;
export interface SyncState { lastSuccessAt: string | null; lastError: string | null; lastLoaded: number }
/** Всё, что отчёты читают из Supabase. Подменяется в тестах. */
export interface ReportsRepo {
listTracked(): Promise<TrackedPerson[]>;
/** Счётчики активности человека по дням (ключ - дата YYYY-MM-DD в его часовом поясе). */
dailyCounts(p: TrackedPerson, from: string, to: string): Promise<Map<string, Partial<DayCounts>>>;
nonWorkdays(from: string, to: string): Promise<Set<string>>;
syncState(): Promise<SyncState>;
listSnapshotDays(): Promise<SnapshotDay[]>;
todoReport(snapshotTs: string): Promise<TodoReportRow[]>;
todoSource(snapshotTs: string, employee?: string): Promise<TodoSourceRow[]>;
/** Активность по именам пользователей JobTread по дням от `from` до `to` включительно (по часовому поясу `tz`). */
activityByUserDays(from: string, to: string, tz: string): Promise<UserActivityByDay>;
}
const EVENT_KINDS = ["todo_closed", "todo_created", "milestone_closed", "milestone_moved", "schedule_moved", "daily_log_created"] as const;
/** Открытый to-do: не закрыт (progress < 1 или пусто), не удалён. */
const OPEN_TODO = "is_todo and not is_deleted and (progress is null or progress < 1)";
/** Снимки зеркала: текущий (jt_*) и предыдущие (jt_*_hist) вместе. */
const ALL_TASKS = "(select * from jt_task union all select * from jt_task_hist)";
const ALL_ASSIGN = "(select * from jt_task_assignment union all select * from jt_task_assignment_hist)";
/**
* Просроченные to-do и to-do без срока на выбранном снимке, по сотрудникам.
* Stale Days - число различных дней (America/New_York) за всю историю снимков, в которых to-do был открыт; суммируется по задачам сотрудника.
*/
export const TODO_REPORT_SQL = `
with tasks as ${ALL_TASKS},
open_todos as (select * from tasks where ${OPEN_TODO}),
stale as (
select id, count(distinct (snapshot_ts at time zone 'America/New_York')::date)::int as stale_days
from open_todos group by id
),
assign as ${ALL_ASSIGN}
select m.user_name as employee_name,
count(distinct t.id)::int as task_count,
coalesce(sum(s.stale_days), 0)::int as stale_days
from open_todos t
join stale s on s.id = t.id
join assign a on a.task_id = t.id and a.snapshot_ts = t.snapshot_ts
join jt_membership m on m.id = a.membership_id
where t.snapshot_ts = $1::timestamptz
and m.user_name <> ''
and (t.end_date is null or t.end_date < (t.snapshot_ts at time zone 'America/New_York')::date)
group by m.user_name
order by stale_days desc, task_count desc, employee_name
`;
/** Исходные строки отчёта: открытые to-do снимка (для сотрудника - только его, для выгрузки - все). */
export const TODO_SOURCE_SQL = `
with tasks as ${ALL_TASKS},
open_todos as (select * from tasks where ${OPEN_TODO}),
stale as (
select id, count(distinct (snapshot_ts at time zone 'America/New_York')::date)::int as stale_days
from open_todos group by id
),
assign as ${ALL_ASSIGN}
select t.snapshot_ts, t.id, j.number as job_number, j.name as job_name, t.name, t.description,
t.start_date::text as start_date, t.end_date::text as end_date, t.progress::float8 as progress,
s.stale_days,
coalesce((select string_agg(distinct m.user_name, ', ' order by m.user_name)
from assign a join jt_membership m on m.id = a.membership_id
where a.task_id = t.id and a.snapshot_ts = t.snapshot_ts and m.user_name <> ''), '') as assignees,
(t.end_date is null or t.end_date < (t.snapshot_ts at time zone 'America/New_York')::date) as overdue_or_undated
from open_todos t
join stale s on s.id = t.id
left join jt_job j on j.id = t.job_id
where t.snapshot_ts = $1::timestamptz
and ($2::text is null or exists (
select 1 from assign a join jt_membership m on m.id = a.membership_id
where a.task_id = t.id and a.snapshot_ts = t.snapshot_ts and m.user_name = $2
))
order by t.id
`;
/** Последний снимок каждого дня (America/New_York), от новых к старым. */
export const SNAPSHOT_DAYS_SQL = `
select distinct on (d) d::text as day, snapshot_ts
from (
select (snapshot_ts at time zone 'America/New_York')::date as d, snapshot_ts
from (select snapshot_ts from jt_task union select snapshot_ts from jt_task_hist) s
) x
order by d desc, snapshot_ts desc
`;
/**
* События JobTread сотрудника по дням его часового пояса. Читается представление v_activity_action: только ручные действия, серия событий
* с паузами до 10 секунд (один сдвиг, вызвавший цепочку) считается одним действием.
*/
export const EVENT_COUNTS_SQL = `
select (e.created_at at time zone $4)::date::text as day, e.kind, count(*)::int as n
from v_activity_action e
where e.user_name = $1
and e.created_at >= ($2::date)::timestamp at time zone $4
and e.created_at < (($3::date) + 1)::timestamp at time zone $4
group by 1, 2
`;
/**
* Сообщения сотрудника в чате с ассистентом и в проектных каналах Slack. Пока в журнале ассистента нет автора (до миграции 008) считаем,
* что писал сам менеджер канала. Сообщение проектного канала, которое уже есть в журнале ассистента, считается один раз.
*/
export const CHAT_COUNTS_SQL = `
with msgs as (
select m.received_at as at
from slack_message_log m
where m.manager_person_id = $1
and (m.sender_slack_user_id is null or m.sender_slack_user_id = $5)
union all
select c.posted_at
from slack_channel_message c
join project_channel pc on pc.channel_id = c.channel_id and pc.track_activity
where c.user_id = $5
and not exists (select 1 from slack_message_log l where l.channel_id = c.channel_id and l.message_ts = c.message_ts)
)
select (at at time zone $4)::date::text as day, count(*)::int as n
from msgs
where at >= ($2::date)::timestamp at time zone $4
and at < (($3::date) + 1)::timestamp at time zone $4
group by 1
`;
/** Активность по пользователям JobTread по дням: события JobTread плюс чат (только у тех, кто есть в person). Параметры: от, до (включительно), часовой пояс. */
export const USER_ACTIVITY_DAYS_SQL = `
with ev as (
select user_name, (created_at at time zone $3)::date::text as day, count(*)::int as n,
(count(*) filter (where kind = 'daily_log_created'))::int as logs
from v_activity_action
where user_name is not null
and created_at >= ($1::date)::timestamp at time zone $3
and created_at < (($2::date) + 1)::timestamp at time zone $3
group by 1, 2
),
msgs as (
select mb.user_name, s.received_at as at
from slack_message_log s
join person p on p.id = s.manager_person_id
join jt_membership mb on mb.id = p.jt_membership_id
where (s.sender_slack_user_id is null or s.sender_slack_user_id = p.slack_user_id)
union all
select mb.user_name, c.posted_at
from slack_channel_message c
join project_channel pc on pc.channel_id = c.channel_id and pc.track_activity
join person p on p.slack_user_id = c.user_id
join jt_membership mb on mb.id = p.jt_membership_id
where not exists (select 1 from slack_message_log l where l.channel_id = c.channel_id and l.message_ts = c.message_ts)
),
chat as (
select user_name, (at at time zone $3)::date::text as day, count(*)::int as n
from msgs
where at >= ($1::date)::timestamp at time zone $3
and at < (($2::date) + 1)::timestamp at time zone $3
group by 1, 2
)
select coalesce(ev.user_name, chat.user_name) as user_name, coalesce(ev.day, chat.day) as day,
coalesce(ev.n, 0) + coalesce(chat.n, 0) as total, coalesce(ev.logs, 0) as logs
from ev full join chat on chat.user_name = ev.user_name and chat.day = ev.day
`;
export function createRepo(db: Queryable): ReportsRepo {
return {
async listTracked() {
const { rows } = await db.query(
`select t.person_id, p.display_name as name, coalesce(cm.timezone, 'America/New_York') as tz, p.slack_user_id, m.user_name as jt_user_name
from activity_tracked_person t
join person p on p.id = t.person_id
left join construction_manager cm on cm.person_id = p.id
left join jt_membership m on m.id = p.jt_membership_id
where t.is_enabled order by p.display_name`,
);
return rows.map((r) => ({ personId: r.person_id, name: r.name, tz: r.tz, slackUserId: r.slack_user_id, jtUserName: r.jt_user_name }));
},
async dailyCounts(p, from, to) {
const out = new Map<string, Partial<DayCounts>>();
const bump = (day: string, kind: keyof DayCounts, n: number) => {
const cur = out.get(day) ?? emptyCounts();
cur[kind] = (cur[kind] ?? 0) + n;
out.set(day, cur);
};
if (p.jtUserName) {
for (const r of (await db.query(EVENT_COUNTS_SQL, [p.jtUserName, from, to, p.tz])).rows) {
if ((EVENT_KINDS as readonly string[]).includes(r.kind)) bump(r.day, r.kind, r.n);
}
}
if (p.slackUserId) {
for (const r of (await db.query(CHAT_COUNTS_SQL, [p.personId, from, to, p.tz, p.slackUserId])).rows) bump(r.day, "chat", r.n);
}
return out;
},
async nonWorkdays(from, to) {
const { rows } = await db.query("select day::text as day from calendar_day where not is_workday and day between $1::date and $2::date", [from, to]);
return new Set(rows.map((r) => r.day as string));
},
async syncState() {
const { rows } = await db.query("select last_success_at, last_error, last_loaded from activity_sync_state where source = 'events'");
const r = rows[0];
return { lastSuccessAt: r?.last_success_at ? new Date(r.last_success_at).toISOString() : null, lastError: r?.last_error ?? null, lastLoaded: r?.last_loaded ?? 0 };
},
async listSnapshotDays() {
return (await db.query(SNAPSHOT_DAYS_SQL)).rows.map((r) => ({ day: r.day as string, snapshotTs: new Date(r.snapshot_ts).toISOString() }));
},
async todoReport(snapshotTs) {
return (await db.query(TODO_REPORT_SQL, [snapshotTs])).rows as TodoReportRow[];
},
async todoSource(snapshotTs, employee) {
const rows = (await db.query(TODO_SOURCE_SQL, [snapshotTs, employee ?? null])).rows;
return rows.map((r) => ({ ...r, snapshot_ts: new Date(r.snapshot_ts).toISOString() })) as TodoSourceRow[];
},
async activityByUserDays(from, to, tz) {
const out: UserActivityByDay = new Map();
for (const r of (await db.query(USER_ACTIVITY_DAYS_SQL, [from, to, tz])).rows) {
const days = out.get(r.user_name) ?? new Map();
days.set(r.day, { total: r.total, dailyLogs: r.logs });
out.set(r.user_name, days);
}
return out;
},
};
}