|
4 | 4 |
|
5 | 5 | use App\Http\Resources\PoliciesCollection; |
6 | 6 | use App\Policy; |
7 | | -use App\PolicyAcceptance; |
8 | 7 | use Carbon\CarbonImmutable; |
| 8 | +use Illuminate\Database\Query\Builder; |
9 | 9 | use Illuminate\Http\Request; |
10 | 10 |
|
11 | 11 | class PoliciesController extends Controller { |
12 | 12 | public function getCurrentPolicies(): PoliciesCollection { |
13 | 13 | $now = CarbonImmutable::now(); |
14 | 14 |
|
15 | | - // This works based on the assumption that the latest policy has the highest id given that id is AUTO_INCREMENT |
16 | | - $latestPolicyIds = Policy::where('active_from', '<', $now) |
17 | | - ->selectRaw('MAX(id) as id') |
18 | | - ->groupBy('policy_type') |
19 | | - ->pluck('id'); |
20 | | - |
21 | | - $currentPolicies = Policy::whereIn('id', $latestPolicyIds)->get(); |
| 15 | + $currentPolicies = Policy::whereIn('id', $this->activePolicyIdsQuery($now))->get(); |
22 | 16 |
|
23 | 17 | return new PoliciesCollection($currentPolicies); |
24 | 18 | } |
25 | 19 |
|
26 | 20 | public function getMissingPolicies(Request $request): PoliciesCollection { |
27 | 21 | $now = CarbonImmutable::now(); |
28 | 22 |
|
29 | | - $activePolicyIds = Policy::where('active_from', '<=', $now) |
30 | | - ->selectRaw('MAX(id) as id') |
31 | | - ->groupBy('policy_type') |
32 | | - ->pluck('id'); |
33 | | - |
34 | | - $acceptedPolicyIds = PolicyAcceptance::where('user_id', $request->user()->id) |
35 | | - ->whereIn('policy_id', $activePolicyIds) |
36 | | - ->pluck('policy_id'); |
37 | | - |
38 | | - $missingPolicies = Policy::whereIn('id', $activePolicyIds) |
39 | | - ->whereNotIn('id', $acceptedPolicyIds) |
| 23 | + $missingPolicies = Policy::whereIn('id', $this->activePolicyIdsQuery($now)) |
| 24 | + ->whereNotExists(function (Builder $query) use ($request): void { |
| 25 | + $query->selectRaw('1') |
| 26 | + ->from('policy_acceptances') |
| 27 | + ->whereColumn('policy_acceptances.policy_id', 'policies.id') |
| 28 | + ->where('policy_acceptances.user_id', $request->user()->id); |
| 29 | + }) |
40 | 30 | ->get(); |
41 | 31 |
|
42 | 32 | return new PoliciesCollection($missingPolicies); |
43 | 33 | } |
| 34 | + |
| 35 | + private function activePolicyIdsQuery(CarbonImmutable $now): Builder { |
| 36 | + return Policy::query() |
| 37 | + ->selectRaw('MAX(id) as id') |
| 38 | + ->where('active_from', '<=', $now) |
| 39 | + ->groupBy('policy_type') |
| 40 | + ->toBase(); |
| 41 | + } |
44 | 42 | } |
0 commit comments