Passed
Push — feature/application-urls ( eaeba2 )
by Tristan
05:58
created

JobController::downloadApplicants()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 51
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 51
rs 9.0968
c 0
b 0
f 0
cc 5
nc 8
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Http\Controllers\Controller;
6
use App\Models\JobApplication;
7
use App\Models\JobApplicationVersion;
8
use App\Models\JobPoster;
9
use App\Models\JobPosterQuestion;
10
use App\Models\Lookup\ApplicationStatus;
11
use App\Models\Lookup\CitizenshipDeclaration;
12
use App\Models\Lookup\JobPosterStatus;
13
use App\Models\Lookup\VeteranStatus;
14
use App\Models\Manager;
15
use App\Services\JobPosterDefaultQuestions;
16
use App\Services\Validation\JobPosterValidator;
17
use Carbon\Carbon;
18
use Facades\App\Services\WhichPortal;
19
use Illuminate\Http\Request;
20
use Illuminate\Support\Facades\Auth;
21
use Illuminate\Support\Facades\Lang;
22
use Illuminate\Support\Facades\Response;
23
use Illuminate\Support\Facades\Validator;
24
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
25
26
class JobController extends Controller
27
{
28
    /**
29
     * Display a listing of JobPosters.
30
     *
31
     * @return \Illuminate\Http\Response
32
     */
33
    public function index()
34
    {
35
        // If true, show the Paused due to COVID-19 message.
36
        $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

36
        $emergency_response = /** @scrutinizer ignore-call */ config('seasonal.is_covid_emergency');
Loading history...
37
38
        // Find published jobs that are currently open for applications.
39
        // Eager load required relationships: Department, Province, JobTerm.
40
        // Eager load the count of submitted applications, to prevent the relationship
41
        // from being actually loaded and firing off events.
42
        $jobs = JobPoster::where('internal_only', false)
43
            ->where('department_id', '!=', config('app.strategic_response_department_id'))
44
            ->where('job_poster_status_id', JobPosterStatus::where('key', 'live')->first()->id)
45
            ->with([
46
                'department',
47
                'province',
48
                'job_term',
49
            ])
50
            ->withCount([
51
                'submitted_applications',
52
            ])
53
            ->get();
54
55
        $null_alert = $emergency_response
56
            ? Lang::get('applicant/job_index.index.covid_null_alert')
57
            : Lang::get('applicant/job_index.index.null_alert');
58
        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

58
        return /** @scrutinizer ignore-call */ view('applicant/job_index', [
Loading history...
59
            'job_index' => Lang::get('applicant/job_index'),
60
            'null_alert' => $null_alert,
61
            'jobs' => $jobs
62
        ]);
63
    }
64
65
    /**
66
     * Display a listing of a manager's JobPosters.
67
     *
68
     * @return \Illuminate\Http\Response
69
     */
70
    public function managerIndex()
71
    {
72
        $manager = Auth::user()->manager;
73
74
        $jobs = JobPoster::where('manager_id', $manager->id)
75
            ->with('classification')
76
            ->withCount('submitted_applications')
77
            ->get();
78
79
        foreach ($jobs as &$job) {
80
            // If the chosen language is null then set to english.
81
            $chosen_lang = $job->chosen_lang ?: 'en';
82
83
            // Show chosen lang title if current title is empty.
84
            if (empty($job->title)) {
85
                $job->title = $job->getTranslation('title', $chosen_lang);
86
                $job->trans_required = true;
87
            }
88
        }
89
90
        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

90
        return /** @scrutinizer ignore-call */ view('manager/job_index', [
Loading history...
91
            // Localization Strings.
92
            'jobs_l10n' => Lang::get('manager/job_index'),
93
            // Data.
94
            'jobs' => $jobs,
95
        ]);
96
    }
97
98
    /**
99
     * Display a listing of a hr advisor's JobPosters.
100
     *
101
     * @param  \Illuminate\Http\Request $request Incoming request object.
102
     * @return \Illuminate\Http\Response
103
     */
104
    public function hrIndex(Request $request)
105
    {
106
        $hrAdvisor = $request->user()->hr_advisor;
107
        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

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

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

239
            return /** @scrutinizer ignore-call */ view(
Loading history...
240
                'applicant/strategic_response_job_post',
241
                [
242
                    'job_post' => $jobLang,
243
                    'frequencies' => Lang::get('common/lookup/frequency'),
244
                    'skill_template' => $skillsLang,
245
                    'job' => $jobPoster,
246
                    'manager' => $jobPoster->manager,
247
                    'criteria' => $criteria,
248
                    'apply_button' => $applyButton,
249
                    'custom_breadcrumbs' => $custom_breadcrumbs,
250
                ]
251
            );
252
        } elseif ($job_created_at > $jpb_release_date) {
253
            // Updated job poster (JPB).
254
            return view(
255
                'applicant/jpb_job_post',
256
                [
257
                    'job_post' => $jobLang,
258
                    'frequencies' => Lang::get('common/lookup/frequency'),
259
                    'skill_template' => $skillsLang,
260
                    'job' => $jobPoster,
261
                    'manager' => $jobPoster->manager,
262
                    'criteria' => $criteria,
263
                    'apply_button' => $applyButton,
264
                    'custom_breadcrumbs' => $custom_breadcrumbs,
265
                    'structured_data' => $this->buildStructuredData($jobPoster),
266
                ]
267
            );
268
        } else {
269
            // Old job poster.
270
            return view(
271
                'applicant/job_post',
272
                [
273
                    'job_post' => $jobLang,
274
                    'frequencies' => Lang::get('common/lookup/frequency'),
275
                    'manager' => $jobPoster->manager,
276
                    'manager_profile_photo_url' => '/images/user.png', // TODO get real photo.
277
                    'team_culture' => $jobPoster->manager->team_culture,
278
                    'work_environment' => $jobPoster->manager->work_environment,
279
                    'workplace_photos' => $workplacePhotos,
280
                    'job' => $jobPoster,
281
                    'criteria' => $criteria,
282
                    'apply_button' => $applyButton,
283
                    'skill_template' => Lang::get('common/skills'),
284
                    'custom_breadcrumbs' => $custom_breadcrumbs,
285
                ]
286
            );
287
        }
288
    }
