feat(bo/product-incos): adapt BO controller, requests, routes and views for Arcadia INCO management

This commit is contained in:
Jérémy Munsch 2026-10-03 10:55:14 +02:00
parent 50df658d58
commit 14647576df
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
20 changed files with 991 additions and 1043 deletions

View file

@ -4,20 +4,21 @@ declare(strict_types=1);
namespace App\Http\Controllers\Bo;
use App\Actions\ProductIncos\CreateProductInco;
use App\Actions\ProductIncos\UpdateProductInco;
use App\Actions\ProductIncos\AssociateProductInco;
use App\Actions\ProductIncos\SyncProductInco;
use App\Contracts\Executor;
use App\Dto\ProductDto;
use App\Dto\ProductIncoDto;
use App\Http\Controllers\Controller;
use App\Http\Requests\Bo\ProductIncos\StoreProductIncoRequest;
use App\Http\Requests\Bo\ProductIncos\UpdateProductIncoRequest;
use App\Http\Requests\Bo\ProductIncos\AssociateProductIncoRequest;
use App\Http\Requests\Bo\ProductIncos\PreviewArcadiaIncoRequest;
use App\Http\Requests\Bo\ProductIncos\SyncProductIncoRequest;
use App\Models\Product;
use App\Models\ProductInco;
use Domain\Enums\Nutriscore;
use App\Queries\ProductIncos\GetArcadiaIncoPreviewQuery;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Str;
class ProductIncosController extends Controller
{
@ -26,61 +27,80 @@ class ProductIncosController extends Controller
) {
}
public function preview(PreviewArcadiaIncoRequest $request, Product $product, GetArcadiaIncoPreviewQuery $query): JsonResponse
{
$this->authorize('associateInco', $product);
try {
$preview = $this->executor->execute(
$query,
$request->toGetArcadiaIncoPreviewQueryInput(),
);
} catch (\RuntimeException $e) {
return response()->json([
'message' => __('Arcadia API error: :error', ['error' => $e->getMessage()]),
], 502);
}
if ($preview === null) {
return response()->json([
'message' => __('No INCO sheet found on Arcadia for this article number.'),
], 404);
}
return response()->json($preview);
}
public function associate(AssociateProductIncoRequest $request, Product $product, AssociateProductInco $action): RedirectResponse
{
$this->authorize('associateInco', $product);
try {
$inco = $this->executor->execute(
$action,
$request->toAssociateProductIncoInput($product),
);
} catch (\RuntimeException $e) {
return back()->with('danger', __('Arcadia API error: :error', ['error' => $e->getMessage()]));
}
return to_route('bo.products.incos.edit', compact('product', 'inco'))
->with('success', __('The INCO sheet has been successfully associated with the product.'));
}
public function sync(SyncProductIncoRequest $request, Product $product, SyncProductInco $action): RedirectResponse
{
$this->authorize('syncInco', $product);
try {
$inco = $this->executor->execute(
$action,
$request->toSyncProductIncoInput($product),
);
} catch (\RuntimeException $e) {
return back()->with('danger', __('Arcadia API error: :error', ['error' => $e->getMessage()]));
}
return to_route('bo.products.incos.edit', compact('product', 'inco'))
->with('success', __('The INCO sheet has been successfully synchronized from Arcadia.'));
}
public function create(Product $product): View
{
$this->authorize('createInco', $product);
$nutriscores = Nutriscore::cases();
$product = ProductDto::fromModel($product);
return view('bo.product-incos.create', compact(
'product',
'nutriscores',
));
return $this->edit($product);
}
public function store(StoreProductIncoRequest $request, Product $product, CreateProductInco $action): RedirectResponse
public function edit(Product $product, ?ProductInco $inco = null): View
{
$this->authorize('createInco', $product);
$this->authorize('associateInco', $product);
$inco = $this->executor->execute(
$action,
$request->toCreateProductIncoInput($product),
);
$productDto = ProductDto::fromModel($product);
$incoModel = $inco ?? $product->inco;
$incoDto = $incoModel instanceof ProductInco ? ProductIncoDto::fromModel($incoModel) : null;
return to_route('bo.products.incos.edit', compact('product', 'inco'))
->with('success', trans('crud.messages.has_been_created', [
'model' => Str::ucfirst(trans_choice('models.classes.product_incos', 1)),
]));
}
public function edit(Product $product, ProductInco $inco): View
{
$this->authorize('updateInco', $product);
$nutriscores = Nutriscore::cases();
$product = ProductDto::fromModel($product);
$inco = ProductIncoDto::fromModel($inco);
return view('bo.product-incos.edit', compact(
'product',
'inco',
'nutriscores',
));
}
public function update(UpdateProductIncoRequest $request, Product $product, ProductInco $inco, UpdateProductInco $action): RedirectResponse
{
$this->authorize('updateInco', $product);
$this->executor->execute(
$action,
$request->toUpdateProductIncoInput($inco),
);
return to_route('bo.products.incos.edit', compact('product', 'inco'))
->with('success', trans('crud.messages.has_been_updated', [
'model' => Str::ucfirst(trans_choice('models.classes.product_incos', 1)),
]));
return view('bo.product-incos.edit', [
'product' => $productDto,
'inco' => $incoDto,
]);
}
}

View file

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\ProductIncos;
use App\Actions\ProductIncos\AssociateProductIncoInput;
use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class AssociateProductIncoRequest extends FormRequest
{
public function __construct(
private readonly AppAdminAuthService $authService
) {
}
public function authorize(): bool
{
return $this->authService->check();
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'no_art' => ['required', 'integer', 'min:1'],
];
}
public function toAssociateProductIncoInput(Product $product): AssociateProductIncoInput
{
return new AssociateProductIncoInput(
product: $product,
no_art: $this->integer('no_art')
);
}
}

