Lines 99.04% 104 / 105
Functions and Methods 83.33% 5 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ScopeAvailabilityDay 99.04% 104 / 105 83.33% 5 / 6 19 0.00% 0 / 1
 readResponse 93.33% 14 / 15 0.00% 0 / 1 2.00
 getScope 100.00% 3 / 3 100.00% 1 / 1 1
 getSlotBuckets 100.00% 31 / 31 100.00% 1 / 1 8
 getAvailabilityData 100.00% 31 / 31 100.00% 1 / 1 3
 readConflictList 100.00% 12 / 12 100.00% 1 / 1 2
 readAvailabilityList 100.00% 13 / 13 100.00% 1 / 1 3
1<?php
2
3/**
4 * @package Zmsadmin
5 * @copyright BerlinOnline Stadtportal GmbH & Co. KG
6 **/
7
8namespace BO\Zmsadmin;
9
10use BO\Slim\Render;
11use BO\Zmsentities\Helper\DateTime;
12use BO\Zmsentities\Collection\AvailabilityList;
13use BO\Zmsentities\Collection\ProcessList;
14use BO\Zmsentities\Exception\UserAccountMissingRights;
15
16class ScopeAvailabilityDay extends BaseController
17{
18    /**
19     * @SuppressWarnings(Param)
20     * @return \Psr\Http\Message\ResponseInterface
21     */
22    #[\Override]
23    public function readResponse(
24        \Psr\Http\Message\RequestInterface $request,
25        \Psr\Http\Message\ResponseInterface $response,
26        array $args
27    ): \Psr\Http\Message\ResponseInterface {
28        $workstation = \App::$http->readGetResult('/workstation/', ['resolveReferences' => 1])->getEntity();
29        if (!$workstation->getUseraccount()->hasPermissions(['availability'])) {
30            throw new UserAccountMissingRights();
31        }
32        $data = static::getAvailabilityData(intval($args['id']), $args['date']);
33        $data['title'] = 'Behörden und Standorte - Öffnungszeiten';
34        $data['menuActive'] = 'owner';
35        $data['workstation'] = $workstation;
36        $data['canViewAvailabilityHistory'] = ScopeAvailabilityHistory::canViewAvailabilityHistory(
37            $workstation->getUseraccount()
38        );
39        return Render::withHtml(
40            $response,
41            'page/availabilityday.twig',
42            $data
43        );
44    }
45
46    protected static function getScope(string|int $scopeId)
47    {
48        return \App::$http->readGetResult('/scope/' . $scopeId . '/', [
49            'resolveReferences' => 3
50        ])->getEntity();
51    }
52
53    /**
54     * @return (int|mixed)[][]
55     *
56     */
57    protected static function getSlotBuckets(\BO\Zmsentities\Collection\AvailabilityList $availabilityList, \BO\Zmsentities\Collection\ProcessList $processList): array
58    {
59        $availability = $availabilityList->getFirst();
60
61        if (!$availability) {
62            return [];
63        }
64
65        $buckets = [];
66
67        $slotTimeInMinutes = $availability->getSlotTimeInMinutes();
68
69        foreach ($availabilityList->getSlotListByType('appointment') as $slot) {
70            $time = $slot->time;
71            if (isset($buckets[$time])) {
72                // Overlapping availabilities add up their workstations
73                $buckets[$time]['public'] += $slot->public;
74                $buckets[$time]['intern'] += $slot->intern;
75                continue;
76            }
77            $buckets[$time] = [
78                'time' => $time,
79                'timeString' => $slot->getTimeString(),
80                'public' => $slot->public,
81                'intern' => $slot->intern,
82                'occupiedCount' => 0,
83            ];
84        }
85
86        foreach ($processList as $process) {
87            $startTime = $process->getAppointments()->getFirst()->getStartTime()->format('H:i');
88            $endTime = $process->getAppointments()->getFirst()->getEndTimeWithCustomSlotTime($slotTimeInMinutes)->format('H:i');
89
90            $startDateTime = new \DateTime($startTime);
91            $endDateTime = new \DateTime($endTime);
92
93            foreach (array_keys($buckets) as $time) {
94                $slotDateTime = new \DateTime($time);
95                if ($slotDateTime >= $startDateTime && $slotDateTime < $endDateTime) {
96                    $buckets[$time]['occupiedCount']++;
97                }
98            }
99        }
100
101        uksort($buckets, function ($time1, $time2) {
102            return strtotime($time1) <=> strtotime($time2);
103        });
104
105        return $buckets;
106    }
107
108    /**
109     * @return (\BO\Zmsentities\Process[]|int|mixed|string)[]
110     *
111     */
112    protected static function getAvailabilityData(int $scopeId, string $dateString): array
113    {
114        $scope = static::getScope($scopeId);
115        $dateTime = new DateTime($dateString);
116        $dateWithTime = $dateTime->setTime(\App::$now->format('H'), \App::$now->format('i'));
117        $availabilityList = static::readAvailabilityList($scopeId, $dateWithTime);
118        $processList = \App::$http
119            ->readGetResult('/scope/' . $scopeId . '/process/' . $dateWithTime->format('Y-m-d') . '/')
120                ->getCollection()
121                ->toQueueList($dateWithTime)
122                ->withoutStatus(['fake'])
123                ->toProcessList();
124        if (!$processList->count()) {
125            $processList = new ProcessList();
126        }
127
128
129        $conflictList = static::readConflictList($scopeId, $dateWithTime);
130        $maxSlots = $availabilityList->getSummerizedSlotCount();
131        $busySlots = $availabilityList->getCalculatedSlotCount($processList);
132
133        return [
134            'slotBuckets' => static::getSlotBuckets($availabilityList, $processList),
135            'scope' => $scope,
136            'availabilityList' => $availabilityList->getArrayCopy(),
137            'conflicts' => ($conflictList) ? $conflictList
138                ->setConflictAmendment()
139                ->getArrayCopy() : [],
140            'processList' => $processList->getArrayCopy(),
141            'dateString' => $dateString,
142            'timestamp' => $dateWithTime->getTimestamp(),
143            'menuActive' => 'availability',
144            'maxWorkstationCount' => $availabilityList->getMaxWorkstationCount(),
145            'maxSlotsForAvailabilities' => $maxSlots,
146            'busySlotsForAvailabilities' => $busySlots,
147            'today' => \App::$now->getTimestamp()
148        ];
149    }
150
151    public static function readConflictList(string|int $scopeId, \DateTimeInterface $dateTime)
152    {
153        $processConflictList = \App::$http
154            ->readGetResult('/scope/' . $scopeId . '/conflict/', [
155                'startDate' => $dateTime->format('Y-m-d'),
156                'endDate' => $dateTime->format('Y-m-d')
157            ])
158            ->getCollection();
159        return ($processConflictList) ? $processConflictList
160            ->sortByAppointmentDate()
161            ->withoutDublicatedConflicts()
162            ->toQueueList($dateTime)
163            ->withoutStatus(['fake', 'queued'])
164            ->toProcessList() : null;
165    }
166
167    public static function readAvailabilityList(string|int $scopeId, \DateTimeInterface $dateTime)
168    {
169        try {
170            $availabilityList = \App::$http
171                ->readGetResult(
172                    '/scope/' . $scopeId . '/availability/',
173                    [
174                        'startDate' => $dateTime->format('Y-m-d'), //for skipping old availabilities
175                    ]
176                )
177                ->getCollection()->sortByCustomKey('startDate');
178        } catch (\BO\Zmsclient\Exception $exception) {
179            if ($exception->template != 'BO\Zmsbackend\Availability\Exception\AvailabilityNotFound') {
180                throw $exception;
181            }
182            $availabilityList = new AvailabilityList();
183        }
184        return $availabilityList->withDateTime($dateTime); //withDateTime to check if opened
185    }
186}