feat(arcadia): add ArcadiaIncoService and DTOs to fetch and preview INCO sheets via Arcadia API

This commit is contained in:
Jérémy Munsch 2026-10-03 10:54:31 +02:00
parent ba99113776
commit 3de48c14fd
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
7 changed files with 532 additions and 3 deletions

View file

@ -53,6 +53,7 @@ UWIL_ADMIN_SECURE_CIDR_PROJECT_ALLOWED_LIST=""
ARCADIA_API_ENDPOINT=
ARCADIA_API_APIKEY=
ARCADIA_API_SECRET=
ARCADIA_API_IGNORE_SELF_SIGNED_CERT=false
# Serial Caster
SERIAL_CASTER_SEED=12345

View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Dto;
use Domain\Enums\Nutriscore;
use Domain\Models\ValueObjects\NutritionalValues;
final readonly class ArcadiaIncoDataDto
{
public function __construct(
public int $noArt,
public string $name,
public string $libelle,
public ?string $brand,
public ?string $ingredients,
public ?string $preparation,
public ?string $servings,
public ?string $allergens,
public ?string $sellingArgument,
public ?Nutriscore $nutriscore,
public ?string $nutriscoreArgs,
public NutritionalValues $nutrition = new NutritionalValues(),
) {
}
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Dto;
final readonly class ArcadiaIncoPreviewDto implements \JsonSerializable
{
public function __construct(
public int $noArt,
public string $name,
public string $libelle,
public ?string $brand,
public ?string $nutriscore,
public ?string $servings,
public ?string $allergens,
public ?string $ingredients = null,
public ?string $preparation = null,
public ?float $energyKcal = null,
public ?float $energyKj = null,
public ?float $fat = null,
public ?float $satFat = null,
public ?float $carbs = null,
public ?float $sugar = null,
public ?float $fiber = null,
public ?float $protein = null,
public ?float $salt = null,
) {
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'no_art' => $this->noArt,
'name' => $this->name,
'libelle' => $this->libelle,
'brand' => $this->brand,
'nutriscore' => $this->nutriscore,
'servings' => $this->servings,
'allergens' => $this->allergens,
'ingredients' => $this->ingredients,
'preparation' => $this->preparation,
'energy_kcal' => $this->energyKcal,
'energy_kj' => $this->energyKj,
'fat' => $this->fat,
'sat_fat' => $this->satFat,
'carbs' => $this->carbs,
'sugar' => $this->sugar,
'fiber' => $this->fiber,
'protein' => $this->protein,
'salt' => $this->salt,
];
}
#[\Override]
public function jsonSerialize(): mixed
{
return $this->toArray();
}
}

View file

