SendExternalCoursesReport   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 48
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 36 5
A __construct() 0 2 1
1
<?php
2
3
namespace App\Listeners;
4
5
use App\Mail\ExternalCourseReport;
6
use App\Models\Partner;
7
use Carbon\Carbon;
8
use Illuminate\Database\Eloquent\Builder;
9
use Illuminate\Support\Facades\Mail;
10
11
class SendExternalCoursesReport
12
{
13
    /**
14
     * Create the event listener.
15
     *
16
     * @return void
17
     */
18
    public function __construct()
19
    {
20
        //
21
    }
22
23
    public function handle()
24
    {
25
        $period_start = Carbon::parse('first day of this month');
26
        $period_end = Carbon::parse('last day of this month');
27
28
        // foreach partner with an alert set for this day of month
29
        foreach (Partner::where('send_report_on', Carbon::now()->day)->get() as $partner) {
30
            // get all courses
31
            $courses = $partner->courses()->whereHas('events', function (Builder $query) use ($period_start, $period_end) {
32
                $query->where('start', '>=', $period_start->toDateString())->where('end', '<=', $period_end->toDateString());
33
            })
34
            ->with('events')->withCount('events')
35
            ->get();
36
37
            if ($courses->count() == 0) {
38
                return;
39
            }
40
41
            $data = [];
42
43
            $partner_balance = 0;
44
            foreach ($courses as $c => $course) {
45
                $data['courses'][$c]['course_name'] = $course->name;
46
                $data['courses'][$c]['hourly_price'] = $course->hourly_price;
47
                $data['courses'][$c]['hours_count'] = 0;
48
                foreach ($course->events->where('start', '>=', $period_start->toDateString())->where('end', '<=', $period_end->toDateString()) as $e => $event) {
49
                    $data['courses'][$c]['events'][$e] = $event->short_date.'('.$event->event_length.'h)';
50
                    $data['courses'][$c]['hours_count'] += $event->event_length;
51
                }
52
                $data['courses'][$c]['value'] = $data['courses'][$c]['hours_count'] * $course->hourly_price;
53
                $partner_balance += $data['courses'][$c]['value'];
54
            }
55
            $data['partner_name'] = $partner->name;
56
            $data['partner_balance'] = $partner_balance;
57
58
            Mail::to(config('settings.secretary_email'))->queue(new ExternalCourseReport($period_start, $period_end, $data));
59
        }
60
    }
61
}
62