summaryrefslogtreecommitdiff
path: root/includes/model/Shifts_model.php
blob: 1fc7fe89406e832f4c19721a159e0a01b94a0d9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
<?php

use Engelsystem\Database\DB;
use Engelsystem\ShiftsFilter;
use Engelsystem\ShiftSignupState;

/**
 * @param array $angeltype
 * @return array
 */
function Shifts_by_angeltype($angeltype) {
    return DB::select('
        SELECT DISTINCT `Shifts`.* FROM `Shifts`
        JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`shift_id` = `Shifts`.`SID`
        WHERE `NeededAngelTypes`.`angel_type_id` = ?
        AND `NeededAngelTypes`.`count` > 0
        AND `Shifts`.`PSID` IS NULL
        
        UNION
        
        SELECT DISTINCT `Shifts`.* FROM `Shifts`
        JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`room_id` = `Shifts`.`RID`
        WHERE `NeededAngelTypes`.`angel_type_id` = ?
        AND `NeededAngelTypes`.`count` > 0
        AND NOT `Shifts`.`PSID` IS NULL
        ', [$angeltype['id'], $angeltype['id']]);
}

/**
 * Returns all shifts with a PSID (from frab import)
 */
function Shifts_from_frab() {
    return DB::select('SELECT * FROM `Shifts` WHERE `PSID` IS NOT NULL ORDER BY `start`');
}

/**
 * @param array $room
 * @return array
 */
function Shifts_by_room($room)
{
    return DB::select('SELECT * FROM `Shifts` WHERE `RID`=? ORDER BY `start`', [$room['RID']]);
}

/**
 * @param ShiftsFilter $shiftsFilter
 * @return array[]
 */
function Shifts_by_ShiftsFilter(ShiftsFilter $shiftsFilter)
{
    $sql = 'SELECT * FROM (
      SELECT DISTINCT `Shifts`.*, `ShiftTypes`.`name`, `Room`.`Name` AS `room_name`
      FROM `Shifts`
      JOIN `Room` USING (`RID`)
      JOIN `ShiftTypes` ON `ShiftTypes`.`id` = `Shifts`.`shifttype_id`
      JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`shift_id` = `Shifts`.`SID`
      WHERE `Shifts`.`RID` IN (' . implode(',', $shiftsFilter->getRooms()) . ')
      AND `start` BETWEEN ? AND ?
      AND `NeededAngelTypes`.`angel_type_id` IN (' . implode(',', $shiftsFilter->getTypes()) . ')
      AND `NeededAngelTypes`.`count` > 0
      AND `Shifts`.`PSID` IS NULL

      UNION

      SELECT DISTINCT `Shifts`.*, `ShiftTypes`.`name`, `Room`.`Name` AS `room_name`
      FROM `Shifts`
      JOIN `Room` USING (`RID`)
      JOIN `ShiftTypes` ON `ShiftTypes`.`id` = `Shifts`.`shifttype_id`
      JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`room_id`=`Shifts`.`RID`
      WHERE `Shifts`.`RID` IN (' . implode(',', $shiftsFilter->getRooms()) . ')
      AND `start` BETWEEN ? AND ?
      AND `NeededAngelTypes`.`angel_type_id` IN (' . implode(',', $shiftsFilter->getTypes()) . ')
      AND `NeededAngelTypes`.`count` > 0
      AND NOT `Shifts`.`PSID` IS NULL) AS tmp_shifts

      ORDER BY `start`';

    return DB::select(
        $sql,
        [
            $shiftsFilter->getStartTime(),
            $shiftsFilter->getEndTime(),
            $shiftsFilter->getStartTime(),
            $shiftsFilter->getEndTime(),
        ]
    );
}

/**
 * @param ShiftsFilter $shiftsFilter
 * @return array[]
 */
