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