Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
350 / 385
31.25% covered (danger)
31.25%
5 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
MapperService
90.91% covered (success)
90.91%
350 / 385
31.25% covered (danger)
31.25%
5 / 16
218.41
0.00% covered (danger)
0.00%
0 / 1
 resolveAllowDisabledServicesMix
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 mapScopeForProvider
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
10.24
 extractReservationDuration
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
5.07
 extractActivationDuration
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
7.29
 mapOfficesWithScope
91.67% covered (success)
91.67%
55 / 60
0.00% covered (danger)
0.00%
0 / 1
50.39
 mapCombinable
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 mapServicesWithCombinations
97.30% covered (success)
97.30%
36 / 37
0.00% covered (danger)
0.00%
0 / 1
15
 mapRelations
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 scopeToThinnedScope
94.20% covered (success)
94.20%
65 / 69
0.00% covered (danger)
0.00%
0 / 1
24.11
 processToThinnedProcess
82.61% covered (warning)
82.61%
38 / 46
0.00% covered (danger)
0.00%
0 / 1
47.00
 thinnedProcessToProcess
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
5
 createScope
100.00% covered (success)
100.00%
41 / 41
100.00% covered (success)
100.00%
1 / 1
6
 createRequests
59.09% covered (warning)
59.09%
13 / 22
0.00% covered (danger)
0.00%
0 / 1
5.10
 contactToThinnedContact
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
 providerToThinnedProvider
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
8
 generateIcsContent
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace BO\Zmscitizenapi\Services\Core;
6
7use BO\Zmscitizenapi\Models\Office;
8use BO\Zmscitizenapi\Models\Combinable;
9use BO\Zmscitizenapi\Models\OfficeServiceRelation;
10use BO\Zmscitizenapi\Models\Service;
11use BO\Zmscitizenapi\Models\ThinnedContact;
12use BO\Zmscitizenapi\Models\ThinnedProcess;
13use BO\Zmscitizenapi\Models\ThinnedProvider;
14use BO\Zmscitizenapi\Models\ThinnedScope;
15use BO\Zmscitizenapi\Models\Collections\OfficeList;
16use BO\Zmscitizenapi\Models\Collections\OfficeServiceRelationList;
17use BO\Zmscitizenapi\Models\Collections\ServiceList;
18use BO\Zmscitizenapi\Models\Collections\ThinnedScopeList;
19use BO\Zmscitizenapi\Utils\ClientIpHelper;
20use BO\Zmsentities\Appointment;
21use BO\Zmsentities\Client;
22use BO\Zmsentities\Contact;
23use BO\Zmsentities\Process;
24use BO\Zmsentities\Provider;
25use BO\Zmsentities\Request;
26use BO\Zmsentities\Scope;
27use BO\Zmsentities\Collection\ProviderList;
28use BO\Zmsentities\Collection\RequestList;
29use BO\Zmsentities\Collection\RequestRelationList;
30
31/**
32 * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
33 * @TODO: Extract class has ExcessiveClassComplexity 101 vs 100
34 */
35class MapperService
36{
37    private static function resolveAllowDisabledServicesMix(Provider $provider): ?array
38    {
39        if (!isset($provider->data['allowDisabledServicesMix']) || !is_array($provider->data['allowDisabledServicesMix'])) {
40            return null;
41        }
42        return array_map('intval', $provider->data['allowDisabledServicesMix']);
43    }
44
45    public static function mapScopeForProvider(
46        int $providerId,
47        ThinnedScopeList $scopes,
48        ?string $providerSource = null
49    ): ?ThinnedScope {
50        foreach ($scopes->getScopes() as $scope) {
51            if (!$scope instanceof ThinnedScope) {
52                continue;
53            }
54
55            $prov = $scope->provider ?? null;
56            if (!$prov) {
57                continue;
58            }
59
60            $provId  = is_object($prov) ? ($prov->id   ?? null) : ($prov['id']    ?? null);
61            $provSrc = is_object($prov) ? ($prov->source ?? null) : ($prov['source'] ?? null);
62
63            if ((string)$provId !== (string)$providerId) {
64                continue;
65            }
66
67            if ($providerSource === null || $providerSource === '') {
68                return $scope;
69            }
70
71            if ((string)$provSrc === (string)$providerSource) {
72                return $scope;
73            }
74        }
75
76        return null;
77    }
78
79    public static function extractReservationDuration(Scope|ThinnedScope|null $scope): ?int
80    {
81        if ($scope === null) {
82            return null;
83        }
84        if ($scope instanceof ThinnedScope) {
85            $reservationDuration = $scope->getReservationDuration();
86            return $reservationDuration !== null ? (int) $reservationDuration : null;
87        }
88        $reservationDuration = $scope?->toProperty()?->preferences?->appointment?->reservationDuration?->get();
89        return $reservationDuration !== null ? (int) $reservationDuration : null;
90    }
91
92    public static function extractActivationDuration(Scope|ThinnedScope|null $scope): ?int
93    {
94        if ($scope === null) {
95            return null;
96        }
97
98        if ($scope instanceof ThinnedScope) {
99            $activationDuration = $scope->getActivationDuration();
100            if ($activationDuration === null || $activationDuration === '') {
101                return null;
102            }
103            return (int) $activationDuration;
104        }
105
106        $activationDuration = $scope?->toProperty()?->preferences?->appointment?->activationDuration?->get();
107        if ($activationDuration === null || $activationDuration === '') {
108            return null;
109        }
110        return (int) $activationDuration;
111    }
112
113    /**
114     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
115     * @SuppressWarnings(PHPMD.NPathComplexity)
116     * @TODO: Extract mapping logic into specialized mapper classes for each entity type
117     *
118     */
119    public static function mapOfficesWithScope(ProviderList $providerList, bool $showUnpublished = false): OfficeList
120    {
121        $offices = [];
122        $scopes = ZmsApiFacadeService::getScopes();
123        if (!$scopes instanceof ThinnedScopeList) {
124            return new OfficeList();
125        }
126
127        foreach ($providerList as $provider) {
128            // âœ… Source normalisieren: leerer String -> Fallback auf App::$source_name
129            $providerSource = isset($provider->source) && $provider->source !== ''
130                ? (string)$provider->source
131                : (string)\App::$source_name;
132
133            $providerScope = self::mapScopeForProvider(
134                (int) $provider->id,
135                $scopes,
136                $providerSource
137            );
138
139            if (!$showUnpublished && isset($provider->data['public']) && !(bool) $provider->data['public']) {
140                continue;
141            }
142
143            $offices[] = new Office(
144                id: isset($provider->id) ? (int) $provider->id : 0,
145                name: isset($provider->displayName) ? $provider->displayName : (isset($provider->name) ? $provider->name : null),
146                address: isset($provider->data['address']) ? $provider->data['address'] : null,
147                showAlternativeLocations: isset($provider->data['showAlternativeLocations']) ? $provider->data['showAlternativeLocations'] : null,
148                displayNameAlternatives: $provider->data['displayNameAlternatives'] ?? [],
149                organization: $provider->data['organization'] ?? null,
150                organizationUnit: $provider->data['organizationUnit'] ?? null,
151                slotTimeInMinutes: $provider->data['slotTimeInMinutes'] ?? null,
152                geo: isset($provider->data['geo']) ? $provider->data['geo'] : null,
153                disabledByServices: isset($provider->data['dontShowByServices']) ? $provider->data['dontShowByServices'] : [],
154                priority: isset($provider->data['prio']) ? $provider->data['prio'] : 1,
155                scope: isset($providerScope) && !isset($providerScope['errors']) ? new ThinnedScope(
156                    id: isset($providerScope->id) ? (int) $providerScope->id : 0,
157                    provider: isset($providerScope->provider) ? $providerScope->provider : null,
158                    shortName: isset($providerScope->shortName) ? (string) $providerScope->shortName : null,
159                    emailFrom: isset($providerScope->emailFrom) ? (string) $providerScope->emailFrom : null,
160                    emailRequired: isset($providerScope->emailRequired) ? (bool) $providerScope->emailRequired : null,
161                    telephoneActivated: isset($providerScope->telephoneActivated) ? (bool) $providerScope->telephoneActivated : null,
162                    telephoneRequired: isset($providerScope->telephoneRequired) ? (bool) $providerScope->telephoneRequired : null,
163                    customTextfieldActivated: isset($providerScope->customTextfieldActivated) ? (bool) $providerScope->customTextfieldActivated : null,
164                    customTextfieldRequired: isset($providerScope->customTextfieldRequired) ? (bool) $providerScope->customTextfieldRequired : null,
165                    customTextfieldLabel: isset($providerScope->customTextfieldLabel) ? (string) $providerScope->customTextfieldLabel : null,
166                    customTextfield2Activated: isset($providerScope->customTextfield2Activated) ? (bool) $providerScope->customTextfield2Activated : null,
167                    customTextfield2Required: isset($providerScope->customTextfield2Required) ? (bool) $providerScope->customTextfield2Required : null,
168                    customTextfield2Label: isset($providerScope->customTextfield2Label) ? (string) $providerScope->customTextfield2Label : null,
169                    captchaActivatedRequired: isset($providerScope->captchaActivatedRequired) ? (bool) $providerScope->captchaActivatedRequired : null,
170                    infoForAppointment: isset($providerScope->infoForAppointment)
171                        ? ((string) $providerScope->infoForAppointment === '' ? null : (string) $providerScope->infoForAppointment)
172                        : null,
173                    infoForAllAppointments: isset($providerScope->infoForAllAppointments)
174                        ? ((string) $providerScope->infoForAllAppointments === '' ? null : (string) $providerScope->infoForAllAppointments)
175                        : null,
176                    appointmentsPerMail: isset($providerScope->appointmentsPerMail) ? ((string) $providerScope->appointmentsPerMail === '' ? null : (string) $providerScope->appointmentsPerMail) : null,
177                    slotsPerAppointment: isset($providerScope->slotsPerAppointment) ? ((string) $providerScope->slotsPerAppointment === '' ? null : (string) $providerScope->slotsPerAppointment) : null,
178                    whitelistedMails: isset($providerScope->whitelistedMails) ? ((string) $providerScope->whitelistedMails === '' ? null : (string) $providerScope->whitelistedMails) : null,
179                    reservationDuration: (int) self::extractReservationDuration($providerScope),
180                    activationDuration: self::extractActivationDuration($providerScope),
181                    hint: isset($providerScope->hint) ? (trim((string) $providerScope->hint) === '' ? null : (string) $providerScope->hint) : null
182                ) : null,
183                slotsPerAppointment: isset($providerScope) && !isset($providerScope['errors']) && isset($providerScope->slotsPerAppointment) ? ((string) $providerScope->slotsPerAppointment === '' ? null : (string) $providerScope->slotsPerAppointment) : null,
184                parentId: isset($provider->parent_id) ? (int) $provider->parent_id : null,
185                allowDisabledServicesMix: self::resolveAllowDisabledServicesMix($provider)
186            );
187        }
188
189        return new OfficeList($offices);
190    }
191
192    public static function mapCombinable(array $serviceCombinations): ?Combinable
193    {
194        return !empty($serviceCombinations) ? new Combinable($serviceCombinations) : null;
195    }
196
197    /**
198     * Map services with combinations based on request and relation lists.
199     *
200     * @param RequestList $requestList
201     * @param RequestRelationList $relationList
202     * @return ServiceList
203     * @SuppressWarnings(PHPMD.NPathComplexity)
204     */
205    public static function mapServicesWithCombinations(
206        RequestList $requestList,
207        RequestRelationList $relationList,
208        bool $showUnpublished = false
209    ): ServiceList {
210        /** @var array<string, array<int>> $servicesProviderIds */
211        $servicesProviderIds = [];
212        foreach ($relationList as $relation) {
213            if (!$showUnpublished && !$relation->isPublic()) {
214                continue;
215            }
216
217            $serviceId = $relation->request->id;
218            $servicesProviderIds[$serviceId] ??= [];
219            $servicesProviderIds[$serviceId][] = $relation->provider->id;
220        }
221
222        /** @var Service[] $services */
223        $services = [];
224        $requestArray = iterator_to_array($requestList);
225        usort($requestArray, function ($a, $b) {
226
227            return $a->getId() <=> $b->getId();
228            // Sorting by service ID (ascending order)
229        });
230        foreach ($requestArray as $service) {
231            if (
232                !$showUnpublished
233                && isset($service->getAdditionalData()['public'])
234                && !$service->getAdditionalData()['public']
235            ) {
236                continue;
237            }
238
239            /** @var array<string, array<int>> $serviceCombinations */
240            $serviceCombinations = [];
241            $combinableData = $service->getAdditionalData()['combinable'] ?? [];
242            foreach ($combinableData as $combinationServiceId) {
243                $commonProviders = array_intersect($servicesProviderIds[$service->getId()] ?? [], $servicesProviderIds[$combinationServiceId] ?? []);
244                $serviceCombinations[$combinationServiceId] = !empty($commonProviders) ? array_values($commonProviders) : [];
245            }
246
247            $combinable = self::mapCombinable($serviceCombinations);
248
249            $extra = $service->getAdditionalData() ?? [];
250            $parentId  = isset($service->parent_id)  ? (int)$service->parent_id  : (isset($extra['parent_id'])  ? (int)$extra['parent_id']  : null);
251            $variantId = isset($service->variant_id) ? (int)$service->variant_id : (isset($extra['variant_id']) ? (int)$extra['variant_id'] : null);
252
253            if (!empty($servicesProviderIds[$service->getId()])) {
254                $services[] = new Service(
255                    id: (int) $service->getId(),
256                    name: $service->getName(),
257                    maxQuantity: $service->getAdditionalData()['maxQuantity'] ?? 1,
258                    combinable: $combinable ?? new Combinable(),
259                    parentId: $parentId,
260                    variantId: $variantId,
261                    showOnStartPage: $service->getAdditionalData()['showOnStartPage'] ?? true,
262                );
263            }
264        }
265
266        return new ServiceList($services);
267    }
268
269
270    public static function mapRelations(
271        RequestRelationList $relationList,
272        bool $showUnpublished = false
273    ): OfficeServiceRelationList {
274        $relations = [];
275        foreach ($relationList as $relation) {
276            if (!$showUnpublished && !$relation->isPublic()) {
277                continue;
278            }
279
280            $relations[] = new OfficeServiceRelation(
281                officeId: (int) $relation->provider->id,
282                serviceId: (int) $relation->request->id,
283                slots: intval($relation->slots),
284                public: (bool) $relation->isPublic(),
285                maxQuantity: (int) $relation->maxQuantity
286            );
287        }
288
289        return new OfficeServiceRelationList($relations);
290    }
291
292    /**
293     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
294     * @SuppressWarnings(PHPMD.NPathComplexity)
295     */
296    public static function scopeToThinnedScope(Scope $scope): ThinnedScope
297    {
298        if (!$scope || !isset($scope->id)) {
299            return new ThinnedScope();
300        }
301
302        $thinnedProvider = null;
303        try {
304            if (isset($scope->provider)) {
305                $provider = $scope->provider;
306                $contact = $provider->contact ?? null;
307                $thinnedProvider = new ThinnedProvider(
308                    id: isset($provider->id) ? (int)$provider->id : null,
309                    name: $provider->name ?? null,
310                    displayName: $provider->displayName ?? null,
311                    source: $provider->source ?? null,
312                    contact: $contact ? self::contactToThinnedContact($contact) : null
313                );
314            }
315        } catch (\BO\Zmsentities\Exception\ScopeMissingProvider $e) {
316            $thinnedProvider = null;
317        }
318
319        return new ThinnedScope(
320            id: (int) ($scope->id ?? 0),
321            provider: $thinnedProvider,
322            shortName: isset($scope->shortName) ? (string) $scope->shortName : null,
323            emailFrom: (string) $scope->getEmailFrom() ?? null,
324            emailRequired: $scope->getEmailRequired() === null
325                ? null
326                : (bool) $scope->getEmailRequired(),
327            telephoneActivated: $scope->getTelephoneActivated() === null
328                ? null
329                : (bool) $scope->getTelephoneActivated(),
330            telephoneRequired: $scope->getTelephoneRequired() === null
331                ? null
332                : (bool) $scope->getTelephoneRequired(),
333            customTextfieldActivated: $scope->getCustomTextfieldActivated() === null
334                ? null
335                : (bool) $scope->getCustomTextfieldActivated(),
336            customTextfieldRequired: $scope->getCustomTextfieldRequired() === null
337                ? null
338                : (bool) $scope->getCustomTextfieldRequired(),
339            customTextfieldLabel: $scope->getCustomTextfieldLabel() === null
340                ? null
341                : (string) $scope->getCustomTextfieldLabel(),
342            customTextfield2Activated: $scope->getCustomTextfield2Activated() === null
343                ? null
344                : (bool) $scope->getCustomTextfield2Activated(),
345            customTextfield2Required: $scope->getCustomTextfield2Required() === null
346                ? null
347                : (bool) $scope->getCustomTextfield2Required(),
348            customTextfield2Label: $scope->getCustomTextfield2Label() === null
349                ? null
350                : (string) $scope->getCustomTextfield2Label(),
351            captchaActivatedRequired: $scope->getCaptchaActivatedRequired() === null
352                ? null
353                : (bool) $scope->getCaptchaActivatedRequired(),
354            infoForAppointment: $scope->getInfoForAppointment() === null
355                ? null
356                : (string) $scope->getInfoForAppointment(),
357            infoForAllAppointments: $scope->getInfoForAllAppointments() === null
358                ? null
359                : (string) $scope->getInfoForAllAppointments(),
360            slotsPerAppointment: $scope->getSlotsPerAppointment() === null
361                ? null
362                : (string) $scope->getSlotsPerAppointment(),
363            appointmentsPerMail: $scope->getAppointmentsPerMail() !== null
364                ? (string) $scope->getAppointmentsPerMail()
365                : null,
366            whitelistedMails: $scope->getWhitelistedMails() === null
367                ? null
368                : (string) $scope->getWhitelistedMails(),
369            reservationDuration: MapperService::extractReservationDuration($scope),
370            activationDuration: MapperService::extractActivationDuration($scope),
371            hint: (trim((string) ($scope->getScopeHint() ?? '')) === '') ? null : (string) $scope->getScopeHint()
372        );
373    }
374
375    /**
376     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
377     * @SuppressWarnings(PHPMD.NPathComplexity)
378     * @TODO: Break down process mapping into smaller, focused methods
379     */
380    public static function processToThinnedProcess(Process $myProcess): ThinnedProcess
381    {
382        if (!$myProcess || !isset($myProcess->id)) {
383            return new ThinnedProcess();
384        }
385
386        $subRequestCounts = [];
387        $mainServiceId = null;
388        $mainServiceName = null;
389        $mainServiceCount = 0;
390        $requests = $myProcess->getRequests() ?? [];
391        if ($requests) {
392            $requests = is_array($requests) ? $requests : iterator_to_array($requests);
393            if (count($requests) > 0) {
394                $mainServiceId = $requests[0]->id;
395                foreach ($requests as $request) {
396                    if ($request->id === $mainServiceId) {
397                        $mainServiceCount++;
398                        if (!$mainServiceName && isset($request->name)) {
399                            $mainServiceName = $request->name;
400                        }
401                    } else {
402                        if (!isset($subRequestCounts[$request->id])) {
403                            $subRequestCounts[$request->id] = [
404                                'id' => (int) $request->id,
405                                'name'  => $request->name,
406                                'count' => 0,
407                            ];
408                        }
409                        $subRequestCounts[$request->id]['count']++;
410                    }
411                }
412            }
413        }
414
415        // Generate ICS content if process has appointments with time
416        $icsContent = self::generateIcsContent($myProcess);
417
418        return new ThinnedProcess(
419            processId: isset($myProcess->id) ? (int) $myProcess->id : 0,
420            timestamp: (isset($myProcess->appointments[0]) && isset($myProcess->appointments[0]->date)) ? strval($myProcess->appointments[0]->date) : null,
421            authKey: isset($myProcess->authKey) ? $myProcess->authKey : null,
422            captchaToken: isset($myProcess->captchaToken) ? $myProcess->captchaToken : null,
423            familyName: (isset($myProcess->clients[0]) && isset($myProcess->clients[0]->familyName)) ? $myProcess->clients[0]->familyName : null,
424            customTextfield: isset($myProcess->customTextfield) ? $myProcess->customTextfield : null,
425            customTextfield2: isset($myProcess->customTextfield2) ? $myProcess->customTextfield2 : null,
426            email: (isset($myProcess->clients[0]) && isset($myProcess->clients[0]->email)) ? $myProcess->clients[0]->email : null,
427            telephone: (isset($myProcess->clients[0]) && isset($myProcess->clients[0]->telephone)) ? $myProcess->clients[0]->telephone : null,
428            officeName: (isset($myProcess->scope->contact) && isset($myProcess->scope->contact->name)) ? $myProcess->scope->contact->name : null,
429            officeId: (isset($myProcess->scope->provider) && isset($myProcess->scope->provider->id)) ? (int) $myProcess->scope->provider->id : 0,
430            scope: isset($myProcess->scope) ? self::scopeToThinnedScope($myProcess->scope) : null,
431            subRequestCounts: isset($subRequestCounts) ? array_values($subRequestCounts) : [],
432            serviceId: isset($mainServiceId) ? (int) $mainServiceId : 0,
433            serviceName: isset($mainServiceName) ? $mainServiceName : null,
434            serviceCount: isset($mainServiceCount) ? $mainServiceCount : 0,
435            status: (isset($myProcess->queue) && isset($myProcess->queue->status)) ? $myProcess->queue->status : null,
436            slotCount: (isset($myProcess->appointments[0]) && isset($myProcess->appointments[0]->slotCount)) ? (int) $myProcess->appointments[0]->slotCount : null,
437            displayNumber: ($myProcess->getDisplayNumber() ?: null),
438            icsContent: isset($icsContent) ? $icsContent : null
439        );
440    }
441
442    public static function thinnedProcessToProcess(ThinnedProcess $thinnedProcess): Process
443    {
444        if (!$thinnedProcess || !isset($thinnedProcess->processId)) {
445            return new Process();
446        }
447
448        $processEntity = new Process();
449        $processEntity->id = $thinnedProcess->processId;
450        $processEntity->authKey = $thinnedProcess->authKey ?? null;
451        $processEntity->customTextfield = $thinnedProcess->customTextfield ?? null;
452        $processEntity->customTextfield2 = $thinnedProcess->customTextfield2 ?? null;
453        $processEntity->captchaToken = $thinnedProcess->captchaToken ?? null;
454
455        $client = new Client();
456        $client->familyName = $thinnedProcess->familyName ?? null;
457        $client->email = $thinnedProcess->email ?? null;
458        $client->telephone = $thinnedProcess->telephone ?? null;
459        $processEntity->clients = [$client];
460
461        $appointment = new Appointment();
462        $appointment->slotCount = $thinnedProcess->slotCount ?? null;
463        $appointment->date = $thinnedProcess->timestamp ?? null;
464        $processEntity->appointments = [$appointment];
465        $processEntity->scope = self::createScope($thinnedProcess);
466        $processEntity->requests = self::createRequests($thinnedProcess);
467
468        if (isset($thinnedProcess->status)) {
469            $processEntity->queue = new \stdClass();
470            $processEntity->queue->status = $thinnedProcess->status;
471            $processEntity->status = $thinnedProcess->status;
472        }
473
474        if (isset($thinnedProcess->displayNumber)) {
475            $processEntity->displayNumber = $thinnedProcess->displayNumber;
476        }
477
478        $processEntity->lastChange = time();
479        $processEntity->createIP = ClientIpHelper::getClientIp();
480        $processEntity->createTimestamp = time();
481        return $processEntity;
482    }
483
484    private static function createScope(ThinnedProcess $thinnedProcess): Scope
485    {
486        $scope = new Scope();
487        if ($thinnedProcess->scope) {
488            $providerSource = $thinnedProcess->scope->provider->source ?? 'dldb';
489
490            $scope->id = $thinnedProcess->scope->id;
491            $scope->source = $providerSource;
492
493            $scope->preferences = [
494                'client' => [
495                    'appointmentsPerMail' => $thinnedProcess->scope->getAppointmentsPerMail() ?? null,
496                    'slotsPerAppointment' => $thinnedProcess->scope->getSlotsPerAppointment() ?? null,
497                    "whitelistedMails" => $thinnedProcess->scope->getWhitelistedMails() ?? null,
498                    'emailFrom' => $thinnedProcess->scope->getEmailFrom() ?? null,
499                    'emailRequired' => $thinnedProcess->scope->getEmailRequired() ?? false,
500                    'telephoneActivated' => $thinnedProcess->scope->getTelephoneActivated() ?? false,
501                    'telephoneRequired' => $thinnedProcess->scope->getTelephoneRequired() ?? false,
502                    'customTextfieldActivated' => $thinnedProcess->scope->getCustomTextfieldActivated() ?? false,
503                    'customTextfieldRequired' => $thinnedProcess->scope->getCustomTextfieldRequired() ?? false,
504                    'customTextfieldLabel' => $thinnedProcess->scope->getCustomTextfieldLabel() ?? null,
505                    'customTextfield2Activated' => $thinnedProcess->scope->getCustomTextfield2Activated() ?? false,
506                    'customTextfield2Required' => $thinnedProcess->scope->getCustomTextfield2Required() ?? false,
507                    'customTextfield2Label' => $thinnedProcess->scope->getCustomTextfield2Label() ?? null
508                ],
509                'notifications' => [
510                    'enabled' => true
511                ]
512            ];
513        }
514        if (isset($thinnedProcess->officeName)) {
515            $scope->contact = new Contact();
516            $scope->contact->name = $thinnedProcess->officeName;
517        }
518        if (isset($thinnedProcess->officeId)) {
519            $scope->provider = new Provider();
520            $scope->provider->id = $thinnedProcess->officeId;
521            if (isset($thinnedProcess->scope->provider)) {
522                $provider = $thinnedProcess->scope->provider;
523                $scope->provider->name  = $provider->name ?? null;
524                $scope->provider->displayName = $provider->displayName ?? null;
525
526                if (isset($provider->contact)) {
527                    $scope->provider->contact = new Contact();
528                    $scope->provider->contact->street = $provider->contact->street ?? null;
529                    $scope->provider->contact->streetNumber = $provider->contact->streetNumber ?? null;
530                }
531            }
532
533            $scope->provider->source = $thinnedProcess->scope->provider->source ?? null;
534        }
535
536        return $scope;
537    }
538
539    private static function createRequests(ThinnedProcess $thinnedProcess): array
540    {
541        $providerSource = $thinnedProcess->scope->provider->source ?? 'dldb';
542
543        $requests = [];
544        $mainServiceId = $thinnedProcess->serviceId ?? null;
545        $mainServiceName = $thinnedProcess->serviceName ?? null;
546        $mainServiceCount = $thinnedProcess->serviceCount ?? 0;
547
548        for ($i = 0; $i < $mainServiceCount; $i++) {
549            $request = new Request();
550            $request->id = $mainServiceId;
551            $request->name = $mainServiceName;
552            $request->source = $providerSource;
553            $requests[] = $request;
554        }
555
556        foreach ($thinnedProcess->subRequestCounts ?? [] as $subRequest) {
557            $subId = $subRequest['id'] ?? null;
558            $subName = $subRequest['name'] ?? null;
559            $count = (int)($subRequest['count'] ?? 0);
560
561            for ($i = 0; $i < $count; $i++) {
562                $request = new Request();
563                $request->id = $subId;
564                $request->name = $subName;
565                $request->source = $providerSource;
566                $requests[] = $request;
567            }
568        }
569
570        return $requests;
571    }
572
573    /**
574     * Converts a raw or existing contact object/array into a ThinnedContact model.
575     *
576     * @param object|array $contact
577     * @return ThinnedContact
578     */
579    public static function contactToThinnedContact($contact): ThinnedContact
580    {
581        if (is_array($contact)) {
582            return new ThinnedContact(
583                city: $contact['city'] ?? null,
584                country: $contact['country'] ?? null,
585                name: $contact['name'] ?? null,
586                postalCode: isset($contact['postalCode']) ? (is_null($contact['postalCode']) ? null : (string)$contact['postalCode']) : null,
587                region: $contact['region'] ?? null,
588                street: $contact['street'] ?? null,
589                streetNumber: $contact['streetNumber'] ?? null
590            );
591        }
592
593        return new ThinnedContact(
594            city: $contact->city ?? null,
595            country: $contact->country ?? null,
596            name: $contact->name ?? null,
597            postalCode: isset($contact->postalCode) ? (is_null($contact->postalCode) ? null : (string)$contact->postalCode) : null,
598            region: $contact->region ?? null,
599            street: $contact->street ?? null,
600            streetNumber: $contact->streetNumber ?? null
601        );
602    }
603
604    /**
605     * Convert a Provider object to a ThinnedProvider.
606     *
607     * @param Provider $provider
608     * @return ThinnedProvider
609     */
610    public static function providerToThinnedProvider(Provider $provider): ThinnedProvider
611    {
612        return new ThinnedProvider(
613            id: isset($provider->id) ? (int) $provider->id : null,
614            name: isset($provider->name) ? $provider->name : null,
615            displayName: isset($provider->displayName) ? $provider->displayName : null,
616            source: isset($provider->source) ? $provider->source : null,
617            lon: isset($provider->data['geo']['lon']) ? (float) $provider->data['geo']['lon'] : null,
618            lat: isset($provider->data['geo']['lat']) ? (float) $provider->data['geo']['lat'] : null,
619            contact: isset($provider->contact) ? self::contactToThinnedContact($provider->contact) : null
620        );
621    }
622
623    /**
624     * Generate ICS content for a process if it has appointments with time.
625     *
626     * @param Process $process The process to generate ICS content for
627     * @return string|null The ICS content or null if generation fails or not applicable
628     */
629    private static function generateIcsContent(Process $process): ?string
630    {
631        if (!isset($process->appointments[0]) || !$process->appointments[0]->hasTime()) {
632            return null;
633        }
634
635        $content = ZmsApiClientService::getIcsContent((int)($process->id ?? 0), (string)($process->authKey ?? ''));
636        return $content ?: null;
637    }
638}