function NeededAngeltypes_by_ShiftsFilter(ShiftsFilter $shiftsFilter)
{
    $sql = '
      SELECT
          `NeededAngelTypes`.*,
          `Shifts`.`SID`,
          `AngelTypes`.`id`,
          `AngelTypes`.`name`,
          `AngelTypes`.`restricted`,
          `AngelTypes`.`no_self_signup`
      FROM `Shifts`
      JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`shift_id`=`Shifts`.`SID`
      JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id`
      WHERE `Shifts`.`RID` IN (' . implode(',', $shiftsFilter->getRooms()) . ')
      AND `start` BETWEEN ? AND ?
      AND `Shifts`.`PSID` IS NULL

      UNION

      SELECT
            `NeededAngelTypes`.*,
            `Shifts`.`SID`,
            `AngelTypes`.`id`,
            `AngelTypes`.`name`,
            `AngelTypes`.`restricted`,
            `AngelTypes`.`no_self_signup`
      FROM `Shifts`
      JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`room_id`=`Shifts`.`RID`
      JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id`
      WHERE `Shifts`.`RID` IN (' . implode(',', $shiftsFilter->getRooms()) . ')
      AND `start` BETWEEN ? AND ?
      AND NOT `Shifts`.`PSID` IS NULL';

    return DB::select(
        $sql,
        [
            $shiftsFilter->getStartTime(),
            $shiftsFilter->getEndTime(),
            $shiftsFilter->getStartTime(),
            $shiftsFilter->getEndTime(),
        ]
    );
}

/**
 * @param array $shift
 * @param array $angeltype
 * @return array|null
 */
function NeededAngeltype_by_Shift_and_Angeltype($shift, $angeltype)
{
    return DB::selectOne('
          SELECT
              `NeededAngelTypes`.*,
              `Shifts`.`SID`,
              `AngelTypes`.`id`,
              `AngelTypes`.`name`,
              `AngelTypes`.`restricted`,
              `AngelTypes`.`no_self_signup`
          FROM `Shifts`
          JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`shift_id`=`Shifts`.`SID`
          JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id`
          WHERE `Shifts`.`SID`=?
          AND `AngelTypes`.`id`=?
          AND `Shifts`.`PSID` IS NULL

          UNION

          SELECT
                `NeededAngelTypes`.*,
                `Shifts`.`SID`,
                `AngelTypes`.`id`,
                `AngelTypes`.`name`,
                `AngelTypes`.`restricted`,
                `AngelTypes`.`no_self_signup`
          FROM `Shifts`
          JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`room_id`=`Shifts`.`RID`
          JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id`
          WHERE `Shifts`.`SID`=?
          AND `AngelTypes`.`id`=?
          AND NOT `Shifts`.`PSID` IS NULL
      ',
        [
            $shift['SID'],
            $angeltype['id'],
            $shift['SID'],
            $angeltype['id']
        ]
    );
}

/**
 * @param ShiftsFilter $shiftsFilter
 * @return array
 */
function ShiftEntries_by_ShiftsFilter(ShiftsFilter $shiftsFilter)
{
    $sql = '
      SELECT
          `User`.`Nick`,
          `User`.`email`,
          `User`.`email_shiftinfo`,
          `User`.`Sprache`,
          `User`.`Gekommen`,
          `ShiftEntry`.`UID`,
          `ShiftEntry`.`TID`,
          `ShiftEntry`.`SID`,
          `ShiftEntry`.`Comment`,
          `ShiftEntry`.`freeloaded`
      FROM `Shifts`
      JOIN `ShiftEntry` ON `ShiftEntry`.`SID`=`Shifts`.`SID`
      JOIN `User` ON `ShiftEntry`.`UID`=`User`.`UID`
      WHERE `Shifts`.`RID` IN (' . implode(',', $shiftsFilter->getRooms()) . ')
      AND `start` BETWEEN ? AND ?
      ORDER BY `Shifts`.`start`';
    return DB::select(
        $sql,
        [
            $shiftsFilter->getStartTime(),
            $shiftsFilter->getEndTime(),
        ]
    );
}

