bitrix_task_control/src/reports/workload/main.ts

251 lines
7.7 KiB
TypeScript

import { REPORT_PREFIXES } from '../../core/constants';
import { getSourceSheet } from '../../core/config';
import { bitrixBooleanToString, decodeTaskCodes } from '../../core/taskCodes';
import { diffMinutes, formatDate, isSameDay } from '../../core/dates';
import { applyReportSheetLayout } from '../../core/sheets/columnLayout';
import { createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
import { MetricsStorage } from '../../core/metrics/storage';
export function reportCurrentWeek(): void {
const range = getCurrentWeekRange();
buildReport(range.start, range.end);
}
export function reportNextWeek(): void {
const range = getNextWeekRange();
buildReport(range.start, range.end);
}
export function report10Days(): void {
const range = getNext10DaysRange();
buildReport(range.start, range.end);
}
function buildReport(startDate: Date, endDate: Date): void {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const dataSheet = getSourceSheet(ss);
const reportSheet = createTimestampedSheet(REPORT_PREFIXES.workload, ss);
const data = dataSheet.getDataRange().getValues();
const map = getHeaderMap(data[0]);
const taskIndex: Record<string, any[]> = {};
for (let i = 1; i < data.length; i++) {
const id = data[i][map['ID']];
if (!id) continue;
taskIndex[id] = data[i];
}
const tasks: any[] = [];
for (let i = 1; i < data.length; i++) {
const task = normalizeTask(data[i], map);
if (!task) continue;
if (task.deadline < startDate || task.deadline > endDate) continue;
tasks.push(task);
}
const grouped: Record<string, any[]> = {};
tasks.forEach(task => {
const executor = task.executor || 'Без исполнителя';
if (!grouped[executor]) grouped[executor] = [];
grouped[executor].push(task);
});
Object.keys(grouped).forEach(executor => {
grouped[executor].sort((a, b) => a.deadline - b.deadline);
});
let currentRow = renderGlobalHeader(reportSheet, 1, startDate, endDate);
Object.keys(grouped).forEach(executor => {
currentRow = renderExecutorBlock(reportSheet, currentRow, executor, grouped[executor], startDate, endDate);
currentRow += 3;
});
decodeTaskCodes(reportSheet);
autoFormat(reportSheet);
setReportSheetFormat(reportSheet);
applyReportSheetLayout(reportSheet, 'workload');
}
function normalizeTask(row: any[], map: Record<string, number>) {
const start = new Date(row[map['Планируемая дата начала']]);
const end = new Date(row[map['Планируемая дата окончания']]);
return {
id: row[map['ID']],
title: row[map['Название']],
creator: row[map['Постановщик']],
executor: row[map['Исполнитель']],
created: row[map['Дата создания']],
deadline: start,
duration: diffMinutes(start, end),
clientRisk: bitrixBooleanToString(row[map['Может привести к потере клиента']])
};
}
function renderExecutorBlock(
sheet: GoogleAppsScript.Spreadsheet.Sheet,
startRow: number,
executor: string,
tasks: any[],
startDate: Date,
endDate: Date
): number {
const dates = getDatesArray(startDate, endDate);
const metricsStorage = new MetricsStorage();
let row = startRow;
const dayTotals: Record<string, number> = {};
const dayCounts: Record<string, number> = {};
dates.forEach(d => {
const key = formatDate(d);
dayTotals[key] = 0;
dayCounts[key] = 0;
});
let totalExecutorHours = 0;
tasks.forEach(task => {
const values: any[] = [
task.id,
task.title,
task.creator,
executor,
task.created ? formatDate(new Date(task.created)) : '',
task.clientRisk
];
dates.forEach(date => {
if (isSameDay(date, task.deadline)) {
values.push(task.duration);
const key = formatDate(date);
dayTotals[key] += task.duration;
dayCounts[key]++;
} else {
values.push('');
}
});
totalExecutorHours += Number(task.duration);
values.push('');
values.push('');
sheet.getRange(row, 1, 1, values.length).setValues([values]);
row++;
});
const totalHoursRow: any[] = ['', '', '', executor, '', 'Итого время'];
dates.forEach(date => {
metricsStorage.updateMetric(date, executor, 'todayMinutes', dayTotals[formatDate(date)]);
metricsStorage.sortSheet();
totalHoursRow.push(dayTotals[formatDate(date)]);
});
totalHoursRow.push(totalExecutorHours);
totalHoursRow.push('');
const maxColumns = sheet.getDataRange().getNumColumns();
sheet.getRange(row, 1, 1, totalHoursRow.length).setValues([totalHoursRow]);
sheet.getRange(row, 1, 2, maxColumns).setBackground('green');
row++;
const totalCountRow: any[] = ['', '', '', executor, '', 'Итого количество'];
let totalCount = 0;
dates.forEach(date => {
const count = dayCounts[formatDate(date)];
metricsStorage.updateMetric(date, executor, 'todayTasks', count);
totalCount += count;
totalCountRow.push(count);
metricsStorage.sortSheet();
});
totalCountRow.push(totalCount);
totalCountRow.push('');
sheet.getRange(row, 1, 1, totalCountRow.length).setValues([totalCountRow]);
const approvalOptions = SpreadsheetApp.newDataValidation()
.requireValueInList(['Да', 'Нет', 'Внес корректировки'])
.setAllowInvalid(false)
.build();
sheet.getRange(row, totalCountRow.length, 1, 1).setDataValidation(approvalOptions);
return row + 1;
}
function autoFormat(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
const range = sheet.getDataRange();
range.setBorder(true, true, true, true, true, true);
range.setVerticalAlignment('middle');
}
function getHeaderMap(headers: any[]): Record<string, number> {
const map: Record<string, number> = {};
headers.forEach((h, i) => {
map[h] = i;
});
return map;
}
function getCurrentWeekRange() {
const now = new Date();
const day = now.getDay();
const monday = new Date(now);
monday.setDate(now.getDate() - (day === 0 ? 6 : day - 1));
monday.setHours(0, 0, 0, 0);
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
sunday.setHours(23, 59, 59, 999);
return { start: monday, end: sunday };
}
function getNextWeekRange() {
const current = getCurrentWeekRange();
const start = new Date(current.start);
start.setDate(start.getDate() + 7);
const end = new Date(current.end);
end.setDate(end.getDate() + 7);
return { start, end };
}
function getNext10DaysRange() {
const start = new Date();
const end = new Date(start);
end.setDate(end.getDate() + 10);
return { start, end };
}
function getDatesArray(start: Date, end: Date): Date[] {
const dates: Date[] = [];
const current = new Date(start);
while (current <= end) {
dates.push(new Date(current));
current.setDate(current.getDate() + 1);
}
return dates;
}
function formatDateWeekDay(date: Date): string {
const weekdays = [
'Воскресенье', 'Понедельник', 'Вторник', 'Среда',
'Четверг', 'Пятница', 'Суббота'
];
return `${formatDate(date)} - ${weekdays[date.getDay()]}`;
}
function renderGlobalHeader(
sheet: GoogleAppsScript.Spreadsheet.Sheet,
row: number,
startDate: Date,
endDate: Date
): number {
const dates = getDatesArray(startDate, endDate);
const headers = [
'ID задачи', 'Название', 'Постановщик', 'Исполнитель',
'Дата создания', 'Ведет к потере клиента'
];
dates.forEach(date => headers.push(formatDateWeekDay(date)));
headers.push('Сумма по периоду');
headers.push('Согласовано');
sheet.getRange(row, 1, 1, headers.length).setValues([headers]).setFontWeight('bold');
return row + 2;
}