Merge branch 'fix-alexis' into 'develop'

Multiple fix front/back

See merge request ldc-web/projets/ldc!116
This commit is contained in:
karl.muller 2026-01-26 08:55:16 +00:00
commit 9cc92e9a7a
165 changed files with 6795 additions and 3096 deletions

5
.gitignore vendored
View file

@ -16,6 +16,11 @@
/public/build
/public/hot
/public/storage
/public/apple-touch-icon.png
/public/safari-pinned-tab.svg
/public/site.webmanifest
/public/web-app-manifest-192x192.png
/public/web-app-manifest-512x512.png
/storage/*.key
/storage/pail
/storage/uploads

View file

@ -1,78 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Document;
use App\Models\DynamicPage;
use App\Models\News;
use App\Models\SearchIndex;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Meilisearch\Client;
class MeilisearchUpdate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'meilisearch:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Configure Meilisearch and rebuilt all indexes in all locales.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
// Get new instance of Meilisearch client.
$client = new Client(
config('scout.meilisearch.host'),
config('scout.meilisearch.key')
);
// Get all supported locales defined in laravel localization config.
$locales = LaravelLocalization::getSupportedLocales();
collect(array_keys($locales))->map(function (string $locale) use ($client) {
$localeName = Str::upper($locale);
$indexName = config('scout.prefix') . $locale;
$index = $client->index($indexName);
$index->updateSearchableAttributes(['title', 'content']);
$index->updateFilterableAttributes(['type']);
$this->info("Meilisearch indexes configured for locale: {$localeName}");
app()->setLocale($locale);
SearchIndex::removeAllFromSearch();
collect([
News::class,
DynamicPage::class,
Document::class,
])->map(function(string $class) {
$class::chunk(100, function ($items) {
$items
->map
->toSearchDocument()
->filter()
->each
->searchable();
});
});
$this->info("Meilisearch indexes rebuilt for locale: {$localeName}");
});
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace App\Console\Commands;
use App\Models\DynamicPage;
use App\Models\News;
use App\Models\Document;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class UpdateMeilisearch extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'update-meilisearch';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
$models = [DynamicPage::class, News::class, Document::class];
$locales = ['fr', 'en'];
foreach ($locales as $locale) {
$this->info("Import {$locale}...");
app()->setLocale($locale);
foreach ($models as $model) {
$this->call('scout:import', ['model' => $model]);
}
}
}
}

View file

@ -2,9 +2,11 @@
namespace App\Helpers;
use App\Enums\Document\DocumentStatusEnum;
use Illuminate\Http\Request;
class DocumentHelper
{
/**
* Extract the Issuu embed URL from an iframe or raw Issuu input.
*
@ -44,4 +46,56 @@ class DocumentHelper
? html_entity_decode($matches[1], ENT_QUOTES)
: null;
}
/**
* Return a document query with all the request filters applied
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query
* @return \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query
*/
public static function getQueryWithFilters(Request $request, $query): \Illuminate\Database\Eloquent\Builder
{
$statusFilter = $request->status;
if($statusFilter) {
$query->where('status', DocumentStatusEnum::make($statusFilter, 'name')->value);
}
$hasNoLinkFilter = request()->boolean('hasNoLink');
$query->when($hasNoLinkFilter, function ($query) {
$locale = app()->getLocale();
$query->where(function ($q) use ($locale) {
$q->whereNull("issuu_path->$locale")
->whereNull("path->$locale");
});
});
$categoriesFilter = $request->input('categories');
$query->when($categoriesFilter, function ($query, $categoriesFilter) {
$categoryIds = collect(explode(',', $categoriesFilter))
->map(fn($id) => (int) $id)
->filter()
->values();
$query->whereHas('categories', function ($q) use ($categoryIds) {
$q->whereIn('document_categories.id', $categoryIds);
});
});
$tagsFilter = $request->input('tags');
$query->when($tagsFilter, function ($query, $tagsFilter) {
$tagIds = collect(explode(',', $tagsFilter))
->map(fn($id) => (int) $id)
->filter()
->values();
$query->whereHas('tags', function ($q) use ($tagIds) {
$q->whereIn('document_tags.id', $tagIds);
});
});
return $query;
}
}

View file