/**
 * Check if a shift collides with other shifts (in time).
 *
 * @param array $shift
 * @param array $shifts
 * @return bool
 */
function Shift_collides($shift, $shifts)
{
    foreach ($shifts as $other_shift) {
        if ($shift['SID'] != $other_shift['SID']) {
            if (!($shift['start'] >= $other_shift['end'] || $shift['end'] <= $other_shift['start'])) {
                return true;
            }
        }
    }
    return false;
}

/**
 * Returns the number of needed angels/free shift entries for an angeltype.
 *
 * @param array   $needed_angeltype
 * @param array[] $shift_entries
 * @return int
 */
function Shift_free_entries($needed_angeltype, $shift_entries)
{
    $taken = 0;
    foreach ($shift_entries as $shift_entry) {
        if ($shift_entry['freeloaded'] == 0) {
            $taken++;
        }
    }
    return max(0, $needed_angeltype['count'] - $taken);
}

/**
 * Check if shift signup is allowed from the end users point of view (no admin like privileges)
 *
 * @param array      $user
 * @param array      $shift       The shift
 * @param array      $angeltype   The angeltype to which the user wants to sign up
 * @param array|null $user_angeltype
 * @param array|null $user_shifts List of the users shifts
 * @param array      $needed_angeltype
 * @param array[]    $shift_entries
 * @return ShiftSignupState
 */
function Shift_signup_allowed_angel(
    $user,
    $shift,
    $angeltype,
    $user_angeltype,
    $user_shifts,
    $needed_angeltype,
    $shift_entries
) {
    $free_entries = Shift_free_entries($needed_angeltype, $shift_entries);

    if (config('signup_requires_arrival') && !$user['Gekommen']) {
        return new ShiftSignupState(ShiftSignupState::SHIFT_ENDED, $free_entries);
    }

    if ($user_shifts == null) {
        $user_shifts = Shifts_by_user($user);
    }

    $signed_up = false;
    foreach ($user_shifts as $user_shift) {
        if ($user_shift['SID'] == $shift['SID']) {
            $signed_up = true;
            break;
        }
    }

    if ($signed_up) {
        // you cannot join if you already singed up for this shift
        return new ShiftSignupState(ShiftSignupState::SIGNED_UP, $free_entries);
    }

    if (time() > $shift['start']) {
        // you can only join if the shift is in future
        return new ShiftSignupState(ShiftSignupState::SHIFT_ENDED, $free_entries);
    }
    if ($free_entries == 0) {
        // you cannot join if shift is full
        return new ShiftSignupState(ShiftSignupState::OCCUPIED, $free_entries);
    }

    if ($user_angeltype == null) {
        $user_angeltype = UserAngelType_by_User_and_AngelType($user, $angeltype);
    }

    if (
        $user_angeltype == null
        || ($angeltype['no_self_signup'] == 1 && $user_angeltype != null)
        || ($angeltype['restricted'] == 1 && $user_angeltype != null && !isset($user_angeltype['confirm_user_id']))
    ) {
        // you cannot join if user is not of this angel type
        // you cannot join if you are not confirmed
        // you cannot join if angeltype has no self signup

        return new ShiftSignupState(ShiftSignupState::ANGELTYPE, $free_entries);
    }

    if (Shift_collides($shift, $user_shifts)) {
        // you cannot join if user alread joined a parallel or this shift
        return new ShiftSignupState(ShiftSignupState::COLLIDES, $free_entries);
    }

    // Hooray, shift is free for you!
    return new ShiftSignupState(ShiftSignupState::FREE, $free_entries);
}

/**
 * Check if an angeltype supporter can sign up a user to a shift.
 *
 * @param array   $needed_angeltype
 * @param array[] $shift_entries
 * @return ShiftSignupState
 */
