ldc-boutique-cnc-sable/app/Actions/ProductIncos/AssociateProductInco.php

59 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\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\Actions\ProductIncos\AssociateProductIncoInput, \App\Models\ProductInco>
*/
final class AssociateProductInco implements Action
{
public function __construct(
private readonly ArcadiaIncoService $arcadiaIncoService,
) {
}
/**
* @param \App\Actions\ProductIncos\AssociateProductIncoInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): ProductInco
{
Assert::isInstanceOf($input, AssociateProductIncoInput::class);
$incoData = $this->arcadiaIncoService->fetchInco($input->no_art);
if ($incoData === null) {
throw new \RuntimeException(sprintf('INCO sheet #%d was not found on Arcadia API.', $input->no_art));
}
// * Remove existing product_inco for this product if present
$existing = ProductInco::query()->where('product_id', $input->product->id)->first();
if ($existing !== null) {
$existing->delete();
}
$inco = new ProductInco();
$inco->product_id = (string) $input->product->id;
$inco->no_art = $incoData->noArt;
$inco->ingredients = $incoData->ingredients;
$inco->preparation = $incoData->preparation;
$inco->servings = $incoData->servings;
$inco->allergens = $incoData->allergens;
$inco->selling_argument = $incoData->sellingArgument;
$inco->nutriscore = $incoData->nutriscore;
$inco->nutriscore_args = $incoData->nutriscoreArgs;
$inco->nutrition = $incoData->nutrition;
$inco->saveOrFail();
return $inco;
}
}