PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / trunk
Booking for Appointments and Events Calendar – Amelia vtrunk
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 / Booking / Appointment / GetAppointmentsCommandHandler.php
ameliabooking / src / Application / Commands / Booking / Appointment Last commit date
AddAppointmentCommand.php 1 year ago AddAppointmentCommandHandler.php 2 months ago AddBookingCommand.php 1 year ago AddBookingCommandHandler.php 1 year ago ApproveBookingRemotelyCommand.php 1 year ago ApproveBookingRemotelyCommandHandler.php 2 months ago CancelBookingCommand.php 1 year ago CancelBookingCommandHandler.php 6 months ago CancelBookingRemotelyCommand.php 1 year ago CancelBookingRemotelyCommandHandler.php 1 month ago DeleteAppointmentCommand.php 1 year ago DeleteAppointmentCommandHandler.php 1 year ago DeleteBookingCommand.php 1 year ago DeleteBookingCommandHandler.php 10 months ago DeleteBookingRemotelyCommand.php 10 months ago DeleteBookingRemotelyCommandHandler.php 6 months ago GetAppointmentBookingsCommand.php 6 months ago GetAppointmentBookingsCommandHandler.php 2 months ago GetAppointmentCommand.php 7 years ago GetAppointmentCommandHandler.php 2 weeks ago GetAppointmentsCommand.php 1 year ago GetAppointmentsCommandHandler.php 2 weeks ago GetIcsCommand.php 6 months ago GetIcsCommandHandler.php 4 years ago GetTimeSlotsCommand.php 1 year ago GetTimeSlotsCommandHandler.php 1 month ago ReassignBookingCommand.php 1 year ago ReassignBookingCommandHandler.php 3 months ago RejectBookingRemotelyCommand.php 1 year ago RejectBookingRemotelyCommandHandler.php 4 months ago SuccessfulBookingCommand.php 1 year ago SuccessfulBookingCommandHandler.php 1 year ago UpdateAppointmentCommand.php 1 year ago UpdateAppointmentCommandHandler.php 3 months ago UpdateAppointmentNoteCommand.php 3 months ago UpdateAppointmentNoteCommandHandler.php 3 months ago UpdateAppointmentStatusCommand.php 1 year ago UpdateAppointmentStatusCommandHandler.php 2 months ago UpdateAppointmentTimeCommand.php 1 year ago UpdateAppointmentTimeCommandHandler.php 1 month ago UpdateBookingStatusCommand.php 1 year ago UpdateBookingStatusCommandHandler.php 5 months ago
GetAppointmentsCommandHandler.php
482 lines
1 <?php
2
3 namespace AmeliaBooking\Application\Commands\Booking\Appointment;
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\AbstractPackageApplicationService;
9 use AmeliaBooking\Application\Services\Booking\AppointmentApplicationService;
10 use AmeliaBooking\Application\Services\Booking\BookingApplicationService;
11 use AmeliaBooking\Application\Services\Helper\HelperService;
12 use AmeliaBooking\Application\Services\User\ProviderApplicationService;
13 use AmeliaBooking\Application\Services\User\UserApplicationService;
14 use AmeliaBooking\Domain\Collection\Collection;
15 use AmeliaBooking\Domain\Common\Exceptions\AuthorizationException;
16 use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
17 use AmeliaBooking\Domain\Entity\Bookable\Service\Service;
18 use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment;
19 use AmeliaBooking\Domain\Entity\Booking\Appointment\CustomerBooking;
20 use AmeliaBooking\Domain\Entity\Entities;
21 use AmeliaBooking\Domain\Entity\User\AbstractUser;
22 use AmeliaBooking\Domain\Services\DateTime\DateTimeService;
23 use AmeliaBooking\Domain\Services\Settings\SettingsService;
24 use AmeliaBooking\Domain\ValueObjects\String\BookingStatus;
25 use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException;
26 use AmeliaBooking\Infrastructure\Repository\Bookable\Service\ServiceRepository;
27 use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\AppointmentRepository;
28 use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\CustomerBookingRepository;
29 use DateTimeZone;
30 use Interop\Container\Exception\ContainerException;
31
32 /**
33 * Class GetAppointmentsCommandHandler
34 *
35 * @package AmeliaBooking\Application\Commands\Booking\Appointment
36 */
37 class GetAppointmentsCommandHandler extends CommandHandler
38 {
39 /**
40 * @param GetAppointmentsCommand $command
41 *
42 * @return CommandResult
43 *
44 * @throws InvalidArgumentException
45 * @throws QueryExecutionException
46 * @throws AccessDeniedException
47 * @throws ContainerException
48 */
49 public function handle(GetAppointmentsCommand $command)
50 {
51 $result = new CommandResult();
52
53 /** @var HelperService $helperService */
54 $helperService = $this->container->get('application.helper.service');
55
56 /** @var AppointmentRepository $appointmentRepository */
57 $appointmentRepository = $this->container->get('domain.booking.appointment.repository');
58
59 /** @var ServiceRepository $serviceRepository */
60 $serviceRepository = $this->container->get('domain.bookable.service.repository');
61
62 /** @var AbstractPackageApplicationService $packageAS */
63 $packageAS = $this->container->get('application.bookable.package');
64
65 /** @var SettingsService $settingsDS */
66 $settingsDS = $this->container->get('domain.settings.service');
67
68 /** @var UserApplicationService $userAS */
69 $userAS = $this->container->get('application.user.service');
70
71 /** @var BookingApplicationService $bookingAS */
72 $bookingAS = $this->container->get('application.booking.booking.service');
73
74 /** @var AppointmentApplicationService $appointmentAS */
75 $appointmentAS = $this->container->get('application.booking.appointment.service');
76
77 /** @var ProviderApplicationService $providerAS */
78 $providerAS = $this->container->get('application.user.provider.service');
79
80 $params = $command->getField('params');
81
82 $isCabinetPage = $command->getPage() === 'cabinet';
83
84 $isCalendarPage = $command->getPage() === 'calendar';
85
86 $isCabinetPackageRequest = $isCabinetPage && isset($params['activePackages']);
87
88 $isDashboardPackageRequest = !$isCabinetPage && (isset($params['packageId']) || !empty($params['packageBookings']));
89
90 try {
91 /** @var AbstractUser $user */
92 $user = $command->getUserApplicationService()->authorization($isCabinetPage ? $command->getToken() : null, $command->getCabinetType());
93 } catch (AuthorizationException $e) {
94 $result->setResult(CommandResult::RESULT_ERROR);
95 $result->setData(
96 [
97 'reauthorize' => true
98 ]
99 );
100
101 return $result;
102 }
103
104 $readOthers = $this->container->getPermissionsService()->currentUserCanReadOthers(Entities::APPOINTMENTS);
105
106 $providerCountParams = [];
107 if (
108 (!$readOthers) &&
109 $user && $user->getType() === Entities::PROVIDER
110 ) {
111 $providerCountParams['providerId'] = $user->getId()->getValue();
112 }
113
114 // TODO: Redesign - replace 'customerId' parameter with 'customers' on all /appointments calls and remove this part
115 if (!empty($params['customerId'])) {
116 $params['customers'] = $params['customerId'];
117 }
118
119 $customerCountParams = [];
120 if ($user && $user->getType() === Entities::CUSTOMER) {
121 $customerCountParams['customers'] = [$user->getId()->getValue()];
122 $params['customers'] = [$user->getId()->getValue()];
123 }
124
125 $helperService->convertDates($params);
126
127 $entitiesIds = !empty($params['search']) && !$isCabinetPackageRequest ?
128 $appointmentAS->getAppointmentEntitiesIdsBySearchString($params['search']) : [];
129
130
131 $countParams = $params;
132
133 $appointmentsIds = [];
134
135 if (
136 !empty($params['search']) &&
137 !$entitiesIds['customers'] &&
138 !$entitiesIds['services'] &&
139 !$entitiesIds['providers']
140 ) {
141 $result->setResult(CommandResult::RESULT_SUCCESS);
142 $result->setMessage('Successfully retrieved appointments');
143 $result->setData(
144 [
145 Entities::APPOINTMENTS => [],
146 'availablePackageBookings' => [],
147 'occupied' => [],
148 'total' => 0,
149 'totalApproved' => 0,
150 'totalPending' => 0,
151 'totalCount' => $appointmentRepository->getPeriodAppointmentsCount(array_merge($providerCountParams, $customerCountParams)),
152 'filteredCount' => 0,
153 ]
154 );
155
156 return $result;
157 }
158
159 $availablePackageBookings = [];
160
161 if (!$isCabinetPackageRequest && !$isDashboardPackageRequest) {
162 /** @var Collection $periodAppointments */
163 $periodAppointments = $appointmentRepository->getPeriodAppointments(
164 array_merge(
165 [
166 'customers' => $isCabinetPage && $user->getType() === Entities::CUSTOMER ?
167 [$user->getId()->getValue()] : [],
168 'providers' => $user && $user->getType() === Entities::PROVIDER ?
169 [$user->getId()->getValue()] : [],
170 ],
171 array_merge($params, ['endsInDateRange' => $isCalendarPage]),
172 $entitiesIds,
173 ['skipBookings' => !$isCabinetPage && empty($params['customers']) && empty($entitiesIds['customers'])]
174 ),
175 !empty($params['limit'])
176 ? max(1, min((int) $params['limit'], 500))
177 : $settingsDS->getSetting('general', 'itemsPerPage')
178 );
179
180 /** @var Appointment $appointment */
181 foreach ($periodAppointments->getItems() as $appointment) {
182 $appointmentsIds[] = $appointment->getId()->getValue();
183 }
184 }
185
186 /** @var Collection $appointments */
187 $appointments = new Collection();
188
189 $customersNoShowCountIds = [];
190
191 $noShowTagEnabled = $settingsDS->isFeatureEnabled('noShowTag');
192
193 if (!$isCabinetPackageRequest && $appointmentsIds) {
194 $appointments = $appointmentRepository->getFiltered(
195 [
196 'ids' => $appointmentsIds,
197 'skipServices' => isset($params['skipServices']) ? $params['skipServices'] : false,
198 'skipProviders' => isset($params['skipProviders']) ? $params['skipProviders'] : false,
199 'joinPackages' => $isCabinetPage
200 ]
201 );
202 } elseif ($isDashboardPackageRequest || ($user && $user->getId() && $isCabinetPackageRequest)) {
203 $availablePackageBookings = $packageAS->getPackageAvailability(
204 $appointments,
205 [
206 'purchased' => !empty($params['dates']) ? $params['dates'] : [],
207 'customers' => $isCabinetPackageRequest ? [$user->getId()->getValue()] : (!empty($params['customers']) ? $params['customers'] : null),
208 'packageId' => !$isCabinetPackageRequest && !empty($params['packageId']) ?
209 (int)$params['packageId'] : null,
210 ]
211 );
212
213 if ($noShowTagEnabled && !!$availablePackageBookings) {
214 $customersNoShowCountIds[] = $availablePackageBookings[0]['customerId'];
215 }
216 }
217
218 /** @var Collection $services */
219 $services = $serviceRepository->getAllArrayIndexedById();
220
221 if (!$isCabinetPage) {
222 $packageAS->setPackageBookingsForAppointments($appointments);
223 }
224
225 $occupiedTimes = [];
226
227 $currentDateTime = DateTimeService::getNowDateTimeObject();
228
229 $groupedAppointments = [];
230
231 /** @var Appointment $appointment */
232 foreach ($appointments->getItems() as $appointment) {
233 /** @var Service $service */
234 $service = $services->getItem($appointment->getServiceId()->getValue());
235
236 $bookingsCount = 0;
237
238 /** @var CustomerBooking $booking */
239 foreach ($appointment->getBookings()->getItems() as $booking) {
240 // fix for wrongly saved JSON
241 if (
242 $booking->getCustomFields() &&
243 json_decode($booking->getCustomFields()->getValue(), true) === null
244 ) {
245 $booking->setCustomFields(null);
246 }
247
248 if ($bookingAS->isBookingApprovedOrPending($booking->getStatus()->getValue())) {
249 $bookingsCount++;
250 }
251
252 if ($noShowTagEnabled && !in_array($booking->getCustomerId()->getValue(), $customersNoShowCountIds)) {
253 $customersNoShowCountIds[] = $booking->getCustomerId()->getValue();
254 }
255 }
256
257 $providerId = $appointment->getProviderId()->getValue();
258
259 $isGroup = false;
260
261 // skip appointments/bookings for other customers if user is customer, and remember that time/date values
262 if ($userAS->isCustomer($user)) {
263 /** @var CustomerBooking $booking */
264 foreach ($appointment->getBookings()->getItems() as $bookingKey => $booking) {
265 if (!$user->getId() || $booking->getCustomerId()->getValue() !== $user->getId()->getValue()) {
266 /** @var CustomerBooking $otherBooking */
267 $otherBooking = $appointment->getBookings()->getItem($bookingKey);
268
269 if (
270 $otherBooking->getStatus()->getValue() === BookingStatus::APPROVED ||
271 $otherBooking->getStatus()->getValue() === BookingStatus::PENDING
272 ) {
273 $isGroup = true;
274 }
275
276 $appointment->getBookings()->deleteItem($bookingKey);
277 }
278 }
279
280 if ($appointment->getBookings()->length() === 0) {
281 $serviceTimeBefore = $service->getTimeBefore() ?
282 $service->getTimeBefore()->getValue() : 0;
283
284 $serviceTimeAfter = $service->getTimeAfter() ?
285 $service->getTimeAfter()->getValue() : 0;
286
287 $occupiedTimeStart = DateTimeService::getCustomDateTimeObject(
288 $appointment->getBookingStart()->getValue()->format('Y-m-d H:i:s')
289 )->modify('-' . $serviceTimeBefore . ' second')->format('H:i:s');
290
291 $occupiedTimeEnd = DateTimeService::getCustomDateTimeObject(
292 $appointment->getBookingEnd()->getValue()->format('Y-m-d H:i:s')
293 )->modify('+' . $serviceTimeAfter . ' second')->format('H:i:s');
294
295 $occupiedTimes[$appointment->getBookingStart()->getValue()->format('Y-m-d')][] =
296 [
297 'employeeId' => $providerId,
298 'startTime' => $occupiedTimeStart,
299 'endTime' => $occupiedTimeEnd,
300 ];
301
302 continue;
303 }
304 }
305
306 // skip appointments for other providers if user is provider
307 if (
308 (!$readOthers || $isCabinetPage) &&
309 $user->getType() === Entities::PROVIDER &&
310 $user->getId()->getValue() !== $providerId
311 ) {
312 continue;
313 }
314
315 $appointmentAS->calculateAndSetAppointmentEnd($appointment, $service);
316
317 $minimumCancelTimeInSeconds = $settingsDS
318 ->getEntitySettings($service->getSettings())
319 ->getGeneralSettings()
320 ->getMinimumTimeRequirementPriorToCanceling();
321
322 $minimumCancelTime = DateTimeService::getCustomDateTimeObject(
323 $appointment->getBookingStart()->getValue()->format('Y-m-d H:i:s')
324 )->modify("-{$minimumCancelTimeInSeconds} seconds");
325
326 $date = $appointment->getBookingStart()->getValue()->format('Y-m-d');
327
328 $cancelable = $currentDateTime <= $minimumCancelTime;
329
330 $minimumRescheduleTimeInSeconds = $settingsDS
331 ->getEntitySettings($service->getSettings())
332 ->getGeneralSettings()
333 ->getMinimumTimeRequirementPriorToRescheduling();
334
335 $minimumRescheduleTime = DateTimeService::getCustomDateTimeObject(
336 $appointment->getBookingStart()->getValue()->format('Y-m-d H:i:s')
337 )->modify("-{$minimumRescheduleTimeInSeconds} seconds");
338
339 $reschedulable = $currentDateTime <= $minimumRescheduleTime;
340
341
342 if ($isCabinetPage || ($user && $user->getType() === Entities::PROVIDER)) {
343 $timeZone = !empty($params['timeZone'])
344 ? $params['timeZone']
345 : ($user && $user->getType() === Entities::PROVIDER ? $providerAS->getTimeZone($user) : 'UTC');
346
347 $appointment->getBookingStart()->getValue()->setTimezone(new DateTimeZone($timeZone));
348
349 $appointment->getBookingEnd()->getValue()->setTimezone(new DateTimeZone($timeZone));
350
351 $date = $appointment->getBookingStart()->getValue()->format('Y-m-d');
352
353 foreach ($availablePackageBookings as &$packageCustomerPurchase) {
354 foreach ($packageCustomerPurchase['packages'] as &$packagePurchase) {
355 foreach ($packagePurchase['services'] as &$packageService) {
356 foreach ($packageService['bookings'] as &$purchase) {
357 $purchasedDate = DateTimeService::getCustomDateTimeObjectInTimeZone(
358 $purchase['purchased'],
359 $timeZone
360 );
361
362 $purchase['purchased'] = $purchasedDate->format('Y-m-d H:i');
363 }
364 }
365 }
366 }
367 }
368
369 $groupedAppointments[$date]['date'] = $date;
370
371 $groupedAppointments[$date]['appointments'][] = array_merge(
372 $appointment->toArray(),
373 [
374 'cancelable' => $cancelable,
375 'reschedulable' => $reschedulable,
376 'past' => $currentDateTime >= $appointment->getBookingStart()->getValue(),
377 'isGroup' => $isGroup,
378 ]
379 );
380 }
381
382 $emptyBookedPackages = null;
383
384 if (
385 !empty($params['packageId']) &&
386 empty($params['services']) &&
387 empty($params['providers']) &&
388 empty($params['locations'])
389 ) {
390 /** @var AbstractPackageApplicationService $packageApplicationService */
391 $packageApplicationService = $this->container->get('application.bookable.package');
392
393 /** @var Collection $emptyBookedPackages */
394 $emptyBookedPackages = $packageApplicationService->getEmptyPackages(
395 [
396 'packages' => [$params['packageId']],
397 'purchased' => !empty($params['dates']) ? $params['dates'] : [],
398 'customers' => !empty($params['customers']) ? $params['customers'] : null,
399 ]
400 );
401 }
402
403 $periodsAppointmentsCount = 0;
404
405 $periodsAppointmentsApprovedCount = 0;
406
407 $periodsAppointmentsPendingCount = 0;
408
409 $periodsAppointmentsTotalCount = 0;
410
411 if (!empty($countParams['page']) || (!$isCabinetPackageRequest && !$isCabinetPage && !$isCalendarPage)) {
412 if (
413 (!$readOthers) &&
414 $user->getType() === Entities::PROVIDER
415 ) {
416 $countParams['providerId'] = $user->getId()->getValue();
417 }
418 $periodsAppointmentsCount = $appointmentRepository->getPeriodAppointmentsCount(
419 array_merge($countParams, $providerCountParams, $entitiesIds)
420 );
421
422 $periodsAppointmentsTotalCount = $appointmentRepository->getPeriodAppointmentsCount(array_merge($providerCountParams, $customerCountParams));
423
424 $periodsAppointmentsApprovedCount = $appointmentRepository->getPeriodAppointmentsCount(
425 array_merge(
426 $countParams,
427 $providerCountParams,
428 ['status' => BookingStatus::APPROVED],
429 $entitiesIds
430 )
431 );
432
433 $periodsAppointmentsPendingCount = $appointmentRepository->getPeriodAppointmentsCount(
434 array_merge(
435 $countParams,
436 $providerCountParams,
437 ['status' => BookingStatus::PENDING],
438 $entitiesIds
439 )
440 );
441 }
442
443 $customersNoShowCount = [];
444
445 if ($noShowTagEnabled && $customersNoShowCountIds) {
446 /** @var CustomerBookingRepository $bookingRepository */
447 $bookingRepository = $this->container->get('domain.booking.customerBooking.repository');
448
449 $customersNoShowCount = $bookingRepository->countByNoShowStatus($customersNoShowCountIds);
450 }
451
452 $groupedAppointments = apply_filters('amelia_get_appointments_filter', $groupedAppointments);
453
454 do_action('amelia_get_appointments', $groupedAppointments);
455
456
457 // TODO: Redesign - remove total, totalApproved, totalPending
458 $result->setResult(CommandResult::RESULT_SUCCESS);
459 $result->setMessage('Successfully retrieved appointments');
460 $result->setData(
461 [
462 Entities::APPOINTMENTS =>
463 !empty($params['asArray']) && filter_var($params['asArray'], FILTER_VALIDATE_BOOLEAN) ?
464 $appointments->toArray() :
465 $groupedAppointments,
466 'availablePackageBookings' => $availablePackageBookings,
467 'emptyPackageBookings' => !empty($emptyBookedPackages) ? $emptyBookedPackages->toArray() : [],
468 'occupied' => $occupiedTimes,
469 'total' => $periodsAppointmentsCount,
470 'totalApproved' => $periodsAppointmentsApprovedCount,
471 'totalPending' => $periodsAppointmentsPendingCount,
472 'totalCount' => $periodsAppointmentsTotalCount,
473 'filteredCount' => $periodsAppointmentsCount,
474 'currentUser' => $user ? $user->toArray() : null,
475 'customersNoShowCount' => $customersNoShowCount ? array_values($customersNoShowCount) : []
476 ]
477 );
478
479 return $result;
480 }
481 }
482