diff --git a/CLAUDE.md b/CLAUDE.md index 1ce7acc..1bad7c5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -266,6 +266,7 @@ php bin/proton worker [--once] [--queue=default,webhooks]|worker:restart|schedul php bin/proton queue:status|queue:retry|queue:purge php bin/proton user:create|user:list|user:password|user:delete|role:list php bin/proton key:create|key:list|key:revoke +php bin/proton settings:export|settings:import перенос настроек и ролей между окружениями php bin/proton mail:test <адрес> пробное письмо php bin/proton webhook:list [--events] подписки или реестр событий php bin/proton webhook:test пробная посылка подписчику diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index a76e807..a575c7f 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -83,3 +83,27 @@ Settings::problem('ui.per_page', 'много'); // текст ошибки ил Настроек базы, ключа приложения и отладки. Их правка требует перезапуска и может оставить приложение без доступа к данным — это работа с `.env` и с сервером, а не кнопка в браузере. + +## Перенос между окружениями + +Настройки, правленные из панели, и свои роли переносятся файлом — донастраивать +второе окружение руками через форму не нужно: + +```bash +php bin/proton settings:export # var/export/settings-ГГГГММДД-ЧЧММСС.json +php bin/proton settings:export --out=deploy.json # или в свой путь + +php bin/proton settings:import deploy.json # спросит подтверждение +php bin/proton settings:import deploy.json --force # для скрипта деплоя +``` + +Секреты (тип `Settings::SECRET`, например ключ почтового сервиса) в файл не +попадают — они зашифрованы мастер-ключом исходного окружения (`APP_KEY`) и на +другом не расшифруются. Список пропущенных ключей команда печатает, значения +переносятся в целевой `.env` руками. + +Встроенную роль администратора команда не выгружает и не правит — её права +всегда берутся из кода. Остальные роли ищутся по имени: совпало — обновляются +описание и права, нет — заводится новая. Настройка, которой целевой реестр не +знает (другая версия кода), пропускается с пометкой в выводе, а не роняет +остальной импорт. Ничего не удаляется: лишних на базе ролей файл не касается. diff --git a/framework/Console/Application.php b/framework/Console/Application.php index 5441d3f..68ce26c 100644 --- a/framework/Console/Application.php +++ b/framework/Console/Application.php @@ -65,6 +65,8 @@ final class Application Commands\KeyCreateCommand::class, Commands\KeyListCommand::class, Commands\KeyRevokeCommand::class, + Commands\SettingsExportCommand::class, + Commands\SettingsImportCommand::class, ], 'Почта' => [ Commands\MailTestCommand::class, diff --git a/framework/Console/Commands/SettingsExportCommand.php b/framework/Console/Commands/SettingsExportCommand.php new file mode 100644 index 0000000..8818df2 --- /dev/null +++ b/framework/Console/Commands/SettingsExportCommand.php @@ -0,0 +1,115 @@ +where('is_system', 0)->orderBy('id')->get() as $role) { + $roles[] = [ + 'name' => (string) $role->name, + 'description' => (string) $role->description, + 'permissions' => $role->permissions, + ]; + } + + $payload = [ + 'app' => (string) Config::get('app.name', 'Proton'), + 'exported_at' => date('Y-m-d H:i:s'), + 'settings' => $settings, + 'roles' => $roles, + ]; + + if ($skipped !== []) { + $payload['settings_skipped_secret'] = $skipped; + } + + $path = (string) $this->option('out', 'var/export/settings-' . date('Ymd-His') . '.json'); + $full = str_starts_with($path, '/') || preg_match('/^[A-Za-z]:/', $path) === 1 + ? $path + : APP_ROOT . '/' . $path; + + $dir = dirname($full); + + if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) { + $this->fail('Не удалось создать каталог ' . $dir); + + return 1; + } + + $json = (string) json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + if (@file_put_contents($full, $json) === false) { + $this->fail('Не удалось записать файл ' . $full); + + return 1; + } + + $this->ok('Настроек: ' . count($settings) . ', ролей: ' . count($roles)); + + if ($skipped !== []) { + $this->line(' Секреты пропущены, перенесите руками: ' . implode(', ', $skipped)); + } + + $this->line('Файл: ' . str_replace(APP_ROOT . '/', '', str_replace('\\', '/', $full))); + + return 0; + } +} diff --git a/framework/Console/Commands/SettingsImportCommand.php b/framework/Console/Commands/SettingsImportCommand.php new file mode 100644 index 0000000..e01f25e --- /dev/null +++ b/framework/Console/Commands/SettingsImportCommand.php @@ -0,0 +1,157 @@ + [--force]'; + } + + public function run(): int + { + $path = trim($this->arg(0)); + + if ($path === '') { + $this->fail('Укажите файл: php bin/proton settings:import var/export/settings.json'); + + return 1; + } + + $full = str_starts_with($path, '/') || preg_match('/^[A-Za-z]:/', $path) === 1 + ? $path + : APP_ROOT . '/' . $path; + + if (!is_file($full)) { + $this->fail('Файл не найден: ' . $path); + + return 1; + } + + $data = json_decode((string) file_get_contents($full), true); + + if (!is_array($data)) { + $this->fail('Не разобрал JSON: ' . $path); + + return 1; + } + + /** @var array $settings */ + $settings = (array) ($data['settings'] ?? []); + /** @var array> $roles */ + $roles = (array) ($data['roles'] ?? []); + + $this->line('В файле: настроек — ' . count($settings) . ', ролей — ' . count($roles)); + + if (!$this->confirm('Применить на этой базе?')) { + $this->line('Отменено'); + + return 1; + } + + $appliedSettings = 0; + $unknownSettings = []; + + foreach ($settings as $key => $value) { + $key = (string) $key; + + if (!Settings::known($key)) { + $unknownSettings[] = $key; + + continue; + } + + Settings::put($key, $value); + $appliedSettings++; + } + + $createdRoles = 0; + $updatedRoles = 0; + $skippedRoles = []; + + foreach ($roles as $row) { + $name = trim((string) ($row['name'] ?? '')); + + if ($name === '') { + continue; + } + + $description = (string) ($row['description'] ?? ''); + $permissions = Permission::filter((array) ($row['permissions'] ?? [])); + + /** @var Role|null $role */ + $role = Role::query()->where('name', $name)->first(); + + if ($role === null) { + Role::create([ + 'name' => $name, + 'description' => $description, + 'permissions' => $permissions, + 'is_system' => 0, + ]); + + $createdRoles++; + + continue; + } + + if ($role->isSystem()) { + $skippedRoles[] = $name; + + continue; + } + + $role->forceFill(['description' => $description, 'permissions' => $permissions])->save(); + + $updatedRoles++; + } + + Audit::action( + 'settings', + 0, + 'импорт из файла: настроек — ' . $appliedSettings . ', ролей заведено — ' . $createdRoles . ', обновлено — ' . $updatedRoles + ); + + $this->ok('Настроек применено: ' . $appliedSettings . ', ролей заведено: ' . $createdRoles . ', обновлено: ' . $updatedRoles); + + if ($unknownSettings !== []) { + $this->line(' Неизвестные настройки пропущены: ' . implode(', ', $unknownSettings)); + } + + if ($skippedRoles !== []) { + $this->line(' Встроенную роль не трогаем: ' . implode(', ', $skippedRoles)); + } + + return 0; + } +} diff --git a/tests/SettingsExportImportTest.php b/tests/SettingsExportImportTest.php new file mode 100644 index 0000000..a23b445 --- /dev/null +++ b/tests/SettingsExportImportTest.php @@ -0,0 +1,163 @@ +} + */ +function runSettingsCommand(object $command, array $args, array $options): array +{ + $lines = []; + + $status = $command->withInput($args, $options, static function (string $line) use (&$lines): void { + $lines[] = trim($line); + })->run(); + + return ['status' => $status, 'lines' => $lines]; +} + +test('settings:export: секрет пропускается, встроенная роль — тоже', function (): void { + withOwnDatabase(static function (): void { + Settings::reset(); + Settings::put('ui.per_page', '77'); + + $path = APP_ROOT . '/var/export/test-export.json'; + + $result = runSettingsCommand(new SettingsExportCommand(), [], ['out' => 'var/export/test-export.json']); + + try { + assertSame(0, $result['status']); + assertTrue(is_file($path)); + + $data = json_decode((string) file_get_contents($path), true); + + assertSame(77, $data['settings']['ui.per_page'] ?? null); + + // Встроенная роль администратора в выгрузку не попадает + $names = array_column($data['roles'], 'name'); + + assertFalse(in_array('Администратор', $names, true)); + } finally { + @unlink($path); + Settings::forget('ui.per_page'); + Settings::reset(); + } + }); +}); + +test('settings:import: без подтверждения ничего не трогает', function (): void { + withOwnDatabase(static function (): void { + Settings::reset(); + + $path = APP_ROOT . '/var/export/test-import-noforce.json'; + + file_put_contents($path, json_encode([ + 'settings' => ['ui.per_page' => 99], + 'roles' => [], + ])); + + try { + $result = runSettingsCommand(new SettingsImportCommand(), [$path], []); + + assertSame(1, $result['status'], 'без --force и без TTY подтверждения не будет'); + assertFalse(Settings::overridden('ui.per_page'), 'настройка не применилась'); + } finally { + @unlink($path); + Settings::reset(); + } + }); +}); + +test('settings:import: применяет настройки, заводит и правит роли, не трогает чужого', function (): void { + withOwnDatabase(static function (): void { + Settings::reset(); + + /** @var Role $existing */ + $existing = Role::create([ + 'name' => 'Уже была', + 'description' => 'старое описание', + 'permissions' => ['notes.view'], + ]); + + $path = APP_ROOT . '/var/export/test-import.json'; + + file_put_contents($path, json_encode([ + 'settings' => ['ui.per_page' => 55, 'нет.такой' => 'x'], + 'roles' => [ + ['name' => 'Уже была', 'description' => 'новое описание', 'permissions' => ['notes.view', 'notes.manage']], + ['name' => 'Новая из импорта', 'description' => 'создана импортом', 'permissions' => ['notes.view']], + ], + ], JSON_UNESCAPED_UNICODE)); + + try { + $result = runSettingsCommand(new SettingsImportCommand(), [$path], ['force' => '1']); + + assertSame(0, $result['status']); + assertSame(55, (int) Settings::value('ui.per_page')); + + $updated = Role::find($existing->id()); + + assertSame('новое описание', (string) $updated->description); + assertSame(['notes.view', 'notes.manage'], $updated->permissions()); + + /** @var Role $created */ + $created = assertNotNull(Role::query()->where('name', 'Новая из импорта')->first()); + + assertSame('создана импортом', (string) $created->description); + + $unknown = array_filter($result['lines'], static fn (string $line): bool => str_contains($line, 'нет.такой')); + + assertTrue($unknown !== [], 'неизвестная настройка отмечена в выводе'); + + $created->forceDelete(); + } finally { + @unlink($path); + $existing->forceDelete(); + Settings::forget('ui.per_page'); + Settings::reset(); + } + }); +}); + +test('settings:import: встроенную роль администратора не трогает', function (): void { + withOwnDatabase(static function (): void { + Settings::reset(); + + /** @var Role $admin */ + $admin = Role::admin(); + $before = $admin->permissions(); + + $path = APP_ROOT . '/var/export/test-import-admin.json'; + + file_put_contents($path, json_encode([ + 'settings' => [], + 'roles' => [ + ['name' => (string) $admin->name, 'description' => 'подменили бы', 'permissions' => ['notes.view']], + ], + ], JSON_UNESCAPED_UNICODE)); + + try { + $result = runSettingsCommand(new SettingsImportCommand(), [$path], ['force' => '1']); + + assertSame(0, $result['status']); + + $stillAdmin = Role::find($admin->id()); + + assertSame($before, $stillAdmin->permissions(), 'права администратора всегда из кода'); + } finally { + @unlink($path); + Settings::reset(); + } + }); +});