Lines 89.62% 674 / 752
Methods 79.01% 64 / 81
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readArchivedEntity 88.88% 8 / 9 0.00% 0 / 1 2.01
 readListByScopeId 100.00% 5 / 5 100.00% 1 / 1 1
 readListByDate 100.00% 5 / 5 100.00% 1 / 1 1
 readListByScopeAndDate 0.00% 0 / 6 0.00% 0 / 1 2
 readListByScopesAndDates 100.00% 6 / 6 100.00% 1 / 1 1
 deleteBeforeDate 100.00% 6 / 6 100.00% 1 / 1 1
 readListForStatistic 100.00% 6 / 6 100.00% 1 / 1 1
 readListIsMissed 100.00% 5 / 5 100.00% 1 / 1 1
 readListWithAppointment 100.00% 5 / 5 100.00% 1 / 1 1
 readResolvedList 100.00% 10 / 10 100.00% 1 / 1 5
 writeEntityFinished 100.00% 25 / 25 100.00% 1 / 1 6
 writeArchivedProcessToStatistic 100.00% 16 / 16 100.00% 1 / 1 2
 writeNewArchivedProcess 100.00% 15 / 15 100.00% 1 / 1 2
 writeXRequestsArchived 100.00% 7 / 7 100.00% 1 / 1 1
 anonymizeNames 0.00% 0 / 6 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readEntity 100.00% 11 / 11 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] readById 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readResolvedReferences 100.00% 7 / 7 100.00% 1 / 1 3
 [BO\Zmsbackend\Process\Service\Process] updateEntity 100.00% 16 / 16 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] updateEntityDisplayNumber 0.00% 0 / 9 0.00% 0 / 1 6
 [BO\Zmsbackend\Process\Service\Process] updateEntityWithSlots 90.00% 18 / 20 0.00% 0 / 1 6.04
 [BO\Zmsbackend\Process\Service\Process] redirectToScope 0.00% 0 / 15 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readSlotCount 100.00% 11 / 11 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] writeEntityWithNewAppointment 100.00% 20 / 20 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] updateFollowingProcesses 53.84% 7 / 13 0.00% 0 / 1 5.57
 [BO\Zmsbackend\Process\Service\Process] updateReassignedRequests 100.00% 4 / 4 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] writeNewProcess 100.00% 22 / 22 100.00% 1 / 1 7
 [BO\Zmsbackend\Process\Service\Process] readNewProcessId 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readAuthKeyByProcessId 100.00% 9 / 9 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readList 90.90% 10 / 11 0.00% 0 / 1 4.01
 [BO\Zmsbackend\Process\Service\Process] readProcessesWithoutRequests 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] attachAllRequestsInOneQuery 78.57% 11 / 14 0.00% 0 / 1 7.48
 [BO\Zmsbackend\Process\Service\Process] readEntityList 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readByWorkstation 100.00% 7 / 7 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readProcessListByScopesAndTime 100.00% 11 / 11 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readConflictListByScopeAndTime 100.00% 24 / 24 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] readProcessListByScopeAndStatus 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readProcessListByClusterAndTime 100.00% 6 / 6 100.00% 1 / 1 3
 [BO\Zmsbackend\Process\Service\Process] readProcessListCountByScope 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readProcessListByMailAddress 100.00% 11 / 11 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readListByMailAndStatusList 100.00% 10 / 10 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] updateProcessStatus 80.00% 4 / 5 0.00% 0 / 1 2.03
 [BO\Zmsbackend\Process\Service\Process] shouldUpdateDisplayNumber 62.50% 5 / 8 0.00% 0 / 1 6.32
 [BO\Zmsbackend\Process\Service\Process] writeDeletedEntity 100.00% 15 / 15 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] deleteEntity 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] writeCanceledEntity 100.00% 12 / 12 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] writeBlockedEntity 100.00% 24 / 24 100.00% 1 / 1 6
 [BO\Zmsbackend\Process\Service\Process] writeRequestsToDb 100.00% 13 / 13 100.00% 1 / 1 7
 [BO\Zmsbackend\Process\Service\Process] deleteRequestsForProcessId 100.00% 6 / 6 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readExpiredProcessList 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readUnconfirmedProcessList 0.00% 0 / 8 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readExpiredProcessListByStatus 100.00% 10 / 10 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readExpiredReservationsList 100.00% 8 / 8 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] newDeleteListQuery 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readDeleteList 100.00% 10 / 10 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readEmailReminderProcessListByInterval 100.00% 11 / 11 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readDeallocateProcessList 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] isAppointmentAllowedWithSameMail 94.44% 17 / 18 0.00% 0 / 1 10.02
 [BO\Zmsbackend\Process\Service\Process] isMailWhitelisted 90.00% 9 / 10 0.00% 0 / 1 6.04
 [BO\Zmsbackend\Process\Service\Process] readProcessWithSameDayAndDisplayNumber 0.00% 0 / 9 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readProcessListByExternalUserId 100.00% 14 / 14 100.00% 1 / 1 3
 [BO\Zmsbackend\Process\Service\Process] readAssignedWorkstationIdForUpdate 80.00% 4 / 5 0.00% 0 / 1 3.07
 [BO\Zmsbackend\Base] __construct 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] init 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] getWriter 100.00% 4 / 4 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] getReader 100.00% 5 / 5 100.00% 1 / 1 3
 [BO\Zmsbackend\Base] fetchPreparedStatement 100.00% 9 / 9 100.00% 1 / 1 3
 [BO\Zmsbackend\Base] startExecute 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] pdoExceptionHandler 100.00% 13 / 13 100.00% 1 / 1 4
 [BO\Zmsbackend\Base] fetchStatement 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchOne 100.00% 7 / 7 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] fetchRow 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchValue 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchAll 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchHandle 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchList 100.00% 8 / 8 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] writeItem 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] deleteItem 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] perform 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchAffected 100.00% 8 / 8 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] hashStringValue 50.00% 5 / 10 0.00% 0 / 1 8.12