View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\ProductIncos;
use App\Queries\ProductIncos\GetArcadiaIncoPreviewQueryInput;
use Illuminate\Foundation\Http\FormRequest;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class PreviewArcadiaIncoRequest extends FormRequest
{
public function __construct(
private readonly AppAdminAuthService $authService
) {
}
public function authorize(): bool
{
return $this->authService->check();
}
#[\Override]
protected function prepareForValidation(): void
{
if (! $this->has('no_art') && $this->route('no_art') !== null) {
$this->merge(['no_art' => $this->route('no_art')]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'no_art' => ['required', 'integer', 'min:1'],
];
}
public function toGetArcadiaIncoPreviewQueryInput(): GetArcadiaIncoPreviewQueryInput
{
return new GetArcadiaIncoPreviewQueryInput(
noArt: $this->integer('no_art')
);
}
}

View file

@ -1,203 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\ProductIncos;
use App\Actions\ProductIncos\CreateProductIncoInput;
use App\Models\Product;
use App\Rules\IncoId;
use App\Traits\Requests\HasPicture;
use Domain\Enums\Nutriscore;
use Domain\Models\ValueObjects\NutritionalValues;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Enum;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class StoreProductIncoRequest extends FormRequest
{
use HasPicture;
public function __construct(
private readonly AppAdminAuthService $authService
) {
}
public function authorize(): bool
{
return $this->authService->check();
}
/** @return array<string,mixed> */
public function rules(): array
{
return [
'no_art' => ['sometimes', 'nullable', new IncoId()],
// Textes et compositions
'ingredients' => ['sometimes', 'nullable', 'string'],
'preparation' => ['sometimes', 'nullable', 'string'],
'servings' => ['sometimes', 'nullable', 'string', 'max:20'],
'allergens' => ['sometimes', 'nullable', 'string'],
'selling_argument' => ['sometimes', 'nullable', 'string'],
// Nutriscore
'nutriscore' => ['sometimes', 'nullable', 'string', new Enum(Nutriscore::class)],
'nutriscore_args' => ['sometimes', 'nullable', 'string'],
// Valeurs nutritionnelles de base (Double 8,2 unsigned => numeric, min:0)
'nv_ref_weight_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_kj' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_kcal' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_fat_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_sat_fat_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_carb_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_sugar_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_fiber_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_protein_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_salt_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
// Valeurs par portion
'nv_serving_size_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_kj' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_kcal' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_fat_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_sat_fat_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_carb_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_sugar_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_fiber_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_protein_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_serving_salt_g' => ['sometimes', 'nullable', 'numeric', 'min:0'],
// Apports journaliers (% AR)
'nv_daily_energy' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_fat' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_sat_fat' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_carb' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_sugar' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_fiber' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_protein' => ['sometimes', 'nullable', 'numeric', 'min:0'],
'nv_daily_salt' => ['sometimes', 'nullable', 'numeric', 'min:0'],
];
}
#[\Override]
public function attributes(): array
{
return [
'ingredients' => trans('validation.custom.attributes.ingredients'),
'preparation' => trans('validation.custom.attributes.preparation'),
'servings' => trans('validation.custom.attributes.servings'),
'allergens' => trans('validation.custom.attributes.allergens'),
'selling_argument' => trans('validation.custom.attributes.selling_argument'),
'nutriscore' => trans('validation.custom.attributes.nutriscore'),
'nutriscore_args' => trans('validation.custom.attributes.nutriscore_args'),
// Poids de référence et portion
'nv_ref_weight_g' => trans('validation.custom.attributes.nv_ref_weight_g'),
'nv_serving_size_g' => trans('validation.custom.attributes.nv_serving_size_g'),
// Base (Pour 100g / Réf)
'nv_kj' => trans('validation.custom.attributes.nv_kj'),
'nv_kcal' => trans('validation.custom.attributes.nv_kcal'),
'nv_fat_g' => trans('validation.custom.attributes.nv_fat_g'),
'nv_sat_fat_g' => trans('validation.custom.attributes.nv_sat_fat_g'),
'nv_carb_g' => trans('validation.custom.attributes.nv_carb_g'),
'nv_sugar_g' => trans('validation.custom.attributes.nv_sugar_g'),
'nv_fiber_g' => trans('validation.custom.attributes.nv_fiber_g'),
'nv_protein_g' => trans('validation.custom.attributes.nv_protein_g'),
'nv_salt_g' => trans('validation.custom.attributes.nv_salt_g'),
// Par portion
'nv_serving_kj' => trans('validation.custom.attributes.nv_serving_kj'),
'nv_serving_kcal' => trans('validation.custom.attributes.nv_serving_kcal'),
'nv_serving_fat_g' => trans('validation.custom.attributes.nv_serving_fat_g'),
'nv_serving_sat_fat_g' => trans('validation.custom.attributes.nv_serving_sat_fat_g'),
'nv_serving_carb_g' => trans('validation.custom.attributes.nv_serving_carb_g'),
'nv_serving_sugar_g' => trans('validation.custom.attributes.nv_serving_sugar_g'),
'nv_serving_fiber_g' => trans('validation.custom.attributes.nv_serving_fiber_g'),
'nv_serving_protein_g' => trans('validation.custom.attributes.nv_serving_protein_g'),
'nv_serving_salt_g' => trans('validation.custom.attributes.nv_serving_salt_g'),
// Apports journaliers (% AR)
'nv_daily_energy' => trans('validation.custom.attributes.nv_daily_energy'),
'nv_daily_fat' => trans('validation.custom.attributes.nv_daily_fat'),
'nv_daily_sat_fat' => trans('validation.custom.attributes.nv_daily_sat_fat'),
'nv_daily_carb' => trans('validation.custom.attributes.nv_daily_carb'),
'nv_daily_sugar' => trans('validation.custom.attributes.nv_daily_sugar'),
'nv_daily_fiber' => trans('validation.custom.attributes.nv_daily_fiber'),
'nv_daily_protein' => trans('validation.custom.attributes.nv_daily_protein'),
'nv_daily_salt' => trans('validation.custom.attributes.nv_daily_salt'),
];
}
public function toNoArt(): ?int
{
$noArt = $this->input('no_art');
return is_numeric($noArt) ? (int) $noArt : null;
}
public function toNutriscore(): ?Nutriscore
{
$nutriscore = $this->input('nutriscore');
if (! is_string($nutriscore) || $nutriscore === '') {
return null;
}
return Nutriscore::tryFrom($nutriscore);
}
public function toNutritionalValues(): NutritionalValues
{
$getFloat = fn (string $key): ?float => $this->filled($key) && is_numeric($this->input($key)) ? (float) $this->input($key) : null;
return new NutritionalValues(
refWeightG: $getFloat('nv_ref_weight_g'),
kj: $getFloat('nv_kj'),
kcal: $getFloat('nv_kcal'),
fatG: $getFloat('nv_fat_g'),
satFatG: $getFloat('nv_sat_fat_g'),
carbG: $getFloat('nv_carb_g'),
sugarG: $getFloat('nv_sugar_g'),
fiberG: $getFloat('nv_fiber_g'),
proteinG: $getFloat('nv_protein_g'),
saltG: $getFloat('nv_salt_g'),
servingSizeG: $getFloat('nv_serving_size_g'),
servingKj: $getFloat('nv_serving_kj'),
servingKcal: $getFloat('nv_serving_kcal'),
servingFatG: $getFloat('nv_serving_fat_g'),
servingSatFatG: $getFloat('nv_serving_sat_fat_g'),
servingCarbG: $getFloat('nv_serving_carb_g'),
servingSugarG: $getFloat('nv_serving_sugar_g'),
servingFiberG: $getFloat('nv_serving_fiber_g'),
servingProteinG: $getFloat('nv_serving_protein_g'),
servingSaltG: $getFloat('nv_serving_salt_g'),
dailyEnergy: $getFloat('nv_daily_energy'),
dailyFat: $getFloat('nv_daily_fat'),
dailySatFat: $getFloat('nv_daily_sat_fat'),
dailyCarb: $getFloat('nv_daily_carb'),
dailySugar: $getFloat('nv_daily_sugar'),
dailyFiber: $getFloat('nv_daily_fiber'),
dailyProtein: $getFloat('nv_daily_protein'),
dailySalt: $getFloat('nv_daily_salt'),
);
}
public function toCreateProductIncoInput(Product $product): CreateProductIncoInput
{
return new CreateProductIncoInput(
product: $product,
no_art: $this->toNoArt(),
ingredients: $this->string('ingredients')->value() ?: null,
preparation: $this->string('preparation')->value() ?: null,
servings: $this->string('servings')->value() ?: null,
allergens: $this->string('allergens')->value() ?: null,
selling_argument: $this->string('selling_argument')->value() ?: null,
nutriscore: $this->toNutriscore(),
nutriscore_args: $this->string('nutriscore_args')->value() ?: null,
nutrition: $this->toNutritionalValues(),
);
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\ProductIncos;
use App\Actions\ProductIncos\SyncProductIncoInput;
use App\Models\Product;
use Illuminate\Foundation\Http\FormRequest;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class SyncProductIncoRequest extends FormRequest
{
public function __construct(
private readonly AppAdminAuthService $authService
) {
}
public function authorize(): bool
{
return $this->authService->check();
}
/** @return array<string, mixed> */
public function rules(): array
{
return [];
}
public function toSyncProductIncoInput(Product $product): SyncProductIncoInput
{
return new SyncProductIncoInput(
product: $product
);
}
}

View file

@ -1,39 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo\ProductIncos;
use App\Actions\ProductIncos\UpdateProductIncoInput;
use App\Models\ProductInco;
use Illuminate\Support\Arr;
class UpdateProductIncoRequest extends StoreProductIncoRequest
{
/** @return array<string,mixed> */
#[\Override]
public function rules(): array
{
return Arr::except(
parent::rules(),
[
'no_art',
]
);
}
public function toUpdateProductIncoInput(ProductInco $inco): UpdateProductIncoInput
{
return new UpdateProductIncoInput(
inco: $inco,
ingredients: $this->string('ingredients')->value() ?: null,
preparation: $this->string('preparation')->value() ?: null,
servings: $this->string('servings')->value() ?: null,
allergens: $this->string('allergens')->value() ?: null,
selling_argument: $this->string('selling_argument')->value() ?: null,
nutriscore: $this->toNutriscore(),
nutriscore_args: $this->string('nutriscore_args')->value() ?: null,
nutrition: $this->toNutritionalValues(),
);
}
}

View file

@ -80,6 +80,20 @@ class ProductPolicy
return $user->role->isAtLeastEqualsTo(UserRole::Admin) && $hasInco;
}
public function associateInco(Customer | User $user, Product | ProductDto $product): bool
{
if ($user instanceof Customer) {
return false;
}
return $user->role->isAtLeastEqualsTo(UserRole::Admin);
}
public function syncInco(Customer | User $user, Product | ProductDto $product): bool
{
return $this->updateInco($user, $product);
}
public function toggleStatus(Customer | User $user): bool
{
if ($user instanceof Customer) {

View file

@ -207,6 +207,7 @@
"End date": "End date",
"End date of the previous period": "End date of the previous period",
"Energy": "Energy",
"Energy (kJ / kcal)": "Energy (kJ / kcal)",
"Environment file already exists.": "Environment file already exists.",
"Environment file not found.": "Environment file not found.",
"Error confirmation": "Error confirmation",
@ -829,5 +830,38 @@
"Visible": "Visible",
"Not visible": "Not visible",
"Connected": "Connected",
"Connected members only": "Connected members only"
"Connected members only": "Connected members only",
"INCO sheet was not found on Arcadia API.": "INCO sheet was not found on Arcadia API.",
"The INCO sheet has been successfully associated.": "The INCO sheet has been successfully associated.",
"The INCO sheet has been successfully synchronized from Arcadia.": "The INCO sheet has been successfully synchronized from Arcadia.",
"Associate INCO sheet": "Associate INCO sheet",
"Preview Arcadia INCO": "Preview Arcadia INCO",
"Preview and Associate": "Preview and Associate",
"Confirm association": "Confirm association",
"Synchronize from Arcadia": "Synchronize from Arcadia",
"Associating this INCO sheet will replace the currently linked INCO sheet for this product.": "Associating this INCO sheet will replace the currently linked INCO sheet for this product.",
"No INCO sheet currently associated with this product.": "No INCO sheet currently associated with this product.",
"INCO article number": "INCO article number",
"Enter the Arcadia INCO article number": "Enter the Arcadia INCO article number",
"Arcadia INCO Sheet Preview": "Arcadia INCO Sheet Preview",
"No INCO sheet found on Arcadia for this article number.": "No INCO sheet found on Arcadia for this article number.",
"The INCO sheet has been successfully associated with the product.": "The INCO sheet has been successfully associated with the product.",
"Please enter an article number.": "Please enter an article number.",
"An error occurred while fetching the preview.": "An error occurred while fetching the preview.",
"Arcadia API error: :error": "Arcadia API error: :error",
"Arcadia INCO Sheet": "Arcadia INCO Sheet",
"Associate an INCO sheet from the Arcadia API by entering the article number.": "Associate an INCO sheet from the Arcadia API by entering the article number.",
"Loading...": "Loading...",
"Fetching data from Arcadia API...": "Fetching data from Arcadia API...",
"Brand": "Brand",
"Designation": "Designation",
"Servings": "Servings",
"Preparation": "Preparation",
"Associated INCO Sheet": "Associated INCO Sheet",
"No INCO sheet is currently associated with this product.": "No INCO sheet is currently associated with this product.",
"Use the Arcadia section above to search and associate an INCO sheet.": "Use the Arcadia section above to search and associate an INCO sheet.",
"Reference Weight": "Reference Weight",
"Portion Size": "Portion Size",
"Nutriscore arguments": "Nutriscore arguments",
"Selling argument": "Selling argument"
}

View file

@ -15,25 +15,25 @@ return [
],
'helpers' => [
'list' => 'List',
'view_associated' => 'View related :model',
'list_all' => 'List all :model',
'create_model' => 'Create :model',
'view_model' => 'View :model',
'associate_model' => 'Associate :model',
'update_model' => 'Edit :model',
'duplicate_model' => 'Duplicate :model',
'delete_model' => 'Delete :model',
'save_model' => 'Save :model',
'edit_model' => 'Update :model',
'no_results' => 'No results for :model',
'publish' => 'Publish',
'unpublish' => 'Unpublish',
'starred' => 'Highlighted',
'discounted' => 'On sale',
'star' => 'Highlight',
'unstar' => 'Do not highlight',
'seo_title' => 'Must accurately describe the page, recommendation for optimal search engine positioning (<title> tag).',
'list' => 'List',
'view_associated' => 'View related :model',
'list_all' => 'List all :model',
'create_model' => 'Create :model',
'view_model' => 'View :model',
'associate_model' => 'Associate :model',
'update_model' => 'Edit :model',
'duplicate_model' => 'Duplicate :model',
'delete_model' => 'Delete :model',
'save_model' => 'Save :model',
'edit_model' => 'Update :model',
'no_results' => 'No results for :model',
'publish' => 'Publish',
'unpublish' => 'Unpublish',
'starred' => 'Highlighted',
'discounted' => 'On sale',
'star' => 'Highlight',
'unstar' => 'Do not highlight',
'seo_title' => 'Must accurately describe the page, recommendation for optimal search engine positioning (<title> tag).',
'seo_description' => 'Must accurately describe the content of the page (<meta> description tag).',
'required_fields' => 'Required fields',
'required_fields_with_aster' => 'Fields followed by an asterisk are required',
@ -41,10 +41,10 @@ return [
'publish_at' => ':model will be published starting from this date.',
'unpublish_at' => ':model will be unpublished starting from this date.',
'nutritionnal_values' => 'Values must be entered in grams, except for energy in kJ and kcal.',
'new_tab_boolean' => 'Check to open in a new tab.',
'game_text' => 'Must contain at least 15 characters and at most 32 words.',
'url' => 'Must be a valid URL.',
'year' => 'Year of the :model',
'new_tab_boolean' => 'Check to open in a new tab.',
'game_text' => 'Must contain at least 15 characters and at most 32 words.',
'url' => 'Must be a valid URL.',
'year' => 'Year of the :model',
],
'labels' => [

View file

@ -204,6 +204,7 @@
"End date": "Date de fin",
"End date of the previous period": "Date de fin de la période précédente",
"Energy": "Énergie",
"Energy (kJ / kcal)": "Énergie (kJ / kcal)",
"Environment file already exists.": "Le fichier d'environnement existe déjà.",
"Environment file not found.": "Fichier d'environnement introuvable.",
"Error confirmation": "Confirmation d'erreur",
@ -816,5 +817,38 @@
"Visible": "Visible",
"Not visible": "Non visible",
"Connected": "Connecté",
"Connected members only": "Membres connectés uniquement"
"Connected members only": "Membres connectés uniquement",
"INCO sheet was not found on Arcadia API.": "La fiche INCO est introuvable sur l'API Arcadia.",
"The INCO sheet has been successfully associated.": "La fiche INCO a été associée avec succès.",
"The INCO sheet has been successfully synchronized from Arcadia.": "La fiche INCO a été synchronisée avec succès depuis Arcadia.",
"Associate INCO sheet": "Associer une fiche INCO",
"Preview Arcadia INCO": "Prévisualiser la fiche Arcadia",
"Preview and Associate": "Prévisualiser et associer",
"Confirm association": "Confirmer l'association",
"Synchronize from Arcadia": "Synchroniser depuis Arcadia",
"Associating this INCO sheet will replace the currently linked INCO sheet for this product.": "L'association de cette fiche remplacera la fiche INCO actuellement liée à ce produit.",
"No INCO sheet currently associated with this product.": "Aucune fiche INCO actuellement associée à ce produit.",
"INCO article number": "Numéro d'article INCO",
"Enter the Arcadia INCO article number": "Saisissez le numéro d'article INCO Arcadia",
"Arcadia INCO Sheet Preview": "Prévisualisation de la fiche INCO Arcadia",
"No INCO sheet found on Arcadia for this article number.": "Aucune fiche INCO trouvée sur Arcadia pour ce numéro d'article.",
"The INCO sheet has been successfully associated with the product.": "La fiche INCO a été associée avec succès au produit.",
"Please enter an article number.": "Veuillez saisir un numéro d'article.",
"An error occurred while fetching the preview.": "Une erreur est survenue lors de la récupération de la prévisualisation.",
"Arcadia API error: :error": "Erreur de l'API Arcadia : :error",
"Arcadia INCO Sheet": "Fiche INCO Arcadia",
"Associate an INCO sheet from the Arcadia API by entering the article number.": "Associez une fiche INCO depuis l'API Arcadia en saisissant le numéro d'article.",
"Loading...": "Chargement...",
"Fetching data from Arcadia API...": "Récupération des données depuis l'API Arcadia...",
"Brand": "Marque",
"Designation": "Désignation",
"Servings": "Portions",
"Preparation": "Préparation",
"Associated INCO Sheet": "Fiche INCO associée",
"No INCO sheet is currently associated with this product.": "Aucune fiche INCO n'est actuellement associée à ce produit.",
"Use the Arcadia section above to search and associate an INCO sheet.": "Utilisez la section Arcadia ci-dessus pour rechercher et associer une fiche INCO.",
"Reference Weight": "Poids de référence",
"Portion Size": "Taille de la portion",
"Nutriscore arguments": "Arguments Nutriscore",
"Selling argument": "Argumentaire de vente"
}

View file

@ -8,6 +8,7 @@ import {
faArrowRight,
faArrowsAltH,
faArrowsAltV,
faArrowsRotate,
faArrowUp,
faBackspace,
faBox,
@ -20,18 +21,22 @@ import {
faChevronRight,
faCircleExclamation,
faCircleInfo,
faCloudArrowDown,
faCog,
faCrop,
faEraser,
faExternalLinkAlt,
faEye,
faFileLines,
faFloppyDisk,
faFolderOpen,
faHashtag,
faHourglassEnd,
faInfo,
faListUl,
faLocationDot,
faLock,
faMagnifyingGlass,
faPen,
faPencil,
faPlateWheat,
@ -118,5 +123,10 @@ library.add(faInfo);
library.add(faCog);
library.add(faLocationDot);
library.add(faLock);
library.add(faHashtag);
library.add(faCloudArrowDown);
library.add(faArrowsRotate);
library.add(faFileLines);
library.add(faMagnifyingGlass);
dom.watch();

View file

@ -0,0 +1,281 @@
<div class="card mb-4 border-primary">
<div class="card-header bg-primary text-white d-flex align-items-center justify-content-between">
<h2 class="h5 mb-0">
<i class="fa-solid fa-cloud-arrow-down me-2"></i>{{ __('Arcadia INCO Sheet') }}
</h2>
@if (isset($inco) && $inco->no_art)
<form action="{{ route('bo.products.incos.sync', $product) }}" method="POST" class="d-inline">
@csrf
<button type="submit" class="btn btn-sm btn-light text-primary fw-bold" data-bs-toggle="tooltip" title="{{ __('Synchronize from Arcadia') }}">
<i class="fa-solid fa-arrows-rotate me-1"></i> {{ __('Synchronize from Arcadia') }}
</button>
</form>
@endif
</div>
<div class="card-body">
@if (isset($inco) && $inco->no_art)
<p class="text-muted small mb-2">
{{ __('Associating this INCO sheet will replace the currently linked INCO sheet for this product.') }}
</p>
@else
<p class="text-muted mb-3">
{{ __('Associate an INCO sheet from the Arcadia API by entering the article number.') }}
</p>
@endif
<div class="row g-2 align-items-center">
<div class="col-12 col-md-9 col-lg-7">
<div class="input-group">
<span class="input-group-text"><i class="fa-solid fa-hashtag"></i></span>
<input type="number" id="arcadia-no-art-input" class="form-control"
placeholder="{{ __('Enter the Arcadia INCO article number') }}"
value="{{ old('arcadia_no_art', $inco->no_art ?? '') }}" min="1">
<button type="button" id="btn-preview-arcadia" class="btn btn-primary">
<i class="fa-solid fa-magnifying-glass me-1"></i> {{ __('Preview and Associate') }}
</button>
</div>
<div id="arcadia-error-feedback" class="text-danger small mt-1 d-none"></div>
</div>
</div>
</div>
</div>
{{-- MODAL PREVIEW --}}
<div class="modal fade" id="arcadiaPreviewModal" tabindex="-1" aria-labelledby="arcadiaPreviewModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="arcadiaPreviewModalLabel">
<i class="fa-solid fa-file-lines me-2 text-primary"></i>{{ __('Arcadia INCO Sheet Preview') }}
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ __('Cancel') }}"></button>
</div>
<div class="modal-body">
{{-- SPINNER --}}
<div id="arcadia-preview-loading" class="text-center py-5 d-none">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
<span class="visually-hidden">{{ __('Loading...') }}</span>
</div>
<p class="mt-3 text-muted fw-bold">{{ __('Fetching data from Arcadia API...') }}</p>
</div>
{{-- ERROR ALERT --}}
<div id="arcadia-preview-error" class="alert alert-danger d-none">
<i class="fa-solid fa-triangle-exclamation me-2"></i>
<span id="arcadia-preview-error-text"></span>
</div>
{{-- CONTENT --}}
<div id="arcadia-preview-content" class="d-none">
<div class="card mb-3 bg-light">
<div class="card-body">
<div class="row g-2">
<div class="col-sm-6">
<strong>{{ __('INCO article number') }} :</strong>
<span id="preview-no-art" class="badge bg-secondary ms-1"></span>
</div>
<div class="col-sm-6">
<strong>{{ __('Brand') }} :</strong>
<span id="preview-brand"></span>
</div>
<div class="col-12">
<strong>{{ __('Designation') }} :</strong>
<span id="preview-name" class="fw-bold"></span>
</div>
<div class="col-sm-6">
<strong>{{ __('Nutriscore') }} :</strong>
<span id="preview-nutriscore" class="badge bg-success ms-1"></span>
</div>
<div class="col-sm-6">
<strong>{{ __('Servings') }} :</strong>
<span id="preview-servings"></span>
</div>
<div class="col-12">
<strong>{{ __('Allergens') }} :</strong>
<span id="preview-allergens" class="text-danger"></span>
</div>
</div>
</div>
</div>
{{-- INGREDIENTS --}}
<div class="mb-3">
<h6 class="fw-bold border-bottom pb-1">{{ __('Ingredients') }}</h6>
<div id="preview-ingredients" class="p-2 border rounded bg-white small"></div>
</div>
{{-- PREPARATION --}}
<div class="mb-3" id="preview-prep-container">
<h6 class="fw-bold border-bottom pb-1">{{ __('Preparation') }}</h6>
<div id="preview-preparation" class="p-2 border rounded bg-white small"></div>
</div>
{{-- NUTRITION --}}
<div class="mb-3">
<h6 class="fw-bold border-bottom pb-1">{{ __('Nutritional values') }} (100g)</h6>
<table class="table table-sm table-bordered mb-0 small">
<tbody>
<tr>
<th class="w-50">{{ __('Energy (kJ / kcal)') }}</th>
<td id="preview-energy"></td>
</tr>
<tr>
<th>{{ __('Fat') }}</th>
<td id="preview-fat"></td>
</tr>
<tr>
<th class="ps-4 text-muted">{{ __('of which saturated fatty acids') }}</th>
<td id="preview-sat-fat"></td>
</tr>
<tr>
<th>{{ __('Carbohydrates') }}</th>
<td id="preview-carbs"></td>
</tr>
<tr>
<th class="ps-4 text-muted">{{ __('of which sugars') }}</th>
<td id="preview-sugar"></td>
</tr>
<tr>
<th>{{ __('Dietary fiber') }}</th>
<td id="preview-fiber"></td>
</tr>
<tr>
<th>{{ __('Proteins') }}</th>
<td id="preview-protein"></td>
</tr>
<tr>
<th>{{ __('Salt') }}</th>
<td id="preview-salt"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
{{ __('Cancel') }}
</button>
<form action="{{ route('bo.products.incos.associate', $product) }}" method="POST" id="form-confirm-associate">
@csrf
<input type="hidden" name="no_art" id="modal-confirm-no-art" value="">
<button type="submit" class="btn btn-success" id="btn-confirm-associate" disabled>
<i class="fa-solid fa-check me-1"></i> {{ __('Confirm association') }}
</button>
</form>
</div>
</div>
</div>
</div>
@push('scripts')
<script nonce="{{ Vite::cspNonce() }}">
document.addEventListener('DOMContentLoaded', function () {
const inputNoArt = document.getElementById('arcadia-no-art-input');
const btnPreview = document.getElementById('btn-preview-arcadia');
const errorFeedback = document.getElementById('arcadia-error-feedback');
const modalEl = document.getElementById('arcadiaPreviewModal');
const modalLoading = document.getElementById('arcadia-preview-loading');
const modalError = document.getElementById('arcadia-preview-error');
const modalErrorText = document.getElementById('arcadia-preview-error-text');
const modalContent = document.getElementById('arcadia-preview-content');
const btnConfirm = document.getElementById('btn-confirm-associate');
const hiddenNoArt = document.getElementById('modal-confirm-no-art');
if (!btnPreview || !modalEl) return;
const bsModal = window.bootstrap ? window.bootstrap.Modal.getOrCreateInstance(modalEl) : null;
function doPreview() {
const noArt = inputNoArt.value.trim();
if (!noArt || parseInt(noArt, 10) <= 0) {
errorFeedback.textContent = "{{ __('Please enter an article number.') }}";
errorFeedback.classList.remove('d-none');
return;
}
errorFeedback.classList.add('d-none');
modalLoading.classList.remove('d-none');
modalError.classList.add('d-none');
modalContent.classList.add('d-none');
btnConfirm.disabled = true;
hiddenNoArt.value = '';
if (bsModal) {
bsModal.show();
}
const previewUrl = "{{ route('bo.products.incos.preview', ['product' => $product, 'no_art' => '__NO_ART__']) }}".replace('__NO_ART__', encodeURIComponent(noArt));
fetch(previewUrl, {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(async (response) => {
modalLoading.classList.add('d-none');
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.message || "{{ __('No INCO sheet found on Arcadia for this article number.') }}");
}
return response.json();
})
.then((data) => {
document.getElementById('preview-no-art').textContent = data.no_art;
document.getElementById('preview-name').textContent = data.libelle || data.name || '-';
document.getElementById('preview-brand').textContent = data.brand || '-';
document.getElementById('preview-nutriscore').textContent = data.nutriscore || 'N/A';
document.getElementById('preview-servings').textContent = data.servings || '-';
document.getElementById('preview-allergens').textContent = data.allergens || "{{ __('None') }}";
const ingEl = document.getElementById('preview-ingredients');
if (data.ingredients) {
ingEl.innerHTML = data.ingredients;
} else {
ingEl.innerHTML = '<em class="text-muted">{{ __('None') }}</em>';
}
const prepEl = document.getElementById('preview-preparation');
if (data.preparation) {
prepEl.innerHTML = data.preparation;
document.getElementById('preview-prep-container').classList.remove('d-none');
} else {
document.getElementById('preview-prep-container').classList.add('d-none');
}
const kj = data.energy_kj !== null ? data.energy_kj + ' kJ' : '-';
const kcal = data.energy_kcal !== null ? data.energy_kcal + ' kcal' : '-';
document.getElementById('preview-energy').textContent = `${kj} / ${kcal}`;
document.getElementById('preview-fat').textContent = data.fat !== null ? data.fat + ' g' : '-';
document.getElementById('preview-sat-fat').textContent = data.sat_fat !== null ? data.sat_fat + ' g' : '-';
document.getElementById('preview-carbs').textContent = data.carbs !== null ? data.carbs + ' g' : '-';
document.getElementById('preview-sugar').textContent = data.sugar !== null ? data.sugar + ' g' : '-';
document.getElementById('preview-fiber').textContent = data.fiber !== null ? data.fiber + ' g' : '-';
document.getElementById('preview-protein').textContent = data.protein !== null ? data.protein + ' g' : '-';
document.getElementById('preview-salt').textContent = data.salt !== null ? data.salt + ' g' : '-';
hiddenNoArt.value = data.no_art;
btnConfirm.disabled = false;
modalContent.classList.remove('d-none');
})
.catch((err) => {
modalLoading.classList.add('d-none');
modalErrorText.textContent = err.message || "{{ __('An error occurred while fetching the preview.') }}";
modalError.classList.remove('d-none');
});
}
btnPreview.addEventListener('click', doPreview);
inputNoArt.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
doPreview();
}
});
});
</script>
@endpush

View file

@ -1,34 +0,0 @@
@extends('bo.layouts.layout')
@section('title', sprintf('%s - %s', Str::ucfirst(__('creation')), Str::ucfirst(trans_choice('models.classes.product_incos', \INF))))
@section('breadcrumb', request()->route()->getName())
@php view()->share('brParam', $product) @endphp
@section('content')
<div class="card">
<div class="card-header">
<div class="row">
<div class="col">
<h1 class="h3">
<a class="btn btn-sm btn-primary"
href="{{ URL::previous() === request()->url() ? route('bo.product-incos.index') : URL::previous() }}"><i
class="fa-solid fa-arrow-left"></i></a>
{{ Str::ucfirst(trans_choice('models.classes.product_incos', 1)) }}&nbsp;{{ Str::ucfirst(__('crud.actions.create')) }}
</h1>
</div>
</div>
</div>
<div class="card-body">
<form action="{{ route('bo.products.incos.store', $product) }}" method="POST" enctype='multipart/form-data'>
@csrf
@include('bo.product-incos.form')
<div class="text-center">
<button class="btn btn-primary" type="submit"><i class="fa fa-floppy-disk"></i>
<span class="d-none d-sm-inline" data-bs-toggle="tooltip"
title="{{ Str::ucfirst(__('crud.actions.save')) }}">{{ Str::ucfirst(__('crud.actions.save')) }}</span></button>
</div>
</form>
</div>
</div>
@endsection

View file

@ -1,43 +1,236 @@
@extends('bo.layouts.layout')
@section('title', sprintf('%s - %s %s', Str::ucfirst(__('crud.actions.edit')), Str::ucfirst(trans_choice('models.classes.product_incos',
1)), $product->name))
@section('title', sprintf('%s - %s', Str::ucfirst(trans_choice('models.classes.product_incos', 1)), $product->name))
@section('breadcrumb', request()->route()->getName())
@php view()->share('brParam', $product) @endphp
@section('content')
@include('bo.product-incos.arcadia-card')
<div class="card">
<div class="card-header">
<div class="row">
<div class="row align-items-center">
<div class="col">
<h1 class="h3">
<a class="btn btn-sm btn-primary"
href="{{ URL::previous() === request()->url() ? route('bo.product-incos.index') : URL::previous() }}"><i
class="fa-solid fa-arrow-left"></i></a>
{{ Str::ucfirst(trans_choice('models.classes.product_incos', 1)) }}&nbsp;{{ Str::ucfirst(__('crud.actions.edit')) }}
<h1 class="h3 mb-0">
<a class="btn btn-sm btn-primary me-2"
href="{{ URL::previous() === request()->url() ? route('bo.products.edit', $product) : URL::previous() }}">
<i class="fa-solid fa-arrow-left"></i>
</a>
{{ Str::ucfirst(trans_choice('models.classes.product_incos', 1)) }} : {{ $product->name }}
</h1>
</div>
</div>
</div>
<div class="card-body">
<form action="{{ route('bo.products.incos.update', [
'product' => $product,
'inco' => $inco,
]) }}"
method="POST" enctype='multipart/form-data'>
@csrf
{{ method_field('PUT') }}
@include('bo.product-incos.form', compact('product', 'inco'))
<div class="text-center">
<span class="d-block mb-3">
<span class="badge text-bg-info">{{ __('crud.helpers.required_fields_with_aster') }}</span>
</span>
<button class="btn btn-primary" type="submit"><i class="fa fa-floppy-disk"></i>
<span class="d-none d-sm-inline" data-bs-toggle="tooltip"
title="{{ Str::ucfirst(__('crud.actions.save')) }}">{{ Str::ucfirst(__('crud.actions.save')) }}</span></button>
@if ($inco)
{{-- GENERAL INFO & NUTRISCORE --}}
<fieldset class="mb-4 border p-3 rounded">
<legend class="h5 px-2">{{ __('General Information & Nutriscore') }}</legend>
<div class="row g-3">
<div class="col-12 col-md-3">
<label class="form-label text-muted fw-bold mb-1">{{ __('INCO article number') }}</label>
<div>
<span class="badge bg-primary fs-6">#{{ $inco->no_art }}</span>
</div>
</div>
<div class="col-12 col-md-3">
<label class="form-label text-muted fw-bold mb-1">{{ __('Servings') }}</label>
<div class="fw-semibold">{{ $inco->servings ?: '-' }}</div>
</div>
<div class="col-12 col-md-3">
<label class="form-label text-muted fw-bold mb-1">{{ __('Nutriscore') }}</label>
<div>
@if ($inco->nutriscore)
<img src="{{ Vite::asset("resources/assets/images/nutriscore/nutriscore-{$inco->nutriscore->value()}.png") }}"
alt="{{ __('Nutriscore') }} {{ $inco->nutriscore->label() }}"
style="height: 38px;">
@else
<span class="badge bg-secondary">{{ __('None') }}</span>
@endif
</div>
</div>
@if ($inco->nutriscore_args)
<div class="col-12 col-md-3">
<label class="form-label text-muted fw-bold mb-1">{{ __('Nutriscore arguments') }}</label>
<div>{{ $inco->nutriscore_args }}</div>
</div>
@endif
</div>
</fieldset>
{{-- COMPOSITION & PREPARATION --}}
<fieldset class="mb-4 border p-3 rounded">
<legend class="h5 px-2">{{ __('Composition & Preparation') }}</legend>
<div class="row g-3">
<div class="col-12">
<label class="form-label text-muted fw-bold mb-1">{{ __('Ingredients') }}</label>
<div class="p-3 border rounded bg-light">
@if ($inco->ingredients)
{!! clean($inco->ingredients) !!}
@else
<em class="text-muted">{{ __('None') }}</em>
@endif
</div>
</div>
@if ($inco->allergens)
<div class="col-12">
<div class="alert alert-warning mb-0">
<i class="fa-solid fa-triangle-exclamation me-2"></i>
<strong>{{ __('Allergens') }} :</strong> {{ $inco->allergens }}
</div>
</div>
@endif
@if ($inco->preparation)
<div class="col-12">
<label class="form-label text-muted fw-bold mb-1">{{ __('Preparation') }}</label>
<div class="p-3 border rounded bg-light">
{!! clean($inco->preparation) !!}
</div>
</div>
@endif
@if ($inco->selling_argument)
<div class="col-12">
<label class="form-label text-muted fw-bold mb-1">{{ __('Selling argument') }}</label>
<div class="p-3 border rounded bg-light">
{!! clean($inco->selling_argument) !!}
</div>
</div>
@endif
</div>
</fieldset>
{{-- NUTRITIONAL VALUES --}}
<fieldset class="mb-3 border p-3 rounded">
<legend class="h5 px-2">{{ __('Nutritional Values') }}</legend>
<div class="row mb-3">
<div class="col-12 col-md-6">
<span class="text-muted fw-bold">{{ __('Reference Weight') }} :</span>
<span class="fw-semibold">{{ $inco->nutrition->refWeightG ?? 100 }} g</span>
</div>
@if ($inco->nutrition->servingSizeG)
<div class="col-12 col-md-6">
<span class="text-muted fw-bold">{{ __('Portion Size') }} :</span>
<span class="fw-semibold">{{ $inco->nutrition->servingSizeG }} g</span>
</div>
@endif
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped align-middle min-w-700px mb-0">
<thead class="table-light text-nowrap">
<tr>
<th class="w-40" scope="col">{{ __('Item') }}</th>
<th class="w-20 text-center" scope="col">{{ __('Per 100g / Ref') }}</th>
<th class="w-20 text-center" scope="col">{{ __('Per Serving') }}</th>
<th class="w-20 text-center" scope="col">{{ __('Daily Intake (% RI)') }}</th>
</tr>
</thead>
<tbody>
{{-- ENERGIE --}}
<tr>
<td><b>{{ __('Energy') }}</b></td>
<td class="text-center">
@if ($inco->nutrition->kj !== null || $inco->nutrition->kcal !== null)
{{ $inco->nutrition->kj !== null ? $inco->nutrition->kj . ' kJ' : '' }}
@if ($inco->nutrition->kj !== null && $inco->nutrition->kcal !== null) / @endif
{{ $inco->nutrition->kcal !== null ? $inco->nutrition->kcal . ' kcal' : '' }}
@else
-
@endif
</td>
<td class="text-center">
@if ($inco->nutrition->servingKj !== null || $inco->nutrition->servingKcal !== null)
{{ $inco->nutrition->servingKj !== null ? $inco->nutrition->servingKj . ' kJ' : '' }}
@if ($inco->nutrition->servingKj !== null && $inco->nutrition->servingKcal !== null) / @endif
{{ $inco->nutrition->servingKcal !== null ? $inco->nutrition->servingKcal . ' kcal' : '' }}
@else
-
@endif
</td>
<td class="text-center">
{{ $inco->nutrition->dailyEnergy !== null ? $inco->nutrition->dailyEnergy . ' %' : '-' }}
</td>
</tr>
{{-- MATIERES GRASSES --}}
<tr>
<td>
<b>{{ __('Fat') }}</b><br>
<small class="text-muted ps-2">{{ __('of which saturated fatty acids') }}</small>
</td>
<td class="text-center">
{{ $inco->nutrition->fatG !== null ? $inco->nutrition->fatG . ' g' : '-' }}<br>
<small class="text-muted">{{ $inco->nutrition->satFatG !== null ? $inco->nutrition->satFatG . ' g' : '-' }}</small>
</td>
<td class="text-center">
{{ $inco->nutrition->servingFatG !== null ? $inco->nutrition->servingFatG . ' g' : '-' }}<br>
<small class="text-muted">{{ $inco->nutrition->servingSatFatG !== null ? $inco->nutrition->servingSatFatG . ' g' : '-' }}</small>
</td>
<td class="text-center">
{{ $inco->nutrition->dailyFat !== null ? $inco->nutrition->dailyFat . ' %' : '-' }}<br>
<small class="text-muted">{{ $inco->nutrition->dailySatFat !== null ? $inco->nutrition->dailySatFat . ' %' : '-' }}</small>
</td>
</tr>
{{-- GLUCIDES --}}
<tr>
<td>
<b>{{ __('Carbohydrates') }}</b><br>
<small class="text-muted ps-2">{{ __('of which sugars') }}</small>
</td>
<td class="text-center">
{{ $inco->nutrition->carbG !== null ? $inco->nutrition->carbG . ' g' : '-' }}<br>
<small class="text-muted">{{ $inco->nutrition->sugarG !== null ? $inco->nutrition->sugarG . ' g' : '-' }}</small>
</td>
<td class="text-center">
{{ $inco->nutrition->servingCarbG !== null ? $inco->nutrition->servingCarbG . ' g' : '-' }}<br>
<small class="text-muted">{{ $inco->nutrition->servingSugarG !== null ? $inco->nutrition->servingSugarG . ' g' : '-' }}</small>
</td>
<td class="text-center">
{{ $inco->nutrition->dailyCarb !== null ? $inco->nutrition->dailyCarb . ' %' : '-' }}<br>
<small class="text-muted">{{ $inco->nutrition->dailySugar !== null ? $inco->nutrition->dailySugar . ' %' : '-' }}</small>
</td>
</tr>
{{-- FIBRES, PROTEINES, SEL --}}
@foreach ([
['label' => 'Fiber', 'prop' => 'fiberG', 'servingProp' => 'servingFiberG', 'dailyProp' => 'dailyFiber'],
['label' => 'Protein', 'prop' => 'proteinG', 'servingProp' => 'servingProteinG', 'dailyProp' => 'dailyProtein'],
['label' => 'Salt', 'prop' => 'saltG', 'servingProp' => 'servingSaltG', 'dailyProp' => 'dailySalt'],
] as $nutrient)
<tr>
<td><b>{{ __($nutrient['label']) }}</b></td>
<td class="text-center">
{{ $inco->nutrition->{$nutrient['prop']} !== null ? $inco->nutrition->{$nutrient['prop']} . ' g' : '-' }}
</td>
<td class="text-center">
{{ $inco->nutrition->{$nutrient['servingProp']} !== null ? $inco->nutrition->{$nutrient['servingProp']} . ' g' : '-' }}
</td>
<td class="text-center">
{{ $inco->nutrition->{$nutrient['dailyProp']} !== null ? $inco->nutrition->{$nutrient['dailyProp']} . ' %' : '-' }}
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</fieldset>
@else
<div class="text-center py-5">
<i class="fa-solid fa-circle-info fa-3x text-muted mb-3 d-block"></i>
<h2 class="h5 text-muted">{{ __('No INCO sheet is currently associated with this product.') }}</h2>
<p class="text-muted mb-0">
{{ __('Use the Arcadia section above to search and associate an INCO sheet.') }}
</p>
</div>
</form>
@endif
</div>
</div>
@endsection