function Shift_signup_allowed_angeltype_supporter($needed_angeltype, $shift_entries)
{
    $free_entries = Shift_free_entries($needed_angeltype, $shift_entries);
    if ($free_entries == 0) {
        return new ShiftSignupState(ShiftSignupState::OCCUPIED, $free_entries);
    }

    return new ShiftSignupState(ShiftSignupState::FREE, $free_entries);
}

/**
 * Check if an admin can sign up a user to a shift.
 *
 * @param array   $needed_angeltype
 * @param array[] $shift_entries
 * @return ShiftSignupState
 */
function Shift_signup_allowed_admin($needed_angeltype, $shift_entries)
{
    $free_entries = Shift_free_entries($needed_angeltype, $shift_entries);

    if ($free_entries == 0) {
        // User shift admins may join anybody in every shift
        return new ShiftSignupState(ShiftSignupState::ADMIN, $free_entries);
    }

    return new ShiftSignupState(ShiftSignupState::FREE, $free_entries);
}

/**
 * Check if an angel can sign up for given shift.
 *
 * @param array      $signup_user
 * @param array      $shift       The shift
 * @param array      $angeltype   The angeltype to which the user wants to sign up
 * @param array|null $user_angeltype
 * @param array|null $user_shifts List of the users shifts
 * @param array      $needed_angeltype
 * @param array[]    $shift_entries
 * @return ShiftSignupState
 */
function Shift_signup_allowed(
    $signup_user,
    $shift,
    $angeltype,
    $user_angeltype,
    $user_shifts,
    $needed_angeltype,
    $shift_entries
) {
    global $user, $privileges;

    if (in_array('user_shifts_admin', $privileges)) {
        return Shift_signup_allowed_admin($needed_angeltype, $shift_entries);
    }

    if (
        in_array('shiftentry_edit_angeltype_supporter', $privileges)
        && User_is_AngelType_supporter($user, $angeltype)
    ) {
        return Shift_signup_allowed_angeltype_supporter($needed_angeltype, $shift_entries);
    }

    return Shift_signup_allowed_angel(
        $signup_user,
        $shift,
        $angeltype,
        $user_angeltype,
        $user_shifts,
        $needed_angeltype,
        $shift_entries
    );
}

/**
 * Delete a shift by its external id.
 *
 * @param int $shift_psid
 */
function Shift_delete_by_psid($shift_psid)
{
    DB::delete('DELETE FROM `Shifts` WHERE `PSID`=?', [$shift_psid]);
}

/**
 * Delete a shift.
 *
 * @param int $shift_id
 */
function Shift_delete($shift_id)
{
    mail_shift_delete(Shift($shift_id));

    DB::delete('DELETE FROM `Shifts` WHERE `SID`=?', [$shift_id]);
}

/**
 * Update a shift.
 *
 * @param array $shift
 * @return int Updated row count
 */
function Shift_update($shift)
{
    global $user;
    $shift['name'] = ShiftType($shift['shifttype_id'])['name'];
    mail_shift_change(Shift($shift['SID']), $shift);

    return DB::update('
      UPDATE `Shifts` SET
      `shifttype_id` = ?,
      `start` = ?,
      `end` = ?,
      `RID` = ?,
      `title` = ?,
      `URL` = ?,
      `PSID` = ?,
      `edited_by_user_id` = ?,
      `edited_at_timestamp` = ?
      WHERE `SID` = ?
    ',
        [
            $shift['shifttype_id'],
            $shift['start'],
            $shift['end'],
            $shift['RID'],
            $shift['title'],
            $shift['URL'],
            $shift['PSID'],
            $user['UID'],
            time(),
            $shift['SID']
        ]
    );
}

/**
 * Update a shift by its external id.
 *
 * @param array $shift
 * @return bool|null
 * @throws Exception
 */
