From fb57db6a4c60f2b58c485741cdcb74692f1df3b5 Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 23 Sep 2025 13:20:23 +0200 Subject: [PATCH] fix: :bug: update validations of fields translation --- app/Contracts/TranslatableModel.php | 24 ++++++ app/Helpers/TranslationHelper.php | 61 ++++++++++++++ .../Back/DynamicPageController.php | 10 +-- .../Controllers/Back/PageConfigController.php | 8 +- app/Http/Middleware/HandleInertiaRequests.php | 10 +-- app/Models/DynamicPage.php | 82 +++++++++---------- app/Models/PageConfig.php | 25 +++++- lang/en/back.php | 4 +- lang/en/crud.php | 2 + lang/fr/back.php | 4 +- lang/fr/crud.php | 2 + .../ts/back/Pages/DynamicPages/Index.tsx | 33 ++++---- resources/ts/back/Pages/PageConfigs/Index.tsx | 24 +++--- 13 files changed, 197 insertions(+), 92 deletions(-) create mode 100644 app/Contracts/TranslatableModel.php create mode 100644 app/Helpers/TranslationHelper.php diff --git a/app/Contracts/TranslatableModel.php b/app/Contracts/TranslatableModel.php new file mode 100644 index 00000000..e33ddb59 --- /dev/null +++ b/app/Contracts/TranslatableModel.php @@ -0,0 +1,24 @@ +getLocale(); + } + return Cache::remember(sprintf('translations_%s', app()->getLocale()), 86400, function () { + $translator = App::make('translator'); + $property = (new \ReflectionClass($translator))->getProperty('loaded'); + $property->setAccessible(true); + return $property->getValue($translator); + }); + } + + /** + * Assert fallback locale translation is present. + * + * @param \App\Contracts\TranslatableModel $model + * @return void + * @throws \Illuminate\Validation\ValidationException Translations missing. + */ + public static function validateFallbackTranslations(TranslatableModel $model): void + { + $localeFallback = config('app.fallback_locale'); + $missingTranslations = []; + foreach ($model->getTranslations() as $key => $value) { + if (!is_null($model->{$key}) && !$model->hasTranslation($key, $localeFallback)) { + $validationTranslations = self::getCachedTranslations()['validation']; + $field = (array_key_exists($key, $validationTranslations['attributes'])) + ? trans("validation.attributes.$key") + : trans("validation.custom.$key"); + $missingTranslations = array_merge($missingTranslations, [ + $key => trans_choice('back.missing_translations', 1, [ + 'field' => $field, + 'locales' => Str::upper($localeFallback), + ]), + ]); + } + } + if ($missingTranslations) { + throw ValidationException::withMessages($missingTranslations); + } + } +} diff --git a/app/Http/Controllers/Back/DynamicPageController.php b/app/Http/Controllers/Back/DynamicPageController.php index 76f1e3c3..816b8635 100644 --- a/app/Http/Controllers/Back/DynamicPageController.php +++ b/app/Http/Controllers/Back/DynamicPageController.php @@ -35,7 +35,7 @@ class DynamicPageController extends Controller $query = DynamicPage::query()->with('config'); if ($request->routeIs("back.dynamic-pages.trash")) { - $query = $query->onlyTrashed(); + $query = $query->onlyTrashed()->with(['config' => fn($q) => $q->withTrashed()]); } /** @var string $search Search field */ @@ -185,14 +185,14 @@ class DynamicPageController extends Controller /** @var array */ $previousQueries = []; \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); - if ($dynamic_page->restoreQuietly()) { + if ($dynamic_page->restore()) { return redirect()->route('back.dynamic-pages.trash', $previousQueries) - ->with('success', __('crud.messages.has_been_deleted', [ + ->with('success', __('crud.messages.has_been_restored', [ 'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', \INF)) ])); } return redirect()->back() - ->with('error', __('crud.messages.cannot_be_deleted', [ + ->with('error', __('crud.messages.cannot_be_restored', [ 'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', \INF)) ])); } @@ -208,7 +208,7 @@ class DynamicPageController extends Controller /** @var array */ $previousQueries = []; \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); - if ($dynamic_page->deleteQuietly()) { + if ($dynamic_page->delete()) { return redirect()->route('back.dynamic-pages.index', $previousQueries) ->with('success', __('crud.messages.has_been_deleted', [ 'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', \INF)) diff --git a/app/Http/Controllers/Back/PageConfigController.php b/app/Http/Controllers/Back/PageConfigController.php index 8dc8f0ab..d44e0054 100644 --- a/app/Http/Controllers/Back/PageConfigController.php +++ b/app/Http/Controllers/Back/PageConfigController.php @@ -180,14 +180,14 @@ class PageConfigController extends Controller /** @var array */ $previousQueries = []; \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); - if ($page_config->restoreQuietly()) { + if ($page_config->restore()) { return redirect()->route('back.page-configs.trash', $previousQueries) - ->with('success', __('crud.messages.has_been_deleted', [ + ->with('success', __('crud.messages.has_been_restored', [ 'model' => Str::ucfirst(trans_choice('models.classes.page-config', \INF)) ])); } return redirect()->back() - ->with('error', __('crud.messages.cannot_be_deleted', [ + ->with('error', __('crud.messages.cannot_be_restored', [ 'model' => Str::ucfirst(trans_choice('models.classes.page-config', \INF)) ])); } @@ -203,7 +203,7 @@ class PageConfigController extends Controller /** @var array */ $previousQueries = []; \parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries); - if ($page_config->deleteQuietly()) { + if ($page_config->delete()) { return redirect()->route('back.page-configs.index', $previousQueries) ->with('success', __('crud.messages.has_been_deleted', [ 'model' => Str::ucfirst(trans_choice('models.classes.page-config', \INF)) diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index 5c5678f8..d9966d8b 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -4,12 +4,11 @@ namespace App\Http\Middleware; use App\Enums\DynamicFieldTypes; use App\Enums\DynamicPages\PageStatusEnum; +use App\Helpers\TranslationHelper; use App\Models\DynamicPage; use App\Models\PageConfig; use Diglactic\Breadcrumbs\Breadcrumbs; use Illuminate\Http\Request; -use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Gate; use Inertia\Middleware; use Uwil\LaravelBackend\Enums\RoleEnum; @@ -34,12 +33,7 @@ class HandleInertiaRequests extends Middleware public function share(Request $request): array { // Get translations from translator app. - $translations = Cache::remember(sprintf('translations_%s', app()->getLocale()), 86400, function () { - $translator = App::make('translator'); - $property = (new \ReflectionClass($translator))->getProperty('loaded'); - $property->setAccessible(true); - return $property->getValue($translator); - }); + $translations = TranslationHelper::getCachedTranslations(); // Get all errors messages of session from middleware and redirect response. $errors = array_filter([ diff --git a/app/Models/DynamicPage.php b/app/Models/DynamicPage.php index fb3cb457..468ce6b3 100644 --- a/app/Models/DynamicPage.php +++ b/app/Models/DynamicPage.php @@ -2,8 +2,10 @@ namespace App\Models; +use App\Contracts\TranslatableModel; use App\Enums\DynamicFieldTypes; use App\Enums\DynamicPages\PageStatusEnum; +use App\Helpers\TranslationHelper; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -25,7 +27,7 @@ use Uwil\LaravelCommon\Helpers\ToolboxHelper; * @property-read \Illuminate\Support\Carbon $updated_at Date on which the dynamic page was updated. * @property-read \Illuminate\Support\Carbon $deleted_at Date on which the dynamic page was updated. */ -class DynamicPage extends Model +class DynamicPage extends Model implements TranslatableModel { use HasFactory; use HasTranslations; @@ -75,20 +77,33 @@ class DynamicPage extends Model { static::creating(function (self $model) { self::manageFields($model); - self::validateTranslations($model); + self::validateFallbackTranslations($model); }); static::created(function () { self::resetCache(); }); static::updating(function (self $model) { self::manageFields($model); - self::validateTranslations($model); + self::validateFallbackTranslations($model); }); static::updated(function (self $model) { self::resetCache(); self::removeImgs($model); }); - static::deleted(function (self $model) { + static::deleted(function () { + self::resetCache(); + }); + static::restoring(function (self $model) { + if ($model->config_id && $model->config()->onlyTrashed()->exists()) { + throw ValidationException::withMessages([ + 'error' => __('crud.messages.cannot_be_restored', [ + 'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', 1)) + ]), + ]); + } + self::resetCache(); + }); + static::forceDeleted(function (self $model) { self::resetCache(); self::removeImgs($model); }); @@ -110,40 +125,6 @@ class DynamicPage extends Model $model->slug = Str::slug($model->title); } - /** - * Validate all translations required are defined. - * - * @param self $model - * @return void - * @throws \Illuminate\Validation\ValidationException Translations missing. - */ - public static function validateTranslations(self $model): void - { - if (! $model->status->equals(PageStatusEnum::published)) { - return; - } - - if ($model->config) { - $modelLocales = collect(array_keys($model->config->getTranslations('config'))); - $locales = collect(config('app.locales')); - $allowedLocales = $modelLocales->intersect($locales); - - $missingLocales = $allowedLocales->reject( - fn($locale) => $model->hasTranslation('content', $locale) - ); - - if ($missingLocales->isNotEmpty()) { - throw ValidationException::withMessages([ - 'content' => trans_choice( - 'back.missing_translations', - $missingLocales->count() > 2 ? \INF : 1, - ['locales' => Str::upper($missingLocales->implode(', '))] - ), - ]); - } - } - } - /** * Remove imgs from wysiwyg OR dynamic wysiwyg. * @@ -172,13 +153,30 @@ class DynamicPage extends Model }); }); } else { - FileHelper::removeOldModelFilesFromHtml( - $model->content, - $model->getOriginal("content")[config('app.locale')] - ); + if (isset($model->getOriginal("content")[config('app.locale')])) { + FileHelper::removeOldModelFilesFromHtml( + $model->content, + $model->getOriginal("content")[config('app.locale')] + ); + } } //end if } + /** + * Assert fallback locale translation is present. + * + * @param self $model + * @return void + * @throws \Illuminate\Validation\ValidationException Translations missing. + */ + public static function validateFallbackTranslations(self $model): void + { + if (! $model->status->equals(PageStatusEnum::published)) { + return; + } + TranslationHelper::validateFallbackTranslations($model); + } + /** * Reset all cache elements related to this model. * diff --git a/app/Models/PageConfig.php b/app/Models/PageConfig.php index 17b95f3a..3fd58d18 100644 --- a/app/Models/PageConfig.php +++ b/app/Models/PageConfig.php @@ -2,7 +2,9 @@ namespace App\Models; +use App\Contracts\TranslatableModel; use App\Enums\DynamicPages\PageStatusEnum; +use App\Helpers\TranslationHelper; use App\Traits\Models\HasTranslations; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -16,7 +18,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \Illuminate\Support\Carbon $updated_at Date on which the page configuration was updated. * @property-read \Illuminate\Support\Carbon $deleted_at Date on which the page configuration was updated. */ -class PageConfig extends Model +class PageConfig extends Model implements TranslatableModel { use HasFactory; use HasTranslations; @@ -59,6 +61,12 @@ class PageConfig extends Model */ protected static function booted(): void { + static::creating(function (self $model) { + TranslationHelper::validateFallbackTranslations($model); + }); + static::updating(function (self $model) { + TranslationHelper::validateFallbackTranslations($model); + }); static::updated(function (self $model) { /** * If the config is updated, delete the content of all associated dynamic pages @@ -76,11 +84,20 @@ class PageConfig extends Model } } }); - static::deleting(function (self $model) { + static::deleted(function (self $model) { $model->pages()->delete(); }); - static::restoring(function (self $model) { - $model->pages()->withTrashed()->restore(); + static::restored(function (self $model) { + $model->pages() + ->onlyTrashed() + ->get() + ->map(function (DynamicPage $dynamicPageModel) { + $dynamicPageModel->status = PageStatusEnum::draft; + $dynamicPageModel->restore(); + }); + }); + static::forceDeleted(function (self $model) { + $model->pages()->forceDelete(); }); } diff --git a/lang/en/back.php b/lang/en/back.php index b0f75126..f08502d5 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -88,6 +88,6 @@ return [ "config_save_warning" => "The configuration of related pages in :locale will be updated accordingly.", "config_save_warning_list" => "Here is the list of :models concerned:|Here is the list of :models concerned:", "unsupported_type" => "Unsupported type:", - "missing_translations" => "The translation for the language :locales is missing in order to publish this - page.|Translations for :locales languages are missing in order to publish this page.", + "missing_translations" => "The translation of the :field for the language :locales is missing.|The translation + of the :field for :locales languages are missing.", ]; diff --git a/lang/en/crud.php b/lang/en/crud.php index b331e839..385966d6 100644 --- a/lang/en/crud.php +++ b/lang/en/crud.php @@ -50,6 +50,8 @@ return [ "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 !", diff --git a/lang/fr/back.php b/lang/fr/back.php index bbaedf35..9e599890 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -88,6 +88,6 @@ return [ en conséquence.", "config_save_warning_list" => "Voici la liste des :models concernés:|Voici la liste des :models concernées:", "unsupported_type" => "Type non supporté:", - "missing_translations" => "La traduction pour la langue :locales est manquante afin de publier cette page.|Les - traductions pour les langues :locales sont manquantes afin de publier cette page.", + "missing_translations" => "La traduction du champs :field pour la langue :locales est manquante.|La traduction + du champs :field pour les langues :locales sont manquantes.", ]; diff --git a/lang/fr/crud.php b/lang/fr/crud.php index 40d759bc..b107d656 100644 --- a/lang/fr/crud.php +++ b/lang/fr/crud.php @@ -50,6 +50,8 @@ return [ "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 !", diff --git a/resources/ts/back/Pages/DynamicPages/Index.tsx b/resources/ts/back/Pages/DynamicPages/Index.tsx index 9d89764e..170a3160 100644 --- a/resources/ts/back/Pages/DynamicPages/Index.tsx +++ b/resources/ts/back/Pages/DynamicPages/Index.tsx @@ -12,6 +12,7 @@ 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 BtnTooltip from "@/back/Components/BtnTooltip"; import DynamicPageStatusBadge from "@/back/Components/DynamicPageStatusBadge"; import { useFormatedDate } from "@/hooks/use-formated-value"; @@ -76,17 +77,16 @@ export default function Dashboard({ ), cell: ({ row }: { row: Row }) => { if (row.getValue("config")) { - const cellValue = (row.getValue("config") as PageConfigModel).label[appEnv.locale]; - return auth.policies.pageConfigs.viewAny ? ( + const pageConfigModel = row.getValue("config") as PageConfigModel; + const cellValue = pageConfigModel.label[appEnv.locale]; + return auth.policies.pageConfigs.viewAny && !pageConfigModel.deleted_at ? (