From 682e77f3092c840a5eac2aed7f35ce1d2bace1a0 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Wed, 12 Nov 2025 15:57:33 +0100 Subject: [PATCH] feat: :sparkles: add news job to publish models on range dates --- app/Console/Kernel.php | 2 + app/Enums/News/NewsStatusEnum.php | 4 +- .../Requests/Back/News/StoreNewsRequest.php | 50 ++--- app/Jobs/NewsStatusUpdate.php | 48 +++++ app/Models/News.php | 182 +++++++++++------- .../DynamicPageRouteServiceProvider.php | 1 + .../Front/News/IndexNewsComponent.php | 14 +- database/factories/NewsFactory.php | 17 +- database/factories/assets/news/525x295.jpg | Bin 0 -> 4441 bytes ..._16_145827_create_contact_counts_table.php | 4 + .../2025_10_24_113240_create_news_table.php | 8 +- ...0_24_113241_create_category_news_table.php | 4 + .../2025_11_13_103942_alter_news_table.php | 42 ++++ database/seeders/NewsSeeder.php | 12 +- lang/en/crud.php | 4 +- lang/en/validation.php | 8 +- lang/fr/crud.php | 4 +- lang/fr/validation.php | 13 +- .../ts/back/Components/Inputs/MultiSelect.tsx | 114 ++++++----- .../Components/Inputs/SimpleDatePicker.tsx | 4 +- .../back/Components/Inputs/SimpleString.tsx | 4 +- resources/ts/back/Pages/DynamicPages/Form.tsx | 4 +- resources/ts/back/Pages/News/Form.tsx | 131 ++++++------- resources/ts/back/Pages/News/Show.tsx | 14 +- resources/ts/back/types/global.d.ts | 4 +- .../components/front/sections/news.blade.php | 8 +- .../views/front/pages/news/show.blade.php | 7 +- 27 files changed, 441 insertions(+), 266 deletions(-) create mode 100644 app/Jobs/NewsStatusUpdate.php create mode 100644 database/factories/assets/news/525x295.jpg create mode 100644 database/migrations/2025_11_13_103942_alter_news_table.php diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 9b1d4fc1..4dca0a05 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -3,6 +3,7 @@ namespace App\Console; use App\Jobs\CleanTrashModels; +use App\Jobs\NewsStatusUpdate; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; @@ -17,5 +18,6 @@ class Kernel extends ConsoleKernel protected function schedule(Schedule $schedule): void { $schedule->job(CleanTrashModels::class)->daily(); + $schedule->job(NewsStatusUpdate::class)->everyMinute(); } } diff --git a/app/Enums/News/NewsStatusEnum.php b/app/Enums/News/NewsStatusEnum.php index 906e7a67..e5347d24 100644 --- a/app/Enums/News/NewsStatusEnum.php +++ b/app/Enums/News/NewsStatusEnum.php @@ -17,7 +17,7 @@ enum NewsStatusEnum: int * @phpstan-ignore-next-line */ private const LABELS = [ - self::unpublished->name => 'enums.news-status.unpublished', - self::published->name => 'enums.news-status.published', + self::unpublished->name => 'enums.news-status.unpublished', + self::published->name => 'enums.news-status.published', ]; } diff --git a/app/Http/Requests/Back/News/StoreNewsRequest.php b/app/Http/Requests/Back/News/StoreNewsRequest.php index b0700c83..b3e1cf18 100644 --- a/app/Http/Requests/Back/News/StoreNewsRequest.php +++ b/app/Http/Requests/Back/News/StoreNewsRequest.php @@ -39,19 +39,19 @@ class StoreNewsRequest extends FormRequest public function rules(): array { return [ - 'titleSeo' => 'nullable|string|max:60', - 'descriptionSeo' => 'nullable|string|max:255', - 'title' => 'required|string|max:255', - 'slug' => 'required|string|max:255', - 'content' => 'required|string', - 'status' => ['required', new Enum(NewsStatusEnum::class)], - 'picture' => $this->pictureRules("nullable|file|mimes:jpg,jpeg,png|max:5120|dimensions:width=525,height=295"), - 'picture_alt' => 'nullable|string|max:60', - 'picture_title' => 'nullable|string|max:60', - 'categories' => 'nullable|array', - 'categories.*' => ['integer', new Enum(NewsCategoryEnum::class)], - 'published_at' => 'nullable|date', - 'unpublished_at' => 'nullable|date|after:published_at', + 'seo_title' => 'required|string|between:3,255', + 'seo_description' => 'required|string|between:3,255', + 'title' => 'required|string|between:3,255', + 'slug' => 'required|string|between:3,255', + 'picture' => $this->pictureRules("nullable|file|mimes:jpg,jpeg,png|max:5120|dimensions:width=525,height=295"), + 'picture_alt' => 'nullable|string|between:3,60', + 'picture_title' => 'nullable|string|between:3,60', + 'content' => 'required|string', + 'status' => ['required', new Enum(NewsStatusEnum::class)], + 'categories' => 'nullable|array', + 'categories.*' => ['integer', new Enum(NewsCategoryEnum::class)], + 'published_at' => 'nullable|date', + 'unpublished_at' => 'nullable|date|after:published_at', ]; } @@ -63,18 +63,18 @@ class StoreNewsRequest extends FormRequest public function attributes(): array { return [ - 'title' => trans('validation.attributes.title'), - 'slug' => trans('validation.custom.slug'), - 'status' => trans('validation.custom.status'), - 'titleSeo' => trans('validation.custom.titleSeo'), - 'descriptionSeo' => trans('validation.custom.descriptionSeo'), - 'categories' => trans('validation.custom.categories'), - 'content' => trans('validation.attributes.content'), - 'picture' => trans('validation.attributes.image'), - 'picture_alt' => trans('validation.custom.attribute_alt'), - 'picture_title' => trans('validation.custom.attribute_title'), - 'published_at' => trans('validation.custom.published_at'), - 'unpublished_at' => trans('validation.custom.unpublished_at'), + 'seo_title' => trans('validation.custom.seo.title'), + 'seo_description' => trans('validation.custom.seo.description'), + 'title' => trans('validation.attributes.title'), + 'slug' => trans('validation.custom.slug'), + 'categories' => trans('validation.custom.categories'), + 'picture' => trans('validation.attributes.image'), + 'picture_alt' => trans('validation.custom.image_alt'), + 'picture_title' => trans('validation.custom.image_title'), + 'status' => trans('validation.custom.status'), + 'content' => trans('validation.attributes.content'), + 'published_at' => trans('validation.custom.published_at'), + 'unpublished_at' => trans('validation.custom.unpublished_at'), ]; } } diff --git a/app/Jobs/NewsStatusUpdate.php b/app/Jobs/NewsStatusUpdate.php new file mode 100644 index 00000000..250db0df --- /dev/null +++ b/app/Jobs/NewsStatusUpdate.php @@ -0,0 +1,48 @@ + */ + $newsListToPublish = News::query() + ->where('published_at', '<=', Carbon::now()) + ->whereNotNull('published_at') + ->where('status', NewsStatusEnum::unpublished) + ->get(); + Log::debug(__CLASS__ . " news to publish " . $newsListToPublish->count()); + foreach ($newsListToPublish as $news) { + $news->status = NewsStatusEnum::published; + $news->saveQuietly(); + } + + // Unpublish all publish models if the unpublished_at date has passed. + /** @var \Illuminate\Database\Eloquent\Collection */ + $newsListToUnPublish = News::query() + ->where('unpublished_at', '<=', Carbon::now()) + ->whereNotNull('unpublished_at') + ->where('status', NewsStatusEnum::published)->get(); + Log::debug(__CLASS__ . " news to unpublish " . $newsListToPublish->count()); + foreach ($newsListToUnPublish as $news) { + $news->status = NewsStatusEnum::unpublished; + $news->saveQuietly(); + } + } +} diff --git a/app/Models/News.php b/app/Models/News.php index b65203f5..ce5a881b 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -11,26 +11,24 @@ use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; -use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; use Uwil\LaravelActivityLogs\Traits\ActivityLog; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Cache; - /** - * @property string $title Title of the news. - * @property string $slug Slug of the news. - * @property string $titleSeo Title of the news. - * @property string $descriptionSeo Slug of the news. - * @property string $content Content of the news. - * @property \App\Enums\News\NewsStatusEnum $status Status of the news. - * @property string $picture Main img of the news. - * @property string $picture_alt Alt text for the picture. - * @property string $picture_title Title for the picture. - * @property-read \Illuminate\Support\Carbon $created_at Date on which the news was created. - * @property-read \Illuminate\Support\Carbon $updated_at Date on which the news was updated. - * @property-read \Illuminate\Support\Carbon $deleted_at Date on which the news was updated. + * @property string $seo_title SEO title of the news. + * @property string $seo_description SEO description of the news. + * @property string $title Title of the news. + * @property string $slug Slug of the news. + * @property string $picture Main img of the news. + * @property string $picture_alt Alt text for the picture. + * @property string $picture_title Title for the picture. + * @property string $content Content of the news. + * @property \App\Enums\News\NewsStatusEnum $status Status of the news. + * @property-read \Illuminate\Support\Carbon $created_at Date on which the news was created. + * @property-read \Illuminate\Support\Carbon $updated_at Date on which the news was updated. + * @property-read \Illuminate\Support\Carbon $deleted_at Date on which the news was updated. */ class News extends Model implements TranslatableModel { @@ -60,15 +58,14 @@ class News extends Model implements TranslatableModel 'content' ]; - /** * The attributes that are mass assignable. * * @var list */ protected $fillable = [ - 'titleSeo', - 'descriptionSeo', + 'seo_title', + 'seo_description', 'title', 'slug', 'content', @@ -80,15 +77,14 @@ class News extends Model implements TranslatableModel 'unpublished_at', ]; - /** * The translatable columns. * * @var list */ public $translatable = [ - 'titleSeo', - 'descriptionSeo', + 'seo_title', + 'seo_description', 'title', 'slug', 'content', @@ -96,14 +92,13 @@ class News extends Model implements TranslatableModel 'picture_title', ]; - /** * The attributes that should be cast. * * @var array */ protected $casts = [ - 'status' => NewsStatusEnum::class, + 'status' => NewsStatusEnum::class, 'published_at' => 'datetime', 'unpublished_at' => 'datetime', ]; @@ -139,30 +134,101 @@ class News extends Model implements TranslatableModel }); } + // * METHODS + + /** + * Manage model fields. + * + * @param self $model + * @return void + */ + private static function manageFields(self $model): void + { + // Check unique fields. + $slug = Str::slug($model->title); + TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title'); + TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', 'title'); + $model->setAttribute('slug', $slug); + // Check translations. + self::validateFallbackTranslations($model); + // Set status. + self::makeStatusSense($model); + } + + public function inertiaFill(array $attributes) + { + $attributes = Arr::except($attributes, ['categories']); + $this->traitInertiaFill($attributes); + } + + /** + * Adjusts model status using current status and publish dates. + * Case 1: publish model when all null -> set published_at date. + * Case 2: unpublish model when all null -> nothing to do. + * Case 3: publish model when published_at is already set -> only change status. + * Case 4: unpublish model when published_at is already set -> can't update model. + * Case 5: publish model when unpublished_at is already set -> can't update model. + * Case 6: unpublish model when unpublished_at is already set -> only change status. + * + * @param self $model + * @return void + */ + private static function makeStatusSense(self $model): void + { + /** @var \Carbon\Carbon|null */ + $published_at = $model->published_at; + /** @var \Carbon\Carbon|null */ + $unpublished_at = $model->unpublished_at; + $wantedStatus = $model->status; + + // Check if dates are already set. + if ($published_at or $unpublished_at) { + $model->status = $model->planificated_status; + } + // If there is a diff, no update. + if ($wantedStatus !== $model->status) { + session()->flash('error', \trans( + 'La publication est modifiée en concordance avec les dates enregistrées. + Pour modifier l\'état de publication, veuillez modifier ou enlever les dates correspondantes.' + )); + } else { + // Set default published_at date when publishing model. + if ($model->status->equals(NewsStatusEnum::published)) { + $model->published_at = Carbon::now(); + } + } + } + /** * Getter the current status following planification dates planificated_status. * - * @return boolean + * @return \App\Enums\News\NewsStatusEnum */ - public function getPlanificatedStatusAttribute(): bool + protected function getPlanificatedStatusAttribute(): \App\Enums\News\NewsStatusEnum { /** @var \Carbon\Carbon|null */ $published_at = $this->published_at; /** @var \Carbon\Carbon|null */ $unpublished_at = $this->unpublished_at; + if ($published_at and $unpublished_at) { - return $unpublished_at->greaterThanOrEqualTo(now()) and $published_at->lessThan(now()); + return ($unpublished_at->greaterThanOrEqualTo(now()) and $published_at->lessThan(now())) + ? NewsStatusEnum::published + : NewsStatusEnum::unpublished; } if ($published_at) { - return $published_at->lessThan(now()); + return $published_at->lessThan(now()) + ? NewsStatusEnum::published + : NewsStatusEnum::unpublished; } if ($unpublished_at) { - return $unpublished_at->greaterThanOrEqualTo(now()); + return $unpublished_at->greaterThanOrEqualTo(now()) + ? NewsStatusEnum::published + : NewsStatusEnum::unpublished; } - return false; + return NewsStatusEnum::unpublished; } - /** * Reset all cache elements related to this model. * @@ -175,7 +241,7 @@ class News extends Model implements TranslatableModel } /** - * Get all published dynamic pages. + * Get all published news. * * @return \Illuminate\Database\Eloquent\Collection */ @@ -189,22 +255,16 @@ class News extends Model implements TranslatableModel }); } - public function publishedAtFormatted() + /** + * Get formated published_at date. + * + * @return string + */ + public function publishedAtFormatted(): string { return Carbon::parse($this->published_at)->format('d/m/Y'); } - /** - * The relation with NewsCategory. - * - * @return HasMany - */ - public function categories(): HasMany - { - return $this->hasMany(NewsCategory::class, 'news_id'); - } - - /** * Get a comma-separated list of all category labels for this news item. * @@ -244,32 +304,6 @@ class News extends Model implements TranslatableModel ]; } - - public function inertiaFill(array $attributes) - { - $attributes = Arr::except($attributes, ['categories']); - $this->traitInertiaFill($attributes); - } - - - /** - * Manage model fields. - * - * @param self $model - * @return void - */ - private static function manageFields(self $model): void - { - // Check unique fields. - $slug = Str::slug($model->title); - TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title'); - TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', 'title'); - $model->setAttribute('slug', $slug); - // Check translations. - self::validateFallbackTranslations($model); - } - - /** * Assert fallback locale translation is present. * @@ -284,4 +318,16 @@ class News extends Model implements TranslatableModel } TranslationHelper::validateFallbackTranslations($model); } + + // * RELATIONSHIPS + + /** + * The relation with NewsCategory. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function categories(): \Illuminate\Database\Eloquent\Relations\HasMany + { + return $this->hasMany(NewsCategory::class, 'news_id'); + } } diff --git a/app/Providers/DynamicPageRouteServiceProvider.php b/app/Providers/DynamicPageRouteServiceProvider.php index ed11a972..51f28204 100644 --- a/app/Providers/DynamicPageRouteServiceProvider.php +++ b/app/Providers/DynamicPageRouteServiceProvider.php @@ -28,6 +28,7 @@ class DynamicPageRouteServiceProvider extends ServiceProvider ], function () { $dynamicPageModels = DynamicPage::getPublishedDynamicPages(); DynamicPage::getPublishedDynamicPages() + ->load('parentPage') ->map(function (DynamicPage $dynamicPageModel) use ($dynamicPageModels) { $locale = app()->getLocale(); $slug = $dynamicPageModel->getTranslation("slug", $locale); diff --git a/app/View/Components/Front/News/IndexNewsComponent.php b/app/View/Components/Front/News/IndexNewsComponent.php index df767bd8..6324c38d 100644 --- a/app/View/Components/Front/News/IndexNewsComponent.php +++ b/app/View/Components/Front/News/IndexNewsComponent.php @@ -30,8 +30,8 @@ class IndexNewsComponent extends Component ->map(fn($category) => NewsCategoryEnum::make((int) $category->value)) ->filter(fn($categoryLocal) => $categoryLocal->categoriesWithLocal()) ->map(fn($categoryLocal) => [ - 'title' => __($categoryLocal->label()), - 'tag' => Str::slug($categoryLocal->value), + 'title' => trans($categoryLocal->label()), + 'tag' => Str::slug($categoryLocal->value), 'category' => 'news', ]) ->values() @@ -41,7 +41,7 @@ class IndexNewsComponent extends Component ->map(fn($year) => NewsYearsEnum::make((int) $year->value)) ->filter(fn($yearLocal) => $yearLocal->yearsWithLocal()) ->map(fn($yearLocal) => [ - 'title' => __($yearLocal->label()), + 'title' => trans($yearLocal->label()), 'tag' => Str::slug($yearLocal->value), 'category' => 'news', ]) @@ -50,8 +50,10 @@ class IndexNewsComponent extends Component /** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $query */ $query = News::query()->with('categories'); + /** Sort columns with a query */ $bladeHelper->runSortQuery($query); + /** Custom pagination */ $this->newsModels = $bladeHelper->runPaginate($query); @@ -105,9 +107,9 @@ class IndexNewsComponent extends Component public function render(): View|Closure|string { return view('components.front.news.index-news-component', [ - 'categories' => $this->categories, - 'years' => $this->years, - 'newsModels' => $this->newsModels, + 'categories' => $this->categories, + 'years' => $this->years, + 'newsModels' => $this->newsModels, 'postContainer' => $this->postContainer ]); } diff --git a/database/factories/NewsFactory.php b/database/factories/NewsFactory.php index 3a6ab6c5..64aaff57 100644 --- a/database/factories/NewsFactory.php +++ b/database/factories/NewsFactory.php @@ -20,15 +20,14 @@ class NewsFactory extends Factory public function definition(): array { return [ - 'titleSeo' => fake()->sentence(6, true), - 'descriptionSeo' => fake()->paragraph(2, true), - 'title' => fake()->sentence(4), - 'slug' => fake()->unique()->slug(), - 'content' => fake()->paragraphs(5, true), - 'status' => collect(NewsStatusEnum::cases())->random(), - 'picture' => fake()->imageUrl(1200, 800, 'news', true, 'headline'), - 'picture_alt' => fake()->sentence(6, true), - 'picture_title' => fake()->sentence(6, true), + 'seo_title' => fake()->sentence(6, true), + 'seo_description' => fake()->paragraph(2, true), + 'title' => fake()->sentence(4), + 'slug' => fake()->unique()->slug(), + 'content' => fake()->paragraphs(5, true), + 'status' => collect(NewsStatusEnum::cases())->random(), + 'picture_alt' => fake()->sentence(6, true), + 'picture_title' => fake()->sentence(6, true), ]; } diff --git a/database/factories/assets/news/525x295.jpg b/database/factories/assets/news/525x295.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4eb30e619808da3c85d983e5375763f587944398 GIT binary patch literal 4441 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 JVL(qi`dstring('descriptionSeo')->nullable()->comment('Seo description of the news'); $table->string('title')->comment('Required title for the news'); $table->string('slug')->unique()->comment('Required and unique slug for the news.show'); - $table->text('content')->comment('Body of the news, wysiwyg to be more specific, from Seattle'); - $table->unsignedTinyInteger('status')->comment('Status of the news'); $table->string('picture')->nullable()->comment('Banner and thumbnail of the news'); $table->string('picture_alt')->nullable()->comment('Alt of the picture of the news'); $table->string('picture_title')->nullable()->comment('Title of the picture of the news'); + $table->text('content')->comment('Body of the news, wysiwyg to be more specific'); + $table->unsignedTinyInteger('status')->comment('Status of the news'); $table->timestamp('published_at')->nullable()->comment('News corporate publishment date.'); $table->timestamp('unpublished_at')->nullable()->comment('News corporate unpublishment date.'); $table->softDeletes(); @@ -31,6 +33,8 @@ return new class extends Migration /** * Reverse the migrations. + * + * @return void */ public function down(): void { diff --git a/database/migrations/2025_10_24_113241_create_category_news_table.php b/database/migrations/2025_10_24_113241_create_category_news_table.php index 91952a8e..cc18de4f 100644 --- a/database/migrations/2025_10_24_113241_create_category_news_table.php +++ b/database/migrations/2025_10_24_113241_create_category_news_table.php @@ -8,6 +8,8 @@ return new class extends Migration { /** * Run the migrations. + * + * @return void */ public function up(): void { @@ -21,6 +23,8 @@ return new class extends Migration /** * Reverse the migrations. + * + * @return void */ public function down(): void { diff --git a/database/migrations/2025_11_13_103942_alter_news_table.php b/database/migrations/2025_11_13_103942_alter_news_table.php new file mode 100644 index 00000000..5960ce62 --- /dev/null +++ b/database/migrations/2025_11_13_103942_alter_news_table.php @@ -0,0 +1,42 @@ +renameColumn('titleSeo', 'seo_title'); + $table->renameColumn('descriptionSeo', 'seo_description'); + }); + Schema::table('news', function (Blueprint $table) { + $table->string('seo_title')->nullable(false)->comment('Seo title for the news')->change(); + $table->string('seo_description')->nullable(false)->comment('Seo description of the news')->change(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down(): void + { + Schema::table('news', function (Blueprint $table) { + $table->renameColumn('seo_title', 'titleSeo'); + $table->renameColumn('seo_description', 'descriptionSeo'); + }); + Schema::table('news', function (Blueprint $table) { + $table->string('titleSeo')->nullable(true)->comment('Seo title for the news')->change(); + $table->string('descriptionSeo')->nullable(true)->comment('Seo description of the news')->change(); + }); + } +}; diff --git a/database/seeders/NewsSeeder.php b/database/seeders/NewsSeeder.php index 85ee8d76..9e46a209 100644 --- a/database/seeders/NewsSeeder.php +++ b/database/seeders/NewsSeeder.php @@ -4,6 +4,7 @@ namespace Database\Seeders; use App\Models\News; use Illuminate\Database\Seeder; +use Uwil\LaravelCommon\Helpers\FileHelper; class NewsSeeder extends Seeder { @@ -14,6 +15,15 @@ class NewsSeeder extends Seeder */ public function run(): void { - News::factory(100)->create(); + News::factory(100)->make() + ->each(function ($model) { + $model->picture = FileHelper::storeFile( + $model, + new \SplFileInfo(\resource_path( + '../database/factories/assets/news/525x295.jpg' + )) + ); + $model->saveOrFail(); + }); } } diff --git a/lang/en/crud.php b/lang/en/crud.php index a9645828..7e36d0db 100644 --- a/lang/en/crud.php +++ b/lang/en/crud.php @@ -28,8 +28,8 @@ return [ in search engines ( tag).", "seo_description" => "Must precisely describe page content (<meta> description tag).", "visibility_with_dates" => "This field will only have an effect if no date is entered.", - "publish_at" => ":model will be published from this date.", - "unpublish_at" => ":model will be unpublished from this date.", + "published_at" => ":model will be published from this date.", + "unpublished_at" => ":model will be unpublished from this date.", "year" => "Must be a year between :yearStart and :yearEnd.", ], diff --git a/lang/en/validation.php b/lang/en/validation.php index f99f01d6..03e45dac 100644 --- a/lang/en/validation.php +++ b/lang/en/validation.php @@ -240,9 +240,11 @@ return [ "locked" => "locked", "field" => "field", "key" => "unique key", - "slug" => "slug", - "titleSeo" => "seo title", - "descriptionSeo" => "seo description", + "slug" => "slug", + "seo" => [ + "title" => "seo title", + "description" => "seo description", + ], "category" => "category|categories", "picture" => [ "picture" => "image", diff --git a/lang/fr/crud.php b/lang/fr/crud.php index d9f88bb0..0b75d70e 100644 --- a/lang/fr/crud.php +++ b/lang/fr/crud.php @@ -28,8 +28,8 @@ return [ optimal dans les moteurs de recherche (balise <title>).", "seo_description" => "Doit décrire précisément le contenu de la page (balise <meta> description).", "visibility_with_dates" => "Ce champ n'aura d'effet que si aucune date n'est renseignée.", - "publish_at" => ":model sera publié à partir de cette date.", - "unpublish_at" => ":model sera dépublié à partir de cette date.", + "published_at" => ":model sera publié à partir de cette date.", + "unpublished_at" => ":model sera dépublié à partir de cette date.", "year" => "Doît être une année comprise entre :yearStart et :yearEnd.", ], diff --git a/lang/fr/validation.php b/lang/fr/validation.php index 6d41fcb6..f4c64c2a 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -241,15 +241,14 @@ return [ "field" => "champs", "key" => "clé", "slug" => "chemin d'accès", - "titleSeo" => "titre SEO", "parent_page" => "page parente", - "descriptionSeo" => "description SEO", - "category" => "catégorie|catégories", - "picture" => [ - "picture" => "image", - "picture_alt" => "texte alternatif de l'image", - "picture_title" => "titre de l'image" + "seo" => [ + "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" => [ "type" => "type de formulaire", diff --git a/resources/ts/back/Components/Inputs/MultiSelect.tsx b/resources/ts/back/Components/Inputs/MultiSelect.tsx index 3fc951e1..20979e8a 100644 --- a/resources/ts/back/Components/Inputs/MultiSelect.tsx +++ b/resources/ts/back/Components/Inputs/MultiSelect.tsx @@ -1,4 +1,3 @@ -import * as React from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { CheckIcon, @@ -7,7 +6,6 @@ import { XIcon, WandSparkles, } from "lucide-react"; - import { cn } from "@/lib/utils"; import { Separator } from "@/components/ui/separator"; import { Button } from "@/components/ui/button"; @@ -31,6 +29,7 @@ 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"; /** * Animation types and configurations @@ -86,7 +85,7 @@ interface MultiSelectOption { /** The unique value associated with the option. */ value: string; /** Optional icon component to display alongside the option. */ - icon?: React.ComponentType<{ className?: string }>; + icon?: ComponentType<{ className?: string }>; /** Whether this option is disabled */ disabled?: boolean; /** Custom styling for the option */ @@ -115,7 +114,7 @@ interface MultiSelectGroup { */ interface MultiSelectProps extends Omit< - React.ButtonHTMLAttributes<HTMLButtonElement>, + ButtonHTMLAttributes<HTMLButtonElement>, "animationConfig" >, VariantProps<typeof multiSelectVariants> { @@ -127,7 +126,7 @@ interface MultiSelectProps * Callback function triggered when the selected values change. * Receives an array of the new selected values. */ - onValueChange: (value: string[]) => void; + onValueChange?: (value: string[]) => void; /** The default selected values when the component mounts. */ defaultValue?: string[]; @@ -192,7 +191,7 @@ interface MultiSelectProps * Custom empty state message when no options match search. * Optional, defaults to "No results found." */ - emptyIndicator?: React.ReactNode; + emptyIndicator?: ReactNode; /** * If true, allows the component to grow and shrink with its content. @@ -352,7 +351,7 @@ export interface MultiSelectRef { focus: () => void; } -export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( +export const MultiSelect = forwardRef<MultiSelectRef, MultiSelectProps>( ( { name, @@ -391,21 +390,20 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( }, ref ) => { - const [selectedValues, setSelectedValues] = - React.useState<string[]>(defaultValue); - const [isPopoverOpen, setIsPopoverOpen] = React.useState(false); - const [isAnimating, setIsAnimating] = React.useState(false); - const [searchValue, setSearchValue] = React.useState(""); + const [selectedValues, setSelectedValues] = useState<string[]>(defaultValue); + const [isPopoverOpen, setIsPopoverOpen] = useState(false); + const [isAnimating, setIsAnimating] = useState(false); + const [searchValue, setSearchValue] = useState(""); - const [politeMessage, setPoliteMessage] = React.useState(""); - const [assertiveMessage, setAssertiveMessage] = React.useState(""); - const prevSelectedCount = React.useRef(selectedValues.length); - const prevIsOpen = React.useRef(isPopoverOpen); - const prevSearchValue = React.useRef(searchValue); + const [politeMessage, setPoliteMessage] = useState(""); + const [assertiveMessage, setAssertiveMessage] = useState(""); + const prevSelectedCount = useRef(selectedValues.length); + const prevIsOpen = useRef(isPopoverOpen); + const prevSearchValue = useRef(searchValue); const { errors } = usePage().props; - const announce = React.useCallback( + const announce = useCallback( (message: string, priority: "polite" | "assertive" = "polite") => { if (priority === "assertive") { setAssertiveMessage(message); @@ -418,14 +416,14 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( [] ); - const multiSelectId = React.useId(); + const multiSelectId = useId(); const listboxId = `${multiSelectId}-listbox`; const triggerDescriptionId = `${multiSelectId}-description`; const selectedCountId = `${multiSelectId}-count`; - const prevDefaultValueRef = React.useRef<string[]>(defaultValue); + const prevDefaultValueRef = useRef<string[]>(defaultValue); - const isGroupedOptions = React.useCallback( + const isGroupedOptions = useCallback( ( opts: MultiSelectOption[] | MultiSelectGroup[] ): opts is MultiSelectGroup[] => { @@ -434,7 +432,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( [] ); - const arraysEqual = React.useCallback( + const arraysEqual = useCallback( (a: string[], b: string[]): boolean => { if (a.length !== b.length) return false; const sortedA = [...a].sort(); @@ -444,29 +442,35 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( [] ); - const resetToDefault = React.useCallback(() => { + const resetToDefault = useCallback(() => { setSelectedValues(defaultValue); setIsPopoverOpen(false); setSearchValue(""); - onValueChange(defaultValue); + if (onValueChange) { + onValueChange(defaultValue); + } setData(name, defaultValue); }, [defaultValue, onValueChange]); - const buttonRef = React.useRef<HTMLButtonElement>(null); + const buttonRef = useRef<HTMLButtonElement>(null); - React.useImperativeHandle( + useImperativeHandle( ref, () => ({ reset: resetToDefault, getSelectedValues: () => selectedValues, setSelectedValues: (values: string[]) => { setSelectedValues(values); - onValueChange(values); + if (onValueChange) { + onValueChange(values); + } setData(name, values); }, clear: () => { setSelectedValues([]); - onValueChange([]); + if (onValueChange) { + onValueChange([]); + } setData(name, []); }, focus: () => { @@ -488,11 +492,11 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( [resetToDefault, selectedValues, onValueChange] ); - const [screenSize, setScreenSize] = React.useState< + const [screenSize, setScreenSize] = useState< "mobile" | "tablet" | "desktop" >("desktop"); - React.useEffect(() => { + useEffect(() => { if (typeof window === "undefined") return; const handleResize = () => { const width = window.innerWidth; @@ -588,7 +592,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( return ""; }; - const getAllOptions = React.useCallback((): MultiSelectOption[] => { + const getAllOptions = useCallback((): MultiSelectOption[] => { if (options.length === 0) return []; let allOptions: MultiSelectOption[]; if (isGroupedOptions(options)) { @@ -627,7 +631,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( return deduplicateOptions ? uniqueOptions : allOptions; }, [options, deduplicateOptions, isGroupedOptions]); - const getOptionByValue = React.useCallback( + const getOptionByValue = useCallback( (value: string): MultiSelectOption | undefined => { const option = getAllOptions().find((option) => option.value === value); if (!option && process.env.NODE_ENV === "development") { @@ -640,7 +644,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( [getAllOptions] ); - const filteredOptions = React.useMemo(() => { + const filteredOptions = useMemo(() => { if (!searchable || !searchValue) return options; if (options.length === 0) return []; if (isGroupedOptions(options)) { @@ -665,7 +669,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( }, [options, searchValue, searchable, isGroupedOptions]); const handleInputKeyDown = ( - event: React.KeyboardEvent<HTMLInputElement> + event: KeyboardEvent<HTMLInputElement> ) => { if (event.key === "Enter") { setIsPopoverOpen(true); @@ -673,7 +677,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( const newSelectedValues = [...selectedValues]; newSelectedValues.pop(); setSelectedValues(newSelectedValues); - onValueChange(newSelectedValues); + if (onValueChange) { + onValueChange(newSelectedValues); + } setData(name, newSelectedValues); } }; @@ -687,7 +693,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( if (!multiple) { const newSelectedValues = selectedValues.includes(optionValue) ? [] : [optionValue]; setSelectedValues(newSelectedValues); - onValueChange(newSelectedValues); + if (onValueChange) { + onValueChange(newSelectedValues); + } setData(name, newSelectedValues); if (closeOnSelect) { setIsPopoverOpen(false); @@ -705,7 +713,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( } const newSelectedValues = selectedValues.filter((value) => value !== optionValue); setSelectedValues(newSelectedValues); - onValueChange(newSelectedValues); + if (onValueChange) { + onValueChange(newSelectedValues); + } setData(name, newSelectedValues); } else { if (maxSelection && selectedValues.length >= maxSelection) { @@ -714,7 +724,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( } const newSelectedValues = [...selectedValues, optionValue]; setSelectedValues(newSelectedValues); - onValueChange(newSelectedValues); + if (onValueChange) { + onValueChange(newSelectedValues); + } setData(name, newSelectedValues); } @@ -730,7 +742,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( return; } setSelectedValues([]); - onValueChange([]); + if (onValueChange) { + onValueChange([]); + } setData(name, []); }; @@ -746,7 +760,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( responsiveSettings.maxCount ); setSelectedValues(newSelectedValues); - onValueChange(newSelectedValues); + if (onValueChange) { + onValueChange(newSelectedValues); + } setData(name, newSelectedValues); }; @@ -767,7 +783,9 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( return; } setSelectedValues(allValues); - onValueChange(allValues); + if (onValueChange) { + onValueChange(allValues); + } setData(name, allValues); } @@ -776,7 +794,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( } }; - React.useEffect(() => { + useEffect(() => { if (!resetOnDefaultValueChange) return; const prevDefaultValue = prevDefaultValueRef.current; if (!arraysEqual(prevDefaultValue, defaultValue)) { @@ -800,13 +818,13 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( const widthConstraints = getWidthConstraints(); - React.useEffect(() => { + useEffect(() => { if (!isPopoverOpen) { setSearchValue(""); } }, [isPopoverOpen]); - React.useEffect(() => { + useEffect(() => { const selectedCount = selectedValues.length; const allOptions = getAllOptions(); const totalOptions = allOptions.filter((opt) => !opt.disabled).length; @@ -868,7 +886,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( } }, [selectedValues, isPopoverOpen, searchValue, announce, getAllOptions]); - React.useEffect(() => { + useEffect(() => { if (minSelection !== undefined && maxSelection !== undefined && minSelection > maxSelection) { console.error('MultiSelect: minSelection cannot be greater than maxSelection'); } @@ -884,7 +902,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( }, [minSelection, maxSelection, multiple]); return ( - <> + <div> <div className="sr-only"> <div aria-live="polite" aria-atomic="true" role="status"> {politeMessage} @@ -963,7 +981,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( if (!option) { return null; } - const badgeStyle: React.CSSProperties = { + const badgeStyle: CSSProperties = { animationDuration: `${animation}s`, ...(customStyle?.badgeColor && { backgroundColor: customStyle.badgeColor, @@ -1316,7 +1334,7 @@ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>( </Popover> {helper && (<small className="text-muted-foreground">{helper}</small>)} <InputError message={errors[name]} /> - </> + </div> ); } ); diff --git a/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx b/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx index 353f91d6..fdf9b5a7 100644 --- a/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx +++ b/resources/ts/back/Components/Inputs/SimpleDatePicker.tsx @@ -58,7 +58,7 @@ export default function SimpleDatePicker({ }; const resetDate = () => { - setData(name, undefined); + setData(name, null); } function handleTimeChange(type: "hour" | "minute", value: string) { @@ -81,7 +81,7 @@ export default function SimpleDatePicker({ <PopoverTrigger asChild> <Button variant={"outline"} - className={cn("w-full font-normal text-muted-foreground", className)} + className={cn("w-full font-normal", { "text-muted-foreground hover:text-muted-foreground": !date }, className)} disabled={disabled} > <span> diff --git a/resources/ts/back/Components/Inputs/SimpleString.tsx b/resources/ts/back/Components/Inputs/SimpleString.tsx index 27870b8e..45da2386 100644 --- a/resources/ts/back/Components/Inputs/SimpleString.tsx +++ b/resources/ts/back/Components/Inputs/SimpleString.tsx @@ -25,7 +25,7 @@ type SimpleStringProps = { disabled?: boolean; pattern?: string; checkVisibility?: boolean; - parentErrors?: Record<string, string>, + parentErrors?: Record<string, string> | null, // eslint-disable-next-line no-unused-vars setData: (name: string, value: string) => void; }; @@ -43,7 +43,7 @@ export default function SimpleString({ disabled = false, pattern, checkVisibility = false, - parentErrors = {}, + parentErrors = null, setData, }: SimpleStringProps) { const [isVisible, setIsVisible] = useState(checkVisibility); diff --git a/resources/ts/back/Pages/DynamicPages/Form.tsx b/resources/ts/back/Pages/DynamicPages/Form.tsx index 13e72fe7..a37a332c 100644 --- a/resources/ts/back/Pages/DynamicPages/Form.tsx +++ b/resources/ts/back/Pages/DynamicPages/Form.tsx @@ -30,7 +30,7 @@ import InputError from "@/back/Components/InputError"; import str from "@/hooks/use-string"; import { useToast } from "@/hooks/use-toast"; import { Methods } from "@/lib/enums"; -import { AppEnv, AuthProp, DynamicField, DynamicPageModel, LaravelEnum, PageConfigModel } from "@/back/types/global"; +import { AppEnv, AuthProp, ConfigField, DynamicPageModel, LaravelEnum, PageConfigModel } from "@/back/types/global"; import { Tooltip, TooltipContent, @@ -162,7 +162,7 @@ export default function Form({ const getConfig = (id: number) => configOptions.find((objet) => objet.id == id)?.config[ locale - ] as DynamicField[]; + ] as ConfigField[]; const { toast } = useToast(); /** Form section */ diff --git a/resources/ts/back/Pages/News/Form.tsx b/resources/ts/back/Pages/News/Form.tsx index 7598fe19..3b52c038 100644 --- a/resources/ts/back/Pages/News/Form.tsx +++ b/resources/ts/back/Pages/News/Form.tsx @@ -62,8 +62,8 @@ export default function Form({ /** Form section */ const { post, setData, data, reset } = useForm({ _method: method === Methods.POST ? 'post' : 'put', - titleSeo: model?.titleSeo ? model?.titleSeo[locale] : "", - descriptionSeo: model?.descriptionSeo ? model?.descriptionSeo[locale] : "", + seo_title: model?.seo_title ? model?.seo_title[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] : "", @@ -125,33 +125,33 @@ export default function Form({ className="sm:grid-cols-2 gap-4" > <SimpleString - name="titleSeo" + name="seo_title" label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.titleSeo"), + attribute: useTrans("validation.custom.seo.title"), }, choice: 1, }), ).ucFirst().value()} - required={false} + required={true} placeholder="ex: John Doe" - value={data.titleSeo ?? ""} + value={data.seo_title ?? ""} setData={setData} /> <SimpleString - name="descriptionSeo" + name="seo_description" label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.descriptionSeo"), + attribute: useTrans("validation.custom.seo.description"), }, choice: 1, }), ).ucFirst().value()} placeholder="ex: John Doe" - required={false} - value={data.descriptionSeo ?? ""} + required={true} + value={data.seo_description ?? ""} setData={setData} /> </FieldsetWrapper> @@ -189,21 +189,6 @@ export default function Form({ value={data.slug} setData={setData} /> - <EnumSelect - name="status" - options={enumNewsStatus} - label={str( - useTrans("back.form_associate_to", { - params: { - attribute: useTrans("validation.custom.status"), - }, - choice: 1, - }), - ).ucFirst().value()} - placeholder={"ex: " + enumNewsStatus.unpublished.label} - selected={String(data.status)} - setData={setData} - /> </FieldsetWrapper> <FieldsetWrapper title={useTrans("back.form_title_configuration")} @@ -239,6 +224,21 @@ export default function Form({ }), ).ucFirst().value()} /> + <EnumSelect + name="status" + options={enumNewsStatus} + label={str( + useTrans("back.form_associate_to", { + params: { + attribute: useTrans("validation.custom.status"), + }, + choice: 1, + }), + ).ucFirst().value()} + placeholder={"ex: " + enumNewsStatus.unpublished.label} + selected={String(data.status)} + setData={setData} + /> </FieldsetWrapper> <FieldsetWrapper title={useTrans("back.form_title_files")} @@ -252,7 +252,7 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.picture.picture_alt"), + attribute: useTrans("validation.custom.image_alt"), }, choice: 1, }), @@ -267,7 +267,7 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.picture.picture_title"), + attribute: useTrans("validation.custom.image_title"), }, choice: 1, }), @@ -283,7 +283,7 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.picture.picture"), + attribute: useTrans("validation.attributes.image"), }, choice: 1, }), @@ -306,46 +306,41 @@ export default function Form({ description={useTrans("back.form_subtitle_content")} className="gap-4" > - <div> - <SimpleWysiwyg - name={"content"} - model="News" - label={str( - useTrans("back.form_associate_to", { - params: { - attribute: useTrans("validation.custom.content"), - }, - choice: 1 - }), - ).ucFirst().value()} - value={data.content} - setData={setData} - /> - </div> - <div> - <MultiSelect - label={str( - useTrans("back.form_associate_to_plural", { - params: { - attribute: useTrans("validation.custom.category", { choice: 2 }), - }, - choice: 2 - }), - ).ucFirst().value()} - multiple={true} - name="categories" - required={false} - variant={"inverted"} - placeholder={str( - useTrans("back.news.categories.placeholder") - ).ucFirst().value()} - badgeAnimation={"wiggle"} - singleLine={true} - setData={setData} - defaultValue={data.categories} - options={options} - onValueChange={() => { }} /> - </div> + <SimpleWysiwyg + name={"content"} + model="News" + label={str( + useTrans("back.form_associate_to", { + params: { + attribute: useTrans("validation.custom.content"), + }, + choice: 1 + }), + ).ucFirst().value()} + value={data.content} + setData={setData} + /> + <MultiSelect + label={str( + useTrans("back.form_associate_to_plural", { + params: { + attribute: useTrans("validation.custom.category", { choice: 2 }), + }, + choice: 2 + }), + ).ucFirst().value()} + multiple={true} + name="categories" + required={false} + variant="inverted" + placeholder={str( + useTrans("back.news.categories.placeholder") + ).ucFirst().value()} + singleLine={true} + setData={setData} + defaultValue={data.categories} + options={options} + /> </FieldsetWrapper> <div className="text-center"> <SubmitButton /> diff --git a/resources/ts/back/Pages/News/Show.tsx b/resources/ts/back/Pages/News/Show.tsx index d5b1925e..479f9bc1 100644 --- a/resources/ts/back/Pages/News/Show.tsx +++ b/resources/ts/back/Pages/News/Show.tsx @@ -41,15 +41,15 @@ export default function Show({ data }: { data: SingleResource }) { console.log(useLocale.use.timezone()); const columns = [ { - accessorKey: "titleSeo", - header: str(useTrans("validation.custom.titleSeo")).ucFirst().value(), + accessorKey: "seo_title", + header: str(useTrans("validation.custom.seo.title")).ucFirst().value(), cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] ? value[appEnv.locale] : (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>), }, { - accessorKey: "descriptionSeo", - header: str(useTrans("validation.custom.descriptionSeo")).ucFirst().value(), + accessorKey: "seo_description", + header: str(useTrans("validation.custom.seo.description")).ucFirst().value(), cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] ? value[appEnv.locale] : (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>), @@ -110,21 +110,21 @@ export default function Show({ data }: { data: SingleResource }) { }, { accessorKey: "picture", - header: str(useTrans("validation.custom.picture.picture")).ucFirst().value(), + header: str(useTrans("validation.attributes.image")).ucFirst().value(), cell: ({ value }: { value: string }) => ( <img src={`${appEnv.url}/${value}`} /> ), }, { accessorKey: "picture_alt", - header: str(useTrans("validation.custom.picture.picture_alt")).ucFirst().value(), + header: str(useTrans("validation.custom.image_alt")).ucFirst().value(), cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] ? value[appEnv.locale] : (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>), }, { accessorKey: "picture_title", - header: str(useTrans("validation.custom.picture.picture_title")).ucFirst().value(), + header: str(useTrans("validation.custom.image_title")).ucFirst().value(), cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] ? value[appEnv.locale] : (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>), diff --git a/resources/ts/back/types/global.d.ts b/resources/ts/back/types/global.d.ts index cf08b95d..a5a3c1cc 100644 --- a/resources/ts/back/types/global.d.ts +++ b/resources/ts/back/types/global.d.ts @@ -107,8 +107,8 @@ type ConfigInternalField = Omit<DynamicField, "children"> & { type NewsModel = { policies: ModelPolicy; id: number; - titleSeo: TranslationField | null; - descriptionSeo: TranslationField | null; + seo_title: TranslationField | null; + seo_description: TranslationField | null; title: TranslationField; slug: TranslationField; content: TranslationField; diff --git a/resources/views/components/front/sections/news.blade.php b/resources/views/components/front/sections/news.blade.php index 977f9cfa..38c4be2f 100644 --- a/resources/views/components/front/sections/news.blade.php +++ b/resources/views/components/front/sections/news.blade.php @@ -21,11 +21,9 @@ </div> @endif <div class="list-item__title posts-list__item-title subtitle">{{ $news['title'] }}</div> - @if (isset($news->created_at)) - <div class="list-item__date date {{ $news->first_category_data['date_classes'] ?? 'date_no-tags' }}"> - {{ $news->created_at }} - </div> - @endif + <div class="list-item__date date {{ $news->first_category_data['date_classes'] ?? 'date_no-tags' }}"> + {{ $news->publishedAtFormatted() }} + </div> <div class="list-item__text ellipsis description"></div> @if ($isButtonStyle) <x-front.cta title="Lire l'article" class="list-item__readmore" diff --git a/resources/views/front/pages/news/show.blade.php b/resources/views/front/pages/news/show.blade.php index 28c418b3..42fc54de 100644 --- a/resources/views/front/pages/news/show.blade.php +++ b/resources/views/front/pages/news/show.blade.php @@ -1,6 +1,6 @@ @extends('front.layouts.layout') -@section('title', $model['titleSeo']) -@section('description', $model['descriptionSeo']) +@section('title', $model['seo_title']) +@section('description', $model['seo_description']) @section('content') <div class="single-news fw"> @@ -18,7 +18,8 @@ {{ $model['title'] }} </h1> <div class="single-news__date date {{ $model->first_category_data['date_classes'] ?? '' }}"> - {{ $model['created_at'] }}</div> + {{ $model->publishedAtFormatted() }} + </div> <div class="textblock__container"> <div class="textblock__image textblock__block image-border-wrap"> <x-front.borders :borders="[