Faza 2: multi-tenancy + Filament dual panels + seed PSauto

Schema centrală:
- companies (slug unique, status, plan_id, settings JSON, trial/active dates)
- super_admins (operator platform)
- plans (free/basic/pro)

Schema tenant (toate cu company_id NOT NULL):
- users (UNIQUE company_id+email)
- clients
- vehicles

Tenancy core:
- App\Tenancy\TenantManager singleton
- App\Models\Concerns\BelongsToTenant trait + TenantScope
- ResolveTenant middleware (slug → Company, 404 pentru rezervate/missing)
- CheckTenantStatus middleware (suspended/expired/archived)
- Fail-safe: TenantScope returns 0 rows când tenant nu e rezolvat

Auth guards:
- 'central' guard cu super_admins provider (panou platform)
- 'web' guard cu users provider (per-tenant)

Filament panels:
- CentralPanelProvider la service.mir.md/admin
- TenantPanelProvider la <slug>.service.mir.md/app
- CompanyResource (central): CRUD companii cu status badge + filtre
- ClientResource (tenant): CRUD clienți cu status, sursă, sold
- VehicleResource (tenant): CRUD mașini cu marcă/model/VIN

Seed:
- 3 plans (free/basic/pro)
- super-admin: vasyka.moraru@gmail.com / admin123
- demo company 'psauto' cu admin user admin@psauto.md / admin123
- 3 clienți + 3 mașini preluate din AutoCRM.html

