diff --git a/.env.example b/.env.example index 70359caf..55221583 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/app/Dto/ArcadiaIncoDataDto.php b/app/Dto/ArcadiaIncoDataDto.php new file mode 100644 index 00000000..67bee069 --- /dev/null +++ b/app/Dto/ArcadiaIncoDataDto.php @@ -0,0 +1,27 @@ + + */ + 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(); + } +} diff --git a/app/Providers/ArcadiaApiProvider.php b/app/Providers/ArcadiaApiProvider.php index 2f56ecac..e35e18d4 100644 --- a/app/Providers/ArcadiaApiProvider.php +++ b/app/Providers/ArcadiaApiProvider.php @@ -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 ); } diff --git a/app/Services/ArcadiaIncoService.php b/app/Services/ArcadiaIncoService.php new file mode 100644 index 00000000..3d0109b5 --- /dev/null +++ b/app/Services/ArcadiaIncoService.php @@ -0,0 +1,203 @@ +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) + ? '
' . nl2br(e(trim($inco->preparationAdvices))) . '
' + : null; + + $sellingArgumentHtml = ! empty($inco->sellArguments) + ? '' . nl2br(e(trim($inco->sellArguments))) . '
' + : 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[] = '' . e($title) . ' : ' . e($text) . '
'; + } else { + $paragraphs[] = '' . e($text) . '
'; + } + } + + 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), + ); + } +} diff --git a/config/services.php b/config/services.php index 0bee48fc..cb8391fc 100644 --- a/config/services.php +++ b/config/services.php @@ -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), ], ]; diff --git a/tests/Unit/App/Services/ArcadiaIncoServiceTest.php b/tests/Unit/App/Services/ArcadiaIncoServiceTest.php new file mode 100644 index 00000000..552ca91f --- /dev/null +++ b/tests/Unit/App/Services/ArcadiaIncoServiceTest.php @@ -0,0 +1,226 @@ +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'); + }); +});