Completed
Push — master ( 304ca2...c09f30 )
by Patrick
01:40
created

ShiftAPI::forceEmpty()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 3
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
1
<?php
2
class ShiftAPI extends VolunteerAPI
3
{
4
    use Processor;
5
6
    public function __construct()
7
    {
8
        parent::__construct('shifts');
9
    }
10
11
    public function setup($app)
12
    {
13
        parent::setup($app);
14
        $app->post('/Actions/CreateGroup', array($this, 'createGroup'));
15
        $app->post('/Actions/NewGroup', array($this, 'newGroup'));
16
        $app->post('/Actions/DeleteGroup', array($this, 'deleteGroup'));
17
        $app->post('/{shift}/Actions/Signup[/]', array($this, 'signup'));
18
        $app->post('/{shift}/Actions/Abandon[/]', array($this, 'abandon'));
19
        $app->post('/{shift}/Actions/Approve[/]', array($this, 'approvePending'));
20
        $app->post('/{shift}/Actions/Disapprove[/]', array($this, 'disapprovePending')); 
21
        $app->post('/{shift}/Actions/StartGroupSignup', array($this, 'startGroupSignup'));
22
        $app->post('/{shift}/Actions/GenerateGroupLink', array($this, 'generateGroupLink'));
23
        $app->post('/{shift}/Actions/ForceShiftEmpty[/]', array($this, 'forceEmpty'));
24
    }
25
26
    protected function canCreate($request)
27
    {
28
        if($this->isVolunteerAdmin($request))
29
        {
30
            return true;
31
        }
32
        //TODO give access to department lead
33
        return false;
34
    }
35
36
    protected function canUpdate($request, $entity)
37
    {
38
 	if($this->isVolunteerAdmin($request))
39
        {
40
            return true;
41
        }
42
        return $this->isUserDepartmentLead($entity['departmentID'], $this->user);
43
    }
44
45
    protected function canDelete($request, $entity)
46
    {
47
        return $this->canUpdate($request, $entity);
48
    }
49
50
    protected function processEntry($entry, $request)
51
    {
52
        return $this->processShift($entry, $request);
53
    }
54
55
    protected function genUUID()
56
    {
57
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
58
            // 32 bits for "time_low"
59
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
60
61
            // 16 bits for "time_mid"
62
            mt_rand(0, 0xffff),
63
64
            // 16 bits for "time_hi_and_version",
65
            // four most significant bits holds version number 4
66
            mt_rand(0, 0x0fff) | 0x4000,
67
68
            // 16 bits, 8 bits for "clk_seq_hi_res",
69
            // 8 bits for "clk_seq_low",
70
            // two most significant bits holds zero and one for variant DCE1.1
71
            mt_rand(0, 0x3fff) | 0x8000,
72
73
            // 48 bits for "node"
74
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
75
        );
76
    }
77
78
    public function createGroup($request, $response)
79
    {
80
        $array = $request->getParsedBody();
81
        $count = count($array);
82
        $entArray = array();
83
        $uuid = $this->genUUID();
84
        $dataTable = $this->getDataTable();
85
        //User must be able to edit all shifts
86
        for($i = 0; $i < $count; $i++)
87
        {
88
            $filter = $this->getFilterForPrimaryKey($array[$i]);
89
            $entity = $dataTable->read($filter);
90
            if($entity === false || !isset($entity[0]))
91
            {
92
                return $response->withStatus(404);
93
            }
94
            $entity = $entity[0];
95
            if(!$this->canUpdate($request, $entity))
96
            {
97
                return $response->withStatus(401);
98
            }
99
            $entity['groupID'] = $uuid;
100
            array_push($entArray, $entity);
101
        }
102
        //If we got here we can update them all
103
        $myRet = true;
104
        $errors = array();
105
        for($i = 0; $i < $count; $i++)
106
        {
107
            $filter = $this->getFilterForPrimaryKey($array[$i]);
108
            $ret = $dataTable->update($filter, $entArray[$i]);
109
            if($ret === false)
110
            {
111
               $myRet = false;
112
               array_push($errors, $array[$i]);
113
            }
114
        }
115
        if($myRet)
116
        {
117
            return $response->withJson($myRet);
118
        }
119
        else
120
        {
121
            return $response->withJson(array('res'=>$myRet, 'errors'=>$errors));
122
        }
123
    }
124
125
    public function newGroup($request, $response)