289
290
    /**
291
     * Display the form for editing an existing Job Poster
292
     * Only allows editing fields that don't appear on the react-built Job Poster Builder.
293
     *
294
     * @param  \Illuminate\Http\Request $request   Incoming request object.
295
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
296
     * @return \Illuminate\Http\Response
297
     */
298
    public function edit(Request $request, JobPoster $jobPoster)
299
    {
300
        $manager = $jobPoster->manager;
301
302
        $defaultQuestionManager = new JobPosterDefaultQuestions();
303
        $defaultQuestionManager->initializeQuestionsIfEmpty($jobPoster);
304
305
        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

305
        return /** @scrutinizer ignore-call */ view(
Loading history...
306
            'manager/job_create',
307
            [
308
                // Localization Strings.
309
                'job_l10n' => Lang::get('manager/job_edit'),
310
                // Data.
311
                'manager' => $manager,
312
                'job' => $jobPoster,
313
                '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

313
                'form_action_url' => /** @scrutinizer ignore-call */ route('admin.jobs.update', $jobPoster),
Loading history...
314
            ]
315
        );
316
    }
317
318
    /**
319
     * Create a blank job poster for the specified manager
320
     *
321
     * @param  \App\Models\Manager $manager Incoming Manager object.
322
     * @return \Illuminate\Http\Response Job Create view
323
     */
324
    public function createAsManager(Manager $manager)
325
    {
326
        $jobPoster = new JobPoster();
327
        $jobPoster->manager_id = $manager->id;
328
329
        // Save manager-specific info to the job poster - equivalent to the intro step of the JPB.
330
        $divisionEn = $manager->getTranslation('division', 'en');
331
        $divisionFr = $manager->getTranslation('division', 'fr');
332
        $jobPoster->fill([
333
            'department_id' => $manager->user->department_id,
334
            'division' => ['en' => $divisionEn],
335
            'division' => ['fr' => $divisionFr],
336
        ]);
337
338
        $jobPoster->save();
339
340
        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

340
        return /** @scrutinizer ignore-call */ redirect()->route('manager.jobs.edit', $jobPoster->id);
Loading history...
341
    }
342
343
    /**
344
     * Update a resource in storage
345
     * NOTE: Only saves fields that are not on the react-built Job Poster Builder
346
     *
347
     * @param  \Illuminate\Http\Request $request   Incoming request object.
348
     * @param  \App\Models\JobPoster    $jobPoster Optional Job Poster object.
349
     * @return \Illuminate\Http\Response
350
     */
351
    public function store(Request $request, JobPoster $jobPoster)
