*/ final class ImportEmployees implements Action { public function __construct( private readonly LoggerInterface $logger, private readonly EmployeeCsvReaderService $employeeCsvReaderService, private readonly EmployeeUpsertService $employeeUpsertService, ) { } /** @param \App\Cqs\Actions\Employee\ImportEmployeesInput $input */ public function __invoke(ActionInput $input): ImportEmployeesOutput { Assert::isAOf($input, ImportEmployeesInput::class); $csvLines = $this->employeeCsvReaderService->importEmployeesFromCsv($input->inputStream); $this->logger->debug('Retrieved employees from CSV.', [ 'count' => count([...$csvLines]), ]); $csvErrors = array_filter( $csvLines, fn ($employee) => is_string($employee) ); $importedEmployees = array_map( fn (ServicesEmployeeCsvImportLine $csvLine) => $this->mapToArcadiaEmployee($csvLine), array_filter( $csvLines, fn ($employee) => $employee instanceof ServicesEmployeeCsvImportLine ) ); $employees = array_filter( $importedEmployees, fn ($employee) => $employee instanceof ArcadiaEmployee ); $mappingErrors = array_filter( $importedEmployees, fn ($employee) => is_string($employee) ); $result = $this->employeeUpsertService->upsertEmployees($employees); $totalInserted = $result->insertedCount; $totalUpdated = $result->updatedCount; $errors = array_values([ ...$csvErrors, ...$mappingErrors, ...$result->errors, ]); $this->logger->info('Employee synchronization completed successfully.', [ 'total_inserted' => $totalInserted, 'total_updated' => $totalUpdated, 'errors_count' => count($errors), ]); return new ImportEmployeesOutput( insertedCount: $totalInserted, updatedCount: $totalUpdated, errors: $errors, ); } private function mapToArcadiaEmployee(ServicesEmployeeCsvImportLine $csvLine): ArcadiaEmployee | string { try { return new ArcadiaEmployee( matricule: new Matricule($csvLine->matricule), lastname: $csvLine->lastName, firstname: $csvLine->firstName, startDate: $csvLine->startDate, endDate: $csvLine->endDate ?? $csvLine->expectedEndDate, etablissement: new ShopperEstablishmentCode($csvLine->establishment), site: new ShopperSiteCode($csvLine->site), service: new ShopperServiceCode($csvLine->service), ); } catch (\Throwable $e) { return "Matricule {$csvLine->matricule}: {$e->getMessage()}"; } } }