@ -11,6 +11,7 @@ use Illuminate\Support\Str;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum;
class CompanyActivityController extends Controller
{
@ -34,7 +35,7 @@ class CompanyActivityController extends Controller
public function index(Request $request): \Inertia\Response
{
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\CompanyActivity> $query */
$query = CompanyActivity::query();
$query = CompanyActivity::query()->with('companies');
if ($request->routeIs("back.$this->modelName.trash")) {
$query = $query->onlyTrashed();
@ -90,8 +91,10 @@ class CompanyActivityController extends Controller
*/
public function show(CompanyActivity $company_activity): \Inertia\Response
{
$companies = $company_activity->companies()->paginate(ItemsPerPaginationEnum::five->value());
return Inertia::render('CompanyActivities/Show', [
'data' => CommonResource::make($company_activity),
'companies' => CommonResource::collection($companies),
'modelName' => $this->modelName,
]);
}

View file

@ -36,7 +36,7 @@ class CompanyController extends Controller
public function index(Request $request): \Inertia\Response
{
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Company> $query */
$query = Company::query();
$query = Company::query()->with(['companyActivity', 'companySector']);
if ($request->routeIs("back.$this->modelName.trash")) {
$query = $query->onlyTrashed();
@ -101,7 +101,7 @@ class CompanyController extends Controller
public function show(Company $company): \Inertia\Response
{
return Inertia::render('Companies/Show', [
'data' => CommonResource::make($company),
'data' => CommonResource::make($company->load(['companyActivity', 'companySector'])),
'modelName' => $this->modelName,
]);
}

View file

@ -11,6 +11,7 @@ use Illuminate\Support\Str;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum;
class CompanySectorController extends Controller
{
@ -34,7 +35,7 @@ class CompanySectorController extends Controller
public function index(Request $request): \Inertia\Response
{
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\CompanySector> $query */
$query = CompanySector::query();
$query = CompanySector::query()->with('companies');
if ($request->routeIs("back.$this->modelName.trash")) {
$query = $query->onlyTrashed();
@ -76,8 +77,10 @@ class CompanySectorController extends Controller
*/
public function create(CompanySector $company_sector): \Inertia\Response
{
$companies = $company_sector->companies()->paginate(ItemsPerPaginationEnum::five->value());
return Inertia::render('CompanySectors/Create', [
'data' => CommonResource::make($company_sector),
'companies' => CommonResource::collection($companies),
'modelName' => $this->modelName,
]);
}

View file

@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum;
class DocumentCategoryController extends Controller
{
@ -35,6 +36,10 @@ class DocumentCategoryController extends Controller
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\DocumentCategory> $query */
$query = DocumentCategory::query()->withCount('documents');
if ($request->routeIs("back.$this->modelName.trash")) {
$query = $query->onlyTrashed();
}
/** @var string $search Search field */
$search = $request->search;
if ($search) {
@ -84,7 +89,7 @@ class DocumentCategoryController extends Controller
*/
public function show(DocumentCategory $document_category): \Inertia\Response
{
$documents = $document_category->documents()->paginate(12);
$documents = $document_category->documents()->paginate(ItemsPerPaginationEnum::five->value());
return Inertia::render('DocumentCategory/Show', [
'data' => CommonResource::make($document_category),
'documents' => CommonResource::collection($documents),
@ -142,6 +147,23 @@ class DocumentCategoryController extends Controller
});
}
/**
* Restore the specified resource.
*
* @param integer $document_category
* @return \Illuminate\Http\RedirectResponse
*/
public function restore(int $document_category): \Illuminate\Http\RedirectResponse
{
$document_category = DocumentCategory::withTrashed()->findOrFail($document_category);
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($document_category->restore()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries);
}
return redirect()->back();
}
/**
* Destroy the specified resource.
@ -159,4 +181,24 @@ class DocumentCategoryController extends Controller
}
return redirect()->back();
}
/**
* Destroy the specified resource.
*
* @param \App\Models\DocumentCategory|integer $document_category
* @return \Illuminate\Http\RedirectResponse
*/
public function forceDestroy(DocumentCategory|int $document_category): \Illuminate\Http\RedirectResponse
{
if (is_int($document_category)) {
$document_category = DocumentCategory::withTrashed()->findOrFail($document_category);
}
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($document_category->forceDelete()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries);
}
return redirect()->back();
}
}

View file

@ -4,6 +4,7 @@ namespace App\Http\Controllers\Back;
use App\Enums\Document\DocumentStatusEnum;
use App\Enums\YearsEnum;
use App\Helpers\DocumentHelper;
use App\Http\Requests\Back\Document\StoreDocumentRequest;
use App\Http\Requests\Back\Document\UpdateDocumentRequest;
use App\Models\Document;
@ -37,7 +38,7 @@ class DocumentController extends Controller
public function index(Request $request): \Inertia\Response
{
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\Document> $query */
$query = Document::query()->with(['categories']);
$query = DocumentHelper::getQueryWithFilters($request, Document::query()->with(['categories', 'tags']));
/** @var string $search Search field */
$search = $request->search;
@ -49,6 +50,7 @@ class DocumentController extends Controller
'name',
);
}
$searchFields = \implode(', ', [
trans('validation.attributes.name'),
]);
@ -63,6 +65,8 @@ class DocumentController extends Controller
'search' => $search,
'searchFields' => $searchFields,
'enumDocumentStatus' => DocumentStatusEnum::toArray(),
'categories' => DocumentCategory::getModelsCached(),
'tags' => DocumentTag::getModelsCached(),
'modelName' => $this->modelName,
]);
}

View file

@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum;
class DocumentTagController extends Controller
{
@ -35,6 +36,10 @@ class DocumentTagController extends Controller
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\DocumentTag> $query */
$query = DocumentTag::query()->withCount('documents');
if ($request->routeIs("back.$this->modelName.trash")) {
$query = $query->onlyTrashed();
}
/** @var string $search Search field */
$search = $request->search;
if ($search) {
@ -84,7 +89,7 @@ class DocumentTagController extends Controller
*/
public function show(DocumentTag $document_tag): \Inertia\Response
{
$documents = $document_tag->documents()->paginate(12);
$documents = $document_tag->documents()->paginate(ItemsPerPaginationEnum::five->value());
return Inertia::render('DocumentTag/Show', [
'data' => CommonResource::make($document_tag),
'documents' => CommonResource::collection($documents),
@ -142,6 +147,24 @@ class DocumentTagController extends Controller
});
}
/**
* Restore the specified resource.
*
* @param integer $document_tag
* @return \Illuminate\Http\RedirectResponse
*/
public function restore(int $document_tag): \Illuminate\Http\RedirectResponse
{
$document_tag = DocumentTag::withTrashed()->findOrFail($document_tag);
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($document_tag->restore()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries);
}
return redirect()->back();
}
/**
* Destroy the specified resource.
*
@ -158,4 +181,24 @@ class DocumentTagController extends Controller
}
return redirect()->back();
}
/**
* Destroy the specified resource.
*
* @param \App\Models\DocumentTag|integer $document_tag
* @return \Illuminate\Http\RedirectResponse
*/
public function forceDestroy(DocumentTag|int $document_tag): \Illuminate\Http\RedirectResponse
{
if (is_int($document_tag)) {
$document_tag = DocumentTag::withTrashed()->findOrFail($document_tag);
}
/** @var array<string,string> */
$previousQueries = [];
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
if ($document_tag->forceDelete()) {
return redirect()->route("back.$this->modelName.trash", $previousQueries);
}
return redirect()->back();
}
}

View file

@ -11,6 +11,7 @@ use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum;
class NewsCategoryController extends Controller
{
@ -90,7 +91,7 @@ class NewsCategoryController extends Controller
*/
public function show(NewsCategory $news_category): \Inertia\Response
{
$news = $news_category->news()->paginate(12);
$news = $news_category->news()->paginate(ItemsPerPaginationEnum::five->value());
return Inertia::render('NewsCategory/Show', [
'data' => CommonResource::make($news_category),
'news' => CommonResource::collection($news),

View file

@ -36,7 +36,7 @@ class NewsController extends Controller
public function index(Request $request): \Inertia\Response
{
/** @var \Illuminate\Database\Eloquent\Builder<\App\Models\News> $query */
$query = News::query();
$query = News::query()->with('categories');
if ($request->routeIs("back.news.trash")) {
$query = $query->onlyTrashed();

View file

@ -11,6 +11,7 @@ use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Uwil\LaravelBackend\Resources\CommonResource;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Enums\ItemsPerPaginationEnum;
class NewsTagController extends Controller
{
@ -90,7 +91,7 @@ class NewsTagController extends Controller
*/
public function show(NewsTag $news_tag): \Inertia\Response
{
$news = $news_tag->news()->paginate(12);
$news = $news_tag->news()->paginate(ItemsPerPaginationEnum::five->value());
return Inertia::render('NewsTag/Show', [
'data' => CommonResource::make($news_tag),
'news' => CommonResource::collection($news),

View file

@ -2,43 +2,84 @@
namespace App\Http\Controllers\Front;
use App\Enums\StaticPageType;
use App\Http\Requests\Front\SearchRequest;
use App\Models\StaticPage;
use App\Models\SearchIndex;
use App\Http\Requests\Front\Search\SearchAjaxRequest;
use App\Http\Requests\Front\Search\SearchRequest;
use App\Models\Document;
use App\Models\DynamicPage;
use App\Models\News;
use App\Enums\Document\DocumentStatusEnum;
use App\Enums\News\NewsStatusEnum;
use App\Enums\DynamicPages\PageStatusEnum;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Builder;
use Mcamara\LaravelLocalization\LaravelLocalization;
use Uwil\LaravelCommon\Controllers\Controller;
use Uwil\LaravelCommon\Helpers\CollectionHelper;
class SearchController extends Controller
{
/**
* Search page.
* Access to the search page.
*
* @param \App\Http\Requests\Front\SearchRequest $request
* @param \App\Http\Requests\Front\Search\SearchRequest $request
* @return \Illuminate\Contracts\View\View
*/
public function search(SearchRequest $request): \Illuminate\Contracts\View\View
public function search(SearchRequest $request)
{
$queryKey = trans('front.search.query');
$pageKey = trans('front.search.page');
$queryKey = trans('front.search.query');
$searchTerm = $request->validated()[$queryKey];
$currentPage = $request->validated()[$pageKey];
$perPage = 10;
$searchQuery = $this->buildExactSearchQuery($searchTerm);
$resultModels = SearchIndex::search($searchQuery)
->paginateRaw(perPage: $perPage, page: $currentPage);
return view('front.pages.search', compact('searchTerm'));
}
/**
* Load results from search.
*
* @param \App\Http\Requests\Front\Search\SearchAjaxRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function ajaxSearchLoadResults(SearchAjaxRequest $request): \Illuminate\Http\JsonResponse
{
$class = $request->validated()['class'];
$searchTerm = $request->validated()['search'];
$currentPage = (int) $request->validated()['page'];
$currentLocale = $request->validated()['locale'];
$perPage = 5;
$resultModels->appends([
$queryKey => $searchTerm,
$pageKey => $currentPage,
'query' => null,
app()->setLocale($currentLocale);
$searchQuery = $this->buildExactSearchQuery($searchTerm);
$models = $class::search($searchQuery, function ($engine, $query, $options) use ($class, $currentLocale) {
$options['attributesToSearchOn'] = $class::searchTransFields($currentLocale);
return $engine->search($query, $options);
})
->where('status', $class::searchStatusEnum())
->paginateRaw(perPage: $perPage, page: $currentPage);
// Render items.
$itemsHtml = collect($models['hits'])->map(fn ($result) =>
view('components.front.search.card', [
'class' => $class,
'result' => $result,
'mainField' => $class::searchMainField(),
'routeName' => $class::searchRouteName($result['id_key'] ?? null),
'customBreadcrumbs' => true,
'searchTerm' => $searchTerm,
'currentLocale' => $currentLocale,
])->render()
)->implode('');
// Pagination.
$paginationHtml = view('components.front.search.pagination', [
'models' => $models,
])->render();
return response()->json([
'items' => $itemsHtml,
'pagination' => $paginationHtml,
'totalHits' => $models['totalHits'],
]);
return view('front.pages.search', compact('searchTerm', 'resultModels'));
}
/**
@ -60,4 +101,95 @@ class SearchController extends Controller
return '+' . implode(' +', $exactTerms);
}
/**
* Highlights all search terms in a text.
*
* @param string $text
* @param string $searchTerm
* @return string
*/
public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string
{
if (trim($searchTerm) === '') {
return $text;
}
// Clean terms list.
$words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY);
if (empty($words)) {
return $text;
}
$fullText = strip_tags($text);
$textLength = strlen($fullText);
$ranges = [];
// Collection of relevant ranges around each word.
foreach ($words as $word) {
$pattern = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
// Check if current word match exactly with terms.
if (preg_match_all($pattern, $fullText, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
$matchPos = $match[1];
$matchLen = strlen($match[0]);
$ranges[] = [
'start' => max(0, $matchPos - $contextLength),
'end' => min($textLength, $matchPos + $matchLen + $contextLength),
];
}
}
}
// Return the entire text if there isn't matches.
if (empty($ranges)) {
return $text;
}
// Merging overlapping intervals.
usort($ranges, fn($a, $b) => $a['start'] <=> $b['start']);
$merged = [];
foreach ($ranges as $r) {
if (empty($merged) || $r['start'] > $merged[array_key_last($merged)]['end']) {
$merged[] = $r;
} else {
$merged[array_key_last($merged)]['end'] = max(
$merged[array_key_last($merged)]['end'],
$r['end']
);
}
}
$snippets = [];
foreach ($merged as $r) {
$snippet = substr($fullText, $r['start'], $r['end'] - $r['start']);
// Cut cleanly without breaking the words
if ($r['start'] > 0) {
$snippet = preg_replace('/^\S*\s/', '…', $snippet, 1);
}
if ($r['end'] < $textLength) {
$snippet = preg_replace('/\s\S*$/', '…', $snippet, 1);
}
// Highlighting searched words
foreach ($words as $word) {
$pattern = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
$snippet = preg_replace(
$pattern,
'<span class="search-highlight">$0</span>',
$snippet
);
}
$snippets[] = trim($snippet);
if (count($snippets) >= 3) break;
}
$result = implode('… ', $snippets);
$result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result);
return trim($result);
}
}

View file

@ -54,8 +54,6 @@ class HandleInertiaRequests extends Middleware
]),
]);
$locales = LaravelLocalization::getSupportedLocales();
$props = [
...parent::share($request),
'appEnv' => [
@ -63,7 +61,7 @@ class HandleInertiaRequests extends Middleware
'name' => config('app.name'),
'url' => config('app.url'),
'locale' => app()->getLocale(),
'locales' => array_keys($locales),
'locales' => LaravelLocalization::getSupportedLanguagesKeys(),
'fallbackLocale' => app()->getFallbackLocale(),
],
'auth' => [
@ -123,14 +121,16 @@ class HandleInertiaRequests extends Middleware
'viewAny' => Gate::allows('viewAny', Document::class),
'create' => Gate::allows('create', Document::class),
],
'documentTags' => [
'viewAny' => Gate::allows('viewAny', DocumentTag::class),
'create' => Gate::allows('create', DocumentTag::class),
],
"documentCategories" => [
'viewAny' => Gate::allows('viewAny', DocumentCategory::class),
'viewTrash' => Gate::allows('viewTrash', DocumentCategory::class),
'create' => Gate::allows('create', DocumentCategory::class),
],
'documentTags' => [
'viewAny' => Gate::allows('viewAny', DocumentTag::class),
'viewTrash' => Gate::allows('viewTrash', DocumentTag::class),
'create' => Gate::allows('create', DocumentTag::class),
],
]
],
'enumItemsPerPagination' => ItemsPerPaginationEnum::toArray(),

View file

@ -94,7 +94,8 @@ class StoreNewsRequest extends FormRequest
'seo_description' => trans('validation.custom.seo.description'),
'title' => trans('validation.attributes.title'),
'slug' => trans('validation.custom.slug'),
'categories' => trans('validation.custom.categories'),
'categories' => trans_choice('models.classes.news-category', \INF),
'tags' => trans_choice('models.classes.news-tag', \INF),
'picture' => trans('validation.attributes.image'),
'picture_alt' => trans('validation.custom.image_alt'),
'picture_title' => trans('validation.custom.image_title'),

View file

@ -0,0 +1,50 @@
<?php
namespace App\Http\Requests\Front\Search;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
class SearchAjaxRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return $this->ajax();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
$supportedLocales = implode(',', LaravelLocalization::getSupportedLanguagesKeys());
return [
'search' => 'required|string|between:3,255',
'page' => 'required|integer|min:1',
'locale' => "required|string|in:$supportedLocales",
'class' => [
'required',
'string',
'starts_with:App\\Models\\',
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed
function ($attribute, $value, $fail) {
if (!class_exists($value)) {
$fail("The specified model does not exist.");
return;
}
if (!is_subclass_of($value, Model::class)) {
$fail("The specified model is not an Eloquent model.");
}
},
],
];
}
}

View file

@ -1,6 +1,6 @@
<?php
namespace App\Http\Requests\Front;
namespace App\Http\Requests\Front\Search;
use Illuminate\Foundation\Http\FormRequest;

View file

@ -4,12 +4,14 @@ namespace App\Models;
use App\Contracts\TranslatableModel;
use App\Helpers\TranslationHelper;
use App\Models\Company;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
/**
@ -71,6 +73,13 @@ class CompanyActivity extends Model implements TranslatableModel
static::updating(function (self $model) {
self::manageFields($model);
});
static::deleting(function (self $model) {
if ($model->companies()->exists()) {
throw ValidationException::withMessages([
'error' => trans('crud.messages.cannot_delete_relation'),
]);
}
});
}
// * METHODS
@ -101,4 +110,16 @@ class CompanyActivity extends Model implements TranslatableModel
}
TranslationHelper::validateFallbackTranslations($model);
}
// RELATIONSHIPS
/**
* Get companies for this activity.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function companies(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Company::class, 'activity_id');
}
}

View file

@ -4,12 +4,14 @@ namespace App\Models;
use App\Contracts\TranslatableModel;
use App\Helpers\TranslationHelper;
use App\Models\Company;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
/**
@ -69,6 +71,13 @@ class CompanySector extends Model implements TranslatableModel
static::updating(function (self $model) {
self::manageFields($model);
});
static::deleting(function (self $model) {
if ($model->companies()->exists()) {
throw ValidationException::withMessages([
'sector_id' => trans('crud.messages.cannot_delete_relation'),
]);
}
});
}
// * METHODS
@ -99,4 +108,16 @@ class CompanySector extends Model implements TranslatableModel
}
TranslationHelper::validateFallbackTranslations($model);
}
// RELATIONSHIPS
/**
* Get companies for this sector.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function companies(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Company::class, 'sector_id');
}
}

View file

@ -5,9 +5,9 @@ namespace App\Models;
use App\Contracts\TranslatableModel;
use App\Enums\Document\DocumentStatusEnum;
use App\Enums\YearsEnum;
use App\Helpers\DocumentHelper;
use App\Helpers\TranslationHelper;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasMeilisearchIndex;
use App\Traits\Models\HasTranslations;
use App\Traits\Models\HasUwilImages;
use Carbon\Carbon;
@ -16,7 +16,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use App\Helpers\DocumentHelper;
use Laravel\Scout\Searchable;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
class Document extends Model implements TranslatableModel
@ -28,7 +28,7 @@ class Document extends Model implements TranslatableModel
use HasUwilImages {
HasUwilImages::inertiaFill as traitInertiaFill;
}
use HasMeilisearchIndex;
use Searchable;
/**
* Champs contenant des images dynamiques à gérer.
@ -221,61 +221,81 @@ class Document extends Model implements TranslatableModel
return sprintf('/%s', $targetModel->path);
}
/**
* Set value of meilisearch indexes.
*
* @return \App\Models\SearchIndex|null
*/
public function toSearchDocument(): ?\App\Models\SearchIndex
{
$locale = app()->getLocale();
// * MEILISEARCH
// Keep only published models.
if (!$this->status->equals(DocumentStatusEnum::published) || !$this->hasTranslation('path', $locale)) {
return null;
/**
* Get model's setting to apply on scout search (meilisearch).
*
* @var array
*/
public static $searchSettings = [
'filterableAttributes' => ['status'],
'sortableAttributes' => ['status']
];
/**
* Get fields that we want to keep in the current locale.
*
* @param string $currentLocale
* @return array
*/
public static function searchTransFields(string $currentLocale): array
{
return [
"name_$currentLocale",
"path_$currentLocale",
];
}
/**
* Get enum status of the model.
*
* @return integer
*/
public static function searchStatusEnum(): int
{
return DocumentStatusEnum::published->value;
}
/**
* Get front route.
*
* @return string
*/
public static function searchRouteName(): string
{
return 'front.documents.show';
}
/**
* Get model identificable field.
*
* @return string
*/
public static function searchMainField(): string
{
return 'name';
}
/**
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
$locales = config('laravellocalization.supportedLocales');
$data = [
'id' => $this->id,
'status' => $this->status->value,
];
foreach ($locales as $locale => $_) {
$data["name_$locale"] = $this->hasTranslation('name', $locale) ? $this->getTranslation('name', $locale) : null;
$data["path_$locale"] = $this->hasTranslation('path', $locale) ? $this->getTranslation('path', $locale) : null;
}
return new SearchIndex([
'type' => Str::snake(class_basename($this)),
'model_id' => $this->getKey(),
'slug' => $this->getTranslation('path', $locale),
'title' => $this->getTranslation('name', $locale),
'content' => null,
]);
}
// * RELATIONSHIPS
/**
* Relation to Tag
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphedByMany(
DocumentTag::class,
'documentable',
'documentables',
'document_id',
'documentable_id'
)->withTimestamps();
}
/**
* Relation to Category
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categories(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphedByMany(
DocumentCategory::class,
'documentable',
'documentables',
'document_id',
'documentable_id'
)->withTimestamps();
return $data;
}
public function inertiaFill(array $attributes)
@ -316,4 +336,38 @@ class Document extends Model implements TranslatableModel
);
});
}
// * RELATIONSHIPS
/**
* Relation to Tag
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphedByMany(
DocumentTag::class,
'documentable',
'documentables',
'document_id',
'documentable_id'
)->withTimestamps();
}
/**
* Relation to Category
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categories(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphedByMany(
DocumentCategory::class,
'documentable',
'documentables',
'document_id',
'documentable_id'
)->withTimestamps();
}
}

View file

@ -7,7 +7,7 @@ use App\Traits\Models\HasCache;
use App\Traits\Models\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
class DocumentCategory extends Model implements TranslatableModel
@ -16,6 +16,7 @@ class DocumentCategory extends Model implements TranslatableModel
use HasFactory;
use HasCache;
use HasTranslations;
use SoftDeletes;
/**
* The attributes that are mass assignable.
@ -40,9 +41,9 @@ class DocumentCategory extends Model implements TranslatableModel
/**
* Relation to Document
*
* @return BelongsToMany
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function documents(): BelongsToMany
public function documents(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphToMany(
Document::class,

View file

@ -2,14 +2,14 @@
namespace App\Models;
use App\Traits\Models\HasCache;
use Illuminate\Support\Facades\App;
use App\Contracts\TranslatableModel;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasTranslations;
use Illuminate\Database\Eloquent\Model;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\App;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
class DocumentTag extends Model implements TranslatableModel
{
@ -17,6 +17,7 @@ class DocumentTag extends Model implements TranslatableModel
use HasFactory;
use HasCache;
use HasTranslations;
use SoftDeletes;
/**
* The attributes that are mass assignable.
@ -51,9 +52,9 @@ class DocumentTag extends Model implements TranslatableModel
/**
* Relation to Document
*
* @return BelongsToMany
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function documents(): BelongsToMany
public function documents(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphToMany(
Document::class,

View file

@ -9,9 +9,7 @@ use App\Enums\DynamicPages\PageStatusEnum;
use App\Helpers\DynamicPageHelper;
use App\Helpers\RouteHelper;
use App\Helpers\TranslationHelper;
use App\Models\SearchIndex;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasMeilisearchIndex;
use App\Traits\Models\HasTranslations;
use App\Traits\Models\HasUwilImages;
use Illuminate\Database\Eloquent\Collection;
@ -22,6 +20,7 @@ use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Scout\Searchable;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
use Uwil\LaravelCommon\Helpers\FileHelper;
@ -47,7 +46,7 @@ class DynamicPage extends Model implements TranslatableModel
use HasTranslations;
use HasUwilImages;
use SoftDeletes;
use HasMeilisearchIndex;
use Searchable;
/**
* The attributes that are mass assignable.
@ -109,10 +108,8 @@ class DynamicPage extends Model implements TranslatableModel
{
static::creating(function (self $model) {
self::manageFields($model);
// Set id_key from slug or title when the dynamic page is root.
$model->id_key = isset($model->slug) && !empty($model->slug)
? $model->slug
: Str::slug($model->title);
// Set id_key from title.
$model->id_key = Str::slug($model->title);
});
static::updating(function (self $model) {
self::manageFields($model);
@ -254,9 +251,10 @@ class DynamicPage extends Model implements TranslatableModel
*/
public static function assertRootIsUnique(self $model): void
{
$oldDynamicPageRoot = self::getModelsCached()->where('isRoot', true)->first();
$oldDynamicPageRoot = self::getModelsCached()->where('id', '!=', $model->getKey())->where('isRoot', true)->first();
if ($oldDynamicPageRoot) {
$oldDynamicPageRoot->isRoot = false;
$oldDynamicPageRoot->status = PageStatusEnum::unpublished;
$oldDynamicPageRoot->isRoot = false;
$oldDynamicPageRoot->saveQuietly();
}
}
@ -320,44 +318,6 @@ class DynamicPage extends Model implements TranslatableModel
return parse_url($url, PHP_URL_PATH) ?? "/";
}
/**
* Set value of meilisearch indexes.
*
* @return \App\Models\SearchIndex|null
*/
public function toSearchDocument(): ?\App\Models\SearchIndex
{
$locale = app()->getLocale();
// Keep only published models.
if (!$this->status->equals(PageStatusEnum::published) || !$this->hasTranslation('slug', $locale)) {
return null;
}
// Clean content (no tags, no paths, no numbers, only string).
$content = strip_tags(collect($this->getTranslation('content', $locale))
->flatten()
->filter(fn($value, $key) =>
is_string($value) &&
!empty($value) &&
!is_numeric($value) &&
!in_array($key, ['order', 'id']) &&
!str_starts_with($key, 'image_') &&
!preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value)
)
->values()
->implode(' '));
return new SearchIndex([
'type' => Str::snake(class_basename($this)),
'model_id' => $this->getKey(),
'id_key' => $this->id_key,
'slug' => $this->getTranslation('slug', $locale),
'title' => $this->getTranslation('title', $locale),
'content' => $content
]);
}
/**
* Get localized path from the locale.
*
@ -386,6 +346,117 @@ class DynamicPage extends Model implements TranslatableModel
: $slug;
}
// * MEILISEARCH
/**
* Get model's setting to apply on scout search (meilisearch).
*
* @var array
*/
public static $searchSettings = [
'filterableAttributes' => ['status'],
'sortableAttributes' => ['status']
];
/**
* Get fields that we want to keep in the current locale.
*
* @return array.
*/
public static function searchTransFields(): array
{
$currentLocale = app()->getLocale();
return [
"title_$currentLocale",
"slug_$currentLocale",
"content_$currentLocale",
];
}
/**
* Get enum status of the model.
*
* @return integer
*/
public static function searchStatusEnum(): int
{
return PageStatusEnum::published->value;
}
/**
* Get front route.
*
* @param string|null $idKey
* @return string
*/
public static function searchRouteName(string|null $idKey): string
{
$currentLocale = app()->getLocale();
return "front.dynamic-pages.$idKey.$currentLocale";
}
/**
* Get model identificable field.
*
* @return string
*/
public static function searchMainField(): string
{
return 'title';
}
/**
* Get fields that we want to keep in the current locale.
*
* @param string $currentLocale
* @return array
*/
public static function searchableTransFields(string $currentLocale): array
{
return [
"title_$currentLocale",
"slug_$currentLocale",
"content_$currentLocale",
];
}
/**
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
$locales = config('laravellocalization.supportedLocales');
$data = [
'id' => $this->id,
'id_key' => $this->id_key,
'status' => $this->status->value,
];
foreach ($locales as $locale => $_) {
$data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null;
$data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null;
$content = $this->hasTranslation('content', $locale) ? strip_tags(collect($this->getTranslation('content', $locale))
->flatten()
->filter(fn($value, $key) =>
is_string($value) &&
!empty($value) &&
!is_numeric($value) &&
!in_array($key, ['order', 'id']) &&
!str_starts_with($key, 'image_') &&
!preg_match('/storage.*\.(?:png|jpe?g|gif|pdf|webp)/i', $value)
)
->values()
->implode(' ')) : null;
$data["content_$locale"] = $content;
}
return $data;
}
// * RELATIONSHIPS
/**

View file

@ -6,9 +6,7 @@ use App\Contracts\TranslatableModel;
use App\Enums\News\NewsStatusEnum;
use App\Helpers\TranslationHelper;
use App\Models\NewsTag;
use App\Models\SearchIndex;
use App\Traits\Models\HasCache;
use App\Traits\Models\HasMeilisearchIndex;
use App\Traits\Models\HasTranslations;
use App\Traits\Models\HasUwilImages;
use Carbon\Carbon;
@ -19,6 +17,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;
use Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
@ -50,7 +49,7 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
use HasUwilImages {
HasUwilImages::inertiaFill as traitInertiaFill;
}
use HasMeilisearchIndex;
use Searchable;
/**
* Get the route key for the model.
@ -295,9 +294,9 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
/**
* Get data related to the first category of this news item.
*
* @return NewsTag|null
* @return \App\Models\NewsTag|null
*/
public function getFirstTagDataAttribute(): ?NewsTag
public function getFirstTagDataAttribute(): ?\App\Models\NewsTag
{
if (empty($this->tags) || empty($this->tags[0])) {
return null;
@ -320,29 +319,6 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
TranslationHelper::validateFallbackTranslations($model);
}
/**
* Set value of meilisearch indexes.
*
* @return \App\Models\SearchIndex|null
*/
public function toSearchDocument(): ?\App\Models\SearchIndex
{
$locale = app()->getLocale();
// Keep only published models.
if (!$this->status->equals(NewsStatusEnum::published) || !$this->hasTranslation('slug', $locale)) {
return null;
}
return new SearchIndex([
'type' => Str::snake(class_basename($this)),
'model_id' => $this->getKey(),
'slug' => $this->getTranslation('slug', $locale),
'title' => $this->getTranslation('title', $locale),
'content' => strip_tags($this->getTranslation('content', $locale)),
]);
}
/**
* Get the url to access a specific resource.
*
@ -358,6 +334,105 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
return route('front.news.show', $targetModel);
}
// * MEILISEARCH
/**
* Get model's setting to apply on scout search (meilisearch).
*
* @var array
*/
public static $searchSettings = [
'filterableAttributes' => ['status'],
'sortableAttributes' => ['status']
];
/**
* Get fields that we want to keep in the current locale.
*
* @param string $currentLocale
* @return array
*/
public static function searchTransFields($currentLocale): array
{
return [
"title_$currentLocale",
"slug_$currentLocale",
"content_$currentLocale",
];
}
/**
* Get enum status of the model.
*
* @return integer
*/
public static function searchStatusEnum(): int
{
return NewsStatusEnum::published->value;
}
/**
* Get front route.
*
* @return string
*/
public static function searchRouteName(): string
{
return 'front.news.show';
}
/**
* Get model identificable field.
*
* @return string
*/
public static function searchMainField(): string
{
return 'title';
}
/**
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
$locales = config('laravellocalization.supportedLocales');
$data = [
'id' => $this->id,
'status' => $this->status->value,
];
foreach ($locales as $locale => $_) {
$data["title_$locale"] = $this->hasTranslation('title', $locale) ? $this->getTranslation('title', $locale) : null;
$data["slug_$locale"] = $this->hasTranslation('slug', $locale) ? $this->getTranslation('slug', $locale) : null;
$data["content_$locale"] = $this->hasTranslation('content', $locale) ? strip_tags($this->getTranslation('content', $locale)) : null;
}
return $data;
}
/**
* Get all published news by category.
*
* @param string $category
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getPublishedNewsByCategoryInCurrentLocale(string $category)
{
$locale = App::getLocale();
return News::getModelsCached()
->where('status', NewsStatusEnum::published)
->filter(function ($news) use ($category, $locale) {
return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains(
fn ($cat) => $cat->slug === $category
);
});
}
// * RELATIONSHIPS
/**
@ -391,24 +466,4 @@ class News extends Model implements TranslatableModel, LocalizedUrlRoutable
'newsable_id'
)->withTimestamps();
}
/**
* Get all published news by category.
*
* @param string $category
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getPublishedNewsByCategoryInCurrentLocale(string $category)
{
$locale = App::getLocale();
return News::getModelsCached()
->where('status', NewsStatusEnum::published)
->filter(function ($news) use ($category, $locale) {
return !empty($news->getTranslation('slug', $locale, false)) && $news->categories->contains(
fn ($cat) => $cat->slug === $category
);
});
}
}

View file

@ -11,7 +11,6 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
* @property int $news_id News focused.
@ -61,9 +60,9 @@ class NewsTag extends Model implements TranslatableModel
/**
* Relation to Document
*
* @return BelongsToMany
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function news(): BelongsToMany
public function news(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->morphToMany(
News::class,

View file

@ -1,152 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
use Illuminate\Support\Str;
class SearchIndex extends Model
{
use Searchable;
/** @var string|null $table */
protected $table = null;
/** @var boolean $timestamps */
public $timestamps = false;
/** @var array $guarded */
protected $guarded = [];
// * METHODS
/**
* Unique name of the Meilisearch index.
*
* @return string
*/
public function searchableAs(): string
{
return config('scout.prefix') . app()->getLocale();
}
/**
* Unique primary key.
*
* @return string
*/
public function getScoutKey(): mixed
{
return "{$this->type}_{$this->model_id}";
}
/**
* Indexed data.
*
* @return array
*/
public function toSearchableArray(): array
{
return [
'id' => $this->getScoutKey(),
'type' => $this->type,
'model_id' => $this->model_id,
'id_key' => $this->id_key ?? null,
'slug' => $this->slug,
'title' => $this->title,
'content' => $this->content,
];
}
/**
* Highlights all search terms in a text.
*
* @param string $text
* @param string $searchTerm
* @return string
*/
public static function highlightTerms(string $text, string $searchTerm, int $contextLength = 150): string
{
if (trim($searchTerm) === '') {
return $text;
}
// Clean terms list.
$words = preg_split('/\s+/', $searchTerm, -1, PREG_SPLIT_NO_EMPTY);
if (empty($words)) {
return $text;
}
$fullText = strip_tags($text);
$textLength = strlen($fullText);
$ranges = [];
// Collection of relevant ranges around each word.
foreach ($words as $word) {
$pattern = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
// Check if current word match exactly with terms.
if (preg_match_all($pattern, $fullText, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
$matchPos = $match[1];
$matchLen = strlen($match[0]);
$ranges[] = [
'start' => max(0, $matchPos - $contextLength),
'end' => min($textLength, $matchPos + $matchLen + $contextLength),
];
}
}
}
// Return the entire text if there isn't matches.
if (empty($ranges)) {
return $text;
}
// Merging overlapping intervals.
usort($ranges, fn($a, $b) => $a['start'] <=> $b['start']);
$merged = [];
foreach ($ranges as $r) {
if (empty($merged) || $r['start'] > $merged[array_key_last($merged)]['end']) {
$merged[] = $r;
} else {
$merged[array_key_last($merged)]['end'] = max(
$merged[array_key_last($merged)]['end'],
$r['end']
);
}
}
$snippets = [];
foreach ($merged as $r) {
$snippet = substr($fullText, $r['start'], $r['end'] - $r['start']);
// Cut cleanly without breaking the words
if ($r['start'] > 0) {
$snippet = preg_replace('/^\S*\s/', '…', $snippet, 1);
}
if ($r['end'] < $textLength) {
$snippet = preg_replace('/\s\S*$/', '…', $snippet, 1);
}
// Highlighting searched words
foreach ($words as $word) {
$pattern = '/(?<!\w)' . preg_quote($word, '/') . '(?!\w)/iu';
$snippet = preg_replace(
$pattern,
'<span class="search-highlight">$0</span>',
$snippet
);
}
$snippets[] = trim($snippet);
if (count($snippets) >= 3) break;
}
$result = implode('… ', $snippets);
$result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result);
return trim($result);
}
}

View file

@ -19,6 +19,17 @@ class DocumentCategoryPolicy
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can view trash models.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function viewTrash(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can view the model.
*
@ -79,11 +90,21 @@ class DocumentCategoryPolicy
* Determine whether the user can delete the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @param \App\Models\News $news
* @return boolean
*/
public function delete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can force delete the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function forceDelete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
}

View file

@ -19,6 +19,17 @@ class DocumentTagPolicy
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can view trash models.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function viewTrash(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can view the model.
*
@ -79,11 +90,21 @@ class DocumentTagPolicy
* Determine whether the user can delete the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @param \App\Models\News $news
* @return boolean
*/
public function delete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
/**
* Determine whether the user can force delete the model.
*
* @param \Illuminate\Database\Eloquent\Model $authModel
* @return boolean
*/
public function forceDelete(Model $authModel): bool
{
return UserStaticRules::atLeastRole($authModel, RoleEnum::admin);
}
}

View file

@ -1,113 +0,0 @@
<?php
namespace App\Traits\Models;
use App\Models\SearchIndex;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
/**
* If there is a static function in a trait (named boot[TraitName]),
* it will be executed as the boot() function would on an Eloquent model.
* Futhermore, event in the Model observer doesn't erase actual events in the model,
* but adds them.
*/
trait HasMeilisearchIndex
{
/**
* Perform any actions required after the model boots.
*
* @return void
*/
public static function bootHasMeilisearchIndex(): void
{
$keyPrefix = Str::snake(class_basename(static::class));
$usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive(static::class));
// Event executed avec saving a model.
static::saved(function ($model) use ($keyPrefix, $usesSoftDeletes) {
// Update ms index depending on status which is a global field non translatable.
$statusChanged = $model->wasChanged('status');
$originalLocale = app()->getLocale();
$locales = $statusChanged
? array_keys(LaravelLocalization::getSupportedLocales())
: [$originalLocale];
// Loop on all locales to update indexes when global fields like status is updated,
// Otherwise, on current locale.
collect($locales)->map(function($locale) use ($keyPrefix, $model, $usesSoftDeletes) {
// Set the locale to alter the right ms index.
app()->setLocale($locale);
$indexId = "{$keyPrefix}_{$model->getKey()}";
// Remove model from meilisearch index.
if ($usesSoftDeletes && method_exists($model, 'trashed') && $model->trashed()) {
SearchIndex::make([
'type' => $keyPrefix,
'model_id' => $model->getKey(),
])->unsearchable();
return;
}
$msIndex = $model->toSearchDocument();
// Add model to the meilisearch index if conditions are true, remove from it if not.
if ($msIndex) {
$msIndex->searchable();
} else {
SearchIndex::make([
'type' => $keyPrefix,
'model_id' => $model->getKey(),
])->unsearchable();
}
});
// Reset the locale with the original.
app()->setLocale($originalLocale);
});
static::deleted(function ($model) use ($keyPrefix) {
$originalLocale = app()->getLocale();
$locales = array_keys(LaravelLocalization::getSupportedLocales());
// Loop on all locales to update indexes when model is deleted (softdeleted or not).
collect($locales)->map(function($locale) use ($keyPrefix, $model) {
// Set the locale to alter the right ms index.
app()->setLocale($locale);
$indexId = "{$keyPrefix}_{$model->getKey()}";
// Remove model from meilisearch index.
SearchIndex::make([
'type' => $keyPrefix,
'model_id' => $model->getKey(),
])->unsearchable();
});
// Reset the locale with the original.
app()->setLocale($originalLocale);
});
if ($usesSoftDeletes) {
static::restored(function ($model) {
$originalLocale = app()->getLocale();
$locales = array_keys(LaravelLocalization::getSupportedLocales());
// Loop on all locales to update indexes when model is restored.
collect($locales)->map(function($locale) use ($model) {
// Set the locale to alter the right ms index.
app()->setLocale($locale);
// Add model to the meilisearch index if conditions are true.
$msIndex = $model->toSearchDocument();
if ($msIndex) {
$msIndex->searchable();
}
});
// Reset the locale with the original.
app()->setLocale($originalLocale);
});
}
}
}

View file

@ -7,22 +7,6 @@ use Monolog\Processor\PsrLogMessageProcessor;
return [
'stdout' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDOUT_FORMATTER'),
'with' => [
'stream' => 'php://stdout',
],
],
'k8s' => [
'driver' => 'stack',
'channels' => ['daily', 'stdout'],
'ignore_exceptions' => false,
],
/**
*--------------------------------------------------------------------------
@ -144,6 +128,22 @@ return [
'path' => storage_path('logs/laravel.log'),
],
'stdout' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDOUT_FORMATTER'),
'with' => [
'stream' => 'php://stdout',
],
],
'k8s' => [
'driver' => 'stack',
'channels' => ['daily', 'stdout'],
'ignore_exceptions' => false,
],
],
];

View file

@ -1,5 +1,6 @@
<?php
use App\Models\Document;
use App\Models\DynamicPage;
use App\Models\News;
@ -87,7 +88,7 @@ return [
|
*/
'soft_delete' => true,
'soft_delete' => false,
/*
|--------------------------------------------------------------------------
@ -105,6 +106,10 @@ return [
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => env('MEILISEARCH_KEY'),
'index-settings' => [],
'index-settings' => [
DynamicPage::class => DynamicPage::$searchSettings,
Document::class => Document::$searchSettings,
News::class => News::$searchSettings,
],
],
];

View file

@ -0,0 +1,29 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\CompanyActivity>
*/
class CompanyActivityFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
"name" => $this->faker->unique()->words(
$this->faker->numberBetween(3, 4),
true
),
"color" => $this->faker->hexColor(),
"published" => $this->faker->boolean(50),
];
}
}

