PlanService.php 979 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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 = User::where('plan_id', $this->plan->plan_id)->count();
  17. return ($this->plan->capacity_limit - $count) > 0;
  18. }
  19. public static function countActiveUsers()
  20. {
  21. return User::select(
  22. DB::raw("plan_id"),
  23. DB::raw("count(*) as count")
  24. )
  25. ->where('plan_id', '!=', NULL)
  26. ->where(function ($query) {
  27. $query->where('expired_at', '>=', time())
  28. ->orWhere('expired_at', NULL);
  29. })
  30. ->groupBy("plan_id")
  31. ->get()
  32. ->keyBy('plan_id');
  33. }
  34. }