feat: ✨ add newsTag model / morphMany table pivot

This commit is contained in:
K Muller 2026-01-07 11:20:27 +01:00
parent d68684459c
commit d001b44e8f
36 changed files with 1363 additions and 117 deletions

View file

@ -7,6 +7,7 @@ use App\Http\Requests\Back\News\StoreNewsRequest;
use App\Http\Requests\Back\News\UpdateNewsRequest;
use App\Models\News;
use App\Models\NewsCategory;
use App\Models\NewsTag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
@ -82,6 +83,7 @@ class NewsController extends Controller
'data' => CommonResource::make($news),
'enumNewsStatus' => NewsStatusEnum::toArray(),
'newsCategory' => NewsCategory::getModelsCached(),
'newsTag' => NewsTag::getModelsCached(),
'modelName' => $this->modelName,
]);
}
@ -95,7 +97,7 @@ class NewsController extends Controller
public function show(News $news): \Inertia\Response
{
return Inertia::render('News/Show', [
'data' => CommonResource::make($news->load('categories')),
'data' => CommonResource::make($news->load('categories', 'tags')),
'enumNewsStatus' => NewsStatusEnum::toArray(),
'modelName' => $this->modelName,
]);
@ -115,6 +117,7 @@ class NewsController extends Controller
if ($newsModel->saveOrFail()) {
$newsModel->categories()->syncWithoutDetaching($request->input('categories', []));
$newsModel->tags()->syncWithoutDetaching($request->input('tags', []));
return redirect()->route("back.$this->modelName.edit", $newsModel);
}
return redirect()->route("back.$this->modelName.create");
@ -130,9 +133,10 @@ class NewsController extends Controller
public function edit(News $news): \Inertia\Response
{
return Inertia::render('News/Edit', [
'data' => CommonResource::make($news->load('categories')),
'data' => CommonResource::make($news->load('categories', 'tags')),
'enumNewsStatus' => NewsStatusEnum::toArray(),
'newsCategory' => NewsCategory::getModelsCached(),
'newsTag' => NewsTag::getModelsCached(),
'modelName' => $this->modelName,
]);
}
@ -150,6 +154,7 @@ class NewsController extends Controller
$news->inertiaFill($request->validated());
if ($news->saveOrFail()) {
$news->categories()->sync($request->input('categories', []));
$news->tags()->sync($request->input('tags', []));
return redirect()->route("back.$this->modelName.edit", $news);
}
return redirect()->route("back.$this->modelName.edit", $news);

View file

@ -0,0 +1,206 @@
<?php
namespace App\Http\Controllers\Back;
use App\Enums\News\NewsStatusEnum;
use App\Http\Requests\Back\NewsTag\StoreNewsTagRequest;
use App\Http\Requests\Back\NewsTag\UpdateNewsTagRequest;
use App\Models\NewsTag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
class NewsTagController extends Controller
{
/** @var string $modelName */
private $modelName = "news-tags";
/**
* Create the controller instance.
*/
public function __construct()
{
$this->authorizeResource(NewsTag::class);
}
/**
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Inertia\Response
*/
public function index(Request $request): \Inertia\Response
{
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $query */
$query = NewsTag::query()->withCount('news');
if ($request->routeIs("back.$this->modelName.trash")) {
$query = $query->onlyTrashed();
}
/** @var string $search Search field */
$search = $request->search;
if ($search) {
$this->searchQuery(
$query,
$search,
null,
'name',
);
}
$searchFields = \implode(', ', [
trans('validation.attributes.name'),
]);
/** Sort columns with a query */
$this->sortQuery($query);
/** Custom pagination */
$newsTagModels = $this->paginate($query);
return Inertia::render('NewsTag/Index', [
'newsTagModels' => CommonResource::collection($newsTagModels),
'search' => $search,
'searchFields' => $searchFields,
'modelName' => $this->modelName,
]);
}
/**
* Show the form for creating a new resource.
*
* @param \App\Models\News $news_tag
* @return \Inertia\Response
*/
public function create(NewsTag $news_tag): \Inertia\Response
{
return Inertia::render('NewsTag/Create', [
'data' => CommonResource::make($news_tag),
'modelName' => $this->modelName,
]);
}
/**
* Show a specific resource.
*
* @param \App\Models\NewsTag $news_tag
* @return \Inertia\Response
*/
public function show(NewsTag $news_tag): \Inertia\Response
{
$news = $news_tag->news()->paginate(12);
return Inertia::render('NewsTag/Show', [
'data' => CommonResource::make($news_tag),
'news' => CommonResource::collection($news),
'enumNewsStatus' => NewsStatusEnum::toArray(),
'modelName' => $this->modelName,
]);
}
/**
* Store a newly created resource.
*
* @param \App\Http\Requests\Back\NewsTag\StoreNewsTagRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(StoreNewsTagRequest $request): \Illuminate\Http\RedirectResponse
{
return DB::transaction(function () use ($request) {
$newsModel = new NewsTag();
$newsModel->fill($request->validated());
if ($newsModel->saveOrFail()) {
return redirect()->route("back.$this->modelName.edit", $newsModel);
}
return redirect()->route("back.$this->modelName.create");
});
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\NewsTag $news_tag
* @return \Inertia\Response
*/
public function edit(NewsTag $news_tag): \Inertia\Response
{
return Inertia::render('NewsTag/Edit', [
'data' => CommonResource::make($news_tag),
'modelName' => $this->modelName,
]);
}
/**
* Update the specified resource.
*
* @param \App\Http\Requests\Back\News\UpdateNewsTagRequest $request
* @param \App\Models\NewsTag $news_tag
* @return \Illuminate\Http\RedirectResponse
*/
public function update(UpdateNewsTagRequest $request, NewsTag $news_tag): \Illuminate\Http\RedirectResponse
{
return DB::transaction(function () use ($request, $news_tag) {
$news_tag->fill($request->validated());
if ($news_tag->saveOrFail()) {
return redirect()->route("back.$this->modelName.edit", $news_tag);
}
return redirect()->route("back.$this->modelName.edit", $news_tag);
});
}
/**
* Restore the specified resource.
*
* @param integer $news_tag
* @return \Illuminate\Http\RedirectResponse
*/
public function restore(int $news_tag): \Illuminate\Http\RedirectResponse
{
$news_tag = NewsTag::withTrashed()->findOrFail($news_tag);
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($news_tag->restore()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries);
}
return redirect()->back();
}
/**
* Destroy the specified resource.
*
* @param \App\Models\NewsTag $news_tag
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(NewsTag $news_tag): \Illuminate\Http\RedirectResponse
{
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($news_tag->delete()) {
return redirect()->route("back.$this->modelName.index", $previousQueries);
}
return redirect()->back();
}
/**
* Destroy the specified resource.
*
* @param \App\Models\NewsTag|integer $news_tag
* @return \Illuminate\Http\RedirectResponse
*/
public function forceDestroy(NewsTag|int $news_tag): \Illuminate\Http\RedirectResponse
{
if (is_int($news_tag)) {
$news_tag = NewsTag::withTrashed()->findOrFail($news_tag);
}
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($news_tag->forceDelete()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries);
}
return redirect()->back();
}
}

