refactor(service): reintroduce EmployeeUpsertService and related classes

- Moved employee upsert logic to a new service for better separation of concerns.
- Updated EmployeeSyncService to utilize the new EmployeeUpsertService.
- Added tests for EmployeeUpsertService to ensure correct functionality.
This commit is contained in:
Jérémy Munsch 2026-11-10 15:14:24 +01:00
parent d0efb0f527
commit 2dacdbabd6
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
6 changed files with 214 additions and 111 deletions

View file

@ -6,11 +6,7 @@ namespace App\Services;
use App\Contracts\QueryInputEmpty;
use App\Cqs\Queries\Settings\GetSettingsQuery;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Domain\Models\ValueObjects\EmployeeUpsertData;
use Domain\Models\ValueObjects\Matricule;
use Domain\Ports\Services\EmployeeImportStorageService;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Support\Carbon;
use Psr\Log\LoggerInterface;
@ -23,8 +19,7 @@ class EmployeeSyncService
private readonly LoggerInterface $logger,
private readonly CacheRepository $cacheRepository,
private readonly ArcadiaEmployeeService $arcadiaEmployeeService,
private readonly CodeGenerationService $codeService,
private readonly EmployeeImportStorageService $employeeImportStorageService,
private readonly EmployeeUpsertService $employeeUpsertService,
private readonly GetSettingsQuery $getSettingsQuery
) {
}
@ -73,7 +68,7 @@ class EmployeeSyncService
'count' => count($employees),
]);
$result = $this->upsertEmployees($employees);
$result = $this->employeeUpsertService->upsertEmployees($employees);
$totalInserted += $result->insertedCount;
$totalUpdated += $result->updatedCount;
@ -114,85 +109,4 @@ class EmployeeSyncService
'timestamp' => $now,
]);
}
/** @param \App\Services\ArcadiaEmployee[] $employeeList */
private function upsertEmployees(array $employeeList): EmployeeSyncServiceResult
{
$matriculesToInsert = [];
$errors = [];
$upsertData = [];
$importStartTime = CarbonImmutable::now()->subSecond();
foreach ($employeeList as $employeeImport) {
$matricule = $employeeImport->matricule->value;
if (in_array($matricule, $matriculesToInsert, true)) {
$errorMsg = "Duplicate detected in the file: The matricule {$matricule} appears multiple times.";
$errors[] = $errorMsg;
$this->logger->warning($errorMsg, [
'matricule' => $matricule,
]);
continue;
}
$matriculesToInsert[] = $matricule;
// NOTE: We generate a new code for each row, but only insert it for new records.
$code = $this->codeService->generateFrom(new Matricule($matricule));
$upsertData[] = new EmployeeUpsertData(
matricule: $employeeImport->matricule,
firstname: $employeeImport->firstname,
lastname: $employeeImport->lastname,
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.';
$this->logger->notice('Upsert skipped: No valid employee data found in list.');
}
if (! empty($upsertData)) {
$this->logger->debug('Dispatching upsert batch to storage service.', [
'batch_size' => count($upsertData),
]);
$this->employeeImportStorageService->upsertEmployees($upsertData);
$result = $this->employeeImportStorageService
->getImportedAfter(
array_map(
fn ($m) => new Matricule($m),
$matriculesToInsert
),
$importStartTime
);
$insertedCount = $result->insertedCount;
$updatedCount = $result->updatedCount;
$this->logger->info('Batch upsert completed.', [
'inserted' => $insertedCount,
'updated' => $updatedCount,
'errors' => count($errors),
]);
} else {
$insertedCount = 0;
$updatedCount = 0;
}
return new EmployeeSyncServiceResult(
insertedCount: $insertedCount,
updatedCount: $updatedCount,
errors: $errors,
);
}
}

View file

