Lines 95.89% 140 / 146
Methods 80.00% 8 / 10
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 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
 [BO\Zmsadmin\BaseController] __invoke 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsadmin\BaseController] getSchemaConstraintList 100.00% 8 / 8 100.00% 1 / 1 4
 [BO\Zmsadmin\BaseController] transformValidationErrors 61.53% 8 / 13 0.00% 0 / 1 15.69
 [BO\Zmsadmin\BaseController] handleEntityWrite 100.00% 17 / 17 100.00% 1 / 1 5
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}

Inherited from BO\Zmsadmin\BaseController

21    public function __invoke(RequestInterface $request, ResponseInterface $response, array $args)
22    {
23        $request = $this->initRequest($request);
24        $noCacheResponse = \BO\Slim\Render::withLastModified($response, time(), '0');
25        return $this->readResponse($request, $noCacheResponse, $args);
26    }
41    public function getSchemaConstraintList(\BO\Zmsentities\Schema\Schema $schema): array
42    {
43        $list = [];
44        $locale = \App::$language->getLocale();
45        foreach ($schema->properties as $key => $property) {
46            if (isset($property['x-locale'])) {
47                $constraints = $property['x-locale'][$locale];
48                if ($constraints) {
49                    $list[$key]['description'] = $constraints['messages'];
50                }
51            }
52        }
53        return $list;
54    }
65    protected function transformValidationErrors($errorData)
66    {
67        if (!is_array($errorData) && !($errorData instanceof \Traversable)) {
68            return [];
69        }
70        $transformed = [];
71        foreach ($errorData as $pointer => $item) {
72            // Extract field name from JSON pointer (e.g., "/id" -> "id", "/contact/email" -> "contact/email")
73            // If the key doesn't start with "/", it's already a field name, so use it as-is
74            $fieldName = (strpos($pointer, '/') === 0) ? ltrim($pointer, '/') : $pointer;
75            // Handle root level errors
76            if ($fieldName === '' || $fieldName === null) {
77                $fieldName = '_root';
78            }
79            // Ensure the item structure is correct (has 'messages' array)
80            if (is_array($item) && isset($item['messages'])) {
81                $transformed[$fieldName] = $item;
82            } elseif (is_array($item)) {
83                // If item is an array but doesn't have 'messages', wrap it
84                $transformed[$fieldName] = $item;
85            } else {
86                $transformed[$fieldName] = $item;
87            }
88        }
89        return $transformed;
90    }
99    protected function handleEntityWrite(callable $httpCall)
100    {
101        try {
102            return $httpCall();
103        } catch (\BO\Zmsclient\Exception $exception) {
104            if ('BO\Zmsentities\Exception\SchemaValidation' == $exception->template) {
105                return [
106                    'template' => 'exception/bo/zmsentities/exception/schemavalidation.twig',
107                    'include' => true,
108                    'data' => $this->transformValidationErrors($exception->data)
109                ];
110            }
111
112            $template = TwigExceptionHandler::getExceptionTemplate($exception);
113            if (
114                '' != $exception->template
115                && \App::$slim->getContainer()->get('view')->getLoader()->exists($template)
116            ) {
117                return [
118                    'template' => $template,
119                    'include' => true,
120                    'data' => $this->transformValidationErrors($exception->data)
121                ];
122            }
123
124            throw $exception;
125        }
126    }