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