View file

@ -15,6 +15,7 @@ use App\Models\DocumentTag;
use App\Models\DynamicPage;
use App\Models\News;
use App\Models\NewsCategory;
use App\Models\NewsTag;
use App\Models\PageConfig;
use Diglactic\Breadcrumbs\Breadcrumbs;
use Illuminate\Http\Request;
@ -95,6 +96,11 @@ class HandleInertiaRequests extends Middleware
'viewTrash' => Gate::allows('viewTrash', NewsCategory::class),
'create' => Gate::allows('create', NewsCategory::class),
],
"newsTags" => [
'viewAny' => Gate::allows('viewAny', NewsTag::class),
'viewTrash' => Gate::allows('viewTrash', NewsTag::class),
'create' => Gate::allows('create', NewsTag::class),
],
'companies' => [
'viewAny' => Gate::allows('viewAny', Company::class),
'viewTrash' => Gate::allows('viewTrash', Company::class),

View file

@ -71,7 +71,9 @@ class StoreNewsRequest extends FormRequest
'content' => ['required', 'string', new WysiwygLength(10, 5000)],
'status' => ['required', new Enum(NewsStatusEnum::class)],
'categories' => 'nullable|array',
'categories.*' => 'integer|exists:news,id',
'categories.*' => 'integer|exists:news_categories,id',
'tags' => 'nullable|array',
'tags.*' => 'integer|exists:news_tags,id',
'published_at' => 'nullable|date',
'unpublished_at' => 'nullable|date|after:published_at',
'inverted' => 'boolean',

View file

@ -0,0 +1,45 @@
<?php
namespace App\Http\Requests\Back\NewsTag;
use App\Models\NewsTag;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
class StoreNewsTagRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return Gate::check('create', NewsTag::class);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'slug' => 'required|string|between:3,255',
'name' => 'required|string|between:3,255',
'color' => 'required|string|hex_color',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array
*/
public function attributes(): array
{
return [
'name' => trans('validation.custom.name'),
'color' => trans('validation.custom.color'),
];
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Http\Requests\Back\NewsTag;
use Illuminate\Support\Facades\Gate;
class UpdateNewsTagRequest extends StoreNewsTagRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return Gate::check('update', $this->route('news_tag'));
}
}

View file