View file

@ -8,6 +8,9 @@ use App\Models\CompanySector;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Company>
*/
class CompanyFactory extends Factory
{
/**
@ -21,7 +24,7 @@ class CompanyFactory extends Factory
$companySectorModel = fake()->randomElement(CompanySector::all());
return [
'name' => fake()->company(),
'name' => fake()->unique()->company(),
'responsable' => fake()->name(),
'informations' => fake()->text(200),
'latitude' => fake()->latitude(),

View file

@ -0,0 +1,28 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\CompanySector>
*/
class CompanySectorFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
"name" => $this->faker->unique()->words(
$this->faker->numberBetween(3, 4),
true
),
"published" => $this->faker->boolean(50),
];
}
}

View file

@ -3,6 +3,7 @@
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\DocumentCategory>
@ -16,8 +17,12 @@ class DocumentCategoryFactory extends Factory
*/
public function definition(): array
{
$name = $this->faker->unique()->word();
$slug = Str::slug($name);
return [
'name' => $this->faker->unique()->word(),
'name' => $name,
'slug' => $slug,
];
}
}

View file

@ -10,42 +10,23 @@ use App\Models\DocumentTag;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Document>
*/
class DocumentFactory extends Factory
{
protected $model = Document::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$title = $this->faker->sentence(3);
return [
'name' => $title,
'path' => 'documents/' . Str::slug($title) . '.pdf',
'exercice' => $this->faker->randomElement(YearsEnum::cases()),
'status' => $this->faker->randomElement(DocumentStatusEnum::cases()),
'published_at' => $this->faker->dateTimeBetween('-1 month', 'now'),
'unpublished_at' => null,
'name' => $this->faker->sentence(3),
'exercice' => $this->faker->randomElement(YearsEnum::cases()),
'status' => $this->faker->randomElement(DocumentStatusEnum::cases()),
'published_at' => $this->faker->dateTimeBetween('-1 month', 'now'),
];
}
/**
* Ajoute automatiquement des tags à un document créé.
*/
public function withTags(int $count = 3): static
{
return $this->afterCreating(function (Document $document) use ($count) {
$tags = DocumentTag::factory()->count($count)->create();
$document->tags()->sync($tags->pluck('id'));
});
}
/**
* Ajoute automatiquement des tags à un document créé.
*/
public function withCategories(int $count = 3): static
{
return $this->afterCreating(function (Document $document) use ($count) {
$cats = DocumentCategory::factory()->count($count)->create();
$document->categories()->sync($cats->pluck('id'));
});
}
}

View file

@ -2,17 +2,27 @@
namespace Database\Factories;
use App\Models\DocumentTag;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\DocumentTag>
*/
class DocumentTagFactory extends Factory
{
protected $model = DocumentTag::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$name = $this->faker->unique()->word();
$slug = Str::slug($name);
return [
'name' => $this->faker->unique()->word(),
'name' => $name,
'slug' => $slug,
];
}
}

View file

@ -2,6 +2,7 @@
namespace Database\Factories;
use Carbon\Carbon;
use App\Enums\DynamicFieldTypes;
use App\Enums\DynamicPages\PageStatusEnum;
use App\Models\DynamicPage;
@ -9,6 +10,9 @@ use App\Models\PageConfig;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\DynamicPage>
*/
class DynamicPageFactory extends Factory
{
/**
@ -19,18 +23,21 @@ class DynamicPageFactory extends Factory
public function definition(): array
{
$title = fake()->unique()->word();
$slug = Str::slug($title);
$configModel = fake()->randomElement(PageConfig::all());
$status = fake()->randomElement(PageStatusEnum::cases());
$pageHome = DynamicPage::query()->where('isRoot', true)->firstOrFail();
return [
'id_key' => Str::slug($title),
'title' => $title,
'slug' => Str::slug($title),
'content' => self::getDataFromConfig($configModel),
'page_id' => null,
'config_id' => $configModel->getKey(),
'status' => $status,
'isLocked' => fake()->boolean(50),
'id_key' => $slug,
'title' => $title,
'slug' => $slug,
'content' => self::getDataFromConfig($configModel),
'page_id' => $pageHome->getKey(),
'config_id' => $configModel->getKey(),
'status' => $status,
'isLocked' => fake()->boolean(25),
'deleted_at' => fake()->boolean(25) ? Carbon::now() : null,
];
}

View file

@ -3,9 +3,10 @@
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\News>
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\NewsCategory>
*/
class NewsCategoryFactory extends Factory
{
@ -16,9 +17,12 @@ class NewsCategoryFactory extends Factory
*/
public function definition(): array
{
$name = $this->faker->unique()->word();
$slug = Str::slug($name);
return [
"name" => $this->faker->unique()->word(),
"slug" => $this->faker->unique()->word(),
"name" => $name,
"slug" => $slug,
];
}
}

View file

@ -28,7 +28,6 @@ class NewsFactory extends Factory
'status' => collect(NewsStatusEnum::cases())->random(),
'picture_alt' => fake()->sentence(6, true),
'picture_title' => fake()->sentence(6, true),
'picture' => 'temp.jpg',
];
}
}

View file

@ -3,6 +3,7 @@
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\NewsTag>
@ -16,10 +17,13 @@ class NewsTagFactory extends Factory
*/
public function definition(): array
{
$name = $this->faker->unique()->word();
$slug = Str::slug($name);
return [
"name" => $this->faker->unique()->word(),
"slug" => $this->faker->unique()->word(),
"color" => "#fff"
"name" => $name,
"slug" => $slug,
"color" => $this->faker->hexColor(),
];
}
}

View file

@ -7,12 +7,15 @@ use App\Models\PageConfig;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\PageConfig>
*/
class PageConfigFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
* @return array<string, mixed>
*/
public function definition(): array
{
@ -43,7 +46,6 @@ class PageConfigFactory extends Factory
],
];
}
return $data;
}
}

View file

