Passed
Push — dependabot/npm_and_yarn/dev/st... ( 60dd2a...57fc25 )
by
unknown
07:12 queued 02:25
created

JobController::hrIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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\Support\Facades\Log;
8
use Illuminate\Http\Request;
9
use App\Http\Controllers\Controller;
10
use Carbon\Carbon;
11
use App\Models\JobPoster;
12
use App\Models\JobPosterQuestion;
13
use App\Models\Manager;
14
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
15
use App\Services\Validation\JobPosterValidator;
16
17
class JobController extends Controller
18
{
19
    /**
20
     * Display a listing of JobPosters.
21
     *
22
     * @return \Illuminate\Http\Response
23
     */
24
    public function index()
25
    {
26
        $now = Carbon::now();
27
28
        // Find published jobs that are currently open for applications.
29
        // Eager load required relationships: Department, Province, JobTerm.
30
        // Eager load the count of submitted applications, to prevent the relationship
31
        // from being actually loaded and firing off events.
32
        $jobs = JobPoster::where('open_date_time', '<=', $now)
33
            ->where('close_date_time', '>=', $now)
34
            ->where('published', true)
35
            ->with([
36
                'department',
37
                'province',
38
                'job_term',
39
            ])
40
            ->withCount([
41
                'submitted_applications',
42
            ])
43
            ->get();
44
        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

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

74
            $job->preview_link = LaravelLocalization::getLocalizedURL($chosen_lang, /** @scrutinizer ignore-call */ route('manager.jobs.show', $job));
Loading history...
75
            $job->edit_link = LaravelLocalization::getLocalizedURL($chosen_lang, route('manager.jobs.edit', $job));
76
        }
77
78
79
        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

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

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

162
                'href' => /** @scrutinizer ignore-call */ route('manager.jobs.edit', $jobPoster->id),
Loading history...
163
                'title' => $jobLang['apply']['edit_link_title'],
164
                'text' => $jobLang['apply']['edit_link_label'],
165
            ];
166
        } elseif (Auth::check() && $jobPoster->isOpen()) {
167
            $applyButton = [
168
                'href' => route('job.application.edit.1', $jobPoster->id),
169
                'title' => $jobLang['apply']['apply_link_title'],
170
                'text' => $jobLang['apply']['apply_link_label'],
171
            ];
172
        } elseif (Auth::guest() && $jobPoster->isOpen()) {
173
            $applyButton = [
174
                'href' => route('job.application.edit.1', $jobPoster->id),
175
                'title' => $jobLang['apply']['login_link_title'],
176
                'text' => $jobLang['apply']['login_link_label'],
177
            ];
178
        } else {
179
            $applyButton = [
180
                'href' => null,
181
                'title' => null,
182
                'text' => $jobLang['apply']['job_closed_label'],
183
            ];
184
        }
185
186
        $jpb_release_date = strtotime('2019-08-21 16:18:17');
187
        $job_created_at = strtotime($jobPoster->created_at);
188
189
        // If the job poster is created after the release of the JPB.
190
        // Then, render with updated poster template.
191
        // Else, render with old poster template.
192
        if ($job_created_at > $jpb_release_date) {
193
            // Updated job poster (JPB).
194
            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

194
            return /** @scrutinizer ignore-call */ view(
Loading history...
195
                'applicant/jpb_job_post',
196
                [
197
                    'job_post' => $jobLang,
198
                    'skill_template' => Lang::get('common/skills'),
199
                    'job' => $jobPoster,
200
                    'manager' => $jobPoster->manager,
201
                    'criteria' => $criteria,
202
                    'apply_button' => $applyButton,
203
                ]
204
            );
205
        } else {
206
            // Old job poster.
207
            return view(
208
                'applicant/job_post',
209
                [
210
                    'job_post' => $jobLang,
211
                    'manager' => $jobPoster->manager,
212
                    'manager_profile_photo_url' => '/images/user.png', // TODO get real photo.
213
                    'team_culture' => $jobPoster->manager->team_culture,
214
                    'work_environment' => $jobPoster->manager->work_environment,
215
                    'workplace_photos' => $workplacePhotos,
216
                    'job' => $jobPoster,
217
                    'criteria' => $criteria,
218
                    'apply_button' => $applyButton,
219
                    'skill_template' => Lang::get('common/skills'),
220
                ]
221
            );
222
        }
223
    }
224
225
    /**
226
     * Display the form for editing an existing Job Poster
227
     * Only allows editing fields that don't appear on the react-built Job Poster Builder.
228
     *
229
     * @param  \Illuminate\Http\Request $request   Incoming request object.
230
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
231
     * @return \Illuminate\Http\Response
232
     */
233
    public function edit(Request $request, JobPoster $jobPoster)
