diff --git a/app/Enums/Contact/ContactFormType.php b/app/Enums/Contact/ContactFormType.php index 2be58a98..9f4d733c 100644 --- a/app/Enums/Contact/ContactFormType.php +++ b/app/Enums/Contact/ContactFormType.php @@ -39,204 +39,6 @@ enum ContactFormType: int self::press->name => 'enums.contactFormType.press.label', ]; - /** - * Optionnal SUBTYPES definition. - */ - private const SUBTYPES = [ - self::professional->name => [ - self::restauration, - self::export, - ], - self::collaborator->name => [], - self::breeder->name => [], - self::restauration->name => [], - self::export->name => [], - self::finance->name => [], - self::commitments->name => [], - self::product->name => [], - self::info->name => [], - self::press->name => [], - ]; - - /** - * Get sub type status. - * - * @return boolean - */ - public function isSubtype(): bool - { - foreach (self::SUBTYPES as $subtypes) { - if (in_array($this, $subtypes, true)) { - return true; - } - } - return false; - } - - /** - * Optionnal TOPLEVELS definition. - */ - private const TOPLEVELS = [ - self::professional->name => true, - self::collaborator->name => true, - self::breeder->name => true, - self::restauration->name => false, - self::export->name => false, - self::finance->name => true, - self::commitments->name => true, - self::product->name => true, - self::info->name => true, - self::press->name => true, - ]; - - /** - * Get top level status. - * - * @return boolean - */ - public function topLevel(): bool - { - return !empty(self::TOPLEVELS[$this->name]) ? - self::TOPLEVELS[$this->name] : false; - } - - /** - * Get the data-target. - * - * @return string|null - */ - public function dataTarget(): ?string - { - return match ($this) { - self::professional => 'askPro', - default => null, - }; - } - - /** - * Get the subtitle. - * - * @return string - */ - public function subtitle(): string - { - return match ($this) { - self::restauration => __('enums.contactFormType.' . $this->name . '.subtitle'), - default => __('enums.contactFormType.' . $this->name . '.label'), - }; - } - - /** - * Get the slug for each type. - * - * @param string|null $locale - * @return string|null - * @phpcs:disable Generic.Metrics.CyclomaticComplexity - */ - public function slug(?string $locale = null): ?string - { - // phpcs:enable - return match ($this) { - self::collaborator => Lang::get('enums.contactFormType.collaborator.slug', [], $locale), - self::breeder => Lang::get('enums.contactFormType.breeder.slug', [], $locale), - self::professional => null, - self::restauration => Lang::get('enums.contactFormType.restauration.slug', [], $locale), - self::export => Lang::get('enums.contactFormType.export.slug', [], $locale), - self::finance => Lang::get('enums.contactFormType.finance.slug', [], $locale), - self::commitments => Lang::get('enums.contactFormType.commitments.slug', [], $locale), - self::product => Lang::get('enums.contactFormType.product.slug', [], $locale), - self::info => Lang::get('enums.contactFormType.info.slug', [], $locale), - self::press => null, - }; - } - - /** - * Check if current lang slug match in specific lang slug. - * - * @param string $slug - * @param string $locale - * @return self - */ - public static function fromSlug(string $slug, string $locale): ?self - { - foreach (self::cases() as $case) { - $caseSlug = $case->slug($locale); - - if ( - $caseSlug !== null && - mb_strtolower($caseSlug) === mb_strtolower($slug) - ) { - return $case; - } - } - return null; - } - - /** - * Get the route. - * - * @return string|null - */ - public function route(): ?string - { - return match ($this) { - self::collaborator, - self::breeder, - self::export, - self::finance, - self::commitments, - self::product, - self::info, - self::restauration => route('front.contact.show', ['slug' => $this->slug()]), - self::professional => null, - self::press => RouteHelper::routeNameChecker('front.dynamic-pages.espace-presse') - . '#page-press-form', - }; - } - - /** - * Get the route for the contact form type. - * - * @return array - */ - public static function getLabelisedRoutes(): array - { - return collect(self::cases())->mapWithKeys(fn($enum) => [ - $enum->name => (object) [ - "label" => $enum->label(), - "route" => $enum->route(), - ], - ])->toArray(); - } - - /** - * Get the slug for each type. - * - * @return array - */ - public function seo(): array - { - $commonRoutes = [ - self::collaborator, - self::breeder, - self::export, - self::finance, - self::commitments, - self::professional, - self::product, - self::info, - self::press, - self::restauration - ]; - return match (true) { - in_array($this, $commonRoutes, true) => [ - 'title' => __('enums.contactFormType.' . $this->name . '.seo.title'), - 'description' => __('enums.contactFormType.' . $this->name . '.seo.description'), - ], - default => [], - }; - } - /** * Get the slug for each type. * diff --git a/app/Enums/DynamicFieldTypes.php b/app/Enums/DynamicFieldTypes.php index bd6e6c40..b6880b6a 100644 --- a/app/Enums/DynamicFieldTypes.php +++ b/app/Enums/DynamicFieldTypes.php @@ -27,7 +27,8 @@ enum DynamicFieldTypes: int case staticroute = 16; // Specific inputs. - case position = 101; + case position = 101; + case contactform = 102; /** * Labels definition. @@ -53,7 +54,8 @@ enum DynamicFieldTypes: int self::staticroute->name => 'enums.dynamic-field-types.staticroute', // Specific inputs. - self::position->name => 'enums.dynamic-field-types.position', + self::position->name => 'enums.dynamic-field-types.position', + self::contactform->name => 'enums.dynamic-field-types.contactform', ]; /** @@ -79,6 +81,7 @@ enum DynamicFieldTypes: int // Specific inputs. self::position->name => 'required|numeric|between:1,5', + self::contactform->name => 'required|numeric|between:1,10' ]; /** @@ -116,6 +119,7 @@ enum DynamicFieldTypes: int self::staticroute->name => false, // Specific inputs. - self::position->name => false, + self::position->name => false, + self::contactform->name => false, ]; } diff --git a/app/Enums/StaticRoutesEnum.php b/app/Enums/StaticRoutesEnum.php index 3ec90662..b2eace89 100644 --- a/app/Enums/StaticRoutesEnum.php +++ b/app/Enums/StaticRoutesEnum.php @@ -10,17 +10,6 @@ enum StaticRoutesEnum: int use BaseEnum; // Set all cases for each static routes. - case collaborator = 1; - case breeder = 2; - case professional = 3; - case restauration = 4; - case export = 5; - case finance = 6; - case commitments = 7; - case product = 8; - case info = 9; - case press = 10; - case search = 11; /** * Get array of each route with his matching value. @@ -28,29 +17,29 @@ enum StaticRoutesEnum: int * @param callable|null $callback * @return array */ - public static function getRoutes(?callable $callback = null): array + public static function getRoutes(?callable $callback = null) { - $dataKeyValue = array_merge(ContactFormType::getLabelisedRoutes(), [ - self::search->name => (object) [ - 'label' => trans('front.search.title'), - 'route' => '/recherche?texte=LDC', - ] - ]); - return collect($dataKeyValue) - ->reject(fn($item) => is_null($item->label) || is_null($item->route)) - ->map(function ($item, $key) { - $targetEnum = collect(self::cases()) - ->first(fn($enum) => $enum->name === $key); + // $dataKeyValue = array_merge([], [ + // self::search->name => (object) [ + // 'label' => trans('front.search.title'), + // 'route' => '/recherche?texte=LDC', + // ] + // ]); + // return collect($dataKeyValue) + // ->reject(fn($item) => is_null($item->label) || is_null($item->route)) + // ->map(function ($item, $key) { + // $targetEnum = collect(self::cases()) + // ->first(fn($enum) => $enum->name === $key); - return (object) [ - 'label' => ucfirst($item->label), - 'value' => $targetEnum->value, - 'route' => $item->route, - ]; - }) - ->when(!is_null($callback), fn ($collection) => $collection->filter($callback)) - ->values() - ->toArray(); + // return (object) [ + // 'label' => ucfirst($item->label), + // 'value' => $targetEnum->value, + // 'route' => $item->route, + // ]; + // }) + // ->when(!is_null($callback), fn ($collection) => $collection->filter($callback)) + // ->values() + // ->toArray(); } /** diff --git a/app/Helpers/RouteHelper.php b/app/Helpers/RouteHelper.php index a984b899..9f5377b0 100644 --- a/app/Helpers/RouteHelper.php +++ b/app/Helpers/RouteHelper.php @@ -2,7 +2,6 @@ namespace App\Helpers; -use App\Enums\Contact\ContactFormType; use App\Models\DynamicPage; use Illuminate\Routing\Route; use Uwil\LaravelCommon\Controllers\Controller; @@ -63,7 +62,6 @@ class RouteHelper extends Controller } return self::resolve( self::getDynamicPageLocalizedUrl($route, $localeCode), - self::getContactShowLocalizedUrl($route, $localeCode), ) ?? LaravelLocalization::getLocalizedURL($localeCode, null, [], false); } @@ -83,50 +81,6 @@ class RouteHelper extends Controller return null; } - /** - * Return the localized url for contact page show. - * - * @param \Illuminate\Routing\Route $route - * @param string $localeCode - * @return string|null - */ - private static function getContactShowLocalizedUrl(Route $route, string $localeCode): ?string - { - $contactPage = $route->parameter('contactPage'); - - if ($contactPage) { - $localizedUrl = LaravelLocalization::getLocalizedURL( - $localeCode, - null, - [], - false - ); - $parsed = parse_url($localizedUrl); - if (!isset($parsed['path'])) { - return $localizedUrl; - } - - $segments = explode('/', trim($parsed['path'], '/')); - $currentSlug = end($segments); - - $enum = ContactFormType::fromSlug( - $currentSlug, - app()->getLocale() - ); - - if ($enum) { - $translatedSlug = $enum->slug($localeCode); - if ($translatedSlug) { - $segments[count($segments) - 1] = $translatedSlug; - return '/' . implode('/', $segments); - } - } - return $localizedUrl; - } //end if - - return null; - } - /** * Return the localized url for all dynamic pages. * diff --git a/app/Helpers/TranslationHelper.php b/app/Helpers/TranslationHelper.php index e0f74924..25ba12a3 100644 --- a/app/Helpers/TranslationHelper.php +++ b/app/Helpers/TranslationHelper.php @@ -64,29 +64,43 @@ class TranslationHelper } /** - * Assert value is unique in a translation field. + * Assert that a value is unique inside a JSON translation field. + * + * The uniqueness can optionally be scoped to another attribute/value pair. + * If $anotherDbAttribute and $anotherValue are provided, the uniqueness + * will be checked only within that scope. Otherwise, the value must be + * globally unique. + * + * @param \Illuminate\Database\Eloquent\Model $model The model instance being validated. + * @param string $value The translated value to check. + * @param string $dbAttribute The JSON column containing translations. + * @param string|null $anotherValue Optional value used to scope uniqueness. + * @param string|null $anotherDbAttribute Optional database column used to scope uniqueness. + * @param string|null $errorAttribute Optional attribute name used in the validation error. + * @param string|null $errorTranslation Optional translated attribute label for the error message. * - * @param \Illuminate\Database\Eloquent\Model $model - * @param string $value - * @param string $dbAttribute - * @param string|null $errorAttribute - * @param string|null $errorTranslation * @return void - * @throws \Illuminate\Validation\ValidationException Value is already used. + * + * @throws \Illuminate\Validation\ValidationException If the value is already used. */ public static function assertTranslationFieldIsUnique( Model $model, string $value, string $dbAttribute, + ?string $anotherValue = null, + ?string $anotherDbAttribute = null, ?string $errorAttribute = null, ?string $errorTranslation = null, ): void { $modelClass = get_class($model); - $exists = $modelClass::query() + $query = $modelClass::query() ->whereKeyNot($model->getKey()) - ->whereRaw("JSON_SEARCH($dbAttribute, 'one', ?) IS NOT NULL", [$value]) - ->exists(); - if ($exists) { + ->whereRaw("JSON_SEARCH(`{$dbAttribute}`, 'one', ?) IS NOT NULL", [$value]); + + if ($anotherDbAttribute !== null && $anotherValue !== null) { + $query->where($anotherDbAttribute, $anotherValue); + } + if ($query->exists()) { throw ValidationException::withMessages([ $errorAttribute ?? $dbAttribute => trans("validation.unique", [ 'attribute' => $errorTranslation ?? trans("validation.attributes.$dbAttribute"), diff --git a/app/Http/Controllers/Back/DynamicPageController.php b/app/Http/Controllers/Back/DynamicPageController.php index 093776f8..542c592e 100644 --- a/app/Http/Controllers/Back/DynamicPageController.php +++ b/app/Http/Controllers/Back/DynamicPageController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers\Back; +use App\Enums\Contact\ContactFormType; use App\Enums\DynamicPages\PageStatusEnum; use App\Enums\ElementPositionEnum; use App\Http\Requests\Back\DynamicPages\StoreDynamicPageRequest; @@ -92,6 +93,7 @@ class DynamicPageController extends Controller 'pageConfigModels' => $pageConfigModels, 'enumDynamicPageStatus' => PageStatusEnum::toArray(), 'enumElementPosition' => ElementPositionEnum::toArray(), + 'enumContactFormType' => ContactFormType::toArray(), 'modelName' => $this->modelName, ]); } @@ -150,6 +152,7 @@ class DynamicPageController extends Controller 'pageConfigModels' => $pageConfigModels, 'enumDynamicPageStatus' => PageStatusEnum::toArray(), 'enumElementPosition' => ElementPositionEnum::toArray(), + 'enumContactFormType' => ContactFormType::toArray(), 'modelName' => $this->modelName, ]); } diff --git a/app/Http/Controllers/Front/ContactController.php b/app/Http/Controllers/Front/ContactController.php index 427bd3b2..bd18dc9b 100644 --- a/app/Http/Controllers/Front/ContactController.php +++ b/app/Http/Controllers/Front/ContactController.php @@ -18,33 +18,6 @@ use LDC\LDCCRM\Models\SingleOptin; class ContactController { - /** - * Show contact index page. - * - * @return \Illuminate\Contracts\View\View - */ - public function index(): \Illuminate\Contracts\View\View - { - $types = ContactFormType::toArray(); - return view('front.pages.contact.index', compact('types')); - } - - /** - * Show contact show page. - * - * @param string $slug - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Contracts\View\View - */ - public function show(string $slug): \Illuminate\Http\RedirectResponse|\Illuminate\Contracts\View\View - { - $enumType = collect(ContactFormType::all())->first(function ($enum) use ($slug) { - return $enum->slug() === $slug; - }); - if (!$enumType) { - return redirect()->route('front.contact.index'); - } - return view('front.pages.contact.show', compact('enumType')); - } /** * Contact send. diff --git a/app/Http/Requests/Back/UpdateDynamicFieldRequest.php b/app/Http/Requests/Back/UpdateDynamicFieldRequest.php index c1b2b4cb..6b787f1c 100644 --- a/app/Http/Requests/Back/UpdateDynamicFieldRequest.php +++ b/app/Http/Requests/Back/UpdateDynamicFieldRequest.php @@ -2,6 +2,7 @@ namespace App\Http\Requests\Back; +use App\Enums\Contact\ContactFormType; use App\Enums\ElementPositionEnum; use App\Enums\DynamicFieldTypes; use App\Enums\StaticRoutesEnum; @@ -201,6 +202,14 @@ abstract class UpdateDynamicFieldRequest extends FormRequest ), ]); break; + case DynamicFieldTypes::contactform->value: + $rules = array_merge($rules, [ + $ruleKey => array_merge( + $this->compileValidate(DynamicFieldTypes::position->getValidation(), $input), + [new Enum(ContactFormType::class)], + ), + ]); + break; default: throw new \UnexpectedValueException("Unrecognized dynamic type: " . ($input['type'] ?? 'null')); } //end switch diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index 0cc38702..352307dc 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -13,6 +13,7 @@ use App\Traits\Models\HasUwilImages; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Laravel\Scout\Searchable; @@ -104,7 +105,14 @@ class DynamicPage extends Model implements TranslatableModel static::creating(function (self $model) { self::manageFields($model); // Set id_key from title. - $model->id_key = Str::slug($model->title); + $idKey = self::generateUniqueField( + 'dynamic_pages', + 'id_key', + Str::slug($model->title), + $model->id + ); + + $model->id_key = $idKey; }); static::updating(function (self $model) { self::manageFields($model); @@ -131,6 +139,42 @@ class DynamicPage extends Model implements TranslatableModel } // * METHODS + /** + * Generate unique value from model field + * + * @param string $table + * @param string $field + * @param string $baseValue + * @param mixed $ignoreId + * @return string + */ + public static function generateUniqueField( + string $table, + string $field, + string $baseValue, + int|string|null $ignoreId = null + ): string { + $value = $baseValue; + $counter = 1; + + // Boucle tant que le slug existe en base + while (true) { + $query = DB::table($table)->where($field, $value); + + if ($ignoreId) { + $query->where('id', '!=', $ignoreId); + } + + if (!$query->exists()) { + // On a trouvé un slug unique + return $value; + } + + // Sinon on incrémente le suffixe + $value = $baseValue . '_' . $counter; + $counter++; + } + } /** * Unpublished all children pages if change status published from draft/unpublished. @@ -198,8 +242,8 @@ class DynamicPage extends Model implements TranslatableModel self::assertRootIsUnique($model); } else { $slug = $model->slug ?? Str::slug($model->title); - TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title'); - TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug'); + TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title', $model->page_id, 'page_id'); + TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', $model->page_id, 'page_id'); $model->setAttribute('slug', $slug); } // Check translations. @@ -413,7 +457,7 @@ class DynamicPage extends Model implements TranslatableModel ? strip_tags(collect($this->getTranslation('content', $locale)) ->flatten() ->filter(fn($value, $key) => - is_string($value) && + is_string($value) && !empty($value) && !is_numeric($value) && !in_array($key, ['order', 'id']) && diff --git a/lang/en/enums.php b/lang/en/enums.php index f700f0fd..e7c74f95 100644 --- a/lang/en/enums.php +++ b/lang/en/enums.php @@ -31,47 +31,7 @@ return [ 'model' => 'Model', 'staticroute' => "Static route", 'position' => 'Element position', - ], - 'contactFormType' => [ - 'collaborator' => [ - 'label' => 'join us as an employee', - 'slug' => 'join-us-as-an-employee' - ], - 'breeder' => [ - 'label' => 'join us as a farmer', - 'slug' => 'join-us-as-a-farmer' - ], - 'professional' => [ - 'label' => 'a request as a professional' - ], - 'restauration' => [ - 'label' => 'foodservice, Industry, Retailer France & Overseas', - 'slug' => 'foodservice-industry-retailer-distributor', - 'subtitle' => 'a request as a customer / retailer / distributor' - ], - 'export' => [ - 'label' => 'other countries / Export', - 'slug' => 'export' - ], - 'finance' => [ - 'label' => 'finance', - 'slug' => 'finance-2' #FIXME: revoir le slug - ], - 'commitments' => [ - 'label' => 'our commitments', - 'slug' => 'our-commitments-2' #FIXME: revoir le slug - ], - 'product' => [ - 'label' => 'product information', - 'slug' => 'product-information' - ], - 'info' => [ - 'label' => 'other general information', - 'slug' => 'other-general-information' - ], - 'press' => [ - 'label' => 'a press request' - ], + 'contactform' => 'Contact form type', ], 'breedType' => [ 'chicken' => 'Chickens / turkeys / guinea fowl', diff --git a/lang/en/routes.php b/lang/en/routes.php index 9e74e7f4..1599b31a 100644 --- a/lang/en/routes.php +++ b/lang/en/routes.php @@ -1,8 +1,6 @@ 'contact-us/{slug}', - 'contact_index' => 'contact-us', 'news' => 'news/{news}', 'search' => 'search', ]; diff --git a/lang/fr/enums.php b/lang/fr/enums.php index c41cdf40..0c033eba 100644 --- a/lang/fr/enums.php +++ b/lang/fr/enums.php @@ -31,47 +31,7 @@ return [ 'model' => 'Modèle', 'staticroute' => "Route statique", 'position' => 'Positionnement de l\'élement', - ], - 'contactFormType' => [ - 'collaborator' => [ - 'label' => 'nous rejoindre en tant que collaborateur', - 'slug' => 'nous-rejoindre-en-tant-que-collaborateur' - ], - 'breeder' => [ - 'label' => 'nous rejoindre en tant qu’éleveur', - 'slug' => 'nous-rejoindre-en-tant-queleveur' - ], - 'professional' => [ - 'label' => 'une demande en tant que professionnel' - ], - 'restauration' => [ - 'label' => 'restaurations, Distributeurs et Détaillants France', - 'subtitle' => 'une demande en tant que client / détaillant / distributeur', - 'slug' => 'une-demande-en-tant-que-client-detaillant-distributeur' - ], - 'export' => [ - 'label' => 'l’export', - 'slug' => 'lexport' - ], - 'finance' => [ - 'label' => 'la finance', - 'slug' => 'la-finance' - ], - 'commitments' => [ - 'label' => 'nos engagements', - 'slug' => 'nos-engagements' - ], - 'product' => [ - 'label' => 'une information produit', - 'slug' => 'une-information-produit' - ], - 'info' => [ - 'label' => 'une autre information générale', - 'slug' => 'une-autre-information-generale' - ], - 'press' => [ - 'label' => 'une demande presse' - ], + 'contactform' => 'Type de formulaire de contact', ], 'breedType' => [ 'chicken' => 'Poulets/dindes/pintades', diff --git a/lang/fr/routes.php b/lang/fr/routes.php index 426c61a6..3b392e7b 100644 --- a/lang/fr/routes.php +++ b/lang/fr/routes.php @@ -1,8 +1,6 @@ 'nous-contacter/{slug}', - 'contact_index' => 'nous-contacter', 'news' => 'actualites/{news}', 'search' => 'recherche', ]; diff --git a/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx b/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx index 00fa52a3..3d934d1d 100644 --- a/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx +++ b/resources/ts/back/Components/DynamicPages/DynamicInputs.tsx @@ -59,7 +59,7 @@ export default function DynamicInputs({ .enumDynamicFieldTypes as DynamicFieldTypes; const enumElementPosition = usePage().props .enumElementPosition as LaravelEnum; - + const enumContactFormType = usePage().props.enumContactFormType as LaravelEnum // Translations. const transAssociateTo = useTrans("back.form_associate_to"); const transUnsupportedType = useTrans("back.unsupported_type"); @@ -360,7 +360,7 @@ export default function DynamicInputs({ ); + case enumDynamicFieldTypes.contactform.value: + return ( + + ) default: return (

{selectedEnum - ? getEnumLabel(selectedEnum) + ? str(getEnumLabel(selectedEnum)).ucFirst().value() : placeholder} @@ -221,7 +221,7 @@ export default function EnumSelect({ handleSelect(option.value) } > - {option.label} + {str(option.label).ucFirst().value()} {selectedEnum === option.value && ( )} diff --git a/resources/views/components/front/back-to-contact.blade.php b/resources/views/components/front/back-to-contact.blade.php index 4c42dbc9..56e5057e 100644 --- a/resources/views/components/front/back-to-contact.blade.php +++ b/resources/views/components/front/back-to-contact.blade.php @@ -1,4 +1,10 @@ -

+@if (isset($pageNousContacter)) + @php + $pageContactRouteName = 'front.dynamic-pages.nous-contacter'; + @endphp + +@endif diff --git a/resources/views/front/layouts/top-nav-menu.blade.php b/resources/views/front/layouts/top-nav-menu.blade.php index 31772675..02ffe8b0 100644 --- a/resources/views/front/layouts/top-nav-menu.blade.php +++ b/resources/views/front/layouts/top-nav-menu.blade.php @@ -1,18 +1,45 @@