Passed
Push — feature/response-home-message ( 8fa134...20069e )
by Tristan
03:51
created

JobController   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 445
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 36
eloc 217
c 6
b 0
f 0
dl 0
loc 445
rs 9.52

9 Methods

Rating   Name   Duplication   Size   Complexity  
A hrIndex() 0 6 1
A index() 0 29 2
A createAsManager() 0 17 1
A fillAndSaveJobPosterQuestions() 0 28 5
A downloadApplicants() 0 51 5
A managerIndex() 0 29 3
C show() 0 138 13
A store() 0 31 4
A destroy() 0 3 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Support\Facades\Lang;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Http\Request;
8
use App\Http\Controllers\Controller;
9
use App\Models\JobApplication;
10
use Carbon\Carbon;
11
use App\Models\JobPoster;
12
use App\Models\JobPosterQuestion;
13
use App\Models\Lookup\ApplicationStatus;
14
use App\Models\Lookup\CitizenshipDeclaration;
15
use App\Models\Lookup\JobPosterStatus;
16
use App\Models\Lookup\VeteranStatus;
17
use App\Models\Manager;
18
use App\Services\JobPosterDefaultQuestions;
19
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
20
use App\Services\Validation\JobPosterValidator;
21
use Facades\App\Services\WhichPortal;
22
use Illuminate\Support\Facades\Response;
23
use Illuminate\Support\Facades\Validator;
24
25
class JobController extends Controller
26
{
27
    /**
28
     * Display a listing of JobPosters.
29
     *
30
     * @return \Illuminate\Http\Response
31
     */
32
    public function index()
33
    {
34
        // If true, show the Paused due to COVID-19 message.
35
        $emergency_response = config('seasonal.is_covid_emergency');
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

35
        $emergency_response = /** @scrutinizer ignore-call */ config('seasonal.is_covid_emergency');
Loading history...
36
37
        // Find published jobs that are currently open for applications.
38
        // Eager load required relationships: Department, Province, JobTerm.
39
        // Eager load the count of submitted applications, to prevent the relationship
40
        // from being actually loaded and firing off events.
41
        $jobs = JobPoster::where('internal_only', false)
42
            ->where('department_id', '!=', config('app.strategic_response_department_id'))
43
            ->where('job_poster_status_id', JobPosterStatus::where('key', 'live')->first()->id)
44
            ->with([
45
                'department',
46
                'province',
47
                'job_term',
48
            ])
49
            ->withCount([
50
                'submitted_applications',
51
            ])
52
            ->get();
53
54
        $null_alert = $emergency_response
55
            ? Lang::get('applicant/job_index.index.covid_null_alert')
56
            : Lang::get('applicant/job_index.index.null_alert');
57
        return view('applicant/job_index', [
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
        return /** @scrutinizer ignore-call */ view('applicant/job_index', [
Loading history...
58
            'job_index' => Lang::get('applicant/job_index'),
59
            'null_alert' => $null_alert,
60
            'jobs' => $jobs
61
        ]);
62
    }
63
64
    /**
65
     * Display a listing of a manager's JobPosters.
66
     *
67
     * @return \Illuminate\Http\Response
68
     */
69
    public function managerIndex()
70
    {
71
        $manager = Auth::user()->manager;
72
73
        $jobs = JobPoster::where('manager_id', $manager->id)
74
            ->with('classification')
75
            ->withCount('submitted_applications')
76
            ->get();
77
78
        foreach ($jobs as &$job) {
79
            $chosen_lang = $job->chosen_lang;
80
81
            // Show chosen lang title if current title is empty.
82
            if (empty($job->title)) {
83
                $job->title = $job->getTranslation('title', $chosen_lang);
84
                $job->trans_required = true;
85
            }
86
87
            // Always preview and edit in the chosen language.
88
            $job->preview_link = LaravelLocalization::getLocalizedURL($chosen_lang, route('manager.jobs.show', $job));
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

88
            $job->preview_link = LaravelLocalization::getLocalizedURL($chosen_lang, /** @scrutinizer ignore-call */ route('manager.jobs.show', $job));
Loading history...
89
            $job->edit_link = LaravelLocalization::getLocalizedURL($chosen_lang, route('manager.jobs.edit', $job));
90
        }
91
92
93
        return view('manager/job_index', [
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

93
        return /** @scrutinizer ignore-call */ view('manager/job_index', [
Loading history...
94
            // Localization Strings.
95
            'jobs_l10n' => Lang::get('manager/job_index'),
96
            // Data.
97
            'jobs' => $jobs,
98
        ]);
99
    }
100
101
    /**
102
     * Display a listing of a hr advisor's JobPosters.
103
     *
104
     * @return \Illuminate\Http\Response
105
     */
106
    public function hrIndex(Request $request)
107
    {
108
        $hrAdvisor = $request->user()->hr_advisor;
109
        return view('hr_advisor/job_index', [
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

109
        return /** @scrutinizer ignore-call */ view('hr_advisor/job_index', [
Loading history...
110
            'title' => Lang::get('hr_advisor/job_index.title'),
111
            'hr_advisor_id' => $hrAdvisor->id
112
        ]);
113
    }
114
115
116
117
118
    /**
119
     * Delete a draft Job Poster.
120
     *
121
     * @param  \Illuminate\Http\Request $request   Incoming request object.
122
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
123
     * @return \Illuminate\Http\Response
124
     */
125
    public function destroy(Request $request, JobPoster $jobPoster)
126
    {
127
        $jobPoster->delete();
128
    }
129
130
    /**
131
     * Display the specified job poster.
132
     *
133
     * @param  \Illuminate\Http\Request $request   Incoming request object.
134
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
135
     * @return \Illuminate\Http\Response
136
     */
137
    public function show(Request $request, JobPoster $jobPoster)
138
    {
139
        $jobPoster->load([
140
            'department',
141
            'criteria.skill.skill_type',
142
            'manager.team_culture',
143
            'manager.work_environment'
144
        ]);
145
146
        $user = Auth::user();
147
148
        // TODO: Improve workplace photos, and reference them in template direction from WorkEnvironment model.
149
        $workplacePhotos = [];
150
        foreach ($jobPoster->manager->work_environment->workplace_photo_captions as $photoCaption) {
151
            $workplacePhotos[] = [
152
                'description' => $photoCaption->description,
153
                'url' => '/images/user.png'
154
            ];
155
        }
156
157
        // TODO: replace route('manager.show',manager.id) in templates with link using slug.
158
        $criteria = [
159
            'essential' => $jobPoster->criteria->filter(
160
                function ($value, $key) {
161
                    return $value->criteria_type->name == 'essential';
162
                }
163
            ),
164
            'asset' => $jobPoster->criteria->filter(
165
                function ($value, $key) {
166
                    return $value->criteria_type->name == 'asset';
167
                }
168
            ),
169
        ];
170
171
        $jobLang = Lang::get('applicant/job_post');
172
173
        $applyButton = [];
174
        if (WhichPortal::isManagerPortal()) {
175
            $applyButton = [
176
                'href' => route('manager.jobs.edit', $jobPoster->id),
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

176
                'href' => /** @scrutinizer ignore-call */ route('manager.jobs.edit', $jobPoster->id),
Loading history...
177
                'title' => $jobLang['apply']['edit_link_title'],
178
                'text' => $jobLang['apply']['edit_link_label'],
179
            ];
180
        } elseif (WhichPortal::isHrPortal()) {
181
            if ($jobPoster->hr_advisors->contains('user_id', $user->id)) {
182
                $applyButton = [
183
                    'href' => route('hr_advisor.jobs.summary', $jobPoster->id),
184
                    'title' => null,
185
                    'text' => Lang::get('hr_advisor/job_summary.summary_title'),
186
                ];
187
            } else {
188
                $applyButton = [
189
                    'href' => route('hr_advisor.jobs.index'),
190
                    'title' => null,
191
                    'text' => Lang::get('hr_advisor/job_index.title'),
192
                ];
193
            }
194
        } elseif (Auth::check() && $jobPoster->isOpen()) {
195
            $application = JobApplication::where('applicant_id', Auth::user()->applicant->id)
196
                ->where('job_poster_id', $jobPoster->id)->first();
197
            // If applicants job application is not draft anymore then link to application preview page.
198
            if ($application != null && $application->application_status->name != 'draft') {
199
                $applyButton = [
200
                    'href' => route('applications.show', $application->id),
201
                    'title' => $jobLang['apply']['view_link_title'],
202
                    'text' => $jobLang['apply']['view_link_label'],
203
                ];
204
            } else {
205
                $applyButton = [
206
                    'href' => route('job.application.edit.1', $jobPoster->id),
207
                    'title' => $jobLang['apply']['apply_link_title'],
208
                    'text' => $jobLang['apply']['apply_link_label'],
209
                ];
210
            }
211
        } elseif (Auth::guest() && $jobPoster->isOpen()) {
212
            $applyButton = [
213
                'href' => route('job.application.edit.1', $jobPoster->id),
214
                'title' => $jobLang['apply']['login_link_title'],
215
                'text' => $jobLang['apply']['login_link_label'],
216
            ];
217
        } else {
218
            $applyButton = [
219
                'href' => null,
220
                'title' => null,
221
                'text' => $jobLang['apply']['job_closed_label'],
222
            ];
223
        }
224
225
        $jpb_release_date = strtotime('2019-08-21 16:18:17');
226
        $job_created_at = strtotime($jobPoster->created_at);
227
228
        // If the poster is part of the Strategic Talent Response dept, use the talent stream template.
229
        // Else, If the job poster is created after the release of the JPB.
230
        // Then, render with updated poster template.
231
        // Else, render with old poster template.
232
        if ($jobPoster->isInStrategicResponseDepartment()) {
233
            return view(
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

233
            return /** @scrutinizer ignore-call */ view(
Loading history...
234
                'applicant/strategic_response_job_post',
235
                [
236
                    'job_post' => $jobLang,
237
                    'frequencies' => Lang::get('common/lookup/frequency'),
238
                    'skill_template' => Lang::get('common/skills'),
239
                    'job' => $jobPoster,
240
                    'manager' => $jobPoster->manager,
241
                    'criteria' => $criteria,
242
                    'apply_button' => $applyButton,
243
                ]
244
            );
245
        } elseif ($job_created_at > $jpb_release_date) {
246
            // Updated job poster (JPB).
247
            return view(
248
                'applicant/jpb_job_post',
249
                [
250
                    'job_post' => $jobLang,
251
                    'frequencies' => Lang::get('common/lookup/frequency'),
252
                    'skill_template' => Lang::get('common/skills'),
253
                    'job' => $jobPoster,
254
                    'manager' => $jobPoster->manager,
255
                    'criteria' => $criteria,
256
                    'apply_button' => $applyButton,
257
                ]
258
            );
259
        } else {
260
            // Old job poster.
261
            return view(
262
                'applicant/job_post',
263
                [
264
                    'job_post' => $jobLang,
265
                    'frequencies' => Lang::get('common/lookup/frequency'),
266
                    'manager' => $jobPoster->manager,
267
                    'manager_profile_photo_url' => '/images/user.png', // TODO get real photo.
268
                    'team_culture' => $jobPoster->manager->team_culture,
269
                    'work_environment' => $jobPoster->manager->work_environment,
270
                    'workplace_photos' => $workplacePhotos,
271
                    'job' => $jobPoster,
272
                    'criteria' => $criteria,
273
                    'apply_button' => $applyButton,
274
                    'skill_template' => Lang::get('common/skills'),
275
                ]
276
            );
277
        }
278
    }
279
280
    /**
281
     * Display the form for editing an existing Job Poster
282
     * Only allows editing fields that don't appear on the react-built Job Poster Builder.
283
     *
284
     * @param  \Illuminate\Http\Request $request   Incoming request object.
285
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
286
     * @return \Illuminate\Http\Response
287
     */
288
    public function edit(Request $request, JobPoster $jobPoster)
289
    {
290
        $manager = $jobPoster->manager;
291
292
        $defaultQuestionManager = new JobPosterDefaultQuestions();
293
        $defaultQuestionManager->initializeQuestionsIfEmpty($jobPoster);
294
295
        return view(
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

295
        return /** @scrutinizer ignore-call */ view(
Loading history...
296
            'manager/job_create',
297
            [
298
                // Localization Strings.
299
                'job_l10n' => Lang::get('manager/job_edit'),
300
                // Data.
301
                'manager' => $manager,
302
                'job' => $jobPoster,
303
                'form_action_url' => route('admin.jobs.update', $jobPoster),
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

303
                'form_action_url' => /** @scrutinizer ignore-call */ route('admin.jobs.update', $jobPoster),
Loading history...
304
            ]
305
        );
306
    }
307
308
    /**
309
     * Create a blank job poster for the specified manager
310
     *
311
     * @param  \App\Models\Manager $manager Incoming Manager object.
312
     * @return \Illuminate\Http\Response Job Create view
313
     */
314
    public function createAsManager(Manager $manager)
315
    {
316
        $jobPoster = new JobPoster();
317
        $jobPoster->manager_id = $manager->id;
318
319
        // Save manager-specific info to the job poster - equivalent to the intro step of the JPB
320
        $divisionEn = $manager->getTranslation('division', 'en');
321
        $divisionFr = $manager->getTranslation('division', 'fr');
322
        $jobPoster->fill([
323
            'department_id' => $manager->user->department_id,
324
            'division' => ['en' => $divisionEn],
325
            'division' => ['fr' => $divisionFr],
326
        ]);
327
328
        $jobPoster->save();
329
330
        return redirect()->route('manager.jobs.edit', $jobPoster->id);
0 ignored issues
show
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

330
        return /** @scrutinizer ignore-call */ redirect()->route('manager.jobs.edit', $jobPoster->id);
Loading history...
331
    }
332
333
    /**
334
     * Update a resource in storage
335
     * NOTE: Only saves fields that are not on the react-built Job Poster Builder
336
     *
337
     * @param  \Illuminate\Http\Request $request   Incoming request object.
338
     * @param  \App\Models\JobPoster    $jobPoster Optional Job Poster object.
339
     * @return \Illuminate\Http\Response
340
     */
341
    public function store(Request $request, JobPoster $jobPoster)
342
    {
343
        // Don't allow edits for published Job Posters
344
        // Also check auth while we're at it.
345
        $this->authorize('update', $jobPoster);
346
        JobPosterValidator::validateUnpublished($jobPoster);
347
348
        $input = $request->input();
349
350
        if ($jobPoster->manager_id == null) {
351
            $jobPoster->manager_id = $request->user()->manager->id;
352
            $jobPoster->save();
353
        }
354
355
        if ($request->input('question')) {
356
            $validator = Validator::make($request->input('question'), [
357
                '*.question.*' => 'required|string',
358
            ], [
359
                'required' => Lang::get('validation.custom.job_poster_question.required'),
360
                'string' => Lang::get('validation.custom.job_poster_question.string')
361
            ]);
362
363
            if ($validator->fails()) {
364
                $request->session()->flash('errors', $validator->errors());
365
                return redirect(route('admin.jobs.edit', $jobPoster->id));
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

365
                return redirect(/** @scrutinizer ignore-call */ route('admin.jobs.edit', $jobPoster->id));
Loading history...
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

365
                return /** @scrutinizer ignore-call */ redirect(route('admin.jobs.edit', $jobPoster->id));
Loading history...
366
            }
367
        }
368
369
        $this->fillAndSaveJobPosterQuestions($input, $jobPoster, true);
370
371
        return redirect(route('manager.jobs.show', $jobPoster->id));
372
    }
373
374
    /**
375
     * Fill Job Poster's questions and save
376
     *
377
     * @param  mixed[]               $input     Field values.
378
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
379
     * @param  boolean               $replace   Remove existing relationships.
380
     * @return void
381
     */
382
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace): void
383
    {
384
        if ($replace) {
385
            $jobPoster->job_poster_questions()->delete();
386
        }
387
388
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
389
            return;
390
        }
391
392
        foreach ($input['question'] as $question) {
393
            $jobQuestion = new JobPosterQuestion();
394
            $jobQuestion->job_poster_id = $jobPoster->id;
395
            $jobQuestion->fill(
396
                [
397
                    'question' => [
398
                        'en' => $question['question']['en'],
399
                        'fr' => $question['question']['fr']
400
401
                    ],
402
                    'description' => [
403
                        'en' => $question['description']['en'],
404
                        'fr' => $question['description']['fr']
405
                    ]
406
                ]
407
            );
408
            $jobPoster->save();
409
            $jobQuestion->save();
410
        }
411
    }
412
413
    /**
414
     * Downloads a CSV file with the applicants who have applied to the job poster.
415
     *
416
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
417
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
418
     */
419
    protected function downloadApplicants(JobPoster $jobPoster)
420
    {
421
        $tables = [];
422
        // The first row in the array represents the names of the columns in the spreadsheet.
423
        $tables[0] = ['Status', 'Applicant Name', 'Email', 'Language'];
424
425
        $application_status_id = ApplicationStatus::where('name', 'submitted')->first()->id;
426
        $applications = JobApplication::where('job_poster_id', $jobPoster->id)
427
            ->where('application_status_id', $application_status_id)
428
            ->get();
429
430
        $index = 1;
431
        foreach ($applications as $application) {
432
            $status = '';
433
            $username = $application->user_name;
434
            $user_email = $application->user_email;
435
            $language = strtoupper($application->preferred_language->name);
436
            // If the applicants veteran status name is NOT 'none' then set status to veteran.
437
            $non_veteran = VeteranStatus::where('name', 'none')->first()->id;
438
            if ($application->veteran_status_id != $non_veteran) {
439
                $status = 'Veteran';
440
            } else {
441
                // Check if the applicant is a canadian citizen.
442
                $canadian_citizen = CitizenshipDeclaration::where('name', 'citizen')->first()->id;
443
                if ($application->citizenship_declaration->id == $canadian_citizen) {
444
                    $status = 'Citizen';
445
                } else {
446
                    $status = 'Non-citizen';
447
                }
448
            }
449
            $tables[$index] = [$status, $username, $user_email, $language];
450
            $index++;
451
        }
452
453
        $filename = $jobPoster->id . '-' . 'applicants-data.csv';
454
455
        // Open file.
456
        $file = fopen($filename, 'w');
457
        // Iterate through tables and add each line to csv file.
458
        foreach ($tables as $line) {
459
            fputcsv($file, $line);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $handle of fputcsv() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

459
            fputcsv(/** @scrutinizer ignore-type */ $file, $line);
Loading history...
460
        }
461
        // Close open file.
462
        fclose($file);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

462
        fclose(/** @scrutinizer ignore-type */ $file);
Loading history...
463
464
        $headers = [
465
            'Content-Type' => 'text/csv',
466
            'Content-Disposition' => 'attachment; filename=' . $filename,
467
        ];
468
469
        return Response::download($filename, $filename, $headers);
470
    }
471
}
472