View file

@ -1,342 +0,0 @@
<div class="row">
<div class="col">
<fieldset class="mb-3 border p-3">
<legend>{{ __('General Information & Nutriscore') }}</legend>
<div class="row mb-3">
@if (!request()->routeIs('bo.products.incos.create'))
{{-- NO ART --}}
<div class="col-12 col-md-4 form-group">
<label class="col-form-label" for="inco-no-art"><b>{{ Str::ucfirst(__('validation.custom.attributes.no_art')) }}</b></label>
<input class="form-control" id="inco-no-art" name="no_art" type="number" value="{{ old('no_art', $inco->no_art ?? '') }}"
step="1" min="0" readonly disabled>
@include('bo.modules.input-error', ['inputName' => 'no_art'])
</div>
@endif
{{-- SERVINGS --}}
<div class="col-12 col-md-4 form-group">
<label class="col-form-label" for="inco-servings"><b>{{ Str::ucfirst(__('validation.custom.attributes.servings')) }}</b></label>
<div class="word-counter" data-json='@json(['for' => 'inco-servings'])'></div>
<input class="form-control" id="inco-servings" name="servings" type="text" value="{{ old('servings', $inco->servings ?? '') }}"
maxlength="20" placeholder="{{ __('Ex: 2 people') }}">
@include('bo.modules.input-error', ['inputName' => 'servings'])
</div>
{{-- NUTRISCORE --}}
<div class="col-12 col-md-4 form-group">
<label class="col-form-label"
for="inco-nutriscore"><b>{{ Str::ucfirst(__('validation.custom.attributes.nutriscore')) }}</b></label>
<select class="form-select" id="inco-nutriscore" name="nutriscore">
<option value="" @if (!old('nutriscore', $inco->nutriscore ?? null)) selected @endif>{{ __('None') }}</option>
@foreach ($nutriscores as $score)
<option value="{{ $score->name() }}" @selected(old('nutriscore', optional($inco ?? null)->nutriscore?->value() ?? null) == $score->value())>{{ $score->name() }}</option>
@endforeach
</select>
@include('bo.modules.input-error', ['inputName' => 'nutriscore'])
</div>
{{-- NUTRISCORE ARGS --}}
<div class="col-12 col-md-8 form-group">
<label class="col-form-label"
for="inco-nutriscore-args"><b>{{ Str::ucfirst(__('validation.custom.attributes.nutriscore_args')) }}</b></label>
<div class="word-counter" data-json='@json(['for' => 'inco-nutriscore-args'])'></div>
<input class="form-control" id="inco-nutriscore-args" name="nutriscore_args" type="text"
value="{{ old('nutriscore_args', $inco->nutriscore_args ?? '') }}">
@include('bo.modules.input-error', ['inputName' => 'nutriscore_args'])
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col">
<fieldset class="mb-3 border p-3">
<legend>{{ __('Composition & Preparation') }}</legend>
<div class="row mb-3">
{{-- INGREDIENTS --}}
<div class="col-12 form-group mb-4">
<label class="h6" for="inco-ingredients">{{ Str::ucfirst(__('validation.custom.attributes.ingredients')) }}</label>
@include('bo.modules.input-error', ['inputName' => 'ingredients'])
@php
$editorIngredients = [
'id' => 'inco-ingredients',
'csrf' => csrf_token(),
'name' => 'ingredients',
'text' => old('ingredients', $inco->ingredients ?? '') ?? '',
];
@endphp
<div class="ck-editor" data-json='@json($editorIngredients)'></div>
</div>
{{-- PREPARATION --}}
<div class="col-12 form-group mb-4">
<label class="h6" for="inco-preparation">{{ Str::ucfirst(__('validation.custom.attributes.preparation')) }}</label>
@include('bo.modules.input-error', ['inputName' => 'preparation'])
@php
$editorPrep = [
'id' => 'inco-preparation',
'csrf' => csrf_token(),
'name' => 'preparation',
'text' => old('preparation', $inco->preparation ?? '') ?? '',
];
@endphp
<div class="ck-editor" data-json='@json($editorPrep)'></div>
</div>
{{-- SELLING ARGUMENT --}}
<div class="col-12 form-group mb-4">
<label class="h6" for="inco-selling-argument">{{ Str::ucfirst(__('validation.custom.attributes.selling_argument')) }}</label>
@include('bo.modules.input-error', ['inputName' => 'selling_argument'])
@php
$editorSelling = [
'id' => 'inco-selling-argument',
'csrf' => csrf_token(),
'name' => 'selling_argument',
'text' => old('selling_argument', $inco->selling_argument ?? '') ?? '',
];
@endphp
<div class="ck-editor" data-json='@json($editorSelling)'></div>
</div>
{{-- ALLERGENS --}}
<div class="col-12 form-group">
<label class="col-form-label"
for="inco-allergens"><b>{{ Str::ucfirst(__('validation.custom.attributes.allergens')) }}</b></label>
<div class="word-counter" data-json='@json(['for' => 'inco-allergens'])'></div>
<textarea class="form-control" id="inco-allergens" name="allergens" rows="3">{{ old('allergens', $inco->allergens ?? '') }}</textarea>
@include('bo.modules.input-error', ['inputName' => 'allergens'])
</div>
</div>
</fieldset>
</div>
</div>
<div class="row">
<div class="col">
<fieldset class="mb-3 border p-3">
<legend>{{ __('Nutritional Values') }}</legend>
<div class="row mb-4">
<div class="col-12 col-md-6 form-group">
<label class="col-form-label"
for="nv_ref_weight_g"><b>{{ Str::ucfirst(__('validation.custom.attributes.nv_ref_weight_g')) }}</b></label>
<input class="form-control" id="nv_ref_weight_g" name="nv_ref_weight_g" type="number"
value="{{ old('nv_ref_weight_g', $inco->nutrition?->refWeightG ?? '') }}" step="0.01">
@include('bo.modules.input-error', ['inputName' => 'nv_ref_weight_g'])
</div>
<div class="col-12 col-md-6 form-group">
<label class="col-form-label"
for="nv_serving_size_g"><b>{{ Str::ucfirst(__('validation.custom.attributes.nv_serving_size_g')) }}</b></label>
<input class="form-control" id="nv_serving_size_g" name="nv_serving_size_g" type="number"
value="{{ old('nv_serving_size_g', $inco->nutrition?->servingSizeG ?? '') }}" step="0.01">
@include('bo.modules.input-error', ['inputName' => 'nv_serving_size_g'])
</div>
</div>
<div class="table-responsive">
<table class="table-bordered table align-middle min-w-700px">
<thead class="table-light text-nowrap">
<tr>
<th class="w-25" scope="col">{{ __('Item') }}</th>
<th class="w-25" scope="col">{{ __('Per 100g / Ref') }}</th>
<th class="w-25" scope="col">{{ __('Per Serving') }}</th>
<th class="w-25" scope="col">{{ __('Daily Intake (% RI)') }}</th>
</tr>
</thead>
<tbody>
{{-- ENERGIE --}}
<tr>
<td><b>{{ __('Energy') }}</b></td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_kj" type="number"
value="{{ old('nv_kj', $inco->nutrition?->kj ?? '') }}" step="0.01" placeholder="kJ">
<small class="input-group-text text-muted">kJ</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_kj'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_kcal" type="number"
value="{{ old('nv_kcal', $inco->nutrition?->kcal ?? '') }}" step="0.01" placeholder="kcal">
<small class="input-group-text text-muted">kcal</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_kcal'])
</td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_serving_kj" type="number"
value="{{ old('nv_serving_kj', $inco->nutrition?->servingKj ?? '') }}" step="0.01" placeholder="kJ">
<small class="input-group-text text-muted">kJ</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_kj'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_serving_kcal" type="number"
value="{{ old('nv_serving_kcal', $inco->nutrition?->servingKcal ?? '') }}" step="0.01" placeholder="kcal">
<small class="input-group-text text-muted">kcal</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_kcal'])
</td>
<td>
<div class="input-group">
<input class="form-control form-control-sm" name="nv_daily_energy" type="number"
value="{{ old('nv_daily_energy', $inco->nutrition?->dailyEnergy ?? '') }}" step="0.01" placeholder="%">
<small class="input-group-text text-muted">%</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_daily_energy'])
</td>
</tr>
{{-- MATIERES GRASSES --}}
<tr>
<td><b>{{ __('Fat') }}</b><br><small class="text-muted">{{ __('of which saturated fatty acids') }}</small></td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_fat_g" type="number"
value="{{ old('nv_fat_g', $inco->nutrition?->fatG ?? '') }}" step="0.01" placeholder="{{ __('Total') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_fat_g'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_sat_fat_g" type="number"
value="{{ old('nv_sat_fat_g', $inco->nutrition?->satFatG ?? '') }}" step="0.01"
placeholder="{{ __('Saturated') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_sat_fat_g'])
</td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_serving_fat_g" type="number"
value="{{ old('nv_serving_fat_g', $inco->nutrition?->servingFatG ?? '') }}" step="0.01"
placeholder="{{ __('Total') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_fat_g'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_serving_sat_fat_g" type="number"
value="{{ old('nv_serving_sat_fat_g', $inco->nutrition?->servingSatFatG ?? '') }}" step="0.01"
placeholder="{{ __('Saturated') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_sat_fat_g'])
</td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_daily_fat" type="number"
value="{{ old('nv_daily_fat', $inco->nutrition?->dailyFat ?? '') }}" step="0.01"
placeholder="{{ __('Total %') }}">
<small class="input-group-text text-muted">%</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_daily_fat'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_daily_sat_fat" type="number"
value="{{ old('nv_daily_sat_fat', $inco->nutrition?->dailySatFat ?? '') }}" step="0.01"
placeholder="{{ __('Sat. %') }}">
<small class="input-group-text text-muted">%</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_daily_sat_fat'])
</td>
</tr>
{{-- GLUCIDES --}}
<tr>
<td><b>{{ __('Carbohydrates') }}</b><br><small class="text-muted">{{ __('of which sugars') }}</small></td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_carb_g" type="number"
value="{{ old('nv_carb_g', $inco->nutrition?->carbG ?? '') }}" step="0.01" placeholder="{{ __('Total') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_carb_g'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_sugar_g" type="number"
value="{{ old('nv_sugar_g', $inco->nutrition?->sugarG ?? '') }}" step="0.01" placeholder="{{ __('Sugars') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_sugar_g'])
</td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_serving_carb_g" type="number"
value="{{ old('nv_serving_carb_g', $inco->nutrition?->servingCarbG ?? '') }}" step="0.01"
placeholder="{{ __('Total') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_carb_g'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_serving_sugar_g" type="number"
value="{{ old('nv_serving_sugar_g', $inco->nutrition?->servingSugarG ?? '') }}" step="0.01"
placeholder="{{ __('Sugars') }}">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_sugar_g'])
</td>
<td>
<div class="input-group mb-1">
<input class="form-control form-control-sm" name="nv_daily_carb" type="number"
value="{{ old('nv_daily_carb', $inco->nutrition?->dailyCarb ?? '') }}" step="0.01"
placeholder="{{ __('Total %') }}">
<small class="input-group-text text-muted">%</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_daily_carb'])
<div class="input-group">
<input class="form-control form-control-sm" name="nv_daily_sugar" type="number"
value="{{ old('nv_daily_sugar', $inco->nutrition?->dailySugar ?? '') }}" step="0.01"
placeholder="{{ __('Sugars %') }}">
<small class="input-group-text text-muted">%</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_daily_sugar'])
</td>
</tr>
{{-- FIBRES, PROTEINES, SEL --}}
@foreach ([['label' => 'Fiber', 'name' => 'fiber', 'prop' => 'fiberG', 'propServing' => 'servingFiberG', 'propDaily' => 'dailyFiber'], ['label' => 'Protein', 'name' => 'protein', 'prop' => 'proteinG', 'propServing' => 'servingProteinG', 'propDaily' => 'dailyProtein'], ['label' => 'Salt', 'name' => 'salt', 'prop' => 'saltG', 'propServing' => 'servingSaltG', 'propDaily' => 'dailySalt']] as $nut)
<tr>
<td><b>{{ __($nut['label']) }}</b></td>
<td>
<div class="input-group">
<input class="form-control form-control-sm" name="nv_{{ $nut['name'] }}_g" type="number"
value="{{ old('nv_' . $nut['name'] . '_g', $inco->nutrition?->{$nut['prop']} ?? '') }}" step="0.01">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_' . $nut['name'] . '_g'])
</td>
<td>
<div class="input-group">
<input class="form-control form-control-sm" name="nv_serving_{{ $nut['name'] }}_g" type="number"
value="{{ old('nv_serving_' . $nut['name'] . '_g', $inco->nutrition?->{$nut['propServing']} ?? '') }}"
step="0.01">
<small class="input-group-text text-muted">g</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_serving_' . $nut['name'] . '_g'])
</td>
<td>
<div class="input-group">
<input class="form-control form-control-sm" name="nv_daily_{{ $nut['name'] }}" type="number"
value="{{ old('nv_daily_' . $nut['name'], $inco->nutrition?->{$nut['propDaily']} ?? '') }}" step="0.01">
<small class="input-group-text text-muted">%</small>
</div>
@include('bo.modules.input-error', ['inputName' => 'nv_daily_' . $nut['name']])
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</fieldset>
</div>
</div>