@ -50,7 +50,7 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
public function getRouteKeyName(): string
{
return 'slug';
return request()->routeIs('back.*') ? 'id' : 'slug';
}
public function getLocalizedRouteKey($locale)
@ -168,7 +168,7 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
public function inertiaFill(array $attributes)
{
$attributes = Arr::except($attributes, ['categories']);
$attributes = Arr::except($attributes, ['categories', 'tags']);
$this->traitInertiaFill($attributes);
}
@ -256,12 +256,12 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
*
* @return string|null
*/
public function getCategoryLabelsAttribute(): ?string
public function getTagLabelsAttribute(): ?string
{
if (empty($this->categories)) {
if (empty($this->tags)) {
return null;
}
$labels = collect($this->categories)
$labels = collect($this->tags)
->map(fn($cat) => $cat->name ?? null)
->filter()
->values();
@ -271,14 +271,14 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
/**
* Get data related to the first category of this news item.
*
* @return NewsCategory|null
* @return NewsTag|null
*/
public function getFirstCategoryDataAttribute(): ?NewsCategory
public function getFirstTagDataAttribute(): ?NewsTag
{
if (empty($this->categories) || empty($this->categories[0])) {
if (empty($this->tags) || empty($this->tags[0])) {
return null;
}
return $this->categories[0];
return $this->tags[0];
}
/**
@ -305,21 +305,37 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
*/
public function categories(): BelongsToMany
{
return $this->belongsToMany(
return $this->morphedByMany(
NewsCategory::class,
'news_category_pivot',
'newsable',
'newsables',
'news_id',
'category_id'
'newsable_id'
);
}
/**
* The relation with NewsTag.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags(): BelongsToMany
{
return $this->morphedByMany(
NewsTag::class,
'newsable',
'newsables',
'news_id',
'newsable_id'
)->withTimestamps();
}
public static function getPublishedNewsInCurrentLocale()
{
$locale = App::getLocale();
// ici mettre le cache avec la relation catégorie
return News::query()
->with('categories')
->with('categories', 'tags')
->whereNotNull("slug->$locale");
}
}

View file

@ -16,7 +16,6 @@ use Uwil\LaravelActivityLogs\Traits\ActivityLog;
/**
* @property int $news_id News focused.
* @property string $name Name of the category.
* @property string $color Color of the category
* @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.
*/
@ -88,11 +87,12 @@ class NewsCategory extends Model implements TranslatableModel
*/
public function news(): BelongsToMany
{
return $this->belongsToMany(
return $this->morphToMany(
News::class,
'news_category_pivot',
'category_id',
'news_id'
'newsable',
'newsables',
'news_id',
'newsable_id'
);
}
}

66
app/Models/NewsTag.php Normal file
View file

@ -0,0 +1,66 @@
<?php
namespace App\Models;
use App\Contracts\TranslatableModel;
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;
/**
* @property int $news_id News focused.
* @property string $name Name of the tag.
* @property string $color Color of the tag
* @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.
*/
class NewsTag extends Model implements TranslatableModel
{
use ActivityLog;
use HasFactory;
use HasCache;
use SoftDeletes;
use HasTranslations;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'slug',
'color'
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'name',
'slug'
];
/**
* Relation to Document
*
* @return BelongsToMany
*/
public function news(): BelongsToMany
{
return $this->morphToMany(
News::class,
'newsable',
'newsables',
'newsable_id',
'news_id'
);
}
}

View file

@ -0,0 +1,112 @@
<?php
namespace App\Policies;
use Illuminate\Database\Eloquent\Model;
use Uwil\LaravelBackend\Enums\RoleEnum;
use Uwil\LaravelBackend\Policies\Rules\UserStaticRules;
class NewsTagPolicy
{
/**
* Determine whether the user can view any models.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function viewAny(Model $authModel): bool
{
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.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function view(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can create models.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function create(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can update the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function update(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can duplicate the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function duplicate(Model $authModel): bool
{
// TODO: duplicate wysiwyg path image.
return false;
}
/**
* Determine whether the user can restore the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function restore(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* 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
* @param \App\Models\News $news
* @return boolean
*/
public function forceDelete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
}

View file

@ -19,7 +19,6 @@ class NewsCategoryFactory extends Factory
return [
"name" => $this->faker->unique()->word(),
"slug" => $this->faker->unique()->word(),
"color" => "#fff"
];
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\NewsTag>
*/
class NewsTagFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
"name" => $this->faker->unique()->word(),
"slug" => $this->faker->unique()->word(),
"color" => "#fff"
];
}
}

View file

@ -0,0 +1,65 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('news_tags', function (Blueprint $table) {
$table->id();
$table->string('name')->comment('Name of the news tag.');
$table->string('slug')->comment('Slug of the news tag.');
$table->string('color')->default("#ff4e4e")->comment('Color of the news tag.');
$table->softDeletes();
$table->timestamps();
});
// News has now meta categories, then the old news categories were in fact tags.
// We need to put the old categories into tags
$categories = \DB::table('news_categories')->get();
foreach ($categories as $category) {
\DB::table('news_tags')->insert([
'name' => $category->name,
'slug' => $category->slug,
'color' => $category->color ?? '#ff4e4e',
'created_at' => now(),
'updated_at' => now(),
]);
}
// then a new table 'newsables' will be used to store pivot between categories and tags
// then all the old news categories pivot will be passed into the newsables + add as tags model
// at this moment we can delete the old categories to pass the good data
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
$categories = \DB::table('news_tags')->get();
foreach ($categories as $category) {
\DB::table('news_categories')->insert([
'name' => $category->name,
'slug' => $category->slug,
'color' => $category->color ?? '#ff4e4e',
'created_at' => now(),
'updated_at' => now(),
]);
}
Schema::dropIfExists('news_tags');
}
};

