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