Bootstrap:
- TrustProxies (Cloudflare→Traefik HTTPS detection)
- forceScheme/forceRootUrl când APP_URL e HTTPS
- Helper global tenant() în app/helpers.php (autoload via composer)
- RUN_SEED env var în entrypoint pentru db:seed condiționat
This commit is contained in:
2026-05-05 21:29:52 +00:00
parent 125566cb81
commit 4b1635d045
48 changed files with 1510 additions and 386 deletions
-45
View File
@@ -1,45 +0,0 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
@@ -1,49 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};
@@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTenantsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('tenants', function (Blueprint $table) {
$table->string('id')->primary();
// your custom columns may go here
$table->timestamps();
$table->json('data')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('tenants');
}
}
@@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDomainsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('domains', function (Blueprint $table) {
$table->increments('id');
$table->string('domain', 255)->unique();
$table->string('tenant_id');
$table->timestamps();
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('domains');
}
}
@@ -1,39 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTenantUserImpersonationTokensTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::create('tenant_user_impersonation_tokens', function (Blueprint $table) {
$table->string('token', 128)->primary();
$table->string('tenant_id');
$table->string('user_id');
$table->string('auth_guard');
$table->string('redirect_url');
$table->timestamp('created_at');
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('tenant_user_impersonation_tokens');
}
}
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('plans', function (Blueprint $t) {
$t->id();
$t->string('slug')->unique();
$t->string('name');
$t->decimal('price_monthly', 10, 2)->default(0);
$t->decimal('price_yearly', 10, 2)->default(0);
$t->string('currency', 3)->default('MDL');
$t->json('features')->nullable(); // ['kanban', 'reports', 'ai', ...]
$t->json('limits')->nullable(); // ['max_users' => 5, 'max_vehicles' => 100, ...]
$t->boolean('is_active')->default(true);
$t->boolean('is_public')->default(true);
$t->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('plans');
}
};
@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('companies', function (Blueprint $t) {
$t->id();
$t->string('slug')->unique(); // psauto, autoplus, ...
$t->string('name'); // PSauto SRL
$t->string('display_name')->nullable(); // shown in UI
$t->string('city')->nullable();
$t->string('phone')->nullable();
$t->string('email')->nullable();
$t->string('contact_name')->nullable();
$t->enum('status', ['trial', 'active', 'expired', 'suspended', 'archived'])
->default('trial');
$t->foreignId('plan_id')->nullable()->constrained()->nullOnDelete();
$t->timestamp('trial_ends_at')->nullable();
$t->timestamp('active_until')->nullable();
// White-label settings (preluat din cfg-ul prototipului AutoCRM.html).
$t->json('settings')->nullable();
// Compatibilitate cu stancl/tenancy v3 — stochează metadate libere.
$t->json('data')->nullable();
$t->timestamps();
$t->softDeletes();
$t->index(['status']);
});
}
public function down(): void
{
Schema::dropIfExists('companies');
}
};
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('super_admins', function (Blueprint $t) {
$t->id();
$t->string('name');
$t->string('email')->unique();
$t->timestamp('email_verified_at')->nullable();
$t->string('password');
$t->boolean('is_active')->default(true);
$t->timestamp('last_login_at')->nullable();
$t->rememberToken();
$t->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('super_admins');
}
};
@@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $t) {
$t->id();
$t->foreignId('company_id')->constrained('companies')->cascadeOnDelete();
$t->string('name');
$t->string('email');
$t->string('phone')->nullable();
$t->string('avatar_url')->nullable();
$t->string('role')->default('user'); // admin / manager / receptionist / mechanic / user
$t->string('status')->default('active'); // active / inactive / blocked
$t->string('locale', 5)->default('ro');
$t->timestamp('email_verified_at')->nullable();
$t->string('password');
$t->timestamp('last_login_at')->nullable();
$t->rememberToken();
$t->timestamps();
$t->softDeletes();
// CRITIC: same email can exist across tenants but unique within tenant.
$t->unique(['company_id', 'email']);
$t->index(['company_id', 'role']);
$t->index(['company_id', 'status']);
});
Schema::create('password_reset_tokens', function (Blueprint $t) {
$t->string('email')->primary();
$t->string('token');
$t->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $t) {
$t->string('id')->primary();
$t->foreignId('user_id')->nullable()->index();
$t->string('ip_address', 45)->nullable();
$t->text('user_agent')->nullable();
$t->longText('payload');
$t->integer('last_activity')->index();
});
}
public function down(): void
{
Schema::dropIfExists('sessions');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('users');
}
};
@@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('clients', function (Blueprint $t) {
$t->id();
$t->foreignId('company_id')->constrained()->cascadeOnDelete();
$t->string('type')->default('individual'); // individual / company
$t->string('name');
$t->string('company_name')->nullable(); // for type=company
$t->string('phone');
$t->string('phone_alt')->nullable();
$t->string('email')->nullable();
$t->string('telegram')->nullable();
$t->string('whatsapp')->nullable();
$t->string('viber')->nullable();
$t->string('source')->nullable(); // call / site / telegram / google / ...
$t->string('marketing_channel')->nullable();
$t->string('status')->default('active'); // new / active / vip / debtor / blocked / lost
$t->decimal('balance', 12, 2)->default(0); // negative = customer owes us
$t->decimal('discount_pct', 5, 2)->default(0);
$t->text('notes')->nullable();
$t->foreignId('assigned_to')->nullable()->constrained('users')->nullOnDelete();
$t->timestamp('last_contact_at')->nullable();
$t->timestamps();
$t->softDeletes();
$t->index(['company_id', 'status']);
$t->index(['company_id', 'phone']);
$t->index(['company_id', 'created_at']);
});
}
public function down(): void
{
Schema::dropIfExists('clients');
}
};
@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('vehicles', function (Blueprint $t) {
$t->id();
$t->foreignId('company_id')->constrained()->cascadeOnDelete();
$t->foreignId('client_id')->constrained()->cascadeOnDelete();
$t->string('make'); // BMW, Audi, ...
$t->string('model'); // X5, A4, ...
$t->smallInteger('year')->nullable();
$t->string('vin', 32)->nullable();
$t->string('plate', 16)->nullable();
$t->string('engine')->nullable(); // 3.0i / 2.0 TDI
$t->string('gearbox')->nullable();
$t->string('fuel')->nullable();
$t->unsignedInteger('mileage')->default(0);
$t->string('color')->nullable();
$t->text('notes')->nullable();
$t->timestamps();
$t->softDeletes();
$t->index(['company_id', 'client_id']);
$t->index(['company_id', 'plate']);
});
}
public function down(): void
{
Schema::dropIfExists('vehicles');
}
};
+126 -12
View File
@@ -2,24 +2,138 @@
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Central\SuperAdmin;
use App\Models\Tenant\Client;
use App\Models\Tenant\User;
use App\Models\Tenant\Vehicle;
use App\Tenancy\TenantManager;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
// ─── Plans ────────────────────────────────────────────────
$free = Plan::firstOrCreate(['slug' => 'free'], [
'name' => 'Free',
'price_monthly' => 0,
'currency' => 'MDL',
'features' => ['core'],
'limits' => ['max_users' => 2, 'max_vehicles' => 50],
]);
Plan::firstOrCreate(['slug' => 'basic'], [
'name' => 'Basic',
'price_monthly' => 299,
'currency' => 'MDL',
'features' => ['core', 'workorders', 'kanban'],
'limits' => ['max_users' => 5, 'max_vehicles' => 500],
]);
Plan::firstOrCreate(['slug' => 'pro'], [
'name' => 'Pro',
'price_monthly' => 599,
'currency' => 'MDL',
'features' => ['core', 'workorders', 'kanban', 'reports', 'ai', 'api'],
'limits' => ['max_users' => -1, 'max_vehicles' => -1],
]);
// ─── Super-admin (operator platformă) ─────────────────────
SuperAdmin::firstOrCreate(['email' => 'vasyka.moraru@gmail.com'], [
'name' => 'Vasyka',
'password' => Hash::make('admin123'),
'is_active' => true,
]);
// ─── PSauto demo company ──────────────────────────────────
$psauto = Company::firstOrCreate(['slug' => 'psauto'], [
'name' => 'PSauto SRL',
'display_name' => 'PSauto',
'city' => 'Chișinău',
'phone' => '+373 22 123 456',
'email' => 'contact@psauto.md',
'contact_name' => 'Manager PSauto',
'status' => 'active',
'plan_id' => $free->id,
'active_until' => now()->addYear(),
'settings' => [
'currency' => 'MDL',
'language' => 'ro',
'theme_color' => '#3B82F6',
'labor_rate' => 400,
'posts' => ['Post 1', 'Post 2', 'Post 3'],
],
]);
// Activate tenant context for the seeded data so global scopes auto-fill company_id.
app(TenantManager::class)->setCurrent($psauto);
// ─── Admin user pentru PSauto ─────────────────────────────
User::firstOrCreate(
['company_id' => $psauto->id, 'email' => 'admin@psauto.md'],
[
'name' => 'Administrator PSauto',
'password' => Hash::make('admin123'),
'role' => 'admin',
'status' => 'active',
'phone' => '+373 22 123 456',
'locale' => 'ro',
'email_verified_at' => now(),
]
);
// ─── Clienți demo (din AutoCRM.html) ──────────────────────
$c1 = Client::firstOrCreate(
['company_id' => $psauto->id, 'phone' => '+373 69 100001'],
[
'type' => 'individual',
'name' => 'Ion Popescu',
'email' => 'ion@mail.com',
'status' => 'vip',
'source' => 'recommend',
]
);
$c2 = Client::firstOrCreate(
['company_id' => $psauto->id, 'phone' => '+373 79 200002'],
[
'type' => 'individual',
'name' => 'Maria Dumitru',
'status' => 'active',
'discount_pct' => 5,
'source' => 'site',
]
);
$c3 = Client::firstOrCreate(
['company_id' => $psauto->id, 'phone' => '+373 60 300003'],
[
'type' => 'individual',
'name' => 'Andrei Lupu',
'status' => 'active',
'discount_pct' => 10,
'notes' => 'Doar piese originale',
'source' => 'instagram',
]
);
// ─── Mașini demo ──────────────────────────────────────────
Vehicle::firstOrCreate(
['company_id' => $psauto->id, 'client_id' => $c1->id, 'make' => 'BMW', 'model' => 'X5'],
['year' => 2020, 'plate' => 'CIU 001', 'engine' => '3.0i', 'gearbox' => 'Automat 8AT', 'fuel' => 'Benzină', 'mileage' => 85000, 'color' => 'Alb']
);
Vehicle::firstOrCreate(
['company_id' => $psauto->id, 'client_id' => $c2->id, 'make' => 'Audi', 'model' => 'A4'],
['year' => 2019, 'plate' => 'CIU 002', 'engine' => '2.0 TDI', 'gearbox' => 'DSG7', 'fuel' => 'Diesel', 'mileage' => 45000, 'color' => 'Negru']
);
Vehicle::firstOrCreate(
['company_id' => $psauto->id, 'client_id' => $c3->id, 'make' => 'Porsche', 'model' => 'Cayenne'],
['year' => 2021, 'plate' => 'CIU 003', 'engine' => '3.0 TDI', 'gearbox' => 'Tiptronic', 'fuel' => 'Diesel', 'mileage' => 22000, 'color' => 'Gri']
);
app(TenantManager::class)->clear();
}
}