From 49cdb160a79a5df77c5111ad4090b999be09ec48 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Thu, 15 Jan 2026 16:55:01 +0100 Subject: [PATCH 01/19] fix: :bug: update dynamic pages routes --- app/Models/DynamicPage.php | 11 +- database/factories/DynamicPageFactory.php | 20 +-- database/factories/NewsFactory.php | 1 - database/factories/PageConfigFactory.php | 1 - database/seeders/DatabaseSeeder.php | 5 + database/seeders/DynamicPageSeeder.php | 71 +++++++--- database/seeders/NewsSeeder.php | 16 ++- lang/fr/front.php | 2 +- lang/fr/validation.php | 2 +- resources/ts/back/Pages/DynamicPages/Form.tsx | 131 ++++++++++-------- resources/ts/back/Pages/Errors/Default.tsx | 2 +- resources/views/back/layouts/head.blade.php | 2 +- .../breadcrumbs/breadcrumb-layout.blade.php | 2 +- .../pages/dynamic-pages/default.blade.php | 4 +- resources/views/front/pages/error.blade.php | 4 +- resources/views/front/pages/home.blade.php | 100 ++++++------- routes/breadcrumbs-front.php | 8 +- 17 files changed, 220 insertions(+), 162 deletions(-) diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index d8aa046b..ce6524e1 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -109,10 +109,8 @@ class DynamicPage extends Model implements TranslatableModel { static::creating(function (self $model) { self::manageFields($model); - // Set id_key from slug or title when the dynamic page is root. - $model->id_key = isset($model->slug) && !empty($model->slug) - ? $model->slug - : Str::slug($model->title); + // Set id_key from title. + $model->id_key = Str::slug($model->title); }); static::updating(function (self $model) { self::manageFields($model); @@ -254,9 +252,10 @@ class DynamicPage extends Model implements TranslatableModel */ public static function assertRootIsUnique(self $model): void { - $oldDynamicPageRoot = self::getModelsCached()->where('isRoot', true)->first(); + $oldDynamicPageRoot = self::getModelsCached()->where('id', '!=', $model->getKey())->where('isRoot', true)->first(); if ($oldDynamicPageRoot) { - $oldDynamicPageRoot->isRoot = false; + $oldDynamicPageRoot->publish = PageStatusEnum::unpublished; + $oldDynamicPageRoot->isRoot = false; $oldDynamicPageRoot->saveQuietly(); } } diff --git a/database/factories/DynamicPageFactory.php b/database/factories/DynamicPageFactory.php index b00337bc..8d63ca21 100644 --- a/database/factories/DynamicPageFactory.php +++ b/database/factories/DynamicPageFactory.php @@ -2,6 +2,7 @@ namespace Database\Factories; +use Carbon\Carbon; use App\Enums\DynamicFieldTypes; use App\Enums\DynamicPages\PageStatusEnum; use App\Models\DynamicPage; @@ -19,18 +20,21 @@ class DynamicPageFactory extends Factory public function definition(): array { $title = fake()->unique()->word(); + $slug = Str::slug($title); $configModel = fake()->randomElement(PageConfig::all()); $status = fake()->randomElement(PageStatusEnum::cases()); + $pageHome = DynamicPage::query()->where('isRoot', true)->firstOrFail(); return [ - 'id_key' => Str::slug($title), - 'title' => $title, - 'slug' => Str::slug($title), - 'content' => self::getDataFromConfig($configModel), - 'page_id' => null, - 'config_id' => $configModel->getKey(), - 'status' => $status, - 'isLocked' => fake()->boolean(50), + 'id_key' => $slug, + 'title' => $title, + 'slug' => $slug, + 'content' => self::getDataFromConfig($configModel), + 'page_id' => $pageHome->getKey(), + 'config_id' => $configModel->getKey(), + 'status' => $status, + 'isLocked' => fake()->boolean(25), + 'deleted_at' => fake()->boolean(25) ? Carbon::now() : null, ]; } diff --git a/database/factories/NewsFactory.php b/database/factories/NewsFactory.php index a2891efb..96b0ea35 100644 --- a/database/factories/NewsFactory.php +++ b/database/factories/NewsFactory.php @@ -28,7 +28,6 @@ class NewsFactory extends Factory 'status' => collect(NewsStatusEnum::cases())->random(), 'picture_alt' => fake()->sentence(6, true), 'picture_title' => fake()->sentence(6, true), - 'picture' => 'temp.jpg', ]; } } diff --git a/database/factories/PageConfigFactory.php b/database/factories/PageConfigFactory.php index 85397b4f..92e2fc91 100644 --- a/database/factories/PageConfigFactory.php +++ b/database/factories/PageConfigFactory.php @@ -43,7 +43,6 @@ class PageConfigFactory extends Factory ], ]; } - return $data; } } diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 8746d6e5..49a4ba61 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -13,9 +13,14 @@ class DatabaseSeeder extends Seeder */ public function run(): void { + // Set locale to the fallback. + app()->setLocale(config('app.fallback_locale')); + + // Call seeders. $this->call([ PageConfigSeeder::class, DynamicPageSeeder::class, + NewsCategorySeeder::class, NewsSeeder::class, CompanySeeder::class, ]); diff --git a/database/seeders/DynamicPageSeeder.php b/database/seeders/DynamicPageSeeder.php index b1c49e25..adcb3c9a 100644 --- a/database/seeders/DynamicPageSeeder.php +++ b/database/seeders/DynamicPageSeeder.php @@ -2,6 +2,7 @@ namespace Database\Seeders; +use App\Enums\DynamicPages\PageStatusEnum; use App\Enums\DynamicFieldTypes; use App\Models\DynamicPage; use Illuminate\Database\Seeder; @@ -17,23 +18,59 @@ class DynamicPageSeeder extends Seeder */ public function run(): void { - DynamicPage::factory(10)->make() - ->each(function ($model) { - $content = $model->content; - // Config factories add just one depth of children. - foreach ($model->content as $key => $value) { - $prefix = sprintf("%s_", DynamicFieldTypes::image->name); - if (Str::startsWith($key, $prefix)) { - $content[$key] = FileHelper::storeFile( - $model, - new \SplFileInfo(\resource_path( - '../database/factories/assets/dynamic-pages/100x100.jpg' - )) - ); - } + // Mandatory dynamic pages. + $titleHome = "Accueil"; + $dynamicPageModel = new DynamicPage; + $dynamicPageModel->id_key = Str::slug($titleHome); + $dynamicPageModel->slug = ""; + $dynamicPageModel->title = $titleHome; + $dynamicPageModel->content = []; + $dynamicPageModel->status = PageStatusEnum::published; + $dynamicPageModel->isLocked = true; + $dynamicPageModel->isRoot = true; + $dynamicPageModel->saveOrFail(); + + $titlePrivacyPolicy = "Politique de confidentialité"; + $slugPrivacyPolicy = Str::slug($titlePrivacyPolicy); + $dynamicPageModel = new DynamicPage; + $dynamicPageModel->id_key = $slugPrivacyPolicy; + $dynamicPageModel->slug = $slugPrivacyPolicy; + $dynamicPageModel->title = $titlePrivacyPolicy; + $dynamicPageModel->content = []; + $dynamicPageModel->status = PageStatusEnum::published; + $dynamicPageModel->isLocked = true; + $dynamicPageModel->isRoot = false; + $dynamicPageModel->saveOrFail(); + + $titleLegalNotice = "Mentions légales"; + $slugLegalNotice = Str::slug($titleLegalNotice); + $dynamicPageModel = new DynamicPage; + $dynamicPageModel->id_key = $slugLegalNotice; + $dynamicPageModel->slug = $slugLegalNotice; + $dynamicPageModel->title = $titleLegalNotice; + $dynamicPageModel->content = []; + $dynamicPageModel->status = PageStatusEnum::published; + $dynamicPageModel->isLocked = true; + $dynamicPageModel->isRoot = false; + $dynamicPageModel->saveOrFail(); + + // Fake dynamic pages. + DynamicPage::factory(20)->make()->each(function ($model) { + $content = $model->content; + // Config factories add just one depth of children. + foreach ($model->content as $key => $value) { + $prefix = sprintf("%s_", DynamicFieldTypes::image->name); + if (Str::startsWith($key, $prefix)) { + $content[$key] = FileHelper::storeFile( + $model, + new \SplFileInfo(\resource_path( + '../database/factories/assets/dynamic-pages/100x100.jpg' + )) + ); } - $model->content = $content; - $model->saveOrFail(); - }); + } + $model->content = $content; + $model->saveOrFail(); + }); } } diff --git a/database/seeders/NewsSeeder.php b/database/seeders/NewsSeeder.php index 33290ae4..ff4dd47f 100644 --- a/database/seeders/NewsSeeder.php +++ b/database/seeders/NewsSeeder.php @@ -16,15 +16,19 @@ class NewsSeeder extends Seeder */ public function run(): void { - $categoriesIds = NewsCategory::pluck('id'); - News::factory(10)->create()->each(function (News $news) use ($categoriesIds) { + News::factory(10)->make()->each(function (News $news) { $news->picture = FileHelper::storeFile( $news, - new \SplFileInfo( - resource_path('../database/factories/assets/news/525x295.jpg') - ) + new \SplFileInfo(resource_path( + '../database/factories/assets/news/525x295.jpg' + )) ); - $news->save(); + $news->saveOrFail(); + }); + + // News relation. + $categoriesIds = NewsCategory::pluck('id'); + News::query()->get()->map(function (News $news) use ($categoriesIds) { $news->categories()->attach( $categoriesIds->random(rand(1, 3))->all() ); diff --git a/lang/fr/front.php b/lang/fr/front.php index b72d97d1..d20c87c8 100644 --- a/lang/fr/front.php +++ b/lang/fr/front.php @@ -51,7 +51,7 @@ return [ 'are_you_breeder_and_join_us' => 'Vous êtes éleveur de volailles ou souhaitez le devenir, et nous rejoindre ? ', 'describe_your_project' => 'Décrivez-nous votre projet le plus précisément possible afin que nous puissions orienter votre demande vers l’interlocuteur adéquat.', 'info_personal_data' => 'Les informations recueillies à partir de ce formulaire sont traitées par le Responsable de Traitement pour donner suite à votre demande de contact. Pour connaître vos droits, vous pouvez consulter', - 'confidentiality' => 'la Charte de confidentialité', + 'confidentiality' => 'la politique de confidentialité', 'other_product_information' => 'Vous souhaitez une information ou avez une remarque sur nos produits ? Dirigez-vous directement sur le site de la marque concernée (rubriques Contact ou Service Consommateurs). Si la marque ou le produit ne possède pas de site web, merci d’adresser votre demande par voie postale à l’adresse du site mentionnée sur l’emballage.', 'inputs' => [ 'breedtype' => [ diff --git a/lang/fr/validation.php b/lang/fr/validation.php index 49147fac..3f67c1fa 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -240,7 +240,7 @@ return [ "validation" => "validation", "reference" => "référence", "locked" => "vérouillé", - "root" => "page racine (accueil)", + "root" => "page racine", "field" => "champs", "key" => "clé", "slug" => "chemin d'accès", diff --git a/resources/ts/back/Pages/DynamicPages/Form.tsx b/resources/ts/back/Pages/DynamicPages/Form.tsx index ed8e90c0..dd19cbf3 100644 --- a/resources/ts/back/Pages/DynamicPages/Form.tsx +++ b/resources/ts/back/Pages/DynamicPages/Form.tsx @@ -62,6 +62,7 @@ export default function Form({ const enumDynamicPageStatus = usePage().props.enumDynamicPageStatus as LaravelEnum; const dynamicPageModels = usePage().props.dynamicPageModels as DynamicPageModel[]; const [selectedGroup, setSelectedGroup] = useState(null); + const isConceptor = userModel.role === enumUserRole.conceptor.value; const pageConfigModels = usePage().props.pageConfigModels as Array; // Models filtered based on the presence of the locale. @@ -211,23 +212,25 @@ export default function Form({ value={data.title} setData={setData} /> - + {(!data?.isLocked || isConceptor) && ( + + )} -
- { - setSelectedGroup(null); - setData("page_id", null); - setData("slug", ""); - // @ts-ignore - setData(name, value); - }} - /> -
- setSelectedGroup((value !== null) ? (value as DynamicPageModel).title[locale] : null)} - disabled={data.isRoot} - /> - + {isConceptor && ( +
+ { + setSelectedGroup(null); + setData("page_id", null); + setData("slug", ""); + // @ts-ignore + setData(name, value); + }} + /> +
+ )} + {!data?.isRoot && ( + <> + setSelectedGroup((value !== null) ? (value as DynamicPageModel).title[locale] : null)} + disabled={data.isRoot} + /> + + + )}
- {userModel.role === enumUserRole.conceptor.value && + {isConceptor && Number(data.config_id) !== defaultConfigId && ( @@ -390,7 +399,7 @@ export default function Form({ /> )} - {userModel.role === enumUserRole.conceptor.value && ( + {isConceptor && ( diff --git a/resources/views/back/layouts/head.blade.php b/resources/views/back/layouts/head.blade.php index e45c4a73..9c39ce38 100644 --- a/resources/views/back/layouts/head.blade.php +++ b/resources/views/back/layouts/head.blade.php @@ -35,7 +35,7 @@ - @routes(nonce: $nonce) + @routes(nonce: $nonce ?? '') @if (app()->hasDebugModeEnabled()) @viteReactRefresh @endif diff --git a/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php b/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php index d7b818b3..5571cc04 100644 --- a/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php +++ b/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php @@ -1,4 +1,4 @@ -@if ($breadcrumbs->isNotEmpty() && request()->route()->getName() !== 'front.dynamic-pages.accueil.' . app()->getLocale()) +@if ($breadcrumbs->isNotEmpty() && request()->path() !== "/") @endif - +
@endforeach diff --git a/resources/views/components/front/sections/accordion/accordion.blade.php b/resources/views/components/front/sections/accordion/accordion.blade.php index 5125d38a..fa2f30f6 100644 --- a/resources/views/components/front/sections/accordion/accordion.blade.php +++ b/resources/views/components/front/sections/accordion/accordion.blade.php @@ -1,19 +1,17 @@ @if (!empty($accordion)) - @php - $type = 'medias'; - @endphp + @php $currentType = $type ?? 'medias'; @endphp
$type !== 'medias' + 'accordeon__wrapper wrapper' => $currentType !== 'medias' ])>
$type !== 'medias' + 'accordeon__list' => $currentType !== 'medias' ])> @foreach ($accordion as $acc) - + @endforeach
diff --git a/resources/views/front/layouts/header.blade.php b/resources/views/front/layouts/header.blade.php index d356f0f6..72723c39 100644 --- a/resources/views/front/layouts/header.blade.php +++ b/resources/views/front/layouts/header.blade.php @@ -11,38 +11,35 @@
+ @php + $sections = [ + 'list_section_key_figures', + 'list_section_our_history', + 'list_section_our_project', + 'list_section_our_values', + 'list_section_our_governance', + 'list_section_our_organization', + ]; + @endphp
    - - @php - $sections = [ - 'list_section_key_figures', - 'list_section_our_history', - 'list_section_our_project', - 'list_section_our_values', - 'list_section_our_governance', - 'list_section_our_organization', - ]; - @endphp - @foreach ($sections as $key => $item) - @php $section = $pageNousConnaitre->content[$item]; @endphp - @if ($section) - @php $title = $section[0]['string_title']; @endphp -
  • - - {{ $title }} - -
  • - @endif - @endforeach + @if(array_intersect($sections, array_keys($pageNousConnaitre->content))) + + @foreach ($sections as $key => $item) + @if (array_key_exists($item, array_keys($pageNousConnaitre->content))) + @php $title = $pageNousConnaitre->content[$item][0]['string_title']; @endphp +
  • + + {{ $title }} + +
  • + @endif + @endforeach + @endif @php $nousConnaitreChildPages = $pageNousConnaitre->childPages->where('status', \App\Enums\DynamicPages\PageStatusEnum::published); @endphp @if ($nousConnaitreChildPages->count()) @@ -196,29 +197,30 @@ {{ $pageNosEngagements->title }}
+ @php + $sections = [ + 'list_section_our_commitments', + 'list_section_our_strategy', + 'list_section_our_ecosystem', + 'list_section_our_governance', + 'list_section_business_ethics', + ]; + @endphp
    - - @php - $sections = [ - 'list_section_our_commitments', - 'list_section_our_strategy', - 'list_section_our_ecosystem', - 'list_section_our_governance', - 'list_section_business_ethics', - ]; - @endphp - @foreach ($sections as $key => $item) - @php $section = $pageNosEngagements->content[$item]; @endphp - @if ($section) - @php $title = $section[0]['string_title']; @endphp -
  • - - {{ $title }} - -
  • - @endif - @endforeach + @if(array_intersect($sections, array_keys($pageNosEngagements->content))) + + @foreach ($sections as $key => $item) + @if (array_key_exists($item, array_keys($pageNosEngagements->content))) + @php $title = $pageNosEngagements->content[$item][0]['string_title']; @endphp +
  • + + {{ $title }} + +
  • + @endif + @endforeach + @endif @php $nosEngagementsChildPages = $pageNosEngagements->childPages->where('status', \App\Enums\DynamicPages\PageStatusEnum::published); @endphp @if ($nosEngagementsChildPages->count())
      - @php - $sections = [ - 'list_our_jobs', - 'list_your_career', - 'list_our_politics', - 'list_your_well_being', - 'list_our_events', - 'list_schools', - 'list_breeders', - ]; - @endphp - @foreach ($sections as $key => $item) - @php $section = $pageNousRejoindre->content[$item]; @endphp - @if ($section) - @php - $title = $section[0]['string_title']; - $subtitle = $section[0]['string_subtitle']; - @endphp -
    • - - {{ Str::ucfirst(Str::lower($title) . " " . Str::lower($subtitle)) }} - -
    • - @endif - @endforeach + @if(array_intersect($sections, array_keys($pageNousRejoindre->content))) + @foreach ($sections as $key => $item) + @if (array_key_exists($item, array_keys($pageNousRejoindre->content))) + @php + $section = $pageNousRejoindre->content[$item]; + $title = $section[0]['string_title']; + $subtitle = $section[0]['string_subtitle']; + @endphp +
    • + + {{ Str::ucfirst(Str::lower($title) . " " . Str::lower($subtitle)) }} + +
    • + @endif + @endforeach + @endif
    @endif @@ -285,30 +289,31 @@ {{ $pageFinance->title }} + @php + $sections = [ + 'list_agir_avec_territoires', + 'list_action_ldc', + 'list_shareholders_area', + 'list_investissor_presentation', + 'list_key_numbers', + 'list_publication_information', + 'list_assemble', + ]; + @endphp
      - @php - $sections = [ - 'list_agir_avec_territoires', - 'list_action_ldc', - 'list_shareholders_area', - 'list_investissor_presentation', - 'list_key_numbers', - 'list_publication_information', - 'list_assemble', - ]; - @endphp - @foreach ($sections as $key => $item) - @php $section = $pageFinance->content[$item]; @endphp - @if ($section) - @php $title = $section[0]['string_title']; @endphp -
    • - - {{ $title }} - -
    • - @endif - @endforeach + @if(array_intersect($sections, array_keys($pageFinance->content))) + @foreach ($sections as $key => $item) + @if (array_key_exists($item, array_keys($pageNousRejoindre->content))) + @php $title = $pageFinance->content[$item][0]['string_title']; @endphp +
    • + + {{ $title }} + +
    • + @endif + @endforeach + @endif @php $FinanceChildPages = $pageFinance->childPages->where('status', \App\Enums\DynamicPages\PageStatusEnum::published); @endphp @if ($FinanceChildPages->count())
      {{-- Section content blocs --}} - @foreach($dynamicPageModel->content['list_section_engagement'] as $key => $sectionEngagement) - @php - $sections[$key] = [ - 'bg' => $sectionEngagement['boolean_background_dark'], - 'title' => $sectionEngagement['string_title'], - 'subtitle' => [ - 'text' => $sectionEngagement['string_subtitle'], - ], - 'list' => [], - ]; - $getConfig = fn($array, $value) => collect($array)->filter(fn($n) => $n['key'] === $value)->first(); - - foreach($sectionEngagement['list_block_content'] as $keyContent => $content) { - $positionMedium = !is_null($content['list_media']) ? intval($content['list_media'][0]['position_medium']) : 0; - array_push($sections[$key]['list'], [ - 'title' => $content['string_title'] ?? null, - 'text' => $content['wysiwyg_content'], - 'quote' => 0, - 'swap_position' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value() - ? true - : $positionMedium === \App\Enums\ElementPositionEnum::showright->value(), - 'in_row' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value(), - 'floated' => !is_null($content['list_media']) ? intval($content['list_media'][0]['boolean_floated']) : 0, - 'align_center' => 1, - 'borders_desktop' => [ - 'left' => true, - 'right' => true, - 'top' => true, - 'bottom' => true, + @if (array_key_exists('list_section_engagement', $dynamicPageModel->content)) + @foreach($dynamicPageModel->content['list_section_engagement'] as $key => $sectionEngagement) + @php + $sections[$key] = [ + 'bg' => $sectionEngagement['boolean_background_dark'], + 'title' => $sectionEngagement['string_title'], + 'subtitle' => [ + 'text' => $sectionEngagement['string_subtitle'], ], - 'borders_mobile' => [ - 'left' => true, - 'right' => true, - 'top' => true, - 'bottom' => true, - ], - 'image' => [], - 'video' => [], - 'button_icon' => '', - 'button' => [], - ]); - if (!is_null($content['list_media']) && $content['list_media'][0]['boolean_medium']) { - foreach ($content['list_media'][0]['list_medium_type'] as $keyImg => $value) { - unset($value['order']); - $filtered = array_filter($value); - $field = array_key_first($filtered); - $aaa = $getConfig($dynamicPageModel->config->config, 'list_section_engagement'); - $bbb = $getConfig($aaa['children'], 'list_block_content'); - $ccc = $getConfig($bbb['children'], 'list_media'); - $ddd = $getConfig($ccc['children'], 'list_medium_type'); - $eee = $getConfig($ddd['children'], $field); + 'list' => [], + ]; + $getConfig = fn($array, $value) => collect($array)->filter(fn($n) => $n['key'] === $value)->first(); - if ($eee['type'] === \App\Enums\DynamicFieldTypes::youtubeid->value()) { - $sections[$key]['list'][$keyContent]['video'] = [ - 'type_video' => 'youtube', - 'video' => $filtered[$field], - ]; - } else { - array_push($sections[$key]['list'][$keyContent]['image'], [ - 'url' => $filtered[$field] ?? null, - ]); + foreach($sectionEngagement['list_block_content'] as $keyContent => $content) { + $positionMedium = isset($content['list_media']) ? intval($content['list_media'][0]['position_medium']) : 0; + array_push($sections[$key]['list'], [ + 'title' => $content['string_title'] ?? null, + 'text' => $content['wysiwyg_content'], + 'quote' => 0, + 'swap_position' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value() + ? true + : $positionMedium === \App\Enums\ElementPositionEnum::showright->value(), + 'in_row' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value(), + 'floated' => isset($content['list_media']) ? intval($content['list_media'][0]['boolean_floated']) : 0, + 'align_center' => 1, + 'borders_desktop' => [ + 'left' => true, + 'right' => true, + 'top' => true, + 'bottom' => true, + ], + 'borders_mobile' => [ + 'left' => true, + 'right' => true, + 'top' => true, + 'bottom' => true, + ], + 'image' => [], + 'video' => [], + 'button_icon' => '', + 'button' => [], + ]); + if (isset($content['list_media']) && $content['list_media'][0]['boolean_medium']) { + foreach ($content['list_media'][0]['list_medium_type'] as $keyImg => $value) { + unset($value['order']); + $filtered = array_filter($value); + $field = array_key_first($filtered); + $aaa = $getConfig($dynamicPageModel->config->config, 'list_section_engagement'); + $bbb = $getConfig($aaa['children'], 'list_block_content'); + $ccc = $getConfig($bbb['children'], 'list_media'); + $ddd = $getConfig($ccc['children'], 'list_medium_type'); + $eee = $getConfig($ddd['children'], $field); + + if ($eee['type'] === \App\Enums\DynamicFieldTypes::youtubeid->value()) { + $sections[$key]['list'][$keyContent]['video'] = [ + 'type_video' => 'youtube', + 'video' => $filtered[$field], + ]; + } else { + array_push($sections[$key]['list'][$keyContent]['image'], [ + 'url' => $filtered[$field] ?? null, + ]); + } } } - } - if (isset($content['list_button']) && $content['list_button'][0]['boolean_button']) { - if (isset($content['list_button'][0]['model_page'])) { - $url = \App\Models\DynamicPage::getAccessModel($content['list_button'][0]['model_page']); - } - if (isset($content['list_button'][0]['model_document'])) { - $url = \App\Models\Document::getAccessModel($content['list_button'][0]['model_document']); - } - $sections[$key]['list'][$keyContent]['button'] = [ - 'url' => $url ?? "#", - 'title' => $content['list_button'][0]['string_label'], - 'target' => '', - ]; - $sections[$key]['list'][$keyContent]['button_icon'] = $content['list_button'][0]['boolean_icon'] ? 'btn__icon_view' : 'btn__icon_arrow-right'; - } - } - @endphp - @endforeach - @foreach ($sections as $section) - - @endforeach - {{-- Sections numbers --}} - @php $section = $dynamicPageModel->content['list_section_numbers'][0]; @endphp -
      -
      - @php - $brands = []; - if ( - isset($pageNosMarques) - && isset($pageNosMarques->content['list_our_big_brands']) - && isset($pageNosMarques->content['list_our_big_brands'][0]['list_brands']) - ) { - foreach ($pageNosMarques->content['list_our_big_brands'][0]['list_brands'] as $key => $logo) { - array_push($brands, [ - 'image' => [ - 'url' => asset($logo['list_logo'][0]['image_brand_logo']), - ], - 'link' => \App\Helpers\RouteHelper::routeNameChecker('front.dynamic-pages.nos-marques'), - ]); + if (isset($content['list_button']) && $content['list_button'][0]['boolean_button']) { + if (isset($content['list_button'][0]['model_page'])) { + $url = \App\Models\DynamicPage::getAccessModel($content['list_button'][0]['model_page']); + } + if (isset($content['list_button'][0]['model_document'])) { + $url = \App\Models\Document::getAccessModel($content['list_button'][0]['model_document']); + } + $sections[$key]['list'][$keyContent]['button'] = [ + 'url' => $url ?? "#", + 'title' => $content['list_button'][0]['string_label'], + 'target' => '', + ]; + $sections[$key]['list'][$keyContent]['button_icon'] = $content['list_button'][0]['boolean_icon'] ? 'btn__icon_view' : 'btn__icon_arrow-right'; } } @endphp - @if(!empty($brands) && request()->route()->getName() === "front.dynamic-pages.bien-nourrir.fr") - - @else - - @endif - + @endforeach + @foreach ($sections as $section) + + @endforeach + @endif + {{-- Sections numbers --}} + @if (array_key_exists('list_section_numbers', $dynamicPageModel->content)) + @php $section = $dynamicPageModel->content['list_section_numbers'][0]; @endphp +
      +
      + @php + $brands = []; + if ( + isset($pageNosMarques) + && isset($pageNosMarques->content['list_our_big_brands']) + && isset($pageNosMarques->content['list_our_big_brands'][0]['list_brands']) + ) { + foreach ($pageNosMarques->content['list_our_big_brands'][0]['list_brands'] as $key => $logo) { + array_push($brands, [ + 'image' => [ + 'url' => asset($logo['list_logo'][0]['image_brand_logo']), + ], + 'link' => \App\Helpers\RouteHelper::routeNameChecker('front.dynamic-pages.nos-marques'), + ]); + } + } + @endphp + @if(!empty($brands) && request()->route()->getName() === "front.dynamic-pages.bien-nourrir.fr") + + @else + + @endif + +
      -
      + @endif @if($pageNosEngagements->childPages->count())
      diff --git a/resources/views/front/pages/our-commitments.blade.php b/resources/views/front/pages/our-commitments.blade.php index 1adf218b..153e9af4 100644 --- a/resources/views/front/pages/our-commitments.blade.php +++ b/resources/views/front/pages/our-commitments.blade.php @@ -1,7 +1,7 @@ @extends('front.layouts.layout') -@section('title', $dynamicPageModel->content['list_seo'][0]['string_seo_title']) -@section('description', $dynamicPageModel->content['list_seo'][0]['textarea_seo_description']) +@section('title', data_get($dynamicPageModel->content, 'list_seo.0.string_seo_title')) +@section('description', data_get($dynamicPageModel->content, 'list_seo.0.textarea_seo_description')) @section('content') @php @@ -12,15 +12,15 @@ @endphp {{-- COMMITMENTS LIST --}} - @php - $section = $getSection('list_section_our_commitments'); - $engagements = [ - 'title' => $section['string_title'], - 'subtitle' => $section['string_subtitle'], - 'text' => $section['wysiwyg_description'], - ]; - @endphp + @php $section = $getSection('list_section_our_commitments'); @endphp @if($section) + @php + $engagements = [ + 'title' => $section['string_title'], + 'subtitle' => $section['string_subtitle'], + 'text' => $section['wysiwyg_description'], + ]; + @endphp + @if ($section) + + @endif {{-- COMMITMENT N°2 --}} @php $section = $getSection('list_section_our_ecosystem'); @endphp - + @if ($section) + + @endif {{-- COMMITMENT N°3 --}} - @php - $section = $getSection('list_section_our_governance'); - - // Anchor construction. - $specificSection = $pageNousConnaitre->content['list_section_our_values']; - $anchor = $specificSection ? '#' . \Illuminate\Support\Str::slug($specificSection[0]['string_title']) : ''; - $targetModel = \App\Models\PageConfig::getModelFromInputModelConfig( - $section['list_page_link'][0]['model_page'], - $section['list_page_link'][0]['reserved_model_page'], - ); - $buttonUrl = sprintf("%s%s", \App\Helpers\RouteHelper::routeNameChecker("front.dynamic-pages.{$targetModel->id_key}"), $anchor); - @endphp - + @php $section = $getSection('list_section_our_governance'); @endphp + @if($section) + @php + // Anchor construction. + $specificSection = $pageNousConnaitre->content['list_section_our_values']; + $anchor = $specificSection ? '#' . \Illuminate\Support\Str::slug($specificSection[0]['string_title']) : ''; + $targetModel = \App\Models\PageConfig::getModelFromInputModelConfig( + $section['list_page_link'][0]['model_page'], + $section['list_page_link'][0]['reserved_model_page'], + ); + $buttonUrl = sprintf("%s%s", \App\Helpers\RouteHelper::routeNameChecker("front.dynamic-pages.{$targetModel->id_key}"), $anchor); + @endphp + + @endif {{-- COMMITMENT N°4 --}} @php $section = $getSection('list_section_business_ethics'); @endphp - + @if($section) + + @endif {{-- COMMITMENT N°5 --}} @php $section = $getSection('list_section_business_ethics'); $section = $section ? $section['list_block_simple'][0] : null; @endphp - + @if($section) + + @endif {{-- COMMITMENTS LIST --}} @if($pageNosEngagements->childPages->count()) diff --git a/resources/views/front/pages/our-division.blade.php b/resources/views/front/pages/our-division.blade.php index d35aea17..d40e58a3 100644 --- a/resources/views/front/pages/our-division.blade.php +++ b/resources/views/front/pages/our-division.blade.php @@ -19,6 +19,7 @@ foreach($groupAccordion['list_accordion'] as $accordion) { array_push($accordions[$key]['accordions']['items'], [ 'image_block' => $accordion['image_visual'], + 'string_title' => $accordion['string_title'], 'string_alt' => $accordion['string_title'], 'wysiwyg_content' => $accordion['wysiwyg_content'], ]) ; From 3dd626697ec6d77c86a99042ceb7f2cd084bd399 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 20 Jan 2026 11:34:25 +0100 Subject: [PATCH 03/19] =?UTF-8?q?fix:=20=F0=9F=90=9B=20update=20meilisearc?= =?UTF-8?q?h=20to=20use=20one=20index=20for=20each=20model=20with=20multip?= =?UTF-8?q?le=20fields=20by=20locales?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Console/Commands/MeilisearchUpdate.php | 78 -------- app/Console/Commands/UpdateMeilisearch.php | 44 +++++ .../Controllers/Front/SearchController.php | 174 +++++++++++++++--- app/Http/Middleware/HandleInertiaRequests.php | 4 +- .../Front/Search/SearchAjaxRequest.php | 50 +++++ .../Front/{ => Search}/SearchRequest.php | 2 +- app/Models/Document.php | 90 +++++++-- app/Models/DynamicPage.php | 154 +++++++++++----- app/Models/News.php | 111 ++++++++--- app/Models/SearchIndex.php | 152 --------------- app/Traits/Models/HasMeilisearchIndex.php | 113 ------------ config/scout.php | 9 +- public/assets/css/style.css | 9 + .../front/search-pagination.blade.php | 28 --- .../components/front/search/card.blade.php | 31 ++++ .../components/front/search/content.blade.php | 90 +++++++++ .../front/search/pagination.blade.php | 28 +++ .../views/front/layouts/mobile-menu.blade.php | 2 +- .../front/layouts/top-nav-menu.blade.php | 6 +- resources/views/front/pages/search.blade.php | 74 ++------ routes/breadcrumbs-front.php | 24 +-- routes/web-front.php | 1 + 22 files changed, 719 insertions(+), 555 deletions(-) delete mode 100644 app/Console/Commands/MeilisearchUpdate.php create mode 100644 app/Console/Commands/UpdateMeilisearch.php create mode 100644 app/Http/Requests/Front/Search/SearchAjaxRequest.php rename app/Http/Requests/Front/{ => Search}/SearchRequest.php (94%) delete mode 100644 app/Models/SearchIndex.php delete mode 100644 app/Traits/Models/HasMeilisearchIndex.php delete mode 100644 resources/views/components/front/search-pagination.blade.php create mode 100644 resources/views/components/front/search/card.blade.php create mode 100644 resources/views/components/front/search/content.blade.php create mode 100644 resources/views/components/front/search/pagination.blade.php diff --git a/app/Console/Commands/MeilisearchUpdate.php b/app/Console/Commands/MeilisearchUpdate.php deleted file mode 100644 index f98a8946..00000000 --- a/app/Console/Commands/MeilisearchUpdate.php +++ /dev/null @@ -1,78 +0,0 @@ -map(function (string $locale) use ($client) { - $localeName = Str::upper($locale); - $indexName = config('scout.prefix') . $locale; - $index = $client->index($indexName); - - $index->updateSearchableAttributes(['title', 'content']); - $index->updateFilterableAttributes(['type']); - - $this->info("Meilisearch indexes configured for locale: {$localeName}"); - - app()->setLocale($locale); - - SearchIndex::removeAllFromSearch(); - - collect([ - News::class, - DynamicPage::class, - Document::class, - ])->map(function(string $class) { - $class::chunk(100, function ($items) { - $items - ->map - ->toSearchDocument() - ->filter() - ->each - ->searchable(); - }); - }); - - $this->info("Meilisearch indexes rebuilt for locale: {$localeName}"); - }); - } -} diff --git a/app/Console/Commands/UpdateMeilisearch.php b/app/Console/Commands/UpdateMeilisearch.php new file mode 100644 index 00000000..ba7ec1c6 --- /dev/null +++ b/app/Console/Commands/UpdateMeilisearch.php @@ -0,0 +1,44 @@ +info("Import {$locale}..."); + app()->setLocale($locale); + + foreach ($models as $model) { + $this->call('scout:import', ['model' => $model]); + } + } + } +} diff --git a/app/Http/Controllers/Front/SearchController.php b/app/Http/Controllers/Front/SearchController.php index 981b03c0..8f2ad16f 100644 --- a/app/Http/Controllers/Front/SearchController.php +++ b/app/Http/Controllers/Front/SearchController.php @@ -2,43 +2,84 @@ namespace App\Http\Controllers\Front; -use App\Enums\StaticPageType; -use App\Http\Requests\Front\SearchRequest; -use App\Models\StaticPage; -use App\Models\SearchIndex; +use App\Http\Requests\Front\Search\SearchAjaxRequest; +use App\Http\Requests\Front\Search\SearchRequest; +use App\Models\Document; +use App\Models\DynamicPage; +use App\Models\News; +use App\Enums\Document\DocumentStatusEnum; +use App\Enums\News\NewsStatusEnum; +use App\Enums\DynamicPages\PageStatusEnum; use Illuminate\Http\Request; use Illuminate\Support\Str; +use Illuminate\Database\Eloquent\Builder; +use Mcamara\LaravelLocalization\LaravelLocalization; use Uwil\LaravelCommon\Controllers\Controller; use Uwil\LaravelCommon\Helpers\CollectionHelper; class SearchController extends Controller { /** - * Search page. + * Access to the search page. * - * @param \App\Http\Requests\Front\SearchRequest $request + * @param \App\Http\Requests\Front\Search\SearchRequest $request * @return \Illuminate\Contracts\View\View */ - public function search(SearchRequest $request): \Illuminate\Contracts\View\View + public function search(SearchRequest $request) { - $queryKey = trans('front.search.query'); - $pageKey = trans('front.search.page'); + $queryKey = trans('front.search.query'); $searchTerm = $request->validated()[$queryKey]; - $currentPage = $request->validated()[$pageKey]; - $perPage = 10; - - $searchQuery = $this->buildExactSearchQuery($searchTerm); - $resultModels = SearchIndex::search($searchQuery) - ->paginateRaw(perPage: $perPage, page: $currentPage); + return view('front.pages.search', compact('searchTerm')); + } + + /** + * Load results from search. + * + * @param \App\Http\Requests\Front\Search\SearchAjaxRequest $request + * @return \Illuminate\Http\JsonResponse + */ + public function ajaxSearchLoadResults(SearchAjaxRequest $request): \Illuminate\Http\JsonResponse + { + $class = $request->validated()['class']; + $searchTerm = $request->validated()['search']; + $currentPage = (int) $request->validated()['page']; + $currentLocale = $request->validated()['locale']; + $perPage = 5; - $resultModels->appends([ - $queryKey => $searchTerm, - $pageKey => $currentPage, - 'query' => null, + app()->setLocale($currentLocale); + $searchQuery = $this->buildExactSearchQuery($searchTerm); + + $models = $class::search($searchQuery, function ($engine, $query, $options) use ($class, $currentLocale) { + $options['attributesToSearchOn'] = $class::searchTransFields($currentLocale); + return $engine->search($query, $options); + }) + ->where('status', $class::searchStatusEnum()) + ->paginateRaw(perPage: $perPage, page: $currentPage); + + // Render items. + $itemsHtml = collect($models['hits'])->map(fn ($result) => + view('components.front.search.card', [ + 'class' => $class, + 'result' => $result, + 'mainField' => $class::searchMainField(), + 'routeName' => $class::searchRouteName($result['id_key'] ?? null), + 'customBreadcrumbs' => true, + 'searchTerm' => $searchTerm, + 'currentLocale' => $currentLocale, + ])->render() + )->implode(''); + + // Pagination. + $paginationHtml = view('components.front.search.pagination', [ + 'models' => $models, + ])->render(); + + return response()->json([ + 'items' => $itemsHtml, + 'pagination' => $paginationHtml, + 'totalHits' => $models['totalHits'], ]); - - return view('front.pages.search', compact('searchTerm', 'resultModels')); } /** @@ -60,4 +101,95 @@ class SearchController extends Controller return '+' . implode(' +', $exactTerms); } + + /** + * Highlights all search terms in a text. + * + * @param string $text + * @param string $searchTerm + * @return string + */ + public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string + { + if (trim($searchTerm) === '') { + return $text; + } + + // Clean terms list. + $words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY); + if (empty($words)) { + return $text; + } + + $fullText = strip_tags($text); + $textLength = strlen($fullText); + $ranges = []; + + // Collection of relevant ranges around each word. + foreach ($words as $word) { + $pattern = '/(? max(0, $matchPos - $contextLength), + 'end' => min($textLength, $matchPos + $matchLen + $contextLength), + ]; + } + } + } + + // Return the entire text if there isn't matches. + if (empty($ranges)) { + return $text; + } + + // Merging overlapping intervals. + usort($ranges, fn($a, $b) => $a['start'] <=> $b['start']); + $merged = []; + foreach ($ranges as $r) { + if (empty($merged) || $r['start'] > $merged[array_key_last($merged)]['end']) { + $merged[] = $r; + } else { + $merged[array_key_last($merged)]['end'] = max( + $merged[array_key_last($merged)]['end'], + $r['end'] + ); + } + } + + $snippets = []; + + foreach ($merged as $r) { + $snippet = substr($fullText, $r['start'], $r['end'] - $r['start']); + + // Cut cleanly without breaking the words + if ($r['start'] > 0) { + $snippet = preg_replace('/^\S*\s/', '…', $snippet, 1); + } + if ($r['end'] < $textLength) { + $snippet = preg_replace('/\s\S*$/', '…', $snippet, 1); + } + + // Highlighting searched words + foreach ($words as $word) { + $pattern = '/(?$0', + $snippet + ); + } + + $snippets[] = trim($snippet); + if (count($snippets) >= 3) break; + } + + $result = implode('… ', $snippets); + $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); + + return trim($result); + } } diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index c7d4454e..d1c7dbac 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -54,8 +54,6 @@ class HandleInertiaRequests extends Middleware ]), ]); - $locales = LaravelLocalization::getSupportedLocales(); - $props = [ ...parent::share($request), 'appEnv' => [ @@ -63,7 +61,7 @@ class HandleInertiaRequests extends Middleware 'name' => config('app.name'), 'url' => config('app.url'), 'locale' => app()->getLocale(), - 'locales' => array_keys($locales), + 'locales' => LaravelLocalization::getSupportedLanguagesKeys(), 'fallbackLocale' => app()->getFallbackLocale(), ], 'auth' => [ diff --git a/app/Http/Requests/Front/Search/SearchAjaxRequest.php b/app/Http/Requests/Front/Search/SearchAjaxRequest.php new file mode 100644 index 00000000..ac1e5029 --- /dev/null +++ b/app/Http/Requests/Front/Search/SearchAjaxRequest.php @@ -0,0 +1,50 @@ +ajax(); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + $supportedLocales = implode(',', LaravelLocalization::getSupportedLanguagesKeys()); + return [ + 'search' => 'required|string|between:3,255', + 'page' => 'required|integer|min:1', + 'locale' => "required|string|in:$supportedLocales", + 'class' => [ + 'required', + 'string', + 'starts_with:App\\Models\\', + // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed + function ($attribute, $value, $fail) { + if (!class_exists($value)) { + $fail("The specified model does not exist."); + return; + } + if (!is_subclass_of($value, Model::class)) { + $fail("The specified model is not an Eloquent model."); + } + }, + ], + ]; + } +} diff --git a/app/Http/Requests/Front/SearchRequest.php b/app/Http/Requests/Front/Search/SearchRequest.php similarity index 94% rename from app/Http/Requests/Front/SearchRequest.php rename to app/Http/Requests/Front/Search/SearchRequest.php index d6ee5b0b..f18e71f9 100644 --- a/app/Http/Requests/Front/SearchRequest.php +++ b/app/Http/Requests/Front/Search/SearchRequest.php @@ -1,6 +1,6 @@ path); } + // * MEILISEARCH + /** - * Set value of meilisearch indexes. + * Get model's setting to apply on scout search (meilisearch). * - * @return \App\Models\SearchIndex|null + * @var array */ - public function toSearchDocument(): ?\App\Models\SearchIndex + public static $searchSettings = [ + 'filterableAttributes' => ['status'], + 'sortableAttributes' => ['status'] + ]; + + /** + * Get fields that we want to keep in the current locale. + * + * @param string $currentLocale + * @return array + */ + public static function searchTransFields(string $currentLocale): array { - $locale = app()->getLocale(); + return [ + "name_$currentLocale", + "path_$currentLocale", + ]; + } - // Keep only published models. - if (!$this->status->equals(DocumentStatusEnum::published) || !$this->hasTranslation('path', $locale)) { - return null; + /** + * Get enum status of the model. + * + * @return integer + */ + public static function searchStatusEnum(): int + { + return DocumentStatusEnum::published->value; + } + + /** + * Get front route. + * + * @return string + */ + public static function searchRouteName(): string + { + return 'front.documents.show'; + } + + /** + * Get model identificable field. + * + * @return string + */ + public static function searchMainField(): string + { + return 'name'; + } + + /** + * Get the indexable data array for the model. + * + * @return array + */ + public function toSearchableArray(): array + { + $locales = config('laravellocalization.supportedLocales'); + + $data = [ + 'id' => $this->id, + 'status' => $this->status->value, + ]; + foreach ($locales as $locale => $_) { + $data["name_$locale"] = $this->hasTranslation('name', $locale) ? $this->getTranslation('name', $locale) : null; + $data["path_$locale"] = $this->hasTranslation('path', $locale) ? $this->getTranslation('path', $locale) : null; } - - return new SearchIndex([ - 'type' => Str::snake(class_basename($this)), - 'model_id' => $this->getKey(), - 'slug' => $this->getTranslation('path', $locale), - 'title' => $this->getTranslation('name', $locale), - 'content' => null, - ]); + + return $data; } // * RELATIONSHIPS diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index ce6524e1..0e2bd95b 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -9,9 +9,7 @@ use App\Enums\DynamicPages\PageStatusEnum; use App\Helpers\DynamicPageHelper; use App\Helpers\RouteHelper; use App\Helpers\TranslationHelper; -use App\Models\SearchIndex; use App\Traits\Models\HasCache; -use App\Traits\Models\HasMeilisearchIndex; use App\Traits\Models\HasTranslations; use App\Traits\Models\HasUwilImages; use Illuminate\Database\Eloquent\Collection; @@ -22,6 +20,7 @@ use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; +use Laravel\Scout\Searchable; use Uwil\LaravelActivityLogs\Traits\ActivityLog; use Uwil\LaravelCommon\Helpers\FileHelper; @@ -47,7 +46,7 @@ class DynamicPage extends Model implements TranslatableModel use HasTranslations; use HasUwilImages; use SoftDeletes; - use HasMeilisearchIndex; + use Searchable; /** * The attributes that are mass assignable. @@ -319,44 +318,6 @@ class DynamicPage extends Model implements TranslatableModel return parse_url($url, PHP_URL_PATH) ?? "/"; } - /** - * Set value of meilisearch indexes. - * - * @return \App\Models\SearchIndex|null - */ - public function toSearchDocument(): ?\App\Models\SearchIndex - { - $locale = app()->getLocale(); - - // Keep only published models. - if (!$this->status->equals(PageStatusEnum::published) || !$this->hasTranslation('slug', $locale)) { - return null; - } - - // Clean content (no tags, no paths, no numbers, only string). - $content = strip_tags(collect($this->getTranslation('content', $locale)) - ->flatten() - ->filter(fn($value, $key) => - is_string($value) && - !empty($value) && - !is_numeric($value) && - !in_array($key, ['order', 'id']) && - !str_starts_with($key, 'image_') && - !preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value) - ) - ->values() - ->implode(' ')); - - return new SearchIndex([ - 'type' => Str::snake(class_basename($this)), - 'model_id' => $this->getKey(), - 'id_key' => $this->id_key, - 'slug' => $this->getTranslation('slug', $locale), - 'title' => $this->getTranslation('title', $locale), - 'content' => $content - ]); - } - /** * Get localized path from the locale. * @@ -385,6 +346,117 @@ class DynamicPage extends Model implements TranslatableModel : $slug; } + // * MEILISEARCH + + /** + * Get model's setting to apply on scout search (meilisearch). + * + * @var array + */ + public static $searchSettings = [ + 'filterableAttributes' => ['status'], + 'sortableAttributes' => ['status'] + ]; + + /** + * Get fields that we want to keep in the current locale. + * + * @return array. + */ + public static function searchTransFields(): array + { + $currentLocale = app()->getLocale(); + return [ + "title_$currentLocale", + "slug_$currentLocale", + "content_$currentLocale", + ]; + } + + /** + * Get enum status of the model. + * + * @return integer + */ + public static function searchStatusEnum(): int + { + return PageStatusEnum::published->value; + } + + /** + * Get front route. + * + * @param string|null $idKey + * @return string + */ + public static function searchRouteName(string|null $idKey): string + { + $currentLocale = app()->getLocale(); + return "front.dynamic-pages.$idKey.$currentLocale"; + } + + /** + * Get model identificable field. + * + * @return string + */ + public static function searchMainField(): string + { + return 'title'; + } + + /** + * Get fields that we want to keep in the current locale. + * + * @param string $currentLocale + * @return array + */ + public static function searchableTransFields(string $currentLocale): array + { + return [ + "title_$currentLocale", + "slug_$currentLocale", + "content_$currentLocale", + ]; + } + + /** + * Get the indexable data array for the model. + * + * @return array + */ + public function toSearchableArray(): array + { + $locales = config('laravellocalization.supportedLocales'); + + $data = [ + 'id' => $this->id, + 'id_key' => $this->id_key, + 'status' => $this->status->value, + ]; + + foreach ($locales as $locale => $_) { + $data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null; + $data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null; + + $content = $this->hasTranslation('content', $locale) ? strip_tags(collect($this->getTranslation('content', $locale)) + ->flatten() + ->filter(fn($value, $key) => + is_string($value) && + !empty($value) && + !is_numeric($value) && + !in_array($key, ['order', 'id']) && + !str_starts_with($key, 'image_') && + !preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value) + ) + ->values() + ->implode(' ')) : null; + $data["content_$locale"] = $content; + } + + return $data; + } + // * RELATIONSHIPS /** diff --git a/app/Models/News.php b/app/Models/News.php index 3c9758a6..2f967f14 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -6,9 +6,7 @@ use App\Contracts\TranslatableModel; use App\Enums\News\NewsStatusEnum; use App\Helpers\TranslationHelper; use App\Models\NewsTag; -use App\Models\SearchIndex; use App\Traits\Models\HasCache; -use App\Traits\Models\HasMeilisearchIndex; use App\Traits\Models\HasTranslations; use App\Traits\Models\HasUwilImages; use Carbon\Carbon; @@ -19,6 +17,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Arr; use Illuminate\Support\Facades\App; use Illuminate\Support\Str; +use Laravel\Scout\Searchable; use Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable; use Uwil\LaravelActivityLogs\Traits\ActivityLog; @@ -50,7 +49,7 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable use HasUwilImages { HasUwilImages::inertiaFill as traitInertiaFill; } - use HasMeilisearchIndex; + use Searchable; /** * Get the route key for the model. @@ -295,9 +294,9 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable /** * Get data related to the first category of this news item. * - * @return NewsTag|null + * @return \App\Models\NewsTag|null */ - public function getFirstTagDataAttribute(): ?NewsTag + public function getFirstTagDataAttribute(): ?\App\Models\NewsTag { if (empty($this->tags) || empty($this->tags[0])) { return null; @@ -320,29 +319,6 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable TranslationHelper::validateFallbackTranslations($model); } - /** - * Set value of meilisearch indexes. - * - * @return \App\Models\SearchIndex|null - */ - public function toSearchDocument(): ?\App\Models\SearchIndex - { - $locale = app()->getLocale(); - - // Keep only published models. - if (!$this->status->equals(NewsStatusEnum::published) || !$this->hasTranslation('slug', $locale)) { - return null; - } - - return new SearchIndex([ - 'type' => Str::snake(class_basename($this)), - 'model_id' => $this->getKey(), - 'slug' => $this->getTranslation('slug', $locale), - 'title' => $this->getTranslation('title', $locale), - 'content' => strip_tags($this->getTranslation('content', $locale)), - ]); - } - /** * Get the url to access a specific resource. * @@ -358,6 +334,85 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable return route('front.news.show', $targetModel); } + // * MEILISEARCH + + /** + * Get model's setting to apply on scout search (meilisearch). + * + * @var array + */ + public static $searchSettings = [ + 'filterableAttributes' => ['status'], + 'sortableAttributes' => ['status'] + ]; + + /** + * Get fields that we want to keep in the current locale. + * + * @param string $currentLocale + * @return array + */ + public static function searchTransFields($currentLocale): array + { + return [ + "title_$currentLocale", + "slug_$currentLocale", + "content_$currentLocale", + ]; + } + + /** + * Get enum status of the model. + * + * @return integer + */ + public static function searchStatusEnum(): int + { + return NewsStatusEnum::published->value; + } + + /** + * Get front route. + * + * @return string + */ + public static function searchRouteName(): string + { + return 'front.news.show'; + } + + /** + * Get model identificable field. + * + * @return string + */ + public static function searchMainField(): string + { + return 'title'; + } + + /** + * Get the indexable data array for the model. + * + * @return array + */ + public function toSearchableArray(): array + { + $locales = config('laravellocalization.supportedLocales'); + + $data = [ + 'id' => $this->id, + 'status' => $this->status->value, + ]; + foreach ($locales as $locale => $_) { + $data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null; + $data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null; + $data["content_$locale"] = $this->hasTranslation('content', $locale) ? strip_tags($this->getTranslation('content', $locale)) : null; + } + + return $data; + } + // * RELATIONSHIPS /** diff --git a/app/Models/SearchIndex.php b/app/Models/SearchIndex.php deleted file mode 100644 index 2027a14e..00000000 --- a/app/Models/SearchIndex.php +++ /dev/null @@ -1,152 +0,0 @@ -getLocale(); - } - - /** - * Unique primary key. - * - * @return string - */ - public function getScoutKey(): mixed - { - return "{$this->type}_{$this->model_id}"; - } - - /** - * Indexed data. - * - * @return array - */ - public function toSearchableArray(): array - { - return [ - 'id' => $this->getScoutKey(), - 'type' => $this->type, - 'model_id' => $this->model_id, - 'id_key' => $this->id_key ?? null, - 'slug' => $this->slug, - 'title' => $this->title, - 'content' => $this->content, - ]; - } - - /** - * Highlights all search terms in a text. - * - * @param string $text - * @param string $searchTerm - * @return string - */ - public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string - { - if (trim($searchTerm) === '') { - return $text; - } - - // Clean terms list. - $words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY); - if (empty($words)) { - return $text; - } - - $fullText = strip_tags($text); - $textLength = strlen($fullText); - $ranges = []; - - // Collection of relevant ranges around each word. - foreach ($words as $word) { - $pattern = '/(? max(0, $matchPos - $contextLength), - 'end' => min($textLength, $matchPos + $matchLen + $contextLength), - ]; - } - } - } - - // Return the entire text if there isn't matches. - if (empty($ranges)) { - return $text; - } - - // Merging overlapping intervals. - usort($ranges, fn($a, $b) => $a['start'] <=> $b['start']); - $merged = []; - foreach ($ranges as $r) { - if (empty($merged) || $r['start'] > $merged[array_key_last($merged)]['end']) { - $merged[] = $r; - } else { - $merged[array_key_last($merged)]['end'] = max( - $merged[array_key_last($merged)]['end'], - $r['end'] - ); - } - } - - $snippets = []; - - foreach ($merged as $r) { - $snippet = substr($fullText, $r['start'], $r['end'] - $r['start']); - - // Cut cleanly without breaking the words - if ($r['start'] > 0) { - $snippet = preg_replace('/^\S*\s/', '…', $snippet, 1); - } - if ($r['end'] < $textLength) { - $snippet = preg_replace('/\s\S*$/', '…', $snippet, 1); - } - - // Highlighting searched words - foreach ($words as $word) { - $pattern = '/(?$0', - $snippet - ); - } - - $snippets[] = trim($snippet); - if (count($snippets) >= 3) break; - } - - $result = implode('… ', $snippets); - $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); - - return trim($result); - } -} diff --git a/app/Traits/Models/HasMeilisearchIndex.php b/app/Traits/Models/HasMeilisearchIndex.php deleted file mode 100644 index 5384c165..00000000 --- a/app/Traits/Models/HasMeilisearchIndex.php +++ /dev/null @@ -1,113 +0,0 @@ -wasChanged('status'); - $originalLocale = app()->getLocale(); - $locales = $statusChanged - ? array_keys(LaravelLocalization::getSupportedLocales()) - : [$originalLocale]; - - // Loop on all locales to update indexes when global fields like status is updated, - // Otherwise, on current locale. - collect($locales)->map(function($locale) use ($keyPrefix, $model, $usesSoftDeletes) { - // Set the locale to alter the right ms index. - app()->setLocale($locale); - - $indexId = "{$keyPrefix}_{$model->getKey()}"; - - // Remove model from meilisearch index. - if ($usesSoftDeletes && method_exists($model, 'trashed') && $model->trashed()) { - SearchIndex::make([ - 'type' => $keyPrefix, - 'model_id' => $model->getKey(), - ])->unsearchable(); - return; - } - $msIndex = $model->toSearchDocument(); - // Add model to the meilisearch index if conditions are true, remove from it if not. - if ($msIndex) { - $msIndex->searchable(); - } else { - SearchIndex::make([ - 'type' => $keyPrefix, - 'model_id' => $model->getKey(), - ])->unsearchable(); - } - }); - - // Reset the locale with the original. - app()->setLocale($originalLocale); - }); - - static::deleted(function ($model) use ($keyPrefix) { - $originalLocale = app()->getLocale(); - $locales = array_keys(LaravelLocalization::getSupportedLocales()); - - // Loop on all locales to update indexes when model is deleted (softdeleted or not). - collect($locales)->map(function($locale) use ($keyPrefix, $model) { - // Set the locale to alter the right ms index. - app()->setLocale($locale); - - $indexId = "{$keyPrefix}_{$model->getKey()}"; - // Remove model from meilisearch index. - SearchIndex::make([ - 'type' => $keyPrefix, - 'model_id' => $model->getKey(), - ])->unsearchable(); - }); - - // Reset the locale with the original. - app()->setLocale($originalLocale); - }); - - if ($usesSoftDeletes) { - static::restored(function ($model) { - $originalLocale = app()->getLocale(); - $locales = array_keys(LaravelLocalization::getSupportedLocales()); - - // Loop on all locales to update indexes when model is restored. - collect($locales)->map(function($locale) use ($model) { - // Set the locale to alter the right ms index. - app()->setLocale($locale); - - // Add model to the meilisearch index if conditions are true. - $msIndex = $model->toSearchDocument(); - if ($msIndex) { - $msIndex->searchable(); - } - }); - - // Reset the locale with the original. - app()->setLocale($originalLocale); - }); - } - } -} diff --git a/config/scout.php b/config/scout.php index 794a607e..d05b4e71 100644 --- a/config/scout.php +++ b/config/scout.php @@ -1,5 +1,6 @@ true, + 'soft_delete' => false, /* |-------------------------------------------------------------------------- @@ -105,6 +106,10 @@ return [ 'meilisearch' => [ 'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'), 'key' => env('MEILISEARCH_KEY'), - 'index-settings' => [], + 'index-settings' => [ + DynamicPage::class => DynamicPage::$searchSettings, + Document::class => Document::$searchSettings, + News::class => News::$searchSettings, + ], ], ]; diff --git a/public/assets/css/style.css b/public/assets/css/style.css index 83119b1e..9747d058 100644 --- a/public/assets/css/style.css +++ b/public/assets/css/style.css @@ -3300,6 +3300,15 @@ div.search-results { font-weight: 700; } +.search-empty-results { + height: 80px; + padding: 30px 0; +} + +.search-page .page-numbers { + cursor: pointer; +} + /* page search END */ /* pagination START */ diff --git a/resources/views/components/front/search-pagination.blade.php b/resources/views/components/front/search-pagination.blade.php deleted file mode 100644 index 629294a0..00000000 --- a/resources/views/components/front/search-pagination.blade.php +++ /dev/null @@ -1,28 +0,0 @@ -@if ($models->lastPage() > 1) -
      -
      - {{-- Page précédente --}} - @if (!$models->onFirstPage()) - - @endif - {{-- Pages --}} - @for ($page = 1; $page <= $models->lastPage(); $page++) - @if ($page == $models->currentPage()) - {{ $page }} - @else - - {{ $page }} - - @endif - @endfor - {{-- Page suivante --}} - @if ($models->hasMorePages()) - - @endif -
      -
      -@endif \ No newline at end of file diff --git a/resources/views/components/front/search/card.blade.php b/resources/views/components/front/search/card.blade.php new file mode 100644 index 00000000..3773f122 --- /dev/null +++ b/resources/views/components/front/search/card.blade.php @@ -0,0 +1,31 @@ +@php + $hasTitle = isset($result["{$mainField}_{$currentLocale}"]) && !is_null($result["{$mainField}_{$currentLocale}"]) && !empty($result["{$mainField}_{$currentLocale}"]); + $hasDescription = isset($result["content_{$currentLocale}"]) && !is_null($result["content_{$currentLocale}"]) && !empty($result["content_{$currentLocale}"]); + $breadcrumbs = \Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray(); +@endphp + + @if($hasTitle) +
      + {!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["{$mainField}_{$currentLocale}"], $searchTerm) !!} +
      + @endif +
      !$hasDescription, + 'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true, + ])> + @foreach($breadcrumbs as $breadcrumb) + {{ $breadcrumb->title }} + @if(!$loop->last) + > + @endif + @endforeach + @if($customBreadcrumbs && $hasTitle && end($breadcrumbs)->title !== $result["{$mainField}_{$currentLocale}"]) + > {{ $result["{$mainField}_{$currentLocale}"] }} + @endif +
      + @if ($hasDescription) +
      + {!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["content_{$currentLocale}"], $searchTerm) !!} +
      + @endif +
      \ No newline at end of file diff --git a/resources/views/components/front/search/content.blade.php b/resources/views/components/front/search/content.blade.php new file mode 100644 index 00000000..f249b244 --- /dev/null +++ b/resources/views/components/front/search/content.blade.php @@ -0,0 +1,90 @@ +
      + {{-- LOADER --}} + + {{-- EMPTY RESULTS --}} + + {{-- RESULTS --}} +
      + {{-- PAGINATION --}} +
      +
      + +@php + // Set a template for the global count. + $resultsLabel = trans('front.search.results_total', [ + 'nbr' => '__COUNT__', + 'terms' => $searchTerm, + ]); + $currentLocale = app()->getLocale(); +@endphp + +@push('scripts') + +@endpush \ No newline at end of file diff --git a/resources/views/components/front/search/pagination.blade.php b/resources/views/components/front/search/pagination.blade.php new file mode 100644 index 00000000..3a8f32ff --- /dev/null +++ b/resources/views/components/front/search/pagination.blade.php @@ -0,0 +1,28 @@ +@if ($models->lastPage() > 1) +
      +
      + {{-- Previous button page --}} + @if (!$models->onFirstPage()) + + @endif + {{-- Numbers pages --}} + @for ($page = 1; $page <= $models->lastPage(); $page++) + @if ($page == $models->currentPage()) + {{ $page }} + @else + + @endif + @endfor + {{-- Next button page --}} + @if ($models->hasMorePages()) + + @endif +
      +
      +@endif diff --git a/resources/views/front/layouts/mobile-menu.blade.php b/resources/views/front/layouts/mobile-menu.blade.php index 03ebd978..00de9366 100644 --- a/resources/views/front/layouts/mobile-menu.blade.php +++ b/resources/views/front/layouts/mobile-menu.blade.php @@ -14,7 +14,7 @@
      - @foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties) + @foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode) @if (!$loop->first) / @endif diff --git a/resources/views/front/layouts/top-nav-menu.blade.php b/resources/views/front/layouts/top-nav-menu.blade.php index 2e7887b9..31772675 100644 --- a/resources/views/front/layouts/top-nav-menu.blade.php +++ b/resources/views/front/layouts/top-nav-menu.blade.php @@ -21,13 +21,11 @@ @endif
    - @foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties) + @foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode) @if (!$loop->first) / @endif - @php - $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); - @endphp + @php $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); @endphp {{ strtoupper($localeCode) }} diff --git a/resources/views/front/pages/search.blade.php b/resources/views/front/pages/search.blade.php index 61bde2e2..27deb3c6 100644 --- a/resources/views/front/pages/search.blade.php +++ b/resources/views/front/pages/search.blade.php @@ -7,66 +7,32 @@
    @include('front.breadcrumbs.breadcrumb-body')
    -

    {{ trans('front.search.results_total', ['nbr' => $resultModels['totalHits'], 'terms' => $searchTerm]) }}

    +

    + {{ trans('front.search.results_total', [ + 'nbr' => 0, + 'terms' => $searchTerm, + ]) }} +

    -
    - +
    + +
    +
    @error(trans('front.search.query'))
    {{ $message }}
    @enderror
    -
    - @forelse($resultModels['hits'] as $result) - @php - $locale = app()->getLocale(); - $hasDescription = isset($result['content']) && !is_null($result['content']) && !empty($result['content']); - @endphp - @php - if ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\DynamicPage::class))) { - $url = \App\Models\DynamicPage::getAccessModel($result['model_id']); - $routeName = sprintf('front.dynamic-pages.%s.%s', $result['id_key'], $locale); - $customBreadcrumbs = false; - } elseif ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\News::class))) { - $url = \App\Models\News::getAccessModel($result['model_id']); - $routeName = 'front.news.show'; - $customBreadcrumbs = true; - } elseif ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\Document::class))) { - $url = \App\Models\Document::getAccessModel($result['model_id']); - $routeName = 'front.documents.show'; - $customBreadcrumbs = true; - } - @endphp - -
    {!! \App\Models\SearchIndex::highlightTerms($result['title'], $searchTerm) !!}
    -
    !$hasDescription, - 'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true, - ])> - @foreach(\Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray() as $breacrumb) - {{ $breacrumb->title }} - @if(!$loop->last) - > - @endif - @endforeach - @if($customBreadcrumbs) - > {{ $result['title'] }} - @endif -
    - @if ($hasDescription) -
    -

    {!! \App\Models\SearchIndex::highlightTerms($result['content'], $searchTerm) !!}

    -
    - @endif -
    - @empty -

    {{ trans('front.search.no_results')}}

    - @endforelse - -
    +

    {{ str(trans_choice('models.classes.news', \INF))->ucFirst() }}

    + +

    {{ str(trans_choice('models.classes.dynamic-page', \INF))->ucFirst() }}

    + +

    {{ str(trans_choice('models.classes.document', \INF))->ucFirst() }}

    +
    -@endsection +@endsection \ No newline at end of file diff --git a/routes/breadcrumbs-front.php b/routes/breadcrumbs-front.php index 64dd2303..3ec67921 100644 --- a/routes/breadcrumbs-front.php +++ b/routes/breadcrumbs-front.php @@ -18,18 +18,20 @@ $pageHome = DynamicPage::getModelsCached() ->first(); // * DYNAMIC PAGES. -DynamicPage::getModelsCached()->map(function (DynamicPage $dynamicPageModel) use ($currentLocale, $pageHome) { - Breadcrumbs::for( - sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->id_key, $currentLocale), - function (Generator $trail) use ($currentLocale, $dynamicPageModel, $pageHome) { - if (!is_null($dynamicPageModel->page_id)) { - $trail->parent(sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->parentPage->id_key, $currentLocale)); - } elseif (isset($pageHome) && $dynamicPageModel->id_key !== $pageHome->id_key) { - $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $currentLocale)); +DynamicPage::getModelsCached()->map(function (DynamicPage $dynamicPageModel) use ($supportedLocales, $pageHome) { + collect($supportedLocales)->map(function (string $locale) use ($dynamicPageModel, $pageHome) { + Breadcrumbs::for( + sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->id_key, $locale), + function (Generator $trail) use ($locale, $dynamicPageModel, $pageHome) { + if (!is_null($dynamicPageModel->page_id)) { + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->parentPage->id_key, $locale)); + } elseif (isset($pageHome) && $dynamicPageModel->id_key !== $pageHome->id_key) { + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $locale)); + } + $trail->push($dynamicPageModel->title, RouteHelper::routeNameChecker(sprintf("front.dynamic-pages.%s", $dynamicPageModel->id_key))); } - $trail->push($dynamicPageModel->title, RouteHelper::routeNameChecker(sprintf("front.dynamic-pages.%s", $dynamicPageModel->id_key))); - } - ); + ); + }); }); // * CONTACT INDEX. diff --git a/routes/web-front.php b/routes/web-front.php index c805e74d..20a29f3a 100644 --- a/routes/web-front.php +++ b/routes/web-front.php @@ -28,6 +28,7 @@ Route::group( // Search routes. Route::get(LaravelLocalization::transRoute('routes.search'), [SearchController::class, 'search'])->name('search'); + Route::post('/search/load/results', [SearchController::class, 'ajaxSearchLoadResults'])->name('search.ajax.news'); // Filters routes. Route::prefix('posts')->group(function () { From 536ac6c254f7f35e0a93ea26b49f5a5a155ba1e8 Mon Sep 17 00:00:00 2001 From: K Muller Date: Fri, 16 Jan 2026 17:25:13 +0100 Subject: [PATCH 04/19] feat: :sparkles: add some filters on documents index --- app/Helpers/DocumentHelper.php | 55 ++++++++++++++++++ .../Controllers/Back/DocumentController.php | 6 +- config/logging.php | 32 +++++----- lang/en/back.php | 21 ++++++- lang/fr/back.php | 21 ++++++- .../ts/back/Components/Filters/EnumFilter.tsx | 44 ++++++++++++++ .../Filters/MultiSelectRelationFilter.tsx | 58 +++++++++++++++++++ .../back/Components/Filters/SwitchFilter.tsx | 33 +++++++++++ .../Pages/Document/Actions/ButtonTrigger.tsx | 36 ++++++++++++ .../back/Pages/Document/Actions/Filters.tsx | 57 ++++++++++++++++++ resources/ts/back/Pages/Document/Index.tsx | 51 ++++++++++++---- resources/ts/back/types/global.d.ts | 1 + resources/ts/lib/filters.tsx | 22 +++++++ 13 files changed, 407 insertions(+), 30 deletions(-) create mode 100644 resources/ts/back/Components/Filters/EnumFilter.tsx create mode 100644 resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx create mode 100644 resources/ts/back/Components/Filters/SwitchFilter.tsx create mode 100644 resources/ts/back/Pages/Document/Actions/ButtonTrigger.tsx create mode 100644 resources/ts/back/Pages/Document/Actions/Filters.tsx create mode 100644 resources/ts/lib/filters.tsx diff --git a/app/Helpers/DocumentHelper.php b/app/Helpers/DocumentHelper.php index d7f1d850..97cce79b 100644 --- a/app/Helpers/DocumentHelper.php +++ b/app/Helpers/DocumentHelper.php @@ -2,6 +2,9 @@ namespace App\Helpers; +use App\Enums\Document\DocumentStatusEnum; +use Illuminate\Http\Request; + class DocumentHelper { @@ -44,4 +47,56 @@ class DocumentHelper ? html_entity_decode($matches[1], ENT_QUOTES) : null; } + + /** + * Return a document query with all the request filters applied + * + * @param Request $request + * @param \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query + * @return \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query + */ + public static function getQueryWithFilters(Request $request, $query): \Illuminate\Database\Eloquent\Builder + { + $statusFilter = $request->status; + if($statusFilter) { + $query->where('status', DocumentStatusEnum::make($statusFilter, 'name')->value); + } + + $hasNoLinkFilter = request()->boolean('hasNoLink'); + $query->when($hasNoLinkFilter, function ($query) { + $locale = app()->getLocale(); + $query->where(function ($q) use ($locale) { + $q->whereNull("issuu_path->$locale") + ->whereNull("path->$locale"); + }); + }); + + $categoriesFilter = $request->input('categories'); + + $query->when($categoriesFilter, function ($query, $categoriesFilter) { + $categoryIds = collect(explode(',', $categoriesFilter)) + ->map(fn($id) => (int) $id) + ->filter() + ->values(); + + $query->whereHas('categories', function ($q) use ($categoryIds) { + $q->whereIn('document_categories.id', $categoryIds); + }); + }); + + $tagsFilter = $request->input('tags'); + + $query->when($tagsFilter, function ($query, $tagsFilter) { + $tagIds = collect(explode(',', $tagsFilter)) + ->map(fn($id) => (int) $id) + ->filter() + ->values(); + + $query->whereHas('tags', function ($q) use ($tagIds) { + $q->whereIn('document_tags.id', $tagIds); + }); + }); + + return $query; + } } diff --git a/app/Http/Controllers/Back/DocumentController.php b/app/Http/Controllers/Back/DocumentController.php index 18e35fb0..7ae3284e 100644 --- a/app/Http/Controllers/Back/DocumentController.php +++ b/app/Http/Controllers/Back/DocumentController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers\Back; use App\Enums\Document\DocumentStatusEnum; use App\Enums\YearsEnum; +use App\Helpers\DocumentHelper; use App\Http\Requests\Back\Document\StoreDocumentRequest; use App\Http\Requests\Back\Document\UpdateDocumentRequest; use App\Models\Document; @@ -37,7 +38,7 @@ class DocumentController extends Controller public function index(Request $request): \Inertia\Response { /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query */ - $query = Document::query()->with(['categories']); + $query = DocumentHelper::getQueryWithFilters($request, Document::query()->with(['categories', 'tags'])); /** @var string $search Search field */ $search = $request->search; @@ -49,6 +50,7 @@ class DocumentController extends Controller 'name', ); } + $searchFields = \implode(', ', [ trans('validation.attributes.name'), ]); @@ -63,6 +65,8 @@ class DocumentController extends Controller 'search' => $search, 'searchFields' => $searchFields, 'enumDocumentStatus' => DocumentStatusEnum::toArray(), + 'categories' => DocumentCategory::getModelsCached(), + 'tags' => DocumentTag::getModelsCached(), 'modelName' => $this->modelName, ]); } diff --git a/config/logging.php b/config/logging.php index b6d11541..f38d0ee8 100644 --- a/config/logging.php +++ b/config/logging.php @@ -7,22 +7,6 @@ use Monolog\Processor\PsrLogMessageProcessor; return [ - 'stdout' => [ - 'driver' => 'monolog', - 'level' => env('LOG_LEVEL', 'debug'), - 'handler' => StreamHandler::class, - 'formatter' => env('LOG_STDOUT_FORMATTER'), - 'with' => [ - 'stream' => 'php://stdout', - ], - ], - - 'k8s' => [ - 'driver' => 'stack', - 'channels' => ['daily', 'stdout'], - 'ignore_exceptions' => false, - ], - /** *-------------------------------------------------------------------------- @@ -144,6 +128,22 @@ return [ 'path' => storage_path('logs/laravel.log'), ], + 'stdout' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => StreamHandler::class, + 'formatter' => env('LOG_STDOUT_FORMATTER'), + 'with' => [ + 'stream' => 'php://stdout', + ], + ], + + 'k8s' => [ + 'driver' => 'stack', + 'channels' => ['daily', 'stdout'], + 'ignore_exceptions' => false, + ], + ], ]; diff --git a/lang/en/back.php b/lang/en/back.php index 325a4160..2ef824af 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -76,7 +76,8 @@ return [ ], "category" => [ "placeholder" => "choose a category" - ] + ], + "no_link" => "this document has neither internal link or Issu link", ], "form_title_additional_files" => "Additionnal files", "form_subtitle_additional_files" => "Add additionnal files", @@ -261,4 +262,22 @@ return [ ] ], "refresh_original" => "reset to original state", + "model_filters" => [ + "button_label" => "filters", + "select_status" => [ + "label" => "status", + "placeholder" => "choose a status" + ], + "has_no_link" => [ + "label" => "filter document with no usable link" + ], + "categories" => [ + "label" => "filter by category", + "placeholder" => "select one or more categories" + ], + "tags" => [ + "label" => "filter by tag", + "placeholder" => "select one or more tags" + ], + ], ]; diff --git a/lang/fr/back.php b/lang/fr/back.php index 0a69653c..8f70fa22 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -75,7 +75,8 @@ return [ ], "category" => [ "placeholder" => "choisir une catégorie" - ] + ], + "no_link" => "ce document ne possède ni lien interne ni lien Issuu", ], "form_title_additional_files" => "Fichier supplémentaire", "form_subtitle_additional_files" => "Ajouter des fichiers supplémentaires", @@ -262,4 +263,22 @@ return [ ] ], "refresh_original" => "remettre à l'état d'origine", + "model_filters" => [ + "button_label" => "filtres", + "select_status" => [ + "label" => "statut", + "placeholder" => "selectionner un statut" + ], + "has_no_link" => [ + "label" => "filtrer les documents qui n'ont aucun lien d'accès" + ], + "categories" => [ + "label" => "filtrer par categorie", + "placeholder" => "selectionner une ou plusieurs catégories" + ], + "tags" => [ + "label" => "filtrer par étiquette", + "placeholder" => "selectionner une ou plusieurs étiquettes" + ], + ] ]; diff --git a/resources/ts/back/Components/Filters/EnumFilter.tsx b/resources/ts/back/Components/Filters/EnumFilter.tsx new file mode 100644 index 00000000..c7c56715 --- /dev/null +++ b/resources/ts/back/Components/Filters/EnumFilter.tsx @@ -0,0 +1,44 @@ +// * Packages +import { route } from "ziggy-js"; +// * Other +import EnumSelect from "@/back/Components/Inputs/EnumSelect"; +import { LaravelEnum } from "@/back/types/global"; +import { addFilterToUrl } from "@/lib/filters"; + +type Props = { + enums: LaravelEnum; + fieldName: string; + modelName: string; + label: string; + placeholder: string; +} + +const EnumFilter = (props: Props) => { + const { enums, fieldName, modelName, label, placeholder } = props; + + const selectedEnumParam = Object.values(enums).find( + status => status.name === route().params.status + ); + return ( + { + const selectedStatusName = Object.values(enums).find( + enumValue => enumValue.value === value + )?.name; + const params = { + ...route().params, + [name]: selectedStatusName, + }; + addFilterToUrl({modelName, params}); + }} + /> + ) +} + +export default EnumFilter; diff --git a/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx new file mode 100644 index 00000000..4ca4085a --- /dev/null +++ b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx @@ -0,0 +1,58 @@ +// * Packages +import { usePage } from "@inertiajs/react"; +import { route } from "ziggy-js"; +// * Other +import { MultiSelect } from "@/back/Components/Inputs/MultiSelect"; +import { mapPivotOptions } from "@/lib/mapPivotOptions"; +import { AppEnv, Model } from "@/back/types/global"; +import { addFilterToUrl } from "@/lib/filters"; + +type Props = { + fieldName: string; + modelName: string; + label: string; + placeholder: string; + options: Model[]; + /** Is the model passed to the multi select translatable */ + modelTranslatable?: boolean; + /** The name of the field to display in options, default is name */ + optionName?: string; +} + +const MultiSelectRelationFilter = (props: Props) => { + const { fieldName, label, placeholder, modelName, options: optionsToSelect, modelTranslatable = false, optionName = "name" } = props; + + const { appEnv } = usePage().props as unknown as { + appEnv: AppEnv; + }; + + const valuesFromUrl: string[] = + typeof route().params[fieldName] === "string" + ? route().params[fieldName].split(",") + : []; + + const { options } = mapPivotOptions(optionsToSelect, [], optionName, modelTranslatable ? appEnv.locale : null); + + return ( + { + const params = { + ...route().params, + [name]: value.length ? value.join(",") : undefined, + }; + addFilterToUrl({ modelName, params }); + }} + defaultValue={valuesFromUrl} + options={options} + /> + ) +} + +export default MultiSelectRelationFilter; diff --git a/resources/ts/back/Components/Filters/SwitchFilter.tsx b/resources/ts/back/Components/Filters/SwitchFilter.tsx new file mode 100644 index 00000000..7794155a --- /dev/null +++ b/resources/ts/back/Components/Filters/SwitchFilter.tsx @@ -0,0 +1,33 @@ +// * Packages +import { route } from "ziggy-js"; +// * Other +import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch"; +import { addFilterToUrl } from "@/lib/filters"; + +type Props = { + fieldName: string; + modelName: string; + label: string; +} + +const SwitchFilter = (props: Props) => { + const { label, fieldName, modelName } = props; + return ( + { + const params = { + ...route().params, + [name]: value, + }; + addFilterToUrl({ modelName, params }); + }} + /> + ) +} + +export default SwitchFilter; diff --git a/resources/ts/back/Pages/Document/Actions/ButtonTrigger.tsx b/resources/ts/back/Pages/Document/Actions/ButtonTrigger.tsx new file mode 100644 index 00000000..3194e04f --- /dev/null +++ b/resources/ts/back/Pages/Document/Actions/ButtonTrigger.tsx @@ -0,0 +1,36 @@ +// * Packages +import { Filter } from "lucide-react"; +// * Components shadcn +import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"; +import { Button } from "@/components/ui/button"; +// * Other +import Filters from "@/back/Pages/Document/Actions/Filters"; +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; + +const ButtonTrigger = () => { + return ( +
    +
    + + + + + + + + {str(useTrans("back.model_filters.button_label")).ucFirst().value()} + + + + + +
    +
    + ); +} + +export default ButtonTrigger; diff --git a/resources/ts/back/Pages/Document/Actions/Filters.tsx b/resources/ts/back/Pages/Document/Actions/Filters.tsx new file mode 100644 index 00000000..8fd390e4 --- /dev/null +++ b/resources/ts/back/Pages/Document/Actions/Filters.tsx @@ -0,0 +1,57 @@ +// * Packages +import { usePage } from "@inertiajs/react"; +// * Components shadcn +import { SheetDescription } from "@/components/ui/sheet"; +// * Other +import EnumFilter from "@/back/Components/Filters/EnumFilter"; +import SwitchFilter from "@/back/Components/Filters/SwitchFilter"; +import MultiSelectRelationFilter from "@/back/Components/Filters/MultiSelectRelationFilter"; +import { DocumentCategoryModel, DocumentTagModel, LaravelEnum } from "@/back/types/global"; +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; + +export default function Filters() { + const modelName = usePage().props.modelName as string; + const categories = usePage().props.categories as DocumentCategoryModel[]; + const tags = usePage().props.tags as DocumentTagModel[]; + const enumDocumentStatus = usePage().props.enumDocumentStatus as LaravelEnum; + + return ( + +
    + + + + + + +
    +
    + ); +} diff --git a/resources/ts/back/Pages/Document/Index.tsx b/resources/ts/back/Pages/Document/Index.tsx index 4b8bc0e1..b2321c09 100644 --- a/resources/ts/back/Pages/Document/Index.tsx +++ b/resources/ts/back/Pages/Document/Index.tsx @@ -1,37 +1,38 @@ // * Packages import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; +import { Row } from "@tanstack/react-table"; +import { Plus, TriangleAlert } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { Views } from "@/lib/utils"; +import ButtonTrigger from "@/back/Pages/Document/Actions/ButtonTrigger"; +import DocumentStatusBadge from "@/back/Components/DocumentStatusBadge"; +import DocumentFinanceTagBadge from "@/back/Components/DocumentFinanceTagBadge"; +import { cn, Views } from "@/lib/utils"; +import { renderTranslationCell } from "@/lib/translationCellFallback"; import { useFormatedDate } from "@/hooks/use-formated-value"; import { AppEnv, AuthProp, - DocumentCategoryModel, DocumentModel, Resource, TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { Row } from "@tanstack/react-table"; -import { Plus } from "lucide-react"; -import DocumentStatusBadge from "@/back/Components/DocumentStatusBadge"; -import DocumentFinanceTagBadge from "@/back/Components/DocumentFinanceTagBadge"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; export default function Index({ documentsModel, search, searchFields, - modelName + modelName, }: { documentsModel: Resource; search: string; @@ -58,8 +59,34 @@ export default function Index({ /> ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") as TranslationField + const locale = appEnv.locale; + + const issuuPath = row.original.issuu_path; + const path = row.original.path; + const hasIssuuPathForLocale = Boolean(issuuPath?.[locale]); + const hasPathForLocale = Boolean(path?.[locale]); + + const hasLink = hasIssuuPathForLocale || hasPathForLocale; + + return ( +
    + {!hasLink && ( + + + + + +

    {str(useTrans('back.document.no_link')).ucFirst().value()}

    +
    +
    + )} + + + {renderTranslationCell( + row.getValue("name") as TranslationField + )} + +
    ); }, }, @@ -97,7 +124,7 @@ export default function Index({ accessorKey: "published_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -147,6 +174,8 @@ export default function Index({ searchText={search} searchFields={searchFields} /> + + { + const { modelName, params } = props; + return router.visit(route(`back.${modelName}.index`), { + method: "get", + data: { + ...params, + page: undefined, + }, + preserveState: true, + preserveScroll: true, + replace: true, + }); +} From a21493aea3496451e182b5edbaf99348aab9bac7 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 20 Jan 2026 15:25:48 +0100 Subject: [PATCH 05/19] fix: :globe_with_meridians: update back translations --- .../Requests/Back/News/StoreNewsRequest.php | 3 +- lang/en/back.php | 1 + lang/en/models.php | 2 +- lang/en/validation.php | 23 +- lang/fr/back.php | 3 +- lang/fr/models.php | 2 +- lang/fr/validation.php | 23 +- .../Components/AssociatedDocumentList.tsx | 83 ++-- .../ts/back/Components/AssociatedNewsList.tsx | 52 ++- .../ts/back/Components/Layout/AppSidebar.tsx | 20 +- .../back/Components/Table/DataTableSearch.tsx | 20 +- .../ts/back/Layouts/AuthenticatedLayout.tsx | 3 - .../ts/back/Pages/ContactCount/Index.tsx | 46 ++- resources/ts/back/Pages/Document/Form.tsx | 381 ++++++++++-------- resources/ts/back/Pages/Document/Index.tsx | 108 +++-- resources/ts/back/Pages/Document/Show.tsx | 192 ++++++--- .../ts/back/Pages/DocumentCategory/Index.tsx | 59 ++- resources/ts/back/Pages/DocumentTag/Index.tsx | 11 +- resources/ts/back/Pages/News/Form.tsx | 218 +++++++--- resources/ts/back/Pages/News/Index.tsx | 7 +- resources/ts/back/Pages/News/Show.tsx | 187 ++++++--- .../ts/back/Pages/NewsCategory/Index.tsx | 140 ++++--- resources/ts/back/Pages/NewsTag/Index.tsx | 161 +++++--- 23 files changed, 1109 insertions(+), 636 deletions(-) diff --git a/app/Http/Requests/Back/News/StoreNewsRequest.php b/app/Http/Requests/Back/News/StoreNewsRequest.php index b5d7d9ed..c5165e58 100644 --- a/app/Http/Requests/Back/News/StoreNewsRequest.php +++ b/app/Http/Requests/Back/News/StoreNewsRequest.php @@ -94,7 +94,8 @@ class StoreNewsRequest extends FormRequest 'seo_description' => trans('validation.custom.seo.description'), 'title' => trans('validation.attributes.title'), 'slug' => trans('validation.custom.slug'), - 'categories' => trans('validation.custom.categories'), + 'categories' => trans_choice('models.classes.news-category', \INF), + 'tags' => trans_choice('models.classes.news-tag', \INF), 'picture' => trans('validation.attributes.image'), 'picture_alt' => trans('validation.custom.image_alt'), 'picture_title' => trans('validation.custom.image_title'), diff --git a/lang/en/back.php b/lang/en/back.php index 2ef824af..78335c4b 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -280,4 +280,5 @@ return [ "placeholder" => "select one or more tags" ], ], + "associated_model" => "associated :model|associated :model", ]; diff --git a/lang/en/models.php b/lang/en/models.php index 5865c8a4..288ee999 100644 --- a/lang/en/models.php +++ b/lang/en/models.php @@ -9,6 +9,7 @@ return [ "contact-count" => "contact form", "news" => "news|news", "news-category" => "news category|news categories", + "news-tag" => "news tag|news tag", "company" => "company|companies", "company-activity" => "activity de société|activities de société", "company-sector" => "company sector|company sectors", @@ -16,6 +17,5 @@ return [ "document-tag" => "document tag|document tags", "document-category" => "document category|document categories", "document-exercice" => "document exercice|document exercices", - "news-tag" => "news tag|news tag", ], ]; diff --git a/lang/en/validation.php b/lang/en/validation.php index ced66178..c684132d 100644 --- a/lang/en/validation.php +++ b/lang/en/validation.php @@ -248,7 +248,6 @@ return [ "title" => "seo title", "description" => "seo description", ], - "category" => "category|categories", "picture" => [ "picture" => "image", "picture_alt" => "alternative text of the image", @@ -259,8 +258,8 @@ return [ "type" => "form type", "submissions" => "count of soumissions" ], - "vimeo_id" => "VIMEO ID", - "youtube_id" => "YOUTUBE ID", + "vimeo_id" => "VIMEO ID", + "youtube_id" => "YOUTUBE ID", "logo" => "logo", "responsable" => "responsable", "url" => "url", @@ -270,20 +269,8 @@ return [ "longitude" => "longitude", "color" => "color", "value" => "value", - "document" => [ - "exercice" => "exercice|exercices", - "tag" => "etiquette|etiquettes", - "path" => "file", - "category" => "category|categories" - ], - "documentTag" => [ - "documents" => "associated file(s)" - ], - "newsCategory" => [ - "news" => "associated news" - ], - "news" => [ - "tag" => "etiquette|etiquettes", - ] + "path" => "path", + "issuu_path" => "link of the Issuu preview", + "is_issuu" => "is an Issuu preview ?" ], ]; diff --git a/lang/fr/back.php b/lang/fr/back.php index 8f70fa22..a8660246 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -280,5 +280,6 @@ return [ "label" => "filtrer par étiquette", "placeholder" => "selectionner une ou plusieurs étiquettes" ], - ] + ], + "associated_model" => ":model associés|:model associées", ]; diff --git a/lang/fr/models.php b/lang/fr/models.php index d8181f21..5b3bd528 100644 --- a/lang/fr/models.php +++ b/lang/fr/models.php @@ -9,6 +9,7 @@ return [ "contact-count" => "formulaire de contact", "news" => "actualité|actualités", "news-category" => "catégorie d'actualité|catégories d'actualité", + "news-tag" => "étiquette d'actualité|étiquettes d'actualité", "company" => "société|sociétés", "company-activity" => "activité de société|activités de société", "company-sector" => "secteur de société|secteurs de société", @@ -16,6 +17,5 @@ return [ "document-tag" => "étiquette de document|étiquettes de document", "document-category" => "catégorie de document|catégories de document", "document-exercice" => "exercice de document|exercices de document", - "news-tag" => "étiquette d'actualité|étiquettes d'actualité", ], ]; diff --git a/lang/fr/validation.php b/lang/fr/validation.php index 3f67c1fa..e339c77b 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -249,11 +249,10 @@ return [ "title" => "titre SEO", "description" => "description SEO", ], - "category" => "catégorie|catégories", "image_alt" => "texte alternatif de l'image", "image_title" => "titre de l'image", "content" => "contenu", - "contactCount" => [ + "contact_count" => [ "type" => "type de formulaire", "submissions" => "nombre de soumissions" ], @@ -268,22 +267,8 @@ return [ "longitude" => "longitude", "color" => "couleur", "value" => "valeur", - "document" => [ - "exercice" => "exercice|exercices", - "tag" => "étiquette|étiquettes", - "path" => "fichier", - "category" => "catégorie|catégories" - ], - "documentTag" => [ - "documents" => "document(s) associé(s)" - ], - "newsCategory" => [ - "news" => "actualité(s) associée(s)" - ], - "news" => [ - "tag" => "étiquette|étiquettes", - ], - "issuu_path" => "lien de la preview Issuu", - "is_issuu" => "est-ce une preview Issuu ?" + "path" => "chemin d'accès", + "issuu_path" => "lien du fichier Issuu", + "is_issuu" => "est-ce un fichier Issuu ?" ], ]; diff --git a/resources/ts/back/Components/AssociatedDocumentList.tsx b/resources/ts/back/Components/AssociatedDocumentList.tsx index f2e3a163..00799987 100644 --- a/resources/ts/back/Components/AssociatedDocumentList.tsx +++ b/resources/ts/back/Components/AssociatedDocumentList.tsx @@ -1,15 +1,20 @@ -import str from "@/hooks/use-string" -import DataTable from "./Table/DataTable" -import useTrans from "@/hooks/use-translations" +import str from "@/hooks/use-string"; +import DataTable from "./Table/DataTable"; +import useTrans from "@/hooks/use-translations"; import DataTableFilterButton from "./Table/DataTableFilterButton"; -import { AppEnv, DocumentModel, Resource, TranslationField } from "../types/global"; +import { + AppEnv, + DocumentModel, + Resource, + TranslationField, +} from "../types/global"; import { Row } from "@tanstack/react-table"; import { usePage } from "@inertiajs/react"; import { Views } from "@/lib/utils"; import { renderTranslationCell } from "@/lib/translationCellFallback"; interface Props { - documents: Resource + documents: Resource; } const AssociatedDocumentList = (props: Props) => { const { documents } = props; @@ -21,48 +26,80 @@ const AssociatedDocumentList = (props: Props) => { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) + return renderTranslationCell(row.getValue("name")); }, }, { accessorKey: "path", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { - return (row.getValue("path") as TranslationField)[appEnv.locale] ? ( - ( - {appEnv.url + '/' + (row.getValue("path") as TranslationField)[appEnv.locale]} - ) - ) : (

    {useTrans('back.table_not_known')}

    ); + return (row.getValue("path") as TranslationField)[ + appEnv.locale + ] ? ( + + {appEnv.url + + "/" + + (row.getValue("path") as TranslationField)[ + appEnv.locale + ]} + + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ); }, }, ]; return ( <> -

    {str(useTrans("validation.custom.documentTag.documents")).ucFirst().value()}

    +

    + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    - ) -} + ); +}; export default AssociatedDocumentList; diff --git a/resources/ts/back/Components/AssociatedNewsList.tsx b/resources/ts/back/Components/AssociatedNewsList.tsx index cfd762a3..4ad48a7e 100644 --- a/resources/ts/back/Components/AssociatedNewsList.tsx +++ b/resources/ts/back/Components/AssociatedNewsList.tsx @@ -1,6 +1,6 @@ -import str from "@/hooks/use-string" -import DataTable from "./Table/DataTable" -import useTrans from "@/hooks/use-translations" +import str from "@/hooks/use-string"; +import DataTable from "./Table/DataTable"; +import useTrans from "@/hooks/use-translations"; import DataTableFilterButton from "./Table/DataTableFilterButton"; import { AppEnv, NewsModel, Resource, TranslationField } from "../types/global"; import { Row } from "@tanstack/react-table"; @@ -12,7 +12,7 @@ import NewsStatusBadge from "./NewsStatusBadge"; import { renderTranslationCell } from "@/lib/translationCellFallback"; interface Props { - news: Resource + news: Resource; } const AssociatedNewsList = (props: Props) => { const { news } = props; @@ -25,35 +25,39 @@ const AssociatedNewsList = (props: Props) => { accessorKey: "title", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("title") - ) + return renderTranslationCell(row.getValue("title")); }, }, { accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { return ( - - ) + + ); }, }, { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -67,18 +71,28 @@ const AssociatedNewsList = (props: Props) => { return ( <> -

    {str(useTrans("validation.custom.newsCategory.news")).ucFirst().value()}

    +

    + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    - ) -} + ); +}; export default AssociatedNewsList; diff --git a/resources/ts/back/Components/Layout/AppSidebar.tsx b/resources/ts/back/Components/Layout/AppSidebar.tsx index c5de9e42..80196a28 100644 --- a/resources/ts/back/Components/Layout/AppSidebar.tsx +++ b/resources/ts/back/Components/Layout/AppSidebar.tsx @@ -167,7 +167,7 @@ export default function AppSidebar() { authPolicies.newsTags.viewAny && ( ), - authPolicies.documentTags.create && ( - - ), authPolicies.documentCategories.create && ( + ), + authPolicies.documentTags.create && ( + ) ] }) diff --git a/resources/ts/back/Components/Table/DataTableSearch.tsx b/resources/ts/back/Components/Table/DataTableSearch.tsx index 19636cdc..15d65fbb 100644 --- a/resources/ts/back/Components/Table/DataTableSearch.tsx +++ b/resources/ts/back/Components/Table/DataTableSearch.tsx @@ -1,22 +1,26 @@ // * Packages import { DeleteIcon } from "lucide-react"; import { router, useForm } from "@inertiajs/react"; -import { FormEvent } from "react"; +import { FormEvent, ReactNode } from "react"; import { route } from "ziggy-js"; // * Other import SimpleString from "@/back/Components/Inputs/SimpleString"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "../BtnOptionnalLinkWithTooltip"; +type DataTableSearchProps = { + modelRoute: string; + searchText: string; + searchFields: string; + children?: ReactNode; +}; + export default function DataTableSearch({ modelRoute, searchText, searchFields, -}: { - modelRoute: string; - searchText: string; - searchFields: string; -}) { + children, +}: DataTableSearchProps) { const url = new URL(window.location.href); const { get, setData, data } = useForm({ search: searchText, @@ -26,7 +30,7 @@ export default function DataTableSearch({ get(route(`back.${modelRoute}.index`)); }; return ( -
    + + {children} } tooltipContent={

    {useTrans("back.table_search_reset")}

    } - className="ml-2" type="button" variant="destructive" onClick={() => router.visit(url.origin + url.pathname)} diff --git a/resources/ts/back/Layouts/AuthenticatedLayout.tsx b/resources/ts/back/Layouts/AuthenticatedLayout.tsx index 1b187229..d56c68f5 100644 --- a/resources/ts/back/Layouts/AuthenticatedLayout.tsx +++ b/resources/ts/back/Layouts/AuthenticatedLayout.tsx @@ -30,8 +30,6 @@ export default function AuthenticatedLayout({ ? localStorage.getItem("vite-ui-collapsed") : null; - - return ( @@ -49,7 +47,6 @@ export default function AuthenticatedLayout({ ); } - function LayoutContent({ title, beforeNode, diff --git a/resources/ts/back/Pages/ContactCount/Index.tsx b/resources/ts/back/Pages/ContactCount/Index.tsx index 3a2f6733..5e17b894 100644 --- a/resources/ts/back/Pages/ContactCount/Index.tsx +++ b/resources/ts/back/Pages/ContactCount/Index.tsx @@ -2,11 +2,7 @@ import { Row } from "@tanstack/react-table"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; -import { - ContactCountModel, - LaravelEnum, - Resource, -} from "@/back/types/global"; +import { ContactCountModel, LaravelEnum, Resource } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; @@ -23,29 +19,51 @@ export default function Index({ { accessorKey: "type", header: ({ column }: { column: { id: string } }) => ( -

    {str(useTrans(`validation.custom.contactCount.${column.id}`)).ucFirst().value()}

    +

    + {str( + useTrans( + `validation.custom.contact_count.${column.id}`, + ), + ) + .ucFirst() + .value()} +

    ), cell: ({ row }: { row: Row }) => { - const type = Object.values(contactFormType).find(item => item.value === (row.getValue("type"))); + const type = Object.values(contactFormType).find( + (item) => item.value === row.getValue("type"), + ); if (!type) return; - return (

    {str(type.label).ucFirst().value()}

    ); - } + return ( +

    + {str(type.label).ucFirst().value()} +

    + ); + }, }, { accessorKey: "submissions", header: ({ column }: { column: { id: string } }) => ( -

    {str(useTrans(`validation.custom.contactCount.${column.id}`)).ucFirst().value()}

    +

    + {str( + useTrans( + `validation.custom.contact_count.${column.id}`, + ), + ) + .ucFirst() + .value()} +

    ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + ); const transTitle = str(transModel).ucFirst().value(); return ( - + (null); /** Form section */ const { post, setData, data, reset } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', + _method: method === Methods.POST ? "post" : "put", name: model?.name ? model?.name[locale] : "", exercice: model?.exercice ? model?.exercice : "", status: model?.status ?? enumDocStatus.unpublished.value, @@ -55,7 +69,7 @@ export default function Form({ issuu_path: model?.issuu_path ? model?.issuu_path[locale] : "", categories: model?.categories ? categoryDefaultValue : [], published_at: model?.published_at ? model?.published_at : null, - unpublished_at: model?.unpublished_at ? model?.unpublished_at : null + unpublished_at: model?.unpublished_at ? model?.unpublished_at : null, }); const submitCrud = useCrudSubmit({ @@ -64,28 +78,31 @@ export default function Form({ modelName, action, model, - post + post, }); const originalDataPath = model && model.path && model.path[locale] ? model.path[locale] - : undefined + : undefined; const refreshFileFromDb = () => { if (model && model.path) { - setData('issuu_path', ""); - setData('is_issuu', false); - setData('path', model.path[locale]); - setDynamicKey(Date.now()) + setData("issuu_path", ""); + setData("is_issuu", false); + setData("path", model.path[locale]); + setDynamicKey(Date.now()); } if (model && model.is_issuu) { - setData('issuu_path', model?.issuu_path ? model.issuu_path[locale] : ""); - setData('is_issuu', true); - setData('path', null); - setDynamicKey(Date.now()) + setData( + "issuu_path", + model?.issuu_path ? model.issuu_path[locale] : "", + ); + setData("is_issuu", true); + setData("path", null); + setDynamicKey(Date.now()); } - } + }; return ( @@ -101,11 +118,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.attributes.name"), + attribute: useTrans( + "validation.attributes.name", + ), }, - choice: 1 + choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} required={true} placeholder="ex: John Doe" value={data.name ?? ""} @@ -126,11 +147,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.published_at"), + attribute: useTrans( + "validation.custom.published_at", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} /> } description={useTrans("back.form_subtitle_content")} - className="gap-4" + className="sm:grid-cols-2 gap-4" > -
    - { - if (data.path || data.issuu_path) { - setData(prev => ({ - ...prev, - path: "", - issuu_path: "" - })); - } - setData('is_issuu', value); - setDynamicKey(Date.now()); - }} - /> -
    -
    -
    - {data.is_issuu ? ( - - ) : ( - - )} - - {(model?.issuu_path || model?.path) && ( - - } - tooltipContent={str(useTrans("back.refresh_original")).ucFirst().value()} - /> - )} -
    -
    -
    -
    - { + if (data.path || data.issuu_path) { + setData((prev) => ({ + ...prev, + path: "", + issuu_path: "", + })); + } + setData("is_issuu", value); + setDynamicKey(Date.now()); + }} + /> +
    + {data.is_issuu ? ( + - - -
    -
    - -
    + ) : ( + + )} + {(model?.issuu_path || model?.path) && ( + } + tooltipContent={str( + useTrans("back.refresh_original"), + ) + .ucFirst() + .value()} + /> + )}
    + + +
    - + })} + />
    ); diff --git a/resources/ts/back/Pages/Document/Index.tsx b/resources/ts/back/Pages/Document/Index.tsx index b2321c09..ee15ca2b 100644 --- a/resources/ts/back/Pages/Document/Index.tsx +++ b/resources/ts/back/Pages/Document/Index.tsx @@ -5,7 +5,11 @@ import { Row } from "@tanstack/react-table"; import { Plus, TriangleAlert } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; @@ -44,17 +48,15 @@ export default function Index({ appEnv: AppEnv; }; const { create } = auth.policies.documents; - const actionModels = [ - Views.VISUALIZATION, - Views.EDITION, - Views.DELETION, - ]; + const actionModels = [Views.VISUALIZATION, Views.EDITION, Views.DELETION]; const columns = [ { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( ), @@ -69,23 +71,30 @@ export default function Index({ const hasLink = hasIssuuPathForLocale || hasPathForLocale; return ( -
    +
    {!hasLink && ( -

    {str(useTrans('back.document.no_link')).ucFirst().value()}

    +

    + {str(useTrans("back.document.no_link")) + .ucFirst() + .value()} +

    )} - {renderTranslationCell( - row.getValue("name") as TranslationField + row.getValue("name") as TranslationField, )} -
    ); }, @@ -94,37 +103,60 @@ export default function Index({ accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { return ( - - ) + + ); }, }, { accessorKey: "categories", - header: str(useTrans("validation.custom.document.category", { choice: 2 })).ucFirst().value(), + header: str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document-category", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value(), cell: ({ row }: { row: Row }) => { - if (!row.original.categories || row.original.categories.length === 0) return null; + if ( + !row.original.categories || + row.original.categories.length === 0 + ) + return null; return (
    {row.original.categories.map((item, i) => ( - + ))}
    ); - } - + }, }, { accessorKey: "published_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -138,7 +170,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -149,33 +183,37 @@ export default function Index({ ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); const transTitle = str(transModel).ucFirst().value(); const afterNode = () => { return (
    - {create && } - tooltipContent={

    {useTrans("back.crud_add_entry")}

    } - />} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )}
    ); }; return ( - + - - + > + + value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.attributes.name")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "path", - header: str(useTrans("validation.custom.document.path")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? ({appEnv.url + '/' + value[appEnv.locale]}) - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.custom.file")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + + {appEnv.url + "/" + value[appEnv.locale]} + + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "issuu_path", - header: str(useTrans("validation.custom.issuu_path")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? ({value[appEnv.locale]}) - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.custom.issuu_path")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + + {value[appEnv.locale]} + + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "exercice", - header: str(useTrans("validation.custom.document.exercice", { choice: 1})).ucFirst().value(), + header: str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document-exercice", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => { - return ( - - ) + return ; }, }, { accessorKey: "status", header: str(useTrans("validation.custom.status")).ucFirst().value(), cell: ({ value }: { value: string }) => { - return ( - - ) + return ; }, }, { accessorKey: "tags", - header: str(useTrans("validation.custom.document.tag", {choice:2})).ucFirst().value(), + header: str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document-tag", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value(), cell: ({ value }: { value?: DocumentTagModel[] }) => { if (!value || value.length === 0) return null; return (
    {value.map((item, i) => ( - + ))}
    ); - } - + }, }, { accessorKey: "categories", - header: str(useTrans("validation.custom.document.category", {choice:2})).ucFirst().value(), + header: str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document-category", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value(), cell: ({ value }: { value?: DocumentCategoryModel[] }) => { if (!value || value.length === 0) return null; return (
    {value.map((item, i) => ( - + ))}
    ); - } - + }, }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => { return ( {useFormatedDate(value)} - ) + ); }, }, { accessorKey: "published_at", - header: str(useTrans("validation.custom.published_at")).ucFirst().value(), + header: str(useTrans("validation.custom.published_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value, useLocale.use.timezone(), true)} + + {useFormatedDate(value, useLocale.use.timezone(), true)} + ), }, { accessorKey: "unpublished_at", - header: str(useTrans("validation.custom.unpublished_at")).ucFirst().value(), + header: str(useTrans("validation.custom.unpublished_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), @@ -152,22 +229,23 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN ]; const beforeNode = () => { - return viewAny && ( -
    - } - tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } - /> -
    + return ( + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) ); }; return ( - + ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) + return renderTranslationCell(row.getValue("name")); }, }, { accessorKey: "documents", header: () => ( -

    {str(useTrans(`validation.custom.documentTag.documents`)).ucFirst().value()}

    +

    + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    ), cell: ({ row }: { row: Row }) => (
    @@ -75,7 +84,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -86,26 +97,30 @@ export default function Index({ ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); const transTitle = str(transModel).ucFirst().value(); const afterNode = () => { return (
    - {create && } - tooltipContent={

    {useTrans("back.crud_add_entry")}

    } - />} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )}
    ); }; return ( - + (

    - {str(useTrans(`validation.custom.documentTag.documents`)) + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document", { + choice: 2, + }), + }, + choice: 2, + }), + ) .ucFirst() .value()}

    diff --git a/resources/ts/back/Pages/News/Form.tsx b/resources/ts/back/Pages/News/Form.tsx index c48646d2..9bb0c6f2 100644 --- a/resources/ts/back/Pages/News/Form.tsx +++ b/resources/ts/back/Pages/News/Form.tsx @@ -1,6 +1,6 @@ // * Packages import { useForm, usePage } from "@inertiajs/react"; -import { BookTextIcon, CogIcon, RefreshCwIcon, GavelIcon } from "lucide-react"; +import { BookTextIcon, CogIcon } from "lucide-react"; import { useEffect, useState } from "react"; // * Components shadcn import { Separator } from "@/components/ui/separator"; @@ -8,7 +8,6 @@ import { Skeleton } from "@/components/ui/skeleton"; import { Card, CardContent } from "@/components/ui/card"; // * Other import FieldsetWrapper from "@/back/Components/FieldsetWrapper"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import InputError from "@/back/Components/InputError"; import GoToFrontView from "@/back/Components/GoToFrontView"; import SimpleString from "@/back/Components/Inputs/SimpleString"; @@ -19,10 +18,16 @@ import SimpleDatePicker from "@/back/Components/Inputs/SimpleDatePicker"; import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile"; import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch"; import SimpleVimeoId from "@/back/Components/Inputs/SimpleVimeoId"; -import { mapLaravelEnumOptions } from "@/lib/mapEnumOptions"; import { cn } from "@/lib/utils"; import { Methods } from "@/lib/enums"; -import { AppEnv, DynamicFieldTypes, LaravelEnum, NewsCategoryModel, NewsModel, NewsTagModel } from "@/back/types/global"; +import { + AppEnv, + DynamicFieldTypes, + LaravelEnum, + NewsCategoryModel, + NewsModel, + NewsTagModel, +} from "@/back/types/global"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; import { useCrudSubmit } from "@/hooks/use-crud-submit"; @@ -46,14 +51,17 @@ export default function Form({ const { locale } = usePage().props.appEnv as AppEnv; const [isGif, setIsGif] = useState(false); const [dynamicKey, setDynamicKey] = useState(null); - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; const newsTag = usePage().props.newsTag as NewsTagModel[]; const newsCategory = usePage().props.newsCategory as NewsCategoryModel[]; const enumNewsStatus = usePage().props.enumNewsStatus as LaravelEnum; - const { options: optionTags, defaultValue: defaultValueTags } = mapPivotOptions(newsTag, model?.tags, "name", locale); - const { options: optionCategories, defaultValue: defaultValueCategories } = mapPivotOptions(newsCategory, model?.categories, "name", locale); + const { options: optionTags, defaultValue: defaultValueTags } = + mapPivotOptions(newsTag, model?.tags, "name", locale); + const { options: optionCategories, defaultValue: defaultValueCategories } = + mapPivotOptions(newsCategory, model?.categories, "name", locale); function isFile(value: unknown): value is File { return value instanceof File; @@ -61,9 +69,11 @@ export default function Form({ /** Form section */ const { post, setData, data, reset } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', + _method: method === Methods.POST ? "post" : "put", seo_title: model?.seo_title ? model?.seo_title[locale] : "", - seo_description: model?.seo_description ? model?.seo_description[locale] : "", + seo_description: model?.seo_description + ? model?.seo_description[locale] + : "", title: model?.title ? model?.title[locale] : "", slug: model?.slug ? model?.slug[locale] : "", content: model?.content ? model?.content[locale] : "", @@ -77,17 +87,19 @@ export default function Form({ tags: model?.tags ? defaultValueTags : [], categories: model?.categories ? defaultValueCategories : [], published_at: model?.published_at ? model?.published_at : null, - unpublished_at: model?.unpublished_at ? model?.unpublished_at : null + unpublished_at: model?.unpublished_at ? model?.unpublished_at : null, }); const refreshFileFromDb = () => { if (model && model.picture) { - const isGif = typeof model.picture === "string" && model.picture.toLowerCase().endsWith(".gif"); + const isGif = + typeof model.picture === "string" && + model.picture.toLowerCase().endsWith(".gif"); setIsGif(isGif); - setData('picture', model.picture) - setDynamicKey(Date.now()) + setData("picture", model.picture); + setDynamicKey(Date.now()); } - } + }; const submitCrud = useCrudSubmit({ method, @@ -95,7 +107,7 @@ export default function Form({ modelName, action, model, - post + post, }); useEffect(() => { @@ -124,11 +136,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.seo.title"), + attribute: useTrans( + "validation.custom.seo.title", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} required={true} placeholder="ex: John Doe" value={data.seo_title ?? ""} @@ -139,11 +155,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.seo.description"), + attribute: useTrans( + "validation.custom.seo.description", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" required={true} value={data.seo_description ?? ""} @@ -162,11 +182,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.attributes.title"), + attribute: useTrans( + "validation.attributes.title", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.title} setData={setData} @@ -178,10 +202,14 @@ export default function Form({ />
    -
    +
    - -
    + +
    @@ -291,9 +347,9 @@ export default function Form({ setData={(_, value) => { setIsGif(value); if (data.picture) { - setData(prev => ({ + setData((prev) => ({ ...prev, - picture: null + picture: null, })); } setDynamicKey(Date.now()); @@ -311,11 +367,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.attributes.image"), + attribute: useTrans( + "validation.attributes.image", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} setData={setData} onRefreshFile={refreshFileFromDb} // @ts-ignore @@ -323,12 +383,20 @@ export default function Form({ value={data.picture} required={true} maxFileSize="5120" - allowedFormats={isGif ? 'gif' : "jpg,jpeg,png,webp"} - validationRules={isGif ? null : { - width: "525", - height: "295" - }} - inputType={isGif ? enumDynamicFieldTypes.file.value : enumDynamicFieldTypes.image.value} + allowedFormats={isGif ? "gif" : "jpg,jpeg,png,webp"} + validationRules={ + isGif + ? null + : { + width: "525", + height: "295", + } + } + inputType={ + isGif + ? enumDynamicFieldTypes.file.value + : enumDynamicFieldTypes.image.value + } />
    @@ -338,11 +406,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.image_alt"), + attribute: useTrans( + "validation.custom.image_alt", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.picture_alt ?? ""} setData={setData} @@ -353,11 +425,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.image_title"), + attribute: useTrans( + "validation.custom.image_title", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.picture_title ?? ""} setData={setData} @@ -369,11 +445,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.content"), + attribute: useTrans( + "validation.custom.content", + ), }, - choice: 1 + choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} value={data.content} setData={setData} /> @@ -382,18 +462,23 @@ export default function Form({ label={str( useTrans("back.form_associate_to_plural", { params: { - attribute: useTrans("validation.custom.news.tag", { choice: 2 }), + attribute: useTrans( + "models.classes.news-tag", + { choice: 2 }, + ), }, - choice: 2 + choice: 2, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} multiple={true} name="tags" required={false} variant="inverted" - placeholder={str( - useTrans("back.news.tags.placeholder") - ).ucFirst().value()} + placeholder={str(useTrans("back.news.tags.placeholder")) + .ucFirst() + .value()} singleLine={true} setData={setData} defaultValue={data.tags} @@ -403,18 +488,25 @@ export default function Form({ label={str( useTrans("back.form_associate_to_plural", { params: { - attribute: useTrans("validation.custom.category", { choice: 2 }), + attribute: useTrans( + "models.classes.news-category", + { choice: 2 }, + ), }, - choice: 2 + choice: 2, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} multiple={true} name="categories" required={false} variant="inverted" placeholder={str( - useTrans("back.news.categories.placeholder") - ).ucFirst().value()} + useTrans("back.news.categories.placeholder"), + ) + .ucFirst() + .value()} singleLine={true} setData={setData} defaultValue={data.categories} @@ -436,11 +528,11 @@ export default function Form({ />
    - + })} + />
    ); diff --git a/resources/ts/back/Pages/News/Index.tsx b/resources/ts/back/Pages/News/Index.tsx index 82ce6a26..afb4bb83 100644 --- a/resources/ts/back/Pages/News/Index.tsx +++ b/resources/ts/back/Pages/News/Index.tsx @@ -1,6 +1,8 @@ // * Packages import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; +import { AlertCircle, Archive, ArrowLeft, Plus } from "lucide-react"; +import { Row } from "@tanstack/react-table"; // * Components shadcn import { Badge } from "@/components/ui/badge"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; @@ -11,6 +13,7 @@ import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import InputError from "@/back/Components/InputError"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import NewsStatusBadge from "@/back/Components/NewsStatusBadge"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; import { @@ -18,13 +21,9 @@ import { AuthProp, NewsModel, Resource, - TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { Row } from "@tanstack/react-table"; -import { AlertCircle, Archive, ArrowLeft, Plus } from "lucide-react"; -import NewsStatusBadge from "@/back/Components/NewsStatusBadge"; import { renderTranslationCell } from "@/lib/translationCellFallback"; export default function Index({ diff --git a/resources/ts/back/Pages/News/Show.tsx b/resources/ts/back/Pages/News/Show.tsx index 92106c86..9de025de 100644 --- a/resources/ts/back/Pages/News/Show.tsx +++ b/resources/ts/back/Pages/News/Show.tsx @@ -26,71 +26,101 @@ import NewsCategoriesBadge from "@/back/Components/NewsCategoriesBadge"; import useLocale from "@/store/use-locale-store"; import { renderTranslationCell } from "@/lib/translationCellFallback"; -export default function Show({ data, modelName }: { data: SingleResource, modelName: string }) { +export default function Show({ + data, + modelName, +}: { + data: SingleResource; + modelName: string; +}) { const { auth, appEnv } = usePage().props as unknown as { auth: AuthProp; appEnv: AppEnv; }; const { viewAny } = auth.policies.news; const newsModel = data.data as NewsModel; - const actionModels = [ - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; + const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; const transTitle = useTrans("crud.helpers.visualization_model", { - params: { model: useTrans(`models.classes.${modelName}`, { choice: 1 }) }, + params: { + model: useTrans(`models.classes.${modelName}`, { choice: 1 }), + }, }); const columns = [ { accessorKey: "seo_title", - header: str(useTrans("validation.custom.seo.title")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.custom.seo.title")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "seo_description", - header: str(useTrans("validation.custom.seo.description")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.custom.seo.description")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "title", - header: str(useTrans("validation.attributes.title")).ucFirst().value(), + header: str(useTrans("validation.attributes.title")) + .ucFirst() + .value(), cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } + return renderTranslationCell(value); + }, }, { accessorKey: "slug", header: str(useTrans("validation.custom.slug")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "content", - header: str(useTrans("validation.attributes.content")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.attributes.content")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "status", header: str(useTrans("validation.custom.status")).ucFirst().value(), cell: ({ value }: { value: string }) => { - return ( - - ) + return ; }, }, { accessorKey: "categories", - header: str(useTrans("validation.custom.category", { choice: 2 })).ucFirst().value(), + header: str(useTrans("models.classes.news-category", { choice: 2 })) + .ucFirst() + .value(), cell: ({ value }: { value?: NewsCategoryModel[] }) => { if (!value || value.length === 0) return null; return ( @@ -100,12 +130,13 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN ))}
    ); - } - + }, }, { accessorKey: "tags", - header: str(useTrans("validation.custom.news.tag", { choice: 2 })).ucFirst().value(), + header: str(useTrans("models.classes.news-tag", { choice: 2 })) + .ucFirst() + .value(), cell: ({ value }: { value?: NewsCategoryModel[] }) => { if (!value || value.length === 0) return null; return ( @@ -115,63 +146,90 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN ))}
    ); - } - + }, }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => { return ( {useFormatedDate(value)} - ) + ); }, }, { accessorKey: "picture", - header: str(useTrans("validation.attributes.image")).ucFirst().value(), + header: str(useTrans("validation.attributes.image")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( ), }, { accessorKey: "picture_alt", - header: str(useTrans("validation.custom.image_alt")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.custom.image_alt")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "picture_title", - header: str(useTrans("validation.custom.image_title")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

    {useTrans('back.table_not_known')}

    ), + header: str(useTrans("validation.custom.image_title")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ), }, { accessorKey: "published_at", - header: str(useTrans("validation.custom.published_at")).ucFirst().value(), + header: str(useTrans("validation.custom.published_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value, useLocale.use.timezone(), true)} + + {useFormatedDate(value, useLocale.use.timezone(), true)} + ), }, { accessorKey: "unpublished_at", - header: str(useTrans("validation.custom.unpublished_at")).ucFirst().value(), + header: str(useTrans("validation.custom.unpublished_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.deleted_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), @@ -179,22 +237,23 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN ]; const beforeNode = () => { - return viewAny && ( -
    - } - tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } - /> -
    + return ( + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) ); }; return ( - + ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) + return renderTranslationCell(row.getValue("name")); }, }, { accessorKey: "news", header: () => ( -

    {str(useTrans(`validation.custom.documentTag.documents`)).ucFirst().value()}

    +

    + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    ), cell: ({ row }: { row: Row }) => (
    @@ -79,7 +92,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -90,36 +105,58 @@ export default function Index({ ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
    - } - tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } - /> -
    + return ( + isArchiveRoute && + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
    - {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } - variant="outline" - />} - {create && } - tooltipContent={

    {useTrans("back.crud_add_entry")}

    } - />} -
    + return ( + !isArchiveRoute && ( +
    + {viewTrash && ( + } + tooltipContent={ +

    {useTrans("back.crud_access_trash")}

    + } + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )} +
    + ) ); }; @@ -131,14 +168,11 @@ export default function Index({ > {isArchiveRoute && ( <> - + - {useTrans('back.warning')} + {useTrans("back.warning")} -

    {useTrans('back.warning_trash')}

    +

    {useTrans("back.warning_trash")}

    diff --git a/resources/ts/back/Pages/NewsTag/Index.tsx b/resources/ts/back/Pages/NewsTag/Index.tsx index 6e12e000..5905e1ee 100644 --- a/resources/ts/back/Pages/NewsTag/Index.tsx +++ b/resources/ts/back/Pages/NewsTag/Index.tsx @@ -1,11 +1,20 @@ // * Packages import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; -import { AlertCircleIcon, ArchiveIcon, ArrowLeftIcon, Plus } from "lucide-react"; +import { + AlertCircleIcon, + ArchiveIcon, + ArrowLeftIcon, + Plus, +} from "lucide-react"; import { Row } from "@tanstack/react-table"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; @@ -16,11 +25,7 @@ import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithT import InputError from "@/back/Components/InputError"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; -import { - AuthProp, - NewsTagModel, - Resource, -} from "@/back/types/global"; +import { AuthProp, NewsTagModel, Resource } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import { renderTranslationCell } from "@/lib/translationCellFallback"; @@ -29,7 +34,7 @@ export default function Index({ newsTagModels, search, searchFields, - modelName + modelName, }: { newsTagModels: Resource; search: string; @@ -41,35 +46,36 @@ export default function Index({ }; const { viewAny, viewTrash, create } = auth.policies.newsTags; const isArchiveRoute = route().current(`back.${modelName}.trash`); - const actionModels = isArchiveRoute ? [ - Views.RESTORATION, - Views.FORCEDELETION, - ] : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; const columns = [ { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) + return renderTranslationCell(row.getValue("name")); }, }, { accessorKey: "color", header: ({ column }: { column: { id: string } }) => ( ), @@ -77,19 +83,35 @@ export default function Index({ return ( -
    +
    {row.getValue("color")}
    - ) + ); }, }, { accessorKey: "news", header: () => ( -

    {str(useTrans(`validation.custom.documentTag.documents`)).ucFirst().value()}

    +

    + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    ), cell: ({ row }: { row: Row }) => (
    @@ -101,7 +123,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -112,36 +136,58 @@ export default function Index({ ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
    - } - tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } - /> -
    + return ( + isArchiveRoute && + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
    - {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } - variant="outline" - />} - {create && } - tooltipContent={

    {useTrans("back.crud_add_entry")}

    } - />} -
    + return ( + !isArchiveRoute && ( +
    + {viewTrash && ( + } + tooltipContent={ +

    {useTrans("back.crud_access_trash")}

    + } + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )} +
    + ) ); }; @@ -153,14 +199,11 @@ export default function Index({ > {isArchiveRoute && ( <> - + - {useTrans('back.warning')} + {useTrans("back.warning")} -

    {useTrans('back.warning_trash')}

    +

    {useTrans("back.warning_trash")}

    From e782cad7898baa41b56dbccf5cccb1bb0ade47bd Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 20 Jan 2026 15:26:39 +0100 Subject: [PATCH 06/19] fix: :bug: change of a bad attribute on dynamic page --- app/Models/DynamicPage.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index 0e2bd95b..c2df355b 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -253,7 +253,7 @@ class DynamicPage extends Model implements TranslatableModel { $oldDynamicPageRoot = self::getModelsCached()->where('id', '!=', $model->getKey())->where('isRoot', true)->first(); if ($oldDynamicPageRoot) { - $oldDynamicPageRoot->publish = PageStatusEnum::unpublished; + $oldDynamicPageRoot->status = PageStatusEnum::unpublished; $oldDynamicPageRoot->isRoot = false; $oldDynamicPageRoot->saveQuietly(); } From 2e568afeaf1f6ee0a3208c7c7a6f01645159bf6e Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 20 Jan 2026 15:28:04 +0100 Subject: [PATCH 07/19] fix: :children_crossing: add missing breacrumbs on news tags --- routes/breadcrumbs-back.php | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/routes/breadcrumbs-back.php b/routes/breadcrumbs-back.php index 1c1afb03..84f39e07 100644 --- a/routes/breadcrumbs-back.php +++ b/routes/breadcrumbs-back.php @@ -132,7 +132,7 @@ Breadcrumbs::for('back.news.trash', function (Generator $trail) { $trail->push(Str::ucfirst(trans('back.archives'))); }); -// * NEWS CATEGORY +// * NEWS CATEGORY. Breadcrumbs::for('back.news-categories.index', function (Generator $trail) { $trail->parent('back.news.index'); $trail->push( @@ -161,7 +161,36 @@ Breadcrumbs::for('back.news-categories.trash', function (Generator $trail) { $trail->push(Str::ucfirst(trans('crud.actions.archive'))); }); -// * ACTIVITY LOGS +// * NEWS TAGS. +Breadcrumbs::for('back.news-tags.index', function (Generator $trail) { + $trail->parent('back.news.index'); + $trail->push( + Str::ucfirst(trans_choice('models.classes.news-tag', \INF)), + route('back.news-tags.index'), + ); +}); +Breadcrumbs::for('back.news-tags.create', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.create')), route('back.news-tags.create')); +}); +Breadcrumbs::for('back.news-tags.edit', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.edit')), route('back.news-tags.edit', [ + 'news_tag' => request()->news_tag + ])); +}); +Breadcrumbs::for('back.news-tags.show', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.visualize')), route('back.news-tags.show', [ + 'news_tag' => request()->news_tag + ])); +}); +Breadcrumbs::for('back.news-tags.trash', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.archive'))); +}); + +// * ACTIVITY LOGS. Breadcrumbs::for('back.activity-logs.index', function (Generator $trail) { $trail->parent('back.dashboard.index'); $trail->push( @@ -174,7 +203,7 @@ Breadcrumbs::for('back.activity-logs.show', function (Generator $trail) { $trail->push(Str::ucfirst(trans('crud.actions.visualize'))); }); -// * CONTACT COUNT +// * CONTACT COUNT. Breadcrumbs::for('back.contact-counts.index', function (Generator $trail) { $trail->parent('back.dashboard.index'); $trail->push( From b3dfc851804cc2e6553e57966444f2b257c2566e Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 20 Jan 2026 15:28:57 +0100 Subject: [PATCH 08/19] fix: :card_file_box: some changes related to database comments --- ...6_01_14_125607_populate_document_table.php | 322 +++++++++--------- ...026_01_20_120146_clean_comments_tables.php | 312 +++++++++++++++++ 2 files changed, 473 insertions(+), 161 deletions(-) create mode 100644 database/migrations/2026_01_20_120146_clean_comments_tables.php diff --git a/database/migrations/2026_01_14_125607_populate_document_table.php b/database/migrations/2026_01_14_125607_populate_document_table.php index f4b1ff15..2e4e815b 100644 --- a/database/migrations/2026_01_14_125607_populate_document_table.php +++ b/database/migrations/2026_01_14_125607_populate_document_table.php @@ -14,196 +14,198 @@ return new class extends Migration { /** * Run the migrations. + * + * @return void */ public function up(): void { - app()->setLocale('fr'); + $jsonPath = Storage::disk('local')->get('document.json'); + if (file_exists($jsonPath)) { + app()->setLocale('fr'); - $json = Storage::disk('local')->get('document.json'); - $data = json_decode($json, true); - $logFile = public_path('documents-error.log'); - file_put_contents($logFile, ''); - $groups = []; + $json = Storage::disk('local')->get('document.json'); + $data = json_decode($json, true); + $logFile = public_path('documents-error.log'); + file_put_contents($logFile, ''); + $groups = []; - foreach ($data['documents'] as $doc) { - $trid = $doc['translation_group_id']; - $lang = $doc['language']; + foreach ($data['documents'] as $doc) { + $trid = $doc['translation_group_id']; + $lang = $doc['language']; - if (!isset($groups[$trid])) { - $groups[$trid] = []; - } - - // Si une langue est déjà présente : doublon de langue dans un groupe - if (isset($groups[$trid][$lang])) { - file_put_contents( - $logFile, - "❌ Doublon de langue '$lang' pour TRID $trid. IDs : " . - $groups[$trid][$lang]['ID'] . " et " . $doc['ID'] . "\n", - FILE_APPEND - ); - } - $groups[$trid][$lang] = $doc; - // Vérification n°1 : plus de 2 entrées dans un TRID - if (count($groups[$trid]) > 2) { - $ids = array_column($groups[$trid], 'ID'); - file_put_contents( - $logFile, - "❌ Plus de 2 entrées pour TRID $trid. IDs : " . implode(',', $ids) . "\n", - FILE_APPEND - ); - } - - // Vérification n°2 : si on a 2 entrées mais même langue - if (count($groups[$trid]) === 2) { - $langs = array_keys($groups[$trid]); - if ($langs[0] === $langs[1]) { - - $ids = array_column($groups[$trid], 'ID'); + if (!isset($groups[$trid])) { + $groups[$trid] = []; + } + // Si une langue est déjà présente : doublon de langue dans un groupe. + if (isset($groups[$trid][$lang])) { file_put_contents( $logFile, - "❌ 2 entrées mais même langue '$langs[0]' pour TRID $trid. IDs : " - . implode(',', $ids) . "\n", + "❌ Doublon de langue '$lang' pour TRID $trid. IDs : " . + $groups[$trid][$lang]['ID'] . " et " . $doc['ID'] . "\n", FILE_APPEND ); } - } - } - - foreach ($groups as $trid => $langs) { - - if (!isset($langs['fr'])) { - // Cas anormal : pas de FR → log - file_put_contents( - $logFile, - "❌ Pas de FR pour TRID $trid. IDs trouvés : " . json_encode(array_column($langs, 'ID')) . "\n", - FILE_APPEND - ); - // continue; - } - - - $financeDocument = new Document(); - $hasFrCats = false; - $hasFrTags = false; - $hasPublished_at = false; - $hasStatus = false; - $hasFrExercice = false; - // ------------------------------ - // 2) Enregistrer la version FR - // ------------------------------ - if (isset($langs['fr'])) { - $fr = $langs['fr']; - $hasFrExercice = true; - $financeDocument->exercice = $this->getExerciceEnumFromOldValues($fr, 'fr'); - $financeDocument->name = $fr['post_title']; - $financeDocument->published_at = $fr['post_date']; - $hasPublished_at = true; - $hasStatus = true; - - - - - $financeDocument->status = $fr['post_status'] === "publish" ? - DocumentStatusEnum::published->value : - DocumentStatusEnum::unpublished->value; - $financeDocument->path = FileHelper::storeFile($financeDocument, $this->replaceUrl($fr)); - - if (!$this->replaceUrl($fr)) { - $financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($fr['post_content']); - $financeDocument->is_issuu = true; + $groups[$trid][$lang] = $doc; + // Vérification n°1 : plus de 2 entrées dans un TRID. + if (count($groups[$trid]) > 2) { + $ids = array_column($groups[$trid], 'ID'); + file_put_contents( + $logFile, + "❌ Plus de 2 entrées pour TRID $trid. IDs : " . implode(',', $ids) . "\n", + FILE_APPEND + ); } - // jusque la ça enregistre un element - // il faut maintenant récupérer la valeur de translation_group_id - // si un autre élément dans la liste à le même translation_group_id vérifier que son language est bien "en" - // si c'est le cas alors on app()->setLocale('en') - // puis on réenregistre les nouvelles valeurs translatable : - // $financeDocument->name = $doc['post_title']; - // $financeDocument->path = $localeUrl; - // et on save - // si le langage est autre chose on log dans un fichier (dans public/documents-error.log) - // dans le fichier de log on va écrire à chaque fois l'id du post "ID" fr + en s'il y a + celui qui serait un autre fr, en ou autre pour que je puisse les retrouver - // et on notera plus ou moins l'erreur dont il s'agit - $financeDocument->saveQuietly(); - $cats = $this->findCategoryByOldSlug($fr, 'fr'); - if ($cats) { - $financeDocument->categories()->sync($cats); - $hasFrCats = true; - } - $tags = $this->findTagsByOldSlug($fr, 'fr'); - if ($tags) { - $financeDocument->tags()->sync($tags); - $hasFrTags = true; + // Vérification n°2 : si on a 2 entrées mais même langue. + if (count($groups[$trid]) === 2) { + $langs = array_keys($groups[$trid]); + if ($langs[0] === $langs[1]) { + + $ids = array_column($groups[$trid], 'ID'); + + file_put_contents( + $logFile, + "❌ 2 entrées mais même langue '$langs[0]' pour TRID $trid. IDs : " + . implode(',', $ids) . "\n", + FILE_APPEND + ); + } } } - if (isset($langs['en'])) { - $en = $langs['en']; - app()->setLocale('en'); - if (!$hasPublished_at) { - $financeDocument->published_at = $en['post_date']; + foreach ($groups as $trid => $langs) { + + if (!isset($langs['fr'])) { + // Cas anormal : pas de FR → log. + file_put_contents( + $logFile, + "❌ Pas de FR pour TRID $trid. IDs trouvés : " . json_encode(array_column($langs, 'ID')) . "\n", + FILE_APPEND + ); + // continue; } - if (!$hasStatus) { - $financeDocument->status = $en['post_status'] === "publish" ? + + $financeDocument = new Document(); + $hasFrCats = false; + $hasFrTags = false; + $hasPublished_at = false; + $hasStatus = false; + $hasFrExercice = false; + // ------------------------------ + // 2) Enregistrer la version FR + // ------------------------------ + if (isset($langs['fr'])) { + $fr = $langs['fr']; + $hasFrExercice = true; + $financeDocument->exercice = $this->getExerciceEnumFromOldValues($fr, 'fr'); + $financeDocument->name = $fr['post_title']; + $financeDocument->published_at = $fr['post_date']; + $hasPublished_at = true; + $hasStatus = true; + + $financeDocument->status = $fr['post_status'] === "publish" ? DocumentStatusEnum::published->value : DocumentStatusEnum::unpublished->value; + $financeDocument->path = FileHelper::storeFile($financeDocument, $this->replaceUrl($fr)); + + if (!$this->replaceUrl($fr)) { + $financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($fr['post_content']); + $financeDocument->is_issuu = true; + } + // jusque la ça enregistre un element + // il faut maintenant récupérer la valeur de translation_group_id + // si un autre élément dans la liste à le même translation_group_id vérifier que son language est bien "en" + // si c'est le cas alors on app()->setLocale('en') + // puis on réenregistre les nouvelles valeurs translatable : + // $financeDocument->name = $doc['post_title']; + // $financeDocument->path = $localeUrl; + // et on save + // si le langage est autre chose on log dans un fichier (dans public/documents-error.log) + // dans le fichier de log on va écrire à chaque fois l'id du post "ID" fr + en s'il y a + celui qui serait un autre fr, en ou autre pour que je puisse les retrouver + // et on notera plus ou moins l'erreur dont il s'agit + $financeDocument->saveQuietly(); + + $cats = $this->findCategoryByOldSlug($fr, 'fr'); + if ($cats) { + $financeDocument->categories()->sync($cats); + $hasFrCats = true; + } + $tags = $this->findTagsByOldSlug($fr, 'fr'); + if ($tags) { + $financeDocument->tags()->sync($tags); + $hasFrTags = true; + } } - $financeDocument->name = $en['post_title']; + if (isset($langs['en'])) { + $en = $langs['en']; + app()->setLocale('en'); - if ($hasFrExercice) { - $financeDocument->exercice = $this->getExerciceEnumFromOldValues($en, 'en'); - } + if (!$hasPublished_at) { + $financeDocument->published_at = $en['post_date']; + } - $sourceUrl = $this->replaceUrl($en); + if (!$hasStatus) { + $financeDocument->status = $en['post_status'] === "publish" ? + DocumentStatusEnum::published->value : + DocumentStatusEnum::unpublished->value; + } + $financeDocument->name = $en['post_title']; - if (empty($sourceUrl)) { + if ($hasFrExercice) { + $financeDocument->exercice = $this->getExerciceEnumFromOldValues($en, 'en'); + } + + $sourceUrl = $this->replaceUrl($en); + + if (empty($sourceUrl)) { + file_put_contents( + $logFile, + "❌ URL EN vide — TRID $trid — ID {$en['ID']}\n", + FILE_APPEND + ); + } + + $financeDocument->path = FileHelper::storeFile($financeDocument, $sourceUrl); + if (!$this->replaceUrl($en)) { + $financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($en['post_content']); + $financeDocument->is_issuu = true; + } + + $financeDocument->saveQuietly(); + if (!$hasFrCats) { + $cats = $this->findCategoryByOldSlug($en, 'en'); + $financeDocument->categories()->sync($cats); + } + if (!$hasFrTags) { + $tags = $this->findTagsByOldSlug($fr, 'en'); + $financeDocument->tags()->sync($tags); + } + app()->setLocale('fr'); + } else { + // ------------------------------ + // 4) Cas : pas de traduction EN → log + // ------------------------------ + $id = isset($langs['fr']) ? $langs['fr']['ID'] : "inconnu"; file_put_contents( $logFile, - "❌ URL EN vide — TRID $trid — ID {$en['ID']}\n", + "⚠️ Pas de traduction EN pour TRID $trid. ID FR: {$id}\n", FILE_APPEND ); } - - $financeDocument->path = FileHelper::storeFile($financeDocument, $sourceUrl); - if (!$this->replaceUrl($en)) { - $financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($en['post_content']); - $financeDocument->is_issuu = true; - } - - $financeDocument->saveQuietly(); - if (!$hasFrCats) { - $cats = $this->findCategoryByOldSlug($en, 'en'); - $financeDocument->categories()->sync($cats); - } - if (!$hasFrTags) { - $tags = $this->findTagsByOldSlug($fr, 'en'); - $financeDocument->tags()->sync($tags); - } - app()->setLocale('fr'); - } else { // ------------------------------ - // 4) Cas : pas de traduction EN → log + // 5) Vérifier si langues inconnues // ------------------------------ - $id = isset($langs['fr']) ? $langs['fr']['ID'] : "inconnu"; - file_put_contents( - $logFile, - "⚠️ Pas de traduction EN pour TRID $trid. ID FR: {$id}\n", - FILE_APPEND - ); - } - // ------------------------------ - // 5) Vérifier si langues inconnues - // ------------------------------ - foreach ($langs as $langCode => $doc) { - if (!in_array($langCode, ['fr', 'en'])) { + foreach ($langs as $langCode => $doc) { + if (!in_array($langCode, ['fr', 'en'])) { - file_put_contents( - $logFile, - "⚠️ Langue inattendue '$langCode' pour TRID $trid. ID: {$doc['ID']}\n", - FILE_APPEND - ); + file_put_contents( + $logFile, + "⚠️ Langue inattendue '$langCode' pour TRID $trid. ID: {$doc['ID']}\n", + FILE_APPEND + ); + } } } } @@ -218,7 +220,6 @@ return new class extends Migration return null; } - private function findCategoryByOldSlug(mixed $doc, string $locale): array { if (empty($doc['category_slugs'])) { @@ -272,8 +273,6 @@ return new class extends Migration return null; } - - return collect(YearsEnum::cases()) ->first( fn(YearsEnum $year) => @@ -281,7 +280,6 @@ return new class extends Migration ); } - // SELECT // p.ID, // MAX(p.post_title) AS post_title, @@ -360,6 +358,8 @@ return new class extends Migration /** * Reverse the migrations. + * + * @return void */ public function down(): void { diff --git a/database/migrations/2026_01_20_120146_clean_comments_tables.php b/database/migrations/2026_01_20_120146_clean_comments_tables.php new file mode 100644 index 00000000..501a2f5e --- /dev/null +++ b/database/migrations/2026_01_20_120146_clean_comments_tables.php @@ -0,0 +1,312 @@ +id()->comment('Primary key of the company.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the company was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the company was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the company was deleted.')->change(); + }); + + Schema::table('company_activities', function (Blueprint $table) { + $table->id()->comment('Primary key of the company activity.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the company activity was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the company activity was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the company activity was deleted.')->change(); + }); + + Schema::table('company_sectors', function (Blueprint $table) { + $table->id()->comment('Primary key of the company sector.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the company sector was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the company sector was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the company sector was deleted.')->change(); + }); + + Schema::table('contact_counts', function (Blueprint $table) { + $table->id()->comment('Primary key of the counter.')->change(); + $table->integer('submissions')->comment('Form submission counter.')->default(0)->change(); + $table->unsignedTinyInteger('type')->comment('Contact form type.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the counter was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the counter was updated.')->change(); + }); + + Schema::table('documentables', function (Blueprint $table) { + $table->id()->comment('Primary key of the document relation.')->change(); + $table->unsignedBigInteger('document_id')->comment('Primary key of the document.')->change(); + $table->unsignedBigInteger('documentable_id')->comment('Primary key of the associated model.')->change(); + $table->string('documentable_type')->comment('Model associated.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the document relation was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the document relation was updated.')->change(); + }); + + Schema::table('documents', function (Blueprint $table) { + $table->id()->comment('Primary key of the document.')->change(); + $table->text('name')->comment('Name of the document.')->change(); + $table->text('path')->nullable()->comment('Path of the document.')->after('name')->change(); + $table->text('issuu_path')->nullable()->comment('Path of the issuu document.')->after('path')->change(); + $table->unsignedTinyInteger('exercice')->nullable()->comment('Exercice of the document.')->change(); + $table->unsignedTinyInteger('status')->comment('Status of the document.')->change(); + $table->boolean('is_issuu')->default(false)->comment('Is an issuu document or not.')->change(); + $table->timestamp('published_at')->nullable()->comment('Date on which the document relation was published.')->change(); + $table->timestamp('unpublished_at')->nullable()->comment('Date on which the document relation was unpublished.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the document relation was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the document relation was updated.')->change(); + }); + + Schema::table('document_categories', function (Blueprint $table) { + $table->id()->comment('Primary key of the document category.')->change(); + $table->text('name')->comment('Name of the document category.')->change(); + $table->text('slug')->comment('Slug of the document category.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the document category was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the document category was updated.')->change(); + }); + + Schema::table('document_tags', function (Blueprint $table) { + $table->id()->comment('Primary key of the document tag.')->change(); + $table->text('name')->comment('Name of the document tag.')->change(); + $table->text('slug')->comment('Slug of the document tag.')->change(); + $table->string('color')->default("#ff4e4e")->after('slug')->comment('Color of the document tag.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the document tag was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the document tag was updated.')->change(); + }); + + Schema::table('dynamic_pages', function (Blueprint $table) { + $table->id()->comment('Primary key of the dynamic page.')->change(); + $table->string('id_key')->nullable()->comment('Unique identification key of the dynamic page.')->change(); + $table->string('title')->comment('Title of the dynamic page.')->change(); + $table->string('slug')->unique()->comment('Slug of the dynamic page.')->change(); + $table->json('content')->nullable()->comment('Content of the dynamic page.')->change(); + $table->unsignedBigInteger('config_id')->nullable()->comment('Associated configuration.')->change(); + $table->unsignedBigInteger('page_id')->nullable()->comment('Associated page.')->change(); + $table->unsignedTinyInteger('status')->comment('Status of the dynamic page.')->change(); + $table->boolean('isLocked')->default(false)->comment('Locked status of the dynamic page.')->change(); + $table->boolean('isRoot')->default(false)->comment('Root status of the dynamic page.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the dynamic page was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the dynamic page was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the dynamic page was deleted.')->change(); + }); + + Schema::table('news', function (Blueprint $table) { + $table->id()->comment('Primary key of the news.')->change(); + $table->text('seo_title')->comment('SEO title of the news.')->change(); + $table->text('seo_description')->comment('SEO description of the news.')->change(); + $table->text('title')->comment('Title of the news.')->change(); + $table->string('picture')->comment('Picture of the news.')->change(); + $table->text('picture_alt')->comment('Alt attribute of the picture.')->change(); + $table->text('picture_title')->comment('Title attribute of the picture.')->change(); + $table->mediumText('content')->comment('Content of the news.')->change(); + $table->boolean('inverted')->default(false)->comment('Position of the content.')->change(); + $table->text('vimeo_id')->nullable()->comment('Vimeo id associated.')->change(); + $table->unsignedTinyInteger('status')->comment('Status of the news.')->change(); + $table->timestamp('published_at')->nullable()->comment('Date on which the news was published.')->change(); + $table->timestamp('unpublished_at')->nullable()->comment('Date on which the news was unpublished.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the news was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the news was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the news was deleted.')->after('updated_at')->change(); + }); + + Schema::table('newsables', function (Blueprint $table) { + $table->id()->comment('Primary key of the news relation.')->change(); + $table->unsignedBigInteger('news_id')->comment('Primary key of the news.')->change(); + $table->unsignedBigInteger('newsable_id')->comment('Primary key of the associated model.')->change(); + $table->string('newsable_type')->comment('Model associated.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the news relation was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the news relation was updated.')->change(); + }); + + Schema::table('news_categories', function (Blueprint $table) { + $table->id()->comment('Primary key of the news category.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the news category was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the news category was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the news category was deleted.')->change(); + }); + + Schema::table('news_tags', function (Blueprint $table) { + $table->id()->comment('Primary key of the news tag.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the news tag was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the news tag was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the news tag was deleted.')->after('updated_at')->change(); + }); + + Schema::table('page_configs', function (Blueprint $table) { + $table->id()->comment('Primary key of the configuration.')->change(); + $table->string('label')->comment('Label of the configuration.')->change(); + $table->string('view')->nullable()->comment('Specific view of the configuration.')->change(); + $table->json('config')->comment('Structured data of the configuration.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the configuration was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the configuration was updated.')->change(); + $table->timestamp('deleted_at')->nullable()->comment('Date on which the configuration was deleted.')->change(); + }); + + Schema::table('users', function (Blueprint $table) { + $table->id()->comment('Primary key of the user.')->change(); + $table->timestamp('created_at')->nullable()->comment('Date on which the user was created.')->change(); + $table->timestamp('updated_at')->nullable()->comment('Date on which the user was updated.')->change(); + $table->timestamp('last_connection')->nullable()->comment('Date on which the user was connected.')->change(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::table('companies', function (Blueprint $table) { + $table->id()->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->change(); + }); + + Schema::table('company_activities', function (Blueprint $table) { + $table->id()->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->change(); + }); + + Schema::table('company_sectors', function (Blueprint $table) { + $table->id()->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->change(); + }); + + Schema::table('contact_counts', function (Blueprint $table) { + $table->id()->change(); + $table->integer('submissions')->comment('How many contact form have been submitted')->default(0)->change(); + $table->unsignedTinyInteger('type')->comment('Enum du type de contact form')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + }); + + Schema::table('documentables', function (Blueprint $table) { + $table->id()->change(); + $table->unsignedBigInteger('document_id')->change(); + $table->unsignedBigInteger('documentable_id')->change(); + $table->string('documentable_type')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + }); + + Schema::table('documents', function (Blueprint $table) { + $table->id()->change(); + $table->text('name')->comment('Name of the file')->change(); + $table->unsignedTinyInteger('exercice')->nullable()->change(); + $table->unsignedTinyInteger('status')->comment('Status of the documents')->change(); + $table->text('path')->nullable()->comment('Path of the file')->after('status')->change(); + $table->boolean('is_issuu')->default(false)->comment('Is the document a Issuu preview')->change(); + $table->text('issuu_path')->nullable()->comment('Path of the file in issuu')->after('is_issuu')->change(); + $table->timestamp('published_at')->nullable()->comment('Document publishment date.')->change(); + $table->timestamp('unpublished_at')->nullable()->comment('Document unpublishment date.')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + }); + + Schema::table('document_categories', function (Blueprint $table) { + $table->id()->change(); + $table->text('name')->comment('Name of the category')->change(); + $table->text('slug')->comment('Slug of the category')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + }); + + Schema::table('document_tags', function (Blueprint $table) { + $table->id()->change(); + $table->text('name')->comment('Name of the tag')->change(); + $table->text('slug')->comment('Slug of the tag')->change(); + $table->string('color')->default("#ff4e4e")->after('slug')->comment('Color of the news category.')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + }); + + Schema::table('dynamic_pages', function (Blueprint $table) { + $table->id()->change(); + $table->string('id_key')->nullable()->comment('Page unique identification key.')->change(); + $table->string('title')->comment('Page title.')->change(); + $table->string('slug')->unique()->comment('Page slug.')->change(); + $table->json('content')->nullable()->comment('Page content.')->change(); + $table->unsignedBigInteger('config_id')->nullable()->comment('Page associated configuration.')->change(); + $table->unsignedBigInteger('page_id')->nullable()->comment('Page associated page.')->change(); + $table->unsignedTinyInteger('status')->comment('Page status.')->change(); + $table->boolean('isLocked')->default(false)->comment('Page locked status.')->change(); + $table->boolean('isRoot')->default(false)->comment('Page root status.')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->change(); + }); + + Schema::table('news', function (Blueprint $table) { + $table->id()->change(); + $table->text('seo_title')->comment('News seo title.')->change(); + $table->text('seo_description')->comment('News seo description.')->change(); + $table->text('title')->comment('News title.')->change(); + $table->string('picture')->comment('News picture.')->change(); + $table->text('picture_alt')->comment('Picture alt attribute.')->change(); + $table->text('picture_title')->comment('Picture title attribute.')->change(); + $table->mediumText('content')->comment('News content.')->change(); + $table->text('vimeo_id')->nullable()->comment('Vimeo id associated.')->change(); + $table->unsignedTinyInteger('status')->comment('News status.')->change(); + $table->boolean('inverted')->default(false)->comment('Content position.')->change(); + $table->timestamp('published_at')->nullable()->comment('News corporate publishment date.')->change(); + $table->timestamp('unpublished_at')->nullable()->comment('News corporate unpublishment date.')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->after('unpublished_at')->change(); + }); + + Schema::table('newsables', function (Blueprint $table) { + $table->id()->change(); + $table->unsignedBigInteger('news_id')->change(); + $table->unsignedBigInteger('newsable_id')->change(); + $table->string('newsable_type')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + }); + + Schema::table('news_categories', function (Blueprint $table) { + $table->id()->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->change(); + }); + + Schema::table('news_tags', function (Blueprint $table) { + $table->id()->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->after('updated_at')->change(); + }); + + Schema::table('page_configs', function (Blueprint $table) { + $table->id()->change(); + $table->string('label')->comment('Configuration label.')->change(); + $table->string('view')->nullable()->comment('Configuration view.')->change(); + $table->json('config')->comment('Configuration details.')->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('deleted_at')->nullable()->change(); + }); + + Schema::table('users', function (Blueprint $table) { + $table->id()->change(); + $table->timestamp('created_at')->nullable()->change(); + $table->timestamp('updated_at')->nullable()->change(); + $table->timestamp('last_connection')->nullable()->change(); + }); + } +}; From 4015b6a20f86132b0c28ceb2697b79596da61205 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 20 Jan 2026 15:05:40 +0100 Subject: [PATCH 09/19] =?UTF-8?q?fix:=20=F0=9F=9A=9A=20move=20resources=20?= =?UTF-8?q?components=20in=20folders?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AssociatedDocumentList.tsx | 12 +++++++----- .../{ => Documents}/DocumentExerciceBadge.tsx | 0 .../DocumentFinanceTagBadge.tsx | 2 +- .../{ => Documents}/DocumentStatusBadge.tsx | 0 .../ts/back/Components/FieldsetWrapper.tsx | 2 +- .../{ => News}/AssociatedNewsList.tsx | 19 +++++++++++-------- .../{ => News}/NewsCategoriesBadge.tsx | 6 ++++-- .../Components/{ => News}/NewsStatusBadge.tsx | 0 resources/ts/back/Pages/Document/Index.tsx | 4 ++-- resources/ts/back/Pages/Document/Show.tsx | 6 +++--- .../ts/back/Pages/DocumentCategory/Show.tsx | 2 +- resources/ts/back/Pages/DocumentTag/Show.tsx | 2 +- resources/ts/back/Pages/News/Index.tsx | 2 +- resources/ts/back/Pages/News/Show.tsx | 4 ++-- resources/ts/back/Pages/NewsCategory/Show.tsx | 2 +- resources/ts/back/Pages/NewsTag/Show.tsx | 2 +- resources/ts/lib/filters.tsx | 2 ++ 17 files changed, 38 insertions(+), 29 deletions(-) rename resources/ts/back/Components/{ => Documents}/AssociatedDocumentList.tsx (94%) rename resources/ts/back/Components/{ => Documents}/DocumentExerciceBadge.tsx (100%) rename resources/ts/back/Components/{ => Documents}/DocumentFinanceTagBadge.tsx (92%) rename resources/ts/back/Components/{ => Documents}/DocumentStatusBadge.tsx (100%) rename resources/ts/back/Components/{ => News}/AssociatedNewsList.tsx (88%) rename resources/ts/back/Components/{ => News}/NewsCategoriesBadge.tsx (84%) rename resources/ts/back/Components/{ => News}/NewsStatusBadge.tsx (100%) diff --git a/resources/ts/back/Components/AssociatedDocumentList.tsx b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx similarity index 94% rename from resources/ts/back/Components/AssociatedDocumentList.tsx rename to resources/ts/back/Components/Documents/AssociatedDocumentList.tsx index 00799987..915e85b4 100644 --- a/resources/ts/back/Components/AssociatedDocumentList.tsx +++ b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx @@ -1,15 +1,17 @@ +// * Packages +import { usePage } from "@inertiajs/react"; +import { Row } from "@tanstack/react-table"; +// * Other import str from "@/hooks/use-string"; -import DataTable from "./Table/DataTable"; +import DataTable from "@/back/Components/Table/DataTable"; import useTrans from "@/hooks/use-translations"; -import DataTableFilterButton from "./Table/DataTableFilterButton"; +import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import { AppEnv, DocumentModel, Resource, TranslationField, -} from "../types/global"; -import { Row } from "@tanstack/react-table"; -import { usePage } from "@inertiajs/react"; +} from "@/back/types/global"; import { Views } from "@/lib/utils"; import { renderTranslationCell } from "@/lib/translationCellFallback"; diff --git a/resources/ts/back/Components/DocumentExerciceBadge.tsx b/resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx similarity index 100% rename from resources/ts/back/Components/DocumentExerciceBadge.tsx rename to resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx diff --git a/resources/ts/back/Components/DocumentFinanceTagBadge.tsx b/resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx similarity index 92% rename from resources/ts/back/Components/DocumentFinanceTagBadge.tsx rename to resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx index b0b9183b..14db2ed7 100644 --- a/resources/ts/back/Components/DocumentFinanceTagBadge.tsx +++ b/resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx @@ -1,6 +1,6 @@ +// * Components shadcn import { Badge } from "@/components/ui/badge"; - type DocumentFinanceTagBadgeProps = { value: string; }; diff --git a/resources/ts/back/Components/DocumentStatusBadge.tsx b/resources/ts/back/Components/Documents/DocumentStatusBadge.tsx similarity index 100% rename from resources/ts/back/Components/DocumentStatusBadge.tsx rename to resources/ts/back/Components/Documents/DocumentStatusBadge.tsx diff --git a/resources/ts/back/Components/FieldsetWrapper.tsx b/resources/ts/back/Components/FieldsetWrapper.tsx index 7a7826f6..33f58f29 100644 --- a/resources/ts/back/Components/FieldsetWrapper.tsx +++ b/resources/ts/back/Components/FieldsetWrapper.tsx @@ -1,4 +1,4 @@ -// * Components shadcn +// * Packages import { ReactNode } from "react"; // * Components shadcn import { diff --git a/resources/ts/back/Components/AssociatedNewsList.tsx b/resources/ts/back/Components/News/AssociatedNewsList.tsx similarity index 88% rename from resources/ts/back/Components/AssociatedNewsList.tsx rename to resources/ts/back/Components/News/AssociatedNewsList.tsx index 4ad48a7e..53c3b7f0 100644 --- a/resources/ts/back/Components/AssociatedNewsList.tsx +++ b/resources/ts/back/Components/News/AssociatedNewsList.tsx @@ -1,15 +1,18 @@ -import str from "@/hooks/use-string"; -import DataTable from "./Table/DataTable"; -import useTrans from "@/hooks/use-translations"; -import DataTableFilterButton from "./Table/DataTableFilterButton"; -import { AppEnv, NewsModel, Resource, TranslationField } from "../types/global"; +// * Packages import { Row } from "@tanstack/react-table"; import { usePage } from "@inertiajs/react"; +// * Components shadcn +import { Badge } from "@/components/ui/badge"; +// * Other +import DataTable from "@/back/Components/Table/DataTable" +import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; +import { AppEnv, NewsModel, Resource } from "@/back/types/global"; +import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; +import { renderTranslationCell } from "@/lib/translationCellFallback"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; -import { Badge } from "@/components/ui/badge"; -import NewsStatusBadge from "./NewsStatusBadge"; -import { renderTranslationCell } from "@/lib/translationCellFallback"; +import useTrans from "@/hooks/use-translations" +import str from "@/hooks/use-string" interface Props { news: Resource; diff --git a/resources/ts/back/Components/NewsCategoriesBadge.tsx b/resources/ts/back/Components/News/NewsCategoriesBadge.tsx similarity index 84% rename from resources/ts/back/Components/NewsCategoriesBadge.tsx rename to resources/ts/back/Components/News/NewsCategoriesBadge.tsx index 2299f06d..7bc93fe4 100644 --- a/resources/ts/back/Components/NewsCategoriesBadge.tsx +++ b/resources/ts/back/Components/News/NewsCategoriesBadge.tsx @@ -1,7 +1,9 @@ +// * Packages +import { usePage } from "@inertiajs/react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { AppEnv, TranslationField } from "../types/global"; -import { usePage } from "@inertiajs/react"; +// * Other +import { AppEnv, TranslationField } from "@/back/types/global"; type NewsCategoriesBadgeProps = { value: TranslationField | string; diff --git a/resources/ts/back/Components/NewsStatusBadge.tsx b/resources/ts/back/Components/News/NewsStatusBadge.tsx similarity index 100% rename from resources/ts/back/Components/NewsStatusBadge.tsx rename to resources/ts/back/Components/News/NewsStatusBadge.tsx diff --git a/resources/ts/back/Pages/Document/Index.tsx b/resources/ts/back/Pages/Document/Index.tsx index ee15ca2b..237aa4bd 100644 --- a/resources/ts/back/Pages/Document/Index.tsx +++ b/resources/ts/back/Pages/Document/Index.tsx @@ -17,8 +17,8 @@ import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import ButtonTrigger from "@/back/Pages/Document/Actions/ButtonTrigger"; -import DocumentStatusBadge from "@/back/Components/DocumentStatusBadge"; -import DocumentFinanceTagBadge from "@/back/Components/DocumentFinanceTagBadge"; +import DocumentStatusBadge from "@/back/Components/Documents/DocumentStatusBadge"; +import DocumentFinanceTagBadge from "@/back/Components/Documents/DocumentFinanceTagBadge"; import { cn, Views } from "@/lib/utils"; import { renderTranslationCell } from "@/lib/translationCellFallback"; import { useFormatedDate } from "@/hooks/use-formated-value"; diff --git a/resources/ts/back/Pages/Document/Show.tsx b/resources/ts/back/Pages/Document/Show.tsx index 8f510b0f..665e8bb2 100644 --- a/resources/ts/back/Pages/Document/Show.tsx +++ b/resources/ts/back/Pages/Document/Show.tsx @@ -23,9 +23,9 @@ import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; import useLocale from "@/store/use-locale-store"; -import DocumentStatusBadge from "@/back/Components/DocumentStatusBadge"; -import DocumentFinanceTagBadge from "@/back/Components/DocumentFinanceTagBadge"; -import YearsEnumeBadge from "@/back/Components/DocumentExerciceBadge"; +import DocumentStatusBadge from "@/back/Components/Documents/DocumentStatusBadge"; +import DocumentFinanceTagBadge from "@/back/Components/Documents/DocumentFinanceTagBadge"; +import YearsEnumeBadge from "@/back/Components/Documents/DocumentExerciceBadge"; export default function Show({ data, diff --git a/resources/ts/back/Pages/DocumentCategory/Show.tsx b/resources/ts/back/Pages/DocumentCategory/Show.tsx index 3acc0264..84909f4e 100644 --- a/resources/ts/back/Pages/DocumentCategory/Show.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Show.tsx @@ -21,7 +21,7 @@ import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; -import AssociatedDocumentList from "@/back/Components/AssociatedDocumentList"; +import AssociatedDocumentList from "@/back/Components/Documents/AssociatedDocumentList"; import { renderTranslationCell } from "@/lib/translationCellFallback"; diff --git a/resources/ts/back/Pages/DocumentTag/Show.tsx b/resources/ts/back/Pages/DocumentTag/Show.tsx index 4ab9a918..7651ebbe 100644 --- a/resources/ts/back/Pages/DocumentTag/Show.tsx +++ b/resources/ts/back/Pages/DocumentTag/Show.tsx @@ -22,7 +22,7 @@ import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; -import AssociatedDocumentList from "@/back/Components/AssociatedDocumentList"; +import AssociatedDocumentList from "@/back/Components/Documents/AssociatedDocumentList"; import { renderTranslationCell } from "@/lib/translationCellFallback"; export default function Show({ diff --git a/resources/ts/back/Pages/News/Index.tsx b/resources/ts/back/Pages/News/Index.tsx index afb4bb83..f6f821c0 100644 --- a/resources/ts/back/Pages/News/Index.tsx +++ b/resources/ts/back/Pages/News/Index.tsx @@ -13,7 +13,7 @@ import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import InputError from "@/back/Components/InputError"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import NewsStatusBadge from "@/back/Components/NewsStatusBadge"; +import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; import { diff --git a/resources/ts/back/Pages/News/Show.tsx b/resources/ts/back/Pages/News/Show.tsx index 9de025de..c00640b9 100644 --- a/resources/ts/back/Pages/News/Show.tsx +++ b/resources/ts/back/Pages/News/Show.tsx @@ -21,8 +21,8 @@ import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; -import NewsStatusBadge from "@/back/Components/NewsStatusBadge"; -import NewsCategoriesBadge from "@/back/Components/NewsCategoriesBadge"; +import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; +import NewsCategoriesBadge from "@/back/Components/News/NewsCategoriesBadge"; import useLocale from "@/store/use-locale-store"; import { renderTranslationCell } from "@/lib/translationCellFallback"; diff --git a/resources/ts/back/Pages/NewsCategory/Show.tsx b/resources/ts/back/Pages/NewsCategory/Show.tsx index fe159aa9..7f075b82 100644 --- a/resources/ts/back/Pages/NewsCategory/Show.tsx +++ b/resources/ts/back/Pages/NewsCategory/Show.tsx @@ -21,7 +21,7 @@ import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; -import AssociatedNewsList from "@/back/Components/AssociatedNewsList"; +import AssociatedNewsList from "@/back/Components/News/AssociatedNewsList"; import { renderTranslationCell } from "@/lib/translationCellFallback"; diff --git a/resources/ts/back/Pages/NewsTag/Show.tsx b/resources/ts/back/Pages/NewsTag/Show.tsx index 2713aac3..893e99c6 100644 --- a/resources/ts/back/Pages/NewsTag/Show.tsx +++ b/resources/ts/back/Pages/NewsTag/Show.tsx @@ -22,7 +22,7 @@ import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -import AssociatedNewsList from "@/back/Components/AssociatedNewsList"; +import AssociatedNewsList from "@/back/Components/News/AssociatedNewsList"; import { renderTranslationCell } from "@/lib/translationCellFallback"; diff --git a/resources/ts/lib/filters.tsx b/resources/ts/lib/filters.tsx index 0d97afad..51d92506 100644 --- a/resources/ts/lib/filters.tsx +++ b/resources/ts/lib/filters.tsx @@ -1,3 +1,4 @@ +// * Packages import { router } from "@inertiajs/react"; import { route } from "ziggy-js"; @@ -9,6 +10,7 @@ type RouterFiltersProps = { } export const addFilterToUrl = (props: RouterFiltersProps) => { const { modelName, params } = props; + return router.visit(route(`back.${modelName}.index`), { method: "get", data: { From 8243dfe4ccbf8431b6fd1778f926277d83cbf043 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Wed, 21 Jan 2026 12:31:07 +0100 Subject: [PATCH 10/19] fix: :art: add SoftDeletes to models and improve accessibility for relations --- .../Back/CompanyActivityController.php | 5 +- .../Controllers/Back/CompanyController.php | 2 +- .../Back/CompanySectorController.php | 5 +- .../Back/DocumentCategoryController.php | 44 +++- .../Back/DocumentTagController.php | 45 +++- .../Back/NewsCategoryController.php | 3 +- .../Controllers/Back/NewsTagController.php | 3 +- app/Http/Middleware/HandleInertiaRequests.php | 10 +- app/Models/CompanyActivity.php | 21 ++ app/Models/CompanySector.php | 21 ++ app/Models/DocumentCategory.php | 7 +- app/Models/DocumentTag.php | 15 +- app/Models/NewsTag.php | 5 +- app/Policies/DocumentCategoryPolicy.php | 23 +- app/Policies/DocumentTagPolicy.php | 23 +- ...elete_to_documents_tags_and_categories.php | 38 ++++ lang/en/back.php | 3 +- lang/en/models.php | 2 +- lang/fr/back.php | 5 +- .../Components/AssociatedCompaniesList.tsx | 114 ++++++++++ .../Documents/AssociatedDocumentList.tsx | 4 +- .../Components/News/AssociatedNewsList.tsx | 4 +- .../ts/back/Components/SoftdeleteWarning.tsx | 25 +++ .../back/Components/Table/DataTableSearch.tsx | 48 ++-- resources/ts/back/Pages/Companies/Index.tsx | 207 ++++++++++++------ resources/ts/back/Pages/Companies/Show.tsx | 60 ++++- .../ts/back/Pages/CompanyActivities/Index.tsx | 42 ++-- .../ts/back/Pages/CompanyActivities/Show.tsx | 8 +- .../ts/back/Pages/CompanySectors/Index.tsx | 38 ++-- .../ts/back/Pages/CompanySectors/Show.tsx | 5 +- resources/ts/back/Pages/Document/Index.tsx | 120 +++++++--- .../ts/back/Pages/DocumentCategory/Edit.tsx | 9 +- .../ts/back/Pages/DocumentCategory/Form.tsx | 4 +- .../ts/back/Pages/DocumentCategory/Index.tsx | 76 +++++-- resources/ts/back/Pages/DocumentTag/Edit.tsx | 9 +- resources/ts/back/Pages/DocumentTag/Index.tsx | 83 +++++-- .../ts/back/Pages/DynamicPages/Index.tsx | 26 +-- resources/ts/back/Pages/News/Index.tsx | 55 ++--- .../ts/back/Pages/NewsCategory/Index.tsx | 23 +- resources/ts/back/Pages/NewsTag/Index.tsx | 29 +-- resources/ts/back/Pages/PageConfigs/Index.tsx | 27 +-- resources/ts/back/types/global.d.ts | 2 + resources/ts/lib/translationCellFallback.tsx | 4 +- routes/breadcrumbs-back.php | 8 + routes/web-back.php | 23 +- 45 files changed, 976 insertions(+), 357 deletions(-) create mode 100644 database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php create mode 100644 resources/ts/back/Components/AssociatedCompaniesList.tsx create mode 100644 resources/ts/back/Components/SoftdeleteWarning.tsx diff --git a/app/Http/Controllers/Back/CompanyActivityController.php b/app/Http/Controllers/Back/CompanyActivityController.php index d71fddbf..28308fae 100644 --- a/app/Http/Controllers/Back/CompanyActivityController.php +++ b/app/Http/Controllers/Back/CompanyActivityController.php @@ -11,6 +11,7 @@ use Illuminate\Support\Str; use Inertia\Inertia; use Uwil\LaravelBackend\Resources\CommonResource; use Uwil\LaravelCommon\Controllers\Controller; +use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class CompanyActivityController extends Controller { @@ -34,7 +35,7 @@ class CompanyActivityController extends Controller public function index(Request $request): \Inertia\Response { /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\CompanyActivity> $query */ - $query = CompanyActivity::query(); + $query = CompanyActivity::query()->with('companies'); if ($request->routeIs("back.$this->modelName.trash")) { $query = $query->onlyTrashed(); @@ -90,8 +91,10 @@ class CompanyActivityController extends Controller */ public function show(CompanyActivity $company_activity): \Inertia\Response { + $companies = $company_activity->companies()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('CompanyActivities/Show', [ 'data' => CommonResource::make($company_activity), + 'companies' => CommonResource::collection($companies), 'modelName' => $this->modelName, ]); } diff --git a/app/Http/Controllers/Back/CompanyController.php b/app/Http/Controllers/Back/CompanyController.php index ba7ca18f..35c8e731 100644 --- a/app/Http/Controllers/Back/CompanyController.php +++ b/app/Http/Controllers/Back/CompanyController.php @@ -101,7 +101,7 @@ class CompanyController extends Controller public function show(Company $company): \Inertia\Response { return Inertia::render('Companies/Show', [ - 'data' => CommonResource::make($company), + 'data' => CommonResource::make($company->load(['companyActivity', 'companySector'])), 'modelName' => $this->modelName, ]); } diff --git a/app/Http/Controllers/Back/CompanySectorController.php b/app/Http/Controllers/Back/CompanySectorController.php index a49a122d..a6cf5c27 100644 --- a/app/Http/Controllers/Back/CompanySectorController.php +++ b/app/Http/Controllers/Back/CompanySectorController.php @@ -11,6 +11,7 @@ use Illuminate\Support\Str; use Inertia\Inertia; use Uwil\LaravelBackend\Resources\CommonResource; use Uwil\LaravelCommon\Controllers\Controller; +use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class CompanySectorController extends Controller { @@ -34,7 +35,7 @@ class CompanySectorController extends Controller public function index(Request $request): \Inertia\Response { /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\CompanySector> $query */ - $query = CompanySector::query(); + $query = CompanySector::query()->with('companies'); if ($request->routeIs("back.$this->modelName.trash")) { $query = $query->onlyTrashed(); @@ -76,8 +77,10 @@ class CompanySectorController extends Controller */ public function create(CompanySector $company_sector): \Inertia\Response { + $companies = $company_sector->companies()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('CompanySectors/Create', [ 'data' => CommonResource::make($company_sector), + 'companies' => CommonResource::collection($companies), 'modelName' => $this->modelName, ]); } diff --git a/app/Http/Controllers/Back/DocumentCategoryController.php b/app/Http/Controllers/Back/DocumentCategoryController.php index fc23d75a..f911fb6e 100644 --- a/app/Http/Controllers/Back/DocumentCategoryController.php +++ b/app/Http/Controllers/Back/DocumentCategoryController.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB; use Inertia\Inertia; use Uwil\LaravelBackend\Resources\CommonResource; use Uwil\LaravelCommon\Controllers\Controller; +use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class DocumentCategoryController extends Controller { @@ -35,6 +36,10 @@ class DocumentCategoryController extends Controller /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\DocumentCategory> $query */ $query = DocumentCategory::query()->withCount('documents'); + if ($request->routeIs("back.$this->modelName.trash")) { + $query = $query->onlyTrashed(); + } + /** @var string $search Search field */ $search = $request->search; if ($search) { @@ -84,7 +89,7 @@ class DocumentCategoryController extends Controller */ public function show(DocumentCategory $document_category): \Inertia\Response { - $documents = $document_category->documents()->paginate(12); + $documents = $document_category->documents()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('DocumentCategory/Show', [ 'data' => CommonResource::make($document_category), 'documents' => CommonResource::collection($documents), @@ -142,6 +147,23 @@ class DocumentCategoryController extends Controller }); } + /** + * Restore the specified resource. + * + * @param integer $document_category + * @return \Illuminate\Http\RedirectResponse + */ + public function restore(int $document_category): \Illuminate\Http\RedirectResponse + { + $document_category = DocumentCategory::withTrashed()->findOrFail($document_category); + /** @var array */ + $previousQueries = []; + \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); + if ($document_category->restore()) { + return redirect()->route("back.$this->modelName.trash", $previousQueries); + } + return redirect()->back(); + } /** * Destroy the specified resource. @@ -159,4 +181,24 @@ class DocumentCategoryController extends Controller } return redirect()->back(); } + + /** + * Destroy the specified resource. + * + * @param \App\Models\DocumentCategory|integer $document_category + * @return \Illuminate\Http\RedirectResponse + */ + public function forceDestroy(DocumentCategory|int $document_category): \Illuminate\Http\RedirectResponse + { + if (is_int($document_category)) { + $document_category = DocumentCategory::withTrashed()->findOrFail($document_category); + } + /** @var array */ + $previousQueries = []; + \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); + if ($document_category->forceDelete()) { + return redirect()->route("back.$this->modelName.trash", $previousQueries); + } + return redirect()->back(); + } } diff --git a/app/Http/Controllers/Back/DocumentTagController.php b/app/Http/Controllers/Back/DocumentTagController.php index 8fd6af1e..073eaca1 100644 --- a/app/Http/Controllers/Back/DocumentTagController.php +++ b/app/Http/Controllers/Back/DocumentTagController.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB; use Inertia\Inertia; use Uwil\LaravelBackend\Resources\CommonResource; use Uwil\LaravelCommon\Controllers\Controller; +use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class DocumentTagController extends Controller { @@ -35,6 +36,10 @@ class DocumentTagController extends Controller /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\DocumentTag> $query */ $query = DocumentTag::query()->withCount('documents'); + if ($request->routeIs("back.$this->modelName.trash")) { + $query = $query->onlyTrashed(); + } + /** @var string $search Search field */ $search = $request->search; if ($search) { @@ -84,7 +89,7 @@ class DocumentTagController extends Controller */ public function show(DocumentTag $document_tag): \Inertia\Response { - $documents = $document_tag->documents()->paginate(12); + $documents = $document_tag->documents()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('DocumentTag/Show', [ 'data' => CommonResource::make($document_tag), 'documents' => CommonResource::collection($documents), @@ -142,6 +147,24 @@ class DocumentTagController extends Controller }); } + /** + * Restore the specified resource. + * + * @param integer $document_tag + * @return \Illuminate\Http\RedirectResponse + */ + public function restore(int $document_tag): \Illuminate\Http\RedirectResponse + { + $document_tag = DocumentTag::withTrashed()->findOrFail($document_tag); + /** @var array */ + $previousQueries = []; + \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); + if ($document_tag->restore()) { + return redirect()->route("back.$this->modelName.trash", $previousQueries); + } + return redirect()->back(); + } + /** * Destroy the specified resource. * @@ -158,4 +181,24 @@ class DocumentTagController extends Controller } return redirect()->back(); } + + /** + * Destroy the specified resource. + * + * @param \App\Models\DocumentTag|integer $document_tag + * @return \Illuminate\Http\RedirectResponse + */ + public function forceDestroy(DocumentTag|int $document_tag): \Illuminate\Http\RedirectResponse + { + if (is_int($document_tag)) { + $document_tag = DocumentTag::withTrashed()->findOrFail($document_tag); + } + /** @var array */ + $previousQueries = []; + \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); + if ($document_tag->forceDelete()) { + return redirect()->route("back.$this->modelName.trash", $previousQueries); + } + return redirect()->back(); + } } diff --git a/app/Http/Controllers/Back/NewsCategoryController.php b/app/Http/Controllers/Back/NewsCategoryController.php index 0133d9c1..beaa1fc6 100644 --- a/app/Http/Controllers/Back/NewsCategoryController.php +++ b/app/Http/Controllers/Back/NewsCategoryController.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\DB; use Inertia\Inertia; use Uwil\LaravelBackend\Resources\CommonResource; use Uwil\LaravelCommon\Controllers\Controller; +use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class NewsCategoryController extends Controller { @@ -90,7 +91,7 @@ class NewsCategoryController extends Controller */ public function show(NewsCategory $news_category): \Inertia\Response { - $news = $news_category->news()->paginate(12); + $news = $news_category->news()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('NewsCategory/Show', [ 'data' => CommonResource::make($news_category), 'news' => CommonResource::collection($news), diff --git a/app/Http/Controllers/Back/NewsTagController.php b/app/Http/Controllers/Back/NewsTagController.php index dea35790..a4a4fc57 100644 --- a/app/Http/Controllers/Back/NewsTagController.php +++ b/app/Http/Controllers/Back/NewsTagController.php @@ -11,6 +11,7 @@ use Illuminate\Support\Facades\DB; use Inertia\Inertia; use Uwil\LaravelBackend\Resources\CommonResource; use Uwil\LaravelCommon\Controllers\Controller; +use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum; class NewsTagController extends Controller { @@ -90,7 +91,7 @@ class NewsTagController extends Controller */ public function show(NewsTag $news_tag): \Inertia\Response { - $news = $news_tag->news()->paginate(12); + $news = $news_tag->news()->paginate(ItemsPerPaginationEnum::five->value()); return Inertia::render('NewsTag/Show', [ 'data' => CommonResource::make($news_tag), 'news' => CommonResource::collection($news), diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index d1c7dbac..388bfcb0 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -121,14 +121,16 @@ class HandleInertiaRequests extends Middleware 'viewAny' => Gate::allows('viewAny', Document::class), 'create' => Gate::allows('create', Document::class), ], - 'documentTags' => [ - 'viewAny' => Gate::allows('viewAny', DocumentTag::class), - 'create' => Gate::allows('create', DocumentTag::class), - ], "documentCategories" => [ 'viewAny' => Gate::allows('viewAny', DocumentCategory::class), + 'viewTrash' => Gate::allows('viewTrash', DocumentCategory::class), 'create' => Gate::allows('create', DocumentCategory::class), ], + 'documentTags' => [ + 'viewAny' => Gate::allows('viewAny', DocumentTag::class), + 'viewTrash' => Gate::allows('viewTrash', DocumentTag::class), + 'create' => Gate::allows('create', DocumentTag::class), + ], ] ], 'enumItemsPerPagination' => ItemsPerPaginationEnum::toArray(), diff --git a/app/Models/CompanyActivity.php b/app/Models/CompanyActivity.php index 5064437f..ce3bca44 100644 --- a/app/Models/CompanyActivity.php +++ b/app/Models/CompanyActivity.php @@ -4,12 +4,14 @@ namespace App\Models; use App\Contracts\TranslatableModel; use App\Helpers\TranslationHelper; +use App\Models\Company; use App\Traits\Models\HasCache; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Cache; +use Illuminate\Validation\ValidationException; use Uwil\LaravelActivityLogs\Traits\ActivityLog; /** @@ -71,6 +73,13 @@ class CompanyActivity extends Model implements TranslatableModel static::updating(function (self $model) { self::manageFields($model); }); + static::deleting(function (self $model) { + if ($model->companies()->exists()) { + throw ValidationException::withMessages([ + 'error' => trans('crud.messages.cannot_delete_relation'), + ]); + } + }); } // * METHODS @@ -101,4 +110,16 @@ class CompanyActivity extends Model implements TranslatableModel } TranslationHelper::validateFallbackTranslations($model); } + + // RELATIONSHIPS + + /** + * Get companies for this activity. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function companies(): \Illuminate\Database\Eloquent\Relations\HasMany + { + return $this->hasMany(Company::class, 'activity_id'); + } } \ No newline at end of file diff --git a/app/Models/CompanySector.php b/app/Models/CompanySector.php index 5650f029..f0e2e0c4 100644 --- a/app/Models/CompanySector.php +++ b/app/Models/CompanySector.php @@ -4,12 +4,14 @@ namespace App\Models; use App\Contracts\TranslatableModel; use App\Helpers\TranslationHelper; +use App\Models\Company; use App\Traits\Models\HasCache; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Cache; +use Illuminate\Validation\ValidationException; use Uwil\LaravelActivityLogs\Traits\ActivityLog; /** @@ -69,6 +71,13 @@ class CompanySector extends Model implements TranslatableModel static::updating(function (self $model) { self::manageFields($model); }); + static::deleting(function (self $model) { + if ($model->companies()->exists()) { + throw ValidationException::withMessages([ + 'sector_id' => trans('crud.messages.cannot_delete_relation'), + ]); + } + }); } // * METHODS @@ -99,4 +108,16 @@ class CompanySector extends Model implements TranslatableModel } TranslationHelper::validateFallbackTranslations($model); } + + // RELATIONSHIPS + + /** + * Get companies for this sector. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function companies(): \Illuminate\Database\Eloquent\Relations\HasMany + { + return $this->hasMany(Company::class, 'sector_id'); + } } \ No newline at end of file diff --git a/app/Models/DocumentCategory.php b/app/Models/DocumentCategory.php index b378a105..172d7427 100644 --- a/app/Models/DocumentCategory.php +++ b/app/Models/DocumentCategory.php @@ -7,7 +7,7 @@ use App\Traits\Models\HasCache; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Eloquent\SoftDeletes; use Uwil\LaravelActivityLogs\Traits\ActivityLog; class DocumentCategory extends Model implements TranslatableModel @@ -16,6 +16,7 @@ class DocumentCategory extends Model implements TranslatableModel use HasFactory; use HasCache; use HasTranslations; + use SoftDeletes; /** * The attributes that are mass assignable. @@ -40,9 +41,9 @@ class DocumentCategory extends Model implements TranslatableModel /** * Relation to Document * - * @return BelongsToMany + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ - public function documents(): BelongsToMany + public function documents(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->morphToMany( Document::class, diff --git a/app/Models/DocumentTag.php b/app/Models/DocumentTag.php index f9ab43d8..84f05569 100644 --- a/app/Models/DocumentTag.php +++ b/app/Models/DocumentTag.php @@ -2,14 +2,14 @@ namespace App\Models; -use App\Traits\Models\HasCache; -use Illuminate\Support\Facades\App; use App\Contracts\TranslatableModel; +use App\Traits\Models\HasCache; use App\Traits\Models\HasTranslations; -use Illuminate\Database\Eloquent\Model; -use Uwil\LaravelActivityLogs\Traits\ActivityLog; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Support\Facades\App; +use Uwil\LaravelActivityLogs\Traits\ActivityLog; class DocumentTag extends Model implements TranslatableModel { @@ -17,6 +17,7 @@ class DocumentTag extends Model implements TranslatableModel use HasFactory; use HasCache; use HasTranslations; + use SoftDeletes; /** * The attributes that are mass assignable. @@ -51,9 +52,9 @@ class DocumentTag extends Model implements TranslatableModel /** * Relation to Document * - * @return BelongsToMany + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ - public function documents(): BelongsToMany + public function documents(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->morphToMany( Document::class, diff --git a/app/Models/NewsTag.php b/app/Models/NewsTag.php index c33afaa0..48b6ce3b 100644 --- a/app/Models/NewsTag.php +++ b/app/Models/NewsTag.php @@ -11,7 +11,6 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Uwil\LaravelActivityLogs\Traits\ActivityLog; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\Relations\BelongsToMany; /** * @property int $news_id News focused. @@ -61,9 +60,9 @@ class NewsTag extends Model implements TranslatableModel /** * Relation to Document * - * @return BelongsToMany + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ - public function news(): BelongsToMany + public function news(): \Illuminate\Database\Eloquent\Relations\BelongsToMany { return $this->morphToMany( News::class, diff --git a/app/Policies/DocumentCategoryPolicy.php b/app/Policies/DocumentCategoryPolicy.php index 679d78a6..f7911cdd 100644 --- a/app/Policies/DocumentCategoryPolicy.php +++ b/app/Policies/DocumentCategoryPolicy.php @@ -19,6 +19,17 @@ class DocumentCategoryPolicy return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); } + /** + * Determine whether the user can view trash models. + * + * @param \Illuminate\Database\Eloquent\Model $authModel + * @return boolean + */ + public function viewTrash(Model $authModel): bool + { + return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); + } + /** * Determine whether the user can view the model. * @@ -79,11 +90,21 @@ class DocumentCategoryPolicy * Determine whether the user can delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function delete(Model $authModel): bool { return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); } + + /** + * Determine whether the user can force delete the model. + * + * @param \Illuminate\Database\Eloquent\Model $authModel + * @return boolean + */ + public function forceDelete(Model $authModel): bool + { + return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); + } } diff --git a/app/Policies/DocumentTagPolicy.php b/app/Policies/DocumentTagPolicy.php index 38db6225..519b5ba8 100644 --- a/app/Policies/DocumentTagPolicy.php +++ b/app/Policies/DocumentTagPolicy.php @@ -19,6 +19,17 @@ class DocumentTagPolicy return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); } + /** + * Determine whether the user can view trash models. + * + * @param \Illuminate\Database\Eloquent\Model $authModel + * @return boolean + */ + public function viewTrash(Model $authModel): bool + { + return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); + } + /** * Determine whether the user can view the model. * @@ -79,11 +90,21 @@ class DocumentTagPolicy * Determine whether the user can delete the model. * * @param \Illuminate\Database\Eloquent\Model $authModel - * @param \App\Models\News $news * @return boolean */ public function delete(Model $authModel): bool { return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); } + + /** + * Determine whether the user can force delete the model. + * + * @param \Illuminate\Database\Eloquent\Model $authModel + * @return boolean + */ + public function forceDelete(Model $authModel): bool + { + return UserStaticRules::atLeastRole($authModel, RoleEnum::admin); + } } diff --git a/database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php b/database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php new file mode 100644 index 00000000..c96f4390 --- /dev/null +++ b/database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php @@ -0,0 +1,38 @@ +timestamp('deleted_at')->nullable()->comment('Date on which the document category was deleted.'); + }); + Schema::table('document_tags', function (Blueprint $table) { + $table->timestamp('deleted_at')->nullable()->comment('Date on which the document tag was deleted.'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::table('document_categories', function (Blueprint $table) { + $table->dropSoftDeletes(); + }); + Schema::table('document_tags', function (Blueprint $table) { + $table->dropSoftDeletes(); + }); + } +}; diff --git a/lang/en/back.php b/lang/en/back.php index 78335c4b..47013933 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -62,7 +62,8 @@ return [ "settings" => "Settings", "crud_back_to_list" => "Back to the list of entries", "crud_add_entry" => "Add a new entry", - "crud_access_trash" => "Access archived entries", + "crud_access_to" => "Access to :target", + "archived_entries" => "archived entries", "table_search" => "Search by :searchFields", "table_search_reset" => "Reset the search", "table_filter_button" => "Filter results by :field", diff --git a/lang/en/models.php b/lang/en/models.php index 288ee999..80fff6a8 100644 --- a/lang/en/models.php +++ b/lang/en/models.php @@ -11,7 +11,7 @@ return [ "news-category" => "news category|news categories", "news-tag" => "news tag|news tag", "company" => "company|companies", - "company-activity" => "activity de société|activities de société", + "company-activity" => "company activity|company activities", "company-sector" => "company sector|company sectors", "document" => "document|documents", "document-tag" => "document tag|document tags", diff --git a/lang/fr/back.php b/lang/fr/back.php index a8660246..3a1c17de 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -61,7 +61,8 @@ return [ "settings" => "Paramètres", "crud_back_to_list" => "Revenir à la liste des entrées", "crud_add_entry" => "Ajouter une nouvelle entrée", - "crud_access_trash" => "Accéder aux entrées archivées", + "crud_access_to" => "Accéder aux :target", + "archived_entries" => "entrées archivées", "table_search" => "Rechercher sur :searchFields", "table_search_reset" => "Effacer la recherche", "table_filter_button" => "Filtrer les résultats par le champs :field", @@ -108,7 +109,7 @@ return [ "form_subtitle_associations" => "Gérer les relations du modèle.", "form_title_implantation" => "Coordonnées géographiques", "form_subtitle_implantation" => "Modifiez les informations de localisation de ce modèle de données.", - "access_model" => "Accéder à la :model", + "access_model" => "Accéder à :model", "clear" => "vider", "close" => "Fermer", "config_modal_title" => "Prévisualisation", diff --git a/resources/ts/back/Components/AssociatedCompaniesList.tsx b/resources/ts/back/Components/AssociatedCompaniesList.tsx new file mode 100644 index 00000000..c2dca4ec --- /dev/null +++ b/resources/ts/back/Components/AssociatedCompaniesList.tsx @@ -0,0 +1,114 @@ +// * Packages +import { Row } from "@tanstack/react-table"; +import { Building2Icon, CheckIcon, XIcon } from "lucide-react"; +// * Components shadcn +import { Badge } from "@/components/ui/badge"; +// * Other +import DataTable from "@/back/Components/Table/DataTable"; +import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; +import { CompanyModel, Resource } from "@/back/types/global"; +import { Views } from "@/lib/utils"; +import { useFormatedDate } from "@/hooks/use-formated-value"; +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; + +interface Props { + companies: Resource; +} +const AssociatedCompaniesList = (props: Props) => { + const { companies } = props; + const columns = [ + { + accessorKey: "name", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return row.getValue("name"); + }, + }, + { + accessorKey: "published", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {row.getValue("published") ? ( + + ) : ( + + )} + {str( + useTrans( + row.getValue("published") ? "back.yes" : "back.no", + ), + ) + .ucFirst() + .value()} + + ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {useFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; + + return ( + <> +

    + + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.company", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    + + + ); +}; + +export default AssociatedCompaniesList; diff --git a/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx index 915e85b4..4cc541df 100644 --- a/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx +++ b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx @@ -1,6 +1,7 @@ // * Packages import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; +import { FileInputIcon } from "lucide-react"; // * Other import str from "@/hooks/use-string"; import DataTable from "@/back/Components/Table/DataTable"; @@ -80,7 +81,8 @@ const AssociatedDocumentList = (props: Props) => { return ( <> -

    +

    + {str( useTrans("back.associated_model", { params: { diff --git a/resources/ts/back/Components/News/AssociatedNewsList.tsx b/resources/ts/back/Components/News/AssociatedNewsList.tsx index 53c3b7f0..c5bf4c56 100644 --- a/resources/ts/back/Components/News/AssociatedNewsList.tsx +++ b/resources/ts/back/Components/News/AssociatedNewsList.tsx @@ -1,6 +1,7 @@ // * Packages import { Row } from "@tanstack/react-table"; import { usePage } from "@inertiajs/react"; +import { NewspaperIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other @@ -74,7 +75,8 @@ const AssociatedNewsList = (props: Props) => { return ( <> -

    +

    + {str( useTrans("back.associated_model", { params: { diff --git a/resources/ts/back/Components/SoftdeleteWarning.tsx b/resources/ts/back/Components/SoftdeleteWarning.tsx new file mode 100644 index 00000000..bbe3aeb8 --- /dev/null +++ b/resources/ts/back/Components/SoftdeleteWarning.tsx @@ -0,0 +1,25 @@ +// * Packages +import { AlertCircle } from "lucide-react"; +// * Components shadcn +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +// * Other +import InputError from "@/back/Components/InputError"; +import useTrans from "@/hooks/use-translations"; + +export default function SoftdeleteWarning() { + return ( + <> + + + {useTrans('back.warning')} + +

    {useTrans('back.warning_trash')}

    +
    +
    + + + ); +} diff --git a/resources/ts/back/Components/Table/DataTableSearch.tsx b/resources/ts/back/Components/Table/DataTableSearch.tsx index 15d65fbb..78399c5b 100644 --- a/resources/ts/back/Components/Table/DataTableSearch.tsx +++ b/resources/ts/back/Components/Table/DataTableSearch.tsx @@ -5,8 +5,9 @@ import { FormEvent, ReactNode } from "react"; import { route } from "ziggy-js"; // * Other import SimpleString from "@/back/Components/Inputs/SimpleString"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import InputError from "@/back/Components/InputError"; import useTrans from "@/hooks/use-translations"; -import BtnOptionnalLinkWithTooltip from "../BtnOptionnalLinkWithTooltip"; type DataTableSearchProps = { modelRoute: string; @@ -30,26 +31,29 @@ export default function DataTableSearch({ get(route(`back.${modelRoute}.index`)); }; return ( -
    - - {children} - } - tooltipContent={

    {useTrans("back.table_search_reset")}

    } - type="button" - variant="destructive" - onClick={() => router.visit(url.origin + url.pathname)} - /> - + <> +
    + + {children} + } + tooltipContent={

    {useTrans("back.table_search_reset")}

    } + type="button" + variant="destructive" + onClick={() => router.visit(url.origin + url.pathname)} + /> + + + ); } diff --git a/resources/ts/back/Pages/Companies/Index.tsx b/resources/ts/back/Pages/Companies/Index.tsx index 84b414b1..e59e02a6 100644 --- a/resources/ts/back/Pages/Companies/Index.tsx +++ b/resources/ts/back/Pages/Companies/Index.tsx @@ -2,23 +2,26 @@ import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; -import { AlertCircleIcon, ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; +import { + ArchiveIcon, + ArrowLeftIcon, + CheckIcon, + PlusIcon, + RadarIcon, + RollerCoasterIcon, + XIcon, +} from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; -import InputError from "@/back/Components/InputError"; +import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { Views } from "@/lib/utils"; -import { - AuthProp, - CompanyModel, - Resource, -} from "@/back/types/global"; +import { AuthProp, CompanyModel, Resource } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; @@ -37,22 +40,26 @@ export default function Index({ auth: AuthProp; }; const { viewAny, viewTrash, create } = auth.policies.companies; + const { viewAny: viewAnyCompanyActivities } = + auth.policies.companyActivities; + const { viewAny: viewAnyCompanySectors } = auth.policies.companySectors; const isArchiveRoute = route().current(`back.${modelName}.trash`); - const actionModels = isArchiveRoute ? [ - Views.RESTORATION, - Views.FORCEDELETION, - ] : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; const columns = [ { accessorKey: "name", header: ({ column }: { column: { id: string } }) => ( ), @@ -62,27 +69,35 @@ export default function Index({ accessorKey: "latitude", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: Row }) => row.getValue("latitude"), + cell: ({ row }: { row: Row }) => + row.getValue("latitude"), }, { accessorKey: "longitude", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: Row }) => row.getValue("longitude"), + cell: ({ row }: { row: Row }) => + row.getValue("longitude"), }, { accessorKey: "published", header: ({ column }: { column: { id: string } }) => ( ), @@ -90,7 +105,9 @@ export default function Index({ {row.getValue("published") ? ( @@ -98,42 +115,116 @@ export default function Index({ ) : ( )} - {str(useTrans(row.getValue("published") ? "back.yes" : "back.no")).ucFirst().value()} + {str( + useTrans( + row.getValue("published") ? "back.yes" : "back.no", + ), + ) + .ucFirst() + .value()} ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel }}) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
    - } - tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } - /> -
    + return ( + isArchiveRoute && + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
    - {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } - variant={"outline"} - />} - {create && } - tooltipContent={

    {useTrans("back.crud_add_entry")}

    } - />} -
    + return ( + !isArchiveRoute && ( +
    + {viewAnyCompanyActivities && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.company-activity", + { choice: 2 }, + ), + }, + })} +

    + } + variant="outline" + /> + )} + {viewAnyCompanySectors && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.company-sector", + { choice: 2 }, + ), + }, + })} +

    + } + variant="outline" + /> + )} + {viewTrash && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "back.archived_entries", + ), + }, + })} +

    + } + variant={"outline"} + /> + )} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )} +
    + ) ); }; @@ -143,21 +234,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

    {useTrans('back.warning_trash')}

    -
    -
    - - - )} + {isArchiveRoute && } value, }, + { + accessorKey: "company_activity", + header: str(useTrans('models.classes.company-activity', { choice: 1 })).ucFirst().value(), + cell: ({ value }: { value: CompanyActivityModel }) => auth.policies.companyActivities.viewAny ? ( + + + {value.name[appEnv.locale]} + + } + tooltipContent={ +

    {useTrans("back.access_model", { + params: { + model: useTrans('models.classes.company-activity', { choice: 1 }) + } + })}

    + } + type="button" + size="default" + variant="secondary" + /> + ) : {value.name[appEnv.locale]} + }, + { + accessorKey: "company_sector", + header: str(useTrans('models.classes.company-sector', { choice: 1 })).ucFirst().value(), + cell: ({ value }: { value: CompanySectorModel|null }) => value !== null && ( + auth.policies.companySectors.viewAny ? ( + + + {value.name[appEnv.locale]} + + } + tooltipContent={ +

    {useTrans("back.access_model", { + params: { + model: useTrans('models.classes.company-sector', { choice: 1 }) + } + })}

    + } + type="button" + size="default" + variant="secondary" + /> + ) : {value.name[appEnv.locale]} + ) + }, { accessorKey: "created_at", header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), diff --git a/resources/ts/back/Pages/CompanyActivities/Index.tsx b/resources/ts/back/Pages/CompanyActivities/Index.tsx index 5c51a1dc..e19581bf 100644 --- a/resources/ts/back/Pages/CompanyActivities/Index.tsx +++ b/resources/ts/back/Pages/CompanyActivities/Index.tsx @@ -2,25 +2,22 @@ import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; -import { AlertCircleIcon, ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; +import { ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; -import InputError from "@/back/Components/InputError"; +import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { Views } from "@/lib/utils"; import { - AppEnv, AuthProp, CompanyActivityModel, Resource, - TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; @@ -37,9 +34,8 @@ export default function Index({ searchFields: string; modelName: string; }) { - const { auth, appEnv } = usePage().props as unknown as { + const { auth } = usePage().props as unknown as { auth: AuthProp; - appEnv: AppEnv; }; const { viewAny, viewTrash, create } = auth.policies.companyActivities; const isArchiveRoute = route().current(`back.${modelName}.trash`); @@ -88,6 +84,18 @@ export default function Index({ ) }, }, + { + accessorKey: "companies", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return (

    {row.original.companies.length}

    ); + }, + }, { accessorKey: "published", header: ({ column }: { column: { id: string } }) => ( @@ -134,7 +142,9 @@ export default function Index({ {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant="outline" />} {create && - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

    {useTrans('back.warning_trash')}

    -
    -
    - - - )} + {isArchiveRoute && } {/* @ts-expect-error Weird error type on cell. */} + ); } diff --git a/resources/ts/back/Pages/CompanySectors/Index.tsx b/resources/ts/back/Pages/CompanySectors/Index.tsx index 2faed543..0f29fc45 100644 --- a/resources/ts/back/Pages/CompanySectors/Index.tsx +++ b/resources/ts/back/Pages/CompanySectors/Index.tsx @@ -2,16 +2,15 @@ import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; -import { AlertCircleIcon, ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; +import { ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; -import InputError from "@/back/Components/InputError"; +import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { Views } from "@/lib/utils"; import { @@ -19,7 +18,6 @@ import { AuthProp, CompanySectorModel, Resource, - TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; @@ -66,6 +64,18 @@ export default function Index({ ) }, }, + { + accessorKey: "companies", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return (

    {row.original.companies.length}

    ); + }, + }, { accessorKey: "published", header: ({ column }: { column: { id: string } }) => ( @@ -112,7 +122,9 @@ export default function Index({ {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant={"outline"} />} {create && - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

    {useTrans('back.warning_trash')}

    -
    -
    - - - )} + {isArchiveRoute && } {/* @ts-expect-error Weird error type on cell. */} + ); } diff --git a/resources/ts/back/Pages/Document/Index.tsx b/resources/ts/back/Pages/Document/Index.tsx index 237aa4bd..a71554fd 100644 --- a/resources/ts/back/Pages/Document/Index.tsx +++ b/resources/ts/back/Pages/Document/Index.tsx @@ -2,7 +2,7 @@ import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; -import { Plus, TriangleAlert } from "lucide-react"; +import { FolderIcon, PlusIcon, TagIcon, TriangleAlertIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; import { @@ -48,6 +48,9 @@ export default function Index({ appEnv: AppEnv; }; const { create } = auth.policies.documents; + const { viewAny: viewAnyDocumentCategories } = + auth.policies.documentCategories; + const { viewAny: viewAnyDocumentTags } = auth.policies.documentTags; const actionModels = [Views.VISUALIZATION, Views.EDITION, Views.DELETION]; const columns = [ { @@ -80,7 +83,7 @@ export default function Index({ {!hasLink && ( - +

    @@ -99,6 +102,46 @@ export default function Index({ ); }, }, + { + accessorKey: "categories", + header: ({ column }: { column: { id: string } }) => ( +

    + {str( + useTrans("back.associated_model", { + params: { + model: useTrans( + "models.classes.document-category", + { + choice: 2, + }, + ), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

    + ), + cell: ({ row }: { row: Row }) => { + if ( + !row.original.categories || + row.original.categories.length === 0 + ) + return null; + + return ( +
    + {row.original.categories.map((item, i) => ( + + ))} +
    + ); + }, + }, { accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( @@ -117,39 +160,6 @@ export default function Index({ ); }, }, - { - accessorKey: "categories", - header: str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.document-category", { - choice: 2, - }), - }, - choice: 2, - }), - ) - .ucFirst() - .value(), - cell: ({ row }: { row: Row }) => { - if ( - !row.original.categories || - row.original.categories.length === 0 - ) - return null; - - return ( -
    - {row.original.categories.map((item, i) => ( - - ))} -
    - ); - }, - }, { accessorKey: "published_at", header: ({ column }: { column: { id: string } }) => ( @@ -192,10 +202,48 @@ export default function Index({ const afterNode = () => { return (
    + {viewAnyDocumentCategories && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.document-category", + { choice: 2 }, + ), + }, + })} +

    + } + variant="outline" + /> + )} + {viewAnyDocumentTags && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.document-tag", + { choice: 2 }, + ), + }, + })} +

    + } + variant="outline" + /> + )} {create && ( } + content={} tooltipContent={

    {useTrans("back.crud_add_entry")}

    } diff --git a/resources/ts/back/Pages/DocumentCategory/Edit.tsx b/resources/ts/back/Pages/DocumentCategory/Edit.tsx index 5e010b39..388c9409 100644 --- a/resources/ts/back/Pages/DocumentCategory/Edit.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Edit.tsx @@ -4,21 +4,22 @@ import { route } from "ziggy-js"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import ModelActions from "@/back/Components/ModelActions"; +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import useTrans from "@/hooks/use-translations"; import { Actions, Methods } from "@/lib/enums"; -import Form from "./Form"; +import Form from "@/back/Pages/DocumentCategory/Form"; import { Views } from "@/lib/utils"; import { AuthProp, DocumentCategoryModel, SingleResource } from "@/back/types/global"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { ArrowLeft } from "lucide-react"; import str from "@/hooks/use-string"; - export default function Edit({ data, modelName }: { data: SingleResource, modelName: string }) { const { viewAny } = (usePage().props.auth as AuthProp).policies.documentCategories; const documentCategoryModel = data.data as DocumentCategoryModel; const actionModels = [ - Views.VISUALIZATION + Views.VISUALIZATION, + Views.DUPLICATION, + Views.ARCHIVATION, ]; const singularModelName = str(modelName).singular().value(); const transTitle = useTrans("crud.helpers.edition_model", { diff --git a/resources/ts/back/Pages/DocumentCategory/Form.tsx b/resources/ts/back/Pages/DocumentCategory/Form.tsx index 4ddf33b3..2f96ddcf 100644 --- a/resources/ts/back/Pages/DocumentCategory/Form.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Form.tsx @@ -6,7 +6,7 @@ import FieldsetWrapper from "@/back/Components/FieldsetWrapper"; import InputError from "@/back/Components/InputError"; import SimpleString from "@/back/Components/Inputs/SimpleString"; import { Methods } from "@/lib/enums"; -import { AppEnv, DocumentTagModel } from "@/back/types/global"; +import { AppEnv, DocumentCategoryModel } from "@/back/types/global"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; import { useCrudSubmit } from "@/hooks/use-crud-submit"; @@ -20,7 +20,7 @@ export default function Form({ action, method, }: { - model?: DocumentTagModel; + model?: DocumentCategoryModel; modelName: string; modelRoute: string; action: string; diff --git a/resources/ts/back/Pages/DocumentCategory/Index.tsx b/resources/ts/back/Pages/DocumentCategory/Index.tsx index 5232b1cf..041d5bcb 100644 --- a/resources/ts/back/Pages/DocumentCategory/Index.tsx +++ b/resources/ts/back/Pages/DocumentCategory/Index.tsx @@ -1,6 +1,8 @@ // * Packages import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; +import { Row } from "@tanstack/react-table"; +import { ArchiveIcon, ArrowLeftIcon, Plus } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other @@ -9,6 +11,7 @@ import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; import { @@ -16,12 +19,9 @@ import { AuthProp, DocumentCategoryModel, Resource, - TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { Row } from "@tanstack/react-table"; -import { Plus } from "lucide-react"; import { renderTranslationCell } from "@/lib/translationCellFallback"; export default function Index({ @@ -39,8 +39,16 @@ export default function Index({ auth: AuthProp; appEnv: AppEnv; }; - const { create } = auth.policies.documentCategories; - const actionModels = [Views.VISUALIZATION, Views.EDITION, Views.DELETION]; + const { viewAny, viewTrash, create } = auth.policies.documentCategories; + const isArchiveRoute = route().current(`back.${modelName}.trash`); + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; const columns = [ { accessorKey: "name", @@ -101,26 +109,64 @@ export default function Index({ `models.classes.${str(modelName).singular().value()}`, { choice: 2 }, ); - const transTitle = str(transModel).ucFirst().value(); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); - const afterNode = () => { + const beforeNode = () => { return ( -
    - {create && ( + isArchiveRoute && + viewAny && ( +
    } + link={route(`back.${modelName}.index`)} + content={} tooltipContent={ -

    {useTrans("back.crud_add_entry")}

    +

    {useTrans("back.crud_back_to_list")}

    } /> - )} -
    +
    + ) + ); + }; + const afterNode = () => { + return ( + !isArchiveRoute && ( +
    + {viewTrash && ( + } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )} +
    + ) ); }; return ( - + + {isArchiveRoute && } { + return ( + isArchiveRoute && + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) + ); + }; const afterNode = () => { return ( -
    - {create && ( - } - tooltipContent={ -

    {useTrans("back.crud_add_entry")}

    - } - /> - )} -
    + !isArchiveRoute && ( +
    + {viewTrash && ( + } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )} +
    + ) ); }; return ( - + + {isArchiveRoute && } } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant="outline" />} {create && - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

    {useTrans('back.warning_trash')}

    -
    -
    - - - )} + {isArchiveRoute && } } + content={} tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } />
    @@ -115,15 +114,33 @@ export default function Index({ const afterNode = () => { return !isArchiveRoute && (
    + {viewAnyNewsCategories && } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('models.classes.news-category', { choice: 2 })} + })}

    } + variant="outline" + />} + {viewAnyNewsTags && } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('models.classes.news-tag', { choice: 2 })} + })}

    } + variant="outline" + />} {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } + content={} + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant="outline" />} {create && } + content={} tooltipContent={

    {useTrans("back.crud_add_entry")}

    } />}
    @@ -136,21 +153,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

    {useTrans('back.warning_trash')}

    -
    -
    - - - )} + {isArchiveRoute && } } - tooltipContent={ -

    {useTrans("back.crud_access_trash")}

    - } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant="outline" /> )} @@ -166,18 +164,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans("back.warning")} - -

    {useTrans("back.warning_trash")}

    -
    -
    - - - )} + {isArchiveRoute && } } - tooltipContent={ -

    {useTrans("back.crud_access_trash")}

    - } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant="outline" /> )} @@ -197,18 +191,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans("back.warning")} - -

    {useTrans("back.warning_trash")}

    -
    -
    - - - )} + {isArchiveRoute && } } - tooltipContent={

    {useTrans("back.crud_access_trash")}

    } + tooltipContent={

    {useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

    } variant="outline" />} {create && - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

    {useTrans('back.warning_trash')}

    -
    -
    - - - )} + {isArchiveRoute && } request()->document_category ])); }); +Breadcrumbs::for('back.document-categories.trash', function (Generator $trail) { + $trail->parent('back.document-categories.index'); + $trail->push(Str::ucfirst(trans('crud.actions.archive'))); +}); // * DOCUMENT TAGS. Breadcrumbs::for('back.document-tags.index', function (Generator $trail) { @@ -385,3 +389,7 @@ Breadcrumbs::for('back.document-tags.show', function (Generator $trail) { 'document_tag' => request()->document_tag ])); }); +Breadcrumbs::for('back.document-tags.trash', function (Generator $trail) { + $trail->parent('back.document-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.archive'))); +}); diff --git a/routes/web-back.php b/routes/web-back.php index 428035c2..e62ad353 100644 --- a/routes/web-back.php +++ b/routes/web-back.php @@ -144,9 +144,30 @@ Route::prefix('admin') Route::get('/company-activities/{company_activity}/duplicate', [CompanyActivityController::class, 'duplicate']) ->name('company-activities.duplicate'); + // * DOCUMENTS. Route::resource('documents', DocumentController::class); - Route::resource('document-tags', DocumentTagController::class); + + // * DOCUMENTS CATEGORIES. + Route::get('/document-categories/trash', [DocumentCategoryController::class, 'index']) + ->name('document-categories.trash'); + Route::patch('/document-categories/{document_category}/restore', [DocumentCategoryController::class, 'restore']) + ->name('document-categories.restore'); + Route::delete('/document-categories/{document_category}/force', [DocumentCategoryController::class, 'forceDestroy']) + ->name('document-categories.forceDestroy'); Route::resource('document-categories', DocumentCategoryController::class); + Route::get('/document-categories/{document_category}/duplicate', [DocumentCategoryController::class, 'duplicate']) + ->name('document-categories.duplicate'); + + // * DOCUMENTS TAGS. + Route::get('/document-tags/trash', [DocumentTagController::class, 'index']) + ->name('document-tags.trash'); + Route::patch('/document-tags/{document_tag}/restore', [DocumentTagController::class, 'restore']) + ->name('document-tags.restore'); + Route::delete('/document-tags/{document_tag}/force', [DocumentTagController::class, 'forceDestroy']) + ->name('document-tags.forceDestroy'); + Route::resource('document-tags', DocumentTagController::class); + Route::get('/document-tags/{document_tag}/duplicate', [DocumentTagController::class, 'duplicate']) + ->name('document-tags.duplicate'); }); // * UPDATE LANGUAGES. From e397c430f1e98997ed89ad5c218c19a4d77f67df Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Wed, 21 Jan 2026 12:32:04 +0100 Subject: [PATCH 11/19] fix: :globe_with_meridians: set post actions translations --- lang/en/crud.php | 63 ++++++++--------- lang/fr/crud.php | 67 +++++++++---------- resources/ts/back/Components/ModelActions.tsx | 42 ++++++++---- 3 files changed, 93 insertions(+), 79 deletions(-) diff --git a/lang/en/crud.php b/lang/en/crud.php index 7e36d0db..a385b6b9 100644 --- a/lang/en/crud.php +++ b/lang/en/crud.php @@ -42,36 +42,37 @@ return [ ], "messages" => [ - "has_been_created" => ":model has been created", - "cannot_be_created" => ":model cannot be created", - "has_been_updated" => ":model has been updated", - "cannot_be_updated" => ":model cannot be updated", - "has_been_deleted" => ":model has been deleted", - "cannot_be_deleted" => ":model cannot be deleted", - "has_been_restored" => ":model has been restored", - "cannot_be_restored" => ":model cannot be restored", - "order_changed" => "The order has been changed !", - "order_not_changed" => "The order has not been changed !", - "publish_status_saved" => "Successful change of publication status !", - "highlight_status_saved" => "A successful change of focus !", - "right" => "You don't have access rights to this part !", - "theme_updated" => "The theme has been updated !", - "user_unpublished" => "You can't deactivate your own account !", + "successful_creation" => "Creation successful !", + "successful_edition" => "Update successful !", + "successful_archivation" => "Archiving successful !", + "successful_restoration" => "Restoration successful !", + "successful_deletion" => "Deletion successful !", + "canceled_creation" => "Creation canceled !", + "canceled_edition" => "Update canceled !", + "canceled_archivation" => "Archiving canceled !", + "canceled_restoration" => "Restoration canceled !", + "canceled_deletion" => "Deletion canceled !", + "successful_archivation_details" => "You have just archived an entry.", + "successful_restoration_details" => "You have just restored an entry.", + "successful_deletion_details" => "You have just permanently deleted an entry.", + "canceled_archivation_details" => "A problem occurred while archiving this entry.", + "canceled_restoration_details" => "A problem occurred while restoring this entry.", + "canceled_deletion_details" => "A problem occurred while deleting this entry.", + "has_been_created" => ":model has been created", + "cannot_be_created" => ":model cannot be created", + "has_been_updated" => ":model has been updated", + "cannot_be_updated" => ":model cannot be updated", + "has_been_deleted" => ":model has been deleted", + "cannot_be_deleted" => ":model cannot be deleted", + "has_been_restored" => ":model has been restored", + "cannot_be_restored" => ":model cannot be restored", + "order_changed" => "The order has been changed !", + "order_not_changed" => "The order has not been changed !", + "publish_status_saved" => "Successful change of publication status !", + "highlight_status_saved" => "A successful change of focus !", + "right" => "You don't have access rights to this part !", + "theme_updated" => "The theme has been updated !", + "user_unpublished" => "You can't deactivate your own account !", + "cannot_delete_relation" => "Deletion not possible because data models are still associated !", ], - - "meta" => [ - "title" => [ - "create" => "{0} Creation of :model|{1} Creation of :model", - "edit" => "{0} Edition of :model|{1} Edition of :model", - "show" => "{0} Details of :model|{1} Details of :model", - ], - // phpcs:disable Generic.Files.LineLength.TooLong - "description" => [ - "index" => "{0} List of all :model|{1} List of all :model", - "create" => "{0} Creation of a brand new :model|{1} Creation of a brand new :model", - "edit" => "{0} Editing an existing :model|{1} Editing an existing :model", - "show" => "{0} Visualizing an existing :model|{1} Visualizing an existing :model", - ], - // phpcs:enable - ] ]; diff --git a/lang/fr/crud.php b/lang/fr/crud.php index 40f6022c..ec12aed6 100644 --- a/lang/fr/crud.php +++ b/lang/fr/crud.php @@ -42,40 +42,37 @@ return [ ], "messages" => [ - "successful_creation" => "Création réussie !", - "successful_edition" => "Mise à jour réussie !", - "canceled_creation" => "Création annulée !", - "canceled_edition" => "Mise à jour annulée !", - "has_been_created" => ":model a été créé", - "cannot_be_created" => ":model ne peut être créé", - "has_been_updated" => ":model a été mis à jour", - "cannot_be_updated" => ":model ne peut être mis à jour", - "has_been_deleted" => ":model a été supprimé", - "cannot_be_deleted" => ":model ne peut être supprimé", - "has_been_restored" => ":model a été restoré", - "cannot_be_restored" => ":model ne peut être restoré", - "order_changed" => "L'ordre a été changé !", - "order_not_changed" => "L'ordre n'a pas été changé !", - "publish_status_saved" => "Changement de l'état de publication réussi !", - "highlight_status_saved" => "Changement de la mise en avant réussi !", - "right" => "Vous n'avez pas les droits pour accéder à cette partie !", - "theme_updated" => "Le thème a été mis à jour !", - "user_unpublished" => "Vous ne pouvez pas désactiver votre propre compte !", + "successful_creation" => "Création réussie !", + "successful_edition" => "Mise à jour réussie !", + "successful_archivation" => "Archivation réussie !", + "successful_restoration" => "Restoration réussie !", + "successful_deletion" => "Suppression réussie !", + "canceled_creation" => "Création annulée !", + "canceled_edition" => "Mise à jour annulée !", + "canceled_archivation" => "Archivation annulée !", + "canceled_restoration" => "Restoration annulée !", + "canceled_deletion" => "Suppression annulée !", + "successful_archivation_details" => "Vous venez d'archiver une entrée.", + "successful_restoration_details" => "Vous venez de restorer une entrée.", + "successful_deletion_details" => "Vous venez de supprimer définitivement une entrée.", + "canceled_archivation_details" => "Un problème est survenu lors de l'archivation de cette entrée.", + "canceled_restoration_details" => "Un problème est survenu lors de la restoration de cette entrée.", + "canceled_deletion_details" => "Un problème est survenu lors de la suppression de cette entrée.", + "has_been_created" => ":model a été créé", + "cannot_be_created" => ":model ne peut être créé", + "has_been_updated" => ":model a été mis à jour", + "cannot_be_updated" => ":model ne peut être mis à jour", + "has_been_deleted" => ":model a été supprimé", + "cannot_be_deleted" => ":model ne peut être supprimé", + "has_been_restored" => ":model a été restoré", + "cannot_be_restored" => ":model ne peut être restoré", + "order_changed" => "L'ordre a été changé !", + "order_not_changed" => "L'ordre n'a pas été changé !", + "publish_status_saved" => "Changement de l'état de publication réussi !", + "highlight_status_saved" => "Changement de la mise en avant réussi !", + "right" => "Vous n'avez pas les droits pour accéder à cette partie !", + "theme_updated" => "Le thème a été mis à jour !", + "user_unpublished" => "Vous ne pouvez pas désactiver votre propre compte !", + "cannot_delete_relation" => "Supression impossible car des modèles de données sont encore associés !", ], - - "meta" => [ - "title" => [ - "create" => "{0} Création d'un :model|{1} Création d'une :model", - "edit" => "{0} Edition d'un :model|{1} Edition d'une :model", - "show" => "{0} Visualisation d'un :model|{1} Visualisation d'une :model", - ], - // phpcs:disable Generic.Files.LineLength.TooLong - "description" => [ - "index" => "{0} Liste de tous les :model|{1} Liste de toutes les :model", - "create" => "{0} Création d'un tout nouveau :model|{1} Création d'une toute nouvelle :model", - "edit" => "{0} Edition d'un :model déjà existant|{1} Edition d'une :model déjà existante", - "show" => "{0} Visualisation d'un :model déjà existant|{1} Visualisation d'une :model déjà existante", - ], - // phpcs:enable - ] ]; diff --git a/resources/ts/back/Components/ModelActions.tsx b/resources/ts/back/Components/ModelActions.tsx index ae5ab11c..cd59a88f 100644 --- a/resources/ts/back/Components/ModelActions.tsx +++ b/resources/ts/back/Components/ModelActions.tsx @@ -54,6 +54,22 @@ export default function ModelActions({ const { delete: destroy, patch } = useForm(); const { toast } = useToast(); + // Translations. + const successfulArchivation = useTrans('crud.messages.successful_archivation'); + const successfulArchivationDetails = useTrans("crud.messages.successful_archivation_details"); + const canceledArchivation = useTrans('crud.messages.canceled_archivation'); + const canceledArchivationDetails = useTrans("crud.messages.canceled_archivation_details"); + + const successfulRestoration = useTrans('crud.messages.successful_restoration'); + const successfulRestorationDetails = useTrans("crud.messages.successful_restoration_details"); + const canceledRestoration = useTrans('crud.messages.canceled_restoration'); + const canceledRestorationDetails = useTrans("crud.messages.canceled_restoration_details"); + + const successfulDeletion = useTrans('crud.messages.successful_deletion'); + const successfulDeletionDetails = useTrans("crud.messages.successful_deletion_details"); + const canceledDeletion = useTrans('crud.messages.canceled_deletion'); + const canceledDeletionDetails = useTrans("crud.messages.canceled_deletion_details"); + /** * Action call on model. * @param event FormEvent @@ -73,34 +89,34 @@ export default function ModelActions({ [Views.ARCHIVATION.label]: { method: destroy, success: { - title: "Archivation réussie !", - description: "Vous venez d'archiver une entrée.", + title: successfulArchivation, + description: successfulArchivationDetails, }, error: { - title: "Archivation annulée !", - description: "Un problème est survenu lors de l'archivation de cette entrée.", + title: canceledArchivation, + description: canceledArchivationDetails, }, }, [Views.RESTORATION.label]: { method: patch, success: { - title: "Restoration réussie !", - description: "Vous venez de restorer une entrée.", + title: successfulRestoration, + description: successfulRestorationDetails, }, error: { - title: "Restoration annulée !", - description: "Un problème est survenu lors de la restoration de cette entrée.", + title: canceledRestoration, + description: canceledRestorationDetails, }, }, [Views.DELETION.label || Views.FORCEDELETION.label]: { method: destroy, success: { - title: "Suppression réussie !", - description: "Vous venez de supprimer définitivement une entrée.", + title: successfulDeletion, + description: successfulDeletionDetails, }, error: { - title: "Suppression annulée !", - description: "Un problème est survenu lors de la suppression de cette entrée.", + title: canceledDeletion, + description: canceledDeletionDetails, }, }, }; @@ -235,7 +251,7 @@ export default function ModelActions({ )} {Boolean(allowedActions.length) && (
    {inDialog ? ( From 99b610c33341d6626cc833c1f8c882220df06a89 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Wed, 21 Jan 2026 16:46:27 +0100 Subject: [PATCH 12/19] fix: :lipstick: update style of multi select component --- lang/en/back.php | 4 +- lang/fr/back.php | 2 + .../Filters/MultiSelectRelationFilter.tsx | 11 + .../ts/back/Components/Inputs/EnumSelect.tsx | 4 +- .../ts/back/Components/Inputs/ModelSelect.tsx | 24 +- .../ts/back/Components/Inputs/MultiSelect.tsx | 861 ++++++++++++------ .../back/Pages/Document/Actions/Filters.tsx | 2 - resources/ts/back/Pages/Document/Form.tsx | 22 + resources/ts/back/Pages/News/Form.tsx | 26 +- 9 files changed, 644 insertions(+), 312 deletions(-) diff --git a/lang/en/back.php b/lang/en/back.php index 47013933..8d264d12 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -177,9 +177,11 @@ return [ ], ], "multi_select" => [ - "search_options" => "search options...", + "search_options" => "search among the options...", "select_all" => "select all", "more" => "more", + "close_popover" => "close popover", + "clear_list" => "deselect all items", ], "simple_date_picker" => [ "reset" => "reset the date" diff --git a/lang/fr/back.php b/lang/fr/back.php index 3a1c17de..cd0153bd 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -181,6 +181,8 @@ return [ "search_options" => "cherchez parmi les options...", "select_all" => "tout sélectionner", "more" => "supplémentaire(s)", + "close_popover" => "fermer la popup", + "clear_list" => "désélectionner tous les éléments", ], "simple_date_picker" => [ "reset" => "vider la date", diff --git a/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx index 4ca4085a..28fcfe70 100644 --- a/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx +++ b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx @@ -51,6 +51,17 @@ const MultiSelectRelationFilter = (props: Props) => { }} defaultValue={valuesFromUrl} options={options} + responsive={{ + mobile: { + maxCount: 3, + }, + tablet: { + maxCount: 4, + }, + desktop: { + maxCount: 5, + } + }} /> ) } diff --git a/resources/ts/back/Components/Inputs/EnumSelect.tsx b/resources/ts/back/Components/Inputs/EnumSelect.tsx index c92f591e..5d9668da 100644 --- a/resources/ts/back/Components/Inputs/EnumSelect.tsx +++ b/resources/ts/back/Components/Inputs/EnumSelect.tsx @@ -138,7 +138,7 @@ export default function EnumSelect({ aria-expanded={open} disabled={disabled} className={cn( - "w-full h-auto max-h-10 justify-between whitespace-normal text-start", + "w-full h-10 justify-between whitespace-normal text-start", { "text-muted-foreground": !selectedEnum }, { "border-destructive/50": localErrors[name] }, )} @@ -177,7 +177,7 @@ export default function EnumSelect({ {Object.values(currentOptions).length === 0 && (

    {useTrans("back.table_no_results")}

    )} -
    +
    {Object.values(currentOptions).map((option) => ( - ))} -
    - )} + )) + )} +
    {/* Pagination boutons */} {options.length > 0 && lastPage !== 1 && (
    diff --git a/resources/ts/back/Components/Inputs/MultiSelect.tsx b/resources/ts/back/Components/Inputs/MultiSelect.tsx index 6015b18a..b14151f8 100644 --- a/resources/ts/back/Components/Inputs/MultiSelect.tsx +++ b/resources/ts/back/Components/Inputs/MultiSelect.tsx @@ -1,12 +1,30 @@ +// * Packages +import { usePage } from "@inertiajs/react"; +import { + ButtonHTMLAttributes, + ComponentType, + CSSProperties, + forwardRef, + KeyboardEvent, + ReactNode, + useCallback, + useEffect, + useId, + useImperativeHandle, + useMemo, + useRef, + useState, +} from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { CheckIcon, - XCircle, - ChevronDown, + XCircleIcon, XIcon, - WandSparkles, + WandSparklesIcon, + SearchIcon, + ChevronsUpDownIcon, } from "lucide-react"; -import { cn } from "@/lib/utils"; +// * Components shadcn import { Separator } from "@/components/ui/separator"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; @@ -19,17 +37,17 @@ import { Command, CommandEmpty, CommandGroup, - CommandInput, CommandItem, CommandList, - CommandSeparator, } from "@/components/ui/command"; -import { Label } from "../../../components/ui/label"; +import { Label } from "@/components/ui/label"; +import { Input } from "@/components/ui/input"; +// * Other +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import InputError from "@/back/Components/InputError"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import InputError from "@/back/Components/InputError"; -import { usePage } from "@inertiajs/react"; -import { ButtonHTMLAttributes, ComponentType, CSSProperties, forwardRef, KeyboardEvent, ReactNode, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; /** * Animation types and configurations @@ -51,10 +69,11 @@ export interface AnimationConfig { * Variants for the multi-select component to handle different styles. * Uses class-variance-authority (cva) to define different styles based on "variant" prop. */ -const multiSelectVariants = cva("m-1 transition-all duration-300 ease-in-out", { +const multiSelectVariants = cva("transition-all duration-300 ease-in-out", { variants: { variant: { - default: "border-foreground/10 text-foreground bg-card hover:bg-card/80", + default: + "border-foreground/10 text-foreground bg-card hover:bg-card/80", secondary: "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: @@ -72,7 +91,7 @@ const multiSelectVariants = cva("m-1 transition-all duration-300 ease-in-out", { }, defaultVariants: { variant: "default", - badgeAnimation: "bounce", + badgeAnimation: "none", }, }); @@ -113,11 +132,8 @@ interface MultiSelectGroup { * Props for MultiSelect component */ interface MultiSelectProps - extends Omit< - ButtonHTMLAttributes, - "animationConfig" - >, - VariantProps { + extends Omit, "animationConfig">, + VariantProps { /** * An array of option objects or groups to be displayed in the multi-select component. */ @@ -225,27 +241,27 @@ interface MultiSelectProps * Can be boolean true for default responsive behavior or an object for custom configuration. */ responsive?: - | boolean - | { - /** Configuration for mobile devices (< 640px) */ - mobile?: { - maxCount?: number; - hideIcons?: boolean; - compactMode?: boolean; - }; - /** Configuration for tablet devices (640px - 1024px) */ - tablet?: { - maxCount?: number; - hideIcons?: boolean; - compactMode?: boolean; - }; - /** Configuration for desktop devices (> 1024px) */ - desktop?: { - maxCount?: number; - hideIcons?: boolean; - compactMode?: boolean; - }; - }; + | boolean + | { + /** Configuration for mobile devices (< 640px) */ + mobile?: { + maxCount?: number; + hideIcons?: boolean; + compactMode?: boolean; + }; + /** Configuration for tablet devices (640px - 1024px) */ + tablet?: { + maxCount?: number; + hideIcons?: boolean; + compactMode?: boolean; + }; + /** Configuration for desktop devices (> 1024px) */ + desktop?: { + maxCount?: number; + hideIcons?: boolean; + compactMode?: boolean; + }; + }; /** * Minimum width for the component. @@ -284,17 +300,17 @@ interface MultiSelectProps /** * The name of the field to complete */ - name: string + name: string; /** * Label of the field */ - label: string + label: string; /** - * Does the field required - */ - required?: boolean + * Does the field required + */ + required?: boolean; /** * The fonction to set the data in useForm inertia @@ -302,9 +318,9 @@ interface MultiSelectProps setData: (name: string, value: string[]) => void; /** - * Does the field required - */ - multiple?: boolean + * Does the field required + */ + multiple?: boolean; /** * Minimum number of selections required (only when multiple is true) @@ -323,6 +339,12 @@ interface MultiSelectProps * Optional, defaults to empty */ helper?: string; + + /** + * Make the Close button visible + * Optional, defaults to empty + */ + closeButtonVisible?: boolean; } /** @@ -386,11 +408,13 @@ export const MultiSelect = forwardRef( deduplicateOptions = false, resetOnDefaultValueChange = true, closeOnSelect = false, + closeButtonVisible = false, ...props }, - ref + ref, ) => { - const [selectedValues, setSelectedValues] = useState(defaultValue); + const [selectedValues, setSelectedValues] = + useState(defaultValue); const [isPopoverOpen, setIsPopoverOpen] = useState(false); const [isAnimating, setIsAnimating] = useState(false); const [searchValue, setSearchValue] = useState(""); @@ -413,7 +437,7 @@ export const MultiSelect = forwardRef( setTimeout(() => setPoliteMessage(""), 100); } }, - [] + [], ); const multiSelectId = useId(); @@ -421,26 +445,34 @@ export const MultiSelect = forwardRef( const triggerDescriptionId = `${multiSelectId}-description`; const selectedCountId = `${multiSelectId}-count`; + // Translations. + const transDelete = useTrans("crud.actions.delete"); + const transClose = useTrans("back.close"); + const transClear = useTrans("back.clear"); + const transNoResults = useTrans("back.table_no_results"); + const transSearchOptions = useTrans("back.multi_select.search_options"); + const transSelectAll = useTrans("back.multi_select.select_all"); + const transMore = useTrans("back.multi_select.more"); + const transClosePopover = useTrans("back.multi_select.close_popover"); + const transClearList = useTrans("back.multi_select.clear_list"); + const prevDefaultValueRef = useRef(defaultValue); const isGroupedOptions = useCallback( ( - opts: MultiSelectOption[] | MultiSelectGroup[] + opts: MultiSelectOption[] | MultiSelectGroup[], ): opts is MultiSelectGroup[] => { return opts.length > 0 && "heading" in opts[0]; }, - [] + [], ); - const arraysEqual = useCallback( - (a: string[], b: string[]): boolean => { - if (a.length !== b.length) return false; - const sortedA = [...a].sort(); - const sortedB = [...b].sort(); - return sortedA.every((val, index) => val === sortedB[index]); - }, - [] - ); + const arraysEqual = useCallback((a: string[], b: string[]): boolean => { + if (a.length !== b.length) return false; + const sortedA = [...a].sort(); + const sortedB = [...b].sort(); + return sortedA.every((val, index) => val === sortedB[index]); + }, []); const resetToDefault = useCallback(() => { setSelectedValues(defaultValue); @@ -477,19 +509,23 @@ export const MultiSelect = forwardRef( if (buttonRef.current) { buttonRef.current.focus(); const originalOutline = buttonRef.current.style.outline; - const originalOutlineOffset = buttonRef.current.style.outlineOffset; - buttonRef.current.style.outline = "2px solid hsl(var(--ring))"; + const originalOutlineOffset = + buttonRef.current.style.outlineOffset; + buttonRef.current.style.outline = + "2px solid hsl(var(--ring))"; buttonRef.current.style.outlineOffset = "2px"; setTimeout(() => { if (buttonRef.current) { - buttonRef.current.style.outline = originalOutline; - buttonRef.current.style.outlineOffset = originalOutlineOffset; + buttonRef.current.style.outline = + originalOutline; + buttonRef.current.style.outlineOffset = + originalOutlineOffset; } }, 1000); } }, }), - [resetToDefault, selectedValues, onValueChange] + [resetToDefault, selectedValues, onValueChange], ); const [screenSize, setScreenSize] = useState< @@ -527,9 +563,21 @@ export const MultiSelect = forwardRef( } if (responsive === true) { const defaultResponsive = { - mobile: { maxCount: 2, hideIcons: false, compactMode: true }, - tablet: { maxCount: 4, hideIcons: false, compactMode: false }, - desktop: { maxCount: 6, hideIcons: false, compactMode: false }, + mobile: { + maxCount: 2, + hideIcons: false, + compactMode: true, + }, + tablet: { + maxCount: 4, + hideIcons: false, + compactMode: false, + }, + desktop: { + maxCount: 6, + hideIcons: false, + compactMode: false, + }, }; const currentSettings = defaultResponsive[screenSize]; return { @@ -614,18 +662,22 @@ export const MultiSelect = forwardRef( uniqueOptions.push(option); } }); - if (process.env.NODE_ENV === "development" && duplicates.length > 0) { + if ( + process.env.NODE_ENV === "development" && + duplicates.length > 0 + ) { const action = deduplicateOptions ? "automatically removed" : "detected"; console.warn( `MultiSelect: Duplicate option values ${action}: ${duplicates.join( - ", " + ", ", )}. ` + - `${deduplicateOptions - ? "Duplicates have been removed automatically." - : "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique." - }` + `${ + deduplicateOptions + ? "Duplicates have been removed automatically." + : "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique." + }`, ); } return deduplicateOptions ? uniqueOptions : allOptions; @@ -633,15 +685,17 @@ export const MultiSelect = forwardRef( const getOptionByValue = useCallback( (value: string): MultiSelectOption | undefined => { - const option = getAllOptions().find((option) => option.value === value); + const option = getAllOptions().find( + (option) => option.value === value, + ); if (!option && process.env.NODE_ENV === "development") { console.warn( - `MultiSelect: Option with value "${value}" not found in options list` + `MultiSelect: Option with value "${value}" not found in options list`, ); } return option; }, - [getAllOptions] + [getAllOptions], ); const filteredOptions = useMemo(() => { @@ -656,24 +710,31 @@ export const MultiSelect = forwardRef( option.label .toLowerCase() .includes(searchValue.toLowerCase()) || - option.value.toLowerCase().includes(searchValue.toLowerCase()) + option.value + .toLowerCase() + .includes(searchValue.toLowerCase()), ), })) .filter((group) => group.options.length > 0); } return options.filter( (option) => - option.label.toLowerCase().includes(searchValue.toLowerCase()) || - option.value.toLowerCase().includes(searchValue.toLowerCase()) + option.label + .toLowerCase() + .includes(searchValue.toLowerCase()) || + option.value + .toLowerCase() + .includes(searchValue.toLowerCase()), ); }, [options, searchValue, searchable, isGroupedOptions]); - const handleInputKeyDown = ( - event: KeyboardEvent - ) => { + const handleInputKeyDown = (event: KeyboardEvent) => { if (event.key === "Enter") { setIsPopoverOpen(true); - } else if (event.key === "Backspace" && !event.currentTarget.value) { + } else if ( + event.key === "Backspace" && + !event.currentTarget.value + ) { const newSelectedValues = [...selectedValues]; newSelectedValues.pop(); setSelectedValues(newSelectedValues); @@ -691,7 +752,9 @@ export const MultiSelect = forwardRef( // MODE SINGLE SELECT if (!multiple) { - const newSelectedValues = selectedValues.includes(optionValue) ? [] : [optionValue]; + const newSelectedValues = selectedValues.includes(optionValue) + ? [] + : [optionValue]; setSelectedValues(newSelectedValues); if (onValueChange) { onValueChange(newSelectedValues); @@ -708,10 +771,15 @@ export const MultiSelect = forwardRef( if (isCurrentlySelected) { if (minSelection && selectedValues.length <= minSelection) { - announce(`Minimum ${minSelection} selection(s) required`, "assertive"); + announce( + `Minimum ${minSelection} selection(s) required`, + "assertive", + ); return; } - const newSelectedValues = selectedValues.filter((value) => value !== optionValue); + const newSelectedValues = selectedValues.filter( + (value) => value !== optionValue, + ); setSelectedValues(newSelectedValues); if (onValueChange) { onValueChange(newSelectedValues); @@ -719,7 +787,10 @@ export const MultiSelect = forwardRef( setData(name, newSelectedValues); } else { if (maxSelection && selectedValues.length >= maxSelection) { - announce(`Maximum ${maxSelection} selection(s) allowed`, "assertive"); + announce( + `Maximum ${maxSelection} selection(s) allowed`, + "assertive", + ); return; } const newSelectedValues = [...selectedValues, optionValue]; @@ -738,7 +809,10 @@ export const MultiSelect = forwardRef( const handleClear = () => { if (disabled) return; if (multiple && minSelection && minSelection > 0) { - announce(`Minimum ${minSelection} selection(s) required`, "assertive"); + announce( + `Minimum ${minSelection} selection(s) required`, + "assertive", + ); return; } setSelectedValues([]); @@ -757,7 +831,7 @@ export const MultiSelect = forwardRef( if (disabled) return; const newSelectedValues = selectedValues.slice( 0, - responsiveSettings.maxCount + responsiveSettings.maxCount, ); setSelectedValues(newSelectedValues); if (onValueChange) { @@ -768,18 +842,26 @@ export const MultiSelect = forwardRef( const toggleAll = () => { if (disabled || !multiple) return; - const allOptions = getAllOptions().filter((option) => !option.disabled); + const allOptions = getAllOptions().filter( + (option) => !option.disabled, + ); if (selectedValues.length === allOptions.length) { if (minSelection && minSelection > 0) { - announce(`Minimum ${minSelection} selection(s) required`, "assertive"); + announce( + `Minimum ${minSelection} selection(s) required`, + "assertive", + ); return; } handleClear(); } else { const allValues = allOptions.map((option) => option.value); if (maxSelection && allValues.length > maxSelection) { - announce(`Maximum ${maxSelection} selection(s) allowed`, "assertive"); + announce( + `Maximum ${maxSelection} selection(s) allowed`, + "assertive", + ); return; } setSelectedValues(allValues); @@ -803,7 +885,12 @@ export const MultiSelect = forwardRef( } prevDefaultValueRef.current = [...defaultValue]; } - }, [defaultValue, selectedValues, arraysEqual, resetOnDefaultValueChange]); + }, [ + defaultValue, + selectedValues, + arraysEqual, + resetOnDefaultValueChange, + ]); const getWidthConstraints = () => { const defaultMinWidth = screenSize === "mobile" ? "0px" : "200px"; @@ -827,29 +914,33 @@ export const MultiSelect = forwardRef( useEffect(() => { const selectedCount = selectedValues.length; const allOptions = getAllOptions(); - const totalOptions = allOptions.filter((opt) => !opt.disabled).length; + const totalOptions = allOptions.filter( + (opt) => !opt.disabled, + ).length; if (selectedCount !== prevSelectedCount.current) { const diff = selectedCount - prevSelectedCount.current; if (diff > 0) { const addedItems = selectedValues.slice(-diff); const addedLabels = addedItems .map( - (value) => allOptions.find((opt) => opt.value === value)?.label + (value) => + allOptions.find((opt) => opt.value === value) + ?.label, ) .filter(Boolean); if (addedLabels.length === 1) { announce( - `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.` + `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`, ); } else { announce( - `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.` + `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`, ); } } else if (diff < 0) { announce( - `Option removed. ${selectedCount} of ${totalOptions} options selected.` + `Option removed. ${selectedCount} of ${totalOptions} options selected.`, ); } prevSelectedCount.current = selectedCount; @@ -858,7 +949,7 @@ export const MultiSelect = forwardRef( if (isPopoverOpen !== prevIsOpen.current) { if (isPopoverOpen) { announce( - `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.` + `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`, ); } else { announce("Dropdown closed."); @@ -873,31 +964,53 @@ export const MultiSelect = forwardRef( if (searchValue && isPopoverOpen) { const filteredCount = allOptions.filter( (opt) => - opt.label.toLowerCase().includes(searchValue.toLowerCase()) || - opt.value.toLowerCase().includes(searchValue.toLowerCase()) + opt.label + .toLowerCase() + .includes(searchValue.toLowerCase()) || + opt.value + .toLowerCase() + .includes(searchValue.toLowerCase()), ).length; announce( - `${filteredCount} option${filteredCount === 1 ? "" : "s" - } found for "${searchValue}"` + `${filteredCount} option${ + filteredCount === 1 ? "" : "s" + } found for "${searchValue}"`, ); } prevSearchValue.current = searchValue; } - }, [selectedValues, isPopoverOpen, searchValue, announce, getAllOptions]); + }, [ + selectedValues, + isPopoverOpen, + searchValue, + announce, + getAllOptions, + ]); useEffect(() => { - if (minSelection !== undefined && maxSelection !== undefined && minSelection > maxSelection) { - console.error('MultiSelect: minSelection cannot be greater than maxSelection'); + if ( + minSelection !== undefined && + maxSelection !== undefined && + minSelection > maxSelection + ) { + console.error( + "MultiSelect: minSelection cannot be greater than maxSelection", + ); } - if (!multiple && (minSelection !== undefined || maxSelection !== undefined)) { - console.warn('MultiSelect: minSelection and maxSelection are ignored when multiple is false'); + if ( + !multiple && + (minSelection !== undefined || maxSelection !== undefined) + ) { + console.warn( + "MultiSelect: minSelection and maxSelection are ignored when multiple is false", + ); } if (minSelection !== undefined && minSelection < 0) { - console.error('MultiSelect: minSelection cannot be negative'); + console.error("MultiSelect: minSelection cannot be negative"); } if (maxSelection !== undefined && maxSelection < 1) { - console.error('MultiSelect: maxSelection must be at least 1'); + console.error("MultiSelect: maxSelection must be at least 1"); } }, [minSelection, maxSelection, multiple]); @@ -915,21 +1028,28 @@ export const MultiSelect = forwardRef( + modal={modalPopover} + >
    - Multi-select dropdown. Use arrow keys to navigate, Enter to select, - and Escape to close. + Multi-select dropdown. Use arrow keys to navigate, Enter + to select, and Escape to close.
    -
    +
    {selectedValues.length === 0 ? "No options selected" - : `${selectedValues.length} option${selectedValues.length === 1 ? "" : "s" - } selected: ${selectedValues - .map((value) => getOptionByValue(value)?.label) - .filter(Boolean) - .join(", ")}`} + : `${selectedValues.length} option${ + selectedValues.length === 1 ? "" : "s" + } selected: ${selectedValues + .map( + (value) => getOptionByValue(value)?.label, + ) + .filter(Boolean) + .join(", ")}`}
    - @@ -1137,74 +1303,111 @@ export const MultiSelect = forwardRef( aria-multiselectable="true" aria-label="Available options" className={cn( - "w-auto p-0", + "w-[var(--radix-popover-trigger-width)] p-0", getPopoverAnimationClass(), - screenSize === "mobile" && "w-[85vw] max-w-[280px]", - screenSize === "tablet" && "w-[70vw] max-w-md", - screenSize === "desktop" && "min-w-[300px]", - popoverClassName + popoverClassName, )} style={{ animationDuration: `${animationConfig?.duration || animation}s`, animationDelay: `${animationConfig?.delay || 0}s`, maxWidth: `min(${widthConstraints.maxWidth}, 85vw)`, - maxHeight: screenSize === "mobile" ? "70vh" : "60vh", + maxHeight: + screenSize === "mobile" ? "70vh" : "60vh", touchAction: "manipulation", }} align="start" - onEscapeKeyDown={() => setIsPopoverOpen(false)}> - + onEscapeKeyDown={() => setIsPopoverOpen(false)} + > + {searchable && ( - - )} - {searchable && ( -
    - Type to filter options. Use arrow keys to navigate results. +
    +
    + +
    + + setSearchValue(e.target.value) + } + onKeyDown={handleInputKeyDown} + className="w-[calc(100%-2.5rem-40px)] border-0 mx-9" + /> + } + tooltipContent={ +

    + {str(transDelete) + .ucFirst() + .value()} +

    + } + type="button" + variant="ghost" + size="icon" + className="absolute top-1/2 right-0 transform -translate-y-1/2 text-muted-foreground" + onClick={() => setSearchValue("")} + disabled={ + searchValue.length < 1 || disabled + } + />
    )} - + {searchable && ( +
    + Type to filter options. Use arrow keys to + navigate results. +
    + )} + - {emptyIndicator || "No results found."} - {" "} + {emptyIndicator || transNoResults} + + {/* First option for select all items */} {!hideSelectAll && !searchValue && multiple && ( - + !opt.disabled).length + getAllOptions().filter( + (opt) => !opt.disabled, + ).length } - aria-label={`Select all ${getAllOptions().length - } options`} - className="cursor-pointer"> + aria-label={`Select all ${ + getAllOptions().length + } options`} + className="cursor-pointer gap-1.5 px-4 py-2 w-full h-auto min-h-10" + >
    !opt.disabled) - .length + getAllOptions().filter( + (opt) => + !opt.disabled, + ).length ? "bg-primary text-primary-foreground" - : "opacity-50 [&_svg]:invisible" + : "opacity-50 [&_svg]:invisible", )} - aria-hidden="true"> + aria-hidden="true" + >
    - ({str(useTrans('back.multi_select.select_all')).ucFirst().value()} + ( + {str(transSelectAll) + .ucFirst() + .value()} {getAllOptions().length > 20 ? ` - ${getAllOptions().length} options` : ""} @@ -1213,80 +1416,119 @@ export const MultiSelect = forwardRef(
    )} + {/* List of items */} {isGroupedOptions(filteredOptions) ? ( filteredOptions.map((group) => ( - + {group.options.map((option) => { - const isSelected = selectedValues.includes( - option.value - ); + const isSelected = + selectedValues.includes( + option.value, + ); return ( toggleOption(option.value)} + onSelect={() => + toggleOption( + option.value, + ) + } role="option" - aria-selected={isSelected} - aria-disabled={option.disabled} - aria-label={`${option.label}${isSelected ? ", selected" : ", not selected" - }${option.disabled ? ", disabled" : ""}`} + aria-selected={ + isSelected + } + aria-disabled={ + option.disabled + } + aria-label={`${option.label}${ + isSelected + ? ", selected" + : ", not selected" + }${option.disabled ? ", disabled" : ""}`} className={cn( - "cursor-pointer", - option.disabled && "opacity-50 cursor-not-allowed" + "cursor-pointer gap-1.5 px-4 py-2 w-full h-auto min-h-10", + option.disabled && + "opacity-50 cursor-not-allowed", )} - disabled={option.disabled}> + disabled={ + option.disabled + } + > {option.icon && ( ); })} )) ) : ( - + {filteredOptions.map((option) => { - const isSelected = selectedValues.includes(option.value); + const isSelected = + selectedValues.includes( + option.value, + ); return ( toggleOption(option.value)} + onSelect={() => + toggleOption( + option.value, + ) + } role="option" aria-selected={isSelected} - aria-disabled={option.disabled} - aria-label={`${option.label}${isSelected ? ", selected" : ", not selected" - }${option.disabled ? ", disabled" : ""}`} + aria-disabled={ + option.disabled + } + aria-label={`${option.label}${ + isSelected + ? ", selected" + : ", not selected" + }${option.disabled ? ", disabled" : ""}`} className={cn( - "cursor-pointer", - option.disabled && "opacity-50 cursor-not-allowed" + "cursor-pointer gap-1.5 px-4 py-2 w-full h-auto min-h-10", + option.disabled && + "opacity-50 cursor-not-allowed", )} - disabled={option.disabled}> + disabled={option.disabled} + > {option.icon && ( )} - - -
    + + {(closeButtonVisible || + selectedValues.length > 0) && ( + +
    {selectedValues.length > 0 && ( - <> - - {str(useTrans('back.clear')).ucFirst().value()} - + + {str(transClearList) + .ucFirst() + .value()} +

    + } + className="w-full" + type="button" + variant="ghost" + size="default" + onClick={handleClear} + disabled={disabled} + /> + )} + {closeButtonVisible && + selectedValues.length > 0 && ( - + )} + {closeButtonVisible && ( + + {str(transClosePopover) + .ucFirst() + .value()} +

    + } + className="w-full" + type="button" + variant="ghost" + size="default" + onClick={() => + setIsPopoverOpen(false) + } + disabled={disabled} + /> )} - setIsPopoverOpen(false)} - className="flex-1 justify-center cursor-pointer max-w-full"> - {str(useTrans('back.close')).ucFirst().value()} -
    - + )} {animation > 0 && selectedValues.length > 0 && ( - setIsAnimating(!isAnimating)} /> )} - {helper && ({helper})} + {helper && ( + {helper} + )}
    ); - } + }, ); MultiSelect.displayName = "MultiSelect"; diff --git a/resources/ts/back/Pages/Document/Actions/Filters.tsx b/resources/ts/back/Pages/Document/Actions/Filters.tsx index 8fd390e4..00f59069 100644 --- a/resources/ts/back/Pages/Document/Actions/Filters.tsx +++ b/resources/ts/back/Pages/Document/Actions/Filters.tsx @@ -31,7 +31,6 @@ export default function Filters() { modelName={modelName} label={str(useTrans('back.model_filters.has_no_link.label')).ucFirst().value()} /> - -
    From bede89f62ce41c9f4cd04be5452ca418101bc1b8 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Wed, 21 Jan 2026 17:14:53 +0100 Subject: [PATCH 13/19] refactor: :recycle: set generic wrapper for crud filters --- app/Helpers/DocumentHelper.php | 3 +- lang/en/back.php | 17 +-- lang/fr/back.php | 17 +-- .../ts/back/Components/Documents/Filters.tsx | 100 ++++++++++++++++++ .../ts/back/Components/FiltersWrapper.tsx | 62 +++++++++++ .../ts/back/Components/Inputs/MultiSelect.tsx | 29 +++-- .../Pages/Document/Actions/ButtonTrigger.tsx | 36 ------- .../back/Pages/Document/Actions/Filters.tsx | 55 ---------- resources/ts/back/Pages/Document/Index.tsx | 4 +- 9 files changed, 197 insertions(+), 126 deletions(-) create mode 100644 resources/ts/back/Components/Documents/Filters.tsx create mode 100644 resources/ts/back/Components/FiltersWrapper.tsx delete mode 100644 resources/ts/back/Pages/Document/Actions/ButtonTrigger.tsx delete mode 100644 resources/ts/back/Pages/Document/Actions/Filters.tsx diff --git a/app/Helpers/DocumentHelper.php b/app/Helpers/DocumentHelper.php index 97cce79b..f9598d3c 100644 --- a/app/Helpers/DocumentHelper.php +++ b/app/Helpers/DocumentHelper.php @@ -7,7 +7,6 @@ use Illuminate\Http\Request; class DocumentHelper { - /** * Extract the Issuu embed URL from an iframe or raw Issuu input. * @@ -51,7 +50,7 @@ class DocumentHelper /** * Return a document query with all the request filters applied * - * @param Request $request + * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query * @return \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query */ diff --git a/lang/en/back.php b/lang/en/back.php index 8d264d12..a3e8f564 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -265,21 +265,22 @@ return [ ] ], "refresh_original" => "reset to original state", - "model_filters" => [ - "button_label" => "filters", - "select_status" => [ + "model_filters" => [ + "button_tooltip" => "open the filters window", + "sheet_title" => "filters window", + "select_status" => [ "label" => "status", "placeholder" => "choose a status" ], - "has_no_link" => [ + "has_no_link" => [ "label" => "filter document with no usable link" ], - "categories" => [ - "label" => "filter by category", + "categories" => [ + "label" => "filter by category", "placeholder" => "select one or more categories" ], - "tags" => [ - "label" => "filter by tag", + "tags" => [ + "label" => "filter by tag", "placeholder" => "select one or more tags" ], ], diff --git a/lang/fr/back.php b/lang/fr/back.php index cd0153bd..7df0bdf3 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -267,20 +267,21 @@ return [ ], "refresh_original" => "remettre à l'état d'origine", "model_filters" => [ - "button_label" => "filtres", - "select_status" => [ - "label" => "statut", + "button_tooltip" => "ouvrir la fenêtre des filtres", + "sheet_title" => "fenêtre des filtres", + "select_status" => [ + "label" => "filtrer par statut", "placeholder" => "selectionner un statut" ], - "has_no_link" => [ + "has_no_link" => [ "label" => "filtrer les documents qui n'ont aucun lien d'accès" ], - "categories" => [ - "label" => "filtrer par categorie", + "categories" => [ + "label" => "filtrer par catégorie", "placeholder" => "selectionner une ou plusieurs catégories" ], - "tags" => [ - "label" => "filtrer par étiquette", + "tags" => [ + "label" => "filtrer par étiquette", "placeholder" => "selectionner une ou plusieurs étiquettes" ], ], diff --git a/resources/ts/back/Components/Documents/Filters.tsx b/resources/ts/back/Components/Documents/Filters.tsx new file mode 100644 index 00000000..a6b2adb4 --- /dev/null +++ b/resources/ts/back/Components/Documents/Filters.tsx @@ -0,0 +1,100 @@ +// * Packages +import { usePage } from "@inertiajs/react"; +// * Other +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; +import EnumFilter from "@/back/Components/Filters/EnumFilter"; +import SwitchFilter from "@/back/Components/Filters/SwitchFilter"; +import MultiSelectRelationFilter from "@/back/Components/Filters/MultiSelectRelationFilter"; +import FiltersWrapper from "@/back/Components/FiltersWrapper"; +import { + DocumentCategoryModel, + DocumentTagModel, + LaravelEnum, +} from "@/back/types/global"; + +const Filters = () => { + const modelName = usePage().props.modelName as string; + const categories = usePage().props.categories as DocumentCategoryModel[]; + const tags = usePage().props.tags as DocumentTagModel[]; + const enumDocumentStatus = usePage().props.enumDocumentStatus as LaravelEnum; + + return ( + + + + + + + ); +}; + +export default Filters; diff --git a/resources/ts/back/Components/FiltersWrapper.tsx b/resources/ts/back/Components/FiltersWrapper.tsx new file mode 100644 index 00000000..62e75cac --- /dev/null +++ b/resources/ts/back/Components/FiltersWrapper.tsx @@ -0,0 +1,62 @@ +// * Packages +import { Filter } from "lucide-react"; +import { ReactNode } from "react"; +// * Components shadcn +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle, + SheetTrigger, +} from "@/components/ui/sheet"; +// * Other +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; + +const FiltersWrapper = ({ children }: { children: ReactNode }) => { + return ( +
    +
    + + + } + tooltipContent={ +

    + {str( + useTrans( + "back.model_filters.button_tooltip", + ), + ) + .ucFirst() + .value()} +

    + } + type="button" + size="icon" + variant="outline" + /> +
    + + + + {str(useTrans("back.model_filters.sheet_title")) + .ucFirst() + .value()} + + + +
    + {children} +
    +
    +
    +
    +
    +
    + ); +}; + +export default FiltersWrapper; diff --git a/resources/ts/back/Components/Inputs/MultiSelect.tsx b/resources/ts/back/Components/Inputs/MultiSelect.tsx index b14151f8..64d805bc 100644 --- a/resources/ts/back/Components/Inputs/MultiSelect.tsx +++ b/resources/ts/back/Components/Inputs/MultiSelect.tsx @@ -1057,6 +1057,7 @@ export const MultiSelect = forwardRef( onClick={handleTogglePopover} disabled={disabled} role="combobox" + variant="outline" aria-expanded={isPopoverOpen} aria-haspopup="listbox" aria-controls={ @@ -1067,10 +1068,9 @@ export const MultiSelect = forwardRef( getAllOptions().length } options selected. ${placeholder}`} className={cn( - "flex rounded-md border min-h-10 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto gap-2 px-4 py-2", + "group/button flex rounded-md border min-h-10 h-auto items-center justify-between [&_svg]:pointer-events-auto gap-2 px-4 py-2", autoSize ? "w-auto" : "w-full", - responsiveSettings.compactMode && - "min-h-8 text-sm", + responsiveSettings.compactMode && "min-h-8 text-sm", screenSize === "mobile" && "min-h-12 text-base", disabled && "opacity-50 cursor-not-allowed", className, @@ -1255,8 +1255,9 @@ export const MultiSelect = forwardRef( )}
    -
    { event.stopPropagation(); @@ -1273,26 +1274,24 @@ export const MultiSelect = forwardRef( } }} aria-label={`Clear all ${selectedValues.length} selected options`} - className="flex items-center justify-center h-4 w-4 me-2 cursor-pointer text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 rounded-sm" + className="flex items-center justify-center h-4 w-4 p-0 me-2 cursor-pointer transition-opacity opacity-50 group-hover:opacity-60 hover:opacity-100 rounded-sm" > -
    +
    ) : ( -
    - - {placeholder} - - +
    +

    {placeholder}

    +
    )} @@ -1401,7 +1400,7 @@ export const MultiSelect = forwardRef( )} aria-hidden="true" > - +
    ( @@ -1467,7 +1466,7 @@ export const MultiSelect = forwardRef( )} aria-hidden="true" > - +
    {option.icon && ( ( )} aria-hidden="true" > - +

    {option.icon && ( { - return ( -
    -
    - - - - - - - - {str(useTrans("back.model_filters.button_label")).ucFirst().value()} - - - - - -
    -
    - ); -} - -export default ButtonTrigger; diff --git a/resources/ts/back/Pages/Document/Actions/Filters.tsx b/resources/ts/back/Pages/Document/Actions/Filters.tsx deleted file mode 100644 index 00f59069..00000000 --- a/resources/ts/back/Pages/Document/Actions/Filters.tsx +++ /dev/null @@ -1,55 +0,0 @@ -// * Packages -import { usePage } from "@inertiajs/react"; -// * Components shadcn -import { SheetDescription } from "@/components/ui/sheet"; -// * Other -import EnumFilter from "@/back/Components/Filters/EnumFilter"; -import SwitchFilter from "@/back/Components/Filters/SwitchFilter"; -import MultiSelectRelationFilter from "@/back/Components/Filters/MultiSelectRelationFilter"; -import { DocumentCategoryModel, DocumentTagModel, LaravelEnum } from "@/back/types/global"; -import useTrans from "@/hooks/use-translations"; -import str from "@/hooks/use-string"; - -export default function Filters() { - const modelName = usePage().props.modelName as string; - const categories = usePage().props.categories as DocumentCategoryModel[]; - const tags = usePage().props.tags as DocumentTagModel[]; - const enumDocumentStatus = usePage().props.enumDocumentStatus as LaravelEnum; - - return ( - -
    - - - - -
    -
    - ); -} diff --git a/resources/ts/back/Pages/Document/Index.tsx b/resources/ts/back/Pages/Document/Index.tsx index a71554fd..bc00fefe 100644 --- a/resources/ts/back/Pages/Document/Index.tsx +++ b/resources/ts/back/Pages/Document/Index.tsx @@ -16,9 +16,9 @@ import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import ButtonTrigger from "@/back/Pages/Document/Actions/ButtonTrigger"; import DocumentStatusBadge from "@/back/Components/Documents/DocumentStatusBadge"; import DocumentFinanceTagBadge from "@/back/Components/Documents/DocumentFinanceTagBadge"; +import Filters from "@/back/Components/Documents/Filters"; import { cn, Views } from "@/lib/utils"; import { renderTranslationCell } from "@/lib/translationCellFallback"; import { useFormatedDate } from "@/hooks/use-formated-value"; @@ -260,7 +260,7 @@ export default function Index({ searchText={search} searchFields={searchFields} > - + Date: Thu, 22 Jan 2026 12:22:55 +0100 Subject: [PATCH 14/19] fix: :bug: update relations buttons in back pages --- .../Controllers/Back/CompanyController.php | 2 +- app/Http/Controllers/Back/NewsController.php | 2 +- app/Models/News.php | 40 +-- .../Documents/DocumentFinanceTagBadge.tsx | 17 -- .../Components/News/NewsCategoriesBadge.tsx | 23 -- .../ts/back/Pages/ActivityLogs/Index.tsx | 111 ++++++-- resources/ts/back/Pages/ActivityLogs/Show.tsx | 2 + resources/ts/back/Pages/Companies/Index.tsx | 163 ++++++++++-- resources/ts/back/Pages/Document/Index.tsx | 80 ++++-- resources/ts/back/Pages/Document/Show.tsx | 140 ++++++---- .../ts/back/Pages/DynamicPages/Index.tsx | 82 ++++-- resources/ts/back/Pages/News/Index.tsx | 247 +++++++++++++----- resources/ts/back/Pages/News/Show.tsx | 106 ++++++-- resources/ts/back/Pages/PageConfigs/Index.tsx | 2 +- resources/ts/back/Pages/PageConfigs/Show.tsx | 1 + resources/ts/back/Pages/Users/Index.tsx | 4 +- resources/ts/back/Pages/Users/Show.tsx | 4 +- 17 files changed, 749 insertions(+), 277 deletions(-) delete mode 100644 resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx delete mode 100644 resources/ts/back/Components/News/NewsCategoriesBadge.tsx diff --git a/app/Http/Controllers/Back/CompanyController.php b/app/Http/Controllers/Back/CompanyController.php index 35c8e731..3abd4a71 100644 --- a/app/Http/Controllers/Back/CompanyController.php +++ b/app/Http/Controllers/Back/CompanyController.php @@ -36,7 +36,7 @@ class CompanyController extends Controller public function index(Request $request): \Inertia\Response { /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Company> $query */ - $query = Company::query(); + $query = Company::query()->with(['companyActivity', 'companySector']); if ($request->routeIs("back.$this->modelName.trash")) { $query = $query->onlyTrashed(); diff --git a/app/Http/Controllers/Back/NewsController.php b/app/Http/Controllers/Back/NewsController.php index 9bbf5fe5..129476f6 100644 --- a/app/Http/Controllers/Back/NewsController.php +++ b/app/Http/Controllers/Back/NewsController.php @@ -36,7 +36,7 @@ class NewsController extends Controller public function index(Request $request): \Inertia\Response { /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $query */ - $query = News::query(); + $query = News::query()->with('categories'); if ($request->routeIs("back.news.trash")) { $query = $query->onlyTrashed(); diff --git a/app/Models/News.php b/app/Models/News.php index 2f967f14..5faf6e99 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -413,6 +413,26 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable return $data; } + /** + * Get all published news by category. + * + * @param string $category + * + * @return \Illuminate\Database\Eloquent\Collection + */ + public static function getPublishedNewsByCategoryInCurrentLocale(string $category) + { + $locale = App::getLocale(); + + return News::getModelsCached() + ->where('status', NewsStatusEnum::published) + ->filter(function ($news) use ($category, $locale) { + return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains( + fn ($cat) => $cat->slug === $category + ); + }); + } + // * RELATIONSHIPS /** @@ -446,24 +466,4 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable 'newsable_id' )->withTimestamps(); } - - /** - * Get all published news by category. - * - * @param string $category - * - * @return \Illuminate\Database\Eloquent\Collection - */ - public static function getPublishedNewsByCategoryInCurrentLocale(string $category) - { - $locale = App::getLocale(); - - return News::getModelsCached() - ->where('status', NewsStatusEnum::published) - ->filter(function ($news) use ($category, $locale) { - return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains( - fn ($cat) => $cat->slug === $category - ); - }); - } } diff --git a/resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx b/resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx deleted file mode 100644 index 14db2ed7..00000000 --- a/resources/ts/back/Components/Documents/DocumentFinanceTagBadge.tsx +++ /dev/null @@ -1,17 +0,0 @@ -// * Components shadcn -import { Badge } from "@/components/ui/badge"; - -type DocumentFinanceTagBadgeProps = { - value: string; -}; - -export default function DocumentFinanceTagBadge({ - value, -}: DocumentFinanceTagBadgeProps) { - - return ( - - {value} - - ); -} diff --git a/resources/ts/back/Components/News/NewsCategoriesBadge.tsx b/resources/ts/back/Components/News/NewsCategoriesBadge.tsx deleted file mode 100644 index 7bc93fe4..00000000 --- a/resources/ts/back/Components/News/NewsCategoriesBadge.tsx +++ /dev/null @@ -1,23 +0,0 @@ -// * Packages -import { usePage } from "@inertiajs/react"; -// * Components shadcn -import { Badge } from "@/components/ui/badge"; -// * Other -import { AppEnv, TranslationField } from "@/back/types/global"; - -type NewsCategoriesBadgeProps = { - value: TranslationField | string; -}; - -export default function NewsCategoriesBadge({ - value, -}: NewsCategoriesBadgeProps) { - const { appEnv } = usePage().props as unknown as { - appEnv: AppEnv; - }; - return ( - - {(value as TranslationField)[appEnv.locale]} - - ); -} diff --git a/resources/ts/back/Pages/ActivityLogs/Index.tsx b/resources/ts/back/Pages/ActivityLogs/Index.tsx index 14ce8b61..dd7d3e46 100644 --- a/resources/ts/back/Pages/ActivityLogs/Index.tsx +++ b/resources/ts/back/Pages/ActivityLogs/Index.tsx @@ -37,13 +37,21 @@ export default function Index({ accessorKey: "event", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: { original: ActivityLogModel; getValue: Function } }) => { + cell: ({ + row, + }: { + row: { original: ActivityLogModel; getValue: Function }; + }) => { const currentEvent = Object.values( - activityLogsEventEnum + activityLogsEventEnum, ).filter((index) => index.value === row.getValue("event")); const bgClass = `bg-${currentEvent[0].tailwindclass}`; const hoverClass = `hover:bg-${currentEvent[0].tailwindclass}/90`; @@ -61,21 +69,44 @@ export default function Index({ accessorKey: "user_id", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: { original: ActivityLogModel; getValue: Function } }) => { + cell: ({ + row, + }: { + row: { original: ActivityLogModel; getValue: Function }; + }) => { if (row.original.user) return ( - - {`${row.original.user.first_name} ${row.original.user.last_name}`} - } - tooltipContent={

    {useTrans("activity-logs.access_model", { params: { model: useTrans('models.classes.user') }})}

    } + link={route("back.users.show", { + user: row.original.user_id, + })} + content={ + <> + + {`${row.original.user.first_name} ${row.original.user.last_name}`} + + } + tooltipContent={ +

    + {useTrans("activity-logs.access_model", { + params: { + model: useTrans( + "models.classes.user", + ), + }, + })} +

    + } size="sm" + variant="secondary" /> ); else if (row.original.is_console) @@ -89,32 +120,63 @@ export default function Index({ accessorKey: "model_class", header: ({ column }: { column: { id: string } }) => ( ), - cell: ({ row }: { row: { getValue: Function, original: ActivityLogModel } }) => { + cell: ({ + row, + }: { + row: { getValue: Function; original: ActivityLogModel }; + }) => { const modelSplit = row.getValue("model_class").split("\\"); const modelName = modelSplit[modelSplit.length - 1]; const model = str(modelName).kebabCase().value(); - return row.original.event !== activityLogsEventEnum.deleted.value ? ( + return row.original.event !== + activityLogsEventEnum.deleted.value ? ( - - {row.getValue("model_class")} - } - tooltipContent={

    {useTrans("activity-logs.access_model", { params: { model: useTrans(`activity-logs.attributes.model_class`) } })}

    } + link={route( + `back.${str(model).plural().value()}.show`, + row.original.model_id, + )} + content={ + <> + + {row.getValue("model_class")} + + } + tooltipContent={ +

    + {useTrans("activity-logs.access_model", { + params: { + model: useTrans( + `activity-logs.attributes.model_class`, + ), + }, + })} +

    + } size="sm" + variant="secondary" /> - ) : {row.getValue("model_class")} + ) : ( + + {row.getValue("model_class")} + + ); }, }, { accessorKey: "created_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -127,7 +189,10 @@ export default function Index({ ]; return ( } tooltipContent={

    {useTrans("activity-logs.access_model", { params: { model: useTrans('models.classes.user') }})}

    } size="sm" + variant="secondary" /> ); else if (activityLogModel.is_console) @@ -94,6 +95,7 @@ export default function Show({ } tooltipContent={

    {useTrans("activity-logs.access_model", { params: { model: useTrans('activity-logs.attributes.model_class') } })}

    } size="sm" + variant="secondary" /> ) : {value} }, diff --git a/resources/ts/back/Pages/Companies/Index.tsx b/resources/ts/back/Pages/Companies/Index.tsx index e59e02a6..04a12fce 100644 --- a/resources/ts/back/Pages/Companies/Index.tsx +++ b/resources/ts/back/Pages/Companies/Index.tsx @@ -21,7 +21,14 @@ import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import { Views } from "@/lib/utils"; -import { AuthProp, CompanyModel, Resource } from "@/back/types/global"; +import { + AppEnv, + AuthProp, + CompanyActivityModel, + CompanyModel, + CompanySectorModel, + Resource, +} from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; @@ -36,7 +43,8 @@ export default function Index({ searchFields: string; modelName: string; }) { - const { auth } = usePage().props as unknown as { + const { appEnv, auth } = usePage().props as unknown as { + appEnv: AppEnv; auth: AuthProp; }; const { viewAny, viewTrash, create } = auth.policies.companies; @@ -66,30 +74,149 @@ export default function Index({ cell: ({ row }: { row: Row }) => row.getValue("name"), }, { - accessorKey: "latitude", - header: ({ column }: { column: { id: string } }) => ( - ( +

    + {str( + useTrans("models.classes.company-activity", { + choice: 1, + }), + ) .ucFirst() .value()} - field={column.id} - /> +

    ), - cell: ({ row }: { row: Row }) => - row.getValue("latitude"), + cell: ({ row }: { row: Row }) => { + const activity = row.getValue( + "company_activity", + ) as CompanyActivityModel | null; + return activity ? ( +
    + {viewAnyCompanyActivities ? ( + + + + {activity.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.company-activity", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {activity.name[appEnv.locale]} + + )} +
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ); + }, }, { - accessorKey: "longitude", - header: ({ column }: { column: { id: string } }) => ( - ( +

    + {str( + useTrans("models.classes.company-sector", { + choice: 1, + }), + ) .ucFirst() .value()} - field={column.id} - /> +

    ), - cell: ({ row }: { row: Row }) => - row.getValue("longitude"), + cell: ({ row }: { row: Row }) => { + const sector = row.getValue( + "company_sector", + ) as CompanySectorModel | null; + return sector ? ( +
    + {viewAnyCompanySectors ? ( + + + + {sector.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.company-sector", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {sector.name[appEnv.locale]} + + )} +
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ); + }, + }, + { + accessorKey: "coords", + header: () => ( +

    + {str(useTrans("validation.custom.latitude")) + .ucFirst() + .value()} + / + {str(useTrans("validation.custom.longitude")) + .ucFirst() + .value()} +

    + ), + cell: ({ row }: { row: Row }) => { + return ( +

    + {row.original.latitude}/{row.original.longitude} +

    + ); + }, }, { accessorKey: "published", diff --git a/resources/ts/back/Pages/Document/Index.tsx b/resources/ts/back/Pages/Document/Index.tsx index bc00fefe..eb2150f6 100644 --- a/resources/ts/back/Pages/Document/Index.tsx +++ b/resources/ts/back/Pages/Document/Index.tsx @@ -17,7 +17,6 @@ import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import DocumentStatusBadge from "@/back/Components/Documents/DocumentStatusBadge"; -import DocumentFinanceTagBadge from "@/back/Components/Documents/DocumentFinanceTagBadge"; import Filters from "@/back/Components/Documents/Filters"; import { cn, Views } from "@/lib/utils"; import { renderTranslationCell } from "@/lib/translationCellFallback"; @@ -25,6 +24,7 @@ import { useFormatedDate } from "@/hooks/use-formated-value"; import { AppEnv, AuthProp, + DocumentCategoryModel, DocumentModel, Resource, TranslationField, @@ -48,8 +48,7 @@ export default function Index({ appEnv: AppEnv; }; const { create } = auth.policies.documents; - const { viewAny: viewAnyDocumentCategories } = - auth.policies.documentCategories; + const { viewAny: viewAnyDocumentCategories } = auth.policies.documentCategories; const { viewAny: viewAnyDocumentTags } = auth.policies.documentTags; const actionModels = [Views.VISUALIZATION, Views.EDITION, Views.DELETION]; const columns = [ @@ -94,7 +93,6 @@ export default function Index({ )} - {renderTranslationCell( row.getValue("name") as TranslationField, )} @@ -104,18 +102,10 @@ export default function Index({ }, { accessorKey: "categories", - header: ({ column }: { column: { id: string } }) => ( + header: () => (

    {str( - useTrans("back.associated_model", { - params: { - model: useTrans( - "models.classes.document-category", - { - choice: 2, - }, - ), - }, + useTrans("models.classes.document-category", { choice: 2, }), ) @@ -123,22 +113,54 @@ export default function Index({ .value()}

    ), - cell: ({ row }: { row: Row }) => { - if ( - !row.original.categories || - row.original.categories.length === 0 - ) - return null; - - return ( -
    - {row.original.categories.map((item, i) => ( - - ))} + cell: ({ row }: { row: Row }) => { + const categories = row.getValue( + "categories", + ) as DocumentCategoryModel[]; + return categories && categories.length > 0 ? ( +
    + {categories.map((item) => + viewAnyDocumentCategories ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.document-category", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    ); }, }, diff --git a/resources/ts/back/Pages/Document/Show.tsx b/resources/ts/back/Pages/Document/Show.tsx index 665e8bb2..494ef335 100644 --- a/resources/ts/back/Pages/Document/Show.tsx +++ b/resources/ts/back/Pages/Document/Show.tsx @@ -1,6 +1,7 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeft, FolderIcon, TagIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other @@ -21,10 +22,8 @@ import { import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { ArrowLeft } from "lucide-react"; import useLocale from "@/store/use-locale-store"; import DocumentStatusBadge from "@/back/Components/Documents/DocumentStatusBadge"; -import DocumentFinanceTagBadge from "@/back/Components/Documents/DocumentFinanceTagBadge"; import YearsEnumeBadge from "@/back/Components/Documents/DocumentExerciceBadge"; export default function Show({ @@ -39,6 +38,8 @@ export default function Show({ appEnv: AppEnv; }; const { viewAny } = auth.policies.documents; + const { viewAny: viewAnyDocumentCategories } = auth.policies.documentCategories; + const { viewAny: viewAnyDocumentTags } = auth.policies.documentTags; const docsModel = data.data as DocumentModel; const actionModels = [Views.EDITION, Views.DELETION]; const singularModelName = str(modelName).singular().value(); @@ -130,59 +131,108 @@ export default function Show({ }, }, { - accessorKey: "tags", - header: str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.document-tag", { - choice: 2, - }), - }, - choice: 2, - }), - ) + accessorKey: "categories", + header: str(useTrans("models.classes.document-category", { choice: 2 })) .ucFirst() .value(), - cell: ({ value }: { value?: DocumentTagModel[] }) => { - if (!value || value.length === 0) return null; - - return ( -
    - {value.map((item, i) => ( - - ))} + cell: ({ value }: { value?: DocumentCategoryModel[] }) => { + return value !== undefined && value.length > 0 ? ( +
    + {value.map((item) => + viewAnyDocumentCategories ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.document-category", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    ); }, }, { - accessorKey: "categories", - header: str( - useTrans("back.associated_model", { - params: { - model: useTrans("models.classes.document-category", { - choice: 2, - }), - }, - choice: 2, - }), - ) + accessorKey: "tags", + header: str(useTrans("models.classes.document-tag", { choice: 2 })) .ucFirst() .value(), - cell: ({ value }: { value?: DocumentCategoryModel[] }) => { - if (!value || value.length === 0) return null; - return ( -
    - {value.map((item, i) => ( - - ))} + cell: ({ value }: { value?: DocumentTagModel[] }) => { + return value !== undefined && value.length > 0 ? ( +
    + {value.map((item) => + viewAnyDocumentTags ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.document-tag", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    ); }, }, diff --git a/resources/ts/back/Pages/DynamicPages/Index.tsx b/resources/ts/back/Pages/DynamicPages/Index.tsx index 47f6f411..4d231567 100644 --- a/resources/ts/back/Pages/DynamicPages/Index.tsx +++ b/resources/ts/back/Pages/DynamicPages/Index.tsx @@ -10,11 +10,10 @@ import { StickyNoteIcon, TriangleAlertIcon, } from "lucide-react"; -import { usePage, Link } from "@inertiajs/react"; +import { usePage } from "@inertiajs/react"; import { Row } from "@tanstack/react-table"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; import { Tooltip, TooltipContent, @@ -58,6 +57,7 @@ export default function Index({ appEnv: AppEnv; }; const { viewAny, viewTrash, create } = auth.policies.dynamicPages; + const { viewAny: viewAnyPageConfigs } = auth.policies.pageConfigs; const isArchiveRoute = route().current(`back.${modelName}.trash`); const actionModels = isArchiveRoute ? [ Views.RESTORATION, @@ -109,20 +109,43 @@ export default function Index({ const dynamicPageModel = row.getValue("parent_page") as DynamicPageModel; const cellValue = dynamicPageModel.title[appEnv.locale]; let value = {cellValue}; - if (auth.policies.dynamicPages.viewAny) { + if (viewAny) { value = ( - + + + {value} + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.dynamic-page", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> ); } if (dynamicPageModel.deleted_at !== null) { value = (
    - {cellValue} + + {value} + {cellValue}; - if (auth.policies.pageConfigs.viewAny) { + if (viewAnyPageConfigs) { value = ( - + + + {value} + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.page-config", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> ); } if (pageConfigModel.deleted_at !== null) { value = (
    - {cellValue} + + {value} + ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("title") - ) + return renderTranslationCell(row.getValue("title")); + }, + }, + { + accessorKey: "categories", + header: () => ( +

    + {str( + useTrans("models.classes.news-category", { + choice: 2, + }), + ) + .ucFirst() + .value()} +

    + ), + cell: ({ row }: { row: Row }) => { + const categories = row.getValue( + "categories", + ) as NewsCategoryModel[]; + return categories && categories.length > 0 ? ( +
    + {categories.map((item) => + viewAnyNewsCategories ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.news-category", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )} +
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    + ); }, }, { accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { return ( - - ) + + ); }, }, { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -97,53 +173,100 @@ export default function Index({ ]; const transModel = useTrans(`models.classes.${modelName}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
    - } - tooltipContent={

    {useTrans("back.crud_back_to_list")}

    } - /> -
    + return ( + isArchiveRoute && + viewAny && ( +
    + } + tooltipContent={ +

    {useTrans("back.crud_back_to_list")}

    + } + /> +
    + ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
    - {viewAnyNewsCategories && } - tooltipContent={

    {useTrans("back.crud_access_to", { - params: { target: useTrans('models.classes.news-category', { choice: 2 })} - })}

    } - variant="outline" - />} - {viewAnyNewsTags && } - tooltipContent={

    {useTrans("back.crud_access_to", { - params: { target: useTrans('models.classes.news-tag', { choice: 2 })} - })}

    } - variant="outline" - />} - {viewTrash && } - tooltipContent={

    {useTrans("back.crud_access_to", { - params: { target: useTrans('back.archived_entries')} - })}

    } - variant="outline" - />} - {create && } - tooltipContent={

    {useTrans("back.crud_add_entry")}

    } - />} -
    + return ( + !isArchiveRoute && ( +
    + {viewAnyNewsCategories && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.news-category", + { choice: 2 }, + ), + }, + })} +

    + } + variant="outline" + /> + )} + {viewAnyNewsTags && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.news-tag", + { choice: 2 }, + ), + }, + })} +

    + } + variant="outline" + /> + )} + {viewTrash && ( + } + tooltipContent={ +

    + {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "back.archived_entries", + ), + }, + })} +

    + } + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

    {useTrans("back.crud_add_entry")}

    + } + /> + )} +
    + ) ); }; diff --git a/resources/ts/back/Pages/News/Show.tsx b/resources/ts/back/Pages/News/Show.tsx index c00640b9..94cccd96 100644 --- a/resources/ts/back/Pages/News/Show.tsx +++ b/resources/ts/back/Pages/News/Show.tsx @@ -1,6 +1,7 @@ // * Packages import { usePage } from "@inertiajs/react"; import { route } from "ziggy-js"; +import { ArrowLeft, FolderIcon, TagIcon } from "lucide-react"; // * Components shadcn import { Badge } from "@/components/ui/badge"; // * Other @@ -14,15 +15,14 @@ import { AuthProp, NewsCategoryModel, NewsModel, + NewsTagModel, SingleResource, TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; -import { ArrowLeft } from "lucide-react"; import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; -import NewsCategoriesBadge from "@/back/Components/News/NewsCategoriesBadge"; import useLocale from "@/store/use-locale-store"; import { renderTranslationCell } from "@/lib/translationCellFallback"; @@ -38,6 +38,8 @@ export default function Show({ appEnv: AppEnv; }; const { viewAny } = auth.policies.news; + const { viewAny: viewAnyNewsCategories } = auth.policies.newsCategories; + const { viewAny: viewAnyNewsTags } = auth.policies.newsTags; const newsModel = data.data as NewsModel; const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION]; const transTitle = useTrans("crud.helpers.visualization_model", { @@ -122,13 +124,50 @@ export default function Show({ .ucFirst() .value(), cell: ({ value }: { value?: NewsCategoryModel[] }) => { - if (!value || value.length === 0) return null; - return ( -
    - {value.map((item, i) => ( - - ))} + return value !== undefined && value.length > 0 ? ( +
    + {value.map((item) => + viewAnyNewsCategories ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.news-category", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    ); }, }, @@ -137,14 +176,51 @@ export default function Show({ header: str(useTrans("models.classes.news-tag", { choice: 2 })) .ucFirst() .value(), - cell: ({ value }: { value?: NewsCategoryModel[] }) => { - if (!value || value.length === 0) return null; - return ( -
    - {value.map((item, i) => ( - - ))} + cell: ({ value }: { value?: NewsTagModel[] }) => { + return value !== undefined && value.length > 0 ? ( +
    + {value.map((item) => + viewAnyNewsTags ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

    + {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.news-category", + { choice: 1 }, + ), + }, + })} +

    + } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
    + ) : ( +

    + {useTrans("back.table_not_known")} +

    ); }, }, diff --git a/resources/ts/back/Pages/PageConfigs/Index.tsx b/resources/ts/back/Pages/PageConfigs/Index.tsx index 5669f67c..a224191a 100644 --- a/resources/ts/back/Pages/PageConfigs/Index.tsx +++ b/resources/ts/back/Pages/PageConfigs/Index.tsx @@ -76,7 +76,7 @@ export default function Index({ ), cell: ({ row }: { row: Row }) => ( row.getValue("view") - ? row.getValue("view") + ? {row.getValue("view")} : (

    {useTrans('back.table_not_known')}

    ) ), }, diff --git a/resources/ts/back/Pages/PageConfigs/Show.tsx b/resources/ts/back/Pages/PageConfigs/Show.tsx index 26d6b282..70045a5c 100644 --- a/resources/ts/back/Pages/PageConfigs/Show.tsx +++ b/resources/ts/back/Pages/PageConfigs/Show.tsx @@ -53,6 +53,7 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN { accessorKey: "view", header: str(useTrans("validation.custom.view")).ucFirst().value(), + cell: ({ value }: { value: string|null }) => {value} }, { accessorKey: "config", diff --git a/resources/ts/back/Pages/Users/Index.tsx b/resources/ts/back/Pages/Users/Index.tsx index a3e20c7d..fb504764 100644 --- a/resources/ts/back/Pages/Users/Index.tsx +++ b/resources/ts/back/Pages/Users/Index.tsx @@ -96,7 +96,7 @@ export default function Index({ /> ), cell: ({ row }: { row: Row }) => ( -

    + {str( String( Object.values(enumUserRole).find( @@ -104,7 +104,7 @@ export default function Index({ )?.label, ), ).ucFirst().value()} -

    + ), }, { diff --git a/resources/ts/back/Pages/Users/Show.tsx b/resources/ts/back/Pages/Users/Show.tsx index bc4ccf65..964a4150 100644 --- a/resources/ts/back/Pages/Users/Show.tsx +++ b/resources/ts/back/Pages/Users/Show.tsx @@ -58,11 +58,11 @@ export default function Show({ data }: { data: SingleResource }) { accessorKey: "role", header: str(useTrans(`validation.attributes.role`)).ucFirst().value(), cell: ({ value }: { value: number }) => ( -

    + {str(String(Object.values(enumUserRole).find( (role) => role.value === value, )?.label)).ucFirst().value()} -

    + ), }, { From b0f3d9dba159b7ad32e734fdf69b6b2e1c589826 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Thu, 22 Jan 2026 12:40:55 +0100 Subject: [PATCH 15/19] fix: :card_file_box: update type for translatable columns in database --- ...1_alter_translatable_columns_in_tables.php | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php diff --git a/database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php b/database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php new file mode 100644 index 00000000..0a0d748d --- /dev/null +++ b/database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php @@ -0,0 +1,90 @@ +dropUnique(['name']); + }); + Schema::table('company_activities', function (Blueprint $table) { + $table->text('name')->comment('Name of the company activity.')->change(); + }); + + Schema::table('company_sectors', function (Blueprint $table) { + $table->dropUnique(['name']); + }); + Schema::table('company_sectors', function (Blueprint $table) { + $table->text('name')->comment('Name of the company sector.')->change(); + }); + + Schema::table('dynamic_pages', function (Blueprint $table) { + $table->dropUnique(['slug']); + }); + Schema::table('dynamic_pages', function (Blueprint $table) { + $table->text('title')->comment('Title of the dynamic page.')->change(); + $table->text('slug')->comment('Slug of the dynamic page.')->change(); + }); + + Schema::table('news_categories', function (Blueprint $table) { + $table->text('name')->comment('Name of the news category.')->change(); + $table->text('slug')->comment('Slug of the news category.')->change(); + }); + + Schema::table('news_tags', function (Blueprint $table) { + $table->text('name')->comment('Name of the news tag.')->change(); + $table->text('slug')->comment('Slug of the news tag.')->change(); + }); + + Schema::table('page_configs', function (Blueprint $table) { + $table->dropUnique(['label']); + }); + Schema::table('page_configs', function (Blueprint $table) { + $table->text('label')->comment('Label of the configuration.')->change(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::table('company_activities', function (Blueprint $table) { + $table->string('name')->unique()->comment('Name of the company activity.')->change(); + }); + + Schema::table('company_sectors', function (Blueprint $table) { + $table->string('name')->unique()->comment('Name of the company sector.')->change(); + }); + + Schema::table('dynamic_pages', function (Blueprint $table) { + $table->string('title')->comment('Title of the dynamic page.')->change(); + $table->string('slug')->unique()->comment('Slug of the dynamic page.')->change(); + }); + + Schema::table('news_categories', function (Blueprint $table) { + $table->string('name')->comment('Name of the news category.')->change(); + $table->string('slug')->comment('Slug of the news category.')->change(); + }); + + Schema::table('news_tags', function (Blueprint $table) { + $table->string('name')->comment('Name of the news tag.')->change(); + $table->string('slug')->comment('Slug of the news tag.')->change(); + }); + + Schema::table('page_configs', function (Blueprint $table) { + $table->string('label')->unique()->comment('Label of the configuration.')->change(); + }); + } +}; From 26619fe486b71943abf6e73d8a77a6481c0fb303 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Thu, 22 Jan 2026 15:30:47 +0100 Subject: [PATCH 16/19] fix: :card_file_box: update/clean existing seeders --- app/Models/Document.php | 68 ++--- database/factories/CompanyActivityFactory.php | 29 ++ database/factories/CompanyFactory.php | 5 +- database/factories/CompanySectorFactory.php | 28 ++ .../factories/DocumentCategoryFactory.php | 7 +- database/factories/DocumentFactory.php | 43 +-- database/factories/DocumentTagFactory.php | 18 +- database/factories/DynamicPageFactory.php | 3 + database/factories/NewsCategoryFactory.php | 10 +- database/factories/NewsTagFactory.php | 10 +- database/factories/PageConfigFactory.php | 5 +- database/seeders/CompanyActivitySeeder.php | 19 ++ database/seeders/CompanySectorSeeder.php | 19 ++ database/seeders/CustomSeeder.php | 282 ++++++++++++++++++ database/seeders/DatabaseSeeder.php | 6 + database/seeders/DocumentCategorySeeder.php | 38 +-- database/seeders/DocumentSeeder.php | 25 +- database/seeders/DocumentTagSeeder.php | 93 +----- database/seeders/NewsTagSeeder.php | 2 + 19 files changed, 504 insertions(+), 206 deletions(-) create mode 100644 database/factories/CompanyActivityFactory.php create mode 100644 database/factories/CompanySectorFactory.php create mode 100644 database/seeders/CompanyActivitySeeder.php create mode 100644 database/seeders/CompanySectorSeeder.php create mode 100644 database/seeders/CustomSeeder.php diff --git a/app/Models/Document.php b/app/Models/Document.php index 352b605a..5714cd4d 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -298,40 +298,6 @@ class Document extends Model implements TranslatableModel return $data; } - // * RELATIONSHIPS - - /** - * Relation to Tag - * - * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany - */ - public function tags(): \Illuminate\Database\Eloquent\Relations\BelongsToMany - { - return $this->morphedByMany( - DocumentTag::class, - 'documentable', - 'documentables', - 'document_id', - 'documentable_id' - )->withTimestamps(); - } - - /** - * Relation to Category - * - * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany - */ - public function categories(): \Illuminate\Database\Eloquent\Relations\BelongsToMany - { - return $this->morphedByMany( - DocumentCategory::class, - 'documentable', - 'documentables', - 'document_id', - 'documentable_id' - )->withTimestamps(); - } - public function inertiaFill(array $attributes) { // j'extrait issuPath et j'applique un traitement ensuite. @@ -370,4 +336,38 @@ class Document extends Model implements TranslatableModel ); }); } + + // * RELATIONSHIPS + + /** + * Relation to Tag + * + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + */ + public function tags(): \Illuminate\Database\Eloquent\Relations\BelongsToMany + { + return $this->morphedByMany( + DocumentTag::class, + 'documentable', + 'documentables', + 'document_id', + 'documentable_id' + )->withTimestamps(); + } + + /** + * Relation to Category + * + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + */ + public function categories(): \Illuminate\Database\Eloquent\Relations\BelongsToMany + { + return $this->morphedByMany( + DocumentCategory::class, + 'documentable', + 'documentables', + 'document_id', + 'documentable_id' + )->withTimestamps(); + } } diff --git a/database/factories/CompanyActivityFactory.php b/database/factories/CompanyActivityFactory.php new file mode 100644 index 00000000..ad54f07a --- /dev/null +++ b/database/factories/CompanyActivityFactory.php @@ -0,0 +1,29 @@ + + */ +class CompanyActivityFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + "name" => $this->faker->unique()->words( + $this->faker->numberBetween(3, 4), + true + ), + "color" => $this->faker->hexColor(), + "published" => $this->faker->boolean(50), + ]; + } +} diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php index 5fda6d51..a4974a8a 100644 --- a/database/factories/CompanyFactory.php +++ b/database/factories/CompanyFactory.php @@ -8,6 +8,9 @@ use App\Models\CompanySector; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; +/** + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Company> + */ class CompanyFactory extends Factory { /** @@ -21,7 +24,7 @@ class CompanyFactory extends Factory $companySectorModel = fake()->randomElement(CompanySector::all()); return [ - 'name' => fake()->company(), + 'name' => fake()->unique()->company(), 'responsable' => fake()->name(), 'informations' => fake()->text(200), 'latitude' => fake()->latitude(), diff --git a/database/factories/CompanySectorFactory.php b/database/factories/CompanySectorFactory.php new file mode 100644 index 00000000..9c8afb13 --- /dev/null +++ b/database/factories/CompanySectorFactory.php @@ -0,0 +1,28 @@ + + */ +class CompanySectorFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + "name" => $this->faker->unique()->words( + $this->faker->numberBetween(3, 4), + true + ), + "published" => $this->faker->boolean(50), + ]; + } +} diff --git a/database/factories/DocumentCategoryFactory.php b/database/factories/DocumentCategoryFactory.php index 47a78009..e63813c0 100644 --- a/database/factories/DocumentCategoryFactory.php +++ b/database/factories/DocumentCategoryFactory.php @@ -3,6 +3,7 @@ namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\DocumentCategory> @@ -16,8 +17,12 @@ class DocumentCategoryFactory extends Factory */ public function definition(): array { + $name = $this->faker->unique()->word(); + $slug = Str::slug($name); + return [ - 'name' => $this->faker->unique()->word(), + 'name' => $name, + 'slug' => $slug, ]; } } diff --git a/database/factories/DocumentFactory.php b/database/factories/DocumentFactory.php index e8ed9471..f8938b51 100644 --- a/database/factories/DocumentFactory.php +++ b/database/factories/DocumentFactory.php @@ -10,42 +10,23 @@ use App\Models\DocumentTag; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; +/** + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Document> + */ class DocumentFactory extends Factory { - protected $model = Document::class; - + /** + * Define the model's default state. + * + * @return array + */ public function definition(): array { - $title = $this->faker->sentence(3); return [ - 'name' => $title, - 'path' => 'documents/' . Str::slug($title) . '.pdf', - 'exercice' => $this->faker->randomElement(YearsEnum::cases()), - 'status' => $this->faker->randomElement(DocumentStatusEnum::cases()), - 'published_at' => $this->faker->dateTimeBetween('-1 month', 'now'), - 'unpublished_at' => null, + 'name' => $this->faker->sentence(3), + 'exercice' => $this->faker->randomElement(YearsEnum::cases()), + 'status' => $this->faker->randomElement(DocumentStatusEnum::cases()), + 'published_at' => $this->faker->dateTimeBetween('-1 month', 'now'), ]; } - - /** - * Ajoute automatiquement des tags à un document créé. - */ - public function withTags(int $count = 3): static - { - return $this->afterCreating(function (Document $document) use ($count) { - $tags = DocumentTag::factory()->count($count)->create(); - $document->tags()->sync($tags->pluck('id')); - }); - } - - /** - * Ajoute automatiquement des tags à un document créé. - */ - public function withCategories(int $count = 3): static - { - return $this->afterCreating(function (Document $document) use ($count) { - $cats = DocumentCategory::factory()->count($count)->create(); - $document->categories()->sync($cats->pluck('id')); - }); - } } diff --git a/database/factories/DocumentTagFactory.php b/database/factories/DocumentTagFactory.php index 43c14a0b..48d82590 100644 --- a/database/factories/DocumentTagFactory.php +++ b/database/factories/DocumentTagFactory.php @@ -2,17 +2,27 @@ namespace Database\Factories; -use App\Models\DocumentTag; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Str; +/** + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\DocumentTag> + */ class DocumentTagFactory extends Factory { - protected $model = DocumentTag::class; - + /** + * Define the model's default state. + * + * @return array + */ public function definition(): array { + $name = $this->faker->unique()->word(); + $slug = Str::slug($name); + return [ - 'name' => $this->faker->unique()->word(), + 'name' => $name, + 'slug' => $slug, ]; } } diff --git a/database/factories/DynamicPageFactory.php b/database/factories/DynamicPageFactory.php index 8d63ca21..37a427b3 100644 --- a/database/factories/DynamicPageFactory.php +++ b/database/factories/DynamicPageFactory.php @@ -10,6 +10,9 @@ use App\Models\PageConfig; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; +/** + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\DynamicPage> + */ class DynamicPageFactory extends Factory { /** diff --git a/database/factories/NewsCategoryFactory.php b/database/factories/NewsCategoryFactory.php index 32d9dfb2..36e878a0 100644 --- a/database/factories/NewsCategoryFactory.php +++ b/database/factories/NewsCategoryFactory.php @@ -3,9 +3,10 @@ namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Str; /** - * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\News> + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\NewsCategory> */ class NewsCategoryFactory extends Factory { @@ -16,9 +17,12 @@ class NewsCategoryFactory extends Factory */ public function definition(): array { + $name = $this->faker->unique()->word(); + $slug = Str::slug($name); + return [ - "name" => $this->faker->unique()->word(), - "slug" => $this->faker->unique()->word(), + "name" => $name, + "slug" => $slug, ]; } } diff --git a/database/factories/NewsTagFactory.php b/database/factories/NewsTagFactory.php index 02fb2cfa..413f8b1c 100644 --- a/database/factories/NewsTagFactory.php +++ b/database/factories/NewsTagFactory.php @@ -3,6 +3,7 @@ namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\NewsTag> @@ -16,10 +17,13 @@ class NewsTagFactory extends Factory */ public function definition(): array { + $name = $this->faker->unique()->word(); + $slug = Str::slug($name); + return [ - "name" => $this->faker->unique()->word(), - "slug" => $this->faker->unique()->word(), - "color" => "#fff" + "name" => $name, + "slug" => $slug, + "color" => $this->faker->hexColor(), ]; } } diff --git a/database/factories/PageConfigFactory.php b/database/factories/PageConfigFactory.php index 92e2fc91..558b4eb6 100644 --- a/database/factories/PageConfigFactory.php +++ b/database/factories/PageConfigFactory.php @@ -7,12 +7,15 @@ use App\Models\PageConfig; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; +/** + * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\PageConfig> + */ class PageConfigFactory extends Factory { /** * Define the model's default state. * - * @return array + * @return array */ public function definition(): array { diff --git a/database/seeders/CompanyActivitySeeder.php b/database/seeders/CompanyActivitySeeder.php new file mode 100644 index 00000000..33e1dfc7 --- /dev/null +++ b/database/seeders/CompanyActivitySeeder.php @@ -0,0 +1,19 @@ +create(); + } +} diff --git a/database/seeders/CompanySectorSeeder.php b/database/seeders/CompanySectorSeeder.php new file mode 100644 index 00000000..5949f191 --- /dev/null +++ b/database/seeders/CompanySectorSeeder.php @@ -0,0 +1,19 @@ +create(); + } +} diff --git a/database/seeders/CustomSeeder.php b/database/seeders/CustomSeeder.php new file mode 100644 index 00000000..5f09bf62 --- /dev/null +++ b/database/seeders/CustomSeeder.php @@ -0,0 +1,282 @@ +companyActivitySeeder(); + $this->companySectorSeeder(); + $this->documentCategorySeeder(); + $this->documentTagSeeder(); + } + + /** + * Set custom company activity seeder. + * + * @return void + */ + private function companyActivitySeeder(): void + { + // Set FR values. + app()->setLocale("fr"); + $firstActivity = CompanyActivity::create([ + "name" => "Amont", + "color" => "#6fbc45", + "published" => 1, + ]); + $secondActivity = CompanyActivity::create([ + "name" => "International", + "color" => "#b24881", + "published" => 1, + ]); + $thirdActivity = CompanyActivity::create([ + "name" => "Plateformes", + "color" => "#6d6d6d", + "published" => 1, + ]); + $fourthActivity = CompanyActivity::create([ + "name" => "Traiteur", + "color" => "#f29100", + "published" => 1, + ]); + $fifthActivity = CompanyActivity::create([ + "name" => "Volaille", + "color" => "#DC2034", + "published" => 1, + ]); + + // Set EN values. + app()->setLocale("en"); + $firstActivity->update([ + "name" => "Upstream", + ]); + $secondActivity->update([ + "name" => "International", + ]); + $thirdActivity->update([ + "name" => "Platforms", + ]); + $fourthActivity->update([ + "name" => "Catering", + ]); + $fifthActivity->update([ + "name" => "Poultry", + ]); + + // Set locale to the fallback. + app()->setLocale(config('app.fallback_locale')); + } + + /** + * Set custom company sector seeder. + * + * @return void + */ + private function companySectorSeeder(): void + { + collect([ + "Allemagne - ECF - Clements BETTERMANN", + "Angleterre - Capestone - Rob Cumine", + "Belgique - Kiplama - Toon KWEENS", + "Hongrie et Roumanie - Ákos Szabó", + "Pologne - Adam Sojka", + "Pôle Amont - Filière Céréales - Gaël Le Conte", + "Pôle Amont - Filière Oeufs - Christophe Bériard", + "Pôle Amont - Filière Spécialités - Didier Richard", + "Pôle Amont - Filière Vif - Stéphane Landreau", + "Pôle Amont - Filière accouvage - Olivier Sionneau", + "Pôle Traiteur - Crêpes et galettes - Christèle Lucas", + "Pôle Traiteur - La Toque Angevine - Pierre Lonjon", + "Pôle Traiteur - Pizzas, tartes, sandwiches et quiches - Yann Gomez", + "Pôle Traiteur - Plats cuisinés : Marie, Traditions d’Asie, Weight Watchers - Guillaume LETENNEUR", + "Pôle Traiteur - Plats cuisinés et produits exotiques - Benjamin Montlahuc", + "Pôle Traiteur - Restauration Hors Domicile - Ludovic Courtier", + "Pôle Traiteur - Surgelés - Didier Gand", + "Pôle Volaille - Cailles Robin - Guy Prod’homme", + "Pôle Volaille - GPA Distribution Paris - Thierry Lambert", + "Pôle Volaille - Hauts de France", + "Pôle Volaille - LDC Aquitaine - Denis Bordes", + "Pôle Volaille - LDC Foods - Mickaël Rio", + "Pôle Volaille - LDC TERRAVENIR - Christophe Pajot", + "Pôle Volaille - PFC - Dominique Théreau", + "Pôle Volaille - Société Arrivé - Roland Tonarelli", + "Pôle Volaille - Société Bretonne de Volaille - Laurent Girard", + "Pôle Volaille - Société Favreau Couthouis - Roland Tonarelli", + "Pôle Volaille - VOLENA - Arnaud Boinard", + "Pôle volaille - Pôle VDR - Philippe Aubert", + ])->map(function (string $sector) { + CompanySector::create([ + "name" => $sector, + "published" => 1, + ]); + }); + } + + /** + * Set custom document category seeder. + * + * @return void + */ + private function documentCategorySeeder(): void + { + // Set FR values. + app()->setLocale("fr"); + $docs = DocumentCategory::create([ + "name" => "Documents", + "slug" => "documents" + ]); + $meetings = DocumentCategory::create([ + "name" => "Assemblées générales", + "slug" => "assemblees-generales" + ]); + $investors = DocumentCategory::create([ + "name" => "Présentation investisseurs", + "slug" => "presentation-investisseurs" + ]); + $press = DocumentCategory::create([ + "name" => "Espace presse", + "slug" => "espace-presse" + ]); + + // Set EN values. + app()->setLocale("en"); + $docs->update([ + "name" => "Documents", + "slug" => "documents" + ]); + $meetings->update([ + "name" => "General meetings", + "slug" => "general-meetings" + ]); + $investors->update([ + "name" => "Investor presentation", + "slug" => "investor-presentation" + ]); + $press->update([ + "name" => "Meetings Press area", + "slug" => "meeting-press-area" + ]); + + // Set locale to the fallback. + app()->setLocale(config('app.fallback_locale')); + } + + /** + * Set custom document tag seeder. + * + * @return void + */ + private function documentTagSeeder(): void + { + // Set FR values. + app()->setLocale("fr"); + $communique = DocumentTag::create([ + "name" => "Communiqués et Avis financiers", + "slug" => "communiques-et-avis-financiers" + ]); + $semestriel = DocumentTag::create([ + "name" => "Rapports financiers annuels et semestriels", + "slug" => "rapports-financiers-annuels-et-semestriels" + ]); + $droitdevote = DocumentTag::create([ + "name" => "Déclaration mensuelles du nombre d’actions et de droits de vote", + "slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote" + ]); + $rachat = DocumentTag::create([ + "name" => "Descriptif de programme de rachats d’actions", + "slug" => "descriptif-de-programme-de-rachats-dactions" + ]); + $liquidite = DocumentTag::create([ + "name" => "Opérations sur contrat de liquidité", + "slug" => "operations-sur-contrat-de-liquidite" + ]); + $trimestriel = DocumentTag::create([ + "name" => "Information Trimestrielle", + "slug" => "information-trimestrielle" + ]); + $publication = DocumentTag::create([ + "name" => "Publication", + "slug" => "publication" + ]); + $finance = DocumentTag::create([ + "name" => "Finance", + "slug" => "finance" + ]); + $general = DocumentTag::create([ + "name" => "Assemblée générale des actionnaires", + "slug" => "assemblee-generale-des-actionnaires" + ]); + $declaration = DocumentTag::create([ + "name" => "Déclaration des rachats d’actions", + "slug" => "declaration-des-rachats-dactions" + ]); + $statuts = DocumentTag::create([ + "name" => "Statuts de la SA LDC", + "slug" => "statuts-de-la-sa-ldc" + ]); + + // Set EN values. + app()->setLocale("en"); + $communique->update([ + "name" => "Press releases and financial notices", + "slug" => "communiques-et-avis-financiers-en" + ]); + $semestriel->update([ + "name" => "Annual and half-yearly financial reports", + "slug" => "rapports-financiers-annuels-et-semestriels-en" + ]); + $droitdevote->update([ + "name" => "Monthly declaration of the number of shares and voting rights", + "slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote-en" + ]); + $rachat->update([ + "name" => "Description of share buyback program", + "slug" => "descriptif-de-programme-de-rachats-dactions-en" + ]); + $liquidite->update([ + "name" => "Liquidity contract transactions", + "slug" => "operations-sur-contrat-de-liquidite-en" + ]); + $trimestriel->update([ + "name" => "Quarterly Information", + "slug" => "information-trimestrielle-en" + ]); + $publication->update([ + "name" => "Publication", + "slug" => "publication-en" + ]); + $finance->update([ + "name" => "Finance", + "slug" => "finance-en" + ]); + $general->update([ + "name" => "General Meeting of Shareholders", + "slug" => "assemblee-generale-des-actionnaires-en" + ]); + $declaration->update([ + "name" => "Declaration of share buybacks", + "slug" => "declaration-des-rachats-dactions-en" + ]); + $statuts->update([ + "name" => "Statutes of SA LDC", + "slug" => "statuts-de-la-sa-ldc-en" + ]); + + // Set locale to the fallback. + app()->setLocale(config('app.fallback_locale')); + } +} diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 49a4ba61..12807789 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -21,8 +21,14 @@ class DatabaseSeeder extends Seeder PageConfigSeeder::class, DynamicPageSeeder::class, NewsCategorySeeder::class, + NewsTagSeeder::class, NewsSeeder::class, + CompanyActivitySeeder::class, + CompanySectorSeeder::class, CompanySeeder::class, + DocumentCategorySeeder::class, + DocumentTagSeeder::class, + DocumentSeeder::class, ]); } } diff --git a/database/seeders/DocumentCategorySeeder.php b/database/seeders/DocumentCategorySeeder.php index 9c314502..be67b5db 100644 --- a/database/seeders/DocumentCategorySeeder.php +++ b/database/seeders/DocumentCategorySeeder.php @@ -9,43 +9,11 @@ class DocumentCategorySeeder extends Seeder { /** * Run the database seeds. + * + * @return void */ public function run(): void { - app()->setLocale("fr"); - $docs = DocumentCategory::create([ - "name" => "Documents", // pour finance - "slug" => "documents" - ]); - $meetings = DocumentCategory::create([ - "name" => "Assemblées générales", // pour finance - "slug" => "assemblees-generales" - ]); - $investors = DocumentCategory::create([ - "name" => "Présentation investisseurs", // pour finance - "slug" => "presentation-investisseurs" - ]); - $press = DocumentCategory::create([ - "name" => "Espace presse", - "slug" => "espace-presse" - ]); - - app()->setLocale("en"); - $docs->update([ - "name" => "Documents", - "slug" => "documents" - ]); - $meetings->update([ - "name" => "General meetings", - "slug" => "general-meetings" - ]); - $investors->update([ - "name" => "Investor presentation", - "slug" => "investor-presentation" - ]); - $press->update([ - "name" => "Meetings Press area", - "slug" => "meeting-press-area" - ]); + DocumentCategory::factory(10)->create(); } } diff --git a/database/seeders/DocumentSeeder.php b/database/seeders/DocumentSeeder.php index e6746d4a..5ba8691c 100644 --- a/database/seeders/DocumentSeeder.php +++ b/database/seeders/DocumentSeeder.php @@ -3,6 +3,8 @@ namespace Database\Seeders; use App\Models\Document; +use App\Models\DocumentCategory; +use App\Models\DocumentTag; use Illuminate\Database\Seeder; use Uwil\LaravelCommon\Helpers\FileHelper; @@ -10,11 +12,12 @@ class DocumentSeeder extends Seeder { /** * Run the database seeds. + * + * @return void */ public function run(): void { - Document::factory(3)->withTags(3)->withCategories(2)->make() - ->each(function ($model) { + Document::factory(3)->make()->each(function (Document $model) { $model->path = FileHelper::storeFile( $model, new \SplFileInfo(\resource_path( @@ -22,6 +25,22 @@ class DocumentSeeder extends Seeder )) ); $model->saveOrFail(); - });; + }); + + // Document categories relation. + $categoriesIds = DocumentCategory::pluck('id'); + Document::query()->get()->map(function (Document $document) use ($categoriesIds) { + $document->categories()->attach( + $categoriesIds->random(rand(1, 3))->all() + ); + }); + + // Document tags relation. + $tagsIds = DocumentTag::pluck('id'); + Document::query()->get()->map(function (Document $document) use ($tagsIds) { + $document->tags()->attach( + $tagsIds->random(rand(1, 3))->all() + ); + }); } } diff --git a/database/seeders/DocumentTagSeeder.php b/database/seeders/DocumentTagSeeder.php index 21354266..25b74f5f 100644 --- a/database/seeders/DocumentTagSeeder.php +++ b/database/seeders/DocumentTagSeeder.php @@ -9,98 +9,11 @@ class DocumentTagSeeder extends Seeder { /** * Run the database seeds. + * + * @return void */ public function run(): void { - app()->setLocale("fr"); - $communique = DocumentTag::create([ - "name" => "Communiqués et Avis financiers", - "slug" => "communiques-et-avis-financiers" - ]); - $semestriel = DocumentTag::create([ - "name" => "Rapports financiers annuels et semestriels", - "slug" => "rapports-financiers-annuels-et-semestriels" - ]); - $droitdevote = DocumentTag::create([ - "name" => "Déclaration mensuelles du nombre d’actions et de droits de vote", - "slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote" - ]); - $rachat = DocumentTag::create([ - "name" => "Descriptif de programme de rachats d’actions", - "slug" => "descriptif-de-programme-de-rachats-dactions" - ]); - $liquidite = DocumentTag::create([ - "name" => "Opérations sur contrat de liquidité", - "slug" => "operations-sur-contrat-de-liquidite" - ]); - $trimestriel = DocumentTag::create([ - "name" => "Information Trimestrielle", - "slug" => "information-trimestrielle" - ]); - $publication = DocumentTag::create([ - "name" => "Publication", - "slug" => "publication" - ]); - $finance = DocumentTag::create([ - "name" => "Finance", - "slug" => "finance" - ]); - $general = DocumentTag::create([ - "name" => "Assemblée générale des actionnaires", - "slug" => "assemblee-generale-des-actionnaires" - ]); - $declaration = DocumentTag::create([ - "name" => "Déclaration des rachats d’actions", - "slug" => "declaration-des-rachats-dactions" - ]); - $statuts = DocumentTag::create([ - "name" => "Statuts de la SA LDC", - "slug" => "statuts-de-la-sa-ldc" - ]); - app()->setLocale("en"); - $communique->update([ - "name" => "Press releases and financial notices", - "slug" => "communiques-et-avis-financiers-en" - ]); - $semestriel->update([ - "name" => "Annual and half-yearly financial reports", - "slug" => "rapports-financiers-annuels-et-semestriels-en" - ]); - $droitdevote->update([ - "name" => "Monthly declaration of the number of shares and voting rights", - "slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote-en" - ]); - $rachat->update([ - "name" => "Description of share buyback program", - "slug" => "descriptif-de-programme-de-rachats-dactions-en" - ]); - $liquidite->update([ - "name" => "Liquidity contract transactions", - "slug" => "operations-sur-contrat-de-liquidite-en" - ]); - $trimestriel->update([ - "name" => "Quarterly Information", - "slug" => "information-trimestrielle-en" - ]); - $publication->update([ - "name" => "Publication", - "slug" => "publication-en" - ]); - $finance->update([ - "name" => "Finance", - "slug" => "finance-en" - ]); - $general->update([ - "name" => "General Meeting of Shareholders", - "slug" => "assemblee-generale-des-actionnaires-en" - ]); - $declaration->update([ - "name" => "Declaration of share buybacks", - "slug" => "declaration-des-rachats-dactions-en" - ]); - $statuts->update([ - "name" => "Statutes of SA LDC", - "slug" => "statuts-de-la-sa-ldc-en" - ]); + DocumentTag::factory(10)->create(); } } diff --git a/database/seeders/NewsTagSeeder.php b/database/seeders/NewsTagSeeder.php index 3e979239..1350443f 100644 --- a/database/seeders/NewsTagSeeder.php +++ b/database/seeders/NewsTagSeeder.php @@ -9,6 +9,8 @@ class NewsTagSeeder extends Seeder { /** * Run the database seeds. + * + * @return void */ public function run(): void { From dad7a60ba0cec0ae4c39f9c4350761e986935353 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Thu, 22 Jan 2026 16:33:03 +0100 Subject: [PATCH 17/19] fix: :lipstick: active links in back navigation on side actions --- .../ts/back/Components/Layout/AppSidebar.tsx | 79 +++++++++---------- 1 file changed, 37 insertions(+), 42 deletions(-) diff --git a/resources/ts/back/Components/Layout/AppSidebar.tsx b/resources/ts/back/Components/Layout/AppSidebar.tsx index 80196a28..bfd1bac0 100644 --- a/resources/ts/back/Components/Layout/AppSidebar.tsx +++ b/resources/ts/back/Components/Layout/AppSidebar.tsx @@ -59,23 +59,36 @@ import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; import { AppEnv, AuthProp, LaravelEnum } from "@/back/types/global"; -type NavList = Array<{ +type NavListProps = Array<{ + /** Title of the group. */ title: string, + /** Condition to set the visibility of the group. */ show: boolean, + /** Links presents in the group. */ links: Array<{ + /** Title of the button. */ title: string, + /** Main model of the button (used for route checking). */ model?: string, + /** External link of the button (if it's a not CRUD, just a simple link). */ link?: string, + /** Define some conditions for active or not the button (in addition to the route model checking if defined). */ + activeCondition?: boolean[], + /** Condition to set the visibility of the button. */ show: boolean, + /** Lucide icon of the button. */ icon: ElementType, + /** Define some actions in side popover (like create/trash). */ actions?: (model: string) => ReactNode, }> }> -type CustomDropdownMenuItem = { +type CustomDropdownMenuItemProps = { + /** Link of the action. */ route: string; - policy?: boolean; + /** Lucide icon of the action. */ icon?: ElementType; + /** Translation of the action. */ trans?: string; }; @@ -89,7 +102,7 @@ export default function AppSidebar() { const { state } = useSidebar(); const prevStateRef = useRef(state); const isCollapsed = state === "collapsed"; - const navList: NavList = [ + const navList: NavListProps = [ { title: useTrans("back.pages"), show: true, @@ -135,10 +148,9 @@ export default function AppSidebar() { show: authPolicies.news.viewAny || auth.policies.contact_counts.viewAny, links: [ { - title: str(useTrans("models.classes.news", { choice: 2 })) - .ucFirst() - .value(), + title: str(useTrans("models.classes.news", { choice: 2 })).ucFirst().value(), model: "news", + activeCondition: [route().current("back.news-categories.*"), route().current('back.news-tags.*')], icon: NewspaperIcon, show: auth.policies.news.viewAny, actions: (model: string) => filterActions({ @@ -159,36 +171,29 @@ export default function AppSidebar() { ), authPolicies.newsTags.viewAny && ( ), ] }) }, { - title: str(useTrans("models.classes.contact-count")) - .ucFirst() - .value(), + title: str(useTrans("models.classes.contact-count")).ucFirst().value(), model: "contact-counts", icon: ContactIcon, show: auth.policies.contact_counts.viewAny, }, { - title: str(useTrans("models.classes.document", { choice: 2 })) - .ucFirst() - .value(), + title: str(useTrans("models.classes.document", { choice: 2 })).ucFirst().value(), model: "documents", + activeCondition: [route().current("back.document-categories.*"), route().current('back.document-tags.*')], icon: FileInputIcon, show: auth.policies.documents.viewAny, actions: (model: string) => filterActions({ @@ -202,29 +207,23 @@ export default function AppSidebar() { ), authPolicies.documentTags.create && ( ) ] }) }, { - title: str(useTrans("models.classes.company", { choice: 2 })) - .ucFirst() - .plural() - .value(), + title: str(useTrans("models.classes.company", { choice: 2 })).ucFirst().plural().value(), model: "companies", + activeCondition: [route().current("back.company-activities.*"), route().current('back.company-sectors.*')], icon: Building2Icon, show: auth.policies.companies.viewAny, actions: (model: string) => filterActions({ @@ -322,7 +321,7 @@ export default function AppSidebar() { route, icon: Icon = Views.CREATION.icon, trans = str(useTrans(`crud.actions.${Views.CREATION.label}`)).ucFirst().value(), - }: CustomDropdownMenuItem) => { + }: CustomDropdownMenuItemProps) => { return (
    - +
    ); } diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts new file mode 100644 index 00000000..5b83fa77 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts @@ -0,0 +1,23 @@ +// * Packages +import type { ImageOptions as TiptapImageOptions } from '@tiptap/extension-image'; +import { Image as TiptapImage } from 'reactjs-tiptap-editor/image'; +import { Editor } from 'reactjs-tiptap-editor'; +// * Other +import ImageButton from '@/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton'; +import useTrans from '@/hooks/use-translations'; + +export const Image = TiptapImage.extend({ + addOptions() { + return { + ...this.parent?.(), + openOnClick: false, + button: ({ editor }: { editor: Editor }) => ({ + component: ImageButton, + componentProps: { + editor, + tooltip: useTrans('back.wysiwyg_plugins.image.tooltip'), + }, + }), + }; + }, +}); \ No newline at end of file diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx new file mode 100644 index 00000000..363e7790 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx @@ -0,0 +1,318 @@ +// * Packages +import { useState } from "react"; +import axios from "axios"; +import { route } from "ziggy-js"; +import { ImageUpIcon } from "lucide-react"; +import { Editor } from "reactjs-tiptap-editor"; +import { z } from "zod"; +// * Components shadcn +import { + Dialog, + DialogDescription, + DialogContent, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +// * Other +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile"; +import SimpleString from "@/back/Components/Inputs/SimpleString"; +import useTrans from "@/hooks/use-translations"; +import str from "@/hooks/use-string"; + +type ImageProps = { + /** Wysiwyg editor instance. */ + editor: Editor; + /** Wysiwyg menu button tooltip. */ + tooltip: string; +}; + +export default function ImageButton({ editor, tooltip }: ImageProps) { + // Get all editor options define with customOptions in the parent SimpleWysiwyg. + const editorOptions = editor.options.editorProps?.attributes as { [name: string]: string }; + + // State of the plugin modal. + const [open, setOpen] = useState(false); + // Value of the input file image. + const [inputFile, setFile] = useState(null); + // Value of the input alt image. + const [inputAlt, setInputAlt] = useState(""); + + // State of the loader. + const [loading, setLoading] = useState(false); + // Value of errors. + const [errors, setErrors] = useState>({}); + + // Duration of modal closing animation. + const animationTime = 200; + + // Zod image schema. + const inputsSchema = z.object({ + inputFile: z + .instanceof(File, { + message: useTrans("validation.file", { + params: { + attribute: useTrans("validation.custom.image"), + }, + }), + }) + .refine( + (file) => + [ + "image/jpeg", + "image/jpg", + "image/png", + "image/webp", + ].includes(file.type), + { + message: useTrans("validation.regex", { + params: { + attribute: useTrans("validation.custom.image"), + }, + }), + }, + ) + .refine((file) => file.size <= 5 * 1024 * 1024, { + message: useTrans("validation.size.file", { + params: { + attribute: useTrans("validation.custom.image"), + size: "5 000", + }, + }), + }), + inputAlt: z + .string({ + message: useTrans("validation.string", { + params: { + attribute: useTrans("validation.custom.image_alt"), + }, + }), + }) + .min(3, { + message: useTrans("validation.min.string", { + params: { + attribute: useTrans("validation.custom.image_alt"), + min: "3", + }, + }), + }) + .max(255, { + message: useTrans("validation.max.string", { + params: { + attribute: useTrans("validation.custom.image_alt"), + max: "255", + }, + }), + }), + }); + + /** + * Upload image in storage. + * + * @param file + * @param alt + * @return Promise + */ + const uploadImage = async (file: File, alt: string): Promise => { + // Get the csrf token value. + const csrfToken = + document + .querySelector('meta[name="csrf-token"]') + ?.getAttribute("content") || ""; + + // Prepare the form data. + const data = new FormData(); + data.append("upload", file); + data.append("folder", editorOptions.model); + + const uploadRoute = route("back.wysiwyg.upload"); + + try { + const response = await axios.post(uploadRoute, data, { + headers: { + "Content-Type": "multipart/form-data", + Accept: "application/json", + "X-Requested-With": "XMLHttpRequest", + "X-Inertia": "false", + "X-CSRF-TOKEN": csrfToken, + }, + }); + editor.commands.setImage({ + src: response.data.url, + alt: alt, + }); + } catch (error: Error | unknown) { + throw new Error(`Erreur upload: ${(error as Error).message}`); + } + }; + + /** + * Add new image. + * + * @return void + */ + const handleAddImage = (): void => { + setLoading(true); + + try { + const parsed = inputsSchema.parse({ inputFile, inputAlt }); + uploadImage(parsed.inputFile, parsed.inputAlt); + setOpen(false); + setTimeout(() => resetComponent(), animationTime); + } catch (err) { + // Get zod error validations. + if (err instanceof z.ZodError) { + const fieldErrors: Record = {}; + const keyMap: Record = { + inputFile: "image", + inputAlt: "alt", + }; + + err.issues.forEach((e) => { + const mappedKey = keyMap[e.path[0] as string]; + if (mappedKey) fieldErrors[mappedKey] = e.message; + }); + + setErrors(fieldErrors); + } + } finally { + setLoading(false); + } + }; + + const handleSetAlt = (name: string, value: string) => { + setErrors((prev) => ({ ...prev, [name]: "" })); + setInputAlt(value); + }; + + /** + * Reset all states and values in the component. + * + * @return void + */ + const resetComponent = () => { + setFile(null); + setInputAlt(""); + setErrors({}); + setLoading(false); + }; + + /** + * Update url value from string input. + * + * @return void + */ + const handleSetImage = ( + name: string, + value: string | File | null, + ): void => { + setErrors((prev) => ({ ...prev, [name]: "" })); + setFile(value); + }; + + /** + * Close modal and reset component. + * + * @return void + */ + const handleCancelImage = (): void => { + setOpen(false); + setTimeout(() => resetComponent(), animationTime); + }; + + return ( + { + setOpen(v); + if (!v) setTimeout(() => resetComponent(), animationTime); + }} + > + {/* Button trigger in wysiwyg navigation. */} + + } + tooltipContent={tooltip} + className="cursor-grab richtext-px-2 richtext-w-[32px] richtext-h-[32px]" + type="button" + variant="ghost" + size="icon" + /> + + + + + {useTrans("back.wysiwyg_plugins.image.title")} + + + {useTrans("back.wysiwyg_plugins.image.subtitle")} + + + console.log("reset", name)} + value={null} + required={true} + maxFileSize="5120" + allowedFormats="jpg,jpeg,png,webp" + validationRules={{ + width: "1920", + height: "1080", + }} + parentErrors={errors} + /> + +
    +
    + {/* Save button. */} + + {/* Cancel button. */} + +
    +
    +
    +
    + ); +} diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts new file mode 100644 index 00000000..52d862d0 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts @@ -0,0 +1,13 @@ +import '@tiptap/core'; + +declare module '@tiptap/core' { + interface Commands { + Image: { + setImage: (attrs: { + src: string, + alt: string; + }) => ReturnType; + unsetImage: () => ReturnType; + }; + } +} diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts index 578c4c05..9b09a86b 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts @@ -30,7 +30,7 @@ export const Link = TiptapLink.extend({ setLink: attrs => ({ state, commands }) => { const { from, to } = state.selection; - // Vérifier si un lien est sélectionné + // Check if there is a selected link. let linkFound = false; state.doc.nodesBetween(from, to, node => { if (node.marks) { @@ -41,7 +41,7 @@ export const Link = TiptapLink.extend({ if (linkFound) { return commands.command(({ tr, state, dispatch }) => { - // Récupérer le mark existant + // Get the existing mark. let existingMark = null; state.doc.nodesBetween(from, to, node => { if (node.marks) { @@ -52,27 +52,27 @@ export const Link = TiptapLink.extend({ if (!existingMark) return false; - // Supprimer le texte existant + // Remove the existing text. tr.delete(from, to); - // Insérer le nouveau texte + // Insert the new text. tr.insertText(attrs.text, from); - // Ajouter le mark avec les nouveaux attrs + // Set the mark with new attributes. tr.addMark( from, from + attrs.text.length, state.schema.marks[this.name].create(attrs) ); - // Appliquer la transaction + // Apply the modification. if (dispatch) dispatch(tr); return true; }); } - // Sinon créer un nouveau lien comme avant + // Otherwise, create a new link like before. return commands.insertContent({ type: "text", text: attrs.text, @@ -82,7 +82,7 @@ export const Link = TiptapLink.extend({ unsetLink: () => ({ state, commands }: CommandProps) => { const { from, to } = state.selection; - // Vérifier qu’il y a bien un mark Link + // Check there is a link mark. let hasLink = false; state.doc.nodesBetween(from, to, node => { if (node.marks?.some(m => m.type.name === this.name)) { @@ -92,7 +92,7 @@ export const Link = TiptapLink.extend({ if (!hasLink) return false; - // Retirer le mark de la sélection + // Remove the mark from the selection. return commands.unsetMark(this.name); }, }; @@ -144,11 +144,11 @@ export const Link = TiptapLink.extend({ const link = target.closest("a"); if (!link) return false; - // Trouver la position exacte du node + // Find the exact position of the gat . const { state } = view; const $pos = state.doc.resolve(pos); - // 🔥 Étendre la sélection à l'ensemble du mark + // Extend the selection to the entire mark. const markRange = getMarkRange($pos, state.schema.marks.Link); if (markRange) { view.dispatch( @@ -158,7 +158,7 @@ export const Link = TiptapLink.extend({ ); } - // Ouvrir ta modale + // Open the modale. this.editor.emit("open-link-editor", { href: link.getAttribute("href") ?? "", blank: link.getAttribute("target") === "_blank", diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx index 38a061eb..0f6e41b3 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx @@ -10,7 +10,6 @@ import { FontSize } from "reactjs-tiptap-editor/fontsize"; import { Heading } from "reactjs-tiptap-editor/heading"; import { History } from "reactjs-tiptap-editor/history"; import { HorizontalRule } from "reactjs-tiptap-editor/horizontalrule"; -import { Image } from "reactjs-tiptap-editor/image"; import { Indent } from "reactjs-tiptap-editor/indent"; import { Italic } from "reactjs-tiptap-editor/italic"; import { OrderedList } from "reactjs-tiptap-editor/orderedlist"; @@ -19,14 +18,13 @@ import { Strike } from "reactjs-tiptap-editor/strike"; import { TextAlign } from "reactjs-tiptap-editor/textalign"; import { TextUnderline } from "reactjs-tiptap-editor/textunderline"; import { Color } from "reactjs-tiptap-editor/color"; -import axios from "axios"; import "react-image-crop/dist/ReactCrop.css"; import "reactjs-tiptap-editor/lib/style.css"; -import { route } from "ziggy-js"; // * Components shadcn import { Label } from "@/components/ui/label"; // * Other import { Link } from "@/back/Components/Inputs/Wysiwyg/Plugins/Link/Link"; +import { Image } from "@/back/Components/Inputs/Wysiwyg/Plugins/Image/Image"; import InputError from "@/back/Components/InputError"; import WordCounter from "@/back/Components/WordCounter"; import useTrans from "@/hooks/use-translations"; @@ -89,27 +87,8 @@ export default function SimpleWysiwyg({ TextAlign, Blockquote, HorizontalRule, - Image.configure({ - upload: async (file: File): Promise => { - // Prepare the form data. - const data = new FormData(); - data.append("upload", file); - data.append("folder", model); - - const uploadRoute = route("back.wysiwyg.upload"); - - try { - const response = await axios.post( - uploadRoute, - data, - { headers: { "Content-Type": "multipart/form-data" } } - ); - return response.data.url; - } catch (error: Error | unknown) { - throw new Error(`Erreur upload: ${(error as Error).message}`); - } - }, - }), + // Custom plugins. + Image, Link, ]; @@ -129,11 +108,17 @@ export default function SimpleWysiwyg({ setData(name, value); }; + // Define some custom attributes in the editor options, + // so that we can access them from plugins. const customOptions: UseEditorOptions = { editorProps: { attributes: { + // Required status. required: String(required), + // Target field name. id, + // Target model name. + model, }, }, };