From 317ca4cd03efb02ae1a3c6adbe6036b2164dbc27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 16 Nov 2026 08:45:40 +0100 Subject: [PATCH] fix(sync): move Arcadia API calls outside transactions, track per-site employee cursors, and release reminder claim on failure --- .../SynchronizeEmployeesWithArcadiaApi.php | 11 +- .../Orders/ReleaseTodayOrderReminder.php | 32 +++++ .../Orders/ReleaseTodayOrderReminderInput.php | 18 +++ .../SynchronizeProductIncosWithArcadiaApi.php | 24 +++- app/Jobs/SendReminderMail.php | 38 ++++-- app/Services/EmployeeSyncService.php | 85 +++++++++++-- config/queue.php | 2 +- tests/Feature/Jobs/SendReminderMailTest.php | 103 ++++++++++++++-- ...SynchronizeEmployeesWithArcadiaApiTest.php | 114 ++++++++++++++++++ .../Orders/ReleaseTodayOrderReminderTest.php | 61 ++++++++++ ...chronizeProductIncosWithArcadiaApiTest.php | 73 +++++++++++ .../App/Services/EmployeeSyncServiceTest.php | 82 +++++++++++++ 12 files changed, 607 insertions(+), 36 deletions(-) create mode 100644 app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php create mode 100644 app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php create mode 100644 tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php create mode 100644 tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php diff --git a/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php b/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php index cd46d309..e9882c2f 100644 --- a/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php +++ b/app/Cqs/Actions/Employee/SynchronizeEmployeesWithArcadiaApi.php @@ -4,16 +4,17 @@ declare(strict_types=1); namespace App\Cqs\Actions\Employee; +use App\Attributes\WithoutTransaction; use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\ActionInputEmpty; -use App\Models\Employee; use App\Services\EmployeeSyncService; use Webmozart\Assert\Assert; /** * @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, void> */ +#[WithoutTransaction] final class SynchronizeEmployeesWithArcadiaApi implements Action { public function __construct( @@ -22,15 +23,11 @@ final class SynchronizeEmployeesWithArcadiaApi implements Action } /** @param \App\Contracts\ActionInputEmpty $input */ + #[\Override] public function __invoke(ActionInput $input): void { Assert::isAOf($input, ActionInputEmpty::class); - $wasLastSyncedAt = Employee::query() - ->orderBy('last_sync', 'desc') - ->limit(1) - ->first('last_sync')?->last_sync; - - $this->syncService->synchronize($wasLastSyncedAt); + $this->syncService->synchronize(); } } diff --git a/app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php new file mode 100644 index 00000000..da3a9536 --- /dev/null +++ b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminder.php @@ -0,0 +1,32 @@ + + */ +final class ReleaseTodayOrderReminder implements Action +{ + /** + * @param \App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): bool + { + Assert::isInstanceOf($input, ReleaseTodayOrderReminderInput::class); + + $updated = Order::query() + ->where('id', $input->orderId->value->toString()) + ->where('reminded_at', $input->remindedAt) + ->update(['reminded_at' => null]); + + return $updated > 0; + } +} diff --git a/app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php new file mode 100644 index 00000000..5e5b3dd4 --- /dev/null +++ b/app/Cqs/Actions/Orders/ReleaseTodayOrderReminderInput.php @@ -0,0 +1,18 @@ + */ +#[WithoutTransaction] final class SynchronizeProductIncosWithArcadiaApi implements Action { public function __construct( @@ -38,7 +41,20 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action $incos = ProductInco::query()->get(); foreach ($incos as $inco) { - $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art); + try { + $incoData = $this->arcadiaIncoService->fetchInco($inco->no_art); + } catch (\Throwable $e) { + $this->logger->error( + "Failed to fetch ProductInco #{$inco->id} (no_art: {$inco->no_art}): {$e->getMessage()}", + [ + 'product_inco_id' => $inco->id, + 'no_art' => $inco->no_art, + 'exception' => $e, + ] + ); + + continue; + } if ($incoData === null) { $this->logger->warning("Could not sync ProductInco #{$inco->id} (no_art: {$inco->no_art}): not found on Arcadia."); @@ -46,8 +62,10 @@ final class SynchronizeProductIncosWithArcadiaApi implements Action continue; } - $inco->hydrateFromArcadiaDto($incoData); - $inco->saveOrFail(); + DB::transaction(static function () use ($inco, $incoData): void { + $inco->hydrateFromArcadiaDto($incoData); + $inco->saveOrFail(); + }); $updatedCount++; } diff --git a/app/Jobs/SendReminderMail.php b/app/Jobs/SendReminderMail.php index 5ffd7d63..b4d5fbf4 100644 --- a/app/Jobs/SendReminderMail.php +++ b/app/Jobs/SendReminderMail.php @@ -7,6 +7,8 @@ namespace App\Jobs; use App\Contracts\Executor; use App\Cqs\Actions\Orders\ClaimTodayOrderReminder; use App\Cqs\Actions\Orders\ClaimTodayOrderReminderInput; +use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder; +use App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput; use App\Dto\OrderReminderDto; use App\Dto\OrderReminderLineDto; use App\Models\Employee; @@ -39,8 +41,11 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue return Date::now()->format('Y-m-d'); } - public function handle(Executor $executor, ClaimTodayOrderReminder $claimAction): void - { + public function handle( + Executor $executor, + ClaimTodayOrderReminder $claimAction, + ReleaseTodayOrderReminder $releaseAction, + ): void { $today = Date::now()->format('Y-m-d'); Order::query() @@ -50,9 +55,9 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue ->whereNull('reminded_at') ->chunkById( self::CHUNK_SIZE, - function (Collection $orders) use ($executor, $claimAction): void { + function (Collection $orders) use ($executor, $claimAction, $releaseAction): void { /** @var \Illuminate\Database\Eloquent\Collection $orders */ - $this->processChunk($orders, $executor, $claimAction); + $this->processChunk($orders, $executor, $claimAction, $releaseAction); }, 'id' ); @@ -65,6 +70,7 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue Collection $orders, Executor $executor, ClaimTodayOrderReminder $claimAction, + ReleaseTodayOrderReminder $releaseAction, ): void { $matricules = $orders ->map(fn (Order $order): string => $order->employee->matricule->value) @@ -84,19 +90,31 @@ class SendReminderMail implements ShouldBeUnique, ShouldQueue continue; } - $claimed = $executor->execute( + $dto = $this->toDto($order, $employee); + $remindedAt = CarbonImmutable::now()->utc()->startOfSecond(); + $claimed = $executor->execute( $claimAction, - new ClaimTodayOrderReminderInput($order->getId(), CarbonImmutable::now()), + new ClaimTodayOrderReminderInput($order->getId(), $remindedAt), ); if (! $claimed) { continue; } - $this->notifyEmployee( - $employee, - $this->toDto($order, $employee) - ); + try { + $this->notifyEmployee($employee, $dto); + } catch (\Throwable $e) { + try { + $executor->execute( + $releaseAction, + new ReleaseTodayOrderReminderInput($order->getId(), $remindedAt), + ); + } catch (\Throwable $releaseException) { + report($releaseException); + } + + throw $e; + } } } diff --git a/app/Services/EmployeeSyncService.php b/app/Services/EmployeeSyncService.php index 19f57cb6..13d9fdb8 100644 --- a/app/Services/EmployeeSyncService.php +++ b/app/Services/EmployeeSyncService.php @@ -6,14 +6,18 @@ namespace App\Services; use App\Contracts\QueryInputEmpty; use App\Cqs\Queries\Settings\GetSettingsQuery; +use App\Models\Employee; use Carbon\CarbonInterface; +use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Contracts\Cache\Repository as CacheRepository; use Illuminate\Support\Carbon; use Psr\Log\LoggerInterface; class EmployeeSyncService { - private const SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC'; + private const SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC'; + + private const SITE_SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC:'; public function __construct( private readonly LoggerInterface $logger, @@ -32,31 +36,36 @@ class EmployeeSyncService ?array $sites = null ): void { $sitesToSync = $sites ?? ($this->getSettingsQuery)(new QueryInputEmpty())->getShopperSiteCodes(); - $sinceDate = $since ?? Carbon::createFromTimestamp(0); $this->logger->info('Starting employee synchronization.', [ - 'since' => $sinceDate->format(Carbon::RFC3339), + 'since' => $since?->format(Carbon::RFC3339), 'sites_count' => count($sitesToSync), ]); $totalInserted = 0; $totalUpdated = 0; + /** @var list $failedSites */ + $failedSites = []; foreach ($sitesToSync as $siteCode) { + $siteSince = $since !== null ? Carbon::instance($since) : $this->resolveSinceForSite($siteCode); + $siteSyncStartedAt = Carbon::now(); + $this->logger->debug("Fetching employees for site: {$siteCode->value}", [ 'site' => $siteCode->value, - 'since' => $sinceDate->format(Carbon::RFC3339), + 'since' => $siteSince->format(Carbon::RFC3339), ]); $employees = $this->arcadiaEmployeeService->getEmployeesOfSiteSince( $siteCode, - $sinceDate + $siteSince ); if ($employees === false) { $this->logger->warning("Failed to fetch employees from Arcadia for site: {$siteCode->value}", [ 'site' => $siteCode->value, ]); + $failedSites[] = $siteCode->value; continue; } @@ -66,20 +75,50 @@ class EmployeeSyncService 'count' => count($employees), ]); - $result = $this->employeeUpsertService->upsertEmployees($employees); + try { + $result = $this->employeeUpsertService->upsertEmployees($employees); + } catch (\Throwable $e) { + $this->logger->error("Failed to persist employees for site {$siteCode->value}: {$e->getMessage()}", [ + 'site' => $siteCode->value, + 'exception' => $e, + ]); + $failedSites[] = $siteCode->value; + + continue; + } + + $this->markSiteLastSync($siteCode, $siteSyncStartedAt); $totalInserted += $result->insertedCount; $totalUpdated += $result->updatedCount; } - $this->markLastSync(); + if ($failedSites === []) { + $this->markLastSync(); + } else { + $this->logger->warning('Employee synchronization finished with failed sites; global cursor unchanged.', [ + 'failed_sites' => $failedSites, + ]); + } - $this->logger->info('Employee synchronization completed successfully.', [ + $this->logger->info('Employee synchronization completed.', [ 'total_inserted' => $totalInserted, 'total_updated' => $totalUpdated, + 'failed_sites' => $failedSites, ]); } + public function getSiteLastSync(ShopperSiteCode $siteCode): ?CarbonInterface + { + $timestamp = $this->cacheRepository->get($this->getSiteLastSyncCacheKey($siteCode)); + + if (! is_string($timestamp)) { + return null; + } + + return Carbon::parse($timestamp); + } + public function getLastSync(): ?CarbonInterface { $timestamp = $this->cacheRepository->get(self::SYNC_TIMESTAMP_CACHE); @@ -93,6 +132,36 @@ class EmployeeSyncService return Carbon::parse($timestamp); } + private function resolveSinceForSite(ShopperSiteCode $siteCode): CarbonInterface + { + $cachedLastSync = $this->getSiteLastSync($siteCode); + $dbLastSync = Employee::query() + ->where('site', $siteCode->value) + ->orderBy('last_sync', 'desc') + ->limit(1) + ->first('last_sync')?->last_sync; + + if ($cachedLastSync !== null && $dbLastSync !== null) { + return $cachedLastSync->greaterThan($dbLastSync) ? $cachedLastSync : $dbLastSync; + } + + return $cachedLastSync ?? $dbLastSync ?? Carbon::createFromTimestamp(0); + } + + private function markSiteLastSync(ShopperSiteCode $siteCode, CarbonInterface $syncedAt): void + { + $this->cacheRepository->put( + $this->getSiteLastSyncCacheKey($siteCode), + $syncedAt->format(Carbon::RFC3339), + 3600 * 36 + ); + } + + private function getSiteLastSyncCacheKey(ShopperSiteCode $siteCode): string + { + return self::SITE_SYNC_TIMESTAMP_CACHE . $siteCode->value; + } + private function markLastSync(): void { $now = Carbon::now()->format(Carbon::RFC3339); diff --git a/config/queue.php b/config/queue.php index 71ae952f..eb079676 100644 --- a/config/queue.php +++ b/config/queue.php @@ -79,7 +79,7 @@ return [ 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), 'block_for' => null, - 'after_commit' => false, + 'after_commit' => true, ], 'deferred' => [ diff --git a/tests/Feature/Jobs/SendReminderMailTest.php b/tests/Feature/Jobs/SendReminderMailTest.php index ec8ec63a..31fc3acd 100644 --- a/tests/Feature/Jobs/SendReminderMailTest.php +++ b/tests/Feature/Jobs/SendReminderMailTest.php @@ -2,14 +2,15 @@ declare(strict_types=1); -use App\Contracts\Executor; use App\Cqs\Actions\Orders\ClaimTodayOrderReminder; +use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder; use App\Jobs\SendReminderMail; use App\Models\Customer; use App\Models\Employee; use App\Models\Order; use App\Models\Shop; use App\Notifications\OrderTodayReminderNotification; +use App\Services\ActionExecutorService; use Domain\Enums\OrderStatus; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\DeliveryAddress; @@ -20,12 +21,17 @@ use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository as CacheRepository; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Money\Currency; use Money\Money; use Money\MoneyFormatter; +use Psr\Log\NullLogger; use Ramsey\Uuid\Uuid; describe('SendReminderMail job', function (): void { @@ -69,22 +75,105 @@ describe('SendReminderMail job', function (): void { 'pickup_day' => '2026-11-20', ]); + /** @var MoneyFormatter&\Mockery\MockInterface $formatter */ $formatter = \Mockery::mock(MoneyFormatter::class); $formatter->shouldReceive('format')->once()->andReturn('30,00 €'); - $executor = $this->app->make(Executor::class); - $claimAction = new ClaimTodayOrderReminder(); - $job = new SendReminderMail($formatter); + $executor = new ActionExecutorService( + new LaravelCacheLock(new CacheRepository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + $claimAction = new ClaimTodayOrderReminder(); + $releaseAction = new ReleaseTodayOrderReminder(); + $job = new SendReminderMail($formatter); // WHEN - $job->handle($executor, $claimAction); + $job->handle($executor, $claimAction, $releaseAction); // Re-running on same day (e.g. retry or duplicate run) must not notify twice. - $job->handle($executor, $claimAction); + $job->handle($executor, $claimAction, $releaseAction); // THEN Notification::assertSentToTimes($employee, OrderTodayReminderNotification::class, 1); expect($order->fresh()?->reminded_at)->not->toBeNull() - ->and($job->uniqueId())->toBe('2026-11-20'); + ->and($job->uniqueId())->toBe('2026-11-20') + ->and(config('queue.connections.redis.after_commit'))->toBeTrue(); + + Date::setTestNow(); + }); + + it('releases reminded_at when notification queue dispatch fails so retry can remind the order', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + Date::setTestNow('2026-11-20 10:00:00'); + + $shop = Shop::factory()->create(); + $customer = Customer::query()->forceCreate([ + 'email' => new Email('retry-reminder@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + $employee = Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('6234567'), + 'nom' => 'Martin', + 'prenom' => 'Luc', + 'code' => new Code('PQR2345'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + ]); + + $order = Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(3000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('6234567'), + 'Luc', + 'Martin', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'), + 'pickup_day' => '2026-11-20', + ]); + + /** @var MoneyFormatter&\Mockery\MockInterface $formatter */ + $formatter = \Mockery::mock(MoneyFormatter::class); + $formatter->shouldReceive('format')->twice()->andReturn('30,00 €'); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new CacheRepository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + $claimAction = new ClaimTodayOrderReminder(); + $releaseAction = new ReleaseTodayOrderReminder(); + $job = new SendReminderMail($formatter); + + Notification::shouldReceive('send') + ->once() + ->andThrow(new \RuntimeException('Redis queue unavailable')); + + // WHEN (first attempt fails during queue dispatch) + expect(fn () => $job->handle($executor, $claimAction, $releaseAction)) + ->toThrow(\RuntimeException::class, 'Redis queue unavailable'); + + // THEN (reminded_at was released back to null) + expect($order->fresh()?->reminded_at)->toBeNull(); + + // WHEN (retry succeeds after queue recovers) + Notification::clearResolvedInstances(); + Notification::fake(); + + $job->handle($executor, $claimAction, $releaseAction); + + // THEN + Notification::assertSentToTimes($employee, OrderTodayReminderNotification::class, 1); + expect($order->fresh()?->reminded_at)->not->toBeNull(); Date::setTestNow(); }); diff --git a/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php new file mode 100644 index 00000000..867111cd --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Employee/SynchronizeEmployeesWithArcadiaApiTest.php @@ -0,0 +1,114 @@ +employee_sites = ['PA', 'LY']; + $setting->saveOrFail(); + + $baseTxLevel = DB::transactionLevel(); + $arcadiaTxLevel = null; + $lySinceTimestamps = []; + + /** @var ArcadiaEmployeeService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with(\Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'PA'), \Mockery::any()) + ->andReturnUsing(static function () use (&$arcadiaTxLevel): array { + $arcadiaTxLevel = DB::transactionLevel(); + + return [ + new ArcadiaEmployee( + matricule: new Matricule('9123456'), + lastname: 'Pa', + firstname: 'Alice', + startDate: CarbonImmutable::parse('2026-01-01'), + endDate: null, + etablissement: new ShopperEstablishmentCode('01'), + site: new ShopperSiteCode('PA'), + service: new ShopperServiceCode('01'), + ), + ]; + }); + + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->twice() + ->with(\Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'LY'), \Mockery::any()) + ->andReturnUsing(static function (ShopperSiteCode $site, \DateTimeInterface $since) use (&$lySinceTimestamps): false { + $lySinceTimestamps[] = $since->getTimestamp(); + + return false; + }); + + $cache = new CacheRepository(new ArrayStore()); + $upsertService = new EmployeeUpsertService( + new NullLogger(), + new CodeGenerationService(new SerialCasterBuilder(new NativeBaseConverter())), + new EloquentEmployeeImportStorageService(), + ); + $syncService = new EmployeeSyncService( + new NullLogger(), + $cache, + $arcadiaService, + $upsertService, + new GetSettingsQuery(), + ); + + $action = new SynchronizeEmployeesWithArcadiaApi($syncService); + $executor = new ActionExecutorService( + new LaravelCacheLock($cache), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $s): bool => $s->value === 'PA'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() > 0), + ) + ->andReturn([]); + + // WHEN + $executor->execute($action, new ActionInputEmpty()); + $executor->execute($action, new ActionInputEmpty()); + + // THEN + expect($arcadiaTxLevel)->toBe($baseTxLevel) + ->and(Employee::query()->where('matricule', '9123456')->first()?->last_sync)->not->toBeNull() + ->and($lySinceTimestamps)->toBe([0, 0]); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php b/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php new file mode 100644 index 00000000..db020ab5 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/ReleaseTodayOrderReminderTest.php @@ -0,0 +1,61 @@ +create(); + $order = Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(2000, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000102'), + 'Jean', + 'Dupont', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'), + 'pickup_day' => '2026-11-20', + 'reminded_at' => $claimedAt, + ]); + + $action = new ReleaseTodayOrderReminder(); + + // WHEN + $mismatchedRelease = $action(new ReleaseTodayOrderReminderInput($order->getId(), $otherAt)); + $matchingRelease = $action(new ReleaseTodayOrderReminderInput($order->getId(), $claimedAt)); + + // THEN + expect($mismatchedRelease)->toBeFalse() + ->and($matchingRelease)->toBeTrue() + ->and($order->fresh()?->reminded_at)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php b/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php index c139e76f..9d369007 100644 --- a/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php +++ b/tests/Integration/WithApp/App/Actions/ProductIncos/SynchronizeProductIncosWithArcadiaApiTest.php @@ -8,6 +8,7 @@ use App\Dto\ArcadiaIncoDataDto; use App\Models\Product; use App\Models\ProductInco; use App\Models\Range; +use App\Services\ActionExecutorService; use App\Services\ArcadiaIncoService; use Domain\Enums\Nutriscore; use Domain\Enums\ProductBrand; @@ -16,9 +17,15 @@ use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\NutritionalValues; +use Illuminate\Cache\ArrayStore; +use Illuminate\Cache\Repository as CacheRepository; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\DB; +use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher; +use Infrastructure\Adapters\Locks\LaravelCacheLock; use Money\Money; use Psr\Log\LoggerInterface; +use Psr\Log\NullLogger; uses(RefreshDatabase::class); @@ -122,4 +129,70 @@ describe('SynchronizeProductIncosWithArcadiaApi action', function (): void { ->and($fresh2?->allergens)->toBe('Lait') ->and($fresh2?->nutriscore)->toBe(Nutriscore::B); }); + + it('fetches Arcadia outside SQL transaction and persists other incos when one fetch throws', function () use ($createProductWithInco): void { + // GIVEN + $inco1 = $createProductWithInco(2001); + $inco2 = $createProductWithInco(2002); + $inco3 = $createProductWithInco(2003); + + $baseTxLevel = DB::transactionLevel(); + $fetchTxLevel = null; + /** @var ArcadiaIncoService&\Mockery\MockInterface $arcadiaService */ + $arcadiaService = \Mockery::mock(ArcadiaIncoService::class); + /** @var LoggerInterface&\Mockery\MockInterface $logger */ + $logger = \Mockery::mock(LoggerInterface::class); + $logger->shouldReceive('info'); + $logger->shouldReceive('warning'); + $logger->shouldReceive('error')->once(); + + $makeDto = static fn (int $noArt, string $ing): ArcadiaIncoDataDto => new ArcadiaIncoDataDto( + noArt: $noArt, + name: "P{$noArt}", + libelle: "Produit {$noArt}", + brand: 'LDC', + ingredients: $ing, + preparation: null, + servings: null, + allergens: null, + sellingArgument: null, + nutriscore: Nutriscore::A, + nutriscoreArgs: null, + nutrition: new NutritionalValues(refWeightG: 100.0, kj: 500.0), + ); + + $arcadiaService->shouldReceive('fetchInco') + ->with(2001) + ->once() + ->andReturnUsing(static function () use (&$fetchTxLevel, $makeDto): ArcadiaIncoDataDto { + $fetchTxLevel = DB::transactionLevel(); + + return $makeDto(2001, '