@ -14,196 +14,198 @@ return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
app()->setLocale('fr');
$jsonPath = Storage::disk('local')->get('document.json');
if (file_exists($jsonPath)) {
app()->setLocale('fr');
$json = Storage::disk('local')->get('document.json');
$data = json_decode($json, true);
$logFile = public_path('documents-error.log');
file_put_contents($logFile, '');
$groups = [];
$json = Storage::disk('local')->get('document.json');
$data = json_decode($json, true);
$logFile = public_path('documents-error.log');
file_put_contents($logFile, '');
$groups = [];
foreach ($data['documents'] as $doc) {
$trid = $doc['translation_group_id'];
$lang = $doc['language'];
foreach ($data['documents'] as $doc) {
$trid = $doc['translation_group_id'];
$lang = $doc['language'];
if (!isset($groups[$trid])) {
$groups[$trid] = [];
}
// Si une langue est déjà présente : doublon de langue dans un groupe
if (isset($groups[$trid][$lang])) {
file_put_contents(
$logFile,
"❌ Doublon de langue '$lang' pour TRID $trid. IDs : " .
$groups[$trid][$lang]['ID'] . " et " . $doc['ID'] . "\n",
FILE_APPEND
);
}
$groups[$trid][$lang] = $doc;
// Vérification n°1 : plus de 2 entrées dans un TRID
if (count($groups[$trid]) > 2) {
$ids = array_column($groups[$trid], 'ID');
file_put_contents(
$logFile,
"❌ Plus de 2 entrées pour TRID $trid. IDs : " . implode(',', $ids) . "\n",
FILE_APPEND
);
}
// Vérification n°2 : si on a 2 entrées mais même langue
if (count($groups[$trid]) === 2) {
$langs = array_keys($groups[$trid]);
if ($langs[0] === $langs[1]) {
$ids = array_column($groups[$trid], 'ID');
if (!isset($groups[$trid])) {
$groups[$trid] = [];
}
// Si une langue est déjà présente : doublon de langue dans un groupe.
if (isset($groups[$trid][$lang])) {
file_put_contents(
$logFile,
"❌ 2 entrées mais même langue '$langs[0]' pour TRID $trid. IDs : "
. implode(',', $ids) . "\n",
"❌ Doublon de langue '$lang' pour TRID $trid. IDs : " .
$groups[$trid][$lang]['ID'] . " et " . $doc['ID'] . "\n",
FILE_APPEND
);
}
}
}
foreach ($groups as $trid => $langs) {
if (!isset($langs['fr'])) {
// Cas anormal : pas de FR → log
file_put_contents(
$logFile,
"❌ Pas de FR pour TRID $trid. IDs trouvés : " . json_encode(array_column($langs, 'ID')) . "\n",
FILE_APPEND
);
// continue;
}
$financeDocument = new Document();
$hasFrCats = false;
$hasFrTags = false;
$hasPublished_at = false;
$hasStatus = false;
$hasFrExercice = false;
// ------------------------------
// 2) Enregistrer la version FR
// ------------------------------
if (isset($langs['fr'])) {
$fr = $langs['fr'];
$hasFrExercice = true;
$financeDocument->exercice = $this->getExerciceEnumFromOldValues($fr, 'fr');
$financeDocument->name = $fr['post_title'];
$financeDocument->published_at = $fr['post_date'];
$hasPublished_at = true;
$hasStatus = true;
$financeDocument->status = $fr['post_status'] === "publish" ?
DocumentStatusEnum::published->value :
DocumentStatusEnum::unpublished->value;
$financeDocument->path = FileHelper::storeFile($financeDocument, $this->replaceUrl($fr));
if (!$this->replaceUrl($fr)) {
$financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($fr['post_content']);
$financeDocument->is_issuu = true;
$groups[$trid][$lang] = $doc;
// Vérification n°1 : plus de 2 entrées dans un TRID.
if (count($groups[$trid]) > 2) {
$ids = array_column($groups[$trid], 'ID');
file_put_contents(
$logFile,
"❌ Plus de 2 entrées pour TRID $trid. IDs : " . implode(',', $ids) . "\n",
FILE_APPEND
);
}
// jusque la ça enregistre un element
// il faut maintenant récupérer la valeur de translation_group_id
// si un autre élément dans la liste à le même translation_group_id vérifier que son language est bien "en"
// si c'est le cas alors on app()->setLocale('en')
// puis on réenregistre les nouvelles valeurs translatable :
// $financeDocument->name = $doc['post_title'];
// $financeDocument->path = $localeUrl;
// et on save
// si le langage est autre chose on log dans un fichier (dans public/documents-error.log)
// dans le fichier de log on va écrire à chaque fois l'id du post "ID" fr + en s'il y a + celui qui serait un autre fr, en ou autre pour que je puisse les retrouver
// et on notera plus ou moins l'erreur dont il s'agit
$financeDocument->saveQuietly();
$cats = $this->findCategoryByOldSlug($fr, 'fr');
if ($cats) {
$financeDocument->categories()->sync($cats);
$hasFrCats = true;
}
$tags = $this->findTagsByOldSlug($fr, 'fr');
if ($tags) {
$financeDocument->tags()->sync($tags);
$hasFrTags = true;
// Vérification n°2 : si on a 2 entrées mais même langue.
if (count($groups[$trid]) === 2) {
$langs = array_keys($groups[$trid]);
if ($langs[0] === $langs[1]) {
$ids = array_column($groups[$trid], 'ID');
file_put_contents(
$logFile,
"❌ 2 entrées mais même langue '$langs[0]' pour TRID $trid. IDs : "
. implode(',', $ids) . "\n",
FILE_APPEND
);
}
}
}
if (isset($langs['en'])) {
$en = $langs['en'];
app()->setLocale('en');
if (!$hasPublished_at) {
$financeDocument->published_at = $en['post_date'];
foreach ($groups as $trid => $langs) {
if (!isset($langs['fr'])) {
// Cas anormal : pas de FR → log.
file_put_contents(
$logFile,
"❌ Pas de FR pour TRID $trid. IDs trouvés : " . json_encode(array_column($langs, 'ID')) . "\n",
FILE_APPEND
);
// continue;
}
if (!$hasStatus) {
$financeDocument->status = $en['post_status'] === "publish" ?
$financeDocument = new Document();
$hasFrCats = false;
$hasFrTags = false;
$hasPublished_at = false;
$hasStatus = false;
$hasFrExercice = false;
// ------------------------------
// 2) Enregistrer la version FR
// ------------------------------
if (isset($langs['fr'])) {
$fr = $langs['fr'];
$hasFrExercice = true;
$financeDocument->exercice = $this->getExerciceEnumFromOldValues($fr, 'fr');
$financeDocument->name = $fr['post_title'];
$financeDocument->published_at = $fr['post_date'];
$hasPublished_at = true;
$hasStatus = true;
$financeDocument->status = $fr['post_status'] === "publish" ?
DocumentStatusEnum::published->value :
DocumentStatusEnum::unpublished->value;
$financeDocument->path = FileHelper::storeFile($financeDocument, $this->replaceUrl($fr));
if (!$this->replaceUrl($fr)) {
$financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($fr['post_content']);
$financeDocument->is_issuu = true;
}
// jusque la ça enregistre un element
// il faut maintenant récupérer la valeur de translation_group_id
// si un autre élément dans la liste à le même translation_group_id vérifier que son language est bien "en"
// si c'est le cas alors on app()->setLocale('en')
// puis on réenregistre les nouvelles valeurs translatable :
// $financeDocument->name = $doc['post_title'];
// $financeDocument->path = $localeUrl;
// et on save
// si le langage est autre chose on log dans un fichier (dans public/documents-error.log)
// dans le fichier de log on va écrire à chaque fois l'id du post "ID" fr + en s'il y a + celui qui serait un autre fr, en ou autre pour que je puisse les retrouver
// et on notera plus ou moins l'erreur dont il s'agit
$financeDocument->saveQuietly();
$cats = $this->findCategoryByOldSlug($fr, 'fr');
if ($cats) {
$financeDocument->categories()->sync($cats);
$hasFrCats = true;
}
$tags = $this->findTagsByOldSlug($fr, 'fr');
if ($tags) {
$financeDocument->tags()->sync($tags);
$hasFrTags = true;
}
}
$financeDocument->name = $en['post_title'];
if (isset($langs['en'])) {
$en = $langs['en'];
app()->setLocale('en');
if ($hasFrExercice) {
$financeDocument->exercice = $this->getExerciceEnumFromOldValues($en, 'en');
}
if (!$hasPublished_at) {
$financeDocument->published_at = $en['post_date'];
}
$sourceUrl = $this->replaceUrl($en);
if (!$hasStatus) {
$financeDocument->status = $en['post_status'] === "publish" ?
DocumentStatusEnum::published->value :
DocumentStatusEnum::unpublished->value;
}
$financeDocument->name = $en['post_title'];
if (empty($sourceUrl)) {
if ($hasFrExercice) {
$financeDocument->exercice = $this->getExerciceEnumFromOldValues($en, 'en');
}
$sourceUrl = $this->replaceUrl($en);
if (empty($sourceUrl)) {
file_put_contents(
$logFile,
"❌ URL EN vide — TRID $trid — ID {$en['ID']}\n",
FILE_APPEND
);
}
$financeDocument->path = FileHelper::storeFile($financeDocument, $sourceUrl);
if (!$this->replaceUrl($en)) {
$financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($en['post_content']);
$financeDocument->is_issuu = true;
}
$financeDocument->saveQuietly();
if (!$hasFrCats) {
$cats = $this->findCategoryByOldSlug($en, 'en');
$financeDocument->categories()->sync($cats);
}
if (!$hasFrTags) {
$tags = $this->findTagsByOldSlug($fr, 'en');
$financeDocument->tags()->sync($tags);
}
app()->setLocale('fr');
} else {
// ------------------------------
// 4) Cas : pas de traduction EN → log
// ------------------------------
$id = isset($langs['fr']) ? $langs['fr']['ID'] : "inconnu";
file_put_contents(
$logFile,
"❌ URL EN vide — TRID $trid — ID {$en['ID']}\n",
"⚠️ Pas de traduction EN pour TRID $trid. ID FR: {$id}\n",
FILE_APPEND
);
}
$financeDocument->path = FileHelper::storeFile($financeDocument, $sourceUrl);
if (!$this->replaceUrl($en)) {
$financeDocument->issuu_path = DocumentHelper::extractDocumentFromIssuIframe($en['post_content']);
$financeDocument->is_issuu = true;
}
$financeDocument->saveQuietly();
if (!$hasFrCats) {
$cats = $this->findCategoryByOldSlug($en, 'en');
$financeDocument->categories()->sync($cats);
}
if (!$hasFrTags) {
$tags = $this->findTagsByOldSlug($fr, 'en');
$financeDocument->tags()->sync($tags);
}
app()->setLocale('fr');
} else {
// ------------------------------
// 4) Cas : pas de traduction EN → log
// 5) Vérifier si langues inconnues
// ------------------------------
$id = isset($langs['fr']) ? $langs['fr']['ID'] : "inconnu";
file_put_contents(
$logFile,
"⚠️ Pas de traduction EN pour TRID $trid. ID FR: {$id}\n",
FILE_APPEND
);
}
// ------------------------------
// 5) Vérifier si langues inconnues
// ------------------------------
foreach ($langs as $langCode => $doc) {
if (!in_array($langCode, ['fr', 'en'])) {
foreach ($langs as $langCode => $doc) {
if (!in_array($langCode, ['fr', 'en'])) {
file_put_contents(
$logFile,
"⚠️ Langue inattendue '$langCode' pour TRID $trid. ID: {$doc['ID']}\n",
FILE_APPEND
);
file_put_contents(
$logFile,
"⚠️ Langue inattendue '$langCode' pour TRID $trid. ID: {$doc['ID']}\n",
FILE_APPEND
);
}
}
}
}
@ -218,7 +220,6 @@ return new class extends Migration
return null;
}
private function findCategoryByOldSlug(mixed $doc, string $locale): array
{
if (empty($doc['category_slugs'])) {
@ -272,8 +273,6 @@ return new class extends Migration
return null;
}
return collect(YearsEnum::cases())
->first(
fn(YearsEnum $year) =>
@ -281,7 +280,6 @@ return new class extends Migration
);
}
// SELECT
// p.ID,
// MAX(p.post_title) AS post_title,
@ -360,6 +358,8 @@ return new class extends Migration
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{

View file

@ -0,0 +1,312 @@
<?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::table('companies', function (Blueprint $table) {
$table->id()->comment('Primary key of the company.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the company was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the company was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the company was deleted.')->change();
});
Schema::table('company_activities', function (Blueprint $table) {
$table->id()->comment('Primary key of the company activity.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the company activity was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the company activity was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the company activity was deleted.')->change();
});
Schema::table('company_sectors', function (Blueprint $table) {
$table->id()->comment('Primary key of the company sector.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the company sector was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the company sector was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the company sector was deleted.')->change();
});
Schema::table('contact_counts', function (Blueprint $table) {
$table->id()->comment('Primary key of the counter.')->change();
$table->integer('submissions')->comment('Form submission counter.')->default(0)->change();
$table->unsignedTinyInteger('type')->comment('Contact form type.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the counter was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the counter was updated.')->change();
});
Schema::table('documentables', function (Blueprint $table) {
$table->id()->comment('Primary key of the document relation.')->change();
$table->unsignedBigInteger('document_id')->comment('Primary key of the document.')->change();
$table->unsignedBigInteger('documentable_id')->comment('Primary key of the associated model.')->change();
$table->string('documentable_type')->comment('Model associated.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the document relation was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the document relation was updated.')->change();
});
Schema::table('documents', function (Blueprint $table) {
$table->id()->comment('Primary key of the document.')->change();
$table->text('name')->comment('Name of the document.')->change();
$table->text('path')->nullable()->comment('Path of the document.')->after('name')->change();
$table->text('issuu_path')->nullable()->comment('Path of the issuu document.')->after('path')->change();
$table->unsignedTinyInteger('exercice')->nullable()->comment('Exercice of the document.')->change();
$table->unsignedTinyInteger('status')->comment('Status of the document.')->change();
$table->boolean('is_issuu')->default(false)->comment('Is an issuu document or not.')->change();
$table->timestamp('published_at')->nullable()->comment('Date on which the document relation was published.')->change();
$table->timestamp('unpublished_at')->nullable()->comment('Date on which the document relation was unpublished.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the document relation was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the document relation was updated.')->change();
});
Schema::table('document_categories', function (Blueprint $table) {
$table->id()->comment('Primary key of the document category.')->change();
$table->text('name')->comment('Name of the document category.')->change();
$table->text('slug')->comment('Slug of the document category.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the document category was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the document category was updated.')->change();
});
Schema::table('document_tags', function (Blueprint $table) {
$table->id()->comment('Primary key of the document tag.')->change();
$table->text('name')->comment('Name of the document tag.')->change();
$table->text('slug')->comment('Slug of the document tag.')->change();
$table->string('color')->default("#ff4e4e")->after('slug')->comment('Color of the document tag.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the document tag was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the document tag was updated.')->change();
});
Schema::table('dynamic_pages', function (Blueprint $table) {
$table->id()->comment('Primary key of the dynamic page.')->change();
$table->string('id_key')->nullable()->comment('Unique identification key of the dynamic page.')->change();
$table->string('title')->comment('Title of the dynamic page.')->change();
$table->string('slug')->unique()->comment('Slug of the dynamic page.')->change();
$table->json('content')->nullable()->comment('Content of the dynamic page.')->change();
$table->unsignedBigInteger('config_id')->nullable()->comment('Associated configuration.')->change();
$table->unsignedBigInteger('page_id')->nullable()->comment('Associated page.')->change();
$table->unsignedTinyInteger('status')->comment('Status of the dynamic page.')->change();
$table->boolean('isLocked')->default(false)->comment('Locked status of the dynamic page.')->change();
$table->boolean('isRoot')->default(false)->comment('Root status of the dynamic page.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the dynamic page was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the dynamic page was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the dynamic page was deleted.')->change();
});
Schema::table('news', function (Blueprint $table) {
$table->id()->comment('Primary key of the news.')->change();
$table->text('seo_title')->comment('SEO title of the news.')->change();
$table->text('seo_description')->comment('SEO description of the news.')->change();
$table->text('title')->comment('Title of the news.')->change();
$table->string('picture')->comment('Picture of the news.')->change();
$table->text('picture_alt')->comment('Alt attribute of the picture.')->change();
$table->text('picture_title')->comment('Title attribute of the picture.')->change();
$table->mediumText('content')->comment('Content of the news.')->change();
$table->boolean('inverted')->default(false)->comment('Position of the content.')->change();
$table->text('vimeo_id')->nullable()->comment('Vimeo id associated.')->change();
$table->unsignedTinyInteger('status')->comment('Status of the news.')->change();
$table->timestamp('published_at')->nullable()->comment('Date on which the news was published.')->change();
$table->timestamp('unpublished_at')->nullable()->comment('Date on which the news was unpublished.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the news was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the news was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the news was deleted.')->after('updated_at')->change();
});
Schema::table('newsables', function (Blueprint $table) {
$table->id()->comment('Primary key of the news relation.')->change();
$table->unsignedBigInteger('news_id')->comment('Primary key of the news.')->change();
$table->unsignedBigInteger('newsable_id')->comment('Primary key of the associated model.')->change();
$table->string('newsable_type')->comment('Model associated.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the news relation was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the news relation was updated.')->change();
});
Schema::table('news_categories', function (Blueprint $table) {
$table->id()->comment('Primary key of the news category.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the news category was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the news category was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the news category was deleted.')->change();
});
Schema::table('news_tags', function (Blueprint $table) {
$table->id()->comment('Primary key of the news tag.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the news tag was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the news tag was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the news tag was deleted.')->after('updated_at')->change();
});
Schema::table('page_configs', function (Blueprint $table) {
$table->id()->comment('Primary key of the configuration.')->change();
$table->string('label')->comment('Label of the configuration.')->change();
$table->string('view')->nullable()->comment('Specific view of the configuration.')->change();
$table->json('config')->comment('Structured data of the configuration.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the configuration was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the configuration was updated.')->change();
$table->timestamp('deleted_at')->nullable()->comment('Date on which the configuration was deleted.')->change();
});
Schema::table('users', function (Blueprint $table) {
$table->id()->comment('Primary key of the user.')->change();
$table->timestamp('created_at')->nullable()->comment('Date on which the user was created.')->change();
$table->timestamp('updated_at')->nullable()->comment('Date on which the user was updated.')->change();
$table->timestamp('last_connection')->nullable()->comment('Date on which the user was connected.')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('companies', function (Blueprint $table) {
$table->id()->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->change();
});
Schema::table('company_activities', function (Blueprint $table) {
$table->id()->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->change();
});
Schema::table('company_sectors', function (Blueprint $table) {
$table->id()->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->change();
});
Schema::table('contact_counts', function (Blueprint $table) {
$table->id()->change();
$table->integer('submissions')->comment('How many contact form have been submitted')->default(0)->change();
$table->unsignedTinyInteger('type')->comment('Enum du type de contact form')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
});
Schema::table('documentables', function (Blueprint $table) {
$table->id()->change();
$table->unsignedBigInteger('document_id')->change();
$table->unsignedBigInteger('documentable_id')->change();
$table->string('documentable_type')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
});
Schema::table('documents', function (Blueprint $table) {
$table->id()->change();
$table->text('name')->comment('Name of the file')->change();
$table->unsignedTinyInteger('exercice')->nullable()->change();
$table->unsignedTinyInteger('status')->comment('Status of the documents')->change();
$table->text('path')->nullable()->comment('Path of the file')->after('status')->change();
$table->boolean('is_issuu')->default(false)->comment('Is the document a Issuu preview')->change();
$table->text('issuu_path')->nullable()->comment('Path of the file in issuu')->after('is_issuu')->change();
$table->timestamp('published_at')->nullable()->comment('Document publishment date.')->change();
$table->timestamp('unpublished_at')->nullable()->comment('Document unpublishment date.')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
});
Schema::table('document_categories', function (Blueprint $table) {
$table->id()->change();
$table->text('name')->comment('Name of the category')->change();
$table->text('slug')->comment('Slug of the category')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
});
Schema::table('document_tags', function (Blueprint $table) {
$table->id()->change();
$table->text('name')->comment('Name of the tag')->change();
$table->text('slug')->comment('Slug of the tag')->change();
$table->string('color')->default("#ff4e4e")->after('slug')->comment('Color of the news category.')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
});
Schema::table('dynamic_pages', function (Blueprint $table) {
$table->id()->change();
$table->string('id_key')->nullable()->comment('Page unique identification key.')->change();
$table->string('title')->comment('Page title.')->change();
$table->string('slug')->unique()->comment('Page slug.')->change();
$table->json('content')->nullable()->comment('Page content.')->change();
$table->unsignedBigInteger('config_id')->nullable()->comment('Page associated configuration.')->change();
$table->unsignedBigInteger('page_id')->nullable()->comment('Page associated page.')->change();
$table->unsignedTinyInteger('status')->comment('Page status.')->change();
$table->boolean('isLocked')->default(false)->comment('Page locked status.')->change();
$table->boolean('isRoot')->default(false)->comment('Page root status.')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->change();
});
Schema::table('news', function (Blueprint $table) {
$table->id()->change();
$table->text('seo_title')->comment('News seo title.')->change();
$table->text('seo_description')->comment('News seo description.')->change();
$table->text('title')->comment('News title.')->change();
$table->string('picture')->comment('News picture.')->change();
$table->text('picture_alt')->comment('Picture alt attribute.')->change();
$table->text('picture_title')->comment('Picture title attribute.')->change();
$table->mediumText('content')->comment('News content.')->change();
$table->text('vimeo_id')->nullable()->comment('Vimeo id associated.')->change();
$table->unsignedTinyInteger('status')->comment('News status.')->change();
$table->boolean('inverted')->default(false)->comment('Content position.')->change();
$table->timestamp('published_at')->nullable()->comment('News corporate publishment date.')->change();
$table->timestamp('unpublished_at')->nullable()->comment('News corporate unpublishment date.')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->after('unpublished_at')->change();
});
Schema::table('newsables', function (Blueprint $table) {
$table->id()->change();
$table->unsignedBigInteger('news_id')->change();
$table->unsignedBigInteger('newsable_id')->change();
$table->string('newsable_type')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
});
Schema::table('news_categories', function (Blueprint $table) {
$table->id()->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->change();
});
Schema::table('news_tags', function (Blueprint $table) {
$table->id()->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->after('updated_at')->change();
});
Schema::table('page_configs', function (Blueprint $table) {
$table->id()->change();
$table->string('label')->comment('Configuration label.')->change();
$table->string('view')->nullable()->comment('Configuration view.')->change();
$table->json('config')->comment('Configuration details.')->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('deleted_at')->nullable()->change();
});
Schema::table('users', function (Blueprint $table) {
$table->id()->change();
$table->timestamp('created_at')->nullable()->change();
$table->timestamp('updated_at')->nullable()->change();
$table->timestamp('last_connection')->nullable()->change();
});
}
};

View file

@ -0,0 +1,38 @@
<?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::table('document_categories', function (Blueprint $table) {
$table->timestamp('deleted_at')->nullable()->comment('Date on which the document category was deleted.');
});
Schema::table('document_tags', function (Blueprint $table) {
$table->timestamp('deleted_at')->nullable()->comment('Date on which the document tag was deleted.');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('document_categories', function (Blueprint $table) {
$table->dropSoftDeletes();
});
Schema::table('document_tags', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
};

View file

@ -0,0 +1,90 @@
<?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::table('company_activities', function (Blueprint $table) {
$table->dropUnique(['name']);
});
Schema::table('company_activities', function (Blueprint $table) {
$table->text('name')->comment('Name of the company activity.')->change();
});
Schema::table('company_sectors', function (Blueprint $table) {
$table->dropUnique(['name']);
});
Schema::table('company_sectors', function (Blueprint $table) {
$table->text('name')->comment('Name of the company sector.')->change();
});
Schema::table('dynamic_pages', function (Blueprint $table) {
$table->dropUnique(['slug']);
});
Schema::table('dynamic_pages', function (Blueprint $table) {
$table->text('title')->comment('Title of the dynamic page.')->change();
$table->text('slug')->comment('Slug of the dynamic page.')->change();
});
Schema::table('news_categories', function (Blueprint $table) {
$table->text('name')->comment('Name of the news category.')->change();
$table->text('slug')->comment('Slug of the news category.')->change();
});
Schema::table('news_tags', function (Blueprint $table) {
$table->text('name')->comment('Name of the news tag.')->change();
$table->text('slug')->comment('Slug of the news tag.')->change();
});
Schema::table('page_configs', function (Blueprint $table) {
$table->dropUnique(['label']);
});
Schema::table('page_configs', function (Blueprint $table) {
$table->text('label')->comment('Label of the configuration.')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('company_activities', function (Blueprint $table) {
$table->string('name')->unique()->comment('Name of the company activity.')->change();
});
Schema::table('company_sectors', function (Blueprint $table) {
$table->string('name')->unique()->comment('Name of the company sector.')->change();
});
Schema::table('dynamic_pages', function (Blueprint $table) {
$table->string('title')->comment('Title of the dynamic page.')->change();
$table->string('slug')->unique()->comment('Slug of the dynamic page.')->change();
});
Schema::table('news_categories', function (Blueprint $table) {
$table->string('name')->comment('Name of the news category.')->change();
$table->string('slug')->comment('Slug of the news category.')->change();
});
Schema::table('news_tags', function (Blueprint $table) {
$table->string('name')->comment('Name of the news tag.')->change();
$table->string('slug')->comment('Slug of the news tag.')->change();
});
Schema::table('page_configs', function (Blueprint $table) {
$table->string('label')->unique()->comment('Label of the configuration.')->change();
});
}
};

View file

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

View file

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

View file

@ -0,0 +1,282 @@
<?php
namespace Database\Seeders;
use App\Models\CompanyActivity;
use App\Models\CompanySector;
use App\Models\DocumentCategory;
use App\Models\DocumentTag;
use Illuminate\Database\Seeder;
class CustomSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
// php artisan db:seed --class=CustomSeeder
$this->companyActivitySeeder();
$this->companySectorSeeder();
$this->documentCategorySeeder();
$this->documentTagSeeder();
}
/**
* Set custom company activity seeder.
*
* @return void
*/
private function companyActivitySeeder(): void
{
// Set FR values.
app()->setLocale("fr");
$firstActivity = CompanyActivity::create([
"name" => "Amont",
"color" => "#6fbc45",
"published" => 1,
]);
$secondActivity = CompanyActivity::create([
"name" => "International",
"color" => "#b24881",
"published" => 1,
]);
$thirdActivity = CompanyActivity::create([
"name" => "Plateformes",
"color" => "#6d6d6d",
"published" => 1,
]);
$fourthActivity = CompanyActivity::create([
"name" => "Traiteur",
"color" => "#f29100",
"published" => 1,
]);
$fifthActivity = CompanyActivity::create([
"name" => "Volaille",
"color" => "#DC2034",
"published" => 1,
]);
// Set EN values.
app()->setLocale("en");
$firstActivity->update([
"name" => "Upstream",
]);
$secondActivity->update([
"name" => "International",
]);
$thirdActivity->update([
"name" => "Platforms",
]);
$fourthActivity->update([
"name" => "Catering",
]);
$fifthActivity->update([
"name" => "Poultry",
]);
// Set locale to the fallback.
app()->setLocale(config('app.fallback_locale'));
}
/**
* Set custom company sector seeder.
*
* @return void
*/
private function companySectorSeeder(): void
{
collect([
"Allemagne - ECF - Clements BETTERMANN",
"Angleterre - Capestone - Rob Cumine",
"Belgique - Kiplama - Toon KWEENS",
"Hongrie et Roumanie - Ákos Szabó",
"Pologne - Adam Sojka",
"Pôle Amont - Filière Céréales - Gaël Le Conte",
"Pôle Amont - Filière Oeufs - Christophe Bériard",
"Pôle Amont - Filière Spécialités - Didier Richard",
"Pôle Amont - Filière Vif - Stéphane Landreau",
"Pôle Amont - Filière accouvage - Olivier Sionneau",
"Pôle Traiteur - Crêpes et galettes - Christèle Lucas",
"Pôle Traiteur - La Toque Angevine - Pierre Lonjon",
"Pôle Traiteur - Pizzas, tartes, sandwiches et quiches - Yann Gomez",
"Pôle Traiteur - Plats cuisinés : Marie, Traditions d’Asie, Weight Watchers - Guillaume LETENNEUR",
"Pôle Traiteur - Plats cuisinés et produits exotiques - Benjamin Montlahuc",
"Pôle Traiteur - Restauration Hors Domicile - Ludovic Courtier",
"Pôle Traiteur - Surgelés - Didier Gand",
"Pôle Volaille - Cailles Robin - Guy Prod’homme",
"Pôle Volaille - GPA Distribution Paris - Thierry Lambert",
"Pôle Volaille - Hauts de France",
"Pôle Volaille - LDC Aquitaine - Denis Bordes",
"Pôle Volaille - LDC Foods - Mickaël Rio",
"Pôle Volaille - LDC TERRAVENIR - Christophe Pajot",
"Pôle Volaille - PFC - Dominique Théreau",
"Pôle Volaille - Société Arrivé - Roland Tonarelli",
"Pôle Volaille - Société Bretonne de Volaille - Laurent Girard",
"Pôle Volaille - Société Favreau Couthouis - Roland Tonarelli",
"Pôle Volaille - VOLENA - Arnaud Boinard",
"Pôle volaille - Pôle VDR - Philippe Aubert",
])->map(function (string $sector) {
CompanySector::create([
"name" => $sector,
"published" => 1,
]);
});
}
/**
* Set custom document category seeder.
*
* @return void
*/
private function documentCategorySeeder(): void
{
// Set FR values.
app()->setLocale("fr");
$docs = DocumentCategory::create([
"name" => "Documents",
"slug" => "documents"
]);
$meetings = DocumentCategory::create([
"name" => "Assemblées générales",
"slug" => "assemblees-generales"
]);
$investors = DocumentCategory::create([
"name" => "Présentation investisseurs",
"slug" => "presentation-investisseurs"
]);
$press = DocumentCategory::create([
"name" => "Espace presse",
"slug" => "espace-presse"
]);
// Set EN values.
app()->setLocale("en");
$docs->update([
"name" => "Documents",
"slug" => "documents"
]);
$meetings->update([
"name" => "General meetings",
"slug" => "general-meetings"
]);
$investors->update([
"name" => "Investor presentation",
"slug" => "investor-presentation"
]);
$press->update([
"name" => "Meetings Press area",
"slug" => "meeting-press-area"
]);
// Set locale to the fallback.
app()->setLocale(config('app.fallback_locale'));
}
/**
* Set custom document tag seeder.
*
* @return void
*/
private function documentTagSeeder(): void
{
// Set FR values.
app()->setLocale("fr");
$communique = DocumentTag::create([
"name" => "Communiqués et Avis financiers",
"slug" => "communiques-et-avis-financiers"
]);
$semestriel = DocumentTag::create([
"name" => "Rapports financiers annuels et semestriels",
"slug" => "rapports-financiers-annuels-et-semestriels"
]);
$droitdevote = DocumentTag::create([
"name" => "Déclaration mensuelles du nombre d’actions et de droits de vote",
"slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote"
]);
$rachat = DocumentTag::create([
"name" => "Descriptif de programme de rachats d’actions",
"slug" => "descriptif-de-programme-de-rachats-dactions"
]);
$liquidite = DocumentTag::create([
"name" => "Opérations sur contrat de liquidité",
"slug" => "operations-sur-contrat-de-liquidite"
]);
$trimestriel = DocumentTag::create([
"name" => "Information Trimestrielle",
"slug" => "information-trimestrielle"
]);
$publication = DocumentTag::create([
"name" => "Publication",
"slug" => "publication"
]);
$finance = DocumentTag::create([
"name" => "Finance",
"slug" => "finance"
]);
$general = DocumentTag::create([
"name" => "Assemblée générale des actionnaires",
"slug" => "assemblee-generale-des-actionnaires"
]);
$declaration = DocumentTag::create([
"name" => "Déclaration des rachats d’actions",
"slug" => "declaration-des-rachats-dactions"
]);
$statuts = DocumentTag::create([
"name" => "Statuts de la SA LDC",
"slug" => "statuts-de-la-sa-ldc"
]);
// Set EN values.
app()->setLocale("en");
$communique->update([
"name" => "Press releases and financial notices",
"slug" => "communiques-et-avis-financiers-en"
]);
$semestriel->update([
"name" => "Annual and half-yearly financial reports",
"slug" => "rapports-financiers-annuels-et-semestriels-en"
]);
$droitdevote->update([
"name" => "Monthly declaration of the number of shares and voting rights",
"slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote-en"
]);
$rachat->update([
"name" => "Description of share buyback program",
"slug" => "descriptif-de-programme-de-rachats-dactions-en"
]);
$liquidite->update([
"name" => "Liquidity contract transactions",
"slug" => "operations-sur-contrat-de-liquidite-en"
]);
$trimestriel->update([
"name" => "Quarterly Information",
"slug" => "information-trimestrielle-en"
]);
$publication->update([
"name" => "Publication",
"slug" => "publication-en"
]);
$finance->update([
"name" => "Finance",
"slug" => "finance-en"
]);
$general->update([
"name" => "General Meeting of Shareholders",
"slug" => "assemblee-generale-des-actionnaires-en"
]);
$declaration->update([
"name" => "Declaration of share buybacks",
"slug" => "declaration-des-rachats-dactions-en"
]);
$statuts->update([
"name" => "Statutes of SA LDC",
"slug" => "statuts-de-la-sa-ldc-en"
]);
// Set locale to the fallback.
app()->setLocale(config('app.fallback_locale'));
}
}

View file

@ -13,11 +13,22 @@ class DatabaseSeeder extends Seeder
*/
public function run(): void
{
// Set locale to the fallback.
app()->setLocale(config('app.fallback_locale'));
// Call seeders.
$this->call([
PageConfigSeeder::class,
DynamicPageSeeder::class,
NewsCategorySeeder::class,
NewsTagSeeder::class,
NewsSeeder::class,
CompanyActivitySeeder::class,
CompanySectorSeeder::class,
CompanySeeder::class,
DocumentCategorySeeder::class,
DocumentTagSeeder::class,
DocumentSeeder::class,
]);
}
}

View file

@ -9,43 +9,11 @@ class DocumentCategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
app()->setLocale("fr");
$docs = DocumentCategory::create([
"name" => "Documents", // pour finance
"slug" => "documents"
]);
$meetings = DocumentCategory::create([
"name" => "Assemblées générales", // pour finance
"slug" => "assemblees-generales"
]);
$investors = DocumentCategory::create([
"name" => "Présentation investisseurs", // pour finance
"slug" => "presentation-investisseurs"
]);
$press = DocumentCategory::create([
"name" => "Espace presse",
"slug" => "espace-presse"
]);
app()->setLocale("en");
$docs->update([
"name" => "Documents",
"slug" => "documents"
]);
$meetings->update([
"name" => "General meetings",
"slug" => "general-meetings"
]);
$investors->update([
"name" => "Investor presentation",
"slug" => "investor-presentation"
]);
$press->update([
"name" => "Meetings Press area",
"slug" => "meeting-press-area"
]);
DocumentCategory::factory(10)->create();
}
}

View file

@ -3,6 +3,8 @@
namespace Database\Seeders;
use App\Models\Document;
use App\Models\DocumentCategory;
use App\Models\DocumentTag;
use Illuminate\Database\Seeder;
use Uwil\LaravelCommon\Helpers\FileHelper;
@ -10,11 +12,12 @@ class DocumentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
Document::factory(3)->withTags(3)->withCategories(2)->make()
->each(function ($model) {
Document::factory(3)->make()->each(function (Document $model) {
$model->path = FileHelper::storeFile(
$model,
new \SplFileInfo(\resource_path(
@ -22,6 +25,22 @@ class DocumentSeeder extends Seeder
))
);
$model->saveOrFail();
});;
});
// Document categories relation.
$categoriesIds = DocumentCategory::pluck('id');
Document::query()->get()->map(function (Document $document) use ($categoriesIds) {
$document->categories()->attach(
$categoriesIds->random(rand(1, 3))->all()
);
});
// Document tags relation.
$tagsIds = DocumentTag::pluck('id');
Document::query()->get()->map(function (Document $document) use ($tagsIds) {
$document->tags()->attach(
$tagsIds->random(rand(1, 3))->all()
);
});
}
}

View file

@ -9,98 +9,11 @@ class DocumentTagSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
app()->setLocale("fr");
$communique = DocumentTag::create([
"name" => "Communiqués et Avis financiers",
"slug" => "communiques-et-avis-financiers"
]);
$semestriel = DocumentTag::create([
"name" => "Rapports financiers annuels et semestriels",
"slug" => "rapports-financiers-annuels-et-semestriels"
]);
$droitdevote = DocumentTag::create([
"name" => "Déclaration mensuelles du nombre d’actions et de droits de vote",
"slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote"
]);
$rachat = DocumentTag::create([
"name" => "Descriptif de programme de rachats d’actions",
"slug" => "descriptif-de-programme-de-rachats-dactions"
]);
$liquidite = DocumentTag::create([
"name" => "Opérations sur contrat de liquidité",
"slug" => "operations-sur-contrat-de-liquidite"
]);
$trimestriel = DocumentTag::create([
"name" => "Information Trimestrielle",
"slug" => "information-trimestrielle"
]);
$publication = DocumentTag::create([
"name" => "Publication",
"slug" => "publication"
]);
$finance = DocumentTag::create([
"name" => "Finance",
"slug" => "finance"
]);
$general = DocumentTag::create([
"name" => "Assemblée générale des actionnaires",
"slug" => "assemblee-generale-des-actionnaires"
]);
$declaration = DocumentTag::create([
"name" => "Déclaration des rachats d’actions",
"slug" => "declaration-des-rachats-dactions"
]);
$statuts = DocumentTag::create([
"name" => "Statuts de la SA LDC",
"slug" => "statuts-de-la-sa-ldc"
]);
app()->setLocale("en");
$communique->update([
"name" => "Press releases and financial notices",
"slug" => "communiques-et-avis-financiers-en"
]);
$semestriel->update([
"name" => "Annual and half-yearly financial reports",
"slug" => "rapports-financiers-annuels-et-semestriels-en"
]);
$droitdevote->update([
"name" => "Monthly declaration of the number of shares and voting rights",
"slug" => "declaration-mensuelles-du-nombre-dactions-et-de-droits-de-vote-en"
]);
$rachat->update([
"name" => "Description of share buyback program",
"slug" => "descriptif-de-programme-de-rachats-dactions-en"
]);
$liquidite->update([
"name" => "Liquidity contract transactions",
"slug" => "operations-sur-contrat-de-liquidite-en"
]);
$trimestriel->update([
"name" => "Quarterly Information",
"slug" => "information-trimestrielle-en"
]);
$publication->update([
"name" => "Publication",
"slug" => "publication-en"
]);
$finance->update([
"name" => "Finance",
"slug" => "finance-en"
]);
$general->update([
"name" => "General Meeting of Shareholders",
"slug" => "assemblee-generale-des-actionnaires-en"
]);
$declaration->update([
"name" => "Declaration of share buybacks",
"slug" => "declaration-des-rachats-dactions-en"
]);
$statuts->update([
"name" => "Statutes of SA LDC",
"slug" => "statuts-de-la-sa-ldc-en"
]);
DocumentTag::factory(10)->create();
}
}

View file

@ -2,6 +2,7 @@
namespace Database\Seeders;
use App\Enums\DynamicPages\PageStatusEnum;
use App\Enums\DynamicFieldTypes;
use App\Models\DynamicPage;
use Illuminate\Database\Seeder;
@ -17,23 +18,59 @@ class DynamicPageSeeder extends Seeder
*/
public function run(): void
{
DynamicPage::factory(10)->make()
->each(function ($model) {
$content = $model->content;
// Config factories add just one depth of children.
foreach ($model->content as $key => $value) {
$prefix = sprintf("%s_", DynamicFieldTypes::image->name);
if (Str::startsWith($key, $prefix)) {
$content[$key] = FileHelper::storeFile(
$model,
new \SplFileInfo(\resource_path(
'../database/factories/assets/dynamic-pages/100x100.jpg'
))
);
}
// Mandatory dynamic pages.
$titleHome = "Accueil";
$dynamicPageModel = new DynamicPage;
$dynamicPageModel->id_key = Str::slug($titleHome);
$dynamicPageModel->slug = "";
$dynamicPageModel->title = $titleHome;
$dynamicPageModel->content = [];
$dynamicPageModel->status = PageStatusEnum::published;
$dynamicPageModel->isLocked = true;
$dynamicPageModel->isRoot = true;
$dynamicPageModel->saveOrFail();
$titlePrivacyPolicy = "Politique de confidentialité";
$slugPrivacyPolicy = Str::slug($titlePrivacyPolicy);
$dynamicPageModel = new DynamicPage;
$dynamicPageModel->id_key = $slugPrivacyPolicy;
$dynamicPageModel->slug = $slugPrivacyPolicy;
$dynamicPageModel->title = $titlePrivacyPolicy;
$dynamicPageModel->content = [];
$dynamicPageModel->status = PageStatusEnum::published;
$dynamicPageModel->isLocked = true;
$dynamicPageModel->isRoot = false;
$dynamicPageModel->saveOrFail();
$titleLegalNotice = "Mentions légales";
$slugLegalNotice = Str::slug($titleLegalNotice);
$dynamicPageModel = new DynamicPage;
$dynamicPageModel->id_key = $slugLegalNotice;
$dynamicPageModel->slug = $slugLegalNotice;
$dynamicPageModel->title = $titleLegalNotice;
$dynamicPageModel->content = [];
$dynamicPageModel->status = PageStatusEnum::published;
$dynamicPageModel->isLocked = true;
$dynamicPageModel->isRoot = false;
$dynamicPageModel->saveOrFail();
// Fake dynamic pages.
DynamicPage::factory(20)->make()->each(function ($model) {
$content = $model->content;
// Config factories add just one depth of children.
foreach ($model->content as $key => $value) {
$prefix = sprintf("%s_", DynamicFieldTypes::image->name);
if (Str::startsWith($key, $prefix)) {
$content[$key] = FileHelper::storeFile(
$model,
new \SplFileInfo(\resource_path(
'../database/factories/assets/dynamic-pages/100x100.jpg'
))
);
}
$model->content = $content;
$model->saveOrFail();
});
}
$model->content = $content;
$model->saveOrFail();
});
}
}

View file

@ -16,15 +16,19 @@ class NewsSeeder extends Seeder
*/
public function run(): void
{
$categoriesIds = NewsCategory::pluck('id');
News::factory(10)->create()->each(function (News $news) use ($categoriesIds) {
News::factory(10)->make()->each(function (News $news) {
$news->picture = FileHelper::storeFile(
$news,
new \SplFileInfo(
resource_path('../database/factories/assets/news/525x295.jpg')
)
new \SplFileInfo(resource_path(
'../database/factories/assets/news/525x295.jpg'
))
);
$news->save();
$news->saveOrFail();
});
// News relation.
$categoriesIds = NewsCategory::pluck('id');
News::query()->get()->map(function (News $news) use ($categoriesIds) {
$news->categories()->attach(
$categoriesIds->random(rand(1, 3))->all()
);

View file

@ -9,6 +9,8 @@ class NewsTagSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{

View file

@ -62,7 +62,8 @@ return [
"settings" => "Settings",
"crud_back_to_list" => "Back to the list of entries",
"crud_add_entry" => "Add a new entry",
"crud_access_trash" => "Access archived entries",
"crud_access_to" => "Access to :target",
"archived_entries" => "archived entries",
"table_search" => "Search by :searchFields",
"table_search_reset" => "Reset the search",
"table_filter_button" => "Filter results by :field",
@ -76,7 +77,8 @@ return [
],
"category" => [
"placeholder" => "choose a category"
]
],
"no_link" => "this document has neither internal link or Issu link",
],
"form_title_additional_files" => "Additionnal files",
"form_subtitle_additional_files" => "Add additionnal files",
@ -175,9 +177,11 @@ return [
],
],
"multi_select" => [
"search_options" => "search options...",
"search_options" => "search among the options...",
"select_all" => "select all",
"more" => "more",
"close_popover" => "close popover",
"clear_list" => "deselect all items",
],
"simple_date_picker" => [
"reset" => "reset the date"
@ -261,4 +265,24 @@ return [
]
],
"refresh_original" => "reset to original state",
"model_filters" => [
"button_tooltip" => "open the filters window",
"sheet_title" => "filters window",
"select_status" => [
"label" => "status",
"placeholder" => "choose a status"
],
"has_no_link" => [
"label" => "filter document with no usable link"
],
"categories" => [
"label" => "filter by category",
"placeholder" => "select one or more categories"
],
"tags" => [
"label" => "filter by tag",
"placeholder" => "select one or more tags"
],
],
"associated_model" => "associated :model|associated :model",
];

View file

@ -42,36 +42,37 @@ return [
],
"messages" => [
"has_been_created" => ":model has been created",
"cannot_be_created" => ":model cannot be created",
"has_been_updated" => ":model has been updated",
"cannot_be_updated" => ":model cannot be updated",
"has_been_deleted" => ":model has been deleted",
"cannot_be_deleted" => ":model cannot be deleted",
"has_been_restored" => ":model has been restored",
"cannot_be_restored" => ":model cannot be restored",
"order_changed" => "The order has been changed !",
"order_not_changed" => "The order has not been changed !",
"publish_status_saved" => "Successful change of publication status !",
"highlight_status_saved" => "A successful change of focus !",
"right" => "You don't have access rights to this part !",
"theme_updated" => "The theme has been updated !",
"user_unpublished" => "You can't deactivate your own account !",
"successful_creation" => "Creation successful !",
"successful_edition" => "Update successful !",
"successful_archivation" => "Archiving successful !",
"successful_restoration" => "Restoration successful !",
"successful_deletion" => "Deletion successful !",
"canceled_creation" => "Creation canceled !",
"canceled_edition" => "Update canceled !",
"canceled_archivation" => "Archiving canceled !",
"canceled_restoration" => "Restoration canceled !",
"canceled_deletion" => "Deletion canceled !",
"successful_archivation_details" => "You have just archived an entry.",
"successful_restoration_details" => "You have just restored an entry.",
"successful_deletion_details" => "You have just permanently deleted an entry.",
"canceled_archivation_details" => "A problem occurred while archiving this entry.",
"canceled_restoration_details" => "A problem occurred while restoring this entry.",
"canceled_deletion_details" => "A problem occurred while deleting this entry.",
"has_been_created" => ":model has been created",
"cannot_be_created" => ":model cannot be created",
"has_been_updated" => ":model has been updated",
"cannot_be_updated" => ":model cannot be updated",
"has_been_deleted" => ":model has been deleted",
"cannot_be_deleted" => ":model cannot be deleted",
"has_been_restored" => ":model has been restored",
"cannot_be_restored" => ":model cannot be restored",
"order_changed" => "The order has been changed !",
"order_not_changed" => "The order has not been changed !",
"publish_status_saved" => "Successful change of publication status !",
"highlight_status_saved" => "A successful change of focus !",
"right" => "You don't have access rights to this part !",
"theme_updated" => "The theme has been updated !",
"user_unpublished" => "You can't deactivate your own account !",
"cannot_delete_relation" => "Deletion not possible because data models are still associated !",
],
"meta" => [
"title" => [
"create" => "{0} Creation of :model|{1} Creation of :model",
"edit" => "{0} Edition of :model|{1} Edition of :model",
"show" => "{0} Details of :model|{1} Details of :model",
],
// phpcs:disable Generic.Files.LineLength.TooLong
"description" => [
"index" => "{0} List of all :model|{1} List of all :model",
"create" => "{0} Creation of a brand new :model|{1} Creation of a brand new :model",
"edit" => "{0} Editing an existing :model|{1} Editing an existing :model",
"show" => "{0} Visualizing an existing :model|{1} Visualizing an existing :model",
],
// phpcs:enable
]
];

View file

@ -9,13 +9,13 @@ return [
"contact-count" => "contact form",
"news" => "news|news",
"news-category" => "news category|news categories",
"news-tag" => "news tag|news tag",
"company" => "company|companies",
"company-activity" => "activity de société|activities de société",
"company-activity" => "company activity|company activities",
"company-sector" => "company sector|company sectors",
"document" => "document|documents",
"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

@ -248,7 +248,6 @@ return [
"title" => "seo title",
"description" => "seo description",
],
"category" => "category|categories",
"picture" => [
"picture" => "image",
"picture_alt" => "alternative text of the image",
@ -259,8 +258,8 @@ return [
"type" => "form type",
"submissions" => "count of soumissions"
],
"vimeo_id" => "VIMEO ID",
"youtube_id" => "YOUTUBE ID",
"vimeo_id" => "VIMEO ID",
"youtube_id" => "YOUTUBE ID",
"logo" => "logo",
"responsable" => "responsable",
"url" => "url",
@ -270,20 +269,8 @@ return [
"longitude" => "longitude",
"color" => "color",
"value" => "value",
"document" => [
"exercice" => "exercice|exercices",
"tag" => "etiquette|etiquettes",
"path" => "file",
"category" => "category|categories"
],
"documentTag" => [
"documents" => "associated file(s)"
],
"newsCategory" => [
"news" => "associated news"
],
"news" => [
"tag" => "etiquette|etiquettes",
]
"path" => "path",
"issuu_path" => "link of the Issuu preview",
"is_issuu" => "is an Issuu preview ?"
],
];

View file

@ -61,7 +61,8 @@ return [
"settings" => "Paramètres",
"crud_back_to_list" => "Revenir à la liste des entrées",
"crud_add_entry" => "Ajouter une nouvelle entrée",
"crud_access_trash" => "Accéder aux entrées archivées",
"crud_access_to" => "Accéder aux :target",
"archived_entries" => "entrées archivées",
"table_search" => "Rechercher sur :searchFields",
"table_search_reset" => "Effacer la recherche",
"table_filter_button" => "Filtrer les résultats par le champs :field",
@ -75,7 +76,8 @@ return [
],
"category" => [
"placeholder" => "choisir une catégorie"
]
],
"no_link" => "ce document ne possède ni lien interne ni lien Issuu",
],
"form_title_additional_files" => "Fichier supplémentaire",
"form_subtitle_additional_files" => "Ajouter des fichiers supplémentaires",
@ -107,7 +109,7 @@ return [
"form_subtitle_associations" => "Gérer les relations du modèle.",
"form_title_implantation" => "Coordonnées géographiques",
"form_subtitle_implantation" => "Modifiez les informations de localisation de ce modèle de données.",
"access_model" => "Accéder à la :model",
"access_model" => "Accéder à :model",
"clear" => "vider",
"close" => "Fermer",
"config_modal_title" => "Prévisualisation",
@ -179,6 +181,8 @@ return [
"search_options" => "cherchez parmi les options...",
"select_all" => "tout sélectionner",
"more" => "supplémentaire(s)",
"close_popover" => "fermer la popup",
"clear_list" => "désélectionner tous les éléments",
],
"simple_date_picker" => [
"reset" => "vider la date",
@ -210,6 +214,17 @@ return [
"use_internal" => "Utilisez un lien interne pour ce domaine",
],
],
"image" => [
"tooltip" => "Image",
"title" => "Insérer une image",
"subtitle" => "Configurer ou modifier une image.",
"add" => "Ajouter ce lien",
"cancel" => "Annuler l’ajout de ce lien",
"validation" => [
"url" => "L’URL doit être un domaine valide avec protocole (https:// ou https://) et TLD (.com, .fr etc...)",
"use_internal" => "Utilisez un lien interne pour ce domaine",
],
],
],
"json_editor" => [
"item_single" => "1 élément",
@ -262,4 +277,24 @@ return [
]
],
"refresh_original" => "remettre à l'état d'origine",
"model_filters" => [
"button_tooltip" => "ouvrir la fenêtre des filtres",
"sheet_title" => "fenêtre des filtres",
"select_status" => [
"label" => "filtrer par statut",
"placeholder" => "selectionner un statut"
],
"has_no_link" => [
"label" => "filtrer les documents qui n'ont aucun lien d'accès"
],
"categories" => [
"label" => "filtrer par catégorie",
"placeholder" => "selectionner une ou plusieurs catégories"
],
"tags" => [
"label" => "filtrer par étiquette",
"placeholder" => "selectionner une ou plusieurs étiquettes"
],
],
"associated_model" => ":model associés|:model associées",
];

View file

@ -42,40 +42,37 @@ return [
],
"messages" => [
"successful_creation" => "Création réussie !",
"successful_edition" => "Mise à jour réussie !",
"canceled_creation" => "Création annulée !",
"canceled_edition" => "Mise à jour annulée !",
"has_been_created" => ":model a été créé",
"cannot_be_created" => ":model ne peut être créé",
"has_been_updated" => ":model a été mis à jour",
"cannot_be_updated" => ":model ne peut être mis à jour",
"has_been_deleted" => ":model a été supprimé",
"cannot_be_deleted" => ":model ne peut être supprimé",
"has_been_restored" => ":model a été restoré",
"cannot_be_restored" => ":model ne peut être restoré",
"order_changed" => "L'ordre a été changé !",
"order_not_changed" => "L'ordre n'a pas été changé !",
"publish_status_saved" => "Changement de l'état de publication réussi !",
"highlight_status_saved" => "Changement de la mise en avant réussi !",
"right" => "Vous n'avez pas les droits pour accéder à cette partie !",
"theme_updated" => "Le thème a été mis à jour !",
"user_unpublished" => "Vous ne pouvez pas désactiver votre propre compte !",
"successful_creation" => "Création réussie !",
"successful_edition" => "Mise à jour réussie !",
"successful_archivation" => "Archivation réussie !",
"successful_restoration" => "Restoration réussie !",
"successful_deletion" => "Suppression réussie !",
"canceled_creation" => "Création annulée !",
"canceled_edition" => "Mise à jour annulée !",
"canceled_archivation" => "Archivation annulée !",
"canceled_restoration" => "Restoration annulée !",
"canceled_deletion" => "Suppression annulée !",
"successful_archivation_details" => "Vous venez d'archiver une entrée.",
"successful_restoration_details" => "Vous venez de restorer une entrée.",
"successful_deletion_details" => "Vous venez de supprimer définitivement une entrée.",
"canceled_archivation_details" => "Un problème est survenu lors de l'archivation de cette entrée.",
"canceled_restoration_details" => "Un problème est survenu lors de la restoration de cette entrée.",
"canceled_deletion_details" => "Un problème est survenu lors de la suppression de cette entrée.",
"has_been_created" => ":model a été créé",
"cannot_be_created" => ":model ne peut être créé",
"has_been_updated" => ":model a été mis à jour",
"cannot_be_updated" => ":model ne peut être mis à jour",
"has_been_deleted" => ":model a été supprimé",
"cannot_be_deleted" => ":model ne peut être supprimé",
"has_been_restored" => ":model a été restoré",
"cannot_be_restored" => ":model ne peut être restoré",
"order_changed" => "L'ordre a été changé !",
"order_not_changed" => "L'ordre n'a pas été changé !",
"publish_status_saved" => "Changement de l'état de publication réussi !",
"highlight_status_saved" => "Changement de la mise en avant réussi !",
"right" => "Vous n'avez pas les droits pour accéder à cette partie !",
"theme_updated" => "Le thème a été mis à jour !",
"user_unpublished" => "Vous ne pouvez pas désactiver votre propre compte !",
"cannot_delete_relation" => "Supression impossible car des modèles de données sont encore associés !",
],
"meta" => [
"title" => [
"create" => "{0} Création d'un :model|{1} Création d'une :model",
"edit" => "{0} Edition d'un :model|{1} Edition d'une :model",
"show" => "{0} Visualisation d'un :model|{1} Visualisation d'une :model",
],
// phpcs:disable Generic.Files.LineLength.TooLong
"description" => [
"index" => "{0} Liste de tous les :model|{1} Liste de toutes les :model",
"create" => "{0} Création d'un tout nouveau :model|{1} Création d'une toute nouvelle :model",
"edit" => "{0} Edition d'un :model déjà existant|{1} Edition d'une :model déjà existante",
"show" => "{0} Visualisation d'un :model déjà existant|{1} Visualisation d'une :model déjà existante",
],
// phpcs:enable
]
];

View file

@ -51,7 +51,7 @@ return [
'are_you_breeder_and_join_us' => 'Vous êtes éleveur de volailles ou souhaitez le devenir, et nous rejoindre ? ',
'describe_your_project' => 'Décrivez-nous votre projet le plus précisément possible afin que nous puissions orienter votre demande vers l’interlocuteur adéquat.',
'info_personal_data' => 'Les informations recueillies à partir de ce formulaire sont traitées par le Responsable de Traitement pour donner suite à votre demande de contact. Pour connaître vos droits, vous pouvez consulter',
'confidentiality' => 'la Charte de confidentialité',
'confidentiality' => 'la politique de confidentialité',
'other_product_information' => 'Vous souhaitez une information ou avez une remarque sur nos produits ? Dirigez-vous directement sur le site de la marque concernée (rubriques Contact ou Service Consommateurs). Si la marque ou le produit ne possède pas de site web, merci d’adresser votre demande par voie postale à l’adresse du site mentionnée sur l’emballage.',
'inputs' => [
'breedtype' => [

View file

@ -9,6 +9,7 @@ return [
"contact-count" => "formulaire de contact",
"news" => "actualité|actualités",
"news-category" => "catégorie d'actualité|catégories d'actualité",
"news-tag" => "étiquette d'actualité|étiquettes d'actualité",
"company" => "société|sociétés",
"company-activity" => "activité de société|activités de société",
"company-sector" => "secteur de société|secteurs de société",
@ -16,6 +17,5 @@ return [
"document-tag" => "étiquette de document|étiquettes de document",
"document-category" => "catégorie de document|catégories de document",
"document-exercice" => "exercice de document|exercices de document",
"news-tag" => "étiquette d'actualité|étiquettes d'actualité",
],
];

View file

@ -240,7 +240,7 @@ return [
"validation" => "validation",
"reference" => "référence",
"locked" => "vérouillé",
"root" => "page racine (accueil)",
"root" => "page racine",
"field" => "champs",
"key" => "clé",
"slug" => "chemin d'accès",
@ -249,11 +249,11 @@ return [
"title" => "titre SEO",
"description" => "description SEO",
],
"category" => "catégorie|catégories",
"image" => "image",
"image_alt" => "texte alternatif de l'image",
"image_title" => "titre de l'image",
"content" => "contenu",
"contactCount" => [
"contact_count" => [
"type" => "type de formulaire",
"submissions" => "nombre de soumissions"
],
@ -268,22 +268,8 @@ return [
"longitude" => "longitude",
"color" => "couleur",
"value" => "valeur",
"document" => [
"exercice" => "exercice|exercices",
"tag" => "étiquette|étiquettes",
"path" => "fichier",
"category" => "catégorie|catégories"
],
"documentTag" => [
"documents" => "document(s) associé(s)"
],
"newsCategory" => [
"news" => "actualité(s) associée(s)"
],
"news" => [
"tag" => "étiquette|étiquettes",
],
"issuu_path" => "lien de la preview Issuu",
"is_issuu" => "est-ce une preview Issuu ?"
"path" => "chemin d'accès",
"issuu_path" => "lien du fichier Issuu",
"is_issuu" => "est-ce un fichier Issuu ?"
],
];

View file

@ -3300,6 +3300,15 @@ div.search-results {
font-weight: 700;
}
.search-empty-results {
height: 80px;
padding: 30px 0;
}
.search-page .page-numbers {
cursor: pointer;
}
/* page search END */
/* pagination START */

View file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 828 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -0,0 +1,9 @@
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 66.000000 66.000000" preserveAspectRatio="xMidYMid meet">
<g transform="translate(0.000000,66.000000) scale(0.100000,-0.100000)" fill="#000000" stroke="none">
<path d="M162 641 c-66 -8 -94 -26 -118 -74 -17 -31 -32 -305 -20 -352 l7 -28 22 44 c27 54 92 121 145 148 22 11 86 38 143 59 113 43 224 95 251 120 29 25 22 51 -18 68 -43 18 -311 27 -412 15z m83 -55 c13 -13 29 -42 36 -64 10 -35 10 -45 -5 -67 -20 -30 -49 -32 -94 -5 -36 22 -65 79 -55 107 20 56 77 70 118 29z"/>
<path d="M622 490 c-7 -20 -39 -78 -73 -129 -94 -147 -111 -186 -117 -268 l-5 -73 54 0 c71 0 119 25 142 72 22 44 34 288 20 378 l-9 55 -12 -35z"/>
<path d="M240 300 c-34 -34 -19 -89 31 -115 62 -33 101 2 79 70 -20 61 -73 82 -110 45z"/>
<path d="M223 126 c-31 -26 -71 -91 -62 -101 9 -8 215 -19 233 -12 15 6 15 10 1 44 -38 91 -111 120 -172 69z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 886 B

View file

@ -0,0 +1,21 @@
{
"name": "LDC Group",
"short_name": "LDC",
"icons": [
{
"src": "/web-app-manifest-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/web-app-manifest-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View file

@ -0,0 +1,114 @@
// * Packages
import { Row } from "@tanstack/react-table";
import { Building2Icon, CheckIcon, XIcon } from "lucide-react";
// * Components shadcn
import { Badge } from "@/components/ui/badge";
// * Other
import DataTable from "@/back/Components/Table/DataTable";
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
import { CompanyModel, Resource } from "@/back/types/global";
import { Views } from "@/lib/utils";
import { useFormatedDate } from "@/hooks/use-formated-value";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
interface Props {
companies: Resource;
}
const AssociatedCompaniesList = (props: Props) => {
const { companies } = props;
const columns = [
{
accessorKey: "name",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<CompanyModel> }) => {
return row.getValue("name");
},
},
{
accessorKey: "published",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.custom.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<CompanyModel> }) => (
<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(
useTrans(
row.getValue("published") ? "back.yes" : "back.no",
),
)
.ucFirst()
.value()}
</Badge>
),
},
{
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<CompanyModel> }) => (
<Badge variant="secondary">
{useFormatedDate(row.getValue("updated_at"))}
</Badge>
),
},
];
return (
<>
<h3 className="text-2xl font-semibold leading-none tracking-tight flex flex-row w-full items-start my-4">
<Building2Icon className="me-2" />
{str(
useTrans("back.associated_model", {
params: {
model: useTrans("models.classes.company", {
choice: 2,
}),
},
choice: 2,
}),
)
.ucFirst()
.value()}
</h3>
<DataTable
columns={columns}
modelRoute="companies"
modelsPaginate={companies}
actions={[Views.VISUALIZATION, Views.EDITION]}
/>
</>
);
};
export default AssociatedCompaniesList;

View file

@ -1,68 +0,0 @@
import str from "@/hooks/use-string"
import DataTable from "./Table/DataTable"
import useTrans from "@/hooks/use-translations"
import DataTableFilterButton from "./Table/DataTableFilterButton";
import { AppEnv, DocumentModel, Resource, TranslationField } from "../types/global";
import { Row } from "@tanstack/react-table";
import { usePage } from "@inertiajs/react";
import { Views } from "@/lib/utils";
import { renderTranslationCell } from "@/lib/translationCellFallback";
interface Props {
documents: Resource
}
const AssociatedDocumentList = (props: Props) => {
const { documents } = props;
const { appEnv } = usePage().props as unknown as {
appEnv: AppEnv;
};
const documentColumns = [
{
accessorKey: "name",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`)).ucFirst().value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<DocumentModel> }) => {
return renderTranslationCell(
row.getValue("name")
)
},
},
{
accessorKey: "path",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`)).ucFirst().value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<DocumentModel> }) => {
return (row.getValue("path") as TranslationField)[appEnv.locale] ? (
(<a target="_blank" className="text-blue-500 underline" href={appEnv.url + '/' + (row.getValue("path") as TranslationField)[appEnv.locale]}>
{appEnv.url + '/' + (row.getValue("path") as TranslationField)[appEnv.locale]}
</a>)
) : (<p className="text-muted-foreground italic m-0">{useTrans('back.table_not_known')}</p>);
},
},
];
return (
<>
<h3 className="mt-5 mb-1 text-xl font-medium">{str(useTrans("validation.custom.documentTag.documents")).ucFirst().value()}</h3>
<DataTable
columns={documentColumns}
modelRoute={"documents"}
modelsPaginate={documents}
actions={[
Views.VISUALIZATION,
Views.EDITION
]}
/>
</>
)
}
export default AssociatedDocumentList;