126
    {
127
        if(!$this->canCreate($request))
128
        {
129
            return $response->withStatus(401);
130
        }
131
        $data = $request->getParsedBody();
132
        $shift = array();
133
        $shift['groupID'] = $this->genUUID();
134
        $shift['departmentID'] = $data['groupDepartmentID'];
135
        $shift['earlyLate'] = $data['groupEarlyLate'];
136
        $shift['enabled'] = $data['groupEnabled'];
137
        $shift['endTime'] = $data['groupEndTime'];
138
        $shift['eventID'] = $data['groupEvent'];
139
        $shift['name'] = $data['groupName'];
140
        $shift['startTime'] = $data['groupStartTime'];
141
        $dataTable = $this->getDataTable();
142
        $ret = true;
143
        foreach($data['roles'] as $role=>$count)
144
        {
145
            $count = intval($count);
146
            for($i = 0; $i < $count; $i++)
147
            {
148
                $shift['roleID'] = $role;
149
                if($dataTable->create($shift) === false)
150
                {
151
                    $ret = false;
152
                }
153
            }
154
        }
155
        return $response->withJSON($ret);
156
    }
157
158
    public function deleteGroup($request, $response)
159
    {
160
        $data = $request->getParsedBody();
161
        $dataTable = $this->getDataTable();
162
        $filter = new \Data\Filter('groupID eq '.$data['groupID']);
163
        $entities = $dataTable->read($filter);
164
        if(empty($entities))
165
        {
166
            return $response->withStatus(404);
167
        }
168
        if(!$this->canUpdate($request, $entities[0]))
169
        {
170
            return $response->withStatus(401);
171
        }
172
        $res = $dataTable->delete($filter);
173
        if($res)
174
        {
175
            return $response->withJSON($res);
176
        }
177
        return $response->withJSON($res, 500);
178
    }
179
180
    public function signup($request, $response, $args)
