Files
gridpilot.gg/core/automation/application/use-cases/StartAutomationSessionUseCase.ts
2025-12-15 13:46:07 +01:00

49 lines
2.3 KiB
TypeScript

import type { AsyncUseCase } from '@gridpilot/shared/application';
import type { ILogger } from '../../../shared/src/logging/ILogger';
import { AutomationSession } from '../../domain/entities/AutomationSession';
import type { HostedSessionConfig } from '../../domain/types/HostedSessionConfig';
import { AutomationEnginePort } from '../ports/AutomationEnginePort';
import type { IBrowserAutomation } from '../ports/ScreenAutomationPort';
import { SessionRepositoryPort } from '../ports/SessionRepositoryPort';
import type { SessionDTO } from '../dto/SessionDTO';
export class StartAutomationSessionUseCase
implements AsyncUseCase<HostedSessionConfig, SessionDTO> {
constructor(
private readonly automationEngine: AutomationEnginePort,
private readonly browserAutomation: IBrowserAutomation,
private readonly sessionRepository: SessionRepositoryPort,
private readonly logger: ILogger
) {}
async execute(config: HostedSessionConfig): Promise<SessionDTO> {
this.logger.debug('Starting automation session execution', { config });
const session = AutomationSession.create(config);
this.logger.info(`Automation session created with ID: ${session.id}`);
const validationResult = await this.automationEngine.validateConfiguration(config);
if (!validationResult.isValid) {
this.logger.warn('Automation session configuration validation failed', { config, error: validationResult.error });
this.logger.error('Automation session configuration validation failed', { config, error: validationResult.error });
throw new Error(validationResult.error);
}
this.logger.debug('Automation session configuration validated successfully.');
await this.sessionRepository.save(session);
this.logger.info(`Automation session with ID: ${session.id} saved to repository.`);
const dto: SessionDTO = {
sessionId: session.id,
state: session.state.value,
currentStep: session.currentStep.value,
config: session.config,
...(session.startedAt ? { startedAt: session.startedAt } : {}),
...(session.completedAt ? { completedAt: session.completedAt } : {}),
...(session.errorMessage ? { errorMessage: session.errorMessage } : {}),
};
this.logger.debug('Automation session executed successfully, returning DTO.', { dto });
return dto;
}
}