352
    {
353
        // Don't allow edits for published Job Posters
354
        // Also check auth while we're at it.
355
        $this->authorize('update', $jobPoster);
356
        JobPosterValidator::validateUnpublished($jobPoster);
357
358
        $input = $request->input();
359
360
        if ($jobPoster->manager_id == null) {
361
            $jobPoster->manager_id = $request->user()->manager->id;
362
            $jobPoster->save();
363
        }
364
365
        if ($request->input('question')) {
366
            $validator = Validator::make($request->input('question'), [
367
                '*.question.*' => 'required|string',
368
            ], [
369
                'required' => Lang::get('validation.custom.job_poster_question.required'),
370
                'string' => Lang::get('validation.custom.job_poster_question.string')
371
            ]);
372
373
            if ($validator->fails()) {
374
                $request->session()->flash('errors', $validator->errors());
375
                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

375
                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

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

469
            fputcsv(/** @scrutinizer ignore-type */ $file, $line);
Loading history...
470
        }
471
        // Close open file.
472
        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

472
        fclose(/** @scrutinizer ignore-type */ $file);
Loading history...
473
474
        $headers = [
475
            'Content-Type' => 'text/csv',
476
            'Content-Disposition' => 'attachment; filename=' . $filename,
477
        ];
478
479
        return Response::download($filename, $filename, $headers);
480
    }
481
482
    /**
483
     * Build Job Poster's structured data
484
     *
485
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
486
     * @return array
487
     */
488
    protected function buildStructuredData(JobPoster $jobPoster)
489
    {
490
        $gocLang = Lang::get('common/goc');
491
492
        $jobLang = Lang::get('applicant/job_post');
493
494
        $essential = $jobPoster->criteria->filter(
495
            function ($value) {
496
                return $value->criteria_type->name == 'essential';
497
            }
498
        )->sortBy('id');
499
        $asset = $jobPoster->criteria->filter(
500
            function ($value) {
501
                return $value->criteria_type->name == 'asset';
502
            }
503
        )->sortBy('id');
504
505
        $skillsArray = [];
506
        foreach ($essential as $criterion) {
507
            $skillsArray[] = [
508
                'skill' => $criterion['skill']['name'],
509
                'level' => $criterion->level_name,
510
            ];
511
        }
512
        foreach ($asset as $criterion) {
513
            $skillsArray[] = [
514
                'skill' => $criterion['skill']['name'],
515
                'level' => $criterion->level_name,
516
            ];
517
        }
518
519
        $skillsString = '';
520
        if (!empty($skillsArray)) {
521
            $lastSkill = end($skillsArray);
522
            foreach ($skillsArray as $skillItem) {
523
                $skillsString .= $skillItem['skill'].' - '.$skillItem['level'].($skillItem == $lastSkill ? '.' : ', ');
524
            }
525
        }
526
527
        $benefitsString = '';
528
        if (is_array($jobLang['structured_data']['benefits'])) {
529
            foreach ($jobLang['structured_data']['benefits'] as $benefit) {
530
                $benefitsString .= $benefit.' ';
531
            }
532
        }
533
534
        $tasksString = '';
535
        if (is_array($jobPoster['job_poster_key_tasks'])) {
536
            $lastTask = end($jobPoster['job_poster_key_tasks']);
0 ignored issues
show
Unused Code introduced by
The assignment to $lastTask is dead and can be removed.
Loading history...
537
            foreach ($jobPoster['job_poster_key_tasks'] as $task) {
538
                $tasksString .= $task['description'].' '.($skillItem == $lastSkill ? '' : ' | ');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $lastSkill does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $skillItem does not seem to be defined for all execution paths leading up to this point.
Loading history...
539
            }
540
        }
541
542
        $securityClearanceString = $jobLang['structured_data']['security_clearance_requirement_level'].': '
543
        .$jobPoster['security_clearance']['value'].'. '
544
        .$jobLang['structured_data']['security_clearance_requirement_description'];
545
546
        $structuredData = [
547
            '@context' => 'https://schema.org',
548
            '@type' => 'JobPosting',
549
            '@id' => url()->current(),
0 ignored issues
show
Bug introduced by
The function url 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

549
            '@id' => /** @scrutinizer ignore-call */ url()->current(),
Loading history...
550
            'url' => url('/'),
551
            'inLanguage' => app()->getLocale(),
0 ignored issues
show
Bug introduced by
The function app 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

551
            'inLanguage' => /** @scrutinizer ignore-call */ app()->getLocale(),
Loading history...
552
            'applicantLocationRequirements' => [
553
                '@type' => 'Country',
554
                'sameAs' => 'https://www.wikidata.org/wiki/Q16',
555
                'name' => 'Canada'
556
            ],
557
            'applicationContact' => [
558
                '@type' => 'ContactPoint',
559
                'email' => '[email protected]'
560
            ],
561
            'baseSalary' => [
562
                '@type' => 'MonetaryAmount',
563
                'currency' => 'CAD',
564
                'minValue' => $jobPoster['salary_min'],
565
                'maxValue' => $jobPoster['salary_max'],
566
            ],
567
            'datePosted' => $jobPoster['open_date_time'],
568
            'employerOverview' => $jobLang['structured_data']['employer_overview'],
569
            'employmentType' => $jobLang['structured_data']['employment_type'],
570
            'estimatedSalary' => [
571
                '@type' => 'MonetaryAmount',
572
                'currency' => 'CAD',
573
                'minValue' => $jobPoster['salary_min'],
574
                'maxValue' => $jobPoster['salary_max']
575
            ],
576
            'hiringOrganization' => [
577
                '@type' => 'GovernmentOrganization',
578
                'name' => $jobPoster['manager']['user']['department']['name'],
579
                'parentOrganization' => [
580
                    '@type' => 'GovernmentOrganization',
581
                    'name' => $jobLang['structured_data']['parent_organization'],
582
                    'url' => $gocLang['logo_link'],
583
                    'logo' => asset('/images/logo_canada_colour.png'),
0 ignored issues
show
Bug introduced by
The function asset 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

583
                    'logo' => /** @scrutinizer ignore-call */ asset('/images/logo_canada_colour.png'),
Loading history...
584
                ]
585
            ],
586
            'industry' => $jobLang['structured_data']['industry'],
587
            'jobBenefits' => $benefitsString,
588
            'jobLocation' => [
589
                '@type' => 'Place',
590
                'address' => [
591
                    '@type' => 'PostalAddress',
592
                    'addressLocality' => $jobPoster['city'],
593
                    'addressRegion' => $jobPoster['province']['value'],
594
                    'addressCountry' => 'CA'
595
                ]
596
            ],
597
            'jobStartDate' => $jobPoster['start_date_time'],
598
            'qualifications' => $jobPoster['education'],
599
            'responsibilities' => $tasksString,
600
            'salaryCurrency' => 'CAD',
601
            'securityClearanceRequirement' => $securityClearanceString,
602
            'skills' => $skillsString,
603
            'specialCommitments' => $jobLang['structured_data']['special_commitments'],
604
            'title' => $jobPoster['title'],
605
            'totalJobOpenings' => '1',
606
            'validThrough' => $jobPoster['close_date_time'],
607
            'description' => $jobPoster['hire_impact'] ? nl2br($jobPoster['hire_impact']) : '',
608
        ];
609
610
        if ($jobPoster['remote_work_allowed'] == true) {
611
            $structuredData['jobLocationType'] = 'TELECOMMUTE';
612
        };
613
614
        return $structuredData;
615
    }
616
617
    /**
618
     * Redirects an applicant to the proper page to start or continue their application.
619
     *
620
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
621
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
622
     */
623
    protected function apply(JobPoster $jobPoster)
624
    {
625
        $applicantId = Auth::user()->applicant->id;
626
        // Check if the current user already has an application.
627
        $application = JobApplication::where('applicant_id', $applicantId)
628
            ->where('job_poster_id', $jobPoster->id)->first();
629
        $version2id = JobApplicationVersion::where('version', 2)->firstOrFail()->id;
630
        if ($application === null) {
631
            // If the job is still open, create a new application and redirect there.
632
            if ($jobPoster->isOpen()) {
633
                $newApplication = new JobApplication();
634
                $newApplication->job_poster_id = $jobPoster->id;
635
                $newApplication->applicant_id = $applicantId;
636
                $newApplication->application_status_id = ApplicationStatus::where('name', 'draft')->firstOrFail()->id;
637
                $newApplication->version_id = $version2id; // All applications created now should be version 2.
638
                $newApplication->save();
639
                $newApplication->attachSteps();
640
641
                return redirect(route('applications.timeline', $newApplication->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

641
                return /** @scrutinizer ignore-call */ redirect(route('applications.timeline', $newApplication->id));
Loading history...
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

641
                return redirect(/** @scrutinizer ignore-call */ route('applications.timeline', $newApplication->id));
Loading history...
642
            }
643
            // If the job is closed, redirect to Job Poster.
644
            return redirect(route('jobs.summary', $jobPoster->id));
645
        }
646
647
        // If the application exists, is a draft, and job is still open, redirect to the Application UI.
648
        if ($application->isDraft() && $jobPoster->isOpen()) {
649
            if ($application->version_id === $version2id) {
650
                return redirect(route('applications.timeline', $application->id));
651
            }
652
            return redirect(route('job.application.edit.1', $jobPoster->id));
653
        }
654
655
        // If the application exists but has already been submitted, or the job is closed,
656
        // redirect to the Application Preview.
657
        return redirect(route('applications.show', $application->id));
658
    }
659
}
660