Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.56% covered (warning)
82.56%
426 / 516
72.34% covered (warning)
72.34%
34 / 47
CRAP
0.00% covered (danger)
0.00%
0 / 1
Process
82.56% covered (warning)
82.56%
426 / 516
72.34% covered (warning)
72.34%
34 / 47
256.56
0.00% covered (danger)
0.00%
0 / 1
 readEntity
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 readById
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 readResolvedReferences
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 updateEntity
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
4
 updateEntityDisplayNumber
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 updateEntityWithSlots
84.21% covered (warning)
84.21%
16 / 19
0.00% covered (danger)
0.00%
0 / 1
6.14
 redirectToScope
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
2
 readSlotCount
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 writeEntityWithNewAppointment
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
2
 updateFollowingProcesses
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 updateReassignedRequests
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 writeNewProcess
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
7
 readNewProcessId
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 readAuthKeyByProcessId
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 readList
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 readProcessesWithoutRequests
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 attachAllRequestsInOneQuery
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
7.48
 readEntityList
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 readByWorkstation
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 readProcessListByScopesAndTime
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 readConflictListByScopeAndTime
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
4
 readProcessListByScopeAndStatus
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 readProcessListByClusterAndTime
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 readProcessListCountByScope
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 readProcessListByMailAddress
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 readListByMailAndStatusList
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 updateProcessStatus
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 shouldUpdateDisplayNumber
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
6.32
 writeDeletedEntity
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 deleteEntity
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 writeCanceledEntity
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 writeBlockedEntity
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
6
 writeRequestsToDb
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
 deleteRequestsForProcessId
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 readExpiredProcessList
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 readUnconfirmedProcessList
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 readExpiredProcessListByStatus
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 readExpiredReservationsList
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 readEmailReminderProcessListByInterval
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 readDeallocateProcessList
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 isAppointmentAllowedWithSameMail
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
10.02
 isAppointmentSlotCountAllowed
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 isServiceQuantityAllowed
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
156
 isMailWhitelisted
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
6.04
 readProcessWithSameDayAndDisplayNumber
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 readProcessListByExternalUserId
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 readAssignedWorkstationIdForUpdate
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
1<?php
2
3namespace BO\Zmsbackend\Process\Service;
4
5use BO\Zmsentities\Collection\AppointmentList;
6use BO\Zmsentities\Process as Entity;
7use BO\Zmsentities\Scope as ScopeEntity;
8use BO\Zmsentities\Collection\ProcessList as Collection;
9use BO\Zmsbackend\Helper\ProcessStatus;
10
11/**
12 *
13 * @SuppressWarnings(CouplingBetweenObjects)
14 * @SuppressWarnings(TooManyPublicMethods)
15 * @SuppressWarnings(Complexity)
16 * @SuppressWarnings(TooManyMethods)
17 */
18class Process extends \BO\Zmsbackend\Base implements \BO\Zmsbackend\Interfaces\ResolveReferences
19{
20    /**
21     * @param \BO\Zmsbackend\Helper\NoAuth|null|string $authKey
22     * @param int|null|string $processId
23     */
24    public function readEntity(int|string|null $processId = null, string|\BO\Zmsbackend\Helper\NoAuth|null $authKey = null, int $resolveReferences = 2): ?Entity
25    {
26        if (null === $processId || null === $authKey) {
27            return null;
28        }
29        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
30        $query->addEntityMapping()
31            ->addResolvedReferences($resolveReferences)
32            ->addConditionProcessId($processId);
33        if (!$authKey instanceof \BO\Zmsbackend\Helper\NoAuth) {
34            $query->addConditionAuthKey($authKey);
35        }
36        $process = $this->fetchOne($query, new Entity());
37        $process = $this->readResolvedReferences($process, $resolveReferences);
38
39        return $process;
40    }
41
42    public function readById($processId, int $resolveReferences = 1): Entity
43    {
44        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
45        $query->addEntityMapping()
46            ->addResolvedReferences($resolveReferences)
47            ->addConditionProcessId($processId);
48        return $this->fetchOne($query, new Entity());
49    }
50
51    /**
52     *
53     * @return \BO\Zmsentities\Schema\Entity
54     */
55    #[\Override]
56    public function readResolvedReferences(\BO\Zmsentities\Schema\Entity $entity, int $resolveReferences)
57    {
58        if (0 <= $resolveReferences) {
59            if ($entity->archiveId) {
60                $entity->requests = (new \BO\Zmsbackend\Request\Service\Request())
61                    ->readRequestByArchiveId($entity->archiveId, $resolveReferences - 1);
62            } else {
63                $entity->requests = (new \BO\Zmsbackend\Request\Service\Request())
64                    ->readRequestByProcessId($entity->id, $resolveReferences - 1);
65            }
66        }
67        return $entity;
68    }
69
70
71    /**
72     * Update a process without changing appointment or scope
73     *
74     * @param null|string $previousStatus
75     *
76     */
77    public function updateEntity(\BO\Zmsentities\Process $process, \DateTimeInterface $now, int $resolveReferences = 0, string|null $previousStatus = null, ?\BO\Zmsentities\Useraccount $useraccount = null): Entity
78    {
79        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::UPDATE);
80        $query->addConditionProcessId($process->getId());
81        $query->addConditionAuthKey($process->getAuthKey());
82        $query->addValuesUpdateProcess($process, $now, 0, $previousStatus);
83        if ($this->perform($query->getLockProcessId(), ['processId' => $process->getId()])) {
84            $this->writeItem($query);
85            $this->writeRequestsToDb($process);
86        }
87        $process = $this->readEntity($process->getId(), $process->authKey, $resolveReferences);
88        if (!$process->getId()) {
89            throw new \BO\Zmsbackend\Process\Exception\ProcessUpdateFailed();
90        }
91        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_UPDATE_FOLLOWING_PROCESS, [
92            'reserved' => ($process->status == 'reserved') ? 1 : 0,
93            'processID' => $process->getId(),
94        ]);
95        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (\BO\Zmsbackend\Process\Service\Process::updateEntity) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process, $useraccount);
96        return $process;
97    }
98
99    public function updateEntityDisplayNumber(Entity $process): Entity
100    {
101        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::UPDATE);
102        $query->addConditionProcessId($process->getId());
103        $query->addConditionAuthKey($process->getAuthKey());
104
105        $process->displayNumber = $query->getNewDisplayNumber($process);
106        $query->addValueDisplayNumber($process);
107        if ($this->perform($query->getLockProcessId(), ['processId' => $process->getId()])) {
108            $this->writeItem($query);
109        }
110
111        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (updateEntityDisplayNumber) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process);
112        return $process;
113    }
114
115    /**
116     * Update a process with overbooked slots
117     *
118     * @param \BO\Zmsentities\Process $process
119     * @param \DateTimeInterface $now
120     * @param Int $slotsRequired we cannot use process.appointments.0.slotCount, because setting slotsRequired is
121     *        a priviliged operation. Just using the input would be a security flaw to get a wider selection of times
122     *        If slotsRequired = 0, readFreeProcesses() uses the slotsRequired based on request-provider relation
123     * @psalm-api
124     */
125    public function updateEntityWithSlots(\BO\Zmsentities\Process $process, \DateTimeInterface $now, $slotType = "intern", $slotsRequired = 0, int $resolveReferences = 0, $userAccount = null)
126    {
127        if ('intern' != $slotType) {
128            return $this->updateEntity($process, $now, $resolveReferences, null, $userAccount);
129        }
130        $process = clone $process;
131        $appointment = $process->getAppointments()->getFirst();
132        $slotList = (new \BO\Zmsbackend\Slot\Service\Slot())->readByAppointment($appointment, $slotsRequired, true);
133        $processEntityList = $this->readEntityList($process->getId());
134        foreach ($processEntityList as $entity) {
135            if ($process->getId() != $entity->getId()) {
136                $this->writeDeletedEntity($entity->getId());
137            }
138        }
139
140        foreach ($slotList as $slot) {
141            $newProcess = clone $process;
142            $newProcess->getFirstAppointment()->setTime($slot->time);
143            if (! $newProcess->getFirstAppointment()->isMatching($process->getFirstAppointment())) {
144                $this->writeNewProcess($newProcess, $now, $process->id, 0, true, $userAccount);
145            }
146        }
147
148        $appointment->addSlotCount($slotList->count());
149
150        $processEntity = $this->updateEntity($process, $now, $resolveReferences, null, $userAccount);
151        $process = $this->readEntity($process->getId(), $process->authKey, $resolveReferences);
152
153        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::updateEntityWithSlots) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process, $userAccount);
154        return $processEntity;
155    }
156
157    public function redirectToScope(Entity $process, \BO\Zmsentities\Scope $scope, int $waitingNumber, ?\BO\Zmsentities\Useraccount $useraccount = null): Entity
158    {
159        $datetime = \App::$now;
160        $process->setStatus('confirmed');
161        $appointment = $process->getFirstAppointment();
162        $date = (new \DateTimeImmutable())->setTimestamp($appointment->date);
163        $date = $date->setTime(0, 0, 0);
164        $appointment->date = $date->getTimestamp();
165        $process->appointments = new AppointmentList([$appointment]);
166        $newQueueNumber = (new \BO\Zmsbackend\Scope\Service\Scope())->readWaitingNumberUpdated($scope->id, $datetime);
167        $process->addQueue($newQueueNumber, $datetime);
168        $process->queue['number'] = $waitingNumber;
169        $process->priority = \BO\Zmsentities\Collection\QueueList::DEFAULT_PRIORITY_WITH_APPOINTMENT;
170        $process = $this->writeNewProcess($process, $datetime);
171        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::redirectToScope) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_REDIRECTED, $process, $useraccount);
172        $this->writeRequestsToDb($process);
173        return $process;
174    }
175
176    public function readSlotCount(\BO\Zmsentities\Process $process): Entity
177    {
178        $scope = new \BO\Zmsentities\Scope($process->scope);
179        $requestRelationList = (new \BO\Zmsbackend\RequestRelation\Service\RequestRelation())
180            ->readListByProviderId($scope->getProviderId(), $scope->getSource());
181        $appointment = $process->getAppointments()->getFirst();
182        $appointment->slotCount = 0;
183        foreach ($process->requests as $request) {
184            foreach ($requestRelationList as $requestRelation) {
185                if ($requestRelation->getRequest()->getId() == $request->getId()) {
186                    $appointment->slotCount += $requestRelation->getSlotCount();
187                }
188            }
189        }
190        $appointment->slotCount = round($appointment->slotCount, 0);
191        return $process;
192    }
193
194    /**
195     * write a new process with appointment and keep id and authkey from original process
196     */
197    public function writeEntityWithNewAppointment(\BO\Zmsentities\Process $process, \BO\Zmsentities\Appointment $appointment, \DateTimeInterface $now, $slotType = 'public', int $slotsRequired = 0, int $resolveReferences = 0, bool $keepReserved = false): Entity|null
198    {
199        // clone to new process with id = 0 and new appointment to reserve
200        $processNew = clone $process;
201        $processNew->id = 0;
202        $processNew->scope = $appointment->scope;
203        $processNew->queue['arrivalTime'] = 0;
204        $processNew->queue['number'] = 0;
205        $processNew->appointments = (new \BO\Zmsentities\Collection\AppointmentList())->addEntity($appointment);
206//delete old process with following processes
207        $this->writeDeletedEntity($process->getId());
208//reserve new appointment
209        $processNew = \BO\Zmsbackend\Process\Service\ProcessStatusFree::init()
210            ->writeEntityReserved($processNew, $now, $slotType, $slotsRequired);
211        $processTempNewId = $processNew->getId();
212// reassign credentials of new process with credentials of old process
213        $processNew->withReassignedCredentials($process);
214// update new process with old credentials, also assigned requests and following slots
215        $this->updateFollowingProcesses($processTempNewId, $processNew);
216        $this->updateReassignedRequests($processTempNewId, $processNew->getId());
217//delete slot mapping for temp process id
218        (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($processTempNewId);
219//write new slot mapping for changed process with old credentials because new appointment data
220        (new \BO\Zmsbackend\Slot\Service\Slot())->writeSlotProcessMappingFor($processNew->getId());
221        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (\BO\Zmsbackend\Process\Service\Process::writeEntityWithNewAppointment) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process);
222        $status = ($keepReserved) ? Entity::STATUS_RESERVED : ENTITY::STATUS_CONFIRMED;
223        return $this->updateProcessStatus($processNew, $status, $now, $resolveReferences);
224    }
225
226    /**
227     * update following process with new credentials (also change process id if necessary)
228     */
229    public function updateFollowingProcesses($processId, \BO\Zmsentities\Process $processData): void
230    {
231        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_PROCESS_CREDENTIALS, [
232            'newProcessId' => $processData->getId(),
233            'newAuthKey' => $processData->getAuthKey(),
234            'processId' => $processId
235        ]);
236        $processEntityList = $this->readEntityList($processId);
237        if ($processEntityList->count()) {
238            foreach ($processEntityList as $entity) {
239                if ($entity->getId() != $processId) {
240                    $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_FOLLWING_PROCESS, [
241                        'newProcessId' => $processData->getId(),
242                        'processId' => $processId
243                    ]);
244                }
245            }
246        }
247    }
248
249    /**
250     * update process requests with new credentials
251     */
252    public function updateReassignedRequests($processId, $newProcessId): void
253    {
254        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_PROCESS_REQUESTS, [
255            'newProcessId' => $newProcessId,
256            'processId' => $processId
257        ]);
258    }
259
260    /**
261     * write a new process to DB
262     *
263     */
264    protected function writeNewProcess(\BO\Zmsentities\Process $process, \DateTimeInterface $dateTime, int $parentProcess = 0, int $childProcessCount = 0, bool $retry = true, \BO\Zmsentities\Useraccount|null $userAccount = null)
265    {
266        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::INSERT);
267        $process->id = $this->readNewProcessId();
268        $process->setRandomAuthKey();
269        $process->createTimestamp = $dateTime->getTimestamp();
270        if ($parentProcess !== 0) {
271            $process->displayNumber = '';
272        }
273
274        $query->addValuesNewProcess($process, $parentProcess, $childProcessCount);
275
276        if ($parentProcess === 0 && !empty($process->getDisplayNumber())) {
277            $query->addValueDisplayNumber($process);
278        }
279
280        $query->addValuesScopeData($process);
281        $query->addValuesAppointmentData($process);
282        $query->addValuesUpdateProcess($process, $dateTime, $parentProcess);
283        try {
284            $this->writeItem($query);
285        } catch (\BO\Zmsbackend\Exception\Pdo\PDOFailed $exception) {
286            if ($retry) {
287        // First try might fail if two processes are created with the same number at the same time
288                sleep(1);
289        // Let the other process complete his transaction
290                return $this->writeNewProcess($process, $dateTime, $parentProcess, $childProcessCount, false, $userAccount);
291            }
292            throw new \BO\Zmsbackend\Process\Exception\ProcessCreateFailed($exception->getMessage());
293        }
294        (new \BO\Zmsbackend\Slot\Service\Slot())->writeSlotProcessMappingFor($process->id);
295        $checksum = ($userAccount) ? sha1($process->id . '-' . $userAccount->getId()) : '';
296
297        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::writeNewProcess) $process $checksum ", \BO\Zmsbackend\Log\Service\Log::ACTION_NEW, $process, $userAccount);
298        return $process;
299    }
300
301    /**
302     * Fetch a free process ID from DB
303     *
304     */
305    protected function readNewProcessId()
306    {
307        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
308        $newProcessId = $this->fetchValue($query->getQueryNewProcessId());
309        return $newProcessId;
310    }
311
312    /**
313     * Read auth data by processId (for request-side auth checks).
314     *
315     * @return array{authKey: string}|null
316     */
317    public function readAuthKeyByProcessId($processId)
318    {
319        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
320        $query
321            ->addEntityMapping()
322            ->addResolvedReferences(0)
323            ->addConditionProcessId($processId);
324        $process = $this->fetchOne($query, new Entity());
325        return ($process->hasId()) ? array(
326            'authKey' => $process->authKey
327        ) : null;
328    }
329
330    protected function readList($statement, int $resolveReferences): Collection
331    {
332        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
333        $processList = new Collection();
334        while ($processData = $statement->fetch(\PDO::FETCH_ASSOC)) {
335            $entity = new Entity($query->postProcessJoins($processData));
336            $entity = $this->readResolvedReferences($entity, $resolveReferences);
337            $processList->addEntity($entity);
338        }
339        return $processList;
340    }
341
342    protected function readProcessesWithoutRequests($statement): Collection
343    {
344        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
345        $processList = new Collection();
346        while ($processData = $statement->fetch(\PDO::FETCH_ASSOC)) {
347            $processList->addEntity(new Entity($query->postProcessJoins($processData)));
348        }
349        return $processList;
350    }
351
352    protected function attachAllRequestsInOneQuery(Collection $processList, int $resolveReferences): Collection
353    {
354        if ($processList->count() === 0 || $resolveReferences < 0) {
355            return $processList;
356        }
357
358        $processIds = [];
359        foreach ($processList as $process) {
360            if ($process->hasId()) {
361                $processIds[] = $process->getId();
362            }
363        }
364
365        $requestsByProcessId = (new \BO\Zmsbackend\Request\Service\Request())
366            ->readAllRequestsForProcessIds($processIds, $resolveReferences - 1);
367
368        foreach ($processList as $process) {
369            if (!$process->hasId()) {
370                continue;
371            }
372            $process->requests = $requestsByProcessId[(int) $process->getId()]
373                ?? new \BO\Zmsentities\Collection\RequestList();
374        }
375
376        return $processList;
377    }
378
379    /**
380     * Read list with following processes in DB
381     */
382    public function readEntityList($processId, int $resolveReferences = 0)
383    {
384        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
385        $query
386            ->addResolvedReferences($resolveReferences)
387            ->addEntityMapping()
388            ->addConditionProcessIdFollow($processId);
389        $statement = $this->fetchStatement($query);
390        return $this->readList($statement, $resolveReferences)->sortByAppointmentDate();
391    }
392
393    public function readByWorkstation(\BO\Zmsentities\Workstation $workstation, int $resolveReferences = 0)
394    {
395        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
396        $query
397            ->addResolvedReferences($resolveReferences)
398            ->addEntityMapping()
399            ->addConditionWorkstationId($workstation->id);
400        $process = $this->fetchOne($query, new Entity());
401        return ($process->hasId()) ? $this->readResolvedReferences($process, $resolveReferences) : null;
402    }
403
404    /**
405     * Read processList by scopeId and DateTime
406     *
407     * @param array|int $scopeIds
408     * @param \DateTimeInterface $dateTime
409     *
410     * @return Collection
411     *
412     */
413    public function readProcessListByScopesAndTime(
414        $scopeIds,
415        \DateTimeInterface $dateTime,
416        int $resolveReferences = 0,
417        $withEntities = []
418    ) {
419        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT, '', false, null, $withEntities);
420        $query
421            ->addResolvedReferences($resolveReferences)
422            ->addEntityMapping()
423            ->addConditionScopeIds($scopeIds)
424            ->addConditionAssigned()
425            ->addConditionIgnoreSlots()
426            ->addConditionTime($dateTime)
427            ->removeDuplicates();
428        $statement = $this->fetchStatement($query);
429        return $this->readList($statement, $resolveReferences);
430    }
431
432    /**
433     * Read conflictList by scope and date range
434     *
435     * @param \BO\Zmsentities\Scope $scope
436     * @param \DateTimeInterface|null $startDate
437     * @param \DateTimeInterface|null $endDate
438     * @param \DateTimeInterface|null $now
439     * @param int $resolveReferences
440     *
441     * @return Collection
442     */
443    public function readConflictListByScopeAndTime(\BO\Zmsentities\Scope $scope, ?\DateTimeInterface $startDate = null, ?\DateTimeInterface $endDate = null, ?\DateTimeInterface $now = null, int $resolveReferences = 1)
444    {
445        $availabilityList = (new \BO\Zmsbackend\Availability\Service\Availability())
446            ->readAvailabilityListByScope($scope, 0, $startDate, $endDate)
447            ->withScope($scope);
448        if (! $endDate) {
449            $availabilityList = $availabilityList->withDateTime($startDate);
450            $endDate = $startDate;
451        }
452        $currentDate = ($startDate) ? $startDate : $now;
453        $conflictList = $availabilityList->getConflicts($startDate, $endDate);
454        while ($currentDate <= $endDate) {
455            $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
456            $query
457                ->addResolvedReferences($resolveReferences)
458                ->addEntityMapping()
459                ->addConditionScopeId($scope->getId())
460                ->addConditionAssigned()
461                ->addConditionIgnoreSlots();
462            $query->addConditionTime($currentDate);
463            $statement = $this->fetchStatement($query);
464            $processList = $this->readList($statement, $resolveReferences);
465            $processList = $processList->toQueueList($currentDate)->withoutStatus(['queued'])->toProcessList();
466            $conflictList->addList($processList->withOutAvailability($availabilityList));
467            $currentDate = $currentDate->modify('+1 day');
468        }
469        $conflictList = $conflictList->withoutExpiredAppointmentDate($now);
470        return $conflictList;
471    }
472
473
474    /**
475     * Read processList by scopeId and status
476     *
477     * @return Collection
478     *
479     */
480    public function readProcessListByScopeAndStatus(int $scopeId, string $status, int $resolveReferences = 0, int $limit = 1000, ?int $offset = null)
481    {
482        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
483        $query
484            ->addResolvedReferences($resolveReferences)
485            ->addEntityMapping()
486            ->addConditionScopeId($scopeId) //removed because of dismatching scope and pickup scope
487            ->addConditionStatus($status)
488            ->addLimit($limit, $offset);
489        $statement = $this->fetchStatement($query);
490        return $this->readList($statement, $resolveReferences);
491    }
492
493    /**
494     * Read processList by clusterId and DateTime
495     *
496     * @param int $clusterId
497     * @param \DateTimeInterface $dateTime
498     *
499     * @return Collection
500     */
501    public function readProcessListByClusterAndTime($clusterId, \DateTimeInterface $dateTime)
502    {
503        $cluster = (new \BO\Zmsbackend\Cluster\Service\Cluster())->readEntity($clusterId, 1);
504        $scopeIds = [];
505        if ($cluster->scopes->count()) {
506            foreach ($cluster->scopes as $scope) {
507                $scopeIds[] = $scope->id;
508            }
509        }
510
511        return $this->readProcessListByScopesAndTime($scopeIds, $dateTime);
512    }
513
514    /**
515     * Read processList by scopeId to get a number of all processes of a scope
516     *
517     * @param int $scopeId
518     *
519     * @return Collection
520     */
521    public function readProcessListCountByScope($scopeId)
522    {
523        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
524        $query
525            ->addCountValue()
526            ->addConditionAssigned()
527            ->addConditionIgnoreSlots()
528            ->addConditionScopeId($scopeId);
529        $statement = $this->fetchStatement($query);
530        $result = $statement->fetch(\PDO::FETCH_ASSOC);
531        return $result['processCount'];
532    }
533
534    /**
535     * Read processList by mail address
536     *
537     * @return Collection
538     */
539    public function readProcessListByMailAddress(string $mailAddress, ?int $scopeId = null, int $resolveReferences = 0, int $limit = 2000): Collection
540    {
541        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
542        $query
543            ->addResolvedReferences($resolveReferences)
544            ->addEntityMapping()
545            ->addConditionMail($mailAddress, true)
546            ->addConditionIgnoreSlots()
547            ->addLimit($limit);
548        if ($scopeId) {
549            $query->addConditionScopeId($scopeId);
550        }
551
552        $statement = $this->fetchStatement($query);
553        return $this->readList($statement, $resolveReferences);
554    }
555
556    /**
557     * Read processList by mail address and statuslist
558     *
559     * @return Collection
560     *
561     */
562    public function readListByMailAndStatusList(string $mailAddress, array $statusList, int $resolveReferences = 1, int $limit = 300): Collection
563    {
564        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
565        $query
566            ->addResolvedReferences($resolveReferences)
567            ->addEntityMapping()
568            ->addConditionMail($mailAddress, true)
569            ->addConditionIgnoreSlots()
570            ->addLimit($limit);
571        $statement = $this->fetchStatement($query);
572        $collection = $this->readList($statement, $resolveReferences);
573        return $collection->toProcessListByStatusList($statusList);
574    }
575
576
577    /**
578     * Markiere einen Termin als bestätigt
579     *
580     * @param \BO\Zmsentities\Process $process
581     *
582     * @return Entity|null
583     *
584     */
585    public function updateProcessStatus(Entity $process, string $status, \DateTimeInterface $dateTime, int $resolveReferences = 0, $userAccount = null)
586    {
587        $process = (new ProcessStatus())
588            ->writeUpdatedStatus($process, $status, $dateTime, $resolveReferences, $userAccount);
589
590        /** @var Entity $process */
591        if ($this->shouldUpdateDisplayNumber($process, $status)) {
592            $this->updateEntityDisplayNumber($process);
593        }
594
595        return $process;
596    }
597
598    public function shouldUpdateDisplayNumber(Entity $process, $status): bool
599    {
600        if ($status !== 'preconfirmed' && $status !== 'confirmed') {
601            return false;
602        }
603        $displayNumberPrefix = $process->scope->getPreference('queue', 'displayNumberPrefix');
604        if (empty($displayNumberPrefix)) {
605            return false;
606        }
607
608        if (str_starts_with($process->getDisplayNumber(), $displayNumberPrefix)) {
609            return false;
610        }
611
612        return true;
613    }
614
615    /**
616     * Löscht einen Termin aus der Datenbank
617     * Regulär sollte aber \BO\Zmsbackend\Process\Service\ProcessStatusArchived::writeEntityFinished()
618     * oder self::writeBlockedEntity() verwendet werden.
619     *
620     * @return bool
621     */
622    public function writeDeletedEntity($processId): bool
623    {
624        $processEntityList = $this->readEntityList($processId);
625        $status = false;
626        if ($processEntityList->count()) {
627            foreach ($processEntityList as $entity) {
628                $entityId = $entity->getId();
629                $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_DELETE;
630                $status = $this->perform($query, array(
631                    $entityId,
632                    $entityId
633                ));
634                if ($status) {
635                            $this->deleteRequestsForProcessId($entityId);
636                            (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($entityId);
637                            \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeDeletedEntity) $entityId ", \BO\Zmsbackend\Log\Service\Log::ACTION_DELETED, $entity);
638                }
639            }
640        }
641
642        return $status;
643    }
644
645    /**
646     * ACHTUNG: Nur noch als Helferfunction vor Refactoring durch MF,
647     * damit unittests und zmsappointment wie gewohnt funktionieren
648     *
649     * @param int|string $processId
650     * @param string $authKey
651     *
652     * @return Entity|null
653     */
654    public function deleteEntity($processId, $authKey)
655    {
656        return $this->writeCanceledEntity($processId, $authKey);
657    }
658
659    /**
660     * Markiere einen Termin als abgesagt
661     *
662     * @param int|string $processId
663     * @param string $authKey
664     *
665     * @return Entity|null
666     */
667    public function writeCanceledEntity($processId, $authKey, $now = null, ?\BO\Zmsentities\Useraccount $useraccount = null)
668    {
669        $canceledTimestamp = ($now) ? $now->getTimestamp() : (new \DateTimeImmutable())->getTimestamp();
670        $newAuthKey = bin2hex(random_bytes(32));
671        $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_CANCELED;
672        $this->perform($query, [
673            'processId' => $processId,
674            'authKey' => $authKey,
675            'canceledTimestamp' => $canceledTimestamp,
676            'newAuthKey' => $newAuthKey
677        ]);
678        $process = $this->readEntity($processId, new \BO\Zmsbackend\Helper\NoAuth(), 0);
679        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeCanceledEntity) $processId ", \BO\Zmsbackend\Log\Service\Log::ACTION_CANCELED, $process, $useraccount);
680        return $process;
681    }
682
683    /**
684     * Markiere einen Termin als dereferenced
685     *
686     * @param \BO\Zmsentities\Process $process
687     * @param bool $releaseSlots
688     * @param \BO\Zmsentities\Useraccount|null $useraccount
689     *
690     * @return Entity|null
691     */
692    public function writeBlockedEntity(\BO\Zmsentities\Process $process, bool $releaseSlots = false, ?\BO\Zmsentities\Useraccount $useraccount = null)
693    {
694        $amendment = $process->toDerefencedAmendment();
695        $customTextfield = $process->toDerefencedcustomTextfield();
696        $customTextfield2 = $process->toDerefencedcustomTextfield2();
697        if (!isset($process->queue['status'])) {
698            $process->queue['status'] = $process->status;
699        }
700        $process->status = 'blocked';
701        $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_DEREFERENCED;
702        $status = $this->perform($query, array(
703            $amendment,
704            $customTextfield,
705            $customTextfield2,
706            $process->id,
707            $process->authKey,
708            $process->id
709        ));
710        if ($status) {
711            $processEntityList = $this->readEntityList($process->id);
712            if ($processEntityList->count()) {
713                foreach ($processEntityList as $entity) {
714                    $entityId = $entity->getId();
715                    if ($releaseSlots) {
716                        (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($entityId);
717                    }
718                    \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeBlockedEntity) $entityId ", \BO\Zmsbackend\Log\Service\Log::ACTION_DELETED, $process, $useraccount);
719                }
720            }
721        }
722        return $status;
723    }
724
725    protected function writeRequestsToDb(\BO\Zmsentities\Process $process): void
726    {
727        // Beware of resolveReferences=0 to not delete the existing requests, except for queued processes
728        $hasRequests = ($process->requests && count($process->requests));
729        if ($hasRequests || 'queued' == $process->status) {
730            $this->deleteRequestsForProcessId($process->id);
731        }
732        if ($hasRequests) {
733            $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::INSERT);
734            foreach ($process->requests as $request) {
735                if ($request->id >= 0) {
736        // allow deleting requests with a -1 request
737                    $query->addValues([
738                            'AnliegenID' => $request['id'],
739                            'source' => $request['source'],
740                            'BuergerID' => $process->id
741                        ]);
742                    $this->writeItem($query);
743                }
744            }
745        }
746    }
747
748    protected function deleteRequestsForProcessId($processId): bool
749    {
750        $status = false;
751        if (0 < $processId) {
752            $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::DELETE);
753            $query->addConditionProcessId($processId);
754            $status = $this->deleteItem($query);
755        }
756        return $status;
757    }
758
759    public function readExpiredProcessList(\DateTimeInterface $expirationDate, int $limit = 500, int $resolveReferences = 0, ?int $offset = null)
760    {
761        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
762        $selectQuery
763            ->addEntityMapping()
764            ->addResolvedReferences($resolveReferences)
765            ->addConditionProcessDeleteInterval($expirationDate)
766            ->addConditionIgnoreSlots()
767            ->addLimit($limit, $offset);
768        $statement = $this->fetchStatement($selectQuery);
769        return $this->readList($statement, $resolveReferences);
770    }
771    public function readUnconfirmedProcessList(\DateTimeInterface $expirationDate, $scopeId = 0, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
772    {
773
774        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
775        $selectQuery
776            ->addEntityMapping()
777            ->addResolvedReferences($resolveReferences)
778            ->addConditionScopeId($scopeId)
779            ->addConditionProcessExpiredIPTimeStamp($expirationDate)
780            ->addConditionStatus('preconfirmed')
781            ->addConditionIgnoreSlots()
782            ->addLimit($limit, $offset);
783        $statement = $this->fetchStatement($selectQuery);
784        return $this->readList($statement, $resolveReferences);
785    }
786
787    public function readExpiredProcessListByStatus(\DateTimeInterface $expirationDate, $status, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
788    {
789        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
790        $selectQuery
791            ->addEntityMapping()
792            ->addResolvedReferences($resolveReferences)
793            ->addConditionProcessDeleteBeforeDate($expirationDate)
794            ->addConditionStatus($status)
795            ->addConditionIgnoreSlots()
796            ->addLimit($limit, $offset);
797        $statement = $this->fetchStatement($selectQuery);
798        return $this->readList($statement, $resolveReferences);
799    }
800
801    public function readExpiredReservationsList(\DateTimeInterface $expirationDate, $scopeId, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
802    {
803        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
804        $selectQuery
805            ->addEntityMapping()
806            ->addResolvedReferences($resolveReferences)
807            ->addConditionScopeId($scopeId)
808            ->addConditionIsReserved()
809            ->addConditionProcessExpiredIPTimeStamp($expirationDate)
810            ->addConditionIgnoreSlots()
811            ->addLimit($limit, $offset);
812        $statement = $this->fetchStatement($selectQuery);
813        return $this->readList($statement, $resolveReferences);
814    }
815
816    public function readEmailReminderProcessListByInterval(\DateTimeInterface $now, \DateTimeInterface $lastRun, int $defaultReminderInMinutes, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
817    {
818        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
819        $selectQuery
820            ->addEntityMapping()
821            ->addResolvedReferences($resolveReferences)
822            ->addConditionProcessMailReminder($now, $lastRun, $defaultReminderInMinutes)
823            ->addConditionAssigned()
824            ->addConditionIgnoreSlots()
825            ->addConditionStatus('confirmed')
826            ->addLimit($limit, $offset);
827        $statement = $this->fetchStatement($selectQuery);
828        return $this->readList($statement, $resolveReferences)->withDepartmentHasMailFrom();
829    }
830
831    public function readDeallocateProcessList(\DateTimeInterface $now, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
832    {
833        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
834        $selectQuery
835            ->addEntityMapping()
836            ->addResolvedReferences($resolveReferences)
837            ->addConditionDeallocate($now)
838            ->addConditionIgnoreSlots()
839            ->addLimit($limit, $offset);
840        $statement = $this->fetchStatement($selectQuery);
841        return $this->readList($statement, $resolveReferences);
842    }
843
844    public function isAppointmentAllowedWithSameMail(Entity $entity): bool
845    {
846        if (empty($entity->getClients()) || empty($entity->getClients()->getFirst())) {
847            return true;
848        }
849
850        $maxAppointmentsPerMail = $entity->scope->getAppointmentsPerMail();
851        $emailToCheck = $entity->getClients()->getFirst()->email;
852        if ($maxAppointmentsPerMail < 1 || empty($emailToCheck)) {
853            return true;
854        }
855
856        if ($this->isMailWhitelisted($emailToCheck, $entity->scope)) {
857            return true;
858        }
859
860        $processes = $this->readProcessListByMailAddress($entity->getClients()->getFirst()->email, $entity->scope->id);
861        $activeAppointments = 0;
862        foreach ($processes as $process) {
863            if ($entity->id == $process->id) {
864                return true;
865            }
866
867            if (in_array($process->getStatus(), ['preconfirmed', 'confirmed'])) {
868                $activeAppointments++;
869                if ($activeAppointments >= $maxAppointmentsPerMail) {
870                    return false;
871                }
872            }
873        }
874
875        return true;
876    }
877
878    public function isAppointmentSlotCountAllowed(Entity $entity): bool
879    {
880        if (empty($entity->scope)) {
881            return true;
882        }
883
884        $maxSlotsPerAppointment = $entity->scope->getSlotsPerAppointment();
885
886        if ($maxSlotsPerAppointment === null || $maxSlotsPerAppointment < 1) {
887            $maxSlotsPerAppointment = \BO\Zmsbackend\Slot\Service\Slot::MAX_SLOTS;
888        }
889
890        $appointment = $entity->getAppointments()->getFirst();
891        if (!$appointment) {
892            return true;
893        }
894
895        $slotCount = (int) ($appointment->slotCount ?? 0);
896        if ($slotCount <= 0) {
897            return true;
898        }
899
900        return $slotCount <= (int) $maxSlotsPerAppointment;
901    }
902
903    public function isServiceQuantityAllowed(Entity $entity): bool
904    {
905        if (empty($entity->scope) || empty($entity->requests)) {
906            return true;
907        }
908
909        try {
910            $providerId = $entity->scope->getProviderId();
911        } catch (\Exception $e) {
912            return true;
913        }
914        if (!$providerId) {
915            return true;
916        }
917
918        $requestCounts = [];
919        foreach ($entity->requests as $request) {
920            $requestId = $request->getId();
921            if (!isset($requestCounts[$requestId])) {
922                $requestCounts[$requestId] = 0;
923            }
924            $requestCounts[$requestId]++;
925        }
926
927        $requestRelationDb = new \BO\Zmsbackend\RequestRelation\Service\RequestRelation();
928        foreach ($requestCounts as $requestId => $count) {
929            $requestRelation = $requestRelationDb->readEntity($requestId, $providerId, 0);
930            if ($requestRelation) {
931                $maxQuantity = $requestRelation->getMaxQuantity();
932                if ($maxQuantity !== null && $maxQuantity > 0 && $count > (int) $maxQuantity) {
933                    return false;
934                }
935            }
936        }
937
938        return true;
939    }
940
941    protected function isMailWhitelisted(string $email, ScopeEntity $scope): bool
942    {
943        $emailsWithNoLimit = explode(',', $scope->getWhitelistedMails());
944        if (empty($emailsWithNoLimit)) {
945            return false;
946        }
947
948        foreach ($emailsWithNoLimit as $whitelistedMail) {
949            $whitelistedMail = trim($whitelistedMail);
950            if ($email === $whitelistedMail) {
951                return true;
952            }
953
954            if (str_starts_with($whitelistedMail, '@') && str_contains($email, $whitelistedMail)) {
955                return true;
956            }
957        }
958
959        return false;
960    }
961
962    public function readProcessWithSameDayAndDisplayNumber($scopeId, $displayNumber, $date)
963    {
964        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
965        $query->addEntityMapping()
966            ->addResolvedReferences(1)
967            ->addConditionScopeId($scopeId)
968            ->addConditionDate($date)
969            ->addConditionDisplayNumber($displayNumber)
970            ->addLimit(1);
971
972        $process = $this->fetchOne($query, new Entity());
973
974        return $this->readResolvedReferences($process, 1);
975    }
976
977    public function readProcessListByExternalUserId(string $externalUserId, ?int $filterId = null, ?string $status = null, int $resolveReferences = 0, int $limit = 1000): Collection
978    {
979        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
980        $query
981            ->addResolvedReferences($resolveReferences)
982            ->addEntityMapping()
983            ->addConditionExternalUserId($externalUserId);
984        if (!is_null($filterId)) {
985            $query->addConditionProcessId($filterId);
986        }
987        if (!is_null($status)) {
988            $query->addConditionStatus($status);
989        }
990        $query
991            ->addLimit($limit);
992
993        $statement = $this->fetchStatement($query);
994        $processList = $this->readProcessesWithoutRequests($statement);
995        return $this->attachAllRequestsInOneQuery($processList, (int) $resolveReferences);
996    }
997
998    public function readAssignedWorkstationIdForUpdate(int $processId): ?int
999    {
1000        $query = (new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT))->getLockAssignedWorkstationId();
1001        $value = $this->fetchValue($query, ['processId' => $processId]);
1002
1003        if ($value === false || $value === null) {
1004            return null;
1005        }
1006
1007        return (int) $value;
1008    }
1009}