ldc-cocotte/infra/Adapters/Services/EloquentEmployeeImportStorageService.php
Jérémy Munsch bc32abb4f1
reafactor(employees): add flash message for no imported or updated lines
Notify users when no lines are imported or updated during the import process.
2026-10-27 09:58:14 +01:00

76 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Infrastructure\Adapters\Services;
use App\Models\Employee;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\EmployeeUpsertData;
use Domain\Ports\Services\EmployeeImportStorageService;
class EloquentEmployeeImportStorageService implements EmployeeImportStorageService
{
/**
* @param list<EmployeeUpsertData> $upsertData
*/
public function upsertEmployees(array $upsertData): void
{
$mappedData = array_map(function (EmployeeUpsertData $data) {
return [
'matricule' => $data->matricule->value,
'nom' => $data->nom,
'prenom' => $data->prenom,
'etablissement' => $data->etablissement,
'service' => $data->service,
'site' => $data->site,
'start_date' => $data->startDate->format('Y-m-d H:i:s'),
'end_date' => $data->endDate?->format('Y-m-d H:i:s'),
'code' => $data->code->value,
];
}, $upsertData);
// NOTE: chunking is essential here because the query builder has a binding limit of 65535
// each row has 9 bindings, so we can insert at most 65535 / 9 = 7281 rows at once
// we use 1000 to be safe
foreach (array_chunk($mappedData, 1000) as $chunk) {
Employee::query()->upsert(
values: $chunk,
uniqueBy: ['matricule'],
update: ['nom', 'prenom', 'etablissement', 'service', 'site', 'start_date', 'end_date']
);
}
}
/**
* @param \Domain\Models\ValueObjects\Matricule[] $matriculesToInsert
* @return object{insertedCount: int, updatedCount: int, matriculesInserted: \Domain\Models\ValueObjects\Matricule[]}
*/
public function getImportedAfter(array $matriculesToInsert, CarbonImmutable $importStartTime): object
{
$employees = Employee::query()
->whereIn('matricule', $matriculesToInsert)
->get(['matricule', 'created_at', 'updated_at']);
/** @var list<\Domain\Models\ValueObjects\Matricule> $matriculesInserted */
$matriculesInserted = $employees
->pluck('matricule')
->values()
->toArray();
$insertedCount = $employees
->where('created_at', '>=', $importStartTime)
->count();
$updatedCount = $employees
->where('created_at', '<', $importStartTime)
->where('updated_at', '>=', $importStartTime)
->count();
return (object) [
'insertedCount' => $insertedCount,
'updatedCount' => $updatedCount,
'matriculesInserted' => $matriculesInserted,
];
}
}