View file

@ -0,0 +1,107 @@
<?php
use App\Models\NewsCategory;
use App\Models\NewsTag;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('newsables', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('news_id');
$table->unsignedBigInteger('newsable_id');
$table->string('newsable_type');
$table->foreign('news_id')
->references('id')->on('news')
->onDelete('cascade');
$table->timestamps();
$table->index(['newsable_id', 'newsable_type']);
});
// all the pivot between old categories and news should be store as tags now
$oldCategoriesPivot = \DB::table('news_category_pivot')->get();
foreach ($oldCategoriesPivot as $catPivot) {
\DB::table('newsables')->insert([
'news_id' => $catPivot->news_id,
'newsable_id' => $catPivot->category_id,
'newsable_type' => NewsTag::class,
'created_at' => now(),
'updated_at' => now(),
]);
}
DB::table('news_categories')->delete();
// supprimer le champs color
Schema::table('news_categories', function (Blueprint $table) {
$table->dropColumn('color');
});
$newTrueCategories = [
[
"fr" => "Actualités",
"en" => "News",
],
[
"fr" => "Espace press",
"en" => "Press space"
],
];
$categoryMap = [];
foreach ($newTrueCategories as $index => $cats) {
app()->setLocale('fr');
$catModel = NewsCategory::create([
'name' => $cats['fr'],
'slug' => Str::slug($cats['fr']),
]);
$categoryMap[$index + 1] = $catModel->id;
foreach ($cats as $locale => $cat) {
if ($locale === 'fr') continue;
if( $locale === "color") continue;
app()->setLocale($locale);
$catModel->update([
'name' => $cat,
'slug' => Str::slug($cat),
]);
}
}
Schema::drop('news_category_pivot');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('newsables');
Schema::table('news_categories', function (Blueprint $table) {
$table->string('color')
->default('#ff4e4e')
->comment('Color of the news category.');
});
}
};

View file

@ -0,0 +1,17 @@
<?php
namespace Database\Seeders;
use App\Models\NewsTag;
use Illuminate\Database\Seeder;
class NewsTagSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
NewsTag::factory(10)->create();
}
}

View file

@ -247,6 +247,9 @@ return [
"news" => [
"categories" => [
"placeholder" => "select your article's categories"
],
"tags" => [
"placeholder" => "select your article's tags"
]
],
];

View file

@ -16,5 +16,6 @@ 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",
],
];

View file

@ -281,5 +281,8 @@ return [
"newsCategory" => [
"news" => "associated news"
],
"news" => [
"tag" => "etiquette|etiquettes",
]
],
];

View file

@ -248,6 +248,9 @@ return [
"news" => [
"categories" => [
"placeholder" => "sélectionnez les catégories de votre article",
],
"tags" => [
"placeholder" => "sélectionnez les étiquettes de votre article",
]
],
];

View file

@ -16,5 +16,6 @@ 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é",
],
];

View file

@ -278,6 +278,9 @@ return [
],
"newsCategory" => [
"news" => "actualité(s) associée(s)"
],
"news" => [
"tag" => "étiquette|étiquettes",
]
],
];

View file

@ -164,6 +164,15 @@ export default function AppSidebar() {
.value()}
/>
),
authPolicies.newsTags.viewAny && (
<CustomDropdownMenuItem
route={route(`back.news-tags.index`)}
icon={FolderIcon}
trans={str(useTrans("models.classes.news-tag", { choice: 2 }))
.ucFirst()
.value()}
/>
),
]
})
},

View file