function Shift_update_by_psid($shift)
{
    $shift_source = DB::selectOne('SELECT `SID` FROM `Shifts` WHERE `PSID`=?', [$shift['PSID']]);

    if (empty($shift_source)) {
        throw new Exception('Shift not found.');
    }

    $shift['SID'] = $shift_source['SID'];
    return Shift_update($shift);
}

/**
 * Create a new shift.
 *
 * @param array $shift
 * @return int ID of the new created shift
 */
function Shift_create($shift)
{
    global $user;
    DB::insert('
          INSERT INTO `Shifts` (
              `shifttype_id`,
              `start`,
              `end`,
              `RID`,
              `title`,
              `URL`,
              `PSID`,
              `created_by_user_id`,
              `edited_at_timestamp`,
              `created_at_timestamp`
          )
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ',
        [
            $shift['shifttype_id'],
            $shift['start'],
            $shift['end'],
            $shift['RID'],
            $shift['title'],
            $shift['URL'],
            $shift['PSID'],
            $user['UID'],
            time(),
            time(),
        ]
    );

    return DB::getPdo()->lastInsertId();
}

/**
 * Return users shifts.
 *
 * @param array $user
 * @param bool  $include_freeload_comments
 * @return array
 */
function Shifts_by_user($user, $include_freeload_comments = false)
{
    return DB::select('
          SELECT `ShiftTypes`.`id` AS `shifttype_id`, `ShiftTypes`.`name`,
          `ShiftEntry`.`id`, `ShiftEntry`.`SID`, `ShiftEntry`.`TID`, `ShiftEntry`.`UID`, `ShiftEntry`.`freeloaded`, `ShiftEntry`.`Comment`,
          ' . ($include_freeload_comments ? '`ShiftEntry`.`freeload_comment`, ' : '') . '
          `Shifts`.*, `Room`.*
          FROM `ShiftEntry`
          JOIN `Shifts` ON (`ShiftEntry`.`SID` = `Shifts`.`SID`)
          JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`)
          JOIN `Room` ON (`Shifts`.`RID` = `Room`.`RID`)
          WHERE `UID` = ?
          ORDER BY `start`
      ',
        [
            $user['UID']
        ]
    );
}

/**
 * Returns Shift by id.
 *
 * @param int $shift_id Shift  ID
 * @return array|null
 */
function Shift($shift_id)
{
    $result = DB::selectOne('
      SELECT `Shifts`.*, `ShiftTypes`.`name`
      FROM `Shifts`
      JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`)
      WHERE `SID`=?', [$shift_id]);

    if (empty($result)) {
        return null;
    }

    $shiftsEntry_source = DB::select('
        SELECT `id`, `TID` , `UID` , `freeloaded`
        FROM `ShiftEntry`
        WHERE `SID`=?', [$shift_id]);

    $result['ShiftEntry'] = $shiftsEntry_source;
    $result['NeedAngels'] = [];

    $angelTypes = NeededAngelTypes_by_shift($shift_id);
    foreach ($angelTypes as $type) {
        $result['NeedAngels'][] = [
            'TID'        => $type['angel_type_id'],
            'count'      => $type['count'],
            'restricted' => $type['restricted'],
            'taken'      => $type['taken']
        ];
    }

    return $result;
}

/**
 * Returns all shifts with needed angeltypes and count of subscribed jobs.
 *
 * @return array
 */
function Shifts()
{
    $shifts_source = DB::select('
        SELECT `ShiftTypes`.`name`, `Shifts`.*, `Room`.`RID`, `Room`.`Name` AS `room_name`
        FROM `Shifts`
        JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`)
        JOIN `Room` ON `Room`.`RID` = `Shifts`.`RID`
    ');

    foreach ($shifts_source as &$shift) {
        $needed_angeltypes = NeededAngelTypes_by_shift($shift['SID']);
        $shift['angeltypes'] = $needed_angeltypes;
    }

    return $shifts_source;
}