76 lines
2.3 KiB
PHP
76 lines
2.3 KiB
PHP
<?php
|
|
|
|
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(
|
|
private readonly ArcadiaIncoService $arcadiaIncoService,
|
|
private readonly LoggerInterface $logger,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @param \App\Contracts\ActionInputEmpty $input
|
|
*/
|
|
#[\Override]
|
|
public function __invoke(ActionInput $input): int
|
|
{
|
|
Assert::isInstanceOf($input, ActionInputEmpty::class);
|
|
|
|
$this->logger->info('Starting synchronization of all ProductIncos with Arcadia API.');
|
|
$updatedCount = 0;
|
|
|
|
/** @var \Illuminate\Database\Eloquent\Collection<int, ProductInco> $incos */
|
|
$incos = ProductInco::query()->get();
|
|
|
|
foreach ($incos as $inco) {
|
|
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.");
|
|
|
|
continue;
|
|
}
|
|
|
|
DB::transaction(static function () use ($inco, $incoData): void {
|
|
$inco->hydrateFromArcadiaDto($incoData);
|
|
$inco->saveOrFail();
|
|
});
|
|
$updatedCount++;
|
|
}
|
|
|
|
$this->logger->info("Completed synchronization of ProductIncos: {$updatedCount} updated.");
|
|
|
|
return $updatedCount;
|
|
}
|
|
}
|