diff --git a/src/reports/completed/formatTaskResult.ts b/src/reports/completed/formatTaskResult.ts new file mode 100644 index 0000000..73d7356 --- /dev/null +++ b/src/reports/completed/formatTaskResult.ts @@ -0,0 +1,292 @@ +import { formatDateWithTime } from '../../core/dates'; + +const DISK_TAG = /\[DISK FILE ID=(?:n)?(\d+)\](?:([^[\]]+?)\[\/DISK[^\]]*\])?/gi; +const FILE_NAME_CLASS = /class="[^"]*file-name[^"]*"[^>]*>([^<]+)/gi; +const DISK_ANCHOR = /]+href="([^"]*disk[^"]*)"[^>]*>([^<]*)<\/a>/gi; + +export interface ResolvedTaskFiles { + names: string[]; + unresolvedIds: string[]; +} + +export function formatRequireResult(value: any): string { + if (value == null || value === '') return 'Нет'; + if (value === true || value === 1) return 'Да'; + if (value === false || value === 0) return 'Нет'; + + const normalized = String(value ?? '') + .trim() + .replace(/\.+$/, '') + .toLowerCase(); + + if (normalized === 'y' || normalized === 'да' || normalized === 'true' || normalized === '1') return 'Да'; + if (normalized === 'n' || normalized === 'нет' || normalized === 'false' || normalized === '0') return 'Нет'; + return ''; +} + +export function readRequireResultValue(task: any): { known: boolean; value: string } { + if (!task || typeof task !== 'object') { + return { known: false, value: '' }; + } + + if ('taskRequireResult' in task) { + return { known: true, value: formatRequireResult(task.taskRequireResult) }; + } + + if ('requireResult' in task) { + return { known: true, value: formatRequireResult(task.requireResult) }; + } + + return { known: false, value: '' }; +} + +export function collectFileIdsToResolve(results: any[] | null | undefined): string[] { + const ids = new Set(); + (results || []).forEach(result => { + resolveFiles(result, {}).unresolvedIds.forEach(id => ids.add(id)); + }); + return [...ids]; +} + +export function collectResultAuthorIds(results: any[] | null | undefined): string[] { + const ids = new Set(); + (results || []).forEach(result => { + const id = authorId(result); + if (id) ids.add(id); + }); + return [...ids]; +} + +export function formatTaskResults( + results: any[] | null | undefined, + authorNames: Record = {}, + fileNames: Record = {}, +): string { + return (results || []) + .slice() + .sort((a, b) => resultTime(a) - resultTime(b)) + .map(result => formatOneResult(result, authorNames, fileNames)) + .filter(Boolean) + .join('\n\n'); +} + +function formatOneResult( + result: any, + authorNames: Record, + fileNames: Record, +): string { + const when = resultDate(result); + const author = authorLabel(result, authorNames); + const prefix = [when, author].filter(Boolean).join(', '); + const files = resolveFiles(result, fileNames); + const text = displayText(result, files.names); + const fileLine = filePhrase(files.names, files.unresolvedIds); + const body = [text, fileLine].filter(Boolean).join('\n'); + + if (!prefix && !body) return ''; + if (!body) return prefix; + if (!prefix) return body; + return `${prefix}: ${body}`; +} + +function resolveFiles(result: any, fileNames: Record): ResolvedTaskFiles { + const names: string[] = []; + const namedIds = new Set(); + const seenIds = new Set(); + + const addName = (name: string, id = '') => { + const trimmed = decodeBasic(name).trim(); + if (!trimmed || trimmed.length > 255) return; + if (id) namedIds.add(id); + if (!names.some(item => item.toLowerCase() === trimmed.toLowerCase())) { + names.push(trimmed); + } + }; + + const addId = (id: string) => { + const normalized = String(id || '').trim().replace(/^n/i, ''); + if (normalized) seenIds.add(normalized); + }; + + fileEntries(result).forEach(entry => { + if (entry.id) addId(entry.id); + if (entry.name) addName(entry.name, entry.id); + }); + + sourceTexts(result).forEach(source => { + DISK_TAG.lastIndex = 0; + let match = DISK_TAG.exec(source); + while (match) { + addId(match[1]); + if (match[2]) addName(match[2], match[1].replace(/^n/i, '')); + match = DISK_TAG.exec(source); + } + + FILE_NAME_CLASS.lastIndex = 0; + let classMatch = FILE_NAME_CLASS.exec(source); + while (classMatch) { + addName(classMatch[1]); + classMatch = FILE_NAME_CLASS.exec(source); + } + + DISK_ANCHOR.lastIndex = 0; + let anchorMatch = DISK_ANCHOR.exec(source); + while (anchorMatch) { + const anchorText = String(anchorMatch[2] || '').trim(); + const hrefName = fileNameFromHref(anchorMatch[1]); + addName(anchorText.includes('.') ? anchorText : hrefName); + anchorMatch = DISK_ANCHOR.exec(source); + } + }); + + seenIds.forEach(id => { + const externalName = fileNames[id]; + if (externalName) addName(externalName, id); + }); + + return { + names, + unresolvedIds: [...seenIds].filter(id => !namedIds.has(id)), + }; +} + +function filePhrase(names: string[], unresolvedIds: string[]): string { + const rendered = [ + ...names.map(name => `файл «${name}»`), + ...unresolvedIds.map(id => `файл #${id}`), + ]; + + if (rendered.length === 0) return ''; + if (rendered.length === 1) return rendered[0]; + if (unresolvedIds.length === 0) { + return `файлы ${names.map(name => `«${name}»`).join(', ')}`; + } + + return rendered.join(', '); +} + +function fileEntries(result: any): Array<{ id: string; name: string }> { + const files = result?.files ?? result?.fileIds; + const list = Array.isArray(files) + ? files + : files && typeof files === 'object' + ? Object.values(files) + : []; + if (list.length === 0) return []; + + return list.map(entry => { + if (entry == null) return { id: '', name: '' }; + if (typeof entry === 'number' || typeof entry === 'string') { + return { id: String(entry).trim().replace(/^n/i, ''), name: '' }; + } + + const id = String(entry.id ?? entry.ID ?? entry.fileId ?? '').trim().replace(/^n/i, ''); + const name = String(entry.name ?? entry.NAME ?? '').trim(); + return { id, name }; + }); +} + +function sourceTexts(result: any): string[] { + return [result?.text, result?.formattedText] + .filter(value => value != null && String(value).trim() !== '') + .map(value => String(value)); +} + +function displayText(result: any, fileNames: string[]): string { + const raw = result?.text != null && String(result.text).trim() !== '' + ? String(result.text) + : String(result?.formattedText || ''); + + let text = cleanResultText(raw); + fileNames.forEach(name => { + if (!name) return; + text = text.replace(new RegExp(escapeRegex(name), 'gi'), ''); + }); + + return text + .split('\n') + .map(line => line.trim()) + .filter((line, index, lines) => !(line === '' && lines[index - 1] === '')) + .join('\n') + .trim(); +} + +function cleanResultText(raw: string): string { + const withoutDiskTags = raw.replace(DISK_TAG, ''); + return stripMarkup(withoutDiskTags); +} + +function stripMarkup(text: string): string { + if (!text) return ''; + + let result = String(text); + result = result.replace(/\[\/?p\]/gi, '\n'); + result = result.replace(/\[br\s*\/?\]/gi, '\n'); + result = result.replace(/\[\/?[a-zA-Z0-9]+(?:=[^\]]*)?\]/g, ''); + result = result.replace(/<\/?[a-zA-Z][^>]*>/g, ''); + + return result + .split('\n') + .map(line => line.trim()) + .filter((line, index, lines) => !(line === '' && lines[index - 1] === '')) + .join('\n') + .trim(); +} + +function authorId(result: any): string { + const raw = result?.createdBy ?? result?.authorId ?? result?.author?.id ?? ''; + return String(raw || '').trim(); +} + +function authorLabel(result: any, authorNames: Record): string { + const id = authorId(result); + if (id && authorNames[id]) return authorNames[id]; + + const embedded = embeddedAuthorName(result?.author); + if (embedded) return embedded; + if (id) return `пользователь ${id}`; + return 'автор не указан'; +} + +function embeddedAuthorName(author: any): string { + if (!author || typeof author !== 'object') return ''; + + const parts = [author.lastName, author.name, author.secondName] + .map(part => String(part || '').trim()) + .filter(Boolean); + + return parts.join(' '); +} + +function resultDate(result: any): string { + const raw = result?.createdAt; + if (!raw) return ''; + return formatDateWithTime(new Date(raw)); +} + +function resultTime(result: any): number { + const raw = result?.createdAt; + if (!raw) return 0; + const time = new Date(raw).getTime(); + return Number.isNaN(time) ? 0 : time; +} + +function fileNameFromHref(href: string): string { + const path = decodeBasic(String(href || '').split('?')[0]); + const base = path.split('/').pop() || ''; + return base.includes('.') ? base : ''; +} + +function escapeRegex(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function decodeBasic(value: string): string { + return String(value || '') + .replace(/ /gi, ' ') + .replace(/&/gi, '&') + .replace(/"/gi, '"') + .replace(/'|'/gi, "'") + .replace(/</gi, '<') + .replace(/>/gi, '>'); +} diff --git a/src/reports/completed/index.ts b/src/reports/completed/index.ts index d3cce77..85bfd5f 100644 --- a/src/reports/completed/index.ts +++ b/src/reports/completed/index.ts @@ -32,5 +32,6 @@ export const completedPlugin: ReportPlugin = { 'BALANCER_PUBLIC', 'BALANCER_SECRET', 'BITRIX_WEBHOOK_TASKS', + 'BITRIX_WEBHOOK_USERS', ], }; diff --git a/src/reports/completed/loadTaskResultInfo.ts b/src/reports/completed/loadTaskResultInfo.ts new file mode 100644 index 0000000..966c410 --- /dev/null +++ b/src/reports/completed/loadTaskResultInfo.ts @@ -0,0 +1,185 @@ +import { getBitrixMethodUrl } from '../../core/config'; +import { buildFullName, fetchBalancer, loadTaskResultsById } from '../../core/bitrix/client'; +import { + collectFileIdsToResolve, + collectResultAuthorIds, + formatTaskResults, + readRequireResultValue, +} from './formatTaskResult'; + +export function loadTaskResultColumn(taskIds: Array): { + texts: Map; + requireResult: Map | null; +} { + const ids = uniqueIds(taskIds); + const resultsByTask = new Map(); + + ids.forEach(id => { + resultsByTask.set(id, loadResults(id)); + }); + + const allResults = [...resultsByTask.values()].flat(); + const authorNames = loadAuthorNames(collectResultAuthorIds(allResults)); + const fileNames = loadFileNames(collectFileIdsToResolve(allResults)); + const texts = new Map(); + + resultsByTask.forEach((results, id) => { + texts.set(id, formatTaskResults(results, authorNames, fileNames)); + }); + + return { + texts, + requireResult: loadRequireResult(ids), + }; +} + +function loadResults(taskId: string): any[] { + try { + const body: any = loadTaskResultsById(taskId); + if (Array.isArray(body)) return body; + if (Array.isArray(body?.result)) return body.result; + if (Array.isArray(body?.items)) return body.items; + return []; + } catch (error: any) { + Logger.log(`Задача ${taskId}: ${error?.message || error}`); + return []; + } +} + +function loadRequireResult(ids: string[]): Map | null { + if (ids.length === 0) return null; + + const response = fetchBalancer( + getBitrixMethodUrl('tasks', 'tasks.task.list'), + { + isRecurrent: true, + resultKey: 'tasks', + muteHttpExceptions: true, + body: { + filter: { ID: ids }, + select: ['ID'], + params: { WITH_RESULT_INFO: true }, + }, + } + ); + + const tasks = asTaskArray(response.data?.body); + if (response.code >= 400 || !tasks) return null; + + const values = new Map(); + let known = false; + + tasks.forEach(task => { + const parsed = readRequireResultValue(task); + if (!parsed.known) return; + known = true; + const id = String(task.id ?? task.ID ?? '').trim(); + if (id) values.set(id, parsed.value); + }); + + return known ? values : null; +} + +function loadAuthorNames(ids: string[]): Record { + const names: Record = {}; + + chunk(ids, 50).forEach(part => { + const response = fetchBalancer( + getBitrixMethodUrl('users', 'user.get'), + { + includePublicKey: true, + muteHttpExceptions: true, + payloadHeaders: { 'Content-Type': 'application/json' }, + body: { FILTER: { ID: part } }, + } + ); + + const users = response.data?.body?.result; + if (!Array.isArray(users)) return; + + users.forEach(user => { + const id = String(user.ID ?? user.id ?? '').trim(); + if (!id) return; + names[id] = buildFullName(user.LAST_NAME ?? user.lastName, user.NAME ?? user.name, user.SECOND_NAME ?? user.secondName); + }); + }); + + return names; +} + +function loadFileNames(ids: string[]): Record { + const names: Record = {}; + let diskDisabled = false; + + ids.forEach(id => { + if (diskDisabled) return; + + const loaded = lookupDiskName(id); + if (loaded.denied) { + diskDisabled = true; + Logger.log('Имена файлов результата недоступны: у вебхука задач нет прав на Диск'); + return; + } + + if (loaded.name) names[id] = loaded.name; + }); + + return names; +} + +function lookupDiskName(id: string): { name: string; denied: boolean } { + const byFile = requestDisk('disk.file.get', id); + if (byFile.denied || byFile.name) return byFile; + return requestDisk('disk.attachedObject.get', id); +} + +function requestDisk(method: string, id: string): { name: string; denied: boolean } { + const response = fetchBalancer( + getBitrixMethodUrl('tasks', method), + { + muteHttpExceptions: true, + body: { id: Number(id) }, + } + ); + + const body = response.data?.body ?? {}; + const error = String(body.error || response.data?.error || '').toUpperCase(); + if ( + response.code === 401 || + response.code === 403 || + error.includes('SCOPE') || + error.includes('ACCESS_DENIED') || + error.includes('INSUFFICIENT') + ) { + return { name: '', denied: true }; + } + + const file = body.result && typeof body.result === 'object' ? body.result : body; + return { + name: String(file.NAME ?? file.name ?? '').trim(), + denied: false, + }; +} + +function asTaskArray(body: any): any[] | null { + if (Array.isArray(body)) return body; + if (Array.isArray(body?.tasks)) return body.tasks; + if (Array.isArray(body?.result?.tasks)) return body.result.tasks; + return null; +} + +function uniqueIds(ids: Array): string[] { + return [...new Set( + (ids || []) + .map(id => String(id ?? '').trim()) + .filter(id => id !== '' && id !== '0') + )]; +} + +function chunk(items: T[], size: number): T[][] { + const chunks: T[][] = []; + for (let index = 0; index < items.length; index += size) { + chunks.push(items.slice(index, index + size)); + } + return chunks; +} diff --git a/src/reports/completed/main.ts b/src/reports/completed/main.ts index 3eb5ebc..94ef9c7 100644 --- a/src/reports/completed/main.ts +++ b/src/reports/completed/main.ts @@ -7,6 +7,7 @@ import { diffMinutes, formatDate, hoursToMinutes, parseDurationToHours, secondsT 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 родительской задачи', 'Название родительской задачи', 'Дата создания', 'Крайний срок задачи', @@ -14,6 +15,9 @@ const REPORT_HEADERS = [ 'Планируемая длительность', 'Ведет к потере клиента', 'Цена задачи', 'Дата завершения' ]; +const RESULT_COLUMN = 'Результат задачи'; +const REQUIRE_RESULT_COLUMN = 'Требовался ли результат'; + const TASK_FIELDS = { id: 'ID задачи', title: 'Наименование задачи', @@ -41,7 +45,8 @@ export function buildCompletedTasksReport(): void { const selfTasks = loadSelfTasks(selfSheet); const executors = buildStatistics(completedTasks, waitingControlTasks, selfTasks); addSalesDepHeadToExecutors(executors); - generateReport(executors); + const includeRequireResult = attachTaskResults(executors); + generateReport(executors, includeRequireResult); } catch (e: any) { SpreadsheetApp.getUi().alert(e.message); throw e; @@ -308,13 +313,38 @@ function addSalesDepHeadToExecutors(executors: Record): string | vo }); } -function generateReport(executors: Record): void { +function attachTaskResults(executors: Record): 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, 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, REPORT_HEADERS.length) - .setValues([REPORT_HEADERS]) + sheet.getRange(row, 1, 1, headers.length) + .setValues([headers]) .setBackground('#ffff00') .setFontWeight('bold'); row++; @@ -330,10 +360,10 @@ function generateReport(executors: Record): void { executor.reportTasks.push(...executor.waitingControl); sortObjects(executor.reportTasks); - const toWrite = createTaskArray(executor); + const toWrite = createTaskArray(executor, includeRequireResult); if (toWrite.length == 0) return; - sheet.getRange(row, 1, toWrite.length, REPORT_HEADERS.length) + sheet.getRange(row, 1, toWrite.length, headers.length) .setValues(toWrite) .setBorder(true, true, true, true, true, true); row += toWrite.length; @@ -370,26 +400,40 @@ function generateReport(executors: Record): void { 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): any[][] { - return executor.reportTasks.map((task: any) => [ - 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) : '' - ]); +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( diff --git a/tests/formatTaskResult.test.ts b/tests/formatTaskResult.test.ts new file mode 100644 index 0000000..ac28e40 --- /dev/null +++ b/tests/formatTaskResult.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { + collectFileIdsToResolve, + formatRequireResult, + formatTaskResults, + readRequireResultValue, +} from '../src/reports/completed/formatTaskResult'; + +describe('formatTaskResults', () => { + const authors = { '7': 'Иванов Иван' }; + + it('пишет текст результата с датой и автором', () => { + const text = formatTaskResults([ + { + createdBy: 7, + createdAt: '2026-06-18T09:05:00+03:00', + text: 'Договор согласован', + }, + ], authors); + + expect(text).toBe('18.06.2026 09.05, Иванов Иван: Договор согласован'); + }); + + it('для файла пишет, кто, когда и какой файл прикрепил', () => { + const text = formatTaskResults([ + { + createdBy: 7, + createdAt: '2026-06-18T09:05:00+03:00', + text: '[DISK FILE ID=n15]', + files: [15], + }, + ], authors, { '15': 'Акт.pdf' }); + + expect(text).toBe('18.06.2026 09.05, Иванов Иван: файл «Акт.pdf»'); + }); + + it('берёт имя файла из текста результата и из вёрстки', () => { + const text = formatTaskResults([ + { + authorId: 7, + createdAt: '2026-06-18T09:05:00+03:00', + text: 'Готово [DISK FILE ID=15]Смета.xlsx[/DISK FILE]', + formattedText: 'Фото.png', + }, + ], authors); + + expect(text).toBe('18.06.2026 09.05, Иванов Иван: Готово\nфайлы «Смета.xlsx», «Фото.png»'); + }); + + it('не дублирует имя файла, если оно осталось в тексте вёрстки', () => { + const text = formatTaskResults([ + { + createdBy: 7, + createdAt: '2026-06-18T09:05:00+03:00', + formattedText: 'Фото.png', + }, + ], authors); + + expect(text).toBe('18.06.2026 09.05, Иванов Иван: файл «Фото.png»'); + }); + + it('если имя файла не пришло, оставляет его идентификатор', () => { + const text = formatTaskResults([ + { + createdBy: 7, + createdAt: '2026-06-18T09:05:00+03:00', + files: [42], + }, + ], authors); + + expect(text).toBe('18.06.2026 09.05, Иванов Иван: файл #42'); + }); + + it('собирает идентификаторы файлов, для которых ещё нет имени', () => { + expect(collectFileIdsToResolve([ + { + files: [15, { id: 16, name: 'a.txt' }], + text: '[DISK FILE ID=17]b.docx[/DISK]', + }, + ])).toEqual(['15']); + }); +}); + +describe('require result', () => { + it('читает taskRequireResult из ответа списка задач', () => { + expect(readRequireResultValue({ taskRequireResult: 'Y' })).toEqual({ known: true, value: 'Да' }); + expect(readRequireResultValue({ requireResult: false })).toEqual({ known: true, value: 'Нет' }); + expect(readRequireResultValue({ taskRequireResult: null })).toEqual({ known: true, value: 'Нет' }); + expect(readRequireResultValue({ id: 1 })).toEqual({ known: false, value: '' }); + expect(formatRequireResult('N')).toBe('Нет'); + }); +});