234
    {
235
        $manager = $jobPoster->manager;
236
237
        if ($jobPoster->job_poster_questions === null || $jobPoster->job_poster_questions->count() === 0) {
238
            $jobPoster->job_poster_questions()->saveMany($this->populateDefaultQuestions());
239
            $jobPoster->refresh();
240
        }
241
242
        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

242
        return /** @scrutinizer ignore-call */ view(
Loading history...
243
            'manager/job_create',
244
            [
245
                // Localization Strings.
246
                'job_l10n' => Lang::get('manager/job_edit'),
247
                // Data.
248
                'manager' => $manager,
249
                'job' => $jobPoster,
250
                '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

250
                'form_action_url' => /** @scrutinizer ignore-call */ route('admin.jobs.update', $jobPoster),
Loading history...
251
            ]
252
        );
253
    }
254
255
    /**
256
     * Create a blank job poster for the specified manager
257
     *
258
     * @param  \App\Models\Manager $manager Incoming Manager object.
259
     * @return \Illuminate\Http\Response Job Create view
260
     */
261
    public function createAsManager(Manager $manager)
262
    {
263
        $jobPoster = new JobPoster();
264
        $jobPoster->manager_id = $manager->id;
265
266
        // Save manager-specific info to the job poster - equivalent to the intro step of the JPB
267
        $divisionEn = $manager->translate('en') !== null ? $manager->translate('en')->division : null;
268
        $divisionFr = $manager->translate('fr') !== null ? $manager->translate('fr')->division : null;
269
        $jobPoster->fill([
270
            'department_id' => $manager->department_id,
271
            'en' => ['division' => $divisionEn],
272
            'fr' => ['division' => $divisionFr],
273
        ]);
274
275
        $jobPoster->save();
276
277
        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

277
        return /** @scrutinizer ignore-call */ redirect()->route('manager.jobs.edit', $jobPoster->id);
Loading history...
278
    }
279
280
    /**
281
     * Update a resource in storage
282
     * NOTE: Only saves fields that are not on the react-built Job Poster Builder
283
     *
284
     * @param  \Illuminate\Http\Request $request   Incoming request object.
285
     * @param  \App\Models\JobPoster    $jobPoster Optional Job Poster object.
286
     * @return \Illuminate\Http\Response
287
     */
288
    public function store(Request $request, JobPoster $jobPoster)
289
    {
290
        // Don't allow edits for published Job Posters
291
        // Also check auth while we're at it.
292
        $this->authorize('update', $jobPoster);
293
        JobPosterValidator::validateUnpublished($jobPoster);
294
295
        $input = $request->input();
296
297
        if ($jobPoster->manager_id == null) {
298
            $jobPoster->manager_id = $request->user()->manager->id;
299
            $jobPoster->save();
300
        }
301
302
        $this->fillAndSaveJobPosterQuestions($input, $jobPoster, true);
303
304
        return redirect(route('manager.jobs.show', $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

304
        return /** @scrutinizer ignore-call */ redirect(route('manager.jobs.show', $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

304
        return redirect(/** @scrutinizer ignore-call */ route('manager.jobs.show', $jobPoster->id));
Loading history...
305
    }
306
307
    /**
308
     * Fill Job Poster's questions and save
309
     *
310
     * @param  mixed[]               $input     Field values.
311
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
312
     * @param  boolean               $replace   Remove existing relationships.
313
     * @return void
314
     */
315
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace) : void
316
    {
317
        if ($replace) {
318
            $jobPoster->job_poster_questions()->delete();
319
        }
320
321
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
322
            return;
323
        }
324
325
        foreach ($input['question'] as $question) {
326
            $jobQuestion = new JobPosterQuestion();
327
            $jobQuestion->job_poster_id = $jobPoster->id;
328
            $jobQuestion->fill(
329
                [
330
                    'en' => [
331
                        'question' => $question['question']['en'],
332
                        'description' => $question['description']['en']
333
                    ],
334
                    'fr' => [
335
                        'question' => $question['question']['fr'],
336
                        'description' => $question['description']['fr']
337
                    ]
338
                ]
339
            );
340
            $jobPoster->save();
341
            $jobQuestion->save();
342
        }
343
    }
344
345
    /**
346
     * Get the localized default questions and add them to an array.
347
     *
348
     * @return mixed[]|void
349
     */
350
    protected function populateDefaultQuestions()
351
    {
352
        $defaultQuestions = [
353
            'en' => array_values(Lang::get('manager/job_create', [], 'en')['questions']),
354
            'fr' => array_values(Lang::get('manager/job_create', [], 'fr')['questions']),
355
        ];
356
357
        if (count($defaultQuestions['en']) !== count($defaultQuestions['fr'])) {
358
            Log::warning('There must be the same number of French and English default questions for a Job Poster.');
359
            return;
360
        }
361
362
        $jobQuestions = [];
363
364
        for ($i = 0; $i < count($defaultQuestions['en']); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
365
            $jobQuestion = new JobPosterQuestion();
366
            $jobQuestion->fill(
367
                [
368
                    'en' => [
369
                        'question' => $defaultQuestions['en'][$i],
370
                    ],
371
                    'fr' => [
372
                        'question' => $defaultQuestions['fr'][$i],
373
                    ]
374
                ]
375
            );
376
            $jobQuestions[] = $jobQuestion;
377
        }
378
379
        return $jobQuestions;
380
    }
381
}
382