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