View file

@ -15,7 +15,15 @@
<span class="btn-group">
@can('viewAny', \App\Models\Product::class)
<a class="btn btn-sm btn-primary"
href="{{ URL::previous() === request()->url() ? route('bo.products.index') : URL::previous() }}">
href="{{ in_array(URL::previous(), [
request()->url(),
route('bo.products.incos.edit', [
'product' => $product,
'inco' => $product->inco ?? 'unknown',
]),
]) === true
? route('bo.products.index')
: URL::previous() }}">
<i class="fa-solid fa-arrow-left"></i>
</a>
@endcan
@ -26,7 +34,7 @@
<div class="col-3 text-end">
<div class="btn-group">
@can('createInco', $product)
<a class="btn btn-primary" class="d-inline" href="{{ route('bo.products.incos.create', $product) }}"
<a class="btn btn-sm btn-primary" class="d-inline" href="{{ route('bo.products.incos.create', $product) }}"
title="{{ __('crud.helpers.associate_model', ['model' => trans_choice('models.classes.product_incos', 1)]) }}">
<i class="fa-solid fa-plus"></i>
<span>{{ Str::title(trans_choice('models.classes.product_incos', 1)) }}</span>

View file

@ -81,10 +81,11 @@ Route::middleware(['auth:backend', 'has-role:Admin'])->group(function (): void {
Route::patch('/products/{product}/{action}', [ProductsController::class, 'changeOrder'])->name('products.change-order');
// * PRODUCTS INCO
Route::resource('products.incos', ProductIncosController::class)
->only(['create', 'store', 'edit', 'update'])
->withoutMiddleware('htmlsanitize')
->middleware('htmlsanitize:ingredients,preparation,selling_argument');
Route::get('/products/{product}/incos/preview/{no_art}', [ProductIncosController::class, 'preview'])->name('products.incos.preview');
Route::post('/products/{product}/incos/associate', [ProductIncosController::class, 'associate'])->name('products.incos.associate');
Route::post('/products/{product}/incos/sync', [ProductIncosController::class, 'sync'])->name('products.incos.sync');
Route::get('/products/{product}/incos/create', [ProductIncosController::class, 'edit'])->name('products.incos.create');
Route::get('/products/{product}/incos/{inco?}/edit', [ProductIncosController::class, 'edit'])->name('products.incos.edit');
// * MERCHANDISING
Route::get('/products/starred', [ProductsController::class, 'starred'])->name('merch.starred');

View file

@ -2,12 +2,15 @@
declare(strict_types=1);
use App\Dto\ArcadiaIncoDataDto;
use App\Dto\ArcadiaIncoPreviewDto;
use App\Dto\ProductDto;
use App\Dto\ProductIncoDto;
use App\Models\Product;
use App\Models\ProductInco;
use App\Models\Range;
use App\Models\User;
use App\Services\ArcadiaIncoService;
use Domain\Enums\Nutriscore;
use Domain\Enums\ProductBrand;
use Domain\Enums\SellUnit;
@ -15,6 +18,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit;
use Domain\Enums\UserRole;
use Domain\Models\ValueObjects\NutritionalValues;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Money\Money;
@ -55,66 +59,16 @@ describe('ProductIncosController', function () {
$this->product->save();
});
it('can access create when product has no inco', function () {
it('can access inco management when product has no inco', function () {
/** @var \Tests\TestCase $this */
// WHEN
$response = $this->get(route('bo.products.incos.create', $this->product));
// THEN
$response->assertStatus(200);
$response->assertViewIs('bo.product-incos.create');
$response->assertViewIs('bo.product-incos.edit');
$response->assertViewHas('product', fn ($p) => $p instanceof ProductDto && $p->id === (string) $this->product->id);
$response->assertViewHas('nutriscores');
});
it('forbids create when product already has an inco', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$inco = new ProductInco();
$inco->no_art = 101;
$inco->product()->associate($this->product);
$inco->save();
// WHEN
$response = $this->get(route('bo.products.incos.create', $this->product));
// THEN
$response->assertStatus(403);
});
it('can store a product inco', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$data = [
'ingredients' => 'Poulet 99%, sel',
'preparation' => 'Au four 40min',
'servings' => '4 personnes',
'allergens' => 'Aucun',
'selling_argument' => 'Élevé en plein air',
'nutriscore' => 'A',
'nutriscore_args' => 'Très sain',
'nv_ref_weight_g' => '100',
'nv_kj' => '450',
'nv_kcal' => '110',
'nv_fat_g' => '2.5',
];
// WHEN
$response = $this->post(route('bo.products.incos.store', $this->product), $data);
// THEN
$inco = ProductInco::query()->where('product_id', $this->product->id)->first();
expect($inco)->not->toBeNull()
->and($inco->ingredients)->toBe('Poulet 99%, sel')
->and($inco->nutriscore)->toBe(Nutriscore::A)
->and($inco->nutrition->refWeightG)->toBe(100.0)
->and($inco->nutrition->kj)->toBe(450.0);
$response->assertRedirect(route('bo.products.incos.edit', [
'product' => $this->product,
'inco' => $inco,
]));
$response->assertSessionHas('success');
$response->assertViewHas('inco', null);
});
it('can access edit when product has an inco', function () {
@ -138,35 +92,125 @@ describe('ProductIncosController', function () {
$response->assertViewHas('inco', fn ($i) => $i instanceof ProductIncoDto && $i->id === $inco->id);
});
it('can update a product inco', function () {
it('can preview an inco sheet from arcadia', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$inco = new ProductInco();
$inco->no_art = 103;
$inco->product()->associate($this->product);
$inco->save();
$arcadiaService = \Mockery::mock(ArcadiaIncoService::class);
$previewDto = new ArcadiaIncoPreviewDto(
noArt: 27996,
name: 'POULET FERMIER',
libelle: 'Poulet Fermier Label Rouge',
brand: 'Loué',
nutriscore: 'A',
servings: '4/5',
allergens: 'Aucun',
ingredients: '<p>Poulet 100%</p>',
preparation: '<p>Au four</p>',
energyKcal: 150.0,
energyKj: 630.0,
);
$data = [
'ingredients' => 'Ingrédients modifiés',
'servings' => '6 personnes',
'nutriscore' => 'B',
'nv_ref_weight_g' => '150',
'nv_kj' => '520',
];
$arcadiaService->shouldReceive('getPreview')
->once()
->with(27996)
->andReturn($previewDto);
$this->app->instance(ArcadiaIncoService::class, $arcadiaService);
// WHEN
$response = $this->put(route('bo.products.incos.update', [
$response = $this->getJson(route('bo.products.incos.preview', [
'product' => $this->product,
'inco' => $inco,
]), $data);
'no_art' => 27996,
]));
// THEN
$refreshed = ProductInco::query()->findOrFail($inco->id);
expect($refreshed->ingredients)->toBe('Ingrédients modifiés')
->and($refreshed->servings)->toBe('6 personnes')
->and($refreshed->nutriscore)->toBe(Nutriscore::B)
->and($refreshed->nutrition->refWeightG)->toBe(150.0)
->and($refreshed->nutrition->kj)->toBe(520.0);
$response->assertOk();
$response->assertJsonPath('no_art', 27996);
$response->assertJsonPath('name', 'POULET FERMIER');
$response->assertJsonPath('brand', 'Loué');
$response->assertJsonPath('nutriscore', 'A');
});
it('returns 404 when previewing non-existent inco sheet on arcadia', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$arcadiaService = \Mockery::mock(ArcadiaIncoService::class);
$arcadiaService->shouldReceive('getPreview')
->once()
->with(99999)
->andReturnNull();
$this->app->instance(ArcadiaIncoService::class, $arcadiaService);
// WHEN
$response = $this->getJson(route('bo.products.incos.preview', [
'product' => $this->product,
'no_art' => 99999,
]));
// THEN
$response->assertNotFound();
});
it('returns 502 when preview fails due to Arcadia API error', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$arcadiaService = \Mockery::mock(ArcadiaIncoService::class);
$arcadiaService->shouldReceive('getPreview')
->once()
->with(50000)
->andThrow(new \RuntimeException('Connection failed'));
$this->app->instance(ArcadiaIncoService::class, $arcadiaService);
// WHEN
$response = $this->getJson(route('bo.products.incos.preview', [
'product' => $this->product,
'no_art' => 50000,
]));
// THEN
$response->assertStatus(502);
$response->assertJsonPath('message', __('Arcadia API error: :error', ['error' => 'Connection failed']));
});
it('can associate an inco sheet from arcadia', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$arcadiaService = \Mockery::mock(ArcadiaIncoService::class);
$incoData = new ArcadiaIncoDataDto(
noArt: 27996,
name: 'POULET FERMIER',
libelle: 'Poulet Fermier Label Rouge',
brand: 'Loué',
ingredients: '<p>Poulet (100%)</p>',
preparation: '<p>Au four</p>',
servings: '4/5',
allergens: 'Aucun',
sellingArgument: '<p>Excellence</p>',
nutriscore: Nutriscore::A,
nutriscoreArgs: null,
nutrition: new NutritionalValues(refWeightG: 100.0, kj: 600.0, kcal: 143.0),
);
$arcadiaService->shouldReceive('fetchInco')
->once()
->with(27996)
->andReturn($incoData);
$this->app->instance(ArcadiaIncoService::class, $arcadiaService);
// WHEN
$response = $this->post(route('bo.products.incos.associate', $this->product), [
'no_art' => 27996,
]);
// THEN
$inco = ProductInco::query()->where('product_id', $this->product->id)->first();
expect($inco)->not->toBeNull()
->and($inco->no_art)->toBe(27996)
->and($inco->nutriscore)->toBe(Nutriscore::A)
->and($inco->ingredients)->toBe('<p>Poulet (100%)</p>');
$response->assertRedirect(route('bo.products.incos.edit', [
'product' => $this->product,
@ -174,4 +218,52 @@ describe('ProductIncosController', function () {
]));
$response->assertSessionHas('success');
});
it('can synchronize an existing inco sheet from arcadia', function () {
/** @var \Tests\TestCase $this */
// GIVEN
$inco = new ProductInco();
$inco->no_art = 27996;
$inco->product()->associate($this->product);
$inco->ingredients = '<p>Ancien</p>';
$inco->save();
$arcadiaService = \Mockery::mock(ArcadiaIncoService::class);
$updatedData = new ArcadiaIncoDataDto(
noArt: 27996,
name: 'POULET FERMIER MAJ',
libelle: 'Poulet Fermier Label Rouge MAJ',
brand: 'Loué',
ingredients: '<p>Poulet (100%) MAJ</p>',
preparation: '<p>Au four MAJ</p>',
servings: '4/5',
allergens: 'Aucun',
sellingArgument: null,
nutriscore: Nutriscore::A,
nutriscoreArgs: null,
nutrition: new NutritionalValues(refWeightG: 100.0, kj: 650.0, kcal: 155.0),
);
$arcadiaService->shouldReceive('fetchInco')
->once()
->with(27996)
->andReturn($updatedData);
$this->app->instance(ArcadiaIncoService::class, $arcadiaService);
// WHEN
$response = $this->post(route('bo.products.incos.sync', $this->product));
// THEN
$refreshed = ProductInco::query()->findOrFail($inco->id);
expect($refreshed->ingredients)->toBe('<p>Poulet (100%) MAJ</p>')
->and($refreshed->preparation)->toBe('<p>Au four MAJ</p>')
->and($refreshed->nutrition->kj)->toBe(650.0);
$response->assertRedirect(route('bo.products.incos.edit', [
'product' => $this->product,
'inco' => $refreshed,
]));
$response->assertSessionHas('success');
});
});

View file

@ -1,155 +0,0 @@
<?php
declare(strict_types=1);
use App\Actions\ProductIncos\CreateProductIncoInput;
use App\Http\Requests\Bo\ProductIncos\StoreProductIncoRequest;
use App\Models\Product;
use Domain\Enums\Nutriscore;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use function Pest\Laravel\mock;
describe('StoreProductIncoRequest', function () {
it('authorizes via auth service', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$authService->shouldReceive('check')->once()->andReturn(true);
$request = new StoreProductIncoRequest($authService);
// WHEN
$request->initialize();
// THEN
expect($request->authorize())->toBeTrue();
});
it('returns rules', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreProductIncoRequest($authService);
$request->initialize();
// WHEN
$rules = $request->rules();
// THEN
expect($rules)->toHaveKeys([
'ingredients',
'preparation',
'servings',
'allergens',
'selling_argument',
'nutriscore',
'nutriscore_args',
'nv_ref_weight_g',
'nv_kj',
'nv_kcal',
'nv_fat_g',
]);
});
it('returns attributes', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreProductIncoRequest($authService);
$request->initialize();
// WHEN
$attributes = $request->attributes();
// THEN
expect($attributes)->toHaveKeys([
'ingredients',
'preparation',
'servings',
'allergens',
'selling_argument',
'nutriscore',
'nutriscore_args',
'nv_ref_weight_g',
'nv_kj',
'nv_kcal',
'nv_fat_g',
]);
});
it('converts request data to value objects', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreProductIncoRequest($authService);
$request->initialize();
$request->merge([
'no_art' => '123',
'nutriscore' => 'A',
'nv_ref_weight_g' => '100.5',
'nv_kj' => '450',
'nv_kcal' => '110.2',
]);
// WHEN
$noArt = $request->toNoArt();
$score = $request->toNutriscore();
$nutrition = $request->toNutritionalValues();
// THEN
expect($noArt)->toBe(123)
->and($score)->toBe(Nutriscore::A)
->and($nutrition->refWeightG)->toBe(100.5)
->and($nutrition->kj)->toBe(450.0)
->and($nutrition->kcal)->toBe(110.2);
});
it('handles empty VO fields gracefully', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreProductIncoRequest($authService);
$request->initialize();
// WHEN
$noArt = $request->toNoArt();
$score = $request->toNutriscore();
$nutrition = $request->toNutritionalValues();
// THEN
expect($noArt)->toBeNull()
->and($score)->toBeNull()
->and($nutrition->refWeightG)->toBeNull();
});
it('converts request data to CreateProductIncoInput', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new StoreProductIncoRequest($authService);
$request->initialize();
$request->merge([
'no_art' => '123',
'ingredients' => 'Poulet, sel',
'preparation' => 'Au four',
'servings' => '4 personnes',
'allergens' => 'Aucun',
'selling_argument' => 'Argument test',
'nutriscore' => 'A',
'nutriscore_args' => 'Argument nutriscore',
'nv_ref_weight_g' => '100',
]);
$product = new Product();
// WHEN
$input = $request->toCreateProductIncoInput($product);
// THEN
expect($input)->toBeInstanceOf(CreateProductIncoInput::class)
->and($input->product)->toBe($product)
->and($input->no_art)->toBe(123)
->and($input->ingredients)->toBe('Poulet, sel')
->and($input->preparation)->toBe('Au four')
->and($input->servings)->toBe('4 personnes')
->and($input->allergens)->toBe('Aucun')
->and($input->selling_argument)->toBe('Argument test')
->and($input->nutriscore)->toBe(Nutriscore::A)
->and($input->nutriscore_args)->toBe('Argument nutriscore')
->and($input->nutrition->refWeightG)->toBe(100.0);
});
});