View file

@ -1,17 +0,0 @@
import { Badge } from "@/components/ui/badge";
type DocumentFinanceTagBadgeProps = {
value: string;
};
export default function DocumentFinanceTagBadge({
value,
}: DocumentFinanceTagBadgeProps) {
return (
<Badge variant="outline">
{value}
</Badge>
);
}

View file

@ -0,0 +1,109 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { Row } from "@tanstack/react-table";
import { FileInputIcon } from "lucide-react";
// * Other
import str from "@/hooks/use-string";
import DataTable from "@/back/Components/Table/DataTable";
import useTrans from "@/hooks/use-translations";
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
import {
AppEnv,
DocumentModel,
Resource,
TranslationField,
} from "@/back/types/global";
import { Views } from "@/lib/utils";
import { renderTranslationCell } from "@/lib/translationCellFallback";
interface Props {
documents: Resource;
}
const AssociatedDocumentList = (props: Props) => {
const { documents } = props;
const { appEnv } = usePage().props as unknown as {
appEnv: AppEnv;
};
const documentColumns = [
{
accessorKey: "name",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<DocumentModel> }) => {
return renderTranslationCell(row.getValue("name"));
},
},
{
accessorKey: "path",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.custom.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<DocumentModel> }) => {
return (row.getValue("path") as TranslationField)[
appEnv.locale
] ? (
<a
target="_blank"
className="text-blue-500 underline"
href={
appEnv.url +
"/" +
(row.getValue("path") as TranslationField)[
appEnv.locale
]
}
>
{appEnv.url +
"/" +
(row.getValue("path") as TranslationField)[
appEnv.locale
]}
</a>
) : (
<p className="text-muted-foreground italic m-0">
{useTrans("back.table_not_known")}
</p>
);
},
},
];
return (
<>
<h3 className="text-2xl font-semibold leading-none tracking-tight flex flex-row w-full items-start my-4">
<FileInputIcon className="me-2" />
{str(
useTrans("back.associated_model", {
params: {
model: useTrans("models.classes.document", {
choice: 2,
}),
},
choice: 2,
}),
)
.ucFirst()
.value()}
</h3>
<DataTable
columns={documentColumns}
modelRoute="documents"
modelsPaginate={documents}
actions={[Views.VISUALIZATION, Views.EDITION]}
/>
</>
);
};
export default AssociatedDocumentList;

