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

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

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

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

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

306
        return /** @scrutinizer ignore-call */ redirect(route('manager.jobs.show', $jobPoster->id));
Loading history...
307
    }
308
309
    /**
310
     * Fill Job Poster's questions and save
311
     *
312
     * @param  mixed[]               $input     Field values.
313
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
314
     * @param  boolean               $replace   Remove existing relationships.
315
     * @return void
316
     */
317
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace) : void
318
    {
319
        if ($replace) {
320
            $jobPoster->job_poster_questions()->delete();
321
        }
322
323
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
324
            return;
325
        }
326
327
        foreach ($input['question'] as $question) {
328
            $jobQuestion = new JobPosterQuestion();
329
            $jobQuestion->job_poster_id = $jobPoster->id;
330
            $jobQuestion->fill(
331
                [
332
                    'en' => [
333
                        'question' => $question['question']['en'],
334
                        'description' => $question['description']['en']
335
                    ],
336
                    'fr' => [
337
                        'question' => $question['question']['fr'],
338
                        'description' => $question['description']['fr']
339
                    ]
340
                ]
341
            );
342
            $jobPoster->save();
343
            $jobQuestion->save();
344
        }
345
    }
346
347
    /**
348
     * Get the localized default questions and add them to an array.
349
     *
350
     * @return mixed[]|void
351
     */
352
    protected function populateDefaultQuestions()
353
    {
354
        $defaultQuestions = [
355
            'en' => array_values(Lang::get('manager/job_create', [], 'en')['questions']),
356
            'fr' => array_values(Lang::get('manager/job_create', [], 'fr')['questions']),
357
        ];
358
359
        if (count($defaultQuestions['en']) !== count($defaultQuestions['fr'])) {
360
            Log::warning('There must be the same number of French and English default questions for a Job Poster.');
361
            return;
362
        }
363
364
        $jobQuestions = [];
365
366
        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...
367
            $jobQuestion = new JobPosterQuestion();
368
            $jobQuestion->fill(
369
                [
370
                    'en' => [
371
                        'question' => $defaultQuestions['en'][$i],
372
                    ],
373
                    'fr' => [
374
                        'question' => $defaultQuestions['fr'][$i],
375
                    ]
376
                ]
377
            );
378
            $jobQuestions[] = $jobQuestion;
379
        }
380
381
        return $jobQuestions;
382
    }
383
}
384