@friggframework/core 2.0.0-next.42 → 2.0.0-next.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
1
+ /**
2
+ * CreateProcess Use Case Tests
3
+ *
4
+ * Tests process creation with validation and error handling.
5
+ */
6
+
7
+ const { CreateProcess } = require('./create-process');
8
+
9
+ describe('CreateProcess', () => {
10
+ let createProcessUseCase;
11
+ let mockProcessRepository;
12
+
13
+ beforeEach(() => {
14
+ mockProcessRepository = {
15
+ create: jest.fn(),
16
+ };
17
+ createProcessUseCase = new CreateProcess({
18
+ processRepository: mockProcessRepository,
19
+ });
20
+ });
21
+
22
+ describe('constructor', () => {
23
+ it('should require processRepository', () => {
24
+ expect(() => new CreateProcess({})).toThrow('processRepository is required');
25
+ });
26
+
27
+ it('should initialize with processRepository', () => {
28
+ expect(createProcessUseCase.processRepository).toBe(mockProcessRepository);
29
+ });
30
+ });
31
+
32
+ describe('execute', () => {
33
+ const validProcessData = {
34
+ userId: 'user-123',
35
+ integrationId: 'integration-456',
36
+ name: 'test-crm-contact-sync',
37
+ type: 'CRM_SYNC',
38
+ };
39
+
40
+ it('should create a process with minimal required data', async () => {
41
+ const mockCreatedProcess = { id: 'process-789', ...validProcessData };
42
+ mockProcessRepository.create.mockResolvedValue(mockCreatedProcess);
43
+
44
+ const result = await createProcessUseCase.execute(validProcessData);
45
+
46
+ expect(mockProcessRepository.create).toHaveBeenCalledWith({
47
+ userId: 'user-123',
48
+ integrationId: 'integration-456',
49
+ name: 'test-crm-contact-sync',
50
+ type: 'CRM_SYNC',
51
+ state: 'INITIALIZING',
52
+ context: {},
53
+ results: {},
54
+ childProcesses: [],
55
+ parentProcessId: null,
56
+ });
57
+ expect(result).toEqual(mockCreatedProcess);
58
+ });
59
+
60
+ it('should create a process with all optional data', async () => {
61
+ const processDataWithOptions = {
62
+ ...validProcessData,
63
+ state: 'FETCHING_TOTAL',
64
+ context: { syncType: 'INITIAL', totalRecords: 100 },
65
+ results: { aggregateData: { totalSynced: 0 } },
66
+ childProcesses: ['child-1', 'child-2'],
67
+ parentProcessId: 'parent-123',
68
+ };
69
+
70
+ const mockCreatedProcess = { id: 'process-789', ...processDataWithOptions };
71
+ mockProcessRepository.create.mockResolvedValue(mockCreatedProcess);
72
+
73
+ const result = await createProcessUseCase.execute(processDataWithOptions);
74
+
75
+ expect(mockProcessRepository.create).toHaveBeenCalledWith(processDataWithOptions);
76
+ expect(result).toEqual(mockCreatedProcess);
77
+ });
78
+
79
+ it('should throw error if userId is missing', async () => {
80
+ const invalidData = { integrationId: 'int-123', name: 'test', type: 'CRM_SYNC' };
81
+
82
+ await expect(createProcessUseCase.execute(invalidData))
83
+ .rejects.toThrow('Missing required fields for process creation: userId');
84
+ });
85
+
86
+ it('should throw error if integrationId is missing', async () => {
87
+ const invalidData = { userId: 'user-123', name: 'test', type: 'CRM_SYNC' };
88
+
89
+ await expect(createProcessUseCase.execute(invalidData))
90
+ .rejects.toThrow('Missing required fields for process creation: integrationId');
91
+ });
92
+
93
+ it('should throw error if name is missing', async () => {
94
+ const invalidData = { userId: 'user-123', integrationId: 'int-123', type: 'CRM_SYNC' };
95
+
96
+ await expect(createProcessUseCase.execute(invalidData))
97
+ .rejects.toThrow('Missing required fields for process creation: name');
98
+ });
99
+
100
+ it('should throw error if type is missing', async () => {
101
+ const invalidData = { userId: 'user-123', integrationId: 'int-123', name: 'test' };
102
+
103
+ await expect(createProcessUseCase.execute(invalidData))
104
+ .rejects.toThrow('Missing required fields for process creation: type');
105
+ });
106
+
107
+ it('should throw error if userId is not a string', async () => {
108
+ const invalidData = { ...validProcessData, userId: 123 };
109
+
110
+ await expect(createProcessUseCase.execute(invalidData))
111
+ .rejects.toThrow('userId must be a string');
112
+ });
113
+
114
+ it('should throw error if integrationId is not a string', async () => {
115
+ const invalidData = { ...validProcessData, integrationId: 456 };
116
+
117
+ await expect(createProcessUseCase.execute(invalidData))
118
+ .rejects.toThrow('integrationId must be a string');
119
+ });
120
+
121
+ it('should throw error if name is not a string', async () => {
122
+ const invalidData = { ...validProcessData, name: 789 };
123
+
124
+ await expect(createProcessUseCase.execute(invalidData))
125
+ .rejects.toThrow('name must be a string');
126
+ });
127
+
128
+ it('should throw error if type is not a string', async () => {
129
+ const invalidData = { ...validProcessData, type: 999 };
130
+
131
+ await expect(createProcessUseCase.execute(invalidData))
132
+ .rejects.toThrow('type must be a string');
133
+ });
134
+
135
+ it('should throw error if state is provided but not a string', async () => {
136
+ const invalidData = { ...validProcessData, state: 123 };
137
+
138
+ await expect(createProcessUseCase.execute(invalidData))
139
+ .rejects.toThrow('state must be a string');
140
+ });
141
+
142
+ it('should throw error if context is provided but not an object', async () => {
143
+ const invalidData = { ...validProcessData, context: 'invalid' };
144
+
145
+ await expect(createProcessUseCase.execute(invalidData))
146
+ .rejects.toThrow('context must be an object');
147
+ });
148
+
149
+ it('should throw error if results is provided but not an object', async () => {
150
+ const invalidData = { ...validProcessData, results: 'invalid' };
151
+
152
+ await expect(createProcessUseCase.execute(invalidData))
153
+ .rejects.toThrow('results must be an object');
154
+ });
155
+
156
+ it('should throw error if childProcesses is provided but not an array', async () => {
157
+ const invalidData = { ...validProcessData, childProcesses: 'invalid' };
158
+
159
+ await expect(createProcessUseCase.execute(invalidData))
160
+ .rejects.toThrow('childProcesses must be an array');
161
+ });
162
+
163
+ it('should throw error if parentProcessId is provided but not a string', async () => {
164
+ const invalidData = { ...validProcessData, parentProcessId: 123 };
165
+
166
+ await expect(createProcessUseCase.execute(invalidData))
167
+ .rejects.toThrow('parentProcessId must be a string');
168
+ });
169
+
170
+ it('should handle repository errors', async () => {
171
+ const repositoryError = new Error('Database connection failed');
172
+ mockProcessRepository.create.mockRejectedValue(repositoryError);
173
+
174
+ await expect(createProcessUseCase.execute(validProcessData))
175
+ .rejects.toThrow('Failed to create process: Database connection failed');
176
+ });
177
+ });
178
+ });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * GetProcess Use Case
3
+ *
4
+ * Retrieves a process by ID with proper error handling.
5
+ * Simple use case that delegates to repository.
6
+ *
7
+ * Design Philosophy:
8
+ * - Use cases provide consistent error handling
9
+ * - Business logic layer between controllers and repositories
10
+ * - Return null for not found vs throwing error (configurable)
11
+ *
12
+ * @example
13
+ * const getProcess = new GetProcess({ processRepository });
14
+ * const process = await getProcess.execute(processId);
15
+ * // or
16
+ * const process = await getProcess.executeOrThrow(processId);
17
+ */
18
+ class GetProcess {
19
+ /**
20
+ * @param {Object} params
21
+ * @param {ProcessRepositoryInterface} params.processRepository - Repository for process data access
22
+ */
23
+ constructor({ processRepository }) {
24
+ if (!processRepository) {
25
+ throw new Error('processRepository is required');
26
+ }
27
+ this.processRepository = processRepository;
28
+ }
29
+
30
+ /**
31
+ * Execute the use case to get a process by ID
32
+ * @param {string} processId - Process ID to retrieve
33
+ * @returns {Promise<Object|null>} Process record or null if not found
34
+ * @throws {Error} If processId is invalid
35
+ */
36
+ async execute(processId) {
37
+ // Validate input
38
+ if (!processId || typeof processId !== 'string') {
39
+ throw new Error('processId must be a non-empty string');
40
+ }
41
+
42
+ // Delegate to repository
43
+ try {
44
+ const process = await this.processRepository.findById(processId);
45
+ return process;
46
+ } catch (error) {
47
+ throw new Error(`Failed to retrieve process: ${error.message}`);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Execute and throw if process not found
53
+ * @param {string} processId - Process ID to retrieve
54
+ * @returns {Promise<Object>} Process record
55
+ * @throws {Error} If process not found or retrieval fails
56
+ */
57
+ async executeOrThrow(processId) {
58
+ const process = await this.execute(processId);
59
+
60
+ if (!process) {
61
+ throw new Error(`Process not found: ${processId}`);
62
+ }
63
+
64
+ return process;
65
+ }
66
+
67
+ /**
68
+ * Get multiple processes by IDs
69
+ * @param {string[]} processIds - Array of process IDs
70
+ * @returns {Promise<Array>} Array of process records (excludes not found)
71
+ */
72
+ async executeMany(processIds) {
73
+ if (!Array.isArray(processIds)) {
74
+ throw new Error('processIds must be an array');
75
+ }
76
+
77
+ const processes = await Promise.all(
78
+ processIds.map(id => this.execute(id))
79
+ );
80
+
81
+ // Filter out nulls (not found)
82
+ return processes.filter(p => p !== null);
83
+ }
84
+ }
85
+
86
+ module.exports = { GetProcess };
87
+
@@ -0,0 +1,190 @@
1
+ /**
2
+ * GetProcess Use Case Tests
3
+ *
4
+ * Tests process retrieval with error handling.
5
+ */
6
+
7
+ const { GetProcess } = require('./get-process');
8
+
9
+ describe('GetProcess', () => {
10
+ let getProcessUseCase;
11
+ let mockProcessRepository;
12
+
13
+ beforeEach(() => {
14
+ mockProcessRepository = {
15
+ findById: jest.fn(),
16
+ };
17
+ getProcessUseCase = new GetProcess({
18
+ processRepository: mockProcessRepository,
19
+ });
20
+ });
21
+
22
+ describe('constructor', () => {
23
+ it('should require processRepository', () => {
24
+ expect(() => new GetProcess({})).toThrow('processRepository is required');
25
+ });
26
+
27
+ it('should initialize with processRepository', () => {
28
+ expect(getProcessUseCase.processRepository).toBe(mockProcessRepository);
29
+ });
30
+ });
31
+
32
+ describe('execute', () => {
33
+ const processId = 'process-123';
34
+ const mockProcess = {
35
+ id: processId,
36
+ userId: 'user-456',
37
+ integrationId: 'integration-789',
38
+ name: 'test-sync',
39
+ type: 'CRM_SYNC',
40
+ state: 'PROCESSING_BATCHES',
41
+ context: {
42
+ syncType: 'INITIAL',
43
+ totalRecords: 1000,
44
+ processedRecords: 500,
45
+ },
46
+ results: {
47
+ aggregateData: {
48
+ totalSynced: 480,
49
+ totalFailed: 20,
50
+ duration: 120000,
51
+ recordsPerSecond: 4.17,
52
+ },
53
+ },
54
+ createdAt: new Date('2024-01-01T10:00:00Z'),
55
+ updatedAt: new Date('2024-01-01T10:02:00Z'),
56
+ };
57
+
58
+ it('should retrieve a process by ID', async () => {
59
+ mockProcessRepository.findById.mockResolvedValue(mockProcess);
60
+
61
+ const result = await getProcessUseCase.execute(processId);
62
+
63
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith(processId);
64
+ expect(result).toEqual(mockProcess);
65
+ });
66
+
67
+ it('should return null if process not found', async () => {
68
+ mockProcessRepository.findById.mockResolvedValue(null);
69
+
70
+ const result = await getProcessUseCase.execute(processId);
71
+
72
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith(processId);
73
+ expect(result).toBeNull();
74
+ });
75
+
76
+ it('should throw error if processId is missing', async () => {
77
+ await expect(getProcessUseCase.execute(''))
78
+ .rejects.toThrow('processId must be a non-empty string');
79
+ });
80
+
81
+ it('should throw error if processId is not a string', async () => {
82
+ await expect(getProcessUseCase.execute(123))
83
+ .rejects.toThrow('processId must be a non-empty string');
84
+ });
85
+
86
+ it('should handle repository errors', async () => {
87
+ const repositoryError = new Error('Database connection failed');
88
+ mockProcessRepository.findById.mockRejectedValue(repositoryError);
89
+
90
+ await expect(getProcessUseCase.execute(processId))
91
+ .rejects.toThrow('Failed to retrieve process: Database connection failed');
92
+ });
93
+ });
94
+
95
+ describe('executeOrThrow', () => {
96
+ const processId = 'process-123';
97
+ const mockProcess = {
98
+ id: processId,
99
+ userId: 'user-456',
100
+ integrationId: 'integration-789',
101
+ name: 'test-sync',
102
+ type: 'CRM_SYNC',
103
+ state: 'COMPLETED',
104
+ };
105
+
106
+ it('should return process if found', async () => {
107
+ mockProcessRepository.findById.mockResolvedValue(mockProcess);
108
+
109
+ const result = await getProcessUseCase.executeOrThrow(processId);
110
+
111
+ expect(result).toEqual(mockProcess);
112
+ });
113
+
114
+ it('should throw error if process not found', async () => {
115
+ mockProcessRepository.findById.mockResolvedValue(null);
116
+
117
+ await expect(getProcessUseCase.executeOrThrow(processId))
118
+ .rejects.toThrow('Process not found: process-123');
119
+ });
120
+
121
+ it('should propagate repository errors', async () => {
122
+ const repositoryError = new Error('Database connection failed');
123
+ mockProcessRepository.findById.mockRejectedValue(repositoryError);
124
+
125
+ await expect(getProcessUseCase.executeOrThrow(processId))
126
+ .rejects.toThrow('Failed to retrieve process: Database connection failed');
127
+ });
128
+ });
129
+
130
+ describe('executeMany', () => {
131
+ const processIds = ['process-1', 'process-2', 'process-3'];
132
+ const mockProcesses = [
133
+ { id: 'process-1', name: 'sync-1', state: 'COMPLETED' },
134
+ { id: 'process-2', name: 'sync-2', state: 'PROCESSING' },
135
+ // process-3 will not be found
136
+ ];
137
+
138
+ it('should retrieve multiple processes', async () => {
139
+ mockProcessRepository.findById
140
+ .mockResolvedValueOnce(mockProcesses[0]) // process-1 found
141
+ .mockResolvedValueOnce(mockProcesses[1]) // process-2 found
142
+ .mockResolvedValueOnce(null); // process-3 not found
143
+
144
+ const result = await getProcessUseCase.executeMany(processIds);
145
+
146
+ expect(mockProcessRepository.findById).toHaveBeenCalledTimes(3);
147
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-1');
148
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-2');
149
+ expect(mockProcessRepository.findById).toHaveBeenCalledWith('process-3');
150
+
151
+ // Should return only found processes
152
+ expect(result).toEqual([mockProcesses[0], mockProcesses[1]]);
153
+ });
154
+
155
+ it('should return empty array if no processes found', async () => {
156
+ mockProcessRepository.findById
157
+ .mockResolvedValueOnce(null)
158
+ .mockResolvedValueOnce(null)
159
+ .mockResolvedValueOnce(null);
160
+
161
+ const result = await getProcessUseCase.executeMany(processIds);
162
+
163
+ expect(result).toEqual([]);
164
+ });
165
+
166
+ it('should throw error if processIds is not an array', async () => {
167
+ await expect(getProcessUseCase.executeMany('not-an-array'))
168
+ .rejects.toThrow('processIds must be an array');
169
+ });
170
+
171
+ it('should handle mixed success and failure', async () => {
172
+ const repositoryError = new Error('Database error');
173
+ mockProcessRepository.findById
174
+ .mockResolvedValueOnce(mockProcesses[0]) // process-1 found
175
+ .mockRejectedValueOnce(repositoryError) // process-2 error
176
+ .mockResolvedValueOnce(null); // process-3 not found
177
+
178
+ // Should propagate the repository error
179
+ await expect(getProcessUseCase.executeMany(processIds))
180
+ .rejects.toThrow('Failed to retrieve process: Database error');
181
+ });
182
+
183
+ it('should handle empty array', async () => {
184
+ const result = await getProcessUseCase.executeMany([]);
185
+
186
+ expect(mockProcessRepository.findById).not.toHaveBeenCalled();
187
+ expect(result).toEqual([]);
188
+ });
189
+ });
190
+ });
@@ -2,10 +2,18 @@ const { GetIntegrationsForUser } = require('./get-integrations-for-user');
2
2
  const { DeleteIntegrationForUser } = require('./delete-integration-for-user');
3
3
  const { CreateIntegration } = require('./create-integration');
4
4
  const { GetIntegration } = require('./get-integration');
5
+ const { CreateProcess } = require('./create-process');
6
+ const { UpdateProcessState } = require('./update-process-state');
7
+ const { UpdateProcessMetrics } = require('./update-process-metrics');
8
+ const { GetProcess } = require('./get-process');
5
9
 
6
10
  module.exports = {
7
11
  GetIntegrationsForUser,
8
12
  DeleteIntegrationForUser,
9
13
  CreateIntegration,
10
14
  GetIntegration,
15
+ CreateProcess,
16
+ UpdateProcessState,
17
+ UpdateProcessMetrics,
18
+ GetProcess,
11
19
  };
@@ -0,0 +1,201 @@
1
+ /**
2
+ TODO:
3
+ This implementation contains a race condition in the `execute` method. When multiple concurrent processes call this method on the same process record, they'll each read the current state, modify it independently, and then save - potentially overwriting each other's changes.
4
+
5
+ For example:
6
+ ```
7
+ Thread 1: reads process with totalSynced=100
8
+ Thread 2: reads process with totalSynced=100
9
+ Thread 1: adds 50 → writes totalSynced=150
10
+ Thread 2: adds 30 → writes totalSynced=130 (overwrites Thread 1's update!)
11
+ ```
12
+
13
+ Consider implementing one of these patterns:
14
+ 1. Database transactions with row locking
15
+ 2. Optimistic concurrency control with version numbers
16
+ 3. Atomic update operations (e.g., `$inc` in MongoDB)
17
+ 4. A FIFO queue for process updates (as described in the PROCESS_MANAGEMENT_QUEUE_SPEC.md)
18
+
19
+ The current approach will lead to lost updates and inconsistent metrics during concurrent processing.
20
+
21
+ */
22
+
23
+ /**
24
+ * UpdateProcessMetrics Use Case
25
+ *
26
+ * Updates process metrics, calculates aggregates, and computes estimated completion time.
27
+ * Optionally broadcasts progress via WebSocket service if provided.
28
+ *
29
+ * Design Philosophy:
30
+ * - Metrics are cumulative (add to existing counts)
31
+ * - Performance metrics calculated automatically (duration, records/sec)
32
+ * - ETA computed based on current progress
33
+ * - Error history limited to last 100 entries
34
+ * - WebSocket broadcasting is optional (DI pattern)
35
+ *
36
+ * @example
37
+ * const updateMetrics = new UpdateProcessMetrics({ processRepository, websocketService });
38
+ * await updateMetrics.execute(processId, {
39
+ * processed: 100,
40
+ * success: 95,
41
+ * errors: 5,
42
+ * errorDetails: [{ contactId: 'abc', error: 'Missing email', timestamp: '...' }]
43
+ * });
44
+ */
45
+ class UpdateProcessMetrics {
46
+ /**
47
+ * @param {Object} params
48
+ * @param {ProcessRepositoryInterface} params.processRepository - Repository for process data access
49
+ * @param {Object} [params.websocketService] - Optional WebSocket service for progress broadcasting
50
+ */
51
+ constructor({ processRepository, websocketService }) {
52
+ if (!processRepository) {
53
+ throw new Error('processRepository is required');
54
+ }
55
+ this.processRepository = processRepository;
56
+ this.websocketService = websocketService;
57
+ }
58
+
59
+ /**
60
+ * Execute the use case to update process metrics
61
+ * @param {string} processId - Process ID to update
62
+ * @param {Object} metricsUpdate - Metrics to add/update
63
+ * @param {number} [metricsUpdate.processed=0] - Number of records processed in this batch
64
+ * @param {number} [metricsUpdate.success=0] - Number of successful records
65
+ * @param {number} [metricsUpdate.errors=0] - Number of failed records
66
+ * @param {Array} [metricsUpdate.errorDetails=[]] - Error details array
67
+ * @returns {Promise<Object>} Updated process record
68
+ * @throws {Error} If process not found or update fails
69
+ */
70
+ async execute(processId, metricsUpdate) {
71
+ // Validate inputs
72
+ if (!processId || typeof processId !== 'string') {
73
+ throw new Error('processId must be a non-empty string');
74
+ }
75
+ if (!metricsUpdate || typeof metricsUpdate !== 'object') {
76
+ throw new Error('metricsUpdate must be an object');
77
+ }
78
+
79
+ // Retrieve current process
80
+ const process = await this.processRepository.findById(processId);
81
+ if (!process) {
82
+ throw new Error(`Process not found: ${processId}`);
83
+ }
84
+
85
+ // Get current context and results
86
+ const context = process.context || {};
87
+ const results = process.results || { aggregateData: {} };
88
+
89
+ // Initialize nested objects if not present
90
+ if (!results.aggregateData) {
91
+ results.aggregateData = {};
92
+ }
93
+
94
+ // Update context counters (cumulative)
95
+ context.processedRecords =
96
+ (context.processedRecords || 0) + (metricsUpdate.processed || 0);
97
+
98
+ // Update results aggregates (cumulative)
99
+ results.aggregateData.totalSynced =
100
+ (results.aggregateData.totalSynced || 0) +
101
+ (metricsUpdate.success || 0);
102
+ results.aggregateData.totalFailed =
103
+ (results.aggregateData.totalFailed || 0) +
104
+ (metricsUpdate.errors || 0);
105
+
106
+ // Append error details (limited to last 100)
107
+ if (
108
+ metricsUpdate.errorDetails &&
109
+ metricsUpdate.errorDetails.length > 0
110
+ ) {
111
+ results.aggregateData.errors = [
112
+ ...(results.aggregateData.errors || []),
113
+ ...metricsUpdate.errorDetails,
114
+ ].slice(-100); // Keep only last 100 errors
115
+ }
116
+
117
+ // Calculate performance metrics
118
+ const startTime = new Date(context.startTime || process.createdAt);
119
+ const elapsed = Date.now() - startTime.getTime();
120
+ results.aggregateData.duration = elapsed;
121
+
122
+ if (elapsed > 0 && context.processedRecords > 0) {
123
+ results.aggregateData.recordsPerSecond =
124
+ context.processedRecords / (elapsed / 1000);
125
+ } else {
126
+ results.aggregateData.recordsPerSecond = 0;
127
+ }
128
+
129
+ // Calculate ETA if we know total
130
+ if (context.totalRecords > 0 && context.processedRecords > 0) {
131
+ const remaining = context.totalRecords - context.processedRecords;
132
+ if (results.aggregateData.recordsPerSecond > 0) {
133
+ const etaMs =
134
+ (remaining / results.aggregateData.recordsPerSecond) * 1000;
135
+ const eta = new Date(Date.now() + etaMs);
136
+ context.estimatedCompletion = eta.toISOString();
137
+ }
138
+ }
139
+
140
+ // Prepare updates
141
+ const updates = {
142
+ context,
143
+ results,
144
+ };
145
+
146
+ // Persist updates
147
+ let updatedProcess;
148
+ try {
149
+ updatedProcess = await this.processRepository.update(
150
+ processId,
151
+ updates
152
+ );
153
+ } catch (error) {
154
+ throw new Error(
155
+ `Failed to update process metrics: ${error.message}`
156
+ );
157
+ }
158
+
159
+ // Broadcast progress via WebSocket (if service provided)
160
+ if (this.websocketService) {
161
+ await this._broadcastProgress(updatedProcess);
162
+ }
163
+
164
+ return updatedProcess;
165
+ }
166
+
167
+ /**
168
+ * Broadcast progress update via WebSocket
169
+ * @private
170
+ * @param {Object} process - Updated process record
171
+ */
172
+ async _broadcastProgress(process) {
173
+ try {
174
+ const context = process.context || {};
175
+ const results = process.results || { aggregateData: {} };
176
+ const aggregateData = results.aggregateData || {};
177
+
178
+ await this.websocketService.broadcast({
179
+ type: 'PROCESS_PROGRESS',
180
+ data: {
181
+ processId: process.id,
182
+ processName: process.name,
183
+ processType: process.type,
184
+ state: process.state,
185
+ processed: context.processedRecords || 0,
186
+ total: context.totalRecords || 0,
187
+ successCount: aggregateData.totalSynced || 0,
188
+ errorCount: aggregateData.totalFailed || 0,
189
+ recordsPerSecond: aggregateData.recordsPerSecond || 0,
190
+ estimatedCompletion: context.estimatedCompletion || null,
191
+ timestamp: new Date().toISOString(),
192
+ },
193
+ });
194
+ } catch (error) {
195
+ // Log but don't fail the update if WebSocket broadcast fails
196
+ console.error('Failed to broadcast process progress:', error);
197
+ }
198
+ }
199
+ }
200
+
201
+ module.exports = { UpdateProcessMetrics };