View file

@ -0,0 +1,100 @@
// * Packages
import { usePage } from "@inertiajs/react";
// * Other
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
import EnumFilter from "@/back/Components/Filters/EnumFilter";
import SwitchFilter from "@/back/Components/Filters/SwitchFilter";
import MultiSelectRelationFilter from "@/back/Components/Filters/MultiSelectRelationFilter";
import FiltersWrapper from "@/back/Components/FiltersWrapper";
import {
DocumentCategoryModel,
DocumentTagModel,
LaravelEnum,
} from "@/back/types/global";
const Filters = () => {
const modelName = usePage().props.modelName as string;
const categories = usePage().props.categories as DocumentCategoryModel[];
const tags = usePage().props.tags as DocumentTagModel[];
const enumDocumentStatus = usePage().props.enumDocumentStatus as LaravelEnum;
return (
<FiltersWrapper>
<EnumFilter
enums={enumDocumentStatus}
modelName={modelName}
fieldName="status"
label={str(
useTrans(
"back.model_filters.select_status.label",
),
)
.ucFirst()
.value()}
placeholder={str(
useTrans(
"back.model_filters.select_status.placeholder",
),
)
.ucFirst()
.value()}
/>
<SwitchFilter
fieldName="hasNoLink"
modelName={modelName}
label={str(
useTrans(
"back.model_filters.has_no_link.label",
),
)
.ucFirst()
.value()}
/>
<MultiSelectRelationFilter
fieldName="categories"
modelName={modelName}
label={str(
useTrans(
"back.model_filters.categories.label",
),
)
.ucFirst()
.value()}
placeholder={str(
useTrans(
"back.model_filters.categories.placeholder",
),
)
.ucFirst()
.value()}
options={categories}
modelTranslatable={true}
optionName="name"
/>
<MultiSelectRelationFilter
fieldName="tags"
modelName={modelName}
label={str(
useTrans(
"back.model_filters.tags.label",
),
)
.ucFirst()
.value()}
placeholder={str(
useTrans(
"back.model_filters.tags.placeholder",
),
)
.ucFirst()
.value()}
options={tags}
modelTranslatable={true}
optionName="name"
/>
</FiltersWrapper>
);
};
export default Filters;

