PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / 1.2.21
Booking for Appointments and Events Calendar – Amelia v1.2.21
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
625 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 /** Events */
127 if (in_array(Entities::EVENTS, $params['types'], true)) {
128 /** @var EventApplicationService $eventAS */
129 $eventAS = $this->container->get('application.booking.event.service');
130
131 /** @var Collection $events */
132 $events = $eventAS->getEventsByCriteria(
133 [
134 'dates' => [DateTimeService::getNowDateTime()],
135 'page' => 1,
136 ],
137 [
138 'fetchEventsPeriods' => true,
139 ],
140 1000
141 );
142
143 $resultData['events'] = $eventDS->getShortcodeForEventList($this->container, $events->toArray());
144 }
145
146 /** Event Tags */
147 if (in_array(Entities::TAGS, $params['types'], true)) {
148 /** @var EventTagsRepository $eventTagsRepository */
149 $eventTagsRepository = $this->container->get('domain.booking.event.tag.repository');
150
151 /** @var Collection $eventsTags */
152 $eventsTags = $eventTagsRepository->getAllDistinctByCriteria(
153 $events->length() ? ['eventIds' => array_column($events->toArray(), 'id')] : []
154 );
155
156 $resultData['tags'] = $eventsTags->toArray();
157 }
158
159 if (in_array(Entities::LOCATIONS, $params['types'], true) ||
160 in_array(Entities::EMPLOYEES, $params['types'], true)
161 ) {
162 /** @var Collection $locations */
163 $locations = $locationAS->getAllOrderedByName();
164 }
165
166 /** Locations */
167 if (in_array(Entities::LOCATIONS, $params['types'], true)) {
168 $resultData['locations'] = $locations->toArray();
169 }
170
171 if (in_array(Entities::CATEGORIES, $params['types'], true) ||
172 in_array(Entities::EMPLOYEES, $params['types'], true) ||
173 in_array(Entities::COUPONS, $params['types'], true)
174 ) {
175 /** @var ServiceRepository $serviceRepository */
176 $serviceRepository = $this->container->get('domain.bookable.service.repository');
177 /** @var CategoryRepository $categoryRepository */
178 $categoryRepository = $this->container->get('domain.bookable.category.repository');
179 /** @var BookableApplicationService $bookableAS */
180 $bookableAS = $this->container->get('application.bookable.service');
181
182 /** @var Collection $allServices */
183 $allServices = $serviceRepository->getAllArrayIndexedById();
184
185 /** @var Service $service */
186 foreach ($allServices->getItems() as $service) {
187 if ($service->getStatus()->getValue() === Status::VISIBLE ||
188 Licence::$premium ||
189 ($currentUser && $currentUser->getType() === AbstractUser::USER_ROLE_ADMIN)
190 ) {
191 $services->addItem($service, $service->getId()->getValue());
192 }
193 }
194
195 /** @var Collection $categories */
196 $categories = $categoryRepository->getAllIndexedById();
197
198 $bookableAS->addServicesToCategories($categories, $services);
199 }
200
201 /** Categories */
202 if (in_array(Entities::CATEGORIES, $params['types'], true)) {
203 $resultData['categories'] = $categories->toArray();
204 }
205
206 /** @var SettingsService $settingsDS */
207 $settingsDS = $this->container->get('domain.settings.service');
208
209 $resultData['customers'] = [];
210
211 /** Customers */
212 if (in_array(Entities::CUSTOMERS, $params['types'], true)) {
213 /** @var UserRepository $userRepo */
214 $userRepo = $this->getContainer()->get('domain.users.repository');
215
216 $resultData['customers'] = [];
217
218 if ($currentUser) {
219 switch ($currentUser->getType()) {
220 case (AbstractUser::USER_ROLE_CUSTOMER):
221 if ($currentUser->getId()) {
222 /** @var Customer $customer */
223 $customer = $userRepo->getById($currentUser->getId()->getValue());
224
225 $resultData['customers'] = [$customer->toArray()];
226 }
227
228 break;
229
230 case (AbstractUser::USER_ROLE_PROVIDER):
231 $resultData['customers'] = $providerAS->getAllowedCustomers($currentUser)->toArray();
232
233 break;
234
235 default:
236 /** @var Collection $customers */
237 $customers = $userRepo->getAllWithAllowedBooking();
238
239 $resultData['customers'] = $customers->toArray();
240 }
241 }
242
243 $noShowTagEnabled = $settingsDS->getSetting('roles', 'enableNoShowTag');
244
245 if ($noShowTagEnabled && $resultData['customers']) {
246 /** @var CustomerBookingRepository $bookingRepository */
247 $bookingRepository = $this->container->get('domain.booking.customerBooking.repository');
248
249 $usersIds = array_map(function ($user) { return $user['id']; }, $resultData['customers']);
250
251 $customersNoShowCount = $bookingRepository->countByNoShowStatus($usersIds);
252
253 foreach ($resultData['customers'] as $key => $customer) {
254 $resultData['customers'][$key]['noShowCount'] = $customersNoShowCount[$key]['count'];
255 }
256 }
257 }
258
259 /** Providers */
260 if (in_array(Entities::EMPLOYEES, $params['types'], true)) {
261 /** @var ProviderRepository $providerRepository */
262 $providerRepository = $this->container->get('domain.users.providers.repository');
263
264 /** @var Collection $testProviders */
265 $providers = $providerRepository->getWithSchedule(
266 [
267 'dates' => [
268 DateTimeService::getNowDateTimeObject()->modify('-1 days')->format('Y-m-d H:i:s')
269 ],
270 'fetchCalendars' => $currentUser && $currentUser->getType() === AbstractUser::USER_ROLE_ADMIN,
271 ]
272 );
273
274 /** @var Provider $provider */
275 foreach ($providers->getItems() as $provider) {
276 $providerService->setProviderServices($provider, $services, true);
277 }
278
279 if (array_key_exists('page', $params) &&
280 in_array($params['page'], [Entities::CALENDAR, Entities::APPOINTMENTS]) &&
281 $userAS->isAdminAndAllowedToBookAtAnyTime()
282 ) {
283 $providerService->setProvidersAlwaysAvailable($providers);
284 }
285
286 $resultData['entitiesRelations'] = [];
287
288 /** @var Provider $provider */
289 foreach ($providers->getItems() as $providerId => $provider) {
290 if ($data = $providerAS->getProviderServiceLocations($provider, $locations, $services)) {
291 $resultData['entitiesRelations'][$providerId] = $data;
292 }
293 }
294
295
296 $resultData['employees'] = $providerAS->removeAllExceptUser(
297 $providers->toArray(),
298 (array_key_exists('page', $params) && $params['page'] === Entities::BOOKING) ?
299 null : $currentUser
300 );
301
302 if ($currentUser === null ||
303 $currentUser->getType() === AbstractUser::USER_ROLE_CUSTOMER ||
304 !$command->getPermissionService()->currentUserCanRead(Entities::EMPLOYEES)
305 ) {
306 foreach ($resultData['employees'] as &$employee) {
307 unset(
308 $employee['appleCalendarId'],
309 $employee['googleCalendar'],
310 $employee['outlookCalendar'],
311 $employee['stripeConnect'],
312 $employee['birthday'],
313 $employee['email'],
314 $employee['externalId'],
315 $employee['phone'],
316 $employee['note']
317 );
318
319 if (isset($params['page']) && $params['page'] !== Entities::CALENDAR) {
320 unset(
321 $employee['weekDayList'],
322 $employee['specialDayList'],
323 $employee['dayOffList']
324 );
325 }
326 }
327 }
328 }
329
330 $resultData[Entities::APPOINTMENTS] = [
331 'futureAppointments' => [],
332 ];
333
334 if (in_array(Entities::APPOINTMENTS, $params['types'], true)) {
335 $userParams = [
336 'dates' => [null, null]
337 ];
338
339 if (!$command->getPermissionService()->currentUserCanReadOthers(Entities::APPOINTMENTS)) {
340 if ($currentUser->getId() === null) {
341 $userParams[$currentUser->getType() . 'Id'] = 0;
342 } else {
343 $userParams[$currentUser->getType() . 'Id'] =
344 $currentUser->getId()->getValue();
345 }
346 }
347
348 /** @var AppointmentRepository $appointmentRepo */
349 $appointmentRepo = $this->container->get('domain.booking.appointment.repository');
350
351 /** @var Collection $appointments */
352 $appointments = $appointmentRepo->getFiltered($userParams);
353
354 $resultData[Entities::APPOINTMENTS] = [
355 'futureAppointments' => $appointments->toArray(),
356 ];
357 }
358
359 /** Custom Fields */
360 if (in_array(Entities::CUSTOM_FIELDS, $params['types'], true) ||
361 in_array('customFields', $params['types'], true)
362 ) {
363 /** @var Collection $customFields */
364 $customFields = $customFieldAS->getAll();
365
366 if (!empty($params['lite'])) {
367 $resultData['customFields'] = [];
368
369 /** @var CustomField $customField */
370 foreach ($customFields->getItems() as $customField) {
371 $item = array_merge(
372 $customField->toArray(),
373 [
374 'services' => [],
375 'events' => [],
376 ]
377 );
378
379 /** @var Service $service */
380 foreach ($customField->getServices()->getItems() as $service) {
381 $item['services'][] = [
382 'id' => $service->getId()->getValue()
383 ];
384 }
385
386 /** @var Event $event */
387 foreach ($customField->getEvents()->getItems() as $event) {
388 $item['events'][] = [
389 'id' => $event->getId()->getValue()
390 ];
391 }
392
393 $resultData['customFields'][] = $item;
394 }
395 } else {
396 $resultData['customFields'] = $customFields->toArray();
397 }
398 }
399
400 /** Coupons */
401 if (in_array(Entities::COUPONS, $params['types'], true) &&
402 $this->getContainer()->getPermissionsService()->currentUserCanRead(Entities::COUPONS)
403 ) {
404 /** @var Collection $coupons */
405 $coupons = $couponAS->getAll();
406
407 /** @var CouponRepository $couponRepository */
408 $couponRepository = $this->container->get('domain.coupon.repository');
409
410 /** @var EventRepository $eventRepository */
411 $eventRepository = $this->container->get('domain.booking.event.repository');
412
413 /** @var PackageRepository $packageRepository */
414 $packageRepository = $this->container->get('domain.bookable.package.repository');
415
416 if ($coupons->length()) {
417 foreach ($couponRepository->getCouponsServicesIds($coupons->keys()) as $ids) {
418 /** @var Coupon $coupon */
419 $coupon = $coupons->getItem($ids['couponId']);
420
421 if ($coupon->getAllServices() && $coupon->getAllServices()->getValue()) {
422 $coupon->setServiceList(new Collection($allServices->getItems()));
423 continue;
424 }
425
426 $coupon->getServiceList()->addItem(
427 $allServices->getItem($ids['serviceId']),
428 $ids['serviceId']
429 );
430 }
431
432 /** @var Collection $allEvents */
433 $allEvents = $eventRepository->getAllIndexedById();
434
435 foreach ($couponRepository->getCouponsEventsIds($coupons->keys()) as $ids) {
436 /** @var Coupon $coupon */
437 $coupon = $coupons->getItem($ids['couponId']);
438
439 if ($coupon->getAllEvents() && $coupon->getAllEvents()->getValue()) {
440 $coupon->setEventList(new Collection($allEvents->getItems()));
441 continue;
442 }
443
444 $coupon->getEventList()->addItem(
445 $allEvents->getItem($ids['eventId']),
446 $ids['eventId']
447 );
448 }
449
450 /** @var Collection $allPackages */
451 $allPackages = $packageRepository->getAllIndexedById();
452
453 foreach ($couponRepository->getCouponsPackagesIds($coupons->keys()) as $ids) {
454 /** @var Coupon $coupon */
455 $coupon = $coupons->getItem($ids['couponId']);
456
457 if ($coupon->getAllPackages() && $coupon->getAllPackages()->getValue()) {
458 $coupon->setPackageList(new Collection($allPackages->getItems()));
459 continue;
460 }
461
462 $coupon->getPackageList()->addItem(
463 $allPackages->getItem($ids['packageId']),
464 $ids['packageId']
465 );
466 }
467 }
468
469 if (!empty($params['lite'])) {
470 $resultData['coupons'] = [];
471
472 /** @var Coupon $coupon */
473 foreach ($coupons->getItems() as $coupon) {
474 $item = array_merge(
475 $coupon->toArray(),
476 [
477 'serviceList' => [],
478 'eventList' => [],
479 'packageList' => [],
480 ]
481 );
482
483 /** @var Service $service */
484 foreach ($coupon->getServiceList()->getItems() as $service) {
485 $item['serviceList'][] = [
486 'id' => $service->getId()->getValue()
487 ];
488 }
489
490 /** @var Event $event */
491 foreach ($coupon->getEventList()->getItems() as $event) {
492 $item['eventList'][] = [
493 'id' => $event->getId()->getValue()
494 ];
495 }
496
497 /** @var Package $package */
498 foreach ($coupon->getPackageList()->getItems() as $package) {
499 $item['packageList'][] = [
500 'id' => $package->getId()->getValue()
501 ];
502 }
503
504 $resultData['coupons'][] = $item;
505 }
506 } else {
507 $resultData['coupons'] = $coupons->toArray();
508 }
509 }
510
511 /** Settings */
512 if (in_array(Entities::SETTINGS, $params['types'], true)) {
513 /** @var HelperService $helperService */
514 $helperService = $this->container->get('application.helper.service');
515
516 $languages = $helperService->getLanguages();
517
518 usort(
519 $languages,
520 function ($x, $y) {
521 return strcasecmp($x['name'], $y['name']);
522 }
523 );
524
525 $languagesSorted = [];
526
527 foreach ($languages as $language) {
528 $languagesSorted[$language['wp_locale']] = $language;
529 }
530
531 /** @var \AmeliaBooking\Application\Services\Settings\SettingsService $settingsAS*/
532 $settingsAS = $this->container->get('application.settings.service');
533
534 $daysOff = $settingsAS->getDaysOff();
535
536 $squareLocations = [];
537 if (!empty($settingsDS->getSetting('payments', 'square')['accessToken']['access_token'])
538 && in_array('squareLocations', $params['types'])) {
539 /** @var SquareService $squareService */
540 $squareService = $this->container->get('infrastructure.payment.square.service');
541
542 try {
543 $squareLocations = $squareService->getLocations();
544 } catch (\Exception $e) {
545 }
546 }
547
548 $resultData['settings'] = [
549 'general' => [
550 'usedLanguages' => $settingsDS->getSetting('general', 'usedLanguages'),
551 ],
552 'languages' => $languagesSorted,
553 'daysOff' => $daysOff,
554 'squareLocations' => $squareLocations
555 ];
556 }
557
558 /** Packages */
559 if (in_array(Entities::PACKAGES, $params['types'], true)) {
560 /** @var AbstractPackageApplicationService $packageApplicationService */
561 $packageApplicationService = $this->container->get('application.bookable.package');
562
563 $resultData['packages'] = $packageApplicationService->getPackagesArray();
564 }
565
566 /** Resources */
567 if (in_array(Entities::RESOURCES, $params['types'], true)) {
568 /** @var AbstractResourceApplicationService $resourceApplicationService */
569 $resourceApplicationService = $this->container->get('application.resource.service');
570
571 /** @var Collection $resources */
572 $resources = $resourceApplicationService->getAll([]);
573
574 $resultData['resources'] = $resources->toArray();
575 }
576
577 /** Taxes */
578 if (in_array(Entities::TAXES, $params['types'], true)) {
579 /** @var TaxApplicationService $taxApplicationService */
580 $taxApplicationService = $this->container->get('application.tax.service');
581
582 /** @var Collection $taxes */
583 $taxes = $taxApplicationService->getAll();
584
585 $resultData['taxes'] = $taxes->toArray();
586 }
587
588 /** Lesson Spaces */
589 if (in_array('lessonSpace_spaces', $params['types'], true) ||
590 in_array('spaces', $params['types'], true)
591 ) {
592 $lessonSpaceApiKey = $settingsDS->getSetting('lessonSpace', 'apiKey');
593 $lessonSpaceEnabled = $settingsDS->getSetting('lessonSpace', 'enabled');
594 $lessonSpaceCompanyId = $settingsDS->getSetting('lessonSpace', 'companyId');
595
596 if ($lessonSpaceEnabled && $lessonSpaceApiKey) {
597 /** @var AbstractLessonSpaceService $lessonSpaceService */
598 $lessonSpaceService = $this->container->get('infrastructure.lesson.space.service');
599
600 if (empty($lessonSpaceCompanyId)) {
601 $companyDetails = $lessonSpaceService->getCompanyId($lessonSpaceApiKey);
602 $lessonSpaceCompanyId = !empty($companyDetails) && !empty($companyDetails['id']) ? $companyDetails['id'] : null;
603 }
604
605 $resultData['spaces'] = $lessonSpaceService->getAllSpaces(
606 $lessonSpaceApiKey,
607 $lessonSpaceCompanyId,
608 !empty($params['lessonSpaceSearch']) ? $params['lessonSpaceSearch'] : null
609 );
610 }
611 }
612
613
614 $resultData = apply_filters('amelia_get_entities_filter', $resultData);
615
616 do_action('amelia_get_entities', $resultData);
617
618 $result->setResult(CommandResult::RESULT_SUCCESS);
619 $result->setMessage('Successfully retrieved entities');
620 $result->setData($resultData);
621
622 return $result;
623 }
624 }
625