PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / 1.2.25
Booking for Appointments and Events Calendar – Amelia v1.2.25
2.4.9 2.4.8 2.4.7 2.4.6 2.4.5 2.4.4 2.4.3 2.4.2 2.4.1 2.4 trunk 1.2.1 1.2.10 1.2.11 1.2.12 1.2.13 1.2.14 1.2.15 1.2.16 1.2.17 1.2.18 1.2.19 1.2.2 1.2.20 1.2.21 1.2.22 1.2.23 1.2.24 1.2.25 1.2.26 1.2.27 1.2.28 1.2.29 1.2.3 1.2.30 1.2.31 1.2.32 1.2.33 1.2.34 1.2.35 1.2.36 1.2.37 1.2.38 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 2.0 2.0.1 2.0.2 2.1 2.1.1 2.1.2 2.1.3 2.2 2.2.1 2.3
ameliabooking / src / Application / Commands / Entities / GetEntitiesCommandHandler.php
ameliabooking / src / Application / Commands / Entities Last commit date
GetEntitiesCommand.php 7 years ago GetEntitiesCommandHandler.php 1 year ago
GetEntitiesCommandHandler.php
628 lines
1 <?php
2
3 namespace AmeliaBooking\Application\Commands\Entities;
4
5 use AmeliaBooking\Application\Commands\CommandHandler;
6 use AmeliaBooking\Application\Commands\CommandResult;
7 use AmeliaBooking\Application\Common\Exceptions\AccessDeniedException;
8 use AmeliaBooking\Application\Services\Bookable\BookableApplicationService;
9 use AmeliaBooking\Application\Services\Bookable\AbstractPackageApplicationService;
10 use AmeliaBooking\Application\Services\Booking\EventApplicationService;
11 use AmeliaBooking\Application\Services\Coupon\AbstractCouponApplicationService;
12 use AmeliaBooking\Application\Services\CustomField\AbstractCustomFieldApplicationService;
13 use AmeliaBooking\Application\Services\Helper\HelperService;
14 use AmeliaBooking\Application\Services\Location\AbstractLocationApplicationService;
15 use AmeliaBooking\Application\Services\Resource\AbstractResourceApplicationService;
16 use AmeliaBooking\Application\Services\Tax\TaxApplicationService;
17 use AmeliaBooking\Application\Services\User\ProviderApplicationService;
18 use AmeliaBooking\Application\Services\User\UserApplicationService;
19 use AmeliaBooking\Domain\Collection\Collection;
20 use AmeliaBooking\Domain\Common\Exceptions\AuthorizationException;
21 use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
22 use AmeliaBooking\Domain\Entity\Bookable\Service\Service;
23 use AmeliaBooking\Domain\Entity\Booking\Event\Event;
24 use AmeliaBooking\Domain\Entity\Coupon\Coupon;
25 use AmeliaBooking\Domain\Entity\Entities;
26 use AmeliaBooking\Domain\Entity\User\AbstractUser;
27 use AmeliaBooking\Domain\Entity\User\Customer;
28 use AmeliaBooking\Domain\Entity\User\Provider;
29 use AmeliaBooking\Domain\Services\Booking\EventDomainService;
30 use AmeliaBooking\Domain\Services\DateTime\DateTimeService;
31 use AmeliaBooking\Domain\Services\Settings\SettingsService;
32 use AmeliaBooking\Domain\Services\User\ProviderService;
33 use AmeliaBooking\Domain\ValueObjects\String\Status;
34 use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException;
35 use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException;
36 use AmeliaBooking\Infrastructure\Licence\Licence as Licence;
37 use AmeliaBooking\Infrastructure\Repository\Bookable\Service\CategoryRepository;
38 use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageRepository;
39 use AmeliaBooking\Infrastructure\Repository\Bookable\Service\ServiceRepository;
40 use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\AppointmentRepository;
41 use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\CustomerBookingRepository;
42 use AmeliaBooking\Infrastructure\Repository\Booking\Event\EventRepository;
43 use AmeliaBooking\Infrastructure\Repository\Booking\Event\EventTagsRepository;
44 use AmeliaBooking\Infrastructure\Repository\Coupon\CouponRepository;
45 use AmeliaBooking\Infrastructure\Repository\User\ProviderRepository;
46 use AmeliaBooking\Infrastructure\Repository\User\UserRepository;
47 use AmeliaBooking\Infrastructure\Services\LessonSpace\AbstractLessonSpaceService;
48 use AmeliaBooking\Infrastructure\Services\Payment\SquareService;
49 use Interop\Container\Exception\ContainerException;
50
51 /**
52 * Class GetEntitiesCommandHandler
53 *
54 * @package AmeliaBooking\Application\Commands\Entities
55 */
56 class GetEntitiesCommandHandler extends CommandHandler
57 {
58 /**
59 * @param GetEntitiesCommand $command
60 *
61 * @return CommandResult
62 * @throws AccessDeniedException
63 * @throws ContainerException
64 * @throws InvalidArgumentException
65 * @throws NotFoundException
66 * @throws QueryExecutionException
67 */
68 public function handle(GetEntitiesCommand $command)
69 {
70 /** @var UserApplicationService $userAS */
71 $userAS = $this->container->get('application.user.service');
72
73 /** @var EventDomainService $eventDS */
74 $eventDS = $this->container->get('domain.booking.event.service');
75
76 /** @var ProviderApplicationService $providerAS */
77 $providerAS = $this->container->get('application.user.provider.service');
78
79 /** @var AbstractCustomFieldApplicationService $customFieldAS */
80 $customFieldAS = $this->container->get('application.customField.service');
81
82 /** @var AbstractLocationApplicationService $locationAS */
83 $locationAS = $this->container->get('application.location.service');
84
85 /** @var AbstractCouponApplicationService $couponAS */
86 $couponAS = $this->container->get('application.coupon.service');
87
88 /** @var ProviderService $providerService */
89 $providerService = $this->container->get('domain.user.provider.service');
90
91 try {
92 /** @var AbstractUser $currentUser */
93 $currentUser = $command->getUserApplicationService()->authorization(
94 $command->getPage() === 'cabinet' ? $command->getToken() : null,
95 $command->getCabinetType()
96 );
97 } catch (AuthorizationException $e) {
98 $currentUser = null;
99 }
100
101 $params = $command->getField('params');
102
103 $params['types'] = !empty($params['types']) ? $params['types'] : [];
104
105 $result = new CommandResult();
106
107 $this->checkMandatoryFields($command);
108
109 /** @var Collection $allServices */
110 $allServices = new Collection();
111
112 /** @var Collection $services */
113 $services = new Collection();
114
115 /** @var Collection $locations */
116 $locations = new Collection();
117
118 /** @var Collection $categories */
119 $categories = new Collection();
120
121 /** @var Collection $events */
122 $events = new Collection();
123
124 $resultData = [];
125
126 /** @var SettingsService $settingsDS */
127 $settingsDS = $this->container->get('domain.settings.service');
128
129
130 /** Events */
131 if (in_array(Entities::EVENTS, $params['types'], true)) {
132 /** @var EventApplicationService $eventAS */
133 $eventAS = $this->container->get('application.booking.event.service');
134
135 /** @var Collection $events */
136 $events = $eventAS->getEventsByCriteria(
137 [
138 'dates' => [DateTimeService::getNowDateTime()],
139 'page' => 1,
140 ],
141 [
142 'fetchEventsPeriods' => true,
143 ],
144 $settingsDS->getSetting('general', 'eventsFilterLimit') ?: 1000
145 );
146
147 $resultData['events'] = $eventDS->getShortcodeForEventList($this->container, $events->toArray());
148 }
149
150 /** Event Tags */
151 if (in_array(Entities::TAGS, $params['types'], true)) {
152 /** @var EventTagsRepository $eventTagsRepository */
153 $eventTagsRepository = $this->container->get('domain.booking.event.tag.repository');
154
155 /** @var Collection $eventsTags */
156 $eventsTags = $eventTagsRepository->getAllDistinctByCriteria(
157 $events->length() ? ['eventIds' => array_column($events->toArray(), 'id')] : []
158 );
159
160 $resultData['tags'] = $eventsTags->toArray();
161 }
162
163 if (in_array(Entities::LOCATIONS, $params['types'], true) ||
164 in_array(Entities::EMPLOYEES, $params['types'], true)
165 ) {
166 /** @var Collection $locations */
167 $locations = $locationAS->getAllOrderedByName();
168 }
169
170 /** Locations */
171 if (in_array(Entities::LOCATIONS, $params['types'], true)) {
172 $resultData['locations'] = $locations->toArray();
173 }
174
175 if (in_array(Entities::CATEGORIES, $params['types'], true) ||
176 in_array(Entities::EMPLOYEES, $params['types'], true) ||
177 in_array(Entities::COUPONS, $params['types'], true)
178 ) {
179 /** @var ServiceRepository $serviceRepository */
180 $serviceRepository = $this->container->get('domain.bookable.service.repository');
181 /** @var CategoryRepository $categoryRepository */
182 $categoryRepository = $this->container->get('domain.bookable.category.repository');
183 /** @var BookableApplicationService $bookableAS */
184 $bookableAS = $this->container->get('application.bookable.service');
185
186 /** @var Collection $allServices */
187 $allServices = $serviceRepository->getAllArrayIndexedById();
188
189 /** @var Service $service */
190 foreach ($allServices->getItems() as $service) {
191 if ($service->getStatus()->getValue() === Status::VISIBLE ||
192 Licence::$premium ||
193 ($currentUser && $currentUser->getType() === AbstractUser::USER_ROLE_ADMIN)
194 ) {
195 $services->addItem($service, $service->getId()->getValue());
196 }
197 }
198
199 /** @var Collection $categories */
200 $categories = $categoryRepository->getAllIndexedById();
201
202 $bookableAS->addServicesToCategories($categories, $services);
203 }
204
205 /** Categories */
206 if (in_array(Entities::CATEGORIES, $params['types'], true)) {
207 $resultData['categories'] = $categories->toArray();
208 }
209
210
211 $resultData['customers'] = [];
212
213 /** Customers */
214 if (in_array(Entities::CUSTOMERS, $params['types'], true)) {
215 /** @var UserRepository $userRepo */
216 $userRepo = $this->getContainer()->get('domain.users.repository');
217
218 $resultData['customers'] = [];
219
220 if ($currentUser) {
221 switch ($currentUser->getType()) {
222 case (AbstractUser::USER_ROLE_CUSTOMER):
223 if ($currentUser->getId()) {
224 /** @var Customer $customer */
225 $customer = $userRepo->getById($currentUser->getId()->getValue());
226
227 $resultData['customers'] = [$customer->toArray()];
228 }
229
230 break;
231
232 case (AbstractUser::USER_ROLE_PROVIDER):
233 $resultData['customers'] = $providerAS->getAllowedCustomers($currentUser)->toArray();
234
235 break;
236
237 default:
238 /** @var Collection $customers */
239 $customers = $userRepo->getAllWithAllowedBooking();
240
241 $resultData['customers'] = $customers->toArray();
242 }
243 }
244
245 $noShowTagEnabled = $settingsDS->getSetting('roles', 'enableNoShowTag');
246
247 if ($noShowTagEnabled && $resultData['customers']) {
248 /** @var CustomerBookingRepository $bookingRepository */
249 $bookingRepository = $this->container->get('domain.booking.customerBooking.repository');
250
251 $usersIds = array_map(function ($user) { return $user['id']; }, $resultData['customers']);
252
253 $customersNoShowCount = $bookingRepository->countByNoShowStatus($usersIds);
254
255 foreach ($resultData['customers'] as $key => $customer) {
256 $resultData['customers'][$key]['noShowCount'] = $customersNoShowCount[$key]['count'];
257 }
258 }
259 }
260
261 /** Providers */
262 if (in_array(Entities::EMPLOYEES, $params['types'], true)) {
263 /** @var ProviderRepository $providerRepository */
264 $providerRepository = $this->container->get('domain.users.providers.repository');
265
266 /** @var Collection $testProviders */
267 $providers = $providerRepository->getWithSchedule(
268 [
269 'dates' => [
270 DateTimeService::getNowDateTimeObject()->modify('-1 days')->format('Y-m-d H:i:s')
271 ],
272 'fetchCalendars' => $currentUser && $currentUser->getType() === AbstractUser::USER_ROLE_ADMIN,
273 ]
274 );
275
276 /** @var Provider $provider */
277 foreach ($providers->getItems() as $provider) {
278 $providerService->setProviderServices($provider, $services, true);
279 }
280
281 if (array_key_exists('page', $params) &&
282 in_array($params['page'], [Entities::CALENDAR, Entities::APPOINTMENTS]) &&
283 $userAS->isAdminAndAllowedToBookAtAnyTime()
284 ) {
285 $providerService->setProvidersAlwaysAvailable($providers);
286 }
287
288 $resultData['entitiesRelations'] = [];
289
290 /** @var Provider $provider */
291 foreach ($providers->getItems() as $providerId => $provider) {
292 if ($data = $providerAS->getProviderServiceLocations($provider, $locations, $services)) {
293 $resultData['entitiesRelations'][$providerId] = $data;
294 }
295 }
296
297
298 $resultData['employees'] = $providerAS->removeAllExceptUser(
299 $providers->toArray(),
300 (array_key_exists('page', $params) && $params['page'] === Entities::BOOKING) ?
301 null : $currentUser
302 );
303
304 if ($currentUser === null ||
305 $currentUser->getType() === AbstractUser::USER_ROLE_CUSTOMER ||
306 !$command->getPermissionService()->currentUserCanRead(Entities::EMPLOYEES)
307 ) {
308 foreach ($resultData['employees'] as &$employee) {
309 unset(
310 $employee['appleCalendarId'],
311 $employee['googleCalendar'],
312 $employee['outlookCalendar'],
313 $employee['stripeConnect'],
314 $employee['birthday'],
315 $employee['email'],
316 $employee['externalId'],
317 $employee['phone'],
318 $employee['note'],
319 $employee['employeeAppleCalendar'],
320 );
321
322 if (isset($params['page']) && $params['page'] !== Entities::CALENDAR) {
323 unset(
324 $employee['weekDayList'],
325 $employee['specialDayList'],
326 $employee['dayOffList']
327 );
328 }
329 }
330 }
331 }
332
333 $resultData[Entities::APPOINTMENTS] = [
334 'futureAppointments' => [],
335 ];
336
337 if (in_array(Entities::APPOINTMENTS, $params['types'], true)) {
338 $userParams = [
339 'dates' => [null, null]
340 ];
341
342 if (!$command->getPermissionService()->currentUserCanReadOthers(Entities::APPOINTMENTS)) {
343 if ($currentUser->getId() === null) {
344 $userParams[$currentUser->getType() . 'Id'] = 0;
345 } else {
346 $userParams[$currentUser->getType() . 'Id'] =
347 $currentUser->getId()->getValue();
348 }
349 }
350
351 /** @var AppointmentRepository $appointmentRepo */
352 $appointmentRepo = $this->container->get('domain.booking.appointment.repository');
353
354 /** @var Collection $appointments */
355 $appointments = $appointmentRepo->getFiltered($userParams);
356
357 $resultData[Entities::APPOINTMENTS] = [
358 'futureAppointments' => $appointments->toArray(),
359 ];
360 }
361
362 /** Custom Fields */
363 if (in_array(Entities::CUSTOM_FIELDS, $params['types'], true) ||
364 in_array('customFields', $params['types'], true)
365 ) {
366 /** @var Collection $customFields */
367 $customFields = $customFieldAS->getAll();
368
369 if (!empty($params['lite'])) {
370 $resultData['customFields'] = [];
371
372 /** @var CustomField $customField */
373 foreach ($customFields->getItems() as $customField) {
374 $item = array_merge(
375 $customField->toArray(),
376 [
377 'services' => [],
378 'events' => [],
379 ]
380 );
381
382 /** @var Service $service */
383 foreach ($customField->getServices()->getItems() as $service) {
384 $item['services'][] = [
385 'id' => $service->getId()->getValue()
386 ];
387 }
388
389 /** @var Event $event */
390 foreach ($customField->getEvents()->getItems() as $event) {
391 $item['events'][] = [
392 'id' => $event->getId()->getValue()
393 ];
394 }
395
396 $resultData['customFields'][] = $item;
397 }
398 } else {
399 $resultData['customFields'] = $customFields->toArray();
400 }
401 }
402
403 /** Coupons */
404 if (in_array(Entities::COUPONS, $params['types'], true) &&
405 $this->getContainer()->getPermissionsService()->currentUserCanRead(Entities::COUPONS)
406 ) {
407 /** @var Collection $coupons */
408 $coupons = $couponAS->getAll();
409
410 /** @var CouponRepository $couponRepository */
411 $couponRepository = $this->container->get('domain.coupon.repository');
412
413 /** @var EventRepository $eventRepository */
414 $eventRepository = $this->container->get('domain.booking.event.repository');
415
416 /** @var PackageRepository $packageRepository */
417 $packageRepository = $this->container->get('domain.bookable.package.repository');
418
419 if ($coupons->length()) {
420 foreach ($couponRepository->getCouponsServicesIds($coupons->keys()) as $ids) {
421 /** @var Coupon $coupon */
422 $coupon = $coupons->getItem($ids['couponId']);
423
424 if ($coupon->getAllServices() && $coupon->getAllServices()->getValue()) {
425 $coupon->setServiceList(new Collection($allServices->getItems()));
426 continue;
427 }
428
429 $coupon->getServiceList()->addItem(
430 $allServices->getItem($ids['serviceId']),
431 $ids['serviceId']
432 );
433 }
434
435 /** @var Collection $allEvents */
436 $allEvents = $eventRepository->getAllIndexedById();
437
438 foreach ($couponRepository->getCouponsEventsIds($coupons->keys()) as $ids) {
439 /** @var Coupon $coupon */
440 $coupon = $coupons->getItem($ids['couponId']);
441
442 if ($coupon->getAllEvents() && $coupon->getAllEvents()->getValue()) {
443 $coupon->setEventList(new Collection($allEvents->getItems()));
444 continue;
445 }
446
447 $coupon->getEventList()->addItem(
448 $allEvents->getItem($ids['eventId']),
449 $ids['eventId']
450 );
451 }
452
453 /** @var Collection $allPackages */
454 $allPackages = $packageRepository->getAllIndexedById();
455
456 foreach ($couponRepository->getCouponsPackagesIds($coupons->keys()) as $ids) {
457 /** @var Coupon $coupon */
458 $coupon = $coupons->getItem($ids['couponId']);
459
460 if ($coupon->getAllPackages() && $coupon->getAllPackages()->getValue()) {
461 $coupon->setPackageList(new Collection($allPackages->getItems()));
462 continue;
463 }
464
465 $coupon->getPackageList()->addItem(
466 $allPackages->getItem($ids['packageId']),
467 $ids['packageId']
468 );
469 }
470 }
471
472 if (!empty($params['lite'])) {
473 $resultData['coupons'] = [];
474
475 /** @var Coupon $coupon */
476 foreach ($coupons->getItems() as $coupon) {
477 $item = array_merge(
478 $coupon->toArray(),
479 [
480 'serviceList' => [],
481 'eventList' => [],
482 'packageList' => [],
483 ]
484 );
485
486 /** @var Service $service */
487 foreach ($coupon->getServiceList()->getItems() as $service) {
488 $item['serviceList'][] = [
489 'id' => $service->getId()->getValue()
490 ];
491 }
492
493 /** @var Event $event */
494 foreach ($coupon->getEventList()->getItems() as $event) {
495 $item['eventList'][] = [
496 'id' => $event->getId()->getValue()
497 ];
498 }
499
500 /** @var Package $package */
501 foreach ($coupon->getPackageList()->getItems() as $package) {
502 $item['packageList'][] = [
503 'id' => $package->getId()->getValue()
504 ];
505 }
506
507 $resultData['coupons'][] = $item;
508 }
509 } else {
510 $resultData['coupons'] = $coupons->toArray();
511 }
512 }
513
514 /** Settings */
515 if (in_array(Entities::SETTINGS, $params['types'], true)) {
516 /** @var HelperService $helperService */
517 $helperService = $this->container->get('application.helper.service');
518
519 $languages = $helperService->getLanguages();
520
521 usort(
522 $languages,
523 function ($x, $y) {
524 return strcasecmp($x['name'], $y['name']);
525 }
526 );
527
528 $languagesSorted = [];
529
530 foreach ($languages as $language) {
531 $languagesSorted[$language['wp_locale']] = $language;
532 }
533
534 /** @var \AmeliaBooking\Application\Services\Settings\SettingsService $settingsAS*/
535 $settingsAS = $this->container->get('application.settings.service');
536
537 $daysOff = $settingsAS->getDaysOff();
538
539 $squareLocations = [];
540 if (!empty($settingsDS->getSetting('payments', 'square')['accessToken']['access_token'])
541 && in_array('squareLocations', $params['types'])) {
542 /** @var SquareService $squareService */
543 $squareService = $this->container->get('infrastructure.payment.square.service');
544
545 try {
546 $squareLocations = $squareService->getLocations();
547 } catch (\Exception $e) {
548 }
549 }
550
551 $resultData['settings'] = [
552 'general' => [
553 'usedLanguages' => $settingsDS->getSetting('general', 'usedLanguages'),
554 ],
555 'languages' => $languagesSorted,
556 'daysOff' => $daysOff,
557 'squareLocations' => $squareLocations
558 ];
559 }
560
561 /** Packages */
562 if (in_array(Entities::PACKAGES, $params['types'], true)) {
563 /** @var AbstractPackageApplicationService $packageApplicationService */
564 $packageApplicationService = $this->container->get('application.bookable.package');
565
566 $resultData['packages'] = $packageApplicationService->getPackagesArray();
567 }
568
569 /** Resources */
570 if (in_array(Entities::RESOURCES, $params['types'], true)) {
571 /** @var AbstractResourceApplicationService $resourceApplicationService */
572 $resourceApplicationService = $this->container->get('application.resource.service');
573
574 /** @var Collection $resources */
575 $resources = $resourceApplicationService->getAll([]);
576
577 $resultData['resources'] = $resources->toArray();
578 }
579
580 /** Taxes */
581 if (in_array(Entities::TAXES, $params['types'], true)) {
582 /** @var TaxApplicationService $taxApplicationService */
583 $taxApplicationService = $this->container->get('application.tax.service');
584
585 /** @var Collection $taxes */
586 $taxes = $taxApplicationService->getAll();
587
588 $resultData['taxes'] = $taxes->toArray();
589 }
590
591 /** Lesson Spaces */
592 if (in_array('lessonSpace_spaces', $params['types'], true) ||
593 in_array('spaces', $params['types'], true)
594 ) {
595 $lessonSpaceApiKey = $settingsDS->getSetting('lessonSpace', 'apiKey');
596 $lessonSpaceEnabled = $settingsDS->getSetting('lessonSpace', 'enabled');
597 $lessonSpaceCompanyId = $settingsDS->getSetting('lessonSpace', 'companyId');
598
599 if ($lessonSpaceEnabled && $lessonSpaceApiKey) {
600 /** @var AbstractLessonSpaceService $lessonSpaceService */
601 $lessonSpaceService = $this->container->get('infrastructure.lesson.space.service');
602
603 if (empty($lessonSpaceCompanyId)) {
604 $companyDetails = $lessonSpaceService->getCompanyId($lessonSpaceApiKey);
605 $lessonSpaceCompanyId = !empty($companyDetails) && !empty($companyDetails['id']) ? $companyDetails['id'] : null;
606 }
607
608 $resultData['spaces'] = $lessonSpaceService->getAllSpaces(
609 $lessonSpaceApiKey,
610 $lessonSpaceCompanyId,
611 !empty($params['lessonSpaceSearch']) ? $params['lessonSpaceSearch'] : null
612 );
613 }
614 }
615
616
617 $resultData = apply_filters('amelia_get_entities_filter', $resultData);
618
619 do_action('amelia_get_entities', $resultData);
620
621 $result->setResult(CommandResult::RESULT_SUCCESS);
622 $result->setMessage('Successfully retrieved entities');
623 $result->setData($resultData);
624
625 return $result;
626 }
627 }
628