Passed
Push — dev ( 17cc34...596d5a )
by Chris
03:59 queued 12s
created

JobController::populateDefaultQuestions()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 28
ccs 20
cts 20
cp 1
rs 9.7666
cc 3
nc 3
nop 0
crap 3
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
        $now = Carbon::now();
0 ignored issues
show
Unused Code introduced by
The assignment to $now is dead and can be removed.
Loading history...
35
36
        // Find published jobs that are currently open for applications.
37
        // Eager load required relationships: Department, Province, JobTerm.
38
        // Eager load the count of submitted applications, to prevent the relationship
39
        // from being actually loaded and firing off events.
40
        $jobs = JobPoster::where('internal_only', false)
41
            ->where('department_id', '!=', config('app.strategic_response_department_id'))
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

41
            ->where('department_id', '!=', /** @scrutinizer ignore-call */ config('app.strategic_response_department_id'))
Loading history...
42
            ->where('job_poster_status_id', JobPosterStatus::where('key', 'live')->first()->id)
43
            ->with([
44
                'department',
45
                'province',
46
                'job_term',
47
            ])
48
            ->withCount([
49
                'submitted_applications',
50
            ])
51
            ->get();
52
        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

52
        return /** @scrutinizer ignore-call */ view('applicant/job_index', [
Loading history...
53
            'job_index' => Lang::get('applicant/job_index'),
54
            'jobs' => $jobs
55
        ]);
56
    }
57
58
    /**
59
     * Display a listing of a manager's JobPosters.
60
     *
61
     * @return \Illuminate\Http\Response
62
     */
63
    public function managerIndex()
64
    {
65
        $manager = Auth::user()->manager;
66
67
        $jobs = JobPoster::where('manager_id', $manager->id)
68
            ->with('classification')
69
            ->withCount('submitted_applications')
70
            ->get();
71
72
        foreach ($jobs as &$job) {
73 1
            $chosen_lang = $job->chosen_lang;
74
75 1
            // Show chosen lang title if current title is empty.
76 1
            if (empty($job->title)) {
77 1
                $job->title = $job->getTranslation('title', $chosen_lang);
78 1
                $job->trans_required = true;
79
            }
80 1
81
            // Always preview and edit in the chosen language.
82 1
            $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

82
            $job->preview_link = LaravelLocalization::getLocalizedURL($chosen_lang, /** @scrutinizer ignore-call */ route('manager.jobs.show', $job));
Loading history...
83
            $job->edit_link = LaravelLocalization::getLocalizedURL($chosen_lang, route('manager.jobs.edit', $job));
84 1
        }
85
86
87
        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

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

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

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

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

289
        return /** @scrutinizer ignore-call */ view(
Loading history...
290
            'manager/job_create',
291 1
            [
292
                // Localization Strings.
293 1
                'job_l10n' => Lang::get('manager/job_edit'),
294 1
                // Data.
295
                'manager' => $manager,
296 1
                'job' => $jobPoster,
297 1
                '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

297
                'form_action_url' => /** @scrutinizer ignore-call */ route('admin.jobs.update', $jobPoster),
Loading history...
298 1
            ]
299 1
        );
300
    }
301
302 1
    /**
303
     * Create a blank job poster for the specified manager
304 1
     *
305
     * @param  \App\Models\Manager $manager Incoming Manager object.
306 1
     * @return \Illuminate\Http\Response Job Create view
307
     */
308 1
    public function createAsManager(Manager $manager)
309 1
    {
310
        $jobPoster = new JobPoster();
311 1
        $jobPoster->manager_id = $manager->id;
312 1
313 1
        // Save manager-specific info to the job poster - equivalent to the intro step of the JPB
314 1
        $divisionEn = $manager->getTranslation('division', 'en');
315
        $divisionFr = $manager->getTranslation('division', 'fr');
316
        $jobPoster->fill([
317 1
            'department_id' => $manager->user->department_id,
318
            'division' => ['en' => $divisionEn],
319 1
            'division' => ['fr' => $divisionFr],
320
        ]);
321 1
322
        $jobPoster->save();
323 1
324 1
        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

324
        return /** @scrutinizer ignore-call */ redirect()->route('manager.jobs.edit', $jobPoster->id);
Loading history...
325
    }
326
327
    /**
328 1
     * Update a resource in storage
329 1
     * NOTE: Only saves fields that are not on the react-built Job Poster Builder
330
     *
331
     * @param  \Illuminate\Http\Request $request   Incoming request object.
332 1
     * @param  \App\Models\JobPoster    $jobPoster Optional Job Poster object.
333 1
     * @return \Illuminate\Http\Response
334
     */
335
    public function store(Request $request, JobPoster $jobPoster)
336
    {
337 1
        // Don't allow edits for published Job Posters
338
        // Also check auth while we're at it.
339 1
        $this->authorize('update', $jobPoster);
340
        JobPosterValidator::validateUnpublished($jobPoster);
341 1
342
        $input = $request->input();
343 1
344 1
        if ($jobPoster->manager_id == null) {
345 1
            $jobPoster->manager_id = $request->user()->manager->id;
346
            $jobPoster->save();
347 1
        }
348
349 1
        if ($request->input('question')) {
350 1
            $validator = Validator::make($request->input('question'), [
351 1
                '*.question.*' => 'required|string',
352
            ], [
353 1
                'required' => Lang::get('validation.custom.job_poster_question.required'),
354 1
                'string' => Lang::get('validation.custom.job_poster_question.string')
355
            ]);
356
357 1
            if ($validator->fails()) {
358
                $request->session()->flash('errors', $validator->errors());
359 1
                return redirect(route('admin.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

359
                return /** @scrutinizer ignore-call */ redirect(route('admin.jobs.edit', $jobPoster->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

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

453
            fputcsv(/** @scrutinizer ignore-type */ $file, $line);
Loading history...
454
        }
455 6
        // Close open file.
456 6
        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

456
        fclose(/** @scrutinizer ignore-type */ $file);
Loading history...
457
458
        $headers = [
459
            'Content-Type' => 'text/csv',
460
            'Content-Disposition' => 'attachment; filename=' . $filename,
461
        ];
462
463
        return Response::download($filename, $filename, $headers);
464
    }
465
}
466