@ -14,6 +14,7 @@ use Uwil\ArcadiaApiPhpClient\Auth\ClientIdentifier;
use Uwil\ArcadiaApiPhpClient\Auth\ClientSecret;
use Uwil\ArcadiaApiPhpClient\Lib\ApiConfig;
use Uwil\ArcadiaApiPhpClient\Service\EmployeeService as LibEmployeeService;
use Uwil\ArcadiaApiPhpClient\Service\IncoService as LibIncoService;
class ArcadiaApiProvider extends ServiceProvider
{
@ -33,6 +34,10 @@ class ArcadiaApiProvider extends ServiceProvider
LibEmployeeService::class,
fn (Application $app) => $app->make(ArcadiaApiClient::class)->employees()
);
$this->app->singleton(
LibIncoService::class,
fn (Application $app) => $app->make(ArcadiaApiClient::class)->incoSheets()
);
}
/**
@ -54,10 +59,13 @@ class ArcadiaApiProvider extends ServiceProvider
Config::string('services.arcadia_api.api_secret')
);
$ignoreSelfSignedCert = Config::boolean('services.arcadia_api.ignore_self_signed_cert', true);
return new ApiConfig(
endpoint: $endpoint,
apiKey: $clientIdentifier,
secret: $clientSecret,
ignoreSelfSignedCert: $ignoreSelfSignedCert,
logger: $logger
);
}

View file

@ -0,0 +1,203 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Dto\ArcadiaIncoDataDto;
use App\Dto\ArcadiaIncoPreviewDto;
use Domain\Enums\Nutriscore;
use Domain\Models\ValueObjects\NutritionalValues;
use Psr\Log\LoggerInterface;
use Uwil\ArcadiaApiPhpClient\Error\ApiError;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco as LibInco;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo as LibIncoCompo;
use Uwil\ArcadiaApiPhpClient\Lib\ApiValueObject\IncoId;
use Uwil\ArcadiaApiPhpClient\Service\IncoService as LibIncoService;
class ArcadiaIncoService
{
public function __construct(
private readonly LibIncoService $incoService,
private readonly LoggerInterface $logger,
) {
}
public function fetchInco(int $noArt): ?ArcadiaIncoDataDto
{
$action = "INCO sheet #{$noArt}";
$this->logger->debug("Fetching {$action} from Arcadia API");
try {
$incoId = new IncoId((string) $noArt);
} catch (\DomainException $e) {
$this->logger->warning("Invalid IncoId format for #{$noArt}: {$e->getMessage()}");
return null;
}
$inco = $this->incoService->findBy($incoId);
if ($inco instanceof ApiError) {
$this->logger->error("Failed to fetch {$action}: {$inco->message()}");
throw new \RuntimeException($inco->message());
}
if (! ($inco instanceof LibInco)) {
$this->logger->info("{$action} not found on Arcadia API (404)");
return null;
}
$compo = $this->incoService->findCompo($incoId);
if ($compo instanceof ApiError) {
$this->logger->warning("Failed to fetch composition for {$action}: {$compo->message()}");
$compo = null;
}
return $this->mapToDataDto($inco, $compo instanceof LibIncoCompo ? $compo : null);
}
public function getPreview(int $noArt): ?ArcadiaIncoPreviewDto
{
$data = $this->fetchInco($noArt);
if ($data === null) {
return null;
}
return new ArcadiaIncoPreviewDto(
noArt: $data->noArt,
name: $data->name,
libelle: $data->libelle,
brand: $data->brand,
nutriscore: $data->nutriscore?->value,
servings: $data->servings,
allergens: $data->allergens,
ingredients: $data->ingredients,
preparation: $data->preparation,
energyKcal: $data->nutrition->kcal,
energyKj: $data->nutrition->kj,
fat: $data->nutrition->fatG,
satFat: $data->nutrition->satFatG,
carbs: $data->nutrition->carbG,
sugar: $data->nutrition->sugarG,
fiber: $data->nutrition->fiberG,
protein: $data->nutrition->proteinG,
salt: $data->nutrition->saltG,
);
}
private function mapToDataDto(LibInco $inco, ?LibIncoCompo $compo): ArcadiaIncoDataDto
{
$ingredientsHtml = $this->buildIngredientsHtml($inco);
$preparationHtml = ! empty($inco->preparationAdvices)
? '<p>' . nl2br(e(trim($inco->preparationAdvices))) . '</p>'
: null;
$sellingArgumentHtml = ! empty($inco->sellArguments)
? '<p>' . nl2br(e(trim($inco->sellArguments))) . '</p>'
: null;
$servings = $inco->portions !== null ? (string) $inco->portions : null;
if ($servings !== null && mb_strlen($servings) > 20) {
$servings = mb_substr($servings, 0, 20);
}
$allergens = ! empty($inco->allergens)
? implode(', ', array_map(fn ($a) => $a->label, $inco->allergens))
: null;
$nutriscore = $this->resolveNutriscore($inco, $compo);
$nutrition = $compo !== null ? $this->mapNutrition($compo) : new NutritionalValues();
return new ArcadiaIncoDataDto(
noArt: (int) $inco->id->value,
name: $inco->name,
libelle: $inco->libelle,
brand: $inco->brand->label !== '' ? $inco->brand->label : $inco->brand->code->value,
ingredients: $ingredientsHtml,
preparation: $preparationHtml,
servings: $servings,
allergens: $allergens,
sellingArgument: $sellingArgumentHtml,
nutriscore: $nutriscore,
nutriscoreArgs: null,
nutrition: $nutrition,
);
}
private function buildIngredientsHtml(LibInco $inco): ?string
{
if ($inco->ingredients->isEmpty()) {
return null;
}
$paragraphs = [];
foreach ($inco->ingredients->groups as $title => $lines) {
$text = implode(', ', $lines);
if (is_string($title) && ! is_numeric($title) && $title !== '') {
$paragraphs[] = '<p><strong>' . e($title) . ' :</strong> ' . e($text) . '</p>';
} else {
$paragraphs[] = '<p>' . e($text) . '</p>';
}
}
return implode('', $paragraphs);
}
private function resolveNutriscore(LibInco $inco, ?LibIncoCompo $compo): ?Nutriscore
{
$nutriscoreStr = $inco->nutriscore?->grade;
if (empty($nutriscoreStr) && $compo !== null && ! empty($compo->nutriScore->classement)) {
$nutriscoreStr = $compo->nutriScore->classement;
}
return ! empty($nutriscoreStr) ? Nutriscore::tryFrom(mb_strtoupper(trim($nutriscoreStr))) : null;
}
private function mapNutrition(LibIncoCompo $compo): NutritionalValues
{
$parseFloat = static function (?string $val): ?float {
if ($val === null || trim($val) === '' || ! is_numeric(trim($val))) {
return null;
}
$floatVal = (float) trim($val);
return $floatVal >= 0 ? $floatVal : null;
};
return new NutritionalValues(
refWeightG: $parseFloat($compo->energie->tailleReference),
kj: $parseFloat($compo->energie->valEnergKjReference),
kcal: $parseFloat($compo->energie->valEnergKcalReference),
fatG: $parseFloat($compo->macronutrimentsRef->matGrassReference),
satFatG: $parseFloat($compo->macronutrimentsRef->acideGrasSatureReference),
carbG: $parseFloat($compo->macronutrimentsRef->glucidesReference),
sugarG: $parseFloat($compo->macronutrimentsRef->sucreReference),
fiberG: $parseFloat($compo->macronutrimentsRef->fibAlimReference),
proteinG: $parseFloat($compo->macronutrimentsRef->proteineReference),
saltG: $parseFloat($compo->macronutrimentsRef->selReference),
servingSizeG: $parseFloat($compo->energie->taillePortion),
servingKj: $parseFloat($compo->energie->valEnergKjPortion),
servingKcal: $parseFloat($compo->energie->valEnergKcalPortion),
servingFatG: $parseFloat($compo->macronutrimentsPortion->matGrassPortion),
servingSatFatG: $parseFloat($compo->macronutrimentsPortion->acideGrasSaturePortion),
servingCarbG: $parseFloat($compo->macronutrimentsPortion->glucidesPortion),
servingSugarG: $parseFloat($compo->macronutrimentsPortion->sucrePortion),
servingFiberG: $parseFloat($compo->macronutrimentsPortion->fibAlimPortion),
servingProteinG: $parseFloat($compo->macronutrimentsPortion->proteinePortion),
servingSaltG: $parseFloat($compo->macronutrimentsPortion->selPortion),
dailyEnergy: $parseFloat($compo->apportsReference->pourcentApportRefKjoP),
dailyFat: $parseFloat($compo->apportsReference->pourcentApportRefFatP),
dailySatFat: $parseFloat($compo->apportsReference->pourcentApportRefFatsatP),
dailyCarb: $parseFloat($compo->apportsReference->pourcentApportRefChovalP),
dailySugar: $parseFloat($compo->apportsReference->pourcentApportRefSugarP),
dailyFiber: null,
dailyProtein: $parseFloat($compo->apportsReference->pourcentApportRefProP),
dailySalt: $parseFloat($compo->apportsReference->pourcentApportRefSalteqP),
);
}
}

View file

@ -29,8 +29,9 @@ return [
'site_id' => env('MATOMO_SITE_ID'),
],
'arcadia_api' => [
'endpoint' => env('ARCADIA_API_ENDPOINT'),
'api_key' => env('ARCADIA_API_APIKEY'),
'api_secret' => env('ARCADIA_API_SECRET'),
'endpoint' => env('ARCADIA_API_ENDPOINT'),
'api_key' => env('ARCADIA_API_APIKEY'),
'api_secret' => env('ARCADIA_API_SECRET'),
'ignore_self_signed_cert' => (bool) env('ARCADIA_API_IGNORE_SELF_SIGNED_CERT', false),
],
];

View file

@ -0,0 +1,226 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\App\Services;
use App\Dto\ArcadiaIncoDataDto;
use App\Dto\ArcadiaIncoPreviewDto;
use App\Services\ArcadiaIncoService;
use Domain\Enums\Nutriscore;
use Psr\Log\LoggerInterface;
use Uwil\ArcadiaApiPhpClient\Error\ApiError;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Brand;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco\Allegations;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco\Allergen;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco as LibInco;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco\Ingredients;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco\Nutriscore as IncoNutriscore;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\Inco\PortionAmount;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\AcideGras;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\AcidesAmines;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\ApportsReference;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo as LibIncoCompo;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\ComposesSpeciaux;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\Energie;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\FruitLegumeNoix;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\GlucidesDetail;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\Identification;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\MacronutrimentsPortion;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\MacronutrimentsRef;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\Mineraux;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\NutriScore as CompoNutriScore;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\PointsNutriScore;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\IncoCompo\Vitamines;
use Uwil\ArcadiaApiPhpClient\Lib\ApiValueObject\BrandCode;
use Uwil\ArcadiaApiPhpClient\Lib\ApiValueObject\IncoCompoId;
use Uwil\ArcadiaApiPhpClient\Lib\ApiValueObject\IncoId;
use Uwil\ArcadiaApiPhpClient\Service\IncoService as LibIncoService;
describe('ArcadiaIncoService', function (): void {
it('throws RuntimeException when API returns an ApiError', function (): void {
// GIVEN
$incoService = \Mockery::mock(LibIncoService::class);
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug');
$logger->shouldReceive('error');
$apiError = \Mockery::mock(ApiError::class);
$apiError->shouldReceive('message')->andReturn('Unauthorized');
$incoService->shouldReceive('findBy')
->once()
->with(\Mockery::type(IncoId::class))
->andReturn($apiError);
$service = new ArcadiaIncoService($incoService, $logger);
// WHEN & THEN
expect(fn () => $service->fetchInco(27996))->toThrow(\RuntimeException::class, 'Unauthorized');
});
it('returns null when INCO sheet is not found (404)', function (): void {
// GIVEN
$incoService = \Mockery::mock(LibIncoService::class);
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug');
$logger->shouldReceive('info');
$incoService->shouldReceive('findBy')
->once()
->with(\Mockery::type(IncoId::class))
->andReturnNull();
$service = new ArcadiaIncoService($incoService, $logger);
// WHEN
$result = $service->fetchInco(99999);
// THEN
expect($result)->toBeNull();
});
it('fetches and maps complete INCO and composition data', function (): void {
// GIVEN
$incoService = \Mockery::mock(LibIncoService::class);
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug');
$logger->shouldReceive('warning');
$incoId = new IncoId('27996');
$libInco = new LibInco(
id: $incoId,
name: 'POULET JAUNE FERMIER',
libelle: 'Poulet Jaune PAC Le Gaulois',
description: 'Volaille fermière de qualité.',
allegations: new Allegations([]),
sellArguments: 'Un poulet savoureux.',
preparationAdvices: 'Cuire à 200°C pendant 1h30.',
tips: 'Arroser régulièrement.',
sellFamilly: 'VOLAILLES',
ingredients: new Ingredients([
'Ingrédients' => ['Poulet Jaune (100%)'],
]),
portions: new PortionAmount(4, 5, true),
allergens: [
new Allergen(1, 'Aucun allergène'),
],
brand: new Brand(new BrandCode('LGL01'), 'Le Gaulois'),
isSeasonal: false,
weight: null,
nutriscore: new IncoNutriscore('A', null),
storageCondition: null,
additives: [],
compo: new IncoCompoId('88888'),
createdAt: new \DateTimeImmutable('2025-01-01T00:00:00Z'),
updatedAt: new \DateTimeImmutable('2025-01-01T00:00:00Z'),
);
$libCompo = new LibIncoCompo(
id: new IncoCompoId('88888'),
idInco: $incoId,
identification: new Identification('Poulet Jaune', '27996', 'SNV'),
energie: new Energie('100', '623', '149', '150', '935', '224'),
macronutrimentsRef: new MacronutrimentsRef(
'7.2', '=', '2.0', '=', '0.0', '=', '0.0', '=', '0.0', '=', '21.0', '=', '0.16', '=', '64'
),
macronutrimentsPortion: new MacronutrimentsPortion(
'10.8', '=', '3.0', '=', '0.0', '=', '0.0', '=', '0.0', '=', '31.5', '=', '0.24', '=', '96'
),
fnl: new FruitLegumeNoix('0', '0', '0', '0', '0', '0', '0', '0'),
apportsReference: new ApportsReference(
'11', '11', '15', '15', '0', '0', '63', '4', '150g', '2.9'
),
nutriScore: new CompoNutriScore(
'2', '2', '5', '5', '-3', '-3', 'A', 'A', '1', '0'
),
pointsNutriScore: new PointsNutriScore('0', '0', '0', '0', '0', '0', '0'),
mineraux: new Mineraux('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'),
vitamines: new Vitamines('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'),
glucidesDetail: new GlucidesDetail('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'),
acideGras: new AcideGras(
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'
),
acidesAmines: new AcidesAmines('0', '0', '0'),
composesSpeciaux: new ComposesSpeciaux('0', '0', '0', '0'),
);
$incoService->shouldReceive('findBy')->once()->andReturn($libInco);
$incoService->shouldReceive('findCompo')->once()->andReturn($libCompo);
$service = new ArcadiaIncoService($incoService, $logger);
// WHEN
$result = $service->fetchInco(27996);
// THEN
expect($result)->toBeInstanceOf(ArcadiaIncoDataDto::class)
->and($result->noArt)->toBe(27996)
->and($result->name)->toBe('POULET JAUNE FERMIER')
->and($result->brand)->toBe('Le Gaulois')
->and($result->nutriscore)->toBe(Nutriscore::A)
->and($result->allergens)->toBe('Aucun allergène')
->and($result->servings)->toBe('entre 4 et 5')
->and($result->preparation)->toContain('Cuire à 200°C')
->and($result->ingredients)->toContain('Poulet Jaune (100%)')
->and($result->nutrition->kj)->toBe(623.0)
->and($result->nutrition->kcal)->toBe(149.0)
->and($result->nutrition->fatG)->toBe(7.2)
->and($result->nutrition->proteinG)->toBe(21.0);
});
it('returns preview DTO correctly', function (): void {
// GIVEN
$incoService = \Mockery::mock(LibIncoService::class);
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('debug');
$incoId = new IncoId('27996');
$libInco = new LibInco(
id: $incoId,
name: 'POULET JAUNE FERMIER',
libelle: 'Poulet Jaune PAC Le Gaulois',
description: 'Volaille fermière.',
allegations: new Allegations([]),
sellArguments: 'Savoureux.',
preparationAdvices: 'Four.',
tips: null,
sellFamilly: null,
ingredients: new Ingredients([
['Poulet'],
]),
portions: null,
allergens: [],
brand: new Brand(new BrandCode('LGL01'), 'Le Gaulois'),
isSeasonal: false,
weight: null,
nutriscore: new IncoNutriscore('A', null),
storageCondition: null,
additives: [],
compo: null,
createdAt: null,
updatedAt: null,
);
$incoService->shouldReceive('findBy')->once()->andReturn($libInco);
$incoService->shouldReceive('findCompo')->once()->andReturnNull();
$service = new ArcadiaIncoService($incoService, $logger);
// WHEN
$preview = $service->getPreview(27996);
// THEN
expect($preview)->toBeInstanceOf(ArcadiaIncoPreviewDto::class)
->and($preview->noArt)->toBe(27996)
->and($preview->name)->toBe('POULET JAUNE FERMIER')
->and($preview->brand)->toBe('Le Gaulois')
->and($preview->nutriscore)->toBe('A');
});
});