PlanService.php 1006 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Plan;
  4. use App\Models\User;
  5. use Illuminate\Support\Facades\DB;
  6. class PlanService
  7. {
  8. public $plan;
  9. public function __construct(int $planId)
  10. {
  11. $this->plan = Plan::lockForUpdate()->find($planId);
  12. }
  13. public function haveCapacity(): bool
  14. {
  15. if ($this->plan->capacity_limit === NULL) return true;
  16. $count = self::countActiveUsers();
  17. $count = $count[$this->plan->id]['count'] ?? 0;
  18. return ($this->plan->capacity_limit - $count) > 0;
  19. }
  20. public static function countActiveUsers()
  21. {
  22. return User::select(
  23. DB::raw("plan_id"),
  24. DB::raw("count(*) as count")
  25. )
  26. ->where('plan_id', '!=', NULL)
  27. ->where(function ($query) {
  28. $query->where('expired_at', '>=', time())
  29. ->orWhere('expired_at', NULL);
  30. })
  31. ->groupBy("plan_id")
  32. ->get()
  33. ->keyBy('plan_id');
  34. }
  35. }