From 842f08d21db5500568cf23c4eca7031c4e481ecf Mon Sep 17 00:00:00 2001 From: horacioskrp Date: Tue, 17 Nov 2026 15:07:13 +0000 Subject: [PATCH 01/10] =?UTF-8?q?feat(install):=20assistant=20web=20d'inst?= =?UTF-8?q?allation=20(Phase=201=20=E2=80=94=20UI=204=20=C3=A9tapes)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assistant d'installation style WordPress, calqué sur le design de la page de connexion (hero + DalibiLogo). Quatre étapes visibles : langue, école, administrateur, protocole de sécurité, puis écran d'exécution. Cette phase couvre l'ossature et l'UI ; l'exécution réelle (migrations, seed, création école/admin, pose du verrou) arrive en Phase 2 — l'écran 'running' est pour l'instant un espace réservé. - InstallState : source de vérité (verrou storage/app/installed.json + auto-cicatrisation si la base contient déjà des utilisateurs) - RequirementsChecker : contrôle PHP/extensions/droits/APP_KEY sans base - EnsureAppInstalled / EnsureAppNotInstalled : redirection vers/hors l'assistant, priorisé avant l'authentification - Session forcée en driver 'file' avant installation (pas de base requise) - Écrans Inertia : welcome, school, admin, security, running, requirements - i18n FR/EN, tests fonctionnels (8) ; TestCase considère l'app installée --- .../Controllers/Install/InstallController.php | 148 ++++++++++++++++++ app/Http/Middleware/EnsureAppInstalled.php | 32 ++++ app/Http/Middleware/EnsureAppNotInstalled.php | 27 ++++ app/Providers/AppServiceProvider.php | 22 ++- app/Support/Install/InstallState.php | 133 ++++++++++++++++ app/Support/Install/RequirementsChecker.php | 102 ++++++++++++ bootstrap/app.php | 18 +++ config/install.php | 58 +++++++ lang/en/install.php | 74 +++++++++ lang/fr/install.php | 74 +++++++++ resources/js/components/install-stepper.tsx | 50 ++++++ .../js/layouts/install/install-layout.tsx | 52 ++++++ resources/js/pages/install/admin.tsx | 97 ++++++++++++ resources/js/pages/install/requirements.tsx | 66 ++++++++ resources/js/pages/install/running.tsx | 43 +++++ resources/js/pages/install/school.tsx | 96 ++++++++++++ resources/js/pages/install/security.tsx | 109 +++++++++++++ resources/js/pages/install/welcome.tsx | 69 ++++++++ routes/install.php | 33 ++++ routes/web.php | 3 + tests/Feature/Install/InstallWizardTest.php | 113 +++++++++++++ tests/TestCase.php | 6 + 22 files changed, 1424 insertions(+), 1 deletion(-) create mode 100644 app/Http/Controllers/Install/InstallController.php create mode 100644 app/Http/Middleware/EnsureAppInstalled.php create mode 100644 app/Http/Middleware/EnsureAppNotInstalled.php create mode 100644 app/Support/Install/InstallState.php create mode 100644 app/Support/Install/RequirementsChecker.php create mode 100644 config/install.php create mode 100644 lang/en/install.php create mode 100644 lang/fr/install.php create mode 100644 resources/js/components/install-stepper.tsx create mode 100644 resources/js/layouts/install/install-layout.tsx create mode 100644 resources/js/pages/install/admin.tsx create mode 100644 resources/js/pages/install/requirements.tsx create mode 100644 resources/js/pages/install/running.tsx create mode 100644 resources/js/pages/install/school.tsx create mode 100644 resources/js/pages/install/security.tsx create mode 100644 resources/js/pages/install/welcome.tsx create mode 100644 routes/install.php create mode 100644 tests/Feature/Install/InstallWizardTest.php diff --git a/app/Http/Controllers/Install/InstallController.php b/app/Http/Controllers/Install/InstallController.php new file mode 100644 index 0000000..6abb85d --- /dev/null +++ b/app/Http/Controllers/Install/InstallController.php @@ -0,0 +1,148 @@ +passes()) { + return redirect('/install/requirements'); + } + + return Inertia::render('install/welcome', [ + 'locales' => Locales::options(), + 'current' => session('install.language.locale', config('install.defaults.locale')), + ]); + } + + public function storeLanguage(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'locale' => ['required', 'string', 'in:'.implode(',', Locales::codes())], + ]); + + session(['install.language' => $validated]); + app()->setLocale($validated['locale']); + + return redirect('/install/school'); + } + + /** Étape 2 — École. */ + public function school(): Response + { + return Inertia::render('install/school', [ + 'defaults' => config('install.defaults'), + 'values' => session('install.school'), + ]); + } + + public function storeSchool(Request $request): RedirectResponse + { + // PHASE 1 : validation minimale pour garder le squelette navigable. + // La validation complète (FormRequest SchoolRequest) arrive en Phase 2. + $validated = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + 'code' => ['nullable', 'string', 'max:50'], + 'currency' => ['nullable', 'string', 'max:10'], + 'timezone' => ['nullable', 'string', 'max:64'], + 'academic_year_start' => ['nullable', 'string', 'max:20'], + 'period_type' => ['nullable', 'string', 'max:30'], + ]); + + session(['install.school' => $validated]); + + return redirect('/install/admin'); + } + + /** Étape 3 — Administrateur. */ + public function admin(): Response + { + return Inertia::render('install/admin', [ + 'values' => array_diff_key((array) session('install.admin', []), ['password' => '', 'password_confirmation' => '']), + ]); + } + + public function storeAdmin(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'firstname' => ['required', 'string', 'max:255'], + 'lastname' => ['required', 'string', 'max:255'], + 'email' => ['required', 'email', 'max:255'], + 'password' => ['required', 'confirmed'], + ]); + + // On ne conserve pas le mot de passe en clair plus que nécessaire ; + // en Phase 2 il sera consommé immédiatement par l'Installer. + session(['install.admin' => $validated]); + + return redirect('/install/security'); + } + + /** Étape 4 — Protocole de sécurité. */ + public function security(): Response + { + return Inertia::render('install/security', [ + 'defaults' => config('install.security_defaults'), + 'values' => session('install.security'), + ]); + } + + public function storeSecurity(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'force_2fa' => ['boolean'], + 'force_https' => ['boolean'], + 'app_debug_off' => ['boolean'], + 'enable_sentry' => ['boolean'], + 'password_policy' => ['nullable', 'string', 'in:strong,medium'], + ]); + + session(['install.security' => $validated]); + + return redirect('/install/run'); + } + + /** + * Exécution de l'installation. + * + * PHASE 1 : écran de progression statique uniquement. L'orchestration réelle + * (migrate --force, db:seed ReferenceDataSeeder, création école/admin/année, + * application des réglages de sécurité, pose du verrou) sera implémentée en + * Phase 2 par App\Support\Install\Installer. + */ + public function run(): Response + { + return Inertia::render('install/running', [ + 'phasePlaceholder' => true, + ]); + } + + /** Écran dédié aux prérequis non satisfaits. */ + public function requirements(RequirementsChecker $requirements): Response + { + return Inertia::render('install/requirements', [ + 'requirements' => $requirements->check(), + 'passes' => $requirements->passes(), + ]); + } +} diff --git a/app/Http/Middleware/EnsureAppInstalled.php b/app/Http/Middleware/EnsureAppInstalled.php new file mode 100644 index 0000000..10f185c --- /dev/null +++ b/app/Http/Middleware/EnsureAppInstalled.php @@ -0,0 +1,32 @@ +state->isInstalled()) { + return $next($request); + } + + // Déjà dans l'assistant : on laisse passer. + if ($request->is('install', 'install/*')) { + return $next($request); + } + + return redirect('/install'); + } +} diff --git a/app/Http/Middleware/EnsureAppNotInstalled.php b/app/Http/Middleware/EnsureAppNotInstalled.php new file mode 100644 index 0000000..751e2fc --- /dev/null +++ b/app/Http/Middleware/EnsureAppNotInstalled.php @@ -0,0 +1,27 @@ +state->isInstalled()) { + return redirect('/login'); + } + + return $next($request); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index bfc495d..957fed8 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -10,6 +10,7 @@ use App\Observers\SchoolObserver; use App\Observers\StudentObserver; use App\Observers\UserObserver; +use App\Support\Install\InstallState; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; @@ -24,7 +25,8 @@ class AppServiceProvider extends ServiceProvider */ public function register(): void { - // + // État d'installation partagé et mémoïsé pour toute la requête. + $this->app->singleton(InstallState::class); } /** @@ -33,6 +35,7 @@ public function register(): void public function boot(): void { $this->configureDefaults(); + $this->useFileSessionBeforeInstall(); $this->registerObservers(); if (app()->environment('production')) { @@ -40,6 +43,23 @@ public function boot(): void } } + /** + * Avant installation, le pilote de session par défaut (« database ») ne peut + * pas fonctionner : la table sessions n'existe pas encore. On bascule donc sur + * le pilote « file » le temps de l'assistant, avant que StartSession ne résolve + * le gestionnaire de session pour la requête. + */ + protected function useFileSessionBeforeInstall(): void + { + if (app()->runningInConsole()) { + return; + } + + if (! $this->app->make(InstallState::class)->isInstalled()) { + config(['session.driver' => 'file']); + } + } + /** * Register model observers. */ diff --git a/app/Support/Install/InstallState.php b/app/Support/Install/InstallState.php new file mode 100644 index 0000000..a0be3d2 --- /dev/null +++ b/app/Support/Install/InstallState.php @@ -0,0 +1,133 @@ +override !== null) { + return $this->override; + } + + if ($this->installed !== null) { + return $this->installed; + } + + if (File::exists($this->lockPath())) { + return $this->installed = true; + } + + // Auto-cicatrisation : une base déjà peuplée = application installée. + // La sonde est protégée (try/catch) : sur un clone neuf sans base, elle + // renvoie false sans erreur. + if ($this->databaseHasUsers()) { + $this->lock(['healed' => true]); + + return $this->installed = true; + } + + return $this->installed = false; + } + + /** Force l'état (tests). Passer null pour rétablir la détection normale. */ + public function fake(?bool $installed): void + { + $this->override = $installed; + $this->installed = null; + } + + /** + * Pose le verrou d'installation avec quelques métadonnées. + * + * @param array $meta + */ + public function lock(array $meta = []): void + { + $payload = array_merge([ + 'installed_at' => now()->toIso8601String(), + 'version' => $this->appVersion(), + 'locale' => config('app.locale'), + ], $meta); + + File::ensureDirectoryExists(dirname($this->lockPath())); + File::put($this->lockPath(), json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); + + $this->installed = true; + } + + /** + * Métadonnées du verrou, ou null si absent. + * + * @return array|null + */ + public function meta(): ?array + { + if (! File::exists($this->lockPath())) { + return null; + } + + $decoded = json_decode((string) File::get($this->lockPath()), true); + + return is_array($decoded) ? $decoded : null; + } + + /** Retire le verrou (tests / réinstallation volontaire). */ + public function unlock(): void + { + File::delete($this->lockPath()); + $this->installed = null; + } + + /** Chemin absolu du fichier-verrou. */ + public function lockPath(): string + { + return storage_path('app/'.config('install.lock_file', 'installed.json')); + } + + /** Sonde prudente : la table users existe-t-elle et contient-elle des lignes ? */ + private function databaseHasUsers(): bool + { + try { + return Schema::hasTable('users') && DB::table('users')->exists(); + } catch (Throwable) { + // Base injoignable (clone neuf) : non installé, sans erreur. + return false; + } + } + + private function appVersion(): string + { + $path = base_path('package.json'); + + if (File::exists($path)) { + return (string) (json_decode((string) File::get($path))->version ?? '—'); + } + + return '—'; + } +} diff --git a/app/Support/Install/RequirementsChecker.php b/app/Support/Install/RequirementsChecker.php new file mode 100644 index 0000000..06229e9 --- /dev/null +++ b/app/Support/Install/RequirementsChecker.php @@ -0,0 +1,102 @@ + + */ + public function check(): array + { + return [ + ...$this->phpRequirement(), + ...$this->extensionRequirements(), + ...$this->writableRequirements(), + ...$this->appKeyRequirement(), + ]; + } + + public function passes(): bool + { + foreach ($this->check() as $requirement) { + if (! $requirement['ok']) { + return false; + } + } + + return true; + } + + /** @return list */ + private function phpRequirement(): array + { + $min = (string) config('install.min_php', '8.3.0'); + $ok = version_compare(PHP_VERSION, $min, '>='); + + return [[ + 'key' => 'php', + 'label' => 'PHP >= '.$min, + 'ok' => $ok, + 'hint' => $ok ? PHP_VERSION : 'Version actuelle : '.PHP_VERSION, + ]]; + } + + /** @return list */ + private function extensionRequirements(): array + { + $out = []; + + foreach ((array) config('install.required_extensions', []) as $ext) { + $ok = extension_loaded($ext); + $out[] = [ + 'key' => 'ext:'.$ext, + 'label' => 'Extension '.$ext, + 'ok' => $ok, + 'hint' => $ok ? 'Chargée' : 'Manquante', + ]; + } + + return $out; + } + + /** @return list */ + private function writableRequirements(): array + { + $out = []; + + foreach ((array) config('install.writable_paths', []) as $path) { + $full = base_path($path); + $ok = File::isDirectory($full) && File::isWritable($full); + $out[] = [ + 'key' => 'writable:'.$path, + 'label' => $path.' inscriptible', + 'ok' => $ok, + 'hint' => $ok ? 'OK' : 'Donnez les droits en écriture', + ]; + } + + return $out; + } + + /** @return list */ + private function appKeyRequirement(): array + { + $ok = (string) config('app.key') !== ''; + + return [[ + 'key' => 'app_key', + 'label' => 'Clé d\'application (APP_KEY)', + 'ok' => $ok, + 'hint' => $ok ? 'Définie' : 'Lancez : php artisan key:generate', + ]]; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index 15c3e25..fbbd277 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,7 @@ alias([ + 'install.guard' => EnsureAppNotInstalled::class, + ]); + + // La redirection « non installé » doit précéder l'authentification, sinon + // une route protégée renverrait vers /login avant d'atteindre l'assistant. + // La liste de priorité cible l'interface, pas la classe concrète. + $middleware->prependToPriorityList( + before: \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, + prepend: EnsureAppInstalled::class, + ); }) ->withExceptions(function (Exceptions $exceptions): void { // Capture des exceptions vers Sentry/GlitchTip. No-op si SENTRY_LARAVEL_DSN est vide. diff --git a/config/install.php b/config/install.php new file mode 100644 index 0000000..3818a20 --- /dev/null +++ b/config/install.php @@ -0,0 +1,58 @@ + '8.3.0', + + 'required_extensions' => [ + 'pdo_pgsql', + 'mbstring', + 'openssl', + 'ctype', + 'json', + 'fileinfo', + 'gd', + 'zip', + ], + + // Dossiers devant être inscriptibles par le serveur web. + 'writable_paths' => [ + 'storage', + 'bootstrap/cache', + ], + + // Fichier-verrou (relatif à storage/app/). Sa présence = application installée. + 'lock_file' => 'installed.json', + + // Valeurs par défaut proposées dans l'étape « École ». + 'defaults' => [ + 'locale' => Locales::DEFAULT, + 'currency' => Currencies::DEFAULT, + 'timezone' => 'Africa/Lome', + ], + + // Réglages de sécurité pré-cochés à l'étape « Protocole de sécurité ». + // (Appliqués en Phase 2 ; ici ils alimentent l'écran.) + 'security_defaults' => [ + 'force_2fa' => true, + 'force_https' => true, + 'app_debug_off' => true, + 'password_policy' => 'strong', + 'enable_sentry' => false, + ], +]; diff --git a/lang/en/install.php b/lang/en/install.php new file mode 100644 index 0000000..18680de --- /dev/null +++ b/lang/en/install.php @@ -0,0 +1,74 @@ + 'Dalibi setup', + 'hero_title' => 'Welcome to Dalibi', + 'hero_subtitle' => 'Let\'s set up your school in a few steps', + + 'steps' => [ + 'language' => 'Language', + 'school' => 'School', + 'admin' => 'Administrator', + 'security' => 'Security', + ], + + 'common' => [ + 'back' => 'Back', + 'continue' => 'Continue', + 'install' => 'Install', + 'optional' => 'optional', + ], + + 'welcome' => [ + 'title' => 'Choose a language', + 'description' => 'Select the application language', + ], + + 'school' => [ + 'title' => 'Your school', + 'description' => 'School identity and starting year', + 'name' => 'School name', + 'code' => 'Code', + 'currency' => 'Currency', + 'timezone' => 'Timezone', + 'academic_year_start' => 'Academic year — start', + 'period_type' => 'Period breakdown', + 'period_trimester' => 'Trimesters', + 'period_semester' => 'Semesters', + ], + + 'admin' => [ + 'title' => 'Administrator account', + 'description' => 'The main management account', + 'firstname' => 'First name', + 'lastname' => 'Last name', + 'email' => 'Email', + 'password' => 'Password', + 'password_confirmation' => 'Confirmation', + ], + + 'security' => [ + 'title' => 'Security protocol', + 'description' => 'Recommended settings — adjustable', + 'force_2fa' => 'Two-factor authentication required at first login', + 'app_debug_off' => 'Debug mode disabled (production)', + 'force_https' => 'Force HTTPS', + 'password_policy' => 'Password policy: strong', + 'enable_sentry' => 'Error logging (Sentry)', + 'lock_note' => 'The installer locks itself after installation.', + ], + + 'requirements' => [ + 'title' => 'System requirements', + 'description' => 'Some requirements must be met before installing', + 'recheck' => 'Re-check', + 'all_good' => 'All requirements are satisfied.', + ], + + 'running' => [ + 'title' => 'Installation in progress', + 'description' => 'Migration, reference data and account creation', + 'phase_note' => 'Phase 1 — demo screen. Real execution will be wired in Phase 2.', + 'to_login' => 'Go to login', + ], +]; diff --git a/lang/fr/install.php b/lang/fr/install.php new file mode 100644 index 0000000..4df8c88 --- /dev/null +++ b/lang/fr/install.php @@ -0,0 +1,74 @@ + 'Installation de Dalibi', + 'hero_title' => 'Bienvenue sur Dalibi', + 'hero_subtitle' => 'Configurons votre établissement en quelques étapes', + + 'steps' => [ + 'language' => 'Langue', + 'school' => 'École', + 'admin' => 'Administrateur', + 'security' => 'Sécurité', + ], + + 'common' => [ + 'back' => 'Retour', + 'continue' => 'Continuer', + 'install' => 'Installer', + 'optional' => 'optionnel', + ], + + 'welcome' => [ + 'title' => 'Choix de la langue', + 'description' => 'Sélectionnez la langue de l\'application', + ], + + 'school' => [ + 'title' => 'Votre établissement', + 'description' => 'Identité de l\'école et année de départ', + 'name' => 'Nom de l\'école', + 'code' => 'Code', + 'currency' => 'Devise', + 'timezone' => 'Fuseau horaire', + 'academic_year_start' => 'Année académique — début', + 'period_type' => 'Découpage des périodes', + 'period_trimester' => 'Trimestres', + 'period_semester' => 'Semestres', + ], + + 'admin' => [ + 'title' => 'Compte administrateur', + 'description' => 'Le compte principal de gestion', + 'firstname' => 'Prénom', + 'lastname' => 'Nom', + 'email' => 'Email', + 'password' => 'Mot de passe', + 'password_confirmation' => 'Confirmation', + ], + + 'security' => [ + 'title' => 'Protocole de sécurité', + 'description' => 'Réglages recommandés — ajustables', + 'force_2fa' => 'Double authentification imposée à la 1re connexion', + 'app_debug_off' => 'Mode debug désactivé (production)', + 'force_https' => 'HTTPS forcé', + 'password_policy' => 'Politique de mot de passe : fort', + 'enable_sentry' => 'Journalisation des erreurs (Sentry)', + 'lock_note' => 'L\'assistant se verrouille après l\'installation.', + ], + + 'requirements' => [ + 'title' => 'Prérequis système', + 'description' => 'Certains prérequis doivent être satisfaits avant l\'installation', + 'recheck' => 'Revérifier', + 'all_good' => 'Tous les prérequis sont satisfaits.', + ], + + 'running' => [ + 'title' => 'Installation en cours', + 'description' => 'Migration, données de référence et création des comptes', + 'phase_note' => 'Phase 1 — écran de démonstration. L\'exécution réelle sera branchée en Phase 2.', + 'to_login' => 'Aller à la connexion', + ], +]; diff --git a/resources/js/components/install-stepper.tsx b/resources/js/components/install-stepper.tsx new file mode 100644 index 0000000..002a64c --- /dev/null +++ b/resources/js/components/install-stepper.tsx @@ -0,0 +1,50 @@ +import { Check } from 'lucide-react'; +import { useTranslation } from '@/helpers/i18n'; + +const STEPS = ['language', 'school', 'admin', 'security'] as const; + +export type InstallStep = (typeof STEPS)[number]; + +export default function InstallStepper({ current }: Readonly<{ current: InstallStep }>) { + const { t } = useTranslation(); + const currentIndex = STEPS.indexOf(current); + + return ( +
    + {STEPS.map((step, index) => { + const done = index < currentIndex; + const active = index === currentIndex; + + return ( +
  1. +
    + + {done ? : index + 1} + + + {t(`install.steps.${step}`)} + +
    + {index < STEPS.length - 1 && ( +
  2. + ); + })} +
+ ); +} diff --git a/resources/js/layouts/install/install-layout.tsx b/resources/js/layouts/install/install-layout.tsx new file mode 100644 index 0000000..7e3d8ae --- /dev/null +++ b/resources/js/layouts/install/install-layout.tsx @@ -0,0 +1,52 @@ +import DalibiLogo from '@/components/dalibi-logo'; +import InstallStepper, { type InstallStep } from '@/components/install-stepper'; +import { useTranslation } from '@/helpers/i18n'; + +/** + * Layout de l'assistant d'installation — reprend la mise en page de la page de + * connexion (image à gauche, contenu à droite) et ajoute le fil des étapes. + */ +export default function InstallLayout({ + children, + title, + description, + step, +}: Readonly<{ + children: React.ReactNode; + title: string; + description: string; + step?: InstallStep; +}>) { + const { t } = useTranslation(); + + return ( +
+ {/* Section image - 50% */} +
+ Dalibi +
+
+

{t('install.hero_title')}

+

{t('install.hero_subtitle')}

+
+
+ + {/* Section formulaire - 50% */} +
+
+
+
+ + {step && } +
+

{title}

+

{description}

+
+
+ {children} +
+
+
+
+ ); +} diff --git a/resources/js/pages/install/admin.tsx b/resources/js/pages/install/admin.tsx new file mode 100644 index 0000000..8e34e1b --- /dev/null +++ b/resources/js/pages/install/admin.tsx @@ -0,0 +1,97 @@ +import { Form, Head, Link } from '@inertiajs/react'; +import { ArrowLeft, ArrowRight, Eye, EyeOff } from 'lucide-react'; +import { useState } from 'react'; +import InputError from '@/components/input-error'; +import PasswordStrength from '@/components/password-strength'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { useTranslation } from '@/helpers/i18n'; +import InstallLayout from '@/layouts/install/install-layout'; + +type Props = { + values?: { firstname?: string; lastname?: string; email?: string } | null; +}; + +export default function InstallAdmin({ values }: Readonly) { + const { t } = useTranslation(); + const v = values ?? {}; + const [password, setPassword] = useState(''); + const [show, setShow] = useState(false); + + return ( + + + +
+ {({ processing, errors }) => ( +
+
+
+ + + +
+
+ + + +
+
+ +
+ + + +
+ +
+ +
+ setPassword(e.target.value)} + /> + +
+ + +
+ +
+ + + +
+ +
+ + +
+
+ )} +
+
+ ); +} diff --git a/resources/js/pages/install/requirements.tsx b/resources/js/pages/install/requirements.tsx new file mode 100644 index 0000000..949fe72 --- /dev/null +++ b/resources/js/pages/install/requirements.tsx @@ -0,0 +1,66 @@ +import { Head, Link } from '@inertiajs/react'; +import { ArrowRight, CheckCircle2, RefreshCw, XCircle } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { useTranslation } from '@/helpers/i18n'; +import InstallLayout from '@/layouts/install/install-layout'; + +type Requirement = { key: string; label: string; ok: boolean; hint: string }; + +type Props = { + requirements: Requirement[]; + passes: boolean; +}; + +export default function InstallRequirements({ requirements, passes }: Readonly) { + const { t } = useTranslation(); + + return ( + + + +
+
    + {requirements.map((req) => ( +
  • + + {req.ok ? ( + + ) : ( + + )} + {req.label} + + {req.hint} +
  • + ))} +
+ + {passes && ( +

+ {t('install.requirements.all_good')} +

+ )} + +
+ + {passes && ( + + )} +
+
+
+ ); +} diff --git a/resources/js/pages/install/running.tsx b/resources/js/pages/install/running.tsx new file mode 100644 index 0000000..c796eed --- /dev/null +++ b/resources/js/pages/install/running.tsx @@ -0,0 +1,43 @@ +import { Head, Link } from '@inertiajs/react'; +import { ArrowRight, Loader2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { useTranslation } from '@/helpers/i18n'; +import InstallLayout from '@/layouts/install/install-layout'; + +type Props = { + phasePlaceholder?: boolean; +}; + +export default function InstallRunning({ phasePlaceholder }: Readonly) { + const { t } = useTranslation(); + + return ( + + + +
+
+ +
+
+
+
+
+
+ + {phasePlaceholder && ( +

+ {t('install.running.phase_note')} +

+ )} + + +
+ + ); +} diff --git a/resources/js/pages/install/school.tsx b/resources/js/pages/install/school.tsx new file mode 100644 index 0000000..414c4ce --- /dev/null +++ b/resources/js/pages/install/school.tsx @@ -0,0 +1,96 @@ +import { Form, Head, Link } from '@inertiajs/react'; +import { ArrowLeft, ArrowRight } from 'lucide-react'; +import InputError from '@/components/input-error'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { useTranslation } from '@/helpers/i18n'; +import InstallLayout from '@/layouts/install/install-layout'; + +type Props = { + defaults: { locale: string; currency: string; timezone: string }; + values?: Record | null; +}; + +export default function InstallSchool({ defaults, values }: Readonly) { + const { t } = useTranslation(); + const v = values ?? {}; + + return ( + + + +
+ {({ processing, errors }) => ( +
+
+ + + +
+ +
+
+ + + +
+
+ + + +
+
+ +
+ + + +
+ +
+
+ + + +
+
+ + + +
+
+ +
+ + +
+
+ )} +
+
+ ); +} diff --git a/resources/js/pages/install/security.tsx b/resources/js/pages/install/security.tsx new file mode 100644 index 0000000..01b2147 --- /dev/null +++ b/resources/js/pages/install/security.tsx @@ -0,0 +1,109 @@ +import { Form, Head, Link } from '@inertiajs/react'; +import { ArrowLeft, Download, KeyRound, Lock, Lock as LockIcon, ShieldCheck } from 'lucide-react'; +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { Spinner } from '@/components/ui/spinner'; +import { useTranslation } from '@/helpers/i18n'; +import InstallLayout from '@/layouts/install/install-layout'; + +type Defaults = { + force_2fa: boolean; + force_https: boolean; + app_debug_off: boolean; + enable_sentry: boolean; + password_policy: string; +}; + +type Props = { + defaults: Defaults; + values?: Partial | null; +}; + +function Toggle({ on, onClick }: Readonly<{ on: boolean; onClick: () => void }>) { + return ( + + ); +} + +export default function InstallSecurity({ defaults, values }: Readonly) { + const { t } = useTranslation(); + const init = { ...defaults, ...(values ?? {}) }; + + const [force2fa, setForce2fa] = useState(!!init.force_2fa); + const [appDebugOff, setAppDebugOff] = useState(init.app_debug_off !== false); + const [forceHttps, setForceHttps] = useState(init.force_https !== false); + const [sentry, setSentry] = useState(!!init.enable_sentry); + + const rows = [ + { icon: ShieldCheck, label: t('install.security.force_2fa'), on: force2fa, set: () => setForce2fa((x) => !x), name: 'force_2fa' }, + { icon: LockIcon, label: t('install.security.app_debug_off'), on: appDebugOff, set: () => setAppDebugOff((x) => !x), name: 'app_debug_off' }, + { icon: Lock, label: t('install.security.force_https'), on: forceHttps, set: () => setForceHttps((x) => !x), name: 'force_https' }, + { icon: Download, label: t('install.security.enable_sentry'), on: sentry, set: () => setSentry((x) => !x), name: 'enable_sentry' }, + ]; + + return ( + + + +
+ {({ processing }) => ( +
+ + {rows.map((row) => )} + +
+ {rows.map((row) => ( +
+ + + {row.label} + + +
+ ))} + +
+ + {t('install.security.password_policy')} +
+
+ +

+ + {t('install.security.lock_note')} +

+ +
+ + +
+
+ )} +
+
+ ); +} diff --git a/resources/js/pages/install/welcome.tsx b/resources/js/pages/install/welcome.tsx new file mode 100644 index 0000000..f6c5a18 --- /dev/null +++ b/resources/js/pages/install/welcome.tsx @@ -0,0 +1,69 @@ +import { Form, Head } from '@inertiajs/react'; +import { ArrowRight, Check } from 'lucide-react'; +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { Spinner } from '@/components/ui/spinner'; +import { useTranslation } from '@/helpers/i18n'; +import InstallLayout from '@/layouts/install/install-layout'; + +type Locale = { code: string; label: string; flag: string }; + +type Props = { + locales: Locale[]; + current: string; +}; + +export default function InstallWelcome({ locales, current }: Readonly) { + const { t } = useTranslation(); + const [selected, setSelected] = useState(current); + + return ( + + + +
+ {({ processing }) => ( +
+ + +
+ {locales.map((locale) => { + const active = selected === locale.code; + return ( + + ); + })} +
+ + +
+ )} +
+
+ ); +} diff --git a/routes/install.php b/routes/install.php new file mode 100644 index 0000000..723804c --- /dev/null +++ b/routes/install.php @@ -0,0 +1,33 @@ +prefix('install')->name('install.')->group(function () { + Route::get('/', [InstallController::class, 'welcome'])->name('welcome'); + Route::post('language', [InstallController::class, 'storeLanguage'])->name('language.store'); + + Route::get('school', [InstallController::class, 'school'])->name('school'); + Route::post('school', [InstallController::class, 'storeSchool'])->name('school.store'); + + Route::get('admin', [InstallController::class, 'admin'])->name('admin'); + Route::post('admin', [InstallController::class, 'storeAdmin'])->name('admin.store'); + + Route::get('security', [InstallController::class, 'security'])->name('security'); + Route::post('security', [InstallController::class, 'storeSecurity'])->name('security.store'); + + Route::get('requirements', [InstallController::class, 'requirements'])->name('requirements'); + + Route::get('run', [InstallController::class, 'run'])->middleware('throttle:10,1')->name('run'); +}); diff --git a/routes/web.php b/routes/web.php index 2e6aa77..3df4ce6 100644 --- a/routes/web.php +++ b/routes/web.php @@ -68,6 +68,9 @@ use Illuminate\Support\Facades\Route; use Inertia\Inertia; +// Assistant d'installation (chargé dans le groupe web : session + Inertia). +require __DIR__.'/install.php'; + Route::get('/', function () { return Inertia::render('welcome'); })->name('home'); diff --git a/tests/Feature/Install/InstallWizardTest.php b/tests/Feature/Install/InstallWizardTest.php new file mode 100644 index 0000000..a3262b8 --- /dev/null +++ b/tests/Feature/Install/InstallWizardTest.php @@ -0,0 +1,113 @@ +app->make(InstallState::class)->fake(false); + } + + private function installed(): void + { + $this->app->make(InstallState::class)->fake(true); + } + + public function test_welcome_screen_renders_when_not_installed(): void + { + $this->notInstalled(); + + $this->get('/install') + ->assertOk() + ->assertInertia(fn ($page) => $page->component('install/welcome')); + } + + public function test_requests_are_redirected_to_installer_when_not_installed(): void + { + $this->notInstalled(); + + $this->get('/login')->assertRedirect('/install'); + $this->get('/dashboard')->assertRedirect('/install'); + } + + public function test_installer_is_locked_once_installed(): void + { + $this->installed(); + + $this->get('/install')->assertRedirect('/login'); + } + + public function test_language_step_validates_and_advances(): void + { + $this->notInstalled(); + + $this->post('/install/language', ['locale' => 'xx']) + ->assertSessionHasErrors('locale'); + + $this->post('/install/language', ['locale' => 'en']) + ->assertRedirect('/install/school') + ->assertSessionHas('install.language.locale', 'en'); + } + + public function test_school_step_requires_a_name_and_advances(): void + { + $this->notInstalled(); + + $this->post('/install/school', []) + ->assertSessionHasErrors('name'); + + $this->post('/install/school', ['name' => 'Collège Dalibi']) + ->assertRedirect('/install/admin') + ->assertSessionHas('install.school.name', 'Collège Dalibi'); + } + + public function test_admin_step_requires_confirmed_password_and_advances(): void + { + $this->notInstalled(); + + $this->post('/install/admin', [ + 'firstname' => 'Ada', + 'lastname' => 'Admin', + 'email' => 'ada@example.test', + 'password' => 'secret-pass-123', + 'password_confirmation' => 'different', + ])->assertSessionHasErrors('password'); + + $this->post('/install/admin', [ + 'firstname' => 'Ada', + 'lastname' => 'Admin', + 'email' => 'ada@example.test', + 'password' => 'secret-pass-123', + 'password_confirmation' => 'secret-pass-123', + ])->assertRedirect('/install/security'); + } + + public function test_security_step_advances_to_run(): void + { + $this->notInstalled(); + + $this->post('/install/security', [ + 'force_2fa' => '1', + 'app_debug_off' => '1', + 'force_https' => '1', + 'enable_sentry' => '0', + 'password_policy' => 'strong', + ])->assertRedirect('/install/run'); + } + + public function test_run_screen_renders_without_executing(): void + { + $this->notInstalled(); + + $this->get('/install/run') + ->assertOk() + ->assertInertia(fn ($page) => $page->component('install/running')); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index eb8dc57..327f6ae 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,6 +2,7 @@ namespace Tests; +use App\Support\Install\InstallState; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; use Illuminate\Support\Facades\DB; @@ -15,6 +16,11 @@ protected function setUp(): void // Vite (manifeste absent en CI, ou périmé en local). La directive @vite // est neutralisée, ce qui n'affecte aucune assertion Inertia. $this->withoutVite(); + + // Par défaut, l'application est considérée installée pour que le middleware + // d'installation reste transparent. Les tests de l'assistant forcent l'état + // « non installé » via InstallState::fake(false). + $this->app->make(InstallState::class)->fake(true); } /** From 8804e24b6a111dc85f84d2f0f876b7d97b8198e5 Mon Sep 17 00:00:00 2001 From: horacioskrp Date: Tue, 17 Nov 2026 15:27:36 +0000 Subject: [PATCH 02/10] =?UTF-8?q?feat(install):=20ex=C3=A9cution=20r=C3=A9?= =?UTF-8?q?elle=20de=20l'installation=20(Phase=202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Branche l'orchestration réelle derrière l'écran de progression : à l'affichage, le front déclenche POST /install/execute qui exécute le service Installer puis redirige vers la connexion. Service App\Support\Install\Installer : - migrate --force (idempotent) - création de l'école (avant le seed, pour les en-têtes/bulletins par défaut) - db:seed ReferenceDataSeeder (rôles & permissions, catalogues) — rejouable - découpage des périodes (trimestre/semestre) appliqué aux types de classe - année scolaire active - administrateur + rôle « administrateur » + matricule (sans changement de mot de passe imposé : il vient de le choisir) - réglages de sécurité best-effort sur .env (APP_DEBUG, APP_URL en HTTPS), jamais sous tests ; choix consignés dans le verrou - pose du verrou storage/app/installed.json Chaque étape est idempotente (firstOrCreate/firstOrNew) : une reprise après échec ne crée pas de doublon. En cas d'erreur, l'écran propose de relancer. Tests : 2 nouveaux cas (garde-fou session, installation complète + verrou), nettoyage du verrou en tearDown. Suite complète verte (515). --- .../Controllers/Install/InstallController.php | 60 +++- app/Support/Install/Installer.php | 296 ++++++++++++++++++ lang/en/install.php | 6 +- lang/fr/install.php | 6 +- resources/js/pages/install/running.tsx | 91 ++++-- routes/install.php | 3 +- tests/Feature/Install/InstallWizardTest.php | 85 +++++ 7 files changed, 508 insertions(+), 39 deletions(-) create mode 100644 app/Support/Install/Installer.php diff --git a/app/Http/Controllers/Install/InstallController.php b/app/Http/Controllers/Install/InstallController.php index 6abb85d..108a73b 100644 --- a/app/Http/Controllers/Install/InstallController.php +++ b/app/Http/Controllers/Install/InstallController.php @@ -4,20 +4,22 @@ use App\Constants\Locales; use App\Http\Controllers\Controller; +use App\Support\Install\Installer; use App\Support\Install\RequirementsChecker; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; use Inertia\Inertia; use Inertia\Response; +use Throwable; /** * Assistant d'installation web (façon « première configuration »). * - * PHASE 1 — squelette navigable : les 4 écrans (langue, école, admin, sécurité) - * s'enchaînent, les données sont accumulées en session, et l'étape finale affiche - * l'écran de progression. L'exécution réelle (migrate + seed de production + - * création école/admin + pose du verrou) sera branchée en Phase 2 dans un service - * Installer dédié. Aucun accès base ni écriture .env n'a lieu ici. + * Les quatre écrans (langue, école, admin, sécurité) accumulent leurs données en + * session ; l'écran final déclenche l'exécution réelle via le service Installer + * (migrate + seed de production + création école/admin/année + réglages de + * sécurité + pose du verrou), puis redirige vers la connexion. */ class InstallController extends Controller { @@ -123,18 +125,48 @@ public function storeSecurity(Request $request): RedirectResponse } /** - * Exécution de l'installation. - * - * PHASE 1 : écran de progression statique uniquement. L'orchestration réelle - * (migrate --force, db:seed ReferenceDataSeeder, création école/admin/année, - * application des réglages de sécurité, pose du verrou) sera implémentée en - * Phase 2 par App\Support\Install\Installer. + * Écran de progression. L'exécution réelle est déclenchée par le front + * (POST /install/execute) dès l'affichage, puis la page redirige vers /login. */ public function run(): Response { - return Inertia::render('install/running', [ - 'phasePlaceholder' => true, - ]); + return Inertia::render('install/running'); + } + + /** + * Exécute l'installation à partir des données accumulées en session. + * + * Idempotent et protégé : en cas d'échec, l'utilisateur revient à l'écran de + * progression avec un message et peut relancer sans créer de doublon. + */ + public function execute(Request $request, Installer $installer): RedirectResponse + { + // Garde-fou : sans les étapes essentielles, on renvoie l'utilisateur au début. + if (! session()->has('install.school') || ! session()->has('install.admin')) { + return redirect('/install'); + } + + $payload = [ + 'locale' => session('install.language.locale', config('install.defaults.locale')), + 'school' => (array) session('install.school', []), + 'admin' => (array) session('install.admin', []), + 'security' => (array) session('install.security', []), + ]; + + try { + $installer->run($payload); + } catch (Throwable $e) { + Log::error('Échec de l\'installation web', ['exception' => $e]); + + return back()->withErrors([ + 'install' => __('install.running.error'), + ]); + } + + // Nettoyage : ne pas conserver les données d'installation (dont le mot de passe). + $request->session()->forget(['install.language', 'install.school', 'install.admin', 'install.security']); + + return redirect('/login')->with('status', __('install.running.done')); } /** Écran dédié aux prérequis non satisfaits. */ diff --git a/app/Support/Install/Installer.php b/app/Support/Install/Installer.php new file mode 100644 index 0000000..0a239c0 --- /dev/null +++ b/app/Support/Install/Installer.php @@ -0,0 +1,296 @@ +, admin?: array, security?: array} $payload + */ + public function run(array $payload): void + { + $locale = Locales::isValid($payload['locale'] ?? null) ? (string) $payload['locale'] : Locales::DEFAULT; + $schoolInput = (array) ($payload['school'] ?? []); + $adminInput = (array) ($payload['admin'] ?? []); + $security = $this->normalizeSecurity((array) ($payload['security'] ?? [])); + + app()->setLocale($locale); + + // 1. Schéma de base de données (idempotent : rien à migrer si déjà à jour). + Artisan::call('migrate', ['--force' => true]); + + // 2. École — créée avant le seed : les en-têtes et bulletins par défaut + // (DocumentHeaderSeeder, BulletinTemplateSeeder) itèrent sur les écoles existantes. + $school = $this->ensureSchool($schoolInput); + + // 3. Données de référence de production (rôles & permissions, catalogues, + // en-têtes/bulletins par école). Entièrement idempotent. + Artisan::call('db:seed', ['--class' => ReferenceDataSeeder::class, '--force' => true]); + + // 4. Découpage des périodes (trimestre / semestre) appliqué aux types de classe. + $this->applyPeriodSystem($schoolInput['period_type'] ?? null); + + // 5. Année scolaire active. + $this->ensureAcademicYear($schoolInput['academic_year_start'] ?? null); + + // 6. Administrateur — après le seed : le rôle « administrateur » existe désormais. + $this->ensureAdministrator($adminInput, $locale); + + // 7. Réglages de sécurité (best-effort sur le fichier .env). + $this->applySecurity($security); + + // 8. Verrou : l'application est désormais installée. + $this->state->lock([ + 'locale' => $locale, + 'school' => $school->name, + 'timezone' => (string) ($schoolInput['timezone'] ?? config('install.defaults.timezone')), + 'security' => $security, + ]); + } + + /** + * @param array $input + */ + private function ensureSchool(array $input): School + { + $name = trim((string) ($input['name'] ?? '')) ?: 'Mon établissement'; + $code = trim((string) ($input['code'] ?? '')) ?: $this->generateSchoolCode($name); + $currency = trim((string) ($input['currency'] ?? '')) ?: Currencies::DEFAULT; + + return School::firstOrCreate( + ['code' => $code], + [ + 'name' => $name, + 'level' => 'primaire', + 'currency' => $currency, + 'active' => true, + ], + ); + } + + private function generateSchoolCode(string $name): string + { + $base = (string) Str::of($name)->ascii()->upper()->replaceMatches('/[^A-Z0-9]/', '')->substr(0, 8); + + return $base !== '' ? $base : 'ECOLE'; + } + + /** Applique le système de périodes aux types de classe (mono-école). */ + private function applyPeriodSystem(mixed $periodType): void + { + $map = [ + 'trimester' => 'trimestre', + 'trimestre' => 'trimestre', + 'semester' => 'semestre', + 'semestre' => 'semestre', + ]; + + $system = $map[strtolower((string) $periodType)] ?? null; + + if ($system === null) { + return; + } + + DB::table('classroom_types')->update([ + 'period_system' => $system, + 'updated_at' => now(), + ]); + } + + private function ensureAcademicYear(mixed $startDate): void + { + $start = $this->parseDate($startDate) ?? $this->defaultYearStart(); + $end = $start->copy()->addYear()->subDay(); + $year = $start->year.'-'.$end->year; + + $created = AcademicYear::firstOrCreate( + ['year' => $year], + [ + 'start_date' => $start->toDateString(), + 'end_date' => $end->toDateString(), + 'active' => false, + ], + ); + + // Garantir qu'exactement une année soit active. + if (! AcademicYear::query()->where('active', true)->exists()) { + $created->update(['active' => true]); + } + } + + /** + * @param array $input + */ + private function ensureAdministrator(array $input, string $locale): void + { + $email = strtolower(trim((string) ($input['email'] ?? ''))); + + if ($email === '') { + return; // garde-fou : l'email est validé en amont par l'assistant. + } + + $user = User::firstOrNew(['email' => $email]); + + $user->firstname = trim((string) ($input['firstname'] ?? $user->firstname)); + $user->lastname = trim((string) ($input['lastname'] ?? $user->lastname)); + $user->locale = $locale; + // L'administrateur vient de choisir son mot de passe : pas de changement imposé. + $user->must_change_password = false; + $user->email_verified_at = $user->email_verified_at ?? Carbon::now(); + + if (! empty($input['password'])) { + $user->password = (string) $input['password']; // casté « hashed » par le modèle. + } + + // Colonnes NOT NULL à renseigner à la création (jamais écrasées sur reprise). + if (! $user->exists) { + $user->gender = 'other'; + $user->natricule = app(MatriculeService::class)->generateUserMatricule(Roles::ADMINISTRATOR); + } + + $user->save(); + $user->syncRoles([Roles::ADMINISTRATOR]); + } + + /** + * Normalise les réglages de sécurité (valeurs par défaut sûres). + * + * @param array $input + * @return array{force_2fa: bool, force_https: bool, app_debug_off: bool, enable_sentry: bool, password_policy: string} + */ + private function normalizeSecurity(array $input): array + { + $defaults = (array) config('install.security_defaults'); + + return [ + 'force_2fa' => (bool) ($input['force_2fa'] ?? $defaults['force_2fa'] ?? true), + 'force_https' => (bool) ($input['force_https'] ?? $defaults['force_https'] ?? true), + 'app_debug_off' => (bool) ($input['app_debug_off'] ?? $defaults['app_debug_off'] ?? true), + 'enable_sentry' => (bool) ($input['enable_sentry'] ?? $defaults['enable_sentry'] ?? false), + 'password_policy' => in_array($input['password_policy'] ?? null, ['strong', 'medium'], true) + ? (string) $input['password_policy'] + : (string) ($defaults['password_policy'] ?? 'strong'), + ]; + } + + /** + * Applique les réglages de sécurité qui ont un effet runtime via .env. + * + * Best-effort : si .env est absent ou non inscriptible, on n'échoue pas + * l'installation (les choix restent consignés dans le verrou). + * + * @param array{force_2fa: bool, force_https: bool, app_debug_off: bool, enable_sentry: bool, password_policy: string} $security + */ + private function applySecurity(array $security): void + { + $changes = []; + + if ($security['app_debug_off']) { + $changes['APP_DEBUG'] = 'false'; + } + + if ($security['force_https']) { + $changes['APP_URL'] = $this->httpsUrl((string) config('app.url')); + } + + if ($changes === []) { + return; + } + + $this->writeEnv($changes); + } + + private function httpsUrl(string $url): string + { + $url = trim($url) ?: 'http://localhost'; + + return (string) preg_replace('#^http://#i', 'https://', $url); + } + + /** + * Écrit/renseigne des clés dans le fichier .env (best-effort). + * + * @param array $changes + */ + private function writeEnv(array $changes): void + { + // Jamais de mutation du .env sous tests (évite tout effet de bord sur le dépôt). + if (app()->runningUnitTests()) { + return; + } + + try { + $path = base_path('.env'); + + if (! File::exists($path) || ! File::isWritable($path)) { + return; + } + + $content = (string) File::get($path); + + foreach ($changes as $key => $value) { + $line = $key.'='.$value; + $pattern = '/^'.preg_quote($key, '/').'=.*$/m'; + + $content = preg_match($pattern, $content) + ? (string) preg_replace($pattern, $line, $content) + : rtrim($content, "\n")."\n".$line."\n"; + } + + File::put($path, $content); + } catch (Throwable) { + // Best-effort : un .env non modifiable ne doit pas faire échouer l'installation. + } + } + + private function parseDate(mixed $value): ?Carbon + { + $value = trim((string) $value); + + if ($value === '') { + return null; + } + + try { + return Carbon::parse($value)->startOfDay(); + } catch (Throwable) { + return null; + } + } + + /** Rentrée par défaut : 1er septembre de l'année scolaire courante. */ + private function defaultYearStart(): Carbon + { + $now = Carbon::now(); + $year = $now->month >= 9 ? $now->year : $now->year - 1; + + return Carbon::create($year, 9, 1)->startOfDay(); + } +} diff --git a/lang/en/install.php b/lang/en/install.php index 18680de..e1b645f 100644 --- a/lang/en/install.php +++ b/lang/en/install.php @@ -68,7 +68,9 @@ 'running' => [ 'title' => 'Installation in progress', 'description' => 'Migration, reference data and account creation', - 'phase_note' => 'Phase 1 — demo screen. Real execution will be wired in Phase 2.', - 'to_login' => 'Go to login', + 'working' => 'Please wait, do not close this page…', + 'error' => 'Installation failed. Check the database and permissions, then try again.', + 'retry' => 'Try again', + 'done' => 'Installation complete. Sign in with the administrator account.', ], ]; diff --git a/lang/fr/install.php b/lang/fr/install.php index 4df8c88..904de41 100644 --- a/lang/fr/install.php +++ b/lang/fr/install.php @@ -68,7 +68,9 @@ 'running' => [ 'title' => 'Installation en cours', 'description' => 'Migration, données de référence et création des comptes', - 'phase_note' => 'Phase 1 — écran de démonstration. L\'exécution réelle sera branchée en Phase 2.', - 'to_login' => 'Aller à la connexion', + 'working' => 'Veuillez patienter, ne fermez pas cette page…', + 'error' => 'L\'installation a échoué. Vérifiez la base de données et les droits, puis réessayez.', + 'retry' => 'Réessayer', + 'done' => 'Installation terminée. Connectez-vous avec le compte administrateur.', ], ]; diff --git a/resources/js/pages/install/running.tsx b/resources/js/pages/install/running.tsx index c796eed..c0497d2 100644 --- a/resources/js/pages/install/running.tsx +++ b/resources/js/pages/install/running.tsx @@ -1,15 +1,49 @@ -import { Head, Link } from '@inertiajs/react'; -import { ArrowRight, Loader2 } from 'lucide-react'; +import { Head, router, usePage } from '@inertiajs/react'; +import { AlertTriangle, Loader2, RefreshCw } from 'lucide-react'; +import { useEffect, useRef, useState } from 'react'; import { Button } from '@/components/ui/button'; import { useTranslation } from '@/helpers/i18n'; import InstallLayout from '@/layouts/install/install-layout'; -type Props = { - phasePlaceholder?: boolean; -}; - -export default function InstallRunning({ phasePlaceholder }: Readonly) { +export default function InstallRunning() { const { t } = useTranslation(); + const { errors } = usePage().props as unknown as { errors: Record }; + const failed = Boolean(errors?.install); + + // Progression simulée : l'exécution est « silencieuse à la fin » (une seule + // requête POST), la barre rassure l'utilisateur pendant le traitement. + const [progress, setProgress] = useState(8); + const started = useRef(false); + + const execute = () => { + router.post( + '/install/execute', + {}, + { + preserveScroll: true, + onStart: () => setProgress(12), + }, + ); + }; + + useEffect(() => { + if (started.current || failed) { + return; + } + started.current = true; + execute(); + }, [failed]); + + useEffect(() => { + if (failed) { + return; + } + const id = setInterval(() => { + setProgress((p) => (p < 90 ? p + Math.max(1, Math.round((90 - p) / 12)) : p)); + }, 600); + + return () => clearInterval(id); + }, [failed]); return ( @@ -17,26 +51,43 @@ export default function InstallRunning({ phasePlaceholder }: Readonly) {
- + {failed ? ( + + ) : ( + + )}
-
+
- {phasePlaceholder && ( -

- {t('install.running.phase_note')} -

+ {failed ? ( + <> +

+ {errors.install} +

+ + + ) : ( +

{t('install.running.working')}

)} - -
); diff --git a/routes/install.php b/routes/install.php index 723804c..32aa4ef 100644 --- a/routes/install.php +++ b/routes/install.php @@ -29,5 +29,6 @@ Route::get('requirements', [InstallController::class, 'requirements'])->name('requirements'); - Route::get('run', [InstallController::class, 'run'])->middleware('throttle:10,1')->name('run'); + Route::get('run', [InstallController::class, 'run'])->name('run'); + Route::post('execute', [InstallController::class, 'execute'])->middleware('throttle:6,1')->name('execute'); }); diff --git a/tests/Feature/Install/InstallWizardTest.php b/tests/Feature/Install/InstallWizardTest.php index a3262b8..d6bc24c 100644 --- a/tests/Feature/Install/InstallWizardTest.php +++ b/tests/Feature/Install/InstallWizardTest.php @@ -2,6 +2,10 @@ namespace Tests\Feature\Install; +use App\Constants\Roles; +use App\Models\AcademicYear; +use App\Models\School; +use App\Models\User; use App\Support\Install\InstallState; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; @@ -10,6 +14,17 @@ class InstallWizardTest extends TestCase { use RefreshDatabase; + protected function tearDown(): void + { + // Ne jamais laisser fuiter le fichier-verrou créé par un test d'exécution. + $lock = storage_path('app/'.config('install.lock_file', 'installed.json')); + if (is_file($lock)) { + @unlink($lock); + } + + parent::tearDown(); + } + private function notInstalled(): void { $this->app->make(InstallState::class)->fake(false); @@ -109,5 +124,75 @@ public function test_run_screen_renders_without_executing(): void $this->get('/install/run') ->assertOk() ->assertInertia(fn ($page) => $page->component('install/running')); + + // L'affichage de l'écran ne crée rien : aucune école, aucun utilisateur. + $this->assertDatabaseCount('schools', 0); + $this->assertDatabaseCount('users', 0); + } + + public function test_execute_requires_the_essential_steps(): void + { + $this->notInstalled(); + + // Sans données école/admin en session, on repart au début. + $this->post('/install/execute')->assertRedirect('/install'); + + $this->assertDatabaseCount('schools', 0); + } + + public function test_execute_installs_the_application_and_locks_it(): void + { + $this->notInstalled(); + + $this->session([ + 'install.language' => ['locale' => 'fr'], + 'install.school' => [ + 'name' => 'Collège Dalibi', + 'currency' => 'XOF', + 'period_type' => 'semester', + 'academic_year_start' => '2026-09-01', + ], + 'install.admin' => [ + 'firstname' => 'Ada', + 'lastname' => 'Admin', + 'email' => 'ada@example.test', + 'password' => 'secret-pass-123', + ], + 'install.security' => [ + 'force_2fa' => true, + 'app_debug_off' => true, + 'force_https' => false, + 'enable_sentry' => false, + 'password_policy' => 'strong', + ], + ]); + + $this->post('/install/execute')->assertRedirect('/login'); + + // École créée. + $school = School::query()->where('name', 'Collège Dalibi')->first(); + $this->assertNotNull($school); + $this->assertSame('XOF', $school->currency); + + // Administrateur créé, rôle attribué, pas de changement de mot de passe imposé. + $admin = User::query()->where('email', 'ada@example.test')->first(); + $this->assertNotNull($admin); + $this->assertTrue($admin->hasRole(Roles::ADMINISTRATOR)); + $this->assertFalse($admin->must_change_password); + $this->assertNotEmpty($admin->natricule); + + // Une année scolaire active existe. + $this->assertTrue(AcademicYear::query()->where('active', true)->exists()); + + // Découpage des périodes appliqué aux types de classe. + $this->assertDatabaseHas('classroom_types', ['period_system' => 'semestre']); + + // Verrou posé : l'assistant est désormais inaccessible. + $this->app->make(InstallState::class)->fake(null); + $this->assertTrue($this->app->make(InstallState::class)->isInstalled()); + $this->get('/install')->assertRedirect('/login'); + + // Les données d'installation (dont le mot de passe) ne restent pas en session. + $this->assertNull(session('install.admin')); } } From ea816d76df420aa849ac4ae94634086f1ada43d0 Mon Sep 17 00:00:00 2001 From: horacioskrp Date: Tue, 17 Nov 2026 18:25:02 +0000 Subject: [PATCH 03/10] =?UTF-8?q?feat(install):=20=C3=A9cole=20en=20dernie?= =?UTF-8?q?r,=20champs=20du=20mod=C3=A8le,=20owner,=20i18n=20live,=20durci?= =?UTF-8?q?ssement=20s=C3=A9curit=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affinements de l'assistant d'installation après la Phase 2. Étapes - Ordre revu : Langue → Administrateur → Sécurité → École (l'école clôt et déclenche l'installation). Stepper, redirections et liens « Retour » alignés. - Le choix de la langue bascule désormais toute l'interface : l'étape écrit session('locale') (lue par SetLocale), les étapes suivantes suivent. École & propriétaire - Formulaire école calqué sur le modèle School (niveau, code, devise, directeur, email, téléphone, adresse, ville, région, description) ; la devise est un sélecteur alimenté par la constante Currencies (validation sur les codes). - Suivi du propriétaire : migration owner_id (FK users, nullOnDelete), relation School::owner(), renseigné par l'Installer (= administrateur créé). Sécurité (suite audit) - H1 : le mot de passe de l'administrateur applique la politique de l'app (trait PasswordValidationRules → Password::default()). - H2 : réglages honnêtes. 2FA retirée (non imposée, laissée au choix de chaque utilisateur) ; force_https réellement effectif via FORCE_HTTPS lu par AppServiceProvider (hors local) ; app_debug_off inchangé. Tests : nouvel ordre, propagation de langue, owner, champs modèle, politique mdp. Suite complète verte (516). PHPStan 0, Pint, tsc, ESLint, build OK. --- .../Controllers/Install/InstallController.php | 44 ++++++--- app/Models/School.php | 12 +++ app/Providers/AppServiceProvider.php | 4 +- app/Support/Install/Installer.php | 58 ++++++++---- config/install.php | 8 +- ...7_000001_add_owner_id_to_schools_table.php | 37 ++++++++ lang/en/install.php | 17 +++- lang/fr/install.php | 17 +++- resources/js/components/install-stepper.tsx | 2 +- resources/js/pages/install/admin.tsx | 2 +- resources/js/pages/install/school.tsx | 90 ++++++++++++++++--- resources/js/pages/install/security.tsx | 10 +-- tests/Feature/Install/InstallWizardTest.php | 59 ++++++++++-- 13 files changed, 295 insertions(+), 65 deletions(-) create mode 100644 database/migrations/2026_11_17_000001_add_owner_id_to_schools_table.php diff --git a/app/Http/Controllers/Install/InstallController.php b/app/Http/Controllers/Install/InstallController.php index 108a73b..d5a31d4 100644 --- a/app/Http/Controllers/Install/InstallController.php +++ b/app/Http/Controllers/Install/InstallController.php @@ -2,6 +2,8 @@ namespace App\Http\Controllers\Install; +use App\Concerns\PasswordValidationRules; +use App\Constants\Currencies; use App\Constants\Locales; use App\Http\Controllers\Controller; use App\Support\Install\Installer; @@ -23,6 +25,8 @@ */ class InstallController extends Controller { + use PasswordValidationRules; + /** Étape 1 — Langue & bienvenue. */ public function welcome(RequirementsChecker $requirements): Response|RedirectResponse { @@ -43,29 +47,44 @@ public function storeLanguage(Request $request): RedirectResponse 'locale' => ['required', 'string', 'in:'.implode(',', Locales::codes())], ]); - session(['install.language' => $validated]); + // On mémorise le choix pour l'installation ET sous la clé « locale » + // standard : le middleware SetLocale l'applique alors à toutes les étapes + // suivantes et à l'ensemble de l'interface (invité, avant connexion). + session([ + 'install.language' => $validated, + 'locale' => $validated['locale'], + ]); app()->setLocale($validated['locale']); - return redirect('/install/school'); + return redirect('/install/admin'); } - /** Étape 2 — École. */ + /** Étape 4 (dernière) — École. Déclenche l'installation. */ public function school(): Response { return Inertia::render('install/school', [ 'defaults' => config('install.defaults'), + 'currencies' => Currencies::options(), 'values' => session('install.school'), ]); } public function storeSchool(Request $request): RedirectResponse { - // PHASE 1 : validation minimale pour garder le squelette navigable. - // La validation complète (FormRequest SchoolRequest) arrive en Phase 2. + // Champs calqués sur le modèle School (colonnes réelles de la table « schools »). $validated = $request->validate([ 'name' => ['required', 'string', 'max:255'], + 'level' => ['nullable', 'in:primaire,college,lycee'], 'code' => ['nullable', 'string', 'max:50'], - 'currency' => ['nullable', 'string', 'max:10'], + 'currency' => ['nullable', 'string', 'in:'.implode(',', Currencies::codes())], + 'principal' => ['nullable', 'string', 'max:255'], + 'email' => ['nullable', 'email', 'max:255'], + 'phone' => ['nullable', 'string', 'max:50'], + 'address' => ['nullable', 'string', 'max:255'], + 'city' => ['nullable', 'string', 'max:120'], + 'region' => ['nullable', 'string', 'max:120'], + 'po_box' => ['nullable', 'string', 'max:50'], + 'description' => ['nullable', 'string', 'max:1000'], 'timezone' => ['nullable', 'string', 'max:64'], 'academic_year_start' => ['nullable', 'string', 'max:20'], 'period_type' => ['nullable', 'string', 'max:30'], @@ -73,10 +92,10 @@ public function storeSchool(Request $request): RedirectResponse session(['install.school' => $validated]); - return redirect('/install/admin'); + return redirect('/install/run'); } - /** Étape 3 — Administrateur. */ + /** Étape 2 — Administrateur. */ public function admin(): Response { return Inertia::render('install/admin', [ @@ -90,7 +109,9 @@ public function storeAdmin(Request $request): RedirectResponse 'firstname' => ['required', 'string', 'max:255'], 'lastname' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', 'max:255'], - 'password' => ['required', 'confirmed'], + // H1 : le compte le plus privilégié applique la politique mdp de l'app + // (Password::default() : min 12, casse mixte, chiffres, symboles, uncompromised en prod). + 'password' => $this->passwordRules(), ]); // On ne conserve pas le mot de passe en clair plus que nécessaire ; @@ -100,7 +121,7 @@ public function storeAdmin(Request $request): RedirectResponse return redirect('/install/security'); } - /** Étape 4 — Protocole de sécurité. */ + /** Étape 3 — Protocole de sécurité. */ public function security(): Response { return Inertia::render('install/security', [ @@ -112,7 +133,6 @@ public function security(): Response public function storeSecurity(Request $request): RedirectResponse { $validated = $request->validate([ - 'force_2fa' => ['boolean'], 'force_https' => ['boolean'], 'app_debug_off' => ['boolean'], 'enable_sentry' => ['boolean'], @@ -121,7 +141,7 @@ public function storeSecurity(Request $request): RedirectResponse session(['install.security' => $validated]); - return redirect('/install/run'); + return redirect('/install/school'); } /** diff --git a/app/Models/School.php b/app/Models/School.php index 39a88fa..bc516d1 100644 --- a/app/Models/School.php +++ b/app/Models/School.php @@ -20,6 +20,7 @@ use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; @@ -48,6 +49,7 @@ class School extends Model 'description', 'active', 'portal_enabled', + 'owner_id', ]; protected $casts = [ @@ -115,4 +117,14 @@ public function activeGradingConfig(): ?GradingConfig { return $this->gradingConfigs()->where('is_active', true)->first(); } + + /** + * Propriétaire de l'établissement (administrateur à l'origine de l'installation). + * + * @return BelongsTo + */ + public function owner(): BelongsTo + { + return $this->belongsTo(User::class, 'owner_id'); + } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 957fed8..b8ddb57 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -38,7 +38,9 @@ public function boot(): void $this->useFileSessionBeforeInstall(); $this->registerObservers(); - if (app()->environment('production')) { + // HTTPS forcé en production, ou lorsque l'assistant d'installation l'a activé + // (FORCE_HTTPS=true) — jamais en local pour ne pas casser le dev en http. + if (app()->environment('production') || (config('install.force_https') && ! app()->environment('local'))) { URL::forceScheme('https'); } } diff --git a/app/Support/Install/Installer.php b/app/Support/Install/Installer.php index 0a239c0..847ee16 100644 --- a/app/Support/Install/Installer.php +++ b/app/Support/Install/Installer.php @@ -51,7 +51,8 @@ public function run(array $payload): void $school = $this->ensureSchool($schoolInput); // 3. Données de référence de production (rôles & permissions, catalogues, - // en-têtes/bulletins par école). Entièrement idempotent. + // en-têtes/bulletins par école). Entièrement idempotent, exécuté APRÈS la + // création de l'école pour que les seeders « par école » s'appliquent. Artisan::call('db:seed', ['--class' => ReferenceDataSeeder::class, '--force' => true]); // 4. Découpage des périodes (trimestre / semestre) appliqué aux types de classe. @@ -61,15 +62,22 @@ public function run(array $payload): void $this->ensureAcademicYear($schoolInput['academic_year_start'] ?? null); // 6. Administrateur — après le seed : le rôle « administrateur » existe désormais. - $this->ensureAdministrator($adminInput, $locale); + $admin = $this->ensureAdministrator($adminInput, $locale); - // 7. Réglages de sécurité (best-effort sur le fichier .env). + // 7. Propriétaire de l'établissement = administrateur à l'origine de l'installation. + if ($admin !== null && $school->owner_id !== $admin->id) { + $school->owner_id = $admin->id; + $school->save(); + } + + // 8. Réglages de sécurité (best-effort sur le fichier .env). $this->applySecurity($security); - // 8. Verrou : l'application est désormais installée. + // 9. Verrou : l'application est désormais installée. $this->state->lock([ 'locale' => $locale, 'school' => $school->name, + 'owner' => $admin?->email, 'timezone' => (string) ($schoolInput['timezone'] ?? config('install.defaults.timezone')), 'security' => $security, ]); @@ -82,16 +90,28 @@ private function ensureSchool(array $input): School { $name = trim((string) ($input['name'] ?? '')) ?: 'Mon établissement'; $code = trim((string) ($input['code'] ?? '')) ?: $this->generateSchoolCode($name); - $currency = trim((string) ($input['currency'] ?? '')) ?: Currencies::DEFAULT; + + $level = in_array($input['level'] ?? null, ['primaire', 'college', 'lycee'], true) + ? (string) $input['level'] + : 'primaire'; + + // Champs facultatifs calqués sur le modèle School. + $optional = []; + foreach (['currency', 'principal', 'email', 'phone', 'address', 'city', 'region', 'po_box', 'description'] as $field) { + $value = trim((string) ($input[$field] ?? '')); + if ($value !== '') { + $optional[$field] = $value; + } + } + $optional['currency'] = $optional['currency'] ?? Currencies::DEFAULT; return School::firstOrCreate( ['code' => $code], - [ + array_merge([ 'name' => $name, - 'level' => 'primaire', - 'currency' => $currency, + 'level' => $level, 'active' => true, - ], + ], $optional), ); } @@ -148,12 +168,12 @@ private function ensureAcademicYear(mixed $startDate): void /** * @param array $input */ - private function ensureAdministrator(array $input, string $locale): void + private function ensureAdministrator(array $input, string $locale): ?User { $email = strtolower(trim((string) ($input['email'] ?? ''))); if ($email === '') { - return; // garde-fou : l'email est validé en amont par l'assistant. + return null; // garde-fou : l'email est validé en amont par l'assistant. } $user = User::firstOrNew(['email' => $email]); @@ -177,20 +197,23 @@ private function ensureAdministrator(array $input, string $locale): void $user->save(); $user->syncRoles([Roles::ADMINISTRATOR]); + + return $user; } /** * Normalise les réglages de sécurité (valeurs par défaut sûres). * + * NB : la 2FA n'est volontairement pas imposée (choix de chaque utilisateur). + * * @param array $input - * @return array{force_2fa: bool, force_https: bool, app_debug_off: bool, enable_sentry: bool, password_policy: string} + * @return array{force_https: bool, app_debug_off: bool, enable_sentry: bool, password_policy: string} */ private function normalizeSecurity(array $input): array { $defaults = (array) config('install.security_defaults'); return [ - 'force_2fa' => (bool) ($input['force_2fa'] ?? $defaults['force_2fa'] ?? true), 'force_https' => (bool) ($input['force_https'] ?? $defaults['force_https'] ?? true), 'app_debug_off' => (bool) ($input['app_debug_off'] ?? $defaults['app_debug_off'] ?? true), 'enable_sentry' => (bool) ($input['enable_sentry'] ?? $defaults['enable_sentry'] ?? false), @@ -206,7 +229,7 @@ private function normalizeSecurity(array $input): array * Best-effort : si .env est absent ou non inscriptible, on n'échoue pas * l'installation (les choix restent consignés dans le verrou). * - * @param array{force_2fa: bool, force_https: bool, app_debug_off: bool, enable_sentry: bool, password_policy: string} $security + * @param array{force_https: bool, app_debug_off: bool, enable_sentry: bool, password_policy: string} $security */ private function applySecurity(array $security): void { @@ -216,14 +239,13 @@ private function applySecurity(array $security): void $changes['APP_DEBUG'] = 'false'; } + // force_https réellement effectif : FORCE_HTTPS est lu par AppServiceProvider + // (hors local) pour appeler URL::forceScheme('https'). On aligne aussi APP_URL. + $changes['FORCE_HTTPS'] = $security['force_https'] ? 'true' : 'false'; if ($security['force_https']) { $changes['APP_URL'] = $this->httpsUrl((string) config('app.url')); } - if ($changes === []) { - return; - } - $this->writeEnv($changes); } diff --git a/config/install.php b/config/install.php index 3818a20..53f7e68 100644 --- a/config/install.php +++ b/config/install.php @@ -39,6 +39,11 @@ // Fichier-verrou (relatif à storage/app/). Sa présence = application installée. 'lock_file' => 'installed.json', + // Forçage HTTPS piloté par l'assistant (écrit FORCE_HTTPS dans .env). Appliqué + // par AppServiceProvider hors environnement local (en production, HTTPS est déjà + // forcé). Lu ici pour rester compatible avec `config:cache`. + 'force_https' => (bool) env('FORCE_HTTPS', false), + // Valeurs par défaut proposées dans l'étape « École ». 'defaults' => [ 'locale' => Locales::DEFAULT, @@ -47,9 +52,8 @@ ], // Réglages de sécurité pré-cochés à l'étape « Protocole de sécurité ». - // (Appliqués en Phase 2 ; ici ils alimentent l'écran.) + // La 2FA n'est volontairement PAS imposée (choix laissé à chaque utilisateur). 'security_defaults' => [ - 'force_2fa' => true, 'force_https' => true, 'app_debug_off' => true, 'password_policy' => 'strong', diff --git a/database/migrations/2026_11_17_000001_add_owner_id_to_schools_table.php b/database/migrations/2026_11_17_000001_add_owner_id_to_schools_table.php new file mode 100644 index 0000000..9957e8a --- /dev/null +++ b/database/migrations/2026_11_17_000001_add_owner_id_to_schools_table.php @@ -0,0 +1,37 @@ +uuid('owner_id')->nullable()->after('active'); + $table->foreign('owner_id')->references('id')->on('users')->nullOnDelete(); + }); + } + + public function down(): void + { + if (! Schema::hasColumn('schools', 'owner_id')) { + return; + } + + Schema::table('schools', function (Blueprint $table) { + $table->dropForeign(['owner_id']); + $table->dropColumn('owner_id'); + }); + } +}; diff --git a/lang/en/install.php b/lang/en/install.php index e1b645f..3e517de 100644 --- a/lang/en/install.php +++ b/lang/en/install.php @@ -26,10 +26,21 @@ 'school' => [ 'title' => 'Your school', - 'description' => 'School identity and starting year', + 'description' => 'Final step: your school identity, then installation starts', 'name' => 'School name', + 'level' => 'Level', + 'level_primary' => 'Primary', + 'level_college' => 'Middle school', + 'level_high' => 'High school', 'code' => 'Code', 'currency' => 'Currency', + 'principal' => 'Principal / Head', + 'email' => 'Email', + 'phone' => 'Phone', + 'address' => 'Address', + 'city' => 'City', + 'region' => 'Region', + 'description' => 'Description', 'timezone' => 'Timezone', 'academic_year_start' => 'Academic year — start', 'period_type' => 'Period breakdown', @@ -50,11 +61,11 @@ 'security' => [ 'title' => 'Security protocol', 'description' => 'Recommended settings — adjustable', - 'force_2fa' => 'Two-factor authentication required at first login', 'app_debug_off' => 'Debug mode disabled (production)', - 'force_https' => 'Force HTTPS', + 'force_https' => 'Force HTTPS (outside local)', 'password_policy' => 'Password policy: strong', 'enable_sentry' => 'Error logging (Sentry)', + 'two_factor_note' => 'Two-factor authentication stays optional — each user can enable it in their settings.', 'lock_note' => 'The installer locks itself after installation.', ], diff --git a/lang/fr/install.php b/lang/fr/install.php index 904de41..1187d03 100644 --- a/lang/fr/install.php +++ b/lang/fr/install.php @@ -26,10 +26,21 @@ 'school' => [ 'title' => 'Votre établissement', - 'description' => 'Identité de l\'école et année de départ', + 'description' => 'Dernière étape : l\'identité de l\'école, puis l\'installation démarre', 'name' => 'Nom de l\'école', + 'level' => 'Niveau', + 'level_primary' => 'Primaire', + 'level_college' => 'Collège', + 'level_high' => 'Lycée', 'code' => 'Code', 'currency' => 'Devise', + 'principal' => 'Directeur / Chef d\'établissement', + 'email' => 'Email', + 'phone' => 'Téléphone', + 'address' => 'Adresse', + 'city' => 'Ville', + 'region' => 'Région', + 'description' => 'Description', 'timezone' => 'Fuseau horaire', 'academic_year_start' => 'Année académique — début', 'period_type' => 'Découpage des périodes', @@ -50,11 +61,11 @@ 'security' => [ 'title' => 'Protocole de sécurité', 'description' => 'Réglages recommandés — ajustables', - 'force_2fa' => 'Double authentification imposée à la 1re connexion', 'app_debug_off' => 'Mode debug désactivé (production)', - 'force_https' => 'HTTPS forcé', + 'force_https' => 'HTTPS forcé (hors environnement local)', 'password_policy' => 'Politique de mot de passe : fort', 'enable_sentry' => 'Journalisation des erreurs (Sentry)', + 'two_factor_note' => 'La double authentification reste facultative, activable par chaque utilisateur dans ses réglages.', 'lock_note' => 'L\'assistant se verrouille après l\'installation.', ], diff --git a/resources/js/components/install-stepper.tsx b/resources/js/components/install-stepper.tsx index 002a64c..5051a11 100644 --- a/resources/js/components/install-stepper.tsx +++ b/resources/js/components/install-stepper.tsx @@ -1,7 +1,7 @@ import { Check } from 'lucide-react'; import { useTranslation } from '@/helpers/i18n'; -const STEPS = ['language', 'school', 'admin', 'security'] as const; +const STEPS = ['language', 'admin', 'security', 'school'] as const; export type InstallStep = (typeof STEPS)[number]; diff --git a/resources/js/pages/install/admin.tsx b/resources/js/pages/install/admin.tsx index 8e34e1b..6791012 100644 --- a/resources/js/pages/install/admin.tsx +++ b/resources/js/pages/install/admin.tsx @@ -78,7 +78,7 @@ export default function InstallAdmin({ values }: Readonly) {
+
+ + + +
+
+ +
- +
+
+ + + +
+
+ +
+
+ + + +
+
+ + + +
- - - + + + +
+ +
+
+ + + +
+
+ + + +
@@ -66,7 +125,7 @@ export default function InstallSchool({ defaults, values }: Readonly) { id="period_type" name="period_type" defaultValue={v.period_type ?? 'trimester'} - className="h-9 rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm" + className={selectClass} > @@ -75,17 +134,28 @@ export default function InstallSchool({ defaults, values }: Readonly) {
+
+ +