Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.43% covered (warning)
77.43%
590 / 762
70.00% covered (warning)
70.00%
49 / 70
CRAP
0.00% covered (danger)
0.00%
0 / 1
Process
77.43% covered (warning)
77.43%
590 / 762
70.00% covered (warning)
70.00%
49 / 70
671.27
0.00% covered (danger)
0.00%
0 / 1
 getQueryNewProcessId
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getLockProcessId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLockAssignedWorkstationId
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 addJoin
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 addJoinAvailability
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 addJoinScope
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 addConditionDate
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 addConditionDisplayNumber
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 calculateStatus
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
506
 getEntityMapping
100.00% covered (success)
100.00%
71 / 71
100.00% covered (success)
100.00%
1 / 1
3
 addCountValue
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 addConditionHasTelephone
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 addConditionProcessDeleteInterval
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 addConditionProcessExpiredIPTimeStamp
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 addConditionProcessReminderInterval
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 addConditionProcessMailReminder
100.00% covered (success)
100.00%
44 / 44
100.00% covered (success)
100.00%
1 / 1
1
 addConditionProcessId
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 addConditionProcessIdFollow
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 addConditionIgnoreSlots
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 addConditionScopeId
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 addConditionScopeIds
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
4.46
 addConditionQueueNumber
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 addConditionWorkstationId
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 addConditionTime
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addConditionTimeframe
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 addConditionAuthKey
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 addConditionAssigned
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addConditionStatus
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addConditionIsReserved
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 addConditionSearch
79.31% covered (warning)
79.31%
23 / 29
0.00% covered (danger)
0.00%
0 / 1
8.57
 addConditionUpcomingOnly
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 addOrderByAppointmentDate
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 addOrderBySearchRelevance
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
2.00
 parseSearchTerms
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
6.35
 appendNamePartLikeGroup
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
3.01
 isNumericSearchQuery
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 escapeLikeValue
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 escapeLikePatternForSqlLiteral
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 escapeSqlStringLiteral
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 addConditionName
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 addConditionMail
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
2.21
 addConditionCustomTextfield
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 addConditionCustomTextfield2
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 addConditionAmendment
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 addConditionRequestId
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 addConditionScopeNameSearch
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
 addConditionServiceNameSearch
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
2
 addConditionDeallocate
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 addValuesNewProcess
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 getNewDisplayNumber
13.33% covered (danger)
13.33%
2 / 15
0.00% covered (danger)
0.00%
0 / 1
8.86
 checkIfDisplayNumberOnSameDateExists
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 addValuesUpdateProcess
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 addValuesIPAdress
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 addValuesFollowingProcessData
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 addValuesAppointmentData
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 addValuesScopeData
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 addValuesStatusData
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
13
 addValuesClientData
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
11
 addValueDisplayNumber
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addProcessingTimeData
36.00% covered (danger)
36.00%
18 / 50
0.00% covered (danger)
0.00%
0 / 1
92.76
 addValuesQueueData
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
10
 addValuesWaitingTimeData