@ -22,7 +22,7 @@ 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 } 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";
@ -47,13 +47,14 @@ export default function Form({
const [isGif, setIsGif] = useState<boolean>(false);
const [dynamicKey, setDynamicKey] = useState<number | null>(null);
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, defaultValue } = mapLaravelEnumOptions(enumNewsCategory, model?.categories, "category");
const { options, defaultValue } = 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);
console.log({defaultValueCategories, defaultValueTags, model})
function isFile(value: unknown): value is File {
return value instanceof File;
}
@ -73,7 +74,8 @@ export default function Form({
picture: model?.picture,
picture_alt: model?.picture_alt ? model?.picture_alt[locale] : "",
picture_title: model?.picture_title ? model?.picture_title[locale] : "",
categories: model?.categories ? defaultValue : [],
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
});
@ -375,27 +377,50 @@ export default function Form({
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}
/>
<div className="grid sm:grid-cols-2 gap-4 col-span-2 gap-4">
<MultiSelect
label={str(
useTrans("back.form_associate_to_plural", {
params: {
attribute: useTrans("validation.custom.news.tag", { choice: 2 }),
},
choice: 2
}),
).ucFirst().value()}
multiple={true}
name="tags"
required={false}
variant="inverted"
placeholder={str(
useTrans("back.news.tags.placeholder")
).ucFirst().value()}
singleLine={true}
setData={setData}
defaultValue={data.tags}
options={optionTags}
/>
<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={optionCategories}
/>
</div>
</FieldsetWrapper>
<FieldsetWrapper
title={useTrans("back.form_title_additional_files")}

View file

@ -102,6 +102,21 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN
);
}
},
{
accessorKey: "tags",
header: str(useTrans("validation.custom.news.tag", { choice: 2 })).ucFirst().value(),
cell: ({ value }: { value?: NewsCategoryModel[] }) => {
if (!value || value.length === 0) return null;
return (
<div className="flex flex-wrap gap-1">
{value.map((item, i) => (
<NewsCategoriesBadge value={item.name} key={i} />
))}
</div>
);
}
},
{
accessorKey: "created_at",

View file

@ -11,7 +11,6 @@ import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import { useCrudSubmit } from "@/hooks/use-crud-submit";
import SubmitButton from "@/back/Components/SubmitButton";
import SimpleColorPicker from "@/back/Components/Inputs/SimpleColorPicker";
import Slugifycator from "@/back/Components/Inputs/Slugifycator";
export default function Form({
@ -34,7 +33,6 @@ export default function Form({
_method: method === Methods.POST ? 'post' : 'put',
name: model?.name ? model?.name[locale] : "",
slug: model?.slug ? model?.slug[locale] : "",
color: model?.color ? model?.color : ""
});
const submit = useCrudSubmit({
@ -75,20 +73,6 @@ export default function Form({
targetValue={data.name}
setData={setData}
/>
<SimpleColorPicker
name="color"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.color"),
},
choice: 1,
}),
).ucFirst().value()}
setData={setData}
value={data.color}
required={true}
/>
</div>
</FieldsetWrapper>
<div className="text-center">

View file

@ -5,7 +5,6 @@ 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 { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
// * Other
import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
@ -17,11 +16,9 @@ import InputError from "@/back/Components/InputError";
import { Views } from "@/lib/utils";
import { useFormatedDate } from "@/hooks/use-formated-value";
import {
AppEnv,
AuthProp,
NewsCategoryModel,
Resource,
TranslationField,
} from "@/back/types/global";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
@ -38,9 +35,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.newsCategories;
const isArchiveRoute = route().current(`back.${modelName}.trash`);
@ -68,27 +64,6 @@ export default function Index({
)
},
},
{
accessorKey: "color",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.custom.${column.id}`)).ucFirst().value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<NewsCategoryModel> }) => {
return (
<Tooltip>
<TooltipTrigger asChild>
<div className="w-8 h-8 rounded-md mx-auto border" style={{
backgroundColor: row.getValue("color"),
}}></div>
</TooltipTrigger>
<TooltipContent>{row.getValue("color")}</TooltipContent>
</Tooltip>
)
},
},
{
accessorKey: "news",
header: () => (

View file

@ -21,7 +21,6 @@ import str from "@/hooks/use-string";
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 { renderTranslationCell } from "@/lib/translationCellFallback";
@ -58,22 +57,6 @@ export default function Show({ data, modelName, news }: { data: SingleResource,
? value[appEnv.locale]
: (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>),
},
{
accessorKey: "color",
header: str(useTrans("validation.custom.color")).ucFirst().value(),
cell: ({ value }: { value: string }) => {
return (
<Tooltip>
<TooltipTrigger asChild>
<div className="w-8 h-8 rounded-md border" style={{
backgroundColor: value,
}}></div>
</TooltipTrigger>
<TooltipContent>{value}</TooltipContent>
</Tooltip>
)
}
},
{
accessorKey: "created_at",
header: str(useTrans("validation.attributes.created_at")).ucFirst().value(),

View file

@ -0,0 +1,58 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
import { ArrowLeft } from "lucide-react";
// * Other
import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import useTrans from "@/hooks/use-translations";
import { Actions, Methods } from "@/lib/enums";
import {
AuthProp,
NewsTagModel,
SingleResource,
} from "@/back/types/global";
import Form from "./Form";
import str from "@/hooks/use-string";
export default function Create({ data, modelName }: { data: SingleResource, modelName: string }) {
const { viewAny } = (usePage().props.auth as AuthProp).policies.newsTags;
const newsTagModel = data.data as NewsTagModel;
const singularModelName = str(modelName).singular().value();
const transTitle = useTrans("crud.helpers.creation_model",
{
params: {
model: useTrans(`models.classes.${singularModelName}`, {
choice: 1,
}),
},
},
);
const beforeNode = () => {
return viewAny && (
<div className="flex justify-end items-center gap-x-1.5">
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.index`)}
content={<ArrowLeft />}
tooltipContent={<p>{useTrans("back.crud_back_to_list")}</p>}
/>
</div>
);
};
return (
<AuthenticatedLayout
title={transTitle}
beforeNode={beforeNode()}
>
<Form
model={newsTagModel}
modelName={singularModelName}
modelRoute={modelName}
action={Actions.STORE}
method={Methods.POST}
/>
</AuthenticatedLayout>
);
}