8class ProcessStatusArchived extends Process
9{
10    /**
11     * @param false|string $archiveId
12     */
13    public function readArchivedEntity(string|false $archiveId, int $resolveReferences = 0)
14    {
15        if (!$archiveId) {
16            return null;
17        }
18        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
19        $query->addEntityMapping()
20            ->addResolvedReferences($resolveReferences)
21            ->addConditionArchiveId($archiveId);
22        $archive = $this->fetchOne($query, new Entity());
23        $archive = $this->readResolvedReferences($archive, $resolveReferences);
24        return $archive;
25    }
26
27    public function readListByScopeId(string|int $scopeId, int $resolveReferences = 0)
28    {
29        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
30        $query->addEntityMapping()
31            ->addResolvedReferences($resolveReferences)
32            ->addConditionScopeId($scopeId);
33        return $this->readResolvedList($query, $resolveReferences);
34    }
35
36    public function readListByDate(\DateTimeInterface $dateTime, int $resolveReferences = 0)
37    {
38        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
39        $query->addEntityMapping()
40            ->addResolvedReferences($resolveReferences)
41            ->addConditionTime($dateTime);
42        return $this->readResolvedList($query, $resolveReferences);
43    }
44
45    /** @psalm-api */
46    public function readListByScopeAndDate(string|int $scopeId, \DateTimeInterface $dateTime, int $resolveReferences = 0)
47    {
48        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
49        $query->addEntityMapping()
50            ->addConditionScopeId($scopeId)
51            ->addResolvedReferences($resolveReferences)
52            ->addConditionTime($dateTime);
53        return $this->readResolvedList($query, $resolveReferences);
54    }
55
56    /**
57     * @param (\BO\Zmsentities\Helper\DateTime|false)[] $dateTimes
58     *
59     */
60    public function readListByScopesAndDates(array $scopeIds, array $dateTimes, int $resolveReferences = 0)
61    {
62        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchivedToday(\BO\Zmsbackend\Query\Base::SELECT);
63        $query->addEntityMapping()
64            ->addConditionScopeIds($scopeIds)
65            ->addResolvedReferences($resolveReferences)
66            ->addConditionTimes($dateTimes);
67
68        return $this->readResolvedList($query, $resolveReferences);
69    }
70
71    public function deleteBeforeDate(\DateTimeInterface $now): bool
72    {
73        return (bool)$this->perform(
74            \BO\Zmsbackend\Process\Repository\ProcessStatusArchivedToday::DELETE_BEFORE_DATE,
75            [
76                'theDay' => $now->format('Y-m-d'),
77            ]
78        );
79    }
80
81    /** @psalm-api */
82    public function readListForStatistic(\DateTimeInterface $dateTime, \BO\Zmsentities\Scope $scope, int $limit = 500, int $resolveReferences = 0)
83    {
84        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
85        $query->addEntityMapping()
86            ->addResolvedReferences($resolveReferences)
87            ->addJoinStatisticFailed($dateTime, $scope)
88            ->addLimit($limit);
89        return $this->readResolvedList($query, $resolveReferences);
90    }
91
92    public function readListIsMissed(int $isMissed = 1, int $resolveReferences = 0)
93    {
94        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
95        $query->addEntityMapping()
96            ->addResolvedReferences($resolveReferences)
97            ->addConditionIsMissed($isMissed);
98        return $this->readResolvedList($query, $resolveReferences);
99    }
100
101    public function readListWithAppointment(int $withAppointment = 1, int $resolveReferences = 0)
102    {
103        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::SELECT);
104        $query->addEntityMapping()
105            ->addResolvedReferences($resolveReferences)
106            ->addConditionWithAppointment($withAppointment);
107        return $this->readResolvedList($query, $resolveReferences);
108    }
109
110    protected function readResolvedList(\BO\Zmsbackend\Process\Repository\ProcessStatusArchived $query, int $resolveReferences): Collection
111    {
112        $processList = new Collection();
113        $resultList = $this->fetchList($query, new Entity());
114        if (count($resultList)) {
115            foreach ($resultList as $entity) {
116                if (0 == $resolveReferences) {
117                    $processList->addEntity($entity);
118                } else {
119                    if ($entity instanceof Entity) {
120                        $entity = $this->readResolvedReferences($entity, $resolveReferences);
121                        $processList->addEntity($entity);
122                    }
123                }
124            }
125        }
126        return $processList;
127    }
128
129    public function writeEntityFinished(
130        \BO\Zmsentities\Process $process,
131        \DateTimeInterface $now,
132        bool $calculateStatistic = false,
133        ?\BO\Zmsentities\Useraccount $useraccount = null,
134        ?string $historyStatus = null
135    ) {
136        if ($process->isDereferenced() || !$process->getScopeId()) {
137            return null;
138        }
139
140        $process = $this->updateEntity(
141            $process,
142            $now,
143            1,
144            null,
145            $useraccount
146        );
147
148        if ($historyStatus !== null) {
149            $historyService = new \BO\Zmsbackend\ProcessSearchHistory\Service\ProcessSearchHistory(
150                $this->getWriter(),
151                $this->getReader()
152            );
153
154            $historyService->writeHistoryEntry(
155                $process,
156                $historyStatus,
157                $now
158            );
159        }
160        $archived = null;
161        if ($this->writeBlockedEntity($process)) {
162            $archived = $this->writeNewArchivedProcess($process, $now, 0, $calculateStatistic);
163        }
164        // update xRequest entry and update process id as well as archived id
165        if ($archived) {
166            $this->writeXRequestsArchived($process->id, $archived->archiveId);
167        }
168        return $archived;
169    }
170
171    /**
172     * write an archived process to statistic table
173     *
174     * @psalm-api
175     */
176    public function writeArchivedProcessToStatistic(
177        Entity $process,
178        string|int $requestId,
179        string|int $clusterId,
180        string|int $providerId,
181        string|int $departmentId,
182        string|int $organisationId,
183        string|int $ownerId,
184        \DateTimeInterface|false $dateTime,
185        ?int $processingTime
186    ) {
187        return $this->perform(
188            \BO\Zmsbackend\Process\Repository\ProcessStatusArchived::QUERY_INSERT_IN_STATISTIC,
189            [
190                'archiveId' => $process->archiveId,
191                'scopeId' => $process->scope->getId(),
192                'clusterId' => $clusterId,
193                'providerId' => $providerId,
194                'departmentId' => $departmentId,
195                'organisationId' => $organisationId,
196                'ownerId' => $ownerId,
197                'date' => $process->getFirstAppointment()->toDateTime()->format('Y-m-d'),
198                'withAppointment' => ($process->toQueue($dateTime)->withAppointment) ? 1 : 0,
199                'requestId' => $requestId,
200                'processingTime' => $processingTime
201            ]
202        );
203    }
204
205    /**
206     * write a new archived process to DB
207     *
208     */
209    public function writeNewArchivedProcess(
210        \BO\Zmsentities\Process $process,
211        \DateTimeInterface $now,
212        int $resolveReferences = 0,
213        bool $calculateStatistic = false
214    ) {
215        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchivedToday(\BO\Zmsbackend\Query\Base::INSERT);
216        $query->addValuesNewArchive($process, $now);
217        $this->writeItem($query);
218
219        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::INSERT);
220        $query->addValuesNewArchive($process, $now);
221        $this->writeItem($query);
222
223        $archiveId = $this->getWriter()->lastInsertId();
224        \BO\Zmsbackend\Log\Service\Log::writeProcessLog(
225            "ARCHIVE (Archive::writeNewArchivedProcess) $archiveId -> $process ",
226            \BO\Zmsbackend\Log\Service\Log::ACTION_ARCHIVED,
227            $process
228        );
229
230        if ($calculateStatistic) {
231            (new \BO\Zmsbackend\Exchange\Service\ExchangeWaitingscope())->updateWaitingStatistics($process, $now);
232        }
233
234        return $this->readArchivedEntity($archiveId, $resolveReferences);
235    }
236
237    protected function writeXRequestsArchived(string|int $processId, string|int $archiveId): void
238    {
239        $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::UPDATE);
240        $query->addConditionProcessId($processId);
241        $query->addValues([
242            'BuergerID' => 0,
243            'BuergerarchivID' => $archiveId
244        ]);
245        $this->writeItem($query);
246    }
247
248    /**
249     * Anonymizes names in the buergerarchiv table for entries older than a specified timespan.
250     *
251     * @param \DateTimeInterface $dateTime The date before which records should be anonymized.
252     * @return bool Indicates whether the update operation was successful.
253     */
254    public function anonymizeNames(\DateTimeInterface $dateTime)
255    {
256        $query = new \BO\Zmsbackend\Process\Repository\ProcessStatusArchived(\BO\Zmsbackend\Query\Base::UPDATE);
257        $query->addConditionOlderThanDate($dateTime);
258        $query->addValues([
259            'name' => 'ANONYMIZED'
260        ]);
261
262        return $this->writeItem($query);
263    }
264}