View file

@ -1,86 +0,0 @@
<?php
declare(strict_types=1);
use App\Actions\ProductIncos\UpdateProductIncoInput;
use App\Http\Requests\Bo\ProductIncos\UpdateProductIncoRequest;
use App\Models\ProductInco;
use Domain\Enums\Nutriscore;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use function Pest\Laravel\mock;
describe('UpdateProductIncoRequest', function () {
it('authorizes via auth service', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$authService->shouldReceive('check')->once()->andReturn(true);
$request = new UpdateProductIncoRequest($authService);
// WHEN
$request->initialize();
// THEN
expect($request->authorize())->toBeTrue();
});
it('returns rules excluding no_art', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new UpdateProductIncoRequest($authService);
$request->initialize();
// WHEN
$rules = $request->rules();
// THEN
expect($rules)->not->toHaveKey('no_art')
->and($rules)->toHaveKeys([
'ingredients',
'preparation',
'servings',
'allergens',
'selling_argument',
'nutriscore',
'nutriscore_args',
'nv_ref_weight_g',
'nv_kj',
'nv_kcal',
'nv_fat_g',
]);
});
it('converts request data to UpdateProductIncoInput', function () {
// GIVEN
$authService = mock(AppAdminAuthService::class);
$request = new UpdateProductIncoRequest($authService);
$request->initialize();
$request->merge([
'ingredients' => 'Poulet, sel',
'preparation' => 'Au four',
'servings' => '4 personnes',
'allergens' => 'Aucun',
'selling_argument' => 'Argument test',
'nutriscore' => 'B',
'nutriscore_args' => 'Argument nutriscore',
'nv_ref_weight_g' => '120',
]);
$inco = new ProductInco();
// WHEN
$input = $request->toUpdateProductIncoInput($inco);
// THEN
expect($input)->toBeInstanceOf(UpdateProductIncoInput::class)
->and($input->inco)->toBe($inco)
->and($input->ingredients)->toBe('Poulet, sel')
->and($input->preparation)->toBe('Au four')
->and($input->servings)->toBe('4 personnes')
->and($input->allergens)->toBe('Aucun')
->and($input->selling_argument)->toBe('Argument test')
->and($input->nutriscore)->toBe(Nutriscore::B)
->and($input->nutriscore_args)->toBe('Argument nutriscore')
->and($input->nutrition->refWeightG)->toBe(120.0);
});
});