View file

@ -0,0 +1,61 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
// * Other
import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
import ModelActions from "@/back/Components/ModelActions";
import useTrans from "@/hooks/use-translations";
import { Actions, Methods } from "@/lib/enums";
import Form from "./Form";
import { Views } from "@/lib/utils";
import { AuthProp, NewsTagModel, 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.newsTags;
const newsTagModel = data.data as NewsTagModel;
const actionModels = [
Views.VISUALIZATION,
Views.DUPLICATION,
Views.ARCHIVATION,
];
const singularModelName = str(modelName).singular().value();
const transTitle = useTrans("crud.helpers.edition_model", {
params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) },
});
const beforeNode = () => {
return viewAny && (
<div className="flex justify-end items-center gap-x-1.5">
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.index`)}
content={<ArrowLeft />}
tooltipContent={<p>{useTrans("back.crud_back_to_list")}</p>}
/>
</div>
);
};
return (
<AuthenticatedLayout
title={transTitle}
beforeNode={beforeNode()}
>
<ModelActions
actions={actionModels}
modelRoute={modelName}
model={newsTagModel}
modelUpdatedAt={newsTagModel.updated_at.toString()}
/>
<Form
model={newsTagModel}
modelName={singularModelName}
modelRoute={modelName}
action={Actions.UPDATE}
method={Methods.PATCH}
/>
</AuthenticatedLayout>
);
}

View file

@ -0,0 +1,103 @@
// * Packages
import { useForm, usePage } from "@inertiajs/react";
import { BookTextIcon } from "lucide-react";
// * Other
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, NewsTagModel } from "@/back/types/global";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import { useCrudSubmit } from "@/hooks/use-crud-submit";
import SubmitButton from "@/back/Components/SubmitButton";
import SimpleColorPicker from "@/back/Components/Inputs/SimpleColorPicker";
import Slugifycator from "@/back/Components/Inputs/Slugifycator";
export default function Form({
model,
modelName,
modelRoute,
action,
method,
}: {
model?: NewsTagModel;
modelName: string;
modelRoute: string;
action: string;
method: number;
}) {
const { locale } = usePage().props.appEnv as AppEnv;
/** Form section */
const { post, setData, data } = useForm({
_method: method === Methods.POST ? 'post' : 'put',
name: model?.name ? model?.name[locale] : "",
slug: model?.slug ? model?.slug[locale] : "",
color: model?.color ? model?.color : ""
});
const submit = useCrudSubmit({
method,
modelRoute,
modelName,
action,
model,
post
});
return (
<form onSubmit={submit}>
<InputError all />
<FieldsetWrapper
title={useTrans("back.form_title_global")}
icon={<BookTextIcon className="mr-1" />}
description={useTrans("back.form_subtitle_global")}
>
<div className="grid grid-cols-2 gap-2">
<SimpleString
name="name"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.attributes.name"),
},
choice: 1
}),
).ucFirst().value()}
required={true}
placeholder="ex: John Doe"
value={data.name ?? ""}
setData={setData}
/>
<Slugifycator
value={data.slug}
targetValue={data.name}
setData={setData}
/>
<SimpleColorPicker
name="color"
label={str(
useTrans("back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.color"),
},
choice: 1,
}),
).ucFirst().value()}
setData={setData}
value={data.color}
required={true}
/>
</div>
</FieldsetWrapper>
<div className="text-center">
<SubmitButton modelTrans={
useTrans(`models.classes.${modelName}`, {
choice: 1,
})
} />
</div>
</form>
);
}

View file

@ -0,0 +1,182 @@
// * Packages
import { route } from "ziggy-js";
import { usePage } from "@inertiajs/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 { 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 BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
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 str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { renderTranslationCell } from "@/lib/translationCellFallback";
export default function Index({
newsTagModels,
search,
searchFields,
modelName
}: {
newsTagModels: Resource;
search: string;
searchFields: string;
modelName: string;
}) {
const { auth } = usePage().props as unknown as {
auth: AuthProp;
};
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 columns = [
{
accessorKey: "name",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`)).ucFirst().value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<NewsTagModel> }) => {
return renderTranslationCell(
row.getValue("name")
)
},
},
{
accessorKey: "color",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.custom.${column.id}`)).ucFirst().value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<NewsTagModel> }) => {
return (
<Tooltip>
<TooltipTrigger asChild>
<div className="w-8 h-8 rounded-md mx-auto border" style={{
backgroundColor: row.getValue("color"),
}}></div>
</TooltipTrigger>
<TooltipContent>{row.getValue("color")}</TooltipContent>
</Tooltip>
)
},
},
{
accessorKey: "news",
header: () => (
<p className="w-full text-center">{str(useTrans(`validation.custom.documentTag.documents`)).ucFirst().value()}</p>
),
cell: ({ row }: { row: Row<NewsTagModel> }) => (
<div className="w-full flex justify-center">
<p>{row.original.news_count ?? 0}</p>
</div>
),
},
{
accessorKey: "updated_at",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`)).ucFirst().value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<NewsTagModel> }) => (
<Badge variant="secondary">
{useFormatedDate(row.getValue("updated_at"))}
</Badge>
),
},
];
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 && (
<div className="flex justify-end items-center gap-x-1.5">
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.index`)}
content={<ArrowLeftIcon />}
tooltipContent={<p>{useTrans("back.crud_back_to_list")}</p>}
/>
</div>
);
};
const afterNode = () => {
return !isArchiveRoute && (
<div className="flex justify-end items-center gap-x-1.5">
{viewTrash && <BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.trash`)}
content={<ArchiveIcon />}
tooltipContent={<p>{useTrans("back.crud_access_trash")}</p>}
variant="outline"
/>}
{create && <BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.create`)}
content={<Plus />}
tooltipContent={<p>{useTrans("back.crud_add_entry")}</p>}
/>}
</div>
);
};
return (
<AuthenticatedLayout
title={transTitle}
beforeNode={beforeNode()}
afterNode={afterNode()}
>
{isArchiveRoute && (
<>
<Alert
variant="destructive"
className="text-left mb-4"
>
<AlertCircleIcon className="h-4 w-4" />
<AlertTitle>{useTrans('back.warning')}</AlertTitle>
<AlertDescription>
<p>{useTrans('back.warning_trash')}</p>
</AlertDescription>
</Alert>
<InputError all={true} />
</>
)}
<DataTableSearch
modelRoute={modelName}
searchText={search}
searchFields={searchFields}
/>
<DataTable
columns={columns}
modelRoute={modelName}
modelsPaginate={newsTagModels}
actions={actionModels}
/>
</AuthenticatedLayout>
);
}

View file

@ -0,0 +1,123 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
// * Components shadcn
import { Badge } from "@/components/ui/badge";
// * Other
import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
import DetailsTable from "@/back/Components/Table/DetailsTable";
import ModelActions from "@/back/Components/ModelActions";
import { Views } from "@/lib/utils";
import { useFormatedDate } from "@/hooks/use-formated-value";
import {
AppEnv,
AuthProp,
NewsTagModel,
Resource,
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 { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import AssociatedNewsList from "@/back/Components/AssociatedNewsList";
import { renderTranslationCell } from "@/lib/translationCellFallback";
export default function Show({ data, modelName, news }: { data: SingleResource, modelName: string, news: Resource }) {
const { auth, appEnv } = usePage().props as unknown as {
auth: AuthProp;
appEnv: AppEnv;
};
const { viewAny } = auth.policies.newsTags;
const model = data.data as NewsTagModel;
const actionModels = [
Views.EDITION,
Views.DELETION,
];
const singularModelName = str(modelName).singular().value();
const transTitle = useTrans("crud.helpers.visualization_model", {
params: { model: useTrans(`models.classes.${singularModelName}`, { choice: 1 }) },
});
const columns = [
{
accessorKey: "name",
header: str(useTrans("validation.attributes.name")).ucFirst().value(),
cell: ({ value }: { value: TranslationField }) => {
return renderTranslationCell(
value
)
}
},
{
accessorKey: "slug",
header: str(useTrans("validation.custom.slug")).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: "color",
header: str(useTrans("validation.custom.color")).ucFirst().value(),
cell: ({ value }: { value: string }) => {
return (
<Tooltip>
<TooltipTrigger asChild>
<div className="w-8 h-8 rounded-md border" style={{
backgroundColor: value,
}}></div>
</TooltipTrigger>
<TooltipContent>{value}</TooltipContent>
</Tooltip>
)
}
},
{
accessorKey: "created_at",
header: str(useTrans("validation.attributes.created_at")).ucFirst().value(),
cell: ({ value }: { value: string }) => {
return (
<Badge variant="secondary">{useFormatedDate(value)}</Badge>
)
},
},
{
accessorKey: "updated_at",
header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(),
cell: ({ value }: { value: string }) => (
<Badge variant="secondary">{useFormatedDate(value)}</Badge>
),
},
];
const beforeNode = () => {
return viewAny && (
<div className="flex justify-end items-center gap-x-1.5">
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.index`)}
content={<ArrowLeft />}
tooltipContent={<p>{useTrans("back.crud_back_to_list")}</p>}
/>
</div>
);
};
return (
<AuthenticatedLayout
title={transTitle}
beforeNode={beforeNode()}
>
<ModelActions
actions={actionModels}
modelRoute={modelName}
model={model}
modelUpdatedAt={model.updated_at.toString()}
/>
{/* @ts-expect-error Weird error type on cell. */}
<DetailsTable columns={columns} model={model} />
<AssociatedNewsList news={news} />
</AuthenticatedLayout>
);
}

