607 lines
23 KiB
TypeScript
607 lines
23 KiB
TypeScript
import { REPORT_PREFIXES } from '../../core/constants';
|
||
import { getTaskControlSet } from '../../core/bitrix/client';
|
||
import { getAppConfig, getCompletedSourceSheet, getSourceSheet } from '../../core/config';
|
||
import { requestDate } from '../../core/ui';
|
||
import { bitrixBooleanToString, decodeTaskCodes, getTaskStatusName } from '../../core/taskCodes';
|
||
import { diffMinutes, formatDate, hoursToMinutes, parseDurationToHours, secondsToHours } from '../../core/dates';
|
||
import { compareNames } from '../../core/mail/emailConfig';
|
||
import { createTimestampedSheet, getColumnIndexesByName } from '../../core/sheets/reportLifecycle';
|
||
import { MetricsStorage } from '../../core/metrics/storage';
|
||
import { loadTaskResultColumn } from './loadTaskResultInfo';
|
||
|
||
const REPORT_HEADERS = [
|
||
'ID задачи', 'Наименование задачи', 'ID родительской задачи', 'Название родительской задачи', 'Дата создания', 'Крайний срок задачи',
|
||
'Постановщик', 'Исполнитель', 'Руководитель филиала', 'Статус',
|
||
'Планируемая длительность', 'Ведет к потере клиента', 'Цена задачи', 'Дата завершения'
|
||
];
|
||
|
||
const RESULT_COLUMN = 'Результат задачи';
|
||
const REQUIRE_RESULT_COLUMN = 'Требовался ли результат';
|
||
|
||
const TASK_FIELDS = {
|
||
id: 'ID задачи',
|
||
title: 'Наименование задачи',
|
||
parentTaskId: 'ID родительской задачи',
|
||
parentTaskTitle: 'Название родительской задачи',
|
||
deadline: 'Крайний срок задачи',
|
||
creator: 'Постановщик',
|
||
responsible: 'Исполнитель',
|
||
status: 'Статус',
|
||
closedDate: 'Дата закрытия',
|
||
crm: 'CRM',
|
||
timeEstimate: 'Время выполнения задачи',
|
||
clientLoss: 'Ведет к потере клиента',
|
||
price: 'Цена задачи',
|
||
completedDate: 'Дата закрытия'
|
||
};
|
||
|
||
export function buildCompletedTasksReport(): void {
|
||
const lastReportDate = requestDate('Введите дату последнего отчета по завершенным задачам');
|
||
try {
|
||
const controlSheet = findSingleTodayReport(REPORT_PREFIXES.waitingControl);
|
||
const selfSheet = findSingleTodayReport(REPORT_PREFIXES.selfTasks);
|
||
const completedTasks = loadCompletedTasks(lastReportDate);
|
||
const waitingControlTasks = loadWaitingControlTasks(controlSheet);
|
||
const selfTasks = loadSelfTasks(selfSheet);
|
||
const executors = buildStatistics(completedTasks, waitingControlTasks, selfTasks);
|
||
addSalesDepHeadToExecutors(executors);
|
||
const includeRequireResult = attachTaskResults(executors);
|
||
generateReport(executors, includeRequireResult);
|
||
} catch (e: any) {
|
||
SpreadsheetApp.getUi().alert(e.message);
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
function findSingleTodayReport(prefix: string) {
|
||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||
const today = formatDate(new Date());
|
||
const found = ss.getSheets().filter(sheet =>
|
||
sheet.getName().startsWith(prefix) && sheet.getName().indexOf(today) !== -1
|
||
);
|
||
|
||
if (found.length === 0) {
|
||
throw new Error(`Не найден отчет "${prefix}" за сегодня`);
|
||
}
|
||
|
||
if (found.length > 1) {
|
||
throw new Error(
|
||
`Обнаружены два ${prefix} за сегодня. Должен быть только один такой отчет. Посмотри, какой из них уже не актуален и удали его. После удаления запусти формирование заново.`
|
||
);
|
||
}
|
||
|
||
return found[0];
|
||
}
|
||
|
||
function getAllExecutorNames(): any[] {
|
||
const sourceSheet = getSourceSheet();
|
||
const dataRange = sourceSheet.getDataRange();
|
||
const sourceSheetHeader = sourceSheet.getRange(1, 1, 1, dataRange.getNumColumns()).getValues()[0];
|
||
const executorColumnIndex = sourceSheetHeader.indexOf('Исполнитель');
|
||
if (executorColumnIndex == -1) return [];
|
||
|
||
const executorColumnValues = sourceSheet
|
||
.getRange(1, executorColumnIndex + 1, dataRange.getNumColumns(), 1)
|
||
.getValues()
|
||
.slice(1);
|
||
|
||
return [...new Set(executorColumnValues.map(row => row[0]))];
|
||
}
|
||
|
||
const COMPLETED_SOURCE_COLUMNS = {
|
||
id: 'ID',
|
||
title: 'Название',
|
||
parentTaskId: 'ID базовой задачи',
|
||
parentTaskTitle: 'Название базовой задачи',
|
||
createdDate: 'Дата создания',
|
||
deadline: 'Крайний срок',
|
||
creator: 'Постановщик',
|
||
responsible: 'Исполнитель',
|
||
status: 'Статус',
|
||
closedDate: 'Дата закрытия',
|
||
plannedDuration: 'Планируемая длительность',
|
||
planStart: 'Планируемая дата начала',
|
||
planEnd: 'Планируемая дата окончания',
|
||
price: 'Цена задачи',
|
||
clientLoss: 'Может привести к потере клиента',
|
||
};
|
||
|
||
function loadCompletedTasks(afterDate: Date) {
|
||
const sheet = getCompletedSourceSheet();
|
||
const values = sheet.getDataRange().getValues();
|
||
if (values.length < 2) {
|
||
throw new Error('На листе выгрузки завершенных задач нет данных');
|
||
}
|
||
|
||
const headers = values[0].map(header => String(header).trim());
|
||
const col: Record<string, number> = {};
|
||
headers.forEach((header, index) => {
|
||
if (header) col[header] = index;
|
||
});
|
||
|
||
const missingColumns = Object.values(COMPLETED_SOURCE_COLUMNS).filter(name => !(name in col));
|
||
if (missingColumns.length) {
|
||
throw new Error('На листе выгрузки завершенных задач не найдены колонки: ' + missingColumns.join(', '));
|
||
}
|
||
|
||
const performerNames = getAllExecutorNames().map(name => String(name ?? '').trim()).filter(Boolean);
|
||
const result = new Map<string, any[]>();
|
||
performerNames.forEach(name => result.set(name, []));
|
||
|
||
const from = startOfDay(afterDate).getTime();
|
||
const to = startOfDay(new Date()).getTime();
|
||
const loaded: Array<{ performerName: string; task: any }> = [];
|
||
|
||
for (let i = 1; i < values.length; i++) {
|
||
const row = values[i];
|
||
const id = row[col[COMPLETED_SOURCE_COLUMNS.id]];
|
||
if (id === '' || id == null) continue;
|
||
|
||
const closedDate = toDate(row[col[COMPLETED_SOURCE_COLUMNS.closedDate]]);
|
||
if (!closedDate) continue;
|
||
const closedTime = closedDate.getTime();
|
||
if (closedTime < from || closedTime >= to) continue;
|
||
|
||
const performerName = String(row[col[COMPLETED_SOURCE_COLUMNS.responsible]] ?? '').trim();
|
||
if (!performerName || !result.has(performerName)) continue;
|
||
|
||
loaded.push({
|
||
performerName,
|
||
task: {
|
||
id,
|
||
title: row[col[COMPLETED_SOURCE_COLUMNS.title]],
|
||
parentTaskId: row[col[COMPLETED_SOURCE_COLUMNS.parentTaskId]],
|
||
parentTaskTitle: row[col[COMPLETED_SOURCE_COLUMNS.parentTaskTitle]],
|
||
createdDate: toDate(row[col[COMPLETED_SOURCE_COLUMNS.createdDate]]),
|
||
deadline: toDate(row[col[COMPLETED_SOURCE_COLUMNS.deadline]]),
|
||
creator: row[col[COMPLETED_SOURCE_COLUMNS.creator]],
|
||
responsible: performerName,
|
||
status: row[col[COMPLETED_SOURCE_COLUMNS.status]],
|
||
timeEstimate: plannedDurationSeconds(row, col),
|
||
clientLoss: bitrixBooleanToString(row[col[COMPLETED_SOURCE_COLUMNS.clientLoss]]),
|
||
price: row[col[COMPLETED_SOURCE_COLUMNS.price]],
|
||
taskControl: 'N',
|
||
completedDate: closedDate,
|
||
},
|
||
});
|
||
}
|
||
|
||
const taskControlSet = getTaskControlSet(loaded.map(item => item.task.id));
|
||
loaded.forEach(item => {
|
||
if (taskControlSet.has(String(item.task.id))) {
|
||
item.task.taskControl = 'Y';
|
||
}
|
||
const performerTasks = result.get(item.performerName);
|
||
if (performerTasks) performerTasks.push(item.task);
|
||
});
|
||
|
||
return result;
|
||
}
|
||
|
||
function plannedDurationSeconds(row: any[], col: Record<string, number>): number {
|
||
const planStart = toDate(row[col[COMPLETED_SOURCE_COLUMNS.planStart]]);
|
||
const planEnd = toDate(row[col[COMPLETED_SOURCE_COLUMNS.planEnd]]);
|
||
if (planStart && planEnd) {
|
||
const minutes = diffMinutes(planStart, planEnd);
|
||
if (minutes !== '') return Number(minutes) * 60;
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
function startOfDay(date: Date): Date {
|
||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||
}
|
||
|
||
function toDate(value: any): Date | null {
|
||
if (value instanceof Date && !isNaN(value.getTime())) return value;
|
||
if (typeof value !== 'string') return null;
|
||
|
||
const match = value.trim().match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/);
|
||
if (!match) return null;
|
||
|
||
const date = new Date(
|
||
Number(match[3]),
|
||
Number(match[2]) - 1,
|
||
Number(match[1]),
|
||
Number(match[4] || 0),
|
||
Number(match[5] || 0),
|
||
Number(match[6] || 0)
|
||
);
|
||
|
||
return isNaN(date.getTime()) ? null : date;
|
||
}
|
||
|
||
function loadWaitingControlTasks(sheet: GoogleAppsScript.Spreadsheet.Sheet) {
|
||
const tasks = getObjects(sheet, TASK_FIELDS);
|
||
const allCreatedDates = getIdToColumnValueMap(getSourceSheet(), 'Дата создания');
|
||
const allTimeEstimates = getIdToColumnValueMap(getSourceSheet(), 'Планируемая длительность');
|
||
|
||
const rejectedTasks = tasks.filter(task =>
|
||
task.status === 'Ждёт выполнения' || task.status === 'Ждет выполнения'
|
||
);
|
||
|
||
rejectedTasks.forEach(task => {
|
||
const taskId = String(task.id);
|
||
if (allCreatedDates.has(taskId)) {
|
||
task.createdDate = allCreatedDates.get(taskId);
|
||
}
|
||
if (allTimeEstimates.has(taskId)) {
|
||
task.timeEstimate = parseDurationToHours(allTimeEstimates.get(taskId)) * 3600;
|
||
}
|
||
});
|
||
|
||
return rejectedTasks;
|
||
}
|
||
|
||
function loadSelfTasks(sheet: GoogleAppsScript.Spreadsheet.Sheet) {
|
||
return getObjects(sheet, TASK_FIELDS);
|
||
}
|
||
|
||
function buildStatistics(completedTasks: Map<string, any[]>, waitingControlTasks: any[], selfTasks: any[]) {
|
||
const executors: Record<string, any> = {};
|
||
|
||
completedTasks.forEach((tasks, executor) => {
|
||
if (!executors[executor]) {
|
||
executors[executor] = createEmptyExecutor(executor);
|
||
}
|
||
|
||
executors[executor].tasks.push(...tasks);
|
||
tasks.forEach(task => {
|
||
executors[executor].completedCount++;
|
||
executors[executor].effectiveDuration += Number(task.timeEstimate) / 60;
|
||
if (task.taskControl == 'Y') {
|
||
executors[executor].sentToAcceptance++;
|
||
executors[executor].acceptedCount++;
|
||
executors[executor].effectiveCount++;
|
||
}
|
||
});
|
||
});
|
||
|
||
waitingControlTasks.forEach(task => {
|
||
const executor = task.responsible;
|
||
if (!executor) return;
|
||
if (!executors[executor]) executors[executor] = createEmptyExecutor(executor);
|
||
executors[executor].waitingControl.push(task);
|
||
executors[executor].sentToAcceptance++;
|
||
});
|
||
|
||
selfTasks.forEach(task => {
|
||
const executor = task.responsible;
|
||
if (!executor) return;
|
||
if (!executors[executor]) executors[executor] = createEmptyExecutor(executor);
|
||
executors[executor].selfTasks.push(task);
|
||
});
|
||
|
||
return executors;
|
||
}
|
||
|
||
function createEmptyExecutor(name: string) {
|
||
return {
|
||
name,
|
||
tasks: [],
|
||
waitingControl: [],
|
||
selfTasks: [],
|
||
depHead: '',
|
||
completedCount: 0,
|
||
effectiveCount: 0,
|
||
acceptedCount: 0,
|
||
sentToAcceptance: 0,
|
||
effectiveDuration: 0
|
||
};
|
||
}
|
||
|
||
function addSalesDepHeadToExecutors(executors: Record<string, any>): string | void {
|
||
const appConfig = getAppConfig();
|
||
const file = DriveApp.getFileById(appConfig.orgStructureFileId);
|
||
const data = JSON.parse(file.getBlob().getDataAsString('UTF-8'));
|
||
const department = data.departments[appConfig.departmentId];
|
||
|
||
if (!department || !department.head) {
|
||
return '';
|
||
}
|
||
|
||
Object.keys(executors).forEach(name => {
|
||
let employeeInDep = false;
|
||
department.employees.forEach((emp: any) => {
|
||
if (compareNames(emp.fullName, name)) employeeInDep = true;
|
||
});
|
||
|
||
executors[name].depHead = employeeInDep
|
||
? department.head.fullName
|
||
: appConfig.defaultFilialHeadName;
|
||
});
|
||
}
|
||
|
||
function attachTaskResults(executors: Record<string, any>): boolean {
|
||
const tasks: any[] = [];
|
||
Object.values(executors).forEach(executor => {
|
||
tasks.push(...executor.tasks, ...executor.waitingControl);
|
||
});
|
||
|
||
const loaded = loadTaskResultColumn(tasks.map(task => task.id));
|
||
tasks.forEach(task => {
|
||
const id = String(task.id ?? '').trim();
|
||
task.resultText = loaded.texts.get(id) || '';
|
||
if (loaded.requireResult) {
|
||
task.requireResult = loaded.requireResult.get(id) || '';
|
||
}
|
||
});
|
||
|
||
return loaded.requireResult !== null;
|
||
}
|
||
|
||
function reportHeaders(includeRequireResult: boolean): string[] {
|
||
const headers = [...REPORT_HEADERS, RESULT_COLUMN];
|
||
if (includeRequireResult) headers.push(REQUIRE_RESULT_COLUMN);
|
||
return headers;
|
||
}
|
||
|
||
function generateReport(executors: Record<string, any>, includeRequireResult: boolean): void {
|
||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||
const sheet = createTimestampedSheet(REPORT_PREFIXES.completed, ss);
|
||
const headers = reportHeaders(includeRequireResult);
|
||
let row = 1;
|
||
|
||
sheet.getRange(row, 1, 1, headers.length)
|
||
.setValues([headers])
|
||
.setBackground('#ffff00')
|
||
.setFontWeight('bold');
|
||
row++;
|
||
|
||
const metricsStorage = new MetricsStorage();
|
||
const now = new Date();
|
||
|
||
Object.values(executors)
|
||
.sort((a, b) => a.name.localeCompare(b.name))
|
||
.forEach(executor => {
|
||
executor.reportTasks = [];
|
||
executor.reportTasks.push(...executor.tasks);
|
||
executor.reportTasks.push(...executor.waitingControl);
|
||
sortObjects(executor.reportTasks);
|
||
|
||
const toWrite = createTaskArray(executor, includeRequireResult);
|
||
if (toWrite.length == 0) return;
|
||
|
||
sheet.getRange(row, 1, toWrite.length, headers.length)
|
||
.setValues(toWrite)
|
||
.setBorder(true, true, true, true, true, true);
|
||
row += toWrite.length;
|
||
|
||
const effectivePercent = executor.reportTasks.length === 0
|
||
? 0
|
||
: executor.completedCount / executor.reportTasks.length * 100;
|
||
|
||
const acceptancePercent = executor.sentToAcceptance === 0
|
||
? 0
|
||
: executor.acceptedCount / executor.sentToAcceptance * 100;
|
||
|
||
metricsStorage.updateMetric(now, executor.name, 'completed', executor.completedCount + executor.sentToAcceptance);
|
||
metricsStorage.updateMetric(now, executor.name, 'returned', executor.sentToAcceptance - executor.acceptedCount);
|
||
metricsStorage.updateMetric(now, executor.name, 'completedPercent', effectivePercent);
|
||
metricsStorage.updateMetric(now, executor.name, 'reviewCompleted', executor.sentToAcceptance);
|
||
metricsStorage.updateMetric(now, executor.name, 'reviewAccepted', executor.acceptedCount);
|
||
metricsStorage.updateMetric(now, executor.name, 'reviewPercent', acceptancePercent);
|
||
metricsStorage.updateMetric(now, executor.name, 'spentHours', executor.effectiveDuration);
|
||
metricsStorage.updateMetric(now, executor.name, 'newTasks', executor.selfTasks.length);
|
||
|
||
writeKpi(
|
||
sheet, row, effectivePercent, executor.completedCount, acceptancePercent,
|
||
executor.selfTasks.length, executor.effectiveDuration, executor.reportTasks.length,
|
||
executor.acceptedCount, executor.sentToAcceptance, executor.name, executor.depHead
|
||
);
|
||
|
||
row += 7;
|
||
});
|
||
|
||
decodeTaskCodes(sheet);
|
||
decodeTaskCodes(sheet, 'Название родительской задачи');
|
||
setupConditionalFormatting(sheet);
|
||
const standardWidth = sheet.getColumnWidth(1);
|
||
sheet.autoResizeColumns(1, sheet.getDataRange().getNumColumns());
|
||
sheet.setColumnWidth(2, standardWidth * 7);
|
||
const resultColumn = findHeaderColumn(sheet, RESULT_COLUMN);
|
||
if (resultColumn !== -1 && sheet.getLastRow() > 0) {
|
||
sheet.setColumnWidth(resultColumn, standardWidth * 6);
|
||
sheet.getRange(1, resultColumn, sheet.getLastRow(), 1).setWrap(true).setVerticalAlignment('top');
|
||
}
|
||
metricsStorage.sortSheet();
|
||
}
|
||
|
||
function createTaskArray(executor: any, includeRequireResult: boolean): any[][] {
|
||
return executor.reportTasks.map((task: any) => {
|
||
const row = [
|
||
task.id,
|
||
task.title,
|
||
task.parentTaskId ?? '',
|
||
task.parentTaskTitle ?? '',
|
||
formatDate(task.createdDate),
|
||
formatDate(task.deadline),
|
||
task.creator,
|
||
task.responsible,
|
||
executor.depHead,
|
||
getTaskStatusName(task.status),
|
||
hoursToMinutes(secondsToHours(task.timeEstimate)),
|
||
task.clientLoss,
|
||
task.price,
|
||
task.completedDate ? formatDate(task.completedDate) : '',
|
||
task.resultText || '',
|
||
];
|
||
|
||
if (includeRequireResult) {
|
||
row.push(task.requireResult || '');
|
||
}
|
||
|
||
return row;
|
||
});
|
||
}
|
||
|
||
function writeKpi(
|
||
sheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||
startRow: number,
|
||
effectivePercent: number,
|
||
completedCount: number,
|
||
acceptancePercent: number,
|
||
selfCount: number,
|
||
duration: number,
|
||
reportTaskCount: number,
|
||
acceptedCount: number,
|
||
sentToAcceptance: number,
|
||
executorName: string,
|
||
filialHeadName: string
|
||
): void {
|
||
const data = [
|
||
['Процент эффективно завершенных задач по отношению ко всем завершенным задачам:', `${effectivePercent.toFixed(0)}% (${completedCount}/${reportTaskCount})`],
|
||
['Процент принятых постановщиком задач по отношению ко всем задачам, требующим приемки:', `${acceptancePercent.toFixed(0)}% (${acceptedCount}/${sentToAcceptance})`],
|
||
['Количество задач самому себе за вчера:', selfCount],
|
||
['Суммарно эффективно затраченное время:', duration],
|
||
['Оценка руководителя филиала (1-5):', ''],
|
||
['Комментарий руководителя филиала:', ''],
|
||
['ID задачи руководителя (если требуется):', '']
|
||
];
|
||
|
||
const columnIndexes = getColumnIndexesByName(1, ['Исполнитель', 'Руководитель филиала']);
|
||
const labelColumn = findHeaderColumn(sheet, 'Наименование задачи');
|
||
const valueColumn = findHeaderColumn(sheet, 'Дата создания');
|
||
|
||
if (labelColumn === -1 || valueColumn === -1) {
|
||
throw new Error('Не найдены столбцы для блока оценки руководителя');
|
||
}
|
||
|
||
sheet.getRange(startRow, columnIndexes[0], 7, 1).setValues(Array.from({ length: 7 }, () => [executorName]));
|
||
sheet.getRange(startRow, columnIndexes[1], 7, 1).setValues(Array.from({ length: 7 }, () => [filialHeadName]));
|
||
|
||
data.forEach((pair, offset) => {
|
||
sheet.getRange(startRow + offset, labelColumn).setValue(pair[0]);
|
||
sheet.getRange(startRow + offset, valueColumn).setValue(pair[1]);
|
||
});
|
||
sheet.getRange(startRow, labelColumn, data.length, 1)
|
||
.setBackground('#ffff00')
|
||
.setBorder(true, true, true, true, true, true);
|
||
sheet.getRange(startRow, valueColumn, data.length, 1)
|
||
.setBackground('#ffff00')
|
||
.setBorder(true, true, true, true, true, true);
|
||
|
||
const rule = SpreadsheetApp.newDataValidation()
|
||
.requireValueInList([1, 2, 3, 4, 5])
|
||
.setAllowInvalid(false)
|
||
.build();
|
||
sheet.getRange(startRow + 4, valueColumn, 1, 1).setDataValidation(rule);
|
||
}
|
||
|
||
function setupConditionalFormatting(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||
const MARKER = 'Оценка руководителя филиала (1-5):';
|
||
const lastRow = sheet.getLastRow();
|
||
const labelColumn = findHeaderColumn(sheet, 'Наименование задачи');
|
||
const valueColumn = findHeaderColumn(sheet, 'Дата создания');
|
||
|
||
if (labelColumn === -1 || valueColumn === -1) {
|
||
throw new Error('Не найдены столбцы для блока оценки руководителя');
|
||
}
|
||
|
||
const values = sheet.getRange(1, labelColumn, lastRow, 1).getValues();
|
||
const valueLetter = columnIndexToLetter(valueColumn);
|
||
const rules: GoogleAppsScript.Spreadsheet.ConditionalFormatRule[] = [];
|
||
|
||
for (let row = 1; row <= values.length; row++) {
|
||
if (values[row - 1][0] !== MARKER) continue;
|
||
|
||
const percentRow = row - 4;
|
||
const scoreRow = row;
|
||
const formula =
|
||
`=OR(` +
|
||
`VALUE(REGEXEXTRACT($${valueLetter}$${percentRow};"^\\d+"))<50;` +
|
||
`$${valueLetter}$${scoreRow}<4` +
|
||
`)`;
|
||
|
||
rules.push(
|
||
SpreadsheetApp.newConditionalFormatRule()
|
||
.whenFormulaSatisfied(formula)
|
||
.setBackground('#ff0000')
|
||
.setRanges([
|
||
sheet.getRange(row + 1, valueColumn),
|
||
sheet.getRange(row + 2, valueColumn)
|
||
])
|
||
.build()
|
||
);
|
||
}
|
||
|
||
sheet.setConditionalFormatRules(rules);
|
||
}
|
||
|
||
function findHeaderColumn(sheet: GoogleAppsScript.Spreadsheet.Sheet, columnName: string): number {
|
||
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
|
||
const index = headers.findIndex(header => String(header).trim() === columnName);
|
||
return index === -1 ? -1 : index + 1;
|
||
}
|
||
|
||
function columnIndexToLetter(columnIndex: number): string {
|
||
let index = columnIndex;
|
||
let letter = '';
|
||
|
||
while (index > 0) {
|
||
const remainder = (index - 1) % 26;
|
||
letter = String.fromCharCode(65 + remainder) + letter;
|
||
index = Math.floor((index - 1) / 26);
|
||
}
|
||
|
||
return letter;
|
||
}
|
||
|
||
function getObjects(sheet: GoogleAppsScript.Spreadsheet.Sheet, mapping: Record<string, string>) {
|
||
const data = sheet.getDataRange().getValues();
|
||
if (data.length < 2) return [];
|
||
|
||
const headers = data[0];
|
||
const indexes: Record<string, number> = {};
|
||
Object.entries(mapping).forEach(([field, columnName]) => {
|
||
indexes[field] = headers.indexOf(columnName);
|
||
});
|
||
|
||
return data.slice(1).map(row => {
|
||
const obj: Record<string, any> = {};
|
||
Object.entries(indexes).forEach(([field, index]) => {
|
||
obj[field] = index >= 0 ? row[index] : null;
|
||
});
|
||
return obj;
|
||
});
|
||
}
|
||
|
||
function sortObjects(arr: any[]): any[] {
|
||
const clientLossPriority: Record<string, number> = { 'Да': 0, 'Нет': 1 };
|
||
|
||
return arr.sort((a, b) => {
|
||
const aPriority = clientLossPriority[a.clientLoss] ?? 2;
|
||
const bPriority = clientLossPriority[b.clientLoss] ?? 2;
|
||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||
|
||
if (aPriority === 2) {
|
||
const lossCompare = String(a.clientLoss).localeCompare(String(b.clientLoss), 'ru');
|
||
if (lossCompare !== 0) return lossCompare;
|
||
}
|
||
|
||
return String(a.status).localeCompare(String(b.status), 'ru');
|
||
});
|
||
}
|
||
|
||
function getIdToColumnValueMap(sheet: GoogleAppsScript.Spreadsheet.Sheet, columnName: string) {
|
||
const values = sheet.getDataRange().getValues();
|
||
if (values.length < 2) return new Map();
|
||
|
||
const headers = values[0];
|
||
const idCol = headers.indexOf('ID');
|
||
const targetColumn = headers.indexOf(columnName);
|
||
if (idCol === -1) throw new Error('Колонка "ID" не найдена');
|
||
if (targetColumn === -1) throw new Error(`Колонка ${columnName} не найдена`);
|
||
|
||
const result = new Map<string, any>();
|
||
for (let i = 1; i < values.length; i++) {
|
||
const id = values[i][idCol];
|
||
if (id !== '' && id != null) {
|
||
result.set(String(id), values[i][targetColumn]);
|
||
}
|
||
}
|
||
|
||
return result;
|
||
}
|