summaryrefslogtreecommitdiff
path: root/includes/pages/schedule/ImportSchedule.php
blob: 136f18168e381aa3eec18f3bd7c491910096e5c3 (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
<?php

declare(strict_types=1);

namespace Engelsystem\Controllers\Admin\Schedule;

use Carbon\Carbon;
use Engelsystem\Controllers\BaseController;
use Engelsystem\Helpers\Schedule\Event;
use Engelsystem\Helpers\Schedule\Room;
use Engelsystem\Helpers\Schedule\Schedule;
use Engelsystem\Helpers\Schedule\XmlParser;
use Engelsystem\Http\Request;
use Engelsystem\Http\Response;
use Engelsystem\Models\Shifts\Schedule as ScheduleUrl;
use Engelsystem\Models\Shifts\ScheduleShift;
use ErrorException;
use GuzzleHttp\Client as GuzzleClient;
use Illuminate\Database\Connection as DatabaseConnection;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Collection as DatabaseCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Psr\Log\LoggerInterface;
use stdClass;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class ImportSchedule extends BaseController
{
    /** @var DatabaseConnection */
    protected $db;

    /** @var LoggerInterface */
    protected $log;

    /** @var array */
    protected $permissions = [
        'schedule.import',
    ];

    /** @var XmlParser */
    protected $parser;

    /** @var Response */
    protected $response;

    /** @var SessionInterface */
    protected $session;

    /** @var string */
    protected $url = '/admin/schedule';

    /** @var GuzzleClient */
    protected $guzzle;

    /**
     * @param Response           $response
     * @param SessionInterface   $session
     * @param GuzzleClient       $guzzle
     * @param XmlParser          $parser
     * @param DatabaseConnection $db
     * @param LoggerInterface    $log
     */
    public function __construct(
        Response $response,
        SessionInterface $session,
        GuzzleClient $guzzle,
        XmlParser $parser,
        DatabaseConnection $db,
        LoggerInterface $log
    ) {
        $this->guzzle = $guzzle;
        $this->parser = $parser;
        $this->response = $response;
        $this->session = $session;
        $this->db = $db;
        $this->log = $log;
    }

    /**
     * @return Response
     */
    public function index(): Response
    {
        return $this->response->withView(
            'admin/schedule/index.twig',
            [
                'errors'      => $this->getFromSession('errors'),
                'success'     => $this->getFromSession('success'),
                'shift_types' => $this->getShiftTypes(),
            ]
        );
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function loadSchedule(Request $request): Response
    {
        try {
            /**
             * @var Event[]     $newEvents
             * @var Event[]     $changeEvents
             * @var Event[]     $deleteEvents
             * @var Room[]      $newRooms
             * @var int         $shiftType
             * @var ScheduleUrl $scheduleUrl
             * @var Schedule    $schedule
             * @var int         $minutesBefore
             * @var int         $minutesAfter
             */
            list(
                $newEvents,
                $changeEvents,
                $deleteEvents,
                $newRooms,
                $shiftType,
                $scheduleUrl,
                $schedule,
                $minutesBefore,
                $minutesAfter
                ) = $this->getScheduleData($request);
        } catch (ErrorException $e) {
            return back()->with('errors', [$e->getMessage()]);
        }

        return $this->response->withView(
            'admin/schedule/load.twig',
            [
                'errors'         => $this->getFromSession('errors'),
                'schedule_url'   => $scheduleUrl->url,
                'shift_type'     => $shiftType,
                'minutes_before' => $minutesBefore,
                'minutes_after'  => $minutesAfter,
                'schedule'       => $schedule,
                'rooms'          => [
                    'add' => $newRooms,
                ],
                'shifts'         => [
                    'add'    => $newEvents,
                    'update' => $changeEvents,
                    'delete' => $deleteEvents,
                ],
            ]
        );
    }

    /**
     * @param Request $request
     *
     * @return Response
     */
    public function importSchedule(Request $request): Response
    {
        try {
            /**
             * @var Event[]     $newEvents
             * @var Event[]     $changeEvents
             * @var Event[]     $deleteEvents
             * @var Room[]      $newRooms
             * @var int         $shiftType
             * @var ScheduleUrl $scheduleUrl
             */
            list(
                $newEvents,
                $changeEvents,
                $deleteEvents,
                $newRooms,
                $shiftType,
                $scheduleUrl
                ) = $this->getScheduleData($request);
        } catch (ErrorException $e) {
            return back()->with('errors', [$e->getMessage()]);
        }

        $this->log('Started schedule "{schedule}" import', ['schedule' => $scheduleUrl->url]);

        foreach ($newRooms as $room) {
            $this->createRoom($room);
        }

        $rooms = $this->getAllRooms();
        foreach ($newEvents as $event) {
            $this->createEvent(
                $event,
                (int)$shiftType,
                $rooms
                    ->where('name', $event->getRoom()->getName())
                    ->first(),
                $scheduleUrl
            );
        }

        foreach ($changeEvents as $event) {
            $this->updateEvent(
                $event,
                (int)$shiftType,
                $rooms
                    ->where('name', $event->getRoom()->getName())
                    ->first()
            );
        }

        foreach ($deleteEvents as $event) {
            $this->deleteEvent($event);
        }

        $this->log('Ended schedule "{schedule}" import', ['schedule' => $scheduleUrl->url]);

        return redirect($this->url, 303)
            ->with('success', ['schedule.import.success']);
    }

    /**
     * @param Room $room
     */
    protected function createRoom(Room $room): void
    {
        $this->db
            ->table('Room')
            ->insert(
                [
                    'Name' => $room->getName(),
                ]
            );

        $this->log('Created schedule room "{room}"', ['room' => $room->getName()]);
    }

    /**
     * @param Event       $shift
     * @param int         $shiftTypeId
     * @param stdClass    $room
     * @param ScheduleUrl $scheduleUrl
     */
    protected function createEvent(Event $shift, int $shiftTypeId, stdClass $room, ScheduleUrl $scheduleUrl): void
    {
        $user = auth()->user();

        $this->db
            ->table('Shifts')
            ->insert(
                [
                    'title'                => $shift->getTitle(),
                    'shifttype_id'         => $shiftTypeId,
                    'start'                => $shift->getDate()->unix(),
                    'end'                  => $shift->getEndDate()->unix(),
                    'RID'                  => $room->id,
                    'URL'                  => $shift->getUrl(),
                    'created_by_user_id'   => $user->id,
                    'created_at_timestamp' => time(),
                    'edited_by_user_id'    => null,
                    'edited_at_timestamp'  => 0,
                ]
            );

        $shiftId = $this->db->getDoctrineConnection()->lastInsertId();

        $scheduleShift = new ScheduleShift(['shift_id' => $shiftId, 'guid' => $shift->getGuid()]);
        $scheduleShift->schedule()->associate($scheduleUrl);
        $scheduleShift->save();

        $this->log(
            'Created schedule shift "{shift}" in "{room}" ({from} {to}, {guid})',
            [
                'shift' => $shift->getTitle(),
                'room'  => $room->name,
                'from'  => $shift->getDate()->format(Carbon::RFC3339),
                'to'    => $shift->getEndDate()->format(Carbon::RFC3339),
                'guid'  => $shift->getGuid(),
            ]
        );
    }

    /**
     * @param Event    $shift
     * @param int      $shiftTypeId
     * @param stdClass $room
     */
    protected function updateEvent(Event $shift, int $shiftTypeId, stdClass $room): void
    {
        $user = auth()->user();

        $this->db
            ->table('Shifts')
            ->join('schedule_shift', 'Shifts.SID', 'schedule_shift.shift_id')
            ->where('schedule_shift.guid', $shift->getGuid())
            ->update(
                [
                    'title'               => $shift->getTitle(),
                    'shifttype_id'        => $shiftTypeId,
                    'start'               => $shift->getDate()->unix(),
                    'end'                 => $shift->getEndDate()->unix(),
                    'RID'                 => $room->id,
                    'URL'                 => $shift->getUrl(),
                    'edited_by_user_id'   => $user->id,
                    'edited_at_timestamp' => time(),
                ]
            );

        $this->log(
            'Updated schedule shift "{shift}" in "{room}" ({from} {to}, {guid})',
            [
                'shift' => $shift->getTitle(),
                'room'  => $room->name,
                'from'  => $shift->getDate()->format(Carbon::RFC3339),
                'to'    => $shift->getEndDate()->format(Carbon::RFC3339),
                'guid'  => $shift->getGuid(),
            ]
        );
    }

    /**
     * @param Event $shift
     */
    protected function deleteEvent(Event $shift): void
    {
        $this->db
            ->table('Shifts')
            ->join('schedule_shift', 'Shifts.SID', 'schedule_shift.shift_id')
            ->where('schedule_shift.guid', $shift->getGuid())
            ->delete();

        $this->log(
            'Deleted schedule shift "{shift}" ({from} {to}, {guid})',
            [
                'shift' => $shift->getTitle(),
                'from'  => $shift->getDate()->format(Carbon::RFC3339),
                'to'    => $shift->getEndDate()->format(Carbon::RFC3339),
                'guid'  => $shift->getGuid(),
            ]
        );
    }

    /**
     * @param Request $request
     * @return Event[]|Room[]|ScheduleUrl|Schedule|string
     * @throws ErrorException
     */
    protected function getScheduleData(Request $request)
    {
        $data = $this->validate(
            $request,
            [
                'schedule-url'   => 'required|url',
                'shift-type'     => 'required|int',
                'minutes-before' => 'optional|int',
                'minutes-after'  => 'optional|int',
            ]
        );

        $scheduleResponse = $this->guzzle->get($data['schedule-url']);
        if ($scheduleResponse->getStatusCode() != 200) {
            throw new ErrorException('schedule.import.request-error');
        }

        $scheduleData = (string)$scheduleResponse->getBody();
        if (!$this->parser->load($scheduleData)) {
            throw new ErrorException('schedule.import.read-error');
        }

        $shiftType = (int)$data['shift-type'];
        if (!isset($this->getShiftTypes()[$shiftType])) {
            throw new ErrorException('schedule.import.invalid-shift-type');
        }

        $scheduleUrl = $this->getScheduleUrl($data['schedule-url']);
        $schedule = $this->parser->getSchedule();
        $minutesBefore = isset($data['minutes-before']) ? (int)$data['minutes-before'] : 15;
        $minutesAfter = isset($data['minutes-after']) ? (int)$data['minutes-after'] : 15;
        $newRooms = $this->newRooms($schedule->getRooms());
        return array_merge(
            $this->shiftsDiff($schedule, $scheduleUrl, $shiftType, $minutesBefore, $minutesAfter),
            [$newRooms, $shiftType, $scheduleUrl, $schedule, $minutesBefore, $minutesAfter]
        );
    }

    /**
     * @param string $name
     * @return Collection
     */
    protected function getFromSession(string $name): Collection
    {
        $data = Collection::make(Arr::flatten($this->session->get($name, [])));
        $this->session->remove($name);

        return $data;
    }

    /**
     * @param Room[] $scheduleRooms
     * @return Room[]
     */
    protected function newRooms(array $scheduleRooms): array
    {
        $newRooms = [];
        $allRooms = $this->getAllRooms();

        foreach ($scheduleRooms as $room) {
            if ($allRooms->where('name', $room->getName())->count()) {
                continue;
            }

            $newRooms[] = $room;
        }

        return $newRooms;
    }

    /**
     * @param Schedule    $schedule
     * @param ScheduleUrl $scheduleUrl
     * @param int         $shiftType
     * @param int         $minutesBefore
     * @param int         $minutesAfter
     * @return Event[]
     */
    protected function shiftsDiff(
        Schedule $schedule,
        ScheduleUrl $scheduleUrl,
        int $shiftType,
        int $minutesBefore,
        int $minutesAfter
    ): array {
        /** @var Event[] $newEvents */
        $newEvents = [];
        /** @var Event[] $changeEvents */
        $changeEvents = [];
        /** @var Event[] $scheduleEvents */
        $scheduleEvents = [];
        /** @var Event[] $deleteEvents */
        $deleteEvents = [];
        $rooms = $this->getAllRooms();

        foreach ($schedule->getDay() as $day) {
            foreach ($day->getRoom() as $room) {
                foreach ($room->getEvent() as $event) {
                    $scheduleEvents[$event->getGuid()] = $event;

                    $event->getDate()->subMinutes($minutesBefore);
                    $event->getEndDate()->addMinutes($minutesAfter);
                    $event->setTitle(sprintf('%s [%s]', $event->getTitle(), $event->getLanguage()));
                }
            }
        }

        $scheduleEventsGuidList = array_keys($scheduleEvents);
        $existingShifts = $this->getScheduleShiftsByGuid($scheduleUrl, $scheduleEventsGuidList);
        foreach ($existingShifts as $shift) {
            $guid = $shift->guid;
            $shift = $this->loadShift($shift->shift_id);
            $event = $scheduleEvents[$guid];
            $room = $rooms->where('name', $event->getRoom()->getName())->first();

            if (
                $shift->title != $event->getTitle()
                || $shift->shift_type_id != $shiftType
                || Carbon::createFromTimestamp($shift->start) != $event->getDate()
                || Carbon::createFromTimestamp($shift->end) != $event->getEndDate()
                || $shift->room_id != ($room->id ?? '')
                || $shift->url != $event->getUrl()
            ) {
                $changeEvents[$guid] = $event;
            }

            unset($scheduleEvents[$guid]);
        }

        foreach ($scheduleEvents as $scheduleEvent) {
            $newEvents[$scheduleEvent->getGuid()] = $scheduleEvent;
        }

        $scheduleShifts = $this->getScheduleShiftsWhereNotGuid($scheduleUrl, $scheduleEventsGuidList);
        foreach ($scheduleShifts as $shift) {
            $event = $this->eventFromScheduleShift($shift);
            $deleteEvents[$event->getGuid()] = $event;
        }

        return [$newEvents, $changeEvents, $deleteEvents];
    }

    /**
     * @param ScheduleShift $scheduleShift
     * @return Event
     */
    protected function eventFromScheduleShift(ScheduleShift $scheduleShift): Event
    {
        $shift = $this->loadShift($scheduleShift->shift_id);
        $start = Carbon::createFromTimestamp($shift->start);
        $end = Carbon::createFromTimestamp($shift->end);
        $duration = $start->diff($end);

        $event = new Event(
            $scheduleShift->guid,
            0,
            new Room($shift->room_name),
            $shift->title,
            '',
            'n/a',
            Carbon::createFromTimestamp($shift->start),
            $start->format('H:i'),
            $duration->format('%H:%I'),
            '',
            '',
            ''
        );

        return $event;
    }

    /**
     * @return Collection
     */
    protected function getAllRooms(): Collection
    {
        return new Collection($this->db->select('SELECT RID as id, Name as name FROM Room'));
    }

    /**
     * @param ScheduleUrl $scheduleUrl
     * @param string[]    $events
     * @return QueryBuilder[]|DatabaseCollection|ScheduleShift[]
     */
    protected function getScheduleShiftsByGuid(ScheduleUrl $scheduleUrl, array $events)
    {
        return ScheduleShift::query()
            ->whereIn('guid', $events)
            ->where('schedule_id', $scheduleUrl->id)
            ->get();
    }

    /**
     * @param ScheduleUrl $scheduleUrl
     * @param string[]    $events
     * @return QueryBuilder[]|DatabaseCollection|ScheduleShift[]
     */
    protected function getScheduleShiftsWhereNotGuid(ScheduleUrl $scheduleUrl, array $events)
    {
        return ScheduleShift::query()
            ->whereNotIn('guid', $events)
            ->where('schedule_id', $scheduleUrl->id)
            ->get();
    }

    /**
     * @param $id
     * @return stdClass|null
     */
    protected function loadShift($id): ?stdClass
    {
        return $this->db->selectOne(
            '
                    SELECT
                           s.SID AS id,
                           s.title,
                           s.start, 
                           s.end,
                           s.shifttype_id AS shift_type_id,
                           s.RID AS room_id,
                           r.Name AS room_name,
                           s.URL as url
                    FROM Shifts AS s
                    LEFT JOIN Room r on s.RID = r.RID
                    WHERE SID = ?
                  ',
            [$id]
        );
    }

    /**
     * @return string[]
     */
    protected function getShiftTypes()
    {
        $return = [];
        /** @var stdClass[] $shiftTypes */
        $shiftTypes = $this->db->select('SELECT t.id, t.name FROM ShiftTypes AS t');

        foreach ($shiftTypes as $shiftType) {
            $return[$shiftType->id] = $shiftType->name;
        }

        return $return;
    }

    /**
     * @param string $scheduleUrl
     * @return ScheduleUrl
     */
    protected function getScheduleUrl(string $scheduleUrl): ScheduleUrl
    {
        if (!$schedule = ScheduleUrl::whereUrl($scheduleUrl)->first()) {
            $schedule = new ScheduleUrl(['url' => $scheduleUrl]);
            $schedule->save();

            $this->log('Created schedule "{schedule}"', ['schedule' => $schedule->url]);
        }

        return $schedule;
    }

    /**
     * @param string $message
     * @param array  $context
     */
    protected function log(string $message, array $context = []): void
    {
        $user = auth()->user();
        $message = sprintf('%s (%u): %s', $user->name, $user->id, $message);

        $this->log->info($message, $context);
    }
}