diff --git a/.gitignore b/.gitignore index d2f723f2..05980c41 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/app/Console/Commands/MeilisearchUpdate.php b/app/Console/Commands/MeilisearchUpdate.php deleted file mode 100644 index f98a8946..00000000 --- a/app/Console/Commands/MeilisearchUpdate.php +++ /dev/null @@ -1,78 +0,0 @@ -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}"); - }); - } -} diff --git a/app/Console/Commands/UpdateMeilisearch.php b/app/Console/Commands/UpdateMeilisearch.php new file mode 100644 index 00000000..ba7ec1c6 --- /dev/null +++ b/app/Console/Commands/UpdateMeilisearch.php @@ -0,0 +1,44 @@ +info("Import {$locale}..."); + app()->setLocale($locale); + + foreach ($models as $model) { + $this->call('scout:import', ['model' => $model]); + } + } + } +} diff --git a/app/Helpers/DocumentHelper.php b/app/Helpers/DocumentHelper.php index d7f1d850..f9598d3c 100644 --- a/app/Helpers/DocumentHelper.php +++ b/app/Helpers/DocumentHelper.php @@ -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; + } } diff --git a/app/Http/Controllers/Back/CompanyActivityController.php b/app/Http/Controllers/Back/CompanyActivityController.php index d71fddbf..28308fae 100644 --- a/app/Http/Controllers/Back/CompanyActivityController.php +++ b/app/Http/Controllers/Back/CompanyActivityController.php @@ -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, ]); } diff --git a/app/Http/Controllers/Back/CompanyController.php b/app/Http/Controllers/Back/CompanyController.php index ba7ca18f..3abd4a71 100644 --- a/app/Http/Controllers/Back/CompanyController.php +++ b/app/Http/Controllers/Back/CompanyController.php @@ -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, ]); } diff --git a/app/Http/Controllers/Back/CompanySectorController.php b/app/Http/Controllers/Back/CompanySectorController.php index a49a122d..a6cf5c27 100644 --- a/app/Http/Controllers/Back/CompanySectorController.php +++ b/app/Http/Controllers/Back/CompanySectorController.php @@ -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, ]); } diff --git a/app/Http/Controllers/Back/DocumentCategoryController.php b/app/Http/Controllers/Back/DocumentCategoryController.php index fc23d75a..f911fb6e 100644 --- a/app/Http/Controllers/Back/DocumentCategoryController.php +++ b/app/Http/Controllers/Back/DocumentCategoryController.php @@ -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 */ + $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 */ + $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(); + } } diff --git a/app/Http/Controllers/Back/DocumentController.php b/app/Http/Controllers/Back/DocumentController.php index 18e35fb0..7ae3284e 100644 --- a/app/Http/Controllers/Back/DocumentController.php +++ b/app/Http/Controllers/Back/DocumentController.php @@ -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, ]); } diff --git a/app/Http/Controllers/Back/DocumentTagController.php b/app/Http/Controllers/Back/DocumentTagController.php index 8fd6af1e..073eaca1 100644 --- a/app/Http/Controllers/Back/DocumentTagController.php +++ b/app/Http/Controllers/Back/DocumentTagController.php @@ -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 */ + $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 */ + $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(); + } } diff --git a/app/Http/Controllers/Back/NewsCategoryController.php b/app/Http/Controllers/Back/NewsCategoryController.php index 0133d9c1..beaa1fc6 100644 --- a/app/Http/Controllers/Back/NewsCategoryController.php +++ b/app/Http/Controllers/Back/NewsCategoryController.php @@ -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), diff --git a/app/Http/Controllers/Back/NewsController.php b/app/Http/Controllers/Back/NewsController.php index 9bbf5fe5..129476f6 100644 --- a/app/Http/Controllers/Back/NewsController.php +++ b/app/Http/Controllers/Back/NewsController.php @@ -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(); diff --git a/app/Http/Controllers/Back/NewsTagController.php b/app/Http/Controllers/Back/NewsTagController.php index dea35790..a4a4fc57 100644 --- a/app/Http/Controllers/Back/NewsTagController.php +++ b/app/Http/Controllers/Back/NewsTagController.php @@ -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), diff --git a/app/Http/Controllers/Front/SearchController.php b/app/Http/Controllers/Front/SearchController.php index 981b03c0..8f2ad16f 100644 --- a/app/Http/Controllers/Front/SearchController.php +++ b/app/Http/Controllers/Front/SearchController.php @@ -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 = '/(? 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 = '/(?$0', + $snippet + ); + } + + $snippets[] = trim($snippet); + if (count($snippets) >= 3) break; + } + + $result = implode('… ', $snippets); + $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); + + return trim($result); + } } diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index c7d4454e..388bfcb0 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -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(), diff --git a/app/Http/Requests/Back/News/StoreNewsRequest.php b/app/Http/Requests/Back/News/StoreNewsRequest.php index b5d7d9ed..c5165e58 100644 --- a/app/Http/Requests/Back/News/StoreNewsRequest.php +++ b/app/Http/Requests/Back/News/StoreNewsRequest.php @@ -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'), diff --git a/app/Http/Requests/Front/Search/SearchAjaxRequest.php b/app/Http/Requests/Front/Search/SearchAjaxRequest.php new file mode 100644 index 00000000..ac1e5029 --- /dev/null +++ b/app/Http/Requests/Front/Search/SearchAjaxRequest.php @@ -0,0 +1,50 @@ +ajax(); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|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."); + } + }, + ], + ]; + } +} diff --git a/app/Http/Requests/Front/SearchRequest.php b/app/Http/Requests/Front/Search/SearchRequest.php similarity index 94% rename from app/Http/Requests/Front/SearchRequest.php rename to app/Http/Requests/Front/Search/SearchRequest.php index d6ee5b0b..f18e71f9 100644 --- a/app/Http/Requests/Front/SearchRequest.php +++ b/app/Http/Requests/Front/Search/SearchRequest.php @@ -1,6 +1,6 @@ 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'); + } } \ No newline at end of file diff --git a/app/Models/CompanySector.php b/app/Models/CompanySector.php index 5650f029..f0e2e0c4 100644 --- a/app/Models/CompanySector.php +++ b/app/Models/CompanySector.php @@ -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'); + } } \ No newline at end of file diff --git a/app/Models/Document.php b/app/Models/Document.php index 9957d487..5714cd4d 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -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 + */ + 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(); + } } diff --git a/app/Models/DocumentCategory.php b/app/Models/DocumentCategory.php index b378a105..172d7427 100644 --- a/app/Models/DocumentCategory.php +++ b/app/Models/DocumentCategory.php @@ -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, diff --git a/app/Models/DocumentTag.php b/app/Models/DocumentTag.php index f9ab43d8..84f05569 100644 --- a/app/Models/DocumentTag.php +++ b/app/Models/DocumentTag.php @@ -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, diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index d8aa046b..c2df355b 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -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 + */ + 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 /** diff --git a/app/Models/News.php b/app/Models/News.php index 3c9758a6..5faf6e99 100644 --- a/app/Models/News.php +++ b/app/Models/News.php @@ -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 + */ + 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 - ); - }); - } } diff --git a/app/Models/NewsTag.php b/app/Models/NewsTag.php index c33afaa0..48b6ce3b 100644 --- a/app/Models/NewsTag.php +++ b/app/Models/NewsTag.php @@ -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, diff --git a/app/Models/SearchIndex.php b/app/Models/SearchIndex.php deleted file mode 100644 index 2027a14e..00000000 --- a/app/Models/SearchIndex.php +++ /dev/null @@ -1,152 +0,0 @@ -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 = '/(? 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 = '/(?$0', - $snippet - ); - } - - $snippets[] = trim($snippet); - if (count($snippets) >= 3) break; - } - - $result = implode('… ', $snippets); - $result = preg_replace('/\s*…\s*(?:…\s*)+/', ' … ', $result); - - return trim($result); - } -} diff --git a/app/Policies/DocumentCategoryPolicy.php b/app/Policies/DocumentCategoryPolicy.php index 679d78a6..f7911cdd 100644 --- a/app/Policies/DocumentCategoryPolicy.php +++ b/app/Policies/DocumentCategoryPolicy.php @@ -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); + } } diff --git a/app/Policies/DocumentTagPolicy.php b/app/Policies/DocumentTagPolicy.php index 38db6225..519b5ba8 100644 --- a/app/Policies/DocumentTagPolicy.php +++ b/app/Policies/DocumentTagPolicy.php @@ -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); + } } diff --git a/app/Traits/Models/HasMeilisearchIndex.php b/app/Traits/Models/HasMeilisearchIndex.php deleted file mode 100644 index 5384c165..00000000 --- a/app/Traits/Models/HasMeilisearchIndex.php +++ /dev/null @@ -1,113 +0,0 @@ -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); - }); - } - } -} diff --git a/config/logging.php b/config/logging.php index b6d11541..f38d0ee8 100644 --- a/config/logging.php +++ b/config/logging.php @@ -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, + ], + ], ]; diff --git a/config/scout.php b/config/scout.php index 794a607e..d05b4e71 100644 --- a/config/scout.php +++ b/config/scout.php @@ -1,5 +1,6 @@ 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, + ], ], ]; diff --git a/database/factories/CompanyActivityFactory.php b/database/factories/CompanyActivityFactory.php new file mode 100644 index 00000000..ad54f07a --- /dev/null +++ b/database/factories/CompanyActivityFactory.php @@ -0,0 +1,29 @@ + + */ +class CompanyActivityFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + 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), + ]; + } +} diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php index 5fda6d51..a4974a8a 100644 --- a/database/factories/CompanyFactory.php +++ b/database/factories/CompanyFactory.php @@ -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(), diff --git a/database/factories/CompanySectorFactory.php b/database/factories/CompanySectorFactory.php new file mode 100644 index 00000000..9c8afb13 --- /dev/null +++ b/database/factories/CompanySectorFactory.php @@ -0,0 +1,28 @@ + + */ +class CompanySectorFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + "name" => $this->faker->unique()->words( + $this->faker->numberBetween(3, 4), + true + ), + "published" => $this->faker->boolean(50), + ]; + } +} diff --git a/database/factories/DocumentCategoryFactory.php b/database/factories/DocumentCategoryFactory.php index 47a78009..e63813c0 100644 --- a/database/factories/DocumentCategoryFactory.php +++ b/database/factories/DocumentCategoryFactory.php @@ -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, ]; } } diff --git a/database/factories/DocumentFactory.php b/database/factories/DocumentFactory.php index e8ed9471..f8938b51 100644 --- a/database/factories/DocumentFactory.php +++ b/database/factories/DocumentFactory.php @@ -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 + */ 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')); - }); - } } diff --git a/database/factories/DocumentTagFactory.php b/database/factories/DocumentTagFactory.php index 43c14a0b..48d82590 100644 --- a/database/factories/DocumentTagFactory.php +++ b/database/factories/DocumentTagFactory.php @@ -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 + */ public function definition(): array { + $name = $this->faker->unique()->word(); + $slug = Str::slug($name); + return [ - 'name' => $this->faker->unique()->word(), + 'name' => $name, + 'slug' => $slug, ]; } } diff --git a/database/factories/DynamicPageFactory.php b/database/factories/DynamicPageFactory.php index b00337bc..37a427b3 100644 --- a/database/factories/DynamicPageFactory.php +++ b/database/factories/DynamicPageFactory.php @@ -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, ]; } diff --git a/database/factories/NewsCategoryFactory.php b/database/factories/NewsCategoryFactory.php index 32d9dfb2..36e878a0 100644 --- a/database/factories/NewsCategoryFactory.php +++ b/database/factories/NewsCategoryFactory.php @@ -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, ]; } } diff --git a/database/factories/NewsFactory.php b/database/factories/NewsFactory.php index a2891efb..96b0ea35 100644 --- a/database/factories/NewsFactory.php +++ b/database/factories/NewsFactory.php @@ -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', ]; } } diff --git a/database/factories/NewsTagFactory.php b/database/factories/NewsTagFactory.php index 02fb2cfa..413f8b1c 100644 --- a/database/factories/NewsTagFactory.php +++ b/database/factories/NewsTagFactory.php @@ -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(), ]; } } diff --git a/database/factories/PageConfigFactory.php b/database/factories/PageConfigFactory.php index 85397b4f..558b4eb6 100644 --- a/database/factories/PageConfigFactory.php +++ b/database/factories/PageConfigFactory.php @@ -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 */ public function definition(): array { @@ -43,7 +46,6 @@ class PageConfigFactory extends Factory ], ]; } - return $data; } } diff --git a/database/migrations/2026_01_14_125607_populate_document_table.php b/database/migrations/2026_01_14_125607_populate_document_table.php index f4b1ff15..2e4e815b 100644 --- a/database/migrations/2026_01_14_125607_populate_document_table.php +++ b/database/migrations/2026_01_14_125607_populate_document_table.php @@ -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 { diff --git a/database/migrations/2026_01_20_120146_clean_comments_tables.php b/database/migrations/2026_01_20_120146_clean_comments_tables.php new file mode 100644 index 00000000..501a2f5e --- /dev/null +++ b/database/migrations/2026_01_20_120146_clean_comments_tables.php @@ -0,0 +1,312 @@ +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(); + }); + } +}; diff --git a/database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php b/database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php new file mode 100644 index 00000000..c96f4390 --- /dev/null +++ b/database/migrations/2026_01_20_153807_add_softdelete_to_documents_tags_and_categories.php @@ -0,0 +1,38 @@ +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(); + }); + } +}; diff --git a/database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php b/database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php new file mode 100644 index 00000000..0a0d748d --- /dev/null +++ b/database/migrations/2026_01_22_122511_alter_translatable_columns_in_tables.php @@ -0,0 +1,90 @@ +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(); + }); + } +}; diff --git a/database/seeders/CompanyActivitySeeder.php b/database/seeders/CompanyActivitySeeder.php new file mode 100644 index 00000000..33e1dfc7 --- /dev/null +++ b/database/seeders/CompanyActivitySeeder.php @@ -0,0 +1,19 @@ +create(); + } +} diff --git a/database/seeders/CompanySectorSeeder.php b/database/seeders/CompanySectorSeeder.php new file mode 100644 index 00000000..5949f191 --- /dev/null +++ b/database/seeders/CompanySectorSeeder.php @@ -0,0 +1,19 @@ +create(); + } +} diff --git a/database/seeders/CustomSeeder.php b/database/seeders/CustomSeeder.php new file mode 100644 index 00000000..5f09bf62 --- /dev/null +++ b/database/seeders/CustomSeeder.php @@ -0,0 +1,282 @@ +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')); + } +} diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 8746d6e5..12807789 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -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, ]); } } diff --git a/database/seeders/DocumentCategorySeeder.php b/database/seeders/DocumentCategorySeeder.php index 9c314502..be67b5db 100644 --- a/database/seeders/DocumentCategorySeeder.php +++ b/database/seeders/DocumentCategorySeeder.php @@ -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(); } } diff --git a/database/seeders/DocumentSeeder.php b/database/seeders/DocumentSeeder.php index e6746d4a..5ba8691c 100644 --- a/database/seeders/DocumentSeeder.php +++ b/database/seeders/DocumentSeeder.php @@ -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() + ); + }); } } diff --git a/database/seeders/DocumentTagSeeder.php b/database/seeders/DocumentTagSeeder.php index 21354266..25b74f5f 100644 --- a/database/seeders/DocumentTagSeeder.php +++ b/database/seeders/DocumentTagSeeder.php @@ -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(); } } diff --git a/database/seeders/DynamicPageSeeder.php b/database/seeders/DynamicPageSeeder.php index b1c49e25..adcb3c9a 100644 --- a/database/seeders/DynamicPageSeeder.php +++ b/database/seeders/DynamicPageSeeder.php @@ -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(); + }); } } diff --git a/database/seeders/NewsSeeder.php b/database/seeders/NewsSeeder.php index 33290ae4..ff4dd47f 100644 --- a/database/seeders/NewsSeeder.php +++ b/database/seeders/NewsSeeder.php @@ -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() ); diff --git a/database/seeders/NewsTagSeeder.php b/database/seeders/NewsTagSeeder.php index 3e979239..1350443f 100644 --- a/database/seeders/NewsTagSeeder.php +++ b/database/seeders/NewsTagSeeder.php @@ -9,6 +9,8 @@ class NewsTagSeeder extends Seeder { /** * Run the database seeds. + * + * @return void */ public function run(): void { diff --git a/lang/en/back.php b/lang/en/back.php index 325a4160..a3e8f564 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -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", ]; diff --git a/lang/en/crud.php b/lang/en/crud.php index 7e36d0db..a385b6b9 100644 --- a/lang/en/crud.php +++ b/lang/en/crud.php @@ -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 - ] ]; diff --git a/lang/en/models.php b/lang/en/models.php index 5865c8a4..80fff6a8 100644 --- a/lang/en/models.php +++ b/lang/en/models.php @@ -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", ], ]; diff --git a/lang/en/validation.php b/lang/en/validation.php index ced66178..c684132d 100644 --- a/lang/en/validation.php +++ b/lang/en/validation.php @@ -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 ?" ], ]; diff --git a/lang/fr/back.php b/lang/fr/back.php index 0a69653c..21d280ef 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -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", ]; diff --git a/lang/fr/crud.php b/lang/fr/crud.php index 40f6022c..ec12aed6 100644 --- a/lang/fr/crud.php +++ b/lang/fr/crud.php @@ -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 - ] ]; diff --git a/lang/fr/front.php b/lang/fr/front.php index b72d97d1..d20c87c8 100644 --- a/lang/fr/front.php +++ b/lang/fr/front.php @@ -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' => [ diff --git a/lang/fr/models.php b/lang/fr/models.php index d8181f21..5b3bd528 100644 --- a/lang/fr/models.php +++ b/lang/fr/models.php @@ -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é", ], ]; diff --git a/lang/fr/validation.php b/lang/fr/validation.php index 49147fac..c01c2d52 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -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 ?" ], ]; diff --git a/public/assets/css/style.css b/public/assets/css/style.css index 83119b1e..9747d058 100644 --- a/public/assets/css/style.css +++ b/public/assets/css/style.css @@ -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 */ diff --git a/public/favicon.ico b/public/favicon.ico deleted file mode 100644 index e69de29b..00000000 diff --git a/resources/favicon/front/apple-touch-icon.png b/resources/favicon/front/apple-touch-icon.png new file mode 100644 index 00000000..f4d469f9 Binary files /dev/null and b/resources/favicon/front/apple-touch-icon.png differ diff --git a/resources/favicon/front/favicon-16x16.png b/resources/favicon/front/favicon-16x16.png new file mode 100644 index 00000000..87f73d11 Binary files /dev/null and b/resources/favicon/front/favicon-16x16.png differ diff --git a/resources/favicon/front/favicon-32x32.png b/resources/favicon/front/favicon-32x32.png new file mode 100644 index 00000000..481b5cf1 Binary files /dev/null and b/resources/favicon/front/favicon-32x32.png differ diff --git a/resources/favicon/front/safari-pinned-tab.svg b/resources/favicon/front/safari-pinned-tab.svg new file mode 100644 index 00000000..bb8982e5 --- /dev/null +++ b/resources/favicon/front/safari-pinned-tab.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/resources/favicon/front/site.webmanifest b/resources/favicon/front/site.webmanifest new file mode 100644 index 00000000..65796046 --- /dev/null +++ b/resources/favicon/front/site.webmanifest @@ -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" +} \ No newline at end of file diff --git a/resources/favicon/front/web-app-manifest-192x192.png b/resources/favicon/front/web-app-manifest-192x192.png new file mode 100644 index 00000000..43350d16 Binary files /dev/null and b/resources/favicon/front/web-app-manifest-192x192.png differ diff --git a/resources/favicon/front/web-app-manifest-512x512.png b/resources/favicon/front/web-app-manifest-512x512.png new file mode 100644 index 00000000..6f1d37b8 Binary files /dev/null and b/resources/favicon/front/web-app-manifest-512x512.png differ diff --git a/resources/ts/back/Components/AssociatedCompaniesList.tsx b/resources/ts/back/Components/AssociatedCompaniesList.tsx new file mode 100644 index 00000000..c2dca4ec --- /dev/null +++ b/resources/ts/back/Components/AssociatedCompaniesList.tsx @@ -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 } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return row.getValue("name"); + }, + }, + { + accessorKey: "published", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {row.getValue("published") ? ( + + ) : ( + + )} + {str( + useTrans( + row.getValue("published") ? "back.yes" : "back.no", + ), + ) + .ucFirst() + .value()} + + ), + }, + { + accessorKey: "updated_at", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => ( + + {useFormatedDate(row.getValue("updated_at"))} + + ), + }, + ]; + + return ( + <> +

+ + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.company", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ + + ); +}; + +export default AssociatedCompaniesList; diff --git a/resources/ts/back/Components/AssociatedDocumentList.tsx b/resources/ts/back/Components/AssociatedDocumentList.tsx deleted file mode 100644 index f2e3a163..00000000 --- a/resources/ts/back/Components/AssociatedDocumentList.tsx +++ /dev/null @@ -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 } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) - }, - }, - { - accessorKey: "path", - header: ({ column }: { column: { id: string } }) => ( - - ), - cell: ({ row }: { row: Row }) => { - return (row.getValue("path") as TranslationField)[appEnv.locale] ? ( - ( - {appEnv.url + '/' + (row.getValue("path") as TranslationField)[appEnv.locale]} - ) - ) : (

{useTrans('back.table_not_known')}

); - }, - }, - ]; - - return ( - <> -

{str(useTrans("validation.custom.documentTag.documents")).ucFirst().value()}

- - - ) -} - -export default AssociatedDocumentList; diff --git a/resources/ts/back/Components/DocumentFinanceTagBadge.tsx b/resources/ts/back/Components/DocumentFinanceTagBadge.tsx deleted file mode 100644 index b0b9183b..00000000 --- a/resources/ts/back/Components/DocumentFinanceTagBadge.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { Badge } from "@/components/ui/badge"; - - -type DocumentFinanceTagBadgeProps = { - value: string; -}; - -export default function DocumentFinanceTagBadge({ - value, -}: DocumentFinanceTagBadgeProps) { - - return ( - - {value} - - ); -} diff --git a/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx new file mode 100644 index 00000000..4cc541df --- /dev/null +++ b/resources/ts/back/Components/Documents/AssociatedDocumentList.tsx @@ -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 } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return renderTranslationCell(row.getValue("name")); + }, + }, + { + accessorKey: "path", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row }) => { + return (row.getValue("path") as TranslationField)[ + appEnv.locale + ] ? ( + + {appEnv.url + + "/" + + (row.getValue("path") as TranslationField)[ + appEnv.locale + ]} + + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ); + }, + }, + ]; + + return ( + <> +

+ + {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.document", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ + + ); +}; + +export default AssociatedDocumentList; diff --git a/resources/ts/back/Components/DocumentExerciceBadge.tsx b/resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx similarity index 100% rename from resources/ts/back/Components/DocumentExerciceBadge.tsx rename to resources/ts/back/Components/Documents/DocumentExerciceBadge.tsx diff --git a/resources/ts/back/Components/DocumentStatusBadge.tsx b/resources/ts/back/Components/Documents/DocumentStatusBadge.tsx similarity index 100% rename from resources/ts/back/Components/DocumentStatusBadge.tsx rename to resources/ts/back/Components/Documents/DocumentStatusBadge.tsx diff --git a/resources/ts/back/Components/Documents/Filters.tsx b/resources/ts/back/Components/Documents/Filters.tsx new file mode 100644 index 00000000..a6b2adb4 --- /dev/null +++ b/resources/ts/back/Components/Documents/Filters.tsx @@ -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 ( + + + + + + + ); +}; + +export default Filters; diff --git a/resources/ts/back/Components/FieldsetWrapper.tsx b/resources/ts/back/Components/FieldsetWrapper.tsx index 7a7826f6..33f58f29 100644 --- a/resources/ts/back/Components/FieldsetWrapper.tsx +++ b/resources/ts/back/Components/FieldsetWrapper.tsx @@ -1,4 +1,4 @@ -// * Components shadcn +// * Packages import { ReactNode } from "react"; // * Components shadcn import { diff --git a/resources/ts/back/Components/Filters/EnumFilter.tsx b/resources/ts/back/Components/Filters/EnumFilter.tsx new file mode 100644 index 00000000..c7c56715 --- /dev/null +++ b/resources/ts/back/Components/Filters/EnumFilter.tsx @@ -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 ( + { + const selectedStatusName = Object.values(enums).find( + enumValue => enumValue.value === value + )?.name; + const params = { + ...route().params, + [name]: selectedStatusName, + }; + addFilterToUrl({modelName, params}); + }} + /> + ) +} + +export default EnumFilter; diff --git a/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx new file mode 100644 index 00000000..28fcfe70 --- /dev/null +++ b/resources/ts/back/Components/Filters/MultiSelectRelationFilter.tsx @@ -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 ( + { + 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; diff --git a/resources/ts/back/Components/Filters/SwitchFilter.tsx b/resources/ts/back/Components/Filters/SwitchFilter.tsx new file mode 100644 index 00000000..7794155a --- /dev/null +++ b/resources/ts/back/Components/Filters/SwitchFilter.tsx @@ -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 ( + { + const params = { + ...route().params, + [name]: value, + }; + addFilterToUrl({ modelName, params }); + }} + /> + ) +} + +export default SwitchFilter; diff --git a/resources/ts/back/Components/FiltersWrapper.tsx b/resources/ts/back/Components/FiltersWrapper.tsx new file mode 100644 index 00000000..62e75cac --- /dev/null +++ b/resources/ts/back/Components/FiltersWrapper.tsx @@ -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 ( +
+
+ + + } + tooltipContent={ +

+ {str( + useTrans( + "back.model_filters.button_tooltip", + ), + ) + .ucFirst() + .value()} +

+ } + type="button" + size="icon" + variant="outline" + /> +
+ + + + {str(useTrans("back.model_filters.sheet_title")) + .ucFirst() + .value()} + + + +
+ {children} +
+
+
+
+
+
+ ); +}; + +export default FiltersWrapper; diff --git a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx index d275e9e6..736e5eee 100644 --- a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx +++ b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx @@ -33,6 +33,7 @@ type CompleteInputFileProps = FileValidation & { required?: boolean; fileName?: string; hasRefreshBtn?: boolean; + parentErrors?: Record | 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>>({ @@ -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) { /> )} - + ); } diff --git a/resources/ts/back/Components/Inputs/EnumSelect.tsx b/resources/ts/back/Components/Inputs/EnumSelect.tsx index c92f591e..5d9668da 100644 --- a/resources/ts/back/Components/Inputs/EnumSelect.tsx +++ b/resources/ts/back/Components/Inputs/EnumSelect.tsx @@ -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 && (

{useTrans("back.table_no_results")}

)} -
+
{Object.values(currentOptions).map((option) => ( - ))} -
- )} + )) + )} +
{/* Pagination boutons */} {options.length > 0 && lastPage !== 1 && (
diff --git a/resources/ts/back/Components/Inputs/MultiSelect.tsx b/resources/ts/back/Components/Inputs/MultiSelect.tsx index 6015b18a..64d805bc 100644 --- a/resources/ts/back/Components/Inputs/MultiSelect.tsx +++ b/resources/ts/back/Components/Inputs/MultiSelect.tsx @@ -1,12 +1,30 @@ +// * Packages +import { usePage } from "@inertiajs/react"; +import { + ButtonHTMLAttributes, + ComponentType, + CSSProperties, + forwardRef, + KeyboardEvent, + ReactNode, + useCallback, + useEffect, + useId, + useImperativeHandle, + useMemo, + useRef, + useState, +} from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { CheckIcon, - XCircle, - ChevronDown, + XCircleIcon, XIcon, - WandSparkles, + WandSparklesIcon, + SearchIcon, + ChevronsUpDownIcon, } from "lucide-react"; -import { cn } from "@/lib/utils"; +// * Components shadcn import { Separator } from "@/components/ui/separator"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; @@ -19,17 +37,17 @@ import { Command, CommandEmpty, CommandGroup, - CommandInput, CommandItem, CommandList, - CommandSeparator, } from "@/components/ui/command"; -import { Label } from "../../../components/ui/label"; +import { Label } from "@/components/ui/label"; +import { Input } from "@/components/ui/input"; +// * Other +import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import InputError from "@/back/Components/InputError"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; -import InputError from "@/back/Components/InputError"; -import { usePage } from "@inertiajs/react"; -import { ButtonHTMLAttributes, ComponentType, CSSProperties, forwardRef, KeyboardEvent, ReactNode, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; /** * Animation types and configurations @@ -51,10 +69,11 @@ export interface AnimationConfig { * Variants for the multi-select component to handle different styles. * Uses class-variance-authority (cva) to define different styles based on "variant" prop. */ -const multiSelectVariants = cva("m-1 transition-all duration-300 ease-in-out", { +const multiSelectVariants = cva("transition-all duration-300 ease-in-out", { variants: { variant: { - default: "border-foreground/10 text-foreground bg-card hover:bg-card/80", + default: + "border-foreground/10 text-foreground bg-card hover:bg-card/80", secondary: "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: @@ -72,7 +91,7 @@ const multiSelectVariants = cva("m-1 transition-all duration-300 ease-in-out", { }, defaultVariants: { variant: "default", - badgeAnimation: "bounce", + badgeAnimation: "none", }, }); @@ -113,11 +132,8 @@ interface MultiSelectGroup { * Props for MultiSelect component */ interface MultiSelectProps - extends Omit< - ButtonHTMLAttributes, - "animationConfig" - >, - VariantProps { + extends Omit, "animationConfig">, + VariantProps { /** * An array of option objects or groups to be displayed in the multi-select component. */ @@ -225,27 +241,27 @@ interface MultiSelectProps * Can be boolean true for default responsive behavior or an object for custom configuration. */ responsive?: - | boolean - | { - /** Configuration for mobile devices (< 640px) */ - mobile?: { - maxCount?: number; - hideIcons?: boolean; - compactMode?: boolean; - }; - /** Configuration for tablet devices (640px - 1024px) */ - tablet?: { - maxCount?: number; - hideIcons?: boolean; - compactMode?: boolean; - }; - /** Configuration for desktop devices (> 1024px) */ - desktop?: { - maxCount?: number; - hideIcons?: boolean; - compactMode?: boolean; - }; - }; + | boolean + | { + /** Configuration for mobile devices (< 640px) */ + mobile?: { + maxCount?: number; + hideIcons?: boolean; + compactMode?: boolean; + }; + /** Configuration for tablet devices (640px - 1024px) */ + tablet?: { + maxCount?: number; + hideIcons?: boolean; + compactMode?: boolean; + }; + /** Configuration for desktop devices (> 1024px) */ + desktop?: { + maxCount?: number; + hideIcons?: boolean; + compactMode?: boolean; + }; + }; /** * Minimum width for the component. @@ -284,17 +300,17 @@ interface MultiSelectProps /** * The name of the field to complete */ - name: string + name: string; /** * Label of the field */ - label: string + label: string; /** - * Does the field required - */ - required?: boolean + * Does the field required + */ + required?: boolean; /** * The fonction to set the data in useForm inertia @@ -302,9 +318,9 @@ interface MultiSelectProps setData: (name: string, value: string[]) => void; /** - * Does the field required - */ - multiple?: boolean + * Does the field required + */ + multiple?: boolean; /** * Minimum number of selections required (only when multiple is true) @@ -323,6 +339,12 @@ interface MultiSelectProps * Optional, defaults to empty */ helper?: string; + + /** + * Make the Close button visible + * Optional, defaults to empty + */ + closeButtonVisible?: boolean; } /** @@ -386,11 +408,13 @@ export const MultiSelect = forwardRef( deduplicateOptions = false, resetOnDefaultValueChange = true, closeOnSelect = false, + closeButtonVisible = false, ...props }, - ref + ref, ) => { - const [selectedValues, setSelectedValues] = useState(defaultValue); + const [selectedValues, setSelectedValues] = + useState(defaultValue); const [isPopoverOpen, setIsPopoverOpen] = useState(false); const [isAnimating, setIsAnimating] = useState(false); const [searchValue, setSearchValue] = useState(""); @@ -413,7 +437,7 @@ export const MultiSelect = forwardRef( setTimeout(() => setPoliteMessage(""), 100); } }, - [] + [], ); const multiSelectId = useId(); @@ -421,26 +445,34 @@ export const MultiSelect = forwardRef( const triggerDescriptionId = `${multiSelectId}-description`; const selectedCountId = `${multiSelectId}-count`; + // Translations. + const transDelete = useTrans("crud.actions.delete"); + const transClose = useTrans("back.close"); + const transClear = useTrans("back.clear"); + const transNoResults = useTrans("back.table_no_results"); + const transSearchOptions = useTrans("back.multi_select.search_options"); + const transSelectAll = useTrans("back.multi_select.select_all"); + const transMore = useTrans("back.multi_select.more"); + const transClosePopover = useTrans("back.multi_select.close_popover"); + const transClearList = useTrans("back.multi_select.clear_list"); + const prevDefaultValueRef = useRef(defaultValue); const isGroupedOptions = useCallback( ( - opts: MultiSelectOption[] | MultiSelectGroup[] + opts: MultiSelectOption[] | MultiSelectGroup[], ): opts is MultiSelectGroup[] => { return opts.length > 0 && "heading" in opts[0]; }, - [] + [], ); - const arraysEqual = useCallback( - (a: string[], b: string[]): boolean => { - if (a.length !== b.length) return false; - const sortedA = [...a].sort(); - const sortedB = [...b].sort(); - return sortedA.every((val, index) => val === sortedB[index]); - }, - [] - ); + const arraysEqual = useCallback((a: string[], b: string[]): boolean => { + if (a.length !== b.length) return false; + const sortedA = [...a].sort(); + const sortedB = [...b].sort(); + return sortedA.every((val, index) => val === sortedB[index]); + }, []); const resetToDefault = useCallback(() => { setSelectedValues(defaultValue); @@ -477,19 +509,23 @@ export const MultiSelect = forwardRef( if (buttonRef.current) { buttonRef.current.focus(); const originalOutline = buttonRef.current.style.outline; - const originalOutlineOffset = buttonRef.current.style.outlineOffset; - buttonRef.current.style.outline = "2px solid hsl(var(--ring))"; + const originalOutlineOffset = + buttonRef.current.style.outlineOffset; + buttonRef.current.style.outline = + "2px solid hsl(var(--ring))"; buttonRef.current.style.outlineOffset = "2px"; setTimeout(() => { if (buttonRef.current) { - buttonRef.current.style.outline = originalOutline; - buttonRef.current.style.outlineOffset = originalOutlineOffset; + buttonRef.current.style.outline = + originalOutline; + buttonRef.current.style.outlineOffset = + originalOutlineOffset; } }, 1000); } }, }), - [resetToDefault, selectedValues, onValueChange] + [resetToDefault, selectedValues, onValueChange], ); const [screenSize, setScreenSize] = useState< @@ -527,9 +563,21 @@ export const MultiSelect = forwardRef( } if (responsive === true) { const defaultResponsive = { - mobile: { maxCount: 2, hideIcons: false, compactMode: true }, - tablet: { maxCount: 4, hideIcons: false, compactMode: false }, - desktop: { maxCount: 6, hideIcons: false, compactMode: false }, + mobile: { + maxCount: 2, + hideIcons: false, + compactMode: true, + }, + tablet: { + maxCount: 4, + hideIcons: false, + compactMode: false, + }, + desktop: { + maxCount: 6, + hideIcons: false, + compactMode: false, + }, }; const currentSettings = defaultResponsive[screenSize]; return { @@ -614,18 +662,22 @@ export const MultiSelect = forwardRef( uniqueOptions.push(option); } }); - if (process.env.NODE_ENV === "development" && duplicates.length > 0) { + if ( + process.env.NODE_ENV === "development" && + duplicates.length > 0 + ) { const action = deduplicateOptions ? "automatically removed" : "detected"; console.warn( `MultiSelect: Duplicate option values ${action}: ${duplicates.join( - ", " + ", ", )}. ` + - `${deduplicateOptions - ? "Duplicates have been removed automatically." - : "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique." - }` + `${ + deduplicateOptions + ? "Duplicates have been removed automatically." + : "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique." + }`, ); } return deduplicateOptions ? uniqueOptions : allOptions; @@ -633,15 +685,17 @@ export const MultiSelect = forwardRef( const getOptionByValue = useCallback( (value: string): MultiSelectOption | undefined => { - const option = getAllOptions().find((option) => option.value === value); + const option = getAllOptions().find( + (option) => option.value === value, + ); if (!option && process.env.NODE_ENV === "development") { console.warn( - `MultiSelect: Option with value "${value}" not found in options list` + `MultiSelect: Option with value "${value}" not found in options list`, ); } return option; }, - [getAllOptions] + [getAllOptions], ); const filteredOptions = useMemo(() => { @@ -656,24 +710,31 @@ export const MultiSelect = forwardRef( option.label .toLowerCase() .includes(searchValue.toLowerCase()) || - option.value.toLowerCase().includes(searchValue.toLowerCase()) + option.value + .toLowerCase() + .includes(searchValue.toLowerCase()), ), })) .filter((group) => group.options.length > 0); } return options.filter( (option) => - option.label.toLowerCase().includes(searchValue.toLowerCase()) || - option.value.toLowerCase().includes(searchValue.toLowerCase()) + option.label + .toLowerCase() + .includes(searchValue.toLowerCase()) || + option.value + .toLowerCase() + .includes(searchValue.toLowerCase()), ); }, [options, searchValue, searchable, isGroupedOptions]); - const handleInputKeyDown = ( - event: KeyboardEvent - ) => { + const handleInputKeyDown = (event: KeyboardEvent) => { if (event.key === "Enter") { setIsPopoverOpen(true); - } else if (event.key === "Backspace" && !event.currentTarget.value) { + } else if ( + event.key === "Backspace" && + !event.currentTarget.value + ) { const newSelectedValues = [...selectedValues]; newSelectedValues.pop(); setSelectedValues(newSelectedValues); @@ -691,7 +752,9 @@ export const MultiSelect = forwardRef( // MODE SINGLE SELECT if (!multiple) { - const newSelectedValues = selectedValues.includes(optionValue) ? [] : [optionValue]; + const newSelectedValues = selectedValues.includes(optionValue) + ? [] + : [optionValue]; setSelectedValues(newSelectedValues); if (onValueChange) { onValueChange(newSelectedValues); @@ -708,10 +771,15 @@ export const MultiSelect = forwardRef( if (isCurrentlySelected) { if (minSelection && selectedValues.length <= minSelection) { - announce(`Minimum ${minSelection} selection(s) required`, "assertive"); + announce( + `Minimum ${minSelection} selection(s) required`, + "assertive", + ); return; } - const newSelectedValues = selectedValues.filter((value) => value !== optionValue); + const newSelectedValues = selectedValues.filter( + (value) => value !== optionValue, + ); setSelectedValues(newSelectedValues); if (onValueChange) { onValueChange(newSelectedValues); @@ -719,7 +787,10 @@ export const MultiSelect = forwardRef( setData(name, newSelectedValues); } else { if (maxSelection && selectedValues.length >= maxSelection) { - announce(`Maximum ${maxSelection} selection(s) allowed`, "assertive"); + announce( + `Maximum ${maxSelection} selection(s) allowed`, + "assertive", + ); return; } const newSelectedValues = [...selectedValues, optionValue]; @@ -738,7 +809,10 @@ export const MultiSelect = forwardRef( const handleClear = () => { if (disabled) return; if (multiple && minSelection && minSelection > 0) { - announce(`Minimum ${minSelection} selection(s) required`, "assertive"); + announce( + `Minimum ${minSelection} selection(s) required`, + "assertive", + ); return; } setSelectedValues([]); @@ -757,7 +831,7 @@ export const MultiSelect = forwardRef( if (disabled) return; const newSelectedValues = selectedValues.slice( 0, - responsiveSettings.maxCount + responsiveSettings.maxCount, ); setSelectedValues(newSelectedValues); if (onValueChange) { @@ -768,18 +842,26 @@ export const MultiSelect = forwardRef( const toggleAll = () => { if (disabled || !multiple) return; - const allOptions = getAllOptions().filter((option) => !option.disabled); + const allOptions = getAllOptions().filter( + (option) => !option.disabled, + ); if (selectedValues.length === allOptions.length) { if (minSelection && minSelection > 0) { - announce(`Minimum ${minSelection} selection(s) required`, "assertive"); + announce( + `Minimum ${minSelection} selection(s) required`, + "assertive", + ); return; } handleClear(); } else { const allValues = allOptions.map((option) => option.value); if (maxSelection && allValues.length > maxSelection) { - announce(`Maximum ${maxSelection} selection(s) allowed`, "assertive"); + announce( + `Maximum ${maxSelection} selection(s) allowed`, + "assertive", + ); return; } setSelectedValues(allValues); @@ -803,7 +885,12 @@ export const MultiSelect = forwardRef( } prevDefaultValueRef.current = [...defaultValue]; } - }, [defaultValue, selectedValues, arraysEqual, resetOnDefaultValueChange]); + }, [ + defaultValue, + selectedValues, + arraysEqual, + resetOnDefaultValueChange, + ]); const getWidthConstraints = () => { const defaultMinWidth = screenSize === "mobile" ? "0px" : "200px"; @@ -827,29 +914,33 @@ export const MultiSelect = forwardRef( useEffect(() => { const selectedCount = selectedValues.length; const allOptions = getAllOptions(); - const totalOptions = allOptions.filter((opt) => !opt.disabled).length; + const totalOptions = allOptions.filter( + (opt) => !opt.disabled, + ).length; if (selectedCount !== prevSelectedCount.current) { const diff = selectedCount - prevSelectedCount.current; if (diff > 0) { const addedItems = selectedValues.slice(-diff); const addedLabels = addedItems .map( - (value) => allOptions.find((opt) => opt.value === value)?.label + (value) => + allOptions.find((opt) => opt.value === value) + ?.label, ) .filter(Boolean); if (addedLabels.length === 1) { announce( - `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.` + `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`, ); } else { announce( - `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.` + `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`, ); } } else if (diff < 0) { announce( - `Option removed. ${selectedCount} of ${totalOptions} options selected.` + `Option removed. ${selectedCount} of ${totalOptions} options selected.`, ); } prevSelectedCount.current = selectedCount; @@ -858,7 +949,7 @@ export const MultiSelect = forwardRef( if (isPopoverOpen !== prevIsOpen.current) { if (isPopoverOpen) { announce( - `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.` + `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`, ); } else { announce("Dropdown closed."); @@ -873,31 +964,53 @@ export const MultiSelect = forwardRef( if (searchValue && isPopoverOpen) { const filteredCount = allOptions.filter( (opt) => - opt.label.toLowerCase().includes(searchValue.toLowerCase()) || - opt.value.toLowerCase().includes(searchValue.toLowerCase()) + opt.label + .toLowerCase() + .includes(searchValue.toLowerCase()) || + opt.value + .toLowerCase() + .includes(searchValue.toLowerCase()), ).length; announce( - `${filteredCount} option${filteredCount === 1 ? "" : "s" - } found for "${searchValue}"` + `${filteredCount} option${ + filteredCount === 1 ? "" : "s" + } found for "${searchValue}"`, ); } prevSearchValue.current = searchValue; } - }, [selectedValues, isPopoverOpen, searchValue, announce, getAllOptions]); + }, [ + selectedValues, + isPopoverOpen, + searchValue, + announce, + getAllOptions, + ]); useEffect(() => { - if (minSelection !== undefined && maxSelection !== undefined && minSelection > maxSelection) { - console.error('MultiSelect: minSelection cannot be greater than maxSelection'); + if ( + minSelection !== undefined && + maxSelection !== undefined && + minSelection > maxSelection + ) { + console.error( + "MultiSelect: minSelection cannot be greater than maxSelection", + ); } - if (!multiple && (minSelection !== undefined || maxSelection !== undefined)) { - console.warn('MultiSelect: minSelection and maxSelection are ignored when multiple is false'); + if ( + !multiple && + (minSelection !== undefined || maxSelection !== undefined) + ) { + console.warn( + "MultiSelect: minSelection and maxSelection are ignored when multiple is false", + ); } if (minSelection !== undefined && minSelection < 0) { - console.error('MultiSelect: minSelection cannot be negative'); + console.error("MultiSelect: minSelection cannot be negative"); } if (maxSelection !== undefined && maxSelection < 1) { - console.error('MultiSelect: maxSelection must be at least 1'); + console.error("MultiSelect: maxSelection must be at least 1"); } }, [minSelection, maxSelection, multiple]); @@ -915,21 +1028,28 @@ export const MultiSelect = forwardRef( + modal={modalPopover} + >
- Multi-select dropdown. Use arrow keys to navigate, Enter to select, - and Escape to close. + Multi-select dropdown. Use arrow keys to navigate, Enter + to select, and Escape to close.
-
+
{selectedValues.length === 0 ? "No options selected" - : `${selectedValues.length} option${selectedValues.length === 1 ? "" : "s" - } selected: ${selectedValues - .map((value) => getOptionByValue(value)?.label) - .filter(Boolean) - .join(", ")}`} + : `${selectedValues.length} option${ + selectedValues.length === 1 ? "" : "s" + } selected: ${selectedValues + .map( + (value) => getOptionByValue(value)?.label, + ) + .filter(Boolean) + .join(", ")}`}
- -
) : ( -
- - {placeholder} - - +
+

{placeholder}

+
)} @@ -1137,74 +1302,111 @@ export const MultiSelect = forwardRef( aria-multiselectable="true" aria-label="Available options" className={cn( - "w-auto p-0", + "w-[var(--radix-popover-trigger-width)] p-0", getPopoverAnimationClass(), - screenSize === "mobile" && "w-[85vw] max-w-[280px]", - screenSize === "tablet" && "w-[70vw] max-w-md", - screenSize === "desktop" && "min-w-[300px]", - popoverClassName + popoverClassName, )} style={{ animationDuration: `${animationConfig?.duration || animation}s`, animationDelay: `${animationConfig?.delay || 0}s`, maxWidth: `min(${widthConstraints.maxWidth}, 85vw)`, - maxHeight: screenSize === "mobile" ? "70vh" : "60vh", + maxHeight: + screenSize === "mobile" ? "70vh" : "60vh", touchAction: "manipulation", }} align="start" - onEscapeKeyDown={() => setIsPopoverOpen(false)}> - + onEscapeKeyDown={() => setIsPopoverOpen(false)} + > + {searchable && ( - - )} - {searchable && ( -
- Type to filter options. Use arrow keys to navigate results. +
+
+ +
+ + setSearchValue(e.target.value) + } + onKeyDown={handleInputKeyDown} + className="w-[calc(100%-2.5rem-40px)] border-0 mx-9" + /> + } + tooltipContent={ +

+ {str(transDelete) + .ucFirst() + .value()} +

+ } + type="button" + variant="ghost" + size="icon" + className="absolute top-1/2 right-0 transform -translate-y-1/2 text-muted-foreground" + onClick={() => setSearchValue("")} + disabled={ + searchValue.length < 1 || disabled + } + />
)} - + {searchable && ( +
+ Type to filter options. Use arrow keys to + navigate results. +
+ )} + - {emptyIndicator || "No results found."} - {" "} + {emptyIndicator || transNoResults} + + {/* First option for select all items */} {!hideSelectAll && !searchValue && multiple && ( - + !opt.disabled).length + getAllOptions().filter( + (opt) => !opt.disabled, + ).length } - aria-label={`Select all ${getAllOptions().length - } options`} - className="cursor-pointer"> + aria-label={`Select all ${ + getAllOptions().length + } options`} + className="cursor-pointer gap-1.5 px-4 py-2 w-full h-auto min-h-10" + >
!opt.disabled) - .length + getAllOptions().filter( + (opt) => + !opt.disabled, + ).length ? "bg-primary text-primary-foreground" - : "opacity-50 [&_svg]:invisible" + : "opacity-50 [&_svg]:invisible", )} - aria-hidden="true"> - + aria-hidden="true" + > +
- ({str(useTrans('back.multi_select.select_all')).ucFirst().value()} + ( + {str(transSelectAll) + .ucFirst() + .value()} {getAllOptions().length > 20 ? ` - ${getAllOptions().length} options` : ""} @@ -1213,80 +1415,119 @@ export const MultiSelect = forwardRef(
)} + {/* List of items */} {isGroupedOptions(filteredOptions) ? ( filteredOptions.map((group) => ( - + {group.options.map((option) => { - const isSelected = selectedValues.includes( - option.value - ); + const isSelected = + selectedValues.includes( + option.value, + ); return ( toggleOption(option.value)} + onSelect={() => + toggleOption( + option.value, + ) + } role="option" - aria-selected={isSelected} - aria-disabled={option.disabled} - aria-label={`${option.label}${isSelected ? ", selected" : ", not selected" - }${option.disabled ? ", disabled" : ""}`} + aria-selected={ + isSelected + } + aria-disabled={ + option.disabled + } + aria-label={`${option.label}${ + isSelected + ? ", selected" + : ", not selected" + }${option.disabled ? ", disabled" : ""}`} className={cn( - "cursor-pointer", - option.disabled && "opacity-50 cursor-not-allowed" + "cursor-pointer gap-1.5 px-4 py-2 w-full h-auto min-h-10", + option.disabled && + "opacity-50 cursor-not-allowed", )} - disabled={option.disabled}> + disabled={ + option.disabled + } + > {option.icon && ( ); })} )) ) : ( - + {filteredOptions.map((option) => { - const isSelected = selectedValues.includes(option.value); + const isSelected = + selectedValues.includes( + option.value, + ); return ( toggleOption(option.value)} + onSelect={() => + toggleOption( + option.value, + ) + } role="option" aria-selected={isSelected} - aria-disabled={option.disabled} - aria-label={`${option.label}${isSelected ? ", selected" : ", not selected" - }${option.disabled ? ", disabled" : ""}`} + aria-disabled={ + option.disabled + } + aria-label={`${option.label}${ + isSelected + ? ", selected" + : ", not selected" + }${option.disabled ? ", disabled" : ""}`} className={cn( - "cursor-pointer", - option.disabled && "opacity-50 cursor-not-allowed" + "cursor-pointer gap-1.5 px-4 py-2 w-full h-auto min-h-10", + option.disabled && + "opacity-50 cursor-not-allowed", )} - disabled={option.disabled}> + disabled={option.disabled} + > {option.icon && ( )} - - -
+ + {(closeButtonVisible || + selectedValues.length > 0) && ( + +
{selectedValues.length > 0 && ( - <> - - {str(useTrans('back.clear')).ucFirst().value()} - + + {str(transClearList) + .ucFirst() + .value()} +

+ } + className="w-full" + type="button" + variant="ghost" + size="default" + onClick={handleClear} + disabled={disabled} + /> + )} + {closeButtonVisible && + selectedValues.length > 0 && ( - + )} + {closeButtonVisible && ( + + {str(transClosePopover) + .ucFirst() + .value()} +

+ } + className="w-full" + type="button" + variant="ghost" + size="default" + onClick={() => + setIsPopoverOpen(false) + } + disabled={disabled} + /> )} - setIsPopoverOpen(false)} - className="flex-1 justify-center cursor-pointer max-w-full"> - {str(useTrans('back.close')).ucFirst().value()} -
- + )} {animation > 0 && selectedValues.length > 0 && ( - setIsAnimating(!isAnimating)} /> )} - {helper && ({helper})} + {helper && ( + {helper} + )}
); - } + }, ); MultiSelect.displayName = "MultiSelect"; diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts new file mode 100644 index 00000000..5b83fa77 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts @@ -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({ + addOptions() { + return { + ...this.parent?.(), + openOnClick: false, + button: ({ editor }: { editor: Editor }) => ({ + component: ImageButton, + componentProps: { + editor, + tooltip: useTrans('back.wysiwyg_plugins.image.tooltip'), + }, + }), + }; + }, +}); \ No newline at end of file diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx new file mode 100644 index 00000000..363e7790 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx @@ -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(null); + // Value of the input alt image. + const [inputAlt, setInputAlt] = useState(""); + + // State of the loader. + const [loading, setLoading] = useState(false); + // Value of errors. + const [errors, setErrors] = useState>({}); + + // 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 + */ + const uploadImage = async (file: File, alt: string): Promise => { + // 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 = {}; + const keyMap: Record = { + 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 ( + { + setOpen(v); + if (!v) setTimeout(() => resetComponent(), animationTime); + }} + > + {/* Button trigger in wysiwyg navigation. */} + + } + tooltipContent={tooltip} + className="cursor-grab richtext-px-2 richtext-w-[32px] richtext-h-[32px]" + type="button" + variant="ghost" + size="icon" + /> + + + + + {useTrans("back.wysiwyg_plugins.image.title")} + + + {useTrans("back.wysiwyg_plugins.image.subtitle")} + + + console.log("reset", name)} + value={null} + required={true} + maxFileSize="5120" + allowedFormats="jpg,jpeg,png,webp" + validationRules={{ + width: "1920", + height: "1080", + }} + parentErrors={errors} + /> + +
+
+ {/* Save button. */} + + {/* Cancel button. */} + +
+
+
+
+ ); +} diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts new file mode 100644 index 00000000..52d862d0 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts @@ -0,0 +1,13 @@ +import '@tiptap/core'; + +declare module '@tiptap/core' { + interface Commands { + Image: { + setImage: (attrs: { + src: string, + alt: string; + }) => ReturnType; + unsetImage: () => ReturnType; + }; + } +} diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts index 578c4c05..9b09a86b 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts @@ -30,7 +30,7 @@ export const Link = TiptapLink.extend({ 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({ 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({ 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({ 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({ 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({ const link = target.closest("a"); if (!link) return false; - // Trouver la position exacte du node + // Find the exact position of the gat . 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({ ); } - // Ouvrir ta modale + // Open the modale. this.editor.emit("open-link-editor", { href: link.getAttribute("href") ?? "", blank: link.getAttribute("target") === "_blank", diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx index 38a061eb..0f6e41b3 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx @@ -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 => { - // 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, }, }, }; diff --git a/resources/ts/back/Components/Layout/AppSidebar.tsx b/resources/ts/back/Components/Layout/AppSidebar.tsx index c5de9e42..bfd1bac0 100644 --- a/resources/ts/back/Components/Layout/AppSidebar.tsx +++ b/resources/ts/back/Components/Layout/AppSidebar.tsx @@ -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() { ), authPolicies.newsTags.viewAny && ( ), ] }) }, { - 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 && ( - - ), authPolicies.documentCategories.create && ( + ), + authPolicies.documentTags.create && ( + ) ] }) }, { - 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 ( + + + {value} + + } + tooltipContent={ +

+ {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.dynamic-page", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> ); } if (dynamicPageModel.deleted_at !== null) { value = (
- {cellValue} + + {value} + {cellValue}; - if (auth.policies.pageConfigs.viewAny) { + if (viewAnyPageConfigs) { value = ( - + + + {value} + + } + tooltipContent={ +

+ {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.page-config", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> ); } if (pageConfigModel.deleted_at !== null) { value = (
- {cellValue} + + {value} + } - tooltipContent={

{useTrans("back.crud_access_trash")}

} + tooltipContent={

{useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

} variant="outline" />} {create && - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

{useTrans('back.warning_trash')}

-
-
- - - )} + {isArchiveRoute && } diff --git a/resources/ts/back/Pages/News/Form.tsx b/resources/ts/back/Pages/News/Form.tsx index c48646d2..d9a758a0 100644 --- a/resources/ts/back/Pages/News/Form.tsx +++ b/resources/ts/back/Pages/News/Form.tsx @@ -1,6 +1,6 @@ // * Packages import { useForm, usePage } from "@inertiajs/react"; -import { BookTextIcon, CogIcon, RefreshCwIcon, GavelIcon } from "lucide-react"; +import { BookTextIcon, CogIcon } from "lucide-react"; import { useEffect, useState } from "react"; // * Components shadcn import { Separator } from "@/components/ui/separator"; @@ -8,7 +8,6 @@ import { Skeleton } from "@/components/ui/skeleton"; import { Card, CardContent } from "@/components/ui/card"; // * Other import FieldsetWrapper from "@/back/Components/FieldsetWrapper"; -import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; import InputError from "@/back/Components/InputError"; import GoToFrontView from "@/back/Components/GoToFrontView"; import SimpleString from "@/back/Components/Inputs/SimpleString"; @@ -19,10 +18,16 @@ import SimpleDatePicker from "@/back/Components/Inputs/SimpleDatePicker"; import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile"; import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch"; import SimpleVimeoId from "@/back/Components/Inputs/SimpleVimeoId"; -import { mapLaravelEnumOptions } from "@/lib/mapEnumOptions"; import { cn } from "@/lib/utils"; import { Methods } from "@/lib/enums"; -import { AppEnv, DynamicFieldTypes, LaravelEnum, NewsCategoryModel, NewsModel, NewsTagModel } from "@/back/types/global"; +import { + AppEnv, + DynamicFieldTypes, + LaravelEnum, + NewsCategoryModel, + NewsModel, + NewsTagModel, +} from "@/back/types/global"; import useTrans from "@/hooks/use-translations"; import str from "@/hooks/use-string"; import { useCrudSubmit } from "@/hooks/use-crud-submit"; @@ -46,14 +51,17 @@ export default function Form({ const { locale } = usePage().props.appEnv as AppEnv; const [isGif, setIsGif] = useState(false); const [dynamicKey, setDynamicKey] = useState(null); - const enumDynamicFieldTypes = usePage().props.enumDynamicFieldTypes as DynamicFieldTypes; + const enumDynamicFieldTypes = usePage().props + .enumDynamicFieldTypes as DynamicFieldTypes; const newsTag = usePage().props.newsTag as NewsTagModel[]; const newsCategory = usePage().props.newsCategory as NewsCategoryModel[]; const enumNewsStatus = usePage().props.enumNewsStatus as LaravelEnum; - const { options: optionTags, defaultValue: defaultValueTags } = mapPivotOptions(newsTag, model?.tags, "name", locale); - const { options: optionCategories, defaultValue: defaultValueCategories } = mapPivotOptions(newsCategory, model?.categories, "name", locale); + const { options: optionTags, defaultValue: defaultValueTags } = + mapPivotOptions(newsTag, model?.tags, "name", locale); + const { options: optionCategories, defaultValue: defaultValueCategories } = + mapPivotOptions(newsCategory, model?.categories, "name", locale); function isFile(value: unknown): value is File { return value instanceof File; @@ -61,9 +69,11 @@ export default function Form({ /** Form section */ const { post, setData, data, reset } = useForm({ - _method: method === Methods.POST ? 'post' : 'put', + _method: method === Methods.POST ? "post" : "put", seo_title: model?.seo_title ? model?.seo_title[locale] : "", - seo_description: model?.seo_description ? model?.seo_description[locale] : "", + seo_description: model?.seo_description + ? model?.seo_description[locale] + : "", title: model?.title ? model?.title[locale] : "", slug: model?.slug ? model?.slug[locale] : "", content: model?.content ? model?.content[locale] : "", @@ -77,17 +87,19 @@ export default function Form({ tags: model?.tags ? defaultValueTags : [], categories: model?.categories ? defaultValueCategories : [], published_at: model?.published_at ? model?.published_at : null, - unpublished_at: model?.unpublished_at ? model?.unpublished_at : null + unpublished_at: model?.unpublished_at ? model?.unpublished_at : null, }); const refreshFileFromDb = () => { if (model && model.picture) { - const isGif = typeof model.picture === "string" && model.picture.toLowerCase().endsWith(".gif"); + const isGif = + typeof model.picture === "string" && + model.picture.toLowerCase().endsWith(".gif"); setIsGif(isGif); - setData('picture', model.picture) - setDynamicKey(Date.now()) + setData("picture", model.picture); + setDynamicKey(Date.now()); } - } + }; const submitCrud = useCrudSubmit({ method, @@ -95,7 +107,7 @@ export default function Form({ modelName, action, model, - post + post, }); useEffect(() => { @@ -124,11 +136,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.seo.title"), + attribute: useTrans( + "validation.custom.seo.title", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} required={true} placeholder="ex: John Doe" value={data.seo_title ?? ""} @@ -139,11 +155,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.seo.description"), + attribute: useTrans( + "validation.custom.seo.description", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" required={true} value={data.seo_description ?? ""} @@ -162,11 +182,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.attributes.title"), + attribute: useTrans( + "validation.attributes.title", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.title} setData={setData} @@ -178,10 +202,14 @@ export default function Form({ />
-
+
- -
+ +
@@ -291,9 +347,9 @@ export default function Form({ setData={(_, value) => { setIsGif(value); if (data.picture) { - setData(prev => ({ + setData((prev) => ({ ...prev, - picture: null + picture: null, })); } setDynamicKey(Date.now()); @@ -311,11 +367,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.attributes.image"), + attribute: useTrans( + "validation.attributes.image", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} setData={setData} onRefreshFile={refreshFileFromDb} // @ts-ignore @@ -323,12 +383,20 @@ export default function Form({ value={data.picture} required={true} maxFileSize="5120" - allowedFormats={isGif ? 'gif' : "jpg,jpeg,png,webp"} - validationRules={isGif ? null : { - width: "525", - height: "295" - }} - inputType={isGif ? enumDynamicFieldTypes.file.value : enumDynamicFieldTypes.image.value} + allowedFormats={isGif ? "gif" : "jpg,jpeg,png,webp"} + validationRules={ + isGif + ? null + : { + width: "525", + height: "295", + } + } + inputType={ + isGif + ? enumDynamicFieldTypes.file.value + : enumDynamicFieldTypes.image.value + } />
@@ -338,11 +406,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.image_alt"), + attribute: useTrans( + "validation.custom.image_alt", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.picture_alt ?? ""} setData={setData} @@ -353,11 +425,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.image_title"), + attribute: useTrans( + "validation.custom.image_title", + ), }, choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} placeholder="ex: John Doe" value={data.picture_title ?? ""} setData={setData} @@ -369,11 +445,15 @@ export default function Form({ label={str( useTrans("back.form_associate_to", { params: { - attribute: useTrans("validation.custom.content"), + attribute: useTrans( + "validation.custom.content", + ), }, - choice: 1 + choice: 1, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} value={data.content} setData={setData} /> @@ -382,43 +462,77 @@ export default function Form({ label={str( useTrans("back.form_associate_to_plural", { params: { - attribute: useTrans("validation.custom.news.tag", { choice: 2 }), + attribute: useTrans( + "models.classes.news-tag", + { choice: 2 }, + ), }, - choice: 2 + choice: 2, }), - ).ucFirst().value()} + ) + .ucFirst() + .value()} multiple={true} name="tags" required={false} variant="inverted" - placeholder={str( - useTrans("back.news.tags.placeholder") - ).ucFirst().value()} - singleLine={true} + placeholder={str(useTrans("back.news.tags.placeholder")) + .ucFirst() + .value()} + singleLine={false} setData={setData} defaultValue={data.tags} options={optionTags} + responsive={{ + mobile: { + maxCount: 3, + }, + tablet: { + maxCount: 4, + }, + desktop: { + maxCount: 5, + } + }} />
@@ -436,11 +550,11 @@ export default function Form({ />
- + })} + />
); diff --git a/resources/ts/back/Pages/News/Index.tsx b/resources/ts/back/Pages/News/Index.tsx index 82ce6a26..b59725f7 100644 --- a/resources/ts/back/Pages/News/Index.tsx +++ b/resources/ts/back/Pages/News/Index.tsx @@ -1,92 +1,166 @@ // * Packages import { route } from "ziggy-js"; import { usePage } from "@inertiajs/react"; +import { + ArchiveIcon, + ArrowLeftIcon, + FolderIcon, + PlusIcon, + TagIcon, +} from "lucide-react"; +import { Row } from "@tanstack/react-table"; // * Components shadcn import { Badge } from "@/components/ui/badge"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; // * Other import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout"; import DataTable from "@/back/Components/Table/DataTable"; import DataTableSearch from "@/back/Components/Table/DataTableSearch"; import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton"; -import InputError from "@/back/Components/InputError"; import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip"; +import NewsStatusBadge from "@/back/Components/News/NewsStatusBadge"; +import SoftdeleteWarning from "@/back/Components/SoftdeleteWarning"; import { Views } from "@/lib/utils"; import { useFormatedDate } from "@/hooks/use-formated-value"; import { AppEnv, AuthProp, + NewsCategoryModel, NewsModel, Resource, - TranslationField, } from "@/back/types/global"; import str from "@/hooks/use-string"; import useTrans from "@/hooks/use-translations"; -import { Row } from "@tanstack/react-table"; -import { AlertCircle, Archive, ArrowLeft, Plus } from "lucide-react"; -import NewsStatusBadge from "@/back/Components/NewsStatusBadge"; import { renderTranslationCell } from "@/lib/translationCellFallback"; export default function Index({ newsModels, search, searchFields, - modelName + modelName, }: { newsModels: Resource; search: string; searchFields: string; modelName: string; }) { - const { auth, appEnv } = usePage().props as unknown as { - auth: AuthProp; + const { appEnv, auth } = usePage().props as unknown as { appEnv: AppEnv; + auth: AuthProp; }; const { viewAny, viewTrash, create } = auth.policies.news; - const isArchiveRoute = route().current("back.news.trash"); - const actionModels = isArchiveRoute ? [ - Views.RESTORATION, - Views.FORCEDELETION, - ] : [ - Views.VISUALIZATION, - Views.EDITION, - Views.DUPLICATION, - Views.ARCHIVATION, - ]; + const { viewAny: viewAnyNewsCategories } = auth.policies.newsCategories; + const { viewAny: viewAnyNewsTags } = auth.policies.newsTags; + const isArchiveRoute = route().current(`back.${modelName}.trash`); + const actionModels = isArchiveRoute + ? [Views.RESTORATION, Views.FORCEDELETION] + : [ + Views.VISUALIZATION, + Views.EDITION, + Views.DUPLICATION, + Views.ARCHIVATION, + ]; const columns = [ { accessorKey: "title", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("title") - ) + return renderTranslationCell(row.getValue("title")); + }, + }, + { + accessorKey: "categories", + header: () => ( +

+ {str( + useTrans("models.classes.news-category", { + choice: 2, + }), + ) + .ucFirst() + .value()} +

+ ), + cell: ({ row }: { row: Row }) => { + const categories = row.getValue( + "categories", + ) as NewsCategoryModel[]; + return categories && categories.length > 0 ? ( +
+ {categories.map((item) => + viewAnyNewsCategories ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

+ {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.news-category", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )} +
+ ) : ( +

+ {useTrans("back.table_not_known")} +

+ ); }, }, { accessorKey: "status", header: ({ column }: { column: { id: string } }) => ( ), cell: ({ row }: { row: Row }) => { return ( - - ) + + ); }, }, { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -99,35 +173,100 @@ export default function Index({ ]; const transModel = useTrans(`models.classes.${modelName}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + isArchiveRoute && + viewAny && ( +
+ } + tooltipContent={ +

{useTrans("back.crud_back_to_list")}

+ } + /> +
+ ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
- {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_trash")}

} - variant="outline" - />} - {create && } - tooltipContent={

{useTrans("back.crud_add_entry")}

} - />} -
+ return ( + !isArchiveRoute && ( +
+ {viewAnyNewsCategories && ( + } + tooltipContent={ +

+ {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.news-category", + { choice: 2 }, + ), + }, + })} +

+ } + variant="outline" + /> + )} + {viewAnyNewsTags && ( + } + tooltipContent={ +

+ {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "models.classes.news-tag", + { choice: 2 }, + ), + }, + })} +

+ } + variant="outline" + /> + )} + {viewTrash && ( + } + tooltipContent={ +

+ {useTrans("back.crud_access_to", { + params: { + target: useTrans( + "back.archived_entries", + ), + }, + })} +

+ } + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

{useTrans("back.crud_add_entry")}

+ } + /> + )} +
+ ) ); }; @@ -137,21 +276,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

{useTrans('back.warning_trash')}

-
-
- - - )} + {isArchiveRoute && } value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), + header: str(useTrans("validation.custom.seo.title")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ), }, { accessorKey: "seo_description", - header: str(useTrans("validation.custom.seo.description")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), + header: str(useTrans("validation.custom.seo.description")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ), }, { accessorKey: "title", - header: str(useTrans("validation.attributes.title")).ucFirst().value(), + header: str(useTrans("validation.attributes.title")) + .ucFirst() + .value(), cell: ({ value }: { value: TranslationField }) => { - return renderTranslationCell( - value - ) - } + return renderTranslationCell(value); + }, }, { accessorKey: "slug", header: str(useTrans("validation.custom.slug")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ), }, { accessorKey: "content", - header: str(useTrans("validation.attributes.content")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), + header: str(useTrans("validation.attributes.content")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ), }, { accessorKey: "status", header: str(useTrans("validation.custom.status")).ucFirst().value(), cell: ({ value }: { value: string }) => { - return ( - - ) + return ; }, }, { accessorKey: "categories", - header: str(useTrans("validation.custom.category", { choice: 2 })).ucFirst().value(), + header: str(useTrans("models.classes.news-category", { choice: 2 })) + .ucFirst() + .value(), cell: ({ value }: { value?: NewsCategoryModel[] }) => { - if (!value || value.length === 0) return null; - return ( -
- {value.map((item, i) => ( - - ))} + return value !== undefined && value.length > 0 ? ( +
+ {value.map((item) => + viewAnyNewsCategories ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

+ {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.news-category", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
+ ) : ( +

+ {useTrans("back.table_not_known")} +

); - } - + }, }, { accessorKey: "tags", - header: str(useTrans("validation.custom.news.tag", { choice: 2 })).ucFirst().value(), - cell: ({ value }: { value?: NewsCategoryModel[] }) => { - if (!value || value.length === 0) return null; - return ( -
- {value.map((item, i) => ( - - ))} + header: str(useTrans("models.classes.news-tag", { choice: 2 })) + .ucFirst() + .value(), + cell: ({ value }: { value?: NewsTagModel[] }) => { + return value !== undefined && value.length > 0 ? ( +
+ {value.map((item) => + viewAnyNewsTags ? ( + + + + {item.name[appEnv.locale]} + + + } + tooltipContent={ +

+ {useTrans("back.access_model", { + params: { + model: useTrans( + "models.classes.news-category", + { choice: 1 }, + ), + }, + })} +

+ } + type="button" + size="default" + variant="secondary" + /> + ) : ( + + {item.name[appEnv.locale]} + + ), + )}
+ ) : ( +

+ {useTrans("back.table_not_known")} +

); - } - + }, }, { accessorKey: "created_at", - header: str(useTrans("validation.attributes.created_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.created_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => { return ( {useFormatedDate(value)} - ) + ); }, }, { accessorKey: "picture", - header: str(useTrans("validation.attributes.image")).ucFirst().value(), + header: str(useTrans("validation.attributes.image")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( ), }, { accessorKey: "picture_alt", - header: str(useTrans("validation.custom.image_alt")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), + header: str(useTrans("validation.custom.image_alt")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ), }, { accessorKey: "picture_title", - header: str(useTrans("validation.custom.image_title")).ucFirst().value(), - cell: ({ value }: { value: TranslationField }) => value[appEnv.locale] - ? value[appEnv.locale] - : (

{useTrans('back.table_not_known')}

), + header: str(useTrans("validation.custom.image_title")) + .ucFirst() + .value(), + cell: ({ value }: { value: TranslationField }) => + value[appEnv.locale] ? ( + value[appEnv.locale] + ) : ( +

+ {useTrans("back.table_not_known")} +

+ ), }, { accessorKey: "published_at", - header: str(useTrans("validation.custom.published_at")).ucFirst().value(), + header: str(useTrans("validation.custom.published_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( - {useFormatedDate(value, useLocale.use.timezone(), true)} + + {useFormatedDate(value, useLocale.use.timezone(), true)} + ), }, { accessorKey: "unpublished_at", - header: str(useTrans("validation.custom.unpublished_at")).ucFirst().value(), + header: str(useTrans("validation.custom.unpublished_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), }, { accessorKey: "updated_at", - header: str(useTrans("validation.attributes.updated_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.updated_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), }, { accessorKey: "deleted_at", - header: str(useTrans("validation.attributes.deleted_at")).ucFirst().value(), + header: str(useTrans("validation.attributes.deleted_at")) + .ucFirst() + .value(), cell: ({ value }: { value: string }) => ( {useFormatedDate(value)} ), @@ -179,22 +313,23 @@ export default function Show({ data, modelName }: { data: SingleResource, modelN ]; const beforeNode = () => { - return viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + viewAny && ( +
+ } + tooltipContent={ +

{useTrans("back.crud_back_to_list")}

+ } + /> +
+ ) ); }; return ( - + ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) + return renderTranslationCell(row.getValue("name")); }, }, { accessorKey: "news", header: () => ( -

{str(useTrans(`validation.custom.documentTag.documents`)).ucFirst().value()}

+

+ {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

), cell: ({ row }: { row: Row }) => (
@@ -79,7 +90,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -90,36 +103,58 @@ export default function Index({ ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + isArchiveRoute && + viewAny && ( +
+ } + tooltipContent={ +

{useTrans("back.crud_back_to_list")}

+ } + /> +
+ ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
- {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_trash")}

} - variant="outline" - />} - {create && } - tooltipContent={

{useTrans("back.crud_add_entry")}

} - />} -
+ return ( + !isArchiveRoute && ( +
+ {viewTrash && ( + } + tooltipContent={

{useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

} + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

{useTrans("back.crud_add_entry")}

+ } + /> + )} +
+ ) ); }; @@ -129,21 +164,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

{useTrans('back.warning_trash')}

-
-
- - - )} + {isArchiveRoute && } ( ), cell: ({ row }: { row: Row }) => { - return renderTranslationCell( - row.getValue("name") - ) + return renderTranslationCell(row.getValue("name")); }, }, { accessorKey: "color", header: ({ column }: { column: { id: string } }) => ( ), @@ -77,19 +77,35 @@ export default function Index({ return ( -
+
{row.getValue("color")}
- ) + ); }, }, { accessorKey: "news", header: () => ( -

{str(useTrans(`validation.custom.documentTag.documents`)).ucFirst().value()}

+

+ {str( + useTrans("back.associated_model", { + params: { + model: useTrans("models.classes.news", { + choice: 2, + }), + }, + choice: 2, + }), + ) + .ucFirst() + .value()} +

), cell: ({ row }: { row: Row }) => (
@@ -101,7 +117,9 @@ export default function Index({ accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( ), @@ -112,36 +130,58 @@ export default function Index({ ), }, ]; - const transModel = useTrans(`models.classes.${str(modelName).singular().value()}`, { choice: 2 }); - const transArchiveTitle = useTrans("crud.helpers.archives_model", { params: { model: transModel } }) - const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel).ucFirst().value(); + const transModel = useTrans( + `models.classes.${str(modelName).singular().value()}`, + { choice: 2 }, + ); + const transArchiveTitle = useTrans("crud.helpers.archives_model", { + params: { model: transModel }, + }); + const transTitle = str(isArchiveRoute ? transArchiveTitle : transModel) + .ucFirst() + .value(); const beforeNode = () => { - return isArchiveRoute && viewAny && ( -
- } - tooltipContent={

{useTrans("back.crud_back_to_list")}

} - /> -
+ return ( + isArchiveRoute && + viewAny && ( +
+ } + tooltipContent={ +

{useTrans("back.crud_back_to_list")}

+ } + /> +
+ ) ); }; const afterNode = () => { - return !isArchiveRoute && ( -
- {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_trash")}

} - variant="outline" - />} - {create && } - tooltipContent={

{useTrans("back.crud_add_entry")}

} - />} -
+ return ( + !isArchiveRoute && ( +
+ {viewTrash && ( + } + tooltipContent={

{useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

} + variant="outline" + /> + )} + {create && ( + } + tooltipContent={ +

{useTrans("back.crud_add_entry")}

+ } + /> + )} +
+ ) ); }; @@ -151,21 +191,7 @@ export default function Index({ beforeNode={beforeNode()} afterNode={afterNode()} > - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

{useTrans('back.warning_trash')}

-
-
- - - )} + {isArchiveRoute && } }) => ( row.getValue("view") - ? row.getValue("view") + ? {row.getValue("view")} : (

{useTrans('back.table_not_known')}

) ), }, @@ -118,7 +117,9 @@ export default function Index({ {viewTrash && } - tooltipContent={

{useTrans("back.crud_access_trash")}

} + tooltipContent={

{useTrans("back.crud_access_to", { + params: { target: useTrans('back.archived_entries')} + })}

} variant="outline" />} {create && - {isArchiveRoute && ( - <> - - - {useTrans('back.warning')} - -

{useTrans('back.warning_trash')}

-
-
- - - )} + {isArchiveRoute && } {value} }, { accessorKey: "config", diff --git a/resources/ts/back/Pages/Users/Index.tsx b/resources/ts/back/Pages/Users/Index.tsx index a3e20c7d..fb504764 100644 --- a/resources/ts/back/Pages/Users/Index.tsx +++ b/resources/ts/back/Pages/Users/Index.tsx @@ -96,7 +96,7 @@ export default function Index({ /> ), cell: ({ row }: { row: Row }) => ( -

+ {str( String( Object.values(enumUserRole).find( @@ -104,7 +104,7 @@ export default function Index({ )?.label, ), ).ucFirst().value()} -

+ ), }, { diff --git a/resources/ts/back/Pages/Users/Show.tsx b/resources/ts/back/Pages/Users/Show.tsx index bc4ccf65..964a4150 100644 --- a/resources/ts/back/Pages/Users/Show.tsx +++ b/resources/ts/back/Pages/Users/Show.tsx @@ -58,11 +58,11 @@ export default function Show({ data }: { data: SingleResource }) { accessorKey: "role", header: str(useTrans(`validation.attributes.role`)).ucFirst().value(), cell: ({ value }: { value: number }) => ( -

+ {str(String(Object.values(enumUserRole).find( (role) => role.value === value, )?.label)).ucFirst().value()} -

+ ), }, { diff --git a/resources/ts/back/types/global.d.ts b/resources/ts/back/types/global.d.ts index 964253e5..ff6ac18e 100644 --- a/resources/ts/back/types/global.d.ts +++ b/resources/ts/back/types/global.d.ts @@ -181,6 +181,7 @@ type CompanyActivityModel = { created_at: Date; updated_at: Date; deleted_at: Date; + companies: CompanyModel[]; } type CompanySectorModel = { @@ -190,6 +191,7 @@ type CompanySectorModel = { created_at: Date; updated_at: Date; deleted_at: Date; + companies: CompanyModel[]; } type DocumentModel = { policies: ModelPolicy; @@ -247,6 +249,7 @@ type Model = | CompanyActivityModel | CompanySectorModel | DocumentTagModel + | DocumentCategoryModel | ActivityLogModel | NewsCategoryModel | NewsTagModel; diff --git a/resources/ts/lib/filters.tsx b/resources/ts/lib/filters.tsx new file mode 100644 index 00000000..51d92506 --- /dev/null +++ b/resources/ts/lib/filters.tsx @@ -0,0 +1,24 @@ +// * Packages +import { router } from "@inertiajs/react"; +import { route } from "ziggy-js"; + +type RouterFiltersProps = { + modelName: string; + params: { + [x: string]: string | boolean | undefined; + } +} +export const addFilterToUrl = (props: RouterFiltersProps) => { + const { modelName, params } = props; + + return router.visit(route(`back.${modelName}.index`), { + method: "get", + data: { + ...params, + page: undefined, + }, + preserveState: true, + preserveScroll: true, + replace: true, + }); +} diff --git a/resources/ts/lib/translationCellFallback.tsx b/resources/ts/lib/translationCellFallback.tsx index 02a2b072..b3b7cdef 100644 --- a/resources/ts/lib/translationCellFallback.tsx +++ b/resources/ts/lib/translationCellFallback.tsx @@ -11,7 +11,7 @@ import { ReactNode } from "react"; * 2. First non-empty available translation (fallback) * * @param value - Translation field containing localized values - * @returns An object with the resolved value and optional fallback locale, + * @return An object with the resolved value and optional fallback locale, * or null if no translation is available */ const getTranslationValue = ( @@ -43,7 +43,7 @@ const getTranslationValue = ( * - Displays a "not known" message when no translation is available * * @param value - Translation field containing localized values - * @returns A ReactNode ready to be rendered inside a table cell + * @return A ReactNode ready to be rendered inside a table cell */ export const renderTranslationCell = ( value?: TranslationField diff --git a/resources/views/back/layouts/head.blade.php b/resources/views/back/layouts/head.blade.php index e45c4a73..9c39ce38 100644 --- a/resources/views/back/layouts/head.blade.php +++ b/resources/views/back/layouts/head.blade.php @@ -35,7 +35,7 @@ - @routes(nonce: $nonce) + @routes(nonce: $nonce ?? '') @if (app()->hasDebugModeEnabled()) @viteReactRefresh @endif diff --git a/resources/views/components/front/commitments/list.blade.php b/resources/views/components/front/commitments/list.blade.php index 57e72afa..e54c5f5d 100644 --- a/resources/views/components/front/commitments/list.blade.php +++ b/resources/views/components/front/commitments/list.blade.php @@ -9,24 +9,26 @@ @php $count = 1; @endphp @foreach($pageNosEngagements->childPages as $childPage) @php $route = \App\Helpers\RouteHelper::routeNameChecker("front.dynamic-pages.$childPage->id_key"); @endphp -
$route === url()->current() || $disabled == $count, - ])> - @if(!empty($childPage->content['list_identification'][0]['image_icon'])) -
- {{ !empty($childPage->content['list_identification'][0]['string_label']) ? $childPage->content['list_identification'][0]['string_label'] : 'engagement' }} -
- @endif - @if(!empty($childPage['text'])) -
{{ $childPage['text'] }}
- @endif - - {{ $childPage->content['list_identification'][0]['string_label'] }} - - -
+ @if(isset($childPage->content['list_identification'])) +
$route === url()->current() || $disabled == $count, + ])> + @if(!empty($childPage->content['list_identification'][0]['image_icon'])) +
+ {{ !empty($childPage->content['list_identification'][0]['string_label']) ? $childPage->content['list_identification'][0]['string_label'] : 'engagement' }} +
+ @endif + @if(!empty($childPage['text'])) +
{{ $childPage['text'] }}
+ @endif + + {{ $childPage->content['list_identification'][0]['string_label'] }} + + +
+ @endif @php $count++; @endphp @endforeach
diff --git a/resources/views/components/front/pages/know-us/pole-page-template.blade.php b/resources/views/components/front/pages/know-us/pole-page-template.blade.php index bc2648fc..d9ef4b32 100644 --- a/resources/views/components/front/pages/know-us/pole-page-template.blade.php +++ b/resources/views/components/front/pages/know-us/pole-page-template.blade.php @@ -46,7 +46,7 @@ @endif
@endif - +
@endforeach diff --git a/resources/views/components/front/search-pagination.blade.php b/resources/views/components/front/search-pagination.blade.php deleted file mode 100644 index 629294a0..00000000 --- a/resources/views/components/front/search-pagination.blade.php +++ /dev/null @@ -1,28 +0,0 @@ -@if ($models->lastPage() > 1) -
-
- {{-- Page précédente --}} - @if (!$models->onFirstPage()) - - @endif - {{-- Pages --}} - @for ($page = 1; $page <= $models->lastPage(); $page++) - @if ($page == $models->currentPage()) - {{ $page }} - @else - - {{ $page }} - - @endif - @endfor - {{-- Page suivante --}} - @if ($models->hasMorePages()) - - @endif -
-
-@endif \ No newline at end of file diff --git a/resources/views/components/front/search/card.blade.php b/resources/views/components/front/search/card.blade.php new file mode 100644 index 00000000..3773f122 --- /dev/null +++ b/resources/views/components/front/search/card.blade.php @@ -0,0 +1,31 @@ +@php + $hasTitle = isset($result["{$mainField}_{$currentLocale}"]) && !is_null($result["{$mainField}_{$currentLocale}"]) && !empty($result["{$mainField}_{$currentLocale}"]); + $hasDescription = isset($result["content_{$currentLocale}"]) && !is_null($result["content_{$currentLocale}"]) && !empty($result["content_{$currentLocale}"]); + $breadcrumbs = \Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray(); +@endphp + + @if($hasTitle) +
+ {!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["{$mainField}_{$currentLocale}"], $searchTerm) !!} +
+ @endif +
!$hasDescription, + 'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true, + ])> + @foreach($breadcrumbs as $breadcrumb) + {{ $breadcrumb->title }} + @if(!$loop->last) + > + @endif + @endforeach + @if($customBreadcrumbs && $hasTitle && end($breadcrumbs)->title !== $result["{$mainField}_{$currentLocale}"]) + > {{ $result["{$mainField}_{$currentLocale}"] }} + @endif +
+ @if ($hasDescription) +
+ {!! \App\Http\Controllers\Front\SearchController::highlightTerms($result["content_{$currentLocale}"], $searchTerm) !!} +
+ @endif +
\ No newline at end of file diff --git a/resources/views/components/front/search/content.blade.php b/resources/views/components/front/search/content.blade.php new file mode 100644 index 00000000..f249b244 --- /dev/null +++ b/resources/views/components/front/search/content.blade.php @@ -0,0 +1,90 @@ +
+ {{-- LOADER --}} + + {{-- EMPTY RESULTS --}} + + {{-- RESULTS --}} +
+ {{-- PAGINATION --}} +
+
+ +@php + // Set a template for the global count. + $resultsLabel = trans('front.search.results_total', [ + 'nbr' => '__COUNT__', + 'terms' => $searchTerm, + ]); + $currentLocale = app()->getLocale(); +@endphp + +@push('scripts') + +@endpush \ No newline at end of file diff --git a/resources/views/components/front/search/pagination.blade.php b/resources/views/components/front/search/pagination.blade.php new file mode 100644 index 00000000..3a8f32ff --- /dev/null +++ b/resources/views/components/front/search/pagination.blade.php @@ -0,0 +1,28 @@ +@if ($models->lastPage() > 1) +
+
+ {{-- Previous button page --}} + @if (!$models->onFirstPage()) + + @endif + {{-- Numbers pages --}} + @for ($page = 1; $page <= $models->lastPage(); $page++) + @if ($page == $models->currentPage()) + {{ $page }} + @else + + @endif + @endfor + {{-- Next button page --}} + @if ($models->hasMorePages()) + + @endif +
+
+@endif diff --git a/resources/views/components/front/sections/accordion/accordion.blade.php b/resources/views/components/front/sections/accordion/accordion.blade.php index 5125d38a..fa2f30f6 100644 --- a/resources/views/components/front/sections/accordion/accordion.blade.php +++ b/resources/views/components/front/sections/accordion/accordion.blade.php @@ -1,19 +1,17 @@ @if (!empty($accordion)) - @php - $type = 'medias'; - @endphp + @php $currentType = $type ?? 'medias'; @endphp
$type !== 'medias' + 'accordeon__wrapper wrapper' => $currentType !== 'medias' ])>
$type !== 'medias' + 'accordeon__list' => $currentType !== 'medias' ])> @foreach ($accordion as $acc) - + @endforeach
diff --git a/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php b/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php index d7b818b3..5571cc04 100644 --- a/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php +++ b/resources/views/front/breadcrumbs/breadcrumb-layout.blade.php @@ -1,4 +1,4 @@ -@if ($breadcrumbs->isNotEmpty() && request()->route()->getName() !== 'front.dynamic-pages.accueil.' . app()->getLocale()) +@if ($breadcrumbs->isNotEmpty() && request()->path() !== "/") + @php + $sections = [ + 'list_our_jobs', + 'list_your_career', + 'list_our_politics', + 'list_your_well_being', + 'list_our_events', + 'list_schools', + 'list_breeders', + ]; + @endphp
    - @php - $sections = [ - 'list_our_jobs', - 'list_your_career', - 'list_our_politics', - 'list_your_well_being', - 'list_our_events', - 'list_schools', - 'list_breeders', - ]; - @endphp - @foreach ($sections as $key => $item) - @php $section = $pageNousRejoindre->content[$item]; @endphp - @if ($section) - @php - $title = $section[0]['string_title']; - $subtitle = $section[0]['string_subtitle']; - @endphp -
  • - - {{ Str::ucfirst(Str::lower($title) . " " . Str::lower($subtitle)) }} - -
  • - @endif - @endforeach + @if(array_intersect($sections, array_keys($pageNousRejoindre->content))) + @foreach ($sections as $key => $item) + @if (array_key_exists($item, array_keys($pageNousRejoindre->content))) + @php + $section = $pageNousRejoindre->content[$item]; + $title = $section[0]['string_title']; + $subtitle = $section[0]['string_subtitle']; + @endphp +
  • + + {{ Str::ucfirst(Str::lower($title) . " " . Str::lower($subtitle)) }} + +
  • + @endif + @endforeach + @endif
@endif @@ -285,30 +289,31 @@ {{ $pageFinance->title }}
+ @php + $sections = [ + 'list_agir_avec_territoires', + 'list_action_ldc', + 'list_shareholders_area', + 'list_investissor_presentation', + 'list_key_numbers', + 'list_publication_information', + 'list_assemble', + ]; + @endphp
    - @php - $sections = [ - 'list_agir_avec_territoires', - 'list_action_ldc', - 'list_shareholders_area', - 'list_investissor_presentation', - 'list_key_numbers', - 'list_publication_information', - 'list_assemble', - ]; - @endphp - @foreach ($sections as $key => $item) - @php $section = $pageFinance->content[$item]; @endphp - @if ($section) - @php $title = $section[0]['string_title']; @endphp -
  • - - {{ $title }} - -
  • - @endif - @endforeach + @if(array_intersect($sections, array_keys($pageFinance->content))) + @foreach ($sections as $key => $item) + @if (array_key_exists($item, array_keys($pageNousRejoindre->content))) + @php $title = $pageFinance->content[$item][0]['string_title']; @endphp +
  • + + {{ $title }} + +
  • + @endif + @endforeach + @endif @php $FinanceChildPages = $pageFinance->childPages->where('status', \App\Enums\DynamicPages\PageStatusEnum::published); @endphp @if ($FinanceChildPages->count())
@endif
-
- - +
\ No newline at end of file diff --git a/resources/views/front/layouts/top-nav-menu.blade.php b/resources/views/front/layouts/top-nav-menu.blade.php index 2e7887b9..31772675 100644 --- a/resources/views/front/layouts/top-nav-menu.blade.php +++ b/resources/views/front/layouts/top-nav-menu.blade.php @@ -21,13 +21,11 @@ @endif
- @foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties) + @foreach (LaravelLocalization::getSupportedLanguagesKeys() as $localeCode) @if (!$loop->first) / @endif - @php - $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); - @endphp + @php $url = \App\Helpers\RouteHelper::getLocalizedUrl($localeCode); @endphp {{ strtoupper($localeCode) }} diff --git a/resources/views/front/pages/dynamic-pages/default.blade.php b/resources/views/front/pages/dynamic-pages/default.blade.php index 1f77ef10..0add8aae 100644 --- a/resources/views/front/pages/dynamic-pages/default.blade.php +++ b/resources/views/front/pages/dynamic-pages/default.blade.php @@ -14,7 +14,9 @@ 'content' => $dynamicPageModel->content, ]) @else - {!! $dynamicPageModel->content !!} + @if (!is_array($dynamicPageModel->content)) + {!! $dynamicPageModel->content !!} + @endif @endif

created_at (Date de création): {{ $dynamicPageModel->created_at }}

updated_at (Date de mise à jour): {{ $dynamicPageModel->updated_at }}

diff --git a/resources/views/front/pages/error.blade.php b/resources/views/front/pages/error.blade.php index 71927380..bebaccd4 100644 --- a/resources/views/front/pages/error.blade.php +++ b/resources/views/front/pages/error.blade.php @@ -6,7 +6,5 @@ @section('content')

{{ sprintf("%s - %s", $status, trans("errors.$status.title")) }}

{{ trans("errors.$status.description") }}

-
- {{ trans("front.back_to_homepage") }} - + {{ trans("front.back_to_homepage") }} @endsection diff --git a/resources/views/front/pages/home.blade.php b/resources/views/front/pages/home.blade.php index 0fec7b20..29eecf3a 100644 --- a/resources/views/front/pages/home.blade.php +++ b/resources/views/front/pages/home.blade.php @@ -5,7 +5,7 @@ @section('content') {{-- VIDEO --}} -@if (isset($dynamicPageModel->content['list_section_presentation'])) +@if (data_get($dynamicPageModel, 'content.list_section_presentation')) @php $video = [ 'show_block' => true, @@ -25,12 +25,12 @@ @endif {{-- ENGAGEMENTS --}} -@if(isset($pageNosEngagements)) +@if(data_get($dynamicPageModel, 'content.list_section_our_commitments')) @php $engagements = [ 'title' => $pageNosEngagements->title, 'subtitle' => '', - 'text' => $dynamicPageModel->content['list_section_our_commitments'][0]['wysiwyg_content'], + 'text' => data_get($dynamicPageModel, 'content.list_section_our_commitments.0.wysiwyg_content'), 'button' => [ 'title' => $pageNosEngagements->title, 'url' => \App\Helpers\RouteHelper::routeNameChecker("front.dynamic-pages.$pageNosEngagements->id_key"), @@ -42,78 +42,79 @@ @endif {{-- KEY FIGURES --}} -@if(isset($pageNousConnaitre)) - +@if(data_get($pageNousConnaitre, 'content.list_section_key_figures.0')) + @endif {{-- VALUES --}} -@if(isset($pageNousConnaitre)) - +@if(data_get($pageNousConnaitre, 'content.list_section_our_values.0')) + @endif {{-- TEXT BLOCK --}} -@php - $blocks = [ - 'hide_block' => false, - 'title' => $dynamicPageModel->content['list_section_together'][0]['string_title'], - 'subtitle' => [ - 'text' => $dynamicPageModel->content['list_section_together'][0]['string_subtitle'], - 'cursive' => true, - ], - 'bg' => true, - 'list' => [], - ]; - foreach($dynamicPageModel->content['list_section_together'][0]['list_content_block'] as $keyContent => $content) { - $positionMedium = intval($content['list_medium'][0]['position_medium']); - array_push($blocks['list'], [ - 'title' => $content['string_title'] ?? null, - 'text' => $content['wysiwyg_description'], - 'quote' => 0, - 'swap_position' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value() - ? true - : $positionMedium === \App\Enums\ElementPositionEnum::showright->value(), - 'in_row' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value(), - 'floated' => 0, - 'align_center' => 1, - 'borders_desktop' => [ - 'left' => true, - 'right' => true, - 'top' => true, - 'bottom' => true, +@if (data_get($dynamicPageModel, 'content.list_section_together')) + @php + $blocks = [ + 'hide_block' => false, + 'title' => $dynamicPageModel->content['list_section_together'][0]['string_title'], + 'subtitle' => [ + 'text' => $dynamicPageModel->content['list_section_together'][0]['string_subtitle'], + 'cursive' => true, ], - 'borders_mobile' => [ - 'left' => true, - 'right' => true, - 'top' => true, - 'bottom' => true, - ], - 'image' => [ - [ - 'url' => $content['list_medium'][0]['image_picture'], - 'alt' => $content['list_medium'][0]['string_alt'], + 'bg' => true, + 'list' => [], + ]; + foreach($dynamicPageModel->content['list_section_together'][0]['list_content_block'] as $keyContent => $content) { + $positionMedium = intval($content['list_medium'][0]['position_medium']); + array_push($blocks['list'], [ + 'title' => $content['string_title'] ?? null, + 'text' => $content['wysiwyg_description'], + 'quote' => 0, + 'swap_position' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value() + ? true + : $positionMedium === \App\Enums\ElementPositionEnum::showright->value(), + 'in_row' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value(), + 'floated' => 0, + 'align_center' => 1, + 'borders_desktop' => [ + 'left' => true, + 'right' => true, + 'top' => true, + 'bottom' => true, ], - ], - 'button' => [ - 'title' => $content['list_button'][0]['string_label'], - 'url' => $content['list_button'][0]['url_link'], - 'target' => '_blank', - ], - 'button_icon' => 'btn__icon_arrow-right', - ]); - } -@endphp - + 'borders_mobile' => [ + 'left' => true, + 'right' => true, + 'top' => true, + 'bottom' => true, + ], + 'image' => [ + [ + 'url' => $content['list_medium'][0]['image_picture'], + 'alt' => $content['list_medium'][0]['string_alt'], + ], + ], + 'button' => [ + 'title' => $content['list_button'][0]['string_label'], + 'url' => $content['list_button'][0]['url_link'], + 'target' => '_blank', + ], + 'button_icon' => 'btn__icon_arrow-right', + ]); + } + @endphp + +@endif {{-- BRANDS --}} @php $brands = []; if ( isset($pageNosMarques) - && isset($pageNosMarques->content['list_our_big_brands']) - && isset($pageNosMarques->content['list_our_big_brands'][0]['list_brands']) + && data_get($pageNosMarques, 'content.list_our_big_brands.0.list_brands') ) { - foreach ($pageNosMarques->content['list_our_big_brands'][0]['list_brands'] as $key => $logo) { + foreach (data_get($pageNosMarques, 'content.list_our_big_brands.0.list_brands') as $key => $logo) { array_push($brands, [ 'image' => [ 'url' => asset($logo['list_logo'][0]['image_brand_logo']), diff --git a/resources/views/front/pages/know-us.blade.php b/resources/views/front/pages/know-us.blade.php index b788f04e..32ba2440 100644 --- a/resources/views/front/pages/know-us.blade.php +++ b/resources/views/front/pages/know-us.blade.php @@ -1,7 +1,7 @@ @extends('front.layouts.layout') -@section('title', $dynamicPageModel->content['string_seo_title']) -@section('description', $dynamicPageModel->content['textarea_seo_description']) +@section('title', data_get($dynamicPageModel->content, 'string_seo_title')) +@section('description', data_get($dynamicPageModel->content, 'textarea_seo_description')) @section('content') @php diff --git a/resources/views/front/pages/our-commitment.blade.php b/resources/views/front/pages/our-commitment.blade.php index 8accfdbf..e19cb251 100644 --- a/resources/views/front/pages/our-commitment.blade.php +++ b/resources/views/front/pages/our-commitment.blade.php @@ -1,125 +1,129 @@ @extends('front.layouts.layout') -@section('title', $dynamicPageModel->content['list_identification'][0]['string_seo_title']) -@section('description', $dynamicPageModel->content['list_identification'][0]['textarea_seo_description']) +@section('title', data_get($dynamicPageModel->content, 'list_identification.0.string_seo_title')) +@section('description', data_get($dynamicPageModel->content, 'list_identification.0.textarea_seo_description')) @section('content')
{{-- Section content blocs --}} - @foreach($dynamicPageModel->content['list_section_engagement'] as $key => $sectionEngagement) - @php - $sections[$key] = [ - 'bg' => $sectionEngagement['boolean_background_dark'], - 'title' => $sectionEngagement['string_title'], - 'subtitle' => [ - 'text' => $sectionEngagement['string_subtitle'], - ], - 'list' => [], - ]; - $getConfig = fn($array, $value) => collect($array)->filter(fn($n) => $n['key'] === $value)->first(); - - foreach($sectionEngagement['list_block_content'] as $keyContent => $content) { - $positionMedium = !is_null($content['list_media']) ? intval($content['list_media'][0]['position_medium']) : 0; - array_push($sections[$key]['list'], [ - 'title' => $content['string_title'] ?? null, - 'text' => $content['wysiwyg_content'], - 'quote' => 0, - 'swap_position' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value() - ? true - : $positionMedium === \App\Enums\ElementPositionEnum::showright->value(), - 'in_row' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value(), - 'floated' => !is_null($content['list_media']) ? intval($content['list_media'][0]['boolean_floated']) : 0, - 'align_center' => 1, - 'borders_desktop' => [ - 'left' => true, - 'right' => true, - 'top' => true, - 'bottom' => true, + @if (array_key_exists('list_section_engagement', $dynamicPageModel->content)) + @foreach($dynamicPageModel->content['list_section_engagement'] as $key => $sectionEngagement) + @php + $sections[$key] = [ + 'bg' => $sectionEngagement['boolean_background_dark'], + 'title' => $sectionEngagement['string_title'], + 'subtitle' => [ + 'text' => $sectionEngagement['string_subtitle'], ], - 'borders_mobile' => [ - 'left' => true, - 'right' => true, - 'top' => true, - 'bottom' => true, - ], - 'image' => [], - 'video' => [], - 'button_icon' => '', - 'button' => [], - ]); - if (!is_null($content['list_media']) && $content['list_media'][0]['boolean_medium']) { - foreach ($content['list_media'][0]['list_medium_type'] as $keyImg => $value) { - unset($value['order']); - $filtered = array_filter($value); - $field = array_key_first($filtered); - $aaa = $getConfig($dynamicPageModel->config->config, 'list_section_engagement'); - $bbb = $getConfig($aaa['children'], 'list_block_content'); - $ccc = $getConfig($bbb['children'], 'list_media'); - $ddd = $getConfig($ccc['children'], 'list_medium_type'); - $eee = $getConfig($ddd['children'], $field); + 'list' => [], + ]; + $getConfig = fn($array, $value) => collect($array)->filter(fn($n) => $n['key'] === $value)->first(); - if ($eee['type'] === \App\Enums\DynamicFieldTypes::youtubeid->value()) { - $sections[$key]['list'][$keyContent]['video'] = [ - 'type_video' => 'youtube', - 'video' => $filtered[$field], - ]; - } else { - array_push($sections[$key]['list'][$keyContent]['image'], [ - 'url' => $filtered[$field] ?? null, - ]); + foreach($sectionEngagement['list_block_content'] as $keyContent => $content) { + $positionMedium = isset($content['list_media']) ? intval($content['list_media'][0]['position_medium']) : 0; + array_push($sections[$key]['list'], [ + 'title' => $content['string_title'] ?? null, + 'text' => $content['wysiwyg_content'], + 'quote' => 0, + 'swap_position' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value() + ? true + : $positionMedium === \App\Enums\ElementPositionEnum::showright->value(), + 'in_row' => $positionMedium === \App\Enums\ElementPositionEnum::showbottom->value(), + 'floated' => isset($content['list_media']) ? intval($content['list_media'][0]['boolean_floated']) : 0, + 'align_center' => 1, + 'borders_desktop' => [ + 'left' => true, + 'right' => true, + 'top' => true, + 'bottom' => true, + ], + 'borders_mobile' => [ + 'left' => true, + 'right' => true, + 'top' => true, + 'bottom' => true, + ], + 'image' => [], + 'video' => [], + 'button_icon' => '', + 'button' => [], + ]); + if (isset($content['list_media']) && $content['list_media'][0]['boolean_medium']) { + foreach ($content['list_media'][0]['list_medium_type'] as $keyImg => $value) { + unset($value['order']); + $filtered = array_filter($value); + $field = array_key_first($filtered); + $aaa = $getConfig($dynamicPageModel->config->config, 'list_section_engagement'); + $bbb = $getConfig($aaa['children'], 'list_block_content'); + $ccc = $getConfig($bbb['children'], 'list_media'); + $ddd = $getConfig($ccc['children'], 'list_medium_type'); + $eee = $getConfig($ddd['children'], $field); + + if ($eee['type'] === \App\Enums\DynamicFieldTypes::youtubeid->value()) { + $sections[$key]['list'][$keyContent]['video'] = [ + 'type_video' => 'youtube', + 'video' => $filtered[$field], + ]; + } else { + array_push($sections[$key]['list'][$keyContent]['image'], [ + 'url' => $filtered[$field] ?? null, + ]); + } } } - } - if (isset($content['list_button']) && $content['list_button'][0]['boolean_button']) { - if (isset($content['list_button'][0]['model_page'])) { - $url = \App\Models\DynamicPage::getAccessModel($content['list_button'][0]['model_page']); - } - if (isset($content['list_button'][0]['model_document'])) { - $url = \App\Models\Document::getAccessModel($content['list_button'][0]['model_document']); - } - $sections[$key]['list'][$keyContent]['button'] = [ - 'url' => $url ?? "#", - 'title' => $content['list_button'][0]['string_label'], - 'target' => '', - ]; - $sections[$key]['list'][$keyContent]['button_icon'] = $content['list_button'][0]['boolean_icon'] ? 'btn__icon_view' : 'btn__icon_arrow-right'; - } - } - @endphp - @endforeach - @foreach ($sections as $section) - - @endforeach - {{-- Sections numbers --}} - @php $section = $dynamicPageModel->content['list_section_numbers'][0]; @endphp -
-
- @php - $brands = []; - if ( - isset($pageNosMarques) - && isset($pageNosMarques->content['list_our_big_brands']) - && isset($pageNosMarques->content['list_our_big_brands'][0]['list_brands']) - ) { - foreach ($pageNosMarques->content['list_our_big_brands'][0]['list_brands'] as $key => $logo) { - array_push($brands, [ - 'image' => [ - 'url' => asset($logo['list_logo'][0]['image_brand_logo']), - ], - 'link' => \App\Helpers\RouteHelper::routeNameChecker('front.dynamic-pages.nos-marques'), - ]); + if (isset($content['list_button']) && $content['list_button'][0]['boolean_button']) { + if (isset($content['list_button'][0]['model_page'])) { + $url = \App\Models\DynamicPage::getAccessModel($content['list_button'][0]['model_page']); + } + if (isset($content['list_button'][0]['model_document'])) { + $url = \App\Models\Document::getAccessModel($content['list_button'][0]['model_document']); + } + $sections[$key]['list'][$keyContent]['button'] = [ + 'url' => $url ?? "#", + 'title' => $content['list_button'][0]['string_label'], + 'target' => '', + ]; + $sections[$key]['list'][$keyContent]['button_icon'] = $content['list_button'][0]['boolean_icon'] ? 'btn__icon_view' : 'btn__icon_arrow-right'; } } @endphp - @if(!empty($brands) && request()->route()->getName() === "front.dynamic-pages.bien-nourrir.fr") - - @else - - @endif - + @endforeach + @foreach ($sections as $section) + + @endforeach + @endif + {{-- Sections numbers --}} + @if (array_key_exists('list_section_numbers', $dynamicPageModel->content)) + @php $section = $dynamicPageModel->content['list_section_numbers'][0]; @endphp +
+
+ @php + $brands = []; + if ( + isset($pageNosMarques) + && isset($pageNosMarques->content['list_our_big_brands']) + && isset($pageNosMarques->content['list_our_big_brands'][0]['list_brands']) + ) { + foreach ($pageNosMarques->content['list_our_big_brands'][0]['list_brands'] as $key => $logo) { + array_push($brands, [ + 'image' => [ + 'url' => asset($logo['list_logo'][0]['image_brand_logo']), + ], + 'link' => \App\Helpers\RouteHelper::routeNameChecker('front.dynamic-pages.nos-marques'), + ]); + } + } + @endphp + @if(!empty($brands) && request()->route()->getName() === "front.dynamic-pages.bien-nourrir.fr") + + @else + + @endif + +
-
+ @endif @if($pageNosEngagements->childPages->count())
diff --git a/resources/views/front/pages/our-commitments.blade.php b/resources/views/front/pages/our-commitments.blade.php index 1adf218b..153e9af4 100644 --- a/resources/views/front/pages/our-commitments.blade.php +++ b/resources/views/front/pages/our-commitments.blade.php @@ -1,7 +1,7 @@ @extends('front.layouts.layout') -@section('title', $dynamicPageModel->content['list_seo'][0]['string_seo_title']) -@section('description', $dynamicPageModel->content['list_seo'][0]['textarea_seo_description']) +@section('title', data_get($dynamicPageModel->content, 'list_seo.0.string_seo_title')) +@section('description', data_get($dynamicPageModel->content, 'list_seo.0.textarea_seo_description')) @section('content') @php @@ -12,15 +12,15 @@ @endphp {{-- COMMITMENTS LIST --}} - @php - $section = $getSection('list_section_our_commitments'); - $engagements = [ - 'title' => $section['string_title'], - 'subtitle' => $section['string_subtitle'], - 'text' => $section['wysiwyg_description'], - ]; - @endphp + @php $section = $getSection('list_section_our_commitments'); @endphp @if($section) + @php + $engagements = [ + 'title' => $section['string_title'], + 'subtitle' => $section['string_subtitle'], + 'text' => $section['wysiwyg_description'], + ]; + @endphp + @if ($section) + + @endif {{-- COMMITMENT N°2 --}} @php $section = $getSection('list_section_our_ecosystem'); @endphp - + @if ($section) + + @endif {{-- COMMITMENT N°3 --}} - @php - $section = $getSection('list_section_our_governance'); - - // Anchor construction. - $specificSection = $pageNousConnaitre->content['list_section_our_values']; - $anchor = $specificSection ? '#' . \Illuminate\Support\Str::slug($specificSection[0]['string_title']) : ''; - $targetModel = \App\Models\PageConfig::getModelFromInputModelConfig( - $section['list_page_link'][0]['model_page'], - $section['list_page_link'][0]['reserved_model_page'], - ); - $buttonUrl = sprintf("%s%s", \App\Helpers\RouteHelper::routeNameChecker("front.dynamic-pages.{$targetModel->id_key}"), $anchor); - @endphp - + @php $section = $getSection('list_section_our_governance'); @endphp + @if($section) + @php + // Anchor construction. + $specificSection = $pageNousConnaitre->content['list_section_our_values']; + $anchor = $specificSection ? '#' . \Illuminate\Support\Str::slug($specificSection[0]['string_title']) : ''; + $targetModel = \App\Models\PageConfig::getModelFromInputModelConfig( + $section['list_page_link'][0]['model_page'], + $section['list_page_link'][0]['reserved_model_page'], + ); + $buttonUrl = sprintf("%s%s", \App\Helpers\RouteHelper::routeNameChecker("front.dynamic-pages.{$targetModel->id_key}"), $anchor); + @endphp + + @endif {{-- COMMITMENT N°4 --}} @php $section = $getSection('list_section_business_ethics'); @endphp - + @if($section) + + @endif {{-- COMMITMENT N°5 --}} @php $section = $getSection('list_section_business_ethics'); $section = $section ? $section['list_block_simple'][0] : null; @endphp - + @if($section) + + @endif {{-- COMMITMENTS LIST --}} @if($pageNosEngagements->childPages->count()) diff --git a/resources/views/front/pages/our-division.blade.php b/resources/views/front/pages/our-division.blade.php index d35aea17..d40e58a3 100644 --- a/resources/views/front/pages/our-division.blade.php +++ b/resources/views/front/pages/our-division.blade.php @@ -19,6 +19,7 @@ foreach($groupAccordion['list_accordion'] as $accordion) { array_push($accordions[$key]['accordions']['items'], [ 'image_block' => $accordion['image_visual'], + 'string_title' => $accordion['string_title'], 'string_alt' => $accordion['string_title'], 'wysiwyg_content' => $accordion['wysiwyg_content'], ]) ; diff --git a/resources/views/front/pages/search.blade.php b/resources/views/front/pages/search.blade.php index 61bde2e2..27deb3c6 100644 --- a/resources/views/front/pages/search.blade.php +++ b/resources/views/front/pages/search.blade.php @@ -7,66 +7,32 @@
@include('front.breadcrumbs.breadcrumb-body')
-

{{ trans('front.search.results_total', ['nbr' => $resultModels['totalHits'], 'terms' => $searchTerm]) }}

+

+ {{ trans('front.search.results_total', [ + 'nbr' => 0, + 'terms' => $searchTerm, + ]) }} +

-
- +
+ +
+
@error(trans('front.search.query'))
{{ $message }}
@enderror
-
- @forelse($resultModels['hits'] as $result) - @php - $locale = app()->getLocale(); - $hasDescription = isset($result['content']) && !is_null($result['content']) && !empty($result['content']); - @endphp - @php - if ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\DynamicPage::class))) { - $url = \App\Models\DynamicPage::getAccessModel($result['model_id']); - $routeName = sprintf('front.dynamic-pages.%s.%s', $result['id_key'], $locale); - $customBreadcrumbs = false; - } elseif ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\News::class))) { - $url = \App\Models\News::getAccessModel($result['model_id']); - $routeName = 'front.news.show'; - $customBreadcrumbs = true; - } elseif ($result['type'] === \Illuminate\Support\Str::snake(class_basename(\App\Models\Document::class))) { - $url = \App\Models\Document::getAccessModel($result['model_id']); - $routeName = 'front.documents.show'; - $customBreadcrumbs = true; - } - @endphp - -
{!! \App\Models\SearchIndex::highlightTerms($result['title'], $searchTerm) !!}
-
!$hasDescription, - 'breadcrumbs breadcrumbs_base_margined search-results__item-bc' => true, - ])> - @foreach(\Diglactic\Breadcrumbs\Breadcrumbs::generate($routeName)->toArray() as $breacrumb) - {{ $breacrumb->title }} - @if(!$loop->last) - > - @endif - @endforeach - @if($customBreadcrumbs) - > {{ $result['title'] }} - @endif -
- @if ($hasDescription) -
-

{!! \App\Models\SearchIndex::highlightTerms($result['content'], $searchTerm) !!}

-
- @endif -
- @empty -

{{ trans('front.search.no_results')}}

- @endforelse - -
+

{{ str(trans_choice('models.classes.news', \INF))->ucFirst() }}

+ +

{{ str(trans_choice('models.classes.dynamic-page', \INF))->ucFirst() }}

+ +

{{ str(trans_choice('models.classes.document', \INF))->ucFirst() }}

+
-@endsection +@endsection \ No newline at end of file diff --git a/routes/breadcrumbs-back.php b/routes/breadcrumbs-back.php index 1c1afb03..778fb6a1 100644 --- a/routes/breadcrumbs-back.php +++ b/routes/breadcrumbs-back.php @@ -132,7 +132,7 @@ Breadcrumbs::for('back.news.trash', function (Generator $trail) { $trail->push(Str::ucfirst(trans('back.archives'))); }); -// * NEWS CATEGORY +// * NEWS CATEGORY. Breadcrumbs::for('back.news-categories.index', function (Generator $trail) { $trail->parent('back.news.index'); $trail->push( @@ -161,7 +161,36 @@ Breadcrumbs::for('back.news-categories.trash', function (Generator $trail) { $trail->push(Str::ucfirst(trans('crud.actions.archive'))); }); -// * ACTIVITY LOGS +// * NEWS TAGS. +Breadcrumbs::for('back.news-tags.index', function (Generator $trail) { + $trail->parent('back.news.index'); + $trail->push( + Str::ucfirst(trans_choice('models.classes.news-tag', \INF)), + route('back.news-tags.index'), + ); +}); +Breadcrumbs::for('back.news-tags.create', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.create')), route('back.news-tags.create')); +}); +Breadcrumbs::for('back.news-tags.edit', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.edit')), route('back.news-tags.edit', [ + 'news_tag' => request()->news_tag + ])); +}); +Breadcrumbs::for('back.news-tags.show', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.visualize')), route('back.news-tags.show', [ + 'news_tag' => request()->news_tag + ])); +}); +Breadcrumbs::for('back.news-tags.trash', function (Generator $trail) { + $trail->parent('back.news-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.archive'))); +}); + +// * ACTIVITY LOGS. Breadcrumbs::for('back.activity-logs.index', function (Generator $trail) { $trail->parent('back.dashboard.index'); $trail->push( @@ -174,7 +203,7 @@ Breadcrumbs::for('back.activity-logs.show', function (Generator $trail) { $trail->push(Str::ucfirst(trans('crud.actions.visualize'))); }); -// * CONTACT COUNT +// * CONTACT COUNT. Breadcrumbs::for('back.contact-counts.index', function (Generator $trail) { $trail->parent('back.dashboard.index'); $trail->push( @@ -331,6 +360,10 @@ Breadcrumbs::for('back.document-categories.show', function (Generator $trail) { 'document_category' => request()->document_category ])); }); +Breadcrumbs::for('back.document-categories.trash', function (Generator $trail) { + $trail->parent('back.document-categories.index'); + $trail->push(Str::ucfirst(trans('crud.actions.archive'))); +}); // * DOCUMENT TAGS. Breadcrumbs::for('back.document-tags.index', function (Generator $trail) { @@ -356,3 +389,7 @@ Breadcrumbs::for('back.document-tags.show', function (Generator $trail) { 'document_tag' => request()->document_tag ])); }); +Breadcrumbs::for('back.document-tags.trash', function (Generator $trail) { + $trail->parent('back.document-tags.index'); + $trail->push(Str::ucfirst(trans('crud.actions.archive'))); +}); diff --git a/routes/breadcrumbs-front.php b/routes/breadcrumbs-front.php index db66e6e2..3ec67921 100644 --- a/routes/breadcrumbs-front.php +++ b/routes/breadcrumbs-front.php @@ -14,22 +14,24 @@ $currentLocale = app()->getLocale(); $supportedLocales = LaravelLocalization::getSupportedLanguagesKeys(); $pageHome = DynamicPage::getModelsCached() ->where('status', PageStatusEnum::published) - ->where('id_key', 'accueil') + ->where('isRoot', true) ->first(); // * DYNAMIC PAGES. -DynamicPage::getModelsCached()->map(function (DynamicPage $dynamicPageModel) use ($currentLocale, $pageHome) { - Breadcrumbs::for( - sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->id_key, $currentLocale), - function (Generator $trail) use ($currentLocale, $dynamicPageModel, $pageHome) { - if (!is_null($dynamicPageModel->page_id)) { - $trail->parent(sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->parentPage->id_key, $currentLocale)); - } elseif ($dynamicPageModel->id_key !== $pageHome->id_key) { - $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $currentLocale)); +DynamicPage::getModelsCached()->map(function (DynamicPage $dynamicPageModel) use ($supportedLocales, $pageHome) { + collect($supportedLocales)->map(function (string $locale) use ($dynamicPageModel, $pageHome) { + Breadcrumbs::for( + sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->id_key, $locale), + function (Generator $trail) use ($locale, $dynamicPageModel, $pageHome) { + if (!is_null($dynamicPageModel->page_id)) { + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $dynamicPageModel->parentPage->id_key, $locale)); + } elseif (isset($pageHome) && $dynamicPageModel->id_key !== $pageHome->id_key) { + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $locale)); + } + $trail->push($dynamicPageModel->title, RouteHelper::routeNameChecker(sprintf("front.dynamic-pages.%s", $dynamicPageModel->id_key))); } - $trail->push($dynamicPageModel->title, RouteHelper::routeNameChecker(sprintf("front.dynamic-pages.%s", $dynamicPageModel->id_key))); - } - ); + ); + }); }); // * CONTACT INDEX. @@ -61,7 +63,7 @@ Breadcrumbs::for('front.contact.show', function (Generator $trail) { // * SEARCH INDEX. Breadcrumbs::for('front.search', function (Generator $trail) use ($pageHome, $currentLocale) { if ($pageHome) { - $trail->parent("front.dynamic-pages.accueil.$currentLocale"); + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $currentLocale)); } $trail->push( Str::of(trans('front.search.trans'))->ucfirst(), @@ -89,6 +91,6 @@ Breadcrumbs::for('front.news.show', function (Generator $trail) use ($currentLoc // Need it for the search page. Breadcrumbs::for('front.documents.show', function (Generator $trail) use ($pageHome, $currentLocale) { if ($pageHome) { - $trail->parent("front.dynamic-pages.accueil.$currentLocale"); + $trail->parent(sprintf("front.dynamic-pages.%s.%s", $pageHome->id_key, $currentLocale)); } }); \ No newline at end of file diff --git a/routes/web-back.php b/routes/web-back.php index 428035c2..e62ad353 100644 --- a/routes/web-back.php +++ b/routes/web-back.php @@ -144,9 +144,30 @@ Route::prefix('admin') Route::get('/company-activities/{company_activity}/duplicate', [CompanyActivityController::class, 'duplicate']) ->name('company-activities.duplicate'); + // * DOCUMENTS. Route::resource('documents', DocumentController::class); - Route::resource('document-tags', DocumentTagController::class); + + // * DOCUMENTS CATEGORIES. + Route::get('/document-categories/trash', [DocumentCategoryController::class, 'index']) + ->name('document-categories.trash'); + Route::patch('/document-categories/{document_category}/restore', [DocumentCategoryController::class, 'restore']) + ->name('document-categories.restore'); + Route::delete('/document-categories/{document_category}/force', [DocumentCategoryController::class, 'forceDestroy']) + ->name('document-categories.forceDestroy'); Route::resource('document-categories', DocumentCategoryController::class); + Route::get('/document-categories/{document_category}/duplicate', [DocumentCategoryController::class, 'duplicate']) + ->name('document-categories.duplicate'); + + // * DOCUMENTS TAGS. + Route::get('/document-tags/trash', [DocumentTagController::class, 'index']) + ->name('document-tags.trash'); + Route::patch('/document-tags/{document_tag}/restore', [DocumentTagController::class, 'restore']) + ->name('document-tags.restore'); + Route::delete('/document-tags/{document_tag}/force', [DocumentTagController::class, 'forceDestroy']) + ->name('document-tags.forceDestroy'); + Route::resource('document-tags', DocumentTagController::class); + Route::get('/document-tags/{document_tag}/duplicate', [DocumentTagController::class, 'duplicate']) + ->name('document-tags.duplicate'); }); // * UPDATE LANGUAGES. diff --git a/routes/web-front.php b/routes/web-front.php index c805e74d..20a29f3a 100644 --- a/routes/web-front.php +++ b/routes/web-front.php @@ -28,6 +28,7 @@ Route::group( // Search routes. Route::get(LaravelLocalization::transRoute('routes.search'), [SearchController::class, 'search'])->name('search'); + Route::post('/search/load/results', [SearchController::class, 'ajaxSearchLoadResults'])->name('search.ajax.news'); // Filters routes. Route::prefix('posts')->group(function () {