Skip to content

Commit 831fb67

Browse files
committed
Added controller method that returns only current policies not accepted by user
Bug: T432337
1 parent 55af326 commit 831fb67

1 file changed

Lines changed: 17 additions & 19 deletions

File tree

app/Http/Controllers/PoliciesController.php

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,41 +4,39 @@
44

55
use App\Http\Resources\PoliciesCollection;
66
use App\Policy;
7-
use App\PolicyAcceptance;
87
use Carbon\CarbonImmutable;
8+
use Illuminate\Database\Query\Builder;
99
use Illuminate\Http\Request;
1010

1111
class PoliciesController extends Controller {
1212
public function getCurrentPolicies(): PoliciesCollection {
1313
$now = CarbonImmutable::now();
1414

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

2317
return new PoliciesCollection($currentPolicies);
2418
}
2519

2620
public function getMissingPolicies(Request $request): PoliciesCollection {
2721
$now = CarbonImmutable::now();
2822

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+
})
4030
->get();
4131

4232
return new PoliciesCollection($missingPolicies);
4333
}
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+
}
4442
}

0 commit comments

Comments
 (0)