| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
-
- namespace App\Billing;
-
- use App\Enums\GenerationStatus;
- use App\Enums\GenerationType;
- use App\Models\Plan;
- use App\Models\StoreGeneration;
- use App\Models\User;
-
- /**
- * What a user's plan allows, and how much of it they have used.
- *
- * - Failed AI jobs never count.
- * - The first design of a store is free; only redesigns count as regenerations.
- * - With no plan (trial over, no subscription) every limit is zero.
- */
- class UsageLimits
- {
- /**
- * @return array{active: bool, plan: string|null, plan_name: string, period: string, on_trial: bool, trial_ends_at: string|null, stores: array{used: int, limit: int}, regenerations: array{used: int, limit: int}, edits: array{used: int, limit: int}}
- */
- public function for(User $user): array
- {
- $plan = $user->currentPlan();
- $period = $plan !== null ? $plan->period : 'month';
- $paying = $plan?->isPaid() ?? false;
-
- return [
- 'active' => $plan !== null,
- 'plan' => $plan?->key,
- 'plan_name' => $plan !== null ? $plan->name : 'No plan',
- 'period' => $period,
- 'on_trial' => $plan !== null && ! $paying,
- 'trial_ends_at' => $user->trial_ends_at?->toIso8601String(),
- 'stores' => [
- 'used' => $user->stores()->count(),
- 'limit' => $plan !== null ? $plan->stores : 0,
- ],
- 'regenerations' => [
- 'used' => $this->used($user, GenerationType::Generate, $period),
- 'limit' => $plan !== null ? $plan->regenerations : 0,
- ],
- 'edits' => [
- 'used' => $this->used($user, GenerationType::Edit, $period),
- 'limit' => $plan !== null ? $plan->edits : 0,
- ],
- ];
- }
-
- /**
- * Whether the user has a plan at all: a paid one, or a free trial that has not ended.
- */
- public function hasPlan(User $user): bool
- {
- return $user->currentPlan() instanceof Plan;
- }
-
- public function canCreateStore(User $user): bool
- {
- return $this->hasRoom($this->for($user)['stores']);
- }
-
- public function canRegenerate(User $user): bool
- {
- return $this->hasRoom($this->for($user)['regenerations']);
- }
-
- public function canEdit(User $user): bool
- {
- return $this->hasRoom($this->for($user)['edits']);
- }
-
- /**
- * @param array{used: int, limit: int} $usage
- */
- private function hasRoom(array $usage): bool
- {
- return $usage['used'] < $usage['limit'];
- }
-
- private function used(User $user, GenerationType $type, string $period): int
- {
- return StoreGeneration::query()
- ->where('user_id', $user->id)
- ->where('type', $type)
- ->where('status', '!=', GenerationStatus::Failed)
- ->when($type === GenerationType::Generate, fn ($query) => $query->where('is_regeneration', true))
- ->when($period === 'month', fn ($query) => $query->where('created_at', '>=', now()->startOfMonth()))
- ->count();
- }
- }
|