View file

@ -127,9 +127,21 @@ type NewsModel = {
updated_at: Date;
deleted_at: Date;
categories: NewsCategoryModel[];
tags: NewsTagModel[];
};
type NewsCategoryModel = {
policies: ModelPolicy;
id: number;
name: TranslationField;
slug: TranslationField;
news_count: number;
created_at: Date;
updated_at: Date;
deleted_at: Date;
}
type NewsTagModel = {
policies: ModelPolicy;
id: number;
name: TranslationField;
@ -152,7 +164,7 @@ type CompanyModel = {
latitude: number;
longitude: number;
activity_id: number;
sector_id: number|null;
sector_id: number | null;
published: boolean;
created_at: Date;
updated_at: Date;
@ -231,7 +243,8 @@ type Model =
| CompanySectorModel
| DocumentTagModel
| ActivityLogModel
| NewsCategoryModel;
| NewsCategoryModel
| NewsTagModel;
// Common policy type.
type CommonPolicy = {

View file

@ -13,15 +13,15 @@
<x-front.borders :borders="!empty($borders) ? $borders : []" />
</div>
<div class="list-item__description description">
@if (isset($news->category_labels))
@if (isset($news->tag_labels))
<div class="list-item__tags tags">
<div class="single-news__tag tag {{ $news->first_category_data['category_classes'] ?? '' }}">
{{ $news->category_labels }}
<div class="single-news__tag tag {{ $news->first_tag_data['category_classes'] ?? '' }}">
{{ $news->tag_labels }}
</div>
</div>
@endif
<div class="list-item__title posts-list__item-title subtitle">{{ $news['title'] }}</div>
<div class="list-item__date date {{ $news->first_category_data['date_classes'] ?? 'date_no-tags' }}">
<div class="list-item__date date {{ $news->first_tag_data['date_classes'] ?? 'date_no-tags' }}">
{{ $news->publishedAtFormatted() }}
</div>
<div class="list-item__text ellipsis description"></div>

View file

@ -8,17 +8,17 @@
<div class="textblock fw fw-container">
@include('front.breadcrumbs.breadcrumb-body')
<div class="textblock__wrapper wrapper">
@if (isset($model['category_labels']))
@if (isset($model['tag_labels']))
<div class="single-news__tags tags">
<div class="single-news__tag tag" data-color="{{ $model->first_category_data['color'] ?? '' }}"
<div class="single-news__tag tag" data-color="{{ $model->first_tag_data['color'] ?? '' }}"
data-color-target="border">
{{ $model['category_labels'] }}</div>
{{ $model['tag_labels'] }}</div>
</div>
@endif
<h1 class="single-news__title subtitle">
{{ $model['title'] }}
</h1>
<div class="single-news__date date" data-color="{{ $model->first_category_data['color'] ?? '' }}"
<div class="single-news__date date" data-color="{{ $model->first_tag_data['color'] ?? '' }}"
data-color-target="background">
{{ $model->publishedAtFormatted() }}
</div>

View file

@ -12,6 +12,7 @@ use App\Http\Controllers\Back\DynamicPageController;
use App\Http\Controllers\Back\InputsController;
use App\Http\Controllers\Back\NewsCategoryController;
use App\Http\Controllers\Back\NewsController;
use App\Http\Controllers\Back\NewsTagController;
use App\Http\Controllers\Back\PageConfigController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
@ -84,6 +85,7 @@ Route::prefix('admin')
Route::delete('/news/{news}/force', [NewsController::class, 'forceDestroy'])
->name('news.forceDestroy');
Route::resource('news', NewsController::class);
Route::get('/news/{news}/duplicate', [NewsController::class, 'duplicate'])
->name('news.duplicate');
@ -98,6 +100,17 @@ Route::prefix('admin')
Route::get('/news-categories/{news_category}/duplicate', [NewsCategoryController::class, 'duplicate'])
->name('news-categories.duplicate');
// * NEWS TAGS.
Route::get('/news-tags/trash', [NewsTagController::class, 'index'])
->name('news-tags.trash');
Route::patch('/news-tags/{news_tag}/restore', [NewsTagController::class, 'restore'])
->name('news-tags.restore');
Route::delete('/news-tags/{news_tag}/force', [NewsTagController::class, 'forceDestroy'])
->name('news-tags.forceDestroy');
Route::resource('news-tags', NewsTagController::class);
Route::get('/news-tags/{news_tag}/duplicate', [NewsTagController::class, 'duplicate'])
->name('news-tags.duplicate');
// * COMPANIES.
Route::get('/companies/trash', [CompanyController::class, 'index'])
->name('companies.trash');