aboutsummaryrefslogtreecommitdiff
path: root/lib/models/ConsultationSlot.php
blob: ab1dfa7ea3fe66d1bbb881cf7c346dfd94548b92 (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
<?php
/**
 * Representation of a consultation slot.
 *
 * @author  Jan-Hendrik Willms <tleilax+studip@gmail.com>
 * @license GPL2 or any later version
 * @since   Stud.IP 4.3
 * @property string slot_id database column
 * @property string id alias column for slot_id
 * @property string block_id database column
 * @property string start_time database column
 * @property string end_time database column
 * @property string note database column
 * @property SimpleORMapCollection bookings has_many ConsultationBooking
 * @property ConsultationBlock block belongs_to ConsultationBlock
 * @property SimpleORMapCollection events has_many EventData
 */
class ConsultationSlot extends SimpleORMap
{
    /**
     * Configures the model.
     * @param array  $config Configuration
     */
    protected static function configure($config = [])
    {
        $config['db_table'] = 'consultation_slots';

        $config['belongs_to']['block'] = [
            'class_name'  => ConsultationBlock::class,
            'foreign_key' => 'block_id',
        ];
        $config['has_many']['bookings'] = [
            'class_name'        => ConsultationBooking::class,
            'assoc_foreign_key' => 'slot_id',
            'on_store'          => 'store',
            'on_delete'         => 'delete',
        ];
        $config['has_many']['events'] = [
            'class_name'        => ConsultationEvent::class,
            'assoc_foreign_key' => 'slot_id',
            'on_delete'         => 'delete',
        ];

        $config['registered_callbacks']['before_create'][] = function (ConsultationSlot $slot) {
            $slot->updateEvents();
        };
        $config['registered_callbacks']['after_delete'][] = function ($slot) {
            $block = $slot->block;
            if ($block && count($block->slots) === 0) {
                $block->delete();
            }
        };

        $config['additional_fields']['has_bookings']['get'] = function ($slot) {
            return count($slot->bookings) > 0;
        };
        $config['additional_fields']['is_expired']['get'] = function ($slot) {
            return $slot->end_time < time();
        };

        parent::configure($config);
    }

    /**
     * Counts all slots of the given range.
     *
     * @param  Range $range   Range
     * @param  bool  $expired
     * @return int
     */
    public static function countByRange(Range $range, $expired = false)
    {
        $expired_condition = $expired
                           ? "end <= UNIX_TIMESTAMP()"
                           : "end > UNIX_TIMESTAMP()";

        $condition = "JOIN `consultation_blocks` USING (`block_id`)
                      WHERE `range_id` = :range_id
                        AND `range_type` = :range_type
                        AND {$expired_condition}";
        return self::countBySQL($condition, [
            ':range_id'   => $range->getRangeId(),
            ':range_type' => $range->getRangeType(),
        ]);
    }

    /**
     * Finds slots of the given teacher.
     *
     * @param Range  $range   Range
     * @param string $order   Desired order of items
     * @param bool   $expired Show expired items?
     * @return array
     */
    public static function findByRange(Range $range, $order = '', $expired = false)
    {
        $expired_condition = $expired
                           ? "end <= UNIX_TIMESTAMP()"
                           : "end > UNIX_TIMESTAMP()";

        $condition = "JOIN consultation_blocks USING (block_id)
                      WHERE range_id = :range_id
                        AND range_type = :range_type
                        AND {$expired_condition}
                      {$order}";
        return self::findBySQL($condition, [
            ':range_id'   => $range->getRangeId(),
            ':range_type' => $range->getRangeType(),
        ]);
    }

    /**
     * Find all occupied slots for a given user and teacher combination.
     *
     * @param string $user_id Id of the user
     * @param Range  $range   Range
     * @return array
     */
    public static function findOccupiedSlotsByUserAndRange($user_id, Range $range)
    {
        $condition = "JOIN consultation_blocks USING (block_id)
                      JOIN consultation_bookings USING (slot_id)
                      WHERE user_id = :user_id
                        AND range_id = :range_id
                        AND range_type = :range_type
                        AND end > UNIX_TIMESTAMP()
                      ORDER BY start_time ASC";
        return self::findBySQL($condition, [
            ':user_id'    => $user_id,
            ':range_id'   => $range->getRangeId(),
            ':range_type' => $range->getRangeType(),
        ]);
    }

    /**
     * Returns whether this slot is occupied (by a given user).
     *
     * @param  mixed $user_id Id of the user (optional)
     * @return boolean indicating whether the slot is occupied (by the given
     *                 user)
     */
    public function isOccupied($user_id = null)
    {
        return $user_id === null
             ? count($this->bookings) >= $this->block->size
             : (bool) $this->bookings->findOneBy('user_id', $user_id);
    }

    /**
     * Returns whether the slot is locked for bookings.
     *
     * @return bool
     */
    public function isLocked(): bool
    {
        return $this->block->lock_time
            && strtotime("-{$this->block->lock_time} hours", $this->block->start) < time();
    }

    /**
     * Creates a Stud.IP calendar event relating to the slot.
     *
     * @param  User $user User object to create the event for
     * @return EventData Created event
     */
    public function createEvent(User $user)
    {
        $event = new EventData();
        $event->uid = $this->createEventId($user);
        $event->author_id = $user->id;
        $event->editor_id = $user->id;
        $event->start     = $this->start_time;
        $event->end       = $this->end_time;
        $event->class     = 'PRIVATE';
        $event->priority  = 0;
        $event->location  = $this->block->room;
        $event->rtype     = 'SINGLE';
        $event->store();

        $calendar_event = new CalendarEvent();
        $calendar_event->range_id     = $user->id;
        $calendar_event->group_status = 0;
        $calendar_event->event_id     = $event->id;
        $calendar_event->store();

        return $event;
    }

    /**
     * Returns a unique event id.
     *
     * @param  User $user [description]
     * @return string unique event id
     */
    protected function createEventId(User $user)
    {
        $rand_id = md5(uniqid(self::class, true));
        return "Termin{$rand_id}-{$user->id}";
    }

    /**
     * Updates the teacher event that belongs to the slot. This will either be
     * set to be unoccupied, occupied by only one user or by a group of user.
     */
    public function updateEvents()
    {
        if ($this->isNew()) {
            return;
        }

        // If no range is associated, remove the event
        if (!$this->block->range) {
            $this->events->delete();
            return;
        }

        if (count($this->bookings) === 0 && !$this->block->calendar_events) {
            $this->events->delete();
            return;
        }

        // Get responsible user ids
        $responsible_ids = array_map(
            function (User $user) {
                return $user->id;
            },
            $this->block->responsible_persons
        );

        // Remove events for no longer responsible users
        foreach ($this->events as $event) {
            if (!in_array($event->user_id, $responsible_ids)) {
                $event->delete();
            }
        }

        // Add events for missing responsible users
        $missing = array_diff($responsible_ids, $this->events->pluck('user_id'));
        foreach ($missing as $user_id) {
            $user = User::find($user_id);
            if (!$user) {
                continue;
            }

            $event = $this->createEvent($user);
            ConsultationEvent::create([
                'slot_id'  => $this->id,
                'user_id'  => $user_id,
                'event_id' => $event->id,
            ]);
        }

        // Reset relation in order to account to the above changes
        $this->resetRelation('events');

        foreach ($this->events as $event) {
            setTempLanguage($event->user_id);

            $bookings = $this->bookings->filter(function (ConsultationBooking $booking) {
                return !$booking->isDeleted()
                    && $booking->user;
            });

            if (count($bookings) > 0) {
                $event->event->category_intern = 1;

                if (count($bookings) === 1) {
                    $booking = $bookings->first();

                    $event->event->summary = sprintf(
                        _('Termin mit %s'),
                        $booking->user ? $booking->user->getFullName() : _('unbekannt')
                    );
                    $event->event->description = $booking->reason;
                } else {
                    $event->event->summary = sprintf(
                        _('Termin mit %u Personen'),
                        count($bookings)
                    );
                    $event->event->description = implode("\n\n----\n\n", $bookings->map(function ($booking) {
                        $name = $booking->user ? $booking->user->getFullName() : _('unbekannt');
                        return "- {$name}:\n{$booking->reason}";
                    }));
                }
            } else {
                $event->event->category_intern = 9;
                $event->event->summary         = _('Freier Termin');
                $event->event->description     = _('Dieser Termin ist noch nicht belegt.');
            }

            $event->event->store();

            restoreLanguage();

        }
    }

    /**
     * Returns whether the given user may create a booking for this slot.
     */
    public function userMayCreateBookingForSlot(\User $user = null): bool
    {
        $user = $user ?? User::findCurrent();

        return ConsultationBooking::userMayCreateBookingForRange($this->block->range, $user)
            && !$this->isOccupied()
            && !$this->isLocked();
    }


    /**
     * @return string A string representation of the consultation slot.
     */
    public function __toString() : string
    {
        return sprintf(
            _('Termin am %1$s, %2$s von %3$s bis %4$s'),
            strftime('%A', $this->start_time),
            strftime('%x', $this->start_time),
            date('H:i', $this->start_time),
            date('H:i', $this->end_time)
        );
    }
}