| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- <?php
-
- namespace App\Billing;
-
- use App\Enums\GenerationStatus;
- use App\Enums\GenerationType;
- use App\Models\StoreGeneration;
- use App\Models\User;
-
- /**
- * How much AI a user has used, and how much their plan allows.
- *
- * Failed jobs never count. The first design of a store is free; only redesigns count as regenerations.
- */
- class UsageLimits
- {
- /**
- * @return array{plan: string, plan_name: string, period: string, regenerations: array{used: int, limit: int}, edits: array{used: int, limit: int}}
- */
- public function for(User $user): array
- {
- $key = array_key_exists($user->plan, config('plans.plans')) ? $user->plan : config('plans.default');
- $plan = config("plans.plans.$key");
-
- return [
- 'plan' => $key,
- 'plan_name' => $plan['name'],
- 'period' => $plan['period'],
- 'regenerations' => [
- 'used' => $this->used($user, GenerationType::Generate, $plan['period']),
- 'limit' => (int) $plan['regenerations'],
- ],
- 'edits' => [
- 'used' => $this->used($user, GenerationType::Edit, $plan['period']),
- 'limit' => (int) $plan['edits'],
- ],
- ];
- }
-
- public function canRegenerate(User $user): bool
- {
- $usage = $this->for($user)['regenerations'];
-
- return $usage['used'] < $usage['limit'];
- }
-
- public function canEdit(User $user): bool
- {
- $usage = $this->for($user)['edits'];
-
- 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();
- }
- }
|