Lines 88.00% 264 / 300
Functions and Methods 50.00% 9 / 18
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ProcessStatusFree 88.00% 264 / 300 50.00% 9 / 18 77.23 0.00% 0 / 1
 prepareCalendarAndDays 100.00% 4 / 4 100.00% 1 / 1 1
 buildDaysList 100.00% 8 / 8 100.00% 1 / 1 3
 buildDaysListFromCalendarDays 75.00% 9 / 12 0.00% 0 / 1 6.56
 readMinimalFreeProcessesFromCalendar 94.11% 16 / 17 0.00% 0 / 1 4.00
 getProcessDataHandle 100.00% 17 / 17 100.00% 1 / 1 6
 readFreeProcesses 100.00% 11 / 11 100.00% 1 / 1 1
 readPreparedFreeProcesses 100.00% 25 / 25 100.00% 1 / 1 3
 readFreeProcessesMinimalDeduplicated 0.00% 0 / 10 0.00% 0 / 1 12
 deduplicateWithRoundRobin 100.00% 29 / 29 100.00% 1 / 1 4
 uniqueCandidatesSortedByScopeId 90.00% 9 / 10 0.00% 0 / 1 2.00
 resolveRoundRobinGroupKey 100.00% 5 / 5 100.00% 1 / 1 3
 pickRoundRobinIndex 66.66% 2 / 3 0.00% 0 / 1 2.15
 extractProcessInfo 81.48% 22 / 27 0.00% 0 / 1 10.64
 createMinimalProcess 100.00% 24 / 24 100.00% 1 / 1 1
 readReservedProcesses 100.00% 15 / 15 100.00% 1 / 1 4
 writeEntityReserved 70.58% 12 / 17 0.00% 0 / 1 4.41
 writeEntityReservedAttempt 98.24% 56 / 57 0.00% 0 / 1 8
 resetWriteTransactionAfterDeadlock 0.00% 0 / 9 0.00% 0 / 1 20
