Files
HRM-System/app/Http/Middleware/EnforceEmployeeLimit.php

41 lines
1.4 KiB
PHP

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use App\Models\TenantEntitlement;
use App\Models\User;
use Symfony\Component\HttpFoundation\Response;
class EnforceEmployeeLimit
{
public function handle(Request $request, Closure $next): Response
{
if (function_exists('tenant') && tenant()) {
$tenantId = tenant('id');
$entitlement = TenantEntitlement::where('tenant_id', $tenantId)->first();
if ($entitlement && $entitlement->max_employees > 0) {
// Count current active employees in this tenant database
$currentCount = User::whereNotIn('type', ['superadmin', 'company'])->count();
if ($currentCount >= $entitlement->max_employees) {
if ($request->wantsJson()) {
return response()->json([
'success' => false,
'message' => "Employee limit reached ({$entitlement->max_employees} staff max allowed under your plan). Cannot add more employees.",
], 403);
}
return redirect()->back()->withErrors([
'employee_limit' => "Employee limit reached ({$entitlement->max_employees} staff max allowed under your plan). Cannot add more employees.",
]);
}
}
}
return $next($request);
}
}