initial commit
This commit is contained in:
commit
335f66ec60
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"scriptId": "PASTE_TARGET_SCRIPT_ID",
|
||||
"rootDir": ".",
|
||||
"scriptExtensions": [
|
||||
".js",
|
||||
".gs"
|
||||
],
|
||||
"htmlExtensions": [
|
||||
".html"
|
||||
],
|
||||
"jsonExtensions": [
|
||||
".json"
|
||||
],
|
||||
"filePushOrder": [],
|
||||
"skipSubdirectories": true
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
node_modules/
|
||||
dist/
|
||||
.clasp.json
|
||||
*.log
|
||||
.DS_Store
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
# Система отчётов Google Sheets
|
||||
|
||||
Исходник правды — git. Редактор Apps Script только для запуска: следующий `clasp push` затрёт ручные правки.
|
||||
|
||||
Сборка даёт IIFE (`const __gas = (...)()`). Меню и `onOpen` Apps Script находит только по объявлениям `function onOpen()` на верхнем уровне файла, поэтому после бандла `tools/build.mjs` дописывает такие обёртки.
|
||||
|
||||
## Команды
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm test
|
||||
npm run build -- universal
|
||||
npm run push -- universal
|
||||
npm run deploy -- universal
|
||||
```
|
||||
|
||||
`deploy` гоняет тесты, собирает бандл отдела и делает `clasp push` в его `scriptId`.
|
||||
|
||||
Перед первым push: `npx clasp login`.
|
||||
|
||||
## Структура
|
||||
|
||||
- `src/core` — общее ядро (конфиг, листы, почта, Bitrix, даты, коды задач)
|
||||
- `src/reports/<id>` — отчёт-плагин: меню, обработчики, свои ключи Config
|
||||
- `src/departments/<id>/profile.ts` — состав поставки отдела
|
||||
- `src/departments/<id>/entry.ts` — точка сборки
|
||||
- `tests` — Vitest, без SpreadsheetApp
|
||||
- `dist/<id>` — собранный проект для clasp (в git не кладётся)
|
||||
- `departments.json` — `scriptId` целевого Apps Script
|
||||
|
||||
Лист `Config` и Script Properties по-прежнему runtime-настройки конкретной таблицы. Профиль отдела задаёт **какой код** в неё попадает.
|
||||
|
||||
## Как добавить отдел
|
||||
|
||||
1. Скопируйте `src/departments/universal/` в `src/departments/<id>/`.
|
||||
2. В профиле оставьте только нужные плагины. Чтобы подменить логику отчёта, импортируйте свою реализацию с тем же `id` и теми же именами `handlers`.
|
||||
3. Добавьте `scriptId` в `departments.json`.
|
||||
4. `npm run deploy -- <id>`.
|
||||
|
||||
Уникальный отчёт кладите в `src/reports/<newId>/` и подключайте только в профилях, которым он нужен.
|
||||
|
||||
## Как добавить отчёт
|
||||
|
||||
1. Папка `src/reports/<id>/` с `index.ts`, где экспортируется `ReportPlugin`.
|
||||
2. В плагине: `menuTitle`, `menuItems`, `handlers`, при необходимости `requiredConfigKeys` / `requiredScriptProperties`.
|
||||
3. Чистую логику (строки → строки отчёта) выносите в отдельный файл и покрывайте тестом, как `src/reports/bigSmall/builder.ts`.
|
||||
4. Подключите плагин в профиле отдела.
|
||||
|
||||
Имена глобальных функций из меню текущего эталона (`universal`) не меняйте — на них могут висеть привычка и триггеры.
|
||||
|
||||
## Выкат в таблицу
|
||||
|
||||
Сборка кладёт в `dist/<id>/` файлы `Code.js`, `appsscript.json`, HTML и `.clasp.json`. Push идёт только из этой папки, а не из корня репозитория.
|
||||
|
||||
Секреты (HMAC, webhook Bitrix) задаются в Script Properties целевого проекта. Что писать на лист `Config` — в [config/README.md](config/README.md).
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"timeZone": "Europe/Moscow",
|
||||
"dependencies": {
|
||||
},
|
||||
"exceptionLogging": "STACKDRIVER",
|
||||
"runtimeVersion": "V8"
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
# Конфигурация филиала
|
||||
|
||||
Код собирается по профилю отдела (`src/departments/<id>`). Набор отчётов и их реализации задаёт профиль. Различия **данных** между таблицами — лист `Config` и Script Properties.
|
||||
|
||||
## Развёртывание
|
||||
|
||||
Из корня репозитория:
|
||||
|
||||
```bash
|
||||
npm test
|
||||
npm run deploy -- universal
|
||||
```
|
||||
|
||||
Это тесты, сборка `dist/universal` и `clasp push` в `scriptId` из `departments.json`. Редактор Apps Script не используйте как место правок исходников.
|
||||
|
||||
Для новой таблицы:
|
||||
|
||||
1. Создайте профиль отдела и запись в `departments.json`.
|
||||
2. Создайте в таблице лист `Config` по образцу `config/config.sheet.example.md`.
|
||||
3. Project Settings → Script properties — секреты из списка ниже.
|
||||
4. `npm run deploy -- <id>`.
|
||||
|
||||
Обязательные ключи Config зависят от включённых в профиль отчётов. Если ключ нужен включённому отчёту и не заполнен, запуск останавливается с явной ошибкой.
|
||||
|
||||
## Лист Config
|
||||
|
||||
Имя листа строго `Config`. Первая строка может быть заголовком `key | value`. Дальше пары ключ–значение.
|
||||
|
||||
| Ключ | Смысл |
|
||||
|------|--------|
|
||||
| SOURCE_SHEET_ID | gid листа выгрузки задач |
|
||||
| EMAILS_SHEET_ID | gid листа email сотрудников |
|
||||
| ROLES_SHEET_ID | gid листа ролей (ячейки B1–B6: РОП, зам. РОПа, рукфил, зам. рукфила, директор, контролёр) |
|
||||
| BACKUP_EMAILS_SPREADSHEET_ID | таблица с запасными email (листы РП и АП) |
|
||||
| MANAGER_TABLES_CONFIG_ID | JSON на Drive: исполнитель → персональная таблица |
|
||||
| ORG_STRUCTURE_FILE_ID | JSON оргструктуры на Drive |
|
||||
| DEPARTMENT_ID | ID отдела в оргструктуре |
|
||||
| TEMPLATE_SCAN_DEPARTMENT_ID | отдел для сканера шаблонов |
|
||||
| BITRIX_PORTAL | `https://example.bitrix24.ru` без слэша на конце |
|
||||
| BALANCER_URL | URL балансировщика Bitrix REST |
|
||||
| TEMPLATE_SCANNER_URL | URL сервиса latest template id |
|
||||
| DEFAULT_FILIAL_HEAD_NAME | ФИО рукфила по умолчанию |
|
||||
|
||||
Необязательные:
|
||||
|
||||
| Ключ | По умолчанию |
|
||||
|------|----------------|
|
||||
| METRICS_SHEET_NAME | Data |
|
||||
| TASK_INDEX_SHEET_NAME | taskIndex |
|
||||
|
||||
## Script Properties (не хранить в git)
|
||||
|
||||
| Ключ | Смысл |
|
||||
|------|--------|
|
||||
| BALANCER_PUBLIC | публичный ключ HMAC балансировщика |
|
||||
| BALANCER_SECRET | секрет HMAC |
|
||||
| BITRIX_WEBHOOK_TASKS | базовый webhook URL для `tasks.task.*` (со слэшем на конце) |
|
||||
| BITRIX_WEBHOOK_USERS | webhook для `user.get` |
|
||||
| BITRIX_WEBHOOK_TEMPLATES | webhook для `tasks.template.get` |
|
||||
|
||||
Константы самих отчётов (префиксы листов, словари кодов, индекс вставки листа) лежат в `src/core/constants.ts`.
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
# Пример листа Config
|
||||
|
||||
Создайте лист с именем `Config`.
|
||||
|
||||
| key | value |
|
||||
|-----|--------|
|
||||
| SOURCE_SHEET_ID | 0 |
|
||||
| EMAILS_SHEET_ID | 1859185202 |
|
||||
| ROLES_SHEET_ID | 1881045695 |
|
||||
| BACKUP_EMAILS_SPREADSHEET_ID | id_таблицы_запасных_email |
|
||||
| MANAGER_TABLES_CONFIG_ID | id_json_персональных_таблиц |
|
||||
| ORG_STRUCTURE_FILE_ID | id_json_оргструктуры |
|
||||
| DEPARTMENT_ID | 98 |
|
||||
| TEMPLATE_SCAN_DEPARTMENT_ID | 29 |
|
||||
| BITRIX_PORTAL | https://thebest.bitrix24.ru |
|
||||
| BALANCER_URL | https://HOST/balancer/api/balancer/send |
|
||||
| TEMPLATE_SCANNER_URL | https://HOST/bitrix-template-scaner/latest/ |
|
||||
| DEFAULT_FILIAL_HEAD_NAME | Фамилия Имя |
|
||||
| METRICS_SHEET_NAME | Data |
|
||||
| TASK_INDEX_SHEET_NAME | taskIndex |
|
||||
|
||||
Числа в колонке value можно оставлять числом (gid листа) или строкой. HMAC и webhook в этот лист не пишите — только Script Properties.
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"universal": {
|
||||
"scriptId": "1AqL4PgNLkch4pp-Bq6WaL1pBmu3K4mL_sIxojO5AUraoeKI9RP4lBByX",
|
||||
"htmlFiles": ["DateRangeDialog.html"]
|
||||
},
|
||||
"salesOriginal": {
|
||||
"scriptId": "1Fy_9bPmflJF1UO3lBG8Gmxwo3yOMdsyh0CzwYxAFRlaSuLYSA1gVogbc",
|
||||
"htmlFiles": ["DateRangeDialog.html"]
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"name": "task-control-gscript",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"build": "node tools/build.mjs",
|
||||
"push": "node tools/push.mjs",
|
||||
"deploy": "node tools/deploy.mjs",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@google/clasp": "^3.4.1",
|
||||
"@types/google-apps-script": "^2.0.13",
|
||||
"@types/node": "^22.20.3",
|
||||
"esbuild": "^0.28.2",
|
||||
"typescript": "^7.0.2",
|
||||
"vitest": "^5.0.1"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,165 @@
|
|||
import { getAppConfig, getBitrixMethodUrl } from '../config';
|
||||
import { generateSignature } from './hmac';
|
||||
import { normalizeSpaces } from '../taskCodes';
|
||||
|
||||
interface FetchBalancerOptions {
|
||||
method?: string;
|
||||
isRecurrent?: boolean;
|
||||
resultKey?: string;
|
||||
payloadHeaders?: Record<string, string>;
|
||||
body?: any;
|
||||
includePublicKey?: boolean;
|
||||
muteHttpExceptions?: boolean;
|
||||
}
|
||||
|
||||
export function fetchBalancer(bitrixUrl: string, options?: FetchBalancerOptions) {
|
||||
const opts = options || {};
|
||||
const cfg = getAppConfig();
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
||||
|
||||
const payload: Record<string, any> = {
|
||||
url: bitrixUrl,
|
||||
method: opts.method || 'POST',
|
||||
};
|
||||
|
||||
if (opts.isRecurrent) {
|
||||
payload.is_recurrent = true;
|
||||
}
|
||||
|
||||
if (opts.resultKey) {
|
||||
payload.result_key = opts.resultKey;
|
||||
}
|
||||
|
||||
if (opts.payloadHeaders) {
|
||||
payload.headers = opts.payloadHeaders;
|
||||
}
|
||||
|
||||
if (opts.body !== undefined) {
|
||||
payload.body = opts.body;
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'X-Timestamp': timestamp,
|
||||
'X-Signature': generateSignature(timestamp),
|
||||
};
|
||||
|
||||
if (opts.includePublicKey) {
|
||||
headers['X-Public-Key'] = cfg.balancerPublic;
|
||||
}
|
||||
|
||||
const response = UrlFetchApp.fetch(cfg.balancerUrl, {
|
||||
method: 'post',
|
||||
contentType: 'application/json',
|
||||
headers: headers,
|
||||
payload: JSON.stringify(payload),
|
||||
muteHttpExceptions: opts.muteHttpExceptions === true,
|
||||
});
|
||||
|
||||
const text = response.getContentText();
|
||||
let data: any = {};
|
||||
|
||||
try {
|
||||
data = text ? JSON.parse(text) : {};
|
||||
} catch (_e) {
|
||||
data = { raw: text };
|
||||
}
|
||||
|
||||
return {
|
||||
code: response.getResponseCode(),
|
||||
data: data,
|
||||
};
|
||||
}
|
||||
|
||||
export function loadDepartmentUsers(departmentId: number | string): Record<number, boolean> {
|
||||
const result = fetchBalancer(
|
||||
getBitrixMethodUrl('users', 'user.get'),
|
||||
{
|
||||
includePublicKey: true,
|
||||
payloadHeaders: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: {
|
||||
FILTER: {
|
||||
UF_DEPARTMENT: departmentId,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const users: Record<number, boolean> = {};
|
||||
const list = (((result.data || {}).body || {}).result) || [];
|
||||
|
||||
list.forEach((user: any) => {
|
||||
users[Number(user.ID)] = true;
|
||||
});
|
||||
|
||||
Logger.log(
|
||||
`Department ${departmentId}: ${Object.keys(users).length} users`
|
||||
);
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
export function loadAllDepartmentUsers(departmentIds: Array<number | string>) {
|
||||
const result: Record<string, Record<number, boolean>> = {};
|
||||
|
||||
departmentIds.forEach(departmentId => {
|
||||
result[String(departmentId)] = loadDepartmentUsers(departmentId);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function findDepartmentForUser(
|
||||
userId: number | string,
|
||||
departmentUsersMap: Record<string, Record<number, boolean>>
|
||||
): string | null {
|
||||
for (const departmentId in departmentUsersMap) {
|
||||
if (departmentUsersMap[departmentId][Number(userId)]) {
|
||||
return departmentId;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function buildFullName(last: string, first: string, second: string): string {
|
||||
return normalizeSpaces([last, first, second]
|
||||
.filter(part => part !== null && part !== undefined && part !== '')
|
||||
.join(' '));
|
||||
}
|
||||
|
||||
export function loadTasksByIds(ids: Array<string | number>): any[] {
|
||||
if (!ids || ids.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const result = fetchBalancer(
|
||||
getBitrixMethodUrl('tasks', 'tasks.task.list'),
|
||||
{
|
||||
isRecurrent: true,
|
||||
resultKey: 'tasks',
|
||||
body: {
|
||||
filter: {
|
||||
ID: ids,
|
||||
},
|
||||
select: [
|
||||
'ID',
|
||||
'TITLE',
|
||||
'CREATED_DATE',
|
||||
'DEADLINE',
|
||||
'CREATED_BY',
|
||||
'RESPONSIBLE_ID',
|
||||
'STATUS',
|
||||
'TIME_ESTIMATE',
|
||||
'TASK_CONTROL',
|
||||
'START_DATE_PLAN',
|
||||
'END_DATE_PLAN',
|
||||
'UF_AUTO_738863346313',
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return (result.data && result.data.body) || [];
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { getAppConfig } from '../config';
|
||||
|
||||
export function generateSignature(timestampStr: string): string {
|
||||
const payload = `${getAppConfig().balancerPublic}:${timestampStr}`;
|
||||
|
||||
const raw = Utilities.computeHmacSha256Signature(
|
||||
payload,
|
||||
getAppConfig().balancerSecret
|
||||
);
|
||||
|
||||
return raw.map(b => {
|
||||
const v = (b < 0 ? b + 256 : b).toString(16);
|
||||
return v.length === 1 ? '0' + v : v;
|
||||
}).join('');
|
||||
}
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
import { CONFIG_SHEET_NAME, OPTIONAL_CONFIG_DEFAULTS } from './constants';
|
||||
|
||||
export interface AppConfig {
|
||||
sourceSheetId: number;
|
||||
emailsSheetId: number;
|
||||
rolesSheetId: number;
|
||||
backupEmailsSpreadsheetId: string;
|
||||
executorTablesConfigId: string;
|
||||
orgStructureFileId: string;
|
||||
departmentId: string;
|
||||
templateScanDepartmentId: number;
|
||||
bitrixPortal: string;
|
||||
balancerUrl: string;
|
||||
templateScannerUrl: string;
|
||||
defaultFilialHeadName: string;
|
||||
metricsSheetName: string;
|
||||
taskIndexSheetName: string;
|
||||
balancerPublic: string;
|
||||
balancerSecret: string;
|
||||
webhooks: {
|
||||
tasks: string;
|
||||
users: string;
|
||||
templates: string;
|
||||
};
|
||||
}
|
||||
|
||||
let requiredSheetKeys: string[] = [];
|
||||
let requiredScriptProperties: string[] = [];
|
||||
let appConfigCache: AppConfig | undefined;
|
||||
|
||||
export function setConfigRequirements(sheetKeys: string[], scriptKeys: string[]): void {
|
||||
requiredSheetKeys = unique(sheetKeys);
|
||||
requiredScriptProperties = unique(scriptKeys);
|
||||
appConfigCache = undefined;
|
||||
}
|
||||
|
||||
function unique(values: string[]): string[] {
|
||||
return Array.from(new Set(values.filter(Boolean)));
|
||||
}
|
||||
|
||||
export function getAppConfig(): AppConfig {
|
||||
if (appConfigCache) {
|
||||
return appConfigCache;
|
||||
}
|
||||
|
||||
const sheetMap = loadConfigSheetMap();
|
||||
const missingSheetKeys = requiredSheetKeys.filter(key => {
|
||||
const value = sheetMap[key];
|
||||
return value === undefined || value === null || String(value).trim() === '';
|
||||
});
|
||||
|
||||
if (missingSheetKeys.length) {
|
||||
throw new Error(
|
||||
'На листе Config не заполнены ключи: ' + missingSheetKeys.join(', ')
|
||||
);
|
||||
}
|
||||
|
||||
const props = PropertiesService.getScriptProperties();
|
||||
const missingProps = requiredScriptProperties.filter(key => {
|
||||
const value = props.getProperty(key);
|
||||
return !value || !String(value).trim();
|
||||
});
|
||||
|
||||
if (missingProps.length) {
|
||||
throw new Error(
|
||||
'В Script Properties не заданы: ' + missingProps.join(', ')
|
||||
);
|
||||
}
|
||||
|
||||
appConfigCache = {
|
||||
sourceSheetId: Number(sheetMap.SOURCE_SHEET_ID),
|
||||
emailsSheetId: Number(sheetMap.EMAILS_SHEET_ID),
|
||||
rolesSheetId: Number(sheetMap.ROLES_SHEET_ID),
|
||||
backupEmailsSpreadsheetId: String(sheetMap.BACKUP_EMAILS_SPREADSHEET_ID || '').trim(),
|
||||
executorTablesConfigId: String(sheetMap.MANAGER_TABLES_CONFIG_ID || '').trim(),
|
||||
orgStructureFileId: String(sheetMap.ORG_STRUCTURE_FILE_ID || '').trim(),
|
||||
departmentId: String(sheetMap.DEPARTMENT_ID || '').trim(),
|
||||
templateScanDepartmentId: Number(sheetMap.TEMPLATE_SCAN_DEPARTMENT_ID),
|
||||
bitrixPortal: String(sheetMap.BITRIX_PORTAL || '').trim().replace(/\/$/, ''),
|
||||
balancerUrl: String(sheetMap.BALANCER_URL || '').trim(),
|
||||
templateScannerUrl: String(sheetMap.TEMPLATE_SCANNER_URL || '').trim(),
|
||||
defaultFilialHeadName: String(sheetMap.DEFAULT_FILIAL_HEAD_NAME || '').trim(),
|
||||
metricsSheetName: String(
|
||||
sheetMap.METRICS_SHEET_NAME || OPTIONAL_CONFIG_DEFAULTS.METRICS_SHEET_NAME
|
||||
).trim(),
|
||||
taskIndexSheetName: String(
|
||||
sheetMap.TASK_INDEX_SHEET_NAME || OPTIONAL_CONFIG_DEFAULTS.TASK_INDEX_SHEET_NAME
|
||||
).trim(),
|
||||
balancerPublic: String(props.getProperty('BALANCER_PUBLIC') || '').trim(),
|
||||
balancerSecret: String(props.getProperty('BALANCER_SECRET') || '').trim(),
|
||||
webhooks: {
|
||||
tasks: normalizeWebhookBase(props.getProperty('BITRIX_WEBHOOK_TASKS')),
|
||||
users: normalizeWebhookBase(props.getProperty('BITRIX_WEBHOOK_USERS')),
|
||||
templates: normalizeWebhookBase(props.getProperty('BITRIX_WEBHOOK_TEMPLATES')),
|
||||
},
|
||||
};
|
||||
|
||||
return appConfigCache;
|
||||
}
|
||||
|
||||
export function getSourceSheet(spreadsheet?: GoogleAppsScript.Spreadsheet.Spreadsheet) {
|
||||
const ss = spreadsheet || SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheet = ss.getSheetById(getAppConfig().sourceSheetId);
|
||||
|
||||
if (!sheet) {
|
||||
throw new Error('Не найден лист выгрузки (SOURCE_SHEET_ID)');
|
||||
}
|
||||
|
||||
return sheet;
|
||||
}
|
||||
|
||||
export function getBitrixMethodUrl(webhookKey: 'tasks' | 'users' | 'templates', method: string) {
|
||||
return getAppConfig().webhooks[webhookKey] + method;
|
||||
}
|
||||
|
||||
export function getBitrixTaskViewUrl(taskId: string | number) {
|
||||
return getAppConfig().bitrixPortal +
|
||||
'/company/personal/user/1/tasks/task/view/' +
|
||||
taskId + '/';
|
||||
}
|
||||
|
||||
function loadConfigSheetMap_(): Record<string, any> {
|
||||
const sheet = SpreadsheetApp
|
||||
.getActiveSpreadsheet()
|
||||
.getSheetByName(CONFIG_SHEET_NAME);
|
||||
|
||||
if (!sheet) {
|
||||
throw new Error(
|
||||
'Не найден лист Config. Добавьте лист с колонками key / value (см. config/README.md).'
|
||||
);
|
||||
}
|
||||
|
||||
const values = sheet.getDataRange().getValues();
|
||||
const map: Record<string, any> = {};
|
||||
let start = 0;
|
||||
|
||||
if (values.length && String(values[0][0]).trim().toLowerCase() === 'key') {
|
||||
start = 1;
|
||||
}
|
||||
|
||||
for (let i = start; i < values.length; i++) {
|
||||
const key = String(values[i][0] || '').trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
map[key] = values[i][1];
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
const loadConfigSheetMap = loadConfigSheetMap_;
|
||||
|
||||
function normalizeWebhookBase(value: string | null): string {
|
||||
const trimmed = String(value || '').trim();
|
||||
if (!trimmed) {
|
||||
return '';
|
||||
}
|
||||
return trimmed.endsWith('/') ? trimmed : trimmed + '/';
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
export const REPORT_SHEET_INSERT_INDEX = 4;
|
||||
|
||||
export const CONFIG_SHEET_NAME = 'Config';
|
||||
|
||||
export const REPORT_NOTES_SHEET_NAME = 'Дополнения к отчетам';
|
||||
|
||||
export const REPORT_NAME_TIMESTAMP_SUFFIX_LENGTH = 17;
|
||||
|
||||
export const REPORT_PREFIXES = {
|
||||
bigSmall: 'Отчет по большим и малым задачам',
|
||||
singleTime: 'Отчет по разовым задачам',
|
||||
waitingControl: 'Отчет по задачам, ожидающим контроля',
|
||||
overdue: 'Отчет по просроченным задачам',
|
||||
selfTasks: 'Отчет по задачам самому себе',
|
||||
completed: 'Отчет по завершенным задачам',
|
||||
workload: 'Отчет по рабочей нагрузке',
|
||||
effectiveness: 'Лист эффективности',
|
||||
newTemplates: 'Отчет по новым шаблонам',
|
||||
planOverdue: 'Отчет по задачам, не завершенным по плану',
|
||||
};
|
||||
|
||||
export const EXECUTOR_SHEET_NAMES = {
|
||||
bigSmallQuestions: 'Вопросы по большим и малым задачам',
|
||||
overdueQuestions: 'Вопросы по просроченным задачам',
|
||||
actualTasks: 'Актуальные задачи',
|
||||
};
|
||||
|
||||
export const BACKUP_EMAIL_SHEET_NAMES = ['РП', 'АП'];
|
||||
|
||||
export const TASK_STATUS_NAMES: Record<string, string> = {
|
||||
'2': 'Ждёт выполнения',
|
||||
'3': 'Выполняется',
|
||||
'4': 'Ждёт контроля',
|
||||
'5': 'Завершена',
|
||||
'6': 'Отложена',
|
||||
};
|
||||
|
||||
export const WAITING_CONTROL_STATUS = TASK_STATUS_NAMES['4'];
|
||||
|
||||
export const TASK_CODE_DICTIONARY: Record<string, string> = {
|
||||
'Р': 'Разовая',
|
||||
'Е': 'Периодическая',
|
||||
'П': 'Постановщик',
|
||||
'О': 'Контролёр',
|
||||
'В': 'Владимир',
|
||||
'З': 'Без контроля',
|
||||
'Б': 'Большая',
|
||||
'М': 'Маленькая',
|
||||
};
|
||||
|
||||
export const DROPDOWN_VALUES = {
|
||||
templateDecision: ['Согласовано', 'Нет согласовано', 'Есть правки'],
|
||||
};
|
||||
|
||||
export const TEMPLATE_SCAN = {
|
||||
STEP: 2,
|
||||
SAFETY_RANGE: 100,
|
||||
MAX_IDS: 1000,
|
||||
SLEEP_MS: 300,
|
||||
};
|
||||
|
||||
export const EMAIL_ROLE_CELLS: Record<string, string> = {
|
||||
salesDepartmentHeadEmail: 'B1',
|
||||
salesDepartmentDeputyEmail: 'B2',
|
||||
filialHeadEmail: 'B3',
|
||||
filialDeputyEmail: 'B4',
|
||||
directorEmail: 'B5',
|
||||
controllerEmail: 'B6',
|
||||
};
|
||||
|
||||
export const OPTIONAL_CONFIG_DEFAULTS: Record<string, string> = {
|
||||
METRICS_SHEET_NAME: 'Data',
|
||||
TASK_INDEX_SHEET_NAME: 'taskIndex',
|
||||
};
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
const DEFAULT_TIME_ZONE = 'Europe/Moscow';
|
||||
|
||||
export function getScriptTimeZone(): string {
|
||||
try {
|
||||
if (typeof Session !== 'undefined' && Session.getScriptTimeZone) {
|
||||
return Session.getScriptTimeZone();
|
||||
}
|
||||
} catch (_error) {
|
||||
// Node tests and environments without GAS globals
|
||||
}
|
||||
|
||||
return DEFAULT_TIME_ZONE;
|
||||
}
|
||||
|
||||
export function formatDateWithTime(date: Date, timeZone = getScriptTimeZone()): string {
|
||||
if (!(date instanceof Date) || isNaN(date.getTime())) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return formatInTimeZone(date, timeZone, {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).replace(',', '').replace(/:/g, '.');
|
||||
}
|
||||
|
||||
export function formatDate(date: Date, timeZone = getScriptTimeZone()): string {
|
||||
if (!(date instanceof Date) || isNaN(date.getTime())) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return formatInTimeZone(date, timeZone, {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
export function formatIsoLocal(date: Date, timeZone = getScriptTimeZone()): string {
|
||||
const datePart = formatInTimeZone(date, timeZone, {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
});
|
||||
const timePart = formatInTimeZone(date, timeZone, {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
}).replace(',', '').trim();
|
||||
|
||||
const [day, month, year] = datePart.split('.');
|
||||
return `${year}-${month}-${day}T${timePart}`;
|
||||
}
|
||||
|
||||
export function isSameDay(date1: Date, date2: Date): boolean {
|
||||
if (!(date1 instanceof Date) || isNaN(date1.getTime())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(date2 instanceof Date) || isNaN(date2.getTime())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
date1.getFullYear() === date2.getFullYear() &&
|
||||
date1.getMonth() === date2.getMonth() &&
|
||||
date1.getDate() === date2.getDate()
|
||||
);
|
||||
}
|
||||
|
||||
export function hoursToMinutes(hours: number): number {
|
||||
return Math.round(Number(hours) * 60);
|
||||
}
|
||||
|
||||
export function diffMinutes(date1: Date, date2: Date): number | '' {
|
||||
if (
|
||||
!(date1 instanceof Date) ||
|
||||
isNaN(date1.getTime()) ||
|
||||
!(date2 instanceof Date) ||
|
||||
isNaN(date2.getTime())
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return Math.floor((date2.getTime() - date1.getTime()) / 60000);
|
||||
}
|
||||
|
||||
export function parseDurationToHours(value: any): number {
|
||||
if (!value) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (Object.prototype.toString.call(value) === '[object Date]') {
|
||||
const hours = value.getHours();
|
||||
const minutes = value.getMinutes();
|
||||
return hours + (minutes / 60);
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const parts = value.split(':');
|
||||
const hours = Number(parts[0]) || 0;
|
||||
const minutes = Number(parts[1]) || 0;
|
||||
return hours + (minutes / 60);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return value * 24;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function secondsToHours(seconds: number): number {
|
||||
return Number(seconds) / 3600;
|
||||
}
|
||||
|
||||
export function msToDuration(ms: any): string {
|
||||
if (!ms || ms == null || isNaN(Number(ms))) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const totalMinutes = Math.round(Number(ms) / 60000);
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
const result: string[] = [];
|
||||
|
||||
if (hours > 0) {
|
||||
result.push(hours + ' ч.');
|
||||
}
|
||||
if (minutes > 0) {
|
||||
result.push(minutes + ' м.');
|
||||
}
|
||||
|
||||
return result.length ? result.join(' ') : '0 м.';
|
||||
}
|
||||
|
||||
export function dateDiffToMs(startDate: any, endDate: any): number | '' {
|
||||
if (!startDate || !endDate) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const start = new Date(startDate);
|
||||
const end = new Date(endDate);
|
||||
|
||||
if (isNaN(start.getTime()) || isNaN(end.getTime())) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return Math.abs(end.getTime() - start.getTime());
|
||||
}
|
||||
|
||||
export function dateDiffToDuration(startDate: any, endDate: any): string {
|
||||
const ms = dateDiffToMs(startDate, endDate);
|
||||
return ms === '' ? '' : msToDuration(ms);
|
||||
}
|
||||
|
||||
export function getNextWorkday(date: Date): Date {
|
||||
const result = new Date(date);
|
||||
result.setDate(result.getDate() + 1);
|
||||
|
||||
const day = result.getDay();
|
||||
if (day === 6) {
|
||||
result.setDate(result.getDate() + 2);
|
||||
} else if (day === 0) {
|
||||
result.setDate(result.getDate() + 1);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function formatInTimeZone(
|
||||
date: Date,
|
||||
timeZone: string,
|
||||
options: Intl.DateTimeFormatOptions
|
||||
): string {
|
||||
const formatter = new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone,
|
||||
...options,
|
||||
});
|
||||
|
||||
const parts = formatter.formatToParts(date);
|
||||
const get = (type: string) => parts.find(part => part.type === type)?.value || '';
|
||||
|
||||
if (options.year && options.hour) {
|
||||
return `${get('day')}.${get('month')}.${get('year')} ${get('hour')}.${get('minute')}`;
|
||||
}
|
||||
|
||||
if (options.year) {
|
||||
return `${get('day')}.${get('month')}.${get('year')}`;
|
||||
}
|
||||
|
||||
if (options.hour && options.second) {
|
||||
return `${get('hour')}:${get('minute')}:${get('second')}`;
|
||||
}
|
||||
|
||||
return formatter.format(date);
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
import { BACKUP_EMAIL_SHEET_NAMES, EMAIL_ROLE_CELLS } from '../constants';
|
||||
import { getAppConfig } from '../config';
|
||||
|
||||
export function getEmailConfig(spreadsheet?: GoogleAppsScript.Spreadsheet.Spreadsheet) {
|
||||
const ss = spreadsheet || SpreadsheetApp.getActiveSpreadsheet();
|
||||
const rolesSheet = ss.getSheetById(getAppConfig().rolesSheetId);
|
||||
|
||||
if (!rolesSheet) {
|
||||
throw new Error('Не найден лист ролей (ROLES_SHEET_ID)');
|
||||
}
|
||||
|
||||
const result: Record<string, string> = {};
|
||||
|
||||
Object.entries(EMAIL_ROLE_CELLS).forEach(([key, cell]) => {
|
||||
result[key] = String(rolesSheet.getRange(cell).getValue() || '').trim();
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function getUserEmailMap(): Record<string, string> {
|
||||
const mainSheet = SpreadsheetApp
|
||||
.getActiveSpreadsheet()
|
||||
.getSheetById(getAppConfig().emailsSheetId);
|
||||
|
||||
if (!mainSheet) {
|
||||
throw new Error('Не найден лист email сотрудников (EMAILS_SHEET_ID)');
|
||||
}
|
||||
|
||||
const mainData = mainSheet.getDataRange().getValues();
|
||||
const emailMap: Record<string, string> = {};
|
||||
const nameVariants: Record<string, string> = {};
|
||||
|
||||
for (let i = 1; i < mainData.length; i++) {
|
||||
const fullName = String(mainData[i][1] || '').trim();
|
||||
const email = String(mainData[i][2] || '').trim();
|
||||
|
||||
if (!fullName || !email) {
|
||||
continue;
|
||||
}
|
||||
|
||||
emailMap[fullName] = email;
|
||||
const normalized = normalizeName(fullName);
|
||||
|
||||
if (normalized) {
|
||||
nameVariants[normalized] = fullName;
|
||||
}
|
||||
}
|
||||
|
||||
const backupSpreadsheet = SpreadsheetApp.openById(
|
||||
getAppConfig().backupEmailsSpreadsheetId
|
||||
);
|
||||
|
||||
for (const sheetName of BACKUP_EMAIL_SHEET_NAMES) {
|
||||
const sheet = backupSpreadsheet.getSheetByName(sheetName);
|
||||
|
||||
if (!sheet) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = sheet.getDataRange().getValues();
|
||||
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const rawName = String(data[i][1] || '').trim();
|
||||
const email = String(data[i][3] || '').trim();
|
||||
|
||||
if (!rawName || !email) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalized = normalizeName(rawName);
|
||||
if (!normalized) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const canonicalName = nameVariants[normalized]
|
||||
? nameVariants[normalized]
|
||||
: reverseName(rawName);
|
||||
|
||||
if (!emailMap[canonicalName]) {
|
||||
emailMap[canonicalName] = email;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return emailMap;
|
||||
}
|
||||
|
||||
export function normalizeName(fullName: string): string {
|
||||
return String(fullName || '')
|
||||
.trim()
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase()
|
||||
.split(' ')
|
||||
.filter(Boolean)
|
||||
.sort()
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export function reverseName(fullName: string): string {
|
||||
const parts = String(fullName || '')
|
||||
.trim()
|
||||
.replace(/\s+/g, ' ')
|
||||
.split(' ')
|
||||
.filter(Boolean);
|
||||
|
||||
if (parts.length < 2) {
|
||||
return fullName;
|
||||
}
|
||||
|
||||
return parts.slice(1).concat(parts[0]).join(' ');
|
||||
}
|
||||
|
||||
export function compareNames(name1: string, name2: string): boolean {
|
||||
return normalizeName(name1) === normalizeName(name2);
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import { getAppConfig } from '../config';
|
||||
|
||||
export function loadConfig(): Record<string, string> {
|
||||
const file = DriveApp.getFileById(getAppConfig().executorTablesConfigId);
|
||||
const content = file.getBlob().getDataAsString();
|
||||
|
||||
if (!content.trim()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
export function saveConfig(config: Record<string, string>): void {
|
||||
const file = DriveApp.getFileById(getAppConfig().executorTablesConfigId);
|
||||
file.setContent(JSON.stringify(config, null, 2));
|
||||
}
|
||||
|
||||
export function clearSheetsForMissingPeople(names: string[], sheetName: string): void {
|
||||
const config = loadConfig();
|
||||
const namesSet = new Set(names);
|
||||
|
||||
Object.entries(config).forEach(([personName, spreadsheetId]) => {
|
||||
if (namesSet.has(personName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
|
||||
const sheet = spreadsheet.getSheetByName(sheetName);
|
||||
if (!sheet) {
|
||||
Logger.log(`Лист "${sheetName}" не найден для ${personName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
sheet.clearContents();
|
||||
} catch (error: any) {
|
||||
Logger.log(`Ошибка при обработке ${personName}: ${error.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
import { askUser } from '../ui';
|
||||
import { getEmailConfig } from './emailConfig';
|
||||
import { exportSheetToPdf } from '../sheets/export';
|
||||
|
||||
export function notifyReportRecievers(reportName: string, additionalText?: string) {
|
||||
return notifyLeadership({
|
||||
reportName: reportName,
|
||||
recipients: 'filialHead',
|
||||
includeDirector: true,
|
||||
additionalText: additionalText || '',
|
||||
});
|
||||
}
|
||||
|
||||
export function notifyReportRecieversSalesDepHead(reportName: string, additionalText?: string) {
|
||||
return notifyLeadership({
|
||||
reportName: reportName,
|
||||
recipients: 'salesHead',
|
||||
includeDirector: false,
|
||||
additionalText: additionalText || '',
|
||||
});
|
||||
}
|
||||
|
||||
export function notifyLeadership(options: {
|
||||
reportName: string;
|
||||
recipients: 'salesHead' | 'filialHead';
|
||||
includeDirector?: boolean;
|
||||
additionalText?: string;
|
||||
onConfirm?: (sheet: GoogleAppsScript.Spreadsheet.Sheet) => void;
|
||||
}): boolean {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheet = spreadsheet.getActiveSheet();
|
||||
const emailConfig = getEmailConfig(spreadsheet);
|
||||
|
||||
let mainEmail = '';
|
||||
let missingMessage = '';
|
||||
|
||||
if (options.recipients === 'salesHead') {
|
||||
mainEmail = emailConfig.salesDepartmentHeadEmail || emailConfig.salesDepartmentDeputyEmail;
|
||||
missingMessage = 'Не заполнены email РОПа или его заместителя';
|
||||
} else {
|
||||
mainEmail = emailConfig.filialHeadEmail || emailConfig.filialDeputyEmail;
|
||||
missingMessage = 'Не заполнены email рук. фила или его заместителя';
|
||||
}
|
||||
|
||||
if (!mainEmail) {
|
||||
SpreadsheetApp.getUi().alert(missingMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof options.onConfirm === 'function') {
|
||||
options.onConfirm(sheet);
|
||||
}
|
||||
|
||||
const pdfBlob = exportSheetToPdf(
|
||||
spreadsheet.getId(),
|
||||
sheet.getSheetId(),
|
||||
sheet.getName()
|
||||
);
|
||||
|
||||
const spreadsheetUrl = spreadsheet.getUrl() + '#gid=' + sheet.getSheetId();
|
||||
const recipients = [mainEmail];
|
||||
|
||||
if (options.includeDirector && emailConfig.directorEmail) {
|
||||
recipients.push(emailConfig.directorEmail);
|
||||
}
|
||||
|
||||
recipients.forEach(email => {
|
||||
sendMail(
|
||||
email,
|
||||
options.reportName,
|
||||
spreadsheetUrl,
|
||||
pdfBlob,
|
||||
options.additionalText || ''
|
||||
);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function sendMail(
|
||||
email: string,
|
||||
reportName: string,
|
||||
spreadsheetUrl: string,
|
||||
pdfBlob: GoogleAppsScript.Base.Blob,
|
||||
additionalText?: string
|
||||
): void {
|
||||
MailApp.sendEmail({
|
||||
to: email,
|
||||
subject: reportName,
|
||||
htmlBody: `
|
||||
<p>Добрый день.</p>
|
||||
|
||||
<p>
|
||||
Для вас сформирован отчет:
|
||||
<b>${reportName}</b>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b>${additionalText || ''}</b>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Ссылка на таблицу:
|
||||
<a href="${spreadsheetUrl}">
|
||||
${spreadsheetUrl}
|
||||
</a>
|
||||
</p>
|
||||
`,
|
||||
attachments: [pdfBlob]
|
||||
});
|
||||
}
|
||||
|
||||
export function pickRoleEmail(
|
||||
emailConfig: Record<string, string>,
|
||||
primaryKey: string,
|
||||
fallbackKey: string
|
||||
): string {
|
||||
return emailConfig[primaryKey] || emailConfig[fallbackKey] || '';
|
||||
}
|
||||
|
|
@ -0,0 +1,203 @@
|
|||
import { getAppConfig } from '../config';
|
||||
|
||||
export class MetricsStorage {
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet;
|
||||
columns: Record<string, number>;
|
||||
lastRow: number;
|
||||
lastColumn: number;
|
||||
dates: number[];
|
||||
|
||||
constructor(sheetName?: string) {
|
||||
const name = sheetName || getAppConfig().metricsSheetName;
|
||||
|
||||
this.sheet = SpreadsheetApp
|
||||
.getActiveSpreadsheet()
|
||||
.getSheetByName(name);
|
||||
|
||||
this.columns = {
|
||||
date: 1,
|
||||
executor: 2,
|
||||
efficiency: 3,
|
||||
completed: 4,
|
||||
returned: 5,
|
||||
completedPercent: 6,
|
||||
reviewCompleted: 7,
|
||||
reviewAccepted: 8,
|
||||
reviewPercent: 9,
|
||||
spentHours: 10,
|
||||
overdue: 11,
|
||||
newTasks: 12,
|
||||
todayTasks: 13,
|
||||
approved: 14,
|
||||
todayMinutes: 15,
|
||||
totalTasks: 16
|
||||
};
|
||||
|
||||
this.lastRow = this.sheet.getLastRow();
|
||||
this.lastColumn = this.sheet.getLastColumn();
|
||||
|
||||
if (this.lastRow <= 1) {
|
||||
this.dates = [];
|
||||
} else {
|
||||
this.dates = this.sheet
|
||||
.getRange(2, this.columns.date, this.lastRow - 1, 1)
|
||||
.getValues()
|
||||
.flat()
|
||||
.map(value => this.normalizeDate(value));
|
||||
}
|
||||
}
|
||||
|
||||
normalizeDate(date: any): number {
|
||||
if (!(date instanceof Date)) {
|
||||
date = new Date(date);
|
||||
}
|
||||
|
||||
date.setHours(0, 0, 0, 0);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
binarySearchFirst(target: number): number {
|
||||
let l = 0;
|
||||
let r = this.dates.length - 1;
|
||||
let ans = -1;
|
||||
|
||||
while (l <= r) {
|
||||
const m = (l + r) >> 1;
|
||||
|
||||
if (this.dates[m] >= target) {
|
||||
ans = m;
|
||||
r = m - 1;
|
||||
} else {
|
||||
l = m + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
|
||||
binarySearchLast(target: number): number {
|
||||
let l = 0;
|
||||
let r = this.dates.length - 1;
|
||||
let ans = -1;
|
||||
|
||||
while (l <= r) {
|
||||
const m = (l + r) >> 1;
|
||||
|
||||
if (this.dates[m] <= target) {
|
||||
ans = m;
|
||||
l = m + 1;
|
||||
} else {
|
||||
r = m - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
|
||||
getRange(fromDate: Date, toDate: Date): any[][] {
|
||||
if (this.dates.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const from = this.normalizeDate(fromDate);
|
||||
const to = this.normalizeDate(toDate);
|
||||
const first = this.binarySearchFirst(from);
|
||||
const last = this.binarySearchLast(to);
|
||||
|
||||
if (first === -1 || last === -1 || first > last) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.sheet
|
||||
.getRange(
|
||||
first + 2,
|
||||
1,
|
||||
last - first + 1,
|
||||
this.lastColumn
|
||||
)
|
||||
.getValues();
|
||||
}
|
||||
|
||||
updateMetric(date: Date, executor: string, metric: string, value: any): void {
|
||||
const lock = LockService.getDocumentLock();
|
||||
lock.waitLock(10000);
|
||||
|
||||
try {
|
||||
const timestamp = this.normalizeDate(date);
|
||||
let row = this.findEmployeeRow(timestamp, executor);
|
||||
|
||||
if (row === null) {
|
||||
row = this.appendEmployee(date, executor);
|
||||
}
|
||||
|
||||
this.sheet
|
||||
.getRange(row, this.columns[metric])
|
||||
.setValue(value);
|
||||
} finally {
|
||||
lock.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
findEmployeeRow(timestamp: number, executor: string): number | null {
|
||||
const first = this.binarySearchFirst(timestamp);
|
||||
|
||||
if (first === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (this.dates[first] !== timestamp) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let last = first;
|
||||
|
||||
while (
|
||||
last + 1 < this.dates.length &&
|
||||
this.dates[last + 1] === timestamp
|
||||
) {
|
||||
last++;
|
||||
}
|
||||
|
||||
const executors = this.sheet
|
||||
.getRange(
|
||||
first + 2,
|
||||
this.columns.executor,
|
||||
last - first + 1,
|
||||
1
|
||||
)
|
||||
.getValues()
|
||||
.flat();
|
||||
|
||||
for (let i = 0; i < executors.length; i++) {
|
||||
if (executors[i] === executor) {
|
||||
return first + i + 2;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
appendEmployee(date: Date, executor: string): number {
|
||||
const row = Array(this.lastColumn).fill('');
|
||||
|
||||
row[this.columns.date - 1] = date;
|
||||
row[this.columns.executor - 1] = executor;
|
||||
|
||||
const newRow = this.lastRow + 1;
|
||||
|
||||
this.sheet
|
||||
.getRange(newRow, 1, 1, this.lastColumn)
|
||||
.setValues([row]);
|
||||
|
||||
this.lastRow++;
|
||||
this.dates.push(this.normalizeDate(date));
|
||||
this.dates.sort();
|
||||
|
||||
return newRow;
|
||||
}
|
||||
|
||||
sortSheet(): void {
|
||||
this.sheet.getDataRange().offset(1, 0).sort({ column: 1, ascending: true });
|
||||
SpreadsheetApp.flush();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
import { setConfigRequirements } from './config';
|
||||
import { setReportSheetExtras } from './sheets/reportNotes';
|
||||
import type { DepartmentProfile, ReportPlugin } from '../reports/types';
|
||||
|
||||
export function collectConfigRequirements(profile: DepartmentProfile): {
|
||||
sheetKeys: string[];
|
||||
scriptKeys: string[];
|
||||
} {
|
||||
const sheetKeys = [...(profile.requiredConfigKeys || [])];
|
||||
const scriptKeys = [...(profile.requiredScriptProperties || [])];
|
||||
|
||||
profile.plugins.forEach(plugin => {
|
||||
(plugin.requiredConfigKeys || []).forEach(key => sheetKeys.push(key));
|
||||
(plugin.requiredScriptProperties || []).forEach(key => scriptKeys.push(key));
|
||||
});
|
||||
|
||||
return { sheetKeys, scriptKeys };
|
||||
}
|
||||
|
||||
export function applyProfileConfig(profile: DepartmentProfile): void {
|
||||
const { sheetKeys, scriptKeys } = collectConfigRequirements(profile);
|
||||
setConfigRequirements(sheetKeys, scriptKeys);
|
||||
setReportSheetExtras(profile.reportSheetExtras);
|
||||
}
|
||||
|
||||
export function collectHandlers(plugins: ReportPlugin[]): Record<string, (...args: any[]) => any> {
|
||||
const handlers: Record<string, (...args: any[]) => any> = {};
|
||||
|
||||
plugins.forEach(plugin => {
|
||||
Object.assign(handlers, plugin.handlers);
|
||||
});
|
||||
|
||||
return handlers;
|
||||
}
|
||||
|
||||
export function exposeGasGlobals(handlers: Record<string, (...args: any[]) => any>): void {
|
||||
const scopes: any[] = [];
|
||||
|
||||
if (typeof globalThis !== 'undefined') {
|
||||
scopes.push(globalThis);
|
||||
}
|
||||
|
||||
try {
|
||||
scopes.push(Function('return this')());
|
||||
} catch (_error) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
Object.entries(handlers).forEach(([name, fn]) => {
|
||||
scopes.forEach(scope => {
|
||||
if (scope) {
|
||||
scope[name] = fn;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function setupMenuFromPlugins(plugins: ReportPlugin[]): void {
|
||||
const ui = SpreadsheetApp.getUi();
|
||||
const mainMenu = ui.createMenu('📋 Работа с отчетами');
|
||||
|
||||
plugins.forEach(plugin => {
|
||||
const subMenu = ui.createMenu(plugin.menuTitle);
|
||||
plugin.menuItems.forEach(item => {
|
||||
subMenu.addItem(item.label, item.functionName);
|
||||
});
|
||||
mainMenu.addSubMenu(subMenu);
|
||||
});
|
||||
|
||||
mainMenu.addToUi();
|
||||
}
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
export function exportSheetToPdf(
|
||||
spreadsheetId: string,
|
||||
sheetId: number,
|
||||
fileName: string,
|
||||
extraParams?: string[]
|
||||
) {
|
||||
const params = extraParams || [
|
||||
'size=A4',
|
||||
'portrait=false',
|
||||
'fitw=true',
|
||||
'sheetnames=false',
|
||||
'printtitle=false',
|
||||
'pagenumbers=false',
|
||||
'gridlines=false',
|
||||
'fzr=false',
|
||||
];
|
||||
|
||||
const url =
|
||||
`https://docs.google.com/spreadsheets/d/${spreadsheetId}/export` +
|
||||
`?format=pdf` +
|
||||
`&gid=${sheetId}` +
|
||||
(params.length ? '&' + params.join('&') : '');
|
||||
|
||||
const response = UrlFetchApp.fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`
|
||||
}
|
||||
});
|
||||
|
||||
return response
|
||||
.getBlob()
|
||||
.setName(`${fileName}.pdf`);
|
||||
}
|
||||
|
||||
export function exportSheetToXlsxBlob(
|
||||
sourceSheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||||
fileName: string
|
||||
) {
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Лист для экспорта в XLSX не найден');
|
||||
}
|
||||
|
||||
const tempSpreadsheet = SpreadsheetApp.create(
|
||||
`temp_export_${Date.now()}`
|
||||
);
|
||||
|
||||
try {
|
||||
const defaultSheet = tempSpreadsheet.getSheets()[0];
|
||||
const copiedSheet = sourceSheet.copyTo(tempSpreadsheet);
|
||||
copiedSheet.setName(sourceSheet.getName() + Math.random());
|
||||
tempSpreadsheet.deleteSheet(defaultSheet);
|
||||
|
||||
const url =
|
||||
`https://docs.google.com/spreadsheets/d/${tempSpreadsheet.getId()}/export?format=xlsx`;
|
||||
|
||||
const response = UrlFetchApp.fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
|
||||
},
|
||||
muteHttpExceptions: true,
|
||||
});
|
||||
|
||||
return response
|
||||
.getBlob()
|
||||
.setName(`${fileName}.xlsx`);
|
||||
} finally {
|
||||
DriveApp.getFileById(tempSpreadsheet.getId()).setTrashed(true);
|
||||
}
|
||||
}
|
||||
|
||||
export function createPdfFromRows(headers: any[], rows: any[][], fileName: string) {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const tempSheet = ss.insertSheet('_tmp_pdf_' + Date.now());
|
||||
|
||||
try {
|
||||
tempSheet
|
||||
.getRange(1, 1, rows.length + 1, headers.length)
|
||||
.setValues([headers, ...rows]);
|
||||
|
||||
tempSheet.autoResizeColumns(1, headers.length);
|
||||
SpreadsheetApp.flush();
|
||||
|
||||
return exportSheetToPdf(
|
||||
ss.getId(),
|
||||
tempSheet.getSheetId(),
|
||||
fileName
|
||||
);
|
||||
} finally {
|
||||
ss.deleteSheet(tempSheet);
|
||||
}
|
||||
}
|
||||
|
||||
export function createExcelFromRows(headers: any[], rows: any[][], fileName: string) {
|
||||
const tempSpreadsheet = SpreadsheetApp.create(
|
||||
'_tmp_xlsx_' + Date.now()
|
||||
);
|
||||
|
||||
try {
|
||||
const sheet = tempSpreadsheet.getSheets()[0];
|
||||
|
||||
sheet
|
||||
.getRange(1, 1, rows.length + 1, headers.length)
|
||||
.setValues([headers, ...rows]);
|
||||
|
||||
sheet.autoResizeColumns(1, headers.length);
|
||||
SpreadsheetApp.flush();
|
||||
|
||||
const url =
|
||||
'https://docs.google.com/spreadsheets/d/' +
|
||||
tempSpreadsheet.getId() +
|
||||
'/export?format=xlsx';
|
||||
|
||||
const response = UrlFetchApp.fetch(url, {
|
||||
headers: {
|
||||
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
|
||||
}
|
||||
});
|
||||
|
||||
return response
|
||||
.getBlob()
|
||||
.setName(fileName + '.xlsx');
|
||||
} finally {
|
||||
DriveApp.getFileById(tempSpreadsheet.getId()).setTrashed(true);
|
||||
}
|
||||
}
|
||||
|
||||
export function sendTempSpreadsheetToEmail(params: {
|
||||
headers: any[];
|
||||
rows: any[][];
|
||||
fileName: string;
|
||||
email: string;
|
||||
subject: string;
|
||||
htmlBody: string;
|
||||
pdfParams?: string[];
|
||||
}): void {
|
||||
const tempSpreadsheet = SpreadsheetApp.create(
|
||||
'tmp_' + Date.now()
|
||||
);
|
||||
|
||||
try {
|
||||
const tempSheet = tempSpreadsheet.getSheets()[0];
|
||||
const output = [params.headers, ...params.rows];
|
||||
|
||||
tempSheet
|
||||
.getRange(1, 1, output.length, output[0].length)
|
||||
.setValues(output);
|
||||
|
||||
tempSheet.autoResizeColumns(1, output[0].length);
|
||||
SpreadsheetApp.flush();
|
||||
|
||||
const pdf = exportSheetToPdf(
|
||||
tempSpreadsheet.getId(),
|
||||
tempSheet.getSheetId(),
|
||||
params.fileName,
|
||||
params.pdfParams || [
|
||||
'portrait=false',
|
||||
'fitw=true',
|
||||
'sheetnames=false',
|
||||
'printtitle=false',
|
||||
'pagenumbers=true',
|
||||
'gridlines=true',
|
||||
'fzr=true',
|
||||
]
|
||||
);
|
||||
|
||||
const xlsx = exportSheetToXlsxBlob(tempSheet, params.fileName);
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: params.email,
|
||||
subject: params.subject,
|
||||
htmlBody: params.htmlBody,
|
||||
attachments: [pdf, xlsx],
|
||||
});
|
||||
} finally {
|
||||
DriveApp.getFileById(tempSpreadsheet.getId()).setTrashed(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
import { DROPDOWN_VALUES, REPORT_SHEET_INSERT_INDEX } from '../constants';
|
||||
import { formatDateWithTime } from '../dates';
|
||||
import { appendDates, reportNameAlias, shouldAppendReportDates, shouldFreezeReportHeader } from './reportNotes';
|
||||
|
||||
export function hideSheetsByPrefix(
|
||||
prefix: string,
|
||||
spreadsheet?: GoogleAppsScript.Spreadsheet.Spreadsheet
|
||||
): void {
|
||||
const ss = spreadsheet || SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheets = ss.getSheets();
|
||||
|
||||
sheets.forEach(sheet => {
|
||||
if (sheet.getName().startsWith(prefix)) {
|
||||
sheet.hideSheet();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function createTimestampedSheet(
|
||||
prefix: string,
|
||||
spreadsheet?: GoogleAppsScript.Spreadsheet.Spreadsheet
|
||||
) {
|
||||
const ss = spreadsheet || SpreadsheetApp.getActiveSpreadsheet();
|
||||
hideSheetsByPrefix(prefix, ss);
|
||||
const sheetName = `${prefix} ${formatDateWithTime(new Date())}`;
|
||||
return ss.insertSheet(sheetName, REPORT_SHEET_INSERT_INDEX);
|
||||
}
|
||||
|
||||
export function setReportSheetFormat(
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||||
formatDateCells?: boolean
|
||||
): void {
|
||||
const shouldFormatDates = formatDateCells !== false;
|
||||
const dataRange = sheet.getDataRange();
|
||||
const dataRangeWidth = dataRange.getNumColumns();
|
||||
|
||||
dataRange.setBorder(true, true, true, true, true, true);
|
||||
|
||||
const headerRange = sheet.getRange(1, 1, 1, dataRangeWidth);
|
||||
headerRange.setFontWeight('bold');
|
||||
headerRange.setBackground('yellow');
|
||||
|
||||
if (shouldFormatDates) {
|
||||
setSheetDateFormat(sheet);
|
||||
}
|
||||
|
||||
if (shouldFreezeReportHeader()) {
|
||||
sheet.setFrozenRows(1);
|
||||
}
|
||||
|
||||
if (shouldAppendReportDates() && dataRange.getNumRows() > 1) {
|
||||
appendDates(reportNameAlias(sheet.getName()), sheet);
|
||||
}
|
||||
}
|
||||
|
||||
export function setSheetDateFormat(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const range = sheet.getDataRange();
|
||||
const values = range.getValues();
|
||||
const formats = range.getNumberFormats();
|
||||
|
||||
for (let r = 0; r < values.length; r++) {
|
||||
for (let c = 0; c < values[r].length; c++) {
|
||||
if (values[r][c] instanceof Date) {
|
||||
formats[r][c] = 'dd.MM.yyyy hh:mm';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
range.setNumberFormats(formats);
|
||||
}
|
||||
|
||||
export function hideColumnsByNames(
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||||
columnNames: string[]
|
||||
): void {
|
||||
const headers = sheet
|
||||
.getRange(1, 1, 1, sheet.getLastColumn())
|
||||
.getValues()[0];
|
||||
|
||||
const namesSet = new Set(columnNames);
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
if (namesSet.has(String(header).trim())) {
|
||||
sheet.hideColumns(index + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function showColumnsByNames(
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||||
columnNames: string[]
|
||||
): void {
|
||||
const headers = sheet
|
||||
.getRange(1, 1, 1, sheet.getLastColumn())
|
||||
.getValues()[0];
|
||||
|
||||
const namesSet = new Set(columnNames);
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
if (namesSet.has(String(header).trim())) {
|
||||
sheet.showColumns(index + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function getColumnIndexesByName(headerRow: number, columnNames: string[]): number[] {
|
||||
const sheet = SpreadsheetApp.getActiveSheet();
|
||||
|
||||
const headers = sheet
|
||||
.getRange(headerRow, 1, 1, sheet.getLastColumn())
|
||||
.getValues()[0];
|
||||
|
||||
const headerMap = new Map<string, number>();
|
||||
headers.forEach((header, index) => {
|
||||
headerMap.set(String(header).trim(), index + 1);
|
||||
});
|
||||
|
||||
return columnNames.map(name =>
|
||||
headerMap.has(name) ? headerMap.get(name) : -1
|
||||
);
|
||||
}
|
||||
|
||||
export function setupDropdown(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const lastColumn = sheet.getLastColumn();
|
||||
const lastRow = sheet.getLastRow();
|
||||
|
||||
const range = sheet.getRange(
|
||||
2,
|
||||
lastColumn,
|
||||
lastRow - 1,
|
||||
1
|
||||
);
|
||||
|
||||
const rule = SpreadsheetApp.newDataValidation()
|
||||
.requireValueInList(
|
||||
DROPDOWN_VALUES.templateDecision,
|
||||
true
|
||||
)
|
||||
.setAllowInvalid(false)
|
||||
.setHelpText('Выберите значение из списка')
|
||||
.build();
|
||||
|
||||
range.setDataValidation(rule);
|
||||
}
|
||||
|
||||
export function addDropdownValidations(
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||||
headers: any[],
|
||||
rowsCount: number,
|
||||
validations: Record<string, Array<string | number>>
|
||||
): void {
|
||||
if (rowsCount <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.entries(validations).forEach(([columnName, values]) => {
|
||||
const columnIndex = headers.indexOf(columnName);
|
||||
|
||||
if (columnIndex === -1) {
|
||||
Logger.log(`Колонка не найдена: ${columnName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const range = sheet.getRange(
|
||||
2,
|
||||
columnIndex + 1,
|
||||
rowsCount - 1,
|
||||
1
|
||||
);
|
||||
|
||||
const rule = SpreadsheetApp.newDataValidation()
|
||||
.requireValueInList(values, true)
|
||||
.setAllowInvalid(false)
|
||||
.build();
|
||||
|
||||
range.setDataValidation(rule);
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
import { REPORT_NAME_TIMESTAMP_SUFFIX_LENGTH, REPORT_NOTES_SHEET_NAME } from '../constants';
|
||||
|
||||
let freezeHeader = false;
|
||||
let appendDatesEnabled = false;
|
||||
|
||||
export function setReportSheetExtras(extras?: {
|
||||
freezeHeader?: boolean;
|
||||
appendDates?: boolean;
|
||||
}): void {
|
||||
freezeHeader = Boolean(extras && extras.freezeHeader);
|
||||
appendDatesEnabled = Boolean(extras && extras.appendDates);
|
||||
}
|
||||
|
||||
export function shouldFreezeReportHeader(): boolean {
|
||||
return freezeHeader;
|
||||
}
|
||||
|
||||
export function shouldAppendReportDates(): boolean {
|
||||
return appendDatesEnabled;
|
||||
}
|
||||
|
||||
export function reportNameAlias(sheetName: string): string {
|
||||
if (sheetName.length <= REPORT_NAME_TIMESTAMP_SUFFIX_LENGTH) {
|
||||
return sheetName;
|
||||
}
|
||||
return sheetName.slice(0, -REPORT_NAME_TIMESTAMP_SUFFIX_LENGTH);
|
||||
}
|
||||
|
||||
export function appendFromConfig(sheetName: string): void {
|
||||
const HEADER_ROWS = 2;
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const configSheet = ss.getSheetByName(REPORT_NOTES_SHEET_NAME);
|
||||
|
||||
if (!configSheet) {
|
||||
throw new Error(`Конфигурационный лист "${REPORT_NOTES_SHEET_NAME}" не найден.`);
|
||||
}
|
||||
|
||||
const targetSheet = ss.getSheetByName(sheetName);
|
||||
if (!targetSheet) {
|
||||
throw new Error(`Лист "${sheetName}" не найден.`);
|
||||
}
|
||||
|
||||
if (targetSheet.getLastRow() <= HEADER_ROWS) {
|
||||
return;
|
||||
}
|
||||
|
||||
const configLastRow = configSheet.getLastRow();
|
||||
const configLastColumn = configSheet.getLastColumn();
|
||||
|
||||
if (configLastRow <= 0 || configLastColumn < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const configData = configSheet
|
||||
.getRange(1, 1, configLastRow, configLastColumn)
|
||||
.getValues();
|
||||
|
||||
const sheetNameAlias = reportNameAlias(sheetName);
|
||||
const matchingRows: number[] = [];
|
||||
|
||||
for (let i = 0; i < configData.length; i++) {
|
||||
if (String(configData[i][0]).trim() === sheetNameAlias) {
|
||||
matchingRows.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (matchingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const startRow = matchingRows[0];
|
||||
let endRow = configData.length - 1;
|
||||
|
||||
for (let i = startRow + 1; i < configData.length; i++) {
|
||||
const value = String(configData[i][0]).trim();
|
||||
if (value !== '' && value !== sheetNameAlias) {
|
||||
endRow = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const numRows = endRow - startRow + 1;
|
||||
const numColumns = configLastColumn - 1;
|
||||
const dataToAppend = configData
|
||||
.slice(startRow, endRow + 1)
|
||||
.map(row => row.slice(1, configLastColumn));
|
||||
|
||||
targetSheet
|
||||
.getRange(targetSheet.getLastRow() + 1, 2, numRows, numColumns)
|
||||
.setValues(dataToAppend);
|
||||
}
|
||||
|
||||
export function appendDates(identifier: string, sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
if (!sheet) {
|
||||
throw new Error('Лист для записи дат не найден');
|
||||
}
|
||||
|
||||
if (!identifier) {
|
||||
throw new Error('Не указан identifier');
|
||||
}
|
||||
|
||||
const properties = PropertiesService.getScriptProperties();
|
||||
const propertyKey = `lastCallDate_${identifier}`;
|
||||
const previousDate = properties.getProperty(propertyKey);
|
||||
const currentDate = new Date();
|
||||
const targetRow = sheet.getLastRow() + 1;
|
||||
|
||||
sheet.getRange(targetRow, 1, 1, 2).setValues([
|
||||
[
|
||||
'Дата предыдущего формирования: ',
|
||||
previousDate ? new Date(previousDate) : '',
|
||||
],
|
||||
]);
|
||||
|
||||
properties.setProperty(propertyKey, currentDate.toISOString());
|
||||
}
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
import { TASK_CODE_DICTIONARY, TASK_STATUS_NAMES } from './constants';
|
||||
|
||||
export function beforeHash(s: string): string {
|
||||
const idx = s.indexOf('#');
|
||||
const starIdx = s.indexOf('*');
|
||||
|
||||
if (idx === -1 && starIdx === -1) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const finalIdx = (idx != -1 ? idx : starIdx);
|
||||
return s.substring(0, finalIdx + 1).toUpperCase();
|
||||
}
|
||||
|
||||
export function normalizeSpaces(item: any): any {
|
||||
if (typeof item !== 'string') {
|
||||
return item;
|
||||
}
|
||||
|
||||
return item
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function normalizeTaskName(name: string): string {
|
||||
return String(name)
|
||||
.replace(/копия/gi, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function validateTaskCode(str: string): { valid: boolean; code?: string; errors?: string[] } {
|
||||
if (!str || typeof str !== 'string') {
|
||||
return {
|
||||
valid: false,
|
||||
errors: ['Пустая строка']
|
||||
};
|
||||
}
|
||||
|
||||
const code = beforeHash(str);
|
||||
const isLegacyCode = code.includes('#');
|
||||
if (isLegacyCode) {
|
||||
return {
|
||||
valid: true
|
||||
};
|
||||
}
|
||||
|
||||
const rules = [
|
||||
{
|
||||
pos: 1,
|
||||
name: 'ЧАСТОТА',
|
||||
allowed: ['Р', 'Е']
|
||||
},
|
||||
{
|
||||
pos: 2,
|
||||
name: 'ЗАВЕРШЕНИЕ',
|
||||
allowed: ['З', 'П', 'О', 'В']
|
||||
},
|
||||
{
|
||||
pos: 3,
|
||||
name: 'РАЗМЕР',
|
||||
allowed: ['Б', 'М']
|
||||
}
|
||||
];
|
||||
|
||||
const errors: string[] = [];
|
||||
|
||||
if (code.length < 4) {
|
||||
errors.push(
|
||||
'Код слишком короткий. Нужно 3 буквы и символ *'
|
||||
);
|
||||
}
|
||||
|
||||
rules.forEach(rule => {
|
||||
const char = code[rule.pos - 1];
|
||||
|
||||
if (!rule.allowed.includes(char)) {
|
||||
errors.push(
|
||||
`Ошибка в позиции ${rule.pos} (${rule.name}): ` +
|
||||
`получено "${char || 'пусто'}", ` +
|
||||
`допустимо: ${rule.allowed.join(', ')}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (code[3] !== '*') {
|
||||
errors.push(
|
||||
'Ошибка в позиции 4: должен быть символ "*"'
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
code: code,
|
||||
errors: errors
|
||||
};
|
||||
}
|
||||
|
||||
export function getTaskControlType(taskName: string): string {
|
||||
const code = beforeHash(String(taskName || '').trim());
|
||||
|
||||
if (code.includes('П')) {
|
||||
return 'П';
|
||||
}
|
||||
|
||||
if (code.includes('О')) {
|
||||
return 'О';
|
||||
}
|
||||
|
||||
if (code.includes('В')) {
|
||||
return 'В';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
export function getTaskSizeType(taskName: string): 'Б' | 'М' | null {
|
||||
const code = beforeHash(String(taskName || ''));
|
||||
|
||||
if (code.includes('Б')) return 'Б';
|
||||
if (code.includes('М')) return 'М';
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getTaskStatusName(statusId: string | number): string {
|
||||
return TASK_STATUS_NAMES[String(statusId)] || String(statusId);
|
||||
}
|
||||
|
||||
export function decodeTaskCodes(
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet,
|
||||
optionalColumnName?: string
|
||||
): void {
|
||||
if (!sheet) {
|
||||
throw new Error('Не передан лист (sheet).');
|
||||
}
|
||||
|
||||
const range = sheet.getDataRange();
|
||||
const values = range.getValues();
|
||||
|
||||
if (values.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const taskColumnIndex = headers.findIndex(header => {
|
||||
const name = String(header).trim().toLowerCase();
|
||||
|
||||
return (
|
||||
name === 'наименование задачи' ||
|
||||
name === 'название задачи' ||
|
||||
name === optionalColumnName
|
||||
);
|
||||
});
|
||||
|
||||
if (taskColumnIndex === -1) {
|
||||
throw new Error(
|
||||
'Не найден столбец "Наименование задачи" или "Название задачи".'
|
||||
);
|
||||
}
|
||||
|
||||
const outputColumnIndex = values[0].length;
|
||||
const result: string[][] = [];
|
||||
|
||||
result.push(
|
||||
optionalColumnName
|
||||
? ['Расшифровка кода для столбца ' + optionalColumnName]
|
||||
: ['Расшифровка кода']
|
||||
);
|
||||
|
||||
for (let row = 1; row < values.length; row++) {
|
||||
const taskText = String(values[row][taskColumnIndex] ?? '');
|
||||
const code = String(beforeHash(taskText) ?? '').trim().slice(0, -1);
|
||||
|
||||
if (!code) {
|
||||
result.push(['']);
|
||||
continue;
|
||||
}
|
||||
|
||||
const decoded = [...code]
|
||||
.map(letter => TASK_CODE_DICTIONARY[letter] || '')
|
||||
.join(' ');
|
||||
|
||||
result.push([decoded]);
|
||||
}
|
||||
|
||||
sheet
|
||||
.getRange(1, outputColumnIndex + 1, result.length, 1)
|
||||
.setValues(result);
|
||||
}
|
||||
|
||||
export function bitrixBooleanToString(value: any): any {
|
||||
if (value == null) return value;
|
||||
|
||||
const normalized = String(value)
|
||||
.trim()
|
||||
.replace(/\.+$/, '')
|
||||
.toLowerCase();
|
||||
|
||||
if (normalized === 'да' || normalized === 'y') return 'Да';
|
||||
if (normalized === 'нет' || normalized === 'n') return 'Нет';
|
||||
|
||||
return value;
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
export function requestDate(promptText: string): Date {
|
||||
const ui = SpreadsheetApp.getUi();
|
||||
|
||||
while (true) {
|
||||
const response = ui.prompt(
|
||||
promptText,
|
||||
'Формат: ДД.ММ.ГГГГ (например, 18.06.2026)',
|
||||
ui.ButtonSet.OK_CANCEL
|
||||
);
|
||||
|
||||
if (response.getSelectedButton() !== ui.Button.OK) {
|
||||
throw new Error('Ввод даты отменён пользователем');
|
||||
}
|
||||
|
||||
const input = response.getResponseText().trim();
|
||||
const match = input.match(/^(\d{2})\.(\d{2})\.(\d{4})$/);
|
||||
|
||||
if (!match) {
|
||||
ui.alert('Некорректный формат. Используйте ДД.ММ.ГГГГ.');
|
||||
continue;
|
||||
}
|
||||
|
||||
const [, day, month, year] = match;
|
||||
const date = new Date(
|
||||
Number(year),
|
||||
Number(month) - 1,
|
||||
Number(day)
|
||||
);
|
||||
|
||||
if (
|
||||
date.getFullYear() === Number(year) &&
|
||||
date.getMonth() === Number(month) - 1 &&
|
||||
date.getDate() === Number(day)
|
||||
) {
|
||||
return date;
|
||||
}
|
||||
|
||||
ui.alert('Такой даты не существует.');
|
||||
}
|
||||
}
|
||||
|
||||
export function askUser(question: string): boolean {
|
||||
const ui = SpreadsheetApp.getUi();
|
||||
|
||||
const result = ui.alert(
|
||||
'Подтверждение',
|
||||
question,
|
||||
ui.ButtonSet.OK_CANCEL
|
||||
);
|
||||
|
||||
return result === ui.Button.OK;
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import { getBitrixMethodUrl } from '../../../core/config';
|
||||
import { fetchBalancer } from '../../../core/bitrix/client';
|
||||
import { bitrixBooleanToString } from '../../../core/taskCodes';
|
||||
import { dateDiffToMs, formatIsoLocal } from '../../../core/dates';
|
||||
|
||||
export function getYesterdayClosedTasksByPerformers(performerNames: string[], afterDate: Date) {
|
||||
const tasks = loadClosedAfterTasks(afterDate);
|
||||
const performerSet = new Set(performerNames);
|
||||
const result = new Map<string, any[]>();
|
||||
|
||||
performerNames.forEach(name => {
|
||||
result.set(name, []);
|
||||
});
|
||||
|
||||
tasks.forEach((task: any) => {
|
||||
const performerName = task.responsible?.name;
|
||||
if (!performerName || !performerSet.has(performerName)) return;
|
||||
|
||||
result.get(performerName).push({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
createdDate: new Date(task.createdDate),
|
||||
deadline: new Date(task.deadline),
|
||||
creator: task.creator.name,
|
||||
responsible: task.responsible.name,
|
||||
status: task.status,
|
||||
timeEstimate: dateDiffToMs(new Date(task.startDatePlan), new Date(task.endDatePlan)),
|
||||
clientLoss: bitrixBooleanToString(task.ufAuto738863346313),
|
||||
price: task.ufAuto392526971904,
|
||||
taskControl: task.taskControl,
|
||||
});
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function loadClosedAfterTasks(afterDate: Date): any[] {
|
||||
const result = fetchBalancer(
|
||||
getBitrixMethodUrl('tasks', 'tasks.task.list'),
|
||||
{
|
||||
isRecurrent: true,
|
||||
resultKey: 'tasks',
|
||||
body: {
|
||||
filter: {
|
||||
'>=CLOSED_DATE': getDateString(afterDate),
|
||||
'<CLOSED_DATE': getDateString(new Date()),
|
||||
STATUS: 5,
|
||||
},
|
||||
select: [
|
||||
'ID', 'TITLE', 'CREATED_DATE', 'DEADLINE', 'CREATED_BY',
|
||||
'RESPONSIBLE_ID', 'STATUS', 'TIME_ESTIMATE',
|
||||
'TASK_CONTROL', 'START_DATE_PLAN', 'END_DATE_PLAN',
|
||||
'UF_AUTO_738863346313', 'UF_AUTO_392526971904',
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return (result.data && result.data.body) || [];
|
||||
}
|
||||
|
||||
function getDateString(date: Date): string {
|
||||
const startOfDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
|
||||
return formatIsoLocal(startOfDay);
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import type { ReportPlugin } from '../../../reports/types';
|
||||
import { notifyCompletedTasks } from '../../../reports/completed/notifyFilialHead';
|
||||
import { notifySalesDepartmentHead } from '../../../reports/completed/notifySalesHead';
|
||||
import { buildCompletedTasksReport } from './main';
|
||||
|
||||
export const completedPlugin: ReportPlugin = {
|
||||
id: 'completed',
|
||||
menuTitle: '9️⃣ ✅ Завершенные задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'buildCompletedTasksReport' },
|
||||
{ label: '👔 Отправить отчет рукфилу', functionName: 'notifyCompletedTasks' },
|
||||
{ label: '👔 Отправить отчет РОПу', functionName: 'notifySalesDepartmentHead' },
|
||||
],
|
||||
handlers: {
|
||||
buildCompletedTasksReport,
|
||||
notifyCompletedTasks,
|
||||
notifySalesDepartmentHead,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'ORG_STRUCTURE_FILE_ID',
|
||||
'DEPARTMENT_ID',
|
||||
'DEFAULT_FILIAL_HEAD_NAME',
|
||||
'BITRIX_PORTAL',
|
||||
'BALANCER_URL',
|
||||
],
|
||||
requiredScriptProperties: [
|
||||
'BALANCER_PUBLIC',
|
||||
'BALANCER_SECRET',
|
||||
'BITRIX_WEBHOOK_TASKS',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,395 @@
|
|||
import { REPORT_PREFIXES } from '../../../core/constants';
|
||||
import { getAppConfig, getSourceSheet } from '../../../core/config';
|
||||
import { requestDate } from '../../../core/ui';
|
||||
import { getTaskStatusName } from '../../../core/taskCodes';
|
||||
import { dateDiffToMs, formatDate, msToDuration } from '../../../core/dates';
|
||||
import { compareNames } from '../../../core/mail/emailConfig';
|
||||
import { createTimestampedSheet, getColumnIndexesByName } from '../../../core/sheets/reportLifecycle';
|
||||
import { appendDates, appendFromConfig } from '../../../core/sheets/reportNotes';
|
||||
import { MetricsStorage } from '../../../core/metrics/storage';
|
||||
import { getYesterdayClosedTasksByPerformers } from './fetchCompletedTasks';
|
||||
|
||||
const REPORT_HEADERS = [
|
||||
'ID задачи', 'Наименование задачи', 'Дата создания', 'Крайний срок задачи',
|
||||
'Постановщик', 'Исполнитель', 'Руководитель филиала', 'Статус',
|
||||
'Планируемая длительность', 'Ведет к потере клиента', 'Цена задачи',
|
||||
];
|
||||
|
||||
const TASK_FIELDS = {
|
||||
id: 'ID задачи',
|
||||
title: 'Наименование задачи',
|
||||
deadline: 'Крайний срок задачи',
|
||||
creator: 'Постановщик',
|
||||
responsible: 'Исполнитель',
|
||||
status: 'Статус',
|
||||
closedDate: 'Дата закрытия',
|
||||
crm: 'CRM',
|
||||
timeEstimate: 'Время выполнения задачи',
|
||||
clientLoss: 'Ведет к потере клиента',
|
||||
price: 'Цена задачи',
|
||||
};
|
||||
|
||||
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);
|
||||
generateReport(executors);
|
||||
} 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]))];
|
||||
}
|
||||
|
||||
function loadCompletedTasks(afterDate: Date) {
|
||||
return getYesterdayClosedTasksByPerformers(getAllExecutorNames(), afterDate);
|
||||
}
|
||||
|
||||
function loadWaitingControlTasks(sheet: GoogleAppsScript.Spreadsheet.Sheet) {
|
||||
const tasks = getObjects(sheet, TASK_FIELDS);
|
||||
const sourceSheet = getSourceSheet();
|
||||
const allCreatedDates = getIdToColumnValueMap(sourceSheet, 'Дата создания');
|
||||
const taskStartsMap = getIdToColumnValueMap(sourceSheet, 'Планируемая дата начала');
|
||||
const taskEndsMap = getIdToColumnValueMap(sourceSheet, 'Планируемая дата окончания');
|
||||
|
||||
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 (taskStartsMap.has(taskId) && taskEndsMap.has(taskId)) {
|
||||
task.timeEstimate = dateDiffToMs(taskStartsMap.get(taskId), taskEndsMap.get(taskId));
|
||||
}
|
||||
});
|
||||
|
||||
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) || 0;
|
||||
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 generateReport(executors: Record<string, any>): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheet = createTimestampedSheet(REPORT_PREFIXES.completed, ss);
|
||||
let row = 1;
|
||||
|
||||
sheet.getRange(row, 1, 1, REPORT_HEADERS.length)
|
||||
.setValues([REPORT_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);
|
||||
if (toWrite.length == 0) return;
|
||||
|
||||
sheet.getRange(row, 1, toWrite.length, REPORT_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;
|
||||
});
|
||||
|
||||
setupConditionalFormatting(sheet);
|
||||
const standardWidth = sheet.getColumnWidth(1);
|
||||
sheet.autoResizeColumns(1, sheet.getDataRange().getNumColumns());
|
||||
sheet.setColumnWidth(2, standardWidth * 7);
|
||||
appendFromConfig(sheet.getName());
|
||||
appendDates(REPORT_PREFIXES.completed, sheet);
|
||||
metricsStorage.sortSheet();
|
||||
}
|
||||
|
||||
function createTaskArray(executor: any): any[][] {
|
||||
return executor.reportTasks.map((task: any) => [
|
||||
task.id,
|
||||
task.title,
|
||||
formatDate(task.createdDate),
|
||||
formatDate(task.deadline),
|
||||
task.creator,
|
||||
task.responsible,
|
||||
executor.depHead,
|
||||
getTaskStatusName(task.status),
|
||||
msToDuration(task.timeEstimate),
|
||||
task.clientLoss,
|
||||
task.price,
|
||||
]);
|
||||
}
|
||||
|
||||
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],
|
||||
['Суммарно эффективно затраченное время:', msToDuration(duration)],
|
||||
['Оценка руководителя филиала (1-5):', ''],
|
||||
['Комментарий руководителя филиала:', ''],
|
||||
['ID задачи руководителя (если требуется):', ''],
|
||||
];
|
||||
|
||||
const columnIndexes = getColumnIndexesByName(1, ['Исполнитель', 'Руководитель филиала']);
|
||||
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]));
|
||||
sheet.getRange(startRow, 2, data.length, 2)
|
||||
.setValues(data)
|
||||
.setBackground('#ffff00')
|
||||
.setBorder(true, true, true, true, true, true);
|
||||
|
||||
const rule = SpreadsheetApp.newDataValidation()
|
||||
.requireValueInList([1, 2, 3, 4, 5] as any)
|
||||
.setAllowInvalid(false)
|
||||
.build();
|
||||
sheet.getRange(startRow + 4, 3, 1, 1).setDataValidation(rule);
|
||||
}
|
||||
|
||||
function setupConditionalFormatting(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const MARKER = 'Оценка руководителя филиала (1-5):';
|
||||
const lastRow = sheet.getLastRow();
|
||||
const values = sheet.getRange(1, 2, lastRow, 1).getValues();
|
||||
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($C$${percentRow};"^\\d+"))<50;` +
|
||||
`$C$${scoreRow}<4` +
|
||||
`)`;
|
||||
|
||||
rules.push(
|
||||
SpreadsheetApp.newConditionalFormatRule()
|
||||
.whenFormulaSatisfied(formula)
|
||||
.setBackground('#ff0000')
|
||||
.setRanges([sheet.getRange(row + 1, 3), sheet.getRange(row + 2, 3)])
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
sheet.setConditionalFormatRules(rules);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import type { ReportPlugin } from '../../../reports/types';
|
||||
import { exportActualTasks } from './main';
|
||||
|
||||
export const currentTasksPlugin: ReportPlugin = {
|
||||
id: 'currentTasks',
|
||||
menuTitle: '8️⃣ 📋 Актуальные задачи менеджеров (вечер)',
|
||||
menuItems: [
|
||||
{ label: '📤 Отправить менеджерам', functionName: 'exportActualTasks' },
|
||||
],
|
||||
handlers: { exportActualTasks },
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'MANAGER_TABLES_CONFIG_ID',
|
||||
'BITRIX_PORTAL',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
import { EXECUTOR_SHEET_NAMES } from '../../../core/constants';
|
||||
import { getBitrixTaskViewUrl, getSourceSheet } from '../../../core/config';
|
||||
import { getUserEmailMap } from '../../../core/mail/emailConfig';
|
||||
import { clearSheetsForMissingPeople, loadConfig } from '../../../core/mail/executorTables';
|
||||
import { dateDiffToMs, getNextWorkday, msToDuration } from '../../../core/dates';
|
||||
import { setReportSheetFormat } from '../../../core/sheets/reportLifecycle';
|
||||
import { MetricsStorage } from '../../../core/metrics/storage';
|
||||
|
||||
function resetTime(date: Date): Date {
|
||||
const result = new Date(date);
|
||||
result.setHours(0, 0, 0, 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function exportActualTasks(): void {
|
||||
const sourceSheet = getSourceSheet();
|
||||
const data = sourceSheet.getDataRange().getValues();
|
||||
const headers = data.shift();
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((h, i) => {
|
||||
col[String(h)] = i;
|
||||
});
|
||||
|
||||
const executorTasks: Record<string, any[]> = {};
|
||||
|
||||
data.forEach(row => {
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
if (status == 'Завершена' || status == 'Ждёт контроля') return;
|
||||
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
if (!executor) return;
|
||||
|
||||
const startDate = row[col['Планируемая дата начала']];
|
||||
const endDate = row[col['Планируемая дата окончания']];
|
||||
const tomorrow = resetTime(getNextWorkday(new Date()));
|
||||
|
||||
if (resetTime(startDate) > tomorrow || resetTime(endDate) < tomorrow) return;
|
||||
|
||||
if (!executorTasks[executor]) executorTasks[executor] = [];
|
||||
executorTasks[executor].push({
|
||||
id: row[col['ID']],
|
||||
title: row[col['Название']],
|
||||
created: row[col['Дата создания']],
|
||||
deadline: row[col['Крайний срок']],
|
||||
creator: row[col['Постановщик']],
|
||||
executor,
|
||||
crm: row[col['CRM']],
|
||||
status,
|
||||
startDate,
|
||||
endDate,
|
||||
duration: dateDiffToMs(startDate, endDate),
|
||||
danger: row[col['Может привести к потере клиента']],
|
||||
});
|
||||
});
|
||||
|
||||
const config = loadConfig();
|
||||
const emailMap = getUserEmailMap();
|
||||
const metricsStorage = new MetricsStorage();
|
||||
const now = new Date();
|
||||
const SHEET_NAME = EXECUTOR_SHEET_NAMES.actualTasks;
|
||||
const existingExecutors = Object.keys(executorTasks);
|
||||
|
||||
clearSheetsForMissingPeople(existingExecutors, SHEET_NAME);
|
||||
|
||||
Object.entries(executorTasks).forEach(([executor, tasks]) => {
|
||||
const spreadsheetId = config[executor];
|
||||
if (!spreadsheetId) {
|
||||
Logger.log('Не найдена таблица: ' + executor);
|
||||
return;
|
||||
}
|
||||
if (!tasks || tasks.length == 0) return;
|
||||
|
||||
metricsStorage.updateMetric(now, executor, 'totalTasks', tasks.length);
|
||||
|
||||
tasks.sort((a, b) => {
|
||||
const va = String(a.danger).toLowerCase() == 'да' ? 1 : 0;
|
||||
const vb = String(b.danger).toLowerCase() == 'да' ? 1 : 0;
|
||||
if (va != vb) return vb - va;
|
||||
|
||||
const da = a.startDate instanceof Date ? a.startDate.getTime() : new Date(a.startDate).getTime();
|
||||
const db = b.startDate instanceof Date ? b.startDate.getTime() : new Date(b.startDate).getTime();
|
||||
return da - db;
|
||||
});
|
||||
|
||||
const ss = SpreadsheetApp.openById(spreadsheetId);
|
||||
let sheet = ss.getSheetByName(SHEET_NAME);
|
||||
if (!sheet) sheet = ss.insertSheet(SHEET_NAME);
|
||||
sheet.clear();
|
||||
sheet.clearFormats();
|
||||
|
||||
sheet.getRange(1, 1, 1, 11).setValues([[
|
||||
'ID задачи/ссылка', 'Наименование задачи', 'Дата создания', 'Крайний срок задачи',
|
||||
'Постановщик', 'Исполнитель', 'CRM', 'Планируемая дата начала',
|
||||
'Планируемая дата завершения', 'Планируемая длительность', 'Ведет к потере клиента',
|
||||
]]);
|
||||
|
||||
const values: any[][] = [];
|
||||
const richTexts: any[][] = [];
|
||||
let total = 0;
|
||||
|
||||
tasks.forEach(task => {
|
||||
values.push([
|
||||
task.title, task.created, task.deadline, task.creator, task.executor,
|
||||
task.crm, task.startDate, task.endDate, msToDuration(task.duration), task.danger,
|
||||
]);
|
||||
richTexts.push([
|
||||
SpreadsheetApp.newRichTextValue()
|
||||
.setText(String(task.id))
|
||||
.setLinkUrl(getBitrixTaskViewUrl(task.id))
|
||||
.build(),
|
||||
]);
|
||||
total += Number(task.duration) || 0;
|
||||
});
|
||||
|
||||
if (values.length) {
|
||||
sheet.getRange(2, 2, values.length, values[0].length).setValues(values);
|
||||
setReportSheetFormat(sheet);
|
||||
sheet.getRange(2, 1, richTexts.length, 1).setRichTextValues(richTexts);
|
||||
}
|
||||
|
||||
metricsStorage.sortSheet();
|
||||
const totalRow = values.length + 2;
|
||||
sheet.getRange(totalRow, 8).setValue('Итого времени:');
|
||||
sheet.getRange(totalRow, 9).setValue(msToDuration(total));
|
||||
sheet.autoResizeColumns(1, 10);
|
||||
|
||||
const email = emailMap[executor];
|
||||
if (email) {
|
||||
MailApp.sendEmail({
|
||||
to: email,
|
||||
subject: 'Актуальные задачи',
|
||||
htmlBody:
|
||||
'Здравствуйте.<br><br>' +
|
||||
'Ваш список актуальных задач доступен по ссылке:<br><br>' +
|
||||
'<a href="' + ss.getUrl() + '#gid=' + sheet.getSheetId() + '">' +
|
||||
'Открыть лист "Актуальные задачи"</a>',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { applyProfileConfig, collectHandlers, setupMenuFromPlugins } from '../../core/runtime';
|
||||
import { salesOriginalProfile } from './profile';
|
||||
|
||||
applyProfileConfig(salesOriginalProfile);
|
||||
|
||||
function onOpen(): void {
|
||||
menuSetup();
|
||||
}
|
||||
|
||||
function menuSetup(): void {
|
||||
setupMenuFromPlugins(salesOriginalProfile.plugins);
|
||||
}
|
||||
|
||||
const gasApi = {
|
||||
onOpen,
|
||||
menuSetup,
|
||||
...collectHandlers(salesOriginalProfile.plugins),
|
||||
};
|
||||
|
||||
export default gasApi;
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import type { ReportPlugin } from '../../../reports/types';
|
||||
import { distributeOverdueTasksToExecutors } from '../../../reports/overdue/executorNotification';
|
||||
import { pullExecutorAnswers } from '../../../reports/overdue/getExecutorComments';
|
||||
import { notifyOverdueTasks } from '../../../reports/overdue/notifyFilialHead';
|
||||
import { sendTasksToCreatorsForApproval } from '../../../reports/overdue/notifyTaskSetters';
|
||||
import { createOverdueTasksReport } from './main';
|
||||
import { saveOverdueTasksReport, saveReportToTaskIndex } from './notifySalesDepHead';
|
||||
|
||||
export const overduePlugin: ReportPlugin = {
|
||||
id: 'overdue',
|
||||
menuTitle: '4️⃣ 🚨 Просроченные задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createOverdueTasksReport' },
|
||||
{ label: '📤 Отправить менеджерам', functionName: 'distributeOverdueTasksToExecutors' },
|
||||
{ label: '💬 Получить комментарии менеджеров', functionName: 'pullExecutorAnswers' },
|
||||
{ label: '👔 Отправить отчет рукфилу', functionName: 'notifyOverdueTasks' },
|
||||
{ label: '✉️ Отправить письма постановщикам', functionName: 'sendTasksToCreatorsForApproval' },
|
||||
{ label: '👔 Уведомить РОПа', functionName: 'saveOverdueTasksReport' },
|
||||
{ label: '💾 Сохранить комментарии', functionName: 'saveReportToTaskIndex' },
|
||||
],
|
||||
handlers: {
|
||||
createOverdueTasksReport,
|
||||
distributeOverdueTasksToExecutors,
|
||||
pullExecutorAnswers,
|
||||
notifyOverdueTasks,
|
||||
sendTasksToCreatorsForApproval,
|
||||
saveOverdueTasksReport,
|
||||
saveReportToTaskIndex,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'MANAGER_TABLES_CONFIG_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
import { REPORT_PREFIXES } from '../../../core/constants';
|
||||
import { getAppConfig, getSourceSheet } from '../../../core/config';
|
||||
import { bitrixBooleanToString } from '../../../core/taskCodes';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../../core/sheets/reportLifecycle';
|
||||
import { appendFromConfig } from '../../../core/sheets/reportNotes';
|
||||
import { TaskIndexService } from '../../../reports/overdue/taskIndexService';
|
||||
|
||||
export function createOverdueTasksReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const reportPrefix = REPORT_PREFIXES.overdue;
|
||||
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Не найден лист выгрузки');
|
||||
}
|
||||
|
||||
const taskIndex = new TaskIndexService(getAppConfig().taskIndexSheetName);
|
||||
const values = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (values.length < 2) {
|
||||
throw new Error('На листе "Для выгрузки" нет данных');
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const requiredColumns = [
|
||||
'ID', 'Название', 'Описание', 'Название базовой задачи', 'CRM',
|
||||
'Постановщик', 'Исполнитель', 'Дата создания', 'Крайний срок',
|
||||
'Дата закрытия', 'Может привести к потере клиента', 'Цена задачи', 'Важная задача',
|
||||
];
|
||||
|
||||
const missingColumns = requiredColumns.filter(name => !(name in col));
|
||||
if (missingColumns.length) {
|
||||
throw new Error('Не найдены колонки: ' + missingColumns.join(', '));
|
||||
}
|
||||
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const reportRows: Array<{ lossClient: any; important: any; executor: string; row: any[] }> = [];
|
||||
const taskNames = new Map<any, any>();
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const taskId = row[col['ID']] || '';
|
||||
if (taskId == '') continue;
|
||||
taskNames.set(taskId, row[col['Название']]);
|
||||
}
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const deadline = row[col['Крайний срок']];
|
||||
|
||||
if (!(deadline instanceof Date) || deadline >= today) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const taskId = String(row[col['ID']] || '').trim();
|
||||
if (taskId == '') continue;
|
||||
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
if (status == '' || status === 'Ждёт контроля') continue;
|
||||
|
||||
const indexRecord = taskIndex.get(taskId);
|
||||
let transferCount = 0;
|
||||
let previousComments = '';
|
||||
|
||||
if (indexRecord) {
|
||||
transferCount = Number(indexRecord.transferCount || 0) + 1;
|
||||
previousComments = indexRecord.comment || '';
|
||||
}
|
||||
|
||||
reportRows.push({
|
||||
lossClient: bitrixBooleanToString(String(row[col['Может привести к потере клиента']] || '')),
|
||||
important: bitrixBooleanToString(String(row[col['Важная задача']] || '')),
|
||||
executor: String(row[col['Исполнитель']] || ''),
|
||||
row: [
|
||||
taskId,
|
||||
row[col['Название']],
|
||||
row[col['Описание']],
|
||||
taskNames.get(row[col['ID базовой задачи']]) || '',
|
||||
row[col['CRM']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Дата создания']],
|
||||
deadline,
|
||||
bitrixBooleanToString(row[col['Может привести к потере клиента']]),
|
||||
row[col['Цена задачи']],
|
||||
transferCount,
|
||||
bitrixBooleanToString(row[col['Важная задача']]),
|
||||
previousComments,
|
||||
'', '', '', '', '', '',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
reportRows.sort((a, b) => {
|
||||
const aLoss = String(a.lossClient) === 'Да';
|
||||
const bLoss = String(b.lossClient) === 'Да';
|
||||
if (aLoss !== bLoss) return aLoss ? -1 : 1;
|
||||
|
||||
const aImportant = String(a.important) === 'Да';
|
||||
const bImportant = String(b.important) === 'Да';
|
||||
if (aImportant !== bImportant) return aImportant ? -1 : 1;
|
||||
|
||||
return a.executor.localeCompare(b.executor, 'ru');
|
||||
});
|
||||
|
||||
const reportHeaders = [
|
||||
'ID задачи', 'Наименование задачи', 'Описание', 'Наименование родительской задачи',
|
||||
'Элементы CRM', 'Постановщик', 'Исполнитель', 'Дата создания задачи',
|
||||
'Крайний срок задачи', 'Ведет к потере клиента', 'Цена задачи',
|
||||
'Ранее переносилась раз', 'Задача, требующая описания причины при переносе сроков',
|
||||
'Прошлые причины переноса', 'Текущая причина переноса',
|
||||
'Новый крайний срок от менеджера', 'Согласование рук. фила',
|
||||
'Новый крайний срок от рук. фила', 'Согласование постановщиком', 'Согласование РОПом',
|
||||
];
|
||||
|
||||
const reportSheet = createTimestampedSheet(reportPrefix, ss);
|
||||
const output = [reportHeaders, ...reportRows.map(item => item.row)];
|
||||
reportSheet.getRange(1, 1, output.length, reportHeaders.length).setValues(output);
|
||||
reportSheet.getRange(1, 1, 1, reportHeaders.length).setBackground('yellow');
|
||||
addApprovalDropdowns(reportSheet);
|
||||
|
||||
const lastCol = reportSheet.getDataRange().getNumColumns();
|
||||
reportSheet.autoResizeColumns(1, lastCol);
|
||||
setReportSheetFormat(reportSheet);
|
||||
reportSheet.setColumnWidth((col['Наименование задачи'] || 0) + 1, 300);
|
||||
reportSheet.setColumnWidth((col['Описание'] || 0) + 1, 300);
|
||||
reportSheet.setColumnWidth((col['Наименование родительской задачи'] || 0) + 1, 300);
|
||||
appendFromConfig(reportSheet.getName());
|
||||
}
|
||||
|
||||
function addApprovalDropdowns(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const values = sheet.getDataRange().getValues();
|
||||
if (values.length < 2) return;
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index + 1;
|
||||
});
|
||||
|
||||
const validation = SpreadsheetApp
|
||||
.newDataValidation()
|
||||
.requireValueInList(['Согласовано', 'Не согласовано'], true)
|
||||
.setAllowInvalid(false)
|
||||
.build();
|
||||
|
||||
const lastRow = sheet.getLastRow();
|
||||
|
||||
['Согласование рук. фила', 'Согласование постановщиком', 'Согласование РОПом']
|
||||
.forEach(columnName => {
|
||||
const column = col[columnName];
|
||||
if (!column) {
|
||||
throw new Error(`Не найден столбец "${columnName}"`);
|
||||
}
|
||||
|
||||
sheet.getRange(2, column, Math.max(lastRow - 1, 1), 1).setDataValidation(validation);
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import { getAppConfig } from '../../../core/config';
|
||||
import { formatDate } from '../../../core/dates';
|
||||
import { notifyLeadership } from '../../../core/mail/notify';
|
||||
import { MetricsStorage } from '../../../core/metrics/storage';
|
||||
import { TaskIndexService } from '../../../reports/overdue/taskIndexService';
|
||||
|
||||
export function saveOverdueTasksReport(): void {
|
||||
notifyLeadership({
|
||||
reportName: 'Отчет по просроченным задачам',
|
||||
recipients: 'salesHead',
|
||||
includeDirector: false,
|
||||
onConfirm(sheet) {
|
||||
updateOverdueMetric(sheet);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function saveReportToTaskIndex(): void {
|
||||
const taskIndex = new TaskIndexService(getAppConfig().taskIndexSheetName);
|
||||
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const values = sheet.getDataRange().getValues();
|
||||
if (values.length < 2) return;
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const today = formatDate(new Date());
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const taskId = String(row[col['ID задачи']] || '').trim();
|
||||
if (!taskId) continue;
|
||||
|
||||
const transferCount = Number(row[col['Ранее переносилась раз']] || 0);
|
||||
const reason = String(row[col['Текущая причина переноса']] || '').trim();
|
||||
const newComment = reason ? `${today} ${reason}` : '';
|
||||
const existing = taskIndex.get(taskId);
|
||||
|
||||
if (!existing) {
|
||||
taskIndex.add(taskId, newComment, transferCount);
|
||||
continue;
|
||||
}
|
||||
|
||||
let comment = existing.comment || '';
|
||||
if (newComment) {
|
||||
comment = comment ? comment + '\n' + newComment : newComment;
|
||||
}
|
||||
|
||||
taskIndex.update(taskId, { comment, transferCount });
|
||||
}
|
||||
|
||||
taskIndex.save();
|
||||
}
|
||||
|
||||
function updateOverdueMetric(tasksSheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
if (!tasksSheet) {
|
||||
throw new Error('Не передан лист отчёта по просроченным задачам');
|
||||
}
|
||||
|
||||
const tasksByAssignee = countTasksByAssignee(tasksSheet);
|
||||
const storage = new MetricsStorage();
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
for (const [assignee, taskCount] of Object.entries(tasksByAssignee)) {
|
||||
storage.updateMetric(today, assignee, 'overdue', taskCount);
|
||||
}
|
||||
|
||||
storage.sortSheet();
|
||||
}
|
||||
|
||||
function countTasksByAssignee(sheet: GoogleAppsScript.Spreadsheet.Sheet): Record<string, number> {
|
||||
const data = sheet.getDataRange().getValues();
|
||||
if (data.length < 2) return {};
|
||||
|
||||
const headers = data[0];
|
||||
const taskColumn = headers.indexOf('Наименование задачи');
|
||||
const assigneeColumn = headers.indexOf('Исполнитель');
|
||||
|
||||
if (taskColumn === -1) throw new Error('Не найден столбец «Наименование задачи»');
|
||||
if (assigneeColumn === -1) throw new Error('Не найден столбец «Исполнитель»');
|
||||
|
||||
const result: Record<string, number> = {};
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const task = String(data[i][taskColumn] || '').trim();
|
||||
const assignee = String(data[i][assigneeColumn] || '').trim();
|
||||
if (task && assignee) {
|
||||
result[assignee] = (result[assignee] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { appendFromConfig } from '../../core/sheets/reportNotes';
|
||||
import type { ReportPlugin } from '../../reports/types';
|
||||
|
||||
export function withAppendFromConfig(plugin: ReportPlugin, handlerNames: string[]): ReportPlugin {
|
||||
const handlers = { ...plugin.handlers };
|
||||
|
||||
handlerNames.forEach(name => {
|
||||
const original = handlers[name];
|
||||
if (!original) {
|
||||
return;
|
||||
}
|
||||
|
||||
handlers[name] = function (...args: any[]) {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const before = new Set(ss.getSheets().map(sheet => sheet.getSheetId()));
|
||||
const result = original.apply(this, args);
|
||||
const created = ss.getSheets().find(sheet => !before.has(sheet.getSheetId()));
|
||||
if (created) {
|
||||
appendFromConfig(created.getName());
|
||||
}
|
||||
return result;
|
||||
};
|
||||
});
|
||||
|
||||
return { ...plugin, handlers };
|
||||
}
|
||||
|
||||
export function withMenuTitle(plugin: ReportPlugin, menuTitle: string): ReportPlugin {
|
||||
return { ...plugin, menuTitle };
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import type { DepartmentProfile } from '../../reports/types';
|
||||
import { bigSmallPlugin } from '../../reports/bigSmall';
|
||||
import { selfTasksPlugin } from '../../reports/selfTasks';
|
||||
import { effectivenessPlugin } from '../../reports/effectiveness';
|
||||
import { newTemplatesPlugin } from '../../reports/newTemplates';
|
||||
import { planOverduePlugin } from '../../reports/planOverdue';
|
||||
import { singleTimePlugin } from './singleTime';
|
||||
import { waitingControlPlugin } from './waitingControl';
|
||||
import { overduePlugin } from './overdue';
|
||||
import { completedPlugin } from './completed';
|
||||
import { workloadPlugin } from './workload';
|
||||
import { currentTasksPlugin } from './currentTasks';
|
||||
import { withAppendFromConfig, withMenuTitle } from './pluginUtils';
|
||||
|
||||
export const salesOriginalProfile: DepartmentProfile = {
|
||||
id: 'salesOriginal',
|
||||
reportSheetExtras: {
|
||||
freezeHeader: true,
|
||||
appendDates: true,
|
||||
},
|
||||
plugins: [
|
||||
withAppendFromConfig(bigSmallPlugin, ['createBigSmallTasksReport']),
|
||||
singleTimePlugin,
|
||||
waitingControlPlugin,
|
||||
overduePlugin,
|
||||
withAppendFromConfig(selfTasksPlugin, ['buildSelfAssignedTasksReport']),
|
||||
planOverduePlugin,
|
||||
workloadPlugin,
|
||||
currentTasksPlugin,
|
||||
completedPlugin,
|
||||
withMenuTitle(
|
||||
withAppendFromConfig(effectivenessPlugin, ['saveDateRange', 'repPreviousWeek']),
|
||||
'🔟 🆕 Лист эффективности'
|
||||
),
|
||||
withMenuTitle(
|
||||
withAppendFromConfig(newTemplatesPlugin, ['createNewTemplatesRepors']),
|
||||
'1️⃣1️⃣ 🆕 Новые шаблоны'
|
||||
),
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
import { beforeHash, bitrixBooleanToString, normalizeTaskName, validateTaskCode } from '../../../core/taskCodes';
|
||||
import { dateDiffToDuration, isSameDay } from '../../../core/dates';
|
||||
|
||||
export const SINGLE_TIME_HEADERS = [
|
||||
'Название задачи',
|
||||
'Название родительской задачи',
|
||||
'ID задачи',
|
||||
'ID родительской задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Крайний срок задачи',
|
||||
'Дата создания задачи',
|
||||
'Крайний срок родительской задачи',
|
||||
'Элементы CRM',
|
||||
'Время выполнения задачи',
|
||||
'Планируемое время начала',
|
||||
'Планируемое время завершения',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
'Важная задача',
|
||||
'Требует внимания',
|
||||
'Согласен с постановкой задачи',
|
||||
];
|
||||
|
||||
export function getSingleTimeColumnIndexes(headers: any[]) {
|
||||
return {
|
||||
id: headers.indexOf('ID'),
|
||||
title: headers.indexOf('Название'),
|
||||
deadline: headers.indexOf('Крайний срок'),
|
||||
creator: headers.indexOf('Постановщик'),
|
||||
executor: headers.indexOf('Исполнитель'),
|
||||
status: headers.indexOf('Статус'),
|
||||
created: headers.indexOf('Дата создания'),
|
||||
parentTaskId: headers.indexOf('ID базовой задачи'),
|
||||
allowDeadlineChange: headers.indexOf('Разрешено изменять крайний срок'),
|
||||
price: headers.indexOf('Цена задачи'),
|
||||
crm: headers.indexOf('CRM'),
|
||||
clientLoss: headers.indexOf('Может привести к потере клиента'),
|
||||
importantTask: headers.indexOf('Важная задача'),
|
||||
startTime: headers.indexOf('Планируемая дата начала'),
|
||||
endTime: headers.indexOf('Планируемая дата окончания'),
|
||||
};
|
||||
}
|
||||
|
||||
export function isSingleTimeTaskRow(
|
||||
row: any[],
|
||||
col: ReturnType<typeof getSingleTimeColumnIndexes>,
|
||||
lastReportDate: Date,
|
||||
now: Date
|
||||
): boolean {
|
||||
const title = String(row[col.title] || '');
|
||||
const createdDate = row[col.created];
|
||||
const isValidCode = validateTaskCode(normalizeTaskName(title)).valid;
|
||||
const isOneTimeTask = beforeHash(title).includes('Р') || !isValidCode;
|
||||
|
||||
const isAfterLastReport =
|
||||
createdDate instanceof Date &&
|
||||
createdDate >= lastReportDate &&
|
||||
!isSameDay(createdDate, now);
|
||||
|
||||
return isOneTimeTask && isAfterLastReport;
|
||||
}
|
||||
|
||||
export function buildAttentionText(task: any[], col: ReturnType<typeof getSingleTimeColumnIndexes>, taskControl: boolean): string {
|
||||
const warnings: string[] = [];
|
||||
const title = String(task[col.title] || '');
|
||||
const allowDeadlineChange = String(task[col.allowDeadlineChange] || '');
|
||||
const taskCodeValidationResult = validateTaskCode(normalizeTaskName(title));
|
||||
const code = beforeHash(title);
|
||||
const isSelfTask = task[col.creator] == task[col.executor];
|
||||
|
||||
if (!isSelfTask && code && (code.includes('П') || code.includes('В')) && !taskControl) {
|
||||
warnings.push('Не включен контроль в задаче, требующей приемки');
|
||||
}
|
||||
|
||||
if (!isSelfTask && code && (code.includes('О') || code.includes('З')) && taskControl) {
|
||||
warnings.push('Включен контроль в задаче, не требующей приемки');
|
||||
}
|
||||
|
||||
if (!isSelfTask && !taskCodeValidationResult.valid) {
|
||||
warnings.push('Ошибка в буквенном коде');
|
||||
}
|
||||
|
||||
if (
|
||||
allowDeadlineChange === 'Y' &&
|
||||
String(task[col.creator]) !== String(task[col.executor])
|
||||
) {
|
||||
warnings.push('Разрешено менять крайний срок');
|
||||
}
|
||||
|
||||
if (task[col.importantTask] == '') {
|
||||
warnings.push('Не заполненно обязательное поле "Важная задача"');
|
||||
}
|
||||
|
||||
if (task[col.clientLoss] == '') {
|
||||
warnings.push('Не заполненно обязательное поле "Ведет к потере клиента"');
|
||||
}
|
||||
|
||||
if (task[col.deadline] == '') {
|
||||
warnings.push('Не указан крайний срок');
|
||||
}
|
||||
|
||||
return warnings.length > 0
|
||||
? 'Да:' + warnings.join(', ')
|
||||
: 'Нет';
|
||||
}
|
||||
|
||||
export function buildSingleTimeReportRow(
|
||||
mainTask: any[],
|
||||
parentTask: any[] | null,
|
||||
col: ReturnType<typeof getSingleTimeColumnIndexes>,
|
||||
taskControl: boolean
|
||||
): any[] {
|
||||
const attention = buildAttentionText(mainTask, col, taskControl);
|
||||
|
||||
return [
|
||||
mainTask[col.title],
|
||||
parentTask ? parentTask[col.title] : '',
|
||||
mainTask[col.id],
|
||||
parentTask ? parentTask[col.id] : '',
|
||||
mainTask[col.creator],
|
||||
mainTask[col.executor],
|
||||
mainTask[col.deadline],
|
||||
mainTask[col.created],
|
||||
parentTask ? parentTask[col.deadline] : '',
|
||||
mainTask[col.crm],
|
||||
dateDiffToDuration(mainTask[col.endTime], mainTask[col.startTime]),
|
||||
mainTask[col.startTime],
|
||||
mainTask[col.endTime],
|
||||
bitrixBooleanToString(mainTask[col.clientLoss]),
|
||||
mainTask[col.price],
|
||||
bitrixBooleanToString(mainTask[col.importantTask]),
|
||||
attention,
|
||||
'',
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import type { ReportPlugin } from '../../../reports/types';
|
||||
import { notifySingleTimeTasks } from '../../../reports/singleTime/reportSender';
|
||||
import { createSingleTimeTasksReport } from './main';
|
||||
import { sendAttentionTasksToCreatorsForApproval } from './notifyTaskSetters';
|
||||
|
||||
export const singleTimePlugin: ReportPlugin = {
|
||||
id: 'singleTime',
|
||||
menuTitle: '2️⃣ 📝 Разовые задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createSingleTimeTasksReport' },
|
||||
{ label: '🔔 Уведомить постановщиков', functionName: 'sendAttentionTasksToCreatorsForApproval' },
|
||||
{ label: '👔 Отправить руководителю', functionName: 'notifySingleTimeTasks' },
|
||||
],
|
||||
handlers: {
|
||||
createSingleTimeTasksReport,
|
||||
sendAttentionTasksToCreatorsForApproval,
|
||||
notifySingleTimeTasks,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'BITRIX_PORTAL',
|
||||
'BALANCER_URL',
|
||||
],
|
||||
requiredScriptProperties: [
|
||||
'BALANCER_PUBLIC',
|
||||
'BALANCER_SECRET',
|
||||
'BITRIX_WEBHOOK_TASKS',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
import { REPORT_PREFIXES } from '../../../core/constants';
|
||||
import { getSourceSheet } from '../../../core/config';
|
||||
import { requestDate } from '../../../core/ui';
|
||||
import { loadTasksByIds } from '../../../core/bitrix/client';
|
||||
import { bitrixBooleanToString } from '../../../core/taskCodes';
|
||||
import { addDropdownValidations, createTimestampedSheet, setReportSheetFormat } from '../../../core/sheets/reportLifecycle';
|
||||
import { appendFromConfig } from '../../../core/sheets/reportNotes';
|
||||
import {
|
||||
SINGLE_TIME_HEADERS,
|
||||
buildSingleTimeReportRow,
|
||||
getSingleTimeColumnIndexes,
|
||||
isSingleTimeTaskRow,
|
||||
} from './builder';
|
||||
|
||||
export function createSingleTimeTasksReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Не найден лист с выгрузкой');
|
||||
}
|
||||
|
||||
const lastReportDate = requestDate('Введите дату формирования последнего отчета по разовым задачам');
|
||||
const data = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
throw new Error('Нет данных для обработки');
|
||||
}
|
||||
|
||||
const headers = data[0];
|
||||
const rows = data.slice(1);
|
||||
const col = getSingleTimeColumnIndexes(headers);
|
||||
const now = new Date();
|
||||
|
||||
const reportTasks = rows.filter(row => isSingleTimeTaskRow(row, col, lastReportDate, now));
|
||||
|
||||
reportTasks.sort((a, b) => {
|
||||
const clientLossA = bitrixBooleanToString(a[col.clientLoss]);
|
||||
const clientLossB = bitrixBooleanToString(b[col.clientLoss]);
|
||||
|
||||
if (clientLossA === '' && clientLossB !== '') return 1;
|
||||
if (clientLossA !== '' && clientLossB === '') return -1;
|
||||
if (clientLossA === '' && clientLossB === '') return 0;
|
||||
|
||||
return String(clientLossA).localeCompare(String(clientLossB));
|
||||
});
|
||||
|
||||
const taskIds = reportTasks.map(task => task[col.id]);
|
||||
const taskControlSet = getTaskControlSet(taskIds);
|
||||
const result: any[][] = [SINGLE_TIME_HEADERS];
|
||||
|
||||
reportTasks.forEach(mainTask => {
|
||||
const parentTaskId = mainTask[col.parentTaskId];
|
||||
const parentTask = rows.find(row => row[col.id] == parentTaskId) || null;
|
||||
result.push(
|
||||
buildSingleTimeReportRow(
|
||||
mainTask,
|
||||
parentTask,
|
||||
col,
|
||||
taskControlSet.has(String(mainTask[col.id]))
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
const reportSheet = createTimestampedSheet(REPORT_PREFIXES.singleTime, ss);
|
||||
reportSheet
|
||||
.getRange(1, 1, result.length, result[0].length)
|
||||
.setValues(result);
|
||||
|
||||
addDropdownValidations(reportSheet, result[0], result.length, {
|
||||
'Согласен с постановкой задачи': ['Да', 'Внес коррективы'],
|
||||
});
|
||||
|
||||
setReportSheetFormat(reportSheet);
|
||||
appendFromConfig(reportSheet.getName());
|
||||
SpreadsheetApp.flush();
|
||||
Logger.log('Отчет успешно сформирован');
|
||||
}
|
||||
|
||||
function getTaskControlSet(taskIds: any[]): Set<string> {
|
||||
if (!taskIds || taskIds.length === 0) {
|
||||
return new Set();
|
||||
}
|
||||
|
||||
const tasks = loadTasksByIds(taskIds);
|
||||
const controlSet = new Set<string>();
|
||||
|
||||
tasks.forEach((task: any) => {
|
||||
if (task.taskControl === 'Y') {
|
||||
controlSet.add(String(task.id));
|
||||
}
|
||||
});
|
||||
|
||||
return controlSet;
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { askUser } from '../../../core/ui';
|
||||
import { getUserEmailMap } from '../../../core/mail/emailConfig';
|
||||
import { sendTempSpreadsheetToEmail } from '../../../core/sheets/export';
|
||||
|
||||
export function sendAttentionTasksToCreatorsForApproval(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const reportSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const reportData = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (reportData.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = reportData[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const emailMap = getUserEmailMap();
|
||||
const creators: Record<string, any[][]> = {};
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = reportData[i];
|
||||
const creator = String(row[col['Постановщик']] || '').trim();
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
|
||||
if (!creator) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (row[col['Требует внимания']] == 'Нет') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (creator === executor) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!creators[creator]) {
|
||||
creators[creator] = [];
|
||||
}
|
||||
|
||||
creators[creator].push([
|
||||
row[col['Название задачи']],
|
||||
row[col['Название родительской задачи']],
|
||||
row[col['ID задачи']],
|
||||
row[col['ID родительской задачи']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Крайний срок задачи']],
|
||||
row[col['Крайний срок родительской задачи']],
|
||||
row[col['Элементы CRM']],
|
||||
row[col['Время выполнения задачи']],
|
||||
row[col['Планируемое время начала']],
|
||||
row[col['Планируемое время завершения']],
|
||||
row[col['Вероятность выполнения задачи']],
|
||||
row[col['Ведет к потере клиента']],
|
||||
row[col['Цена задачи']],
|
||||
row[col['Важная задача']],
|
||||
row[col['Требует внимания']],
|
||||
]);
|
||||
}
|
||||
|
||||
const pdfHeaders = [
|
||||
'Название задачи',
|
||||
'Название родительской задачи',
|
||||
'ID задачи',
|
||||
'ID родительской задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Крайний срок задачи',
|
||||
'Крайний срок родительской задачи',
|
||||
'Элементы CRM',
|
||||
'Время выполнения задачи',
|
||||
'Вероятность выполнения задачи',
|
||||
'Планируемое время начала',
|
||||
'Планируемое время завершения',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
'Важная задача',
|
||||
'Требует внимания',
|
||||
];
|
||||
|
||||
Object.entries(creators).forEach(([creator, rows]) => {
|
||||
const email = emailMap[creator];
|
||||
if (!email) {
|
||||
return;
|
||||
}
|
||||
|
||||
sendTempSpreadsheetToEmail({
|
||||
email,
|
||||
fileName: 'Разовые задачи - ' + creator,
|
||||
headers: pdfHeaders,
|
||||
rows,
|
||||
subject: 'Замечание по разовым задачам',
|
||||
htmlBody: 'Во вложении находятся разовые задачи, требующие исправления',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import type { ReportPlugin } from '../../../reports/types';
|
||||
import { sendWaitingControlReports } from '../../../reports/waitingControl/notifyTaskSetters';
|
||||
import { refreshWaitingControlReport } from '../../../reports/waitingControl/reportScanner';
|
||||
import { checkWaitingControlReasonsAndSendPdf } from '../../../reports/waitingControl/salesDepHeadNotification';
|
||||
import { buildWaitingControlReport } from './main';
|
||||
|
||||
export const waitingControlPlugin: ReportPlugin = {
|
||||
id: 'waitingControl',
|
||||
menuTitle: '3️⃣ ⏳ Ожидают контроля',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'buildWaitingControlReport' },
|
||||
{ label: '🔔 Уведомить постановщиков', functionName: 'sendWaitingControlReports' },
|
||||
{ label: '🔄 Обновить статусы задач', functionName: 'refreshWaitingControlReport' },
|
||||
{ label: '👔 Отправить отчет РОПу', functionName: 'checkWaitingControlReasonsAndSendPdf' },
|
||||
],
|
||||
handlers: {
|
||||
buildWaitingControlReport,
|
||||
sendWaitingControlReports,
|
||||
refreshWaitingControlReport,
|
||||
checkWaitingControlReasonsAndSendPdf,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
import { REPORT_PREFIXES, WAITING_CONTROL_STATUS } from '../../../core/constants';
|
||||
import { getSourceSheet } from '../../../core/config';
|
||||
import { beforeHash, bitrixBooleanToString } from '../../../core/taskCodes';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../../core/sheets/reportLifecycle';
|
||||
import { appendFromConfig } from '../../../core/sheets/reportNotes';
|
||||
|
||||
export function buildWaitingControlReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const values = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (values.length < 2) {
|
||||
throw new Error('На листе нет данных');
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const requiredColumns = [
|
||||
'ID',
|
||||
'Название',
|
||||
'Крайний срок',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Статус',
|
||||
'Дата закрытия',
|
||||
'Может привести к потере клиента',
|
||||
];
|
||||
|
||||
const missing = requiredColumns.filter(name => !(name in col));
|
||||
if (missing.length) {
|
||||
throw new Error('Не найдены колонки: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
const reportHeaders = [
|
||||
'ID задачи',
|
||||
'Наименование задачи',
|
||||
'Крайний срок задачи',
|
||||
'Дата создания задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Статус',
|
||||
'Дата закрытия',
|
||||
'Ведет к потере клиента',
|
||||
'Если сохраняется статус Ждет контроля, то опиши причину',
|
||||
];
|
||||
|
||||
const result: Array<{ lossClient: any; creator: string; executor: string; row: any[] }> = [];
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
if (status !== WAITING_CONTROL_STATUS) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const taskName = String(row[col['Название']] || '').trim();
|
||||
const code = beforeHash(taskName);
|
||||
const hasRequiredLetter = code.includes('П') || code.includes('О') || code.includes('В');
|
||||
if (!hasRequiredLetter) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result.push({
|
||||
lossClient: bitrixBooleanToString(String(row[col['Может привести к потере клиента']] || '')),
|
||||
creator: String(row[col['Постановщик']] || ''),
|
||||
executor: String(row[col['Исполнитель']] || ''),
|
||||
row: [
|
||||
row[col['ID']],
|
||||
taskName,
|
||||
row[col['Крайний срок']],
|
||||
row[col['Дата создания']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Статус']],
|
||||
row[col['Дата закрытия']],
|
||||
bitrixBooleanToString(row[col['Может привести к потере клиента']]),
|
||||
'',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
result.sort((a, b) => {
|
||||
const aLoss = String(a.lossClient).trim().toLowerCase() === 'да';
|
||||
const bLoss = String(b.lossClient).trim().toLowerCase() === 'да';
|
||||
if (aLoss !== bLoss) {
|
||||
return aLoss ? -1 : 1;
|
||||
}
|
||||
|
||||
const creatorCompare = String(a.creator).localeCompare(String(b.creator), 'ru');
|
||||
if (creatorCompare !== 0) {
|
||||
return creatorCompare;
|
||||
}
|
||||
|
||||
return String(a.executor).localeCompare(String(b.executor), 'ru');
|
||||
});
|
||||
|
||||
const reportSheet = createTimestampedSheet(REPORT_PREFIXES.waitingControl, ss);
|
||||
const output = [reportHeaders, ...result.map(item => item.row)];
|
||||
reportSheet
|
||||
.getRange(1, 1, output.length, reportHeaders.length)
|
||||
.setValues(output);
|
||||
reportSheet.autoResizeColumns(1, reportHeaders.length);
|
||||
setReportSheetFormat(reportSheet);
|
||||
appendFromConfig(reportSheet.getName());
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import type { ReportPlugin } from '../../../reports/types';
|
||||
import { notifyWorkloadReport } from '../../../reports/workload/reportSender';
|
||||
import { saveResponse } from '../../../reports/workload/saveHeadResponse';
|
||||
import { reportCurrentWeek, reportNextWeek, report10Days } from './main';
|
||||
|
||||
export const workloadPlugin: ReportPlugin = {
|
||||
id: 'workload',
|
||||
menuTitle: '7️⃣ 📅 Рабочая нагрузка',
|
||||
menuItems: [
|
||||
{ label: '📆 Отчет за текущую неделю', functionName: 'reportCurrentWeek' },
|
||||
{ label: '⏭️ Отчет за следующую неделю', functionName: 'reportNextWeek' },
|
||||
{ label: '⏭️ Отчет на 10 дней вперед', functionName: 'report10Days' },
|
||||
{ label: '👔 Отправить руководителю', functionName: 'notifyWorkloadReport' },
|
||||
{ label: '💾 Сохранить ответ руководителя', functionName: 'saveResponse' },
|
||||
],
|
||||
handlers: {
|
||||
reportCurrentWeek,
|
||||
reportNextWeek,
|
||||
report10Days,
|
||||
notifyWorkloadReport,
|
||||
saveResponse,
|
||||
},
|
||||
requiredConfigKeys: ['SOURCE_SHEET_ID'],
|
||||
};
|
||||
|
|
@ -0,0 +1,250 @@
|
|||
import { REPORT_PREFIXES } from '../../../core/constants';
|
||||
import { getSourceSheet } from '../../../core/config';
|
||||
import { bitrixBooleanToString } from '../../../core/taskCodes';
|
||||
import { dateDiffToMs, formatDate, isSameDay, msToDuration } from '../../../core/dates';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../../core/sheets/reportLifecycle';
|
||||
import { appendFromConfig } from '../../../core/sheets/reportNotes';
|
||||
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.startTime < startDate || task.startTime > 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.startTime - b.startTime);
|
||||
});
|
||||
|
||||
let currentRow = renderGlobalHeader(reportSheet, 1, startDate, endDate);
|
||||
Object.keys(grouped).forEach(executor => {
|
||||
currentRow = renderExecutorBlock(reportSheet, currentRow, executor, grouped[executor], startDate, endDate);
|
||||
currentRow += 3;
|
||||
});
|
||||
|
||||
autoFormat(reportSheet);
|
||||
setReportSheetFormat(reportSheet);
|
||||
appendFromConfig(reportSheet.getName());
|
||||
}
|
||||
|
||||
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['Крайний срок']],
|
||||
startTime: start,
|
||||
duration: dateDiffToMs(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 totalExecutorTime = 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.startTime)) {
|
||||
values.push(msToDuration(task.duration));
|
||||
const key = formatDate(date);
|
||||
dayTotals[key] += Number(task.duration) || 0;
|
||||
dayCounts[key]++;
|
||||
} else {
|
||||
values.push('');
|
||||
}
|
||||
});
|
||||
|
||||
totalExecutorTime += Number(task.duration) || 0;
|
||||
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(msToDuration(dayTotals[formatDate(date)]));
|
||||
});
|
||||
totalHoursRow.push(msToDuration(totalExecutorTime));
|
||||
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 {
|
||||
sheet.autoResizeColumns(1, 20);
|
||||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { applyProfileConfig, collectHandlers, setupMenuFromPlugins } from '../../core/runtime';
|
||||
import { universalProfile } from './profile';
|
||||
|
||||
applyProfileConfig(universalProfile);
|
||||
|
||||
function onOpen(): void {
|
||||
menuSetup();
|
||||
}
|
||||
|
||||
function menuSetup(): void {
|
||||
setupMenuFromPlugins(universalProfile.plugins);
|
||||
}
|
||||
|
||||
const gasApi = {
|
||||
onOpen,
|
||||
menuSetup,
|
||||
...collectHandlers(universalProfile.plugins),
|
||||
};
|
||||
|
||||
export default gasApi;
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import type { DepartmentProfile } from '../../reports/types';
|
||||
import { bigSmallPlugin } from '../../reports/bigSmall';
|
||||
import { singleTimePlugin } from '../../reports/singleTime';
|
||||
import { waitingControlPlugin } from '../../reports/waitingControl';
|
||||
import { overduePlugin } from '../../reports/overdue';
|
||||
import { selfTasksPlugin } from '../../reports/selfTasks';
|
||||
import { completedPlugin } from '../../reports/completed';
|
||||
import { workloadPlugin } from '../../reports/workload';
|
||||
import { currentTasksPlugin } from '../../reports/currentTasks';
|
||||
import { effectivenessPlugin } from '../../reports/effectiveness';
|
||||
import { newTemplatesPlugin } from '../../reports/newTemplates';
|
||||
|
||||
export const universalProfile: DepartmentProfile = {
|
||||
id: 'universal',
|
||||
plugins: [
|
||||
bigSmallPlugin,
|
||||
singleTimePlugin,
|
||||
waitingControlPlugin,
|
||||
overduePlugin,
|
||||
selfTasksPlugin,
|
||||
completedPlugin,
|
||||
workloadPlugin,
|
||||
currentTasksPlugin,
|
||||
effectivenessPlugin,
|
||||
newTemplatesPlugin,
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<base target="_top">
|
||||
|
||||
<!-- Flatpickr -->
|
||||
<link rel="stylesheet"
|
||||
href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/ru.js"></script>
|
||||
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.buttons {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 8px 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h3>Выберите период</h3>
|
||||
|
||||
<input id="dateRange" placeholder="Выберите даты">
|
||||
|
||||
<div class="buttons">
|
||||
<button onclick="google.script.host.close()">Отмена</button>
|
||||
<button onclick="submitRange()">OK</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const picker = flatpickr("#dateRange", {
|
||||
mode: "range",
|
||||
dateFormat: "Y-m-d",
|
||||
locale: flatpickr.l10ns.ru
|
||||
});
|
||||
|
||||
function submitRange() {
|
||||
|
||||
const dates = picker.selectedDates;
|
||||
|
||||
if (dates.length !== 2) {
|
||||
alert("Выберите диапазон дат.");
|
||||
return;
|
||||
}
|
||||
|
||||
const format = d => d.getFullYear() + "-" +
|
||||
String(d.getMonth() + 1).padStart(2, "0") + "-" +
|
||||
String(d.getDate()).padStart(2, "0");
|
||||
|
||||
google.script.run
|
||||
.withSuccessHandler(() => google.script.host.close())
|
||||
.saveDateRange(
|
||||
format(dates[0]),
|
||||
format(dates[1])
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,257 @@
|
|||
import { bitrixBooleanToString, getTaskSizeType } from '../../core/taskCodes';
|
||||
import { diffMinutes, formatDate, isSameDay } from '../../core/dates';
|
||||
|
||||
export const BIG_SMALL_HEADERS = [
|
||||
'Название задачи',
|
||||
'Название родительской задачи',
|
||||
'ID Р. задачи',
|
||||
'ID задачи',
|
||||
'Исполнитель',
|
||||
'Постановщик',
|
||||
'Элемент CRM',
|
||||
'Большая или мелкая',
|
||||
'Крайний срок Р. задачи',
|
||||
'Крайний срок задачи',
|
||||
'Дата создания подзадачи',
|
||||
'Время выполнения',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
'Требует внимания',
|
||||
'Комментарий исполнителя',
|
||||
'Комментарий руководителя',
|
||||
];
|
||||
|
||||
export function getCrmElement(row: any[], col: Record<string, number>): any {
|
||||
const crmFields = ['Лид', 'Контакт', 'Компания', 'Сделка', 'CRM'];
|
||||
|
||||
for (const field of crmFields) {
|
||||
const value = row[col[field]];
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
export function isTaskOverdue(deadline: any, now: Date): boolean {
|
||||
if (!deadline) return false;
|
||||
const date = new Date(deadline);
|
||||
return date < now;
|
||||
}
|
||||
|
||||
export function checkAttention(params: {
|
||||
taskType: string | null;
|
||||
parentDeadline: any;
|
||||
taskDeadline: any;
|
||||
isOverdue: boolean;
|
||||
taskExecutionTime: number | '';
|
||||
taskClientLossMarker: string;
|
||||
taskEnd: any;
|
||||
hasSubtask: boolean;
|
||||
taskCreationDate: any;
|
||||
taskStart: any;
|
||||
now: Date;
|
||||
}): string {
|
||||
const {
|
||||
taskType,
|
||||
parentDeadline,
|
||||
taskDeadline,
|
||||
isOverdue,
|
||||
taskExecutionTime,
|
||||
taskClientLossMarker,
|
||||
taskEnd,
|
||||
hasSubtask,
|
||||
taskCreationDate,
|
||||
taskStart,
|
||||
now,
|
||||
} = params;
|
||||
|
||||
const problems: string[] = [];
|
||||
|
||||
if (isOverdue) {
|
||||
problems.push('задача просрочена');
|
||||
}
|
||||
|
||||
if (taskClientLossMarker == '') {
|
||||
problems.push('не заполнено обязательное поле "Ведет к потере клиента" задачи');
|
||||
}
|
||||
|
||||
if (!taskStart) {
|
||||
problems.push('не заполнено поле "Планируемое время начала" задачи');
|
||||
}
|
||||
|
||||
if (!taskEnd) {
|
||||
problems.push('не заполнено поле "Планируемое время завершения" задачи');
|
||||
}
|
||||
|
||||
if (taskDeadline == '') {
|
||||
problems.push('нет крайнего срока подзадачи');
|
||||
}
|
||||
|
||||
if (parentDeadline && taskDeadline) {
|
||||
const parentDate = new Date(parentDeadline);
|
||||
const subDate = new Date(taskDeadline);
|
||||
|
||||
if (subDate > parentDate) {
|
||||
problems.push('крайний срок подзадачи больше крайнего срока родительской задачи');
|
||||
}
|
||||
}
|
||||
|
||||
if (taskEnd && taskEnd < now) {
|
||||
const dateString = formatDate(taskEnd);
|
||||
problems.push('задача должна была быть завершена ' + dateString);
|
||||
}
|
||||
|
||||
if (taskType == 'Б' && !hasSubtask) {
|
||||
problems.push('нет подзадач у большой задачи');
|
||||
}
|
||||
|
||||
if (parentDeadline && taskEnd) {
|
||||
const parentDate = new Date(parentDeadline);
|
||||
const subDate = new Date(taskEnd);
|
||||
|
||||
if (subDate > parentDate) {
|
||||
problems.push('планируемое время завершения задачи больше крайнего срока родительской задачи');
|
||||
}
|
||||
}
|
||||
|
||||
if (taskDeadline && taskEnd) {
|
||||
const taskDeadlineDate = new Date(taskDeadline);
|
||||
const taskEndDate = new Date(taskEnd);
|
||||
|
||||
if (taskEndDate > taskDeadlineDate) {
|
||||
problems.push('планируемое время завершения задачи больше её крайнего срока');
|
||||
}
|
||||
}
|
||||
|
||||
if (taskCreationDate && taskEnd) {
|
||||
const taskCreationDateConverted = new Date(taskCreationDate);
|
||||
const taskEndDate = new Date(taskEnd);
|
||||
|
||||
if (taskCreationDateConverted > taskEndDate) {
|
||||
problems.push('планируемое время завершения задачи раньше даты её создания');
|
||||
}
|
||||
}
|
||||
|
||||
if (taskExecutionTime > 360) {
|
||||
problems.push('длителность задачи больше 6 часов');
|
||||
}
|
||||
|
||||
if (problems.length != 0) {
|
||||
return 'Да: ' + problems.join(', ');
|
||||
}
|
||||
|
||||
return 'Нет';
|
||||
}
|
||||
|
||||
export function buildBigSmallReportRows(
|
||||
sourceRows: any[][],
|
||||
sourceHeaders: any[],
|
||||
lastLaunch: Date,
|
||||
now: Date = new Date()
|
||||
): any[][] {
|
||||
const col: Record<string, number> = {};
|
||||
sourceHeaders.forEach((header, index) => {
|
||||
col[header] = index;
|
||||
});
|
||||
|
||||
const tasksById: Record<string, any[]> = {};
|
||||
const parentTasksByid: Record<string, any> = {};
|
||||
|
||||
sourceRows.forEach(row => {
|
||||
const id = row[col['ID']];
|
||||
tasksById[id] = row;
|
||||
|
||||
const parentId = row[col['ID базовой задачи']];
|
||||
if (parentTasksByid) {
|
||||
parentTasksByid[parentId] = id;
|
||||
}
|
||||
});
|
||||
|
||||
const body: any[][] = [];
|
||||
|
||||
sourceRows.forEach(task => {
|
||||
const parentId = task[col['ID базовой задачи']] || '';
|
||||
const parentTask = tasksById[parentId] || '';
|
||||
const taskCreationDate = task[col['Дата создания']];
|
||||
|
||||
if (taskCreationDate < lastLaunch || isSameDay(taskCreationDate, now)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parentName = String(parentTask[col['Название']] || '').trim();
|
||||
const taskName = String(task[col['Название']] || '').trim();
|
||||
const taskType = getTaskSizeType(taskName);
|
||||
const parentDeadline = parentTask[col['Крайний срок']] || '';
|
||||
const taskDeadline = task[col['Крайний срок']];
|
||||
const taskStart = task[col['Планируемая дата начала']] || '';
|
||||
const taskEnd = task[col['Планируемая дата окончания']] || '';
|
||||
const taskExecutionTime = diffMinutes(taskStart, taskEnd);
|
||||
const taskClientLossMarker = String(task[col['Может привести к потере клиента']] || '').trim();
|
||||
const isOverdue = isTaskOverdue(taskDeadline, now);
|
||||
const hasSubtask = Boolean(parentTasksByid[task[col['ID']]]);
|
||||
|
||||
const needAttention = checkAttention({
|
||||
taskType,
|
||||
parentDeadline,
|
||||
taskDeadline,
|
||||
isOverdue,
|
||||
taskExecutionTime,
|
||||
taskClientLossMarker,
|
||||
taskEnd,
|
||||
hasSubtask,
|
||||
taskCreationDate,
|
||||
taskStart,
|
||||
now,
|
||||
});
|
||||
|
||||
body.push([
|
||||
taskName,
|
||||
parentName,
|
||||
parentTask[col['ID']] || '',
|
||||
task[col['ID']],
|
||||
task[col['Исполнитель']],
|
||||
task[col['Постановщик']],
|
||||
getCrmElement(task, col),
|
||||
taskType,
|
||||
parentDeadline,
|
||||
taskDeadline,
|
||||
taskCreationDate,
|
||||
taskExecutionTime,
|
||||
bitrixBooleanToString(taskClientLossMarker),
|
||||
task[col['Цена задачи']],
|
||||
needAttention,
|
||||
'',
|
||||
'',
|
||||
]);
|
||||
});
|
||||
|
||||
const clientLossIndex = BIG_SMALL_HEADERS.indexOf('Ведет к потере клиента');
|
||||
const executorIndex = BIG_SMALL_HEADERS.indexOf('Исполнитель');
|
||||
const taskTypeIndex = BIG_SMALL_HEADERS.indexOf('Большая или мелкая');
|
||||
|
||||
body.sort((a, b) => {
|
||||
const clientLossA = a[clientLossIndex];
|
||||
const clientLossB = b[clientLossIndex];
|
||||
if (clientLossA != clientLossB) {
|
||||
return clientLossA === 'Да' ? -1 : 1;
|
||||
}
|
||||
|
||||
const executorA = a[executorIndex];
|
||||
const executorB = b[executorIndex];
|
||||
if (executorA != executorB) {
|
||||
return String(executorA).localeCompare(String(executorB));
|
||||
}
|
||||
|
||||
const taskTypeA = a[taskTypeIndex];
|
||||
const taskTypeB = b[taskTypeIndex];
|
||||
if (taskTypeA != taskTypeB) {
|
||||
return String(taskTypeA).localeCompare(String(taskTypeB));
|
||||
}
|
||||
|
||||
return String(a[0]).localeCompare(String(b[0]), 'ru');
|
||||
});
|
||||
|
||||
return [BIG_SMALL_HEADERS, ...body];
|
||||
}
|
||||
|
|
@ -0,0 +1,206 @@
|
|||
import { EXECUTOR_SHEET_NAMES } from '../../core/constants';
|
||||
import { askUser } from '../../core/ui';
|
||||
import { getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { loadConfig, saveConfig } from '../../core/mail/executorTables';
|
||||
import { sendExecutorNotification } from './executorEmail';
|
||||
|
||||
const EXECUTOR_SHEET_HEADERS = [
|
||||
'Название задачи',
|
||||
'Название родительской задачи',
|
||||
'ID Р. задачи',
|
||||
'ID задачи',
|
||||
'Исполнитель',
|
||||
'Постановщик',
|
||||
'Элемент CRM',
|
||||
'Большая или мелкая',
|
||||
'Крайний срок Р. задачи',
|
||||
'Крайний срок задачи',
|
||||
'Дата создания подзадачи',
|
||||
'Время выполнения',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
'Требует внимания',
|
||||
'Комментарий исполнителя',
|
||||
'Комментарий руководителя',
|
||||
'Расшифровка кода',
|
||||
'Расшифровка кода для столбца Название родительской задачи'
|
||||
];
|
||||
|
||||
export function distributeTasksToExecutors(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const reportSheet = SpreadsheetApp.getActiveSheet();
|
||||
|
||||
if (!reportSheet) {
|
||||
throw new Error('Лист Итог не найден');
|
||||
}
|
||||
|
||||
const data = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = data[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((h, i) => {
|
||||
col[String(h)] = i;
|
||||
});
|
||||
|
||||
const rows = data.slice(1);
|
||||
const config = loadConfig();
|
||||
const usersMap = getUserEmailMap();
|
||||
const grouped: Record<string, any[][]> = {};
|
||||
|
||||
rows.forEach(row => {
|
||||
const attention = String(row[col['Требует внимания']] || '');
|
||||
|
||||
if (!attention.startsWith('Да')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
const taskSetter = String(row[col['Постановщик']] || '').trim();
|
||||
|
||||
if (!executor) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
executor != taskSetter &&
|
||||
!(attention.toLowerCase().includes('время завершения') ||
|
||||
attention.toLowerCase().includes('длительность задачи'))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!grouped[executor]) {
|
||||
grouped[executor] = [];
|
||||
}
|
||||
|
||||
grouped[executor].push(row);
|
||||
});
|
||||
|
||||
Object.keys(grouped).forEach(executor => {
|
||||
let spreadsheetId = config[executor];
|
||||
let spreadsheet: GoogleAppsScript.Spreadsheet.Spreadsheet | null = null;
|
||||
|
||||
if (spreadsheetId) {
|
||||
try {
|
||||
spreadsheet = SpreadsheetApp.openById(spreadsheetId);
|
||||
} catch (_e) {
|
||||
spreadsheet = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!spreadsheet) {
|
||||
spreadsheet = SpreadsheetApp.create('Задачи - ' + executor);
|
||||
spreadsheetId = spreadsheet.getId();
|
||||
config[executor] = spreadsheetId;
|
||||
}
|
||||
|
||||
const sheet = prepareExecutorSpreadsheet(spreadsheet, grouped[executor]);
|
||||
sendExecutorNotification({ executor, spreadsheet, usersMap, sheet });
|
||||
});
|
||||
|
||||
saveConfig(config);
|
||||
}
|
||||
|
||||
function prepareExecutorSpreadsheet(
|
||||
spreadsheet: GoogleAppsScript.Spreadsheet.Spreadsheet,
|
||||
rows: any[][]
|
||||
) {
|
||||
const SHEET_NAME = EXECUTOR_SHEET_NAMES.bigSmallQuestions;
|
||||
let sheet = spreadsheet.getSheetByName(SHEET_NAME);
|
||||
|
||||
if (!sheet) {
|
||||
sheet = spreadsheet.insertSheet(SHEET_NAME);
|
||||
}
|
||||
|
||||
sheet.clearContents();
|
||||
|
||||
const result = [
|
||||
EXECUTOR_SHEET_HEADERS,
|
||||
...rows
|
||||
];
|
||||
|
||||
sheet
|
||||
.getRange(1, 1, result.length, result[0].length)
|
||||
.setValues(result);
|
||||
|
||||
sheet.autoResizeColumns(1, result[0].length);
|
||||
|
||||
return sheet;
|
||||
}
|
||||
|
||||
export function loadExecutorComments(): void {
|
||||
const SHEET_NAME = 'Вопросы по большим и малым задачам';
|
||||
const config = loadConfig();
|
||||
const commentsMap: Record<string, any> = {};
|
||||
|
||||
Object.keys(config).forEach(executor => {
|
||||
const spreadsheetId = config[executor];
|
||||
|
||||
try {
|
||||
const ss = SpreadsheetApp.openById(spreadsheetId);
|
||||
const sheet = ss.getSheetByName(SHEET_NAME);
|
||||
const data = sheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = data[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((h, i) => {
|
||||
col[String(h)] = i;
|
||||
});
|
||||
|
||||
data.slice(1).forEach(row => {
|
||||
const taskId = row[col['ID задачи']];
|
||||
const comment = row[col['Комментарий исполнителя']];
|
||||
|
||||
if (taskId && comment) {
|
||||
commentsMap[String(taskId)] = comment;
|
||||
}
|
||||
});
|
||||
} catch (_e) {
|
||||
Logger.log('Ошибка чтения таблицы: ' + executor);
|
||||
}
|
||||
});
|
||||
|
||||
updateMainReportComments(commentsMap);
|
||||
}
|
||||
|
||||
function updateMainReportComments(commentsMap: Record<string, any>): void {
|
||||
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const data = sheet.getDataRange().getValues();
|
||||
const headers = data[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((h, i) => {
|
||||
col[String(h)] = i;
|
||||
});
|
||||
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const row = data[i];
|
||||
const attention = String(row[col['Требует внимания']] || '');
|
||||
|
||||
if (!attention.startsWith('Да')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const taskId = String(row[col['ID задачи']] || '');
|
||||
if (!taskId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const comment = commentsMap[taskId];
|
||||
if (comment !== undefined) {
|
||||
sheet.getRange(i + 1, col['Комментарий исполнителя'] + 1).setValue(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
export function sendExecutorNotification(params: {
|
||||
executor: string;
|
||||
spreadsheet: GoogleAppsScript.Spreadsheet.Spreadsheet;
|
||||
usersMap: Record<string, string>;
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet;
|
||||
}): void {
|
||||
const { executor, spreadsheet, usersMap, sheet } = params;
|
||||
const userEmail = usersMap[executor];
|
||||
|
||||
if (!userEmail) {
|
||||
Logger.log('Не найден email для: ' + executor);
|
||||
return;
|
||||
}
|
||||
|
||||
if (userEmail == '') {
|
||||
Logger.log('Пустой email для: ' + executor);
|
||||
return;
|
||||
}
|
||||
|
||||
const url = spreadsheet.getUrl() + '#gid=' + sheet.getSheetId();
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: userEmail,
|
||||
subject: 'Требуют внимания задачи',
|
||||
body: `
|
||||
Здравствуйте.
|
||||
|
||||
В вашу таблицу добавлены задачи, требующие внимания.
|
||||
|
||||
Ссылка:
|
||||
${url}
|
||||
|
||||
Это автоматическое уведомление.
|
||||
`,
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { createBigSmallTasksReport } from './main';
|
||||
import { distributeTasksToExecutors, loadExecutorComments } from './commentService';
|
||||
import { exportFinalReport } from './sendReport';
|
||||
|
||||
export const bigSmallPlugin: ReportPlugin = {
|
||||
id: 'bigSmall',
|
||||
menuTitle: '1️⃣ 📊 Большие и малые задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createBigSmallTasksReport' },
|
||||
{ label: '📤 Отправить исполнителям', functionName: 'distributeTasksToExecutors' },
|
||||
{ label: '💬 Получить комментарии исполнителей', functionName: 'loadExecutorComments' },
|
||||
{ label: '👔 Отправить руководителю', functionName: 'exportFinalReport' },
|
||||
],
|
||||
handlers: {
|
||||
createBigSmallTasksReport,
|
||||
distributeTasksToExecutors,
|
||||
loadExecutorComments,
|
||||
exportFinalReport,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'MANAGER_TABLES_CONFIG_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { getSourceSheet } from '../../core/config';
|
||||
import { requestDate } from '../../core/ui';
|
||||
import { decodeTaskCodes } from '../../core/taskCodes';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
import { buildBigSmallReportRows } from './builder';
|
||||
|
||||
export function createBigSmallTasksReport(): void {
|
||||
const reportPrefix = REPORT_PREFIXES.bigSmall;
|
||||
const lastLaunch = requestDate('Введите дату формирования предыдущего отчета по большим и малым задачам');
|
||||
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const data = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
throw new Error('Нет данных');
|
||||
}
|
||||
|
||||
const finalData = buildBigSmallReportRows(data.slice(1), data[0], lastLaunch, new Date());
|
||||
const sheet = createTimestampedSheet(reportPrefix, ss);
|
||||
sheet
|
||||
.getRange(1, 1, finalData.length, finalData[0].length)
|
||||
.setValues(finalData);
|
||||
decodeTaskCodes(sheet);
|
||||
decodeTaskCodes(sheet, 'Название родительской задачи');
|
||||
setReportSheetFormat(sheet);
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import { askUser } from '../../core/ui';
|
||||
import { getEmailConfig } from '../../core/mail/emailConfig';
|
||||
import { exportSheetToPdf } from '../../core/sheets/export';
|
||||
|
||||
export function exportFinalReport(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const sourceSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = sourceSpreadsheet.getActiveSheet();
|
||||
const sourceSheetName = sourceSheet.getName();
|
||||
const reportEmailsConfig = getEmailConfig(sourceSpreadsheet);
|
||||
const reportEmails = Object.values(reportEmailsConfig).filter(value => value !== '');
|
||||
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Лист Итог не найден');
|
||||
}
|
||||
|
||||
const pdfBlob = exportSheetToPdf(
|
||||
sourceSpreadsheet.getId(),
|
||||
sourceSheet.getSheetId(),
|
||||
sourceSheet.getName()
|
||||
);
|
||||
|
||||
const spreadsheetUrl =
|
||||
sourceSpreadsheet.getUrl() + '#gid=' + sourceSheet.getSheetId();
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: reportEmails.join(','),
|
||||
subject: 'Новый отчет по задачам',
|
||||
body: `
|
||||
Здравствуйте.
|
||||
|
||||
Сформирован новый отчет по большим и малым задачам.
|
||||
|
||||
Ссылка на таблицу:
|
||||
${spreadsheetUrl}
|
||||
|
||||
Лист:
|
||||
${sourceSheetName}
|
||||
|
||||
PDF-версия отчета приложена к письму.
|
||||
|
||||
Это автоматическое уведомление.
|
||||
`,
|
||||
attachments: [pdfBlob]
|
||||
});
|
||||
|
||||
Logger.log('Отчет отправлен');
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import { getBitrixMethodUrl } from '../../core/config';
|
||||
import { fetchBalancer } from '../../core/bitrix/client';
|
||||
import { bitrixBooleanToString } from '../../core/taskCodes';
|
||||
import { diffMinutes, formatIsoLocal } from '../../core/dates';
|
||||
|
||||
export function getYesterdayClosedTasksByPerformers(performerNames: string[], afterDate: Date) {
|
||||
const tasks = loadClosedAfterTasks(afterDate);
|
||||
const performerSet = new Set(performerNames);
|
||||
const result = new Map<string, any[]>();
|
||||
|
||||
performerNames.forEach(name => {
|
||||
result.set(name, []);
|
||||
});
|
||||
|
||||
tasks.forEach((task: any) => {
|
||||
const performerName = task.responsible?.name;
|
||||
if (!performerName || !performerSet.has(performerName)) return;
|
||||
|
||||
result.get(performerName).push({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
createdDate: new Date(task.createdDate),
|
||||
deadline: new Date(task.deadline),
|
||||
creator: task.creator.name,
|
||||
responsible: task.responsible.name,
|
||||
status: task.status,
|
||||
timeEstimate: diffMinutes(new Date(task.startDatePlan), new Date(task.endDatePlan)) * 60,
|
||||
clientLoss: bitrixBooleanToString(task.ufAuto738863346313),
|
||||
price: task.ufAuto392526971904,
|
||||
taskControl: task.taskControl,
|
||||
completedDate: task.closedDate ? new Date(task.closedDate) : ''
|
||||
});
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function loadClosedAfterTasks(afterDate: Date): any[] {
|
||||
const result = fetchBalancer(
|
||||
getBitrixMethodUrl('tasks', 'tasks.task.list'),
|
||||
{
|
||||
isRecurrent: true,
|
||||
resultKey: 'tasks',
|
||||
body: {
|
||||
filter: {
|
||||
'>=CLOSED_DATE': getDateString(afterDate),
|
||||
'<CLOSED_DATE': getDateString(new Date()),
|
||||
STATUS: 5
|
||||
},
|
||||
select: [
|
||||
'ID', 'TITLE', 'CREATED_DATE', 'DEADLINE', 'CREATED_BY',
|
||||
'RESPONSIBLE_ID', 'STATUS', 'CLOSED_DATE', 'TIME_ESTIMATE',
|
||||
'TASK_CONTROL', 'START_DATE_PLAN', 'END_DATE_PLAN',
|
||||
'UF_AUTO_738863346313', 'UF_AUTO_392526971904'
|
||||
]
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return (result.data && result.data.body) || [];
|
||||
}
|
||||
|
||||
function getDateString(date: Date): string {
|
||||
const startOfDay = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
|
||||
return formatIsoLocal(startOfDay);
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { buildCompletedTasksReport } from './main';
|
||||
import { notifyCompletedTasks } from './notifyFilialHead';
|
||||
import { notifySalesDepartmentHead } from './notifySalesHead';
|
||||
|
||||
export const completedPlugin: ReportPlugin = {
|
||||
id: 'completed',
|
||||
menuTitle: '6️⃣ ✅ Завершенные задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'buildCompletedTasksReport' },
|
||||
{ label: '👔 Отправить отчет рукфилу', functionName: 'notifyCompletedTasks' },
|
||||
{ label: '👔 Отправить отчет РОПу', functionName: 'notifySalesDepartmentHead' },
|
||||
],
|
||||
handlers: {
|
||||
buildCompletedTasksReport,
|
||||
notifyCompletedTasks,
|
||||
notifySalesDepartmentHead,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'ORG_STRUCTURE_FILE_ID',
|
||||
'DEPARTMENT_ID',
|
||||
'DEFAULT_FILIAL_HEAD_NAME',
|
||||
'BITRIX_PORTAL',
|
||||
'BALANCER_URL',
|
||||
],
|
||||
requiredScriptProperties: [
|
||||
'BALANCER_PUBLIC',
|
||||
'BALANCER_SECRET',
|
||||
'BITRIX_WEBHOOK_TASKS',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,393 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { getAppConfig, getSourceSheet } from '../../core/config';
|
||||
import { requestDate } from '../../core/ui';
|
||||
import { decodeTaskCodes, getTaskStatusName } from '../../core/taskCodes';
|
||||
import { 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 { getYesterdayClosedTasksByPerformers } from './fetchCompletedTasks';
|
||||
|
||||
const REPORT_HEADERS = [
|
||||
'ID задачи', 'Наименование задачи', 'Дата создания', 'Крайний срок задачи',
|
||||
'Постановщик', 'Исполнитель', 'Руководитель филиала', 'Статус',
|
||||
'Планируемая длительность', 'Ведет к потере клиента', 'Цена задачи', 'Дата завершения'
|
||||
];
|
||||
|
||||
const TASK_FIELDS = {
|
||||
id: 'ID задачи',
|
||||
title: 'Наименование задачи',
|
||||
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);
|
||||
generateReport(executors);
|
||||
} 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]))];
|
||||
}
|
||||
|
||||
function loadCompletedTasks(afterDate: Date) {
|
||||
return getYesterdayClosedTasksByPerformers(getAllExecutorNames(), afterDate);
|
||||
}
|
||||
|
||||
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 generateReport(executors: Record<string, any>): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheet = createTimestampedSheet(REPORT_PREFIXES.completed, ss);
|
||||
let row = 1;
|
||||
|
||||
sheet.getRange(row, 1, 1, REPORT_HEADERS.length)
|
||||
.setValues([REPORT_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);
|
||||
if (toWrite.length == 0) return;
|
||||
|
||||
sheet.getRange(row, 1, toWrite.length, REPORT_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);
|
||||
setupConditionalFormatting(sheet);
|
||||
const standardWidth = sheet.getColumnWidth(1);
|
||||
sheet.autoResizeColumns(1, sheet.getDataRange().getNumColumns());
|
||||
sheet.setColumnWidth(2, standardWidth * 7);
|
||||
metricsStorage.sortSheet();
|
||||
}
|
||||
|
||||
function createTaskArray(executor: any): any[][] {
|
||||
return executor.reportTasks.map((task: any) => [
|
||||
task.id,
|
||||
task.title,
|
||||
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 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, ['Исполнитель', 'Руководитель филиала']);
|
||||
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]));
|
||||
sheet.getRange(startRow, 2, data.length, 2)
|
||||
.setValues(data)
|
||||
.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, 3, 1, 1).setDataValidation(rule);
|
||||
}
|
||||
|
||||
function setupConditionalFormatting(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const MARKER = 'Оценка руководителя филиала (1-5):';
|
||||
const lastRow = sheet.getLastRow();
|
||||
const values = sheet.getRange(1, 2, lastRow, 1).getValues();
|
||||
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($C$${percentRow};"^\\d+"))<50;` +
|
||||
`$C$${scoreRow}<4` +
|
||||
`)`;
|
||||
|
||||
rules.push(
|
||||
SpreadsheetApp.newConditionalFormatRule()
|
||||
.whenFormulaSatisfied(formula)
|
||||
.setBackground('#ff0000')
|
||||
.setRanges([sheet.getRange(row + 1, 3), sheet.getRange(row + 2, 3)])
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
sheet.setConditionalFormatRules(rules);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
import { notifyReportRecievers } from '../../core/mail/notify';
|
||||
|
||||
export function notifyCompletedTasks(): void {
|
||||
const additionalText = 'Необходимо выставить оценку менеджеру и если процент выполнения меньше 50% или оценка менеджеру меньше 4, то необходимо прописать комментарий руководителя филиала почему такая низкая оценка или почему такой высокий процент отклоненных постановщиком задач и сформировать себе задачу в битрикс по исправлению ситуации.';
|
||||
notifyReportRecievers('Отчет по Завершенным задачам', additionalText);
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
import { askUser } from '../../core/ui';
|
||||
import { getEmailConfig } from '../../core/mail/emailConfig';
|
||||
import { pickRoleEmail, sendMail } from '../../core/mail/notify';
|
||||
import { exportSheetToPdf } from '../../core/sheets/export';
|
||||
import { getColumnIndexesByName } from '../../core/sheets/reportLifecycle';
|
||||
import { MetricsStorage } from '../../core/metrics/storage';
|
||||
|
||||
function validateBlocks() {
|
||||
const sheet = SpreadsheetApp.getActiveSheet();
|
||||
const MARKER = 'Оценка руководителя филиала (1-5):';
|
||||
const [executorCol, filialHeadCol] = getColumnIndexesByName(1, ['Исполнитель', 'Руководитель филиала']);
|
||||
|
||||
if (executorCol === -1 || filialHeadCol === -1) {
|
||||
return {
|
||||
valid: false,
|
||||
errors: 'Не найдены столбцы "Исполнитель" или "Руководитель филиала"'
|
||||
};
|
||||
}
|
||||
|
||||
const lastRow = sheet.getLastRow();
|
||||
const columnB = sheet.getRange(1, 2, lastRow, 1).getValues();
|
||||
const errors: string[] = [];
|
||||
const metricsStorage = new MetricsStorage();
|
||||
const now = new Date();
|
||||
|
||||
for (let row = 1; row <= lastRow; row++) {
|
||||
if (columnB[row - 1][0] !== MARKER) continue;
|
||||
|
||||
const percentRow = row - 4;
|
||||
const scoreRow = row;
|
||||
const commentRow = row + 1;
|
||||
const taskRow = row + 2;
|
||||
const infoRow = percentRow - 1;
|
||||
|
||||
const executor = sheet.getRange(infoRow, executorCol).getDisplayValue().trim();
|
||||
const filialHead = sheet.getRange(infoRow, filialHeadCol).getDisplayValue().trim();
|
||||
const personInfo = `"${filialHead}","${executor}"`;
|
||||
const percentValue = sheet.getRange(percentRow, 3).getDisplayValue().trim();
|
||||
const scoreValue = sheet.getRange(scoreRow, 3).getDisplayValue().trim();
|
||||
const commentValue = sheet.getRange(commentRow, 3).getDisplayValue().trim();
|
||||
const taskValue = sheet.getRange(taskRow, 3).getDisplayValue().trim();
|
||||
|
||||
if (!scoreValue) {
|
||||
errors.push(`${personInfo}: не заполнена оценка `);
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = percentValue.match(/^(\d+)/);
|
||||
const percent = match ? Number(match[1]) : 0;
|
||||
const score = Number(scoreValue);
|
||||
metricsStorage.updateMetric(now, executor, 'efficiency', score);
|
||||
|
||||
if (percent < 50 || score < 4) {
|
||||
if (!commentValue) errors.push(`${personInfo}: не заполнен комментарий `);
|
||||
if (!taskValue) errors.push(`${personInfo}: не заполнен ID задачи руководителя `);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors: errors.join('\n')
|
||||
};
|
||||
}
|
||||
|
||||
export function notifySalesDepartmentHead(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const validationResult = validateBlocks();
|
||||
if (!validationResult.valid) {
|
||||
SpreadsheetApp.getUi().alert(validationResult.errors);
|
||||
return;
|
||||
}
|
||||
|
||||
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheet = spreadsheet.getActiveSheet();
|
||||
const emailConfig = getEmailConfig(spreadsheet);
|
||||
const mainEmail = pickRoleEmail(
|
||||
emailConfig,
|
||||
'salesDepartmentHeadEmail',
|
||||
'salesDepartmentDeputyEmail'
|
||||
);
|
||||
|
||||
if (!mainEmail) {
|
||||
SpreadsheetApp.getUi().alert('Не заполнены email РОПа или его заместителя');
|
||||
return;
|
||||
}
|
||||
|
||||
const pdfBlob = exportSheetToPdf(spreadsheet.getId(), sheet.getSheetId(), sheet.getName());
|
||||
const spreadsheetUrl = spreadsheet.getUrl() + '#gid=' + sheet.getSheetId();
|
||||
sendMail(mainEmail, 'Отчет по завершенным задачам', spreadsheetUrl, pdfBlob);
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { exportActualTasks } from './main';
|
||||
|
||||
export const currentTasksPlugin: ReportPlugin = {
|
||||
id: 'currentTasks',
|
||||
menuTitle: '8️⃣ 📋 Актуальные задачи менеджеров (вечер)',
|
||||
menuItems: [
|
||||
{ label: '📤 Отправить менеджерам', functionName: 'exportActualTasks' },
|
||||
],
|
||||
handlers: { exportActualTasks },
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'MANAGER_TABLES_CONFIG_ID',
|
||||
'BITRIX_PORTAL',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
import { EXECUTOR_SHEET_NAMES } from '../../core/constants';
|
||||
import { getBitrixTaskViewUrl, getSourceSheet } from '../../core/config';
|
||||
import { askUser } from '../../core/ui';
|
||||
import { getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { loadConfig } from '../../core/mail/executorTables';
|
||||
import { diffMinutes } from '../../core/dates';
|
||||
import { setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
import { MetricsStorage } from '../../core/metrics/storage';
|
||||
|
||||
function resetTime(date: Date): Date {
|
||||
const result = new Date(date);
|
||||
result.setHours(0, 0, 0, 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function exportActualTasks(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const sourceSheet = getSourceSheet();
|
||||
const data = sourceSheet.getDataRange().getValues();
|
||||
const headers = data.shift();
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((h, i) => {
|
||||
col[String(h)] = i;
|
||||
});
|
||||
|
||||
const executorTasks: Record<string, any[]> = {};
|
||||
|
||||
data.forEach(row => {
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
if (status == 'Завершена' || status == 'Ждёт контроля') return;
|
||||
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
if (!executor) return;
|
||||
|
||||
const startDate = row[col['Планируемая дата начала']];
|
||||
const endDate = row[col['Планируемая дата окончания']];
|
||||
const tomorrow = resetTime(new Date());
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
|
||||
if (resetTime(startDate) > tomorrow || resetTime(endDate) < tomorrow) return;
|
||||
|
||||
if (!executorTasks[executor]) executorTasks[executor] = [];
|
||||
executorTasks[executor].push({
|
||||
id: row[col['ID']],
|
||||
title: row[col['Название']],
|
||||
created: row[col['Дата создания']],
|
||||
deadline: row[col['Крайний срок']],
|
||||
creator: row[col['Постановщик']],
|
||||
executor,
|
||||
crm: row[col['CRM']],
|
||||
status,
|
||||
startDate,
|
||||
endDate,
|
||||
duration: diffMinutes(startDate, endDate),
|
||||
danger: row[col['Может привести к потере клиента']]
|
||||
});
|
||||
});
|
||||
|
||||
const config = loadConfig();
|
||||
const emailMap = getUserEmailMap();
|
||||
const metricsStorage = new MetricsStorage();
|
||||
const now = new Date();
|
||||
const SHEET_NAME = EXECUTOR_SHEET_NAMES.actualTasks;
|
||||
|
||||
Object.entries(executorTasks).forEach(([executor, tasks]) => {
|
||||
const spreadsheetId = config[executor];
|
||||
if (!spreadsheetId) {
|
||||
Logger.log('Не найдена таблица: ' + executor);
|
||||
return;
|
||||
}
|
||||
if (!tasks || tasks.length == 0) return;
|
||||
|
||||
metricsStorage.updateMetric(now, executor, 'totalTasks', tasks.length);
|
||||
|
||||
tasks.sort((a, b) => {
|
||||
const va = String(a.danger).toLowerCase() == 'да' ? 1 : 0;
|
||||
const vb = String(b.danger).toLowerCase() == 'да' ? 1 : 0;
|
||||
if (va != vb) return vb - va;
|
||||
|
||||
const da = a.startDate instanceof Date ? a.startDate.getTime() : new Date(a.startDate).getTime();
|
||||
const db = b.startDate instanceof Date ? b.startDate.getTime() : new Date(b.startDate).getTime();
|
||||
return da - db;
|
||||
});
|
||||
|
||||
const ss = SpreadsheetApp.openById(spreadsheetId);
|
||||
let sheet = ss.getSheetByName(SHEET_NAME);
|
||||
if (!sheet) sheet = ss.insertSheet(SHEET_NAME);
|
||||
sheet.clear();
|
||||
sheet.clearFormats();
|
||||
|
||||
sheet.getRange(1, 1, 1, 11).setValues([[
|
||||
'ID задачи/ссылка', 'Наименование задачи', 'Дата создания', 'Крайний срок задачи',
|
||||
'Постановщик', 'Исполнитель', 'CRM', 'Планируемая дата начала',
|
||||
'Планируемая дата завершения', 'Планируемая длительность', 'Ведет к потере клиента'
|
||||
]]);
|
||||
|
||||
const values: any[][] = [];
|
||||
const richTexts: any[][] = [];
|
||||
let total = 0;
|
||||
|
||||
tasks.forEach(task => {
|
||||
values.push([
|
||||
task.title, task.created, task.deadline, task.creator, task.executor,
|
||||
task.crm, task.startDate, task.endDate, task.duration, task.danger
|
||||
]);
|
||||
richTexts.push([
|
||||
SpreadsheetApp.newRichTextValue()
|
||||
.setText(String(task.id))
|
||||
.setLinkUrl(getBitrixTaskViewUrl(task.id))
|
||||
.build()
|
||||
]);
|
||||
total += Number(task.duration) || 0;
|
||||
});
|
||||
|
||||
if (values.length) {
|
||||
sheet.getRange(2, 2, values.length, values[0].length).setValues(values);
|
||||
setReportSheetFormat(sheet);
|
||||
sheet.getRange(2, 1, richTexts.length, 1).setRichTextValues(richTexts);
|
||||
}
|
||||
|
||||
metricsStorage.sortSheet();
|
||||
const totalRow = values.length + 2;
|
||||
sheet.getRange(totalRow, 8).setValue('Итого времени:');
|
||||
sheet.getRange(totalRow, 9).setValue(total);
|
||||
sheet.autoResizeColumns(1, 10);
|
||||
|
||||
const email = emailMap[executor];
|
||||
if (email) {
|
||||
MailApp.sendEmail({
|
||||
to: email,
|
||||
subject: 'Актуальные задачи',
|
||||
htmlBody:
|
||||
'Здравствуйте.<br><br>' +
|
||||
'Ваш список актуальных задач доступен по ссылке:<br><br>' +
|
||||
'<a href="' + ss.getUrl() + '#gid=' + sheet.getSheetId() + '">' +
|
||||
'Открыть лист "Актуальные задачи"</a>'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { showDateRangeDialog, repPreviousWeek, saveDateRange } from './main';
|
||||
import { sendEffectivenessReport } from './sendReport';
|
||||
|
||||
export const effectivenessPlugin: ReportPlugin = {
|
||||
id: 'effectiveness',
|
||||
menuTitle: '9️⃣ 🆕 Лист эффективности',
|
||||
menuItems: [
|
||||
{ label: '📆 Отчет за диапазон', functionName: 'showDateRangeDialog' },
|
||||
{ label: '📆 Отчет за предыдущую неделю', functionName: 'repPreviousWeek' },
|
||||
{ label: '👔 Отправить отчет рукфилу и РОПу', functionName: 'sendEffectivenessReport' },
|
||||
],
|
||||
handlers: {
|
||||
showDateRangeDialog,
|
||||
saveDateRange,
|
||||
repPreviousWeek,
|
||||
sendEffectivenessReport,
|
||||
},
|
||||
htmlFiles: ['DateRangeDialog.html'],
|
||||
requiredConfigKeys: [
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
import { MetricsReport } from './reportBuilder';
|
||||
|
||||
export function createEffectivenessReport(startDate: Date, endDate: Date): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sheet = createTimestampedSheet(REPORT_PREFIXES.effectiveness, ss);
|
||||
new MetricsReport(sheet.getName()).build(startDate, endDate);
|
||||
setReportSheetFormat(sheet, false);
|
||||
sheet.autoResizeColumns(1, sheet.getDataRange().getNumColumns());
|
||||
}
|
||||
|
||||
export function showDateRangeDialog(): void {
|
||||
const html = HtmlService.createHtmlOutputFromFile('DateRangeDialog')
|
||||
.setWidth(420)
|
||||
.setHeight(600);
|
||||
SpreadsheetApp.getUi().showModalDialog(html, 'Выберите диапазон дат');
|
||||
}
|
||||
|
||||
export function saveDateRange(startDate: string, endDate: string): void {
|
||||
createEffectivenessReport(new Date(startDate), new Date(endDate));
|
||||
}
|
||||
|
||||
export function repPreviousWeek(): void {
|
||||
const weekDays = getPreviousWeekDates();
|
||||
createEffectivenessReport(weekDays.monday, weekDays.sunday);
|
||||
}
|
||||
|
||||
function getPreviousWeekDates() {
|
||||
const today = new Date();
|
||||
const day = today.getDay();
|
||||
const diffToMonday = day === 0 ? -6 : 1 - day;
|
||||
const monday = new Date(today);
|
||||
monday.setDate(today.getDate() + diffToMonday - 7);
|
||||
monday.setHours(0, 0, 0, 0);
|
||||
const sunday = new Date(monday);
|
||||
sunday.setDate(monday.getDate() + 6);
|
||||
sunday.setHours(23, 59, 59, 999);
|
||||
return { monday, sunday };
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { formatDate } from '../../core/dates';
|
||||
import { MetricsStorage } from '../../core/metrics/storage';
|
||||
|
||||
const DAYS = ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'];
|
||||
|
||||
export function formatRuDate(date: Date): string {
|
||||
const formatted = formatDate(date);
|
||||
return `${DAYS[date.getDay()]}, ${formatted.slice(0, 5)}`;
|
||||
}
|
||||
|
||||
export function formatDateRange(startDate: Date, endDate: Date): string[] {
|
||||
const dates: string[] = [];
|
||||
const current = new Date(startDate);
|
||||
while (current <= endDate) {
|
||||
dates.push(formatRuDate(current));
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
export class MetricsReport {
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet;
|
||||
storage: MetricsStorage;
|
||||
metrics: Array<{ title: string; field: string }>;
|
||||
columns: Record<string, number>;
|
||||
|
||||
constructor(reportSheet = 'Отчет') {
|
||||
this.sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(reportSheet);
|
||||
this.storage = new MetricsStorage();
|
||||
this.metrics = [
|
||||
{ title: 'Общее количество завершенных задач', field: 'completed' },
|
||||
{ title: 'Количество завершенных задач, требующих приемки', field: 'reviewCompleted' },
|
||||
{ title: 'Количество принятых задач, требующих приемки', field: 'reviewAccepted' },
|
||||
{ title: 'Эффективность по требующим приемки', field: 'reviewPercent' },
|
||||
{ title: 'Суммарно эффективно затраченное время за вчера', field: 'spentHours' },
|
||||
{ title: 'Количество просроченных и потом перенсенных задач на сегодня', field: 'overdue' },
|
||||
{ title: 'Количество новых задач самому себе за вчера', field: 'newTasks' },
|
||||
{ title: 'Количество задач в работе со сроком на сегодня', field: 'todayTasks' },
|
||||
{ title: 'Суммарное время, которое сотрудник потратит на выполнение этих задач в часах', field: 'todayHours' },
|
||||
{ title: 'Согласовано ли общее время и количество задач на сегодня руководителем', field: 'approved' },
|
||||
{ title: 'Общее количество задач в работе', field: 'totalTasks' },
|
||||
{ title: 'Оценка эффективности сотрудника от руководителя', field: 'efficiency' }
|
||||
];
|
||||
this.columns = {
|
||||
date: 0, executor: 1, efficiency: 2, completed: 3, returned: 4,
|
||||
completedPercent: 5, reviewCompleted: 6, reviewAccepted: 7, reviewPercent: 8,
|
||||
spentHours: 9, overdue: 10, newTasks: 11, todayTasks: 12, approved: 13,
|
||||
todayHours: 14, totalTasks: 15
|
||||
};
|
||||
}
|
||||
|
||||
build(fromDate: Date, toDate: Date): void {
|
||||
const rows = this.storage.getRange(fromDate, toDate);
|
||||
const executors: string[] = [];
|
||||
const allDates = formatDateRange(fromDate, toDate);
|
||||
const map: Record<string, any> = {};
|
||||
|
||||
rows.forEach(row => {
|
||||
const executor = row[this.columns.executor];
|
||||
const date = formatRuDate(row[this.columns.date]);
|
||||
if (!map[executor]) {
|
||||
map[executor] = {};
|
||||
executors.push(executor);
|
||||
}
|
||||
if (!map[executor][date]) map[executor][date] = {};
|
||||
this.metrics.forEach(metric => {
|
||||
map[executor][date][metric.field] = row[this.columns[metric.field]];
|
||||
});
|
||||
});
|
||||
|
||||
const result: any[][] = [['Сотрудник', 'Критерий', ...allDates, 'Среднее']];
|
||||
|
||||
executors.forEach(executor => {
|
||||
this.metrics.forEach(metric => {
|
||||
const line: any[] = [executor, metric.title];
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
|
||||
allDates.forEach(date => {
|
||||
let value = map[executor][date] ? map[executor][date][metric.field] : '';
|
||||
if (metric.field === 'completedPercent' || metric.field === 'reviewPercent') {
|
||||
value = Math.round(value * 10) / 10;
|
||||
line.push(value ? `${value}%` : '');
|
||||
} else {
|
||||
line.push(value);
|
||||
}
|
||||
|
||||
if (value && typeof value === 'number') {
|
||||
sum += value;
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
line.push(count ? Math.round(sum / count * 10) / 10 : '');
|
||||
result.push(line);
|
||||
});
|
||||
result.push(Array(result[0].length).fill(''));
|
||||
});
|
||||
|
||||
this.sheet.clearContents();
|
||||
this.sheet.getRange(1, 1, result.length, result[0].length).setValues(result);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { notifyReportRecieversSalesDepHead } from '../../core/mail/notify';
|
||||
|
||||
export function sendEffectivenessReport(): void {
|
||||
notifyReportRecieversSalesDepHead('Лист эффективности');
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
export function formatDeadlineOffset(secondsString: string | number, matchWorkTime: string): string {
|
||||
const seconds = parseInt(String(secondsString), 10);
|
||||
if (isNaN(seconds) || seconds <= 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (matchWorkTime === 'N') {
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const remaining = seconds % 86400;
|
||||
const hours = Math.floor(remaining / 3600);
|
||||
|
||||
if (days > 0 && hours > 0) return `${days} д, ${hours} ч`;
|
||||
if (days > 0) return `${days} д`;
|
||||
return `${hours} ч`;
|
||||
}
|
||||
|
||||
const workDaySeconds = 9 * 3600;
|
||||
const days = Math.floor(seconds / workDaySeconds);
|
||||
const remaining = seconds % workDaySeconds;
|
||||
const hours = Math.floor(remaining / 3600);
|
||||
|
||||
if (days > 0 && hours > 0) return `${days} раб. д, ${hours} раб. ч`;
|
||||
if (days > 0) return `${days} раб. д`;
|
||||
return `${hours} раб. ч`;
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import { getAppConfig } from '../../core/config';
|
||||
|
||||
export function getLatestTemplateID(): number {
|
||||
const response = UrlFetchApp.fetch(getAppConfig().templateScannerUrl);
|
||||
const result = JSON.parse(response.getContentText());
|
||||
return result.latest_template_id;
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { getBitrixMethodUrl } from '../../core/config';
|
||||
import { fetchBalancer } from '../../core/bitrix/client';
|
||||
|
||||
export function getTemplate(templateID: number) {
|
||||
const result = fetchBalancer(
|
||||
getBitrixMethodUrl('templates', 'tasks.template.get'),
|
||||
{
|
||||
includePublicKey: true,
|
||||
muteHttpExceptions: true,
|
||||
payloadHeaders: { 'Content-Type': 'application/json' },
|
||||
body: { templateId: templateID },
|
||||
}
|
||||
);
|
||||
|
||||
if (result.code !== 200) {
|
||||
throw new Error(JSON.stringify(result.data));
|
||||
}
|
||||
|
||||
const body = (result.data || {}).body;
|
||||
if (result.data.error || !body || !body.result || !body.result.ID) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return body.result;
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { createNewTemplatesRepors } from './main';
|
||||
import { notifyNewTemplates } from './reportSender';
|
||||
|
||||
export const newTemplatesPlugin: ReportPlugin = {
|
||||
id: 'newTemplates',
|
||||
menuTitle: '🔟 🆕 Новые шаблоны',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createNewTemplatesRepors' },
|
||||
{ label: '🔔 Уведомить РОПа', functionName: 'notifyNewTemplates' },
|
||||
],
|
||||
handlers: {
|
||||
createNewTemplatesRepors,
|
||||
notifyNewTemplates,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'TEMPLATE_SCAN_DEPARTMENT_ID',
|
||||
'TEMPLATE_SCANNER_URL',
|
||||
'BITRIX_PORTAL',
|
||||
'BALANCER_URL',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
],
|
||||
requiredScriptProperties: [
|
||||
'BALANCER_PUBLIC',
|
||||
'BALANCER_SECRET',
|
||||
'BITRIX_WEBHOOK_USERS',
|
||||
'BITRIX_WEBHOOK_TEMPLATES',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
import { TEMPLATE_SCAN } from '../../core/constants';
|
||||
import { getAppConfig } from '../../core/config';
|
||||
import { beforeHash } from '../../core/taskCodes';
|
||||
import { buildFullName, findDepartmentForUser, loadAllDepartmentUsers } from '../../core/bitrix/client';
|
||||
import { decodeReplicateParams } from './phpDecoder';
|
||||
import { decodeFullReplicationParams } from './replicationParamsParser';
|
||||
import { formatDeadlineOffset } from './deadlineOffsetParser';
|
||||
import { getLatestTemplateID } from './fetchLatestId';
|
||||
import { getTemplate } from './fetchTemplate';
|
||||
import { saveDepartmentSheets } from './sheetService';
|
||||
import { loadState, saveState } from './stateService';
|
||||
|
||||
export function createNewTemplatesRepors(): void {
|
||||
const state = loadState();
|
||||
const departmentId = getAppConfig().templateScanDepartmentId;
|
||||
const latestExistingID = getLatestTemplateID();
|
||||
|
||||
Logger.log(`Last local ID: ${state.lastTemplateId}`);
|
||||
Logger.log(`Latest API ID: ${latestExistingID}`);
|
||||
|
||||
const startID = state.lastTemplateId + TEMPLATE_SCAN.STEP;
|
||||
const endID = latestExistingID + TEMPLATE_SCAN.SAFETY_RANGE;
|
||||
|
||||
if (endID - startID > TEMPLATE_SCAN.MAX_IDS) {
|
||||
SpreadsheetApp.getUi().alert('Было создано слишком много шаблонов задач. Обратись в тех отдел для получения альтернативного инструмента контроля шаблонов.');
|
||||
return;
|
||||
}
|
||||
|
||||
const departmentRows: any[][] = [];
|
||||
const departmentUsersMap = loadAllDepartmentUsers([departmentId]);
|
||||
|
||||
for (let id = startID; id <= endID; id += TEMPLATE_SCAN.STEP) {
|
||||
try {
|
||||
const template = getTemplate(id);
|
||||
if (!template) {
|
||||
Utilities.sleep(TEMPLATE_SCAN.SLEEP_MS);
|
||||
continue;
|
||||
}
|
||||
|
||||
const responsibleID = Number(template.RESPONSIBLE_ID);
|
||||
const foundDepartmentId = findDepartmentForUser(responsibleID, departmentUsersMap);
|
||||
if (!foundDepartmentId || Number(foundDepartmentId) !== Number(departmentId)) {
|
||||
Utilities.sleep(TEMPLATE_SCAN.SLEEP_MS);
|
||||
continue;
|
||||
}
|
||||
|
||||
Logger.log(`FOUND template ${id}`);
|
||||
|
||||
let baseTemplate = null;
|
||||
if (template.BASE_TEMPLATE_ID !== '0') {
|
||||
baseTemplate = getTemplate(Number(template.BASE_TEMPLATE_ID));
|
||||
}
|
||||
|
||||
let appliedReplicationParams = template.REPLICATE_PARAMS;
|
||||
let baseTemplateID = '';
|
||||
let baseTemplateTitle = '';
|
||||
|
||||
if (baseTemplate) {
|
||||
appliedReplicationParams = baseTemplate.REPLICATE_PARAMS;
|
||||
baseTemplateID = baseTemplate.ID;
|
||||
baseTemplateTitle = baseTemplate.TITLE;
|
||||
}
|
||||
|
||||
const replicationParams = decodeReplicateParams(appliedReplicationParams);
|
||||
departmentRows.push([
|
||||
template.ID,
|
||||
template.TITLE,
|
||||
buildFullName(template.CREATED_BY_LAST_NAME, template.CREATED_BY_NAME, template.CREATED_BY_SECOND_NAME),
|
||||
buildFullName(template.RESPONSIBLE_LAST_NAME, template.RESPONSIBLE_NAME, template.RESPONSIBLE_SECOND_NAME),
|
||||
decodeFullReplicationParams(replicationParams),
|
||||
formatDeadlineOffset(template.DEADLINE_AFTER, template.MATCH_WORK_TIME),
|
||||
beforeHash(template.TITLE),
|
||||
'',
|
||||
baseTemplateID,
|
||||
baseTemplateTitle,
|
||||
'',
|
||||
]);
|
||||
} catch (e) {
|
||||
Logger.log(`Template ${id} error: ${e}`);
|
||||
}
|
||||
|
||||
Utilities.sleep(TEMPLATE_SCAN.SLEEP_MS);
|
||||
}
|
||||
|
||||
saveDepartmentSheets(departmentRows);
|
||||
saveState({ lastTemplateId: latestExistingID });
|
||||
Logger.log('Done.');
|
||||
}
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
export function phpUnserialize(data: string): any {
|
||||
let offset = 0;
|
||||
|
||||
function readUntil(stopChar: string): string {
|
||||
const start = offset;
|
||||
while (data[offset] !== stopChar) {
|
||||
offset++;
|
||||
}
|
||||
return data.substring(start, offset);
|
||||
}
|
||||
|
||||
function parse(): any {
|
||||
const type = data[offset];
|
||||
|
||||
if (type === 'N') {
|
||||
offset += 2;
|
||||
return null;
|
||||
}
|
||||
|
||||
offset += 2;
|
||||
|
||||
switch (type) {
|
||||
case 'b': {
|
||||
const value = readUntil(';');
|
||||
offset++;
|
||||
return value === '1';
|
||||
}
|
||||
case 'i': {
|
||||
const value = readUntil(';');
|
||||
offset++;
|
||||
return parseInt(value, 10);
|
||||
}
|
||||
case 'd': {
|
||||
const value = readUntil(';');
|
||||
offset++;
|
||||
return parseFloat(value);
|
||||
}
|
||||
case 's': {
|
||||
const len = parseInt(readUntil(':'), 10);
|
||||
offset += 2;
|
||||
const str = data.substr(offset, len);
|
||||
offset += len;
|
||||
offset += 2;
|
||||
return str;
|
||||
}
|
||||
case 'a': {
|
||||
const length = parseInt(readUntil(':'), 10);
|
||||
offset += 2;
|
||||
const result: Record<any, any> = {};
|
||||
const arr: any[] = [];
|
||||
let isArray = true;
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const key = parse();
|
||||
const value = parse();
|
||||
result[key] = value;
|
||||
if (typeof key !== 'number' || key !== arr.length) {
|
||||
isArray = false;
|
||||
} else {
|
||||
arr.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
offset++;
|
||||
return isArray ? arr : result;
|
||||
}
|
||||
default:
|
||||
throw new Error('Unsupported type: ' + type);
|
||||
}
|
||||
}
|
||||
|
||||
return parse();
|
||||
}
|
||||
|
||||
export function decodeReplicateParams(raw: string) {
|
||||
const decoded = phpUnserialize(raw);
|
||||
const params = {
|
||||
PERIOD: toString(decoded.PERIOD),
|
||||
EVERY_DAY: toInt(decoded.EVERY_DAY),
|
||||
WORKDAY_ONLY: toString(decoded.WORKDAY_ONLY),
|
||||
EVERY_WEEK: toInt(decoded.EVERY_WEEK),
|
||||
MONTHLY_TYPE: toInt(decoded.MONTHLY_TYPE),
|
||||
MONTHLY_DAY_NUM: toInt(decoded.MONTHLY_DAY_NUM),
|
||||
MONTHLY_MONTH_NUM_1: toInt(decoded.MONTHLY_MONTH_NUM_1),
|
||||
MONTHLY_WEEK_DAY_NUM: toInt(decoded.MONTHLY_WEEK_DAY_NUM),
|
||||
MONTHLY_WEEK_DAY: toInt(decoded.MONTHLY_WEEK_DAY),
|
||||
MONTHLY_MONTH_NUM_2: toInt(decoded.MONTHLY_MONTH_NUM_2),
|
||||
YEARLY_TYPE: toInt(decoded.YEARLY_TYPE),
|
||||
YEARLY_DAY_NUM: toInt(decoded.YEARLY_DAY_NUM),
|
||||
YEARLY_MONTH_1: toInt(decoded.YEARLY_MONTH_1),
|
||||
YEARLY_WEEK_DAY_NUM: toInt(decoded.YEARLY_WEEK_DAY_NUM),
|
||||
YEARLY_WEEK_DAY: toInt(decoded.YEARLY_WEEK_DAY),
|
||||
YEARLY_MONTH_2: toInt(decoded.YEARLY_MONTH_2),
|
||||
REPEAT_TILL: toString(decoded.REPEAT_TILL),
|
||||
TIMES: toInt(decoded.TIMES),
|
||||
END_DATE: toString(decoded.END_DATE),
|
||||
TIME: toString(decoded.TIME),
|
||||
WEEK_DAYS: [] as number[]
|
||||
};
|
||||
|
||||
const rawDays = decoded.WEEK_DAYS;
|
||||
if (rawDays !== undefined && rawDays !== null) {
|
||||
if (Array.isArray(rawDays)) {
|
||||
rawDays.forEach(v => params.WEEK_DAYS.push(toInt(v)));
|
||||
} else if (typeof rawDays === 'object') {
|
||||
Object.values(rawDays).forEach(v => params.WEEK_DAYS.push(toInt(v)));
|
||||
} else {
|
||||
params.WEEK_DAYS.push(toInt(rawDays));
|
||||
}
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
function toInt(v: any): number {
|
||||
if (v === null || v === undefined || v === '') return 0;
|
||||
return parseInt(v, 10) || 0;
|
||||
}
|
||||
|
||||
function toString(v: any): string {
|
||||
if (v === null || v === undefined) return '';
|
||||
return String(v);
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
const weekdays: Record<number, string> = {
|
||||
1: 'понедельник',
|
||||
2: 'вторник',
|
||||
3: 'среда',
|
||||
4: 'четверг',
|
||||
5: 'пятница',
|
||||
6: 'суббота',
|
||||
7: 'воскресенье',
|
||||
};
|
||||
|
||||
const weekdaysAccusative: Record<number, string> = {
|
||||
1: 'понедельник',
|
||||
2: 'вторник',
|
||||
3: 'среду',
|
||||
4: 'четверг',
|
||||
5: 'пятницу',
|
||||
6: 'субботу',
|
||||
7: 'воскресенье',
|
||||
};
|
||||
|
||||
const ordinalWeeks: Record<string, string> = {
|
||||
1: 'первый',
|
||||
2: 'второй',
|
||||
3: 'третий',
|
||||
4: 'четвертый',
|
||||
'-1': 'последний',
|
||||
};
|
||||
|
||||
const months: Record<number, string> = {
|
||||
0: 'января',
|
||||
1: 'февраля',
|
||||
2: 'марта',
|
||||
3: 'апреля',
|
||||
4: 'мая',
|
||||
5: 'июня',
|
||||
6: 'июля',
|
||||
7: 'августа',
|
||||
8: 'сентября',
|
||||
9: 'октября',
|
||||
10: 'ноября',
|
||||
11: 'декабря',
|
||||
};
|
||||
|
||||
const ordinalDays: Record<number, string> = {
|
||||
1: 'первого', 2: 'второго', 3: 'третьего', 4: 'четвертого', 5: 'пятого',
|
||||
6: 'шестого', 7: 'седьмого', 8: 'восьмого', 9: 'девятого', 10: 'десятого',
|
||||
11: 'одиннадцатого', 12: 'двенадцатого', 13: 'тринадцатого', 14: 'четырнадцатого',
|
||||
15: 'пятнадцатого', 16: 'шестнадцатого', 17: 'семнадцатого', 18: 'восемнадцатого',
|
||||
19: 'девятнадцатого', 20: 'двадцатого', 21: 'двадцать первого', 22: 'двадцать второго',
|
||||
23: 'двадцать третьего', 24: 'двадцать четвертого', 25: 'двадцать пятого',
|
||||
26: 'двадцать шестого', 27: 'двадцать седьмого', 28: 'двадцать восьмого',
|
||||
29: 'двадцать девятого', 30: 'тридцатого', 31: 'тридцать первого',
|
||||
};
|
||||
|
||||
export function decodeFullReplicationParams(p: any): string {
|
||||
try {
|
||||
const base = decodeReplicate(p);
|
||||
const till = decodeRepeatTill(p);
|
||||
const timeSt = decodeTime(p);
|
||||
if (!till) return base;
|
||||
return `${base} ${timeSt} (${till})`;
|
||||
} catch (_e) {
|
||||
return 'Не распознано';
|
||||
}
|
||||
}
|
||||
|
||||
function decodeReplicate(p: any): string {
|
||||
switch (p.PERIOD) {
|
||||
case 'daily': return decodeDaily(p);
|
||||
case 'weekly': return decodeWeekly(p);
|
||||
case 'monthly': return decodeMonthly(p);
|
||||
case 'yearly': return decodeYearly(p);
|
||||
default: return 'Неизвестный тип повторения';
|
||||
}
|
||||
}
|
||||
|
||||
function decodeDaily(p: any): string {
|
||||
if (p.WORKDAY_ONLY === 'Y') {
|
||||
if (p.EVERY_DAY <= 1) return 'Каждый рабочий день';
|
||||
return `Каждые ${p.EVERY_DAY} рабочих дня`;
|
||||
}
|
||||
if (p.EVERY_DAY <= 1) return 'Каждый день';
|
||||
return `Каждые ${p.EVERY_DAY} дня`;
|
||||
}
|
||||
|
||||
function decodeWeekly(p: any): string {
|
||||
if (!p.WEEK_DAYS || p.WEEK_DAYS.length === 0) return 'Повтор каждую неделю';
|
||||
|
||||
const daysStr = [...p.WEEK_DAYS]
|
||||
.sort((a: number, b: number) => a - b)
|
||||
.map((d: number) => weekdaysAccusative[d])
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
|
||||
if (p.EVERY_WEEK <= 1) return `Каждую неделю в ${daysStr}`;
|
||||
return `Каждые ${p.EVERY_WEEK} недели в ${daysStr}`;
|
||||
}
|
||||
|
||||
function decodeMonthly(p: any): string {
|
||||
switch (p.MONTHLY_TYPE) {
|
||||
case 1: {
|
||||
const interval = p.MONTHLY_MONTH_NUM_1;
|
||||
if (interval <= 1) return `${ordinalDay(p.MONTHLY_DAY_NUM)} числа каждого месяца`;
|
||||
return `${ordinalDay(p.MONTHLY_DAY_NUM)} числа каждые ${interval} месяца`;
|
||||
}
|
||||
case 2: {
|
||||
const week = ordinalWeeks[p.MONTHLY_WEEK_DAY_NUM];
|
||||
const day = weekdays[p.MONTHLY_WEEK_DAY];
|
||||
const interval = p.MONTHLY_MONTH_NUM_2;
|
||||
if (interval <= 1) return `${capitalize(week)} ${day} каждого месяца`;
|
||||
return `${capitalize(week)} ${day} каждые ${interval} месяца`;
|
||||
}
|
||||
}
|
||||
return 'Ежемесячное повторение';
|
||||
}
|
||||
|
||||
function decodeYearly(p: any): string {
|
||||
switch (p.YEARLY_TYPE) {
|
||||
case 1:
|
||||
return `Каждый год ${p.YEARLY_DAY_NUM} ${months[p.YEARLY_MONTH_1]}`;
|
||||
case 2:
|
||||
return `${capitalize(ordinalWeeks[p.YEARLY_WEEK_DAY_NUM])} ${weekdays[p.YEARLY_WEEK_DAY]} ${months[p.YEARLY_MONTH_2]} каждого года`;
|
||||
}
|
||||
return 'Ежегодное повторение';
|
||||
}
|
||||
|
||||
function ordinalDay(day: number): string {
|
||||
return ordinalDays[day] || String(day);
|
||||
}
|
||||
|
||||
function capitalize(str: string): string {
|
||||
if (!str) return str;
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
|
||||
function decodeRepeatTill(p: any): string {
|
||||
switch (p.REPEAT_TILL) {
|
||||
case 'endless':
|
||||
return 'бесконечно';
|
||||
case 'times':
|
||||
if (p.TIMES <= 1) return '1 раз';
|
||||
return `${p.TIMES} раз`;
|
||||
case 'date': {
|
||||
if (!p.END_DATE) return '';
|
||||
const parts = p.END_DATE.split(' ');
|
||||
if (parts.length > 0) return `до ${parts[0]}`;
|
||||
return `до ${p.END_DATE}`;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function decodeTime(p: any): string {
|
||||
if (!p.TIME) return '';
|
||||
return `в ${p.TIME}`;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { notifyReportRecievers } from '../../core/mail/notify';
|
||||
|
||||
export function notifyNewTemplates(): void {
|
||||
notifyReportRecievers('Отчет по новым шаблонам задач');
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { createTimestampedSheet, setReportSheetFormat, setupDropdown } from '../../core/sheets/reportLifecycle';
|
||||
|
||||
export function saveDepartmentSheets(departmentRows: any[][]): void {
|
||||
if (!departmentRows.length) return;
|
||||
|
||||
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const headers = [
|
||||
'ID', 'Название', 'Постановщик', 'Исполнитель', 'Повторять задачу',
|
||||
'Крайний срок', 'Буквенный код', 'Тэги', 'ID базового шаблона',
|
||||
'Название базового шаблона', 'Решение руководителя'
|
||||
];
|
||||
|
||||
const sheet = createTimestampedSheet(REPORT_PREFIXES.newTemplates, spreadsheet);
|
||||
sheet.appendRow(headers);
|
||||
sheet.getRange(sheet.getLastRow() + 1, 1, departmentRows.length, departmentRows[0].length)
|
||||
.setValues(departmentRows);
|
||||
sheet.autoResizeColumns(1, sheet.getLastColumn());
|
||||
sheet.getRange(1, 1, 1, sheet.getLastColumn()).setFontWeight('bold');
|
||||
setupDropdown(sheet);
|
||||
setReportSheetFormat(sheet);
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
export function loadState() {
|
||||
const props = PropertiesService.getScriptProperties();
|
||||
return {
|
||||
lastTemplateId: Number(props.getProperty('lastTemplateId') || 0),
|
||||
};
|
||||
}
|
||||
|
||||
export function saveState(state: { lastTemplateId: number }): void {
|
||||
PropertiesService.getScriptProperties().setProperty(
|
||||
'lastTemplateId',
|
||||
String(state.lastTemplateId)
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
import { EXECUTOR_SHEET_NAMES } from '../../core/constants';
|
||||
import { askUser } from '../../core/ui';
|
||||
import { getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { loadConfig } from '../../core/mail/executorTables';
|
||||
|
||||
export function distributeOverdueTasksToExecutors(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const SHEET_NAME = EXECUTOR_SHEET_NAMES.overdueQuestions;
|
||||
const config = loadConfig();
|
||||
const reportSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const values = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (values.length < 2) {
|
||||
Logger.log('В отчете нет задач');
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const REPORT = {
|
||||
TASK_ID: 'ID задачи',
|
||||
TASK_NAME: 'Наименование задачи',
|
||||
DESC: 'Описание',
|
||||
PARENT_TASK_NAME: 'Наименование родительской задачи',
|
||||
CRM: 'Элементы CRM',
|
||||
CREATOR: 'Постановщик',
|
||||
EXECUTOR: 'Исполнитель',
|
||||
CREATED: 'Дата создания задачи',
|
||||
DEADLINE: 'Крайний срок задачи',
|
||||
LOSS_CLIENT: 'Ведет к потере клиента',
|
||||
PRICE: 'Цена задачи',
|
||||
TRANSFER_COUNT: 'Ранее переносилась раз',
|
||||
NEED_REASON: 'Задача, требующая описания причины при переносе сроков',
|
||||
OLD_REASON: 'Прошлые причины переноса',
|
||||
NEW_REASON: 'Текущая причина переноса',
|
||||
NEW_DEADLINE: 'Новый крайний срок от менеджера'
|
||||
};
|
||||
|
||||
const executorTasks: Record<string, any[][]> = {};
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const executor = String(row[col[REPORT.EXECUTOR]] || '').trim();
|
||||
if (!executor) continue;
|
||||
|
||||
if (!executorTasks[executor]) {
|
||||
executorTasks[executor] = [];
|
||||
}
|
||||
|
||||
executorTasks[executor].push([
|
||||
row[col[REPORT.TASK_ID]],
|
||||
row[col[REPORT.TASK_NAME]],
|
||||
row[col[REPORT.DESC]],
|
||||
row[col[REPORT.PARENT_TASK_NAME]],
|
||||
row[col[REPORT.CRM]],
|
||||
row[col[REPORT.CREATOR]],
|
||||
row[col[REPORT.EXECUTOR]],
|
||||
row[col[REPORT.CREATED]],
|
||||
row[col[REPORT.DEADLINE]],
|
||||
row[col[REPORT.LOSS_CLIENT]],
|
||||
row[col[REPORT.PRICE]],
|
||||
row[col[REPORT.TRANSFER_COUNT]],
|
||||
row[col[REPORT.NEED_REASON]],
|
||||
row[col[REPORT.OLD_REASON]],
|
||||
row[col[REPORT.NEW_REASON]],
|
||||
row[col[REPORT.NEW_DEADLINE]]
|
||||
]);
|
||||
}
|
||||
|
||||
const targetHeaders = [
|
||||
REPORT.TASK_ID, REPORT.TASK_NAME, REPORT.DESC, REPORT.PARENT_TASK_NAME,
|
||||
REPORT.CRM, REPORT.CREATOR, REPORT.EXECUTOR, REPORT.CREATED, REPORT.DEADLINE,
|
||||
REPORT.LOSS_CLIENT, REPORT.PRICE, REPORT.TRANSFER_COUNT, REPORT.NEED_REASON,
|
||||
REPORT.OLD_REASON, REPORT.NEW_REASON, REPORT.NEW_DEADLINE
|
||||
];
|
||||
|
||||
const today = new Date();
|
||||
const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
|
||||
const emailMap = getUserEmailMap();
|
||||
|
||||
Object.entries(executorTasks).forEach(([executorName, executorRows]) => {
|
||||
const spreadsheetId = config[executorName];
|
||||
if (!spreadsheetId) {
|
||||
Logger.log(`Для исполнителя "${executorName}" не найдена таблица`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const targetSpreadsheet = SpreadsheetApp.openById(spreadsheetId);
|
||||
let targetSheet = targetSpreadsheet.getSheetByName(SHEET_NAME);
|
||||
if (!targetSheet) {
|
||||
targetSheet = targetSpreadsheet.insertSheet(SHEET_NAME);
|
||||
}
|
||||
|
||||
targetSheet.getDataRange().clearDataValidations();
|
||||
targetSheet.clear();
|
||||
targetSheet.clearFormats();
|
||||
|
||||
const output = [targetHeaders, ...executorRows];
|
||||
targetSheet.getRange(1, 1, output.length, targetHeaders.length).setValues(output);
|
||||
|
||||
if (output.length > 1) {
|
||||
const validation = SpreadsheetApp
|
||||
.newDataValidation()
|
||||
.requireDateAfter(yesterday)
|
||||
.setAllowInvalid(false)
|
||||
.build();
|
||||
|
||||
const newDeadlineCol = targetHeaders.indexOf(REPORT.NEW_DEADLINE) + 1;
|
||||
targetSheet.getRange(2, newDeadlineCol, output.length - 1, 1).setDataValidation(validation);
|
||||
|
||||
const needReasonCol = targetHeaders.indexOf(REPORT.NEED_REASON) + 1;
|
||||
const newReasonCol = targetHeaders.indexOf(REPORT.NEW_REASON) + 1;
|
||||
const needReasonValues = targetSheet.getRange(2, needReasonCol, output.length - 1, 1).getValues();
|
||||
|
||||
for (let rowIndex = 0; rowIndex < needReasonValues.length; rowIndex++) {
|
||||
const value = String(needReasonValues[rowIndex][0] || '').trim();
|
||||
if (value !== 'Да') {
|
||||
targetSheet.getRange(rowIndex + 2, newReasonCol).setBackground('#000000');
|
||||
}
|
||||
}
|
||||
|
||||
sendOverdueExecutorEmail(
|
||||
emailMap[executorName],
|
||||
SpreadsheetApp.openById(spreadsheetId).getUrl() + '#gid=' + targetSheet.getSheetId()
|
||||
);
|
||||
}
|
||||
|
||||
targetSheet.autoResizeColumns(1, targetHeaders.length);
|
||||
} catch (error) {
|
||||
Logger.log(`Ошибка для ${executorName}: ${error}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function sendOverdueExecutorEmail(email: string, spreadsheetUrl: string): void {
|
||||
if (!email || !spreadsheetUrl) return;
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: email,
|
||||
subject: 'Требуют внимания просроченные задачи',
|
||||
body: `
|
||||
Здравствуйте.
|
||||
|
||||
В вашу таблицу добавлены просроченные задачи, требующие внимания.
|
||||
|
||||
Ссылка:
|
||||
${spreadsheetUrl}
|
||||
|
||||
Это автоматическое уведомление.
|
||||
`
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
import { EXECUTOR_SHEET_NAMES } from '../../core/constants';
|
||||
import { loadConfig } from '../../core/mail/executorTables';
|
||||
|
||||
export function pullExecutorAnswers(): void {
|
||||
const config = loadConfig();
|
||||
const reportSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const reportData = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (reportData.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const reportHeaders = reportData[0];
|
||||
const reportCol: Record<string, number> = {};
|
||||
reportHeaders.forEach((header, index) => {
|
||||
reportCol[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const executorTasks: Record<string, Array<{ taskId: string; reportRow: number }>> = {};
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = reportData[i];
|
||||
const executor = String(row[reportCol['Исполнитель']] || '').trim();
|
||||
const taskId = String(row[reportCol['ID задачи']] || '').trim();
|
||||
if (!executor || !taskId) continue;
|
||||
|
||||
if (!executorTasks[executor]) {
|
||||
executorTasks[executor] = [];
|
||||
}
|
||||
|
||||
executorTasks[executor].push({ taskId, reportRow: i + 1 });
|
||||
}
|
||||
|
||||
const taskAnswers: Record<string, any> = {};
|
||||
|
||||
Object.keys(executorTasks).forEach(executorName => {
|
||||
const spreadsheetId = config[executorName];
|
||||
if (!spreadsheetId) return;
|
||||
|
||||
try {
|
||||
const executorSpreadsheet = SpreadsheetApp.openById(spreadsheetId);
|
||||
const sheet = executorSpreadsheet.getSheetByName(EXECUTOR_SHEET_NAMES.overdueQuestions);
|
||||
if (!sheet) return;
|
||||
|
||||
const values = sheet.getDataRange().getValues();
|
||||
if (values.length < 2) return;
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
for (let r = 1; r < values.length; r++) {
|
||||
const row = values[r];
|
||||
const taskId = String(row[col['ID задачи']] || '').trim();
|
||||
if (!taskId) continue;
|
||||
|
||||
taskAnswers[taskId] = {
|
||||
comment: row[col['Текущая причина переноса']],
|
||||
deadline: row[col['Новый крайний срок от менеджера']],
|
||||
secondComment: row[col['Комментарий Исполнителя: условия, которые гарантируют выполнение задачи в запрашиваемый новый крайний срок']],
|
||||
executorName,
|
||||
executorSheetRow: r + 1
|
||||
};
|
||||
}
|
||||
} catch (e: any) {
|
||||
Logger.log(executorName + ': ' + e.message);
|
||||
}
|
||||
});
|
||||
|
||||
const missing: string[] = [];
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = reportData[i];
|
||||
const taskId = String(row[reportCol['ID задачи']] || '').trim();
|
||||
if (!taskId) continue;
|
||||
|
||||
const answer = taskAnswers[taskId];
|
||||
if (!answer) {
|
||||
missing.push('Строка ' + (i + 1) + ' задачи нет в листах менеджеров. Убедись что менеджеры получили список задач перед сбором комментариев');
|
||||
continue;
|
||||
}
|
||||
|
||||
const needReason = String(row[reportCol['Задача, требующая описания причины при переносе сроков']] || '')
|
||||
.trim()
|
||||
.toLowerCase() === 'да';
|
||||
|
||||
if (needReason && (!answer.comment || String(answer.comment).trim() === '')) {
|
||||
missing.push('Строка ' + answer.executorSheetRow + ' в таблице ' + answer.executorName + ' (нет комментария)');
|
||||
}
|
||||
|
||||
if (!answer.deadline) {
|
||||
missing.push('Строка ' + answer.executorSheetRow + ' в таблице ' + answer.executorName + ' (нет даты)');
|
||||
}
|
||||
|
||||
if (!answer.secondComment) {
|
||||
missing.push('Строка ' + answer.executorSheetRow + ' в таблице ' + answer.executorName + ' (нет условий выполнения)');
|
||||
}
|
||||
|
||||
if (needReason) {
|
||||
reportSheet.getRange(i + 1, reportCol['Текущая причина переноса'] + 1).setValue(answer.comment);
|
||||
}
|
||||
|
||||
reportSheet.getRange(i + 1, reportCol['Новый крайний срок от менеджера'] + 1).setValue(answer.deadline);
|
||||
reportSheet
|
||||
.getRange(
|
||||
i + 1,
|
||||
reportCol['Комментарий Исполнителя: условия, которые гарантируют выполнение задачи в запрашиваемый новый крайний срок'] + 1
|
||||
)
|
||||
.setValue(answer.secondComment);
|
||||
}
|
||||
|
||||
SpreadsheetApp.getUi().alert(
|
||||
missing.length
|
||||
? 'Не заполнены данные по задачам:\n\n' + missing.join('\n')
|
||||
: 'Все данные исполнителей успешно загружены.'
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { createOverdueTasksReport } from './main';
|
||||
import { distributeOverdueTasksToExecutors } from './executorNotification';
|
||||
import { pullExecutorAnswers } from './getExecutorComments';
|
||||
import { notifyOverdueTasks } from './notifyFilialHead';
|
||||
import { sendTasksToCreatorsForApproval } from './notifyTaskSetters';
|
||||
import { saveOverdueTasksReport } from './notifySalesDepHead';
|
||||
|
||||
export const overduePlugin: ReportPlugin = {
|
||||
id: 'overdue',
|
||||
menuTitle: '4️⃣ 🚨 Просроченные задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createOverdueTasksReport' },
|
||||
{ label: '📤 Отправить менеджерам', functionName: 'distributeOverdueTasksToExecutors' },
|
||||
{ label: '💬 Получить комментарии менеджеров', functionName: 'pullExecutorAnswers' },
|
||||
{ label: '👔 Отправить отчет рукфилу', functionName: 'notifyOverdueTasks' },
|
||||
{ label: '✉️ Отправить письма постановщикам', functionName: 'sendTasksToCreatorsForApproval' },
|
||||
{ label: '💾 Сохранить комментарии и уведомить РОПа', functionName: 'saveOverdueTasksReport' },
|
||||
],
|
||||
handlers: {
|
||||
createOverdueTasksReport,
|
||||
distributeOverdueTasksToExecutors,
|
||||
pullExecutorAnswers,
|
||||
notifyOverdueTasks,
|
||||
sendTasksToCreatorsForApproval,
|
||||
saveOverdueTasksReport,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'MANAGER_TABLES_CONFIG_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,165 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { getAppConfig, getSourceSheet } from '../../core/config';
|
||||
import { bitrixBooleanToString, decodeTaskCodes } from '../../core/taskCodes';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
import { TaskIndexService } from './taskIndexService';
|
||||
|
||||
export function createOverdueTasksReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const reportPrefix = REPORT_PREFIXES.overdue;
|
||||
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Не найден лист выгрузки');
|
||||
}
|
||||
|
||||
const taskIndex = new TaskIndexService(getAppConfig().taskIndexSheetName);
|
||||
const values = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (values.length < 2) {
|
||||
throw new Error('На листе "Для выгрузки" нет данных');
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const requiredColumns = [
|
||||
'ID', 'Название', 'Описание', 'Название базовой задачи', 'CRM',
|
||||
'Постановщик', 'Исполнитель', 'Дата создания', 'Крайний срок',
|
||||
'Дата закрытия', 'Может привести к потере клиента', 'Цена задачи', 'Важная задача'
|
||||
];
|
||||
|
||||
const missingColumns = requiredColumns.filter(name => !(name in col));
|
||||
if (missingColumns.length) {
|
||||
throw new Error('Не найдены колонки: ' + missingColumns.join(', '));
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const reportRows: Array<{ lossClient: any; important: any; executor: string; row: any[] }> = [];
|
||||
const taskNames = new Map<any, any>();
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const taskId = row[col['ID']] || '';
|
||||
if (taskId == '') continue;
|
||||
taskNames.set(taskId, row[col['Название']]);
|
||||
}
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const deadline = row[col['Крайний срок']];
|
||||
|
||||
if (!(deadline instanceof Date) || deadline >= now) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const taskId = String(row[col['ID']] || '').trim();
|
||||
if (taskId == '') continue;
|
||||
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
if (status == '' || status === 'Ждёт контроля') continue;
|
||||
|
||||
const indexRecord = taskIndex.get(taskId);
|
||||
let transferCount = 0;
|
||||
let previousComments = '';
|
||||
|
||||
if (indexRecord) {
|
||||
transferCount = Number(indexRecord.transferCount || 0) + 1;
|
||||
previousComments = indexRecord.comment || '';
|
||||
}
|
||||
|
||||
reportRows.push({
|
||||
lossClient: bitrixBooleanToString(String(row[col['Может привести к потере клиента']] || '')),
|
||||
important: bitrixBooleanToString(String(row[col['Важная задача']] || '')),
|
||||
executor: String(row[col['Исполнитель']] || ''),
|
||||
row: [
|
||||
taskId,
|
||||
row[col['Название']],
|
||||
row[col['Описание']],
|
||||
taskNames.get(row[col['ID базовой задачи']]) || '',
|
||||
row[col['CRM']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Дата создания']],
|
||||
deadline,
|
||||
bitrixBooleanToString(row[col['Может привести к потере клиента']]),
|
||||
row[col['Цена задачи']],
|
||||
transferCount,
|
||||
bitrixBooleanToString(row[col['Важная задача']]),
|
||||
previousComments,
|
||||
'', '', '', '', '', '', ''
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
reportRows.sort((a, b) => {
|
||||
const aLoss = String(a.lossClient) === 'Да';
|
||||
const bLoss = String(b.lossClient) === 'Да';
|
||||
if (aLoss !== bLoss) return aLoss ? -1 : 1;
|
||||
|
||||
const aImportant = String(a.important) === 'Да';
|
||||
const bImportant = String(b.important) === 'Да';
|
||||
if (aImportant !== bImportant) return aImportant ? -1 : 1;
|
||||
|
||||
return a.executor.localeCompare(b.executor, 'ru');
|
||||
});
|
||||
|
||||
const reportSheet = createTimestampedSheet(reportPrefix, ss);
|
||||
const reportHeaders = [
|
||||
'ID задачи', 'Наименование задачи', 'Описание', 'Наименование родительской задачи',
|
||||
'Элементы CRM', 'Постановщик', 'Исполнитель', 'Дата создания задачи',
|
||||
'Крайний срок задачи', 'Ведет к потере клиента', 'Цена задачи',
|
||||
'Ранее переносилась раз', 'Задача, требующая описания причины при переносе сроков',
|
||||
'Прошлые причины переноса', 'Текущая причина переноса',
|
||||
'Комментарий Исполнителя: условия, которые гарантируют выполнение задачи в запрашиваемый новый крайний срок',
|
||||
'Новый крайний срок от менеджера', 'Согласование рук. фила',
|
||||
'Новый крайний срок от рук. фила', 'Согласование постановщиком', 'Согласование РОПом'
|
||||
];
|
||||
|
||||
const output = [reportHeaders, ...reportRows.map(item => item.row)];
|
||||
reportSheet.getRange(1, 1, output.length, reportHeaders.length).setValues(output);
|
||||
decodeTaskCodes(reportSheet);
|
||||
decodeTaskCodes(reportSheet, 'Наименование родительской задачи');
|
||||
reportSheet.getRange(1, 1, 1, reportHeaders.length).setBackground('yellow');
|
||||
addApprovalDropdowns(reportSheet);
|
||||
|
||||
const lastCol = reportSheet.getDataRange().getNumColumns();
|
||||
reportSheet.autoResizeColumns(1, lastCol);
|
||||
setReportSheetFormat(reportSheet);
|
||||
reportSheet.setColumnWidth(col['Наименование задачи'] + 1, 300);
|
||||
reportSheet.setColumnWidth(col['Описание'] + 1, 300);
|
||||
reportSheet.setColumnWidth(col['Наименование родительской задачи'] + 1, 300);
|
||||
}
|
||||
|
||||
function addApprovalDropdowns(sheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const values = sheet.getDataRange().getValues();
|
||||
if (values.length < 2) return;
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index + 1;
|
||||
});
|
||||
|
||||
const validation = SpreadsheetApp
|
||||
.newDataValidation()
|
||||
.requireValueInList(['Согласовано', 'Не согласовано'], true)
|
||||
.setAllowInvalid(false)
|
||||
.build();
|
||||
|
||||
const lastRow = sheet.getLastRow();
|
||||
|
||||
['Согласование рук. фила', 'Согласование постановщиком', 'Согласование РОПом']
|
||||
.forEach(columnName => {
|
||||
const column = col[columnName];
|
||||
if (!column) {
|
||||
throw new Error(`Не найден столбец "${columnName}"`);
|
||||
}
|
||||
|
||||
sheet.getRange(2, column, Math.max(lastRow - 1, 1), 1).setDataValidation(validation);
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { notifyReportRecievers } from '../../core/mail/notify';
|
||||
|
||||
export function notifyOverdueTasks(): void {
|
||||
notifyReportRecievers('Отчет по просроченным задачам');
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
import { getAppConfig } from '../../core/config';
|
||||
import { formatDate } from '../../core/dates';
|
||||
import { notifyLeadership } from '../../core/mail/notify';
|
||||
import { MetricsStorage } from '../../core/metrics/storage';
|
||||
import { TaskIndexService } from './taskIndexService';
|
||||
|
||||
export function saveOverdueTasksReport(): void {
|
||||
notifyLeadership({
|
||||
reportName: 'Отчет по просроченным задачам',
|
||||
recipients: 'salesHead',
|
||||
includeDirector: false,
|
||||
onConfirm(sheet) {
|
||||
updateOverdueMetric(sheet);
|
||||
},
|
||||
});
|
||||
|
||||
saveReportToTaskIndex();
|
||||
}
|
||||
|
||||
function saveReportToTaskIndex(): void {
|
||||
const taskIndex = new TaskIndexService(getAppConfig().taskIndexSheetName);
|
||||
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const values = sheet.getDataRange().getValues();
|
||||
if (values.length < 2) return;
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const today = formatDate(new Date());
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const taskId = String(row[col['ID задачи']] || '').trim();
|
||||
if (!taskId) continue;
|
||||
|
||||
const transferCount = Number(row[col['Ранее переносилась раз']] || 0);
|
||||
const reason = String(row[col['Текущая причина переноса']] || '').trim();
|
||||
const newComment = reason ? `${today} ${reason}` : '';
|
||||
const existing = taskIndex.get(taskId);
|
||||
|
||||
if (!existing) {
|
||||
taskIndex.add(taskId, newComment, transferCount);
|
||||
continue;
|
||||
}
|
||||
|
||||
let comment = existing.comment || '';
|
||||
if (newComment) {
|
||||
comment = comment ? comment + '\n' + newComment : newComment;
|
||||
}
|
||||
|
||||
taskIndex.update(taskId, { comment, transferCount });
|
||||
}
|
||||
|
||||
taskIndex.save();
|
||||
}
|
||||
|
||||
function updateOverdueMetric(tasksSheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
if (!tasksSheet) {
|
||||
throw new Error('Не передан лист отчёта по просроченным задачам');
|
||||
}
|
||||
|
||||
const tasksByAssignee = countTasksByAssignee(tasksSheet);
|
||||
const storage = new MetricsStorage();
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
for (const [assignee, taskCount] of Object.entries(tasksByAssignee)) {
|
||||
storage.updateMetric(today, assignee, 'overdue', taskCount);
|
||||
}
|
||||
|
||||
storage.sortSheet();
|
||||
}
|
||||
|
||||
function countTasksByAssignee(sheet: GoogleAppsScript.Spreadsheet.Sheet): Record<string, number> {
|
||||
const data = sheet.getDataRange().getValues();
|
||||
if (data.length < 2) return {};
|
||||
|
||||
const headers = data[0];
|
||||
const taskColumn = headers.indexOf('Наименование задачи');
|
||||
const assigneeColumn = headers.indexOf('Исполнитель');
|
||||
|
||||
if (taskColumn === -1) throw new Error('Не найден столбец «Наименование задачи»');
|
||||
if (assigneeColumn === -1) throw new Error('Не найден столбец «Исполнитель»');
|
||||
|
||||
const result: Record<string, number> = {};
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const task = String(data[i][taskColumn] || '').trim();
|
||||
const assignee = String(data[i][assigneeColumn] || '').trim();
|
||||
if (task && assignee) {
|
||||
result[assignee] = (result[assignee] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
import { askUser } from '../../core/ui';
|
||||
import { getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { sendTempSpreadsheetToEmail } from '../../core/sheets/export';
|
||||
|
||||
export function sendTasksToCreatorsForApproval(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const reportSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const reportData = reportSheet.getDataRange().getValues();
|
||||
if (reportData.length < 2) return;
|
||||
|
||||
const headers = reportData[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const emailMap = getUserEmailMap();
|
||||
const creators: Record<string, any[][]> = {};
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = reportData[i];
|
||||
const creator = String(row[col['Постановщик']] || '').trim();
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
if (!creator || creator === executor) continue;
|
||||
|
||||
if (!creators[creator]) {
|
||||
creators[creator] = [];
|
||||
}
|
||||
|
||||
creators[creator].push([
|
||||
row[col['ID задачи']],
|
||||
row[col['Наименование задачи']],
|
||||
row[col['Описание']],
|
||||
row[col['Наименование родительской задачи']],
|
||||
row[col['Элементы CRM']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Дата создания задачи']],
|
||||
row[col['Крайний срок задачи']],
|
||||
row[col['Ведет к потере клиента']],
|
||||
row[col['Ранее переносилась раз']],
|
||||
row[col['Задача, требующая описания причины при переносе сроков']],
|
||||
row[col['Прошлые причины переноса']],
|
||||
row[col['Текущая причина переноса']],
|
||||
row[col['Новый крайний срок от менеджера']],
|
||||
row[col['Согласование рук. фила']],
|
||||
row[col['Новый крайний срок от рук. фила']]
|
||||
]);
|
||||
}
|
||||
|
||||
const pdfHeaders = [
|
||||
'ID задачи', 'Наименование задачи', 'Описание', 'Наименование родительской задачи',
|
||||
'Элементы CRM', 'Постановщик', 'Исполнитель', 'Дата создания задачи',
|
||||
'Крайний срок задачи', 'Ведет к потере клиента', 'Ранее переносилась раз',
|
||||
'Задача, требующая описания причины при переносе сроков', 'Прошлые причины переноса',
|
||||
'Текущая причина переноса', 'Новый крайний срок от менеджера',
|
||||
'Согласование рук. фила', 'Новый крайний срок от рук. фила'
|
||||
];
|
||||
|
||||
Object.entries(creators).forEach(([creator, rows]) => {
|
||||
const email = emailMap[creator];
|
||||
if (!email) return;
|
||||
|
||||
sendTempSpreadsheetToEmail({
|
||||
email,
|
||||
fileName: 'Просроченные задачи - ' + creator,
|
||||
headers: pdfHeaders,
|
||||
rows,
|
||||
subject: 'Согласование переноса просроченных задач',
|
||||
htmlBody: 'Во вложении находятся задачи, требующие согласования переноса сроков. О решении сообщи контролеру отдела продаж',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
export class TaskIndexService {
|
||||
sheet: GoogleAppsScript.Spreadsheet.Sheet;
|
||||
index: Record<string, { taskId: string; comment: string; transferCount: number }>;
|
||||
|
||||
constructor(sheetName: string) {
|
||||
this.sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
|
||||
this.index = {};
|
||||
this.load();
|
||||
}
|
||||
|
||||
load(): void {
|
||||
const values = this.sheet.getDataRange().getValues();
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const [taskId, comment, transferCount] = values[i];
|
||||
if (!taskId) continue;
|
||||
|
||||
this.index[String(taskId)] = {
|
||||
taskId: String(taskId),
|
||||
comment: comment || '',
|
||||
transferCount: Number(transferCount || 0)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
get(taskId: string | number) {
|
||||
return this.index[String(taskId)] || null;
|
||||
}
|
||||
|
||||
exists(taskId: string | number): boolean {
|
||||
return String(taskId) in this.index;
|
||||
}
|
||||
|
||||
add(taskId: string | number, comment = '', transferCount = 0) {
|
||||
const id = String(taskId);
|
||||
if (this.exists(id)) {
|
||||
return this.index[id];
|
||||
}
|
||||
|
||||
const task = { taskId: id, comment, transferCount };
|
||||
this.index[id] = task;
|
||||
return task;
|
||||
}
|
||||
|
||||
update(taskId: string | number, data: Partial<{ comment: string; transferCount: number }>) {
|
||||
const id = String(taskId);
|
||||
if (!this.exists(id)) {
|
||||
throw new Error(`Task ${id} not found`);
|
||||
}
|
||||
|
||||
this.index[id] = { ...this.index[id], ...data };
|
||||
return this.index[id];
|
||||
}
|
||||
|
||||
save(): void {
|
||||
const rows: any[][] = [['TASK_ID', 'COMMENT', 'TRANSFER_COUNT']];
|
||||
|
||||
for (const task of Object.values(this.index)) {
|
||||
rows.push([task.taskId, task.comment, task.transferCount]);
|
||||
}
|
||||
|
||||
this.sheet.clearContents();
|
||||
this.sheet.getRange(1, 1, rows.length, 3).setValues(rows);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
import { WAITING_CONTROL_STATUS } from '../../core/constants';
|
||||
import { bitrixBooleanToString } from '../../core/taskCodes';
|
||||
import { getCrmElement } from '../bigSmall/builder';
|
||||
|
||||
export const PLAN_OVERDUE_HEADERS = [
|
||||
'ID задачи',
|
||||
'Наименование задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Элементы CRM',
|
||||
'Дата создания задачи',
|
||||
'Крайний срок задачи',
|
||||
'Планируемая дата начала',
|
||||
'Планируемая дата конца',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
];
|
||||
|
||||
export function matchesPlanOverdueTask(row: any[], col: Record<string, number>, now: Date): boolean {
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
if (status === WAITING_CONTROL_STATUS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const plannedEnd = row[col['Планируемая дата окончания']];
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
if (!(plannedEnd instanceof Date) || plannedEnd >= startOfToday) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const deadline = row[col['Крайний срок']];
|
||||
if (deadline instanceof Date && deadline < now) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(String(row[col['Исполнитель']] || '').trim());
|
||||
}
|
||||
|
||||
export function pluralizeTasksWord(count: number): string {
|
||||
const mod10 = count % 10;
|
||||
const mod100 = count % 100;
|
||||
|
||||
if (mod100 >= 11 && mod100 <= 14) {
|
||||
return 'задач';
|
||||
}
|
||||
if (mod10 === 1) {
|
||||
return 'задача';
|
||||
}
|
||||
if (mod10 >= 2 && mod10 <= 4) {
|
||||
return 'задачи';
|
||||
}
|
||||
return 'задач';
|
||||
}
|
||||
|
||||
export function buildPlanOverdueReport(values: any[][], now: Date = new Date()): {
|
||||
output: any[][];
|
||||
totalRowIndexes: number[];
|
||||
} | null {
|
||||
if (values.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const requiredColumns = [
|
||||
'ID',
|
||||
'Название',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Статус',
|
||||
'Дата создания',
|
||||
'Крайний срок',
|
||||
'Планируемая дата начала',
|
||||
'Планируемая дата окончания',
|
||||
'Может привести к потере клиента',
|
||||
'Цена задачи',
|
||||
];
|
||||
|
||||
const missing = requiredColumns.filter(name => !(name in col));
|
||||
if (missing.length) {
|
||||
throw new Error('Не найдены колонки: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
const executorTasks: Record<string, Array<{ clientLoss: any; price: number; row: any[] }>> = {};
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
if (!matchesPlanOverdueTask(row, col, now)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
const clientLoss = bitrixBooleanToString(
|
||||
String(row[col['Может привести к потере клиента']] || '')
|
||||
);
|
||||
|
||||
if (!executorTasks[executor]) {
|
||||
executorTasks[executor] = [];
|
||||
}
|
||||
|
||||
executorTasks[executor].push({
|
||||
clientLoss,
|
||||
price: Number(row[col['Цена задачи']]) || 0,
|
||||
row: [
|
||||
row[col['ID']],
|
||||
row[col['Название']],
|
||||
row[col['Постановщик']],
|
||||
executor,
|
||||
getCrmElement(row, col),
|
||||
row[col['Дата создания']],
|
||||
row[col['Крайний срок']],
|
||||
row[col['Планируемая дата начала']],
|
||||
row[col['Планируемая дата окончания']],
|
||||
clientLoss,
|
||||
row[col['Цена задачи']],
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const executors = Object.keys(executorTasks).sort((a, b) => a.localeCompare(b, 'ru'));
|
||||
if (!executors.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
executors.forEach(executor => {
|
||||
executorTasks[executor].sort((a, b) => {
|
||||
const aLoss = a.clientLoss === 'Да';
|
||||
const bLoss = b.clientLoss === 'Да';
|
||||
if (aLoss !== bLoss) {
|
||||
return aLoss ? -1 : 1;
|
||||
}
|
||||
return b.price - a.price;
|
||||
});
|
||||
});
|
||||
|
||||
const output: any[][] = [PLAN_OVERDUE_HEADERS];
|
||||
const totalRowIndexes: number[] = [];
|
||||
|
||||
executors.forEach(executor => {
|
||||
executorTasks[executor].forEach(item => {
|
||||
output.push(item.row);
|
||||
});
|
||||
|
||||
const totalRow = Array(PLAN_OVERDUE_HEADERS.length).fill('');
|
||||
totalRow[0] = 'Итого';
|
||||
totalRow[1] = executorTasks[executor].length;
|
||||
output.push(totalRow);
|
||||
totalRowIndexes.push(output.length);
|
||||
});
|
||||
|
||||
return { output, totalRowIndexes };
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { createPlanOverdueTasksReport } from './main';
|
||||
import { notifyPlanOverdueExecutors } from './notifyExecutors';
|
||||
|
||||
export const planOverduePlugin: ReportPlugin = {
|
||||
id: 'planOverdue',
|
||||
menuTitle: '6️⃣ 📌 Задачи, не завершенные по плану',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createPlanOverdueTasksReport' },
|
||||
{ label: '🔔 Уведомить исполнителей', functionName: 'notifyPlanOverdueExecutors' },
|
||||
],
|
||||
handlers: {
|
||||
createPlanOverdueTasksReport,
|
||||
notifyPlanOverdueExecutors,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'BITRIX_PORTAL',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { getSourceSheet } from '../../core/config';
|
||||
import { createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
import { appendFromConfig } from '../../core/sheets/reportNotes';
|
||||
import { PLAN_OVERDUE_HEADERS, buildPlanOverdueReport } from './builder';
|
||||
|
||||
export function createPlanOverdueTasksReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Не найден лист для выгрузки');
|
||||
}
|
||||
|
||||
const values = sourceSheet.getDataRange().getValues();
|
||||
if (values.length < 2) {
|
||||
throw new Error('На листе нет данных');
|
||||
}
|
||||
|
||||
const built = buildPlanOverdueReport(values, new Date());
|
||||
if (!built) {
|
||||
SpreadsheetApp.getUi().alert('Нет задач, подходящих под условия отчета');
|
||||
return;
|
||||
}
|
||||
|
||||
const reportSheet = createTimestampedSheet(REPORT_PREFIXES.planOverdue, ss);
|
||||
reportSheet
|
||||
.getRange(1, 1, built.output.length, PLAN_OVERDUE_HEADERS.length)
|
||||
.setValues(built.output);
|
||||
|
||||
setReportSheetFormat(reportSheet);
|
||||
highlightTotalRows(reportSheet, built.totalRowIndexes);
|
||||
reportSheet.autoResizeColumns(1, PLAN_OVERDUE_HEADERS.length);
|
||||
appendFromConfig(reportSheet.getName());
|
||||
}
|
||||
|
||||
function highlightTotalRows(sheet: GoogleAppsScript.Spreadsheet.Sheet, rowIndexes: number[]): void {
|
||||
rowIndexes.forEach(rowIndex => {
|
||||
sheet
|
||||
.getRange(rowIndex, 1, 1, PLAN_OVERDUE_HEADERS.length)
|
||||
.setBackground('#e69138');
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
import { askUser } from '../../core/ui';
|
||||
import { getAppConfig } from '../../core/config';
|
||||
import { getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { pluralizeTasksWord } from './builder';
|
||||
|
||||
export function notifyPlanOverdueExecutors(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const reportSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const data = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
SpreadsheetApp.getUi().alert('В отчете нет данных');
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = data[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
if (!('Исполнитель' in col)) {
|
||||
throw new Error('Не найдена колонка "Исполнитель"');
|
||||
}
|
||||
|
||||
const executorCounts: Record<string, number> = {};
|
||||
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const row = data[i];
|
||||
const firstCell = String(row[0] || '').trim();
|
||||
if (firstCell === 'Итого' || firstCell === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
if (!executor) {
|
||||
continue;
|
||||
}
|
||||
|
||||
executorCounts[executor] = (executorCounts[executor] || 0) + 1;
|
||||
}
|
||||
|
||||
const emailMap = getUserEmailMap();
|
||||
const notSent: string[] = [];
|
||||
const plannerUrl = getAppConfig().bitrixPortal + '/marketplace/app/124/';
|
||||
|
||||
Object.entries(executorCounts).forEach(([executor, count]) => {
|
||||
const email = emailMap[executor];
|
||||
if (!email) {
|
||||
Logger.log('Не найден email для: ' + executor);
|
||||
notSent.push(executor);
|
||||
return;
|
||||
}
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: email,
|
||||
subject: 'Задачи, не завершенные по плану',
|
||||
body:
|
||||
`Добрый день
|
||||
|
||||
У вас есть ${count} ${pluralizeTasksWord(count)}, которые должны были быть завершены вчера согласно их планируемым срокам.
|
||||
Поменяйте планируемое время выполнения этих задач или завершите их.
|
||||
Ссылка на инструмент планирования в Битриксе: ${plannerUrl}
|
||||
|
||||
Это автоматическое уведомление.`,
|
||||
});
|
||||
});
|
||||
|
||||
if (notSent.length) {
|
||||
SpreadsheetApp.getUi().alert('Не найден email для: \n\n' + notSent.join('\n'));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { buildSelfAssignedTasksReport } from './main';
|
||||
import { notifySelfTasksReportRecievers } from './notifyFilialHead';
|
||||
|
||||
export const selfTasksPlugin: ReportPlugin = {
|
||||
id: 'selfTasks',
|
||||
menuTitle: '5️⃣ 🙋 Задачи самому себе',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'buildSelfAssignedTasksReport' },
|
||||
{ label: '📤 Отправить отчет', functionName: 'notifySelfTasksReportRecievers' },
|
||||
],
|
||||
handlers: {
|
||||
buildSelfAssignedTasksReport,
|
||||
notifySelfTasksReportRecievers,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { getSourceSheet } from '../../core/config';
|
||||
import { requestDate } from '../../core/ui';
|
||||
import { bitrixBooleanToString, decodeTaskCodes } from '../../core/taskCodes';
|
||||
import { diffMinutes, isSameDay } from '../../core/dates';
|
||||
import { addDropdownValidations, createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
|
||||
export function buildSelfAssignedTasksReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const values = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (values.length < 2) {
|
||||
throw new Error('На листе нет данных');
|
||||
}
|
||||
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const requiredColumns = [
|
||||
'ID', 'Название', 'Крайний срок', 'Дата создания', 'Постановщик',
|
||||
'Исполнитель', 'CRM', 'Планируемая длительность',
|
||||
'Может привести к потере клиента', 'Цена задачи', 'ID базовой задачи'
|
||||
];
|
||||
|
||||
const missing = requiredColumns.filter(name => !(name in col));
|
||||
if (missing.length) {
|
||||
throw new Error('Не найдены колонки: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
const reportPrefix = REPORT_PREFIXES.selfTasks;
|
||||
const reportSheet = createTimestampedSheet(reportPrefix, ss);
|
||||
const reportHeaders = [
|
||||
'ID задачи', 'Наименование задачи', 'Крайний срок задачи', 'Дата создания',
|
||||
'Постановщик', 'Исполнитель', 'CRM', 'Планируемая дата начала',
|
||||
'Время выполнения задачи', 'Ведет к потере клиента', 'Цена задачи',
|
||||
'Комментарий рук.фила'
|
||||
];
|
||||
|
||||
const lastReportDate = requestDate('Введите дату последнего отчета по задачам самому себе');
|
||||
const result: Array<{ lossClient: any; executor: string; row: any[] }> = [];
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const parentTask = String(row[col['ID базовой задачи']] || '').trim();
|
||||
if (parentTask) continue;
|
||||
|
||||
const creator = String(row[col['Постановщик']] || '').trim();
|
||||
const executor = String(row[col['Исполнитель']] || '').trim();
|
||||
if (creator !== executor) continue;
|
||||
|
||||
const createdValue = row[col['Дата создания']];
|
||||
if (!createdValue) continue;
|
||||
|
||||
const createdDate = new Date(createdValue);
|
||||
createdDate.setHours(0, 0, 0, 0);
|
||||
|
||||
if (createdDate.getTime() < lastReportDate.getTime() || isSameDay(createdDate, new Date())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const lossClient = bitrixBooleanToString(row[col['Может привести к потере клиента']]);
|
||||
const startDate = row[col['Планируемая дата начала']];
|
||||
const endDate = row[col['Планируемая дата окончания']];
|
||||
|
||||
result.push({
|
||||
lossClient,
|
||||
executor,
|
||||
row: [
|
||||
row[col['ID']],
|
||||
row[col['Название']],
|
||||
row[col['Крайний срок']],
|
||||
createdValue,
|
||||
creator,
|
||||
executor,
|
||||
row[col['CRM']],
|
||||
startDate,
|
||||
diffMinutes(startDate, endDate),
|
||||
lossClient,
|
||||
row[col['Цена задачи']],
|
||||
''
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
result.sort((a, b) => {
|
||||
const aLoss = String(a.lossClient).trim().toLowerCase() === 'да';
|
||||
const bLoss = String(b.lossClient).trim().toLowerCase() === 'да';
|
||||
if (aLoss !== bLoss) return aLoss ? -1 : 1;
|
||||
return String(a.executor).localeCompare(String(b.executor), 'ru');
|
||||
});
|
||||
|
||||
const output = [reportHeaders, ...result.map(item => item.row)];
|
||||
reportSheet.getRange(1, 1, output.length, reportHeaders.length).setValues(output);
|
||||
|
||||
addDropdownValidations(reportSheet, reportHeaders, output.length, {
|
||||
'Комментарий рук.фила': [
|
||||
'Правок нет, согласовано',
|
||||
'внес правки',
|
||||
'прошу сменить постановщика на рук.фила'
|
||||
]
|
||||
});
|
||||
|
||||
decodeTaskCodes(reportSheet);
|
||||
reportSheet.autoResizeColumns(1, reportHeaders.length);
|
||||
setReportSheetFormat(reportSheet);
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import { notifyReportRecievers } from '../../core/mail/notify';
|
||||
|
||||
export function notifySelfTasksReportRecievers(): void {
|
||||
notifyReportRecievers('Отчет по задачам самому себе');
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { createSingleTimeTasksReport } from './main';
|
||||
import { sendAttentionTasksToCreatorsForApproval } from './notifyTaskSetters';
|
||||
import { notifySingleTimeTasks } from './reportSender';
|
||||
|
||||
export const singleTimePlugin: ReportPlugin = {
|
||||
id: 'singleTime',
|
||||
menuTitle: '2️⃣ 📝 Разовые задачи',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'createSingleTimeTasksReport' },
|
||||
{ label: '🔔 Уведомить постановщиков', functionName: 'sendAttentionTasksToCreatorsForApproval' },
|
||||
{ label: '👔 Отправить руководителю', functionName: 'notifySingleTimeTasks' },
|
||||
],
|
||||
handlers: {
|
||||
createSingleTimeTasksReport,
|
||||
sendAttentionTasksToCreatorsForApproval,
|
||||
notifySingleTimeTasks,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,163 @@
|
|||
import { REPORT_PREFIXES } from '../../core/constants';
|
||||
import { getSourceSheet } from '../../core/config';
|
||||
import { requestDate } from '../../core/ui';
|
||||
import { beforeHash, bitrixBooleanToString, decodeTaskCodes, normalizeTaskName, validateTaskCode } from '../../core/taskCodes';
|
||||
import { diffMinutes, isSameDay } from '../../core/dates';
|
||||
import { addDropdownValidations, createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
|
||||
export function createSingleTimeTasksReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const reportPrefix = REPORT_PREFIXES.singleTime;
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
|
||||
if (!sourceSheet) {
|
||||
throw new Error('Не найден лист с выгрузкой');
|
||||
}
|
||||
|
||||
const lastReportDate = requestDate('Введите дату формирования последнего отчета по разовым задачам');
|
||||
const data = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
throw new Error('Нет данных для обработки');
|
||||
}
|
||||
|
||||
const headers = data[0];
|
||||
const rows = data.slice(1);
|
||||
const col = getColumnIndexes(headers);
|
||||
|
||||
const reportTasks = rows.filter(row => {
|
||||
const title = String(row[col.title] || '');
|
||||
const createdDate = row[col.created];
|
||||
const isValidCode = validateTaskCode(normalizeTaskName(title)).valid;
|
||||
const isOneTimeTask = beforeHash(title).includes('Р') || !isValidCode;
|
||||
const isAfterLastReport =
|
||||
createdDate instanceof Date &&
|
||||
createdDate >= lastReportDate && !isSameDay(createdDate, new Date());
|
||||
|
||||
return isOneTimeTask && isAfterLastReport;
|
||||
});
|
||||
|
||||
const result: any[][] = [[
|
||||
'Название задачи',
|
||||
'Название родительской задачи',
|
||||
'ID задачи',
|
||||
'ID родительской задачи',
|
||||
'Статус задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Крайний срок задачи',
|
||||
'Дата создания задачи',
|
||||
'Крайний срок родительской задачи',
|
||||
'Элементы CRM',
|
||||
'Время выполнения задачи',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
'Важная задача',
|
||||
'Требует внимания',
|
||||
'Согласен с постановкой задачи',
|
||||
'Комментарий Владимира'
|
||||
]];
|
||||
|
||||
reportTasks.sort((a, b) => Number(a[col.parentTaskId]) - Number(b[col.parentTaskId]));
|
||||
|
||||
reportTasks.forEach(mainTask => {
|
||||
const parentTaskId = mainTask[col.parentTaskId];
|
||||
const parentTask = rows.find(row => row[col.id] == parentTaskId);
|
||||
result.push(buildReportRow(mainTask, parentTask || null, col));
|
||||
});
|
||||
|
||||
const reportSheet = createTimestampedSheet(reportPrefix, ss);
|
||||
reportSheet
|
||||
.getRange(1, 1, result.length, result[0].length)
|
||||
.setValues(result);
|
||||
|
||||
addDropdownValidations(reportSheet, result[0], result.length, {
|
||||
'Согласен с постановкой задачи': ['Да', 'Внес коррективы']
|
||||
});
|
||||
|
||||
decodeTaskCodes(reportSheet);
|
||||
decodeTaskCodes(reportSheet, 'Название родительской задачи');
|
||||
setReportSheetFormat(reportSheet);
|
||||
SpreadsheetApp.flush();
|
||||
Logger.log('Отчет успешно сформирован');
|
||||
}
|
||||
|
||||
function buildReportRow(mainTask: any[], subtask: any[] | null, col: Record<string, number>): any[] {
|
||||
const attention = buildAttentionText(mainTask, col);
|
||||
|
||||
return [
|
||||
mainTask[col.title],
|
||||
subtask ? subtask[col.title] : '',
|
||||
mainTask[col.id],
|
||||
subtask ? subtask[col.id] : '',
|
||||
mainTask[col.status],
|
||||
mainTask[col.creator],
|
||||
mainTask[col.executor],
|
||||
mainTask[col.deadline],
|
||||
mainTask[col.created],
|
||||
subtask ? subtask[col.deadline] : '',
|
||||
mainTask[col.crm],
|
||||
diffMinutes(mainTask[col.startTime], mainTask[col.endTime]),
|
||||
bitrixBooleanToString(mainTask[col.clientLoss]),
|
||||
mainTask[col.price],
|
||||
bitrixBooleanToString(mainTask[col.importantTask]),
|
||||
attention,
|
||||
'',
|
||||
''
|
||||
];
|
||||
}
|
||||
|
||||
function buildAttentionText(task: any[], col: Record<string, number>): string {
|
||||
const warnings: string[] = [];
|
||||
const title = String(task[col.title] || '');
|
||||
const allowDeadlineChange = String(task[col.allowDeadlineChange] || '');
|
||||
const taskCodeValidationResult = validateTaskCode(normalizeTaskName(title));
|
||||
const isSelfTask = task[col.creator] == task[col.executor];
|
||||
|
||||
if (!taskCodeValidationResult.valid) {
|
||||
warnings.push('Ошибка в буквенном коде');
|
||||
}
|
||||
|
||||
if (
|
||||
allowDeadlineChange === 'Y' &&
|
||||
String(task[col.creator]) !== String(task[col.executor])
|
||||
) {
|
||||
warnings.push('Разрешено менять крайний срок');
|
||||
}
|
||||
|
||||
if (task[col.importantTask] == '' && !isSelfTask) {
|
||||
warnings.push('Не заполнено обязательное поле "Важная задача"');
|
||||
}
|
||||
|
||||
if (task[col.clientLoss] == '') {
|
||||
warnings.push('Не заполнено обязательное поле "Ведет к потере клиента"');
|
||||
}
|
||||
|
||||
if (task[col.deadline] == '') {
|
||||
warnings.push('Не указан крайний срок');
|
||||
}
|
||||
|
||||
return warnings.length > 0
|
||||
? 'Да:' + warnings.join(', ')
|
||||
: 'Нет';
|
||||
}
|
||||
|
||||
function getColumnIndexes(headers: any[]) {
|
||||
return {
|
||||
id: headers.indexOf('ID'),
|
||||
title: headers.indexOf('Название'),
|
||||
deadline: headers.indexOf('Крайний срок'),
|
||||
creator: headers.indexOf('Постановщик'),
|
||||
executor: headers.indexOf('Исполнитель'),
|
||||
status: headers.indexOf('Статус'),
|
||||
created: headers.indexOf('Дата создания'),
|
||||
parentTaskId: headers.indexOf('ID базовой задачи'),
|
||||
allowDeadlineChange: headers.indexOf('Разрешено изменять крайний срок'),
|
||||
price: headers.indexOf('Цена задачи'),
|
||||
crm: headers.indexOf('CRM'),
|
||||
clientLoss: headers.indexOf('Может привести к потере клиента'),
|
||||
importantTask: headers.indexOf('Важная задача'),
|
||||
startTime: headers.indexOf('Планируемая дата начала'),
|
||||
endTime: headers.indexOf('Планируемая дата окончания'),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
import { askUser } from '../../core/ui';
|
||||
import { getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { sendTempSpreadsheetToEmail } from '../../core/sheets/export';
|
||||
|
||||
export function sendAttentionTasksToCreatorsForApproval(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const reportSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
|
||||
const reportData = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (reportData.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = reportData[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const emailMap = getUserEmailMap();
|
||||
const creators: Record<string, any[][]> = {};
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = reportData[i];
|
||||
const creator = String(row[col['Постановщик']] || '').trim();
|
||||
|
||||
if (!creator) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (row[col['Требует внимания']] == 'Нет') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!creators[creator]) {
|
||||
creators[creator] = [];
|
||||
}
|
||||
|
||||
creators[creator].push([
|
||||
row[col['Название задачи']],
|
||||
row[col['Название родительской задачи']],
|
||||
row[col['ID задачи']],
|
||||
row[col['ID родительской задачи']],
|
||||
row[col['Статус задачи']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Крайний срок задачи']],
|
||||
row[col['Крайний срок родительской задачи']],
|
||||
row[col['Элементы CRM']],
|
||||
row[col['Время выполнения задачи']],
|
||||
row[col['Вероятность выполнения задачи']],
|
||||
row[col['Ведет к потере клиента']],
|
||||
row[col['Цена задачи']],
|
||||
row[col['Важная задача']],
|
||||
row[col['Требует внимания']],
|
||||
row[col['Комментарий Владимира']]
|
||||
]);
|
||||
}
|
||||
|
||||
const pdfHeaders = [
|
||||
'Название задачи',
|
||||
'Название родительской задачи',
|
||||
'ID задачи',
|
||||
'ID родительской задачи',
|
||||
'Статус задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Крайний срок задачи',
|
||||
'Крайний срок родительской задачи',
|
||||
'Элементы CRM',
|
||||
'Время выполнения задачи',
|
||||
'Вероятность выполнения задачи',
|
||||
'Ведет к потере клиента',
|
||||
'Цена задачи',
|
||||
'Важная задача',
|
||||
'Требует внимания',
|
||||
'Комментарий Владимира'
|
||||
];
|
||||
|
||||
Object.entries(creators).forEach(([creator, rows]) => {
|
||||
const email = emailMap[creator];
|
||||
if (!email) {
|
||||
return;
|
||||
}
|
||||
|
||||
sendTempSpreadsheetToEmail({
|
||||
email: email,
|
||||
fileName: 'Разовые задачи - ' + creator,
|
||||
headers: pdfHeaders,
|
||||
rows: rows,
|
||||
subject: 'Замечание по разовым задачам',
|
||||
htmlBody: 'Во вложении находятся разовые задачи, требующие исправления',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import { hideColumnsByNames, showColumnsByNames } from '../../core/sheets/reportLifecycle';
|
||||
import { notifyReportRecievers } from '../../core/mail/notify';
|
||||
|
||||
export function notifySingleTimeTasks(): void {
|
||||
const sheet = SpreadsheetApp.getActiveSheet();
|
||||
hideColumnsByNames(sheet, [
|
||||
'Согласен с крайним сроком',
|
||||
'Согласен с временем выполнения',
|
||||
'Согласен с актуальностью задачи',
|
||||
'Согласен с формулировкой'
|
||||
]);
|
||||
notifyReportRecievers('Отчет по разовым задачам');
|
||||
showColumnsByNames(sheet, [
|
||||
'Согласен с крайним сроком',
|
||||
'Согласен с временем выполнения',
|
||||
'Согласен с актуальностью задачи',
|
||||
'Согласен с формулировкой'
|
||||
]);
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
export interface MenuItem {
|
||||
label: string;
|
||||
functionName: string;
|
||||
}
|
||||
|
||||
export interface ReportPlugin {
|
||||
id: string;
|
||||
menuTitle: string;
|
||||
menuItems: MenuItem[];
|
||||
handlers: Record<string, (...args: any[]) => any>;
|
||||
requiredConfigKeys?: string[];
|
||||
requiredScriptProperties?: string[];
|
||||
htmlFiles?: string[];
|
||||
}
|
||||
|
||||
export interface ReportSheetExtras {
|
||||
freezeHeader?: boolean;
|
||||
appendDates?: boolean;
|
||||
}
|
||||
|
||||
export interface DepartmentProfile {
|
||||
id: string;
|
||||
plugins: ReportPlugin[];
|
||||
requiredConfigKeys?: string[];
|
||||
requiredScriptProperties?: string[];
|
||||
reportSheetExtras?: ReportSheetExtras;
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { buildWaitingControlReport } from './main';
|
||||
import { sendWaitingControlReports } from './notifyTaskSetters';
|
||||
import { refreshWaitingControlReport } from './reportScanner';
|
||||
import { checkWaitingControlReasonsAndSendPdf } from './salesDepHeadNotification';
|
||||
|
||||
export const waitingControlPlugin: ReportPlugin = {
|
||||
id: 'waitingControl',
|
||||
menuTitle: '3️⃣ ⏳ Ожидают контроля',
|
||||
menuItems: [
|
||||
{ label: '📈 Сформировать отчет', functionName: 'buildWaitingControlReport' },
|
||||
{ label: '🔔 Уведомить постановщиков', functionName: 'sendWaitingControlReports' },
|
||||
{ label: '🔄 Обновить статусы задач', functionName: 'refreshWaitingControlReport' },
|
||||
{ label: '👔 Отправить отчет РОПу', functionName: 'checkWaitingControlReasonsAndSendPdf' },
|
||||
],
|
||||
handlers: {
|
||||
buildWaitingControlReport,
|
||||
sendWaitingControlReports,
|
||||
refreshWaitingControlReport,
|
||||
checkWaitingControlReasonsAndSendPdf,
|
||||
},
|
||||
requiredConfigKeys: [
|
||||
'SOURCE_SHEET_ID',
|
||||
'EMAILS_SHEET_ID',
|
||||
'ROLES_SHEET_ID',
|
||||
'BACKUP_EMAILS_SPREADSHEET_ID',
|
||||
'BITRIX_PORTAL',
|
||||
'BALANCER_URL',
|
||||
],
|
||||
requiredScriptProperties: [
|
||||
'BALANCER_PUBLIC',
|
||||
'BALANCER_SECRET',
|
||||
'BITRIX_WEBHOOK_TASKS',
|
||||
],
|
||||
};
|
||||
|
|
@ -0,0 +1,211 @@
|
|||
import { REPORT_PREFIXES, WAITING_CONTROL_STATUS } from '../../core/constants';
|
||||
import { getSourceSheet, getBitrixMethodUrl } from '../../core/config';
|
||||
import { beforeHash, bitrixBooleanToString, decodeTaskCodes } from '../../core/taskCodes';
|
||||
import { fetchBalancer } from '../../core/bitrix/client';
|
||||
import { addDropdownValidations, createTimestampedSheet, setReportSheetFormat } from '../../core/sheets/reportLifecycle';
|
||||
|
||||
export function buildWaitingControlReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const values = sourceSheet.getDataRange().getValues();
|
||||
|
||||
if (values.length < 2) {
|
||||
throw new Error('На листе нет данных');
|
||||
}
|
||||
|
||||
const reportPrefix = REPORT_PREFIXES.waitingControl;
|
||||
const headers = values[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const requiredColumns = [
|
||||
'ID',
|
||||
'Название',
|
||||
'Крайний срок',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Статус',
|
||||
'Дата закрытия',
|
||||
'Может привести к потере клиента'
|
||||
];
|
||||
|
||||
const missing = requiredColumns.filter(name => !(name in col));
|
||||
if (missing.length) {
|
||||
throw new Error('Не найдены колонки: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
const reportSheet = createTimestampedSheet(reportPrefix, ss);
|
||||
const reportHeaders = [
|
||||
'ID задачи',
|
||||
'Наименование задачи',
|
||||
'ID родительской задачи',
|
||||
'Название родительской задачи',
|
||||
'Крайний срок задачи',
|
||||
'Дата создания задачи',
|
||||
'Постановщик',
|
||||
'Исполнитель',
|
||||
'Статус',
|
||||
'Результат задачи',
|
||||
'Дата закрытия',
|
||||
'Ведет к потере клиента',
|
||||
'Если сохраняется статус Ждет контроля, то опиши причину',
|
||||
'Резолюция Владимира Принять задачу или вернуть на доработку'
|
||||
];
|
||||
|
||||
const result: Array<{ lossClient: any; creator: string; executor: string; row: any[] }> = [];
|
||||
|
||||
for (let i = 1; i < values.length; i++) {
|
||||
const row = values[i];
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
|
||||
if (status !== WAITING_CONTROL_STATUS) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const taskName = String(row[col['Название']] || '').trim();
|
||||
const code = beforeHash(taskName);
|
||||
const hasRequiredLetter = code.includes('П') || code.includes('О') || code.includes('В');
|
||||
|
||||
if (!hasRequiredLetter) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result.push({
|
||||
lossClient: bitrixBooleanToString(String(row[col['Может привести к потере клиента']] || '')),
|
||||
creator: String(row[col['Постановщик']] || ''),
|
||||
executor: String(row[col['Исполнитель']] || ''),
|
||||
row: [
|
||||
row[col['ID']],
|
||||
taskName,
|
||||
row[col['ID базовой задачи']],
|
||||
row[col['Название базовой задачи']],
|
||||
row[col['Крайний срок']],
|
||||
row[col['Дата создания']],
|
||||
row[col['Постановщик']],
|
||||
row[col['Исполнитель']],
|
||||
row[col['Статус']],
|
||||
'',
|
||||
row[col['Дата закрытия']],
|
||||
bitrixBooleanToString(row[col['Может привести к потере клиента']]),
|
||||
'',
|
||||
''
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
result.sort((a, b) => {
|
||||
const aLoss = String(a.lossClient).trim().toLowerCase() === 'да';
|
||||
const bLoss = String(b.lossClient).trim().toLowerCase() === 'да';
|
||||
|
||||
if (aLoss !== bLoss) {
|
||||
return aLoss ? -1 : 1;
|
||||
}
|
||||
|
||||
const creatorCompare = String(a.creator).localeCompare(String(b.creator), 'ru');
|
||||
if (creatorCompare !== 0) {
|
||||
return creatorCompare;
|
||||
}
|
||||
|
||||
return String(a.executor).localeCompare(String(b.executor), 'ru');
|
||||
});
|
||||
|
||||
const output = [reportHeaders, ...result.map(item => item.row)];
|
||||
|
||||
reportSheet
|
||||
.getRange(1, 1, output.length, reportHeaders.length)
|
||||
.setValues(output);
|
||||
|
||||
reportSheet.autoResizeColumns(1, reportHeaders.length);
|
||||
|
||||
addDropdownValidations(reportSheet, output[0], result.length + 1, {
|
||||
'Резолюция Владимира Принять задачу или вернуть на доработку': [
|
||||
'Принять',
|
||||
'Вернуть на доработку',
|
||||
'Сохранить в "Ждет контроля"'
|
||||
]
|
||||
});
|
||||
|
||||
addTaskResultsToReportSheet(reportSheet);
|
||||
decodeTaskCodes(reportSheet);
|
||||
decodeTaskCodes(reportSheet, 'Название родительской задачи');
|
||||
setReportSheetFormat(reportSheet);
|
||||
}
|
||||
|
||||
function addTaskResultsToReportSheet(reportSheet: GoogleAppsScript.Spreadsheet.Sheet): void {
|
||||
const reportData = reportSheet.getDataRange().getValues();
|
||||
if (reportData.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
const reportHeaders = reportData[0];
|
||||
const reportCol: Record<string, number> = {};
|
||||
|
||||
reportHeaders.forEach((header, index) => {
|
||||
reportCol[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = reportData[i];
|
||||
const taskId = String(row[reportCol['ID задачи']] || '').trim();
|
||||
if (!taskId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let comment = '';
|
||||
|
||||
try {
|
||||
const results = getTaskResults(taskId);
|
||||
comment = results
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
|
||||
const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
|
||||
return dateA - dateB;
|
||||
})
|
||||
.map(r => stripBitrixMarkup(r.text).trim())
|
||||
.filter(Boolean)
|
||||
.join('\n\n');
|
||||
} catch (e: any) {
|
||||
Logger.log('Задача ' + taskId + ': ' + e.message);
|
||||
}
|
||||
|
||||
reportSheet
|
||||
.getRange(i + 1, reportCol['Результат задачи'] + 1)
|
||||
.setValue(comment);
|
||||
}
|
||||
}
|
||||
|
||||
function getTaskResults(taskId: string): any[] {
|
||||
const result = fetchBalancer(
|
||||
getBitrixMethodUrl('tasks', 'tasks.task.result.list'),
|
||||
{
|
||||
isRecurrent: true,
|
||||
muteHttpExceptions: true,
|
||||
body: { taskId: Number(taskId) }
|
||||
}
|
||||
);
|
||||
|
||||
return (result.data && result.data.body) || [];
|
||||
}
|
||||
|
||||
export function stripBitrixMarkup(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, idx, arr) => !(line === '' && arr[idx - 1] === ''))
|
||||
.join('\n')
|
||||
.trim();
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
import { askUser } from '../../core/ui';
|
||||
import { getEmailConfig, getUserEmailMap } from '../../core/mail/emailConfig';
|
||||
import { getTaskControlType } from '../../core/taskCodes';
|
||||
import { createExcelFromRows, createPdfFromRows } from '../../core/sheets/export';
|
||||
|
||||
export function sendWaitingControlReports(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const emailConfig = getEmailConfig(spreadsheet);
|
||||
const EMAIL_O = emailConfig.controllerEmail;
|
||||
const EMAIL_V = emailConfig.directorEmail;
|
||||
const reportSheet = spreadsheet.getActiveSheet();
|
||||
const data = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (data.length < 2) {
|
||||
Logger.log('В отчете нет данных');
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = data[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const missing = ['Наименование задачи', 'Постановщик'].filter(name => !(name in col));
|
||||
if (missing.length) {
|
||||
throw new Error('Не найдены колонки: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
const emailMap = getUserEmailMap();
|
||||
const tasksByCreator: Record<string, any[][]> = {};
|
||||
const tasksO: any[][] = [];
|
||||
const tasksV: any[][] = [];
|
||||
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const row = data[i];
|
||||
const taskName = String(row[col['Наименование задачи']] || '').trim();
|
||||
const creator = String(row[col['Постановщик']] || '').trim();
|
||||
const type = getTaskControlType(taskName);
|
||||
|
||||
if (!type) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === 'П') {
|
||||
if (!tasksByCreator[creator]) {
|
||||
tasksByCreator[creator] = [];
|
||||
}
|
||||
tasksByCreator[creator].push(row);
|
||||
} else if (type === 'О') {
|
||||
tasksO.push(row);
|
||||
} else if (type === 'В') {
|
||||
tasksV.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
Object.keys(tasksByCreator).forEach(creator => {
|
||||
const email = emailMap[creator];
|
||||
if (!email) {
|
||||
Logger.log('Не найден email для постановщика: ' + creator);
|
||||
return;
|
||||
}
|
||||
|
||||
const pdf = createPdfFromRows(headers, tasksByCreator[creator], 'Задачи П - ' + creator);
|
||||
const xlsx = createExcelFromRows(headers, tasksByCreator[creator], 'Задачи П - ' + creator);
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: email,
|
||||
subject: 'Задачи, ожидающие контроля',
|
||||
body: 'Во вложении список задач, ожидающих контроля.',
|
||||
attachments: [pdf, xlsx]
|
||||
});
|
||||
});
|
||||
|
||||
if (tasksO.length) {
|
||||
const pdf = createPdfFromRows(headers, tasksO, 'Задачи О');
|
||||
MailApp.sendEmail({
|
||||
to: EMAIL_O,
|
||||
subject: 'Задачи, ожидающие контроля контролером',
|
||||
body: 'Во вложении список задач.',
|
||||
attachments: [pdf]
|
||||
});
|
||||
}
|
||||
|
||||
if (tasksV.length) {
|
||||
const pdf = createPdfFromRows(headers, tasksV, 'Задачи В');
|
||||
MailApp.sendEmail({
|
||||
to: [EMAIL_V, EMAIL_O].join(','),
|
||||
subject: 'Задачи, ожидающие контроля Владимиром',
|
||||
body: 'Во вложении список задач.',
|
||||
attachments: [pdf]
|
||||
});
|
||||
}
|
||||
|
||||
SpreadsheetApp.setActiveSheet(reportSheet);
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
import { getSourceSheet } from '../../core/config';
|
||||
|
||||
export function refreshWaitingControlReport(): void {
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const reportSheet = ss.getActiveSheet();
|
||||
const sourceSheet = getSourceSheet(ss);
|
||||
const reportData = reportSheet.getDataRange().getValues();
|
||||
|
||||
if (reportData.length < 2) {
|
||||
SpreadsheetApp.getUi().alert('Задач, требующих приемки нет');
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceData = sourceSheet.getDataRange().getValues();
|
||||
const reportHeaders = reportData[0];
|
||||
const reportCol: Record<string, number> = {};
|
||||
|
||||
reportHeaders.forEach((header, index) => {
|
||||
reportCol[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const reportMissing = ['ID задачи', 'Статус', 'Постановщик'].filter(name => !(name in reportCol));
|
||||
if (reportMissing.length) {
|
||||
throw new Error('В отчете отсутствуют колонки: ' + reportMissing.join(', '));
|
||||
}
|
||||
|
||||
const sourceHeaders = sourceData[0];
|
||||
const sourceCol: Record<string, number> = {};
|
||||
|
||||
sourceHeaders.forEach((header, index) => {
|
||||
sourceCol[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const sourceMissing = ['ID', 'Статус'].filter(name => !(name in sourceCol));
|
||||
if (sourceMissing.length) {
|
||||
throw new Error('В выгрузке отсутствуют колонки: ' + sourceMissing.join(', '));
|
||||
}
|
||||
|
||||
const sourceTasks = new Map<string, any[]>();
|
||||
for (let i = 1; i < sourceData.length; i++) {
|
||||
const row = sourceData[i];
|
||||
const id = String(row[sourceCol['ID']] || '').trim();
|
||||
if (!id) continue;
|
||||
sourceTasks.set(id, row);
|
||||
}
|
||||
|
||||
const newReportData = [reportHeaders];
|
||||
const waitingTasks: Record<string, number[]> = {};
|
||||
|
||||
for (let i = 1; i < reportData.length; i++) {
|
||||
const row = [...reportData[i]];
|
||||
const id = String(row[reportCol['ID задачи']] || '').trim();
|
||||
const sourceRow = sourceTasks.get(id);
|
||||
|
||||
if (!sourceRow) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const actualStatus = String(sourceRow[sourceCol['Статус']] || '').trim();
|
||||
row[reportCol['Статус']] = actualStatus;
|
||||
newReportData.push(row);
|
||||
|
||||
if (actualStatus === 'Ждёт контроля') {
|
||||
const creator = String(row[reportCol['Постановщик']] || '').trim();
|
||||
const reportRowNumber = newReportData.length;
|
||||
|
||||
if (!waitingTasks[creator]) {
|
||||
waitingTasks[creator] = [];
|
||||
}
|
||||
|
||||
waitingTasks[creator].push(reportRowNumber);
|
||||
}
|
||||
}
|
||||
|
||||
reportSheet.clearContents();
|
||||
reportSheet
|
||||
.getRange(1, 1, newReportData.length, newReportData[0].length)
|
||||
.setValues(newReportData);
|
||||
|
||||
const creators = Object.keys(waitingTasks);
|
||||
if (!creators.length) {
|
||||
SpreadsheetApp.getUi().alert('Задач, требующих приемки нет');
|
||||
return;
|
||||
}
|
||||
|
||||
const lines = ['Остались не обработанные постановщиками задачи', ''];
|
||||
creators.sort().forEach(creator => {
|
||||
lines.push(creator + ': ' + waitingTasks[creator].join(', '));
|
||||
});
|
||||
|
||||
SpreadsheetApp.getUi().alert(lines.join('\n'));
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import { WAITING_CONTROL_STATUS } from '../../core/constants';
|
||||
import { askUser } from '../../core/ui';
|
||||
import { getEmailConfig } from '../../core/mail/emailConfig';
|
||||
import { pickRoleEmail } from '../../core/mail/notify';
|
||||
import { exportSheetToPdf } from '../../core/sheets/export';
|
||||
|
||||
export function checkWaitingControlReasonsAndSendPdf(): void {
|
||||
const confirmed = askUser('Подтвеждаете отправку?');
|
||||
if (!confirmed) return;
|
||||
|
||||
const ss = SpreadsheetApp.getActiveSpreadsheet();
|
||||
const emailConfig = getEmailConfig(ss);
|
||||
const recipient = pickRoleEmail(
|
||||
emailConfig,
|
||||
'salesDepartmentHeadEmail',
|
||||
'salesDepartmentDeputyEmail'
|
||||
);
|
||||
|
||||
if (!recipient) {
|
||||
SpreadsheetApp.getUi().alert('Не заполнены email РОПа или его заместителя');
|
||||
return;
|
||||
}
|
||||
|
||||
const sheet = ss.getActiveSheet();
|
||||
const data = sheet.getDataRange().getValues();
|
||||
const headers = data[0];
|
||||
const col: Record<string, number> = {};
|
||||
|
||||
headers.forEach((header, index) => {
|
||||
col[String(header).trim()] = index;
|
||||
});
|
||||
|
||||
const missing = [
|
||||
'Статус',
|
||||
'Если сохраняется статус Ждет контроля, то опиши причину'
|
||||
].filter(name => !(name in col));
|
||||
|
||||
if (missing.length) {
|
||||
throw new Error('Не найдены колонки: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
const invalidRows: number[] = [];
|
||||
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
const row = data[i];
|
||||
const status = String(row[col['Статус']] || '').trim();
|
||||
const reason = String(
|
||||
row[col['Если сохраняется статус Ждет контроля, то опиши причину']] || ''
|
||||
).trim();
|
||||
|
||||
if (status === WAITING_CONTROL_STATUS && !reason) {
|
||||
invalidRows.push(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidRows.length) {
|
||||
SpreadsheetApp.getUi().alert(
|
||||
'Не заполнена причина сохранения статуса "' + WAITING_CONTROL_STATUS + '" в строках:\n\n' +
|
||||
invalidRows.join(', ')
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const pdfBlob = exportSheetToPdf(ss.getId(), sheet.getSheetId(), 'Задачи на контроле');
|
||||
|
||||
MailApp.sendEmail({
|
||||
to: recipient,
|
||||
subject: 'Отчет по задачам, ожидающим контроля',
|
||||
body: 'Во вложении отчет.',
|
||||
attachments: [pdfBlob]
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import type { ReportPlugin } from '../types';
|
||||
import { reportCurrentWeek, reportNextWeek, report10Days } from './main';
|
||||
import { notifyWorkloadReport } from './reportSender';
|
||||
import { saveResponse } from './saveHeadResponse';
|
||||
|
||||
export const workloadPlugin: ReportPlugin = {
|
||||
id: 'workload',
|
||||
menuTitle: '7️⃣ 📅 Рабочая нагрузка',
|
||||
menuItems: [
|
||||
{ label: '📆 Отчет за текущую неделю', functionName: 'reportCurrentWeek' },
|
||||
{ label: '⏭️ Отчет за следующую неделю', functionName: 'reportNextWeek' },
|
||||
{ label: '⏭️ Отчет на 10 дней вперед', functionName: 'report10Days' },
|
||||
{ label: '👔 Отправить руководителю', functionName: 'notifyWorkloadReport' },
|
||||
{ label: '💾 Сохранить ответ руководителя', functionName: 'saveResponse' },
|
||||
],
|
||||
handlers: {
|
||||
reportCurrentWeek,
|
||||
reportNextWeek,
|
||||
report10Days,
|
||||
notifyWorkloadReport,
|
||||
saveResponse,
|
||||
},
|
||||
requiredConfigKeys: ['SOURCE_SHEET_ID'],
|
||||
};
|
||||
|
|
@ -0,0 +1,249 @@
|
|||
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 { 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);
|
||||
}
|
||||
|
||||
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 {
|
||||
sheet.autoResizeColumns(1, 20);
|
||||
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;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue