New_Micro_Learning/backend/app/Modules/Subscriptions/Http/SubscriptionController.php

47 خطوط
2.2 KiB
PHP

<?php
namespace App\Modules\Subscriptions\Http;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Modules\Identity\Application\RolePermissions;
use App\Modules\Identity\Domain\Enums\AccountStatus;
use App\Modules\Identity\Domain\Enums\Permission;
use App\Modules\Identity\Domain\UserInvitation;
use App\Modules\Subscriptions\Domain\Subscription;
use App\Modules\Tenancy\Application\TenantContext;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class SubscriptionController extends Controller
{
public function __construct(private readonly TenantContext $tenant, private readonly RolePermissions $permissions) {}
public function current(Request $request): JsonResponse
{
abort_unless($this->permissions->allows($request->user(), Permission::SubscriptionView), 403);
$subscription = Subscription::query()
->where('organization_id', $this->tenant->id())
->where('status', 'active')
->where('starts_at', '<=', now())
->where(fn ($query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now()))
->latest('starts_at')
->first();
$seatUsed = User::query()->where('organization_id', $this->tenant->id())->whereIn('status', [AccountStatus::Active, AccountStatus::Invited])->count()
+ UserInvitation::query()->where('organization_id', $this->tenant->id())->whereNull('accepted_at')->whereNull('revoked_at')->where('expires_at', '>', now())->count();
return response()->json(['data' => $subscription ? [
'id' => $subscription->getKey(), 'planKey' => $subscription->plan_key,
'status' => $subscription->status, 'startsAt' => $subscription->starts_at->toISOString(),
'expiresAt' => $subscription->expires_at?->toISOString(), 'seatLimit' => $subscription->seat_limit,
'storageQuotaBytes' => $subscription->storage_quota_bytes,
'storageUsedBytes' => $subscription->storage_used_bytes,
'aiCreditQuota' => $subscription->ai_credit_quota,
'aiCreditsUsed' => $subscription->ai_credits_used,
'seatUsed' => $seatUsed,
'enabledFeatures' => $subscription->enabled_features ?? [],
] : null]);
}
}