Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.29% covered (warning)
81.29%
139 / 171
50.00% covered (danger)
50.00%
7 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
ProcessSearchHistory
81.29% covered (warning)
81.29%
139 / 171
50.00% covered (danger)
50.00%
7 / 14
38.71
0.00% covered (danger)
0.00%
0 / 1
 writeHistoryEntry
84.21% covered (warning)
84.21%
16 / 19
0.00% covered (danger)
0.00%
0 / 1
4.06
 existsByHistoryKey
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 readFullyResolvedProcess
71.43% covered (warning)
71.43%
15 / 21
0.00% covered (danger)
0.00%
0 / 1
4.37
 buildHistoryEntryData
100.00% covered (success)
100.00%
45 / 45
100.00% covered (success)
100.00%
1 / 1
1
 createHistoryKey
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
4.18
 buildServiceNames
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
4.07
 getScope
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dateTimeFromTimestamp
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getNullableString
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 validateStatus
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 isDuplicateKeyException
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 getAppointmentAt
40.00% covered (danger)
40.00%
4 / 10
0.00% covered (danger)
0.00%
0 / 1
2.86
 getScopeId
33.33% covered (danger)
33.33%
3 / 9
0.00% covered (danger)
0.00%
0 / 1
3.19
 deleteOlderThan
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace BO\Zmsbackend\ProcessSearchHistory\Service;
4
5use BO\Zmsbackend\Exception\Pdo\PDOFailed;
6use BO\Zmsbackend\Process\Service\Process as ProcessService;
7use BO\Zmsbackend\ProcessSearchHistory\Repository\ProcessSearchHistory as HistoryRepository;
8use BO\Zmsbackend\Query\Base as QueryBase;
9use BO\Zmsentities\Process as ProcessEntity;
10use BO\Zmsentities\Scope as ScopeEntity;
11
12class ProcessSearchHistory extends \BO\Zmsbackend\Base
13{
14    public const string STATUS_COMPLETED = 'completed';
15    public const string STATUS_MISSED = 'missed';
16    public const string STATUS_CANCELLED_BY_CITIZEN = 'cancelled_citizen';
17    public const string STATUS_CANCELLED_BY_STAFF = 'cancelled_staff';
18
19    private const array SUPPORTED_STATUSES = [
20        self::STATUS_COMPLETED,
21        self::STATUS_MISSED,
22        self::STATUS_CANCELLED_BY_CITIZEN,
23        self::STATUS_CANCELLED_BY_STAFF,
24    ];
25
26    private const int RESOLVE_REFERENCES = 2;
27    private const int DUPLICATE_KEY_ERROR_CODE = 1062;
28
29    /**
30     * Bei einem bereits vorhandenen history_key wird kein zweiter
31     * Datensatz angelegt. In beiden Fällen wird der history_key
32     * zurückgegeben.
33     */
34    public function writeHistoryEntry(
35        ProcessEntity $process,
36        string $status,
37        \DateTimeInterface $finalizedAt
38    ): string {
39        $this->validateStatus($status);
40
41        $process = $this->readFullyResolvedProcess($process);
42        $historyKey = $this->createHistoryKey($process);
43
44        if ($this->existsByHistoryKey($historyKey)) {
45            return $historyKey;
46        }
47
48        $query = new HistoryRepository(QueryBase::INSERT);
49        $query->addValuesNewHistory(
50            $this->buildHistoryEntryData(
51                $process,
52                $historyKey,
53                $status,
54                $finalizedAt
55            )
56        );
57
58        try {
59            $this->writeItem($query);
60        } catch (PDOFailed $exception) {
61            if (!$this->isDuplicateKeyException($exception)) {
62                throw $exception;
63            }
64        }
65
66        return $historyKey;
67    }
68
69    public function existsByHistoryKey(string $historyKey): bool
70    {
71        $query = new HistoryRepository(QueryBase::SELECT);
72        $query
73            ->addCountValue()
74            ->addConditionHistoryKey($historyKey);
75
76        return (int) $this->fetchValue(
77            $query,
78            $query->getParameters()
79        ) > 0;
80    }
81
82    private function readFullyResolvedProcess(
83        ProcessEntity $process
84    ): ProcessEntity {
85        if (!$process->hasProcessCredentials()) {
86            throw new \InvalidArgumentException(
87                'Process id and authKey are required for the history snapshot.'
88            );
89        }
90
91        $processService = new ProcessService(
92            $this->getWriter(),
93            $this->getReader()
94        );
95
96        $resolvedProcess = $processService->readEntity(
97            $process->getId(),
98            $process->getAuthKey(),
99            self::RESOLVE_REFERENCES
100        );
101
102        if ($resolvedProcess === null || !$resolvedProcess->hasId()) {
103            throw new \RuntimeException(
104                sprintf(
105                    'Process %d could not be loaded for the history snapshot.',
106                    $process->getId()
107                )
108            );
109        }
110
111        return $resolvedProcess;
112    }
113
114    private function buildHistoryEntryData(
115        ProcessEntity $process,
116        string $historyKey,
117        string $status,
118        \DateTimeInterface $finalizedAt
119    ): array {
120        $client = $process->getFirstClient();
121        $scope = $this->getScope($process);
122
123        return [
124            'historyKey' => $historyKey,
125
126            'processId' => (int) $process->getId(),
127            'scopeId' => $this->getScopeId($process),
128            'displayNumber' => $this->getNullableString(
129                $process->getDisplayNumber()
130            ),
131
132            'appointmentAt' => $this->getAppointmentAt($process),
133            'bookedAt' => $this->dateTimeFromTimestamp(
134                (int) $process['createTimestamp']
135            ),
136            'calledAt' => $this->dateTimeFromTimestamp(
137                (int) $process
138                    ->toProperty()
139                    ->queue
140                    ->callTime
141                    ->get(0)
142            ),
143
144            'finalizedAt' => $finalizedAt,
145            'status' => $status,
146
147            'citizenName' => (string) $client
148                ->toProperty()
149                ->familyName
150                ->get(''),
151
152            'telephone' => (string) $client
153                ->toProperty()
154                ->telephone
155                ->get(''),
156
157            'citizenEmail' => (string) $client
158                ->toProperty()
159                ->email
160                ->get(''),
161
162            'amendment' => $this->getNullableString(
163                $process->getAmendment()
164            ),
165
166            'locationName' => trim(
167                (string) $scope->getShortName()
168            ),
169
170            'providerName' => trim(
171                (string) $scope->getProvider()->getName()
172            ),
173
174            'services' => $this->buildServiceNames($process),
175        ];
176    }
177
178    private function createHistoryKey(
179        ProcessEntity $process
180    ): string {
181        $processId = (int) $process->getId();
182        $createTimestamp = (int) $process['createTimestamp'];
183        $authKey = (string) $process->getAuthKey();
184
185        if (
186            $processId <= 0
187            || $createTimestamp <= 0
188            || $authKey === ''
189        ) {
190            throw new \InvalidArgumentException(
191                'Process id, createTimestamp and authKey are required '
192                . 'to create the history key.'
193            );
194        }
195
196        return hash(
197            'sha256',
198            $processId
199                . '|'
200                . $createTimestamp
201                . '|'
202                . $authKey
203        );
204    }
205
206    private function buildServiceNames(
207        ProcessEntity $process
208    ): ?string {
209        $serviceNames = [];
210
211        foreach ($process->getRequests() as $request) {
212            $serviceName = trim((string) $request->getName());
213
214            if ($serviceName === '') {
215                continue;
216            }
217
218            $serviceNames[$serviceName] = true;
219        }
220
221        if ($serviceNames === []) {
222            return null;
223        }
224
225        return implode(
226            "\n",
227            array_keys($serviceNames)
228        );
229    }
230
231    private function getScope(
232        ProcessEntity $process
233    ): ScopeEntity {
234        return $process->getCurrentScope();
235    }
236
237    private function dateTimeFromTimestamp(
238        int $timestamp
239    ): ?\DateTimeImmutable {
240        if ($timestamp <= 0) {
241            return null;
242        }
243
244        return (new \DateTimeImmutable())
245            ->setTimestamp($timestamp);
246    }
247
248    private function getNullableString(
249        mixed $value
250    ): ?string {
251        $value = trim((string) $value);
252
253        return $value !== '' ? $value : null;
254    }
255
256    private function validateStatus(string $status): void
257    {
258        if (
259            !in_array(
260                $status,
261                self::SUPPORTED_STATUSES,
262                true
263            )
264        ) {
265            throw new \InvalidArgumentException(
266                sprintf(
267                    'Unsupported process search history status "%s".',
268                    $status
269                )
270            );
271        }
272    }
273
274    private function isDuplicateKeyException(
275        PDOFailed $exception
276    ): bool {
277        $previous = $exception->getPrevious();
278
279        if (!$previous instanceof \PDOException) {
280            return false;
281        }
282
283        return (int) ($previous->errorInfo[1] ?? 0)
284            === self::DUPLICATE_KEY_ERROR_CODE;
285    }
286
287    private function getAppointmentAt(
288        ProcessEntity $process
289    ): \DateTimeImmutable {
290        $appointment = $process->getFirstAppointment();
291        $timestamp = $appointment->toDateTime()->getTimestamp();
292
293        if ($timestamp <= 0) {
294            throw new \InvalidArgumentException(
295                sprintf(
296                    'Process %d has no valid appointment date.',
297                    $process->getId()
298                )
299            );
300        }
301
302        return $appointment->toDateTime();
303    }
304
305    private function getScopeId(ProcessEntity $process): int
306    {
307        $scopeId = (int) $process->getScopeId();
308
309        if ($scopeId <= 0) {
310            throw new \InvalidArgumentException(
311                sprintf(
312                    'Process %d has no valid scope.',
313                    $process->getId()
314                )
315            );
316        }
317
318        return $scopeId;
319    }
320
321    public function deleteOlderThan(
322        \DateTimeInterface $dateTime
323    ): bool {
324        $query = new
325            \BO\Zmsbackend\ProcessSearchHistory\Repository\ProcessSearchHistory(
326                \BO\Zmsbackend\Query\Base::DELETE
327            );
328
329        $query->addConditionOlderThan($dateTime);
330
331        return $this->deleteItem($query);
332    }
333}