1<?php
2
3namespace BO\Zmsbackend\Process\Service;
4
5use BO\Zmsentities\Process as Entity;
6use BO\Zmsentities\Collection\ProcessList as Collection;
7
8/**
9 * @SuppressWarnings(Coupling)
10 */
11class ProcessStatusFree extends Process
12{
13    /**
14     * @return (\BO\Zmsbackend\Day\Service\Day|\BO\Zmsentities\Calendar|array)[]
15     *
16     */
17    private function prepareCalendarAndDays(
18        \BO\Zmsentities\Calendar $calendar,
19        \DateTimeInterface $now,
20        int|null $slotsRequired = null
21    ): array {
22        $calendar = (new \BO\Zmsbackend\Calendar\Service\Calendar())->readResolvedEntity($calendar, $now, true);
23        $dayquery = new \BO\Zmsbackend\Day\Service\Day();
24        $dayquery->writeTemporaryScopeList($calendar, $slotsRequired);
25
26        return [$calendar, $dayquery, $this->buildDaysList($calendar)];
27    }
28
29    private function buildDaysList(\BO\Zmsentities\Calendar $calendar): array
30    {
31        $selectedDate = $calendar->getFirstDay();
32        $days = [$selectedDate];
33        if ($calendar->getLastDay(false)) {
34            $days = [];
35            while ($selectedDate <= $calendar->getLastDay(false)) {
36                $days[] = $selectedDate;
37                $selectedDate = $selectedDate->modify('+1 day');
38            }
39        }
40
41        return $days;
42    }
43
44    /**
45     * Prefer concrete days already on the calendar (e.g. bookable days only).
46     * Falls back to the full firstDay→lastDay range when no days are set.
47     */
48    private function buildDaysListFromCalendarDays(\BO\Zmsentities\Calendar $calendar): array
49    {
50        if (!isset($calendar->days) || count($calendar->days) < 1) {
51            return $this->buildDaysList($calendar);
52        }
53
54        $daysByDate = [];
55        foreach ($calendar->days as $day) {
56            if (!$day instanceof \BO\Zmsentities\Day) {
57                $day = new \BO\Zmsentities\Day($day);
58            }
59            $dateTime = $day->toDateTime();
60            $daysByDate[$dateTime->format('Y-m-d')] = $dateTime;
61        }
62
63        if ($daysByDate === []) {
64            return $this->buildDaysList($calendar);
65        }
66
67        ksort($daysByDate);
68
69        return array_values($daysByDate);
70    }
71
72    public function readMinimalFreeProcessesFromCalendar(
73        \BO\Zmsentities\Calendar $calendar,
74        string $slotType = 'public',
75        ?int $slotsRequired = null,
76        bool $groupData = false
77    ): array {
78        $days = $this->buildDaysListFromCalendarDays($calendar);
79        if ($days === []) {
80            return [];
81        }
82
83        $processData = $this->getProcessDataHandle(
84            $days,
85            $slotType,
86            $slotsRequired,
87            $groupData,
88            true
89        );
90
91        $processInfos = [];
92        while ($item = $processData->fetch(\PDO::FETCH_ASSOC)) {
93            $processInfo = $this->extractProcessInfo($item, $calendar);
94            if ($processInfo) {
95                $processInfos[] = $processInfo;
96            }
97        }
98
99        $processData->closeCursor();
100
101        return $this->deduplicateWithRoundRobin($processInfos);
102    }
103
104    private function getProcessDataHandle(
105        array $days,
106        string $slotType,
107        int|null $slotsRequired,
108        bool $groupData,
109        bool $useAvailabilityQuery = false,
110        ?\DateTimeInterface $appointmentTime = null
111    ) {
112        $query = $useAvailabilityQuery
113            ? \BO\Zmsbackend\Process\Repository\ProcessStatusFree::QUERY_SELECT_PROCESSLIST_DAYS_AVAILABILITY
114            : \BO\Zmsbackend\Process\Repository\ProcessStatusFree::QUERY_SELECT_PROCESSLIST_DAYS;
115
116        $condition = \BO\Zmsbackend\Process\Repository\ProcessStatusFree::buildDaysCondition($days);
117        $params = [
118            'slotType' => $slotType,
119            'forceRequiredSlots' =>
120                ($slotsRequired === null || $slotsRequired < 1) ? 1 : intval($slotsRequired),
121        ];
122        if ($appointmentTime !== null) {
123            // Reserving only needs to verify the requested time, not every slot on that day.
124            $condition .= ' AND s.time = :appointmentTime';
125            $params['appointmentTime'] = $appointmentTime->format('H:i:s');
126        }
127
128        return $this->fetchHandle(
129            sprintf($query, $condition)
130            . ($groupData ? \BO\Zmsbackend\Process\Repository\ProcessStatusFree::GROUPBY_SELECT_PROCESSLIST_DAY : ''),
131            $params
132        );
133    }
134
135    public function readFreeProcesses(
136        \BO\Zmsentities\Calendar $calendar,
137        \DateTimeInterface $now,
138        string $slotType = 'public',
139        int|null $slotsRequired = null,
140        bool $groupData = false,
141        ?\DateTimeInterface $appointmentTime = null
142    ): Collection {
143        list($calendar, $dayquery, $days) = $this->prepareCalendarAndDays($calendar, $now, $slotsRequired);
144        $processList = $this->readPreparedFreeProcesses(
145            $calendar,
146            $days,
147            $slotType,
148            $slotsRequired,
149            $groupData,
150            $appointmentTime
151        );
152        unset($dayquery);
153        return $processList;
154    }
155
156    private function readPreparedFreeProcesses(
157        \BO\Zmsentities\Calendar $calendar,
158        array $days,
159        string $slotType,
160        int|null $slotsRequired,
161        bool $groupData,
162        ?\DateTimeInterface $appointmentTime
163    ): Collection {
164        $processData = $this->getProcessDataHandle(
165            $days,
166            $slotType,
167            $slotsRequired,
168            $groupData,
169            false,
170            $appointmentTime
171        );
172        $processList = new Collection();
173        $scopeList = [];
174        while ($item = $processData->fetch(\PDO::FETCH_ASSOC)) {
175            $process = new \BO\Zmsentities\Process($item);
176            $process->requests = $calendar->requests;
177            $process->appointments->getFirst()->setDateByString(
178                $process->appointments->getFirst()->date,
179                'Y-m-d H:i:s'
180            );
181
182            if (! isset($scopeList[$process->scope->id])) {
183                $scopeList[$process->scope->id] = $calendar->scopes->getEntity($process->scope->id);
184            }
185
186            $process->scope = $scopeList[$process->scope->id];
187            $process->queue['withAppointment'] = 1;
188            $process->appointments->getFirst()->scope = $process->scope;
189            $processList->addEntity($process);
190        }
191        $processData->closeCursor();
192        return $processList;
193    }
194
195    public function readFreeProcessesMinimalDeduplicated(
196        \BO\Zmsentities\Calendar $calendar,
197        \DateTimeInterface $now,
198        string $slotType = 'public',
199        ?int $slotsRequired = null,
200        bool $groupData = false
201    ): array {
202        list($calendar, $dayquery, $days) = $this->prepareCalendarAndDays($calendar, $now, $slotsRequired);
203        $processData = $this->getProcessDataHandle($days, $slotType, $slotsRequired, $groupData);
204
205        $processInfos = [];
206        while ($item = $processData->fetch(\PDO::FETCH_ASSOC)) {
207            $processInfo = $this->extractProcessInfo($item, $calendar);
208            if ($processInfo) {
209                $processInfos[] = $processInfo;
210            }
211        }
212
213        $processData->closeCursor();
214        unset($dayquery);
215
216        return $this->deduplicateWithRoundRobin($processInfos);
217    }
218
219    /**
220     * Keep one free process per round-robin group + timestamp.
221     *
222     * Default group is the provider id. When provider.data.sharedBookingOfficeIds
223     * is set, all peer providers share one group so the same wall-clock slot is
224     * offered once and successive timeslots round-robin across eligible scopes
225     * of every peer (ZMSKVR-1046). Scopes that cannot fit the slot never appear
226     * here, so fall-through is preserved.
227     *
228     * @param array<int, array<string, mixed>> $processInfos
229     * @return array<int, array<string, mixed>>
230     */
231    private function deduplicateWithRoundRobin(array $processInfos): array
232    {
233        // Composite key: round-robin group (provider or shared-office set) + slot timestamp.
234        $candidatesByGroupTimestampKey = [];
235        $groupTimestampKeyOrder = [];
236        foreach ($processInfos as $processInfo) {
237            $roundRobinGroupKey = self::resolveRoundRobinGroupKey(
238                (string) $processInfo['providerId'],
239                $processInfo['sharedBookingOfficeIds'] ?? null
240            );
241            $groupTimestampKey = $roundRobinGroupKey . '_' . $processInfo['date'];
242            if (!isset($candidatesByGroupTimestampKey[$groupTimestampKey])) {
243                $groupTimestampKeyOrder[] = $groupTimestampKey;
244                $candidatesByGroupTimestampKey[$groupTimestampKey] = [];
245            }
246            $candidatesByGroupTimestampKey[$groupTimestampKey][] = $processInfo;
247        }
248
249        $roundRobinIndexByGroup = [];
250        $deduplicatedProcesses = [];
251        foreach ($groupTimestampKeyOrder as $groupTimestampKey) {
252            $candidates = self::uniqueCandidatesSortedByScopeId(
253                $candidatesByGroupTimestampKey[$groupTimestampKey]
254            );
255            $roundRobinGroupKey = self::resolveRoundRobinGroupKey(
256                (string) $candidates[0]['providerId'],
257                $candidates[0]['sharedBookingOfficeIds'] ?? null
258            );
259            $roundRobinTimeslotIndex = $roundRobinIndexByGroup[$roundRobinGroupKey] ?? 0;
260            $chosenCandidate = $candidates[
261                self::pickRoundRobinIndex($roundRobinTimeslotIndex, count($candidates))
262            ];
263            $roundRobinIndexByGroup[$roundRobinGroupKey] = $roundRobinTimeslotIndex + 1;
264            $deduplicatedProcesses[] = $this->createMinimalProcess($chosenCandidate);
265        }
266
267        return $deduplicatedProcesses;
268    }
269
270    /**
271     * @param array<int, array<string, mixed>> $candidates
272     * @return array<int, array<string, mixed>>
273     */
274    private static function uniqueCandidatesSortedByScopeId(array $candidates): array
275    {
276        $candidatesByScopeId = [];
277        foreach ($candidates as $candidate) {
278            $candidatesByScopeId[(string) $candidate['scopeId']] = $candidate;
279        }
280        $uniqueCandidates = array_values($candidatesByScopeId);
281        usort(
282            $uniqueCandidates,
283            static fn (array $left, array $right): int =>
284                ((int) $left['scopeId']) <=> ((int) $right['scopeId'])
285        );
286
287        return $uniqueCandidates;
288    }
289
290    /**
291     * @internal Exposed for unit tests.
292     * @param array<int, int|string>|null $sharedBookingOfficeIds
293     */
294    public static function resolveRoundRobinGroupKey(
295        string $providerId,
296        ?array $sharedBookingOfficeIds
297    ): string {
298        if (!is_array($sharedBookingOfficeIds) || $sharedBookingOfficeIds === []) {
299            return $providerId;
300        }
301
302        $sortedSharedOfficeIds = array_map('intval', $sharedBookingOfficeIds);
303        sort($sortedSharedOfficeIds, SORT_NUMERIC);
304
305        return implode(',', $sortedSharedOfficeIds);
306    }
307
308    /**
309     * @internal Exposed for unit tests.
310     */
311    public static function pickRoundRobinIndex(int $timeslotIndex, int $candidateCount): int
312    {
313        if ($candidateCount < 1) {
314            throw new \InvalidArgumentException('candidateCount must be >= 1');
315        }
316
317        return $timeslotIndex % $candidateCount;
318    }
319
320    private function extractProcessInfo(array $item, \BO\Zmsentities\Calendar $calendar): ?array
321    {
322        $scopeId = $item['scope__id'] ?? null;
323        $dateString = $item['appointments__0__date'] ?? null;
324
325        if (!$scopeId || !$dateString) {
326            return null;
327        }
328
329        $date = strtotime($dateString);
330        if (!$date) {
331            return null;
332        }
333
334        $scope = $calendar->scopes->getEntity($scopeId);
335        if (!$scope) {
336            return null;
337        }
338
339        $providerId = $scope->getProviderId();
340        if (!$providerId) {
341            return null;
342        }
343
344        $sharedBookingOfficeIds = null;
345        $provider = $scope->getProvider();
346        if (
347            $provider
348            && isset($provider->data['sharedBookingOfficeIds'])
349            && is_array($provider->data['sharedBookingOfficeIds'])
350            && $provider->data['sharedBookingOfficeIds'] !== []
351        ) {
352            $sharedBookingOfficeIds = array_map('intval', $provider->data['sharedBookingOfficeIds']);
353        }
354
355        return [
356            'scopeId' => $scopeId,
357            'source' => $scope->getSource(),
358            'providerId' => $providerId,
359            'sharedBookingOfficeIds' => $sharedBookingOfficeIds,
360            'date' => $date
361        ];
362    }
363
364    private function createMinimalProcess(array $processInfo): array
365    {
366        return [
367            '$schema' => 'https://schema.berlin.de/queuemanagement/process.json',
368            'scope' => [
369                'id' => $processInfo['scopeId'],
370                'source' => $processInfo['source'],
371                'provider' => [
372                    'id' => $processInfo['providerId'],
373                    'source' => $processInfo['source'],
374                ]
375            ],
376            'appointments' => [
377                [
378                    'date' => (string)$processInfo['date'],
379                    'scope' => [
380                        'id' => $processInfo['scopeId'],
381                        'source' => $processInfo['source'],
382                        'provider' => [
383                            'id' => $processInfo['providerId'],
384                            'source' => $processInfo['source'],
385                        ]
386                    ]
387                ]
388            ]
389        ];
390    }
391
392    public function readReservedProcesses(int $resolveReferences = 2): Collection
393    {
394        $processList = new Collection();
395        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
396        $query
397            ->addResolvedReferences($resolveReferences)
398            ->addEntityMapping()
399            ->addConditionAssigned()
400            ->addConditionIsReserved();
401        $resultData = $this->fetchList($query, new Entity());
402        foreach ($resultData as $process) {
403            if (2 == $resolveReferences) {
404                $process->requests = (new \BO\Zmsbackend\Request\Service\Request())->readRequestByProcessId($process->id, $resolveReferences);
405                $process->scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readEntity($process->getScopeId(), $resolveReferences);
406            }
407            if ($process instanceof Entity) {
408                $processList->addEntity($process);
409            }
410        }
411        return $processList;
412    }
413
414    /**
415     * Insert a new process if there are free slots
416     *
417     * @param \BO\Zmsentities\Process $process
418     * @param \DateTimeInterface $now
419     * @param String $slotType
420     * @param Int $slotsRequired we cannot use process.appointments.0.slotCount, because setting slotsRequired is
421     *        a priviliged operation. Just using the input would be a security flaw to get a wider selection of times
422     *        If slotsRequired = 0, readFreeProcesses() uses the slotsRequired based on request-provider relation
423     */
424    public function writeEntityReserved(
425        \BO\Zmsentities\Process $process,
426        \DateTimeInterface $now,
427        string $slotType = "public",
428        int $slotsRequired = 0,
429        int $resolveReferences = 0,
430        ?\BO\Zmsentities\Useraccount $userAccount = null
431    ): ?\BO\Zmsentities\Process {
432        $maxAttempts = 3;
433        $attempt = 0;
434        while (true) {
435            try {
436                return $this->writeEntityReservedAttempt(
437                    $process,
438                    $now,
439                    $slotType,
440                    $slotsRequired,
441                    $resolveReferences,
442                    $userAccount
443                );
444            } catch (\BO\Zmsbackend\Exception\Pdo\DeadLockFound $exception) {
445                $attempt++;
446                if ($attempt >= $maxAttempts) {
447                    throw $exception;
448                }
449                $this->resetWriteTransactionAfterDeadlock();
450                usleep(50000 * $attempt);
451            }
452        }
453    }
454
455    protected function writeEntityReservedAttempt(
456        \BO\Zmsentities\Process $process,
457        \DateTimeInterface $now,
458        string $slotType = "public",
459        int $slotsRequired = 0,
460        int $resolveReferences = 0,
461        ?\BO\Zmsentities\Useraccount $userAccount = null
462    ): ?\BO\Zmsentities\Process {
463        $process = clone $process;
464        $process->status = 'reserved';
465        $appointment = $process->getAppointments()->getFirst();
466        $appointmentTime = $appointment->toDateTime();
467        // Calendar lookup and the first free-slot check stay outside the slot lock.
468        $this->getWriter();
469        [$calendar, $dayquery, $days] = $this->prepareCalendarAndDays(
470            $process->toCalendar(),
471            $now,
472            $slotsRequired
473        );
474        $freeProcessList = $this->readPreparedFreeProcesses(
475            $calendar,
476            $days,
477            $slotType,
478            $slotsRequired,
479            false,
480            $appointmentTime
481        );
482        if (!$freeProcessList->getAppointmentList()->hasAppointment($appointment)) {
483            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
484        }
485
486        try {
487            // The availability chosen under the slot locks is the one the reservation is mapped to.
488            $reservation = (new \BO\Zmsbackend\Slot\Service\Slot())->readReservationByAppointment(
489                $appointment,
490                $slotsRequired,
491                (null !== $userAccount),
492                true,
493                $slotType
494            );
495        } catch (\BO\Zmsbackend\Exception\Pdo\LockTimeout) {
496            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
497        }
498        $slotList = $reservation['slotList'];
499        $availabilityId = (int) $reservation['availability']->getId() ?: null;
500        $freeProcessList = $this->readPreparedFreeProcesses(
501            $calendar,
502            $days,
503            $slotType,
504            $slotsRequired,
505            false,
506            $appointmentTime
507        );
508        if (!$freeProcessList->getAppointmentList()->hasAppointment($appointment) || ! $slotList) {
509            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
510        }
511        unset($dayquery);
512
513        // One row stores the length. The save maps every step of that length on the chosen availability.
514        if ($process->id === 0) {
515            $process = $this->writeNewProcess(
516                $process,
517                $now,
518                0,
519                count($slotList) - 1,
520                true,
521                $userAccount,
522                $availabilityId
523            );
524        } elseif ($process->id <= 99999) {
525            throw new \Exception("SQL UPDATE error on inserting new $process");
526        } else {
527            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
528        }
529        $this->writeRequestsToDb($process);
530        return $this->readEntity($process->getId(), new \BO\Zmsbackend\Helper\NoAuth(), $resolveReferences);
531    }
532
533    /**
534     * After InnoDB aborts a transaction on deadlock, clear PDO state and start a fresh transaction.
535     */
536    protected function resetWriteTransactionAfterDeadlock(): void
537    {
538        $connection = \BO\Zmsbackend\Connection\Select::getWriteConnection();
539        if ($connection->inTransaction()) {
540            try {
541                $connection->rollBack();
542            } catch (\PDOException $exception) {
543                \App::$log->warning('Rollback after deadlock failed', [
544                    'error' => $exception->getMessage(),
545                ]);
546            }
547        }
548        if (!$connection->inTransaction()) {
549            $connection->beginTransaction();
550        }
551    }
552}