PluginProbe ʕ •ᴥ•ʔ
Booking for Appointments and Events Calendar – Amelia / 1.2.13
Booking for Appointments and Events Calendar – Amelia v1.2.13
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 / Infrastructure / Repository / Booking / Event / EventRepository.php
ameliabooking / src / Infrastructure / Repository / Booking / Event Last commit date
CustomerBookingEventPeriodRepository.php 6 years ago CustomerBookingEventTicketRepository.php 1 year ago EventPeriodsRepository.php 4 years ago EventProvidersRepository.php 6 years ago EventRepository.php 1 year ago EventTagsRepository.php 6 years ago EventTicketRepository.php 1 year ago
EventRepository.php
1875 lines
1 <?php
2
3 namespace AmeliaBooking\Infrastructure\Repository\Booking\Event;
4
5 use AmeliaBooking\Domain\Collection\Collection;
6 use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
7 use AmeliaBooking\Domain\Entity\Booking\Event\Event;
8 use AmeliaBooking\Domain\Factory\Booking\Appointment\CustomerBookingFactory;
9 use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory;
10 use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface;
11 use AmeliaBooking\Domain\Services\DateTime\DateTimeService;
12 use AmeliaBooking\Domain\ValueObjects\String\Status;
13 use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException;
14 use AmeliaBooking\Infrastructure\Licence;
15 use AmeliaBooking\Infrastructure\Repository\AbstractRepository;
16 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable;
17 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToEventsPeriodsTable;
18 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingToEventsTicketsTable;
19 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable;
20 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsProvidersTable;
21 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTagsTable;
22 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTicketsTable;
23 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable;
24 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToEventsTable;
25 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery\GalleriesTable;
26 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable;
27 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersGoogleCalendarTable;
28 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersOutlookCalendarTable;
29 use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable;
30
31 /**
32 * Class EventRepository
33 *
34 * @package AmeliaBooking\Infrastructure\Repository\Booking\Event
35 */
36 class EventRepository extends AbstractRepository implements EventRepositoryInterface
37 {
38
39 const FACTORY = EventFactory::class;
40
41 /**
42 * @param Event $entity
43 *
44 * @return bool
45 * @throws QueryExecutionException
46 */
47 public function add($entity)
48 {
49 $data = $entity->toArray();
50
51 $params = [
52 ':bookingOpens' => $data['bookingOpens'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingOpens']) : null,
53 ':bookingCloses' => $data['bookingCloses'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingCloses']) : null,
54 ':bookingOpensRec' => $data['bookingOpensRec'],
55 ':bookingClosesRec' => $data['bookingClosesRec'],
56 ':status' => $data['status'],
57 ':name' => $data['name'],
58 ':description' => $data['description'],
59 ':color' => $data['color'],
60 ':price' => $data['price'],
61 ':bringingAnyone' => $data['bringingAnyone'] ? 1 : 0,
62 ':bookMultipleTimes' => $data['bookMultipleTimes'] ? 1 : 0,
63 ':maxCapacity' => $data['maxCapacity'],
64 ':maxCustomCapacity' => $data['maxCustomCapacity'],
65 ':maxExtraPeople' => $data['maxExtraPeople'],
66 ':show' => $data['show'] ? 1 : 0,
67 ':notifyParticipants' => $data['notifyParticipants'],
68 ':customLocation' => $data['customLocation'],
69 ':parentId' => $data['parentId'],
70 ':created' => $data['created'],
71 ':closeAfterMin' => $data['closeAfterMin'],
72 ':closeAfterMinBookings' => $data['closeAfterMinBookings'] ? 1 : 0,
73 ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0,
74 ':error' => '',
75 ];
76
77 $additionalData = Licence\DataModifier::getEventRepositoryData($data);
78
79 $params = array_merge($params, $additionalData['values'], $additionalData['addValues']);
80
81 try {
82 $statement = $this->connection->prepare(
83 "INSERT INTO {$this->table}
84 (
85 {$additionalData['columns']}
86 `bookingOpens`,
87 `bookingCloses`,
88 `bookingOpensRec`,
89 `bookingClosesRec`,
90 `status`,
91 `name`,
92 `description`,
93 `color`,
94 `price`,
95 `bringingAnyone`,
96 `bookMultipleTimes`,
97 `maxCapacity`,
98 `maxCustomCapacity`,
99 `maxExtraPeople`,
100 `show`,
101 `notifyParticipants`,
102 `customLocation`,
103 `parentId`,
104 `created`,
105 `closeAfterMin`,
106 `closeAfterMinBookings`,
107 `aggregatedPrice`,
108 `error`
109 )
110 VALUES (
111 {$additionalData['placeholders']}
112 :bookingOpens,
113 :bookingCloses,
114 :bookingOpensRec,
115 :bookingClosesRec,
116 :status,
117 :name,
118 :description,
119 :color,
120 :price,
121 :bringingAnyone,
122 :bookMultipleTimes,
123 :maxCapacity,
124 :maxCustomCapacity,
125 :maxExtraPeople,
126 :show,
127 :notifyParticipants,
128 :customLocation,
129 :parentId,
130 :created,
131 :closeAfterMin,
132 :closeAfterMinBookings,
133 :aggregatedPrice,
134 :error
135 )"
136 );
137
138 $res = $statement->execute($params);
139
140 if (!$res) {
141 throw new QueryExecutionException('Unable to add data in ' . __CLASS__);
142 }
143
144 return $this->connection->lastInsertId();
145 } catch (\Exception $e) {
146 throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e);
147 }
148 }
149
150 /**
151 * @param int $id
152 * @param Event $entity
153 *
154 * @return mixed
155 * @throws QueryExecutionException
156 */
157 public function update($id, $entity)
158 {
159 $data = $entity->toArray();
160
161 $params = [
162 ':id' => $id,
163 ':bookingOpens' => $data['bookingOpens'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingOpens']) : null,
164 ':bookingCloses' => $data['bookingCloses'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingCloses']) : null,
165 ':bookingOpensRec' => $data['bookingOpensRec'],
166 ':bookingClosesRec' => $data['bookingClosesRec'],
167 ':status' => $data['status'],
168 ':name' => $data['name'],
169 ':description' => $data['description'],
170 ':color' => $data['color'],
171 ':price' => $data['price'],
172 ':bringingAnyone' => $data['bringingAnyone'] ? 1 : 0,
173 ':bookMultipleTimes' => $data['bookMultipleTimes'] ? 1 : 0,
174 ':maxCapacity' => $data['maxCapacity'],
175 ':maxCustomCapacity' => $data['maxCustomCapacity'],
176 ':maxExtraPeople' => $data['maxExtraPeople'],
177 ':show' => $data['show'] ? 1 : 0,
178 ':notifyParticipants' => $data['notifyParticipants'] ? 1 : 0,
179 ':customLocation' => $data['customLocation'],
180 ':parentId' => $data['parentId'],
181 ':closeAfterMin' => $data['closeAfterMin'],
182 ':closeAfterMinBookings' => $data['closeAfterMinBookings'] ? 1 : 0,
183 ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0
184 ];
185
186 $additionalData = Licence\DataModifier::getEventRepositoryData($data);
187
188 $params = array_merge($params, $additionalData['values']);
189
190 try {
191 $statement = $this->connection->prepare(
192 "UPDATE {$this->table}
193 SET
194 {$additionalData['columnsPlaceholders']}
195 `bookingOpens` = :bookingOpens,
196 `bookingCloses` = :bookingCloses,
197 `bookingOpensRec` = :bookingOpensRec,
198 `bookingClosesRec` = :bookingClosesRec,
199 `status` = :status,
200 `name` = :name,
201 `description` = :description,
202 `color` = :color,
203 `price` = :price,
204 `bringingAnyone` = :bringingAnyone,
205 `bookMultipleTimes` = :bookMultipleTimes,
206 `maxCapacity` = :maxCapacity,
207 `maxCustomCapacity` = :maxCustomCapacity,
208 `maxExtraPeople` = :maxExtraPeople,
209 `show` = :show,
210 `notifyParticipants` = :notifyParticipants,
211 `customLocation` = :customLocation,
212 `parentId` = :parentId,
213 `closeAfterMin` = :closeAfterMin,
214 `closeAfterMinBookings` = :closeAfterMinBookings,
215 `aggregatedPrice` = :aggregatedPrice
216 WHERE id = :id"
217 );
218
219 $res = $statement->execute($params);
220
221 if (!$res) {
222 throw new QueryExecutionException('Unable to save data in ' . __CLASS__);
223 }
224
225 return $res;
226 } catch (\Exception $e) {
227 throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e);
228 }
229 }
230
231 /**
232 * @param int $id
233 * @param int $status
234 *
235 * @return mixed
236 * @throws QueryExecutionException
237 */
238 public function updateStatusById($id, $status)
239 {
240 $params = [
241 ':id' => $id,
242 ':status' => $status
243 ];
244
245 try {
246 $statement = $this->connection->prepare(
247 "UPDATE {$this->table}
248 SET
249 `status` = :status
250 WHERE id = :id"
251 );
252
253 $res = $statement->execute($params);
254
255 if (!$res) {
256 throw new QueryExecutionException('Unable to save data in ' . __CLASS__);
257 }
258
259 return $res;
260 } catch (\Exception $e) {
261 throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e);
262 }
263 }
264
265 /**
266 * @param int $id
267 * @param int $parentId
268 *
269 * @return mixed
270 * @throws QueryExecutionException
271 */
272 public function updateParentId($id, $parentId)
273 {
274 $params = [
275 ':id' => $id,
276 ':parentId' => $parentId,
277 ];
278
279 try {
280 $statement = $this->connection->prepare(
281 "UPDATE {$this->table}
282 SET
283 `parentId` = :parentId
284 WHERE id = :id"
285 );
286
287 $res = $statement->execute($params);
288
289 if (!$res) {
290 throw new QueryExecutionException('Unable to save data in ' . __CLASS__);
291 }
292
293 return $res;
294 } catch (\Exception $e) {
295 throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e);
296 }
297 }
298
299 /**
300 * @param array $criteria
301 *
302 * @return Collection
303 * @throws QueryExecutionException
304 * @throws InvalidArgumentException
305 */
306 public function getProvidersEvents($criteria)
307 {
308 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
309 $eventsProvidersTable = EventsProvidersTable::getTableName();
310 $usersTable = UsersTable::getTableName();
311
312 $params = [];
313 $where = [];
314
315 if (!empty($criteria['dates'])) {
316 if (isset($criteria['dates'][0], $criteria['dates'][1])) {
317 $whereStart = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom AND :eventTo)";
318 $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
319 $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]);
320
321 $whereEnd = "(DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom2 AND :bookingTo2)";
322 $params[':bookingFrom2'] = $params[':eventFrom'];
323 $params[':bookingTo2'] = $params[':eventTo'];
324
325 $where[] = "({$whereStart} OR {$whereEnd})";
326 } elseif (isset($criteria['dates'][0])) {
327 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom)";
328 $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
329 } elseif (isset($criteria['dates'][1])) {
330 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)";
331 $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]);
332 } else {
333 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)";
334 $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc();
335 }
336 }
337
338 if (!empty($criteria['providers'])) {
339 $queryProviders = [];
340
341 foreach ((array)$criteria['providers'] as $index => $value) {
342 $param = ':provider' . $index;
343 $queryProviders[] = $param;
344 $params[$param] = $value;
345 }
346
347 $where[] = 'epr.userId IN (' . implode(', ', $queryProviders) . ')';
348 }
349
350 if (!empty($criteria['status'])) {
351 $params[':status'] = $criteria['status'];
352
353 $where[] = 'e.status = :status';
354 }
355
356 $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';
357
358 try {
359 $statement = $this->connection->prepare(
360 "SELECT
361 e.id AS event_id,
362 e.name AS event_name,
363 e.status AS event_status,
364 e.bookingOpens AS event_bookingOpens,
365 e.bookingCloses AS event_bookingCloses,
366 e.recurringCycle AS event_recurringCycle,
367 e.recurringOrder AS event_recurringOrder,
368 e.recurringInterval AS event_recurringInterval,
369 e.recurringUntil AS event_recurringUntil,
370 e.recurringMonthly AS event_recurringMonthly,
371 e.monthlyDate AS event_monthlyDate,
372 e.monthlyOnRepeat AS event_monthlyOnRepeat,
373 e.monthlyOnDay AS event_monthlyOnDay,
374 e.bringingAnyone AS event_bringingAnyone,
375 e.bookMultipleTimes AS event_bookMultipleTimes,
376 e.maxCapacity AS event_maxCapacity,
377 e.maxCustomCapacity AS event_maxCustomCapacity,
378 e.maxExtraPeople AS event_maxExtraPeople,
379 e.price AS event_price,
380 e.description AS event_description,
381 e.color AS event_color,
382 e.show AS event_show,
383 e.locationId AS event_locationId,
384 e.customLocation AS event_customLocation,
385 e.parentId AS event_parentId,
386 e.created AS event_created,
387 e.notifyParticipants AS event_notifyParticipants,
388 e.translations AS event_translations,
389 e.deposit AS event_deposit,
390 e.depositPayment AS event_depositPayment,
391 e.depositPerPerson AS event_depositPerPerson,
392 e.fullPayment AS event_fullPayment,
393 e.customPricing AS event_customPricing,
394 e.aggregatedPrice AS event_aggregatedPrice,
395
396 ep.id AS event_periodId,
397 ep.periodStart AS event_periodStart,
398 ep.periodEnd AS event_periodEnd,
399
400 pu.id AS provider_id,
401 pu.firstName AS provider_firstName,
402 pu.lastName AS provider_lastName,
403 pu.email AS provider_email,
404 pu.note AS provider_note,
405 pu.description AS provider_description,
406 pu.phone AS provider_phone,
407 pu.gender AS provider_gender,
408 pu.pictureFullPath AS provider_pictureFullPath,
409 pu.pictureThumbPath AS provider_pictureThumbPath,
410 pu.translations AS provider_translations
411 FROM {$this->table} e
412 INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id
413 INNER JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
414 INNER JOIN {$usersTable} pu ON pu.id = epr.userId
415 {$where}
416 ORDER BY ep.periodStart"
417 );
418
419 $statement->execute($params);
420
421 $rows = $statement->fetchAll();
422 } catch (\Exception $e) {
423 throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e);
424 }
425
426 return call_user_func([static::FACTORY, 'createCollection'], $rows);
427 }
428
429 /**
430 * @param array $criteria
431 * @param int $itemsPerPage
432 *
433 * @return array
434 * @throws QueryExecutionException
435 * @throws InvalidArgumentException
436 */
437 public function getFilteredIds($criteria, $itemsPerPage)
438 {
439 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
440 $eventsTagsTable = EventsTagsTable::getTableName();
441 $customerBookingsTable = CustomerBookingsTable::getTableName();
442 $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName();
443 $eventsProvidersTable = EventsProvidersTable::getTableName();
444 $usersTable = UsersTable::getTableName();
445
446 $params = [];
447
448 $where = [];
449
450 if (isset($criteria['parentId'])) {
451 $params[':parentId'] = $criteria['parentId'];
452
453 $params[':originParentId'] = $criteria['parentId'];
454
455 $where[] = 'e.parentId = :parentId OR e.id = :originParentId';
456 }
457
458 if (!empty($criteria['search'])) {
459 $where[] = "(e.name LIKE '%" . $criteria['search'] . "%'
460 OR e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%\"description\":{%'
461 OR e.translations LIKE '{\"description\":{%\"name\":{%" . $criteria['search'] . "%'
462 OR (e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%' AND e.translations NOT LIKE '%\"description\":{%'))";
463 }
464
465
466 if (isset($criteria['show'])) {
467 $where[] = 'e.show = 1';
468 }
469
470 if (!empty($criteria['dates'])) {
471 if (isset($criteria['dates'][0], $criteria['dates'][1])) {
472 $where[] = "((DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom1 AND :eventTo1)
473 OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom2 AND :eventTo2)
474 OR (:eventFrom3 BETWEEN DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') AND DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s'))
475 OR (:eventTo3 BETWEEN DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') AND DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s')))";
476
477 $params[':eventFrom1'] = $params[':eventFrom2'] = $params[':eventFrom3'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
478 $params[':eventTo1'] = $params[':eventTo2'] = $params[':eventTo3'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]);
479 } elseif (isset($criteria['dates'][0])) {
480 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') >= :eventTo))";
481 $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
482 $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
483 } elseif (isset($criteria['dates'][1])) {
484 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)";
485 $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]);
486 } else {
487 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)";
488 $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc();
489 }
490 }
491
492 $tagJoin = '';
493
494 if (isset($criteria['tag'])) {
495 $queryTags = [];
496
497 $tags = $criteria['tag'];
498 foreach ((array)$tags as $index => $value) {
499 $param = ':tag' . $index;
500
501 $queryTags[] = $param;
502
503 $params[$param] = $value;
504 }
505
506 $where[] = 'et.name IN (' . implode(', ', $queryTags) . ')';
507
508 $tagJoin = "INNER JOIN {$eventsTagsTable} et ON et.eventId = e.id";
509 }
510
511 if (!empty($criteria['id'])) {
512 if (!empty($criteria['recurring'])) {
513 $whereOr = [];
514 foreach ((array)$criteria['id'] as $index => $value) {
515 $param = 'id' . $index;
516
517 $params[':rec1' . $param] = (int)$value;
518 $params[':rec2' . $param] = (int)$value;
519 $params[':rec3' . $param] = (int)$value;
520 $params[':rec4' . $param] = (int)$value;
521
522 $whereOr[] = "((e.id = :rec1id" . $index . " AND e.parentId IS NULL) OR
523 (e.parentId IN (SELECT parentId FROM {$this->table} WHERE parentId = :rec2id" . $index . ")) OR
524 (e.id >= :rec3id" . $index . " AND e.parentId IN (SELECT parentId FROM {$this->table} WHERE id = :rec4id" . $index . ")))";
525 }
526 $where[] = implode(' OR ', $whereOr);
527 } else {
528 $queryIds = [];
529
530 foreach ((array)$criteria['id'] as $index => $value) {
531 $param = ':id' . $index;
532
533 $queryIds[] = $param;
534
535 $params[$param] = (int)$value;
536 }
537
538 $where[] = 'e.id IN (' . implode(', ', $queryIds) . ')';
539 }
540 }
541
542 $customerJoin = '';
543
544 if (!empty($criteria['customerId']) || !empty($criteria['customerBookingsIds'])) {
545 $customerJoin = "
546 LEFT JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id
547 LEFT JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId";
548
549 if (!empty($criteria['customerId'])) {
550 $params[':customerId'] = $criteria['customerId'];
551
552 $where[] = 'cb.customerId = :customerId';
553 }
554
555 if (!empty($criteria['customerBookingsIds'])) {
556 $queryBookingsIds = [];
557
558 foreach ($criteria['customerBookingsIds'] as $index => $value) {
559 $param = ':customerBookingId' . $index;
560
561 $queryBookingsIds[] = $param;
562
563 $params[$param] = $value;
564 }
565
566 $where[] = 'cb.id IN (' . implode(', ', $queryBookingsIds) . ')';
567 }
568
569 if (!empty($criteria['customerBookingStatus'])) {
570 $params[':customerBookingStatus'] = $criteria['customerBookingStatus'];
571
572 $where[] = 'cb.status = :customerBookingStatus';
573 }
574
575 if (!empty($criteria['customerBookingCouponId'])) {
576 $params[':customerBookingCouponId'] = $criteria['customerBookingCouponId'];
577
578 $where[] = 'cb.couponId = :customerBookingCouponId';
579 }
580 }
581
582 if (!empty($criteria['locationId'])) {
583 $params[':locationId'] = $criteria['locationId'];
584
585 $where[] = 'e.locationId = :locationId';
586 }
587
588 if (!empty($criteria['locations'])) {
589 foreach ((array)$criteria['locations'] as $index => $value) {
590 $param = ':location' . $index;
591 $queryLocations[] = $param;
592 $params[$param] = $value;
593 }
594
595 $where3 = 'e.locationId IN (' . implode(', ', $queryLocations) . ')';
596
597 $where[] = '(' . $where3 . ')';
598 }
599
600 $providerJoin = '';
601
602 if (!empty($criteria['providers'])) {
603 $providerJoin = "
604 LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
605 INNER JOIN {$usersTable} pu ON pu.id = epr.userId OR pu.id = e.organizerId";
606 $queryProviders = [];
607
608 foreach ((array)$criteria['providers'] as $index => $value) {
609 $param = ':provider' . $index;
610 $queryProviders[] = $param;
611 $params[$param] = $value;
612 }
613
614 $where1 = 'epr.userId IN (' . implode(', ', $queryProviders) . ')';
615
616 $queryProviders = [];
617 foreach ((array)$criteria['providers'] as $index => $value) {
618 $param = ':organizer' . $index;
619 $queryProviders[] = $param;
620 $params[$param] = $value;
621 }
622
623 $where2 = 'e.organizerId IN (' . implode(', ', $queryProviders) . ')';
624
625 $where[] = '(' . $where1 . ' OR ' . $where2 . ')';
626
627 }
628
629 $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';
630
631 $limit = $this->getLimit(
632 !empty($criteria['page']) ? (int)$criteria['page'] : 0,
633 (int)$itemsPerPage
634 );
635
636 try {
637 $statement = $this->connection->prepare(
638 "SELECT
639 e.id
640 FROM {$this->table} e
641 INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id
642 {$tagJoin}
643 {$providerJoin}
644 {$customerJoin}
645 {$where}
646 GROUP BY e.id
647 ORDER BY ep.periodStart, e.id
648 {$limit}"
649 );
650
651 $statement->execute($params);
652
653 $rows = $statement->fetchAll();
654 } catch (\Exception $e) {
655 throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e);
656 }
657
658 return array_column($rows, 'id');
659 }
660
661 /**
662 * @param array $criteria
663 *
664 * @return int
665 * @throws QueryExecutionException
666 * @throws InvalidArgumentException
667 */
668 public function getFilteredIdsCount($criteria)
669 {
670 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
671 $eventsTagsTable = EventsTagsTable::getTableName();
672 $eventsProvidersTable = EventsProvidersTable::getTableName();
673 $usersTable = UsersTable::getTableName();
674
675
676 $params = [];
677 $where = [];
678
679 if (isset($criteria['parentId'])) {
680 $params[':parentId'] = $criteria['parentId'];
681
682 $params[':originParentId'] = $criteria['parentId'];
683
684 $where[] = 'e.parentId = :parentId OR e.id = :originParentId';
685 }
686
687 if (!empty($criteria['search'])) {
688 $where[] = "(e.name LIKE '%" . $criteria['search'] . "%'
689 OR e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%\"description\":{%'
690 OR e.translations LIKE '{\"description\":{%\"name\":{%" . $criteria['search'] . "%'
691 OR (e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%' AND e.translations NOT LIKE '%\"description\":{%'))";
692 }
693
694 if (isset($criteria['show'])) {
695 $where[] = 'e.show = 1';
696 }
697
698 if (!empty($criteria['dates'])) {
699 if (isset($criteria['dates'][0], $criteria['dates'][1])) {
700 $where[] = "((DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom1 AND :eventTo1)
701 OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom2 AND :eventTo2)
702 OR (:eventFrom3 BETWEEN DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') AND DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s'))
703 OR (:eventTo3 BETWEEN DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') AND DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s')))";
704
705 $params[':eventFrom1'] = $params[':eventFrom2'] = $params[':eventFrom3'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
706 $params[':eventTo1'] = $params[':eventTo2'] = $params[':eventTo3'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]);
707 } elseif (isset($criteria['dates'][0])) {
708 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') >= :eventTo))";
709 $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
710 $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]);
711 } elseif (isset($criteria['dates'][1])) {
712 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)";
713 $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]);
714 } else {
715 $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)";
716 $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc();
717 }
718 }
719
720 if (!empty($criteria['locationId'])) {
721 $params[':locationId'] = $criteria['locationId'];
722
723 $where[] = 'e.locationId = :locationId';
724 }
725
726 if (!empty($criteria['locations'])) {
727 foreach ((array)$criteria['locations'] as $index => $value) {
728 $param = ':location' . $index;
729 $queryLocations[] = $param;
730 $params[$param] = $value;
731 }
732
733 $where3 = 'e.locationId IN (' . implode(', ', $queryLocations) . ')';
734
735 $where[] = '(' . $where3 . ')';
736 }
737
738
739 $tagJoin = '';
740
741 if (isset($criteria['tag'])) {
742 $queryTags = [];
743
744 $tags = $criteria['tag'];//explode(',', $criteria['tag']);
745 foreach ((array)$tags as $index => $value) {
746 $param = ':tag' . $index;
747
748 $queryTags[] = $param;
749
750 $params[$param] = $value;//trim($value, '{}');
751 }
752
753 $where[] = 'et.name IN (' . implode(', ', $queryTags) . ')';
754
755 $tagJoin = "INNER JOIN {$eventsTagsTable} et ON et.eventId = e.id";
756 }
757
758 if (!empty($criteria['id'])) {
759 if (!empty($criteria['recurring'])) {
760 $whereOr = [];
761 foreach ((array)$criteria['id'] as $index => $value) {
762 $param = 'id' . $index;
763
764 $params[':rec1' . $param] = (int)$value;
765 $params[':rec2' . $param] = (int)$value;
766 $params[':rec3' . $param] = (int)$value;
767 $params[':rec4' . $param] = (int)$value;
768
769 $whereOr[] = "((e.id = :rec1id" . $index . " AND e.parentId IS NULL) OR
770 (e.parentId IN (SELECT parentId FROM {$this->table} WHERE parentId = :rec2id" . $index . ")) OR
771 (e.id >= :rec3id" . $index . " AND e.parentId IN (SELECT parentId FROM {$this->table} WHERE id = :rec4id" . $index . ")))";
772 }
773 $where[] = implode(' OR ', $whereOr);
774 } else {
775 $queryIds = [];
776
777 foreach ((array)$criteria['id'] as $index => $value) {
778 $param = ':id' . $index;
779
780 $queryIds[] = $param;
781
782 $params[$param] = (int)$value;
783 }
784
785 $where[] = 'e.id IN (' . implode(', ', $queryIds) . ')';
786 }
787 }
788
789 $providerJoin = '';
790
791 if (!empty($criteria['providers'])) {
792 $providerJoin = "
793 LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
794 INNER JOIN {$usersTable} pu ON pu.id = epr.userId OR pu.id = e.organizerId";
795
796 $queryProviders = [];
797
798 foreach ((array)$criteria['providers'] as $index => $value) {
799 $param = ':provider' . $index;
800 $queryProviders[] = $param;
801 $params[$param] = $value;
802 }
803 $where1 = 'epr.userId IN (' . implode(', ', $queryProviders) . ')';
804
805 $queryProviders = [];
806 foreach ((array)$criteria['providers'] as $index => $value) {
807 $param = ':organizer' . $index;
808 $queryProviders[] = $param;
809 $params[$param] = $value;
810 }
811 $where2 = 'e.organizerId IN (' . implode(', ', $queryProviders) . ')';
812
813 $where[] = '(' . $where1 . ' OR ' . $where2 . ')';
814 }
815
816 $customerJoin = '';
817
818 $customerBookingsTable = CustomerBookingsTable::getTableName();
819 $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName();
820
821 if (!empty($criteria['customerId']) || !empty($criteria['customerBookingsIds'])) {
822 $customerJoin = "
823 LEFT JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id
824 LEFT JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId";
825
826 if (!empty($criteria['customerId'])) {
827 $params[':customerId'] = $criteria['customerId'];
828
829 $where[] = 'cb.customerId = :customerId';
830 }
831
832 if (!empty($criteria['customerBookingsIds'])) {
833 $queryBookingsIds = [];
834
835 foreach ($criteria['customerBookingsIds'] as $index => $value) {
836 $param = ':customerBookingId' . $index;
837
838 $queryBookingsIds[] = $param;
839
840 $params[$param] = $value;
841 }
842
843 $where[] = 'cb.id IN (' . implode(', ', $queryBookingsIds) . ')';
844 }
845
846 if (!empty($criteria['customerBookingStatus'])) {
847 $params[':customerBookingStatus'] = $criteria['customerBookingStatus'];
848
849 $where[] = 'cb.status = :customerBookingStatus';
850 }
851
852 if (!empty($criteria['customerBookingCouponId'])) {
853 $params[':customerBookingCouponId'] = $criteria['customerBookingCouponId'];
854
855 $where[] = 'cb.couponId = :customerBookingCouponId';
856 }
857 }
858
859 $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';
860
861 try {
862 $statement = $this->connection->prepare(
863 "SELECT e.id
864 FROM {$this->table} e
865 INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id
866 {$tagJoin}
867 {$providerJoin}
868 {$customerJoin}
869 {$where}
870 GROUP BY e.id
871 ORDER BY ep.periodStart"
872 );
873
874 $statement->execute($params);
875
876 $rows = $statement->fetchAll();
877 } catch (\Exception $e) {
878 throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e);
879 }
880
881 return sizeOf($rows);
882 }
883
884 /**
885 * @param int $id
886 *
887 * @return Event
888 * @throws QueryExecutionException
889 * @throws InvalidArgumentException
890 */
891 public function getById($id)
892 {
893 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
894 $eventsTagsTable = EventsTagsTable::getTableName();
895 $eventsTicketTable = EventsTicketsTable::getTableName();
896
897 $customerBookingsTable = CustomerBookingsTable::getTableName();
898 $paymentsTable = PaymentsTable::getTableName();
899 $usersTable = UsersTable::getTableName();
900 $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName();
901 $galleriesTable = GalleriesTable::getTableName();
902 $eventsProvidersTable = EventsProvidersTable::getTableName();
903 $couponsTable = CouponsTable::getTableName();
904
905 try {
906 $statement = $this->connection->prepare(
907 "SELECT
908 e.id AS event_id,
909 e.name AS event_name,
910 e.status AS event_status,
911 e.bookingOpens AS event_bookingOpens,
912 e.bookingCloses AS event_bookingCloses,
913 e.bookingOpensRec AS event_bookingOpensRec,
914 e.bookingClosesRec AS event_bookingClosesRec,
915 e.ticketRangeRec AS event_ticketRangeRec,
916 e.recurringCycle AS event_recurringCycle,
917 e.recurringOrder AS event_recurringOrder,
918 e.recurringInterval AS event_recurringInterval,
919 e.recurringMonthly AS event_recurringMonthly,
920 e.monthlyDate AS event_monthlyDate,
921 e.monthlyOnRepeat AS event_monthlyOnRepeat,
922 e.monthlyOnDay AS event_monthlyOnDay,
923 e.recurringUntil AS event_recurringUntil,
924 e.bringingAnyone AS event_bringingAnyone,
925 e.bookMultipleTimes AS event_bookMultipleTimes,
926 e.maxCapacity AS event_maxCapacity,
927 e.maxCustomCapacity AS event_maxCustomCapacity,
928 e.maxExtraPeople AS event_maxExtraPeople,
929 e.price AS event_price,
930 e.description AS event_description,
931 e.color AS event_color,
932 e.show AS event_show,
933 e.notifyParticipants AS event_notifyParticipants,
934 e.locationId AS event_locationId,
935 e.customLocation AS event_customLocation,
936 e.parentId AS event_parentId,
937 e.created AS event_created,
938 e.settings AS event_settings,
939 e.zoomUserId AS event_zoomUserId,
940 e.organizerId AS event_organizerId,
941 e.translations AS event_translations,
942 e.deposit AS event_deposit,
943 e.depositPayment AS event_depositPayment,
944 e.depositPerPerson AS event_depositPerPerson,
945 e.fullPayment AS event_fullPayment,
946 e.customPricing AS event_customPricing,
947 e.aggregatedPrice AS event_aggregatedPrice,
948
949 ep.id AS event_periodId,
950 ep.periodStart AS event_periodStart,
951 ep.periodEnd AS event_periodEnd,
952 ep.zoomMeeting AS event_periodZoomMeeting,
953 ep.lessonSpace AS event_periodLessonSpace,
954 ep.googleCalendarEventId AS event_googleCalendarEventId,
955 ep.googleMeetUrl AS event_googleMeetUrl,
956 ep.outlookCalendarEventId AS event_outlookCalendarEventId,
957
958 et.id AS event_tagId,
959 et.name AS event_tagName,
960
961 cb.id AS booking_id,
962 cb.customerId AS booking_customerId,
963 cb.status AS booking_status,
964 cb.price AS booking_price,
965 cb.persons AS booking_persons,
966 cb.customFields AS booking_customFields,
967 cb.info AS booking_info,
968 cb.aggregatedPrice AS booking_aggregatedPrice,
969 cb.token AS booking_token,
970 cb.utcOffset AS booking_utcOffset,
971 cb.couponId AS booking_couponId,
972
973 cu.id AS customer_id,
974 cu.firstName AS customer_firstName,
975 cu.lastName AS customer_lastName,
976 cu.email AS customer_email,
977 cu.note AS customer_note,
978 cu.phone AS customer_phone,
979 cu.gender AS customer_gender,
980 cu.birthday AS customer_birthday,
981
982 p.id AS payment_id,
983 p.amount AS payment_amount,
984 p.dateTime AS payment_dateTime,
985 p.status AS payment_status,
986 p.gateway AS payment_gateway,
987 p.gatewayTitle AS payment_gatewayTitle,
988 p.transactionId AS payment_transactionId,
989 p.data AS payment_data,
990 p.wcOrderId AS payment_wcOrderId,
991 p.wcOrderItemId AS payment_wcOrderItemId,
992 p.invoiceNumber AS payment_invoiceNumber,
993
994 pu.id AS provider_id,
995 pu.firstName AS provider_firstName,
996 pu.lastName AS provider_lastName,
997 pu.email AS provider_email,
998 pu.note AS provider_note,
999 pu.description AS provider_description,
1000 pu.phone AS provider_phone,
1001 pu.gender AS provider_gender,
1002 pu.translations AS provider_translations,
1003 pu.timeZone AS provider_timeZone,
1004
1005 g.id AS gallery_id,
1006 g.pictureFullPath AS gallery_picture_full,
1007 g.pictureThumbPath AS gallery_picture_thumb,
1008 g.position AS gallery_position,
1009
1010 c.id AS coupon_id,
1011 c.code AS coupon_code,
1012 c.discount AS coupon_discount,
1013 c.deduction AS coupon_deduction,
1014 c.limit AS coupon_limit,
1015 c.customerLimit AS coupon_customerLimit,
1016 c.status AS coupon_status,
1017
1018 t.id AS ticket_id,
1019 t.name AS ticket_name,
1020 t.enabled AS ticket_enabled,
1021 t.price AS ticket_price,
1022 t.spots AS ticket_spots,
1023 t.waitingListSpots AS ticket_waiting_list_spots,
1024 t.dateRanges AS ticket_dateRanges,
1025 t.translations AS ticket_translations
1026
1027 FROM {$this->table} e
1028 INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id
1029 LEFT JOIN {$eventsTagsTable} et ON et.eventId = e.id
1030 LEFT JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id
1031 LEFT JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId
1032 LEFT JOIN {$usersTable} cu ON cu.id = cb.customerId
1033 LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
1034 LEFT JOIN {$usersTable} pu ON pu.id = epr.userId
1035 LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id
1036 LEFT JOIN {$galleriesTable} g ON g.entityId = e.id AND g.entityType = 'event'
1037 LEFT JOIN {$couponsTable} c ON c.id = cb.couponId
1038 LEFT JOIN {$eventsTicketTable} t ON t.eventId = e.id
1039
1040 WHERE e.id = :eventId"
1041 );
1042
1043 $statement->bindParam(':eventId', $id);
1044
1045 $statement->execute();
1046
1047 $rows = $statement->fetchAll();
1048 } catch (\Exception $e) {
1049 throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e);
1050 }
1051
1052 return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($id);
1053 }
1054
1055
1056 /**
1057 * @param int $id
1058 *
1059 * @return mixed
1060 * @throws QueryExecutionException
1061 */
1062 public function isRecurring($id)
1063 {
1064 try {
1065 $statement = $this->connection->prepare(
1066 "SELECT
1067 e.recurringOrder AS event_recurringOrder,
1068 e.parentId AS event_parentId
1069 FROM {$this->table} e
1070 WHERE e.id = :eventId"
1071 );
1072
1073 $statement->bindParam(':eventId', $id);
1074
1075 $statement->execute();
1076
1077 return $statement->fetch();
1078 } catch (\Exception $e) {
1079 throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e);
1080 }
1081 }
1082
1083
1084 /**
1085 * @param int $id
1086 * @param int $parentId
1087 *
1088 * @return mixed
1089 * @throws QueryExecutionException
1090 */
1091 public function getRecurringIds($id, $parentId)
1092 {
1093 $whereParent = empty($parentId) ? '' : ' OR e.parentId = :parentId';
1094 try {
1095 $statement = $this->connection->prepare(
1096 "SELECT
1097 e.id AS eventId
1098 FROM {$this->table} e
1099 WHERE e.parentId = :eventId" . $whereParent
1100 );
1101
1102 $statement->bindParam(':eventId', $id);
1103 if ($parentId) {
1104 $statement->bindParam(':parentId', $parentId);
1105 }
1106
1107 $statement->execute();
1108
1109 $events = $statement->fetchAll();
1110
1111 return array_column($events, 'eventId');
1112 } catch (\Exception $e) {
1113 throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e);
1114 }
1115 }
1116
1117 /**
1118 * @param $criteria
1119 *
1120 * @return Collection
1121 * @throws InvalidArgumentException
1122 * @throws QueryExecutionException
1123 * @throws InvalidArgumentException
1124 */
1125 public function getWithCoupons($criteria)
1126 {
1127 $couponToEventsTable = CouponsToEventsTable::getTableName();
1128 $couponsTable = CouponsTable::getTableName();
1129 $eventsProvidersTable = EventsProvidersTable::getTableName();
1130 $usersTable = UsersTable::getTableName();
1131 $eventsTicketTable = EventsTicketsTable::getTableName();
1132
1133 $params = [];
1134
1135 $where = [];
1136
1137 foreach ((array)$criteria as $index => $value) {
1138 $params[':event' . $index] = $value['eventId'];
1139
1140 if ($value['couponId']) {
1141 $params[':coupon' . $index] = $value['couponId'];
1142 $params[':couponStatus' . $index] = Status::VISIBLE;
1143 }
1144
1145 $where[] = "(e.id = :event$index"
1146 . ($value['couponId'] ? " AND c.id = :coupon$index AND c.status = :couponStatus$index" : '') . ')';
1147 }
1148
1149 $where = $where ? 'WHERE ' . implode(' OR ', $where) : '';
1150
1151 try {
1152 $statement = $this->connection->prepare(
1153 "SELECT
1154 e.id AS event_id,
1155 e.name AS event_name,
1156 e.status AS event_status,
1157 e.bookingOpens AS event_bookingOpens,
1158 e.bookingCloses AS event_bookingCloses,
1159 e.recurringCycle AS event_recurringCycle,
1160 e.recurringOrder AS event_recurringOrder,
1161 e.recurringInterval AS event_recurringInterval,
1162 e.recurringUntil AS event_recurringUntil,
1163 e.bringingAnyone AS event_bringingAnyone,
1164 e.bookMultipleTimes AS event_bookMultipleTimes,
1165 e.maxCapacity AS event_maxCapacity,
1166 e.maxCustomCapacity AS event_maxCustomCapacity,
1167 e.maxExtraPeople AS event_maxExtraPeople,
1168 e.price AS event_price,
1169 e.description AS event_description,
1170 e.color AS event_color,
1171 e.show AS event_show,
1172 e.notifyParticipants AS event_notifyParticipants,
1173 e.locationId AS event_locationId,
1174 e.customLocation AS event_customLocation,
1175 e.parentId AS event_parentId,
1176 e.created AS event_created,
1177 e.translations AS event_translations,
1178 e.deposit AS event_deposit,
1179 e.depositPayment AS event_depositPayment,
1180 e.depositPerPerson AS event_depositPerPerson,
1181 e.fullPayment AS event_fullPayment,
1182 e.customPricing AS event_customPricing,
1183 e.aggregatedPrice AS event_aggregatedPrice,
1184
1185 pu.id AS provider_id,
1186 pu.firstName AS provider_firstName,
1187 pu.lastName AS provider_lastName,
1188 pu.email AS provider_email,
1189 pu.note AS provider_note,
1190 pu.description AS provider_description,
1191 pu.phone AS provider_phone,
1192 pu.gender AS provider_gender,
1193 pu.translations AS provider_translations,
1194
1195 t.id AS ticket_id,
1196 t.name AS ticket_name,
1197 t.enabled AS ticket_enabled,
1198 t.price AS ticket_price,
1199 t.spots AS ticket_spots,
1200 t.waitingListSpots AS ticket_waiting_list_spots,
1201 t.dateRanges AS ticket_dateRanges,
1202 t.translations AS ticket_translations,
1203
1204 c.id AS coupon_id,
1205 c.code AS coupon_code,
1206 c.discount AS coupon_discount,
1207 c.deduction AS coupon_deduction,
1208 c.limit AS coupon_limit,
1209 c.customerLimit AS coupon_customerLimit,
1210 c.status AS coupon_status
1211 FROM {$this->table} e
1212 LEFT JOIN {$couponToEventsTable} ce ON ce.eventId = e.id
1213 LEFT JOIN {$couponsTable} c ON c.id = ce.couponId
1214 LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
1215 LEFT JOIN {$usersTable} pu ON pu.id = epr.userId
1216 LEFT JOIN {$eventsTicketTable} t ON t.eventId = e.id
1217 {$where}"
1218 );
1219
1220 $statement->execute($params);
1221
1222 $rows = $statement->fetchAll();
1223 } catch (\Exception $e) {
1224 throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e);
1225 }
1226
1227 return call_user_func([static::FACTORY, 'createCollection'], $rows);
1228 }
1229
1230 /**
1231 * @param int $bookingId
1232 * @param array $criteria
1233 *
1234 * @return Event
1235 * @throws QueryExecutionException
1236 * @throws InvalidArgumentException
1237 */
1238 public function getByBookingId($bookingId, $criteria = [])
1239 {
1240 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
1241
1242 $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName();
1243
1244 $fields = '';
1245
1246 $joins = '';
1247
1248 if (!empty($criteria['fetchEventsCoupons'])) {
1249 $couponsTable = CouponsTable::getTableName();
1250
1251 $fields .= '
1252 ec.id AS coupon_id,
1253 ec.code AS coupon_code,
1254 ec.discount AS coupon_discount,
1255 ec.deduction AS coupon_deduction,
1256 ec.limit AS coupon_limit,
1257 ec.customerLimit AS coupon_customerLimit,
1258 ec.status AS coupon_status,
1259 ';
1260
1261 $joins .= "
1262 LEFT JOIN {$couponsTable} ec ON ec.id = cb.couponId
1263 ";
1264 }
1265
1266 if (!empty($criteria['fetchEventsTickets'])) {
1267 $ticketsTable = EventsTicketsTable::getTableName();
1268
1269 $fields .= '
1270 eti.id AS ticket_id,
1271 eti.name AS ticket_name,
1272 eti.enabled AS ticket_enabled,
1273 eti.price AS ticket_price,
1274 eti.spots AS ticket_spots,
1275 eti.waitingListSpots AS ticket_waiting_list_spots,
1276 eti.dateRanges AS ticket_dateRanges,
1277 eti.translations AS ticket_translations,
1278 ';
1279
1280 $joins .= "
1281 LEFT JOIN {$ticketsTable} eti ON eti.eventId = e.id
1282 ";
1283 }
1284
1285 if (!empty($criteria['fetchEventsTags'])) {
1286 $tagsTable = EventsTagsTable::getTableName();
1287
1288 $fields .= '
1289 eta.id AS event_tagId,
1290 eta.name AS event_tagName,
1291 ';
1292
1293 $joins .= "
1294 LEFT JOIN {$tagsTable} eta ON eta.eventId = e.id
1295 ";
1296 }
1297
1298 if (!empty($criteria['fetchEventsImages'])) {
1299 $galleriesTable = GalleriesTable::getTableName();
1300
1301 $fields .= '
1302 eg.id AS gallery_id,
1303 eg.pictureFullPath AS gallery_picture_full,
1304 eg.pictureThumbPath AS gallery_picture_thumb,
1305 eg.position AS gallery_position,
1306 ';
1307
1308 $joins .= "
1309 LEFT JOIN {$galleriesTable} eg ON eg.entityId = e.id AND eg.entityType = 'event'
1310 ";
1311 }
1312
1313 if (!empty($criteria['fetchEventsProviders'])) {
1314 $eventsProvidersTable = EventsProvidersTable::getTableName();
1315
1316 $usersTable = UsersTable::getTableName();
1317
1318 $joins .= "
1319 LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
1320 LEFT JOIN {$usersTable} pu ON pu.id = epr.userId
1321 ";
1322
1323 $fields .= '
1324 pu.id AS provider_id,
1325 pu.firstName AS provider_firstName,
1326 pu.lastName AS provider_lastName,
1327 pu.email AS provider_email,
1328 pu.note AS provider_note,
1329 pu.description AS provider_description,
1330 pu.phone AS provider_phone,
1331 pu.gender AS provider_gender,
1332 pu.pictureFullPath AS provider_pictureFullPath,
1333 pu.pictureThumbPath AS provider_pictureThumbPath,
1334 pu.translations AS provider_translations,
1335 pu.timeZone AS provider_timeZone,
1336 ';
1337 }
1338
1339 $fields .= "
1340 e.id AS event_id,
1341 e.name AS event_name,
1342 e.status AS event_status,
1343 e.bookingOpens AS event_bookingOpens,
1344 e.bookingCloses AS event_bookingCloses,
1345 e.recurringCycle AS event_recurringCycle,
1346 e.recurringOrder AS event_recurringOrder,
1347 e.recurringInterval AS event_recurringInterval,
1348 e.recurringUntil AS event_recurringUntil,
1349 e.bringingAnyone AS event_bringingAnyone,
1350 e.bookMultipleTimes AS event_bookMultipleTimes,
1351 e.maxCapacity AS event_maxCapacity,
1352 e.maxCustomCapacity AS event_maxCustomCapacity,
1353 e.maxExtraPeople AS event_maxExtraPeople,
1354 e.price AS event_price,
1355 e.description AS event_description,
1356 e.color AS event_color,
1357 e.show AS event_show,
1358 e.notifyParticipants AS event_notifyParticipants,
1359 e.locationId AS event_locationId,
1360 e.customLocation AS event_customLocation,
1361 e.customPricing AS event_customPricing,
1362 e.parentId AS event_parentId,
1363 e.created AS event_created,
1364 e.settings AS event_settings,
1365 e.zoomUserId AS event_zoomUserId,
1366 e.translations AS event_translations,
1367 e.deposit AS event_deposit,
1368 e.depositPayment AS event_depositPayment,
1369 e.depositPerPerson AS event_depositPerPerson,
1370 e.fullPayment AS event_fullPayment,
1371 e.organizerId AS event_organizerId,
1372 e.aggregatedPrice AS event_aggregatedPrice,
1373
1374 ep.id AS event_periodId,
1375 ep.periodStart AS event_periodStart,
1376 ep.periodEnd AS event_periodEnd,
1377 ep.zoomMeeting AS event_periodZoomMeeting,
1378 ep.lessonSpace AS event_periodLessonSpace,
1379 ep.googleCalendarEventId AS event_googleCalendarEventId,
1380 ep.googleMeetUrl AS event_googleMeetUrl,
1381 ep.outlookCalendarEventId AS event_outlookCalendarEventId
1382 ";
1383
1384 $params = [
1385 ':customerBookingId' => $bookingId,
1386 ];
1387
1388 try {
1389 $statement = $this->connection->prepare(
1390 "SELECT
1391 {$fields}
1392 FROM {$customerBookingsEventsPeriods} cbe
1393 INNER JOIN {$eventsPeriodsTable} ep ON ep.id = cbe.eventPeriodId
1394 INNER JOIN {$this->table} e ON e.id = ep.eventId
1395 {$joins}
1396 WHERE cbe.customerBookingId = :customerBookingId"
1397 );
1398
1399 $statement->execute($params);
1400
1401 $rows = $statement->fetchAll();
1402 } catch (\Exception $e) {
1403 throw new QueryExecutionException('Unable to find event by booking id in ' . __CLASS__, $e->getCode(), $e);
1404 }
1405
1406 /** @var Collection $events */
1407 $events = call_user_func([static::FACTORY, 'createCollection'], $rows);
1408
1409 return $events->length() ? $events->getItem($events->keys()[0]) : null;
1410 }
1411
1412 /**
1413 * @param array $ids
1414 * @param array $criteria
1415 *
1416 * @return Collection
1417 * @throws QueryExecutionException
1418 * @throws InvalidArgumentException
1419 */
1420 public function getByIdsWithEntities($ids, $criteria = [])
1421 {
1422 $params = [];
1423
1424 $where = [];
1425
1426 $fields = '';
1427
1428 $joins = '';
1429
1430 $orderBy = '';
1431
1432 if (!empty($criteria['fetchEventsPeriods'])) {
1433 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
1434
1435 $fields .= '
1436 ep.id AS event_periodId,
1437 ep.periodStart AS event_periodStart,
1438 ep.periodEnd AS event_periodEnd,
1439 ep.zoomMeeting AS event_periodZoomMeeting,
1440 ep.lessonSpace AS event_periodLessonSpace,
1441 ep.googleCalendarEventId AS event_googleCalendarEventId,
1442 ep.googleMeetUrl AS event_googleMeetUrl,
1443 ep.outlookCalendarEventId AS event_outlookCalendarEventId,
1444 ';
1445
1446 $joins .= "
1447 INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id
1448 ";
1449
1450 $orderBy = 'ORDER BY ep.periodStart';
1451 }
1452
1453 if (!empty($criteria['fetchEventsCoupons'])) {
1454 $couponsTable = CouponsTable::getTableName();
1455
1456 $fields .= '
1457 ec.id AS coupon_id,
1458 ec.code AS coupon_code,
1459 ec.discount AS coupon_discount,
1460 ec.deduction AS coupon_deduction,
1461 ec.limit AS coupon_limit,
1462 ec.customerLimit AS coupon_customerLimit,
1463 ec.status AS coupon_status,
1464 ';
1465
1466 $joins .= "
1467 LEFT JOIN {$couponsTable} ec ON ec.id = cb.couponId
1468 ";
1469 }
1470
1471 if (!empty($criteria['fetchEventsTickets'])) {
1472 $ticketsTable = EventsTicketsTable::getTableName();
1473
1474 $fields .= '
1475 eti.id AS ticket_id,
1476 eti.name AS ticket_name,
1477 eti.enabled AS ticket_enabled,
1478 eti.price AS ticket_price,
1479 eti.spots AS ticket_spots,
1480 eti.waitingListSpots AS ticket_waiting_list_spots,
1481 eti.dateRanges AS ticket_dateRanges,
1482 eti.translations AS ticket_translations,
1483 ';
1484
1485 $joins .= "
1486 LEFT JOIN {$ticketsTable} eti ON eti.eventId = e.id
1487 ";
1488 }
1489
1490 if (!empty($criteria['fetchEventsTags'])) {
1491 $tagsTable = EventsTagsTable::getTableName();
1492
1493 $fields .= '
1494 eta.id AS event_tagId,
1495 eta.name AS event_tagName,
1496 ';
1497
1498 $joins .= "
1499 LEFT JOIN {$tagsTable} eta ON eta.eventId = e.id
1500 ";
1501 }
1502
1503 if (!empty($criteria['fetchEventsImages'])) {
1504 $galleriesTable = GalleriesTable::getTableName();
1505
1506 $fields .= '
1507 eg.id AS gallery_id,
1508 eg.pictureFullPath AS gallery_picture_full,
1509 eg.pictureThumbPath AS gallery_picture_thumb,
1510 eg.position AS gallery_position,
1511 ';
1512
1513 $joins .= "
1514 LEFT JOIN {$galleriesTable} eg ON eg.entityId = e.id AND eg.entityType = 'event'
1515 ";
1516 }
1517
1518 if (!empty($criteria['fetchEventsProviders'])) {
1519 $eventsProvidersTable = EventsProvidersTable::getTableName();
1520
1521 $usersTable = UsersTable::getTableName();
1522
1523 $joins .= "
1524 LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id
1525 LEFT JOIN {$usersTable} pu ON pu.id = epr.userId
1526 ";
1527
1528 $fields .= '
1529 pu.id AS provider_id,
1530 pu.firstName AS provider_firstName,
1531 pu.lastName AS provider_lastName,
1532 pu.email AS provider_email,
1533 pu.note AS provider_note,
1534 pu.description AS provider_description,
1535 pu.phone AS provider_phone,
1536 pu.gender AS provider_gender,
1537 pu.pictureFullPath AS provider_pictureFullPath,
1538 pu.pictureThumbPath AS provider_pictureThumbPath,
1539 pu.translations AS provider_translations,
1540 pu.timeZone AS provider_timeZone,
1541 ';
1542 }
1543
1544 $fields .= "
1545 e.id AS event_id,
1546 e.name AS event_name,
1547 e.status AS event_status,
1548 e.bookingOpens AS event_bookingOpens,
1549 e.bookingCloses AS event_bookingCloses,
1550 e.bookingOpensRec AS event_bookingOpensRec,
1551 e.bookingClosesRec AS event_bookingClosesRec,
1552 e.ticketRangeRec AS event_ticketRangeRec,
1553 e.recurringCycle AS event_recurringCycle,
1554 e.recurringOrder AS event_recurringOrder,
1555 e.recurringInterval AS event_recurringInterval,
1556 e.recurringMonthly AS event_recurringMonthly,
1557 e.monthlyDate AS event_monthlyDate,
1558 e.monthlyOnRepeat AS event_monthlyOnRepeat,
1559 e.monthlyOnDay AS event_monthlyOnDay,
1560 e.recurringUntil AS event_recurringUntil,
1561 e.bringingAnyone AS event_bringingAnyone,
1562 e.bookMultipleTimes AS event_bookMultipleTimes,
1563 e.maxCapacity AS event_maxCapacity,
1564 e.maxCustomCapacity AS event_maxCustomCapacity,
1565 e.maxExtraPeople AS event_maxExtraPeople,
1566 e.price AS event_price,
1567 e.description AS event_description,
1568 e.color AS event_color,
1569 e.show AS event_show,
1570 e.notifyParticipants AS event_notifyParticipants,
1571 e.locationId AS event_locationId,
1572 e.customLocation AS event_customLocation,
1573 e.parentId AS event_parentId,
1574 e.created AS event_created,
1575 e.settings AS event_settings,
1576 e.zoomUserId AS event_zoomUserId,
1577 e.organizerId AS event_organizerId,
1578 e.translations AS event_translations,
1579 e.deposit AS event_deposit,
1580 e.depositPayment AS event_depositPayment,
1581 e.depositPerPerson AS event_depositPerPerson,
1582 e.fullPayment AS event_fullPayment,
1583 e.customPricing AS event_customPricing,
1584 e.closeAfterMin AS event_closeAfterMin,
1585 e.closeAfterMinBookings AS event_closeAfterMinBookings,
1586 e.aggregatedPrice AS event_aggregatedPrice
1587 ";
1588
1589 if (!empty($ids)) {
1590 $queryIds = [];
1591
1592 foreach ($ids as $index => $value) {
1593 $param = ':id' . $index;
1594
1595 $queryIds[] = $param;
1596
1597 $params[$param] = $value;
1598 }
1599
1600 $where[] = 'e.id IN (' . implode(', ', $queryIds) . ')';
1601 }
1602
1603 $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';
1604
1605 try {
1606 $statement = $this->connection->prepare(
1607 "SELECT
1608 {$fields}
1609 FROM {$this->table} e
1610 {$joins}
1611 {$where}
1612 {$orderBy}"
1613 );
1614
1615 $statement->execute($params);
1616
1617 $rows = $statement->fetchAll();
1618 } catch (\Exception $e) {
1619 throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e);
1620 }
1621
1622 return call_user_func([static::FACTORY, 'createCollection'], $rows);
1623 }
1624
1625 /**
1626 * @param array $criteria
1627 *
1628 * @return Collection
1629 * @throws QueryExecutionException
1630 * @throws InvalidArgumentException
1631 */
1632 public function getBookingsByCriteria($criteria = [])
1633 {
1634 $params = [];
1635
1636 $where = [];
1637
1638 $fields = '';
1639
1640 $joins = '';
1641
1642 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
1643
1644 $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName();
1645
1646 $customerBookingsTable = CustomerBookingsTable::getTableName();
1647
1648 if (!empty($criteria['fetchApprovedBookings'])) {
1649 $where[] = "cb.status = 'approved'";
1650 }
1651
1652 if (!empty($criteria['customerBookingId'])) {
1653 $params[':customerBookingId'] = $criteria['customerBookingId'];
1654
1655 $where[] = 'cb.id = :customerBookingId';
1656 }
1657
1658 if (!empty($criteria['fetchBookingsPayments'])) {
1659 $paymentsTable = PaymentsTable::getTableName();
1660
1661 $fields .= '
1662 p.id AS payment_id,
1663 p.amount AS payment_amount,
1664 p.dateTime AS payment_dateTime,
1665 p.created AS payment_created,
1666 p.status AS payment_status,
1667 p.gateway AS payment_gateway,
1668 p.gatewayTitle AS payment_gatewayTitle,
1669 p.transactionId AS payment_transactionId,
1670 p.data AS payment_data,
1671 p.wcOrderId AS payment_wcOrderId,
1672 p.wcOrderItemId AS payment_wcOrderItemId,
1673 p.invoiceNumber AS payment_invoiceNumber,
1674 ';
1675
1676 $joins .= "
1677 LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id
1678 ";
1679 }
1680
1681 if (!empty($criteria['fetchBookingsCoupons'])) {
1682 $couponsTable = CouponsTable::getTableName();
1683
1684 $fields .= '
1685 c.id AS coupon_id,
1686 c.code AS coupon_code,
1687 c.discount AS coupon_discount,
1688 c.deduction AS coupon_deduction,
1689 c.limit AS coupon_limit,
1690 c.customerLimit AS coupon_customerLimit,
1691 c.status AS coupon_status,
1692 ';
1693
1694 $joins .= "
1695 LEFT JOIN {$couponsTable} c ON c.id = cb.couponId
1696 ";
1697 }
1698
1699 if (!empty($criteria['fetchBookingsUsers'])) {
1700 $usersTable = UsersTable::getTableName();
1701
1702 $fields .= '
1703 cu.id AS customer_id,
1704 cu.type AS customer_type,
1705 cu.firstName AS customer_firstName,
1706 cu.lastName AS customer_lastName,
1707 cu.email AS customer_email,
1708 cu.note AS customer_note,
1709 cu.phone AS customer_phone,
1710 cu.gender AS customer_gender,
1711 cu.birthday AS customer_birthday,
1712 ';
1713
1714 $joins .= "
1715 INNER JOIN {$usersTable} cu ON cu.id = cb.customerId
1716 ";
1717 }
1718
1719 if (!empty($criteria['fetchBookingsTickets'])) {
1720 $bookingsTicketsTable = CustomerBookingToEventsTicketsTable::getTableName();
1721
1722 $fields .= '
1723 cbt.id AS booking_ticket_id,
1724 cbt.eventTicketId AS booking_ticket_eventTicketId,
1725 cbt.price AS booking_ticket_price,
1726 cbt.persons AS booking_ticket_persons,
1727 ';
1728
1729 $joins .= "
1730 LEFT JOIN {$bookingsTicketsTable} cbt ON cbt.customerBookingId = cb.id
1731 ";
1732 }
1733
1734 $fields .= '
1735 ep.eventId AS eventId,
1736 cb.id AS booking_id,
1737 cb.appointmentId AS booking_appointmentId,
1738 cb.customerId AS booking_customerId,
1739 cb.status AS booking_status,
1740 cb.price AS booking_price,
1741 cb.tax AS booking_tax,
1742 cb.persons AS booking_persons,
1743 cb.couponId AS booking_couponId,
1744 cb.customFields AS booking_customFields,
1745 cb.info AS booking_info,
1746 cb.utcOffset AS booking_utcOffset,
1747 cb.token AS booking_token,
1748 cb.aggregatedPrice AS booking_aggregatedPrice,
1749 cb.tax AS booking_tax
1750 ';
1751
1752 if (!empty($criteria['ids'])) {
1753 $queryIds = [];
1754
1755 foreach ($criteria['ids'] as $index => $value) {
1756 $param = ':id' . $index;
1757
1758 $queryIds[] = $param;
1759
1760 $params[$param] = $value;
1761 }
1762
1763 $where[] = 'ep.eventId IN (' . implode(', ', $queryIds) . ')';
1764 }
1765
1766 $where = $where ? 'WHERE ' . implode(' AND ', $where) : '';
1767
1768 try {
1769 $statement = $this->connection->prepare(
1770 "SELECT
1771 {$fields}
1772 FROM {$eventsPeriodsTable} ep
1773 INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id
1774 INNER JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId
1775 {$joins}
1776 {$where}
1777 ORDER BY cb.id"
1778 );
1779
1780 $statement->execute($params);
1781
1782 $rows = $statement->fetchAll();
1783 } catch (\Exception $e) {
1784 throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e);
1785 }
1786
1787 $reformattedData = [];
1788
1789 foreach ($rows as $row) {
1790 if (empty($reformattedData[$row['eventId']])) {
1791 $reformattedData[$row['eventId']] = [];
1792 }
1793
1794 $reformattedData[$row['eventId']][] = $row;
1795 }
1796
1797 $result = new Collection();
1798
1799 foreach ($reformattedData as $eventId => $bookingsData) {
1800 $reformattedBookingsData = CustomerBookingFactory::reformat($bookingsData);
1801
1802 $eventBookings = new Collection();
1803
1804 foreach ($reformattedBookingsData as $bookingId => $data) {
1805 $eventBookings->addItem(CustomerBookingFactory::create($data), $bookingId);
1806 }
1807
1808 $result->addItem($eventBookings, $eventId);
1809 }
1810
1811 return $result;
1812 }
1813
1814
1815 /**
1816 * @param Event $event
1817 * @param array $booking
1818 * @param array $limitPerCustomer
1819 * @return int
1820 * @throws QueryExecutionException
1821 * @throws InvalidArgumentException
1822 */
1823 public function getRelevantBookingsCount($event, $booking, $limitPerCustomer)
1824 {
1825 $eventsPeriodsTable = EventsPeriodsTable::getTableName();
1826
1827 $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName();
1828
1829 $customerBookingsTable = CustomerBookingsTable::getTableName();
1830
1831 $params = [
1832 ':customerId' => $booking['customerId']
1833 ];
1834
1835 $paymentTableJoin = '';
1836 $compareToDate = 'ep.periodStart';
1837
1838 if ($limitPerCustomer['from'] === 'bookingDate') {
1839 $eventStartDate = (clone $event->getPeriods()->getItems()[0]->getPeriodStart()->getValue())->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i');
1840 } else {
1841 $paymentTableJoin = 'INNER JOIN ' . PaymentsTable::getTableName() . ' p ON p.customerBookingId = cb.id';
1842 $eventStartDate = DateTimeService::getNowDateTimeObject()->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i');
1843 $compareToDate = 'p.created';
1844 }
1845
1846 $intervalString = "interval " . $limitPerCustomer['period'] . " " . $limitPerCustomer['timeFrame'];
1847
1848 $where = "(STR_TO_DATE('". $eventStartDate ."', '%Y-%m-%d %H:%i:%s') BETWEEN " .
1849 "(" . $compareToDate . " - " . $intervalString . " + interval 1 second)" .
1850 " AND (".
1851 $compareToDate . " + " . $intervalString . " - interval 1 second))";
1852
1853 try {
1854 $statement = $this->connection->prepare(
1855 "SELECT COUNT(DISTINCT cb.id) AS count FROM
1856 {$this->table} e
1857 INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id
1858 INNER JOIN {$customerBookingsEventsPeriods} cbep ON cbep.eventPeriodId = ep.id
1859 INNER JOIN {$customerBookingsTable} cb ON cb.id = cbep.customerBookingId
1860 {$paymentTableJoin}
1861 WHERE cb.customerId = :customerId AND {$where} AND e.status = 'approved' AND cb.status = 'approved'
1862 "
1863 );
1864
1865 $statement->execute($params);
1866
1867 $rows = $statement->fetch()['count'];
1868 } catch (\Exception $e) {
1869 throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e);
1870 }
1871
1872 return $rows;
1873 }
1874 }
1875