Inherited from BO\Zmsbackend\Process\Service\Process

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    }
42    public function readById(string|int $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    }
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    }
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    }
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    }
125    public function updateEntityWithSlots(\BO\Zmsentities\Process $process, \DateTimeInterface $now, ?string $slotType = "intern", $slotsRequired = 0, int $resolveReferences = 0, ?\BO\Zmsentities\Useraccount $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        $slotService = new \BO\Zmsbackend\Slot\Service\Slot();
133        $reservation = $slotService->readReservationByAppointment($appointment, $slotsRequired, true);
134        $slotList = $reservation['slotList'];
135        $availabilityId = (int) $reservation['availability']->getId() ?: null;
136        $processEntityList = $this->readEntityList($process->getId());
137        foreach ($processEntityList as $entity) {
138            if ($process->getId() != $entity->getId()) {
139                $this->writeDeletedEntity($entity->getId());
140            }
141        }
142        // One row stores the length. Map its steps after that length is saved, on the availability
143        // chosen under the slot lock.
144        $appointment->addSlotCount($slotList->count());
145        $processEntity = $this->updateEntity($process, $now, $resolveReferences, null, $userAccount);
146        $savedProcess = $this->readEntity($process->getId(), $process->authKey, $resolveReferences);
147        if ($savedProcess instanceof Entity) {
148            $process = $savedProcess;
149        }
150        $slotService->writeSlotProcessMappingFor($process->getId(), $availabilityId);
151
152        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::updateEntityWithSlots) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process, $userAccount);
153        return $processEntity;
154    }
156    public function redirectToScope(Entity $process, \BO\Zmsentities\Scope $scope, int $waitingNumber, ?\BO\Zmsentities\Useraccount $useraccount = null): Entity
157    {
158        $datetime = \App::$now;
159        $process->setStatus('confirmed');
160        $appointment = $process->getFirstAppointment();
161        $date = (new \DateTimeImmutable())->setTimestamp($appointment->date);
162        $date = $date->setTime(0, 0, 0);
163        $appointment->date = $date->getTimestamp();
164        $process->appointments = new AppointmentList([$appointment]);
165        $newQueueNumber = (new \BO\Zmsbackend\Scope\Service\Scope())->readWaitingNumberUpdated($scope->id, $datetime);
166        $process->addQueue($newQueueNumber, $datetime);
167        $process->queue['number'] = $waitingNumber;
168        $process->priority = \BO\Zmsentities\Collection\QueueList::DEFAULT_PRIORITY_WITH_APPOINTMENT;
169        $process = $this->writeNewProcess($process, $datetime);
170        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::redirectToScope) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_REDIRECTED, $process, $useraccount);
171        $this->writeRequestsToDb($process);
172        return $process;
173    }
175    public function readSlotCount(\BO\Zmsentities\Process $process): Entity
176    {
177        $scope = new \BO\Zmsentities\Scope($process->scope);
178        $requestRelationList = (new \BO\Zmsbackend\RequestRelation\Service\RequestRelation())
179            ->readListByProviderId($scope->getProviderId(), $scope->getSource());
180        $appointment = $process->getAppointments()->getFirst();
181        $appointment->slotCount = 0;
182        foreach ($process->requests as $request) {
183            foreach ($requestRelationList as $requestRelation) {
184                if ($requestRelation->getRequest()->getId() == $request->getId()) {
185                    $appointment->slotCount += $requestRelation->getSlotCount();
186                }
187            }
188        }
189        $appointment->slotCount = round($appointment->slotCount, 0);
190        return $process;
191    }
196    public function writeEntityWithNewAppointment(\BO\Zmsentities\Process $process, \BO\Zmsentities\Appointment $appointment, \DateTimeInterface $now, string $slotType = 'public', int $slotsRequired = 0, int $resolveReferences = 0, bool $keepReserved = false): Entity|null
197    {
198        // clone to new process with id = 0 and new appointment to reserve
199        $processNew = clone $process;
200        $processNew->id = 0;
201        $processNew->scope = $appointment->scope;
202        $processNew->queue['arrivalTime'] = 0;
203        $processNew->queue['number'] = 0;
204        $processNew->appointments = (new \BO\Zmsentities\Collection\AppointmentList())->addEntity($appointment);
205//delete old process with following processes
206        $this->writeDeletedEntity($process->getId());
207//reserve new appointment
208        $processNew = \BO\Zmsbackend\Process\Service\ProcessStatusFree::init()
209            ->writeEntityReserved($processNew, $now, $slotType, $slotsRequired);
210        $processTempNewId = $processNew->getId();
211// reassign credentials of new process with credentials of old process
212        $processNew->withReassignedCredentials($process);
213// update new process with old credentials, also assigned requests and following slots
214        $this->updateFollowingProcesses($processTempNewId, $processNew);
215        $this->updateReassignedRequests($processTempNewId, $processNew->getId());
216//keep the availability chosen by the reservation, then delete slot mapping for temp process id
217        $slotService = new \BO\Zmsbackend\Slot\Service\Slot();
218        $reservedAvailabilityId = $slotService->readMappedAvailabilityId($processTempNewId);
219        $slotService->deleteSlotProcessMappingFor($processTempNewId);
220//write new slot mapping for changed process with old credentials because new appointment data
221        $slotService->writeSlotProcessMappingFor($processNew->getId(), $reservedAvailabilityId);
222        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (\BO\Zmsbackend\Process\Service\Process::writeEntityWithNewAppointment) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process);
223        $status = ($keepReserved) ? Entity::STATUS_RESERVED : ENTITY::STATUS_CONFIRMED;
224        return $this->updateProcessStatus($processNew, $status, $now, $resolveReferences);
225    }
230    public function updateFollowingProcesses(string|int $processId, \BO\Zmsentities\Process $processData): void
231    {
232        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_PROCESS_CREDENTIALS, [
233            'newProcessId' => $processData->getId(),
234            'newAuthKey' => $processData->getAuthKey(),
235            'processId' => $processId
236        ]);
237        $processEntityList = $this->readEntityList($processId);
238        if ($processEntityList->count()) {
239            foreach ($processEntityList as $entity) {
240                if ($entity->getId() != $processId) {
241                    $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_FOLLWING_PROCESS, [
242                        'newProcessId' => $processData->getId(),
243                        'processId' => $processId
244                    ]);
245                }
246            }
247        }
248    }
253    public function updateReassignedRequests(string|int $processId, string|int $newProcessId): void
254    {
255        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_PROCESS_REQUESTS, [
256            'newProcessId' => $newProcessId,
257            'processId' => $processId
258        ]);
259    }
265    protected function writeNewProcess(\BO\Zmsentities\Process $process, \DateTimeInterface $dateTime, int $parentProcess = 0, int $childProcessCount = 0, bool $retry = true, \BO\Zmsentities\Useraccount|null $userAccount = null, ?int $availabilityId = null)
266    {
267        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::INSERT);
268        $process->id = $this->readNewProcessId();
269        $process->setRandomAuthKey();
270        $process->createTimestamp = $dateTime->getTimestamp();
271        if ($parentProcess !== 0) {
272            $process->displayNumber = '';
273        }
274
275        $query->addValuesNewProcess($process, $parentProcess, $childProcessCount);
276
277        if ($parentProcess === 0 && !empty($process->getDisplayNumber())) {
278            $query->addValueDisplayNumber($process);
279        }
280
281        $query->addValuesScopeData($process);
282        $query->addValuesAppointmentData($process);
283        $query->addValuesUpdateProcess($process, $dateTime, $parentProcess);
284        try {
285            $this->writeItem($query);
286        } catch (\BO\Zmsbackend\Exception\Pdo\PDOFailed $exception) {
287            if ($retry) {
288        // First try might fail if two processes are created with the same number at the same time
289                sleep(1);
290        // Let the other process complete his transaction
291                return $this->writeNewProcess($process, $dateTime, $parentProcess, $childProcessCount, false, $userAccount, $availabilityId);
292            }
293            throw new \BO\Zmsbackend\Process\Exception\ProcessCreateFailed($exception->getMessage());
294        }
295        (new \BO\Zmsbackend\Slot\Service\Slot())->writeSlotProcessMappingFor($process->id, $availabilityId);
296        $checksum = ($userAccount) ? sha1($process->id . '-' . $userAccount->getId()) : '';
297
298        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::writeNewProcess) $process $checksum ", \BO\Zmsbackend\Log\Service\Log::ACTION_NEW, $process, $userAccount);
299        return $process;
300    }
306    protected function readNewProcessId()
307    {
308        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
309        $newProcessId = $this->fetchValue($query->getQueryNewProcessId());
310        return $newProcessId;
311    }
318    public function readAuthKeyByProcessId(string|int $processId)
319    {
320        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
321        $query
322            ->addEntityMapping()
323            ->addResolvedReferences(0)
324            ->addConditionProcessId($processId);
325        $process = $this->fetchOne($query, new Entity());
326        return ($process->hasId()) ? array(
327            'authKey' => $process->authKey
328        ) : null;
329    }
331    protected function readList(\PDOStatement $statement, int $resolveReferences): Collection
332    {
333        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
334        $processList = new Collection();
335        $processIds = [];
336        while ($processData = $statement->fetch(\PDO::FETCH_ASSOC)) {
337            $entity = new Entity($query->postProcessJoins($processData));
338            // The availability join may match a process once per overlapping availability
339            if ($entity->getId() && isset($processIds[$entity->getId()])) {
340                continue;
341            }
342            $processIds[$entity->getId()] = true;
343            $entity = $this->readResolvedReferences($entity, $resolveReferences);
344            $processList->addEntity($entity);
345        }
346        return $processList;
347    }
349    protected function readProcessesWithoutRequests(\PDOStatement $statement): Collection
350    {
351        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
352        $processList = new Collection();
353        while ($processData = $statement->fetch(\PDO::FETCH_ASSOC)) {
354            $processList->addEntity(new Entity($query->postProcessJoins($processData)));
355        }
356        return $processList;
357    }
359    protected function attachAllRequestsInOneQuery(Collection $processList, int $resolveReferences): Collection
360    {
361        if ($processList->count() === 0 || $resolveReferences < 0) {
362            return $processList;
363        }
364
365        $processIds = [];
366        foreach ($processList as $process) {
367            if ($process->hasId()) {
368                $processIds[] = $process->getId();
369            }
370        }
371
372        $requestsByProcessId = (new \BO\Zmsbackend\Request\Service\Request())
373            ->readAllRequestsForProcessIds($processIds, $resolveReferences - 1);
374
375        foreach ($processList as $process) {
376            if (!$process->hasId()) {
377                continue;
378            }
379            $process->requests = $requestsByProcessId[(int) $process->getId()]
380                ?? new \BO\Zmsentities\Collection\RequestList();
381        }
382
383        return $processList;
384    }
389    public function readEntityList(string|int $processId, int $resolveReferences = 0)
390    {
391        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
392        $query
393            ->addResolvedReferences($resolveReferences)
394            ->addEntityMapping()
395            ->addConditionProcessIdFollow($processId);
396        $statement = $this->fetchStatement($query);
397        return $this->readList($statement, $resolveReferences)->sortByAppointmentDate();
398    }
400    public function readByWorkstation(\BO\Zmsentities\Workstation $workstation, int $resolveReferences = 0)
401    {
402        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
403        $query
404            ->addResolvedReferences($resolveReferences)
405            ->addEntityMapping()
406            ->addConditionWorkstationId($workstation->id);
407        $process = $this->fetchOne($query, new Entity());
408        return ($process->hasId()) ? $this->readResolvedReferences($process, $resolveReferences) : null;
409    }
420    public function readProcessListByScopesAndTime(
421        $scopeIds,
422        \DateTimeInterface $dateTime,
423        int $resolveReferences = 0,
424        array $withEntities = []
425    ) {
426        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT, '', false, null, $withEntities);
427        $query
428            ->addResolvedReferences($resolveReferences)
429            ->addEntityMapping()
430            ->addConditionScopeIds($scopeIds)
431            ->addConditionAssigned()
432            ->addConditionIgnoreSlots()
433            ->addConditionTime($dateTime)
434            ->removeDuplicates();
435        $statement = $this->fetchStatement($query);
436        return $this->readList($statement, $resolveReferences);
437    }
450    public function readConflictListByScopeAndTime(\BO\Zmsentities\Scope $scope, ?\DateTimeInterface $startDate = null, ?\DateTimeInterface $endDate = null, ?\DateTimeInterface $now = null, int $resolveReferences = 1)
451    {
452        $availabilityList = (new \BO\Zmsbackend\Availability\Service\Availability())
453            ->readAvailabilityListByScope($scope, 0, $startDate, $endDate)
454            ->withScope($scope);
455        if (! $endDate) {
456            $availabilityList = $availabilityList->withDateTime($startDate);
457            $endDate = $startDate;
458        }
459        $currentDate = ($startDate) ? $startDate : $now;
460        $conflictList = $availabilityList->getConflicts($startDate, $endDate);
461        while ($currentDate <= $endDate) {
462            $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
463            $query
464                ->addResolvedReferences($resolveReferences)
465                ->addEntityMapping()
466                ->addConditionScopeId($scope->getId())
467                ->addConditionAssigned()
468                ->addConditionIgnoreSlots();
469            $query->addConditionTime($currentDate);
470            $statement = $this->fetchStatement($query);
471            $processList = $this->readList($statement, $resolveReferences);
472            $processList = $processList->toQueueList($currentDate)->withoutStatus(['queued'])->toProcessList();
473            $conflictList->addList($processList->withOutAvailability($availabilityList));
474            $currentDate = $currentDate->modify('+1 day');
475        }
476        $conflictList = $conflictList->withoutExpiredAppointmentDate($now);
477        return $conflictList;
478    }
487    public function readProcessListByScopeAndStatus(int $scopeId, string $status, int $resolveReferences = 0, int $limit = 1000, ?int $offset = null)
488    {
489        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
490        $query
491            ->addResolvedReferences($resolveReferences)
492            ->addEntityMapping()
493            ->addConditionScopeId($scopeId) //removed because of dismatching scope and pickup scope
494            ->addConditionStatus($status)
495            ->addLimit($limit, $offset);
496        $statement = $this->fetchStatement($query);
497        return $this->readList($statement, $resolveReferences);
498    }
508    public function readProcessListByClusterAndTime($clusterId, \DateTimeInterface $dateTime)
509    {
510        $cluster = (new \BO\Zmsbackend\Cluster\Service\Cluster())->readEntity($clusterId, 1);
511        $scopeIds = [];
512        if ($cluster->scopes->count()) {
513            foreach ($cluster->scopes as $scope) {
514                $scopeIds[] = $scope->id;
515            }
516        }
517
518        return $this->readProcessListByScopesAndTime($scopeIds, $dateTime);
519    }
528    public function readProcessListCountByScope($scopeId)
529    {
530        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
531        $query
532            ->addCountValue()
533            ->addConditionAssigned()
534            ->addConditionIgnoreSlots()
535            ->addConditionScopeId($scopeId);
536        $statement = $this->fetchStatement($query);
537        $result = $statement->fetch(\PDO::FETCH_ASSOC);
538        return $result['processCount'];
539    }
546    public function readProcessListByMailAddress(string $mailAddress, ?int $scopeId = null, int $resolveReferences = 0, int $limit = 2000): Collection
547    {
548        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
549        $query
550            ->addResolvedReferences($resolveReferences)
551            ->addEntityMapping()
552            ->addConditionMail($mailAddress, true)
553            ->addConditionIgnoreSlots()
554            ->addLimit($limit);
555        if ($scopeId) {
556            $query->addConditionScopeId($scopeId);
557        }
558
559        $statement = $this->fetchStatement($query);
560        return $this->readList($statement, $resolveReferences);
561    }
569    public function readListByMailAndStatusList(string $mailAddress, array $statusList, int $resolveReferences = 1, int $limit = 300): Collection
570    {
571        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
572        $query
573            ->addResolvedReferences($resolveReferences)
574            ->addEntityMapping()
575            ->addConditionMail($mailAddress, true)
576            ->addConditionIgnoreSlots()
577            ->addLimit($limit);
578        $statement = $this->fetchStatement($query);
579        $collection = $this->readList($statement, $resolveReferences);
580        return $collection->toProcessListByStatusList($statusList);
581    }
592    public function updateProcessStatus(Entity $process, string $status, \DateTimeInterface $dateTime, int $resolveReferences = 0, ?\BO\Zmsentities\Useraccount $userAccount = null)
593    {
594        $process = (new ProcessStatus())
595            ->writeUpdatedStatus($process, $status, $dateTime, $resolveReferences, $userAccount);
596
597        /** @var Entity $process */
598        if ($this->shouldUpdateDisplayNumber($process, $status)) {
599            $this->updateEntityDisplayNumber($process);
600        }
601
602        return $process;
603    }
605    public function shouldUpdateDisplayNumber(Entity $process, string $status): bool
606    {
607        if ($status !== 'preconfirmed' && $status !== 'confirmed') {
608            return false;
609        }
610        $displayNumberPrefix = $process->scope->getPreference('queue', 'displayNumberPrefix');
611        if (empty($displayNumberPrefix)) {
612            return false;
613        }
614
615        if (str_starts_with($process->getDisplayNumber(), $displayNumberPrefix)) {
616            return false;
617        }
618
619        return true;
620    }
629    public function writeDeletedEntity(string|int $processId): bool
630    {
631        $processEntityList = $this->readEntityList($processId);
632        $status = false;
633        if ($processEntityList->count()) {
634            foreach ($processEntityList as $entity) {
635                $entityId = $entity->getId();
636                $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_DELETE;
637                $status = $this->perform($query, array(
638                    $entityId,
639                    $entityId
640                ));
641                if ($status) {
642                            $this->deleteRequestsForProcessId($entityId);
643                            (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($entityId);
644                            \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeDeletedEntity) $entityId ", \BO\Zmsbackend\Log\Service\Log::ACTION_DELETED, $entity);
645                }
646            }
647        }
648
649        return $status;
650    }
661    public function deleteEntity($processId, $authKey)
662    {
663        return $this->writeCanceledEntity($processId, $authKey);
664    }
674    public function writeCanceledEntity($processId, $authKey, ?\DateTimeInterface $now = null, ?\BO\Zmsentities\Useraccount $useraccount = null)
675    {
676        $canceledTimestamp = ($now) ? $now->getTimestamp() : (new \DateTimeImmutable())->getTimestamp();
677        $newAuthKey = bin2hex(random_bytes(32));
678        $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_CANCELED;
679        $this->perform($query, [
680            'processId' => $processId,
681            'authKey' => $authKey,
682            'canceledTimestamp' => $canceledTimestamp,
683            'newAuthKey' => $newAuthKey
684        ]);
685        $process = $this->readEntity($processId, new \BO\Zmsbackend\Helper\NoAuth(), 0);
686        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeCanceledEntity) $processId ", \BO\Zmsbackend\Log\Service\Log::ACTION_CANCELED, $process, $useraccount);
687        return $process;
688    }
699    public function writeBlockedEntity(\BO\Zmsentities\Process $process, bool $releaseSlots = false, ?\BO\Zmsentities\Useraccount $useraccount = null)
700    {
701        $amendment = $process->toDerefencedAmendment();
702        $customTextfield = $process->toDerefencedcustomTextfield();
703        $customTextfield2 = $process->toDerefencedcustomTextfield2();
704        if (!isset($process->queue['status'])) {
705            $process->queue['status'] = $process->status;
706        }
707        $process->status = 'blocked';
708        $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_DEREFERENCED;
709        $status = $this->perform($query, array(
710            $amendment,
711            $customTextfield,
712            $customTextfield2,
713            $process->id,
714            $process->authKey,
715            $process->id
716        ));
717        if ($status) {
718            $processEntityList = $this->readEntityList($process->id);
719            if ($processEntityList->count()) {
720                foreach ($processEntityList as $entity) {
721                    $entityId = $entity->getId();
722                    if ($releaseSlots) {
723                        (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($entityId);
724                    }
725                    \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeBlockedEntity) $entityId ", \BO\Zmsbackend\Log\Service\Log::ACTION_DELETED, $process, $useraccount);
726                }
727            }
728        }
729        return $status;
730    }
732    protected function writeRequestsToDb(\BO\Zmsentities\Process $process): void
733    {
734        // Beware of resolveReferences=0 to not delete the existing requests, except for queued processes
735        $hasRequests = ($process->requests && count($process->requests));
736        if ($hasRequests || 'queued' == $process->status) {
737            $this->deleteRequestsForProcessId($process->id);
738        }
739        if ($hasRequests) {
740            $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::INSERT);
741            foreach ($process->requests as $request) {
742                if ($request->id >= 0) {
743        // allow deleting requests with a -1 request
744                    $query->addValues([
745                            'AnliegenID' => $request['id'],
746                            'source' => $request['source'],
747                            'BuergerID' => $process->id
748                        ]);
749                    $this->writeItem($query);
750                }
751            }
752        }
753    }
755    protected function deleteRequestsForProcessId(string|int $processId): bool
756    {
757        $status = false;
758        if (0 < $processId) {
759            $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::DELETE);
760            $query->addConditionProcessId($processId);
761            $status = $this->deleteItem($query);
762        }
763        return $status;
764    }
766    public function readExpiredProcessList(\DateTimeInterface $expirationDate, int $limit = 500, int $resolveReferences = 0, ?int $offset = null)
767    {
768        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
769        $selectQuery
770            ->addEntityMapping()
771            ->addResolvedReferences($resolveReferences)
772            ->addConditionProcessDeleteInterval($expirationDate)
773            ->addConditionIgnoreSlots()
774            ->addLimit($limit, $offset);
775        $statement = $this->fetchStatement($selectQuery);
776        return $this->readList($statement, $resolveReferences);
777    }
781    public function readUnconfirmedProcessList(\DateTimeInterface $expirationDate, int $scopeId = 0, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
782    {
783        $selectQuery = $this->newDeleteListQuery();
784        $selectQuery
785            ->addConditionScopeId($scopeId)
786            ->addConditionProcessExpiredIPTimeStamp($expirationDate)
787            ->addConditionStatus('preconfirmed')
788            ->addConditionIgnoreSlots()
789            ->addLimit($limit, $offset);
790        return $this->readDeleteList($selectQuery);
791    }
793    public function readExpiredProcessListByStatus(\DateTimeInterface $expirationDate, string $status, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
794    {
795        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
796        $selectQuery
797            ->addEntityMapping()
798            ->addResolvedReferences($resolveReferences)
799            ->addConditionProcessDeleteBeforeDate($expirationDate)
800            ->addConditionStatus($status)
801            ->addConditionIgnoreSlots()
802            ->addLimit($limit, $offset);
803        $statement = $this->fetchStatement($selectQuery);
804        return $this->readList($statement, $resolveReferences);
805    }
810    public function readExpiredReservationsList(\DateTimeInterface $expirationDate, string|int $scopeId, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
811    {
812        $selectQuery = $this->newDeleteListQuery();
813        $selectQuery
814            ->addConditionScopeId($scopeId)
815            ->addConditionIsReserved()
816            ->addConditionProcessExpiredIPTimeStamp($expirationDate)
817            ->addConditionIgnoreSlots()
818            ->addLimit($limit, $offset);
819        return $this->readDeleteList($selectQuery);
820    }
822    protected function newDeleteListQuery(): \BO\Zmsbackend\Process\Repository\Process
823    {
824        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(
825            \BO\Zmsbackend\Query\Base::SELECT,
826            '',
827            false,
828            null,
829            ['delete-list']
830        );
831        $selectQuery->addDeleteListColumns();
832        return $selectQuery;
833    }
835    protected function readDeleteList(\BO\Zmsbackend\Process\Repository\Process $selectQuery): Collection
836    {
837        $statement = $this->fetchStatement($selectQuery);
838        $processList = new Collection();
839        while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
840            $processList->addEntity(new Entity([
841                'id' => $row['id'],
842                'status' => $row['status'],
843                'createTimestamp' => $row['createTimestamp'],
844            ]));
845        }
846        $statement->closeCursor();
847        return $processList;
848    }
850    public function readEmailReminderProcessListByInterval(\DateTimeInterface $now, \DateTimeInterface $lastRun, int $defaultReminderInMinutes, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
851    {
852        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
853        $selectQuery
854            ->addEntityMapping()
855            ->addResolvedReferences($resolveReferences)
856            ->addConditionProcessMailReminder($now, $lastRun, $defaultReminderInMinutes)
857            ->addConditionAssigned()
858            ->addConditionIgnoreSlots()
859            ->addConditionStatus('confirmed')
860            ->addLimit($limit, $offset);
861        $statement = $this->fetchStatement($selectQuery);
862        return $this->readList($statement, $resolveReferences)->withDepartmentHasMailFrom();
863    }
865    public function readDeallocateProcessList(\DateTimeInterface $now, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
866    {
867        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
868        $selectQuery
869            ->addEntityMapping()
870            ->addResolvedReferences($resolveReferences)
871            ->addConditionDeallocate($now)
872            ->addConditionIgnoreSlots()
873            ->addLimit($limit, $offset);
874        $statement = $this->fetchStatement($selectQuery);
875        return $this->readList($statement, $resolveReferences);
876    }
878    public function isAppointmentAllowedWithSameMail(Entity $entity): bool
879    {
880        if (empty($entity->getClients()) || empty($entity->getClients()->getFirst())) {
881            return true;
882        }
883
884        $maxAppointmentsPerMail = $entity->scope->getAppointmentsPerMail();
885        $emailToCheck = $entity->getClients()->getFirst()->email;
886        if ($maxAppointmentsPerMail < 1 || empty($emailToCheck)) {
887            return true;
888        }
889
890        if ($this->isMailWhitelisted($emailToCheck, $entity->scope)) {
891            return true;
892        }
893
894        $processes = $this->readProcessListByMailAddress($entity->getClients()->getFirst()->email, $entity->scope->id);
895        $activeAppointments = 0;
896        foreach ($processes as $process) {
897            // Skip the process under change so list order cannot short-circuit the limit
898            // check (a reserved sibling with a lower id used to make preconfirm succeed).
899            if ($entity->id == $process->id) {
900                continue;
901            }
902
903            if (in_array($process->getStatus(), ['preconfirmed', 'confirmed'])) {
904                $activeAppointments++;
905                if ($activeAppointments >= $maxAppointmentsPerMail) {
906                    return false;
907                }
908            }
909        }
910
911        return true;
912    }
914    protected function isMailWhitelisted(string $email, ScopeEntity $scope): bool
915    {
916        $emailsWithNoLimit = explode(',', $scope->getWhitelistedMails());
917        if (empty($emailsWithNoLimit)) {
918            return false;
919        }
920
921        foreach ($emailsWithNoLimit as $whitelistedMail) {
922            $whitelistedMail = trim($whitelistedMail);
923            if ($email === $whitelistedMail) {
924                return true;
925            }
926
927            if (str_starts_with($whitelistedMail, '@') && str_contains($email, $whitelistedMail)) {
928                return true;
929            }
930        }
931
932        return false;
933    }
935    public function readProcessWithSameDayAndDisplayNumber(string|int $scopeId, string $displayNumber, string $date)
936    {
937        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
938        $query->addEntityMapping()
939            ->addResolvedReferences(1)
940            ->addConditionScopeId($scopeId)
941            ->addConditionDate($date)
942            ->addConditionDisplayNumber($displayNumber)
943            ->addLimit(1);
944
945        $process = $this->fetchOne($query, new Entity());
946
947        return $this->readResolvedReferences($process, 1);
948    }
950    public function readProcessListByExternalUserId(string $externalUserId, ?int $filterId = null, ?string $status = null, int $resolveReferences = 0, int $limit = 1000): Collection
951    {
952        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
953        $query
954            ->addResolvedReferences($resolveReferences)
955            ->addEntityMapping()
956            ->addConditionExternalUserId($externalUserId);
957        if (!is_null($filterId)) {
958            $query->addConditionProcessId($filterId);
959        }
960        if (!is_null($status)) {
961            $query->addConditionStatus($status);
962        }
963        $query
964            ->addLimit($limit);
965
966        $statement = $this->fetchStatement($query);
967        $processList = $this->readProcessesWithoutRequests($statement);
968        return $this->attachAllRequestsInOneQuery($processList, (int) $resolveReferences);
969    }
971    public function readAssignedWorkstationIdForUpdate(int $processId): ?int
972    {
973        $query = (new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT))->getLockAssignedWorkstationId();
974        $value = $this->fetchValue($query, ['processId' => $processId]);
975
976        if ($value === false || $value === null) {
977            return null;
978        }
979
980        return (int) $value;
981    }

Inherited from BO\Zmsbackend\Base

38    public function __construct(?Connection\Pdo $writeConnection = null, ?Connection\Pdo $readConnection = null)
39    {
40        $this->writeDb = $writeConnection;
41        $this->readDb = $readConnection;
42    }
44    public static function init(?Connection\Pdo $writeConnection = null, ?Connection\Pdo $readConnection = null): static
45    {
46        $instance = new static($writeConnection, $readConnection);
47        return $instance;
48    }
50    public function getWriter(): Connection\Pdo
51    {
52        if (null === $this->writeDb) {
53            $this->writeDb = Connection\Select::getWriteConnection();
54            $this->readDb = $this->writeDb;
55        }
56        return $this->writeDb;
57    }
59    public function getReader(): Connection\Pdo
60    {
61        if (null !== $this->writeDb) {
62            // if readDB gets a reset, still use writeDB
63            return $this->writeDb;
64        }
65        if (null === $this->readDb) {
66            $this->readDb = Connection\Select::getReadConnection();
67        }
68        return $this->readDb;
69    }
71    public function fetchPreparedStatement(Query\Base|string $query)
72    {
73        $sql = "$query";
74        $reader = $this->getReader();
75        if (spl_object_hash($reader) != static::$preparedConnectionId) {
76            // do not use prepared statements on a different connection
77            static::$preparedCache = [];
78            static::$preparedConnectionId = spl_object_hash($reader);
79        }
80        if (!isset(static::$preparedCache[$sql])) {
81            $prepared = $this->getReader()->prepare($sql);
82            static::$preparedCache[$sql] = $prepared;
83        }
84        return static::$preparedCache[$sql];
85    }
87    public function startExecute(\PDOStatement $statement, array $parameters)
88    {
89        $statement = static::pdoExceptionHandler(function () use ($statement, $parameters) {
90            $statement->execute($parameters);
91            return $statement;
92        });
93        return $statement;
94    }
96    protected static function pdoExceptionHandler(\Closure $pdoFunction, array $parameters = [])
97    {
98        try {
99            $statement = $pdoFunction($parameters);
100        } catch (\PDOException $pdoException) {
101            if (stripos($pdoException->getMessage(), 'Lock wait timeout') !== false) {
102                throw new \BO\Zmsbackend\Exception\Pdo\LockTimeout();
103            }
104            //@codeCoverageIgnoreStart
105            if (stripos($pdoException->getMessage(), 'Deadlock found') !== false) {
106                throw new \BO\Zmsbackend\Exception\Pdo\DeadLockFound();
107            }
108            //@codeCoverageIgnoreEnd
109            $message = "SQL: "
110                . " Err: "
111                . $pdoException->getMessage()
112                //. " || Statement: "
113                //.$statement->queryString
114                //." || Parameters=". var_export($parameters, true)
115                ;
116            throw new \BO\Zmsbackend\Exception\Pdo\PDOFailed($message, 0, $pdoException);
117        }
118        return $statement;
119    }
121    public function fetchStatement(Query\Base $query)
122    {
123        $parameters = $query->getParameters();
124        $statement = $this->startExecute($this->fetchPreparedStatement($query), $parameters);
125        return $statement;
126    }
133    public function fetchOne(Query\Base $query, \BO\Zmsentities\Schema\Entity $entity)
134    {
135        $statement = $this->fetchStatement($query);
136        $data = $statement->fetch(\PDO::FETCH_ASSOC);
137        if ($data) {
138            $entity->exchangeArray($query->postProcessJoins($data));
139            $entity->setResolveLevel($query->getResolveLevel());
140        }
141        $statement->closeCursor();
142        return $entity;
143    }
145    public function fetchRow(Query\Base|string $query, array|null $parameters = null)
146    {
147        return static::pdoExceptionHandler(function () use ($query, $parameters) {
148            $prepared = $this->fetchPreparedStatement($query);
149            $prepared->execute($parameters);
150            $row = $prepared->fetch(\PDO::FETCH_ASSOC);
151            $prepared->closeCursor();
152            return $row;
153        });
154    }
156    public function fetchValue(Query\Base|string $query, array|null $parameters = null)
157    {
158        return static::pdoExceptionHandler(function () use ($query, $parameters) {
159            $prepared = $this->fetchPreparedStatement($query);
160            $prepared->execute($parameters);
161            $value = $prepared->fetchColumn();
162            $prepared->closeCursor();
163            return $value;
164        });
165    }
167    public function fetchAll(Query\Base|string $query, array|null $parameters = null)
168    {
169        return static::pdoExceptionHandler(function () use ($query, $parameters) {
170            $prepared = $this->fetchPreparedStatement($query);
171            $prepared->execute($parameters);
172            $list = $prepared->fetchAll(\PDO::FETCH_ASSOC);
173            $prepared->closeCursor();
174            return $list;
175        });
176    }
178    public function fetchHandle(Query\Base|string $query, array|null $parameters = null)
179    {
180        return static::pdoExceptionHandler(function () use ($query, $parameters) {
181            $prepared = $this->fetchPreparedStatement($query);
182            $prepared->execute($parameters);
183            return $prepared;
184        });
185    }
187    public function fetchList(Query\Base $query, \BO\Zmsentities\Schema\Entity $entity, array|\ArrayAccess $resultList = [])
188    {
189        $statement = $this->fetchStatement($query);
190        while ($data = $statement->fetch(\PDO::FETCH_ASSOC)) {
191            $dataEntity = clone $entity;
192            $dataEntity->exchangeArray($query->postProcessJoins($data));
193            $dataEntity->setResolveLevel($query->getResolveLevel());
194            $resultList[] = $dataEntity;
195        }
196        $statement->closeCursor();
197        return $resultList;
198    }
206    public function writeItem(Query\Base $query)
207    {
208        return static::pdoExceptionHandler(function () use ($query) {
209            $this->getWriter(); //Switch to writer for write/delete
210            $statement = $this->fetchPreparedStatement($query);
211            $status = $statement->execute($query->getParameters());
212            $statement->closeCursor();
213            return $status;
214        });
215    }
221    public function deleteItem(Query\Base $query)
222    {
223        return $this->writeItem($query);
224    }
226    public function perform(string $sql, array|null $parameters = null)
227    {
228        return static::pdoExceptionHandler(function () use ($sql, $parameters) {
229            $this->getWriter(); //Switch to writer for perform
230            $prepared = $this->fetchPreparedStatement($sql);
231            $status = $prepared->execute($parameters);
232            $prepared->closeCursor();
233            return $status;
234        });
235    }
237    public function fetchAffected(string $sql, array|null $parameters = null)
238    {
239        return static::pdoExceptionHandler(function () use ($sql, $parameters) {
240            $this->getWriter(); //Switch to writer for perform
241            $prepared = $this->fetchPreparedStatement($sql);
242            $prepared->execute($parameters);
243            $count = $prepared->rowCount();
244            $prepared->closeCursor();
245            return $count;
246        });
247    }
268    public function hashStringValue(string $value, ?callable $callable = null): string
269    {
270        if ($callable === null) {
271            $callable = 'sha1';
272        }
273
274        if (is_callable($callable)) {
275            $hash = $callable($value);
276
277            if (is_string($callable)) {
278                return $callable . ':' . $hash;
279            }
280            if ($callable instanceof \Closure) {
281                return 'closure:' . $hash;
282            }
283            // else
284            return 'custom:' . $hash;
285        }
286
287        throw new \InvalidArgumentException('hashStringValue() should be called with a callable as second parameter.');
288    }