View file

@ -1,4 +1,4 @@
// * Components shadcn
// * Packages
import { ReactNode } from "react";
// * Components shadcn
import {

View file

@ -0,0 +1,44 @@
// * Packages
import { route } from "ziggy-js";
// * Other
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
import { LaravelEnum } from "@/back/types/global";
import { addFilterToUrl } from "@/lib/filters";
type Props = {
enums: LaravelEnum;
fieldName: string;
modelName: string;
label: string;
placeholder: string;
}
const EnumFilter = (props: Props) => {
const { enums, fieldName, modelName, label, placeholder } = props;
const selectedEnumParam = Object.values(enums).find(
status => status.name === route().params.status
);
return (
<EnumSelect
name={fieldName}
label={label}
options={enums}
placeholder={placeholder}
required={false}
selected={selectedEnumParam?.value ?? undefined}
setData={(name, value) => {
const selectedStatusName = Object.values(enums).find(
enumValue => enumValue.value === value
)?.name;
const params = {
...route().params,
[name]: selectedStatusName,
};
addFilterToUrl({modelName, params});
}}
/>
)
}
export default EnumFilter;

View file

@ -0,0 +1,69 @@
// * Packages
import { usePage } from "@inertiajs/react";
import { route } from "ziggy-js";
// * Other
import { MultiSelect } from "@/back/Components/Inputs/MultiSelect";
import { mapPivotOptions } from "@/lib/mapPivotOptions";
import { AppEnv, Model } from "@/back/types/global";
import { addFilterToUrl } from "@/lib/filters";
type Props = {
fieldName: string;
modelName: string;
label: string;
placeholder: string;
options: Model[];
/** Is the model passed to the multi select translatable */
modelTranslatable?: boolean;
/** The name of the field to display in options, default is name */
optionName?: string;
}
const MultiSelectRelationFilter = (props: Props) => {
const { fieldName, label, placeholder, modelName, options: optionsToSelect, modelTranslatable = false, optionName = "name" } = props;
const { appEnv } = usePage().props as unknown as {
appEnv: AppEnv;
};
const valuesFromUrl: string[] =
typeof route().params[fieldName] === "string"
? route().params[fieldName].split(",")
: [];
const { options } = mapPivotOptions(optionsToSelect, [], optionName, modelTranslatable ? appEnv.locale : null);
return (
<MultiSelect
label={label}
multiple={true}
name={fieldName}
required={false}
variant="inverted"
placeholder={placeholder}
singleLine={false}
setData={(name, value) => {
const params = {
...route().params,
[name]: value.length ? value.join(",") : undefined,
};
addFilterToUrl({ modelName, params });
}}
defaultValue={valuesFromUrl}
options={options}
responsive={{
mobile: {
maxCount: 3,
},
tablet: {
maxCount: 4,
},
desktop: {
maxCount: 5,
}
}}
/>
)
}
export default MultiSelectRelationFilter;

View file

@ -0,0 +1,33 @@
// * Packages
import { route } from "ziggy-js";
// * Other
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
import { addFilterToUrl } from "@/lib/filters";
type Props = {
fieldName: string;
modelName: string;
label: string;
}
const SwitchFilter = (props: Props) => {
const { label, fieldName, modelName } = props;
return (
<SimpleSwitch
name={fieldName}
label={label}
required={false}
disabled={false}
checked={route().params[fieldName] === "true"}
setData={(name, value) => {
const params = {
...route().params,
[name]: value,
};
addFilterToUrl({ modelName, params });
}}
/>
)
}
export default SwitchFilter;

View file

@ -0,0 +1,62 @@
// * Packages
import { Filter } from "lucide-react";
import { ReactNode } from "react";
// * Components shadcn
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
const FiltersWrapper = ({ children }: { children: ReactNode }) => {
return (
<div className="flex justify-between items-center">
<div className="flex justify-end gap-2">
<Sheet>
<SheetTrigger asChild>
<BtnOptionnalLinkWithTooltip
content={<Filter />}
tooltipContent={
<p>
{str(
useTrans(
"back.model_filters.button_tooltip",
),
)
.ucFirst()
.value()}
</p>
}
type="button"
size="icon"
variant="outline"
/>
</SheetTrigger>
<SheetContent>
<SheetHeader className="mb-4">
<SheetTitle>
{str(useTrans("back.model_filters.sheet_title"))
.ucFirst()
.value()}
</SheetTitle>
</SheetHeader>
<SheetDescription asChild>
<div className="flex flex-col gap-3">
{children}
</div>
</SheetDescription>
</SheetContent>
</Sheet>
</div>
</div>
);
};
export default FiltersWrapper;

View file

@ -33,6 +33,7 @@ type CompleteInputFileProps = FileValidation & {
required?: boolean;
fileName?: string;
hasRefreshBtn?: boolean;
parentErrors?: Record<string, string> | null,
setData: (name: string, value: File | string | null) => void;
reset: (name?: string) => void;
};
@ -82,7 +83,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
}
);
const localErrors = props.parentErrors ?? errors;
const [isDialogOpen, setDialogOpen] = useState(false);
const [accept, setAccept] = useState<Record<string, Array<string>>>({
@ -300,7 +301,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
type="button"
className={cn(
"flex border border-dashed overflow-hidden whitespace-normal [&_svg]:!pointer-events-auto [&_svg]:!size-auto [&_svg]:!shrink text-muted-foreground w-full h-36",
{ "border-destructive": errors[name] }
{ "border-destructive": localErrors[name] }
)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...getRootProps()}
@ -349,7 +350,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
/>
)}
</div>
<InputError message={errors[name]} />
<InputError message={localErrors[name]} />
</div>
);
}

View file

