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(); } }