@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace App\Services;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\EmployeeUpsertData;
use Domain\Models\ValueObjects\Matricule;
use Domain\Ports\Services\EmployeeImportStorageService;
use Psr\Log\LoggerInterface;
use Webmozart\Assert\Assert;
class EmployeeUpsertService
{
public function __construct(
private readonly LoggerInterface $logger,
private readonly CodeGenerationService $codeService,
private readonly EmployeeImportStorageService $employeeImportStorageService
) {
}
/** @param \App\Services\ArcadiaEmployee[] $employeeList */
public function upsertEmployees(array $employeeList): EmployeeUpsertServiceResult
{
Assert::allIsInstanceOf($employeeList, ArcadiaEmployee::class);
$matriculesToInsert = [];
$errors = [];
$upsertData = [];
$importStartTime = CarbonImmutable::now()->subSecond();
foreach ($employeeList as $employeeToImport) {
$matricule = $employeeToImport->matricule->value;
if (in_array($matricule, $matriculesToInsert, true)) {
$errorMsg = "Duplicate detected in the file: The matricule {$matricule} appears multiple times.";
$errors[] = $errorMsg;
$this->logger->warning($errorMsg, [
'matricule' => $matricule,
]);
continue;
}
$matriculesToInsert[] = $matricule;
// NOTE: We generate a new code for each row, but only insert it for new records.
$code = $this->codeService->generateFrom(new Matricule($matricule));
$upsertData[] = new EmployeeUpsertData(
matricule: $employeeToImport->matricule,
firstname: $employeeToImport->firstname,
lastname: $employeeToImport->lastname,
etablissement: $employeeToImport->etablissement,
service: $employeeToImport->service,
site: $employeeToImport->site,
startDate: $employeeToImport->startDate,
endDate: $employeeToImport->endDate,
code: $code
);
}
if (empty($upsertData) && empty($errors)) {
$errors[] = 'The file contains no valid data.';
$this->logger->notice('Upsert skipped: No valid employee data found in list.');
}
if (! empty($upsertData)) {
$this->logger->debug('Dispatching upsert batch to storage service.', [
'batch_size' => count($upsertData),
]);
$this->employeeImportStorageService->upsertEmployees($upsertData);
$result = $this->employeeImportStorageService
->getImportedAfter(
array_map(
fn ($m) => new Matricule($m),
$matriculesToInsert
),
$importStartTime
);
$insertedCount = $result->insertedCount;
$updatedCount = $result->updatedCount;
$this->logger->info('Batch upsert completed.', [
'inserted' => $insertedCount,
'updated' => $updatedCount,
'errors' => count($errors),
]);
} else {
$insertedCount = 0;
$updatedCount = 0;
}
return new EmployeeUpsertServiceResult(
insertedCount: $insertedCount,
updatedCount: $updatedCount,
errors: $errors,
);
}
}

View file