@ -138,7 +138,7 @@ export default function EnumSelect({
aria-expanded={open}
disabled={disabled}
className={cn(
"w-full h-auto max-h-10 justify-between whitespace-normal text-start",
"w-full h-10 justify-between whitespace-normal text-start",
{ "text-muted-foreground": !selectedEnum },
{ "border-destructive/50": localErrors[name] },
)}
@ -177,7 +177,7 @@ export default function EnumSelect({
{Object.values(currentOptions).length === 0 && (
<p className="text-sm text-muted-foreground text-center py-5">{useTrans("back.table_no_results")}</p>
)}
<div className="flex flex-col justify-between gap-1">
<div className="flex flex-col justify-between">
{Object.values(currentOptions).map((option) => (
<Button
key={option.value}

View file

@ -330,20 +330,18 @@ export default function ModelSelect({
</div>
<div
className="overflow-auto border-t flex flex-col justify-between p-1 gap-1"
style={{ minHeight: options.length > 0 && lastPage !== 1 ? '265px' : '225px' }}
style={{ minHeight: options.length > 0 && lastPage !== 1 ? '250px' : '200px' }}
>
{!loading && options.length === 0 && (
<p className="text-sm text-muted-foreground text-center py-5">{useTrans("back.table_no_results")}</p>
)}
{loading ? (
<>
{[...Array(pageSize)].map(() => (
<Skeleton className="h-10" />
))}
</>
) : (
<div className="flex flex-col justify-between gap-1">
{options.map((option) => (
<div className="flex flex-col justify-between">
{loading ? (
[...Array(pageSize)].map(() => (
<Skeleton className="h-9 mb-1" />
))
) : (
options.map((option) => (
<Button
key={option.id}
className="w-full h-auto min-h-10 justify-between whitespace-normal text-start"
@ -354,9 +352,9 @@ export default function ModelSelect({
<span>{getModelField(option)}</span>
{selectedId === option.id && <CheckIcon />}
</Button>
))}
</div>
)}
))
)}
</div>
{/* Pagination boutons */}
{options.length > 0 && lastPage !== 1 && (
<div className="flex flex-col xl:flex-row justify-center items-center gap-1.5">

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,23 @@
// * Packages
import type { ImageOptions as TiptapImageOptions } from '@tiptap/extension-image';
import { Image as TiptapImage } from 'reactjs-tiptap-editor/image';
import { Editor } from 'reactjs-tiptap-editor';
// * Other
import ImageButton from '@/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton';
import useTrans from '@/hooks/use-translations';
export const Image = TiptapImage.extend<TiptapImageOptions>({
addOptions() {
return {
...this.parent?.(),
openOnClick: false,
button: ({ editor }: { editor: Editor }) => ({
component: ImageButton,
componentProps: {
editor,
tooltip: useTrans('back.wysiwyg_plugins.image.tooltip'),
},
}),
};
},
});

View file

@ -0,0 +1,318 @@
// * Packages
import { useState } from "react";
import axios from "axios";
import { route } from "ziggy-js";
import { ImageUpIcon } from "lucide-react";
import { Editor } from "reactjs-tiptap-editor";
import { z } from "zod";
// * Components shadcn
import {
Dialog,
DialogDescription,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
// * Other
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile";
import SimpleString from "@/back/Components/Inputs/SimpleString";
import useTrans from "@/hooks/use-translations";
import str from "@/hooks/use-string";
type ImageProps = {
/** Wysiwyg editor instance. */
editor: Editor;
/** Wysiwyg menu button tooltip. */
tooltip: string;
};
export default function ImageButton({ editor, tooltip }: ImageProps) {
// Get all editor options define with customOptions in the parent SimpleWysiwyg.
const editorOptions = editor.options.editorProps?.attributes as { [name: string]: string };
// State of the plugin modal.
const [open, setOpen] = useState(false);
// Value of the input file image.
const [inputFile, setFile] = useState<string | File | null>(null);
// Value of the input alt image.
const [inputAlt, setInputAlt] = useState<string>("");
// State of the loader.
const [loading, setLoading] = useState(false);
// Value of errors.
const [errors, setErrors] = useState<Record<string, string>>({});
// Duration of modal closing animation.
const animationTime = 200;
// Zod image schema.
const inputsSchema = z.object({
inputFile: z
.instanceof(File, {
message: useTrans("validation.file", {
params: {
attribute: useTrans("validation.custom.image"),
},
}),
})
.refine(
(file) =>
[
"image/jpeg",
"image/jpg",
"image/png",
"image/webp",
].includes(file.type),
{
message: useTrans("validation.regex", {
params: {
attribute: useTrans("validation.custom.image"),
},
}),
},
)
.refine((file) => file.size <= 5 * 1024 * 1024, {
message: useTrans("validation.size.file", {
params: {
attribute: useTrans("validation.custom.image"),
size: "5 000",
},
}),
}),
inputAlt: z
.string({
message: useTrans("validation.string", {
params: {
attribute: useTrans("validation.custom.image_alt"),
},
}),
})
.min(3, {
message: useTrans("validation.min.string", {
params: {
attribute: useTrans("validation.custom.image_alt"),
min: "3",
},
}),
})
.max(255, {
message: useTrans("validation.max.string", {
params: {
attribute: useTrans("validation.custom.image_alt"),
max: "255",
},
}),
}),
});
/**
* Upload image in storage.
*
* @param file
* @param alt
* @return Promise<void>
*/
const uploadImage = async (file: File, alt: string): Promise<void> => {
// Get the csrf token value.
const csrfToken =
document
.querySelector('meta[name="csrf-token"]')
?.getAttribute("content") || "";
// Prepare the form data.
const data = new FormData();
data.append("upload", file);
data.append("folder", editorOptions.model);
const uploadRoute = route("back.wysiwyg.upload");
try {
const response = await axios.post(uploadRoute, data, {
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-Inertia": "false",
"X-CSRF-TOKEN": csrfToken,
},
});
editor.commands.setImage({
src: response.data.url,
alt: alt,
});
} catch (error: Error | unknown) {
throw new Error(`Erreur upload: ${(error as Error).message}`);
}
};
/**
* Add new image.
*
* @return void
*/
const handleAddImage = (): void => {
setLoading(true);
try {
const parsed = inputsSchema.parse({ inputFile, inputAlt });
uploadImage(parsed.inputFile, parsed.inputAlt);
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
} catch (err) {
// Get zod error validations.
if (err instanceof z.ZodError) {
const fieldErrors: Record<string, string> = {};
const keyMap: Record<string, string> = {
inputFile: "image",
inputAlt: "alt",
};
err.issues.forEach((e) => {
const mappedKey = keyMap[e.path[0] as string];
if (mappedKey) fieldErrors[mappedKey] = e.message;
});
setErrors(fieldErrors);
}
} finally {
setLoading(false);
}
};
const handleSetAlt = (name: string, value: string) => {
setErrors((prev) => ({ ...prev, [name]: "" }));
setInputAlt(value);
};
/**
* Reset all states and values in the component.
*
* @return void
*/
const resetComponent = () => {
setFile(null);
setInputAlt("");
setErrors({});
setLoading(false);
};
/**
* Update url value from string input.
*
* @return void
*/
const handleSetImage = (
name: string,
value: string | File | null,
): void => {
setErrors((prev) => ({ ...prev, [name]: "" }));
setFile(value);
};
/**
* Close modal and reset component.
*
* @return void
*/
const handleCancelImage = (): void => {
setOpen(false);
setTimeout(() => resetComponent(), animationTime);
};
return (
<Dialog
open={open}
onOpenChange={(v) => {
setOpen(v);
if (!v) setTimeout(() => resetComponent(), animationTime);
}}
>
{/* Button trigger in wysiwyg navigation. */}
<DialogTrigger asChild>
<BtnOptionnalLinkWithTooltip
content={<ImageUpIcon className="w-4 h-4 m-auto" />}
tooltipContent={tooltip}
className="cursor-grab richtext-px-2 richtext-w-[32px] richtext-h-[32px]"
type="button"
variant="ghost"
size="icon"
/>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
{useTrans("back.wysiwyg_plugins.image.title")}
</DialogTitle>
<DialogDescription>
{useTrans("back.wysiwyg_plugins.image.subtitle")}
</DialogDescription>
</DialogHeader>
<CompleteInputFile
fileName="image"
name="image"
label={str(useTrans("validation.custom.image"))
.ucFirst()
.value()}
setData={handleSetImage}
reset={(name) => console.log("reset", name)}
value={null}
required={true}
maxFileSize="5120"
allowedFormats="jpg,jpeg,png,webp"
validationRules={{
width: "1920",
height: "1080",
}}
parentErrors={errors}
/>
<SimpleString
name="alt"
label={str(useTrans("validation.custom.image_alt"))
.ucFirst()
.value()}
placeholder="ex: John Doe"
required={true}
value={inputAlt}
setData={handleSetAlt}
disabled={loading}
parentErrors={errors}
/>
<div className="flex justify-between">
<div className="flex justify-between gap-1.5">
{/* Save button. */}
<BtnOptionnalLinkWithTooltip
content={str(useTrans("crud.actions.save"))
.ucFirst()
.value()}
tooltipContent={useTrans(
"back.wysiwyg_plugins.image.add",
)}
className="cursor-pointer"
type="button"
size="default"
disabled={loading}
onClick={handleAddImage}
/>
{/* Cancel button. */}
<BtnOptionnalLinkWithTooltip
content={str(useTrans("back.cancel"))
.ucFirst()
.value()}
tooltipContent={useTrans(
"back.wysiwyg_plugins.image.cancel",
)}
className="cursor-pointer"
variant="secondary"
type="button"
size="default"
disabled={loading}
onClick={handleCancelImage}
/>
</div>
</div>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,13 @@
import '@tiptap/core';
declare module '@tiptap/core' {
interface Commands<ReturnType> {
Image: {
setImage: (attrs: {
src: string,
alt: string;
}) => ReturnType;
unsetImage: () => ReturnType;
};
}
}

View file

@ -30,7 +30,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
setLink: attrs => ({ state, commands }) => {
const { from, to } = state.selection;
// Vérifier si un lien est sélectionné
// Check if there is a selected link.
let linkFound = false;
state.doc.nodesBetween(from, to, node => {
if (node.marks) {
@ -41,7 +41,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
if (linkFound) {
return commands.command(({ tr, state, dispatch }) => {
// Récupérer le mark existant
// Get the existing mark.
let existingMark = null;
state.doc.nodesBetween(from, to, node => {
if (node.marks) {
@ -52,27 +52,27 @@ export const Link = TiptapLink.extend<LinkOptions>({
if (!existingMark) return false;
// Supprimer le texte existant
// Remove the existing text.
tr.delete(from, to);
// Insérer le nouveau texte
// Insert the new text.
tr.insertText(attrs.text, from);
// Ajouter le mark avec les nouveaux attrs
// Set the mark with new attributes.
tr.addMark(
from,
from + attrs.text.length,
state.schema.marks[this.name].create(attrs)
);
// Appliquer la transaction
// Apply the modification.
if (dispatch) dispatch(tr);
return true;
});
}
// Sinon créer un nouveau lien comme avant
// Otherwise, create a new link like before.
return commands.insertContent({
type: "text",
text: attrs.text,
@ -82,7 +82,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
unsetLink: () => ({ state, commands }: CommandProps) => {
const { from, to } = state.selection;
// Vérifier qu’il y a bien un mark Link
// Check there is a link mark.
let hasLink = false;
state.doc.nodesBetween(from, to, node => {
if (node.marks?.some(m => m.type.name === this.name)) {
@ -92,7 +92,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
if (!hasLink) return false;
// Retirer le mark de la sélection
// Remove the mark from the selection.
return commands.unsetMark(this.name);
},
};
@ -144,11 +144,11 @@ export const Link = TiptapLink.extend<LinkOptions>({
const link = target.closest("a");
if (!link) return false;
// Trouver la position exacte du node <a>
// Find the exact position of the gat <a>.
const { state } = view;
const $pos = state.doc.resolve(pos);
// 🔥 Étendre la sélection à l'ensemble du mark
// Extend the selection to the entire mark.
const markRange = getMarkRange($pos, state.schema.marks.Link);
if (markRange) {
view.dispatch(
@ -158,7 +158,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
);
}
// Ouvrir ta modale
// Open the modale.
this.editor.emit("open-link-editor", {
href: link.getAttribute("href") ?? "",
blank: link.getAttribute("target") === "_blank",

View file

@ -10,7 +10,6 @@ import { FontSize } from "reactjs-tiptap-editor/fontsize";
import { Heading } from "reactjs-tiptap-editor/heading";
import { History } from "reactjs-tiptap-editor/history";
import { HorizontalRule } from "reactjs-tiptap-editor/horizontalrule";
import { Image } from "reactjs-tiptap-editor/image";
import { Indent } from "reactjs-tiptap-editor/indent";
import { Italic } from "reactjs-tiptap-editor/italic";
import { OrderedList } from "reactjs-tiptap-editor/orderedlist";
@ -19,14 +18,13 @@ import { Strike } from "reactjs-tiptap-editor/strike";
import { TextAlign } from "reactjs-tiptap-editor/textalign";
import { TextUnderline } from "reactjs-tiptap-editor/textunderline";
import { Color } from "reactjs-tiptap-editor/color";
import axios from "axios";
import "react-image-crop/dist/ReactCrop.css";
import "reactjs-tiptap-editor/lib/style.css";
import { route } from "ziggy-js";
// * Components shadcn
import { Label } from "@/components/ui/label";
// * Other
import { Link } from "@/back/Components/Inputs/Wysiwyg/Plugins/Link/Link";
import { Image } from "@/back/Components/Inputs/Wysiwyg/Plugins/Image/Image";
import InputError from "@/back/Components/InputError";
import WordCounter from "@/back/Components/WordCounter";
import useTrans from "@/hooks/use-translations";
@ -89,27 +87,8 @@ export default function SimpleWysiwyg({
TextAlign,
Blockquote,
HorizontalRule,
Image.configure({
upload: async (file: File): Promise<string> => {
// Prepare the form data.
const data = new FormData();
data.append("upload", file);
data.append("folder", model);
const uploadRoute = route("back.wysiwyg.upload");
try {
const response = await axios.post(
uploadRoute,
data,
{ headers: { "Content-Type": "multipart/form-data" } }
);
return response.data.url;
} catch (error: Error | unknown) {
throw new Error(`Erreur upload: ${(error as Error).message}`);
}
},
}),
// Custom plugins.
Image,
Link,
];
@ -129,11 +108,17 @@ export default function SimpleWysiwyg({
setData(name, value);
};
// Define some custom attributes in the editor options,
// so that we can access them from plugins.
const customOptions: UseEditorOptions = {
editorProps: {
attributes: {
// Required status.
required: String(required),
// Target field name.
id,
// Target model name.
model,
},
},
};

View file

@ -59,23 +59,36 @@ import str from "@/hooks/use-string";
import useTrans from "@/hooks/use-translations";
import { AppEnv, AuthProp, LaravelEnum } from "@/back/types/global";
type NavList = Array<{
type NavListProps = Array<{
/** Title of the group. */
title: string,
/** Condition to set the visibility of the group. */
show: boolean,
/** Links presents in the group. */
links: Array<{
/** Title of the button. */
title: string,
/** Main model of the button (used for route checking). */
model?: string,
/** External link of the button (if it's a not CRUD, just a simple link). */
link?: string,
/** Define some conditions for active or not the button (in addition to the route model checking if defined). */
activeCondition?: boolean[],
/** Condition to set the visibility of the button. */
show: boolean,
/** Lucide icon of the button. */
icon: ElementType,
/** Define some actions in side popover (like create/trash). */
actions?: (model: string) => ReactNode,
}>
}>
type CustomDropdownMenuItem = {
type CustomDropdownMenuItemProps = {
/** Link of the action. */
route: string;
policy?: boolean;
/** Lucide icon of the action. */
icon?: ElementType;
/** Translation of the action. */
trans?: string;
};
@ -89,7 +102,7 @@ export default function AppSidebar() {
const { state } = useSidebar();
const prevStateRef = useRef(state);
const isCollapsed = state === "collapsed";
const navList: NavList = [
const navList: NavListProps = [
{
title: useTrans("back.pages"),
show: true,
@ -135,10 +148,9 @@ export default function AppSidebar() {
show: authPolicies.news.viewAny || auth.policies.contact_counts.viewAny,
links: [
{
title: str(useTrans("models.classes.news", { choice: 2 }))
.ucFirst()
.value(),
title: str(useTrans("models.classes.news", { choice: 2 })).ucFirst().value(),
model: "news",
activeCondition: [route().current("back.news-categories.*"), route().current('back.news-tags.*')],
icon: NewspaperIcon,
show: auth.policies.news.viewAny,
actions: (model: string) => filterActions({
@ -159,36 +171,29 @@ export default function AppSidebar() {
<CustomDropdownMenuItem
route={route(`back.news-categories.index`)}
icon={FolderIcon}
trans={str(useTrans("models.classes.news-category", { choice: 2 }))
.ucFirst()
.value()}
trans={str(useTrans("models.classes.news-category", { choice: 2 })).ucFirst().value()}
/>
),
authPolicies.newsTags.viewAny && (
<CustomDropdownMenuItem
route={route(`back.news-tags.index`)}
icon={FolderIcon}
trans={str(useTrans("models.classes.news-tag", { choice: 2 }))
.ucFirst()
.value()}
icon={TagIcon}
trans={str(useTrans("models.classes.news-tag", { choice: 2 })).ucFirst().value()}
/>
),
]
})
},
{
title: str(useTrans("models.classes.contact-count"))
.ucFirst()
.value(),
title: str(useTrans("models.classes.contact-count")).ucFirst().value(),
model: "contact-counts",
icon: ContactIcon,
show: auth.policies.contact_counts.viewAny,
},
{
title: str(useTrans("models.classes.document", { choice: 2 }))
.ucFirst()
.value(),
title: str(useTrans("models.classes.document", { choice: 2 })).ucFirst().value(),
model: "documents",
activeCondition: [route().current("back.document-categories.*"), route().current('back.document-tags.*')],
icon: FileInputIcon,
show: auth.policies.documents.viewAny,
actions: (model: string) => filterActions({
@ -198,33 +203,27 @@ export default function AppSidebar() {
route={route(`back.${model}.create`)}
/>
),
authPolicies.documentTags.create && (
<CustomDropdownMenuItem
icon={TagIcon}
route={route(`back.document-tags.index`)}
trans={str(useTrans("models.classes.document-tag", { choice: 2 }))
.ucFirst()
.value()}
/>
),
authPolicies.documentCategories.create && (
<CustomDropdownMenuItem
icon={FolderIcon}
route={route(`back.document-categories.index`)}
trans={str(useTrans("models.classes.document-category", { choice: 2 }))
.ucFirst()
.value()}
trans={str(useTrans("models.classes.document-category", { choice: 2 })).ucFirst().value()}
/>
),
authPolicies.documentTags.create && (
<CustomDropdownMenuItem
icon={TagIcon}
route={route(`back.document-tags.index`)}
trans={str(useTrans("models.classes.document-tag", { choice: 2 })).ucFirst().value()}
/>
)
]
})
},
{
title: str(useTrans("models.classes.company", { choice: 2 }))
.ucFirst()
.plural()
.value(),
title: str(useTrans("models.classes.company", { choice: 2 })).ucFirst().plural().value(),
model: "companies",
activeCondition: [route().current("back.company-activities.*"), route().current('back.company-sectors.*')],
icon: Building2Icon,
show: auth.policies.companies.viewAny,
actions: (model: string) => filterActions({
@ -322,7 +321,7 @@ export default function AppSidebar() {
route,
icon: Icon = Views.CREATION.icon,
trans = str(useTrans(`crud.actions.${Views.CREATION.label}`)).ucFirst().value(),
}: CustomDropdownMenuItem) => {
}: CustomDropdownMenuItemProps) => {
return (
<DropdownMenuItem className="p-0">
<Button variant="ghost" asChild>
@ -375,12 +374,10 @@ export default function AppSidebar() {
<SidebarMenu>
{navGroup.links.map((navLink) => {
if (navLink.show) {
const isActive = route().current(`back.${navLink.model}.*`) || navLink.activeCondition?.some(Boolean);
const sidebarButton = (
<SidebarMenuButton
className={`${route().current(`back.${navLink.model}.*`)
? "text-secondary-foreground"
: "text-primary-foreground"
}`}
className={isActive ? "text-secondary-foreground" : "text-primary-foreground"}
asChild
>
{navLink.link ? (
@ -405,10 +402,9 @@ export default function AppSidebar() {
);
return <SidebarMenuItem
key={navLink.title}
className={`transition-colors rounded-md ${route().current(
`back.${navLink.model}.*`,
) ? "bg-secondary text-secondary-foreground" : "bg-opacity-0"
}`}
className={
`transition-colors rounded-md ${isActive ? "bg-secondary text-secondary-foreground" : "bg-opacity-0"}`
}
>
{isCollapsed ? (
<Tooltip>
@ -426,10 +422,9 @@ export default function AppSidebar() {
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuAction
className={`${route().current(
`back.${navLink.model}.*`,
) ? "text-secondary-foreground" : ""
} !top-0 !right-0 px-4 h-full`}
className={
`${isActive ? "text-secondary-foreground" : ""} !top-0 !right-0 px-4 h-full`
}
>
<MoreHorizontalIcon />
</SidebarMenuAction>

View file

@ -54,6 +54,22 @@ export default function ModelActions({
const { delete: destroy, patch } = useForm();
const { toast } = useToast();
// Translations.
const successfulArchivation = useTrans('crud.messages.successful_archivation');
const successfulArchivationDetails = useTrans("crud.messages.successful_archivation_details");
const canceledArchivation = useTrans('crud.messages.canceled_archivation');
const canceledArchivationDetails = useTrans("crud.messages.canceled_archivation_details");
const successfulRestoration = useTrans('crud.messages.successful_restoration');
const successfulRestorationDetails = useTrans("crud.messages.successful_restoration_details");
const canceledRestoration = useTrans('crud.messages.canceled_restoration');
const canceledRestorationDetails = useTrans("crud.messages.canceled_restoration_details");
const successfulDeletion = useTrans('crud.messages.successful_deletion');
const successfulDeletionDetails = useTrans("crud.messages.successful_deletion_details");
const canceledDeletion = useTrans('crud.messages.canceled_deletion');
const canceledDeletionDetails = useTrans("crud.messages.canceled_deletion_details");
/**
* Action call on model.
* @param event FormEvent<HTMLFormElement>
@ -73,34 +89,34 @@ export default function ModelActions({
[Views.ARCHIVATION.label]: {
method: destroy,
success: {
title: "Archivation réussie !",
description: "Vous venez d'archiver une entrée.",
title: successfulArchivation,
description: successfulArchivationDetails,
},
error: {
title: "Archivation annulée !",
description: "Un problème est survenu lors de l'archivation de cette entrée.",
title: canceledArchivation,
description: canceledArchivationDetails,
},
},
[Views.RESTORATION.label]: {
method: patch,
success: {
title: "Restoration réussie !",
description: "Vous venez de restorer une entrée.",
title: successfulRestoration,
description: successfulRestorationDetails,
},
error: {
title: "Restoration annulée !",
description: "Un problème est survenu lors de la restoration de cette entrée.",
title: canceledRestoration,
description: canceledRestorationDetails,
},
},
[Views.DELETION.label || Views.FORCEDELETION.label]: {
method: destroy,
success: {
title: "Suppression réussie !",
description: "Vous venez de supprimer définitivement une entrée.",
title: successfulDeletion,
description: successfulDeletionDetails,
},
error: {
title: "Suppression annulée !",
description: "Un problème est survenu lors de la suppression de cette entrée.",
title: canceledDeletion,
description: canceledDeletionDetails,
},
},
};
@ -235,7 +251,7 @@ export default function ModelActions({
)}
{Boolean(allowedActions.length) && (
<div className={`flex justify-between items-center ${
!inDialog ? "flex-col sm:flex-row mt-4 xl:mt-0" : "flex-col w-full"
!inDialog ? "flex-col sm:flex-row mt-4 xl:mt-0 gap-1.5" : "flex-col w-full"
}`}>
{inDialog ? (
<DropdownMenu open={open} onOpenChange={setOpen}>

View file

@ -1,18 +1,22 @@
import str from "@/hooks/use-string"
import DataTable from "./Table/DataTable"
import useTrans from "@/hooks/use-translations"
import DataTableFilterButton from "./Table/DataTableFilterButton";
import { AppEnv, NewsModel, Resource, TranslationField } from "../types/global";
// * Packages
import { Row } from "@tanstack/react-table";
import { usePage } from "@inertiajs/react";
import { NewspaperIcon } from "lucide-react";
// * Components shadcn
import { Badge } from "@/components/ui/badge";
// * Other
import DataTable from "@/back/Components/Table/DataTable"
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
import { AppEnv, NewsModel, Resource } from "@/back/types/global";
import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge";
import { renderTranslationCell } from "@/lib/translationCellFallback";
import { Views } from "@/lib/utils";
import { useFormatedDate } from "@/hooks/use-formated-value";
import { Badge } from "@/components/ui/badge";
import NewsStatusBadge from "./NewsStatusBadge";
import { renderTranslationCell } from "@/lib/translationCellFallback";
import useTrans from "@/hooks/use-translations"
import str from "@/hooks/use-string"
interface Props {
news: Resource
news: Resource;
}
const AssociatedNewsList = (props: Props) => {
const { news } = props;
@ -25,35 +29,39 @@ const AssociatedNewsList = (props: Props) => {
accessorKey: "title",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`)).ucFirst().value()}
label={str(useTrans(`validation.attributes.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<NewsModel> }) => {
return renderTranslationCell(
row.getValue("title")
)
return renderTranslationCell(row.getValue("title"));
},
},
{
accessorKey: "status",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.custom.${column.id}`)).ucFirst().value()}
label={str(useTrans(`validation.custom.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
cell: ({ row }: { row: Row<NewsModel> }) => {
return (
<NewsStatusBadge value={parseInt(row.getValue('status'))} />
)
<NewsStatusBadge value={parseInt(row.getValue("status"))} />
);
},
},
{
accessorKey: "updated_at",
header: ({ column }: { column: { id: string } }) => (
<DataTableFilterButton
label={str(useTrans(`validation.attributes.${column.id}`)).ucFirst().value()}
label={str(useTrans(`validation.attributes.${column.id}`))
.ucFirst()
.value()}
field={column.id}
/>
),
@ -67,18 +75,29 @@ const AssociatedNewsList = (props: Props) => {
return (
<>
<h3 className="mt-5 mb-1 text-xl font-medium">{str(useTrans("validation.custom.newsCategory.news")).ucFirst().value()}</h3>
<h3 className="text-2xl font-semibold leading-none tracking-tight flex flex-row w-full items-start my-4">
<NewspaperIcon className="me-2" />
{str(
useTrans("back.associated_model", {
params: {
model: useTrans("models.classes.news", {
choice: 2,
}),
},
choice: 2,
}),
)
.ucFirst()
.value()}
</h3>
<DataTable
columns={columns}
modelRoute={"news"}
modelsPaginate={news}
actions={[
Views.VISUALIZATION,
Views.EDITION
]}
actions={[Views.VISUALIZATION, Views.EDITION]}
/>
</>
)
}
);
};
export default AssociatedNewsList;

Some files were not shown because too many files have changed in this diff Show more