add superadmin dashboard. subscriptions
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
/**
|
||||
* Миграция для таблицы сессий CodeIgniter 4
|
||||
*
|
||||
* Эта таблица используется для хранения сессий в базе данных,
|
||||
* что позволяет управлять активными сессиями пользователей.
|
||||
*/
|
||||
class CreateCiSessionsTable extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$this->forge->addField([
|
||||
'id' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 128,
|
||||
],
|
||||
'ip_address' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 45,
|
||||
],
|
||||
'timestamp' => [
|
||||
'type' => 'INT',
|
||||
'unsigned' => true,
|
||||
'default' => 0,
|
||||
],
|
||||
'data' => [
|
||||
'type' => 'BLOB',
|
||||
'null' => true,
|
||||
],
|
||||
]);
|
||||
$this->forge->addKey('id', true);
|
||||
$this->forge->addKey('timestamp');
|
||||
$this->forge->createTable('ci_sessions');
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$this->forge->dropTable('ci_sessions');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class AddPasswordResetFieldsToUsers extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$fields = [
|
||||
'reset_token' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 255,
|
||||
'null' => true,
|
||||
'after' => 'verified_at',
|
||||
],
|
||||
'reset_expires_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
'after' => 'reset_token',
|
||||
],
|
||||
];
|
||||
|
||||
$this->forge->addColumn('users', $fields);
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$this->forge->dropColumn('users', ['reset_token', 'reset_expires_at']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class AddSystemRoleToUsers extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$fields = [
|
||||
'system_role' => [
|
||||
'type' => 'ENUM',
|
||||
'constraint' => ['user', 'admin', 'superadmin'],
|
||||
'default' => 'user',
|
||||
'after' => 'password',
|
||||
],
|
||||
];
|
||||
|
||||
$this->forge->addColumn('users', $fields);
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$this->forge->dropColumn('users', 'system_role');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
/**
|
||||
* Migration для создания таблицы тарифов (plans)
|
||||
*/
|
||||
class AddPlansTable extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$this->forge->addField([
|
||||
'id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'auto_increment' => true,
|
||||
],
|
||||
'name' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 100,
|
||||
'null' => false,
|
||||
],
|
||||
'description' => [
|
||||
'type' => 'TEXT',
|
||||
'null' => true,
|
||||
],
|
||||
'price' => [
|
||||
'type' => 'DECIMAL',
|
||||
'constraint' => '10,2',
|
||||
'default' => 0.00,
|
||||
],
|
||||
'currency' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 3,
|
||||
'default' => 'RUB',
|
||||
],
|
||||
'billing_period' => [
|
||||
'type' => 'ENUM',
|
||||
'constraint' => ['monthly', 'yearly', 'quarterly'],
|
||||
'default' => 'monthly',
|
||||
],
|
||||
'max_users' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'default' => 5,
|
||||
],
|
||||
'max_clients' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'default' => 100,
|
||||
],
|
||||
'max_storage' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'default' => 10,
|
||||
],
|
||||
'features' => [
|
||||
'type' => 'JSON',
|
||||
'null' => true,
|
||||
],
|
||||
'is_active' => [
|
||||
'type' => 'TINYINT',
|
||||
'default' => 1,
|
||||
],
|
||||
'is_default' => [
|
||||
'type' => 'TINYINT',
|
||||
'default' => 0,
|
||||
],
|
||||
'created_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => false,
|
||||
],
|
||||
'updated_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$this->forge->addKey('id', true);
|
||||
$this->forge->addUniqueKey(['name']);
|
||||
$this->forge->createTable('plans');
|
||||
|
||||
// Добавление базовых тарифов по умолчанию
|
||||
$seedData = [
|
||||
[
|
||||
'name' => 'Бесплатный',
|
||||
'description' => 'Базовый тариф для небольших команд',
|
||||
'price' => 0,
|
||||
'currency' => 'RUB',
|
||||
'billing_period' => 'monthly',
|
||||
'max_users' => 3,
|
||||
'max_clients' => 50,
|
||||
'max_storage' => 5,
|
||||
'features' => json_encode([
|
||||
'Базовые модули',
|
||||
'Email поддержка',
|
||||
'Экспорт в CSV',
|
||||
]),
|
||||
'is_active' => 1,
|
||||
'is_default' => 1,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
],
|
||||
[
|
||||
'name' => 'Старт',
|
||||
'description' => 'Тариф для растущих компаний',
|
||||
'price' => 990,
|
||||
'currency' => 'RUB',
|
||||
'billing_period' => 'monthly',
|
||||
'max_users' => 10,
|
||||
'max_clients' => 500,
|
||||
'max_storage' => 50,
|
||||
'features' => json_encode([
|
||||
'Все модули',
|
||||
'Приоритетная поддержка',
|
||||
'Экспорт в PDF и Excel',
|
||||
'API доступ',
|
||||
]),
|
||||
'is_active' => 1,
|
||||
'is_default' => 0,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
],
|
||||
[
|
||||
'name' => 'Бизнес',
|
||||
'description' => 'Полный функционал для крупных компаний',
|
||||
'price' => 4990,
|
||||
'currency' => 'RUB',
|
||||
'billing_period' => 'monthly',
|
||||
'max_users' => 50,
|
||||
'max_clients' => 5000,
|
||||
'max_storage' => 500,
|
||||
'features' => json_encode([
|
||||
'Все модули',
|
||||
'Персональный менеджер',
|
||||
'Экспорт в PDF и Excel',
|
||||
'Полный API доступ',
|
||||
'Интеграции',
|
||||
'Брендинг',
|
||||
]),
|
||||
'is_active' => 1,
|
||||
'is_default' => 0,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
],
|
||||
];
|
||||
|
||||
$this->db->table('plans')->insertBatch($seedData);
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$this->forge->dropTable('plans');
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
/**
|
||||
* Migration для создания таблицы подписок организаций на тарифы
|
||||
* Использует ту же структуру что и organization_subscriptions для модулей
|
||||
*/
|
||||
class CreateOrganizationPlanSubscriptionsTable extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$this->forge->addField([
|
||||
'id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'auto_increment' => true,
|
||||
],
|
||||
'organization_id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
],
|
||||
'plan_id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
],
|
||||
'status' => [
|
||||
'type' => 'ENUM',
|
||||
'constraint' => ['trial', 'active', 'expired', 'cancelled'],
|
||||
'default' => 'trial',
|
||||
],
|
||||
'trial_ends_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'expires_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'created_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'updated_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$this->forge->addKey('id', true);
|
||||
|
||||
// Организация не может иметь две активные подписки на один тариф одновременно
|
||||
$this->forge->addUniqueKey(['organization_id', 'plan_id']);
|
||||
|
||||
$this->forge->addForeignKey('organization_id', 'organizations', 'id', 'CASCADE', 'CASCADE');
|
||||
$this->forge->addForeignKey('plan_id', 'plans', 'id', 'CASCADE', 'CASCADE');
|
||||
|
||||
$this->forge->createTable('organization_plan_subscriptions');
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$this->forge->dropTable('organization_plan_subscriptions');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Seeds;
|
||||
|
||||
use CodeIgniter\Database\Seeder;
|
||||
use App\Models\UserModel;
|
||||
|
||||
/**
|
||||
* Seeder для назначения системных ролей пользователям
|
||||
*
|
||||
* Использование:
|
||||
* php spark db:seed "App\Database\Seeds\SetSystemRoleSeeder" -email=admin@example.com -role=superadmin
|
||||
*
|
||||
* Только email (по умолчанию роль superadmin):
|
||||
* php spark db:seed "App\Database\Seeds\SetSystemRoleSeeder" -email=admin@example.com
|
||||
*/
|
||||
class SetSystemRoleSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Системные роли
|
||||
*/
|
||||
public const ROLE_USER = 'user';
|
||||
public const ROLE_ADMIN = 'admin';
|
||||
public const ROLE_SUPERADMIN = 'superadmin';
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
// Получаем параметры из командной строки
|
||||
$email = $this->parseArg('email');
|
||||
$role = $this->parseArg('role') ?? self::ROLE_SUPERADMIN;
|
||||
|
||||
if (empty($email)) {
|
||||
echo "Ошибка: Не указан email пользователя\n";
|
||||
echo "\n";
|
||||
echo "Использование:\n";
|
||||
echo " php spark db:seed \"App\Database\Seeds\SetSystemRoleSeeder\" -email=admin@example.com -role=superadmin\n";
|
||||
echo "\n";
|
||||
echo "Доступные роли: user, admin, superadmin\n";
|
||||
echo "По умолчанию: superadmin\n";
|
||||
return;
|
||||
}
|
||||
|
||||
$this->assignRole($email, $role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Парсинг аргумента из командной строки
|
||||
*/
|
||||
protected function parseArg(string $name): ?string
|
||||
{
|
||||
global $argv;
|
||||
|
||||
foreach ($argv as $arg) {
|
||||
// Формат: -email=value
|
||||
if (preg_match("/^-{$name}=(.+)$/", $arg, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Назначение роли пользователю по email
|
||||
*/
|
||||
public function assignRole(string $email, string $role): bool
|
||||
{
|
||||
$userModel = new UserModel();
|
||||
|
||||
// Ищем пользователя по email
|
||||
$user = $userModel->where('email', $email)->first();
|
||||
|
||||
if (!$user) {
|
||||
echo "Ошибка: Пользователь с email '{$email}' не найден в базе данных\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Отладка
|
||||
echo "DEBUG: Found user ID = " . $user['id'] . "\n";
|
||||
echo "DEBUG: Current system_role = " . ($user['system_role'] ?? 'NULL') . "\n";
|
||||
|
||||
// Валидируем роль
|
||||
$validRoles = [self::ROLE_USER, self::ROLE_ADMIN, self::ROLE_SUPERADMIN];
|
||||
if (!in_array($role, $validRoles)) {
|
||||
echo "Ошибка: Неизвестная роль '{$role}'. Доступные роли: " . implode(', ', $validRoles) . "\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Используем DB Builder для обновления
|
||||
$db = \Config\Database::connect();
|
||||
$result = $db->table('users')
|
||||
->where('id', $user['id'])
|
||||
->set('system_role', $role)
|
||||
->update();
|
||||
|
||||
if (!$result) {
|
||||
echo "Ошибка обновления\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Проверяем что обновилось
|
||||
$updatedUser = $userModel->find($user['id']);
|
||||
echo "DEBUG: New system_role = " . ($updatedUser['system_role'] ?? 'NULL') . "\n";
|
||||
|
||||
$roleLabels = [
|
||||
self::ROLE_USER => 'Пользователь',
|
||||
self::ROLE_ADMIN => 'Администратор',
|
||||
self::ROLE_SUPERADMIN => 'Суперадмин',
|
||||
];
|
||||
|
||||
$roleLabel = $roleLabels[$role] ?? $role;
|
||||
|
||||
echo "Успех!\n";
|
||||
echo " Email: {$email}\n";
|
||||
echo " User ID: {$user['id']}\n";
|
||||
echo " Назначенная роль: {$roleLabel}\n";
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user