feat: ✨ add brands crud #122

This commit is contained in:
Alexis Gousseau 2026-05-19 16:44:38 +02:00
parent 89dd5e1db7
commit 106508419e
No known key found for this signature in database
GPG key ID: 7F3C786EE12DBB72
20 changed files with 1323 additions and 1 deletions

View file

@ -0,0 +1,261 @@
<?php
namespace App\Http\Controllers\Back;
use App\Http\Requests\Back\Brands\StoreBrandRequest;
use App\Http\Requests\Back\Brands\UpdateBrandRequest;
use App\Models\Brand;
use App\Models\Site;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Uwil\LaravelBackend\Controllers\BackendController;
use Uwil\LaravelBackend\Resources\CommonResource;
/**
* Handles CRUD operations for Brand in the backend.
*/
class BrandController extends BackendController
{
/**
* Gitlab projects collection.
*
* @var \Illuminate\Support\Collection<int,\App\Models\Site>
*/
private \Illuminate\Support\Collection $siteModels;
/**
* Create the controller instance.
*/
public function __construct()
{
$this->authorizeResource(Brand::class);
$this->modelName = Brand::modelName();
$this->modelPage = Brand::modelPage();
$this->siteModels = Site::getModelsCached();
}
/**
* 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\Brand> $query */
$query = Brand::query();
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 */
$models = $this->paginate($query);
return $this->inertiaRender("back/Pages/$this->modelPage/Index", [
'models' => CommonResource::collection($models),
'search' => $search,
'searchFields' => $searchFields,
]);
}
/**
* Show the form for creating a new resource.
*
* @param \App\Models\Brand $brand
* @return \Inertia\Response
*/
public function create(Brand $brand): \Inertia\Response
{
return $this->inertiaRender("back/Pages/$this->modelPage/Create", [
'data' => CommonResource::make($brand),
'siteModels' => $this->siteModels,
]);
}
/**
* Show a specific resource.
*
* @param \App\Models\Brand $brand
* @return \Inertia\Response
*/
public function show(Brand $brand): \Inertia\Response
{
return $this->inertiaRender("back/Pages/$this->modelPage/Show", [
'data' => CommonResource::make($brand->load(['sites'])),
]);
}
/**
* Store a newly created resource.
*
* @param \App\Http\Requests\Back\Brands\StoreBrandRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(StoreBrandRequest $request): \Illuminate\Http\RedirectResponse
{
return DB::transaction(function () use ($request) {
$validatedData = $request->validated();
$brand = new Brand();
$brand->fill(Arr::except($validatedData, 'sites'));
if ($brand->saveOrFail()) {
$brand->sites()->syncWithoutDetaching(Arr::get($validatedData, 'sites'));
return redirect()->route("back.$this->modelName.edit", $brand)
->with('success', trans('uwil-backend::crud.messages.has_been_created', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
return redirect()->back()
->with('error', trans('uwil-backend::crud.messages.cannot_be_created', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
});
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Brand $brand
* @return \Inertia\Response
*/
public function edit(Brand $brand): \Inertia\Response
{
return $this->inertiaRender("back/Pages/$this->modelPage/Edit", [
'data' => CommonResource::make($brand->load(['sites'])),
'siteModels' => $this->siteModels,
]);
}
/**
* Update the specified resource.
*
* @param \App\Http\Requests\Back\Brands\UpdateBrandRequest $request
* @param \App\Models\Brand $brand
* @return \Illuminate\Http\RedirectResponse
*/
public function update(
UpdateBrandRequest $request,
Brand $brand,
): \Illuminate\Http\RedirectResponse {
return DB::transaction(function () use ($request, $brand) {
$validatedData = $request->validated();
$brand->fill(Arr::except($validatedData, 'sites'));
if ($brand->saveOrFail()) {
$brand->sites()->sync(Arr::get($validatedData, 'sites'));
return redirect()->route("back.$this->modelName.edit", $brand)
->with('success', trans('uwil-backend::crud.messages.has_been_updated', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
return redirect()->route("back.$this->modelName.edit", $brand)
->with('error', trans('uwil-backend::crud.messages.cannot_be_updated', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
});
}
/**
* Duplicate the specified resource.
*
* @param \App\Models\Brand $brand
* @return \Inertia\Response
*/
public function duplicate(Brand $brand): \Inertia\Response
{
return $this->create($brand->replicate());
}
/**
* Restore the specified resource.
*
* @param integer $brand
* @return \Illuminate\Http\RedirectResponse
*/
public function restore(int $brand): \Illuminate\Http\RedirectResponse
{
$brand = Brand::withTrashed()->findOrFail($brand);
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($brand->restore()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries)
->with('success', trans('uwil-backend::crud.messages.has_been_restored', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
return redirect()->back()
->with('error', trans('uwil-backend::crud.messages.cannot_be_restored', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
/**
* Destroy the specified resource.
*
* @param \App\Models\Brand $brand
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Brand $brand): \Illuminate\Http\RedirectResponse
{
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($brand->delete()) {
return redirect()->route("back.$this->modelName.index", $previousQueries)
->with('success', trans('uwil-backend::crud.messages.has_been_deleted', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
return redirect()->back()
->with('error', trans('uwil-backend::crud.messages.cannot_be_deleted', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
/**
* Destroy the specified resource.
*
* @param \App\Models\Brand|integer $brand
* @return \Illuminate\Http\RedirectResponse
*/
public function forceDestroy(Brand|int $brand): \Illuminate\Http\RedirectResponse
{
if (is_int($brand)) {
$brand = Brand::withTrashed()->findOrFail($brand);
}
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($brand->forceDelete()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries)
->with('success', trans('uwil-backend::crud.messages.has_been_deleted', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
return redirect()->back()
->with('error', trans('uwil-backend::crud.messages.cannot_be_deleted', [
'model' => Str::ucfirst(trans_choice("models.classes.$this->modelName", 1)),
]));
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace App\Http\Requests\Back\Brands;
use App\Models\Brand;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
/**
* Handles authorization and validation for creating a new Brand.
*/
class StoreBrandRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return Gate::check('create', Brand::class);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'name' => 'required|string|between:3,255|unique:brands,name',
'sites' => 'nullable|array',
'sites.*' => 'integer|exists:sites,id|distinct',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array<string, string>
*/
public function attributes(): array
{
return [
'name' => trans('validation.custom.name'),
'sites' => trans_choice('models.classes.sites', \INF),
];
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace App\Http\Requests\Back\Brands;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
/**
* Handles authorization and validation for updating an existing Brand.
*/
class UpdateBrandRequest extends StoreBrandRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
#[\Override]
public function authorize(): bool
{
return Gate::check('update', $this->route('brand'));
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
#[\Override]
public function rules(): array
{
/** @var \App\Models\Brand $brand */
$brand = $this->route('brand');
return array_merge(parent::rules(), [
'name' => [
'required',
'string',
'between:3,255',
Rule::unique('brands', 'name')->ignore($brand->getRouteKey()),
],
]);
}
}

65
app/Models/Brand.php Normal file
View file

@ -0,0 +1,65 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Uwil\LaravelActivityLogs\Traits\HasActivityLog;
use Uwil\LaravelBackend\Traits\Models\HasCache;
use Uwil\LaravelBackend\Traits\Models\HasModelNaming;
use Uwil\LaravelI18n\Traits\Models\HasTranslations;
/**
* @property integer $id Id of the brand.
* @property string $name Name of the brand.
* @property-read \Illuminate\Support\Carbon $created_at Date the Brand was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date the Brand was updated.
* @property-read \Illuminate\Support\Carbon $deleted_at Date the Brand was deleted.
*/
class Brand extends Model
{
use HasActivityLog;
use HasCache;
/** @use \Illuminate\Database\Eloquent\Factories\HasFactory<\Database\Factories\BrandFactory> */
use HasFactory;
use HasModelNaming;
use HasTranslations;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'name',
];
// * RELATIONS.
/**
* Get sites associated to the brand.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany<\App\Models\Site>
*/
public function sites(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphToMany(
Site::class,
'sitable',
'sitables',
'sitable_id',
'site_id',
)->withPivot('created_at');
}
}

View file

@ -98,7 +98,23 @@ class Site extends Model
'sitable',
'sitables',
'site_id',
'sitable_id'
'sitable_id',
)->withPivot('created_at');
}
/**
* Get brands associated to the site.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany<\App\Models\Brand>
*/
public function brands(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphedByMany(
Brand::class,
'sitable',
'sitables',
'site_id',
'sitable_id',
)->withPivot('created_at');
}

View file

@ -0,0 +1,112 @@
<?php
namespace App\Policies;
use Illuminate\Database\Eloquent\Model;
use Uwil\LaravelBackend\Policies\Rules\UserStaticRules;
use Uwil\LaravelBackend\Support\UserRoleRegistry;
/**
* Handles authorization for Brand model actions.
*/
class BrandPolicy
{
/**
* 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, UserRoleRegistry::get('developper')->value);
}
/**
* 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, UserRoleRegistry::get('developper')->value);
}
/**
* 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, UserRoleRegistry::get('developper')->value);
}
/**
* 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, UserRoleRegistry::get('developper')->value);
}
/**
* 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, UserRoleRegistry::get('developper')->value);
}
/**
* Determine whether the user can duplicate the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function duplicate(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
* 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, UserRoleRegistry::get('developper')->value);
}
/**
* Determine whether the user can soft delete the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function delete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
* Determine whether the user can permanently delete the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function forceDelete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
}

View file

@ -3,6 +3,7 @@
namespace App\Providers;
use App\Enums\NoticeTypeEnum;
use App\Models\Brand;
use App\Models\GitlabProject;
use App\Models\InvoiceCompany;
use App\Models\InvoicePackage;
@ -54,5 +55,10 @@ class AppServiceProvider extends ServiceProvider
'viewTrash' => Gate::allows('viewTrash', Site::class),
'create' => Gate::allows('create', Site::class),
]);
InertiaSharedRegistry::add('auth.policies.brands', fn () => [
'viewAny' => Gate::allows('viewAny', Brand::class),
'viewTrash' => Gate::allows('viewTrash', Brand::class),
'create' => Gate::allows('create', Brand::class),
]);
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace Database\Factories;
use App\Models\Brand;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* Factory for generating Brand model instances with randomized data.
*/
class BrandFactory extends Factory
{
/**
* Associated model.
*
* @var class-string<\App\Models\Brand>
*/
protected $model = Brand::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
"name" => fake()->unique()->words(3, true),
];
}
}

View file

@ -0,0 +1,34 @@
<?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('brands', function (Blueprint $table) {
$table->id()->comment('Id of the brand.');
$table->string('name')->unique()->comment('Name of the brand.');
$table->timestamp('created_at')->nullable()->comment('Date the brand was created.');
$table->timestamp('updated_at')->nullable()->comment('Date the brand was updated.');
$table->timestamp('deleted_at')->nullable()->comment('Date the brand was deleted.');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('brands');
}
};

View file

@ -0,0 +1,25 @@
<?php
namespace Database\Seeders\Classic;
use App\Models\Brand;
use Illuminate\Database\Seeder;
/**
* Seeds the brands table.
*/
class BrandSeeder extends Seeder
{
/** @var string $table Associated table to this seeder. */
public static string $table = 'brands';
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
Brand::factory(10)->create();
}
}

View file

@ -9,5 +9,6 @@ return [
"invoice-companies" => "devis - société|devis - sociétés",
"gitlab-projects" => "gitlab - projet|gitlab - projets",
"sites" => "site|sites",
"brands" => "marque|marques",
],
];

View file

@ -0,0 +1,73 @@
// * Packages
import { InfoIcon } from "lucide-react";
import { route } from "ziggy-js";
import { Link } from "@inertiajs/react";
// * Components shadcn
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
// * Other
import {
filterActions,
NavListLinksProps,
} from "@/back/Components/Layout/Sidebar/AppSidebar";
import { SidebarGroupLink } from "@/back/Components/Layout/Sidebar/SidebarRegistry";
import { AuthProp } from "@/back/types/global";
import str from "@/hooks/use-string";
import { GetTranslation } from "@/lib/utils";
import useTrans from "@/hooks/use-translations";
import Views from "@/back/lib/actions";
export default function SidebarLinkBrands(auth: AuthProp): SidebarGroupLink {
const modelName = "brands";
// Translations.
const transModel = GetTranslation(`models.classes.${modelName}`, {
choice: 2,
});
const transCreate = str(
useTrans(`uwil-backend::crud.actions.${Views.CREATION.label}`),
)
.ucFirst()
.value();
const transArchives = str(useTrans("uwil-backend::back.archives"))
.ucFirst()
.value();
const link: NavListLinksProps = {
title: str(transModel).ucFirst().value(),
model: modelName,
icon: InfoIcon,
show: auth.policies.brands.viewAny,
actions: (model: string) =>
filterActions({
auth,
model,
items: [
auth.policies.brands.create && (
<DropdownMenuItem key="create" className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.create`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Views.CREATION.icon />
{transCreate}
</Link>
</Button>
</DropdownMenuItem>
),
auth.policies.brands.viewTrash && (
<DropdownMenuItem className="p-0">
<Button variant="ghost" asChild>
<Link href={route(`back.${model}.trash`)} className="w-full">
{/* eslint-disable-next-line react/jsx-pascal-case */}
<Views.ARCHIVATION.icon />
{transArchives}
</Link>
</Button>
</DropdownMenuItem>
),
],
}),
};
return { link, group: "modules" };
}

View file

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

View file

@ -0,0 +1,71 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
import { ArrowLeftIcon } from "lucide-react";
// * Other
import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
import ModelActions from "@/back/Components/ModelActions";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import Form from "@/back/Pages/Brands/Form";
import useTrans from "@/hooks/use-translations";
import { Actions, Methods } from "@/back/lib/enums";
import { Views } from "@/back/lib/actions";
import { AuthProp, DefaultModel, SingleResource } from "@/back/types/global";
export default function Edit({
data,
modelName,
}: {
data: SingleResource;
modelName: string;
}) {
const { viewAny } = (usePage().props.auth as AuthProp).policies.brands;
const model = data.data as DefaultModel;
const actionModels = [
Views.VISUALIZATION,
Views.DUPLICATION,
Views.ARCHIVATION,
];
// Translations.
const transBackToList = useTrans("uwil-backend::back.crud_back_to_list");
const transTitle = useTrans("uwil-backend::crud.helpers.edition_model", {
params: {
model: useTrans(`models.classes.${modelName}`, {
choice: 1,
}),
},
});
const beforeNode = () => {
return (
viewAny && (
<div className="flex justify-end items-center gap-x-1.5">
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.index`)}
content={<ArrowLeftIcon />}
tooltipContent={<p>{transBackToList}</p>}
/>
</div>
)
);
};
return (
<AuthenticatedLayout title={transTitle} beforeNode={beforeNode()}>
<ModelActions
actions={actionModels}
modelRoute={modelName}
model={model}
modelUpdatedAt={model.updated_at.toString()}
/>
<Form
model={model}
modelName={modelName}
modelRoute={modelName}
action={Actions.UPDATE}
method={Methods.PATCH}
/>
</AuthenticatedLayout>
);
}

View file

@ -0,0 +1,127 @@
// * Packages
import { useForm, usePage } from "@inertiajs/react";
import { BookTextIcon } from "lucide-react";
// * Components shadcn
//
// * Other
import FieldsetWrapper from "@/back/Components/FieldsetWrapper";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import useTrans from "@/hooks/use-translations";
import InputError from "@/back/Components/InputError";
import SubmitButton from "@/back/Components/SubmitButton";
import useCrudSubmit from "@/back/hooks/use-crud-submit";
import { BrandModel, SiteModel } from "@/back/types/project";
import str from "@/hooks/use-string";
import { AppEnv } from "@/types/global";
import { MultiSelect } from "@/back/Components/Inputs/MultiSelect";
import { extractIdsFromDatabasePivotRelation, mapPivotOptions } from "@/lib/mapPivotOptions";
export default function Form({
model,
modelName,
modelRoute,
action,
method,
}: {
model?: BrandModel;
modelName: string;
modelRoute: string;
action: string;
method: number;
}) {
const {
appEnv,
siteModels
} = usePage().props as unknown as {
appEnv: AppEnv;
siteModels: Array<SiteModel>;
};
/** Form section */
const { post, setData, data } = useForm({
name: model?.name ? model?.name[appEnv.locale] : undefined,
sites: extractIdsFromDatabasePivotRelation(model?.sites),
});
const submit = useCrudSubmit({
method,
modelRoute,
modelName,
action,
model,
post,
data,
modelNameTrans: useTrans(`models.classes.${modelName}`, {
choice: 1,
}),
});
const selectOptionsSites = mapPivotOptions(siteModels, model?.sites, 'name', appEnv.locale);
return (
<form id="config-form" onSubmit={submit}>
<InputError all />
<FieldsetWrapper
title={useTrans("uwil-backend::back.form_title_global")}
icon={<BookTextIcon className="mr-1" />}
description={useTrans("uwil-backend::back.form_subtitle_global")}
className="sm:grid-cols-2 gap-4"
>
<SimpleString
name="name"
label={str(
useTrans("uwil-backend::back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.name"),
},
choice: 1,
}),
)
.ucFirst()
.value()}
placeholder="ex: John Doe"
value={data.name}
setData={setData}
/>
<MultiSelect
name="sites"
label={str(
useTrans("uwil-backend::back.form_associate_to", {
params: {
attribute: useTrans("models.classes.sites", {
choice: 2,
}),
},
choice: 1,
}),
)
.ucFirst()
.value()}
placeholder={str(
useTrans("back.select_element", {
params: {
element: useTrans("models.classes.sites", {
choice: 2,
}),
},
}),
)
.ucFirst()
.value()}
options={selectOptionsSites.options}
defaultValue={selectOptionsSites.defaultValue}
setData={setData}
required={false}
closeButtonVisible
/>
</FieldsetWrapper>
<div className="text-center">
<SubmitButton
modelTrans={useTrans(`models.classes.${modelName}`, {
choice: 1,
})}
/>
</div>
</form>
);
}

View file

@ -0,0 +1,161 @@
// * Packages
import { route } from "ziggy-js";
import { usePage } from "@inertiajs/react";
import { Row } from "@tanstack/react-table";
import { ArchiveIcon, ArrowLeftIcon, PlusIcon } from "lucide-react";
// * Components shadcn
import { Badge } from "@/components/ui/badge";
// * 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 SoftdeleteWarning from "@/back/Components/SoftdeleteWarning";
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import { GetFormatedDate, GetTranslation } from "@/lib/utils";
import { Views } from "@/back/lib/actions";
import { AuthProp, Resource } from "@/back/types/global";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell";
import { BrandModel } from "@/back/types/project";
const getColumns = () => {
return [
{
accessorKey: "name",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(GetTranslation(`validation.custom.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<BrandModel> }) => (
<RenderTranslationCell value={row.getValue("name")} />
),
},
{
accessorKey: "updated_at",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(
GetTranslation(`uwil-backend::validation.attributes.${column.id}`),
)
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<BrandModel> }) => (
<Badge variant="secondary">
{GetFormatedDate(row.getValue("updated_at"))}
</Badge>
),
},
];
};
export default function Index({
models,
searchFields,
modelName,
}: {
models: Resource;
searchFields: string;
modelName: string;
}) {
const { auth } = usePage().props as unknown as {
auth: AuthProp;
};
const { viewAny, viewTrash, create } = auth.policies.brands;
const isArchiveRoute = route().current(`back.${modelName}.trash`);
const actionModels = isArchiveRoute
? [Views.RESTORATION, Views.FORCEDELETION]
: [
Views.VISUALIZATION,
Views.EDITION,
Views.DUPLICATION,
Views.ARCHIVATION,
];
const columns = getColumns();
// Translations.
const transModel = useTrans(`models.classes.${modelName}`, { choice: 2 });
const transArchiveTitle = useTrans(
"uwil-backend::crud.helpers.archives_model",
{
params: { model: transModel },
},
);
const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel)
.ucFirst()
.value();
const transCrudBackList = useTrans("uwil-backend::back.crud_back_to_list");
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>{transCrudBackList}</p>}
/>
</div>
)
);
};
const transCrudAddEntry = useTrans("uwil-backend::back.crud_add_entry");
const transAccessTo = useTrans("uwil-backend::back.crud_access_to", {
params: {
target: useTrans("uwil-backend::back.archived_entries"),
},
});
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>{transAccessTo}</p>}
variant="outline"
/>
)}
{create && (
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.create`)}
content={<PlusIcon />}
tooltipContent={<p>{transCrudAddEntry}</p>}
/>
)}
</div>
)
);
};
return (
<AuthenticatedLayout
title={transTitle}
beforeNode={beforeNode()}
afterNode={afterNode()}
>
{isArchiveRoute && <SoftdeleteWarning />}
<DataTableSearch
modelRoute={modelName}
searchFields={searchFields}
isArchiveRoute={isArchiveRoute}
/>
<DataTable
columns={columns}
modelRoute={modelName}
modelsPaginate={models}
actions={actionModels}
/>
</AuthenticatedLayout>
);
}

View file

@ -0,0 +1,119 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
import { ArrowLeftIcon } from "lucide-react";
// * 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 BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import { GetFormatedDate, GetTranslation } from "@/lib/utils";
import { Views } from "@/back/lib/actions";
import { AuthProp, DefaultModel, SingleResource } from "@/back/types/global";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { TranslationField } from "@/back/types/i18n";
import RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell";
const getColumns = () => {
return [
{
accessorKey: "name",
header: str(GetTranslation("validation.custom.name")).ucFirst().value(),
cell: ({ value }: { value: TranslationField }) => (
<RenderTranslationCell value={value} />
),
},
{
accessorKey: "created_at",
header: str(
GetTranslation("uwil-backend::validation.attributes.created_at"),
)
.ucFirst()
.value(),
cell: ({ value }: { value: string }) => (
<Badge variant="secondary">{GetFormatedDate(value)}</Badge>
),
},
{
accessorKey: "updated_at",
header: str(
GetTranslation("uwil-backend::validation.attributes.updated_at"),
)
.ucFirst()
.value(),
cell: ({ value }: { value: string }) => (
<Badge variant="secondary">{GetFormatedDate(value)}</Badge>
),
},
{
accessorKey: "deleted_at",
header: str(
GetTranslation("uwil-backend::validation.attributes.deleted_at"),
)
.ucFirst()
.value(),
cell: ({ value }: { value: string }) => (
<Badge variant="secondary">{GetFormatedDate(value)}</Badge>
),
},
];
};
export default function Show({
data,
modelName,
}: {
data: SingleResource;
modelName: string;
}) {
const { auth } = usePage().props as unknown as {
auth: AuthProp;
};
const { viewAny } = auth.policies.brands;
const model = data.data as DefaultModel;
const actionModels = [Views.EDITION, Views.DUPLICATION, Views.ARCHIVATION];
const transTitle = useTrans(
"uwil-backend::crud.helpers.visualization_model",
{
params: {
model: useTrans(`models.classes.${modelName}`, {
choice: 1,
}),
},
},
);
const columns = getColumns();
// Translations.
const transCrudBackToList = useTrans("uwil-backend::back.crud_back_to_list");
const beforeNode = () => {
return (
viewAny && (
<div className="flex justify-end items-center gap-x-1.5">
<BtnOptionnalLinkWithTooltip
link={route(`back.${modelName}.index`)}
content={<ArrowLeftIcon />}
tooltipContent={<p>{transCrudBackToList}</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} />
</AuthenticatedLayout>
);
}

View file

@ -34,3 +34,8 @@ type SiteModel = DefaultModel & {
gitlab_project: GitlabProjectModel;
users: Array<UserModel>;
};
type BrandModel = DefaultModel & {
name: TranslationField;
sites: Array<SiteModel>;
}

14
routes/back/brands.php Normal file
View file

@ -0,0 +1,14 @@
<?php
use App\Http\Controllers\Back\BrandController;
use Illuminate\Support\Facades\Route;
Route::get('/brands/trash', [BrandController::class, 'index'])
->name('brands.trash');
Route::patch('/brands/{brand}/restore', [BrandController::class, 'restore'])
->name('brands.restore');
Route::delete('/brands/{brand}/force', [BrandController::class, 'forceDestroy'])
->name('brands.forceDestroy');
Route::resource('brands', BrandController::class);
Route::get('/brands/{brand}/duplicate', [BrandController::class, 'duplicate'])
->name('brands.duplicate');

View file

@ -0,0 +1,45 @@
<?php
use Diglactic\Breadcrumbs\Breadcrumbs;
use Diglactic\Breadcrumbs\Generator;
use Illuminate\Support\Str;
Breadcrumbs::for('back.brands.index', function (Generator $trail) {
$trail->push(
Str::ucfirst(trans_choice('models.classes.brands', \INF)),
route('back.brands.index')
);
});
Breadcrumbs::for('back.brands.create', function (Generator $trail) {
$trail->parent('back.brands.index');
$trail->push(
Str::ucfirst(trans('uwil-backend::crud.actions.create')),
route('back.brands.create'),
);
});
Breadcrumbs::for('back.brands.edit', function (Generator $trail) {
$trail->parent('back.brands.index');
$trail->push(
Str::ucfirst(trans('uwil-backend::crud.actions.edit')),
route('back.brands.edit', [
'brand' => request()->brand,
])
);
});
Breadcrumbs::for('back.brands.duplicate', function (Generator $trail) {
$trail->parent('back.brands.index');
$trail->push(Str::ucfirst(trans('uwil-backend::crud.actions.duplicate')));
});
Breadcrumbs::for('back.brands.show', function (Generator $trail) {
$trail->parent('back.brands.index');
$trail->push(
Str::ucfirst(trans('uwil-backend::crud.actions.visualize')),
route('back.brands.show', [
'brand' => request()->brand,
]),
);
});
Breadcrumbs::for('back.brands.trash', function (Generator $trail) {
$trail->parent('back.brands.index');
$trail->push(Str::ucfirst(trans('uwil-backend::back.archives')));
});