@ -4,7 +4,7 @@ declare(strict_types=1);
namespace App\Services;
class EmployeeSyncServiceResult
class EmployeeUpsertServiceResult
{
public function __construct(
public readonly int $insertedCount,

View file

@ -4,7 +4,7 @@ declare(strict_types=1);
use App\Exceptions\GlobalHandler;
use App\Services\ArcadiaEmployee;
use App\Services\EmployeeSyncServiceResult;
use App\Services\EmployeeUpsertServiceResult;
use Symfony\Component\Finder\Finder;
describe('naming conventions in app', function (): void {
@ -52,7 +52,7 @@ describe('naming conventions in app', function (): void {
->toHaveSuffix('Service')
->ignoring([
ArcadiaEmployee::class,
EmployeeSyncServiceResult::class,
EmployeeUpsertServiceResult::class,
]);
arch('queries have Query, QueryInput or QueryOutput suffix', function (): void {

View file

@ -6,14 +6,14 @@ use App\Cqs\Queries\Settings\GetSettingsQuery;
use App\Models\Setting;
use App\Services\ArcadiaEmployee;
use App\Services\ArcadiaEmployeeService;
use App\Services\CodeGenerationService;
use App\Services\EmployeeSyncService;
use App\Services\EmployeeUpsertService;
use App\Services\EmployeeUpsertServiceResult;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Ports\Services\EmployeeImportStorageService;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Psr\Log\LoggerInterface;
@ -33,8 +33,7 @@ describe('EmployeeSyncService', function (): void {
$logger = app(LoggerInterface::class);
$cache = app(CacheRepository::class);
$codeService = app(CodeGenerationService::class);
$storageService = \Mockery::mock(EmployeeImportStorageService::class);
$upsertService = \Mockery::mock(EmployeeUpsertService::class);
$employee = new ArcadiaEmployee(
matricule: new Matricule('1234567'),
@ -47,19 +46,25 @@ describe('EmployeeSyncService', function (): void {
service: new ShopperServiceCode('101')
);
$storageService->shouldReceive('upsertEmployees')
->once()
$upsertService->shouldReceive('upsertEmployees')
->with(\Mockery::on(static function (array $data): bool {
return count($data) === 1 && $data[0]->matricule->value === '1234567';
}));
$storageService->shouldReceive('getImportedAfter')
}))
->once()
->andReturn((object) [
'insertedCount' => 1,
'updatedCount' => 0,
'matriculesInserted' => [new Matricule('1234567')],
]);
->andReturn(new EmployeeUpsertServiceResult(
insertedCount: 1,
updatedCount: 0,
errors: []
));
$upsertService->shouldReceive('upsertEmployees')
->with(\Mockery::on(static fn (array $data) => empty($data)))
->once()
->andReturn(new EmployeeUpsertServiceResult(
insertedCount: 0,
updatedCount: 0,
errors: []
));
$arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class);
$arcadiaService->shouldReceive('getEmployeesOfSiteSince')
@ -75,8 +80,7 @@ describe('EmployeeSyncService', function (): void {
$logger,
$cache,
$arcadiaService,
$codeService,
$storageService,
$upsertService,
app(GetSettingsQuery::class)
);
@ -91,8 +95,16 @@ describe('EmployeeSyncService', function (): void {
// GIVEN
$logger = app(LoggerInterface::class);
$cache = app(CacheRepository::class);
$codeService = app(CodeGenerationService::class);
$storageService = \Mockery::mock(EmployeeImportStorageService::class);
$upsertService = \Mockery::mock(EmployeeUpsertService::class);
$upsertService->shouldReceive('upsertEmployees')
->with(\Mockery::on(static fn (array $data) => empty($data)))
->once()
->andReturn(new EmployeeUpsertServiceResult(
insertedCount: 0,
updatedCount: 0,
errors: []
));
$arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class);
$arcadiaService->shouldReceive('getEmployeesOfSiteSince')
@ -104,8 +116,7 @@ describe('EmployeeSyncService', function (): void {
$logger,
$cache,
$arcadiaService,
$codeService,
$storageService,
$upsertService,
app(GetSettingsQuery::class)
);

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
use App\Models\Setting;
use App\Services\ArcadiaEmployee;
use App\Services\CodeGenerationService;
use App\Services\EmployeeUpsertService;
use App\Services\EmployeeUpsertServiceResult;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Ports\Services\EmployeeImportStorageService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Psr\Log\LoggerInterface;
uses(RefreshDatabase::class);
afterEach(function (): void {
\Mockery::close();
});
describe('EmployeeUpsertService', function (): void {
it('upserts a single employee correctly', function (): void {
// GIVEN
$setting = Setting::getSingleton();
$setting->employee_sites = ['PA', 'LY'];
$setting->saveOrFail();
$logger = app(LoggerInterface::class);
$codeService = app(CodeGenerationService::class);
$storageService = \Mockery::mock(EmployeeImportStorageService::class);
$employee = new ArcadiaEmployee(
matricule: new Matricule('1234567'),
lastname: 'Dupont',
firstname: 'Jean',
startDate: CarbonImmutable::parse('2026-01-01'),
endDate: null,
etablissement: new ShopperEstablishmentCode('ETAB'),
site: new ShopperSiteCode('PA'),
service: new ShopperServiceCode('101')
);
$storageService->shouldReceive('upsertEmployees')
->once()
->with(\Mockery::on(static function (array $data): bool {
return count($data) === 1 && $data[0]->matricule->value === '1234567';
}));
$storageService->shouldReceive('getImportedAfter')
->once()
->andReturn((object) [
'insertedCount' => 1,
'updatedCount' => 0,
'matriculesInserted' => [new Matricule('1234567')],
]);
$service = new EmployeeUpsertService(
$logger,
$codeService,
$storageService,
);
// WHEN
$result = $service->upsertEmployees([$employee]);
// THEN
expect($result)->toBeInstanceOf(EmployeeUpsertServiceResult::class);
});
});