PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / 1.2.20
Booking for Appointments and Events Calendar – Amelia v1.2.20
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
627 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
127
128 /** Events */
129 if (in_array(Entities::EVENTS, $params['types'], true)) {
130 /** @var EventApplicationService $eventAS */
131 $eventAS = $this->container->get('application.booking.event.service');
132
133 /** @var Collection $events */
134 $events = $eventAS->getEventsByCriteria(
135 [
136 'dates' => [DateTimeService::getNowDateTime()],
137 'page' => 1,
138 ],
139 [
140 'fetchEventsPeriods' => true,
141 ],
142 1000
143 );
144
145 $resultData['events'] = $eventDS->getShortcodeForEventList($this->container, $events->toArray());
146 }
147
148 /** Event Tags */
149 if (in_array(Entities::TAGS, $params['types'], true)) {
150 /** @var EventTagsRepository $eventTagsRepository */
151 $eventTagsRepository = $this->container->get('domain.booking.event.tag.repository');
152
153 /** @var Collection $eventsTags */
154 $eventsTags = $eventTagsRepository->getAllDistinctByCriteria(
155 $events->length() ? ['eventIds' => array_column($events->toArray(), 'id')] : []
156 );
157
158 $resultData['tags'] = $eventsTags->toArray();
159 }
160
161 if (in_array(Entities::LOCATIONS, $params['types'], true) ||
162 in_array(Entities::EMPLOYEES, $params['types'], true)
163 ) {
164 /** @var Collection $locations */
165 $locations = $locationAS->getAllOrderedByName();
166 }
167
168 /** Locations */
169 if (in_array(Entities::LOCATIONS, $params['types'], true)) {
170 $resultData['locations'] = $locations->toArray();
171 }
172
173 if (in_array(Entities::CATEGORIES, $params['types'], true) ||
174 in_array(Entities::EMPLOYEES, $params['types'], true) ||
175 in_array(Entities::COUPONS, $params['types'], true)
176 ) {
177 /** @var ServiceRepository $serviceRepository */
178 $serviceRepository = $this->container->get('domain.bookable.service.repository');
179 /** @var CategoryRepository $categoryRepository */
180 $categoryRepository = $this->container->get('domain.bookable.category.repository');
181 /** @var BookableApplicationService $bookableAS */
182 $bookableAS = $this->container->get('application.bookable.service');
183
184 /** @var Collection $allServices */
185 $allServices = $serviceRepository->getAllArrayIndexedById();
186
187 /** @var Service $service */
188 foreach ($allServices->getItems() as $service) {
189 if ($service->getStatus()->getValue() === Status::VISIBLE ||
190 Licence::$premium ||
191 ($currentUser && $currentUser->getType() === AbstractUser::USER_ROLE_ADMIN)
192 ) {
193 $services->addItem($service, $service->getId()->getValue());
194 }
195 }
196
197 /** @var Collection $categories */
198 $categories = $categoryRepository->getAllIndexedById();
199
200 $bookableAS->addServicesToCategories($categories, $services);
201 }
202
203 /** Categories */
204 if (in_array(Entities::CATEGORIES, $params['types'], true)) {
205 $resultData['categories'] = $categories->toArray();
206 }
207
208 /** @var SettingsService $settingsDS */
209 $settingsDS = $this->container->get('domain.settings.service');
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 );
320
321 if (isset($params['page']) && $params['page'] !== Entities::CALENDAR) {
322 unset(
323 $employee['weekDayList'],
324 $employee['specialDayList'],
325 $employee['dayOffList']
326 );
327 }
328 }
329 }
330 }
331
332 $resultData[Entities::APPOINTMENTS] = [
333 'futureAppointments' => [],
334 ];
335
336 if (in_array(Entities::APPOINTMENTS, $params['types'], true)) {
337 $userParams = [
338 'dates' => [null, null]
339 ];
340
341 if (!$command->getPermissionService()->currentUserCanReadOthers(Entities::APPOINTMENTS)) {
342 if ($currentUser->getId() === null) {
343 $userParams[$currentUser->getType() . 'Id'] = 0;
344 } else {
345 $userParams[$currentUser->getType() . 'Id'] =
346 $currentUser->getId()->getValue();
347 }
348 }
349
350 /** @var AppointmentRepository $appointmentRepo */
351 $appointmentRepo = $this->container->get('domain.booking.appointment.repository');
352
353 /** @var Collection $appointments */
354 $appointments = $appointmentRepo->getFiltered($userParams);
355
356 $resultData[Entities::APPOINTMENTS] = [
357 'futureAppointments' => $appointments->toArray(),
358 ];
359 }
360
361 /** Custom Fields */
362 if (in_array(Entities::CUSTOM_FIELDS, $params['types'], true) ||
363 in_array('customFields', $params['types'], true)
364 ) {
365 /** @var Collection $customFields */
366 $customFields = $customFieldAS->getAll();
367
368 if (!empty($params['lite'])) {
369 $resultData['customFields'] = [];
370
371 /** @var CustomField $customField */
372 foreach ($customFields->getItems() as $customField) {
373 $item = array_merge(
374 $customField->toArray(),
375 [
376 'services' => [],
377 'events' => [],
378 ]
379 );
380
381 /** @var Service $service */
382 foreach ($customField->getServices()->getItems() as $service) {
383 $item['services'][] = [
384 'id' => $service->getId()->getValue()
385 ];
386 }
387
388 /** @var Event $event */
389 foreach ($customField->getEvents()->getItems() as $event) {
390 $item['events'][] = [
391 'id' => $event->getId()->getValue()
392 ];
393 }
394
395 $resultData['customFields'][] = $item;
396 }
397 } else {
398 $resultData['customFields'] = $customFields->toArray();
399 }
400 }
401
402 /** Coupons */
403 if (in_array(Entities::COUPONS, $params['types'], true) &&
404 $this->getContainer()->getPermissionsService()->currentUserCanRead(Entities::COUPONS)
405 ) {
406 /** @var Collection $coupons */
407 $coupons = $couponAS->getAll();
408
409 /** @var CouponRepository $couponRepository */
410 $couponRepository = $this->container->get('domain.coupon.repository');
411
412 /** @var EventRepository $eventRepository */
413 $eventRepository = $this->container->get('domain.booking.event.repository');
414
415 /** @var PackageRepository $packageRepository */
416 $packageRepository = $this->container->get('domain.bookable.package.repository');
417
418 if ($coupons->length()) {
419 foreach ($couponRepository->getCouponsServicesIds($coupons->keys()) as $ids) {
420 /** @var Coupon $coupon */
421 $coupon = $coupons->getItem($ids['couponId']);
422
423 if ($coupon->getAllServices() && $coupon->getAllServices()->getValue()) {
424 $coupon->setServiceList(new Collection($allServices->getItems()));
425 continue;
426 }
427
428 $coupon->getServiceList()->addItem(
429 $allServices->getItem($ids['serviceId']),
430 $ids['serviceId']
431 );
432 }
433
434 /** @var Collection $allEvents */
435 $allEvents = $eventRepository->getAllIndexedById();
436
437 foreach ($couponRepository->getCouponsEventsIds($coupons->keys()) as $ids) {
438 /** @var Coupon $coupon */
439 $coupon = $coupons->getItem($ids['couponId']);
440
441 if ($coupon->getAllEvents() && $coupon->getAllEvents()->getValue()) {
442 $coupon->setEventList(new Collection($allEvents->getItems()));
443 continue;
444 }
445
446 $coupon->getEventList()->addItem(
447 $allEvents->getItem($ids['eventId']),
448 $ids['eventId']
449 );
450 }
451
452 /** @var Collection $allPackages */
453 $allPackages = $packageRepository->getAllIndexedById();
454
455 foreach ($couponRepository->getCouponsPackagesIds($coupons->keys()) as $ids) {
456 /** @var Coupon $coupon */
457 $coupon = $coupons->getItem($ids['couponId']);
458
459 if ($coupon->getAllPackages() && $coupon->getAllPackages()->getValue()) {
460 $coupon->setPackageList(new Collection($allPackages->getItems()));
461 continue;
462 }
463
464 $coupon->getPackageList()->addItem(
465 $allPackages->getItem($ids['packageId']),
466 $ids['packageId']
467 );
468 }
469 }
470
471 if (!empty($params['lite'])) {
472 $resultData['coupons'] = [];
473
474 /** @var Coupon $coupon */
475 foreach ($coupons->getItems() as $coupon) {
476 $item = array_merge(
477 $coupon->toArray(),
478 [
479 'serviceList' => [],
480 'eventList' => [],
481 'packageList' => [],
482 ]
483 );
484
485 /** @var Service $service */
486 foreach ($coupon->getServiceList()->getItems() as $service) {
487 $item['serviceList'][] = [
488 'id' => $service->getId()->getValue()
489 ];
490 }
491
492 /** @var Event $event */
493 foreach ($coupon->getEventList()->getItems() as $event) {
494 $item['eventList'][] = [
495 'id' => $event->getId()->getValue()
496 ];
497 }
498
499 /** @var Package $package */
500 foreach ($coupon->getPackageList()->getItems() as $package) {
501 $item['packageList'][] = [
502 'id' => $package->getId()->getValue()
503 ];
504 }
505
506 $resultData['coupons'][] = $item;
507 }
508 } else {
509 $resultData['coupons'] = $coupons->toArray();
510 }
511 }
512
513 /** Settings */
514 if (in_array(Entities::SETTINGS, $params['types'], true)) {
515 /** @var HelperService $helperService */
516 $helperService = $this->container->get('application.helper.service');
517
518 $languages = $helperService->getLanguages();
519
520 usort(
521 $languages,
522 function ($x, $y) {
523 return strcasecmp($x['name'], $y['name']);
524 }
525 );
526
527 $languagesSorted = [];
528
529 foreach ($languages as $language) {
530 $languagesSorted[$language['wp_locale']] = $language;
531 }
532
533 /** @var \AmeliaBooking\Application\Services\Settings\SettingsService $settingsAS*/
534 $settingsAS = $this->container->get('application.settings.service');
535
536 $daysOff = $settingsAS->getDaysOff();
537
538 $squareLocations = [];
539 if (!empty($settingsDS->getSetting('payments', 'square')['accessToken']['access_token'])
540 && in_array('squareLocations', $params['types'])) {
541 /** @var SquareService $squareService */
542 $squareService = $this->container->get('infrastructure.payment.square.service');
543
544 try {
545 $squareLocations = $squareService->getLocations();
546 } catch (\Exception $e) {
547 }
548 }
549
550 $resultData['settings'] = [
551 'general' => [
552 'usedLanguages' => $settingsDS->getSetting('general', 'usedLanguages'),
553 ],
554 'languages' => $languagesSorted,
555 'daysOff' => $daysOff,
556 'squareLocations' => $squareLocations
557 ];
558 }
559
560 /** Packages */
561 if (in_array(Entities::PACKAGES, $params['types'], true)) {
562 /** @var AbstractPackageApplicationService $packageApplicationService */
563 $packageApplicationService = $this->container->get('application.bookable.package');
564
565 $resultData['packages'] = $packageApplicationService->getPackagesArray();
566 }
567
568 /** Resources */
569 if (in_array(Entities::RESOURCES, $params['types'], true)) {
570 /** @var AbstractResourceApplicationService $resourceApplicationService */
571 $resourceApplicationService = $this->container->get('application.resource.service');
572
573 /** @var Collection $resources */
574 $resources = $resourceApplicationService->getAll([]);
575
576 $resultData['resources'] = $resources->toArray();
577 }
578
579 /** Taxes */
580 if (in_array(Entities::TAXES, $params['types'], true)) {
581 /** @var TaxApplicationService $taxApplicationService */
582 $taxApplicationService = $this->container->get('application.tax.service');
583
584 /** @var Collection $taxes */
585 $taxes = $taxApplicationService->getAll();
586
587 $resultData['taxes'] = $taxes->toArray();
588 }
589
590 /** Lesson Spaces */
591 if (in_array('lessonSpace_spaces', $params['types'], true) ||
592 in_array('spaces', $params['types'], true)
593 ) {
594 $lessonSpaceApiKey = $settingsDS->getSetting('lessonSpace', 'apiKey');
595 $lessonSpaceEnabled = $settingsDS->getSetting('lessonSpace', 'enabled');
596 $lessonSpaceCompanyId = $settingsDS->getSetting('lessonSpace', 'companyId');
597
598 if ($lessonSpaceEnabled && $lessonSpaceApiKey) {
599 /** @var AbstractLessonSpaceService $lessonSpaceService */
600 $lessonSpaceService = $this->container->get('infrastructure.lesson.space.service');
601
602 if (empty($lessonSpaceCompanyId)) {
603 $companyDetails = $lessonSpaceService->getCompanyId($lessonSpaceApiKey);
604 $lessonSpaceCompanyId = !empty($companyDetails) && !empty($companyDetails['id']) ? $companyDetails['id'] : null;
605 }
606
607 $resultData['spaces'] = $lessonSpaceService->getAllSpaces(
608 $lessonSpaceApiKey,
609 $lessonSpaceCompanyId,
610 !empty($params['lessonSpaceSearch']) ? $params['lessonSpaceSearch'] : null
611 );
612 }
613 }
614
615
616 $resultData = apply_filters('amelia_get_entities_filter', $resultData);
617
618 do_action('amelia_get_entities', $resultData);
619
620 $result->setResult(CommandResult::RESULT_SUCCESS);
621 $result->setMessage('Successfully retrieved entities');
622 $result->setData($resultData);
623
624 return $result;
625 }
626 }
627