181
    {
182
        $this->validateLoggedIn($request);
183
        $shiftId = $args['shift'];
184
        $dataTable = $this->getDataTable();
185
        $filter = $this->getFilterForPrimaryKey($shiftId);
186
        $entity = $dataTable->read($filter);
187
        if(empty($entity))
188
        {
189
            return $response->withStatus(404);
190
        }
191
        $entity = $entity[0];
192 View Code Duplication
        if(isset($entity['participant']) && strlen($entity['participant']) > 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
193
        {
194
            return $response->withStatus(401);
195
        }
196
        $shift = new \VolunteerShift($shiftId, $entity);
197
        $entity = $this->processShift($entity, $request);
198
        if(isset($entity['minShifts']) && $entity['minShifts'] > 0)
199
        {
200
          $shift->makeCopy($dataTable);
201
        }
202
        if(isset($entity['overlap']) && $entity['overlap'])
203
        {
204
            $overlaps = $shift->findOverlaps($this->user->uid);
205
            $count = count($overlaps);
206
            $leads = array();
207
            for($i = 0; $i < $count; $i++)
208
            {
209
                $dept = new \VolunteerDepartment($overlaps[$i]->departmentID);
210
                $leads = array_merge($leads, $dept->getLeadEmails());
211
                $overlaps[$i]->status = 'pending';
212
                $tmp = new \Data\Filter('_id eq '.$overlaps[$i]->{'_id'});
213
                $res = $dataTable->update($tmp, $overlaps[$i]);
214
                if($res === false)
215
                {
216
                    return $response->withJSON(array('err'=>'Unable to update overlap with id '.$overlaps[$i]->{'_id'}));
217
                }
218
            }
219
            $dept = new \VolunteerDepartment($entity['departmentID']);
220
            $leads = array_merge($leads, $dept->getLeadEmails());
221
            $leads = array_unique($leads);
222
            $entity['participant'] = $this->user->uid;
223
            $entity['status'] = 'pending';
224
            $profile = new \VolunteerProfile($this->user->uid);
225
            $email = new \Emails\TwoShiftsAtOnceEmail($profile);
226
            $email->addLeads($leads);
227
            $emailProvider = \EmailProvider::getInstance();
228
            if($emailProvider->sendEmail($email) === false)
229
            {
230
                throw new \Exception('Unable to send duplicate email!');
231
            }
232
            return $response->withJSON($dataTable->update($filter, $entity));
233
        }
234 View Code Duplication
        if(isset($entity['available']) && $entity['available'])
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
235
        {
236
            $entity['participant'] = $this->user->uid;
237
            $entity['status'] = 'filled';
238
            return $response->withJSON($dataTable->update($filter, $entity));
239
        }
240 View Code Duplication
        if(isset($entity['status']) && $entity['status'] === 'groupPending')
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
241
        {
242
            $entity['participant'] = $this->user->uid;
243
            $entity['status'] = 'filled';
244
            return $response->withJSON($dataTable->update($filter, $entity));
245
        }
246
        print_r($entity); die();
247
    }
248
249
    public function abandon($request, $response, $args)
250
    {
251
        $this->validateLoggedIn($request);
252
        $shiftId = $args['shift'];
253
        $dataTable = $this->getDataTable();
254
        $filter = $this->getFilterForPrimaryKey($shiftId);
255
        $entity = $dataTable->read($filter);
256
        if(empty($entity))
257
        {
258
            return $response->withStatus(404);
259
        }
260
        $entity = $entity[0];
261
        if(!isset($entity['participant']) || $entity['participant'] !== $this->user->uid)
262
        {
263
            return $response->withStatus(401);
264
        }
265
        $entity['participant'] = '';
266
        $entity['status'] = 'unfilled';
267
        return $response->withJSON($dataTable->update($filter, $entity));
268
    }
269
270
    public function approvePending($request, $response, $args)
271
    {
272
        if(!$this->canCreate($request))
273
        {
274
            return $response->withStatus(401);
275
        }
276
        $shiftId = $args['shift'];
277
        $dataTable = $this->getDataTable();
278
        $filter = $this->getFilterForPrimaryKey($shiftId);
279
        $entity = $dataTable->read($filter);
280
        if(empty($entity))
281
        {
282
            return $response->withStatus(404);
283
        }
284
        $entity = $entity[0];
285
        $entity['status'] = 'filled';
286
        return $response->withJSON($dataTable->update($filter, $entity));
287
    }
288
289
    public function disapprovePending($request, $response, $args)
290
    {
291
        if(!$this->canCreate($request))
292
        {
293
            return $response->withStatus(401);
294
        }
295
        $shiftId = $args['shift'];
296
        $dataTable = $this->getDataTable();
297
        $filter = $this->getFilterForPrimaryKey($shiftId);
298
        $entity = $dataTable->read($filter);
299
        if(empty($entity))
300
        {
301
            return $response->withStatus(404);
302
        }
303
        $entity['participant'] = '';
304
        $entity['status'] = 'unfilled';
305
        $profile = new \VolunteerProfile($this->user->uid);
306
        $email = new \Emails\PendingRejectedEmail($profile);
307
        $email->setShift($entity);
308
        $emailProvider = \EmailProvider::getInstance();
309
        if($emailProvider->sendEmail($email) === false)
310
        {
311
            throw new \Exception('Unable to send duplicate email!');
312
        }
313
        return $response->withJSON($dataTable->update($filter, $entity));
314
    }
315
316
    public function startGroupSignup($request, $response, $args)
317
    {
318
        $this->validateLoggedIn($request);
319
        $shiftId = $args['shift'];
320
        $dataTable = $this->getDataTable();
321
        $filter = $this->getFilterForPrimaryKey($shiftId);
322
        $entity = $dataTable->read($filter);
323
        if(empty($entity))
324
        {
325
            return $response->withStatus(404);
326
        }
327
        $entity = $entity[0];
328 View Code Duplication
        if(isset($entity['participant']) && strlen($entity['participant']) > 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
329
        {
330
            return $response->withStatus(401);
331
        }
332
        $filter = new \Data\Filter('groupID eq '.$entity['groupID'].' and enabled eq true');
333
        $entities = $dataTable->read($filter);
334
        $count = count($entities);
335
        $dept = new \VolunteerDepartment($entity['departmentID']);
336
        $res = array();
337
        $res['department'] = $dept->departmentName;
0 ignored issues
show
Bug introduced by
The property departmentName does not seem to exist in VolunteerDepartment.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
338
        $res['earlyLate'] = $entity['earlyLate'];
339
        $res['endTime'] = $entity['endTime'];
340
        $res['eventID'] = $entity['eventID'];
341
        $res['name'] = $entity['name'];
342
        $res['startTime'] = $entity['startTime'];
343
        $res['groupID'] = $entity['groupID'];
344
        $res['shifts'] = array();
345
        $roles = array();
346
        for($i = 0; $i < $count; $i++)
347
        {
348 View Code Duplication
            if(isset($entities[$i]['status']) && ($entities[$i]['status'] === 'filled' || $entities[$i]['status'] === 'pending'))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
349
            {
350
                continue;
351
            }
352
            if(!isset($roles[$entities[$i]['roleID']]))
353
            {
354
                $roles[$entities[$i]['roleID']] = new \VolunteerRole($entities[$i]['roleID']);
355
            }
356
            $role = $roles[$entities[$i]['roleID']];
357
            $entities[$i]['role'] = $role->display_name;
358
            array_push($res['shifts'], $entities[$i]);
359
        }
360
        return $response->withJSON($res);
361
    }
362
363
    public function generateGroupLink($request, $response, $args)
364
    {
365
        $this->validateLoggedIn($request);
366
        $shiftId = $args['shift'];
367
        $dataTable = $this->getDataTable();
368
        $filter = $this->getFilterForPrimaryKey($shiftId);
369
        $entity = $dataTable->read($filter);
370
        if(empty($entity))
371
        {
372
            return $response->withStatus(404);
373
        }
374
        $entity = $entity[0];
375 View Code Duplication
        if(isset($entity['participant']) && strlen($entity['participant']) > 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
376
        {
377
            return $response->withStatus(401);
378
        }
379
        $data = $request->getParsedBody();
380
        $myShift = $data['myshift'];
381
        $roles = array();
382
        foreach($data as $key => $value)
383
        {
384
            if(substr($key, 0, 6) === "roles.")
385
            {
386
                $roles[substr($key, 6)] = $value;
387
            }
388
        }
389
        $filter = new \Data\Filter('groupID eq '.$entity['groupID'].' and enabled eq true');
390
        $entities = $dataTable->read($filter);
391
        $count = count($entities);
392
        $uuid = $this->genUUID();
393
        for($i = 0; $i < $count; $i++)
394
        {
395 View Code Duplication
            if(isset($entities[$i]['status']) && ($entities[$i]['status'] === 'filled' || $entities[$i]['status'] === 'pending'))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
396
            {
397
                $entities[$i] = false;
398
                continue;
399
            }
400
            if((string)$entities[$i]['_id'] === (string)new \MongoDB\BSON\ObjectId($myShift))
401
            {
402
                $entities[$i]['participant'] = $this->user->uid;
403
                $entities[$i]['status'] = 'filled';
404
                $entities[$i]['signupLink'] = $uuid;
405
            }
406
            else if(isset($roles[$entities[$i]['roleID']]))
407
            {
408
                $entities[$i]['status'] = 'groupPending';
409
                $entities[$i]['signupLink'] = $uuid;
410
                $roles[$entities[$i]['roleID']]--;
411
                if($roles[$entities[$i]['roleID']] === 0)
412
                {
413
                    unset($roles[$entities[$i]['roleID']]);
414
                }
415
            }
416
            else
417
            {
418
                $entities[$i] = false;
419
            }
420
        }
421
        if(count($roles) !== 0)
422
        {
423
            throw new \Exception('Not enough shifts to fullfill requests');
424
        }
425
        for($i = 0; $i < $count; $i++)
426
        {
427
            if($entities[$i] === false)
428
            {
429
                continue;
430
            }
431
            $filter = new \Data\Filter('_id eq '.$entities[$i]['_id']);
432
            $res = $dataTable->update($filter, $entities[$i]);
433
            if($res === false)
434
            {
435
                throw new \Exception('Not able to save shift '.$entities[$i]['_id']);
436
            }
437
        }
438
        return $response->withJSON(array('uuid' => $uuid));
439
    }
440
441
    function forceEmpty($request, $response, $args)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
442
    {
443
        $this->validateLoggedIn($request);
444
        $shiftId = $args['shift'];
445
        $dataTable = $this->getDataTable();
446
        $filter = $this->getFilterForPrimaryKey($shiftId);
447
        $entity = $dataTable->read($filter);
448
        if(empty($entity))
449
        {
450
            return $response->withStatus(404);
451
        }
452
        $entity = $entity[0];
453
        if(!$this->canUpdate($request, $entity))
454
        {
455
            return $response->withStatus(401);
456
        }
457
        $entity['participant'] = '';
458
        $entity['status'] = 'unfilled';
459
        return $response->withJSON($dataTable->update($filter, $entity));
460
    }
461
}
462