fix(sync): move Arcadia API calls outside transactions, track per-site employee cursors, and release reminder claim on failure

This commit is contained in:
Jérémy Munsch 2026-11-16 08:45:40 +01:00
parent 1ae8f65d7c
commit 317ca4cd03
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
12 changed files with 607 additions and 36 deletions

View file

@ -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();
}
}

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\Order;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput, bool>
*/
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;
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ReleaseTodayOrderReminderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
public CarbonImmutable $remindedAt,
) {
}
}

View file

@ -4,17 +4,20 @@ declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\ActionInputEmpty;
use App\Models\ProductInco;
use App\Services\ArcadiaIncoService;
use Illuminate\Support\Facades\DB;
use Psr\Log\LoggerInterface;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Contracts\ActionInputEmpty, int>
*/
#[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++;
}

View file

@ -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<int, \App\Models\Order> $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;
}
}
}

View file

@ -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<string> $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);

View file

@ -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' => [

View file

@ -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();
});

View file

@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
use App\Contracts\ActionInputEmpty;
use App\Cqs\Actions\Employee\SynchronizeEmployeesWithArcadiaApi;
use App\Cqs\Queries\Settings\GetSettingsQuery;
use App\Models\Employee;
use App\Models\Setting;
use App\Services\ActionExecutorService;
use App\Services\ArcadiaEmployee;
use App\Services\ArcadiaEmployeeService;
use App\Services\CodeGenerationService;
use App\Services\EmployeeSyncService;
use App\Services\EmployeeUpsertService;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Matricule;
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\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Infrastructure\Adapters\Locks\LaravelCacheLock;
use Infrastructure\Adapters\Services\EloquentEmployeeImportStorageService;
use Kwaadpepper\Serial\Converters\NativeBaseConverter;
use Kwaadpepper\Serial\SerialCasterBuilder;
use Psr\Log\NullLogger;
uses(RefreshDatabase::class);
describe('SynchronizeEmployeesWithArcadiaApi action', function (): void {
it('executes outside a SQL transaction and preserves failed site cursor independently of succeeded sites', function (): void {
// GIVEN
$setting = Setting::getSingleton();
$setting->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]);
});
});

View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder;
use App\Cqs\Actions\Orders\ReleaseTodayOrderReminderInput;
use App\Models\Order;
use App\Models\Shop;
use Carbon\CarbonImmutable;
use Domain\Enums\OrderStatus;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Money\Currency;
use Money\Money;
use Ramsey\Uuid\Uuid;
uses(RefreshDatabase::class);
describe('ReleaseTodayOrderReminder action', function (): void {
it('releases reminded_at only when timestamp matches the claim timestamp', function (): void {
// GIVEN
$claimedAt = CarbonImmutable::parse('2026-11-20 10:00:00');
$otherAt = CarbonImmutable::parse('2026-11-20 10:05:00');
$shop = Shop::factory()->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();
});
});

View file

@ -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, '<p>Updated 2001</p>');
});
$arcadiaService->shouldReceive('fetchInco')
->with(2002)
->once()
->andThrow(new \RuntimeException('Arcadia timeout on 2002'));
$arcadiaService->shouldReceive('fetchInco')
->with(2003)
->once()
->andReturn($makeDto(2003, '<p>Updated 2003</p>'));
$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('<p>Updated 2001</p>')
->and(ProductInco::query()->find($inco2->id)?->ingredients)->toBe('Anciens ingrédients')
->and(ProductInco::query()->find($inco3->id)?->ingredients)->toBe('<p>Updated 2003</p>');
});
});

View file

@ -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();
});
});