Updated 2001

'); + }); + $arcadiaService->shouldReceive('fetchInco') + ->with(2002) + ->once() + ->andThrow(new \RuntimeException('Arcadia timeout on 2002')); + $arcadiaService->shouldReceive('fetchInco') + ->with(2003) + ->once() + ->andReturn($makeDto(2003, '

Updated 2003

')); + + $action = new SynchronizeProductIncosWithArcadiaApi($arcadiaService, $logger); + $executor = new ActionExecutorService( + new LaravelCacheLock(new CacheRepository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $synced = $executor->execute($action, new ActionInputEmpty()); + + // THEN + expect($synced)->toBe(2) + ->and($fetchTxLevel)->toBe($baseTxLevel) + ->and(ProductInco::query()->find($inco1->id)?->ingredients)->toBe('

Updated 2001

') + ->and(ProductInco::query()->find($inco2->id)?->ingredients)->toBe('Anciens ingrédients') + ->and(ProductInco::query()->find($inco3->id)?->ingredients)->toBe('

Updated 2003

'); + }); }); diff --git a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php index d22b1201..7bce7931 100644 --- a/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php +++ b/tests/Integration/WithApp/App/Services/EmployeeSyncServiceTest.php @@ -10,6 +10,7 @@ use App\Services\EmployeeSyncService; use App\Services\EmployeeUpsertService; use App\Services\EmployeeUpsertServiceResult; use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; @@ -17,6 +18,7 @@ use Domain\Models\ValueObjects\ShopperSiteCode; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository as CacheRepository; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Carbon; use Psr\Log\NullLogger; uses(RefreshDatabase::class); @@ -127,4 +129,84 @@ describe('EmployeeSyncService', function (): void { // THEN expect($service->getLastSync())->not->toBeNull(); }); + + it('keeps per-site sync cursor when one site fails so failed site updates are not lost', function (): void { + // GIVEN + $setting = Setting::getSingleton(); + $setting->employee_sites = ['PA', 'LY']; + $setting->saveOrFail(); + + $logger = new NullLogger(); + $cache = new CacheRepository(new ArrayStore()); + $upsertService = \Mockery::mock(EmployeeUpsertService::class); + $upsertService->shouldReceive('upsertEmployees') + ->andReturn(new EmployeeUpsertServiceResult( + insertedCount: 0, + updatedCount: 0, + errors: [] + )); + + $arcadiaService = \Mockery::mock(ArcadiaEmployeeService::class); + + $firstRunTime = CarbonImmutable::parse('2026-11-16 08:00:00'); + Carbon::setTestNow($firstRunTime); + + // First run: PA succeeds, LY fails + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'PA'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === 0), + ) + ->andReturn([]); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'LY'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === 0), + ) + ->andReturnFalse(); + + // Second run: PA uses T1 cursor, LY STILL uses epoch 0 cursor because LY previously failed + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'PA'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === $firstRunTime->getTimestamp()), + ) + ->andReturn([]); + $arcadiaService->shouldReceive('getEmployeesOfSiteSince') + ->once() + ->with( + \Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'LY'), + \Mockery::on(static fn (\DateTimeInterface $since): bool => $since->getTimestamp() === 0), + ) + ->andReturn([]); + + $service = new EmployeeSyncService( + $logger, + $cache, + $arcadiaService, + $upsertService, + new GetSettingsQuery() + ); + + // WHEN + $service->synchronize(); + + // THEN (after partial failure) + expect($service->getLastSync())->toBeNull() + ->and($service->getSiteLastSync(new ShopperSiteCode('PA')))->toBeInstanceOf(CarbonInterface::class) + ->and($service->getSiteLastSync(new ShopperSiteCode('LY')))->toBeNull(); + + // WHEN (second run succeeds for all sites) + $secondRunTime = CarbonImmutable::parse('2026-11-16 09:00:00'); + Carbon::setTestNow($secondRunTime); + $service->synchronize(); + Carbon::setTestNow(); + + // THEN + expect($service->getLastSync())->not->toBeNull() + ->and($service->getSiteLastSync(new ShopperSiteCode('LY')))->not->toBeNull(); + }); });