ldc-cocotte/app/Services/EmployeeSyncService.php

179 lines
5.7 KiB
PHP

<?php
declare(strict_types=1);
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 SITE_SYNC_TIMESTAMP_CACHE = 'EMPLOYEE_LAST_SYNC:';
public function __construct(
private readonly LoggerInterface $logger,
private readonly CacheRepository $cacheRepository,
private readonly ArcadiaEmployeeService $arcadiaEmployeeService,
private readonly EmployeeUpsertService $employeeUpsertService,
private readonly GetSettingsQuery $getSettingsQuery
) {
}
/**
* @param array<int, \Domain\Models\ValueObjects\ShopperSiteCode>|null $sites
*/
public function synchronize(
?\DateTimeInterface $since = null,
?array $sites = null
): void {
$sitesToSync = $sites ?? ($this->getSettingsQuery)(new QueryInputEmpty())->getShopperSiteCodes();
$this->logger->info('Starting employee synchronization.', [
'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' => $siteSince->format(Carbon::RFC3339),
]);
$employees = $this->arcadiaEmployeeService->getEmployeesOfSiteSince(
$siteCode,
$siteSince
);
if ($employees === false) {
$this->logger->warning("Failed to fetch employees from Arcadia for site: {$siteCode->value}", [
'site' => $siteCode->value,
]);
$failedSites[] = $siteCode->value;
continue;
}
$this->logger->debug("Retrieved employees for site {$siteCode->value}.", [
'site' => $siteCode->value,
'count' => count($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;
}
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.', [
'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);
if (! is_string($timestamp)) {
$this->logger->debug('No last synchronization timestamp found in cache.');
return null;
}
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);
$this->cacheRepository->put(
self::SYNC_TIMESTAMP_CACHE,
$now,
3600 * 36 // Cache for 36 hours
);
$this->logger->debug('Last sync timestamp updated in cache.', [
'timestamp' => $now,
]);
}
}