File: /home/posscale/public_html/printmanager/app/Console/Commands/SyncTenantUserRolesFromUserType.php
<?php
namespace App\Console\Commands;
use App\Models\Tenant as TenantModel;
use App\Models\User;
use Illuminate\Console\Command;
class SyncTenantUserRolesFromUserType extends Command
{
protected $signature = 'sync:tenant-user-roles';
protected $description = 'Assign Spatie roles (admin/manager/user) to tenant users based on the existing user_type field.';
public function handle(): int
{
$this->info('Syncing tenant users to Spatie roles based on user_type...');
TenantModel::all()->each(function (TenantModel $tenant) {
$this->info("Processing tenant: {$tenant->id}");
tenancy()->initialize($tenant);
User::query()->chunkById(100, function ($users) {
foreach ($users as $user) {
$roleName = match ((int) $user->user_type) {
1, 2 => 'admin', // main customer or super-admin bridge => full admin in tenant
default => 'user',
};
$user->syncRoles([$roleName]);
}
});
tenancy()->end();
});
$this->info('Sync complete.');
return self::SUCCESS;
}
}