84.62% covered (warning)
84.62%
33 / 39
0.00% covered (danger)
0.00%
0 / 1
19.18
 addValuesWayTimeData
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
2.98
 addValuesWasMissed
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 addValuesPriority
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 addValuesExternalUserId
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 postProcess
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
7
 removeDuplicates
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 addRequiredJoins
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 addConditionExternalUserId
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace BO\Zmsbackend\Process\Repository;
4
5use BO\Zmsbackend\Scope\Service\Scope as ScopeEntity;
6use BO\Zmsentities\Process as ProcessEntity;
7use BO\Zmsdldb\Helper\DateTime;
8use DateTimeImmutable;
9
10/**
11 * @SuppressWarnings(Methods)
12 * @SuppressWarnings(Complexity)
13 */
14class Process extends \BO\Zmsbackend\Query\Base implements \BO\Zmsbackend\Query\MappingInterface
15{
16    /**
17     *     * @var String TABLE mysql table reference
18     */
19    const TABLE = 'buerger';
20
21    const QUERY_DEREFERENCED = "UPDATE `buerger` process LEFT JOIN `standort` s USING(StandortID)
22        SET
23            process.Anmerkung = ?,
24            process.custom_text_field = ?,
25            process.custom_text_field2 = ?,
26            process.StandortID = 0,
27            process.AbholortID = 0,
28            process.Abholer = 0,
29            process.Name = 'dereferenced',
30            process.IPadresse = '',
31            process.IPTimeStamp = 0,
32            process.NutzerID = 0,
33            process.vorlaeufigeBuchung = 0,
34            process.bestaetigt = 1,
35            process.absagecode = 'deref!0',
36            process.EMail = '',
37            process.NutzerID = 0,
38            process.priority = null,
39            process.status = 'blocked'
40        WHERE
41            (process.BuergerID = ? AND process.absagecode = ?)
42            OR process.istFolgeterminvon = ?
43        ";
44
45    const QUERY_CANCELED = "
46        UPDATE `buerger` process LEFT JOIN `standort` s USING(StandortID)
47            SET
48                process.Anmerkung = CONCAT(
49                    'Abgesagter Termin gebucht am: ',
50                    FROM_UNIXTIME(process.IPTimeStamp,'%d.%m.%Y, %H:%i'),' Uhr | ',
51                    IFNULL(process.Anmerkung,'')
52                ),              
53                process.Name = '(abgesagt)',
54                process.IPadresse = '',
55                process.IPTimeStamp = :canceledTimestamp + (IFNULL(s.loeschdauer, 15) * 60),
56                process.NutzerID = 0,
57                process.vorlaeufigeBuchung = 1,
58                process.status = 'deleted',
59                process.absagecode = :newAuthKey
60            WHERE
61                (process.BuergerID = :processId AND process.absagecode = :authKey)
62                OR process.istFolgeterminvon = :processId
63        ";
64
65    const QUERY_DELETE = "DELETE FROM `buerger`
66        WHERE
67            BuergerID = ?
68            OR istFolgeterminvon = ?
69        ";
70
71    const QUERY_REASSIGN_PROCESS_CREDENTIALS = "UPDATE `buerger` process
72       SET 
73            process.BuergerID = :newProcessId, 
74            process.absagecode = :newAuthKey
75        WHERE BuergerID = :processId
76    ";
77
78    const QUERY_REASSIGN_PROCESS_REQUESTS = "UPDATE `buergeranliegen` requests
79        SET 
80            requests.BuergerID = :newProcessId
81        WHERE BuergerID = :processId
82    ";
83
84    const QUERY_REASSIGN_FOLLWING_PROCESS = "UPDATE `buerger` process
85        SET process.istFolgeterminvon = :newProcessId
86        WHERE istFolgeterminvon = :processId
87    ";
88
89    const QUERY_UPDATE_FOLLOWING_PROCESS = "UPDATE buerger 
90        SET vorlaeufigeBuchung = :reserved 
91        WHERE istFolgeterminvon = :processID
92        ";
93
94    public function getQueryNewProcessId()
95    {
96        $random = rand(20, 999);
97        return 'SELECT pseq.processId AS `nextid`
98            FROM process_sequence pseq
99            WHERE pseq.processId = (
100                SELECT ps.processID FROM `process_sequence` ps LEFT JOIN `' . self::getTablename() . '` p
101                    ON ps.processId = p.BuergerID
102                WHERE p.`BuergerID` IS NULL
103                LIMIT ' . $random . ',1)
104            FOR UPDATE';
105    }
106
107    public function getLockProcessId()
108    {
109        return 'SELECT p.`BuergerID` FROM `' . self::getTablename() . '` p WHERE p.`BuergerID` = :processId FOR UPDATE';
110    }
111
112    public function getLockAssignedWorkstationId()
113    {
114        return 'SELECT p.`NutzerID`
115            FROM `' . self::getTablename() . '` p
116            WHERE p.`BuergerID` = :processId
117            FOR UPDATE';
118    }
119
120    #[\Override]
121    public function addJoin()
122    {
123        $joins = [];
124
125        if ($this->shouldLoadEntity('availability')) {
126            $joins[] = $this->addJoinAvailability();
127        }
128
129        if ($this->shouldLoadEntity('scope')) {
130            $joins[] = $this->addJoinScope();
131        }
132
133        return $joins;
134    }
135
136    /**
137     * Add Availability to the dataset
138     */
139    protected function addJoinAvailability()
140    {
141        $this->leftJoin(
142            new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Availability\Repository\Availability::TABLE, 'availability'),
143            \BO\Zmsbackend\Availability\Repository\Availability::getJoinExpression('`process`', '`availability`')
144        );
145        $joinQuery = new \BO\Zmsbackend\Availability\Repository\Availability($this, $this->getPrefixed('appointments__0__availability__'));
146        return $joinQuery;
147    }
148
149    /**
150     * Add Scope to the dataset
151     */
152    protected function addJoinScope()
153    {
154        $this->leftJoin(
155            new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Query\Scope::TABLE, 'scope'),
156            self::expression(
157                'IF(`process`.`AbholortID`,
158                    `process`.`AbholortID`,
159                    `process`.`StandortID`
160                )'
161            ),
162            '=',
163            'scope.StandortID'
164        );
165        $joinQuery = new \BO\Zmsbackend\Query\Scope($this, $this->getPrefixed('scope__'));
166        return $joinQuery;
167    }
168
169    public function addConditionDate($date)
170    {
171        $this->query->where('process.Datum', '=', $date);
172        return $this;
173    }
174
175    public function addConditionDisplayNumber($displayNumber)
176    {
177        $this->query->where('process.displayNumber', '=', $displayNumber);
178        return $this;
179    }
180
181    protected function calculateStatus()
182    {
183        if ($this->query->value('Name') === '(abgesagt)') {
184            return 'deleted';
185        }
186
187        if (
188            $this->query->value('StandortID') == 0
189            && $this->query->value('AbholortID') == 0
190        ) {
191            return 'blocked';
192        }
193
194        if (
195            $this->query->value('vorlaeufigeBuchung') == 1
196            && $this->query->value('bestaetigt') == 0
197        ) {
198            return 'reserved';
199        }
200
201        if ($this->query->value('nicht_erschienen') != 0) {
202            return 'missed';
203        }
204
205        if ($this->query->value('parked') != 0) {
206            return 'parked';
207        }
208
209        if (
210            $this->query->value('Abholer') != 0
211            && $this->query->value('AbholortID') != 0
212            && $this->query->value('NutzerID') == 0
213        ) {
214            return 'pending';
215        }
216
217        if (
218            $this->query->value('AbholortID') == 0
219            && $this->query->value('aufruferfolgreich') != 0
220            && $this->query->value('NutzerID') != 0
221        ) {
222            return 'processing';
223        }
224
225        if (
226            $this->query->value('aufrufzeit') != "00:00:00"
227            && $this->query->value('NutzerID') != 0
228            && $this->query->value('AbholortID') == 0
229        ) {
230            return 'called';
231        }
232
233        if ($this->query->value('Uhrzeit') == "00:00:00") {
234            return 'queued';
235        }
236
237        if (
238            $this->query->value('vorlaeufigeBuchung') == 0
239            && $this->query->value('bestaetigt') == 0
240        ) {
241            return 'preconfirmed';
242        }
243
244        if (
245            $this->query->value('vorlaeufigeBuchung') == 0
246            && $this->query->value('bestaetigt') == 1
247        ) {
248            return 'confirmed';
249        }
250
251        return null;
252    }
253
254    #[\Override]
255    public function getEntityMapping()
256    {
257        $status_expression = self::expression(
258            'CASE
259                WHEN process.status = "called" AND process.aufrufzeit != "00:00:00" AND process.NutzerID != 0 AND process.AbholortID = 0
260                    THEN "called"
261                WHEN process.status = "called" AND process.Uhrzeit = "00:00:00"
262                    THEN "queued"
263                WHEN process.status = "called" AND process.vorlaeufigeBuchung = 0 AND process.bestaetigt = 1
264                    THEN "confirmed"
265                ELSE process.status
266            END'
267        );
268
269        return array_filter([
270            'amendment' => 'process.Anmerkung',
271            'id' => 'process.BuergerID',
272            'appointments__0__date' => self::expression(
273                'CONCAT(`process`.`Datum`, " ", `process`.`Uhrzeit`)'
274            ),
275            'scope__id' => self::expression(
276                'IF(`process`.`AbholortID`,
277                    `process`.`AbholortID`,
278                    `process`.`StandortID`
279)'
280            ),
281            'appointments__0__scope__id' => 'process.StandortID',
282            // 'appointments__0__slotCount' => 'process.hatFolgetermine',
283            'appointments__0__slotCount' => self::expression('process.hatFolgetermine + 1'),
284            'authKey' => 'process.absagecode',
285            'clients__0__email' => 'process.EMail',
286            'clients__0__emailSendCount' => 'process.EMailverschickt',
287            'clients__0__familyName' => 'process.Name',
288            'clients__0__surveyAccepted' => 'process.zustimmung_kundenbefragung',
289            'clients__0__telephone' => self::expression(
290                'IF(`process`.`telefonnummer_fuer_rueckfragen`!="",
291                    `process`.`telefonnummer_fuer_rueckfragen`,
292                    `process`.`Telefonnummer`
293                )'
294            ),
295            'customTextfield' => 'process.custom_text_field',
296            'customTextfield2' => 'process.custom_text_field2',
297            'createIP' => 'process.IPAdresse',
298            'priority' => 'process.priority',
299            'createTimestamp' => 'process.IPTimeStamp',
300            'lastChange' => 'process.updateTimestamp',
301            'showUpTime' => 'process.showUpTime',
302            'processingTime' => 'process.processing_time',
303            'timeoutTime' => 'process.timeoutTime',
304            'finishTime' => 'process.finishTime',
305            'status' => $status_expression,
306            'queue__status' => $status_expression,
307            'queue__arrivalTime' => self::expression(
308                'CONCAT(
309                    `process`.`Datum`,
310                    " ",
311                    IF(`process`.`wsm_aufnahmezeit`, `process`.`wsm_aufnahmezeit`, `process`.`Uhrzeit`)
312                )'
313            ),
314            'queue__callCount' => 'process.AnzahlAufrufe',
315            'queue__callTime' => 'process.aufrufzeit',
316            'queue__lastCallTime' => 'process.Timestamp',
317            'displayNumber' => self::expression(
318                'COALESCE(
319                    `process`.`displayNumber`,
320                    IF(`process`.`wartenummer`,
321                        `process`.`wartenummer`,
322                        `process`.`BuergerID`
323                    )
324                )'
325            ),
326            'queue__number' => self::expression(
327                'IF(`process`.`wartenummer`,
328                    `process`.`wartenummer`,
329                    `process`.`BuergerID`
330                )'
331            ),
332            'queue__destination' => $this->shouldLoadEntity('processuser')
333                ? 'processuser.Arbeitsplatznr'
334                : '',
335            'queue__destinationHint' => $this->shouldLoadEntity('processuser')
336                ? 'processuser.aufrufzusatz'
337                : '',
338            'queue__waitingTime' => 'process.waiting_time',
339            'queue__wayTime' => 'process.way_time',
340            'queue__withAppointment' => self::expression(
341                'IF(`process`.`wartenummer`,
342                    "0",
343                    "1"
344                )'
345            ),
346            'reminderTimestamp' => 'process.Erinnerungszeitpunkt',
347            '__clientsCount' => 'process.AnzahlPersonen',
348            'wasMissed' => 'process.wasMissed',
349            'externalUserId' => 'process.external_user_id',
350            'isTicketprinter' => 'process.is_ticketprinter',
351            'parkedBy' => 'process.parkedBy',
352        ], 'strlen');
353    }
354
355    public function addCountValue()
356    {
357        $this->query->select([
358            'processCount' => self::expression('COUNT(*)'),
359        ]);
360        return $this;
361    }
362
363    public function addConditionHasTelephone()
364    {
365        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) {
366            $condition
367                ->andWith('process.telefonnummer_fuer_rueckfragen', '!=', '')
368                ->orWith('process.Telefonnummer', '!=', '');
369        });
370        return $this;
371    }
372
373    public function addConditionProcessDeleteInterval(\DateTimeInterface $expirationDate)
374    {
375        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($expirationDate) {
376            $query->andWith(
377                self::expression(
378                    'CONCAT(`process`.`Datum`, " ", `process`.`Uhrzeit`)'
379                ),
380                '<=',
381                $expirationDate->format('Y-m-d H:i:s')
382            );
383        });
384        $this->query->orderBy('appointments__0__date', 'ASC');
385        return $this;
386    }
387
388    public function addConditionProcessExpiredIPTimeStamp(\DateTimeInterface $expirationDate)
389    {
390        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($expirationDate) {
391            $query->andWith('process.IPTimeStamp', '<=', $expirationDate->getTimestamp());
392        });
393        $this->query->orderBy('appointments__0__date', 'ASC');
394        return $this;
395    }
396
397    public function addConditionProcessReminderInterval(\DateTimeInterface $dateTime)
398    {
399        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($dateTime) {
400            $query
401                ->andWith('process.Erinnerungszeitpunkt', '<=', $dateTime->getTimestamp())
402                ->andWith('process.Erinnerungszeitpunkt', '>=', $dateTime->modify("-5 Minutes")->getTimestamp());
403        });
404        $this->query->orderBy('reminderTimestamp', 'ASC');
405        return $this;
406    }
407
408    public function addConditionProcessMailReminder(
409        \DateTimeInterface $now,
410        \DateTimeInterface $lastRun,
411        $defaultReminderInMinutes
412    ) {
413        $this->query
414            ->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($now, $lastRun, $defaultReminderInMinutes) {
415                $query
416                    ->andWith(
417                        self::expression(
418                            'CONCAT(`process`.`Datum`, " ", `process`.`Uhrzeit`)'
419                        ),
420                        '>',
421                        $lastRun->format('Y-m-d H:i:s')
422                    )
423                    ->andWith(
424                        self::expression(
425                            'CONCAT(`process`.`Datum`, " ", `process`.`Uhrzeit`)'
426                        ),
427                        '>',
428                        $now->format('Y-m-d H:i:s')
429                    )
430                    ->andWith(
431                        'scopemail.send_reminder',
432                        '=',
433                        1
434                    )
435                    ->andWith(
436                        'process.EMail',
437                        '<>',
438                        ""
439                    )
440                    ->andWith(
441                        'process.EMailverschickt',
442                        '=',
443                        0
444                    )
445                    ->andWith(
446                        self::expression(
447                            'DATE_SUB(CONCAT(`process`.`Datum`, " ", `process`.`Uhrzeit`), INTERVAL '
448                                . 'IFNULL(scopemail.send_reminder_minutes_before, ' . $defaultReminderInMinutes
449                                . ') MINUTE)'
450                        ),
451                        '<=',
452                        $now->format('Y-m-d H:i:s')
453                    );
454            });
455        $this->query->orderBy('appointments__0__date', 'ASC');
456        return $this;
457    }
458
459    public function addConditionProcessId($processId)
460    {
461        $this->query->where('process.BuergerID', '=', $processId);
462        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) {
463            $condition
464                ->andWith('process.istFolgeterminvon', 'IS', null)
465                ->orWith('process.istFolgeterminvon', '=', 0);
466        });
467        return $this;
468    }
469
470    public function addConditionProcessIdFollow($processId)
471    {
472        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) use ($processId) {
473            $condition
474                ->andWith('process.BuergerID', '=', $processId)
475                ->orWith('process.istFolgeterminvon', '=', $processId);
476        });
477        return $this;
478    }
479
480    public function addConditionIgnoreSlots()
481    {
482        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) {
483            $condition
484                ->andWith('process.istFolgeterminvon', 'IS', null)
485                ->orWith('process.istFolgeterminvon', '=', 0);
486        });
487        return $this;
488    }
489
490    public function addConditionScopeId($scopeId)
491    {
492        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($scopeId) {
493            $query
494                ->andWith('process.StandortID', '=', $scopeId)
495                ->orWith('process.AbholortID', '=', $scopeId);
496        });
497        return $this;
498    }
499
500    public function addConditionScopeIds($scopeIds)
501    {
502        if (count($scopeIds) === 0) {
503            $this->query->where(self::expression('1'), '=', 0);
504            return $this;
505        }
506
507        if (count($scopeIds) === 1) {
508            return $this->addConditionScopeId($scopeIds[0]);
509        }
510
511        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($scopeIds) {
512            $query
513                ->andWith('process.StandortID', 'IN', $scopeIds)
514                ->orWith('process.AbholortID', 'IN', $scopeIds);
515        });
516
517        return $this;
518    }
519
520    public function addConditionQueueNumber($queueNumber, $queueLimit = 10000)
521    {
522        ($queueLimit > $queueNumber)
523            ? $this->query->where('process.wartenummer', '=', $queueNumber)
524            : $this->query->where('process.BuergerID', '=', $queueNumber);
525        return $this;
526    }
527
528    public function addConditionWorkstationId($workstationId)
529    {
530        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($workstationId) {
531            $query->andWith('process.NutzerID', '=', $workstationId);
532            $query->andWith('process.StandortID', '>', 0);
533        });
534        return $this;
535    }
536
537    public function addConditionTime($dateTime)
538    {
539        $this->query->where('process.Datum', '=', $dateTime->format('Y-m-d'));
540        return $this;
541    }
542
543    /**
544     * Identify processes between two dates
545     */
546    public function addConditionTimeframe(\DateTimeInterface $startDate, \DateTimeInterface $endDate)
547    {
548        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) use ($startDate, $endDate) {
549            $condition
550                ->andWith('process.Datum', '<=', $endDate->format('Y-m-d'))
551                ->andWith('process.Datum', '>=', $startDate->format('Y-m-d'));
552        });
553        return $this;
554    }
555
556    public function addConditionAuthKey($authKey)
557    {
558        $authKey = urldecode($authKey);
559        $this->query->where('process.absagecode', '=', $authKey);
560        return $this;
561    }
562
563    public function addConditionAssigned()
564    {
565        $this->query->where('process.StandortID', '!=', "0");
566        return $this;
567    }
568
569    public function addConditionStatus($status)
570    {
571        $this->query->where('process.status', '=', $status);
572        return $this;
573    }
574
575    public function addConditionIsReserved()
576    {
577        $this->query->where('process.name', 'NOT IN', array(
578            'dereferenced',
579            '(abgesagt)'
580        ))
581            ->where('process.vorlaeufigeBuchung', '=', 1)
582            ->where('process.StandortID', '>', 0);
583        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) {
584            $condition
585                ->andWith('process.istFolgeterminvon', 'IS', null)
586                ->orWith('process.istFolgeterminvon', '=', 0);
587        });
588        return $this;
589    }
590
591    public function addConditionSearch($queryString, $orWhere = false)
592    {
593        $queryString = trim($queryString);
594        $terms = $this->parseSearchTerms($queryString);
595        if ($terms === []) {
596            return $this;
597        }
598
599        $condition = function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($terms) {
600            if (count($terms) > 1) {
601                foreach ($terms as $term) {
602                    $query->andWith(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $inner) use ($term) {
603                        $this->appendNamePartLikeGroup($inner, $term['value'], true);
604                    });
605                }
606                return;
607            }
608
609            $term = $terms[0]['value'];
610            if ($terms[0]['quoted']) {
611                $this->appendNamePartLikeGroup($query, $term, true);
612                return;
613            }
614
615            $likeContains = '%' . $this->escapeLikeValue($term) . '%';
616            $useNameWordBoundary = !$this->isNumericSearchQuery($term) && mb_strlen($term) <= 3;
617
618            if ($useNameWordBoundary) {
619                $this->appendNamePartLikeGroup($query, $term, true, true);
620            } else {
621                $query->orWith('process.Name', 'LIKE', $likeContains);
622            }
623            $query->orWith('process.EMail', 'LIKE', $likeContains);
624            $query->orWith('process.Telefonnummer', 'LIKE', $likeContains);
625            $query->orWith('process.telefonnummer_fuer_rueckfragen', 'LIKE', $likeContains);
626            $query->orWith('process.displayNumber', 'LIKE', $likeContains);
627        };
628        if ($orWhere) {
629            $this->query->orWhere($condition);
630        } else {
631            $this->query->where($condition);
632        }
633        return $this;
634    }
635
636    public function addConditionUpcomingOnly(\DateTimeInterface $now)
637    {
638        $today = $now->format('Y-m-d');
639        $time = $now->format('H:i:s');
640        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $condition) use ($today, $time) {
641            $condition
642                ->andWith('process.Datum', '>', $today)
643                ->orWith(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $inner) use ($today, $time) {
644                    $inner
645                        ->andWith('process.Datum', '=', $today)
646                        ->andWith('process.Uhrzeit', '>=', $time);
647                });
648        });
649        return $this;
650    }
651
652    public function addOrderByAppointmentDate()
653    {
654        $this->query->orderBy('process.Datum', 'ASC');
655        $this->query->orderBy('process.Uhrzeit', 'ASC');
656        $this->query->orderBy('process.BuergerID', 'ASC');
657        return $this;
658    }
659
660    public function addOrderBySearchRelevance($queryString)
661    {
662        $queryString = trim($queryString);
663        if ($queryString === '') {
664            return $this;
665        }
666
667        $terms = $this->parseSearchTerms($queryString);
668        $primaryTerm = $terms[0]['value'] ?? $queryString;
669        $escapedLike = $this->escapeLikePatternForSqlLiteral($primaryTerm);
670        $this->query->orderBy(self::expression(
671            "CASE
672                WHEN process.Name LIKE '{$escapedLike} %' OR process.Name = '{$escapedLike}' THEN 0
673                WHEN process.Name LIKE '% {$escapedLike}' OR process.Name LIKE '% {$escapedLike} %' THEN 1
674                WHEN process.Name LIKE '%{$escapedLike}%' THEN 2
675                ELSE 3
676            END"
677        ));
678        $this->query->orderBy('process.Datum', 'ASC');
679        $this->query->orderBy('process.Uhrzeit', 'ASC');
680        $this->query->orderBy('process.BuergerID', 'ASC');
681
682        return $this;
683    }
684
685    /**
686     * @return array<int, array{value: string, quoted: bool}>
687     */
688    private function parseSearchTerms(string $queryString): array
689    {
690        if ($queryString === '') {
691            return [];
692        }
693
694        if (!preg_match_all('/"([^"]+)"|(\S+)/u', $queryString, $matches, PREG_SET_ORDER)) {
695            return [['value' => $queryString, 'quoted' => false]];
696        }
697
698        $terms = [];
699        foreach ($matches as $match) {
700            $value = trim($match[1] !== '' ? $match[1] : $match[2]);
701            if ($value === '') {
702                continue;
703            }
704            $terms[] = [
705                'value' => $value,
706                'quoted' => $match[1] !== '',
707            ];
708        }
709
710        return $terms;
711    }
712
713    private function appendNamePartLikeGroup(
714        \BO\Zmsbackend\Query\Builder\ConditionBuilder $query,
715        string $term,
716        bool $wordBoundaryOnly = false,
717        bool $includeWordPrefix = false
718    ): void {
719        $escaped = $this->escapeLikeValue($term);
720        $query->orWith('process.Name', 'LIKE', $escaped . ' %');
721        $query->orWith('process.Name', 'LIKE', '% ' . $escaped);
722        $query->orWith('process.Name', 'LIKE', '% ' . $escaped . ' %');
723        $query->orWith('process.Name', '=', $term);
724        if ($wordBoundaryOnly) {
725            if ($includeWordPrefix) {
726                $query->orWith('process.Name', 'LIKE', $escaped . '%');
727                $query->orWith('process.Name', 'LIKE', '% ' . $escaped . '%');
728            }
729        } else {
730            $query->orWith('process.Name', 'LIKE', '%' . $escaped . '%');
731        }
732    }
733
734    private function isNumericSearchQuery($queryString): bool
735    {
736        return (bool) preg_match('#^\d+$#', $queryString);
737    }
738
739    private function escapeLikeValue($value): string
740    {
741        return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value);
742    }
743
744    private function escapeLikePatternForSqlLiteral(string $value): string
745    {
746        return $this->escapeSqlStringLiteral($this->escapeLikeValue($value));
747    }
748
749    private function escapeSqlStringLiteral(string $value): string
750    {
751        return str_replace("'", "''", $value);
752    }
753
754    public function addConditionName($name, $exactMatching = false)
755    {
756        if ($exactMatching) {
757            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($name) {
758                $query->andWith('process.Name', '=', $name);
759            });
760        } else {
761            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($name) {
762                $query->andWith('process.Name', 'LIKE', "%$name%");
763            });
764        }
765        return $this;
766    }
767
768    public function addConditionMail($mailAddress, $exactMatching = false)
769    {
770        if ($exactMatching) {
771            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($mailAddress) {
772                $query->andWith('process.Email', '=', $mailAddress);
773            });
774        } else {
775            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($mailAddress) {
776                $query->andWith('process.Email', 'LIKE', "%$mailAddress%");
777            });
778        }
779        return $this;
780    }
781
782    public function addConditionCustomTextfield($customText, $exactMatching = false)
783    {
784        if ($exactMatching) {
785            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($customText) {
786                $query->andWith('process.custom_text_field', '=', $customText);
787            });
788        } else {
789            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($customText) {
790                $query->andWith('process.custom_text_field', 'LIKE', "%$customText%");
791            });
792        }
793        return $this;
794    }
795
796    public function addConditionCustomTextfield2($customText2, $exactMatching = false)
797    {
798        if ($exactMatching) {
799            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($customText2) {
800                $query->andWith('process.custom_text_field2', '=', $customText2);
801            });
802        } else {
803            $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($customText2) {
804                $query->andWith('process.custom_text_field2', 'LIKE', "%$customText2%");
805            });
806        }
807        return $this;
808    }
809
810    public function addConditionAmendment($amendment)
811    {
812        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($amendment) {
813            $query->andWith('process.Anmerkung', 'LIKE', "%$amendment%");
814        });
815        return $this;
816    }
817
818    /**
819     * Add Requests Join
820     */
821    public function addConditionRequestId($requestId)
822    {
823        $this->leftJoin(
824            new \BO\Zmsbackend\Query\Alias("buergeranliegen", 'buergeranliegen'),
825            'buergeranliegen.BuergerID',
826            '=',
827            'process.BuergerID'
828        );
829        $this->query->where('buergeranliegen.AnliegenID', '=', $requestId);
830        return $this;
831    }
832
833    public function addConditionScopeNameSearch(string $scopeName)
834    {
835        $likeValue = '%' . $this->escapeLikeValue($scopeName) . '%';
836        $this->leftJoin(
837            new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Query\Scope::TABLE, 'search_scope'),
838            self::expression(
839                'IF(`process`.`AbholortID`, `process`.`AbholortID`, `process`.`StandortID`)'
840            ),
841            '=',
842            'search_scope.StandortID'
843        );
844        $this->leftJoin(
845            new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Provider\Repository\Provider::TABLE, 'search_scope_provider'),
846            self::expression(
847                'search_scope.InfoDienstleisterID = search_scope_provider.id
848                AND search_scope.source = search_scope_provider.source'
849            )
850        );
851        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($likeValue) {
852            $query->orWith('search_scope.Bezeichnung', 'LIKE', $likeValue);
853            $query->orWith('search_scope.standortinfozeile', 'LIKE', $likeValue);
854            $query->orWith('search_scope.standortkuerzel', 'LIKE', $likeValue);
855            $query->orWith('search_scope_provider.name', 'LIKE', $likeValue);
856        });
857
858        return $this;
859    }
860
861    public function addConditionServiceNameSearch(string $serviceName)
862    {
863        $likeValue = '%' . $this->escapeLikeValue($serviceName) . '%';
864        $this->leftJoin(
865            new \BO\Zmsbackend\Query\Alias('buergeranliegen', 'search_request_link'),
866            'search_request_link.BuergerID',
867            '=',
868            'process.BuergerID'
869        );
870        $this->leftJoin(
871            new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Request\Repository\Request::TABLE, 'search_request'),
872            self::expression(
873                'search_request_link.AnliegenID = search_request.id
874                AND search_request_link.source = search_request.source'
875            )
876        );
877        $this->query->where('search_request.name', 'LIKE', $likeValue);
878
879        return $this;
880    }
881
882    /**
883     * add condition to get process if deallocation time < now
884     */
885    public function addConditionDeallocate($now)
886    {
887        $this->query->where(function (\BO\Zmsbackend\Query\Builder\ConditionBuilder $query) use ($now) {
888            $query
889                ->andWith('process.Name', '=', '(abgesagt)')
890                ->andWith('process.IPTimeStamp', '<', $now->getTimestamp());
891        });
892        $this->query->orderBy('process.IPTimeStamp', 'ASC');
893        return $this;
894    }
895
896    public function addValuesNewProcess(ProcessEntity $process, $parentProcess = 0, $childProcessCount = 0)
897    {
898        $values = [
899            'BuergerID' => $process->id,
900            'IPTimeStamp' => $process->createTimestamp,
901            'absagecode' => $process->authKey,
902            'hatFolgetermine' => $childProcessCount,
903            'istFolgeterminvon' => $parentProcess,
904            'displayNumber' => $parentProcess === 0 && empty($process->queue['number'])
905                ? $this->getNewDisplayNumber($process)
906                : null,
907            'wartenummer' => $process->queue['number']
908        ];
909        if ($process->toProperty()->apiclient->apiClientID->isAvailable()) {
910            $values['apiClientID'] = $process->apiclient->apiClientID;
911        }
912        if (isset($process->isTicketprinter) && $process->isTicketprinter) {
913            $values['is_ticketprinter'] = 1;
914        }
915        $this->addValues($values);
916    }
917
918    public function getNewDisplayNumber($process)
919    {
920        if (empty($process->scope->getPreference('queue', 'displayNumberPrefix'))) {
921            return $process->id;
922        }
923
924        $newDisplayNumber = $process->scope->getPreference('queue', 'displayNumberPrefix') . str_pad(
925            (new ScopeEntity())->readDisplayNumberUpdated($process->scope->id),
926            4,
927            '0',
928            STR_PAD_LEFT
929        );
930
931        if (
932            $this->checkIfDisplayNumberOnSameDateExists(
933                $process->scope->id,
934                $newDisplayNumber,
935                \DateTime::createFromFormat('U', (int) $process->getFirstAppointment()->date)
936            )
937        ) {
938            return $this->getNewDisplayNumber($process);
939        }
940
941        return $newDisplayNumber;
942    }
943
944    public function checkIfDisplayNumberOnSameDateExists($scopeId, $displayNumber, $date): bool
945    {
946        $processWithDisplayNumber = (new \BO\Zmsbackend\Process\Service\Process())->readProcessWithSameDayAndDisplayNumber(
947            $scopeId,
948            $displayNumber,
949            $date->format('Y-m-d')
950        );
951
952        return !empty($processWithDisplayNumber->getId());
953    }
954
955    public function addValuesUpdateProcess(
956        ProcessEntity $process,
957        \DateTimeInterface $dateTime,
958        $parentProcess = 0,
959        $previousStatus = null
960    ) {
961        $this->addValuesIPAdress($process);
962        if (0 === $parentProcess) {
963            $this->addValuesClientData($process);
964            $this->addProcessingTimeData($process, $dateTime, $previousStatus);
965            $this->addValuesQueueData($process);
966            $this->addValuesWaitingTimeData($process, $previousStatus);
967            $this->addValuesWayTimeData($process);
968        }
969        if ($process->isWithAppointment()) {
970            $this->addValuesFollowingProcessData($process, $parentProcess);
971        }
972        $this->addValuesWasMissed($process);
973        $this->addValuesPriority($process);
974        $this->addValuesStatusData($process, $dateTime);
975        $this->addValuesExternalUserId($process);
976    }
977
978    public function addValuesIPAdress(ProcessEntity $process)
979    {
980        $data = array();
981        $data['IPAdresse'] = $process->createIP;
982        $this->addValues($data);
983    }
984
985    public function addValuesFollowingProcessData($process, $parentProcess)
986    {
987        $data = array();
988        if (0 === $parentProcess) {
989            $data['hatFolgetermine'] = (1 <= $process->getFirstAppointment()->getSlotCount()) ?
990                $process->getFirstAppointment()->getSlotCount() - 1 :
991                0;
992        } else {
993            $data['Name'] = '(Folgetermin)';
994        }
995        $this->addValues($data);
996    }
997
998    public function addValuesAppointmentData(
999        ProcessEntity $process
1000    ) {
1001        $data = array();
1002        $appointment = $process->getFirstAppointment();
1003        $datetime = $appointment->toDateTime();
1004        $data['Datum'] = $datetime->format('Y-m-d');
1005        $data['Uhrzeit'] = $datetime->format('H:i:s');
1006        $this->addValues($data);
1007    }
1008
1009    public function addValuesScopeData(
1010        ProcessEntity $process
1011    ) {
1012        $data = array();
1013        $data['StandortID'] = $process->getScopeId();
1014        $this->addValues($data);
1015    }
1016
1017    public function addValuesStatusData(ProcessEntity $process, \DateTimeInterface $dateTime)
1018    {
1019        $data = array();
1020        $data['vorlaeufigeBuchung'] = ($process->status == 'reserved') ? 1 : 0;
1021        $data['aufruferfolgreich'] = ($process->status == 'processing') ? 1 : 0;
1022        if ($process->status == 'called') {
1023            $data['parked'] = 0;
1024            $data['nicht_erschienen'] = 0;
1025        }
1026        if ($process->status == 'pending') {
1027            $data['AbholortID'] = $process->scope->id;
1028            $data['Abholer'] = 1;
1029            $data['nicht_erschienen'] = 0;
1030            $data['parked'] = 0;
1031        }
1032        if ($process->status == 'queued') {
1033            $data['nicht_erschienen'] = 0;
1034            $data['parked'] = 0;
1035            if (
1036                $process->hasArrivalTime() &&
1037                (isset($process->queue->withAppointment) && $process->queue->withAppointment)
1038            ) {
1039                $data['wsm_aufnahmezeit'] = $dateTime->format('H:i:s');
1040            }
1041        }
1042        if ($process->status == 'missed') {
1043            $data['nicht_erschienen'] = 1;
1044        }
1045        if ($process->status == 'parked') {
1046            $data['parked'] = 1;
1047        }
1048        if ($process->status == 'confirmed') {
1049            $data['bestaetigt'] = 1;
1050        }
1051        if ($process->status == 'preconfirmed') {
1052            $data['bestaetigt'] = 0;
1053        }
1054        $data['status'] = $process->status;
1055        $data['parkedBy'] = $process->getParkedBy();
1056
1057        $this->addValues($data);
1058    }
1059
1060    protected function addValuesClientData($process)
1061    {
1062        $data = array();
1063        $client = $process->getFirstClient();
1064        if ($client && $client->hasFamilyName()) {
1065            $data['Name'] = $client->familyName;
1066        }
1067        if ($client && $client->hasEmail()) {
1068            $data['EMail'] = $client->email;
1069        }
1070        if ($client && $client->offsetExists('telephone')) {
1071            $data['telefonnummer_fuer_rueckfragen'] = $client->telephone;
1072            $data['Telefonnummer'] = $client->telephone; // to stay compatible with ZMS1
1073        }
1074        if ($client && $client->offsetExists('emailSendCount')) {
1075            $data['EMailverschickt'] = ('-1' == $client->emailSendCount) ? 0 : $client->emailSendCount;
1076        }
1077        $data['Anmerkung'] = $process->getAmendment();
1078        $data['custom_text_field'] = $process->getCustomTextfield();
1079        $data['custom_text_field2'] = $process->getCustomTextfield2();
1080        $data['zustimmung_kundenbefragung'] = ($client->surveyAccepted) ? 1 : 0;
1081        $data['Erinnerungszeitpunkt'] = $process->getReminderTimestamp();
1082        $data['AnzahlPersonen'] = $process->getClients()->count();
1083        $this->addValues($data);
1084    }
1085
1086    public function addValueDisplayNumber($process)
1087    {
1088        $data['displayNumber'] = $process->displayNumber;
1089        $this->addValues($data);
1090    }
1091
1092    protected function addProcessingTimeData($process, \DateTimeInterface $dateTime, $previousStatus = null)
1093    {
1094        $data = array();
1095        $timeoutTime = null;
1096        $finishTime = null;
1097
1098        if (
1099            isset($previousStatus) &&
1100            (($process->status == 'called' && $previousStatus == 'called') ||
1101                ($process->status == 'processing' && $previousStatus == 'processing'))
1102        ) {
1103            $timeoutTime = $dateTime->format('Y-m-d H:i:s');
1104            $data['timeoutTime'] = $timeoutTime;
1105        } elseif ($process->status == 'processing') {
1106            $showUpTime = $dateTime->format('Y-m-d H:i:s');
1107            $data['showUpTime'] = $showUpTime;
1108        } elseif ($process->status == 'finished') {
1109            $finishTime = $dateTime->format('Y-m-d H:i:s');
1110            $data['finishTime'] = $finishTime;
1111        } elseif (
1112            $process->status == 'queued'
1113            && isset($previousStatus)
1114            && in_array($previousStatus, ['called', 'processing'], true)
1115        ) {
1116            $data['showUpTime'] = null;
1117            $data['timeoutTime'] = null;
1118        }
1119
1120
1121        if (isset($finishTime) && isset($process->showUpTime)) {
1122            $showUpDateTime = new \DateTime($process->showUpTime);
1123            $finishTime = new \DateTime($finishTime);
1124
1125            $processingTimeStr = $process->getProcessingTime();
1126            $previousProcessingTimeInSeconds = 0; // Default to 0 if not set
1127
1128            if (!empty($processingTimeStr)) {
1129                // Assume the format is HH:MM:SS and parse it
1130                list($hours, $minutes, $seconds) = explode(':', $processingTimeStr);
1131                // Convert hours, minutes, and seconds to total seconds
1132                $previousProcessingTimeInSeconds = (int)$hours * 3600 + (int)$minutes * 60 + (int)$seconds;
1133            }
1134
1135            $interval = $showUpDateTime->diff($finishTime);
1136            $totalSeconds = ($interval->days * 24 * 60 * 60) + ($interval->h * 60 * 60) + ($interval->i * 60) + $interval->s;
1137
1138            $totalSeconds += $previousProcessingTimeInSeconds;
1139
1140            $hours = intdiv($totalSeconds, 3600);
1141            $minutes = intdiv($totalSeconds % 3600, 60);
1142            $seconds = $totalSeconds % 60;
1143
1144            $data['processing_time'] = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
1145        } elseif (isset($timeoutTime) && isset($process->showUpTime)) {
1146            $showUpDateTime = new \DateTime($process->showUpTime);
1147            $timeoutDateTime = new \DateTime($timeoutTime);
1148            $processingTimeStr = $process->getProcessingTime();
1149
1150            $previousProcessingTimeInSeconds = 0; // Default to 0 if not set
1151            if (!empty($processingTimeStr)) {
1152                // Assume the format is HH:MM:SS and parse it
1153                list($hours, $minutes, $seconds) = explode(':', $processingTimeStr);
1154                // Convert hours, minutes, and seconds to total seconds
1155                $previousProcessingTimeInSeconds = (int)$hours * 3600 + (int)$minutes * 60 + (int)$seconds;
1156            }
1157            $interval = $showUpDateTime->diff($timeoutDateTime);
1158            $totalSeconds = ($interval->days * 24 * 60 * 60) + ($interval->h * 60 * 60) + ($interval->i * 60) + $interval->s;
1159
1160            $totalSeconds += $previousProcessingTimeInSeconds;
1161
1162            $hours = intdiv($totalSeconds, 3600);
1163            $minutes = intdiv($totalSeconds % 3600, 60);
1164            $seconds = $totalSeconds % 60;
1165
1166            $data['processing_time'] = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
1167        }
1168
1169        $this->addValues($data);
1170    }
1171
1172    protected function addValuesQueueData($process)
1173    {
1174        $data = array();
1175        $appointmentTime = $process->getFirstAppointment()->toDateTime()->format('H:i:s');
1176
1177        if (isset($process->queue['callCount'])) {
1178            $data['AnzahlAufrufe'] = (int) $process->queue['callCount'];
1179        }
1180        if (isset($process->queue['callTime']) && $process->queue['callTime']) {
1181            $data['aufrufzeit'] = (new \DateTimeImmutable())
1182                ->setTimestamp($process->queue['callTime'])->format('H:i:s');
1183        }
1184        if (isset($process->queue['lastCallTime']) && $process->queue['lastCallTime']) {
1185            $data['Timestamp'] = (new \DateTimeImmutable())
1186                ->setTimestamp($process->queue['lastCallTime'])->format('H:i:s');
1187        }
1188        if (isset($process->queue['arrivalTime']) && $process->queue['arrivalTime']) {
1189            $data['wsm_aufnahmezeit'] = (new \DateTimeImmutable())
1190                ->setTimestamp($process->queue['arrivalTime'])->format('H:i:s');
1191        }
1192        if (isset($data['wsm_aufnahmezeit']) && $data['wsm_aufnahmezeit'] == $appointmentTime) {
1193            // Do not save arrivalTime if it is an appointment
1194            $data['wsm_aufnahmezeit'] = 0;
1195        }
1196        $this->addValues($data);
1197    }
1198
1199    protected function addValuesWaitingTimeData(ProcessEntity $process, $previousStatus = null)
1200    {
1201        $data = array();
1202        $hasWaitingTimeAlready = (
1203            isset($process->queue->waitingTime)
1204            && $process->queue->waitingTime
1205            && $process->queue->waitingTime !== '00:00:00'
1206        );
1207
1208        if (
1209            !$hasWaitingTimeAlready
1210            && (
1211            (
1212                // Szenario 1: Vorheriger Status ist queued, missed oder confirmed und aktueller Status ist called
1213                in_array($previousStatus, ['queued', 'missed', 'confirmed'])
1214                && $process->status == 'called'
1215                && (
1216                    (
1217                        isset($process->queue->callCount)
1218                        && $process->queue->callCount <= 0
1219                    )
1220                    || (
1221                        ($previousStatus === 'queued' || $previousStatus === 'confirmed')
1222                        && (
1223                            !isset($process->queue->callTime)
1224                            || (int) $process->queue->callTime === 0
1225                        )
1226                    )
1227                )
1228            )
1229            ||
1230            (
1231                // Szenario 2: Vorheriger Status ist missed, aktueller Status ist queued,
1232                // es gibt den Hinweis wasMissed und die Queue sowie waitingTime sind gesetzt
1233                $previousStatus == 'missed'
1234                && $process->status == 'queued'
1235                && !empty($process->wasMissed)
1236                && isset($process->queue)
1237                && isset($process->queue->waitingTime)
1238            )
1239            )
1240        ) {
1241            $wartezeitInSeconds = $process->getWaitedSeconds();
1242            $wartezeitInSeconds = $wartezeitInSeconds > 0 ? $wartezeitInSeconds : 0;
1243
1244            // Convert total seconds into HH:MM:SS format
1245            $hours = intdiv($wartezeitInSeconds, 3600);
1246            $minutes = intdiv($wartezeitInSeconds % 3600, 60);
1247            $seconds = $wartezeitInSeconds % 60;
1248
1249            $data['waiting_time'] = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
1250        }
1251
1252        $this->addValues($data);
1253    }
1254
1255
1256    protected function addValuesWayTimeData(ProcessEntity $process)
1257    {
1258        $data = array();
1259        if ($process->status == 'processing') {
1260            $wayTimeInSeconds = max(0, (int) $process->getWaySeconds());
1261            $hours = intdiv($wayTimeInSeconds, 3600);
1262            $minutes = intdiv($wayTimeInSeconds % 3600, 60);
1263            $seconds = $wayTimeInSeconds % 60;
1264            $data['way_time'] = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
1265        }
1266        $this->addValues($data);
1267    }
1268
1269    protected function addValuesWasMissed($process)
1270    {
1271        $data = [
1272            'wasMissed' => $process->wasMissed ? 1 : 0,
1273        ];
1274
1275        $this->addValues($data);
1276        return $this;
1277    }
1278
1279    protected function addValuesPriority($process)
1280    {
1281        $data = [
1282            'priority' => $process->priority,
1283        ];
1284
1285        $this->addValues($data);
1286        return $this;
1287    }
1288
1289    protected function addValuesExternalUserId($process)
1290    {
1291        $data = [
1292            'external_user_id' => $process->externalUserId,
1293        ];
1294
1295        $this->addValues($data);
1296        return $this;
1297    }
1298
1299    #[\Override]
1300    public function postProcess($data)
1301    {
1302        $data[$this->getPrefixed("appointments__0__date")] =
1303            strtotime($data[$this->getPrefixed("appointments__0__date")]);
1304        if ('00:00:00' != $data[$this->getPrefixed("queue__callTime")]) {
1305            $time = explode(':', $data[$this->getPrefixed("queue__callTime")]);
1306            $data[$this->getPrefixed("queue__callTime")] = (new \DateTimeImmutable())
1307                ->setTimestamp($data[$this->getPrefixed("appointments__0__date")])
1308                ->setTime($time[0], $time[1], $time[2])
1309                ->getTimestamp();
1310        } else {
1311            $data[$this->getPrefixed("queue__callTime")] = 0;
1312        }
1313        if ('00:00:00' != $data[$this->getPrefixed("queue__lastCallTime")]) {
1314            $time = explode(':', $data[$this->getPrefixed("queue__lastCallTime")]);
1315            $data[$this->getPrefixed("queue__lastCallTime")] = (new \DateTimeImmutable())
1316                ->setTimestamp($data[$this->getPrefixed("appointments__0__date")])
1317                ->setTime($time[0], $time[1], $time[2])
1318                ->getTimestamp();
1319        } else {
1320            $data[$this->getPrefixed("queue__lastCallTime")] = 0;
1321        }
1322        $data[$this->getPrefixed("queue__arrivalTime")] =
1323            strtotime($data[$this->getPrefixed("queue__arrivalTime")]);
1324        if (
1325            isset($data[$this->getPrefixed('scope__provider__data')])
1326            && $data[$this->getPrefixed('scope__provider__data')]
1327        ) {
1328            $data[$this->getPrefixed('scope__provider__data')] =
1329                json_decode($data[$this->getPrefixed('scope__provider__data')], true);
1330        }
1331        if (isset($data[$this->getPrefixed('__clientsCount')])) {
1332            $clientsCount = $data[$this->getPrefixed('__clientsCount')];
1333            unset($data[$this->getPrefixed('__clientsCount')]);
1334            while (--$clientsCount > 0) {
1335                $data[$this->getPrefixed('clients__' . $clientsCount . '__familyName')] = 'Unbekannt';
1336            }
1337        }
1338        $data[$this->getPrefixed("lastChange")] =
1339            (new \DateTimeImmutable($data[$this->getPrefixed("lastChange")] .
1340                \BO\Zmsbackend\Connection\Select::$connectionTimezone))->getTimestamp();
1341        return $data;
1342    }
1343
1344    public function removeDuplicates()
1345    {
1346        $this->query->groupBy('process.BuergerID');
1347        return $this;
1348    }
1349
1350    #[\Override]
1351    protected function addRequiredJoins()
1352    {
1353        if ($this->shouldLoadEntity('processuser')) {
1354            $this->leftJoin(
1355                new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Useraccount\Repository\Useraccount::TABLE, 'processuser'),
1356                'process.NutzerID',
1357                '=',
1358                'processuser.NutzerID'
1359            );
1360        }
1361
1362        if ($this->shouldLoadEntity('processscope')) {
1363            $this->leftJoin(
1364                new \BO\Zmsbackend\Query\Alias(\BO\Zmsbackend\Query\Scope::TABLE, 'processscope'),
1365                'process.StandortID',
1366                '=',
1367                'processscope.StandortID'
1368            );
1369        }
1370    }
1371
1372    public function addConditionExternalUserId(string $externalUserId)
1373    {
1374        $this->query->where('process.external_user_id', '=', $externalUserId);
1375        return $this;
1376    }
1377}