TrainingController::createTrainingNotes()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 0
cts 8
cp 0
rs 9.1288
c 0
b 0
f 0
cc 5
nc 8
nop 1
crap 30
1
<?php
2
3
namespace SET\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Facades\Event;
9
use Illuminate\Support\Facades\Input;
10
use Krucas\Notification\Facades\Notification;
11
use SET\Attachment;
12
use SET\Events\TrainingAssigned;
13
use SET\Group;
14
use SET\Handlers\Excel\CompletedTrainingExport;
15
use SET\Http\Requests\AssignTrainingRequest;
16
use SET\Http\Requests\BulkUpdateTrainingRequest;
17
use SET\Http\Requests\StoreTrainingRequest;
18
use SET\Training;
19
use SET\TrainingType;
20
use SET\TrainingUser;
21
use SET\User;
22
23
/**
24
 * Class TrainingController.
25
 */
26
class TrainingController extends Controller
27
{
28
    /**
29
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
30
     */
31
    public function index(Request $request, $trainingTypeID = null)
32
    {
33
        $this->authorize('view');
34
35
        $hasTrainingType = TrainingType::count() > 0;
36
        $isTrainingType = (strpos($request->path(), '/trainingtype/'));
37
38
        if ($trainingTypeID) {
39
            $trainings = Training::with(['users' => function ($q) {
40
                $q->active();
41
            }])
42
                          ->where('training_type_id', $trainingTypeID)
43
                          ->get()
44
                          ->sortBy('name');
45
        } else {
46
            $trainings = Training::with(['users' => function ($q) {
47
                $q->active();
48
            }])->get()->sortBy('name');
49
        }
50
51
        return view('training.index', compact('trainings', 'isTrainingType', 'hasTrainingType'));
52
    }
53
54 View Code Duplication
    public function create()
55
    {
56
        $this->authorize('edit');
57
58
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id');
59
        $groups = Group::orderBy('name')->get()->pluck('name', 'id');
60
        $training_types = TrainingType::whereStatus(true)->orderBy('name')->get()->pluck('name', 'id');
61
62
        return view('training.create', compact('users', 'groups', 'training_types'));
63
    }
64
65
    /**
66
     * Store a newly created resource in storage.
67
     *
68
     * @param StoreTrainingRequest $request
69
     *
70
     * @return \Illuminate\Http\RedirectResponse
71
     */
72
    public function store(StoreTrainingRequest $request)
73
    {
74
        $data = $request->all();
75
        $training = Training::create($data);
76
77
        if ($request->hasFile('files')) {
78
            Attachment::upload($training, $request->file('files'));
79
        }
80
81
        $data['training_id'] = $training->id;
82
83
        $this->createTrainingNotes($data);
84
85
        Notification::container()->success('Training Created');
86
87
        return redirect()->action('TrainingController@index');
88
    }
89
90
    /**
91
     * Show the individual training record.
92
     *
93
     * @param $trainingId
94
     *
95
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
96
     */
97
    public function show($trainingId)
98
    {
99
        $this->authorize('view');
100
        $showAll = Input::get('showAll');
101
102
        $training = Training::with('attachments')->find($trainingId);
103
        $notes = $training->assignedUsers()
104
            ->with('user')
105
            ->orderBy(DB::raw('CASE WHEN completed_date IS NULL THEN 0 ELSE 1 END'))
106
            ->orderBy('completed_date', 'desc')
107
            ->get();
108
        if (!$showAll) {
109
            $notes = $notes->unique('user_id')->where('user.status', 'active');
110
        }
111
112
        return view('training.show', compact('notes', 'training', 'showAll'));
113
    }
114
115 View Code Duplication
    public function edit(Training $training)
116
    {
117
        $this->authorize('edit');
118
119
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id');
120
        $groups = Group::orderBy('name')->get()->pluck('name', 'id');
121
        $training_types = TrainingType::whereStatus(true)->orderBy('name')->get()->pluck('name', 'id');
122
123
        return view('training.edit', compact('training', 'users', 'groups', 'training_types'));
124
    }
125
126 View Code Duplication
    public function update(Request $request, Training $training)
127
    {
128
        $this->authorize('edit');
129
130
        $data = $request->all();
131
        $training->update($data);
132
        if ($request->hasFile('files')) {
133
            Attachment::upload($training, $request->file('files'));
134
        }
135
136
        $data['training_id'] = $training->id;
137
        $this->createTrainingNotes($data);
138
139
        Notification::container()->success('Training Updated');
140
141
        return redirect()->action('TrainingController@show', $training->id);
142
    }
143
144
    /**
145
     * Remove the specified resource from storage.
146
     *
147
     * @param int $trainingId
148
     */
149
    public function destroy($trainingId)
150
    {
151
        $this->authorize('edit');
152
        Training::findOrFail($trainingId)->delete();
153
    }
154
155 View Code Duplication
    public function assignForm($trainingID)
156
    {
157
        $this->authorize('edit');
158
159
        $training = Training::findOrFail($trainingID);
160
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id');
161
        $groups = Group::orderBy('name')->get()->pluck('name', 'id');
162
163
        return view('training.assign_user', compact('users', 'groups', 'training'));
164
    }
165
166
    /**
167
     * Assign our users to training.
168
     *
169
     * @param AssignTrainingRequest $request
170
     * @param int                   $trainingID
171
     *
172
     * @return \Illuminate\Http\RedirectResponse
173
     */
174 View Code Duplication
    public function assign(AssignTrainingRequest $request, $trainingID)
175
    {
176
        $this->authorize('edit');
177
178
        $data = $request->all();
179
        $data['training_id'] = $trainingID;
180
181
        $this->createTrainingNotes($data);
182
183
        Notification::container()->success('Training was assigned to the user(s).');
184
185
        return redirect()->action('TrainingController@show', $trainingID);
186
    }
187
188
    /**
189
     * Provide the form data to the bulk update a training form.
190
     *
191
     * @param $trainingID
192
     *
193
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
194
     */
195
    public function updateForm($trainingID)
196
    {
197
        $this->authorize('edit');
198
        $training = Training::findOrFail($trainingID);
199
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id')->toArray();
200
201
        $incompleteUsers = $training->users()->active()->whereNull('training_user.completed_date')->get()->pluck('UserFullName', 'id')->toArray();
202
203
        return view('training.bulk_update', compact('users', 'training', 'incompleteUsers'));
204
    }
205
206
    /**
207
     * Bulk update a training. Useful when FSO provides a training and needs to update
208
     * the training for all assigned users with the same completed date and attach the sign-in sheet.
209
     *
210
     * @param BulkUpdateTrainingRequest $request
211
     * @param int                       $trainingID
212
     *
213
     * @return \Illuminate\Http\RedirectResponse
214
     */
215
    public function bulkupdate(BulkUpdateTrainingRequest $request, $trainingID)
216
    {
217
        $this->authorize('edit');
218
219
        $data = $request->all();
220
        $data['training_id'] = $trainingID;
221
        $data['author_id'] = Auth::user()->id;
222
223
        if (array_key_exists('users', $data)) {
224
            $users = $data['users'];
225
226
            //update records for each unique
227
            foreach (array_unique($users) as $user) {
228
                $data['user_id'] = $user;
229
230
                // Getting only one record as a collection, so have to use first()
231
                // to extract out of the array.
232
                $trainingUser = TrainingUser::whereTraining_id($trainingID)
0 ignored issues
show
Bug introduced by
The method whereTraining_id() does not exist on SET\TrainingUser. Did you maybe mean training()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
233
                        ->where('user_id', $user)->whereNull('completed_date')->get()->first();
234
                $trainingUser->update($data);
235
            }
236
        }
237
238
        $training = Training::findOrFail($trainingID);
239
        if ($request->hasFile('files')) {
240
            $encrypt = false;
241
            if (array_key_exists('encrypt', $data)) {
242
                $encrypt = $data['encrypt'];
243
            }
244
245
            $admin_only = false;
246
            if (array_key_exists('admin_only', $data)) {
247
                $admin_only = $data['admin_only'];
248
            }
249
            Attachment::upload($training, $request->file('files'), $encrypt, $admin_only);
250
        }
251
252
        Notification::container()->success('Training was updated for the users.');
253
254
        return redirect()->action('TrainingController@show', $trainingID);
0 ignored issues
show
Documentation introduced by
$trainingID is of type integer, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
255
    }
256
257
    /**
258
     * Generate Excel file with user/training table with date of completion.
259
     *
260
     * Calls to \SET\app\Handlers\Excel\
261
     *
262
     * @param CompletedTrainingExport $export
263
     *
264
     * @return mixed
265
     */
266
    public function showCompleted(CompletedTrainingExport $export)
267
    {
268
        $this->authorize('view');
269
270
        return $export->handleExport();
271
    }
272
273
    /**
274
     * Send out a reminder that the training is due.
275
     *
276
     * @param $trainingUserId
277
     *
278
     * @return \Illuminate\Http\RedirectResponse
279
     */
280
    public function sendReminder($trainingUserId)
281
    {
282
        $trainingUser = TrainingUser::with('user')->find($trainingUserId);
283
        Event::fire(new TrainingAssigned($trainingUser));
284
        Notification::container()->success('Reminder sent to '.$trainingUser->user->userFullName);
285
286
        return redirect()->back();
287
    }
288
289
    /***************************/
290
    /* BEGIN PRIVATE FUNCTIONS */
291
    /***************************/
292
293
    /**
294
     * Get a list of users and create training notes from that list.
295
     *
296
     * @param $data
297
     */
298
    private function createTrainingNotes($data)
299
    {
300
        $data['author_id'] = Auth::user()->id;
301
302
        $users = [];
303
304
        //If we have groups, let's get the user ids.
305
        if (isset($data['groups'])) {
306
            $groupUsers = User::whereHas('groups', function ($q) use ($data) {
307
                $q->where('id', $data['groups']);
308
            })->get();
309
310
            //get the user ids from our groups
311
            foreach ($groupUsers as $user) {
312
                array_push($users, $user->id);
313
            }
314
        }
315
316
        //pull out our user ids.
317
        if (isset($data['users'])) {
318
            $users = array_merge($users, $data['users']);
319
        }
320
321
        //create records for each unique
322
        foreach (array_unique($users) as $user) {
323
            $data['user_id'] = $user;
324
            $note = TrainingUser::create($data);
325
            Event::fire(new TrainingAssigned($note));
326
        }
327
    }
328
}
329