Completed
Push — master ( 5d3ba1...38153d )
by Sheela
12:37
created

TrainingController::createTrainingNotes()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 30
ccs 0
cts 8
cp 0
rs 8.439
cc 5
eloc 15
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\StoreTrainingRequest;
17
use SET\Training;
18
use SET\TrainingType;
19
use SET\TrainingUser;
20
use SET\User;
21
22
/**
23
 * Class TrainingController.
24
 */
25
class TrainingController extends Controller
26
{
27
    /**
28
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
29
     */
30
    public function index(Request $request, $trainingTypeID = null)
31
    {
32
        $this->authorize('view');
33
34
        $hasTrainingType = TrainingType::count() > 0;
35
        $isTrainingType = (strpos($request->path(), '/trainingtype/'));
36
37
        if ($trainingTypeID) {
38
            $trainings = Training::with(['users' => function ($q) {
39
                $q->active();
40
            }])
41
                          ->where('training_type_id', $trainingTypeID)
42
                          ->get()
43
                          ->sortBy('name');
44
        } else {
45
            $trainings = Training::with(['users' => function ($q) {
46
                $q->active();
47
            }])->get()->sortBy('name');
48
        }
49
50
        return view('training.index', compact('trainings', 'isTrainingType', 'hasTrainingType'));
51
    }
52
53 View Code Duplication
    public function create()
54
    {
55
        $this->authorize('edit');
56
57
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id');
58
        $groups = Group::orderBy('name')->get()->pluck('name', 'id');
59
        $training_types = TrainingType::whereStatus(true)->orderBy('name')->get()->pluck('name', 'id');
60
61
        return view('training.create', compact('users', 'groups', 'training_types'));
62
    }
63
64
    /**
65
     * Store a newly created resource in storage.
66
     *
67
     * @param StoreTrainingRequest $request
68
     *
69
     * @return \Illuminate\Http\RedirectResponse
70
     */
71 View Code Duplication
    public function store(StoreTrainingRequest $request)
72
    {
73
        $data = $request->all();
74
        $training = Training::create($data);
75
76
        if ($request->hasFile('files')) {
77
            Attachment::upload($training, $request->file('files'));
78
        }
79
80
        $data['training_id'] = $training->id;
81
82
        $this->createTrainingNotes($data);
83
84
        Notification::container()->success('Training Created');
85
86
        return redirect()->action('TrainingController@index');
87
    }
88
89
    /**
90
     * Show the individual training record.
91
     *
92
     * @param $trainingId
93
     *
94
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
95
     */
96
    public function show($trainingId)
97
    {
98
        $this->authorize('view');
99
        $showAll = Input::get('showAll');
100
101
        $training = Training::with('attachments')->find($trainingId);
102
        $notes = $training->assignedUsers()
103
            ->with('user')
104
            ->orderBy(DB::raw('CASE WHEN completed_date IS NULL THEN 0 ELSE 1 END'))
105
            ->orderBy('completed_date', 'desc')
106
            ->get();
107
        if (!$showAll) {
108
            $notes = $notes->unique('user_id')->where('user.status', 'active');
109
        }
110
111
        return view('training.show', compact('notes', 'training', 'showAll'));
112
    }
113
114 View Code Duplication
    public function edit(Training $training)
115
    {
116
        $this->authorize('edit');
117
118
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id');
119
        $groups = Group::orderBy('name')->get()->pluck('name', 'id');
120
        $training_types = TrainingType::whereStatus(true)->orderBy('name')->get()->pluck('name', 'id');
121
122
        return view('training.edit', compact('training', 'users', 'groups', 'training_types'));
123
    }
124
125 View Code Duplication
    public function update(Request $request, Training $training)
126
    {
127
        $this->authorize('edit');
128
129
        $data = $request->all();
130
        $training->update($data);
131
        if ($request->hasFile('files')) {
132
            Attachment::upload($training, $request->file('files'));
133
        }
134
135
        $data['training_id'] = $training->id;
136
        $this->createTrainingNotes($data);
137
138
        Notification::container()->success('Training Updated');
139
140
        return redirect()->action('TrainingController@show', $training->id);
141
    }
142
143
    /**
144
     * Remove the specified resource from storage.
145
     *
146
     * @param int $trainingId
147
     */
148
    public function destroy($trainingId)
149
    {
150
        $this->authorize('edit');
151
        Training::findOrFail($trainingId)->delete();
152
    }
153
154 View Code Duplication
    public function assignForm($trainingID)
155
    {
156
        $this->authorize('edit');
157
158
        $training = Training::findOrFail($trainingID);
159
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id');
160
        $groups = Group::orderBy('name')->get()->pluck('name', 'id');
161
162
        return view('training.assign_user', compact('users', 'groups', 'training'));
163
    }
164
165
    /**
166
     * Assign our users to training.
167
     *
168
     * @param AssignTrainingRequest $request
169
     * @param int                   $trainingID
170
     *
171
     * @return \Illuminate\Http\RedirectResponse
172
     */
173 View Code Duplication
    public function assign(AssignTrainingRequest $request, $trainingID)
174
    {
175
        $this->authorize('edit');
176
177
        $data = $request->all();
178
        $data['training_id'] = $trainingID;
179
180
        $this->createTrainingNotes($data);
181
182
        Notification::container()->success('Training was assigned to the user(s).');
183
184
        return redirect()->action('TrainingController@show', $trainingID);
185
    }
186
187
    /**
188
     * Provide the form data to the bulk update a training form. 
189
     * 
190
     * @param $trainingID
191
     *
192
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
193
     */
194 View Code Duplication
    public function updateForm($trainingID)
195
    {        
196
        $this->authorize('edit');
197
        $training = Training::findOrFail($trainingID);        
198
        $users = User::skipSystem()->active()->orderBy('last_name')->get()->pluck('UserFullName', 'id')->toArray();
199
        
200
        $incompleteUsers = $training->users()->whereNull('training_user.completed_date')->get()->pluck('UserFullName', 'id')->toArray();
201
        return view('training.bulk_update', compact('users', 'training', 'incompleteUsers'));
202
    }
203
    
204
    /**
205
     * Bulk update a training. Useful when FSO provides a training and needs to update
206
     * the training for all assigned users with the same completed date and attach the sign-in sheet.
207
     *
208
     * @param AssignTrainingRequest $request
209
     * @param int                   $trainingID
210
     *
211
     * @return \Illuminate\Http\RedirectResponse
212
     */
213
    public function bulkupdate(Request $request, $trainingID)
214
    {
215
        $this->authorize('edit');
216
        
217
        $data = $request->all();        
218
        $data['training_id'] = $trainingID;
219
        $data['author_id'] = Auth::user()->id;
220
                
221
        if (array_key_exists('users', $data)) {
222
            $users = $data['users'];
223
224
            //update records for each unique
225
            foreach (array_unique($users) as $user) {
226
                $data['user_id'] = $user;
227
228
                // Getting only one record as a collection, so have to use first()
229
                // to extract out of the array.
230
                $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...
231
                        ->where('user_id', $user)->whereNull('completed_date')->get()->first();
232
                $trainingUser->update($data);           
233
            }
234
        }
235
        
236
        $training = Training::findOrFail($trainingID);
237
        if ($request->hasFile('files')) {
238
                        
239
            $encrypt = false;
240
            if (array_key_exists('encrypt', $data)) {
241
                $encrypt = $data['encrypt'];
242
            }
243
            
244
            $admin_only = false;
245
            if (array_key_exists('admin_only', $data)) {
246
                $admin_only = $data['admin_only'];
247
            }
248
            Attachment::upload($training, $request->file('files'), $encrypt, $admin_only);
249
        }
250
251
        Notification::container()->success('Training was updated for the users.');
252
253
        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...
254
    }
255
    
256
    /**
257
     * Generate Excel file with user/training table with date of completion.
258
     *
259
     * Calls to \SET\app\Handlers\Excel\
260
     *
261
     * @param CompletedTrainingExport $export
262
     *
263
     * @return mixed
264
     */
265
    public function showCompleted(CompletedTrainingExport $export)
266
    {
267
        $this->authorize('view');
268
269
        return $export->handleExport();
270
    }
271
272
    /**
273
     * Send out a reminder that the training is due.
274
     *
275
     * @param $trainingUserId
276
     *
277
     * @return \Illuminate\Http\RedirectResponse
278
     */
279
    public function sendReminder($trainingUserId)
280
    {
281
        $trainingUser = TrainingUser::with('user')->find($trainingUserId);
282
        Event::fire(new TrainingAssigned($trainingUser));
283
        Notification::container()->success('Reminder sent to '.$trainingUser->user->userFullName);
284
285
        return redirect()->back();
286
    }
287
288
    /***************************/
289
    /* BEGIN PRIVATE FUNCTIONS */
290
    /***************************/
291
292
    /**
293
     * Get a list of users and create training notes from that list.
294
     *
295
     * @param $data
296
     */
297
    private function createTrainingNotes($data)
298
    {
299
        $data['author_id'] = Auth::user()->id;
300
301
        $users = [];
302
303
        //If we have groups, let's get the user ids.
304
        if (isset($data['groups'])) {
305
            $groupUsers = User::whereHas('groups', function ($q) use ($data) {
306
                $q->where('id', $data['groups']);
307
            })->get();
308
309
            //get the user ids from our groups
310
            foreach ($groupUsers as $user) {
311
                array_push($users, $user->id);
312
            }
313
        }
314
315
        //pull out our user ids.
316
        if (isset($data['users'])) {
317
            $users = array_merge($users, $data['users']);
318
        }
319
320
        //create records for each unique
321
        foreach (array_unique($users) as $user) {
322
            $data['user_id'] = $user;
323
            $note = TrainingUser::create($data);
324
            Event::fire(new TrainingAssigned($note));
325
        }
326
    }
327
}
328