feat: ✨ add invoice packages crud #118

This commit is contained in:
Alexis Gousseau 2026-04-30 15:42:04 +02:00
parent c2b4da5ad3
commit b2befb0a21
No known key found for this signature in database
GPG key ID: 7F3C786EE12DBB72
22 changed files with 1373 additions and 48 deletions

View file

@ -0,0 +1,245 @@
<?php
namespace App\Http\Controllers\Back;
use App\Http\Requests\Back\InvoicePackages\StoreInvoicePackageRequest;
use App\Http\Requests\Back\InvoicePackages\UpdateInvoicePackageRequest;
use App\Models\InvoicePackage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Uwil\LaravelBackend\Controllers\BackendController;
use Uwil\LaravelBackend\Resources\CommonResource;
/**
* Handles CRUD operations for InvoicePackage in the backend.
*/
class InvoicePackageController extends BackendController
{
/**
* Create the controller instance.
*/
public function __construct()
{
$this->authorizeResource(InvoicePackage::class);
$this->modelName = InvoicePackage::modelName();
$this->modelPage = InvoicePackage::modelPage();
}
/**
* 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\InvoicePackage> $query */
$query = InvoicePackage::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,
// TODO: Fields here.
);
}
$searchFields = \implode(', ', [
// TODO: Translations here.
]);
/** 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\InvoicePackage $invoice_package
* @return \Inertia\Response
*/
public function create(InvoicePackage $invoice_package): \Inertia\Response
{
return $this->inertiaRender("back/Pages/$this->modelPage/Create", [
'data' => CommonResource::make($invoice_package),
]);
}
/**
* Show a specific resource.
*
* @param \App\Models\InvoicePackage $invoice_package
* @return \Inertia\Response
*/
public function show(InvoicePackage $invoice_package): \Inertia\Response
{
return $this->inertiaRender("back/Pages/$this->modelPage/Show", [
'data' => CommonResource::make($invoice_package),
]);
}
/**
* Store a newly created resource.
*
* @param \App\Http\Requests\Back\InvoicePackages\StoreInvoicePackageRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(StoreInvoicePackageRequest $request): \Illuminate\Http\RedirectResponse
{
return DB::transaction(function () use ($request) {
$invoice_package = new InvoicePackage();
$invoice_package->inertiaFill($request->validated());
if ($invoice_package->saveOrFail()) {
return redirect()->route("back.$this->modelName.edit", $invoice_package)
->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\InvoicePackage $invoice_package
* @return \Inertia\Response
*/
public function edit(InvoicePackage $invoice_package): \Inertia\Response
{
return $this->inertiaRender("back/Pages/$this->modelPage/Edit", [
'data' => CommonResource::make($invoice_package),
]);
}
/**
* Update the specified resource.
*
* @param \App\Http\Requests\Back\InvoicePackages\UpdateInvoicePackageRequest $request
* @param \App\Models\InvoicePackage $invoice_package
* @return \Illuminate\Http\RedirectResponse
*/
public function update(
UpdateInvoicePackageRequest $request,
InvoicePackage $invoice_package
): \Illuminate\Http\RedirectResponse {
return DB::transaction(function () use ($request, $invoice_package) {
$invoice_package->inertiaFill($request->validated());
if ($invoice_package->saveOrFail()) {
return redirect()->route("back.$this->modelName.edit", $invoice_package)
->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", $invoice_package)
->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\InvoicePackage $invoice_package
* @return \Inertia\Response
*/
public function duplicate(InvoicePackage $invoice_package): \Inertia\Response
{
return $this->create($invoice_package->replicate());
}
/**
* Restore the specified resource.
*
* @param integer $invoice_package
* @return \Illuminate\Http\RedirectResponse
*/
public function restore(int $invoice_package): \Illuminate\Http\RedirectResponse
{
$invoice_package = InvoicePackage::withTrashed()->findOrFail($invoice_package);
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($invoice_package->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\InvoicePackage $invoice_package
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(InvoicePackage $invoice_package): \Illuminate\Http\RedirectResponse
{
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($invoice_package->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\InvoicePackage|integer $invoice_package
* @return \Illuminate\Http\RedirectResponse
*/
public function forceDestroy(InvoicePackage|int $invoice_package): \Illuminate\Http\RedirectResponse
{
if (is_int($invoice_package)) {
$invoice_package = InvoicePackage::withTrashed()->findOrFail($invoice_package);
}
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($invoice_package->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

@ -3,6 +3,7 @@
namespace App\Http\Middlewares;
use App\Enums\NoticeTypeEnum;
use App\Models\InvoicePackage;
use App\Models\Notice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
@ -28,8 +29,13 @@ class HandleInertiaRequests extends Middleware
'viewAny' => Gate::allows('viewAny', Notice::class),
'viewTrash' => Gate::allows('viewTrash', Notice::class),
'create' => Gate::allows('create', Notice::class),
]
]
],
'invoicePackages' => [
'viewAny' => Gate::allows('viewAny', InvoicePackage::class),
'viewTrash' => Gate::allows('viewTrash', InvoicePackage::class),
'create' => Gate::allows('create', InvoicePackage::class),
],
],
],
'noticeTypeEnum' => NoticeTypeEnum::toArray(),
];

View file

@ -0,0 +1,51 @@
<?php
namespace App\Http\Requests\Back\InvoicePackages;
use App\Models\InvoicePackage;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
/**
* Handles authorization and validation for creating a new InvoicePackage.
*/
class StoreInvoicePackageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return Gate::check('create', InvoicePackage::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',
'amount' => 'required|numeric|decimal:0,2|between:1,10000',
'published' => 'required|boolean',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array<string, string>
*/
public function attributes(): array
{
return [
'name' => trans('validation.custom.name'),
'amount' => trans('validation.custom.amount'),
'published' => trans('validation.custom.published'),
];
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Http\Requests\Back\InvoicePackages;
use Illuminate\Support\Facades\Gate;
/**
* Handles authorization and validation for updating an existing InvoicePackage.
*/
class UpdateInvoicePackageRequest extends StoreInvoicePackageRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return Gate::check('update', $this->route('invoice_package'));
}
}

View file

@ -0,0 +1,61 @@
<?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\LaravelBackend\Traits\Models\HasUwilImages;
use Uwil\LaravelI18n\Traits\Models\HasTranslations;
/**
* @property integer $id Id of the invoice package.
* @property string $name Name of the invoice package.
* @property string $amount Amount of the invoice package.
* @property string $published Published status of the invoice package.
* @property-read \Illuminate\Support\Carbon $created_at Date the invoice package password was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date the invoice package password was updated.
* @property-read \Illuminate\Support\Carbon $deleted_at Date the invoice package password was deleted.
*/
class InvoicePackage extends Model
{
use HasActivityLog;
use HasCache;
use HasFactory;
use HasModelNaming;
use HasTranslations;
use HasUwilImages;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'amount',
'published',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'published' => 'boolean',
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'name',
];
}

View file

@ -60,40 +60,4 @@ class Notice extends Model
'title',
'message',
];
/**
* Relations should be included in the cache.
*
* @var list<string>
*/
protected static $cacheRelations = [
// TODO: Relations here.
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
// TODO: Methods here.
});
static::updating(function (self $model) {
// TODO: Methods here.
});
static::updated(function (self $model) {
// TODO: Methods here.
});
static::restoring(function (self $model) {
// TODO: Methods here.
});
static::deleted(function (self $model) {
// TODO: Methods here.
});
static::forceDeleted(function (self $model) {
// TODO: Methods here.
});
}
}

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 InvoicePackage model actions.
*/
class InvoicePackagePolicy
{
/**
* 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

@ -19,7 +19,7 @@ class NoticePolicy
*/
public function viewAny(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -30,7 +30,7 @@ class NoticePolicy
*/
public function viewTrash(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -41,7 +41,7 @@ class NoticePolicy
*/
public function view(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -52,7 +52,7 @@ class NoticePolicy
*/
public function create(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -63,7 +63,7 @@ class NoticePolicy
*/
public function update(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -74,7 +74,7 @@ class NoticePolicy
*/
public function duplicate(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -85,7 +85,7 @@ class NoticePolicy
*/
public function restore(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -96,7 +96,7 @@ class NoticePolicy
*/
public function delete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
/**
@ -107,6 +107,6 @@ class NoticePolicy
*/
public function forceDelete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('client')->value);
return UserStaticRules::atLeastRole($authModel, UserRoleRegistry::get('developper')->value);
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Database\Factories;
use App\Models\InvoicePackage;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* Factory for generating InvoicePackage model instances with randomized data.
*/
class InvoicePackageFactory extends Factory
{
/**
* Associated model.
*
* @var class-string<\App\Models\InvoicePackage>
*/
protected $model = InvoicePackage::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
"name" => fake()->word(),
"amount" => fake()->randomFloat(2, 1, 1000),
"published" => fake()->boolean(75),
];
}
}

View file

@ -0,0 +1,36 @@
<?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('invoice_packages', function (Blueprint $table) {
$table->id()->comment('Id of the invoice package.');
$table->string('name')->comment('Name of the invoice package.');
$table->double('amount')->comment('Amount of the invoice package.');
$table->boolean('published')->comment('Published status of the invoice package.');
$table->timestamp('created_at')->nullable()->comment('Date the invoice package password was created.');
$table->timestamp('updated_at')->nullable()->comment('Date the invoice package password was updated.');
$table->timestamp('deleted_at')->nullable()->comment('Date the invoice package password was deleted.');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('invoice_packages');
}
};

View file

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

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
return [
"classes" => [
"notices" => "information|informations",
"notices" => "information|informations",
"invoice-packages" => "devis - forfait|devis - forfaits",
],
];

View file

@ -9,5 +9,8 @@ return [
"title" => "titre",
"message" => "message",
"type" => "type",
"name" => "nom",
"amount" => "jour",
"published" => "publié",
],
];

View file

@ -0,0 +1,73 @@
// * Packages
import { HandCoinsIcon } 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 SidebarLinkInvoicePackages(auth: AuthProp): SidebarGroupLink {
const modelName = "invoice-packages";
// 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: HandCoinsIcon,
show: auth.policies.invoicePackages.viewAny,
actions: (model: string) =>
filterActions({
auth,
model,
items: [
auth.policies.invoicePackages.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.invoicePackages.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/InvoicePackages/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.invoicePackages;
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/InvoicePackages/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.invoicePackages;
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,125 @@
// * Packages
import { useForm, usePage } from "@inertiajs/react";
import { BookTextIcon, EyeIcon } from "lucide-react";
// * Components shadcn
//
// * Other
import FieldsetWrapper from "@/back/Components/FieldsetWrapper";
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 { AppEnv } from "@/types/global";
import { InvoicePackageModel } from "@/back/types/project";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import SimpleNumber from "@/back/Components/Inputs/SimpleNumber";
import str from "@/hooks/use-string";
export default function Form({
model,
modelName,
modelRoute,
action,
method,
}: {
model?: InvoicePackageModel;
modelName: string;
modelRoute: string;
action: string;
method: number;
}) {
const { appEnv } = usePage().props as unknown as {
appEnv: AppEnv;
};
/** Form section */
const { post, setData, data } = useForm({
name: model?.name ? model?.name[appEnv.locale] : "",
amount: model?.amount ?? 0,
published: model?.published ?? false,
});
const submit = useCrudSubmit({
method,
modelRoute,
modelName,
action,
model,
post,
data,
modelNameTrans: useTrans(`models.classes.${modelName}`, {
choice: 1,
}),
});
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: Newsletter"
value={data.name}
setData={setData}
/>
<SimpleNumber
name="amount"
label={str(
useTrans("uwil-backend::back.form_associate_to", {
params: {
attribute: useTrans("validation.custom.amount"),
},
choice: 1,
}),
)
.ucFirst()
.value()}
step={0.01}
limits={{
min: 1,
max: 10000,
}}
placeholder="ex: 100"
value={data.amount}
setData={setData}
/>
</FieldsetWrapper>
<FieldsetWrapper
className="gap-4"
title={useTrans("uwil-backend::back.form_title_visibility")}
icon={<EyeIcon className="mr-1" />}
description={useTrans("uwil-backend::back.form_subtitle_visibility")}
inline
>
<SimpleSwitch
name="published"
checked={data.published}
setData={setData}
/>
</FieldsetWrapper>
<div className="text-center">
<SubmitButton
modelTrans={useTrans(`models.classes.${modelName}`, {
choice: 1,
})}
/>
</div>
</form>
);
}

View file

@ -0,0 +1,215 @@
// * Packages
import { route } from "ziggy-js";
import { usePage } from "@inertiajs/react";
import { Row } from "@tanstack/react-table";
import { ArchiveIcon, ArrowLeftIcon, CheckIcon, PlusIcon, XIcon } 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 RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell";
import { GetFormatedDate, GetTranslation } from "@/lib/utils";
import { Views } from "@/back/lib/actions";
import { AuthProp, DefaultModel, Resource } from "@/back/types/global";
import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { InvoicePackageModel } 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<InvoicePackageModel> }) => (
<RenderTranslationCell value={row.getValue("name")} />
),
},
{
accessorKey: "amount",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(
GetTranslation(`validation.custom.${column.id}`),
)
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<InvoicePackageModel> }) => row.getValue("amount"),
},
{
accessorKey: "published",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(
GetTranslation(`uwil-backend::validation.custom.${column.id}`),
)
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<InvoicePackageModel> }) => (
<Badge
variant="outline"
className={`border-0 ${
row.getValue("published")
? "bg-green-200 dark:bg-green-900"
: "bg-red-200 dark:bg-red-900"
}`}
>
{row.getValue("published") ? (
<CheckIcon size={15} className="mr-1" />
) : (
<XIcon size={15} className="mr-1" />
)}
{str(
GetTranslation(
row.getValue("published")
? "uwil-backend::back.yes"
: "uwil-backend::back.no",
),
)
.ucFirst()
.value()}
</Badge>
),
},
{
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<DefaultModel> }) => (
<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.invoicePackages;
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,161 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
import { ArrowLeftIcon, CheckIcon, XIcon } 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 RenderTranslationCell from "@/back/Components/Table/RenderTranslationCell";
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";
const getColumns = () => {
return [
{
accessorKey: "name",
header: str(
GetTranslation("validation.custom.name"),
)
.ucFirst()
.value(),
cell: ({ value }: { value: TranslationField }) => (
<RenderTranslationCell value={value} />
),
},
{
accessorKey: "amount",
header: str(
GetTranslation("validation.custom.amount"),
)
.ucFirst()
.value(),
cell: ({ value }: { value: number }) => value,
},
{
accessorKey: "published",
header: str(GetTranslation("uwil-backend::validation.custom.published"))
.ucFirst()
.value(),
cell: ({ value }: { value: boolean }) => (
<Badge
variant="outline"
className={`border-0 ${
value
? "bg-green-200 dark:bg-green-900"
: "bg-red-200 dark:bg-red-900"
}`}
>
{value ? (
<CheckIcon size={15} className="mr-1" />
) : (
<XIcon size={15} className="mr-1" />
)}
{str(
GetTranslation(
value ? "uwil-backend::back.yes" : "uwil-backend::back.no",
),
)
.ucFirst()
.value()}
</Badge>
),
},
{
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.invoicePackages;
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

@ -6,3 +6,9 @@ type NoticeModel = DefaultModel & {
message: TranslationField;
type: LaravelEnum;
};
type InvoicePackageModel = DefaultModel & {
name: TranslationField;
amount: number;
published: boolean;
};

View file

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

View file

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