ldc-cocotte/domain/Services/EmployeeImportService.php
2026-10-27 09:58:12 +01:00

197 lines
6.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Domain\Services;
use Carbon\CarbonImmutable;
use Domain\Events\Dto\SalariesHaveBeenImported;
use Domain\Models\ValueObjects\CsvImportFile;
use Domain\Models\ValueObjects\EmployeeImport;
use Domain\Models\ValueObjects\EmployeeUpsertData;
use Domain\Models\ValueObjects\Matricule;
use Domain\Ports\Services\AdminAuthenticationService;
use Domain\Ports\Services\CsvReaderService;
use Domain\Ports\Services\EmployeeImportStorageService;
use Shared\DDD\DomainEventDispatcher;
use Shared\Helpers\DatesHelper;
class EmployeeImportService
{
public function __construct(
private readonly CsvReaderService $csvReader,
private readonly CodeGenerationService $codeService,
/** @var AdminAuthenticationService<\Domain\Contracts\AdminDetails> */
private readonly AdminAuthenticationService $authService,
private readonly DomainEventDispatcher $eventDispatcher,
private readonly EmployeeImportStorageService $employeeImportStorageService
) {
}
/**
* @return object{insertedCount:int,updatedCount:int,errors:string[]}
*/
public function import(CsvImportFile $file): object
{
$errors = [];
$matriculesToInsert = [];
$matriculesInserted = [];
$upsertData = [];
$importStartTime = CarbonImmutable::now()->subSecond();
$stream = $this->csvReader->read(
$file,
fn (array $row) => $this->fromCsvRow($row)
);
foreach ($stream as $importRowResult) {
if (! $importRowResult->isSuccess()) {
$errors[] = "Line {$importRowResult->lineNumber} : " . $importRowResult->error;
continue;
}
/** @var \Domain\Models\ValueObjects\EmployeeImport $employeeImport */
$employeeImport = $importRowResult->mappedResult;
$matricule = $employeeImport->matricule->value;
if (in_array($matricule, $matriculesToInsert, true)) {
$errors[] = "Duplicate detected in the file: The matricule {$matricule} appears multiple times.";
continue;
}
$matriculesToInsert[] = $matricule;
// NOTE: We generate a new code for each row, but only insert it for new records.
$code = $this->codeService->generate();
$upsertData[] = new EmployeeUpsertData(
matricule: $employeeImport->matricule,
nom: $employeeImport->nom,
prenom: $employeeImport->prenom,
etablissement: $employeeImport->etablissement,
service: $employeeImport->service,
site: $employeeImport->site,
startDate: $employeeImport->startDate,
endDate: $employeeImport->endDate,
code: $code
);
}
if (empty($upsertData) && empty($errors)) {
$errors[] = 'The file contains no valid data.';
}
if (! empty($upsertData)) {
$this->employeeImportStorageService->upsertEmployees($upsertData);
$result = $this->employeeImportStorageService
->getImportedAfter(
array_map(fn ($m) => new Matricule($m), $matriculesToInsert),
$importStartTime
);
$matriculesInserted = $result->matriculesInserted;
$insertedCount = $result->insertedCount;
$updatedCount = $result->updatedCount;
} else {
$insertedCount = 0;
$updatedCount = 0;
}
if (! empty($matriculesInserted)) {
$this->eventDispatcher->dispatch(new SalariesHaveBeenImported(
$this->authService->getMandatoryUserId(),
$matriculesInserted
));
}
return (object) [
'insertedCount' => $insertedCount,
'updatedCount' => $updatedCount,
'errors' => $errors,
];
}
/** @return string[] */
public function getImportColumns(): array
{
return [
'matricule',
'nom',
'prenom',
'etablissement',
'site',
'service',
'date_debut',
'date_fin',
'date_fin_prevue',
];
}
/**
* @param array<string, mixed> $row
*
* @throws \DomainException
*/
private function fromCsvRow(array $row): EmployeeImport
{
$matricule = $this->toString($row['matricule'] ?? null);
$nom = $this->toString($row['nom'] ?? null);
$prenom = $this->toString($row['prenom'] ?? null);
$etablissement = $this->toString($row['etablissement'] ?? null);
$service = $this->toString($row['service'] ?? null);
$site = $this->toString($row['site'] ?? null);
$startDate = $this->toString($row['date_debut'] ?? null);
$endDateRaw = $this->toString($row['date_fin'] ?? $row['date_fin_prevue'] ?? null);
if (empty($matricule)) {
throw new \DomainException('The matricule is required');
}
if (empty($startDate)) {
throw new \DomainException('The start date is required');
}
try {
$startDate = DatesHelper::parseDateTime($startDate);
} catch (\InvalidArgumentException) {
throw new \DomainException("The start date format is invalid ({$startDate})");
}
if ($endDateRaw === 'null' || $endDateRaw === '') {
$endDateRaw = null;
}
$endDate = null;
if (is_string($endDateRaw)) {
try {
$endDate = DatesHelper::parseDateTime($endDateRaw);
} catch (\InvalidArgumentException) {
throw new \DomainException("The end date format is invalid ({$endDateRaw})");
}
}
return new EmployeeImport(
matricule: new Matricule($matricule),
nom: $nom,
prenom: $prenom,
etablissement: $etablissement,
service: $service,
site: $site,
startDate: CarbonImmutable::createFromInterface($startDate),
endDate: $endDate !== null ? CarbonImmutable::createFromInterface($endDate) : null,
);
}
private function toString(mixed $value): string
{
return mb_trim(
is_scalar($value) ?
(string) $value : ''
);
}
}