ldc-cocotte/app/Cqs/Actions/ProductIncos/AssociateProductInco.php

61 lines
1.7 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace App\Cqs\Actions\ProductIncos;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\ProductInco;
use App\Services\ArcadiaIncoService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput,
* \App\Cqs\Actions\ProductIncos\AssociateProductIncoOutput
* >
*/
final class AssociateProductInco implements Action
{
public function __construct(
private readonly ArcadiaIncoService $arcadiaIncoService,
) {
}
/**
* @param \App\Cqs\Actions\ProductIncos\AssociateProductIncoInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): AssociateProductIncoOutput
{
Assert::isInstanceOf($input, AssociateProductIncoInput::class);
try {
$incoData = $this->arcadiaIncoService->fetchInco($input->no_art);
} catch (\RuntimeException $e) {
return AssociateProductIncoOutput::apiError($e->getMessage());
}
if ($incoData === null) {
return AssociateProductIncoOutput::notFoundOnArcadia($input->no_art);
}
$productId = $input->productId->value->toString();
// * Remove existing product_inco for this product if present
$existing = ProductInco::query()->where('product_id', $productId)->first();
if ($existing !== null) {
$existing->delete();
}
$inco = new ProductInco();
$inco->product_id = $productId;
$inco->no_art = $incoData->noArt;
$inco->hydrateFromArcadiaDto($incoData);
$inco->saveOrFail();
return AssociateProductIncoOutput::success($inco);
}
}