v2board/app/Services/PlanService.php

42 lines
1006 B
PHP
Raw Normal View History

2022-06-30 03:18:30 +08:00
<?php
namespace App\Services;
use App\Models\Plan;
2022-07-08 02:36:33 +08:00
use App\Models\User;
2022-07-19 03:11:36 +08:00
use Illuminate\Support\Facades\DB;
2022-06-30 03:18:30 +08:00
class PlanService
{
public $plan;
public function __construct(int $planId)
{
$this->plan = Plan::lockForUpdate()->find($planId);
}
2022-07-08 02:36:33 +08:00
public function haveCapacity(): bool
2022-06-30 03:18:30 +08:00
{
2022-07-08 12:07:36 +08:00
if ($this->plan->capacity_limit === NULL) return true;
2022-08-02 16:37:42 +08:00
$count = self::countActiveUsers();
2022-08-03 14:52:42 +08:00
$count = $count[$this->plan->id]['count'] ?? 0;
2022-07-28 15:05:48 +08:00
return ($this->plan->capacity_limit - $count) > 0;
2022-06-30 03:18:30 +08:00
}
2022-07-19 03:11:36 +08:00
public static function countActiveUsers()
{
return User::select(
DB::raw("plan_id"),
DB::raw("count(*) as count")
)
->where('plan_id', '!=', NULL)
->where(function ($query) {
$query->where('expired_at', '>=', time())
->orWhere('expired_at', NULL);
})
->groupBy("plan_id")
->get()
->keyBy('plan_id');
}
2022-06-30 03:18:30 +08:00
}