/
npronnikov
/
ProcessVisualizer
Обзор
Документация
Войти
/
npronnikov
/
ProcessVisualizer
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
backend/src/scripts/seed-test-data.ts
304 строки
12 KB
Madnick
refactor metrics fields and update remaining calculation
18 май 2026, 19:06
18 май 2026, 19:06
0f0c9d2
Код
Авторство
О чём код?
import db from '../database/connection'; import { v4 as uuidv4 } from 'uuid'; // Test data structure interface GroupData { name: string; description: string; weightUnit: 'percentage'; processes: ProcessData[]; } interface ProcessData { name: string; description: string; responsible: string; totalValue: number; targetValue: number; hasBpmn: boolean; // true = OK status, false = NEED_BPM_DIAGRAM operations: OperationData[]; } interface OperationData { name: string; bpmnElementId: string; isManual: boolean; factEffort: number; targetEffort: number; } // Clear all data except users function clearData(): void { console.log('Clearing existing data (keeping users)...'); db.exec('DELETE FROM operation_history'); db.exec('DELETE FROM operations'); db.exec('DELETE FROM processes'); db.exec('DELETE FROM process_groups'); console.log('Data cleared.'); } // Generate history records for an operation // Past dates (before today Feb 6, 2026): plan AND fact // Future dates (after today): plan only function generateHistory(operationId: string, isManual: boolean, baseFact: number, baseTarget: number): void { const today = new Date('2026-02-06'); // History dates spread from Jan 1 to Mar 30 const historyDates = [ new Date('2026-01-05T10:00:00Z'), // past - plan & fact new Date('2026-01-20T10:00:00Z'), // past - plan & fact new Date('2026-02-03T10:00:00Z'), // past - plan & fact new Date('2026-02-15T10:00:00Z'), // future - plan only new Date('2026-03-01T10:00:00Z'), // future - plan only new Date('2026-03-20T10:00:00Z'), // future - plan only ]; // Randomly pick 4-6 dates const numRecords = 4 + Math.floor(Math.random() * 3); // 4, 5, or 6 const selectedDates = historyDates.slice(0, numRecords); for (let i = 0; i < selectedDates.length; i++) { const date = selectedDates[i]; const id = uuidv4(); const isPast = date < today; // Gradually improving values (fact decreasing towards target) const planValue = Math.max(baseTarget, baseFact - (i * 0.5)); const factValue = isPast ? Math.max(baseTarget, baseFact - (i * 0.3)) : null; db.prepare(` INSERT INTO operation_history (id, operation_id, plan_effort_per_day, fact_effort, target_effort, is_manual, comment, user_login, recorded_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `).run( id, operationId, planValue, factValue, baseTarget, isManual ? 1 : 0, isPast ? `Факт за ${date.toLocaleDateString('ru-RU')}` : `План на ${date.toLocaleDateString('ru-RU')}`, 'user', date.toISOString() ); } } // Seed test data function seedData(): void { console.log('Seeding test data...'); // Get demo user ID const demoUser = db.prepare('SELECT id FROM users WHERE login = ?').get('demo') as { id: string } | undefined; if (!demoUser) { throw new Error('Demo user not found. Please ensure demo user exists in database.'); } const demoUserId = demoUser.id; console.log(`Using creator_id: ${demoUserId} (demo user)`); const testData: GroupData[] = [ { name: 'Финансовые процессы', description: 'Процессы финансового отдела', weightUnit: 'percentage', processes: [ { name: 'Расчёт заработной платы', description: 'Ежемесячный расчёт ЗП сотрудников', responsible: 'Иванов И.И.', totalValue: 120, targetValue: 40, hasBpmn: true, operations: [ { name: 'Сбор табелей', bpmnElementId: 'Activity_Collect', isManual: true, factEffort: 4, targetEffort: 1 }, { name: 'Расчёт начислений', bpmnElementId: 'Activity_Calculate', isManual: true, factEffort: 6, targetEffort: 2 }, ], }, { name: 'Формирование отчётности', description: 'Квартальная финансовая отчётность', responsible: 'Петров П.П.', totalValue: 80, targetValue: 30, hasBpmn: true, operations: [ { name: 'Сверка данных', bpmnElementId: 'Activity_Verify', isManual: true, factEffort: 5, targetEffort: 1.5 }, { name: 'Консолидация', bpmnElementId: 'Activity_Consolidate', isManual: true, factEffort: 4, targetEffort: 1 }, { name: 'Выгрузка в систему', bpmnElementId: 'Activity_Export', isManual: true, factEffort: 2, targetEffort: 0.5 }, ], }, { name: 'Оплата счетов', description: 'Обработка и оплата счетов поставщиков', responsible: 'Сидорова А.А.', totalValue: 60, targetValue: 20, hasBpmn: true, operations: [ { name: 'Проверка счетов', bpmnElementId: 'Activity_CheckInvoice', isManual: true, factEffort: 3, targetEffort: 0.5 }, ], }, ], }, { name: 'HR процессы', description: 'Процессы управления персоналом', weightUnit: 'percentage', processes: [ { name: 'Приём на работу', description: 'Процесс оформления новых сотрудников', responsible: 'Козлова М.В.', totalValue: 40, targetValue: 15, hasBpmn: true, operations: [ { name: 'Проверка документов', bpmnElementId: 'Activity_CheckDocs', isManual: true, factEffort: 2, targetEffort: 0.5 }, { name: 'Оформление в системе', bpmnElementId: 'Activity_Register', isManual: true, factEffort: 1.5, targetEffort: 0.3 }, ], }, { name: 'Оценка персонала', description: 'Ежегодная оценка эффективности', responsible: 'Козлова М.В.', totalValue: 100, targetValue: 40, hasBpmn: false, // NO BPMN - will trigger alert operations: [ { name: 'Сбор показателей', bpmnElementId: 'Activity_CollectKPI', isManual: true, factEffort: 8, targetEffort: 2 }, { name: 'Формирование отчётов', bpmnElementId: 'Activity_Reports', isManual: true, factEffort: 5, targetEffort: 1 }, ], }, ], }, { name: 'Документооборот', description: 'Процессы обработки документов', weightUnit: 'percentage', processes: [ { name: 'Входящая корреспонденция', description: 'Обработка входящих документов', responsible: 'Николаева Е.С.', totalValue: 500, targetValue: 150, hasBpmn: true, operations: [ { name: 'Регистрация', bpmnElementId: 'Activity_RegisterDoc', isManual: true, factEffort: 50, targetEffort: 10 }, { name: 'Сканирование', bpmnElementId: 'Activity_Scan', isManual: true, factEffort: 30, targetEffort: 5 }, ], }, { name: 'Исходящая корреспонденция', description: 'Отправка исходящих документов', responsible: 'Николаева Е.С.', totalValue: 300, targetValue: 100, hasBpmn: true, operations: [ { name: 'Подготовка к отправке', bpmnElementId: 'Activity_Prepare', isManual: true, factEffort: 25, targetEffort: 8 }, ], }, { name: 'Архивирование', description: 'Архивирование документов', responsible: 'Федоров К.Л.', totalValue: 200, targetValue: 50, hasBpmn: true, operations: [ { name: 'Сортировка', bpmnElementId: 'Activity_Sort', isManual: true, factEffort: 20, targetEffort: 5 }, { name: 'Размещение в архиве', bpmnElementId: 'Activity_Archive', isManual: true, factEffort: 15, targetEffort: 3 }, { name: 'Внесение в реестр', bpmnElementId: 'Activity_Registry', isManual: true, factEffort: 10, targetEffort: 2 }, ], }, { name: 'Электронный архив', description: 'Перевод в электронный вид', responsible: 'Федоров К.Л.', totalValue: 400, targetValue: 100, hasBpmn: true, operations: [ { name: 'Оцифровка', bpmnElementId: 'Activity_Digitize', isManual: true, factEffort: 40, targetEffort: 10 }, { name: 'Индексация', bpmnElementId: 'Activity_Index', isManual: true, factEffort: 25, targetEffort: 5 }, ], }, ], }, ]; // Insert data for (const group of testData) { const groupId = uuidv4(); const now = new Date().toISOString(); // Insert group db.prepare(` INSERT INTO process_groups (id, name, description, weight_unit, creator_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) `).run(groupId, group.name, group.description, group.weightUnit, demoUserId, now, now); console.log(`Created group: ${group.name}`); for (const process of group.processes) { const processId = uuidv4(); const status = process.hasBpmn ? 'OK' : 'NEED_BPM_DIAGRAM'; const bpmnPath = process.hasBpmn ? `bpmn/${processId}.bpmn` : null; // Insert process db.prepare(` INSERT INTO processes (id, group_id, name, description, responsible, total_value, target_value, bpmn_file_path, status, creator_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run(processId, groupId, process.name, process.description, process.responsible, process.totalValue, process.targetValue, bpmnPath, status, demoUserId, now, now); console.log(` Created process: ${process.name} (${status})`); for (const op of process.operations) { const operationId = uuidv4(); // Insert operation db.prepare(` INSERT INTO operations (id, process_id, bpmn_element_id, name, is_manual, fact_effort, target_effort, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `).run(operationId, processId, op.bpmnElementId, op.name, op.isManual ? 1 : 0, op.factEffort, op.targetEffort, now, now); console.log(` Created operation: ${op.name}`); // Generate history for manual operations if (op.isManual) { generateHistory(operationId, op.isManual, op.factEffort, op.targetEffort); console.log(` Generated 4-6 history records`); } } } } // Count stats const groupCount = testData.length; const processCount = testData.reduce((sum, g) => sum + g.processes.length, 0); const operationCount = testData.reduce((sum, g) => sum + g.processes.reduce((s, p) => s + p.operations.length, 0), 0); const processesWithBpmn = testData.reduce((sum, g) => sum + g.processes.filter(p => p.hasBpmn).length, 0); const processesWithoutBpmn = processCount - processesWithBpmn; console.log('\nTest data seeding completed!'); console.log('Summary:'); console.log(` Groups: ${groupCount}`); console.log(` Processes: ${processCount} (${processesWithBpmn} OK, ${processesWithoutBpmn} without BPMN)`); console.log(` Operations: ${operationCount}`); console.log(` History: 4-6 records per operation`); console.log(` - Past dates (before Feb 6): plan + fact`); console.log(` - Future dates (after Feb 6): plan only`); } // Main execution function main(): void { try { clearData(); seedData(); } catch (error) { console.error('Error seeding data:', error); process.exit(1); } } main();