File manager - Edit - /home/premiey/www/wp-includes/images/media/Infrastructure.tar
Back
Connection.php 0000666 00000004456 15165376447 0007413 0 ustar 00 <?php /** * @author Slavko Babic * @date 2017-08-21 */ namespace AmeliaBooking\Infrastructure; use mysqli; use \PDO; /** * Class Connection * * @package Infrastructure */ abstract class Connection { /** @var string $username */ protected $username; /** @var string $password */ protected $password; /** @var string $charset */ protected $charset; /** @var PDO|mysqli $handler */ protected $handler; /** @var int port */ protected $port; /** @var string $host */ protected $host; /** @var string $name */ protected $database; /** @var string $socket */ protected $socket; /** @var string $socketPath */ protected $socketPath; /** * Connection constructor. * * @param string $database * @param string $username * @param string $password * @param string $host * @param int $port * @param string $charset */ public function __construct( $host, $database, $username, $password, $charset = 'utf8', $port = 3306 ) { $this->database = (string)$database; $this->username = (string)$username; $this->password = (string)$password; $this->host = $this->socket = (string)$host; $this->port = (int)$port; $this->charset = (string)$charset; } /** * @return PDO|mysqli */ public function __invoke() { return $this->handler; } /** * */ protected function socketHandler() { if (strpos($this->socket, ':') === false) { $this->host = $this->socket; return; } $data = explode(':', $this->socket); $this->host = $data[0]; if (isset($data[1]) && is_numeric($data[1]) && (int)$data[1]) { $this->port = $data[1]; } elseif (isset($data[1]) && strpos($data[1], '/') !== false) { $position = strpos($data[1], '/'); if ($position === 0) { $this->socketPath = $data[1]; } else { $this->port = substr($data[1], 0, $position); $this->socketPath = substr($data[1], $position); } } elseif (isset($data[1]) && (int)$data[1]) { $this->port = $data[1]; } } } Services/Notification/MailerFactory.php 0000666 00000003147 15165376447 0014262 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Services\Notification; use AmeliaBooking\Domain\Services\Settings\SettingsService; /** * Class MailerFactory * * @package AmeliaBooking\Infrastructure\Services\Notification */ class MailerFactory { /** * Mailer constructor. * * @param SettingsService $settingsService * * @return MailgunService|PHPMailService|SMTPService|WpMailService */ public static function create(SettingsService $settingsService) { $settings = $settingsService->getCategorySettings('notifications'); if ($settings['mailService'] === 'smtp') { return new SMTPService( $settings['senderEmail'], $settings['senderName'], $settings['smtpHost'], $settings['smtpPort'], $settings['smtpSecure'], $settings['smtpUsername'], $settings['smtpPassword'] ); } if ($settings['mailService'] === 'mailgun') { return new MailgunService( $settings['senderEmail'], $settings['senderName'], $settings['mailgunApiKey'], $settings['mailgunDomain'], $settings['mailgunEndpoint'] ); } if ($settings['mailService'] === 'wp_mail') { return new WpMailService( $settings['senderEmail'], $settings['senderName'] ); } return new PHPMailService( $settings['senderEmail'], $settings['senderName'] ); } } Services/Notification/PHPMailService.php 0000666 00000003175 15165376447 0014275 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Services\Notification; use AmeliaBooking\Domain\Services\Notification\AbstractMailService; use AmeliaBooking\Domain\Services\Notification\MailServiceInterface; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; /** * Class PHPMailService */ class PHPMailService extends AbstractMailService implements MailServiceInterface { /** @noinspection MoreThanThreeArgumentsInspection */ /** * @param $to * @param $subject * @param $body * @param array $bccEmails * @param array $attachments * * @return mixed|void * @throws Exception * @SuppressWarnings(PHPMD) */ public function send($to, $subject, $body, $bccEmails = [], $attachments = []) { $mail = new PHPMailer; try { //Recipients $mail->setFrom($this->from, $this->fromName); $mail->addAddress($to); $mail->addReplyTo($this->from); foreach ($bccEmails as $bccEmail) { $mail->addBCC($bccEmail); } foreach ($attachments as $attachment) { $mail->addStringAttachment($attachment['content'], $attachment['name'], 'base64', $attachment['type']); } //Content $mail->CharSet = 'UTF-8'; $mail->isHTML(); $mail->Subject = $subject; $mail->Body = $body; $mail->send(); } catch (Exception $e) { throw $e; } } } Services/Notification/WpMailService.php 0000666 00000003360 15165376447 0014230 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Services\Notification; use AmeliaBooking\Domain\Services\Notification\AbstractMailService; use AmeliaBooking\Domain\Services\Notification\MailServiceInterface; /** * Class WpMailService */ class WpMailService extends AbstractMailService implements MailServiceInterface { /** * WpMailService constructor. * * @param $from * @param $fromName */ public function __construct($from, $fromName) { parent::__construct($from, $fromName); } /** @noinspection MoreThanThreeArgumentsInspection */ /** * @param $to * @param $subject * @param $body * @param array $bccEmails * @param array $attachments * * @return mixed|void * @SuppressWarnings(PHPMD) */ public function send($to, $subject, $body, $bccEmails = [], $attachments = []) { $content = ['Content-Type: text/html; charset=UTF-8','From: ' . $this->fromName . ' <' . $this->from . '>']; if ($bccEmails) { $content[] = 'Bcc:' . implode(', ', $bccEmails); } $attachmentsLocations = []; foreach ($attachments as $attachment) { if (!empty($attachment['content']) && ($tmpFile = tempnam(sys_get_temp_dir(), 'cal_')) !== false && file_put_contents($tmpFile, $attachment['content']) !== false && @rename($tmpFile, $tmpFile .= '.ics') !== false ) { $attachmentsLocations[] = $tmpFile; } } wp_mail($to, $subject, $body, $content, $attachmentsLocations); } } Services/Frontend/LessParserService.php 0000666 00000003703 15165376447 0014254 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Services\Frontend; use AmeliaBooking\Domain\Services\Settings\SettingsService; use Exception; use Less_Exception_Parser; use Less_Parser; /** * Class LessParserService */ class LessParserService { /** @var string */ private $inputCssScript; /** @var string */ private $outputPath; /** @var SettingsService */ private $settingsService; /** * LessParserService constructor. * * @param string $inputCssScript * @param string $outputPath * @param SettingsService $settingsService */ public function __construct($inputCssScript, $outputPath, $settingsService) { $this->inputCssScript = $inputCssScript; $this->outputPath = $outputPath; $this->settingsService = $settingsService; } /** * @param array $data * * @return string * @throws Exception * @throws Less_Exception_Parser */ public function compileAndSave($data) { $parser = new Less_Parser(); $parser->parseFile($this->inputCssScript); $parser->ModifyVars($data); !is_dir($this->outputPath) && !mkdir($this->outputPath, 0755, true) && !is_dir($this->outputPath); $hash = $this->generateRandomString(); file_put_contents($this->outputPath . '/amelia-booking.' . $hash . '.css', $parser->getCss()); return $hash; } /** * @param int $length * * @return false|string */ public function generateRandomString($length = 10) { return substr( str_shuffle( str_repeat( $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)) ) ), 1, $length ); } } Common/Container.php 0000666 00000003444 15165376447 0010462 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Common; use AmeliaBooking\Domain\Repository\User\UserRepositoryInterface; use AmeliaBooking\Infrastructure\Connection; /** * Class Container * * @package AmeliaBooking\Infrastructure\Common */ final class Container extends \Slim\Container { /** * @return Connection * @throws \Interop\Container\Exception\ContainerException */ public function getDatabaseConnection() { return $this->get('app.connection'); } /** * @return UserRepositoryInterface * @throws \Interop\Container\Exception\ContainerException */ public function getUserRepository() { return $this->get('domain.users.repository'); } /** * Get the command bus * * @return mixed * @throws \Interop\Container\Exception\ContainerException */ public function getCommandBus() { return $this->get('command.bus'); } /** * Get the event bus * * @return mixed * @throws \Interop\Container\Exception\ContainerException */ public function getEventBus() { return $this->get('domain.event.bus'); } /** * Get the Permissions domain service * * @throws \Interop\Container\Exception\ContainerException */ public function getPermissionsService() { return $this->get('domain.permissions.service'); } /** * @return mixed * @throws \Interop\Container\Exception\ContainerException */ public function getMailerService() { return $this->get('application.mailer'); } /** * @return mixed * @throws \Interop\Container\Exception\ContainerException */ public function getSettingsService() { return $this->get('domain.settings.service'); } } Common/Exceptions/NotFoundException.php 0000666 00000001063 15165376447 0014267 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Common\Exceptions; use Exception; /** * Class NotFoundException * * @package AmeliaBooking\Infrastructure\Common\Exceptions */ class NotFoundException extends \Exception { /** * NotFoundException constructor. * * @param string $message * @param int $code * @param Exception|null $previous */ public function __construct($message = 'not_found', $code = 0, Exception $previous = null) { parent::__construct($message, $code, $previous); } } Common/Exceptions/QueryExecutionException.php 0000666 00000001331 15165376447 0015522 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Common\Exceptions; use Exception; /** * Class QueryExecutionException * * @package AmeliaBooking\Infrastructure\Common\Exceptions */ class QueryExecutionException extends \Exception { /** * QueryExecutionException constructor. * * @param string $message * @param int $code * @param Exception|null $previous */ public function __construct($message = 'Query Execution Error', $code = 0, Exception $previous = null) { if (!is_int($code)) { $message .= $previous ? ' ' . $previous->getMessage() : ''; $code = 0; } parent::__construct($message, $code, $previous); } } WP/Translations/FrontendStrings.php 0000666 00000240714 15165376447 0013453 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\Translations; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; /** * Class FrontendStrings * * @package AmeliaBooking\Infrastructure\WP\Translations * * @phpcs:disable */ class FrontendStrings { /** @var array */ private static $settings; /** * Set Settings * * @return array|mixed */ public static function getLabelsFromSettings() { if (!self::$settings) { self::$settings = new SettingsService(new SettingsStorage()); } if (self::$settings->getSetting('labels', 'enabled') === true) { $labels = self::$settings->getCategorySettings('labels'); unset($labels['enabled']); return $labels; } return []; } /** * Return all strings for frontend * * @return array */ public static function getAllStrings() { return array_merge( self::getCommonStrings(), self::getBookingStrings(), self::getBookableStrings(), self::getCatalogStrings(), self::getSearchStrings(), self::getLabelsFromSettings(), self::getEventStrings(), self::getCabinetStrings() ); } /** * Returns the array for the bookable strings * * @return array */ public static function getBookableStrings() { return [ 'allow_customers_to_pay_total' => __('Check this option if you want your<br> customers to have the option to choose<br> whether they will pay a full amount<br> or just a deposit. If unchecked,<br> customers will only have deposit<br> as a payment option.', 'wpamelia'), 'deposit_by_the_number_of_people' => __('Check this option if you want the deposit<br> amount to be multiplied by the number<br> of people that customers add in the<br> "Bringing anyone with you" section.', 'wpamelia'), 'allow_total_amount' => __('Allow customers to pay total appointment amount', 'wpamelia'), 'allow_total_event_amount' => __('Allow customers to pay total event amount', 'wpamelia'), 'deposit' => __('Deposit', 'wpamelia'), 'pay_now' => __('(Paying now)', 'wpamelia'), 'pay_later' => __('Left to pay', 'wpamelia'), 'deposit_amount' => __('Deposit amount', 'wpamelia'), 'deposit_enabled' => __('Enable deposit payment', 'wpamelia'), 'deposit_payment' => __('Deposit type', 'wpamelia'), 'deposit_payment_tooltip' => __('Percentage deposit will be calculated on the total booking price<br>and fixed amount can be multiplied by the number of people or stay fixed on the total booking price.', 'wpamelia'), 'deposit_info' => __('Remaining of total amount will be paid on site.', 'wpamelia'), 'deposit_per_person' => __('Multiply deposit amount by the number of people in one booking', 'wpamelia'), 'fixed_amount' => __('Fixed amount', 'wpamelia'), 'percentage' => __('Percentage', 'wpamelia'), ]; } /** * Returns the array of the common frontend strings * * @return array */ public static function getCommonStrings() { return [ 'add_coupon' => __('Add Coupon', 'wpamelia'), 'add_to_calendar' => __('Add to Calendar', 'wpamelia'), 'and' => __('and'), 'no_package_services' => __('It seems like there are no available or visible services assigned to the packages, at this moment.'), 'no_services_employees' => __('It seems like there are no employees or services created, or no employees are assigned to the service, at this moment.'), 'add_services_employees' => __('If you are the admin of this page, see how to'), 'add_services_url' => __('Add services'), 'add_employees_url' => __('employees.'), 'all_slots_selected' => __('All slots are selected', 'wpamelia'), 'appointment' => __('Appointment', 'wpamelia'), 'appointments' => __('Appointments', 'wpamelia'), 'appointment_info' => __('Appointment Info', 'wpamelia'), 'at' => __('at', 'wpamelia'), 'back' => __('Back', 'wpamelia'), 'base_price_colon' => __('Base Price:', 'wpamelia'), 'book' => __('Book', 'wpamelia'), 'booking_completed_approved' => __('Thank you! Your booking is completed.', 'wpamelia'), 'booking_completed_email' => __('An email with details of your booking has been sent to you.', 'wpamelia'), 'booking_completed_pending' => __('Thank you! Your booking is completed and now is pending confirmation.', 'wpamelia'), 'bookings_limit_reached' => __('Maximum bookings reached', 'wpamelia'), 'cancel' => __('Cancel', 'wpamelia'), 'canceled' => __('Canceled', 'wpamelia'), 'capacity_colon' => __('Capacity:', 'wpamelia'), 'client_time_colon' => __('Client Time:', 'wpamelia'), 'closed' => __('Closed', 'wpamelia'), 'expired' => __('Expired', 'wpamelia'), 'full' => __('Full', 'wpamelia'), 'upcoming' => __('Upcoming', 'wpamelia'), 'confirm' => __('Confirm', 'wpamelia'), 'congratulations' => __('Congratulations', 'wpamelia'), 'coupon_invalid' => __('This coupon is not valid anymore', 'wpamelia'), 'coupon_expired' => __('This coupon has expired', 'wpamelia'), 'coupon_missing' => __('Please enter coupon', 'wpamelia'), 'coupon_send_text' => __('You can use this coupon for next booking: ', 'wpamelia'), 'coupon_unknown' => __('The coupon you entered is not valid', 'wpamelia'), 'coupon_used' => __('Used coupon', 'wpamelia'), 'credit_card' => __('Credit Card', 'wpamelia'), 'mollie' => __('Mollie', 'wpamelia'), 'credit_or_debit_card_colon' => __('Credit or debit card:', 'wpamelia'), 'custom_fields' => __('Custom Fields', 'wpamelia'), 'customer' => __('Customer', 'wpamelia'), 'customer_already_booked_app' => __('You have already booked this appointment', 'wpamelia'), 'customer_already_booked_ev' => __('You have already booked this event', 'wpamelia'), 'date' => __('Date', 'wpamelia'), 'date_colon' => __('Date:', 'wpamelia'), 'discount_amount_colon' => __('Discount', 'wpamelia'), 'duration_colon' => __('Duration:', 'wpamelia'), 'email_colon' => __('Email:', 'wpamelia'), 'email_exist_error' => __('Email already exists with different name. Please check your name.', 'wpamelia'), 'email_not_sent_error' => __('Unfortunately a server error occurred and your email was not sent.', 'wpamelia'), 'email_placeholder' => __('example@mail.com', 'wpamelia'), 'employee' => __('employee', 'wpamelia'), 'employees' => __('employees', 'wpamelia'), 'enter_email_warning' => __('Please enter email', 'wpamelia'), 'enter_first_name_warning' => __('Please enter first name', 'wpamelia'), 'enter_last_name_warning' => __('Please enter last name', 'wpamelia'), 'enter_phone_warning' => __('Please enter phone number', 'wpamelia'), 'enter_valid_email_warning' => __('Please enter a valid email address', 'wpamelia'), 'enter_valid_phone_warning' => __('Please enter a valid phone number', 'wpamelia'), 'event_info' => __('Event Info', 'wpamelia'), 'event_booking_unavailable' => __('Event booking is unavailable', 'wpamelia'), 'extras_costs_colon' => __('Extras Cost:', 'wpamelia'), 'file_upload' => __('Drop file here or click to upload', 'wpamelia'), 'file_upload_error' => __('Please upload the file', 'wpamelia'), 'finish_appointment' => __('Finish', 'wpamelia'), 'first_name_colon' => __('First Name:', 'wpamelia'), 'forbidden_file_upload' => __('This file is forbidden for upload', 'wpamelia'), 'outlook_calendar' => __('Outlook Calendar', 'wpamelia'), 'h' => __('h', 'wpamelia'), 'incomplete_cvc' => __('Your card\'s security code is incomplete', 'wpamelia'), 'incomplete_expiry' => __('Your card\'s expiration date is incomplete', 'wpamelia'), 'incomplete_number' => __('Your card number is incomplete', 'wpamelia'), 'incomplete_zip' => __('Your postal code is incomplete', 'wpamelia'), 'invalid_expiry_year_past' => __('Your card\'s expiration year is in the past', 'wpamelia'), 'invalid_number' => __('Your card number is invalid', 'wpamelia'), 'last_name_colon' => __('Last Name:', 'wpamelia'), 'location' => __('Location', 'wpamelia'), 'location_colon' => __('Location:', 'wpamelia'), 'maximum_capacity_reached' => __('Maximum capacity is reached', 'wpamelia'), 'min' => __('min', 'wpamelia'), 'name' => __('Name', 'wpamelia'), 'no' => __('No', 'wpamelia'), 'number_of_additional_persons' => __('Number of Additional People:', 'wpamelia'), 'on_site' => __('On-site', 'wpamelia'), 'oops' => __('Oops...'), 'on_line' => __('Online', 'wpamelia'), 'open' => __('Open', 'wpamelia'), 'opened' => __('Opened', 'wpamelia'), 'out_of' => __('out of', 'wpamelia'), 'package' => __('Package', 'wpamelia'), 'package_info' => __('Package Info', 'wpamelia'), 'paid' => __('Paid', 'wpamelia'), 'partially_paid' => __('Partially Paid', 'wpamelia'), 'pay_pal' => __('PayPal', 'wpamelia'), 'payment_error' => __('Sorry, there was an error processing your payment. Please try again later.', 'wpamelia'), 'unavailable_booking_error' => __('Please check if services and employees are created and connected to each other.', 'wpamelia'), 'payment_error_default' => __('Payment error', 'wpamelia'), 'payment_link_error' => __('Sorry, there was an error creating a payment link. Please try again later.', 'wpamelia'), 'payment_method_colon' => __('Payment Method:', 'wpamelia'), 'payment_type_colon' => __('Payment Type:', 'wpamelia'), 'payment_btn_on_site' => __('On-Site', 'wpamelia'), 'payment_btn_stripe' => __('Stripe', 'wpamelia'), 'payment_btn_mollie' => __('Online', 'wpamelia'), 'persons' => __('people', 'wpamelia'), 'phone' => __('Phone', 'wpamelia'), 'phone_colon' => __('Phone:', 'wpamelia'), 'please_wait' => __('Please Wait', 'wpamelia'), 'price_colon' => __('Price:', 'wpamelia'), 'razorpay' => __('Razorpay', 'wpamelia'), 'recaptcha_error' => __('Please confirm you are not a robot', 'wpamelia'), 'recaptcha_invalid_error' => __('Verification expired. Please try again.', 'wpamelia'), 'required_field' => __('This field is required', 'wpamelia'), 'select_calendar' => __('Select Calendar', 'wpamelia'), 'service' => __('service', 'wpamelia'), 'services' => __('Services', 'wpamelia'), 'services_lower' => __('services', 'wpamelia'), 'stripe' => __('Stripe', 'wpamelia'), 'subtotal_colon' => __('Subtotal:', 'wpamelia'), 'text_mode' => __('Text Mode', 'wpamelia'), 'html_mode' => __('HTML Mode', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'time_colon' => __('Local Time:', 'wpamelia'), 'time_slot_unavailable' => __('Time slot is unavailable', 'wpamelia'), 'time_slot_unavailable_plural' => __('Time slots are unavailable', 'wpamelia'), 'package_booking_unavailable' => __('Booking is unavailable', 'wpamelia'), 'total_cost_colon' => __('Total Cost:', 'wpamelia'), 'total_number_of_persons' => __('Total Number of People:', 'wpamelia'), 'waiting_for_payment' => __('Waiting for payment', 'wpamelia'), 'wc' => __('On-line', 'wpamelia'), 'wc_appointment_is_removed' => __('Appointment is removed from the cart.', 'wpamelia'), 'wc_appointment_remove' => __('On-line', 'wpamelia'), 'wc_error' => __('Sorry, there was an error while adding booking to WooCommerce cart.', 'wpamelia'), 'wc_product_name' => __('Appointment', 'wpamelia'), 'zoom_join' => __('Join Zoom Meeting', 'wpamelia'), 'zoom_start' => __('Start Zoom Meeting', 'wpamelia'), 'google_meet_join' => __('Join Google Meeting', 'wpamelia'), 'day' => __('Day', 'wpamelia'), 'days' => __('Days', 'wpamelia'), 'week' => __('Week', 'wpamelia'), 'weeks' => __('Weeks', 'wpamelia'), 'month' => __('Month', 'wpamelia'), 'months' => __('Months', 'wpamelia'), 'year' => __('Year', 'wpamelia'), 'years' => __('Years', 'wpamelia'), 'free' => __('Free', 'wpamelia'), ]; } /** * Returns the array of the frontend strings for the search shortcode * * @return array */ public static function getSearchStrings() { return [ 'appointment_date_colon' => __('Appointment Date:', 'wpamelia'), 'book_package' => __('Book Package', 'wpamelia'), 'bringing_anyone' => __('Bringing anyone with you?', 'wpamelia'), 'enter_appointment_date' => __('Please enter appointment date...', 'wpamelia'), 'from' => __('From', 'wpamelia'), 'name_asc' => __('Name Ascending', 'wpamelia'), 'name_desc' => __('Name Descending', 'wpamelia'), 'next' => __('Next', 'wpamelia'), 'no_results_found' => __('No results found...', 'wpamelia'), 'of' => __('of', 'wpamelia'), 'price_asc' => __('Price Ascending', 'wpamelia'), 'price_desc' => __('Price Descending', 'wpamelia'), 'refine_search' => __('Please refine your search criteria', 'wpamelia'), 'results' => __('results', 'wpamelia'), 'search' => __('Search...', 'wpamelia'), 'search_filters' => __('Search Filters', 'wpamelia'), 'search_results' => __('Search Results', 'wpamelia'), 'select' => __('Select', 'wpamelia'), 'select_appointment_time' => __('Select the Appointment Time', 'wpamelia'), 'select_extras' => __('Select the Extras you\'d like', 'wpamelia'), 'select_location' => __('Select Location', 'wpamelia'), 'showing' => __('Showing', 'wpamelia'), 'time_range_colon' => __('Time Range:', 'wpamelia'), 'to_lower' => __('to', 'wpamelia'), 'to_upper' => __('To', 'wpamelia'), ]; } /** * Returns the array of the frontend strings for the booking shortcode * * @return array */ public static function getBookingStrings() { return [ 'add_extra' => __('Add extra', 'wpamelia'), 'add_people' => __('Number of people that are coming with you.', 'wpamelia'), 'any' => __('Any', 'wpamelia'), 'any_employee' => __('Any Employee', 'wpamelia'), 'book_appointment' => __('Book Appointment', 'wpamelia'), 'bringing_anyone_with_you' => __('Bringing anyone with you?', 'wpamelia'), 'card_number_colon' => __('Card number', 'wpamelia'), 'continue' => __('Continue', 'wpamelia'), 'coupons_used' => __('Coupon Limit Reached', 'wpamelia'), 'coupons_used_description' => __('Number of appointments with applied coupon is', 'wpamelia'), 'disable_popup_blocker' => __('Popup Blocker is enabled! To add your appointment to your calendar, please allow popups and add this site to your exception list.', 'wpamelia'), 'email_address_colon' => __('Email Address', 'wpamelia'), 'employee_information' => __('Employee information', 'wpamelia'), 'employee_information_package' => __('Employee information', 'wpamelia'), 'expires_after' => __('Expires after', 'wpamelia'), 'expires_day' => __('day', 'wpamelia'), 'expires_days' => __('days', 'wpamelia'), 'expires_week' => __('week', 'wpamelia'), 'expires_weeks' => __('weeks', 'wpamelia'), 'expires_month' => __('month', 'wpamelia'), 'expires_months' => __('months', 'wpamelia'), 'expires_at' => __('Expires at', 'wpamelia'), 'expires_date_colon' => __('Expiration date', 'wpamelia'), 'extras_available' => __('Extras available', 'wpamelia'), 'extra_colon' => __('Extra:', 'wpamelia'), 'extra_error' => __('Please select the extra:', 'wpamelia'), 'full_amount_consent' => __('I want to pay full amount', 'wpamelia'), 'get_in_touch' => __('Get in Touch', 'wpamelia'), 'collapse_menu' => __('Collapse menu', 'wpamelia'), 'includes_colon' => __('includes:', 'wpamelia'), 'min_req_extras_colon' => __('Minimum required extras:', 'wpamelia'), 'multiple_locations' => __('Multiple Locations', 'wpamelia'), 'package_available' => __('Available in package', 'wpamelia'), 'package_list_overview' => __('Overview', 'wpamelia'), 'package_discount_text' => __('Save ', 'wpamelia'), 'package_book_service' => __('All services are booked separately.', 'wpamelia'), 'package_book_service_2' => __('This package has', 'wpamelia'), 'package_book_duration' => __('The package is time-limited to', 'wpamelia'), 'package_book_expire' => __('Valid Until:', 'wpamelia'), 'package_book_multiple' => __('Multiple packages purchased.', 'wpamelia'), 'package_book_first_pack_apps' => __('Appointments from the first package expire on:', 'wpamelia'), 'package_book_expiration' => __('Duration:', 'wpamelia'), 'package_book_unlimited' => __('Unlimited', 'wpamelia'), 'package_next_appointment' => __('Add appointment', 'wpamelia'), 'package_next_service' => __('Next Service', 'wpamelia'), 'package_min_book' => __('appointment is required to be booked now.', 'wpamelia'), 'package_min_book_plural' => __('appointments are required to be booked now.', 'wpamelia'), 'payment_protected_policy' => __('Payment protected by policy and powered by', 'wpamelia'), 'payment_type_deposit_only' => __('Deposit only', 'wpamelia'), 'payment_type_full_amount' => __('Whole amount', 'wpamelia'), 'payment_onsite_sentence' => __('The payment will be done on-site.', 'wpamelia'), 'payment_wc_mollie_sentence' => __('You will be redirected to the payment checkout.', 'wpamelia'), 'person_upper' => __('Person', 'wpamelia'), 'persons_upper' => __('People', 'wpamelia'), 'phone_number_colon' => __('Phone Number', 'wpamelia'), 'pick_date_and_time_colon' => __('Pick date & time:', 'wpamelia'), 'please_select' => __('Please select', 'wpamelia'), 'plus_more' => __('+more', 'wpamelia'), 'price_changed_message' => __('This change will lead to a price increase for certain bookings. Do you want payment links to be created?', 'wpamelia'), 'qty_colon' => __('Qty:', 'wpamelia'), 'recurring' => __('Recurring', 'wpamelia'), 'recurring_costs_colon' => __('Recurring Appointments:', 'wpamelia'), 'recurring_appointments' => __('Recurring Appointments', 'wpamelia'), 'recurring_edit' => __('You can edit or delete each appointment', 'wpamelia'), 'recurring_sub_message1' => __('Some of the desired slots are busy. We offered you the nearest time slots instead.', 'wpamelia'), 'recurring_sub_message2' => __('Number of adjusted time slots: ', 'wpamelia'), 'recurring_active' => __('Repeat this appointment', 'wpamelia'), 'recurring_type_daily' => __('Daily', 'wpamelia'), 'recurring_type_weekly' => __('Weekly', 'wpamelia'), 'recurring_type_monthly' => __('Monthly', 'wpamelia'), 'recurring_repeat' => __('Repeat:', 'wpamelia'), 'recurring_every' => __('Every:', 'wpamelia'), 'recurring_until' => __('Until:', 'wpamelia'), 'recurring_every_text' => __('Every', 'wpamelia'), 'recurring_from_text' => __('from', 'wpamelia'), 'recurring_until_text' => __('until', 'wpamelia'), 'recurring_on' => __('On:', 'wpamelia'), 'recurring_each' => __('Each:', 'wpamelia'), 'recurring_substring_on' => __('on', 'wpamelia'), 'recurring_times' => __('Time(s):', 'wpamelia'), 'recurring_date_specific' => __('Specific Date', 'wpamelia'), 'recurring_date_first' => __('First', 'wpamelia'), 'recurring_date_second' => __('Second', 'wpamelia'), 'recurring_date_third' => __('Third', 'wpamelia'), 'recurring_date_fourth' => __('Fourth', 'wpamelia'), 'recurring_date_last' => __('Last', 'wpamelia'), 'recurring_confirm_delete' => __('Do you want to delete this appointment?', 'wpamelia'), 'recurring_changed_message' => __('List of your appointments has changed. Take one more look and continue by clicking the Save button.', 'wpamelia'), 'remaining_amount_colon' => __('Remaining Amount:', 'wpamelia'), 'repeat_appointment' => __('Repeat Appointment', 'wpamelia'), 'repeat_appointment_quest' => __('Do you want to repeat this appointment?', 'wpamelia'), 'select_this_employee' => __('Select this Employee', 'wpamelia'), 'select_this_employee_package' => __('Select this Employee', 'wpamelia'), 'show_more' => __('Show more', 'wpamelia'), 'show_less' => __('Show less', 'wpamelia'), 'summary' => __('Summary', 'wpamelia'), 'total_amount_colon' => __('Total Amount:', 'wpamelia'), 'upload_file_here' => __('Upload file here', 'wpamelia'), 'without_expiration' => __('Without expiration', 'wpamelia'), 'your_name_colon' => __('Your Name', 'wpamelia'), 'service_selection' => __('Service Selection', 'wpamelia'), 'service_colon' => __('Service', 'wpamelia'), 'select_location' => __('Select Location', 'wpamelia'), 'employee_colon' => __('Employee', 'wpamelia'), 'select_employee' => __('Select Employee', 'wpamelia'), 'please_select_service' => __('Please select service', 'wpamelia'), 'please_select_employee' => __('Please select employee', 'wpamelia'), 'please_select_location' => __('Please select location', 'wpamelia'), 'dropdown_category_heading' => __('Category', 'wpamelia'), 'dropdown_items_heading' => __('Service', 'wpamelia'), 'dropdown_empty' => __('No matching data', 'wpamelia'), 'bringing_anyone' => __('Bringing Anyone With You', 'wpamelia'), 'bringing_anyone_title' => __('Bringing anyone with you?', 'wpamelia'), 'bringing_people' => __('Additional people', 'wpamelia'), 'bringing_yes' => __('Yes', 'wpamelia'), 'bringing_no' => __('No', 'wpamelia'), 'package_selection' => __('Package Selection', 'wpamelia'), 'package_heading' => __('Hey, there are special packages with this service, check them out!', 'wpamelia'), 'discount_save' => __('Save', 'wpamelia'), 'separator_or' => __('Or', 'wpamelia'), 'continue_without_package' => __('Skip packages and continue with the selected service', 'wpamelia'), 'extras' => __('Extras', 'wpamelia'), 'extras_card_open' => __('Learn More', 'wpamelia'), 'extras_card_close' => __('Hide', 'wpamelia'), 'date_time' => __('Date & Time', 'wpamelia'), 'date_time_slots_selected' => __('All slots are selected', 'wpamelia'), 'recurring_step' => __('Recurring Appointment', 'wpamelia'), 'recurrence' => __('Recurrence', 'wpamelia'), 'recurrence_choosing_time' => __('Choose time you want to repeat appointment', 'wpamelia'), 'repeat_every' => __('Repeat every', 'wpamelia'), 'recurrence_day' => __('day', 'wpamelia'), 'recurrence_week' => __('week', 'wpamelia'), 'recurrence_month' => __('month', 'wpamelia'), 'recurrence_days' => __('days', 'wpamelia'), 'recurrence_weeks' => __('weeks', 'wpamelia'), 'recurrence_months' => __('months', 'wpamelia'), 'recurrence_repeat_on' => __('Repeat on', 'wpamelia'), 'recurrence_specific_date' => __('Specific date', 'wpamelia'), 'recurrence_first' => __('First', 'wpamelia'), 'recurrence_second' => __('Second', 'wpamelia'), 'recurrence_third' => __('Third', 'wpamelia'), 'recurrence_fourth' => __('Fourth', 'wpamelia'), 'recurrence_last' => __('Last', 'wpamelia'), 'recurrence_ends' => __('Ends', 'wpamelia'), 'recurrence_choose_ends' => __('Choose when the repeating ends', 'wpamelia'), 'recurrence_on' => __('On', 'wpamelia'), 'recurrence_select_date' => __('Select Date', 'wpamelia'), 'recurrence_after' => __('After', 'wpamelia'), 'occurrences' => __('Occurrences', 'wpamelia'), 'appointment_repeats' => __('Appointment Repeats', 'wpamelia'), 'recurrence_every' => __('Every', 'wpamelia'), 'repeats_on' => __('on', 'wpamelia'), 'repeats_at' => __('at', 'wpamelia'), 'repeats_from' => __('from', 'wpamelia'), 'ends_after' => __('Ends after', 'wpamelia'), 'ends_on' => __('Ends on', 'wpamelia'), 'recurring_summary' => __('Recurring Summary', 'wpamelia'), 'recurring_unavailable_slots' => __('Unavailable Time Slots', 'wpamelia'), 'recurring_alert_content' => __('slots you selected are busy. We offered you the nearest time slots instead.', 'wpamelia'), 'recurring_chose_date' => __('Choose Date and Time', 'wpamelia'), 'recurring_delete' => __('Delete', 'wpamelia'), 'number_of_recurrences' => __('Number of Recurrences:', 'wpamelia'), 'recurring_slots_selected' => __('All slots are selected', 'wpamelia'), 'info_step' => __('Your Information', 'wpamelia'), 'enter_first_name' => __('Enter first name', 'wpamelia'), 'enter_last_name' => __('Enter last name', 'wpamelia'), 'enter_email' => __('Enter email', 'wpamelia'), 'enter_phone' => __('Enter phone', 'wpamelia'), 'package_info_step' => __('Package', 'wpamelia'), 'package_info_discount' => __('Save', 'wpamelia'), 'package_info_includes' => __('includes', 'wpamelia'), 'package_info_employees' => __('Employees', 'wpamelia'), 'package_appointment_step' => __('Appointments', 'wpamelia'), 'package_appointment_required' => __('Number of appointments required for booking', 'wpamelia'), 'package_appointment_remaining' => __('The rest of the appointments can be booked later on the Customers panel.', 'wpamelia'), 'package_appointment_employee' => __('Employee', 'wpamelia'), 'package_appointment_any_employee' => __('Any Employee', 'wpamelia'), 'package_appointment_location' => __('Location', 'wpamelia'), 'package_appointment_any_location' => __('Any Location', 'wpamelia'), 'package_appointments' => __('Appointments', 'wpamelia'), 'package_appointments_date' => __('Date and Time', 'wpamelia'), 'package_appointments_select' => __('Select', 'wpamelia'), 'package_appointments_selected' => __('Selected', 'wpamelia'), 'package_appointments_add_more' => __('Add more Appointments', 'wpamelia'), 'package_appointments_slots_selected' => __('All slots are selected', 'wpamelia'), 'package_booking_overview' => __('Booking Overview', 'wpamelia'), 'package_overview_all_selected' => __('All appointments are selected', 'wpamelia'), 'package_overview_selected_later' => __('All appointments will be selected later', 'wpamelia'), 'package_overview_info' => __('Appointment information', 'wpamelia'), 'package_overview_date' => __('Date', 'wpamelia'), 'package_overview_time' => __('Time', 'wpamelia'), 'package_overview_employee' => __('Employee', 'wpamelia'), 'package_overview_location' => __('Location', 'wpamelia'), 'package_info' => __('Package', 'wpamelia'), 'payment_step' => __('Payments', 'wpamelia'), 'coupon' => __('Coupon', 'wpamelia'), 'add_coupon_btn' => __('Add', 'wpamelia'), 'summary_services' => __('Services', 'wpamelia'), 'summary_services_subtotal' => __('Service Subtotal', 'wpamelia'), 'summary_person' => __('person', 'wpamelia'), 'summary_persons' => __('people', 'wpamelia'), 'summary_recurrence' => __('Recurrence', 'wpamelia'), 'summary_recurrences' => __('Recurrences', 'wpamelia'), 'summary_extras' => __('Extras', 'wpamelia'), 'summary_extras_subtotal' => __('Extras Subtotal', 'wpamelia'), 'summary_package' => __('Package', 'wpamelia'), 'summary_event' => __('Event', 'wpamelia'), 'summary_event_subtotal' => __('Event Subtotal', 'wpamelia'), 'paying_now' => __('Paying now', 'wpamelia'), 'paying_later' => __('Paying later', 'wpamelia'), 'appointment_id' => __('Appointment ID', 'wpamelia'), 'event_id' => __('Event ID', 'wpamelia'), 'congrats_total_amount' => __('Total Amount', 'wpamelia'), 'congrats_payment' => __('Payment', 'wpamelia'), 'congrats_date' => __('Date', 'wpamelia'), 'congrats_time' => __('Local Time', 'wpamelia'), 'congrats_service' => __('Service', 'wpamelia'), 'congrats_package' => __('Package', 'wpamelia'), 'congrats_employee' => __('Employee', 'wpamelia'), 'congrats_location' => __('Location', 'wpamelia'), 'congrats_panel' => __('Customer Panel', 'wpamelia'), 'whatsapp_opt_in_text' => __('By entering your phone number you agree to receive messages via WhatsApp', 'wpamelia') ]; } /** * Returns the array of the frontend strings for the event shortcode * * @return array */ public static function getEventStrings() { return [ 'add_ticket_category' => __('Add Pricing Category', 'wpamelia'), 'apply_to_all' => __('Apply this to all recurring events', 'wpamelia'), 'custom_pricing_warning' => __('Custom pricing spots will override Maximum allowed spots value.', 'wpamelia'), 'custom_pricing_date_warning' => __('Set event period first to enable pricing by date range.', 'wpamelia'), 'event' => __('Event', 'wpamelia'), 'events' => __('Events', 'wpamelia'), 'event_about' => __('About this Event', 'wpamelia'), 'event_add_date_range' => __('Add Date Range', 'wpamelia'), 'event_free' => __('Free', 'wpamelia'), 'event_book_now' => __('Book now', 'wpamelia'), 'event_book_event' => __('Book event', 'wpamelia'), 'ev_spot' => __('Spot', 'wpamelia'), 'ev_spots' => __('Spots', 'wpamelia'), 'ev_no_spots' => __('No spots left', 'wpamelia'), 'event_book' => __('Book this event', 'wpamelia'), 'event_book_persons' => __('Number of people', 'wpamelia'), 'event_book_tickets' => __('Number of tickets', 'wpamelia'), 'event_date_range_warning' => __('Date Ranges that are not defined will use default price from ticket category.', 'wpamelia'), 'event_pick_min_date' => __('Show from date', 'wpamelia'), 'event_type' => __('Event Type', 'wpamelia'), 'event_location' => __('Event Location', 'wpamelia'), 'event_status' => __('Event Status', 'wpamelia'), 'event_employee' => __('Event Employee', 'wpamelia'), 'event_capacity' => __('Capacity:', 'wpamelia'), 'event_today' => __('Today', 'wpamelia'), 'event_filters' => __('Filters', 'wpamelia'), 'event_upcoming_events' => __('Upcoming events', 'wpamelia'), 'event_spot' => __('spot left', 'wpamelia'), 'event_spots_left' => __('spots left', 'wpamelia'), 'event_spots' => __('Spots', 'wpamelia'), 'event_no_spots' => __('No spots left', 'wpamelia'), 'event_day' => __('Day', 'wpamelia'), 'event_organizer' => __('Organizer', 'wpamelia'), 'event_organizer_tooltip' => __('Here you can assign yourself to be the organizer of the Google/Outlook event.<br> Otherwise you will be assigned as staff and added as a guest in the event', 'wpamelia'), 'event_schedule' => __('Schedule:', 'wpamelia'), 'event_hosted_by' => __('Hosted by:', 'wpamelia'), 'event_show_less' => __('Show less', 'wpamelia'), 'event_show_more' => __('Show more', 'wpamelia'), 'event_many_people' => __('How many people are coming?', 'wpamelia'), 'event_upcoming_empty' => __('There are no upcoming events for this period', 'wpamelia'), 'event_ticket_name' => __('Ticket name', 'wpamelia'), 'event_tickets' => __('Tickets', 'wpamelia'), 'event_tickets_context' => __('Select the number of tickets that you want to book for each ticket type', 'wpamelia'), 'event_ticket_types' => __('Ticket Types', 'wpamelia'), 'no_events' => __('No results found...', 'wpamelia'), 'event_start' => __('Event Starts', 'wpamelia'), 'event_end' => __('Event Ends', 'wpamelia'), 'event_at' => __('at', 'wpamelia'), 'event_close' => __('Close', 'wpamelia'), 'event_select_tickets' => __('Select Tickets', 'wpamelia'), 'event_congrats' => __('Congratulations', 'wpamelia'), 'event_payment' => __('Payment', 'wpamelia'), 'event_customer_info' => __('Your Information', 'wpamelia'), 'event_about_list' => __('About Event', 'wpamelia'), 'congrats_panel' => __('Customer Panel', 'wpamelia'), 'events_available' => __('Events Available', 'wpamelia'), 'event_available' => __('Event Available', 'wpamelia'), 'event_page' => __('Page', 'wpamelia'), 'event_search' => __('Search for Events', 'wpamelia'), 'event_calendar' => __('Calendar', 'wpamelia'), 'event_begins' => __('Begins', 'wpamelia'), 'event_slot_left' => __('slot left', 'wpamelia'), 'event_slots_left' => __('slots left', 'wpamelia'), 'event_learn_more' => __('Learn more', 'wpamelia'), 'event_read_more' => __('Read more', 'wpamelia'), 'event_timetable' => __('Timetable', 'wpamelia'), 'about' => __('About', 'wpamelia'), 'event_tickets_left' => __('tickets left', 'wpamelia'), 'event_ticket_left' => __('ticket left', 'wpamelia'), 'back_btn' => __('Go Back', 'wpamelia'), 'event_bringing' => __('How many attendees do you want to book event for?', 'wpamelia'), ]; } /** * Returns the array of the frontend strings for the catalog shortcode * * @return array */ public static function getCatalogStrings() { return [ 'booking_appointment' => __('Booking Appointment', 'wpamelia'), 'buffer_time' => __('Buffer Time', 'wpamelia'), 'categories' => __('Categories', 'wpamelia'), 'category_colon' => __('Category:', 'wpamelia'), 'description' => __('Description', 'wpamelia'), 'description_colon' => __('Description:', 'wpamelia'), 'extras' => __('Extras', 'wpamelia'), 'info' => __('Info', 'wpamelia'), 'maximum_quantity_colon' => __('Maximum Quantity:', 'wpamelia'), 'view_more' => __('View More', 'wpamelia'), 'view_all' => __('View All', 'wpamelia'), 'filter_input' => __('Search', 'wpamelia'), 'filter_employee' => __('Filter by Employee', 'wpamelia'), 'filter_location' => __('Filter by Location', 'wpamelia'), 'filter_all' => __('All', 'wpamelia'), 'filter_packages' => __('Packages', 'wpamelia'), 'filter_services' => __('Services', 'wpamelia'), 'services' => __('Services', 'wpamelia'), 'package' => __('Package', 'wpamelia'), 'packages' => __('Packages', 'wpamelia'), 'view_employees' => __('View Employees', 'wpamelia'), 'save' => __('Save', 'wpamelia'), 'free' => __('Free', 'wpamelia'), 'in_package' => __('In Package', 'wpamelia'), 'book_now' => __('Book Now', 'wpamelia'), 'about_service' => __('About Service', 'wpamelia'), 'about_package' => __('About Package', 'wpamelia'), 'view_all_photos' => __('View all photos', 'wpamelia'), 'service_available_in_package' => __('This service is available in a Package', 'wpamelia'), 'more_packages' => __('View More Packages', 'wpamelia'), 'less_packages' => __('View Less Packages', 'wpamelia'), 'package_includes' => __('Package includes', 'wpamelia'), 'expires_day' => __('day', 'wpamelia'), 'expires_days' => __('days', 'wpamelia'), 'expires_week' => __('week', 'wpamelia'), 'expires_weeks' => __('weeks', 'wpamelia'), 'expires_month' => __('month', 'wpamelia'), 'expires_months' => __('months', 'wpamelia'), 'back_btn' => __('Go Back', 'wpamelia'), 'employees' => __('Employees', 'wpamelia'), 'heading_service' => __('Service', 'wpamelia'), 'heading_services' => __('Services', 'wpamelia'), 'employee_info' => __('Employee information', 'wpamelia'), 'book_service' => __('Book This Service', 'wpamelia'), 'book_package' => __('Book This Package', 'wpamelia'), 'no_search_data' => __('No results', 'wpamelia'), 'tab_employees' => __('Employees', 'wpamelia'), ]; } /** * Returns the array of the frontend strings for the event shortcode * * @return array */ public static function getCabinetStrings() { return [ 'add_date' => __('Add Date', 'wpamelia'), 'add_day_off' => __('Add Day Off', 'wpamelia'), 'add_day_off_placeholder' => __('Enter holiday or day off name', 'wpamelia'), 'add_period' => __('Add Period', 'wpamelia'), 'add_special_day' => __('Add Special Day', 'wpamelia'), 'apply_to_all_days' => __('Apply to All Days', 'wpamelia'), 'appointment_canceled' => __('Appointment Canceled', 'wpamelia'), 'appointment_change_time' => __('To reschedule your appointment, select an available date time from the calendar, then click Confirm.', 'wpamelia'), 'appointment_deleted' => __('Appointment has been deleted', 'wpamelia'), 'appointment_rescheduled' => __('Appointment has been rescheduled', 'wpamelia'), 'appointment_saved' => __('Appointment has been saved', 'wpamelia'), 'appointments' => __('Appointments', 'wpamelia'), 'appointments_to_book' => __('Appointments to book', 'wpamelia'), 'approved' => __('Approved', 'wpamelia'), 'assigned_services' => __('Assigned Services', 'wpamelia'), 'attendees' => __('Attendees', 'wpamelia'), 'available' => __('Available', 'wpamelia'), 'away' => __('Away', 'wpamelia'), 'booking_cancel_exception' => __('Booking can\'t be canceled', 'wpamelia'), 'booking_closes' => __('Booking Closes', 'wpamelia'), 'booking_opens' => __('Booking Opens', 'wpamelia'), 'booking_reschedule_exception' => __('Appointment can\'t be rescheduled', 'wpamelia'), 'break' => __('On Break', 'wpamelia'), 'break_hours' => __('Break Hours', 'wpamelia'), 'breaks' => __('Breaks', 'wpamelia'), 'busy' => __('Busy', 'wpamelia'), 'cancel' => __('Cancel', 'wpamelia'), 'cancel_appointment' => __('Cancel Appointment', 'wpamelia'), 'cancel_event' => __('Cancel Event', 'wpamelia'), 'cancel_following' => __('Cancel following', 'wpamelia'), 'cancel_package' => __('Cancel Package', 'wpamelia'), 'canceled' => __('Canceled', 'wpamelia'), 'capacity' => __('Capacity', 'wpamelia'), 'category' => __('Category', 'wpamelia'), 'change_group_status' => __('Change group status', 'wpamelia'), 'change_password' => __('Change Password', 'wpamelia'), 'choose_a_group_service' => __('Choose a group service', 'wpamelia'), 'choose_appointment_date' => __('Please choose appointment date', 'wpamelia'), 'choose_appointment_time' => __('Please choose appointment time', 'wpamelia'), 'company_days_off' => __('Company Days off', 'wpamelia'), 'confirm_cancel' => __('Are you sure you want to cancel this event?', 'wpamelia'), 'confirm_cancel_appointment' => __('Are you sure you want to cancel this appointment?', 'wpamelia'), 'confirm_cancel_event' => __('Are you sure you want to cancel your attendance?', 'wpamelia'), 'confirm_cancel_following' => __('Do you want to cancel following events?', 'wpamelia'), 'confirm_delete' => __('Are you sure you want to delete this event?', 'wpamelia'), 'confirm_delete_appointment' => __('Are you sure you want to delete this appointment?', 'wpamelia'), 'confirm_delete_attendee' => __('Are you sure you want to delete selected attendee?', 'wpamelia'), 'confirm_delete_attendees' => __('Are you sure you want to delete selected attendees?', 'wpamelia'), 'confirm_delete_following' => __('Do you want to delete following canceled events?', 'wpamelia'), 'confirm_duplicate_appointment' => __('Are you sure you want to duplicate this appointment?', 'wpamelia'), 'confirm_duplicate_event' => __('Are you sure you want to duplicate this event?', 'wpamelia'), 'confirm_open' => __('Are you sure you want to open this event?', 'wpamelia'), 'confirm_open_following' => __('Do you want to open following events?', 'wpamelia'), 'confirm_save_following' => __('Do you want to update following events?', 'wpamelia'), 'create_new' => __('Create New', 'wpamelia'), 'custom_fields' => __('Custom Fields', 'wpamelia'), 'customer_profile' => __('Customer Profile ', 'wpamelia'), 'customers' => __('Customers', 'wpamelia'), 'customers_singular_plural' => __('Customer(s)', 'wpamelia'), 'customers_tooltip' => __('Indicates the number of new and returning customers<br/>for the selected date range.', 'wpamelia'), 'customize' => __('Customize', 'wpamelia'), 'date' => __('Date', 'wpamelia'), 'date_of_birth' => __('Date of Birth', 'wpamelia'), 'day1' => __('1 day', 'wpamelia'), 'day_off_name' => __('Day Off name', 'wpamelia'), 'dayoff' => __('Day Off', 'wpamelia'), 'days2' => __('2 days', 'wpamelia'), 'days3' => __('3 days', 'wpamelia'), 'days4' => __('4 days', 'wpamelia'), 'days5' => __('5 days', 'wpamelia'), 'days6' => __('6 days', 'wpamelia'), 'days_off' => __('Days Off', 'wpamelia'), 'days_off_add' => __('Add Day Off', 'wpamelia'), 'days_off_date_warning' => __('Please enter date', 'wpamelia'), 'days_off_name_warning' => __('Please enter name', 'wpamelia'), 'days_off_repeat_yearly' => __('Repeat Yearly', 'wpamelia'), 'delete' => __('Delete', 'wpamelia'), 'delete_following' => __('Delete following', 'wpamelia'), 'delete_profile' => __('Delete profile', 'wpamelia'), 'delete_profile_description' => __('Are you sure you want to delete your profile? You will lose access to all your bookings and access to the customer panel.', 'wpamelia'), 'description' => __('Description', 'wpamelia'), 'details' => __('Details', 'wpamelia'), 'disabled' => __('Disabled', 'wpamelia'), 'discount_amount' => __('Discount', 'wpamelia'), 'duration' => __('Duration', 'wpamelia'), 'edit' => __('Edit', 'wpamelia'), 'edit_appointment' => __('Edit Appointment', 'wpamelia'), 'edit_event' => __('Edit Event', 'wpamelia'), 'email' => __('Email', 'wpamelia'), 'email_or_username' => __('Email or Username', 'wpamelia'), 'employee_days_off' => __('Employee Days off', 'wpamelia'), 'enter_address' => __('Enter Address', 'wpamelia'), 'enter_email_warning' => __('Please enter email', 'wpamelia'), 'enter_event_name' => __('Enter Event Name', 'wpamelia'), 'enter_event_name_warning' => __('Please enter name', 'wpamelia'), 'enter_location_warning' => __('Please select location', 'wpamelia'), 'enter_password_warning' => __('Please enter password', 'wpamelia'), 'enter_valid_email_warning' => __('Please enter a valid email address', 'wpamelia'), 'error' => __('Error', 'wpamelia'), 'event_add_attendee' => __('Add Attendee', 'wpamelia'), 'event_attendee_deleted' => __('Attendee have been deleted', 'wpamelia'), 'event_attendee_not_deleted' => __('Attendee have not been deleted', 'wpamelia'), 'event_attendee_remove' => __('Remove Attendee', 'wpamelia'), 'event_attendee_saved' => __('Attendee has been saved', 'wpamelia'), 'event_edit_attendees' => __('Edit Attendees', 'wpamelia'), 'event_aggregated_price' => __('The price will multiply by the number of people/spots', 'wpamelia'), 'event_attendees' => __('Attendees', 'wpamelia'), 'event_attendees_deleted' => __('Attendees have been deleted', 'wpamelia'), 'event_attendees_not_deleted' => __('Attendees have not been deleted', 'wpamelia'), 'event_book_more_than_once' => __('Allow the same customer to book more than once', 'wpamelia'), 'event_attendees_search' => __('Find Attendees', 'wpamelia'), 'event_booking_closes_after' => __('Booking closes when event starts', 'wpamelia'), 'event_booking_closes_on' => __('Closes on:', 'wpamelia'), 'event_booking_closes_apply' => __('If this option is not checked the plugin will calculate the time <br> for closing the booking based on the selected time for the first event', 'wpamelia'), 'event_booking_opens_apply' => __('If this option is not checked the plugin will calculate the time <br> for opening the booking based on the selected time for the first event', 'wpamelia'), 'event_booking_opens_now' => __('Booking opens immediately', 'wpamelia'), 'event_booking_opens_on' => __('Opens on:', 'wpamelia'), 'event_bringing_anyone' => __('Allow bringing more people', 'wpamelia'), 'event_cancel' => __('Cancel Event', 'wpamelia'), 'event_canceled' => __('Event has been canceled', 'wpamelia'), 'event_close_after_min' => __('Close Event after certain minimum is reached', 'wpamelia'), 'event_close_min_total' => __('Minimum of attendees', 'wpamelia'), 'event_close_min_bookings' => __('Minimum of bookings', 'wpamelia'), 'event_close_min_total_tt' => __('One spot is equal to one attendee.', 'wpamelia'), 'event_close_min_bookings_tt' => __('One booking can have multiple attendees/spots in it.', 'wpamelia'), 'event_close_minimum' => __('Set Minimum', 'wpamelia'), 'event_colors' => __('Event Colors:', 'wpamelia'), 'event_colors_custom' => __('Custom Color', 'wpamelia'), 'event_colors_preset' => __('Preset Colors', 'wpamelia'), 'event_custom_address' => __('Custom Address', 'wpamelia'), 'event_delete' => __('Delete Event', 'wpamelia'), 'event_deleted' => __('Event has been deleted', 'wpamelia'), 'event_details' => __('Details', 'wpamelia'), 'event_duplicate' => __('Duplicate', 'wpamelia'), 'event_edit_attendee' => __('Edit Attendee', 'wpamelia'), 'event_gallery' => __('Event Gallery:', 'wpamelia'), 'event_max_capacity' => __('Maximum allowed spots', 'wpamelia'), 'event_name' => __('Name:', 'wpamelia'), 'event_open' => __('Open Event', 'wpamelia'), 'event_opened' => __('Event has been opened', 'wpamelia'), 'event_period_dates' => __('Dates:', 'wpamelia'), 'event_period_time' => __('Time:', 'wpamelia'), 'event_recurring_enabled' => __('This is recurring event', 'wpamelia'), 'event_recurring_period' => __('Repeat Event', 'wpamelia'), 'event_recurring_until' => __('Until when?', 'wpamelia'), 'event_saved' => __('Event has been saved', 'wpamelia'), 'event_select_address' => __('Select Address', 'wpamelia'), 'event_show_on_site' => __('Show event on site', 'wpamelia'), 'event_staff' => __('Staff', 'wpamelia'), 'event_status_changed' => __('Booking status has been changed to ', 'wpamelia'), 'event_tags' => __('Tags', 'wpamelia'), 'event_tags_create' => __('No Tags. Create a new one.', 'wpamelia'), 'event_tags_select_or_create' => __('Select or Create Tag', 'wpamelia'), 'export' => __('Export', 'wpamelia'), 'export_tooltip_attendees' => __('You can use this option to export attendees in CSV file<br/>for the selected event.', 'wpamelia'), 'extras' => __('Extras', 'wpamelia'), 'forgot_password' => __('Forgot Password?', 'wpamelia'), 'general' => __('General', 'wpamelia'), 'google_calendar' => __('Google Calendar', 'wpamelia'), 'google_calendar_tooltip' => __('Connect your Google Calendar here so once<br/>the appointment is scheduled it can be added<br/>to your Google Calendar automatically.', 'wpamelia'), 'google_sign_in' => __('Sign in with Google', 'wpamelia'), 'google_sign_out' => __('Sign out from Google', 'wpamelia'), 'h1' => __('1h', 'wpamelia'), 'h10' => __('10h', 'wpamelia'), 'h11' => __('11h', 'wpamelia'), 'h12' => __('12h', 'wpamelia'), 'h1min30' => __('1h 30min', 'wpamelia'), 'h2' => __('2h', 'wpamelia'), 'h3' => __('3h', 'wpamelia'), 'h4' => __('4h', 'wpamelia'), 'h6' => __('6h', 'wpamelia'), 'h8' => __('8h', 'wpamelia'), 'h9' => __('9h', 'wpamelia'), 'invalid_credentials' => __('Incorrect email or password', 'wpamelia'), 'integrations_settings' => __('Integrations', 'wpamelia'), 'lesson_space' => __('Lesson Space', 'wpamelia'), 'lesson_space_join' => __('Join Space', 'wpamelia'), 'lesson_space_link' => __('Lesson Space Link', 'wpamelia'), 'lesson_space_links' => __('Lesson Space Links', 'wpamelia'), 'lesson_space_new_space' => __('New Space', 'wpamelia'), 'limit_extra_people' => __('Limit the additional number of people', 'wpamelia'), 'limit_extra_people_set' => __('Set Limit', 'wpamelia'), 'limit_extra_people_tooltip' => __('Limit the number of people that one customer can add during the booking', 'wpamelia'), 'loader_message' => __('Please Wait', 'wpamelia'), 'login' => __('Login', 'wpamelia'), 'login_email_placeholder' => __('Enter your email', 'wpamelia'), 'login_password_placeholder' => __('Enter your password', 'wpamelia'), 'logout' => __('Logout', 'wpamelia'), 'maximum_capacity' => __('Max. Capacity', 'wpamelia'), 'min1' => __('1min', 'wpamelia'), 'min10' => __('10min', 'wpamelia'), 'min12' => __('12min', 'wpamelia'), 'min15' => __('15min', 'wpamelia'), 'min2' => __('2min', 'wpamelia'), 'min20' => __('20min', 'wpamelia'), 'min30' => __('30min', 'wpamelia'), 'min45' => __('45min', 'wpamelia'), 'min5' => __('5min', 'wpamelia'), 'minimum_capacity' => __('Min. Capacity', 'wpamelia'), 'minimum_time_before_canceling' => __('Minimum time required before canceling', 'wpamelia'), 'minimum_time_before_canceling_tooltip' => __('Set the time before the appointment when customers<br/>will not be able to cancel the appointment.', 'wpamelia'), 'months3' => __('3 months', 'wpamelia'), 'months6' => __('6 months', 'wpamelia'), 'multiple_emails' => __('Multiple Emails', 'wpamelia'), 'my_profile' => __('My Profile', 'wpamelia'), 'new_appointment' => __('New Appointment', 'wpamelia'), 'new_event' => __('New Event', 'wpamelia'), 'new_password_colon' => __('New Password:', 'wpamelia'), 'new_password_length' => __('Password must be longer than 3 characters', 'wpamelia'), 'new_password_required' => __('Please enter new password', 'wpamelia'), 'no_attendees_yet' => __('There are no attendees yet...', 'wpamelia'), 'no_results' => __('There are no results...', 'wpamelia'), 'no_selected_extras_requirements' => __('Select customer, employee and service', 'wpamelia'), 'no_selected_slot_requirements' => __('Select date and time', 'wpamelia'), 'no-show' => __('No-show', 'wpamelia'), 'note' => __('Note', 'wpamelia'), 'note_internal' => __('Note (Internal)', 'wpamelia'), 'notify_attendees' => __('Notify the attendee(s)', 'wpamelia'), 'notify_attendees_tooltip' => __('Check this checkbox if you want your attendee(s) to<br/>receive an email about the event’s updated information.', 'wpamelia'), 'notify_customers' => __('Notify the customer(s)', 'wpamelia'), 'notify_customers_tooltip' => __('Check this checkbox if you want your customer to<br/>receive an email about the scheduled appointment.', 'wpamelia'), 'once_off' => __('Once Off', 'wpamelia'), 'open_following' => __('Open following', 'wpamelia'), 'package_back_to_appointments' => __('Back to appointments', 'wpamelia'), 'package_total_appointments' => __('Appointments in this service', 'wpamelia'), 'package_left_appointments' => __('appointment slots left to be booked', 'wpamelia'), 'package_book_next_appointment' => __('Book next appointment', 'wpamelia'), 'package_continue_booking' => __('Continue Booking', 'wpamelia'), 'package_booked_appointments' => __('Booked Appointments', 'wpamelia'), 'package_deal' => __('This booking is part of a package deal', 'wpamelia'), 'package_service_info' => __('Service info', 'wpamelia'), 'package_price' => __('Package price', 'wpamelia'), 'partially_paid' => __('Partially Paid', 'wpamelia'), 'partially_refunded' => __('Partially Refunded', 'wpamelia'), 'password' => __('Password', 'wpamelia'), 'password_has_been_changed' => __('Password has been changed', 'wpamelia'), 'password_is_set' => __('Password is set', 'wpamelia'), 'passwords_do_not_match' => __('Passwords do not match', 'wpamelia'), 'payment' => __('Payment', 'wpamelia'), 'pay' => __('Pay', 'wpamelia'), 'pay_now' => __('Pay now', 'wpamelia'), 'payment_method' => __('Payment Method', 'wpamelia'), 'payment_status' => __('Payment Status', 'wpamelia'), 'payment_links' => __('Enable Payment from Link', 'wpamelia'), 'payment_links_enable' => __('Allow payment via Payment Link', 'wpamelia'), 'payment_links_enable_tooltip' => __('If this option is enabled customers will be able to pay via email notifications or through their Customer panel.', 'wpamelia'), 'payment_links_change_status' => __('Update booking status automatically', 'wpamelia'), 'payment_links_change_status_tooltip' => __('Update booking status to approved after succesfull payment from link', 'wpamelia'), 'payment_links_redirect' => __('Redirect URL after Payment', 'wpamelia'), 'payment_links_redirect_tooltip' => __('Customer will be redirected to this URL once the payment from the link is processed.', 'wpamelia'), 'payment_links_warning' => __('Please note: For this option to work you need to add new payment link placeholders to the message templates', 'wpamelia'), 'payments' => __('Payments', 'wpamelia'), 'pending' => __('Pending', 'wpamelia'), 'period_location_filter1_tooltip' => __('Select specific location for this period.', 'wpamelia'), 'period_location_filter2_tooltip' => __('Select specific location for each period.', 'wpamelia'), 'period_services_filter' => __('Applied for all assigned services', 'wpamelia'), 'period_services_filter1_tooltip' => __('Select only specific services for this period.<br/>If no services are selected, then all assigned services for this employee<br/>will be available for booking in this period.', 'wpamelia'), 'period_services_filter2_tooltip' => __('Select specific services for each period.', 'wpamelia'), 'periods' => __('Periods', 'wpamelia'), 'pick_a_date_or_range' => __('Pick a date or range', 'wpamelia'), 'pick_a_year' => __('Pick a year', 'wpamelia'), 'price' => __('Price', 'wpamelia'), 'price_per_spot' => __('Price per Spot', 'wpamelia'), 'profile_deleted' => __('Profile deleted', 'wpamelia'), 'profile_saved' => __('Profile has been updated', 'wpamelia'), 'provider_profile' => __('Employee Profile', 'wpamelia'), 're_type_requred' => __('Please enter new password again', 'wpamelia'), 'recovery_email_sent' => __('Email with access link has been sent', 'wpamelia'), 'recurring' => __('Recurring', 'wpamelia'), 'recurring_active' => __('Repeat this appointment', 'wpamelia'), 'recurring_active_tooltip' => __('Check this option if you want to create recurring appointments', 'wpamelia'), 'recurring_type_monthly' => __('Monthly', 'wpamelia'), 'recurring_type_weekly' => __('Weekly', 'wpamelia'), 'recurring_type_yearly' => __('Yearly', 'wpamelia'), 'redirect_url_after_appointment' => __('Redirect URL After Booking', 'wpamelia'), 'redirect_url_after_appointment_tooltip' => __('Customer will be redirected to this URL once he schedules the appointment.', 'wpamelia'), 'refunded' => __('Refunded', 'wpamelia'), 'rejected' => __('Rejected', 'wpamelia'), 'repeat_every_year' => __('Repeat Every Year', 'wpamelia'), 'reschedule' => __('Reschedule', 'wpamelia'), 'retype_new_password_colon' => __('Re-type New Password:', 'wpamelia'), 'save' => __('Save', 'wpamelia'), 'duplicate' => __('Duplicate', 'wpamelia'), 'save_changes' => __('Save Changes', 'wpamelia'), 'save_single' => __('No, just this one', 'wpamelia'), 'save_special_day' => __('Save Special Day', 'wpamelia'), 'schedule' => __('Schedule', 'wpamelia'), 'select' => __('Select', 'wpamelia'), 'select_customer_warning' => __('Please select at least one customer', 'wpamelia'), 'select_customers' => __('Select Customer(s)', 'wpamelia'), 'select_date_warning' => __('Please select date', 'wpamelia'), 'select_cycle_warning' => __('Please select repeat period', 'wpamelia'), 'select_interval_warning' => __('Please select repeat interval', 'wpamelia'), 'select_employee' => __('Select Employee', 'wpamelia'), 'select_employee_warning' => __('Please select employee', 'wpamelia'), 'select_coupon' => __('Select Coupon', 'wpamelia'), 'select_location' => __('Select Location', 'wpamelia'), 'select_max_customer_count_warning' => __('Maximum number of places is', 'wpamelia'), 'select_repeat_period' => __('Select Repeat Period', 'wpamelia'), 'select_repeat_interval' => __('Select Repeat Interval', 'wpamelia'), 'select_service' => __('Select Service', 'wpamelia'), 'select_service_category' => __('Select Service Category', 'wpamelia'), 'select_service_warning' => __('Please select service', 'wpamelia'), 'select_time' => __('Select Time', 'wpamelia'), 'select_time_warning' => __('Please select time', 'wpamelia'), 'selected_customers' => __('Selected Customers', 'wpamelia'), 'send' => __('Send', 'wpamelia'), 'send_recovery_email' => __('Send Access Link', 'wpamelia'), 'send_recovery_email_description' => __('Enter your account email address and we will send you an access link to your inbox.', 'wpamelia'), 'service_category' => __('Service Category', 'wpamelia'), 'service_no_extras' => __('This service does not have any extras', 'wpamelia'), 'service_price' => __('Service Price', 'wpamelia'), 'service_provider_remove_fail' => __('You have appointments for this service', 'wpamelia'), 'service_provider_remove_fail_all' => __('You have appointments for', 'wpamelia'), 'set_password' => __('Set Password', 'wpamelia'), 'settings' => __('Settings', 'wpamelia'), 'sign_in' => __('Sign In', 'wpamelia'), 'special_day_date_warning' => __('Please enter date', 'wpamelia'), 'special_day_end_time_warning' => __('Please enter end time', 'wpamelia'), 'special_day_start_time_warning' => __('Please enter start time', 'wpamelia'), 'special_days' => __('Special Days', 'wpamelia'), 'special_days_reflect_services' => __('Reflect On', 'wpamelia'), 'spots' => __('Spots', 'wpamelia'), 'status' => __('Status', 'wpamelia'), 'subtotal' => __('Subtotal', 'wpamelia'), 'success' => __('Success', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'today' => __('Today', 'wpamelia'), 'tomorrow' => __('Tomorrow', 'wpamelia'), 'total' => __('Total', 'wpamelia'), 'total_price' => __('Total Price', 'wpamelia'), 'created_on' => __('Created On', 'wpamelia'), 'update_following' => __('Update following', 'wpamelia'), 'user_profile' => __('User Profile', 'wpamelia'), 'week1' => __('1 week', 'wpamelia'), 'weekday_friday' => __('Friday', 'wpamelia'), 'weekday_monday' => __('Monday', 'wpamelia'), 'weekday_saturday' => __('Saturday', 'wpamelia'), 'weekday_sunday' => __('Sunday', 'wpamelia'), 'weekday_thursday' => __('Thursday', 'wpamelia'), 'weekday_tuesday' => __('Tuesday', 'wpamelia'), 'weekday_wednesday' => __('Wednesday', 'wpamelia'), 'weeks2' => __('2 weeks', 'wpamelia'), 'weeks3' => __('3 weeks', 'wpamelia'), 'weeks4' => __('4 weeks', 'wpamelia'), 'wc_product' => __('Select WooCommerce product', 'wpamelia'), 'wc_product_tooltip' => __('Here you can choose the product that will be used for WooCommerce integration.', 'wpamelia'), 'work_hours' => __('Work Hours', 'wpamelia'), 'working_hours' => __('Working Hours', 'wpamelia'), 'timezone' => __('Timezone', 'wpamelia'), 'yes' => __('Yes', 'wpamelia'), 'outlook_sign_in' => __('Sign in with Outlook', 'wpamelia'), 'outlook_sign_out' => __('Sign out from Outlook', 'wpamelia'), 'outlook_calendar_tooltip' => __('Here you can connect employee with Outlook Calendar,<br/>so once the appointment is scheduled it will be<br/>automatically added to employee\'s calendar.', 'wpamelia'), 'outlook_placeholder' => __('Select Outlook Calendar', 'wpamelia'), 'zoom' => __('Zoom', 'wpamelia'), 'zoom_click_to_join' => __('Join Zoom Meeting', 'wpamelia'), 'zoom_click_to_start' => __('Start Zoom Meeting', 'wpamelia'), 'zoom_join_link' => __('Zoom Join Link (Participants)', 'wpamelia'), 'zoom_link' => __('Zoom Link', 'wpamelia'), 'zoom_links' => __('Zoom Links', 'wpamelia'), 'zoom_start_link' => __('Zoom Start Link (Host)', 'wpamelia'), 'zoom_user' => __('Zoom User', 'wpamelia'), 'zoom_user_placeholder' => __('Select Zoom User', 'wpamelia'), 'zoom_user_tooltip' => __('Here you can select Zoom User,<br/>so once the appointment is scheduled,<br/>zoom meeting will be automatically created.', 'wpamelia'), ]; } } WP/Translations/BackendStrings.php 0000666 00000656142 15165376447 0013231 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\Translations; /** * Class BackendStrings * * @package AmeliaBooking\Infrastructure\WP\Translations * * @SuppressWarnings(ExcessiveMethodLength) * @SuppressWarnings(ExcessiveClassLength) * @phpcs:disable */ class BackendStrings { /** * Returns the array for the common strings * * @return array */ public static function getCommonStrings() { return [ 'admin' => __('Admin', 'wpamelia'), 'add_date' => __('Add Date', 'wpamelia'), 'add_language' => __('Add Language', 'wpamelia'), 'all' => __('All', 'wpamelia'), 'all_locations' => __('All Locations', 'wpamelia'), 'all_packages' => __('All Packages', 'wpamelia'), 'all_services' => __('All Services', 'wpamelia'), 'all_events' => __('All events', 'wpamelia'), 'appointment' => __('Appointment', 'wpamelia'), 'appointments' => __('Appointments', 'wpamelia'), 'approved' => __('Approved', 'wpamelia'), 'apply_coupon' => __('Apply Coupon:', 'wpamelia'), 'booked' => __('Booked', 'wpamelia'), 'booking' => __('Booking', 'wpamelia'), 'cancel' => __('Cancel', 'wpamelia'), 'canceled' => __('Canceled', 'wpamelia'), 'canceled_by_admin' => __('Canceled By Admin', 'wpamelia'), 'canceled_by_attendee' => __('Canceled By Attendee', 'wpamelia'), 'capacity' => __('Spots', 'wpamelia'), 'content_mode_tooltip' => __('Don\'t use Text mode option if you already have HTML code in the description,<br>since once this option is enabled the existing HTML tags could be lost.', 'wpamelia'), 'confirm' => __('Confirm', 'wpamelia'), 'close' => __('Close', 'wpamelia'), 'closed' => __('Closed', 'wpamelia'), 'create' => __('Create', 'wpamelia'), 'csv_delimiter' => __('Select Delimiter', 'wpamelia'), 'csv_delimiter_comma' => __('Comma (,)', 'wpamelia'), 'csv_delimiter_semicolon' => __('Semicolon (;)', 'wpamelia'), 'continue' => __('Continue', 'wpamelia'), 'coupon' => __('Coupon', 'wpamelia'), 'customer' => __('Customer', 'wpamelia'), 'date_specific' => __('Specific Date', 'wpamelia'), 'expired' => __('Expired', 'wpamelia'), 'minutes' => __('Minutes', 'wpamelia'), 'hour' => __('Hour', 'wpamelia'), 'hours' => __('Hours', 'wpamelia'), 'day' => __('Day', 'wpamelia'), 'days' => __('Days', 'wpamelia'), 'week' => __('Week', 'wpamelia'), 'weeks' => __('Weeks', 'wpamelia'), 'month' => __('Month', 'wpamelia'), 'months' => __('Months', 'wpamelia'), 'year' => __('Year', 'wpamelia'), 'years' => __('Years', 'wpamelia'), 'date' => __('Date', 'wpamelia'), 'delete' => __('Delete', 'wpamelia'), 'description' => __('Description', 'wpamelia'), 'details' => __('Details', 'wpamelia'), 'disabled' => __('Disabled', 'wpamelia'), 'discard' => __('Discard', 'wpamelia'), 'discount' => __('Discount (%)', 'wpamelia'), 'duration' => __('Duration', 'wpamelia'), 'duplicate' => __('Duplicate', 'wpamelia'), 'edit' => __('Edit', 'wpamelia'), 'email_placeholder' => __('example@mail.com', 'wpamelia'), 'employee' => __('Employee', 'wpamelia'), 'employees' => __('Employees', 'wpamelia'), 'enter_email_warning' => __('Please enter email', 'wpamelia'), 'enter_valid_email_warning' => __('Please enter a valid email address', 'wpamelia'), 'error' => __('Error', 'wpamelia'), 'event' => __('Event', 'wpamelia'), 'events' => __('Events', 'wpamelia'), 'export' => __('Export', 'wpamelia'), 'extras' => __('Extras', 'wpamelia'), 'google_calendar' => __('Google Calendar', 'wpamelia'), 'google_meet_join' => __('Join With Google Meet', 'wpamelia'), 'outlook_calendar' => __('Outlook Calendar', 'wpamelia'), 'h' => __('h', 'wpamelia'), 'id' => __('ID', 'wpamelia'), 'import' => __('Import', 'wpamelia'), 'language' => __('Language', 'wpamelia'), 'lesson_space' => __('Lesson Space', 'wpamelia'), 'lesson_space_new_space' => __('New Space', 'wpamelia'), 'delete_amelia_short' => __('Delete Amelia content', 'wpamelia'), 'delete_amelia' => __('Delete tables, roles, files and settings once the Amelia plugin is deleted.', 'wpamelia'), 'delete_amelia_tooltip' => __('Enable this option if you want to delete plugin tables, roles, files and settings<br>when deleting the plugin from plugins page', 'wpamelia'), 'appointment_space_name' => __('Appointment Space Name', 'wpamelia'), 'event_space_name' => __('Event Space Name', 'wpamelia'), 'lesson_space_join' => __('Join Space', 'wpamelia'), 'lesson_space_pending' => __('Create spaces for pending appointments', 'wpamelia'), 'lesson_space_pending_tt' => __('Enable this option if you want to create spaces for appointments with pending status.', 'wpamelia'), 'limit_extra_people' => __('Limit the additional number of people', 'wpamelia'), 'limit_extra_people_set' => __('Set Limit', 'wpamelia'), 'limit_extra_people_tooltip'=> __('Limit the number of people that one customer can add during the booking', 'wpamelia'), 'location' => __('Location', 'wpamelia'), 'locations' => __('Locations', 'wpamelia'), 'min' => __('min', 'wpamelia'), 'name' => __('Name', 'wpamelia'), 'enter_name_warning' => __('Please enter name', 'wpamelia'), 'name_ascending' => __('Name Ascending', 'wpamelia'), 'name_descending' => __('Name Descending', 'wpamelia'), 'need_help' => __('Need Help', 'wpamelia'), 'no' => __('No', 'wpamelia'), 'no_employees_yet' => __('You don\'t have any employees here yet...', 'wpamelia'), 'no_results' => __('There are no results...', 'wpamelia'), 'no_packages_yet' => __('You don\'t have any packages here yet...', 'wpamelia'), 'no_resources_yet' => __('You don\'t have any resources yet...', 'wpamelia'), 'no_services_yet' => __('You don\'t have any services here yet...', 'wpamelia'), 'no-show' => __('No-show', 'wpamelia'), 'note' => __('Note', 'wpamelia'), 'note_internal' => __('Note (Internal)', 'wpamelia'), 'notifications' => __('Notification', 'wpamelia'), 'of' => __('of', 'wpamelia'), 'ok' => __('OK', 'wpamelia'), 'on_site' => __('On-site', 'wpamelia'), 'on_site_tooltip' => __('Here you can enable/disable On-Site payments for this service', 'wpamelia'), 'open' => __('Open', 'wpamelia'), 'opened' => __('Opened', 'wpamelia'), 'out_of' => __('out of', 'wpamelia'), 'package' => __('Package', 'wpamelia'), 'packages' => __('Packages', 'wpamelia'), 'package_price' => __('Package Price', 'wpamelia'), 'paid' => __('Paid', 'wpamelia'), 'partially_paid' => __('Partially Paid', 'wpamelia'), 'payment' => __('Payment', 'wpamelia'), 'payment_amount' => __('Payment Amount', 'wpamelia'), 'payment_method' => __('Payment Method', 'wpamelia'), 'payment_status' => __('Payment Status', 'wpamelia'), 'payment_tooltip' => __('Here you can select which payment methods will be available.<br/>If you disable all payment methods,<br/>then the default payment method from general settings will be used.', 'wpamelia'), 'payment_warning' => __('You have disabled all available payment methods. This means that default payment method from general settings will be used.', 'wpamelia'), 'payment_warning_settings' => __('Some services/events have all payment methods disabled. This means that default payment method will be used for those services/events.', 'wpamelia'), 'pending' => __('Pending', 'wpamelia'), 'period' => __('Period', 'wpamelia'), 'phone' => __('Phone', 'wpamelia'), 'php_version_message' => __('<p>The <strong>Amelia</strong> plugin requires PHP version 5.5 or greater.</p>', 'wpamelia'), 'php_version_title' => __('Plugin Activation Error', 'wpamelia'), 'pick_a_date' => __('Pick a date range', 'wpamelia'), 'elementor_popup_notice' => __('Please use the built-in Elementor shortcode widget instead of Amelia widget when adding Amelia to a popup', 'wpamelia'), 'profile' => __('Hide Employee Profile', 'wpamelia'), 'recurring' => __('Recurring', 'wpamelia'), 'recurring_type_daily' => __('Daily', 'wpamelia'), 'recurring_type_monthly' => __('Monthly', 'wpamelia'), 'recurring_type_weekly' => __('Weekly', 'wpamelia'), 'recurring_type_yearly' => __('Yearly', 'wpamelia'), 'refund' => __('Refund', 'wpamelia'), 'refunded' => __('Refunded', 'wpamelia'), 'rejected' => __('Rejected', 'wpamelia'), 'rescheduled' => __('Rescheduled', 'wpamelia'), 'resource' => __('Resource', 'wpamelia'), 'resources' => __('Resources', 'wpamelia'), 'package_appointments' => __('Package Appointments', 'wpamelia'), 'save' => __('Save', 'wpamelia'), 'recurring_every' => __('Every:', 'wpamelia'), 'schedule' => __('Schedule', 'wpamelia'), 'select_date_warning' => __('Please select date', 'wpamelia'), 'select_cycle_warning' => __('Please select repeat period', 'wpamelia'), 'select_interval_warning' => __('Please select repeat interval', 'wpamelia'), 'select_time' => __('Select Time', 'wpamelia'), 'select_time_warning' => __('Please select time', 'wpamelia'), 'service' => __('Service', 'wpamelia'), 'services' => __('Services', 'wpamelia'), 'settings_saved' => __('Settings has been saved', 'wpamelia'), 'shared' => __('Shared', 'wpamelia'), 'showing' => __('Showing', 'wpamelia'), 'sort' => __('Sort', 'wpamelia'), 'status' => __('Status', 'wpamelia'), 'status_colon' => __('Status:', 'wpamelia'), 'success' => __('Success', 'wpamelia'), 'text_mode' => __('Text Mode', 'wpamelia'), 'html_mode' => __('HTML Mode', 'wpamelia'), 'to' => __('to', 'wpamelia'), 'today' => __('Today', 'wpamelia'), 'tomorrow' => __('Tomorrow', 'wpamelia'), 'total' => __('Total', 'wpamelia'), 'translate' => __('Translate', 'wpamelia'), 'translation' => __('Translation', 'wpamelia'), 'type' => __('Type', 'wpamelia'), 'unique' => __('Unique', 'wpamelia'), 'view' => __('View', 'wpamelia'), 'weekday_friday' => __('Friday', 'wpamelia'), 'weekday_monday' => __('Monday', 'wpamelia'), 'weekday_saturday' => __('Saturday', 'wpamelia'), 'weekday_sunday' => __('Sunday', 'wpamelia'), 'weekday_thursday' => __('Thursday', 'wpamelia'), 'weekday_tuesday' => __('Tuesday', 'wpamelia'), 'weekday_wednesday' => __('Wednesday', 'wpamelia'), 'yes' => __('Yes', 'wpamelia'), 'zoom' => __('Zoom', 'wpamelia'), 'zoom_click_to_join' => __('Join Zoom Meeting', 'wpamelia'), 'zoom_click_to_start' => __('Start Zoom Meeting', 'wpamelia'), 'zoom_join_link' => __('Zoom Join Link (Participants)', 'wpamelia'), 'zoom_start_link' => __('Zoom Start Link (Host)', 'wpamelia'), 'zoom_user' => __('Zoom User', 'wpamelia'), 'zoom_user_placeholder' => __('Select Zoom User', 'wpamelia'), 'zoom_warning' => __('Certain employees that are assigned to the service are not connected to Zoom users. Please go to employees\' profiles and connect them to Zoom users in order to use this integration properly.', 'wpamelia'), 'unlimited' => __('Unlimited', 'wpamelia'), 'customize_dialog_heading' => __('New Event List 2.0 Booking Form', 'wpamelia'), 'customize_dialog_sub_heading' => __('Introducing Event List 2.0 - A Fresh, Modern, and User-Friendly Booking Form! Enjoy the new filters and search functionality, simplifying event discovery and streamlining the booking process. Explore new customization options by going to the Customize page or use <strong>[ameliaeventlistbooking]</strong> for a faster and personalized look.', 'wpamelia'), 'customize_dialog_faster' => __('Faster Pages', 'wpamelia'), 'customize_dialog_easy' => __('Easy Customization', 'wpamelia'), 'customize_dialog_friendly' => __('More User-Friendly Design', 'wpamelia'), 'customize_dialog_go_to' => __('Go to the Customize Event List 2.0 page', 'wpamelia'), 'customize_dialog_check' => __('Check it out Event List 2.0', 'wpamelia'), 'customize_dialog_close' => __('Close', 'wpamelia'), 'survey_heading' => __('Quick Survey', 'wpamelia'), 'survey_close' => __('Close forever', 'wpamelia'), 'survey_maybe' => __('Maybe later', 'wpamelia'), 'survey_sure' => __('Yes, Sure!', 'wpamelia'), 'survey_content' => __('<div>Hey there!</div><span>We would like to know you a little bit better! Could you spare a minute or two to answer a few questions?</span>', 'wpamelia'), ]; } /** * Returns the array for the settings strings * * @return array */ public static function getSettingsStrings() { return [ 'activate' => __('Activate', 'wpamelia'), 'activation' => __('Activation', 'wpamelia'), 'activation_activated' => __('Plugin has been activated', 'wpamelia'), 'activation_deactivated' => __('Plugin has been deactivated', 'wpamelia'), 'activation_envato_failed' => __('It seems that Envato API is currently busy (please try again) or you don\'t have a valid purchase of Amelia', 'wpamelia'), 'activation_settings' => __('Activation Settings', 'wpamelia'), 'activation_settings_description' => __('Use this setting to activate the plugin code so you can have access to auto updates of Amelia', 'wpamelia'), 'activation_settings_domains_limit' => __('You have reached maximum number of registered domains', 'wpamelia'), 'activation_settings_explanation' => __('Activate the plugin by entering Purchase code or using Envato API.', 'wpamelia'), 'activation_settings_invalid_code' => __('The purchase code is invalid or it has expired', 'wpamelia'), 'activation_settings_hidden_code' => __('Your purchase code has been hidden for security reasons. You can find it on your store page', 'wpamelia'), 'add_metaData' => __('Add New MetaData'), 'add_new_role' => __('Add New Role', 'wpamelia'), 'add_web_hook' => __('Add New Web Hook', 'wpamelia'), 'add_to_calendar' => __('Show Add To Calendar option to customers', 'wpamelia'), 'add_to_calendar_tooltip' => __('Suggest customers to add an appointment to their calendar<br/>when booking is finalized.', 'wpamelia'), 'address' => __('Address', 'wpamelia'), 'after' => __('After', 'wpamelia'), 'after_with_space' => __('After with space', 'wpamelia'), 'allow_booking_if_not_min' => __('Allow booking below minimum capacity', 'wpamelia'), 'allow_admin_book_at_any_time' => __('Allow admin to book appointment at any time', 'wpamelia'), 'allow_admin_book_at_any_time_tooltip' => __('If you enable this option, Admin will be able to book appointment at any time<br>(working hours, special days and days off for all employees will be ignored).', 'wpamelia'), 'allow_configure_days_off' => __('Configure their days off', 'wpamelia'), 'allow_configure_services' => __('Configure their services', 'wpamelia'), 'allow_configure_schedule' => __('Configure their schedule', 'wpamelia'), 'allow_configure_special_days' => __('Configure their special days', 'wpamelia'), 'allow_booking_if_pending' => __('Allow booking above maximum capacity', 'wpamelia'), 'allow_booking_if_pending_tooltip' => __('If this is disabled, your front-end customers won\'t be able to book appointment with Pending status above the maximum capacity.<br/>Once the maximum capacity is reached appointment will close and time slot will become unavailable.', 'wpamelia'), 'allow_booking_if_not_min_tooltip' => __('If this is disabled, your front-end customers won\'t be able to submit a booking unless they fill in the minimum service capacity,<br/>but once they book for any capacity above minimum, the time slot will become unavailable for booking for others.<br/>If enabled, multiple customers will be able to book the same time slot, without having to fill in the minimum capacity.', 'wpamelia'), 'allow_customer_reschedule' => __('Allow customers to reschedule their own appointments', 'wpamelia'), 'allow_customer_reschedule_tooltip' => __('Enable this option if you want to allow your customers to reschedule their own appointments.', 'wpamelia'), 'allow_customer_delete_profile' => __('Allow customers to delete their profile', 'wpamelia'), 'allow_customer_delete_profile_tooltip' => __('Enable this option if you want to allow your customers to delete their profile data (bookings won\'t be deleted).', 'wpamelia'), 'allow_customer_cancel_packages' => __('Allow customers to cancel packages', 'wpamelia'), 'allow_write_appointments' => __('Manage their appointments', 'wpamelia'), 'allow_write_events' => __('Manage their events', 'wpamelia'), 'amelia_role' => __('Amelia Role', 'wpamelia'), 'appointments' => __('Appointments', 'wpamelia'), 'appointments_settings' => __('Appointments Settings', 'wpamelia'), 'appointments_settings_description' => __('Use these settings to manage frontend bookings', 'wpamelia'), 'automatically_create_customer' => __('Automatically create Amelia Customer user', 'wpamelia'), 'automatically_create_customer_tooltip' => __('If you enable this option every time a new customer schedules the appointment<br/>he will get Amelia Customer user role and automatic email with login details.', 'wpamelia'), 'back_links' => __('Support Amelia by enabling this option', 'wpamelia'), 'back_links_tooltip' => __('Allow the short description below the booking form to support<br/>Amelia Booking Plugin and spread the word about it.', 'wpamelia'), 'bcc_email' => __('Send all notifications to additional addresses', 'wpamelia'), 'bcc_email_placeholder' => __('Please enter email address', 'wpamelia'), 'bcc_email_tooltip' => __('Here you can enter additional email addresses where all notifications will be sent.<br/>To add an address click Enter.', 'wpamelia'), 'bcc_sms' => __('Send all SMS messages to additional numbers', 'wpamelia'), 'bcc_sms_placeholder' => __('Please enter phone number', 'wpamelia'), 'bcc_sms_tooltip' => __('Here you can enter additional phone numbers where all SMS messages will be sent.<br/>To add a number click Enter.', 'wpamelia'), 'before' => __('Before', 'wpamelia'), 'before_with_space' => __('Before with space', 'wpamelia'), 'buffer_time_in_slot' => __('Include service buffer time in time slots', 'wpamelia'), 'buffer_time_in_slot_tooltip' => __('If this option is enabled<br>time slots will be shown with included service buffer time', 'wpamelia'), 'calendar' => __('Calendar', 'wpamelia'), 'cancel_error_url' => __('Unsuccessful Cancellation Redirect URL', 'wpamelia'), 'cancel_error_url_tooltip' => __('URL on which will user be redirected if appointment can\'t be canceled<br/>because of \'Minimum time required before canceling\' value', 'wpamelia'), 'cancel_success_url' => __('Successful Cancellation Redirect URL', 'wpamelia'), 'cancel_url_placeholder' => __('Please enter URL', 'wpamelia'), 'codecanyon_purchase_code' => __('CodeCanyon Purchase Code', 'wpamelia'), 'comma_dot' => __('Comma-Dot', 'wpamelia'), 'company' => __('Company', 'wpamelia'), 'company_settings' => __('Company Settings', 'wpamelia'), 'company_settings_description' => __('Use these settings to set up picture, name, address, phone and website of your company', 'wpamelia'), 'coupons' => __('Coupons', 'wpamelia'), 'enable_google_meet' => __('Enable Google Meet', 'wpamelia'), 'facebook_pixel' => __('Facebook Pixel', 'wpamelia'), 'google_analytics' => __('Google Analytics', 'wpamelia'), 'enable_google_meet_tooltip' => __('Enable this option if you want to include Google Meet in your event.', 'wpamelia'), 'currency' => __('Currency', 'wpamelia'), 'custom_fields' => __('Custom Fields', 'wpamelia'), 'custom_fields_description' => __('Add/edit custom fields', 'wpamelia'), 'custom_fields_settings' => __('Custom fields settings', 'wpamelia'), 'customers_as_attendees' => __('Add Event\'s Attendees', 'wpamelia'), 'customers_as_attendees_tooltip' => __('Enable this option if you want your employees to see<br/>in the event customers that attend the appointment.', 'wpamelia'), 'customer_cabinet' => __('Customer Panel Page URL', 'wpamelia'), 'employee_cabinet' => __('Employee Panel Page URL', 'wpamelia'), 'customer_cabinet_tooltip' => __('Enter here URL of the page with [ameliacustomerpanel] shortcode if you want to send it to your customers in notifications.<br/>Make sure to also add the placeholder in notification so the URL can be sent.', 'wpamelia'), 'employee_cabinet_tooltip' => __('Enter here URL of the page with [ameliaemployeepanel] shortcode if you want to send it to your employees in notifications.<br/>Make sure to also add the placeholder in notification so the URL can be sent.', 'wpamelia'), 'dashboard' => __('Dashboard', 'wpamelia'), 'day1' => __('1 day', 'wpamelia'), 'days2' => __('2 days', 'wpamelia'), 'days3' => __('3 days', 'wpamelia'), 'days4' => __('4 days', 'wpamelia'), 'days5' => __('5 days', 'wpamelia'), 'days6' => __('6 days', 'wpamelia'), 'days_off_settings' => __('Days Off Settings', 'wpamelia'), 'days_off_settings_description' => __('Use these settings to set company working hours and days off which will be applied for every employee', 'wpamelia'), 'deactivate' => __('Deactivate', 'wpamelia'), 'default_appointment_status' => __('Default Appointment Status', 'wpamelia'), 'default_appointment_status_tooltip' => __('All appointments will be scheduled with the<br/>status you choose here.', 'wpamelia'), 'default_items_per_page' => __('Default items per page', 'wpamelia'), 'default_page_on_backend' => __('Default page on back-end', 'wpamelia'), 'default_payment_method' => __('Default Payment Method', 'wpamelia'), 'default_phone_country_code' => __('Default phone country code', 'wpamelia'), 'default_time_slot_step' => __('Default Time Slot Step', 'wpamelia'), 'default_time_slot_step_tooltip' => __('The Time Slot Step you define here will be applied<br/>for all time slots in the plugin.', 'wpamelia'), 'description_mollie' => __('Description for Mollie', 'wpamelia'), 'description_paypal' => __('Description for PayPal', 'wpamelia'), 'description_razorpay' => __('Description for Razorpay', 'wpamelia'), 'name_razorpay' => __('Name for Razorpay', 'wpamelia'), 'description_stripe' => __('Description for Stripe', 'wpamelia'), 'description_wc' => __('Description for WooCommerce', 'wpamelia'), 'dot_comma' => __('Dot-Comma', 'wpamelia'), 'enable_labels_settings' => __('Enable Labels Settings', 'wpamelia'), 'enable_labels_settings_tooltip' => __('Disable this option if you want to translate these<br/>strings using the third party translation plugin.', 'wpamelia'), 'enable_customer_cabinet' => __('Enable Customer Panel', 'wpamelia'), 'enable_employee_cabinet' => __('Enable Employee Panel', 'wpamelia'), 'enable_polyfill' => __('Enable usage for older IE browsers', 'wpamelia'), 'enabled' => __('Enabled', 'wpamelia'), 'endpoint' => __('Endpoint', 'wpamelia'), 'endpoint_tooltip' => __('Enter here an endpoint if you are using Mailgun from EU countries', 'wpamelia'), 'enter_valid_url_warning' => __('Please enter a valid URL with protocol (http:// or https://)', 'wpamelia'), 'envato_api' => __('Envato API', 'wpamelia'), 'envato_api_activate' => __('Activate with Envato', 'wpamelia'), 'envato_api_activated' => __('Activated with Envato', 'wpamelia'), 'events' => __('Events', 'wpamelia'), 'event_description' => __('Event Description', 'wpamelia'), 'event_description_tooltip' => __('Description of the event that will be displayed in the Google Calendar.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'event_description_tooltip_outlook' => __('Description of the event that will be displayed in the Outlook Calendar.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'event_title_and_description' => __('Event Title and Description', 'wpamelia'), 'event_title' => __('Event Title', 'wpamelia'), 'event_title_tooltip' => __('Title of the event that will be displayed in the Google Calendar.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'event_title_tooltip_outlook' => __('Title of the event that will be displayed in the Outlook Calendar.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'meeting_title' => __('Meeting Title', 'wpamelia'), 'meeting_title_tooltip' => __('Title of the meeting that will be displayed in the Zoom.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'meeting_agenda' => __('Meeting Agenda', 'wpamelia'), 'meeting_agenda_tooltip' => __('Agenda of the meeting that will be displayed in the Zoom.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'general' => __('General', 'wpamelia'), 'general_settings' => __('General Settings', 'wpamelia'), 'general_settings_description' => __('Use these settings to define plugin general settings and default settings for your services and appointments', 'wpamelia'), 'gMap_api_key' => __('Google Map API Key', 'wpamelia'), 'gMap_api_key_tooltip' => __('Add Google Map API Key to show Google static map on<br/>"Locations" page.', 'wpamelia'), 'google_calendar_settings' => __('Google Calendar Settings', 'wpamelia'), 'google_calendar_settings_description' => __("Allow synchronizing employee's calendar with Google Calendar for smoother personal scheduling", 'wpamelia'), 'zoom_settings' => __('Zoom Settings', 'wpamelia'), 'google_client_id' => __('Client ID', 'wpamelia'), 'google_client_secret' => __('Client Secret', 'wpamelia'), 'outlook_client_id' => __('Application (client) ID', 'wpamelia'), 'outlook_client_secret' => __('Client Secret', 'wpamelia'), 'google_credentials_obtain' => __('Click here to see how to obtain<br/>Google Client ID and Secret', 'wpamelia'), 'outlook_credentials_obtain' => __('Click here to see how to obtain<br/>Outlook Application (client) ID and Secret', 'wpamelia'), 'google_redirect_uri' => __('Redirect URI', 'wpamelia'), 'google_redirect_uri_tooltip' => __('This is the path in your application that users are redirected to after<br/>they have authenticated with Google. Add this URI in your Google<br/>project credentials under "Authorized redirect URIs".', 'wpamelia'), 'outlook_redirect_uri' => __('Redirect URI', 'wpamelia'), 'outlook_redirect_uri_tooltip' => __('This is the path in your application that users are redirected to after<br/>they have authenticated with Outlook. Add this URI in your Outlook<br/>application under "Redirect URIs".', 'wpamelia'), 'zoom_api_key' => __('Client Key', 'wpamelia'), 'zoom_api_secret' => __('Client Secret', 'wpamelia'), 'zoom_credentials_obtain' => __('Click here to see how to obtain<br/>Zoom API Key and Secret', 'wpamelia'), 'zoom_credentials_tooltip' => __('Click here to see how to obtain<br/>Zoom Application ID, Client ID and Client Secret', 'wpamelia'), 'zoom_jwt_warning' => __('The JWT app type is deprecated. We recommend that you create Server-to-Server OAuth', 'wpamelia'), 'zoom_s2s' => __('Enable Server-to-Server OAuth', 'wpamelia'), 'zoom_account_id' => __('Account ID', 'wpamelia'), 'zoom_client_id' => __('Client ID', 'wpamelia'), 'zoom_client_secret' => __('Client Secret', 'wpamelia'), 'lesson_space_api_key' => __('Lesson Space API Key', 'wpamelia'), 'limit_app_per_customer' => __('Limit appointments per customer', 'wpamelia'), 'limit_app_per_customer_from' => __('Time period is calculated from', 'wpamelia'), 'limit_app_per_customer_from_tt' => __('‘Booking date and time’ will set the limit based on the date when the booking is created, regardless of the appointment date and time.<br>The ‘Appointment date and time’ option will set the limit based on the appointment scheduled date.', 'wpamelia'), 'limit_app_booking_date' => __('Appointment date and time', 'wpamelia'), 'limit_app_date_booked' => __('Booking date and time', 'wpamelia'), 'limit_app_per_customer_tt' => __('The limit is checked by customer email', 'wpamelia'), 'limit_package_per_customer' => __('Limit package purchases per customer', 'wpamelia'), 'limit_package_per_customer_tt' => __('The limit is checked by customer email', 'wpamelia'), 'limit_events_per_customer' => __('Limit events per customer', 'wpamelia'), 'limit_events_per_customer_from' => __('Time period is calculated from', 'wpamelia'), 'limit_events_per_customer_from_tt' => __('‘Booking date and time’ will set the limit based on the date when the booking is created, regardless of the event’s date and time.<br>The ‘Event start date and time’ will set it based on the event’s start date and time.', 'wpamelia'), 'limit_events_booking_date' => __('Event start date and time', 'wpamelia'), 'limit_events_booking_date_tt' => __('Limit will be based on the event date, not based on the date when booking is created.', 'wpamelia'), 'limit_events_date_booked' => __('Booking date and time', 'wpamelia'), 'limit_events_date_booked_tt' => __('Limit will be based on the date when booking is created, regardless of the event date and time.', 'wpamelia'), 'limit_events_per_customer_tt' => __('The limit is checked by customer email', 'wpamelia'), 'number_of_events' => __('Number of events', 'wpamelia'), 'integrations_settings' => __('Integrations', 'wpamelia'), 'integrations_settings_description' => __("Manage Google Calendar Integration, Outlook Calendar Integration, Zoom Integration and Web Hooks", 'wpamelia'), 'h1' => __('1h', 'wpamelia'), 'h10' => __('10h', 'wpamelia'), 'h11' => __('11h', 'wpamelia'), 'h12' => __('12h', 'wpamelia'), 'h1min30' => __('1h 30min', 'wpamelia'), 'h2' => __('2h', 'wpamelia'), 'h3' => __('3h', 'wpamelia'), 'h4' => __('4h', 'wpamelia'), 'h6' => __('6h', 'wpamelia'), 'h8' => __('8h', 'wpamelia'), 'h9' => __('9h', 'wpamelia'), 'identify_country_code' => __('Identify country code by user\'s IP address', 'wpamelia'), 'insert_pending_appointments' => __('Insert Pending Appointments', 'wpamelia'), 'insert_pending_appointments_tooltip' => __('Enable this option if you want your employees to see<br/>appointments with pending status in their calendar.', 'wpamelia'), 'pending_appointments_meetings' => __('Create Meetings For Pending Appointments', 'wpamelia'), 'pending_appointments_meetings_tooltip' => __('Enable this option if you want to create zoom meetings for appointments with pending status.', 'wpamelia'), 'inspect_customer_info' => __('Check customer\'s name for existing email when booking', 'wpamelia'), 'inspect_customer_info_tooltip' => __('Enable this option if you don\'t want to allow "existing customer"<br/>to use different first and last name when booking.', 'wpamelia'), 'instructions' => __('Instructions', 'wpamelia'), 'label_employee' => __('Employee', 'wpamelia'), 'label_employees' => __('Employees', 'wpamelia'), 'label_service' => __('Service', 'wpamelia'), 'label_services' => __('Services', 'wpamelia'), 'labels' => __('Labels', 'wpamelia'), 'labels_settings' => __('Labels Settings', 'wpamelia'), 'labels_settings_description' => __('Use these settings to change labels on frontend pages', 'wpamelia'), 'labels_settings_web_hooks' => __('Use these settings to register URLs to which booking information will be sent when booking action occurs.', 'wpamelia'), 'limit_number_of_fetched_events' => __('Limit Number of Fetched Events', 'wpamelia'), 'live_api_key' => __('Live API Key', 'wpamelia'), 'live_client_id' => __('Live Client ID', 'wpamelia'), 'live_key_id' => __('Live Key ID', 'wpamelia'), 'live_key_secret' => __('Live Key Secret', 'wpamelia'), 'live_publishable_key' => __('Live Publishable Key', 'wpamelia'), 'live_secret' => __('Live Secret', 'wpamelia'), 'live_secret_key' => __('Live Secret Key', 'wpamelia'), 'mail_service' => __('Mail Service', 'wpamelia'), 'mailgun' => __('Mailgun', 'wpamelia'), 'mailgun_api_key' => __('Mailgun API Key', 'wpamelia'), 'mailgun_api_key_warning' => __('Please enter Mailgun API key', 'wpamelia'), 'mailgun_domain' => __('Mailgun Domain', 'wpamelia'), 'mailgun_domain_warning' => __('Please enter Mailgun Domain', 'wpamelia'), 'manage_languages' => __('Manage languages', 'wpamelia'), 'manage_languages_tooltip' => __('Here you can define languages that you want to have in the plugin<br>for translating dynamic strings (names, descriptions, notifications).', 'wpamelia'), 'marketing_tools' => __('Marketing Tools', 'wpamelia'), 'metadata_value_tooltip' => __('You can find available placeholders on the Notifications page', 'wpamelia'), 'min1' => __('1min', 'wpamelia'), 'min10' => __('10min', 'wpamelia'), 'min12' => __('12min', 'wpamelia'), 'min15' => __('15min', 'wpamelia'), 'min2' => __('2min', 'wpamelia'), 'min20' => __('20min', 'wpamelia'), 'min30' => __('30min', 'wpamelia'), 'min45' => __('45min', 'wpamelia'), 'min5' => __('5min', 'wpamelia'), 'minimum_time_before_booking' => __('Minimum time required before booking', 'wpamelia'), 'minimum_time_before_booking_tooltip' => __('Set the time before the appointment when customers<br/>will not be able to book the appointment.', 'wpamelia'), 'minimum_time_before_canceling' => __('Minimum time required before canceling', 'wpamelia'), 'minimum_time_before_canceling_tooltip' => __('Set the time before the appointment when customers<br/>will not be able to cancel the appointment.', 'wpamelia'), 'minimum_time_before_rescheduling' => __('Minimum time required before rescheduling', 'wpamelia'), 'minimum_time_before_rescheduling_tooltip' => __('Set the time before the appointment when customers<br/>will not be able to reschedule the appointment.', 'wpamelia'), 'mollie' => __('Mollie', 'wpamelia'), 'mollie_service' => __('Mollie Service', 'wpamelia'), 'mollie_test_api_key_error' => __('Please enter test API Key', 'wpamelia'), 'mollie_live_api_key_error' => __('Please enter live API Key', 'wpamelia'), 'months3' => __('3 months', 'wpamelia'), 'months6' => __('6 months', 'wpamelia'), 'name' => __('Name', 'wpamelia'), 'notifications_settings' => __('Notification Settings', 'wpamelia'), 'notifications_settings_description' => __('Use these settings to set your mail settings which will be used to notify your customers and employees', 'wpamelia'), 'notify_customers_default' => __('Notify the customer(s) by default', 'wpamelia'), 'number_of_appointments' => __('Number of appointments', 'wpamelia'), 'number_of_events_returned' => __('Maximum Number Of Events Returned', 'wpamelia'), 'number_of_events_returned_tooltip' => __('Maximum number of events returned on one result page.<br/>It is recommended to use smaller number of returned<br/>events if your server performance is not so good.', 'wpamelia'), 'number_of_packages' => __('Number of packages', 'wpamelia'), 'payments' => __('Payments', 'wpamelia'), 'payment_links_enable' => __('Allow payment via Payment Link', 'wpamelia'), 'payments_settings' => __('Payments Settings', 'wpamelia'), 'payments_settings_description' => __('Use these settings to set price format, payment method and coupons that will be used in all bookings', 'wpamelia'), 'payPal' => __('PayPal', 'wpamelia'), 'payPal_live_client_id_error' => __('Please enter live ClientId', 'wpamelia'), 'payPal_live_secret_error' => __('Please enter live Secret', 'wpamelia'), 'payPal_service' => __('PayPal Service', 'wpamelia'), 'payPal_test_client_id_error' => __('Please enter test ClientId', 'wpamelia'), 'payPal_test_secret_error' => __('Please enter test Secret', 'wpamelia'), 'period_available_for_booking' => __('Period available for booking in advance', 'wpamelia'), 'period_available_for_booking_tooltip' => __('Set how far customers can book.', 'wpamelia'), 'php_mail' => __('PHP Mail', 'wpamelia'), 'plugin_not_activated' => __('To receive automatic updates license activation is required. Please visit %s to activate Amelia.', 'wpamelia'), 'price_number_of_decimals' => __('Price Number Of Decimals', 'wpamelia'), 'price_separator' => __('Price Separator', 'wpamelia'), 'price_symbol_position' => __('Price Symbol Position', 'wpamelia'), 'purchase_code' => __('Purchase code', 'wpamelia'), 'provider_details_settings' => __('Provider Details', 'wpamelia'), 'provider_details_settings_description' => __('Use this setting to configure provider details', 'wpamelia'), 'razorpay' => __('Razorpay', 'wpamelia'), 'razorpay_service' => __('Razorpay Service', 'wpamelia'), 'recaptcha_enabled' => __('Enable Google reCAPTCHA', 'wpamelia'), 'recaptcha_enabled_tooltip' => __('Enable this option if you want to add Google reCAPTCHA on the front-end booking forms', 'wpamelia'), 'recaptcha_invisible' => __('Add "Invisible Google reCaptcha"', 'wpamelia'), 'recaptcha_invisible_tooltip' => __('If you enable this option Google reCAPTCHA will stay visible in the bottom right corner<br>but the plugin will check the user automatically, without the need to mark the checkbox.', 'wpamelia'), 'recaptcha_site_key' => __('Google reCAPTCHA Site Key', 'wpamelia'), 'recaptcha_site_key_tooltip' => __('Paste here the Site Key that you have got once you have signed up for the API key pair on Google reCAPTCHA.', 'wpamelia'), 'recaptcha_secret' => __('Google reCAPTCHA Secret Key', 'wpamelia'), 'recaptcha_secret_tooltip' => __('Paste here the Secret Key that you have got once you have signed up for the API key pair on Google reCAPTCHA.', 'wpamelia'), 'recaptcha_site_key_error' => __('Please enter site key', 'wpamelia'), 'recaptcha_secret_error' => __('Please enter secret', 'wpamelia'), 'redirect_url_after_appointment' => __('Redirect URL After Booking', 'wpamelia'), 'redirect_url_after_appointment_tooltip' => __('Customer will be redirected to this URL once he schedules the appointment.', 'wpamelia'), 'remove_google_busy_slots' => __('Remove Google Calendar Busy Slots', 'wpamelia'), 'remove_google_busy_slots_tooltip' => __('Enable this option if you want to remove busy slots in<br/>Google Calendar from Employee\'s working schedule.', 'wpamelia'), 'remove_outlook_busy_slots' => __('Remove Outlook Calendar Busy Slots', 'wpamelia'), 'remove_outlook_busy_slots_tooltip' => __('Enable this option if you want to remove busy slots in<br/>Outlook Calendar from Employee\'s working schedule.', 'wpamelia'), 'include_buffer_time_google' => __('Include Buffer time in Google events', 'wpamelia'), 'include_buffer_time_google_tooltip' => __('If you disable this option buffer time for scheduled appointments<br/>will not be added to the Google Calendar events.', 'wpamelia'), 'include_buffer_time_outlook' => __('Include Buffer time in Outlook events', 'wpamelia'), 'include_buffer_time_outlook_tooltip' => __('If you disable this option buffer time for scheduled appointments<br/>will not be added to the Outlook Calendar events.', 'wpamelia'), 'package_placeholders' => __('Package placeholders', 'wpamelia'), 'package_placeholders_tooltip' => __('Placeholders for package appointments that will be sent in email.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'recurring_placeholders' => __('Recurring placeholders', 'wpamelia'), 'recurring_placeholders_tooltip' => __('Placeholders for recurring appointments that will be sent in email.<br/>You can find available placeholders on the Notifications page.', 'wpamelia'), 'require_cabinet_password' => __('Require password for login', 'wpamelia'), 'require_cabinet_password_tooltip' => __('If you disable this option, your customers will be able to access customer panel with link that is sent to their email account.', 'wpamelia'), 'required_email_field' => __('Set email as a mandatory field', 'wpamelia'), 'required_phone_number_field' => __('Set a phone number as a mandatory field', 'wpamelia'), 'rest_api_clientid' => __('Rest App Client ID', 'wpamelia'), 'rest_api_secret' => __('Rest App Secret', 'wpamelia'), 'roles_settings' => __('Roles Settings', 'wpamelia'), 'roles_settings_description' => __('Use these settings to define settings that will be applied for the specific Amelia roles', 'wpamelia'), 'sandbox_mode' => __('Sandbox Mode', 'wpamelia'), 'select_value_warning' => __('Please select option', 'wpamelia'), 'send_event_invitation_email' => __('Send Event Invitation Email', 'wpamelia'), 'send_event_invitation_email_tooltip' => __('Enable this option if you want your customers to<br/>receive an email about the event.', 'wpamelia'), 'send_ics_attachment_approved' => __('Send ics file for Approved bookings', 'wpamelia'), 'send_ics_attachment_pending' => __('Send ics file for Pending bookings', 'wpamelia'), 'send_ics_attachment_approved_tooltip' => __('Enable this option if you want to send ics file in email after approved bookings.', 'wpamelia'), 'send_ics_attachment_pending_tooltip' => __('Enable this option if you want to send ics file in email after pending bookings.', 'wpamelia'), 'sender_email' => __('Sender Email', 'wpamelia'), 'sender_email_warning' => __('Please enter sender email', 'wpamelia'), 'sender_name' => __('Sender Name', 'wpamelia'), 'sender_name_warning' => __('Please enter sender name', 'wpamelia'), 'service_duration_as_slot' => __('Use service duration for booking a time slot', 'wpamelia'), 'service_duration_as_slot_tooltip' => __('Enable this option if you want to make time slot step<br/>the same as service duration in the booking process', 'wpamelia'), 'set_metaData_and_description' => __('Set MetaData and Description'), 'set_ics_description' => __('Set Ics File Description'), 'settings' => __('Settings', 'wpamelia'), 'settings_lower' => __('settings', 'wpamelia'), 'show_attendees' => __('Allow customers to see other attendees', 'wpamelia'), 'show_attendees_tooltip' => __('Enable this option if you want your customers to see<br/>all attendees in the appointment in their google calendar.', 'wpamelia'), 'show_client_time_zone' => __('Show booking slots in client time zone', 'wpamelia'), 'show_client_time_zone_tooltip' => __('Enable this option if you want to show booking slots<br/>in client time zone.', 'wpamelia'), 'smtp' => __('SMTP', 'wpamelia'), 'smtp_host' => __('SMTP Host', 'wpamelia'), 'smtp_host_warning' => __('Please enter SMTP host', 'wpamelia'), 'smtp_password' => __('SMTP Password', 'wpamelia'), 'smtp_password_warning' => __('Please enter SMTP password', 'wpamelia'), 'smtp_port' => __('SMTP Port', 'wpamelia'), 'smtp_port_warning' => __('Please enter SMTP port', 'wpamelia'), 'smtp_secure' => __('SMTP Secure', 'wpamelia'), 'smtp_secure_disabled' => __('Disabled', 'wpamelia'), 'smtp_secure_ssl' => __('SSL', 'wpamelia'), 'smtp_secure_tls' => __('TLS', 'wpamelia'), 'smtp_username' => __('SMTP Username', 'wpamelia'), 'smtp_username_warning' => __('Please enter SMTP username', 'wpamelia'), 'space_comma' => __('Space-Comma', 'wpamelia'), 'space_dot' => __('Space-Dot', 'wpamelia'), 'stash_entities' => __('Load Entities on page load', 'wpamelia'), 'stash_entities_tooltip' => __('Enable this option if you want to avoid AJAX calls<br>for fetching entities (services, employees, locations, packages, tags)', 'wpamelia'), 'stripe' => __('Stripe', 'wpamelia'), 'stripe_live_publishable_key_error' => __('Please enter live publishable key', 'wpamelia'), 'stripe_live_secret_key_error' => __('Please enter live secret key', 'wpamelia'), 'stripe_service' => __('Stripe Service', 'wpamelia'), 'stripe_ssl_warning' => __('SSL (HTTPS) is not enabled. You will not be able to process live Stripe transactions until SSL is enabled.', 'wpamelia'), 'outlook_ssl_warning' => __('SSL (HTTPS) is not enabled. You will not be able to use Outlook Calendar integration until SSL is enabled.', 'wpamelia'), 'stripe_test_publishable_key_error' => __('Please enter test publishable key', 'wpamelia'), 'stripe_test_secret_key_error' => __('Please enter test secret key', 'wpamelia'), 'template_for_event_title' => __('Template for Event Title', 'wpamelia'), 'test_api_key' => __('Test API Key', 'wpamelia'), 'test_client_id' => __('Test Client ID', 'wpamelia'), 'test_key_id' => __('Test Key ID', 'wpamelia'), 'test_key_secret' => __('Test Key Secret', 'wpamelia'), 'test_mode' => __('Test Mode', 'wpamelia'), 'test_publishable_key' => __('Test Publishable Key', 'wpamelia'), 'test_secret' => __('Test Secret', 'wpamelia'), 'test_secret_key' => __('Test Secret Key', 'wpamelia'), 'two_way_sync' => __('2 Way Sync', 'wpamelia'), 'unable_to_deactivate_plugin' => __('Unable to deactivate plugin. Please try again later.', 'wpamelia'), 'update_for_all' => __('Update for all', 'wpamelia'), 'url' => __('URL', 'wpamelia'), 'custom_fields_upload_path' => __('Attachment upload path', 'wpamelia'), 'custom_fields_upload_path_tooltip' => __('If you leave this field empty, all attachments will be uploaded into the Wordpress uploads folder.', 'wpamelia'), 'value' => __('Value', 'wpamelia'), 'view_activation_settings' => __('View Activation Settings', 'wpamelia'), 'view_appointments_settings' => __('View Appointments Settings', 'wpamelia'), 'view_company_settings' => __('View Company Settings', 'wpamelia'), 'view_days_off_settings' => __('View Working Hours & Days Off Settings', 'wpamelia'), 'view_general_settings' => __('View General Settings', 'wpamelia'), 'view_google_calendar_settings' => __('View Google Calendar Settings', 'wpamelia'), 'view_integrations_settings' => __('View Integrations Settings', 'wpamelia'), 'view_labels_settings' => __('View Labels Settings', 'wpamelia'), 'view_notifications_settings' => __('View Notifications Settings', 'wpamelia'), 'view_payments_settings' => __('View Payments Settings', 'wpamelia'), 'view_provider_details_settings' => __('View Provider Details Settings', 'wpamelia'), 'view_roles_settings_description' => __('View Roles Settings', 'wpamelia'), 'view_web_hooks_settings' => __('View Web Hooks Settings', 'wpamelia'), 'wc' => __('Enable integration with WooCommerce', 'wpamelia'), 'wc_product' => __('Select WooCommerce product', 'wpamelia'), 'wc_product_tooltip' => __('Here you can choose the product that will be used for WooCommerce integration.', 'wpamelia'), 'wc_service' => __('WooCommerce Service', 'wpamelia'), 'wc_on_site_if_free' => __('Hide WooCommerce cart when price is 0', 'wpamelia'), 'website' => __('Website', 'wpamelia'), 'web_hooks' => __('Web Hooks', 'wpamelia'), 'web_hooks_settings' => __('Web Hooks Settings', 'wpamelia'), 'web_hook_delete_confirmation' => __('Are you sure you want to delete this web hook', 'wpamelia'), 'web_hook_action' => __('Action', 'wpamelia'), 'web_hook_action_warning' => __('Please select action', 'wpamelia'), 'web_hook_name_warning' => __('Please enter name', 'wpamelia'), 'web_hook_booking_type' => __('Type', 'wpamelia'), 'web_hook_booking_type_warning' => __('Please enter booking type', 'wpamelia'), 'web_hook_booking_completed' => __('Booking Completed', 'wpamelia'), 'web_hook_booking_rescheduled' => __('Booking Rescheduled', 'wpamelia'), 'web_hook_booking_canceled' => __('Booking Canceled', 'wpamelia'), 'web_hook_booking_status_updated' => __('Booking Status Changed', 'wpamelia'), 'web_hook_package_purchased' => __('Package Purchased', 'wpamelia'), 'web_hook_package_canceled' => __('Package Canceled', 'wpamelia'), 'web_hook_package_tooltip' => __('This Web Hook is triggered when the customer purchases a package without booking any appointments', 'wpamelia'), 'week1' => __('1 week', 'wpamelia'), 'weeks2' => __('2 weeks', 'wpamelia'), 'weeks3' => __('3 weeks', 'wpamelia'), 'weeks4' => __('4 weeks', 'wpamelia'), 'work_hours_days_off' => __('Working Hours & Days Off', 'wpamelia'), 'wp_mail' => __('WP Mail', 'wpamelia'), 'wp_role' => __('WP Role', 'wpamelia'), 'hide_currency_symbol_frontend' => __('Hide Currency Symbol on the booking form', 'wpamelia'), 'custom_currency_symbol' => __('Custom Currency Symbol', 'wpamelia'), ]; } /** * Returns the array for the email notifications strings * * @return array */ public static function getNotificationsStrings() { return [ 'accepted' => __('Accepted', 'wpamelia'), 'after' => __('After', 'wpamelia'), 'already_have_an_account' => __('Already have an account?', 'wpamelia'), 'amelia_sms' => __('Amelia SMS', 'wpamelia'), 'amount_colon' => __('Amount:', 'wpamelia'), 'balance_colon' => __('Balance:', 'wpamelia'), 'balance_recharged' => __('Your balance has been recharged', 'wpamelia'), 'before' => __('Before', 'wpamelia'), 'cant_checkout' => __('This payment cannot be completed', 'wpamelia'), 'cant_recharge_balance' => __('This payment cannot be completed and your account has not been charged', 'wpamelia'), 'carrier' => __('Carrier:', 'wpamelia'), 'change_alpha_sender_id' => __('Change Alpha Sender ID', 'wpamelia'), 'change_password' => __('Change Password', 'wpamelia'), 'choose_ph' => __('Choose Placeholder', 'wpamelia'), 'choose_type' => __('Choose Type', 'wpamelia'), 'choose_when' => __('Choose when', 'wpamelia'), 'configure' => __('Configure', 'wpamelia'), 'configure_placeholder' => __('Configure placeholder', 'wpamelia'), 'configure_placeholder_here' => __('Configure placeholder here', 'wpamelia'), 'cost_colon' => __('Cost:', 'wpamelia'), 'create_notification' => __('Create New Notification', 'wpamelia'), 'cron_instruction' => __('To send this notification please add the following line in your cron', 'wpamelia'), 'current_password_colon' => __('Current Password:', 'wpamelia'), 'current_password_requred' => __('Please enter current password', 'wpamelia'), 'custom_amount' => __('Custom Amount', 'wpamelia'), 'customer_appointment_approved' => __('Appointment Approved', 'wpamelia'), 'customer_appointment_canceled' => __('Appointment Canceled', 'wpamelia'), 'customer_appointment_follow_up' => __('Appointment Follow Up', 'wpamelia'), 'customer_appointment_next_day_reminder' => __('Appointment Next Day Reminder', 'wpamelia'), 'customer_appointment_pending' => __('Appointment Pending', 'wpamelia'), 'customer_appointment_rejected' => __('Appointment Rejected', 'wpamelia'), 'customer_appointment_rescheduled' => __('Appointment Rescheduled', 'wpamelia'), 'customer_account_recovery' => __('Customer Panel Access', 'wpamelia'), 'customer_appointment_updated' => __('Appointment Details Changed', 'wpamelia'), 'customer_birthday_greeting' => __('Birthday Greeting', 'wpamelia'), 'customer_event_approved' => __('Event Booked', 'wpamelia'), 'customer_event_canceled' => __('Event Canceled By Attendee', 'wpamelia'), 'customer_event_follow_up' => __('Event Follow Up', 'wpamelia'), 'customer_event_next_day_reminder' => __('Event Next Day Reminder', 'wpamelia'), 'customer_event_rejected' => __('Event Canceled By Admin', 'wpamelia'), 'customer_event_rescheduled' => __('Event Rescheduled', 'wpamelia'), 'customer_event_updated' => __('Event Details Changed', 'wpamelia'), 'customer_other_notifications' => __('Other', 'wpamelia'), 'provider_other_notifications' => __('Other', 'wpamelia'), 'customer_package_canceled' => __('Package Canceled', 'wpamelia'), 'customer_package_purchased' => __('Package Purchased', 'wpamelia'), 'customize_sms' => __('Customize SMS', 'wpamelia'), 'date_colon' => __('Date:', 'wpamelia'), 'default_content_customer' => __('Dear <b>%customer_full_name%</b>, <br><br>Thank you for choosing our company, <br> <b>%company_name%</b>'), 'default_content_customer_sms' => __('Dear %customer_full_name%, Thank you for choosing our company, %company_name%'), 'default_content_employee' => __('Hi <b>%employee_full_name%</b>, <br><br>Thank you, <br> <b>%company_name%</b>'), 'default_content_employee_sms' => __('Hi %employee_full_name%, Thank you, %company_name%'), 'delivered' => __('Delivered', 'wpamelia'), 'details_changed' => __('Details Changed', 'wpamelia'), 'delete_message' => __('Are you sure you want to delete this notification? <br> You can\'t undo this action', 'wpamelia'), 'dont_have_an_account' => __('Don\'t have an account?', 'wpamelia'), 'duplicate_of' => __('Duplicate of ', 'wpamelia'), 'edit_notification' => __('Edit Notification', 'wpamelia'), 'email' => __('Email', 'wpamelia'), 'email_colon' => __('Email:', 'wpamelia'), 'email_notifications' => __('Email Notifications', 'wpamelia'), 'email_placeholders' => __('Email Placeholders', 'wpamelia'), 'email_taken' => __('This email address is already being used', 'wpamelia'), 'enter_password_warning' => __('Please enter password', 'wpamelia'), 'enter_recipient_email_warning' => __('Please enter recipient email', 'wpamelia'), 'enter_recipient_phone_warning' => __('Please enter recipient phone', 'wpamelia'), 'enter_valid_email_warning' => __('Please enter a valid email address', 'wpamelia'), 'enter_valid_phone_warning' => __('Please enter a valid phone number', 'wpamelia'), 'failed' => __('Failed', 'wpamelia'), 'forgot_password' => __('Forgot Password?', 'wpamelia'), 'incorrect_email' => __('You have entered an incorrect email', 'wpamelia'), 'incorrect_password' => __('You have entered an incorrect password', 'wpamelia'), 'insert_email_placeholders' => __('Insert email placeholders', 'wpamelia'), 'insert_email_placeholders_tooltip' => __('Choose one of the placeholders from the lists below, click on it to copy and then paste into the template.', 'wpamelia'), 'invalid_token' => __('Invalid Token', 'wpamelia'), 'loading' => __('Loading...', 'wpamelia'), 'logout' => __('Logout', 'wpamelia'), 'manage_languages' => __('Manage languages', 'wpamelia'), 'message_colon' => __('Message:', 'wpamelia'), 'messages_lower' => __('messages', 'wpamelia'), 'new_password_colon' => __('New Password:', 'wpamelia'), 'new_password_requred' => __('Please enter new password', 'wpamelia'), 'no_messages' => __('There are no SMS messages...', 'wpamelia'), 'notification_enabled' => __('Notification is enabled', 'wpamelia'), 'notification_not_saved' => __('Notification has not been saved', 'wpamelia'), 'notification_saved' => __('Notification has been saved', 'wpamelia'), 'notification_not_deleted' => __('Notification has not been deleted', 'wpamelia'), 'notification_deleted' => __('Notification has been deleted', 'wpamelia'), 'notification_scheduled' => __('Scheduled notification', 'wpamelia'), 'notification_appointment_status' => __('Appointment status', 'wpamelia'), 'notification_event_action' => __('Event action', 'wpamelia'), 'notification_template' => __('Notification Template', 'wpamelia'), 'notification_triggered' => __('Action triggered notification', 'wpamelia'), 'notification_type' => __('Notification Type', 'wpamelia'), 'notifications' => __('Notifications', 'wpamelia'), 'package_placeholder_label' => __('Package Appointments List', 'wpamelia'), 'paddle' => __('Paddle', 'wpamelia'), 'password' => __('Password', 'wpamelia'), 'past_event' => __('Past event', 'wpamelia'), 'password_colon' => __('Password:', 'wpamelia'), 'password_has_been_changed' => __('Password has been changed', 'wpamelia'), 'password_length' => __('Password must have a length between 5 and 40 characters', 'wpamelia'), 'password_reset_success' => __('Your password has been reset successfully', 'wpamelia'), 'password_whitespace' => __('Password must not contain whitespace', 'wpamelia'), 'passwords_do_not_match' => __('Passwords do not match', 'wpamelia'), 'payment_history' => __('Payment History', 'wpamelia'), 'payment_history_error' => __('Unable to retrieve payments results', 'wpamelia'), 'payment_id' => __('Payment ID', 'wpamelia'), 'payment_id_colon' => __('Payment ID:', 'wpamelia'), 'payments_lower' => __('payments', 'wpamelia'), 'payPal' => __('PayPal', 'wpamelia'), 'ph_appointment_cancel_url' => __('Cancel Appointment Link', 'wpamelia'), 'ph_appointment_date' => __('Date of the appointment', 'wpamelia'), 'ph_appointment_date_time' => __('Date & Time of the appointment', 'wpamelia'), 'ph_initial_appointment_date' => __('Initial Date of the appointment', 'wpamelia'), 'ph_initial_appointment_date_time' => __('Initial Date & Time of the appointment', 'wpamelia'), 'ph_initial_appointment_start_time' => __('Initial Start time of the appointment', 'wpamelia'), 'ph_initial_appointment_end_time' => __('Initial End time of the appointment', 'wpamelia'), 'ph_appointment_duration' => __('Duration of the appointment', 'wpamelia'), 'ph_appointment_end_time' => __('End time of the appointment', 'wpamelia'), 'ph_appointment_id' => __('Id of the appointment', 'wpamelia'), 'ph_appointment_notes' => __('Appointment notes', 'wpamelia'), 'ph_appointment_price' => __('Appointment price', 'wpamelia'), 'ph_appointment_deposit_payment' => __('Appointment deposit', 'wpamelia'), 'ph_payment_link_mollie' => __('Payment link for Mollie', 'wpamelia'), 'ph_payment_link_paypal' => __('Payment link for PayPal', 'wpamelia'), 'ph_payment_link_razorpay' => __('Payment link for Razorpay', 'wpamelia'), 'ph_payment_link_stripe' => __('Payment link for Stripe', 'wpamelia'), 'ph_payment_link_woocommerce' => __('Payment link for WooCommerce', 'wpamelia'), 'ph_payment_type' => __('Payment type', 'wpamelia'), 'ph_appointment_status' => __('Status of the appointment', 'wpamelia'), 'ph_appointment_start_time' => __('Start time of the appointment', 'wpamelia'), 'ph_attendee_code' => __('Attendee code', 'wpamelia'), 'ph_booked_customer' => __('Booked Customer (full name, email, phone)', 'wpamelia'), 'ph_booking_number_of_persons' => __('Number of people', 'wpamelia'), 'ph_category_name' => __('Category name', 'wpamelia'), 'ph_company_address' => __('Company address', 'wpamelia'), 'ph_company_name' => __('Company name', 'wpamelia'), 'ph_company_phone' => __('Company phone', 'wpamelia'), 'ph_company_website' => __('Company website', 'wpamelia'), 'ph_company_email' => __('Company email', 'wpamelia'), 'ph_coupon_used' => __('Used Coupon', 'wpamelia'), 'ph_customer_cabinet_url' => __('Customer Panel Access Link', 'wpamelia'), 'ph_customer_email' => __('Customer email', 'wpamelia'), 'ph_employee_cabinet_url' => __('Employee Panel Access Link', 'wpamelia'), 'ph_employee_password' => __('Employee Password', 'wpamelia'), 'ph_customer_first_name' => __('Customer first name', 'wpamelia'), 'ph_customer_full_name' => __('Customer full name', 'wpamelia'), 'ph_customer_last_name' => __('Customer last name', 'wpamelia'), 'ph_customer_note' => __('Customer note', 'wpamelia'), 'ph_customer_phone' => __('Customer phone', 'wpamelia'), 'ph_employee_description' => __('Employee description', 'wpamelia'), 'ph_employee_email' => __('Employee email', 'wpamelia'), 'ph_employee_first_name' => __('Employee first name', 'wpamelia'), 'ph_employee_full_name' => __('Employee full name', 'wpamelia'), 'ph_employee_last_name' => __('Employee last name', 'wpamelia'), 'ph_employee_name_email_phone' => __('Employee name, email & phone', 'wpamelia'), 'ph_employee_note' => __('Employee note', 'wpamelia'), 'ph_employee_phone' => __('Employee phone', 'wpamelia'), 'ph_employee_photo' => __('Employee photo', 'wpamelia'), 'ph_event_cancel_url' => __('Cancel Event Link', 'wpamelia'), 'ph_event_description' => __('Event description', 'wpamelia'), 'ph_event_location' => __('Event Location', 'wpamelia'), 'ph_event_tickets' => __('Event tickets', 'wpamelia'), 'ph_event_end_date' => __('End date of the event', 'wpamelia'), 'ph_event_end_date_time' => __('End date & time of the event', 'wpamelia'), 'ph_event_end_time' => __('End time of the event', 'wpamelia'), 'ph_event_name' => __('Event name', 'wpamelia'), 'ph_event_period_date' => __('Date period of the event', 'wpamelia'), 'ph_event_period_date_time' => __('Date & Time period of the event', 'wpamelia'), 'ph_event_price' => __('Event price', 'wpamelia'), 'ph_booking_price' => __('Booking price', 'wpamelia'), 'ph_event_deposit_payment' => __('Event deposit', 'wpamelia'), 'ph_event_start_date' => __('Start date of the event', 'wpamelia'), 'ph_event_start_date_time' => __('Start date & time of the event', 'wpamelia'), 'ph_event_start_time' => __('Start time of the event', 'wpamelia'), 'ph_initial_event_start_date' => __('Initial Start date of the event', 'wpamelia'), 'ph_initial_event_start_date_time' => __('Initial Start date & time of the event', 'wpamelia'), 'ph_initial_event_start_time' => __('Initial Start time of the event', 'wpamelia'), 'ph_initial_event_end_date' => __('Initial End date of the event', 'wpamelia'), 'ph_initial_event_end_date_time' => __('Initial End date & time of the event', 'wpamelia'), 'ph_initial_event_end_time' => __('Initial End time of the event', 'wpamelia'), 'ph_extras' => __('Selected extras', 'wpamelia'), 'ph_location_address' => __('Location address', 'wpamelia'), 'ph_location_description' => __('Location description', 'wpamelia'), 'ph_location_name' => __('Location name', 'wpamelia'), 'ph_location_phone' => __('Location phone', 'wpamelia'), 'ph_package_appointments_details' => __('Package appointments details', 'wpamelia'), 'ph_package_name' => __('Package name', 'wpamelia'), 'ph_package_description' => __('Package description', 'wpamelia'), 'ph_package_details_setup' => __('Package appointments list placeholder set up', 'wpamelia'), 'ph_package_duration' => __('Package duration', 'wpamelia'), 'ph_package_price' => __('Package price description', 'wpamelia'), 'ph_package_deposit_payment' => __('Package deposit', 'wpamelia'), 'ph_package_tooltip' => __('Set what details you want to send to your customers/employees about their packages.', 'wpamelia'), 'ph_recurring_appointments_details' => __('Recurring appointments details', 'wpamelia'), 'ph_recurring_details_setup' => __('Recurring appointments details placeholder set up', 'wpamelia'), 'ph_recurring_tooltip' => __('Set what details you want to send to your customers/employees about their recurring appointments.', 'wpamelia'), 'ph_reservation_description' => __('Service or Event description', 'wpamelia'), 'ph_reservation_name' => __('Service or Event name', 'wpamelia'), 'ph_service_description' => __('Service description', 'wpamelia'), 'ph_service_duration' => __('Service duration', 'wpamelia'), 'ph_service_name' => __('Service name', 'wpamelia'), 'ph_service_price' => __('Service price', 'wpamelia'), 'ph_time_zone' => __('Time Zone', 'wpamelia'), 'ph_zoom_host_url' => __('Zoom Start Meeting (Hosts) Link', 'wpamelia'), 'ph_zoom_host_url_date' => __('Date periods of the event with Zoom start links', 'wpamelia'), 'ph_zoom_host_url_date_date' => __('Date & Time periods of the event with Zoom start links', 'wpamelia'), 'ph_zoom_join_url' => __('Zoom Join Meeting (Participants) Link', 'wpamelia'), 'ph_zoom_join_url_date' => __('Date periods of the event with Zoom join links', 'wpamelia'), 'ph_zoom_join_url_date_date' => __('Date & Time periods of the event with Zoom join links', 'wpamelia'), 'ph_google_meet_url_date' => __('Date periods of the event with Google Meet join links', 'wpamelia'), 'ph_google_meet_url_date_date' => __('Date & Time periods of the event with Google Meet join links', 'wpamelia'), 'ph_google_meet_url' => __('Google Meet Join Link', 'wpamelia'), 'phone_colon' => __('Phone:', 'wpamelia'), 'companyPlaceholders' => __('Company', 'wpamelia'), 'customerPlaceholders' => __('Customer', 'wpamelia'), 'packagePlaceholders' => __('Package', 'wpamelia'), 'paymentPlaceholders' => __('Payment', 'wpamelia'), 'employeePlaceholders' => __('Employee', 'wpamelia'), 'categoryPlaceholders' => __('Category', 'wpamelia'), 'locationPlaceholders' => __('Location', 'wpamelia'), 'appointmentPlaceholders' => __('Appointment', 'wpamelia'), 'eventPlaceholders' => __('Event', 'wpamelia'), 'customFieldsPlaceholders' => __('Custom fields', 'wpamelia'), 'extrasPlaceholders' => __('Extra', 'wpamelia'), 'couponsPlaceholders' => __('Coupon', 'wpamelia'), 'placeholder' => __('Placeholder', 'wpamelia'), 'placeholders' => __('Placeholders', 'wpamelia'), 'placeholder_copied' => __('Placeholder Copied', 'wpamelia'), 'prepared' => __('Prepared', 'wpamelia'), 'price' => __('Price', 'wpamelia'), 'pricing' => __('Pricing', 'wpamelia'), 'pricing_error' => __('Unable to retrieve pricing', 'wpamelia'), 'provider_appointment_approved' => __('Appointment Approved', 'wpamelia'), 'provider_appointment_canceled' => __('Appointment Canceled', 'wpamelia'), 'provider_appointment_next_day_reminder' => __('Appointment Next Day Reminder', 'wpamelia'), 'provider_appointment_updated' => __('Appointment Details Changed', 'wpamelia'), 'provider_package_canceled' => __('Package Canceled', 'wpamelia'), 'provider_package_purchased' => __('Package Purchased', 'wpamelia'), 'provider_panel_access' => __('Employee Panel Access', 'wpamelia'), 'provider_panel_recovery' => __('Employee Panel Recovery', 'wpamelia'), 'provider_appointment_pending' => __('Appointment Pending', 'wpamelia'), 'provider_appointment_rejected' => __('Appointment Rejected', 'wpamelia'), 'provider_appointment_rescheduled' => __('Appointment Rescheduled', 'wpamelia'), 'provider_event_approved' => __('Event Booked', 'wpamelia'), 'provider_event_canceled' => __('Event Canceled By Attendee', 'wpamelia'), 'provider_event_next_day_reminder' => __('Event Next Day Reminder', 'wpamelia'), 'provider_event_rejected' => __('Event Canceled By Admin', 'wpamelia'), 'provider_event_rescheduled' => __('Event Rescheduled', 'wpamelia'), 'provider_event_updated' => __('Event Details Changed', 'wpamelia'), 'queued' => __('Queued', 'wpamelia'), 're_type_requred' => __('Please enter new password again', 'wpamelia'), 'recharge' => __('Recharge', 'wpamelia'), 'recharge_balance' => __('Recharge Balance', 'wpamelia'), 'recharge_custom_amount' => __('Recharge Custom Amount', 'wpamelia'), 'recipient_email' => __('Recipient Email', 'wpamelia'), 'recipient_phone' => __('Recipient Phone', 'wpamelia'), 'recovery_email_sent' => __('Account recovery email has been sent', 'wpamelia'), 'recurring_ph_warning' => __('Once set, this placeholder applies to all types of notifications where it is added', 'wpamelia'), 'refresh' => __('Refresh', 'wpamelia'), 'requires_scheduling_setup' => __('Requires Scheduling Setup', 'wpamelia'), 'reset_password' => __('Reset Password', 'wpamelia'), 'retype_new_password_colon' => __('Re-type New Password:', 'wpamelia'), 'same_day' => __('On the same day', 'wpamelia'), 'scheduled_after_appointment' => __('Scheduled After Appointment', 'wpamelia'), 'scheduled_after_event' => __('Scheduled After Event', 'wpamelia'), 'scheduled_before' => __('Scheduled For Before Appointment', 'wpamelia'), 'scheduled_for' => __('Scheduled For', 'wpamelia'), 'security' => __('Security', 'wpamelia'), 'segments_colon' => __('Segments:', 'wpamelia'), 'select_email_template_warning' => __('Please select email template', 'wpamelia'), 'send' => __('Send', 'wpamelia'), 'send_only_this' => __('Send only this notification', 'wpamelia'), 'send_only_this_tooltip' => __('If this is selected the default notification will not be sent for the selected services', 'wpamelia'), 'send_only_this_tooltip_event' => __('If this is selected the default notification will not be sent for the selected events', 'wpamelia'), 'send_recovery_email' => __('Send Recovery Email', 'wpamelia'), 'send_test_email' => __('Send Test Email', 'wpamelia'), 'send_test_sms' => __('Send Test SMS', 'wpamelia'), 'send_test_whatsapp' => __('Send Test WhatsApp Message', 'wpamelia'), 'sender_id_colon' => __('Alpha Sender ID:', 'wpamelia'), 'sender_id_invalid_characters_error' => __('Special characters are not allowed', 'wpamelia'), 'sender_id_length_error' => __('Sender ID supports up to 11 characters', 'wpamelia'), 'sender_id_letter_error' => __('Your ID must include at least one letter', 'wpamelia'), 'sender_id_required' => __('Alpha Sender ID can\'t be empty', 'wpamelia'), 'sender_id_saved' => __('Alpha Sender ID has been saved', 'wpamelia'), 'sent' => __('Sent', 'wpamelia'), 'show_email_codes' => __('</> Show Email Placeholders', 'wpamelia'), 'show_sms_codes' => __('</> Show SMS Placeholders', 'wpamelia'), 'sign_in' => __('Sign In', 'wpamelia'), 'sign_up' => __('Sign Up', 'wpamelia'), 'sms_history' => __('SMS History', 'wpamelia'), 'sms_notifications' => __('SMS Notifications', 'wpamelia'), 'sms_placeholders' => __('SMS Placeholders', 'wpamelia'), 'sms_vat_apply' => __('If you are from a country where VAT or GST applies, a VAT/GST charge will be added to the transaction.', 'wpamelia'), 'status_colon' => __('Status:', 'wpamelia'), 'subject' => __('Subject', 'wpamelia'), 'test_email_error' => __('Email has not been sent', 'wpamelia'), 'test_email_success' => __('Email has been sent', 'wpamelia'), 'test_email_warning' => __('To be able to send test email please configure "Sender Email" in Notification Settings.', 'wpamelia'), 'test_whatsapp_error' => __('WhatsApp message has not been sent', 'wpamelia'), 'test_whatsapp_success' => __('WhatsApp message has been sent', 'wpamelia'), 'test_sms_error' => __('SMS has not been sent', 'wpamelia'), 'test_sms_success' => __('SMS has been sent', 'wpamelia'), 'test_sms_warning' => __('To be able to send test SMS please recharge your balance.', 'wpamelia'), 'text_colon' => __('Text:', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'time_colon' => __('Time:', 'wpamelia'), 'to_customer' => __('To Customer', 'wpamelia'), 'to_employee' => __('To Employee', 'wpamelia'), 'token_expired' => __('Token has been expired', 'wpamelia'), 'type' => __('Type', 'wpamelia'), 'type_colon' => __('Type:', 'wpamelia'), 'undelivered' => __('Undelivered', 'wpamelia'), 'user_colon' => __('User:', 'wpamelia'), 'user_profile' => __('User Profile', 'wpamelia'), 'use_placeholder' => __('Use placeholder:', 'wpamelia'), 'view_message' => __('View Message', 'wpamelia'), 'view_pricing_for' => __('View pricing for:', 'wpamelia'), 'view_profile' => __('View Profile', 'wpamelia'), 'whatsapp_access_token' => __('Permanent access token', 'wpamelia'), 'whatsapp_auto_reply_enable' => __('Enable Auto-reply message', 'wpamelia'), 'whatsapp_auto_reply_notice' => __('Messages sent through WhatsApp are without a reply option, so we advise setting the “Auto-Reply” message', 'wpamelia'), 'whatsapp_auto_reply_token' => __('WhatsApp Webhook Verify Token', 'wpamelia'), 'whatsapp_auto_reply_token_tt' => __('This is a unique hash created for security reasons.<br>Copy this token into the WhatsApp “Verify token“ field when creating a webhook. ', 'wpamelia'), 'whatsapp_auto_reply_msg' => __('WhatsApp Auto-reply message', 'wpamelia'), 'whatsapp_auto_reply_msg_tt' => __('This message is sent once the customer tries to answer the message via WhatsApp<br> in order to notify that the messages sent via WhatsApp are without a reply option. ', 'wpamelia'), 'whatsapp_business_id' => __('WhatsApp Business Account ID', 'wpamelia'), 'whatsapp_choose_template' => __('Choose template ', 'wpamelia'), 'whatsapp_default_language' => __('Default language', 'wpamelia'), 'whatsapp_default_language_tooltip' => __('Only templates that are in the default language will be displayed on the backend. <br> If the template doesn\'t exist in customer\'s language it will be sent in the default language.', 'wpamelia'), 'whatsapp_enter_access_token' => __('Enter Permanent access token ', 'wpamelia'), 'whatsapp_enter_business_id' => __('Enter Business ID', 'wpamelia'), 'whatsapp_choose_language' => __('Choose default language', 'wpamelia'), 'whatsapp_enter_phone_id' => __('Enter Phone number ID', 'wpamelia'), 'whatsapp_header' => __('Header', 'wpamelia'), 'whatsapp_notice_header' => __('The message header needs to be set on the Facebook Developers Settings. The character limit is 60 with the replaced placeholders.', 'wpamelia'), 'whatsapp_notice_body' => __('The message body needs to be set on the Facebook Developers Settings', 'wpamelia'), 'whatsapp_notice_ph' => __('Line breaks will be replaced with semicolons since new rows are not supported in WhatsApp parameters', 'wpamelia'), 'whatsapp_notifications' => __('WhatsApp Notifications', 'wpamelia'), 'whatsapp_enabled' => __('Enable WhatsApp Notifications', 'wpamelia'), 'whatsapp_phone_id' => __('Phone number ID', 'wpamelia'), 'whatsapp_select_ph' => __('Please select placeholder', 'wpamelia'), 'whatsapp_settings' => __('Settings', 'wpamelia'), 'whatsapp_status_tooltip' => __('This is the status in whatsapp.', 'wpamelia'), 'whatsapp_template_name' => __('Template name', 'wpamelia'), 'whatsapp_webhook_url_callback' => __('WhatsApp Webhook Callback URL', 'wpamelia'), ]; } /** * Returns the array for the common strings * * @return array */ public static function getDashboardStrings() { return [ 'appointments_count' => __('# of appointments', 'wpamelia'), 'appointments_revenue' => __('Sum of payments', 'wpamelia'), 'appointments_hours' => __('# of Hours in appointment', 'wpamelia'), 'appointments_load' => __('% of load', 'wpamelia'), 'approved_appointments' => __('Approved Appointments', 'wpamelia'), 'approved_appointments_tooltip' => __('Indicates the number of approved appointments<br/>for a chosen date range.', 'wpamelia'), 'average_bookings' => __('Average Bookings', 'wpamelia'), 'average_bookings_tooltip' => __('Shows the average number of bookings per day<br/>for the selected date range.', 'wpamelia'), 'conversions' => __('Interests / Conversions', 'wpamelia'), 'conversions_tooltip' => __('Shows the number of views for the employee/service/location<br/>vs. the number of times they were booked during<br/>the selected date range.', 'wpamelia'), 'customers_tooltip' => __('Indicates the number of new and returning customers<br/>for the selected date range.', 'wpamelia'), 'dashboard' => __('Dashboard', 'wpamelia'), 'new' => __('New', 'wpamelia'), 'no_today_appointments' => __('There are no appointments for today', 'wpamelia'), 'no_upcoming_appointments' => __('You don\'t have any upcoming appointments yet', 'wpamelia'), 'packages_purchased_count' => __('Times bought', 'wpamelia'), 'pending_appointments' => __('Pending Appointments', 'wpamelia'), 'pending_appointments_tooltip' => __('Shows the number of pending appointments<br/>in the selected date range.', 'wpamelia'), 'percentage_of_load' => __('Percentage of Load', 'wpamelia'), 'percentage_of_load_tooltip' => __('Indicates the percentage of occupied time against available time for appointments<br/>in the chosen date range.', 'wpamelia'), 'returning' => __('Returning', 'wpamelia'), 'revenue' => __('Revenue', 'wpamelia'), 'revenue_tooltip' => __('Shows the total income for paid appointments<br/>in the chosen date range.', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'today_appointments' => __('Today\'s appointments', 'wpamelia'), 'views' => __('Views', 'wpamelia'), 'hello_message_part0' => __('Hello', 'wpamelia'), 'hello_message_part1' => __('You have', 'wpamelia'), 'hello_message_part2' => __('and', 'wpamelia'), 'hello_message_part3' => __('for today', 'wpamelia'), 'upcoming_appointments' => __('Upcoming appointments', 'wpamelia'), 'trafft' => __('Trafft', 'wpamelia'), 'trafft_text1' => __('Cloud-hosted appointment scheduling and business automation software from the authors of Amelia plugin.', 'wpamelia'), 'trafft_text2' => __('No hosting, installation or configuration needed, website builder included!', 'wpamelia'), 'coupon_text' => __('Apply "AMELIA30" coupon code and get 30% on all prices!', 'wpamelia'), 'promo_text' => __('Upgrade your Amelia Lite to Premium ', 'wpamelia'), 'promo_live_qa' => __('LIVE Q&A', 'wpamelia'), 'promo_text1' => __('with Amelia Support', 'wpamelia'), 'only_on_our' => __('only on our', 'wpamelia'), 'youtube' => __('YouTube', 'wpamelia'), 'channel' => __('channel', 'wpamelia'), 'not_show' => __("Don't show again", 'wpamelia'), 'learn_more' => __("Learn More", 'wpamelia'), 'grab_yours' => __("Grab Yours", 'wpamelia'), 'promo' => __("Promo", 'wpamelia'), 'promo_date' => __("1. November at 4Pm cest", 'wpamelia'), ]; } /** * Returns the array for the schedule modal * * @return array */ public static function getScheduleStrings() { return [ 'add_break' => __('Add Break', 'wpamelia'), 'add_day_off' => __('Add Day Off', 'wpamelia'), 'add_day_off_placeholder' => __('Enter holiday or day off name', 'wpamelia'), 'add_period' => __('Add Period', 'wpamelia'), 'add_special_day' => __('Add Special Day', 'wpamelia'), 'apply_to_all_days' => __('Apply to All Days', 'wpamelia'), 'breaks' => __('Breaks', 'wpamelia'), 'company_days_off' => __('Company Days off', 'wpamelia'), 'company_days_off_settings' => __('Company Days Off Settings', 'wpamelia'), 'company_work_hours_settings' => __('Company Working Hours Settings', 'wpamelia'), 'confirm_global_change_working_hours' => __('You will change working hours setting which is also set for each employee separately. Do you want to update it for all employees?', 'wpamelia'), 'day_off_name' => __('Day Off name', 'wpamelia'), 'days_off' => __('Days Off', 'wpamelia'), 'days_off_add' => __('Add Day Off', 'wpamelia'), 'days_off_date_warning' => __('Please enter date', 'wpamelia'), 'days_off_name_warning' => __('Please enter name', 'wpamelia'), 'days_off_repeat_yearly' => __('Repeat Yearly', 'wpamelia'), 'edit_company_days_off' => __('Edit Company Days off', 'wpamelia'), 'employee_days_off' => __('Employee Days off', 'wpamelia'), 'once_off' => __('Once Off', 'wpamelia'), 'pick_a_date_or_range' => __('Pick a date or range', 'wpamelia'), 'pick_a_year' => __('Pick a year', 'wpamelia'), 'reflects_on' => __('Reflects on', 'wpamelia'), 'repeat_every_year' => __('Repeat Every Year', 'wpamelia'), 'save_special_day' => __('Save Special Day', 'wpamelia'), 'set_break_time' => __('Set Break Time', 'wpamelia'), 'set_work_time' => __('Set Work Time', 'wpamelia'), 'special_day_date_warning' => __('Please enter date', 'wpamelia'), 'special_day_end_time_warning' => __('Please enter end time', 'wpamelia'), 'special_day_start_time_warning' => __('Please enter start time', 'wpamelia'), 'work_hours' => __('Work Hours', 'wpamelia'), 'break_hours' => __('Break Hours', 'wpamelia'), 'work_hours_days_off_settings' => __('Working Hours & Days Off Settings', 'wpamelia'), ]; } /** * Returns the array for the entities modal * * @return array */ public static function getEntityFormStrings() { return [ 'delete' => __('Delete', 'wpamelia'), 'loader_message' => __('Please Wait', 'wpamelia'), 'visibility_hide' => __('Hide', 'wpamelia'), 'visibility_show' => __('Show', 'wpamelia'), 'visible' => __('Visible', 'wpamelia'), ]; } /** * Returns the array for the location page * * @return array */ public static function getLocationStrings() { return [ 'add_location' => __('Add Location', 'wpamelia'), 'address' => __('Address', 'wpamelia'), 'click_add_locations' => __('Start by clicking the Add Location button', 'wpamelia'), 'confirm_delete_location' => __('Are you sure you want to delete this location?', 'wpamelia'), 'confirm_duplicate_location' => __('Are you sure you want to duplicate this location?', 'wpamelia'), 'confirm_hide_location' => __('Are you sure you want to hide this location?', 'wpamelia'), 'confirm_show_location' => __('Are you sure you want to show this location?', 'wpamelia'), 'edit_location' => __('Edit Location', 'wpamelia'), 'enter_location_address_warning' => __('Please enter address', 'wpamelia'), 'enter_location_name_warning' => __('Please enter name', 'wpamelia'), 'google_maps_notice' => __('To enable Google maps, enter the Google Map API key in General Settings', 'wpamelia'), 'latitude' => __('Latitude', 'wpamelia'), 'location_address' => __('Location Address', 'wpamelia'), 'location_deleted' => __('Location has been deleted', 'wpamelia'), 'location_hidden' => __('Your Location is hidden', 'wpamelia'), 'location_saved' => __('Location has been saved', 'wpamelia'), 'location_visible' => __('Your Location is visible', 'wpamelia'), 'locations_lower' => __('locations', 'wpamelia'), 'locations_search_placeholder' => __('Search Locations...', 'wpamelia'), 'longitude' => __('Longitude', 'wpamelia'), 'map' => __('Map', 'wpamelia'), 'new_location' => __('New Location', 'wpamelia'), 'no_locations_yet' => __('You don\'t have any locations here yet...', 'wpamelia'), 'not_right_address' => __('This is not the right address?', 'wpamelia'), 'pin_icon' => __('Pin Icon', 'wpamelia'), 'pin_orange' => __('Orange', 'wpamelia'), 'pin_purple' => __('Purple', 'wpamelia'), 'pin_red' => __('Red', 'wpamelia'), 'pin_green' => __('Green', 'wpamelia'), ]; } /** * Returns the array for the service page * * @return array */ public static function getServiceStrings() { return [ 'add_category' => __('Add Category', 'wpamelia'), 'add_duration' => __('Add Duration', 'wpamelia'), 'add_extra' => __('Add Extra', 'wpamelia'), 'add_image' => __('Add Image', 'wpamelia'), 'add_package' => __('Add Package', 'wpamelia'), 'add_service' => __('Add Service', 'wpamelia'), 'add_resource' => __('Add Resource', 'wpamelia'), 'all_employees' => __('All Employees', 'wpamelia'), 'all_locations' => __('All Locations', 'wpamelia'), 'all_services' => __('All Services', 'wpamelia'), 'available_images' => __('Available Images', 'wpamelia'), 'book_package' => __('Book Package', 'wpamelia'), 'bringing_anyone' => __('Show "Bringing anyone with you" option', 'wpamelia'), 'bringing_anyone_tooltip' => __('Hide this option to allow only individual people to<br/>book a group appointment without the possibility<br/>to come with somebody.', 'wpamelia'), 'categories' => __('Categories', 'wpamelia'), 'categories_delete_fail' => __('Unable to delete category', 'wpamelia'), 'categories_positions_saved' => __('Categories positions has been saved', 'wpamelia'), 'categories_positions_saved_fail' => __('Unable to save categories positions', 'wpamelia'), 'category' => __('Category', 'wpamelia'), 'category_add_fail' => __('Unable to add category', 'wpamelia'), 'category_deleted' => __('Category has been deleted', 'wpamelia'), 'category_duplicated' => __('Category has been duplicated', 'wpamelia'), 'category_saved' => __('Category has been saved', 'wpamelia'), 'category_saved_fail' => __('Unable to save category', 'wpamelia'), 'click_add_category' => __('Start by clicking the Add Category button', 'wpamelia'), 'click_add_package' => __('Start by clicking the Add Package button', 'wpamelia'), 'click_add_resource' => __('Start by clicking the Add Resource button', 'wpamelia'), 'click_add_service' => __('Start by clicking the Add Service button', 'wpamelia'), 'confirm_delete_service' => __('Are you sure you want to delete this service?', 'wpamelia'), 'confirm_delete_resource' => __('Are you sure you want to delete this resource?', 'wpamelia'), 'confirm_delete_resource_plural' => __('Are you sure you want to delete these resources?', 'wpamelia'), 'confirm_duplicate_service' => __('Are you sure you want to duplicate this service?', 'wpamelia'), 'confirm_duplicate_resource' => __('Are you sure you want to duplicate this resource?', 'wpamelia'), 'confirm_global_change_service' => __('You will change a setting which is also set for each employee separately. Do you want to update it for all employees?', 'wpamelia'), 'confirm_hide_service' => __('Are you sure you want to hide this service?', 'wpamelia'), 'confirm_hide_resource' => __('Are you sure you want to hide this resource?', 'wpamelia'), 'confirm_show_service' => __('Are you sure you want to show this service?', 'wpamelia'), 'confirm_show_resource' => __('Are you sure you want to show this resource?', 'wpamelia'), 'confirm_delete_package' => __('Are you sure you want to delete this package?', 'wpamelia'), 'confirm_duplicate_package' => __('Are you sure you want to duplicate this package?', 'wpamelia'), 'confirm_hide_package' => __('Are you sure you want to hide this package?', 'wpamelia'), 'confirm_show_package' => __('Are you sure you want to show this package?', 'wpamelia'), 'delete_category_confirmation' => __('Are you sure you want to delete this category', 'wpamelia'), 'delete_extra_confirmation' => __('Are you sure you want to delete this extra', 'wpamelia'), 'duration_and_pricing' => __('Duration & Pricing ', 'wpamelia'), 'custom_pricing_enabled' => __('Custom Duration & Pricing', 'wpamelia'), 'edit_package' => __('Edit Package', 'wpamelia'), 'edit_resource' => __('Edit Resource', 'wpamelia'), 'edit_service' => __('Edit Service', 'wpamelia'), 'enter_extra_name_warning' => __('Please enter extra name', 'wpamelia'), 'enter_extra_price_warning' => __('Please enter extra price', 'wpamelia'), 'enter_non_negative_price_warning' => __('Price must be non-negative number', 'wpamelia'), 'enter_service_price_warning' => __('Please enter price', 'wpamelia'), 'extra_delete_fail' => __('Unable to delete extra', 'wpamelia'), 'gallery' => __('Gallery', 'wpamelia'), 'hex' => __('Hex', 'wpamelia'), 'maximum_capacity' => __('Maximum Capacity', 'wpamelia'), 'maximum_capacity_tooltip' => __('Here you can set the maximum number of people<br/>per one appointment.', 'wpamelia'), 'maximum_quantity' => __('Maximum Quantity', 'wpamelia'), 'minimum_capacity' => __('Minimum Capacity', 'wpamelia'), 'minimum_capacity_tooltip' => __('Here you can set the minimum number of people<br/>per one booking of this service.', 'wpamelia'), 'aggregated_price' => __('The price will multiply by the number of people', 'wpamelia'), 'aggregated_price_tooltip' => __('If you disable this option the price will be the same<br/>regardless of how many customers book in the group appointment.', 'wpamelia'), 'new_category' => __('New Category', 'wpamelia'), 'new_package' => __('New Package', 'wpamelia'), 'new_package_booking' => __('New Package Booking', 'wpamelia'), 'new_resource' => __('New Resource', 'wpamelia'), 'new_service' => __('New Service', 'wpamelia'), 'no_categories_yet' => __('You don\'t have any categories here yet...', 'wpamelia'), 'package_details' => __('Package Details', 'wpamelia'), 'package_hidden' => __('Package is hidden', 'wpamelia'), 'package_saved' => __('Package has been saved', 'wpamelia'), 'package_visible' => __('Package is visible', 'wpamelia'), 'package_deleted' => __('Package has been deleted', 'wpamelia'), 'packages_sorting' => __('Sort Packages:', 'wpamelia'), 'package_price_calculated' => __('Calculated price', 'wpamelia'), 'package_price_calculated_text' => __('Calculated price for package', 'wpamelia'), 'package_price_custom' => __('Custom price', 'wpamelia'), 'packages_positions_saved' => __('Packages positions has been saved', 'wpamelia'), 'packages_positions_saved_fail' => __('Unable to save packages positions', 'wpamelia'), 'package_total' => __('Total', 'wpamelia'), 'package_to_be_booked' => __('to be booked', 'wpamelia'), 'period' => __('Period', 'wpamelia'), 'price' => __('Price', 'wpamelia'), 'pricing' => __('Pricing', 'wpamelia'), 'purchased_packages' => __('Manage Packages', 'wpamelia'), 'schedule_package_total' => __('Number of appointments', 'wpamelia'), 'schedule_package_total_tooltip' => __('A number of appointments included in the package for this service.', 'wpamelia'), 'schedule_package_sum_total_tooltip' => __('A number of appointments included in the package.', 'wpamelia'), 'schedule_package_minimum' => __('Minimum bookings required', 'wpamelia'), 'schedule_package_minimum_tooltip' => __('A minimum number of appointments a customer needs to schedule at the moment of booking.', 'wpamelia'), 'schedule_package_maximum' => __('Maximum bookings required', 'wpamelia'), 'schedule_package_maximum_tooltip' => __('A maximum number of appointments a customer can schedule at the moment of booking.', 'wpamelia'), 'search_resources' => __('Search for a Resource...', 'wpamelia'), 'select_customer' => __('Select Customer', 'wpamelia'), 'select_package_service_warning' => __('Please select at least one service', 'wpamelia'), 'select_service_category_warning' => __('Please select category', 'wpamelia'), 'select_service_duration_warning' => __('Please select duration', 'wpamelia'), 'select_service_employee_warning' => __('Please select select at least one employee', 'wpamelia'), 'service_buffer_time_after' => __('Buffer Time After', 'wpamelia'), 'service_buffer_time_after_tooltip' => __('Time after the appointment (rest, clean up, etc.),<br/>when another booking for same service and<br/>employee cannot be made.', 'wpamelia'), 'service_buffer_time_before' => __('Buffer Time Before', 'wpamelia'), 'service_buffer_time_before_tooltip' => __('Time needed to prepare for the appointment, when<br/>another booking for same service and employee<br/>cannot be made.', 'wpamelia'), 'service_deleted' => __('Service has been deleted', 'wpamelia'), 'service_details' => __('Service Details', 'wpamelia'), 'service_hidden' => __('Service is hidden', 'wpamelia'), 'service_provider_remove_fail' => __('Provider has appointments for this service', 'wpamelia'), 'service_saved' => __('Service has been saved', 'wpamelia'), 'service_visible' => __('Service is visible', 'wpamelia'), 'services_positions_saved' => __('Services positions has been saved', 'wpamelia'), 'services_positions_saved_fail' => __('Unable to save services positions', 'wpamelia'), 'services_sorting' => __('Sort Services:', 'wpamelia'), 'services_sorting_custom' => __('Custom', 'wpamelia'), 'services_sorting_name_asc' => __('Name Ascending', 'wpamelia'), 'services_sorting_name_desc' => __('Name Descending', 'wpamelia'), 'services_sorting_price_asc' => __('Price Ascending', 'wpamelia'), 'services_sorting_price_desc' => __('Price Descending', 'wpamelia'), 'service_show_on_site' => __('Show service on site', 'wpamelia'), 'service_show_on_site_tooltip' => __('If this option is disabled, service will be available for booking from back-end pages only.', 'wpamelia'), 'service_recurring_cycle' => __('Set recurring appointment', 'wpamelia'), 'service_recurring_cycle_tooltip' => __('If this option is disabled, your customers won\'t be able to book recurring appointments at the same time.', 'wpamelia'), 'service_recurring_sub' => __('Handle unavailable recurring dates', 'wpamelia'), 'service_recurring_sub_tooltip' => __('Set how an alternate date should be suggested to the customer<br>if the desired date has no available time-slots for booking.', 'wpamelia'), 'service_recurring_sub_future' => __('Recommend the closest date after', 'wpamelia'), 'service_recurring_sub_past' => __('Recommend the closest date before ', 'wpamelia'), 'service_recurring_sub_both' => __('Recommend the closest date before or after', 'wpamelia'), 'service_recurring_payment' => __('Handle recurring appointment payments', 'wpamelia'), 'service_recurring_payment_tooltip' => __('Set how you want payments to be processed.<br>If you choose to request payment only for the first appointment customers will be able to pay the rest on-site.', 'wpamelia'), 'service_recurring_payment_none' => __('Customers will have to pay only for the first appointment', 'wpamelia'), 'service_recurring_payment_all' => __('Customers will have to pay for all appointments at once', 'wpamelia'), 'shared_capacity' => __('Total Number of Appointments', 'wpamelia'), 'shared_capacity_tooltip' => __('If this option is disabled, you can set the total number of appointments per service. When it is enabled, you can set the total number of appointments per package.', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'update_for_all' => __('Update for all', 'wpamelia'), 'mandatory_extra_enable' => __('Set extra as a mandatory field', 'wpamelia'), 'min_required_extras' => __('Minimum required extras', 'wpamelia'), ]; } /** * Returns the array for the user page * * @return array */ public static function getUserStrings() { return [ 'birthday' => __('Birthday', 'wpamelia'), 'create_new' => __('Create New', 'wpamelia'), 'dont_import' => __('Don\'t import', 'wpamelia'), 'email' => __('Email', 'wpamelia'), 'enter_first_name_warning' => __('Please enter first name', 'wpamelia'), 'enter_last_name_warning' => __('Please enter last name', 'wpamelia'), 'first_name' => __('First Name', 'wpamelia'), 'last_name' => __('Last Name', 'wpamelia'), 'female' => __('Female', 'wpamelia'), 'male' => __('Male', 'wpamelia'), 'notification_language' => __('Notification Language', 'wpamelia'), 'select_wp_user' => __('Select or Create New', 'wpamelia'), 'wp_user' => __('WordPress User', 'wpamelia'), 'wp_user_customer_tooltip' => __('Here you can map a WordPress user to the customer if<br/>you want to give customers access to the list of their<br/>appointments in the back-end of the plugin.', 'wpamelia'), 'wp_user_employee_tooltip' => __('Here you can map a WordPress user to the employee if<br/>you want to give employee access to the list of their<br/>appointments in the back-end of the plugin.', 'wpamelia'), 'wp_customer_lang_tooltip' => __('This is the language in which the customer will receive notifications for bookings made on the admin/employee panel. It is preselected if the customer has booked on a page in the language available in Amelia notifications, or it can be set here.', 'wpamelia'), ]; } /** * Returns the array for the employee page * * @return array */ public static function getEmployeeStrings() { return [ 'activity' => __('Status', 'wpamelia'), 'add_employee' => __('Add Employee', 'wpamelia'), 'assigned_services' => __('Assigned Services', 'wpamelia'), 'available' => __('Available', 'wpamelia'), 'away' => __('Away', 'wpamelia'), 'break' => __('On Break', 'wpamelia'), 'busy' => __('Busy', 'wpamelia'), 'capacity' => __('Capacity', 'wpamelia'), 'click_add_employee' => __('Start by clicking the Add Employee button', 'wpamelia'), 'confirm_delete_employee' => __('Are you sure you want to delete this employee?', 'wpamelia'), 'confirm_duplicate_employee' => __('Are you sure you want to duplicate this employee?', 'wpamelia'), 'confirm_hide_employee' => __('Are you sure you want to hide this employee?', 'wpamelia'), 'confirm_show_employee' => __('Are you sure you want to show this employee?', 'wpamelia'), 'connect' => __('Connect', 'wpamelia'), 'dayoff' => __('Day Off', 'wpamelia'), 'disconnect' => __('Disconnect', 'wpamelia'), 'settings_employee' => __('Provider Settings', 'wpamelia'), 'edit_employee' => __('Edit Employee', 'wpamelia'), 'employee_deleted' => __('Employee has been deleted', 'wpamelia'), 'employee_hidden' => __('Employee is hidden', 'wpamelia'), 'employee_not_deleted' => __('Employee can not be deleted because of the future appointment', 'wpamelia'), 'employee_saved' => __('Employee has been saved', 'wpamelia'), 'employee_search_placeholder' => __('Search Employees...', 'wpamelia'), 'employee_visible' => __('Employee is visible', 'wpamelia'), 'employees_deleted' => __('Employees have been deleted', 'wpamelia'), 'employees_lower' => __('employees', 'wpamelia'), 'employees_not_deleted' => __('Employees could not be deleted because of the future appointment', 'wpamelia'), 'employee_panel_password' => __('Employee Panel Password', 'wpamelia'), 'enter_location_warning' => __('Please select location', 'wpamelia'), 'google_sign_in' => __('Sign in with Google', 'wpamelia'), 'google_sign_out' => __('Sign out from Google', 'wpamelia'), 'outlook_sign_in' => __('Sign in with Outlook', 'wpamelia'), 'outlook_sign_out' => __('Sign out from Outlook', 'wpamelia'), 'google_calendar_error' => __('Unable to connect to Google Calendar', 'wpamelia'), 'google_calendar_tooltip' => __('Here you can connect employee with Google Calendar,<br/>so once the appointment is scheduled it will be<br/>automatically added to employee\'s calendar.', 'wpamelia'), 'outlook_calendar_tooltip' => __('Here you can connect employee with Outlook Calendar,<br/>so once the appointment is scheduled it will be<br/>automatically added to employee\'s calendar.', 'wpamelia'), 'grid_view' => __('Grid View', 'wpamelia'), 'new_employee' => __('New Employee', 'wpamelia'), 'period_location_filter' => __('Applied for default employee location', 'wpamelia'), 'period_location_filter1_tooltip' => __('Select specific location for this period.', 'wpamelia'), 'period_location_filter2_tooltip' => __('Select specific location for each period.', 'wpamelia'), 'period_services_filter' => __('Applied for all assigned services', 'wpamelia'), 'period_services_filter1_tooltip' => __('Select only specific services for this period.<br/>If no services are selected, then all assigned services for this employee<br/>will be available for booking in this period.', 'wpamelia'), 'period_services_filter2_tooltip' => __('Select specific services for each period.', 'wpamelia'), 'price' => __('Price', 'wpamelia'), 'service_provider_remove_fail' => __('Provider has appointments for this service', 'wpamelia'), 'service_provider_remove_fail_all' => __('Provider has appointments for', 'wpamelia'), 'special_days' => __('Special Days', 'wpamelia'), 'special_days_reflect_services' => __('Reflect On', 'wpamelia'), 'table_view' => __('Table View', 'wpamelia'), 'password' => __('Password', 'wpamelia'), 'enter_employee_panel_password' => __('Enter to set or reset password', 'wpamelia'), 'send_employee_panel_access_email' => __('Send Employee Panel Access Email', 'wpamelia'), 'new_password_length' => __('Password must be longer than 3 characters', 'wpamelia'), 'zoom_user_tooltip' => __('Here you can select Zoom User,<br/>so once the appointment is scheduled,<br/>zoom meeting will be automatically created.', 'wpamelia'), 'timezone' => __('Timezone', 'wpamelia'), ]; } /** * Returns the array for the customer page * * @return array */ public static function getCustomerStrings() { return [ 'add_customer' => __('Add Customer', 'wpamelia'), 'all_customer_appointments' => __('All customer appointments', 'wpamelia'), 'click_add_customers' => __('Start by clicking the Add Customer button or', 'wpamelia'), 'confirm_delete_customer' => __('Are you sure you want to delete this customer?', 'wpamelia'), 'customer_deleted' => __('Customer has been deleted', 'wpamelia'), 'customer_not_deleted' => __('Customer can not be deleted because of the future booking', 'wpamelia'), 'customer_not_imported' => __('customers were not imported for missing First Name, Last Name, having invalid Email and Phone number or combination of these reasons.', 'wpamelia'), 'customer_conflicts' => __('customers with the same email address are already in your customer list. If you choose to overwrite with new records some data will be saved.', 'wpamelia'), 'customer_note' => __('Note', 'wpamelia'), 'customer_saved' => __('Customer has been saved', 'wpamelia'), 'customers' => __('Customers', 'wpamelia'), 'customers_deleted' => __('Customers have been deleted', 'wpamelia'), 'customers_lower' => __('customers', 'wpamelia'), 'customers_not_deleted' => __('Customers could not be deleted because of the future bookings', 'wpamelia'), 'customers_search_placeholder' => __('Search Customers...', 'wpamelia'), 'created_on' => __('Created On', 'wpamelia'), 'date_of_birth' => __('Date of Birth', 'wpamelia'), 'edit_customer' => __('Edit Customer', 'wpamelia'), 'email_placeholder' => __('example@mail.com', 'wpamelia'), 'export_tooltip_customers' => __('You can use this option to export customers in CSV file.', 'wpamelia'), 'gender' => __('Gender', 'wpamelia'), 'import_customers' => __('Import customers', 'wpamelia'), 'import_rules_desc' => __('<ul><li>No first row with column names</li><li><b>First</b> and <b>Last name</b> are two separate fields</li><li><b>Date of birth</b> in the same format as chosen in your WP settings (if date format with a comma is used the dates should be in quotes)</li><li><b>Phone</b> has a country code</li><li><b>Gender</b> in Male or Female form</li></ul>'), 'import_rules_req' => __('Valid <b>First</b> and <b>Last name</b> are required fields. <br>If invalid, other values will be skipped and not imported.<br>If multiple customers have the same email address, only the first one will be imported.'), 'import_successful_desc' => __('customers have been imported successfully to your customer list', 'wpamelia'), 'import_tooltip_customers' => __('You can use this option to import customers from a CSV file.', 'wpamelia'), 'imported_customers' => __('Imported customers from file:', 'wpamelia'), 'importing_customers' => __('We are importing customers,<br>this will be completed in a few moments', 'wpamelia'), 'last_appointment' => __('Last Appointment', 'wpamelia'), 'last_appointment_date' => __('Last appointment date', 'wpamelia'), 'last_appointment_ascending' => __('Last Appointment Ascending', 'wpamelia'), 'last_appointment_descending' => __('Last Appointment Descending', 'wpamelia'), 'new_customer' => __('New Customer', 'wpamelia'), 'no_customers_yet' => __('You don\'t have any customers here yet...', 'wpamelia'), 'number_of_appointments' => __('Number of appointments', 'wpamelia'), 'note_internal' => __('Note (Internal)', 'wpamelia'), 'pending_appointments' => __('Pending Appointments', 'wpamelia'), 'required_data' => __('Required fields are: <b>First Name</b> and <b>Last Name</b>.', 'wpamelia'), 'select_date_of_birth' => __('Select Date of Birth', 'wpamelia'), 'total_appointments' => __('Total Appointments', 'wpamelia'), 'upload_csv' => __('Upload Customers .csv file', 'wpamelia'), ]; } /** * Returns the array for the import dialog * * @return array */ public static function getImportStrings() { return [ 'check_csv' => __('Please check your .csv file and try again', 'wpamelia'), 'download_csv' => __('Download .csv', 'wpamelia'), 'drag_drop' => __('Drag and drop or choose from <em>files</em>', 'wpamelia'), 'import_customer_data' => __('Import customer data', 'wpamelia'), 'import_failed' => __('Import failed', 'wpamelia'), 'import_rules' => __('Import rules'), 'import_successful' => __('Import successful', 'wpamelia'), 'import_partially_successful' => __('Import partially successful', 'wpamelia'), 'none_of' => __('None of', 'wpamelia'), 'map_data' => __('Please map corresponding data to columns.', 'wpamelia'), 'missing_value' => __('Missing required value:', 'wpamelia'), 'more_than_one' => __('More than one field of the same type has been selected for different values', 'wpamelia'), 'overwrite_records' => __('Overwrite records', 'wpamelia'), 'prepared_csv' => __('We\'ve prepared a .csv document for you, with customers that were not imported. After fixing issues, you can try again.', 'wpamelia'), 'skip_import' => __('Skip import', 'wpamelia'), 'values_overwritten' => __('Values that will be overwritten', 'wpamelia'), 'values_saved' => __('Values that will be saved', 'wpamelia'), 'wrong_format' => __('Some records have a wrong format', 'wpamelia'), ]; } /** * Returns the array for the finance page * * @return array */ public static function getFinanceStrings() { return [ 'amount' => __('Amount', 'wpamelia'), 'booking_start' => __('Booking Start', 'wpamelia'), 'code' => __('Code', 'wpamelia'), 'code_tooltip' => __('Here you need to define a coupon code which customers will<br/>enter in their booking so they can get a discount.', 'wpamelia'), 'confirm_delete_coupon' => __('Are you sure you want to delete this coupon?', 'wpamelia'), 'confirm_duplicate_coupon' => __('Are you sure you want to duplicate this coupon?', 'wpamelia'), 'confirm_hide_coupon' => __('Are you sure you want to hide this coupon?', 'wpamelia'), 'confirm_show_coupon' => __('Are you sure you want to show this coupon?', 'wpamelia'), 'coupon_deleted' => __('Coupon has been deleted', 'wpamelia'), 'coupon_hidden' => __('Your Coupon is hidden', 'wpamelia'), 'coupon_not_deleted' => __('Coupon has not been deleted', 'wpamelia'), 'coupon_saved' => __('Coupon has been saved', 'wpamelia'), 'coupon_usage_limit_validation' => __('Coupon usage limit must be at least 1', 'wpamelia'), 'coupon_visible' => __('Your Coupon is active', 'wpamelia'), 'coupons' => __('Coupons', 'wpamelia'), 'coupons_deleted' => __('Coupons have been deleted', 'wpamelia'), 'coupons_lower' => __('coupons', 'wpamelia'), 'coupons_multiple_services_text' => __(' & Other Services', 'wpamelia'), 'coupons_multiple_events_text' => __(' & Other Events', 'wpamelia'), 'coupons_not_deleted' => __('Coupons have not been deleted', 'wpamelia'), 'customer_email' => __('Customer Email', 'wpamelia'), 'deduction' => __('Deduction', 'wpamelia'), 'edit_coupon' => __('Edit Coupon', 'wpamelia'), 'employee_email' => __('Employee Email', 'wpamelia'), 'enter_coupon_code_warning' => __('Please enter code', 'wpamelia'), 'export_tooltip_coupons' => __('You can use this option to export coupons in CSV file.', 'wpamelia'), 'export_tooltip_payments' => __('You can use this option to export payments in CSV file<br/>for the selected date range.', 'wpamelia'), 'finance_coupons_search_placeholder' => __('Search Coupons', 'wpamelia'), 'limit' => __('Limit', 'wpamelia'), 'method' => __('Method', 'wpamelia'), 'new_coupon' => __('New Coupon', 'wpamelia'), 'no_coupon_amount' => __('Coupon needs to have discount or deduction', 'wpamelia'), 'no_coupons_yet' => __('You don\'t have any coupons here yet', 'wpamelia'), 'no_payments_yet' => __('You don\'t have any payments here yet', 'wpamelia'), 'no_entities_selected' => __('Select at least one service or event', 'wpamelia'), 'paid' => __('Paid', 'wpamelia'), 'partiallyPaid' => __('Partially Paid', 'wpamelia'), 'payment_date' => __('Payment date', 'wpamelia'), 'payments' => __('Payments', 'wpamelia'), 'payments_lower' => __('payments', 'wpamelia'), 'pending' => __('Pending', 'wpamelia'), 'refunded' => __('Refunded', 'wpamelia'), 'send_interval' => __('Notification interval', 'wpamelia'), 'send_interval_tooltip' => __('Here you can set the number of approved bookings after which the customer will automatically receive the coupon in notification.<br/>Please note that the coupon placeholder needs to be set in the notification template in order for this to work.', 'wpamelia'), 'send_recurring' => __('Recurring notification', 'wpamelia'), 'send_recurring_tooltip' => __('Here you can define if notification interval will repeat.', 'wpamelia'), 'select_all_services' => __('Select All Service', 'wpamelia'), 'services_tooltip' => __('Select the services for which the coupon can be used.', 'wpamelia'), 'select_all_events' => __('Select All Events', 'wpamelia'), 'events_tooltip' => __('Select the events for which the coupon can be used.', 'wpamelia'), 'times_used' => __('Times Used', 'wpamelia'), 'usage_limit' => __('Usage Limit', 'wpamelia'), 'usage_limit_tooltip' => __('Here you need to define the number of coupons for use. After the<br/>limit is reached your coupon will become unavailable.', 'wpamelia'), 'usage_customer_limit' => __('Maximum Usage Per Customer', 'wpamelia'), 'usage_customer_limit_tooltip' => __('Here you can define the maximum number of coupons for use for single customer. After the<br/>limit is reached for single customer, your coupon will become unavailable for that customer.', 'wpamelia'), 'used' => __('Used', 'wpamelia'), ]; } /** * Returns the array for the finance page * * @return array */ public static function getPaymentStrings() { return [ 'appointment_date' => __('Appointment Date', 'wpamelia'), 'appointment_info' => __('Appointment Info', 'wpamelia'), 'event_info' => __('Event Info', 'wpamelia'), 'event_date' => __('Event Date', 'wpamelia'), 'confirm_delete_payment' => __('Are you sure you want to delete this payment?', 'wpamelia'), 'confirm_refund_payment' => __('Are you sure you want to refund this payment?', 'wpamelia'), 'refund_payment_amount' => __('The refund amount is', 'wpamelia'), 'refund_rec_payment' => __('The refund will apply to all recurring appointments', 'wpamelia'), 'discount_amount' => __('Discount', 'wpamelia'), 'deduction' => __('Deduction', 'wpamelia'), 'deposit' => __('Deposit', 'wpamelia'), 'due' => __('Due', 'wpamelia'), 'enter_new_payment_amount' => __('Enter new payment amount', 'wpamelia'), 'expiration_date' => __('Expiration date', 'wpamelia'), 'finance' => __('Finance', 'wpamelia'), 'online' => __('Online', 'wpamelia'), 'package_deal' => __('This booking is part of a package deal', 'wpamelia'), 'package_purchased' => __('Package Purchased', 'wpamelia'), 'paid' => __('Paid', 'wpamelia'), 'paid_deposit' => __('Paid deposit', 'wpamelia'), 'paid_remaining_amount' => __('Paid remaining amount', 'wpamelia'), 'payment_deleted' => __('Payment has been deleted', 'wpamelia'), 'payment_details' => __('Payment Details', 'wpamelia'), 'payment_not_deleted' => __('Payment has not been deleted', 'wpamelia'), 'payment_refund_failed' => __('Payment refund failed', 'wpamelia'), 'payment_refunded' => __('Payment refunded successfully', 'wpamelia'), 'payment_saved' => __('Payment has been saved', 'wpamelia'), 'payments_deleted' => __('Payments have been deleted', 'wpamelia'), 'payments_not_deleted' => __('Payments have not been deleted', 'wpamelia'), 'payment_type' => __('Payment Type', 'wpamelia'), 'plus_tax' => __('(+tax)', 'wpamelia'), 'service_price' => __('Service Price', 'wpamelia'), 'event_price' => __('Event Price', 'wpamelia'), 'subtotal' => __('Subtotal', 'wpamelia'), 'total_price' => __('Total Price', 'wpamelia'), ]; } /** * Returns the array for the appointment strings * * @return array */ public static function getAppointmentStrings() { return [ 'appointment_deleted' => __('Appointment has been deleted', 'wpamelia'), 'appointment_id' => __('Appointment ID', 'wpamelia'), 'appointment_not_deleted' => __('Appointment has not been deleted', 'wpamelia'), 'appointment_saved' => __('Appointment has been saved', 'wpamelia'), 'appointment_status_changed' => __('Appointment status has been changed to ', 'wpamelia'), 'appointments_deleted' => __('Appointments have been deleted', 'wpamelia'), 'appointments_not_deleted' => __('Appointment have not been deleted', 'wpamelia'), 'appointments_search_placeholder' => __('Search for Customers, Employees, Services...', 'wpamelia'), 'assigned' => __('Assigned', 'wpamelia'), 'assigned_to' => __('Assigned to', 'wpamelia'), 'cancel_appointment' => __('Cancel Appointment', 'wpamelia'), 'category' => __('Category', 'wpamelia'), 'change_group_status' => __('Change group status', 'wpamelia'), 'choose_a_group_service' => __('Choose a group service', 'wpamelia'), 'click_add_appointments' => __('Start by clicking the New Appointment button', 'wpamelia'), 'confirm_delete_appointment' => __('Are you sure you want to delete this appointment?', 'wpamelia'), 'confirm_delete_appointment_plural' => __('Are you sure you want to delete these appointments?', 'wpamelia'), 'confirm_duplicate_appointment' => __('Are you sure you want to duplicate this appointment?', 'wpamelia'), 'create_customer' => __('Create Customer', 'wpamelia'), 'create_new' => __('Create New', 'wpamelia'), 'custom_fields' => __('Custom Fields', 'wpamelia'), 'customer_email' => __('Customer Email', 'wpamelia'), 'customer_name' => __('Customer Name', 'wpamelia'), 'customer_phone' => __('Customer Phone', 'wpamelia'), 'customers' => __('Customers', 'wpamelia'), 'customers_singular_plural' => __('Customer(s)', 'wpamelia'), 'customers_tooltip' => __('Here you can define the number of people that are coming<br/>with this customer. The number you can choose depends<br/>on the service and employee capacity.', 'wpamelia'), 'edit_payment_details' => __('Edit Payment Details', 'wpamelia'), 'edit_appointment' => __('Edit Appointment', 'wpamelia'), 'end_time' => __('End Time', 'wpamelia'), 'export_tooltip_appointments' => __('You can use this option to export appointments in CSV file<br/>for the selected date range.', 'wpamelia'), 'export_tooltip_attendees' => __('You can use this option to export attendees in CSV file<br/>for the selected event.', 'wpamelia'), 'minimum_number_of_persons' => __('Minimum number of people for bookings to approve appointment is', 'wpamelia'), 'mollie' => __('Mollie', 'wpamelia'), 'multiple_emails' => __('Multiple Emails', 'wpamelia'), 'new_appointment' => __('New Appointment', 'wpamelia'), 'no_appointments_yet' => __('You don\'t have any appointments here yet...', 'wpamelia'), 'no_selected_customers' => __('There are no selected customers', 'wpamelia'), 'no_selected_extras_requirements' => __('Select customer, employee and service', 'wpamelia'), 'no_selected_slot_requirements' => __('Select date and time', 'wpamelia'), 'no_selected_fields_requirements' => __('Select customer and service', 'wpamelia'), 'notify_attendees' => __('Notify the attendee(s)', 'wpamelia'), 'notify_attendees_tooltip' => __('Check this checkbox if you want your attendee(s) to<br/>receive an email about the event’s updated information.', 'wpamelia'), 'notify_customers' => __('Notify the customer(s)', 'wpamelia'), 'notify_customers_tooltip' => __('Check this checkbox if you want your customer to<br/>receive an email about the scheduled appointment.', 'wpamelia'), 'notify_free_subject' => __('Amelia booking limit notification', 'wpamelia'), 'notify_free_body' => __('You have 15 appointments left available for booking. If you need more please upgrade to full plugin version.', 'wpamelia'), 'bookings_regular_tooltip' => __('customers booked this appointment out of package deal', 'wpamelia'), 'bookings_package_tooltip' => __('customers booked this appointment as a part of package:', 'wpamelia'), 'bookings_payment_package_tooltip' => __('Payments for the package deal are not included in this paid amount', 'wpamelia'), 'recurring_changed_message' => __('List of your appointments has changed. Take one more look and continue by clicking the Save button.', 'wpamelia'), 'required_field' => __('This field is required', 'wpamelia'), 'schedule' => __('Schedule', 'wpamelia'), 'select_customer_warning' => __('Please select at least one customer', 'wpamelia'), 'select_a_customer_warning' => __('Please select customer', 'wpamelia'), 'select_single_customer_warning' => __('Please select customer', 'wpamelia'), 'select_customers' => __('Select Customer(s)', 'wpamelia'), 'select_employee' => __('Select Employee', 'wpamelia'), 'select_employee_warning' => __('Please select employee', 'wpamelia'), 'select_coupon' => __('Select Coupon', 'wpamelia'), 'select_location' => __('Select Location', 'wpamelia'), 'select_max_customer_count_warning' => __('Maximum number of places is', 'wpamelia'), 'select_service' => __('Select Service', 'wpamelia'), 'select_service_category' => __('Select Service Category', 'wpamelia'), 'select_service_warning' => __('Please select service', 'wpamelia'), 'select_rows_settings' => __('Choose how to export group appointments', 'wpamelia'), 'select_rows_settings_event' => __('Choose how to export event attendees', 'wpamelia'), 'selected_customers' => __('Selected Customers', 'wpamelia'), 'service_category' => __('Service Category', 'wpamelia'), 'service_no_extras' => __('This service does not have any extras', 'wpamelia'), 'select_payment_method' => __('Select Payment Method for link', 'wpamelia'), 'stripe' => __('Stripe', 'wpamelia'), 'exported_same_row' => __('Booking info from group appointment exported in the same row', 'wpamelia'), 'exported_separate_rows' => __('Booking info from group appointment exported in separate rows', 'wpamelia'), 'exported_same_row_event' => __('Booking info from attendees exported in the same row', 'wpamelia'), 'exported_separate_rows_event' => __('Booking info from attendees exported in separate rows', 'wpamelia'), 'start_time' => __('Start Time', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'time_slot_unavailable' => __('Time slot is unavailable', 'wpamelia'), 'package_booking_unavailable' => __('Booking is unavailable', 'wpamelia'), 'view_payment_details' => __('View Payment Details', 'wpamelia'), 'booking_cancel_exception' => __('Appointment can\'t be canceled', 'wpamelia'), 'booking_reschedule_exception' => __('Appointment can\'t be rescheduled', 'wpamelia'), 'wc' => __('WooCommerce', 'wpamelia'), ]; } /** * Returns the array for the bookable strings * * @return array */ public static function getBookableStrings() { return [ 'deposit_enabled' => __('Deposit Payment', 'wpamelia'), 'custom_pricing_enabled' => __('Custom Pricing', 'wpamelia'), 'custom_duration_pricing_enabled' => __('Custom Duration and Pricing', 'wpamelia'), ]; } /** * Returns the array for the event strings * * @return array */ public static function getEventStrings() { return [ 'apply_to_all' => __('Apply this to all recurring events', 'wpamelia'), 'click_add_events' => __('Start by clicking the New Event button', 'wpamelia'), 'confirm_delete_attendee' => __('Are you sure you want to delete selected attendee?', 'wpamelia'), 'confirm_delete_attendees' => __('Are you sure you want to delete selected attendees?', 'wpamelia'), 'confirm_delete' => __('Are you sure you want to delete this event?', 'wpamelia'), 'confirm_delete_following' => __('Do you want to delete following canceled events?', 'wpamelia'), 'confirm_duplicate_event' => __('Are you sure you want to duplicate this event?', 'wpamelia'), 'confirm_cancel' => __('Are you sure you want to cancel this event?', 'wpamelia'), 'confirm_cancel_following' => __('Do you want to cancel following events?', 'wpamelia'), 'confirm_open' => __('Are you sure you want to open this event?', 'wpamelia'), 'confirm_open_following' => __('Do you want to open following events?', 'wpamelia'), 'confirm_save_following' => __('Do you want to update following events?', 'wpamelia'), 'description' => __('Description', 'wpamelia'), 'event_cancel_before_delete' => __('Please cancel the event first before deleting it.', 'wpamelia'), 'customize' => __('Customize', 'wpamelia'), 'pricing' => __('Pricing', 'wpamelia'), 'closed' => __('Closed', 'wpamelia'), 'full' => __('Full', 'wpamelia'), 'upcoming' => __('Upcoming', 'wpamelia'), 'edit_event' => __('Edit Event', 'wpamelia'), 'event' => __('Event', 'wpamelia'), 'event_attendees' => __('Attendees', 'wpamelia'), 'event_add_attendee' => __('Add Attendee', 'wpamelia'), 'event_book_persons' => __('Number of people', 'wpamelia'), 'event_book_status' => __('Status', 'wpamelia'), 'event_book_tickets' => __('Number of tickets', 'wpamelia'), 'event_edit_attendee' => __('Edit Attendee', 'wpamelia'), 'event_aggregated_price' => __('The price will multiply by the number of people/spots', 'wpamelia'), 'event_attendee_saved' => __('Attendee has been saved', 'wpamelia'), 'event_attendee_remove' => __('Remove Attendee', 'wpamelia'), 'event_attendees_remove' => __('Remove Selected', 'wpamelia'), 'event_attendees_search' => __('Find Attendees', 'wpamelia'), 'event_attendee_deleted' => __('Attendee have been deleted', 'wpamelia'), 'event_attendee_not_deleted' => __('Attendee have not been deleted', 'wpamelia'), 'event_attendees_deleted' => __('Attendees have been deleted', 'wpamelia'), 'event_attendees_not_deleted' => __('Attendees have not been deleted', 'wpamelia'), 'event_book_more_than_once' => __('Allow the same customer to book more than once', 'wpamelia'), 'event_bringing_anyone' => __('Allow bringing more people', 'wpamelia'), 'event_cancel' => __('Cancel Event', 'wpamelia'), 'event_capacity' => __('Spots:', 'wpamelia'), 'event_close_after_min' => __('Close Event after certain minimum is reached', 'wpamelia'), 'event_close_min_total' => __('Minimum of attendees', 'wpamelia'), 'event_close_min_bookings' => __('Minimum of bookings', 'wpamelia'), 'event_close_min_total_tt' => __('One spot is equal to one attendee.', 'wpamelia'), 'event_close_min_bookings_tt' => __('One booking can have multiple attendees/spots in it.', 'wpamelia'), 'event_close_minimum' => __('Set Minimum', 'wpamelia'), 'event_custom_address' => __('Custom Address', 'wpamelia'), 'event_delete' => __('Delete Event', 'wpamelia'), 'event_deleted' => __('Event has been deleted', 'wpamelia'), 'event_duplicate' => __('Duplicate Event', 'wpamelia'), 'event_name' => __('Name:', 'wpamelia'), 'event_location' => __('Location:', 'wpamelia'), 'event_booking_closes' => __('Booking closes:', 'wpamelia'), 'event_booking_opens' => __('Booking opens:', 'wpamelia'), 'event_booking_closes_on' => __('Closes on:', 'wpamelia'), 'event_booking_closes_apply' => __('If this option is not checked the plugin will calculate the time <br> for closing the booking based on the selected time for the first event', 'wpamelia'), 'event_booking_opens_on' => __('Opens on:', 'wpamelia'), 'event_booking_opens_apply' => __('If this option is not checked the plugin will calculate the time <br> for opening the booking based on the selected time for the first event', 'wpamelia'), 'event_booking_closes_after' => __('Booking closes when event starts', 'wpamelia'), 'event_booking_opens_now' => __('Booking opens immediately', 'wpamelia'), 'event_details' => __('Details', 'wpamelia'), 'event_period_time' => __('Time:', 'wpamelia'), 'event_open' => __('Open Event', 'wpamelia'), 'event_recurring' => __('Recurring:', 'wpamelia'), 'event_recurring_enabled' => __('This is a recurring event', 'wpamelia'), 'event_recurring_period' => __('Repeat Event', 'wpamelia'), 'event_recurring_count' => __('How many times?', 'wpamelia'), 'event_recurring_until' => __('Until when?', 'wpamelia'), 'event_booking_deleted' => __('Event booking has been deleted', 'wpamelia'), 'event_booking_not_deleted' => __('Event booking has not been deleted', 'wpamelia'), 'event_opened' => __('Event has been opened', 'wpamelia'), 'event_canceled' => __('Event has been canceled', 'wpamelia'), 'event_saved' => __('Event has been saved', 'wpamelia'), 'event_schedule' => __('Schedule', 'wpamelia'), 'event_search_placeholder' => __('Search Events...', 'wpamelia'), 'event_max_capacity' => __('Maximum allowed spots', 'wpamelia'), 'event_select_address' => __('Select Address', 'wpamelia'), 'event_staff' => __('Staff', 'wpamelia'), 'event_organizer' => __('Organizer', 'wpamelia'), 'event_organizer_tooltip' => __('Here you can choose the employee that will be added as Organizer of the Google/Outlook Event. <br>Other employees chosen under the Staff option will be added as guests.', 'wpamelia'), 'event_period_dates' => __('Dates:', 'wpamelia'), 'event_tags' => __('Tags', 'wpamelia'), 'event_tags_create' => __('No Tags. Create a new one.', 'wpamelia'), 'event_tags_select_or_create' => __('Select or Create Tag', 'wpamelia'), 'enter_event_name' => __('Enter Event Name', 'wpamelia'), 'enter_event_name_warning' => __('Please enter name', 'wpamelia'), 'event_gallery' => __('Event Gallery:', 'wpamelia'), 'event_colors' => __('Event Colors:', 'wpamelia'), 'event_colors_preset' => __('Preset Colors', 'wpamelia'), 'event_colors_custom' => __('Custom Color', 'wpamelia'), 'select_repeat_period' => __('Select Repeat Period', 'wpamelia'), 'select_repeat_interval' => __('Select Repeat Interval', 'wpamelia'), 'event_show_on_site' => __('Show event on site', 'wpamelia'), 'event_status_changed' => __('Booking status has been changed to ', 'wpamelia'), 'no_events_yet' => __('You don\'t have any events here yet...', 'wpamelia'), 'no_attendees_yet' => __('There are no attendees yet...', 'wpamelia'), 'new_event' => __('New Event', 'wpamelia'), 'price' => __('Price', 'wpamelia'), 'enter_address' => __('Enter Address', 'wpamelia'), 'select' => __('Select', 'wpamelia'), 'time' => __('Time', 'wpamelia'), 'save_single' => __('No, just this one', 'wpamelia'), 'update_following' => __('Update following', 'wpamelia'), 'delete_following' => __('Delete following', 'wpamelia'), 'cancel_following' => __('Cancel following', 'wpamelia'), 'open_following' => __('Open following', 'wpamelia'), 'cancel' => __('Cancel', 'wpamelia'), 'maximum_capacity_reached' => __('Maximum capacity is reached', 'wpamelia'), ]; } /** * Returns the array for the calendar strings * * @return array */ public static function getCalendarStrings() { return [ 'add_customer' => __('Add Customer', 'wpamelia'), 'add_employee' => __('Add Employee', 'wpamelia'), 'add_location' => __('Add Location', 'wpamelia'), 'add_service' => __('Add Service', 'wpamelia'), 'all_employees' => __('All employees', 'wpamelia'), 'appointment_change_time' => __('This will change the time of the appointment. Continue?', 'wpamelia'), 'appointment_drag_breaks' => __('Appointment can\'t be moved because of employee break in the selected period', 'wpamelia'), 'appointment_drag_exist' => __('There is already an appointment for this employee in selected time period', 'wpamelia'), 'appointment_drag_out_schedule' => __('Appointment can\'t be moved because the employee doesn\'t provide this service at the selected time', 'wpamelia'), 'appointment_drag_past' => __('Appointment can\'t be moved in past time period', 'wpamelia'), 'appointment_drag_working_hours' => __('Appointment can\'t be moved out of employee working hours', 'wpamelia'), 'appointment_rescheduled' => __('Appointment has been rescheduled', 'wpamelia'), 'calendar' => __('Calendar', 'wpamelia'), 'confirm' => __('Confirm', 'wpamelia'), 'day' => __('Day', 'wpamelia'), 'group_booking' => __('Group appointment', 'wpamelia'), 'list' => __('List', 'wpamelia'), 'month' => __('Month', 'wpamelia'), 'new_coupon' => __('New Coupon', 'wpamelia'), 'no_appointments_to_display' => __('No appointments to display', 'wpamelia'), 'timeline' => __('Timeline', 'wpamelia'), 'today' => __('Today', 'wpamelia'), 'total' => __('Total', 'wpamelia'), 'timelineDay' => __('Timeline', 'wpamelia'), 'week' => __('Week', 'wpamelia'), ]; } /** * Returns the array for the Customize page * * @return array */ public static function getCustomizeStrings() { return [ 'add_custom_field' => __('Add Custom Field', 'wpamelia'), 'add_extra' => __('Add Extra', 'wpamelia'), 'address' => __('Address', 'wpamelia'), 'are_you_sure_reset_customize' => __('Are you sure you want to reset your form settings?', 'wpamelia'), 'current_changes_will_be_lost' => __('Your current changes will be lost.', 'wpamelia'), 'reset_yes' => __('Yes, Reset', 'wpamelia'), 'reset_no' => __('No, Cancel', 'wpamelia'), 'reset_form' => __('Reset Form', 'wpamelia'), 'package_available' => __('Available in package', 'wpamelia'), 'bringing_anyone_with_you' => __('Bringing Anyone with You?', 'wpamelia'), 'buttons' => __('Buttons', 'wpamelia'), 'btn_type_filled' => __('filled', 'wpamelia'), 'btn_type_plain' => __('plain', 'wpamelia'), 'btn_type_text' => __('text', 'wpamelia'), 'number_of_additional_persons' => __('Number of Additional People', 'wpamelia'), 'one_person' => __('Person', 'wpamelia'), 'one_persons' => __('People', 'wpamelia'), 'package_discount_text' => __('Save', 'wpamelia'), 'extra_colon' => __('Extra', 'wpamelia'), 'select_extra' => __('John Doe', 'wpamelia'), 'select_extra2' => __('Jane Doe', 'wpamelia'), 'qty_colon' => __('Qty', 'wpamelia'), 'default_label' => __('Default Label', 'wpamelia'), 'duration_colon' => __('Duration', 'wpamelia'), 'price_colon' => __('Price', 'wpamelia'), 'checkbox' => __('Checkbox', 'wpamelia'), 'click_add_custom_field' => __('Start by clicking the Add Custom Field button', 'wpamelia'), 'colors_and_fonts' => __('Colors & Fonts', 'wpamelia'), 'text_content' => __('Text Content', 'wpamelia'), 'continue' => __('Continue', 'wpamelia'), 'custom_fields' => __('Custom Fields', 'wpamelia'), 'customize' => __('Customize', 'wpamelia'), 'font' => __('Font', 'wpamelia'), 'label' => __('Label', 'wpamelia'), 'label_name' => __('Label name', 'wpamelia'), 'no_custom_fields_yet' => __('You don\'t have any custom fields here yet...', 'wpamelia'), 'options' => __('Options', 'wpamelia'), 'pick_date_and_time' => __('Pick date & time', 'wpamelia'), 'please_select_service' => __('Please select service', 'wpamelia'), 'primary_color' => __('Primary Color', 'wpamelia'), 'success_color' => __('Success Color', 'wpamelia'), 'warning_color' => __('Warning Color', 'wpamelia'), 'error_color' => __('Error Color', 'wpamelia'), 'primary_gradient' => __('Primary Gradient', 'wpamelia'), 'radio' => __('Radio Buttons', 'wpamelia'), 'reset' => __('Reset', 'wpamelia'), 'select' => __('Selectbox', 'wpamelia'), 'steps' => __('Steps', 'wpamelia'), 'parts' => __('Parts', 'wpamelia'), 'select_service' => __('Select Service', 'wpamelia'), 'global_customize_settings_notice' => __('Global Settings apply only to the Event Calendar and Search Booking forms, to customize other booking forms use the settings on the right.', 'wpamelia'), 'text' => __('Text', 'wpamelia'), 'text-area' => __('Text Area', 'wpamelia'), 'text_color' => __('Text Color', 'wpamelia'), 'placeholder_color' => __('Placeholder Color', 'wpamelia'), 'text_color_on_background' => __('Text Color on Background', 'wpamelia'), 'file' => __('Attachment', 'wpamelia'), 'datepicker' => __('Date Picker', 'wpamelia'), 'preview' => __('Preview', 'wpamelia'), 'bgr_color' => __('Background Color', 'wpamelia'), 'bgr_gradient_color1' => __('Background Gradient Color 1', 'wpamelia'), 'bgr_gradient_color2' => __('Background Gradient Color 2', 'wpamelia'), 'bgr_gradient_angle' => __('Background Gradient Angle', 'wpamelia'), 'input_color' => __('Input Color', 'wpamelia'), 'input_text_color' => __('Input Text Color', 'wpamelia'), 'dropdown_color' => __('Dropdown Color', 'wpamelia'), 'dropdown_text_color' => __('Dropdown Text Color', 'wpamelia'), 'image_color' => __('Image Color', 'wpamelia'), 'recurring_active' => __('Repeat this appointment', 'wpamelia'), 'first_name_colon' => __('First Name', 'wpamelia'), 'last_name_colon' => __('Last Name', 'wpamelia'), 'last_name_input_field' => __('Last Name Input Field', 'wpamelia'), 'email_colon' => __('Email', 'wpamelia'), 'email_input_field' => __('Email Input Field', 'wpamelia'), 'phone_colon' => __('Phone', 'wpamelia'), 'phone_input_field' => __('Phone Input Field', 'wpamelia'), 'confirm' => __('Confirm', 'wpamelia'), 'back' => __('Back', 'wpamelia'), 'go_back' => __('Go Back', 'wpamelia'), 'service_name' => __('Service name', 'wpamelia'), 'display_field' => __('Display Field:', 'wpamelia'), 'mandatory_field' => __('Mandatory Field:', 'wpamelia'), 'end_time_visibility' => __('End Time Visibility:', 'wpamelia'), 'any_employee_visibility' => __('Any Employee Option Visibility:', 'wpamelia'), 'event_type' => __('Event Type', 'wpamelia'), 'event_location' => __('Event Location', 'wpamelia'), 'open' => __('Open', 'wpamelia'), 'full' => __('Full', 'wpamelia'), 'from' => __('From', 'wpamelia'), 'upcoming' => __('Upcoming', 'wpamelia'), 'event_free' => __('Free', 'wpamelia'), 'event_capacity' => __('Capacity', 'wpamelia'), 'event_date' => __('Event Date and Time', 'wpamelia'), 'event_price' => __('Event Price', 'wpamelia'), 'event_about' => __('About this Event', 'wpamelia'), 'event_book' => __('Book this event', 'wpamelia'), 'event_book_persons' => __('Number of people', 'wpamelia'), 'categories' => __('Categories', 'wpamelia'), 'services_lower' => __('services', 'wpamelia'), 'service_images_thumbs' => __('Image Thumbs', 'wpamelia'), 'view_more' => __('View More', 'wpamelia'), 'service_badge' => __('Service badge', 'wpamelia'), 'service_price' => __('Service price', 'wpamelia'), 'service_employees_list' => __('Service employees list', 'wpamelia'), 'package_badge' => __('Package badge', 'wpamelia'), 'package_price' => __('Package price', 'wpamelia'), 'package_services_list' => __('Package services list', 'wpamelia'), 'h' => __('h', 'wpamelia'), 'min' => __('min', 'wpamelia'), 'service_info' => __('Service Info', 'wpamelia'), 'maximum_quantity_colon' => __('Maximum Quantity:', 'wpamelia'), 'description_colon' => __('Description:', 'wpamelia'), 'category_colon' => __('Category:', 'wpamelia'), 'capacity_colon' => __('Capacity:', 'wpamelia'), 'weeks' => __('weeks', 'wpamelia'), 'package_book_duration' => __('The package is time-limited to', 'wpamelia'), 'book_appointment' => __('Book Appointment', 'wpamelia'), 'package_rules_description' => __('Package rules and description', 'wpamelia'), 'selected_services' => __('Selected services', 'wpamelia'), 'manage_languages' => __('Manage languages', 'wpamelia'), 'package_name' => __('Package Name', 'wpamelia'), 'congratulations' => __('Congratulations!', 'wpamelia'), 'add_to_calendar' => __('Add to Calendar', 'wpamelia'), 'finish_appointment' => __('Finish', 'wpamelia'), 'form_colors' => __('Form colors', 'wpamelia'), 'form_type_step_by_step' => __('Step By Step Booking Form', 'wpamelia'), 'event_status' => __('Event Status', 'wpamelia'), 'event_filters' => __('Filters', 'wpamelia'), 'event_show_more' => __('Show more', 'wpamelia'), 'event_show_less' => __('Show less', 'wpamelia'), 'event_book_event' => __('Book event', 'wpamelia'), 'form_block_service' => __('Service', 'wpamelia'), 'form' => __('Form', 'wpamelia'), 'form_flow' => __('Form Flow', 'wpamelia'), 'custom' => __('Custom', 'wpamelia'), 'font_url' => __('Font URL', 'wpamelia'), 'font_family' => __('Font Family', 'wpamelia'), 'use_global_colors' => __('Use Global Colors', 'wpamelia'), 'service_selection' => __('Service Selection', 'wpamelia'), 'service_colon' => __('Service', 'wpamelia'), 'select_location' => __('Select Location', 'wpamelia'), 'employee_colon' => __('Employee', 'wpamelia'), 'select_employee' => __('Select Employee', 'wpamelia'), 'please_select_employee' => __('Please select employee', 'wpamelia'), 'please_select_location' => __('Please select location', 'wpamelia'), 'dropdown_category_heading' => __('Category', 'wpamelia'), 'dropdown_items_heading' => __('Service', 'wpamelia'), 'dropdown_empty' => __('No matching data', 'wpamelia'), 'bringing_anyone' => __('Bringing Anyone With You', 'wpamelia'), 'bringing_anyone_title' => __('Bringing anyone with you?', 'wpamelia'), 'show_more' => __('Show more', 'wpamelia'), 'show_less' => __('Show less', 'wpamelia'), 'date_time' => __('Date & Time', 'wpamelia'), 'date_time_slots_selected' => __('All slots are selected', 'wpamelia'), 'info_step' => __('Your Information', 'wpamelia'), 'enter_first_name' => __('Enter first name', 'wpamelia'), 'enter_first_name_warning' => __('Please enter first name', 'wpamelia'), 'enter_last_name' => __('Enter last name', 'wpamelia'), 'enter_last_name_warning' => __('Please enter last name', 'wpamelia'), 'enter_email' => __('Enter email', 'wpamelia'), 'enter_valid_email_warning' => __('Please enter valid email', 'wpamelia'), 'enter_phone' => __('Enter phone', 'wpamelia'), 'enter_phone_warning' => __('Please enter phone', 'wpamelia'), 'payment_step' => __('Payment', 'wpamelia'), 'summary' => __('Summary', 'wpamelia'), 'summary_services' => __('Services', 'wpamelia'), 'summary_services_subtotal' => __('Service Subtotal', 'wpamelia'), 'summary_person' => __('person', 'wpamelia'), 'summary_persons' => __('people', 'wpamelia'), 'subtotal' => __('Subtotal', 'wpamelia'), 'total_amount_colon' => __('Total Amount', 'wpamelia'), 'payment_onsite_sentence' => __('The payment will be done on-site.', 'wpamelia'), 'appointment_id' => __('Appointment ID', 'wpamelia'), 'congrats_total_amount' => __('Total Amount', 'wpamelia'), 'congrats_payment' => __('Payment', 'wpamelia'), 'your_name_colon' => __('Your Name', 'wpamelia'), 'email_address_colon' => __('Email Address', 'wpamelia'), 'phone_number_colon' => __('Phone Number', 'wpamelia'), 'congrats_date' => __('Date', 'wpamelia'), 'congrats_time' => __('Local Time', 'wpamelia'), 'congrats_service' => __('Service', 'wpamelia'), 'congrats_employee' => __('Employee', 'wpamelia'), 'choose_form' => __('Choose a Form', 'wpamelia'), 'choose_form_for_customize' => __('Choose a form you want to customize. The Step-by-Step 2.0 form is the new and improved version which provides you with better design and user experience, as well as better speed.', 'wpamelia'), 'sbs_booking_form' => __('Step-by-Step Booking Form 2.0', 'wpamelia'), 'sbs_booking_form_old' => __('Booking Forms 1.0', 'wpamelia'), 'new_caps' => __('NEW', 'wpamelia'), 'redesigned_sbs_booking_form' => __('Redesigned and upgraded Step-by-Step Booking form with a better user experience, animations, improved speed, and a stand-out design!', 'wpamelia'), 'old_forms_text' => __('Step-by-Step 1.0 Booking, Catalog Booking, Search Booking, Event List and Event Calendar Bookings.', 'wpamelia'), 'primary_and_state_colors' => __('Primary and state colors', 'wpamelia'), 'primary' => __('Primary', 'wpamelia'), 'warning' => __('Warning', 'wpamelia'), 'sidebar' => __('Sidebar', 'wpamelia'), 'background_color' => __('Background Color', 'wpamelia'), 'content' => __('Content', 'wpamelia'), 'heading_text_color' => __('Heading Text Color', 'wpamelia'), 'content_text_color' => __('Content Text Color', 'wpamelia'), 'main_content' => __('Main Content', 'wpamelia'), 'input_fields' => __('Input Fields', 'wpamelia'), 'border_color' => __('Border Color', 'wpamelia'), 'placeholder' => __('Placeholder', 'wpamelia'), 'dropdowns' => __('Dropdowns', 'wpamelia'), 'employee_description' => __('Employee Description Popup', 'wpamelia'), 'employee_information' => __('Employee Information', 'wpamelia'), 'employee_information_package' => __('Employee Information', 'wpamelia'), 'select_this_employee' => __('Select this employee', 'wpamelia'), 'select_this_employee_package' => __('Select this employee', 'wpamelia'), 'init_cell' => __('Init Cell', 'wpamelia'), 'init_cell_text' => __('Init Cell Text', 'wpamelia'), 'cell_selected_background' => __('Cell Selected Background', 'wpamelia'), 'cell_selected_text' => __('Cell Selected Text', 'wpamelia'), 'cell_disabled_background' => __('Cell Disabled Background', 'wpamelia'), 'cell_disabled_text' => __('Cell Disabled Text', 'wpamelia'), 'primary_background' => __('Primary background', 'wpamelia'), 'primary_text' => __('Primary text', 'wpamelia'), 'secondary_background' => __('Secondary background', 'wpamelia'), 'secondary_text' => __('Secondary text', 'wpamelia'), 'layout' => __('Layout', 'wpamelia'), 'layout_and_inputs' => __('Layout & Inputs', 'wpamelia'), 'colors' => __('Colors', 'wpamelia'), 'fonts' => __('Fonts', 'wpamelia'), 'fonts_and_colors' => __('Fonts and colors', 'wpamelia'), 'order' => __('Order', 'wpamelia'), 'change_colors' => __('Change Colors', 'wpamelia'), 'step_title' => __('Step Title', 'wpamelia'), 'footer_buttons' => __('Footer Buttons', 'wpamelia'), 'step_content' => __('Step Content', 'wpamelia'), 'alert_content' => __('Alert Content', 'wpamelia'), 'popup_title' => __('Popup Title', 'wpamelia'), 'popup_content' => __('Popup Content', 'wpamelia'), 'popup_buttons' => __('Popup Buttons', 'wpamelia'), 'primary_btn_type' => __('Primary Button Type', 'wpamelia'), 'secondary_btn_type' => __('Secondary Button Type', 'wpamelia'), 'finish_btn_type' => __('Finish Button Type', 'wpamelia'), 'panel_btn_type' => __('Panel Button Type', 'wpamelia'), 'summary_segment' => __('Summary Segment', 'wpamelia'), 'payment_segment' => __('Payment Segment', 'wpamelia'), 'heading_title' => __('Heading Title', 'wpamelia'), 'sub_steps' => __('Sub Steps', 'wpamelia'), 'button_type' => __('Button Type', 'wpamelia'), /* csb - customize side bar */ 'csb_global_settings_content' => __('Fonts and colors', 'wpamelia'), 'csb_sidebar_content' => __('Set up Sidebar visibility and its content', 'wpamelia'), 'csb_services' => __('Service Selection', 'wpamelia'), 'csb_services_content' => __('Set up Services, Locations, Employees selection options', 'wpamelia'), 'csb_date_time' => __('Date & Time Selection', 'wpamelia'), 'csb_date_time_content' => __('Set up Calendar layout and Recurring popup options', 'wpamelia'), 'csb_info_step' => __('Customer Information', 'wpamelia'), 'csb_info_step_content' => __('Field order, mandatory fields, labels and display options', 'wpamelia'), 'csb_payment' => __('Payment Summary', 'wpamelia'), 'csb_payment_content' => __('Set up labels and buttons', 'wpamelia'), 'csb_layout_labels_content' => __('Layout and labels options', 'wpamelia'), 'csb_placeholder' => __('placeholder', 'wpamelia'), 'csb_mandatory' => __('mandatory notice', 'wpamelia'), 'cpb_service_appointment' => __('Services list, Appointments', 'wpamelia'), 'cpb_your_info_content' => __('Registration, Telephone Number, Email', 'wpamelia'), 'cpb_payment_content' => __('Payment type, deposit payment...', 'wpamelia'), 'cpb_congratulations_content' => __('Overview, tables, calendars...', 'wpamelia'), 'cb_global_settings_heading' => __('Global Settings', 'wpamelia'), 'cb_sidebar' => __('Sidebar', 'wpamelia'), 'cb_section' => __('Section', 'wpamelia'), 'cb_field_order_heading' => __('Field Order', 'wpamelia'), 'cb_congratulations_heading' => __('Congratulations', 'wpamelia'), 'sidebar_footer' => __('Footer', 'wpamelia'), 'plus_more' => __('+more', 'wpamelia'), 'get_in_touch' => __('Get in Touch', 'wpamelia'), 'collapse_menu' => __('Collapse Menu', 'wpamelia'), 'sb_radio_filled' => __('Filled', 'wpamelia'), 'sb_radio_plain' => __('Plain', 'wpamelia'), 'sb_radio_text' => __('Text', 'wpamelia'), 'location_input_field' => __('Location Input Field', 'wpamelia'), 'employee_input_field' => __('Employee Input Field', 'wpamelia'), 'continue_button_type' => __('Continue Button Type', 'wpamelia'), 'primary_button_type' => __('Primary Button Type', 'wpamelia'), 'secondary_button_type' => __('Secondary Button Type', 'wpamelia'), 'location' => __('Location', 'wpamelia'), 'heading' => __('Heading', 'wpamelia'), 'info' => __('Info', 'wpamelia'), 'popup_heading' => __('Popup Heading', 'wpamelia'), 'calendar_slot_end_time' => __('Calendar Slot End Time', 'wpamelia'), 'show_busy_slots' => __('Show Busy Time Slots', 'wpamelia'), 'calendar_time_zone' => __('Calendar Time Zone', 'wpamelia'), 'extras_heading' => __('Extras Heading', 'wpamelia'), 'extras_description' => __('Extras Description', 'wpamelia'), 'extras_duration' => __('Extras Duration', 'wpamelia'), 'first_name' => __('First Name', 'wpamelia'), 'last_name' => __('Last Name', 'wpamelia'), 'email' => __('Email', 'wpamelia'), 'phone' => __('Phone', 'wpamelia'), 'finish_button_type' => __('Finish Button Type', 'wpamelia'), 'panel_button_type' => __('Panel Button Type', 'wpamelia'), 'sidebar_visibility' => __('Sidebar Visibility', 'wpamelia'), 'publish_form' => __('Publish Form', 'wpamelia'), 'view_all' => __('View All', 'wpamelia'), 'csb_categories' => __('Categories', 'wpamelia'), 'csb_categories_content' => __('Set up categories cards', 'wpamelia'), 'cards' => __('Cards', 'wpamelia'), 'card_button_type' => __('Card Button Type', 'wpamelia'), 'csb_category_items' => __('Services and Packages Overview', 'wpamelia'), 'csb_category_items_content' => __('Set up Services and Packages view', 'wpamelia'), 'csb_category_services' => __('Services Overview', 'wpamelia'), 'csb_category_services_content' => __('Set up Services view', 'wpamelia'), 'csb_category_service' => __('Service Details', 'wpamelia'), 'csb_category_service_content' => __('Set up Service detailed view', 'wpamelia'), 'csb_category_package' => __('Package Details', 'wpamelia'), 'csb_category_package_content' => __('Set up Package detailed view', 'wpamelia'), 'booking_form' => __('Booking Form', 'wpamelia'), 'booking_form_content' => __('Set options, colors and labels for booking form', 'wpamelia'), 'cat_booking_form' => __('Catalog Booking Form 2.0', 'wpamelia'), 'redesigned_cat_booking_form' => __('Modernized Catalog Booking Form 2.0 with better user experience, improved speed, animation and a stand-out design!', 'wpamelia'), // cl - categories list 'cl_card' => __('Card', 'wpamelia'), 'card_services_number' => __('Total Number of Services', 'wpamelia'), 'card_packages_number' => __('Total Number of Packages', 'wpamelia'), 'back_btn_heading' => __('Back Button', 'wpamelia'), 'back_btn_type' => __('“Back” Button Type', 'wpamelia'), 'back_btn' => __('Go Back', 'wpamelia'), 'booking_btn_type' => __('“Book Now” Button Type', 'wpamelia'), // cl - category list 'cl_btn' => __('Main Category Button', 'wpamelia'), 'cl_side_color' => __('Category Card Side Color', 'wpamelia'), // cli - category items list // keys only used on backend customize 'cil_filter_menu_btn' => __('Filter Menu Button Type', 'wpamelia'), 'cil_filter_buttons' => __('“All/Packages/Services” filter option', 'wpamelia'), 'cil_sidebar' => __('Categories Sidebar', 'wpamelia'), 'cil_filter_block' => __('Filters Block', 'wpamelia'), 'cil_side_menu_block' => __('Categories Sidebar', 'wpamelia'), 'cil_main_header' => __('Page Header', 'wpamelia'), 'cil_main_content' => __('Main Content', 'wpamelia'), 'employee_btn_type' => __('"View Employee" Button Type', 'wpamelia'), 'book_employee_btn_type' => __('Book Option on Employee Dialog', 'wpamelia'), 'employee_dialog' => __('Employee Dialog', 'wpamelia'), 'employee_info' => __('Employee information', 'wpamelia'), 'book_service' => __('Book This Service', 'wpamelia'), 'book_package' => __('Book This Package', 'wpamelia'), 'package_category' => __('Package Category', 'wpamelia'), 'package_duration' => __('Package Duration', 'wpamelia'), 'package_capacity' => __('Package Capacity', 'wpamelia'), 'package_location' => __('Package Location', 'wpamelia'), 'service_category' => __('Service Category', 'wpamelia'), 'service_duration' => __('Service Duration', 'wpamelia'), 'service_capacity' => __('Service Capacity', 'wpamelia'), 'service_location' => __('Service Location', 'wpamelia'), 'service_about' => __('About Service', 'wpamelia'), 'service_employees' => __('Employees', 'wpamelia'), 'package_about' => __('About Package', 'wpamelia'), 'package_employees' => __('Employees', 'wpamelia'), 'package_block' => __('Packages Block', 'wpamelia'), 'cil_filter_input' => __('“Search” option', 'wpamelia'), 'cil_filter_employee' => __('“Filter by Employee” option', 'wpamelia'), 'cil_filter_location' => __('“Filter by Location” option', 'wpamelia'), // keys used on back and front 'filter_input' => __('Search', 'wpamelia'), 'filter_employee' => __('Filter by Employee', 'wpamelia'), 'filter_location' => __('Filter by Location', 'wpamelia'), 'filter_all' => __('All', 'wpamelia'), 'filter_packages' => __('Packages', 'wpamelia'), 'filter_services' => __('Services', 'wpamelia'), 'available' => __('Available', 'wpamelia'), 'heading_service' => __('Service', 'wpamelia'), 'heading_services' => __('Services', 'wpamelia'), 'package' => __('Package', 'wpamelia'), 'packages' => __('Packages', 'wpamelia'), 'no_search_data' => __('No results', 'wpamelia'), 'view_employees' => __('View Employees', 'wpamelia'), 'save' => __('Save', 'wpamelia'), 'free' => __('Free', 'wpamelia'), 'in_package' => __('In Package', 'wpamelia'), 'book_now' => __('Book Now', 'wpamelia'), 'about_service' => __('About Service', 'wpamelia'), 'about_package' => __('About Package', 'wpamelia'), 'view_all_photos' => __('View all photos', 'wpamelia'), 'service_available_in_package' => __('This Service is available in a Package', 'wpamelia'), 'more_packages' => __('View More Packages', 'wpamelia'), 'less_packages' => __('View Less Packages', 'wpamelia'), 'package_includes' => __('Package includes', 'wpamelia'), 'employee_price' => __('Employee Price', 'wpamelia'), 'tab_employees' => __('Employees', 'wpamelia'), 'extras_costs_colon' => __('Extras Cost:', 'wpamelia'), 'subtotal_colon' => __('Subtotal:', 'wpamelia'), 'deposit' => __('Deposit', 'wpamelia'), 'pay_now' => __('(Paying now)', 'wpamelia'), 'pay_later' => __('Left to pay', 'wpamelia'), 'recurring_costs_colon' => __('Recurring Appointments:', 'wpamelia'), 'support_heading' => __('Support Heading:', 'wpamelia'), 'company_phone' => __('Company Phone:', 'wpamelia'), 'company_email' => __('Company Email:', 'wpamelia'), // elf - event list form 'elf_booking_form' => __('Event List Booking Form 2.0', 'wpamelia'), 'redesigned_elf_booking_form' => __('Modernized Event List Booking Form 2.0 with better user experience, improved speed, animation and a stand-out design!', 'wpamelia'), 'csb_events_list' => __('Events List', 'wpamelia'), 'csb_events_list_content' => __('Set up Location, Images, Filters, Capacity, Price, and Status visibility options', 'wpamelia'), 'csb_event_info' => __('Event Info', 'wpamelia'), 'csb_event_info_content' => __('Set up Staff, Location, Gallery and other Event information visibility', 'wpamelia'), 'csb_event_tickets' => __('Event Tickets', 'wpamelia'), 'csb_event_tickets_content' => __('Set up visibility and labels of ticket selection', 'wpamelia'), 'csb_event_customer' => __('Customer Info', 'wpamelia'), 'csb_event_customer_content' => __('Field order, mandatory fields, labels and display options', 'wpamelia'), 'csb_event_payment' => __('Payment', 'wpamelia'), 'csb_event_payment_content' => __('Set up labels and buttons', 'wpamelia'), 'csb_event_congratulations' => __('Congratulations', 'wpamelia'), 'csb_event_congratulations_content' => __('Set up button types and labels', 'wpamelia'), 'events_available' => __('Events Available', 'wpamelia'), 'event_available' => __('Event Available', 'wpamelia'), 'event_page' => __('Page', 'wpamelia'), 'event_search' => __('Search for Events', 'wpamelia'), 'event_calendar' => __('Calendar', 'wpamelia'), 'event_begins' => __('Begins', 'wpamelia'), 'event_slot_left' => __('slot left', 'wpamelia'), 'event_slots_left' => __('slots left', 'wpamelia'), 'event_learn_more' => __('Learn more', 'wpamelia'), 'event_read_more' => __('Read more', 'wpamelia'), 'event_close' => __('Close', 'wpamelia'), 'event_select_tickets' => __('Select Tickets', 'wpamelia'), 'event_customer_info' => __('Your Information', 'wpamelia'), 'summary_event' => __('Event', 'wpamelia'), 'event_id' => __('Event ID', 'wpamelia'), 'about' => __('About', 'wpamelia'), 'event_tickets_context' => __('Select the number of tickets that you want to book for each ticket type', 'wpamelia'), 'event_ticket_types' => __('Ticket Types', 'wpamelia'), 'event_tickets_left' => __('tickets left', 'wpamelia'), 'event_ticket_left' => __('ticket left', 'wpamelia'), 'event_organizer' => __('Organizer', 'wpamelia'), 'event_info' => __('Event Info', 'wpamelia'), 'event_timetable' => __('Timetable', 'wpamelia'), 'event_tickets' => __('Tickets', 'wpamelia'), 'event_payment' => __('Payment', 'wpamelia'), 'coupons_used' => __('Coupon Limit Reached', 'wpamelia'), 'coupons_used_description' => __('Number of appointments with applied coupon is', 'wpamelia'), 'event_congrats' => __('Congratulations', 'wpamelia'), 'event_about_list' => __('About Event', 'wpamelia'), 'event_start' => __('Event Starts', 'wpamelia'), 'event_end' => __('Event Ends', 'wpamelia'), 'event_at' => __('at', 'wpamelia'), 'event_bringing' => __('How many attendees do you want to book event for?', 'wpamelia'), // strings used only on backend 'step_filters' => __('Step Filters', 'wpamelia'), 'event_card' => __('Event Card', 'wpamelia'), 'step_pagination' => __('Step Pagination', 'wpamelia'), 'event_slots_capacity' => __('Event Slots Capacity', 'wpamelia'), 'filters_button_type' => __('Filters Button Type', 'wpamelia'), 'read_more_button_type' => __('Read More Button Type', 'wpamelia'), 'learn_more_button_type' => __('Learn More Button Type', 'wpamelia'), 'event_tab_img' => __('Event Tab Image', 'wpamelia'), 'step_header' => __('Step Header', 'wpamelia'), 'step_info_tab' => __('Step Info Tab', 'wpamelia'), 'step_tickets_tab' => __('Step Tickets Tab', 'wpamelia'), 'booking_event_btn' => __('Booking Event Button', 'wpamelia'), 'finish_event_btn' => __('Finish Button', 'wpamelia'), 'close_event_btn' => __('Close Event Button', 'wpamelia'), 'customer_panel_btn' => __('Customer Panel Button', 'wpamelia'), 'event_gallery' => __('Event Gallery', 'wpamelia'), 'event_description' => __('Event Description', 'wpamelia'), 'event_employees' => __('Event Employees', 'wpamelia'), 'coupon_segment' => __('Coupon Segment', 'wpamelia'), ]; } /** * @return array */ public static function getWordPressStrings() { return [ 'catalog' => __('Catalog', 'wpamelia'), 'filter' => __('Preselect Booking Parameters', 'wpamelia'), 'insert_amelia_shortcode' => __('Insert Amelia Booking Shortcode', 'wpamelia'), 'notice_panel' => __('Notice: Please select at least one panel.', 'wpamelia'), 'search' => __('Search', 'wpamelia'), 'search_date' => __('Preselect Current Date', 'wpamelia'), 'select_catalog_view' => __('Select Catalog View', 'wpamelia'), 'select_category' => __('Select Category', 'wpamelia'), 'select_employee' => __('Select Employee', 'wpamelia'), 'select_location' => __('Select Location', 'wpamelia'), 'select_package' => __('Select Package', 'wpamelia'), 'select_service' => __('Select Service', 'wpamelia'), 'select_event' => __('Select Event', 'wpamelia'), 'select_tag' => __('Select Tag', 'wpamelia'), 'select_view' => __('Select View', 'wpamelia'), 'show' => __('Show', 'wpamelia'), 'show_all' => __('Show All', 'wpamelia'), 'manually_loading' => __('Load booking form manually', 'wpamelia'), 'manually_loading_description' => __('Add element (button, link...) ID, that will manually load amelia shortcode content', 'wpamelia'), 'show_all_categories' => __('Show all categories', 'wpamelia'), 'show_all_employees' => __('Show all employees', 'wpamelia'), 'show_all_locations' => __('Show all locations', 'wpamelia'), 'show_all_services' => __('Show all services', 'wpamelia'), 'show_all_events' => __('Show all events', 'wpamelia'), 'show_all_packages' => __('Show all packages', 'wpamelia'), 'show_all_tags' => __('Show all tags', 'wpamelia'), 'show_catalog' => __('Show catalog of all categories', 'wpamelia'), 'show_category' => __('Show specific category', 'wpamelia'), 'show_package' => __('Show specific package', 'wpamelia'), 'show_event' => __('Show event', 'wpamelia'), 'show_event_view_type' => __('Show Type', 'wpamelia'), 'show_event_view_list' => __('List (default)', 'wpamelia'), 'show_event_view_calendar' => __('Calendar', 'wpamelia'), 'show_tag' => __('Show tag', 'wpamelia'), 'show_service' => __('Show specific service', 'wpamelia'), 'trigger_type' => __('Trigger type', 'wpamelia'), 'trigger_type_id' => __('Id', 'wpamelia'), 'trigger_type_class' => __('Class', 'wpamelia'), 'trigger_type_tooltip' => __('Trigger by attribute', 'wpamelia'), 'step_booking' => __('Step Booking', 'wpamelia'), 'catalog_booking' => __('Catalog Booking', 'wpamelia'), 'events_list_booking' => __('Events List Booking', 'wpamelia'), 'recurring_event' => __('Show recurring events', 'wpamelia'), 'search_divi' => __('AM - Search view', 'wpamelia'), 'booking_divi' => __('AM - Booking view', 'wpamelia'), 'step_booking_divi' => __('AM - Step Booking', 'wpamelia'), 'catalog_booking_divi' => __('AM - Catalog Booking', 'wpamelia'), 'catalog_divi' => __('AM - Catalog view', 'wpamelia'), 'events_divi' => __('AM - Events view', 'wpamelia'), 'events_list_booking_divi' => __('AM - Events List Booking', 'wpamelia'), 'customer_cabinet_divi' => __('AM - Customer Panel', 'wpamelia'), 'employee_cabinet_divi' => __('AM - Employee Panel', 'wpamelia'), 'search_gutenberg_block' => [ 'title' => __('Amelia - Search view', 'wpamelia'), 'description' => __('Front-end Booking Search is shortcode that give your customers the possibility to search for appointment by selecting several filters so that they could find the best time slots and services for their needs.', 'wpamelia'), ], 'booking_gutenberg_block' => [ 'title' => __('Amelia - Booking view', 'wpamelia'), 'description' => __('Step-By-Step Booking Wizard gives your customers the option to choose everything about the booking in a few steps', 'wpamelia'), ], 'step_booking_gutenberg_block' => [ 'title' => __('Amelia - Step-By-Step Booking', 'wpamelia'), 'description' => __('Step-by-Step booking view guides the customers through several steps in order to make their bookings.', 'wpamelia'), ], 'catalog_booking_gutenberg_block' => [ 'title' => __('Amelia - Catalog Booking', 'wpamelia'), 'description' => __('Front-end Booking Catalog is shortcode when you want to show your service in a form of a catalog', 'wpamelia'), ], 'catalog_gutenberg_block' => [ 'title' => __('Amelia - Catalog view', 'wpamelia'), 'description' => __('Front-end Booking Catalog is shortcode when you want to show your service in a form of a cataloge', 'wpamelia'), ], 'events_gutenberg_block' => [ 'title' => __('Amelia - Events', 'wpamelia'), 'description' => __('Event Booking is shortcode that gives your customers the option to book one of the events that you\'ve created on the back-end in a simple event list view.', 'wpamelia'), ], 'events_list_booking_gutenberg_block' => [ 'title' => __('Amelia - Events List', 'wpamelia'), 'description' => __('Event Booking is shortcode that gives your customers the option to book one of the events that you\'ve created on the back-end in a simple event list view.', 'wpamelia'), ], 'customer_cabinet_gutenberg_block' => [ 'title' => __('Amelia - Customer Panel', 'wpamelia'), 'description' => __('Front-end Customer Panel is a shortcode that gives your customers the possibility to manage their bookings and profile information.', 'wpamelia'), ], 'employee_cabinet_gutenberg_block' => [ 'title' => __('Amelia - Employee Panel', 'wpamelia'), 'description' => __('Front-end Employee Panel is a shortcode that gives your employees the possibility to manage their bookings, working hours, days off, assigned services and profile information.', 'wpamelia'), ], ]; } /** * @return array */ public static function getBuddyBossStrings() { return [ ]; } /** * @return array */ public static function getRecurringStrings() { return [ 'recurring_appointments' => __('Recurring Appointments', 'wpamelia'), 'recurring_sub_message1' => __('Some of the desired slots are busy. We offered you the nearest time slots instead.', 'wpamelia'), 'recurring_sub_message2' => __('Number of adjusted time slots: ', 'wpamelia'), 'recurring_active' => __('Repeat this appointment', 'wpamelia'), 'recurring_active_tooltip' => __('Check this option if you want to create recurring appointments', 'wpamelia'), 'recurring_type_daily' => __('Daily', 'wpamelia'), 'recurring_type_weekly' => __('Weekly', 'wpamelia'), 'recurring_type_monthly' => __('Monthly', 'wpamelia'), 'recurring_repeat' => __('Repeat:', 'wpamelia'), 'recurring_every' => __('Every:', 'wpamelia'), 'recurring_until' => __('Until:', 'wpamelia'), 'recurring_every_text' => __('Every', 'wpamelia'), 'recurring_until_text' => __('until', 'wpamelia'), 'recurring_on' => __('On:', 'wpamelia'), 'recurring_each' => __('Each:', 'wpamelia'), 'recurring_times' => __('Time(s):', 'wpamelia'), 'recurring_date_specific' => __('Specific Date', 'wpamelia'), 'recurring_date_first' => __('First', 'wpamelia'), 'recurring_date_second' => __('Second', 'wpamelia'), 'recurring_date_third' => __('Third', 'wpamelia'), 'recurring_date_fourth' => __('Fourth', 'wpamelia'), 'recurring_date_last' => __('Last', 'wpamelia'), ]; } } WP/Translations/NotificationsStrings.php 0000666 00000172205 15165376447 0014504 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\Translations; /** * Class NotificationsStrings * * @package AmeliaBooking\Infrastructure\WP\Translations * * @SuppressWarnings(ExcessiveMethodLength) */ class NotificationsStrings { /** * Array of default customer's notifications that are not time based * * @return array */ public static function getAppointmentCustomerNonTimeBasedEmailNotifications() { return [ [ 'name' => 'customer_appointment_approved', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Approved', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>You have successfully scheduled <strong>%service_name%</strong> appointment with <strong>%employee_full_name%</strong>. We are waiting you at <strong>%location_address% </strong>on <strong>%appointment_date_time%</strong>. <br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ], [ 'name' => 'customer_appointment_pending', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Pending', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>The <strong>%service_name%</strong> appointment with <strong>%employee_full_name%</strong> at <strong>%location_address%</strong>, scheduled for <strong>%appointment_date_time%</strong> is waiting for a confirmation.<br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ], [ 'name' => 'customer_appointment_rejected', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Rejected', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Your <strong>%service_name%</strong> appointment, scheduled on <strong>%appointment_date_time%</strong> at <strong>%location_address% </strong>has been rejected.<br><br>Thank you for choosing our company, <br><strong>%company_name%</strong>' ], [ 'name' => 'customer_appointment_canceled', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Canceled', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Your <strong>%service_name%</strong> appointment, scheduled on <strong>%appointment_date_time%</strong> at <strong>%location_address% </strong>has been canceled.<br><br>Thank you for choosing our company, <br><strong>%company_name%</strong>' ], [ 'name' => 'customer_appointment_rescheduled', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Rescheduled', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>The details for your <strong>%service_name%</strong> appointment with <strong>%employee_full_name%</strong> at <strong>%location_name%</strong> has been changed. The appointment is now set for <strong>%appointment_date%</strong> at <strong>%appointment_start_time%</strong>.<br><br> Thank you for choosing our company,<br><strong>%company_name%</strong>' ] ]; } /** * Array of default customer's notifications that are time based (require cron job) * * @return array */ public static function getAppointmentCustomerTimeBasedEmailNotifications() { return [ [ 'name' => 'customer_appointment_next_day_reminder', 'entity' => 'appointment', 'type' => 'email', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Reminder', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>We would like to remind you that you have <strong>%service_name%</strong> appointment tomorrow at <strong>%appointment_start_time%</strong>. We are waiting for you at <strong>%location_name%</strong>.<br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ], [ 'name' => 'customer_appointment_follow_up', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 1800, 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Follow Up', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Thank you once again for choosing our company. We hope you were satisfied with your <strong>%service_name%</strong>.<br><br>We look forward to seeing you again soon,<br><strong>%company_name%</strong>' ], [ 'name' => 'customer_birthday_greeting', 'entity' => 'appointment', 'type' => 'email', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'Happy Birthday', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Happy birthday!<br>We wish you all the best. <br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ] ]; } /** * Array of default employee's notifications that are not time based * * @return array */ public static function getAppointmentProviderNonTimeBasedEmailNotifications() { return [ [ 'name' => 'provider_appointment_approved', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Approved', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>You have one confirmed <strong>%service_name%</strong> appointment at <strong>%location_name%</strong> on <strong>%appointment_date%</strong> at <strong>%appointment_start_time%</strong>. The appointment is added to your schedule.<br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_appointment_pending', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Pending', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>You have new appointment in <strong>%service_name%</strong>. The appointment is waiting for a confirmation.<br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_appointment_rejected', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Rejected', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>Your <strong>%service_name%</strong> appointment at <strong>%location_name%</strong>, scheduled for <strong>%appointment_date%</strong> at <strong>%appointment_start_time%</strong> has been rejected. <br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_appointment_canceled', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Canceled', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>Your <strong>%service_name%</strong> appointment, scheduled on <strong>%appointment_date%</strong>, at <strong>%location_name%</strong> has been canceled.<br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_appointment_rescheduled', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Rescheduled', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>The details for your <strong>%service_name%</strong> appointment at <strong>%location_name%</strong> has been changed. The appointment is now set for <strong>%appointment_date%</strong> at <strong>%appointment_start_time%</strong>.<br><br>Thank you,<br><strong>%company_name%</strong>' ] ]; } /** * Array of default providers's notifications that are time based (require cron job) * * @return array */ public static function getAppointmentProviderTimeBasedEmailNotifications() { return [ [ 'name' => 'provider_appointment_next_day_reminder', 'entity' => 'appointment', 'type' => 'email', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Reminder', 'content' => 'Dear <strong>%employee_full_name%</strong>,<br><br>We would like to remind you that you have <strong>%service_name%</strong> appointment tomorrow at <strong>%appointment_start_time%</strong> at <strong>%location_name%</strong>.<br><br>Thank you, <br><strong>%company_name%</strong>' ] ]; } /** * Array of default customer's notifications that are not time based * * @return array */ public static function getAppointmentCustomerNonTimeBasedSMSNotifications() { return [ [ 'name' => 'customer_appointment_approved', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, You have successfully scheduled %service_name% appointment with %employee_full_name%. We are waiting for you at %location_address% on %appointment_date_time%. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_appointment_pending', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, The %service_name% appointment with %employee_full_name% at %location_address%, scheduled for %appointment_date_time% is waiting for a confirmation. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_appointment_rejected', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Your %service_name% appointment, scheduled on %appointment_date_time% at %location_address% has been rejected. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_appointment_canceled', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Your %service_name% appointment, scheduled on %appointment_date_time% at %location_address% has been canceled. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_appointment_rescheduled', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, The details for your %service_name% appointment with %employee_full_name% at %location_name% has been changed. The appointment is now set for %appointment_date% at %appointment_start_time%. Thank you for choosing our company, %company_name%' ] ]; } /** * Array of default customer's notifications that are time based (require cron job) * * @return array */ public static function getAppointmentCustomerTimeBasedSMSNotifications() { return [ [ 'name' => 'customer_appointment_next_day_reminder', 'entity' => 'appointment', 'type' => 'sms', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, We would like to remind you that you have %service_name% appointment tomorrow at %appointment_start_time%. We are waiting for you at %location_name%. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_appointment_follow_up', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 1800, 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Thank you once again for choosing our company. We hope you were satisfied with your %service_name%. We look forward to seeing you again soon, %company_name%' ], [ 'name' => 'customer_birthday_greeting', 'entity' => 'appointment', 'type' => 'sms', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Happy birthday! We wish you all the best. Thank you for choosing our company, %company_name%' ] ]; } /** * Array of default employee's notifications that are not time based * * @return array */ public static function getAppointmentProviderNonTimeBasedSMSNotifications() { return [ [ 'name' => 'provider_appointment_approved', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, You have one confirmed %service_name% appointment at %location_name% on %appointment_date% at %appointment_start_time%. The appointment is added to your schedule. Thank you, %company_name%' ], [ 'name' => 'provider_appointment_pending', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, You have new appointment in %service_name%. The appointment is waiting for a confirmation. Thank you, %company_name%' ], [ 'name' => 'provider_appointment_rejected', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, Your %service_name% appointment at %location_name%, scheduled for %appointment_date% at %appointment_start_time% has been rejected. Thank you, %company_name%' ], [ 'name' => 'provider_appointment_canceled', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, Your %service_name% appointment, scheduled on %appointment_date%, at %location_name% has been canceled. Thank you, %company_name%' ], [ 'name' => 'provider_appointment_rescheduled', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, The details for your %service_name% appointment at %location_name% has been changed. The appointment is now set for %appointment_date% at %appointment_start_time%. Thank you, %company_name%' ] ]; } /** * Array of default providers's notifications that are time based (require cron job) * * @return array */ public static function getAppointmentProviderTimeBasedSMSNotifications() { return [ [ 'name' => 'provider_appointment_next_day_reminder', 'entity' => 'appointment', 'type' => 'sms', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Dear %employee_full_name%, We would like to remind you that you have %service_name% appointment tomorrow at %appointment_start_time% at %location_name%. Thank you, %company_name%' ] ]; } /** * Array of default customer's notifications that are not time based * * @return array */ public static function getEventCustomerNonTimeBasedEmailNotifications() { return [ [ 'name' => 'customer_event_approved', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Booked', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>You have successfully scheduled <strong>%event_name%</strong> event. We are waiting you at <strong>%event_location% </strong>on <strong>%event_start_date_time%</strong>. <br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ], [ 'name' => 'customer_event_rejected', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Canceled By Admin', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Your <strong>%event_name%</strong> event, scheduled on <strong>%event_start_date_time%</strong> at <strong>%event_location% </strong>has been canceled.<br><br>Thank you for choosing our company, <br><strong>%company_name%</strong>' ], [ 'name' => 'customer_event_canceled', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Canceled By Attendee', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Your <strong>%event_name%</strong> event, scheduled on <strong>%event_start_date_time%</strong> at <strong>%event_location% </strong>has been canceled.<br><br>Thank you for choosing our company, <br><strong>%company_name%</strong>' ], [ 'name' => 'customer_event_rescheduled', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Rescheduled', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>The details for your <strong>%event_name%</strong> event at <strong>%event_location%</strong> has been changed. The event is now set for <strong>%event_start_date_time%</strong>.<br><br> Thank you for choosing our company,<br><strong>%company_name%</strong>' ] ]; } /** * Array of default customer's notifications that are time based (require cron job) * * @return array */ public static function getEventCustomerTimeBasedEmailNotifications() { return [ [ 'name' => 'customer_event_next_day_reminder', 'entity' => 'event', 'type' => 'email', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Reminder', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>We would like to remind you that you have <strong>%event_name%</strong> event tomorrow at <strong>%event_start_date_time%</strong>. We are waiting for you at <strong>%event_location%</strong>.<br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ], [ 'name' => 'customer_event_follow_up', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 1800, 'sendTo' => 'customer', 'subject' => '%event_name% Event Follow Up', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Thank you once again for choosing our company. We hope you were satisfied with your <strong>%event_name%</strong>.<br><br>We look forward to seeing you again soon,<br><strong>%company_name%</strong>' ] ]; } /** * Array of default employee's notifications that are not time based * * @return array */ public static function getEventProviderNonTimeBasedEmailNotifications() { return [ [ 'name' => 'provider_event_approved', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Booked', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>You have one confirmed <strong>%event_name%</strong> Event at <strong>%event_location%</strong> on <strong>%event_start_date_time%</strong>. The event is added to your schedule.<br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_event_rejected', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Canceled By Admin', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>Your <strong>%event_name%</strong> event at <strong>%event_location%</strong>, scheduled for <strong>%event_start_date_time%</strong> has been canceled.<br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_event_canceled', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Canceled By Customer', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>Your <strong>%event_name%</strong> event, scheduled on <strong>%event_start_date_time%</strong>, at <strong>%event_location%</strong> has been canceled.<br><br>Thank you,<br><strong>%company_name%</strong>' ], [ 'name' => 'provider_event_rescheduled', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Rescheduled', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>The details for your <strong>%event_name%</strong> event at <strong>%event_location%</strong> has been changed. The event is now set for <strong>%event_start_date_time%</strong>. <br><br>Thank you,<br><strong>%company_name%</strong>' ] ]; } /** * Array of default providers's notifications that are time based (require cron job) * * @return array */ public static function getEventProviderTimeBasedEmailNotifications() { return [ [ 'name' => 'provider_event_next_day_reminder', 'entity' => 'event', 'type' => 'email', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Reminder', 'content' => 'Dear <strong>%employee_full_name%</strong>,<br><br>We would like to remind you that you have <strong>%event_name%</strong> event at <strong>%event_start_date_time%</strong> at <strong>%event_location%</strong>.<br><br>Thank you, <br><strong>%company_name%</strong>' ] ]; } /** * Array of default customer's notifications that are not time based * * @return array */ public static function getEventCustomerNonTimeBasedSMSNotifications() { return [ [ 'name' => 'customer_event_approved', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, You have successfully scheduled %event_name% event. We are waiting for you at %event_location% on %event_start_date_time%. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_event_rejected', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Your %event_name% event, scheduled on %event_start_date_time% at %event_location% has been cancelled. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_event_canceled', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Your %event_name% event, scheduled on %event_start_date_time% at %event_location% has been cancelled. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_event_rescheduled', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, The details for your %event_name% event at %event_location% has been changed. The event is now set for %event_start_date_time%. Thank you for choosing our company, %company_name%' ] ]; } /** * Array of default customer's notifications that are time based (require cron job) * * @return array */ public static function getEventCustomerTimeBasedSMSNotifications() { return [ [ 'name' => 'customer_event_next_day_reminder', 'entity' => 'event', 'type' => 'sms', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, We would like to remind you that you have %event_name% event at %event_start_date_time%. We are waiting for you at %event_location%. Thank you for choosing our company, %company_name%' ], [ 'name' => 'customer_event_follow_up', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 1800, 'sendTo' => 'customer', 'subject' => 'NULL', 'content' => 'Dear %customer_full_name%, Thank you once again for choosing our company. We hope you were satisfied with your %event_name%. We look forward to seeing you again soon, %company_name%' ] ]; } /** * Array of default employee's notifications that are not time based * * @return array */ public static function getEventProviderNonTimeBasedSMSNotifications() { return [ [ 'name' => 'provider_event_approved', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, You have one confirmed %event_name% event at %event_location% on %event_start_date_time%. The event is added to your schedule. Thank you, %company_name%' ], [ 'name' => 'provider_event_rejected', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, Your %event_name% event at %event_location%, scheduled for %event_start_date_time% has been canceled by admin. Thank you, %company_name%' ], [ 'name' => 'provider_event_canceled', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, Your %event_name% event, scheduled on %event_start_date_time%, at %event_location% has been canceled. Thank you, %company_name%' ], [ 'name' => 'provider_event_rescheduled', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Hi %employee_full_name%, The details for your %event_name% event at %event_location% has been changed. The event is now set for %event_start_date_time%. Thank you, %company_name%' ] ]; } /** * Array of default providers's notifications that are time based (require cron job) * * @return array */ public static function getEventProviderTimeBasedSMSNotifications() { return [ [ 'name' => 'provider_event_next_day_reminder', 'entity' => 'event', 'type' => 'sms', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'NULL', 'content' => 'Dear %employee_full_name%, We would like to remind you that you have %event_name% event at %event_start_date_time% at %event_location%. Thank you, %company_name%' ] ]; } /** * default customer's notification * * @return array */ public static function getAccountRecoveryNotification() { return [ 'name' => 'customer_account_recovery', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'Customer Panel Access', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>You can access your profile on this <b><a href="%customer_panel_url%">link</a></b>. <br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ]; } /** * default customer's notification * * @return array */ public static function getEmployeeAccountRecoveryNotification() { return [ 'name' => 'provider_panel_recovery', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'Employee Panel Access', 'content' => 'Dear <strong>%employee_full_name%</strong>,<br><br>You can access your profile and track your bookings on this <b><a href="%employee_panel_url%">link</a></b>. <br><br>Best regards,<br><strong>%company_name%</strong>' ]; } /** * Employee Panel Access Notification * * @return array */ public static function getEmployeePanelAccessNotification() { return [ 'name' => 'provider_panel_access', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'Employee Panel Access', 'content' => 'Dear <strong>%employee_full_name%</strong>,<br><br>You can access your profile and track your bookings on this <b><a href="%employee_panel_url%">link</a></b>.<br><br>Your login credentials:<br>Email: <b>%employee_email%</b><br>Password: <b>%employee_password%</b> <br><br>Best regards,<br><strong>%company_name%</strong>' ]; } /** * default customer's package notification * * @return array */ public static function getCustomerPackagePurchasedEmailNotification() { return [ 'name' => 'customer_package_purchased', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'Package %package_name% purchased', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>You have successfully purchased <strong>%package_name%</strong>. <br><br>Thank you for choosing our company,<br><strong>%company_name%</strong>' ]; } /** * default customer's package notification * * @return array */ public static function getCustomerPackagePurchasedSmsNotification() { return [ 'name' => 'customer_package_purchased', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'Package %package_name% purchased', 'content' => 'Dear %customer_full_name%, You have successfully purchased %package_name%. Thank you for choosing our company, %company_name%' ]; } /** * default provider's package notification * * @return array */ public static function getProviderPackagePurchasedEmailNotification() { return [ 'name' => 'provider_package_purchased', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'Package %package_name% purchased', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br> Customer <strong>%customer_full_name%</strong> has purchased <strong>%package_name%</strong> package.<br><br> Thank you,<br><strong>%company_name%</strong>' ]; } /** * default provider's package notification * * @return array */ public static function getProviderPackagePurchasedSmsNotification() { return [ 'name' => 'provider_package_purchased', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'Package %package_name% purchased', 'content' => 'Hi %employee_full_name%, Customer %customer_full_name% has purchased %package_name% package. Thank you, %company_name%' ]; } /** * default customer's package canceled notification * * @return array */ public static function getCustomerPackageCanceledEmailNotification() { return [ 'name' => 'customer_package_canceled', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'Package %package_name% canceled', 'content' => 'Dear <strong>%customer_full_name%</strong>, The <strong>%package_name%</strong> that you have purchased has been canceled. Thank you, <strong>%company_name%</strong>' ]; } /** * default customer's package canceled notification * * @return array */ public static function getCustomerPackageCanceledSmsNotification() { return [ 'name' => 'customer_package_canceled', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => 'Package %package_name% canceled', 'content' => 'Dear %customer_full_name%, The %package_name% that you have purchased has been canceled. Thank you, %company_name%' ]; } /** * default provider's package canceled notification * * @return array */ public static function getProviderPackageCanceledEmailNotification() { return [ 'name' => 'provider_package_canceled', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'Package %package_name% canceled', 'content' => 'Dear <strong>%employee_full_name%</strong>, The <strong>%package_name%</strong> purchased by <strong>%customer_full_name%</strong> has been canceled.' ]; } /** * default provider's package canceled notification * * @return array */ public static function getProviderPackageCanceledSmsNotification() { return [ 'name' => 'provider_package_canceled', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => 'Package %package_name% canceled', 'content' => 'Dear %employee_full_name%, The %package_name% purchased by %customer_full_name% has been canceled.' ]; } /** * Array of default whatsapp notifications * * @return array */ public static function getWhatsAppNotifications() { // needs to be changed for basic and lite $sendTo = ['customer', 'provider']; $statuses = ['approved', 'pending', 'rejected', 'canceled', 'rescheduled', 'next_day_reminder', 'follow_up']; $entities = ['appointment', 'event']; $newRows = []; foreach ($entities as $entity) { foreach ($sendTo as $to) { foreach ($statuses as $status) { if ($status === 'follow_up' && $to === 'provider' || $status === 'pending' && $entity === 'event') { continue; } $newRows[] = [ 'name' => $to . '_' . $entity . '_' . $status, 'entity' => $entity, 'type' => 'whatsapp', 'time' => $status === 'next_day_reminder' ? '"17:00:00"' : 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => $status === 'follow_up' ? 1800 : 'NULL', 'sendTo' => $to, 'subject' => '', 'content' => '' ]; } } } $sendTo = ['customer', 'provider']; $statuses = ['purchased', 'canceled']; foreach ($sendTo as $to) { foreach ($statuses as $status) { $newRows[] = [ 'name' => $to . '_package_' . $status, 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => $to, 'subject' => '', 'content' => '' ]; } } $newRows[] = [ 'name' => 'customer_birthday_greeting', 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => '"17:00:00"', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '', 'content' => '' ]; return array_merge( $newRows, [ [ 'name' => 'customer_account_recovery', 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '', 'content' => '' ], [ 'name' => 'provider_panel_access', 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '', 'content' => '' ], [ 'name' => 'provider_panel_recovery', 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '', 'content' => '' ] ] ); } /** * default appointment updated notifications * * @return array */ public static function getAppointmentUpdatedNotifications($newActivation) { $status = $newActivation ? 'enabled' : 'disabled'; return [ [ 'name' => 'customer_appointment_updated', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Details Changed', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Details of the appointment on <strong>%appointment_date_time%</strong> have changed: <br> <ul> <li>Employee: <strong>%employee_full_name%</strong></li> <li>Location: <strong>%location_name%</strong></li> <li>Extras: <strong>%service_extras%</strong></li> </ul><br>Thank you for choosing our company,<br> <strong>%company_name%</strong>', 'status' => $status ], [ 'name' => 'provider_appointment_updated', 'entity' => 'appointment', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Details Changed', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>Details of the appointment on <strong>%appointment_date_time%</strong> have changed: <br> <ul> <li>Customers: <strong>%customer_full_name%</strong></li> <li>Location: <strong>%location_name%</strong></li> <li>Extras: <strong>%service_extras%</strong></li> </ul><br>Thank you,<br> <strong>%company_name%</strong>', 'status' => $status ], [ 'name' => 'customer_appointment_updated', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%service_name% Appointment Details Changed', 'content' => 'Dear %customer_full_name%, Details of the appointment on %appointment_date_time% have changed: Employee: %employee_full_name% Location: %location_name% Extras: %service_extras% Thank you for choosing our company, %company_name%', 'status' => $status ], [ 'name' => 'provider_appointment_updated', 'entity' => 'appointment', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%service_name% Appointment Details Changed', 'content' => 'Hi %employee_full_name%, Details of the appointment on %appointment_date_time% have changed: Customers: %customer_full_name%, Location: %location_name%, Extras: %service_extras% Thank you, %company_name%', 'status' => $status ], [ 'name' => 'customer_appointment_updated', 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '', 'content' => '', 'status' => $status ], [ 'name' => 'provider_appointment_updated', 'entity' => 'appointment', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '', 'content' => '', 'status' => $status ], ]; } /** * default event updated notifications * * @return array */ public static function getEventUpdatedNotifications($newActivation) { $status = $newActivation ? 'enabled' : 'disabled'; return [ [ 'name' => 'customer_event_updated', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Details Changed', 'content' => 'Dear <strong>%customer_full_name%</strong>,<br><br>Details of the event on <strong>%event_start_date_time%</strong> have changed: <ul> <li>Organizer: <strong>%employee_full_name%</strong></li> <li>Location: <strong>%location_name%</strong></li> </ul><br>Thank you for choosing our company, <br> <strong>%company_name%</strong>', 'status' => $status ], [ 'name' => 'provider_event_updated', 'entity' => 'event', 'type' => 'email', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Details Changed', 'content' => 'Hi <strong>%employee_full_name%</strong>,<br><br>Details of the event on <strong>%event_start_date_time%</strong> have changed: <ul> <li>Description: <strong>%event_description%</strong></li> <li>Location: <strong>%location_name%</strong></li> </ul><br>Thank you, <br> <strong>%company_name%</strong>', 'status' => $status ], [ 'name' => 'customer_event_updated', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '%event_name% Event Details Changed', 'content' => 'Dear %customer_full_name%, Details of the event on %event_start_date_time% have changed: Organizer: %employee_full_name Location: %location_name% Thank you for choosing our company, %company_name%', 'status' => $status ], [ 'name' => 'provider_event_updated', 'entity' => 'event', 'type' => 'sms', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '%event_name% Event Details Changed', 'content' => 'Hi %employee_full_name%, Details of the event on %event_start_date_time% have changed: Description: %event_description%, Location: %location_name% Thank you, %company_name%', 'status' => $status ], [ 'name' => 'customer_event_updated', 'entity' => 'event', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'customer', 'subject' => '', 'content' => '', 'status' => $status ], [ 'name' => 'provider_event_updated', 'entity' => 'event', 'type' => 'whatsapp', 'time' => 'NULL', 'timeBefore' => 'NULL', 'timeAfter' => 'NULL', 'sendTo' => 'provider', 'subject' => '', 'content' => '', 'status' => $status ], ]; } } WP/HelperService/HelperService.php 0000666 00000003742 15165376447 0013137 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\HelperService; /** * Class HelperService * * @package AmeliaBooking\Infrastructure\WP\HelperService */ class HelperService { public static $jsVars = []; /** * Helper method to add PHP vars to JS vars * * @param $varName * @param $phpVar */ public static function exportJSVar($varName, $phpVar) { self::$jsVars[$varName] = $phpVar; } /** * Helper method to print PHP vars to JS vars */ public static function printJSVars() { if (!empty(self::$jsVars)) { $jsBlock = '<script type="text/javascript">'; foreach (self::$jsVars as $varName => $jsVar) { $jsBlock .= "var {$varName} = " . json_encode($jsVar) . ';'; } $jsBlock .= '</script>'; echo $jsBlock; } } /** * @param int $orderId * * @return string|null */ public static function getWooCommerceOrderUrl($orderId) { return get_edit_post_link($orderId, ''); } /** * @param int $orderId * * @return array */ public static function getWooCommerceOrderItemAmountValues($orderId) { $order = wc_get_order($orderId); $prices = []; if ($order) { foreach ($order->get_items() as $itemId => $orderItem) { $data = wc_get_order_item_meta($itemId, 'ameliabooking'); if ($data && is_array($data)) { $prices[] = [ 'coupon' => (float)round($orderItem->get_subtotal() - $orderItem->get_total(), 2), 'tax' => !isset($data['taxIncluded']) || !$data['taxIncluded'] ? (float)$orderItem->get_total_tax() : 0, ]; } } } return $prices; } } WP/ErrorService/ErrorService.php 0000666 00000002064 15165376447 0012657 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\ErrorService; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ErrorService * * @package AmeliaBooking\Infrastructure\WP\ErrorService */ class ErrorService { /** * Set Notice */ public static function setNotices() { // Add notice if database prefix is too long if (!AbstractDatabaseTable::isValidTablePrefix()) { add_action('admin_notices', function () { $class = 'notice notice-error is-dismissible'; $message = '<h3>Amelia</h3> <p>Maximum allowed database prefix is 16 characters.</p> <p>Please change the database prefix, deactivate and activate plugin again.</p> <button type="button" class="notice-dismiss"> <span class="screen-reader-text">Dismiss this notice.</span> </button>'; printf('<div class="%1$s">%2$s</div>', $class, $message); }); } } } WP/WPMenu/Submenu.php 0000666 00000004455 15165376447 0010432 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\WPMenu; /** * Class Submenu * * @package AmeliaBooking\Infrastructure\WPMenu */ class Submenu { /** @var SubmenuPageHandler $submenuHandler */ private $submenuHandler; /** @var array $menu */ private $menu; /** * Submenu constructor. * * @param SubmenuPageHandler $submenuHandler * @param array $menu */ public function __construct($submenuHandler, $menu) { $this->submenuHandler = $submenuHandler; $this->menu = $menu; } /** * Initialize admin menu in WP */ public function init() { add_action('admin_menu', [$this, 'addOptionsPages']); } /** * Add options in WP menu */ public function addOptionsPages() { add_menu_page( 'Amelia Booking', 'Amelia', 'amelia_read_menu', 'amelia', '', AMELIA_URL . 'public/img/amelia-logo-admin-icon.svg' ); foreach ($this->menu as $menu) { $this->handleMenuItem($menu); } remove_submenu_page('amelia', 'amelia'); } /** * @param array $menu */ public function handleMenuItem($menu) { if (isset($menu['parentSlug'], $menu['pageTitle'], $menu['menuTitle'], $menu['capability'], $menu['menuSlug'])) { $this->addSubmenuPage( $menu['parentSlug'], $menu['pageTitle'], $menu['menuTitle'], $menu['capability'], $menu['menuSlug'], function () use ($menu) { $this->submenuHandler->render($menu['menuSlug']); } ); } } /** * @noinspection MoreThanThreeArgumentsInspection * * @param $parentSlug * @param $pageTitle * @param $menuTitle * @param $capability * @param $menuSlug * @param string $function */ private function addSubmenuPage($parentSlug, $pageTitle, $menuTitle, $capability, $menuSlug, $function = '') { add_submenu_page( $parentSlug, $pageTitle, $menuTitle, $capability, $menuSlug, $function ); } } WP/WPMenu/SubmenuPageHandler.php 0000666 00000034215 15165376447 0012522 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\WPMenu; use AmeliaBooking\Application\Services\Helper\HelperService; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\Integrations\WooCommerce\WooCommerceService; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Renders menu pages */ class SubmenuPageHandler { /** @var SettingsService $settingsService */ private $settingsService; /** * SubmenuPageHandler constructor. * * @param SettingsService $settingsService */ public function __construct(SettingsService $settingsService) { $this->settingsService = $settingsService; } /** * Submenu page render function * * @param $page */ public function render($page) { if ($page !== 'wpamelia-customize-new') { $this->renderOld($page); } else { $this->renderNew($page); } } private function renderOld($page) { if ($this->settingsService->getSetting('activation', 'enablePolyfill')) { wp_enqueue_script('amelia_polyfill', 'https://polyfill.io/v2/polyfill.js?features=Intl.~locale.en'); } // Enqueue Scripts wp_enqueue_script( 'amelia_booking_scripts', AMELIA_URL . 'public/js/backend/amelia-booking.js', [], AMELIA_VERSION ); if (in_array($page, ['wpamelia-locations', 'wpamelia-settings', 'wpamelia-appointments', 'wpamelia-events', 'wpamelia-dashboard', 'wpamelia-calendar', 'wpamelia-services'])) { $gmapApiKey = $this->settingsService->getSetting('general', 'gMapApiKey'); if ($gmapApiKey) { wp_enqueue_script( 'google_maps_api', "https://maps.googleapis.com/maps/api/js?key={$gmapApiKey}&libraries=places" ); } } wp_enqueue_script( 'papaparse', "https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.1/papaparse.min.js" ); if ($page === 'wpamelia-notifications') { wp_enqueue_script('amelia_paddle', AMELIA_URL . 'public/js/paddle/paddle.js'); } // Enqueue Styles wp_enqueue_style( 'amelia_booking_styles', AMELIA_URL . 'public/css/backend/amelia-booking.css', [], AMELIA_VERSION ); // WordPress enqueue wp_enqueue_media(); wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLanguages', HelperService::getLanguages() ); $wcSettings = $this->settingsService->getSetting('payments', 'wc'); if ($wcSettings['enabled'] && WooCommerceService::isEnabled()) { wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaWcProducts', WooCommerceService::getInitialProducts() ); } // Strings Localization switch ($page) { case ('wpamelia-locations'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getEntityFormStrings(), BackendStrings::getLocationStrings(), BackendStrings::getCommonStrings() ) ); break; case ('wpamelia-services'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getPaymentStrings(), BackendStrings::getSettingsStrings(), BackendStrings::getEntityFormStrings(), BackendStrings::getServiceStrings(), BackendStrings::getBookableStrings(), BackendStrings::getCommonStrings(), BackendStrings::getAppointmentStrings(), BackendStrings::getRecurringStrings(), BackendStrings::getCustomerStrings(), BackendStrings::getUserStrings() ) ); break; case ('wpamelia-employees'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getEntityFormStrings(), BackendStrings::getUserStrings(), BackendStrings::getEmployeeStrings(), BackendStrings::getCommonStrings(), BackendStrings::getScheduleStrings() ) ); break; case ('wpamelia-customers'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getEntityFormStrings(), BackendStrings::getUserStrings(), BackendStrings::getCustomerStrings(), BackendStrings::getCommonStrings(), BackendStrings::getScheduleStrings(), BackendStrings::getImportStrings() ) ); break; case ('wpamelia-finance'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getEntityFormStrings(), BackendStrings::getCommonStrings(), BackendStrings::getFinanceStrings(), BackendStrings::getPaymentStrings(), BackendStrings::getEventStrings() ) ); break; case ('wpamelia-appointments'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getNotificationsStrings(), BackendStrings::getEntityFormStrings(), BackendStrings::getCommonStrings(), BackendStrings::getUserStrings(), BackendStrings::getCustomerStrings(), BackendStrings::getAppointmentStrings(), BackendStrings::getPaymentStrings(), BackendStrings::getRecurringStrings() ) ); break; case ('wpamelia-events'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getSettingsStrings(), BackendStrings::getEntityFormStrings(), BackendStrings::getCommonStrings(), BackendStrings::getUserStrings(), BackendStrings::getCustomerStrings(), BackendStrings::getAppointmentStrings(), BackendStrings::getEventStrings(), BackendStrings::getBookableStrings(), BackendStrings::getRecurringStrings() ) ); break; case ('wpamelia-dashboard'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getEntityFormStrings(), BackendStrings::getCommonStrings(), BackendStrings::getAppointmentStrings(), BackendStrings::getUserStrings(), BackendStrings::getCustomerStrings(), BackendStrings::getDashboardStrings(), BackendStrings::getPaymentStrings(), BackendStrings::getRecurringStrings(), BackendStrings::getNotificationsStrings() ) ); break; case ('wpamelia-calendar'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getEntityFormStrings(), BackendStrings::getCommonStrings(), BackendStrings::getAppointmentStrings(), BackendStrings::getUserStrings(), BackendStrings::getCustomerStrings(), BackendStrings::getCalendarStrings(), BackendStrings::getPaymentStrings(), BackendStrings::getEventStrings(), BackendStrings::getBookableStrings(), BackendStrings::getRecurringStrings() ) ); break; case ('wpamelia-notifications'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getPaymentStrings(), BackendStrings::getNotificationsStrings() ) ); break; case ('wpamelia-smsnotifications'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getNotificationsStrings() ) ); break; case ('wpamelia-settings'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getFinanceStrings(), BackendStrings::getCommonStrings(), BackendStrings::getScheduleStrings(), BackendStrings::getUserStrings(), BackendStrings::getEmployeeStrings(), BackendStrings::getSettingsStrings(), BackendStrings::getNotificationsStrings() ) ); break; case ('wpamelia-customize'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getCustomizeStrings() ) ); break; case ('wpamelia-cf'): wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getCustomizeStrings() ) ); break; } // Settings Localization wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaSettings', $this->settingsService->getFrontendSettings() ); wp_localize_script( 'amelia_booking_scripts', 'localeLanguage', [AMELIA_LOCALE] ); wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaTimeZone', [DateTimeService::getTimeZone()->getName()] ); include AMELIA_PATH . '/view/backend/view.php'; } private function renderNew($page) { $scriptId = AMELIA_DEV ? 'amelia_booking_scripts_dev_vite' : 'amelia_booking_script_index'; if (AMELIA_DEV) { wp_enqueue_script( 'amelia_booking_scripts_dev_vite', 'http://localhost:3000/@vite/client', [], null, false ); wp_enqueue_script( 'amelia_booking_scripts_dev_main', 'http://localhost:3000/src/assets/js/admin/admin.js', [], null, true ); } else { wp_enqueue_script( $scriptId, AMELIA_URL . 'v3/public/assets/admin.acae04ba.js', [], AMELIA_VERSION, true ); } wp_localize_script( $scriptId, 'localeLanguage', [AMELIA_LOCALE] ); wp_localize_script( $scriptId, 'wpAmeliaLanguages', HelperService::getLanguages() ); // Settings Localization wp_localize_script( $scriptId, 'wpAmeliaSettings', $this->settingsService->getFrontendSettings() ); // Labels wp_localize_script( $scriptId, 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getSettingsStrings(), BackendStrings::getCustomizeStrings() ) ); wp_localize_script( $scriptId, 'localeLanguage', [AMELIA_LOCALE] ); wp_localize_script( $scriptId, 'wpAmeliaUrls', [ 'wpAmeliaUseUploadsAmeliaPath' => AMELIA_UPLOADS_FILES_PATH_USE, 'wpAmeliaPluginURL' => AMELIA_URL, 'wpAmeliaPluginAjaxURL' => AMELIA_ACTION_URL ] ); include AMELIA_PATH . '/view/backend/view-new.php'; } } WP/Elementor/AmeliaStepBookingElementorWidget.php 0000666 00000021355 15165376447 0016145 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\GutenbergBlock\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaStepBookingElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaStepBookingElementorWidget extends Widget_Base { protected $controls_data; public function get_name() { return 'stepbooking'; } public function get_title() { return BackendStrings::getWordPressStrings()['step_booking_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $controls_data = self::amelia_elementor_get_data(); $this->start_controls_section( 'amelia_booking_section', [ 'label' => '<div class="amelia-elementor-content"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['step_booking_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['step_booking_gutenberg_block']['description'] . '</p>', ] ); $this->add_control( 'preselect', [ 'label' => BackendStrings::getWordPressStrings()['filter'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'select_category', [ 'label' => BackendStrings::getWordPressStrings()['select_category'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['categories'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_service', [ 'label' => BackendStrings::getWordPressStrings()['select_service'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['services'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_employee', [ 'label' => BackendStrings::getWordPressStrings()['select_employee'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['employees'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_location', [ 'label' => BackendStrings::getWordPressStrings()['select_location'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['locations'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); if ($controls_data['show']) { $this->add_control( 'select_package', [ 'label' => BackendStrings::getWordPressStrings()['select_package'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['packages'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); } if ($controls_data['show']) { $this->add_control( 'select_show', [ 'label' => BackendStrings::getWordPressStrings()['show_all'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['show'], 'condition' => ['preselect' => 'yes'], 'default' => '', ] ); } $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->add_control( 'trigger_type', [ 'label' => BackendStrings::getWordPressStrings()['trigger_type'], 'type' => Controls_Manager::SELECT, 'description' => BackendStrings::getWordPressStrings()['trigger_type_tooltip'], 'options' => $controls_data['trigger_types'], 'default' => 'id' ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $trigger_type = $settings['load_manually'] && $settings['trigger_type'] !== '' ? ' trigger_type=' . $settings['trigger_type'] : ''; $category = $settings['select_category'] === '0' ? '' : ' category=' . $settings['select_category']; $service = $settings['select_service'] === '0' ? '' : ' service=' . $settings['select_service']; $category_service = $settings['select_service'] === '0' ? $category : $service; $employee = $settings['select_employee'] === '0' ? '' : ' employee=' . $settings['select_employee']; $location = $settings['select_location'] === '0' ? '' : ' location=' . $settings['select_location']; $package = empty($settings['select_package']) || $settings['select_package'] === '0' ? '' : ' package=' . $settings['select_package']; $show = empty($settings['select_show']) ? '' : ' show=' . $settings['select_show']; $shortcode = '[ameliastepbooking' . $trigger . $trigger_type; if ($settings['preselect']) { echo $shortcode . $show . $category_service . $employee . $location . $package . ']'; } else { echo $shortcode . ']'; } } public static function amelia_elementor_get_data() { $data = GutenbergBlock::getEntitiesData()['data']; $elementorData = []; $elementorData['categories'] = []; $elementorData['categories'][0] = BackendStrings::getWordPressStrings()['show_all_categories']; foreach ($data['categories'] as $category) { $elementorData['categories'][$category['id']] = $category['name'] . ' (id: ' . $category['id'] . ')'; } $elementorData['services'] = []; $elementorData['services'][0] = BackendStrings::getWordPressStrings()['show_all_services']; foreach ($data['servicesList'] as $service) { if ($service) { $elementorData['services'][$service['id']] = $service['name'] . ' (id: ' . $service['id'] . ')'; } } $elementorData['employees'] = []; $elementorData['employees'][0] = BackendStrings::getWordPressStrings()['show_all_employees']; foreach ($data['employees'] as $provider) { $elementorData['employees'][$provider['id']] = $provider['firstName'] . $provider['lastName'] . ' (id: ' . $provider['id'] . ')'; } $elementorData['locations'] = []; $elementorData['locations'][0] = BackendStrings::getWordPressStrings()['show_all_locations']; foreach ($data['locations'] as $location) { $elementorData['locations'][$location['id']] = $location['name'] . ' (id: ' . $location['id'] . ')'; } $elementorData['packages'] = []; $elementorData['packages'][0] = BackendStrings::getWordPressStrings()['show_all_packages']; foreach ($data['packages'] as $package) { $elementorData['packages'][$package['id']] = $package['name'] . ' (id: ' . $package['id'] . ')'; } $elementorData['show'] = $data['packages'] ? [ '' => BackendStrings::getWordPressStrings()['show_all'], 'services' => BackendStrings::getCommonStrings()['services'], 'packages' => BackendStrings::getCommonStrings()['packages'] ] : []; $elementorData['trigger_types'] = [ 'id' => BackendStrings::getWordPressStrings()['trigger_type_id'], 'class' => BackendStrings::getWordPressStrings()['trigger_type_class'] ]; return $elementorData; } } WP/Elementor/AmeliaEmployeePanelElementorWidget.php 0000666 00000007260 15165376447 0016457 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaEmployeePanelElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaEmployeePanelElementorWidget extends Widget_Base { public function get_name() { return 'ameliaemployeepanel'; } public function get_title() { return BackendStrings::getWordPressStrings()['employee_cabinet_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $this->start_controls_section( 'amelia_employee_panel_section', [ 'label' => '<div class="amelia-elementor-content"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['employee_cabinet_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['employee_cabinet_gutenberg_block']['description'] . '</p>', ] ); $this->add_control( 'appointments', [ 'label' => BackendStrings::getCommonStrings()['appointments'], 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'events', [ 'label' => BackendStrings::getCommonStrings()['events'], 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'profile', [ 'label' => BackendStrings::getCommonStrings()['profile'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $appointments = $settings['appointments'] ? ' appointments=1' : ''; $events = $settings['events'] ? ' events=1' : ''; $profile = $settings['profile'] ? ' profile-hidden=1' : ''; if ($settings['appointments'] || $settings['events'] || !$settings['profile']) { echo esc_html('[ameliaemployeepanel' . $trigger . $appointments . $events . $profile . ']'); } else { echo esc_html(BackendStrings::getWordPressStrings()['notice_panel']); } } } WP/Elementor/AmeliaCustomerPanelElementorWidget.php 0000666 00000006222 15165376447 0016476 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaCustomerPanelElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaCustomerPanelElementorWidget extends Widget_Base { public function get_name() { return 'ameliacustomerpanel'; } public function get_title() { return BackendStrings::getWordPressStrings()['customer_cabinet_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $this->start_controls_section( 'amelia_customer_panel_section', [ 'label' => '<div class="amelia-elementor-content"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['customer_cabinet_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['customer_cabinet_gutenberg_block']['description'] . '</p>', ] ); $this->add_control( 'appointments', [ 'label' => BackendStrings::getCommonStrings()['appointments'], 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'events', [ 'label' => BackendStrings::getCommonStrings()['events'], 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); $appointments = $settings['appointments'] ? ' appointments=1' : ''; $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $events = $settings['events'] ? ' events=1' : ''; if ($settings['appointments'] || $settings['events']) { echo esc_html('[ameliacustomerpanel' . $trigger . $appointments . $events . ']'); } else { echo esc_html(BackendStrings::getWordPressStrings()['notice_panel']); } } } WP/Elementor/AmeliaEventsElementorWidget.php 0000666 00000013216 15165376447 0015162 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\GutenbergBlock\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaEventsElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaEventsElementorWidget extends Widget_Base { public function get_name() { return 'ameliaevents'; } public function get_title() { return BackendStrings::getWordPressStrings()['events_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $this->start_controls_section( 'amelia_events_section', [ 'label' => '<div class="amelia-elementor-content"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['events_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['events_gutenberg_block']['description'] . '</p>', ] ); if (!AMELIA_LITE_VERSION) { $this->add_control( 'selected_type', [ 'label' => BackendStrings::getWordPressStrings()['show_event_view_type'], 'type' => Controls_Manager::SELECT, 'options' => [ 'list' => BackendStrings::getWordPressStrings()['show_event_view_list'], 'calendar' => BackendStrings::getWordPressStrings()['show_event_view_calendar'] ], 'default' => 'list', ] ); } $this->add_control( 'preselect', [ 'label' => BackendStrings::getWordPressStrings()['filter'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'select_event', [ 'label' => BackendStrings::getWordPressStrings()['select_event'], 'type' => Controls_Manager::SELECT, 'options' => self::amelia_elementor_get_events(), 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_tag', [ 'label' => BackendStrings::getWordPressStrings()['select_tag'], 'type' => Controls_Manager::SELECT, 'options' => self::amelia_elementor_get_tags(), 'condition' => ['preselect' => 'yes'], 'default' => '', ] ); $this->add_control( 'show_recurring', [ 'label' => __('Show recurring events:'), 'type' => Controls_Manager::SWITCHER, 'condition' => ['preselect' => 'yes'], 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'condition' => ['preselect' => 'yes'], 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); $selected_type = ''; if ($settings['preselect']) { $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $selected_event = $settings['select_event'] === '0' ? '' : ' event=' . $settings['select_event']; $show_recurring = $settings['show_recurring'] ? ' recurring=1' : ''; $selected_tag = $settings['select_tag'] ? ' tag=' . '"' . $settings['select_tag'] . '"' : ''; echo esc_html('[ameliaevents' . $selected_type . $trigger . $selected_event . $selected_tag . $show_recurring . ']'); } else { $selected_type = ''; echo esc_html('[ameliaevents' . $selected_type . ']'); } } public static function amelia_elementor_get_events() { $events = GutenbergBlock::getEntitiesData()['data']['events']; $returnEvents = []; $returnEvents['0'] = BackendStrings::getWordPressStrings()['show_all_events']; foreach ($events as $event) { $returnEvents[$event['id']] = $event['name'] . ' (id: ' . $event['id'] . ') - ' . $event['formattedPeriodStart']; } return $returnEvents; } public static function amelia_elementor_get_tags() { $tags = GutenbergBlock::getEntitiesData()['data']['tags']; $returnTags = []; $returnTags[''] = BackendStrings::getWordPressStrings()['show_all_tags']; foreach ($tags as $index => $tag) { $returnTags[$tag['name']] = $tag['name']; } return $returnTags; } } WP/Elementor/AmeliaEventsListBookingElementorWidget.php 0000666 00000012027 15165376447 0017326 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\GutenbergBlock\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaEventsListBookingElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaEventsListBookingElementorWidget extends Widget_Base { public function get_name() { return 'ameliaeventslistbooking'; } public function get_title() { return BackendStrings::getWordPressStrings()['events_list_booking_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo-beta'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $this->start_controls_section( 'amelia_events_section', [ 'label' => '<div class="amelia-elementor-content-beta"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['events_list_booking_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['events_list_booking_gutenberg_block']['description'] . '</p>', ] ); $this->add_control( 'preselect', [ 'label' => BackendStrings::getWordPressStrings()['filter'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'select_event', [ 'label' => BackendStrings::getWordPressStrings()['select_event'], 'type' => Controls_Manager::SELECT, 'options' => self::amelia_elementor_get_events(), 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_tag', [ 'label' => BackendStrings::getWordPressStrings()['select_tag'], 'type' => Controls_Manager::SELECT, 'options' => self::amelia_elementor_get_tags(), 'condition' => ['preselect' => 'yes'], 'default' => '', ] ); $this->add_control( 'show_recurring', [ 'label' => __('Show recurring events:'), 'type' => Controls_Manager::SWITCHER, 'condition' => ['preselect' => 'yes'], 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'condition' => ['preselect' => 'yes'], 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); if ($settings['preselect']) { $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $selected_event = $settings['select_event'] === '0' ? '' : ' event=' . $settings['select_event']; $show_recurring = $settings['show_recurring'] ? ' recurring=1' : ''; $selected_tag = $settings['select_tag'] ? ' tag=' . "'" . $settings['select_tag'] . "'" : ''; echo '[ameliaeventslistbooking' . $trigger . $selected_event . $selected_tag . $show_recurring . ']'; } else { echo '[ameliaeventslistbooking]'; } } public static function amelia_elementor_get_events() { $events = GutenbergBlock::getEntitiesData()['data']['events']; $returnEvents = []; $returnEvents['0'] = BackendStrings::getWordPressStrings()['show_all_events']; foreach ($events as $event) { $returnEvents[$event['id']] = $event['name'] . ' (id: ' . $event['id'] . ') - ' . $event['formattedPeriodStart']; } return $returnEvents; } public static function amelia_elementor_get_tags() { $tags = GutenbergBlock::getEntitiesData()['data']['tags']; $returnTags = []; $returnTags[''] = BackendStrings::getWordPressStrings()['show_all_tags']; foreach ($tags as $index => $tag) { $returnTags[$tag['name']] = $tag['name']; } return $returnTags; } } WP/Elementor/AmeliaCatalogElementorWidget.php 0000666 00000022367 15165376447 0015277 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\GutenbergBlock\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaCatalogElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaCatalogElementorWidget extends Widget_Base { protected $controls_data; public function get_name() { return 'ameliacatalog'; } public function get_title() { return BackendStrings::getWordPressStrings()['catalog_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $controls_data = self::amelia_elementor_get_data(); $this->start_controls_section( 'amelia_catalog_section', [ 'label' => '<div class="amelia-elementor-content"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['catalog_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['catalog_gutenberg_block']['description'] . '</p>', ] ); $options = [ 'show_catalog' => BackendStrings::getWordPressStrings()['show_catalog'], 'show_category' => BackendStrings::getWordPressStrings()['show_category'], 'show_service' => BackendStrings::getWordPressStrings()['show_service'], ]; if ($controls_data['packages']) { $options['show_package'] = BackendStrings::getWordPressStrings()['show_package']; } $this->add_control( 'select_catalog', [ 'label' => BackendStrings::getWordPressStrings()['select_catalog_view'], 'type' => Controls_Manager::SELECT, 'label_block' => true, 'options' => $options, 'default' => 'show_catalog', ] ); $this->add_control( 'select_category', [ 'label' => BackendStrings::getWordPressStrings()['select_category'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['categories'], 'condition' => ['select_catalog' => 'show_category'], 'default' => array_keys($controls_data['categories']) ? array_keys($controls_data['categories'])[0] : 0, ] ); $this->add_control( 'select_service', [ 'label' => BackendStrings::getWordPressStrings()['select_service'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['services'], 'condition' => ['select_catalog' => 'show_service'], 'default' => array_keys($controls_data['services']) ? array_keys($controls_data['services'])[0] : 0, ] ); if ($controls_data['packages']) { $this->add_control( 'select_package', [ 'label' => BackendStrings::getWordPressStrings()['select_package'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['packages'], 'condition' => ['select_catalog' => 'show_package'], 'default' => array_keys($controls_data['packages']) ? array_keys($controls_data['packages'])[0] : 0, ] ); } $this->add_control( 'preselect', [ 'label' => BackendStrings::getWordPressStrings()['filter'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'select_employee', [ 'label' => BackendStrings::getWordPressStrings()['select_employee'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['employees'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_location', [ 'label' => BackendStrings::getWordPressStrings()['select_location'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['locations'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'condition' => ['preselect' => 'yes'], 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); if ($controls_data['show']) { $this->add_control( 'select_show', [ 'label' => BackendStrings::getWordPressStrings()['show_all'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['show'], 'condition' => ['preselect' => 'yes'], 'default' => '', ] ); } $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); if ($settings['select_catalog'] === 'show_service' || $settings['select_catalog'] === 'show_package') { $this->remove_control('select_show'); } $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $show = ''; if ($settings['select_catalog'] === 'show_catalog') { $category_service = ''; $show = empty($settings['select_show']) ? '' : ' show=' . $settings['select_show']; } elseif ($settings['select_catalog'] === 'show_category') { $category_service = ' category=' . $settings['select_category']; $show = empty($settings['select_show']) ? '' : ' show=' . $settings['select_show']; } elseif ($settings['select_catalog'] === 'show_service') { $category_service = ' service=' . $settings['select_service']; } elseif ($settings['select_catalog'] === 'show_package') { $category_service = ' package=' . $settings['select_package']; } else { $category_service = ''; } if ($settings['preselect']) { $employee = $settings['select_employee'] === '0' ? '' : ' employee=' . $settings['select_employee']; $location = $settings['select_location'] === '0' ? '' : ' location=' . $settings['select_location']; } else { $employee = ''; $location = ''; $trigger = ''; } echo esc_html('[ameliacatalog' . $show . $trigger . $category_service . $employee . $location . ']'); } public static function amelia_elementor_get_data() { $data = GutenbergBlock::getEntitiesData()['data']; $elementorData = []; $elementorData['categories'] = []; foreach ($data['categories'] as $category) { $elementorData['categories'][$category['id']] = $category['name'] . ' (id: ' . $category['id'] . ')'; } $elementorData['services'] = []; foreach ($data['servicesList'] as $service) { if ($service) { $elementorData['services'][$service['id']] = $service['name'] . ' (id: ' . $service['id'] . ')'; } } $elementorData['packages'] = []; foreach ($data['packages'] as $package) { $elementorData['packages'][$package['id']] = $package['name'] . ' (id: ' . $package['id'] . ')'; } $elementorData['employees'] = []; $elementorData['employees'][0] = BackendStrings::getWordPressStrings()['show_all_employees']; foreach ($data['employees'] as $provider) { $elementorData['employees'][$provider['id']] = $provider['firstName'] . $provider['lastName'] . ' (id: ' . $provider['id'] . ')'; } $elementorData['locations'] = []; $elementorData['locations'][0] = BackendStrings::getWordPressStrings()['show_all_locations']; foreach ($data['locations'] as $location) { $elementorData['locations'][$location['id']] = $location['name'] . ' (id: ' . $location['id'] . ')'; } $elementorData['show'] = $data['packages'] ? [ '' => BackendStrings::getWordPressStrings()['show_all'], 'services' => BackendStrings::getCommonStrings()['services'], 'packages' => BackendStrings::getCommonStrings()['packages'] ] : []; return $elementorData; } } WP/Elementor/ElementorBlock.php 0000666 00000006206 15165376447 0012474 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\Elementor; use Elementor\AmeliaBookingElementorWidget; use Elementor\AmeliaStepBookingElementorWidget; use Elementor\AmeliaCatalogBookingElementorWidget; use Elementor\AmeliaCustomerPanelElementorWidget; use Elementor\AmeliaCatalogElementorWidget; use Elementor\AmeliaEmployeePanelElementorWidget; use Elementor\AmeliaEventsElementorWidget; use Elementor\AmeliaEventsListBookingElementorWidget; use Elementor\AmeliaSearchElementorWidget; use Elementor\Plugin; /** * Class ElementorBlock * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class ElementorBlock { protected static $instance; public static function get_instance() { if (!isset(static::$instance)) { static::$instance = new static; } return static::$instance; } protected function __construct() { add_action('elementor/editor/before_enqueue_scripts', [$this, 'widget_styles']); add_action('elementor/widgets/register', [$this, 'register_widgets']); add_action('elementor/frontend/after_enqueue_styles', [$this, 'widget_styles']); add_action('elementor/elements/categories_registered', [$this, 'register_widget_categories']); } public function includes() { require_once(AMELIA_PATH . '/src/Infrastructure/WP/Elementor/AmeliaStepBookingElementorWidget.php'); require_once(AMELIA_PATH . '/src/Infrastructure/WP/Elementor/AmeliaCatalogBookingElementorWidget.php'); require_once(AMELIA_PATH . '/src/Infrastructure/WP/Elementor/AmeliaBookingElementorWidget.php'); require_once(AMELIA_PATH . '/src/Infrastructure/WP/Elementor/AmeliaCatalogElementorWidget.php'); require_once(AMELIA_PATH . '/src/Infrastructure/WP/Elementor/AmeliaEventsElementorWidget.php'); require_once(AMELIA_PATH . '/src/Infrastructure/WP/Elementor/AmeliaEventsListBookingElementorWidget.php'); } public function register_widgets() { $this->includes(); Plugin::instance()->widgets_manager->register(new AmeliaStepBookingElementorWidget()); Plugin::instance()->widgets_manager->register(new AmeliaCatalogBookingElementorWidget()); Plugin::instance()->widgets_manager->register(new AmeliaBookingElementorWidget()); Plugin::instance()->widgets_manager->register(new AmeliaCatalogElementorWidget()); Plugin::instance()->widgets_manager->register(new AmeliaEventsElementorWidget()); Plugin::instance()->widgets_manager->register(new AmeliaEventsListBookingElementorWidget()); } public function widget_styles() { wp_register_style('amelia-elementor-widget-font', AMELIA_URL . 'public/css/frontend/elementor.css', array(), AMELIA_VERSION); wp_enqueue_style('amelia-elementor-widget-font'); } public function register_widget_categories($elements_manager) { $elements_manager->add_category( 'amelia-elementor', [ 'title' => 'Amelia', 'icon' => 'amelia-logo', ], 1); } } WP/Elementor/AmeliaBookingElementorWidget.php 0000666 00000016212 15165376447 0015305 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\GutenbergBlock\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaBookingElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaBookingElementorWidget extends Widget_Base { protected $controls_data; public function get_name() { return 'ameliabooking'; } public function get_title() { return BackendStrings::getWordPressStrings()['booking_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function register_controls() { $controls_data = self::amelia_elementor_get_data(); $this->start_controls_section( 'amelia_booking_section', [ 'label' => '<div class="amelia-elementor-content"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['booking_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['booking_gutenberg_block']['description'] . '</p>', ] ); $this->add_control( 'preselect', [ 'label' => BackendStrings::getWordPressStrings()['filter'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'select_category', [ 'label' => BackendStrings::getWordPressStrings()['select_category'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['categories'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_service', [ 'label' => BackendStrings::getWordPressStrings()['select_service'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['services'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_employee', [ 'label' => BackendStrings::getWordPressStrings()['select_employee'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['employees'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_location', [ 'label' => BackendStrings::getWordPressStrings()['select_location'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['locations'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); if ($controls_data['show']) { $this->add_control( 'select_show', [ 'label' => BackendStrings::getWordPressStrings()['show_all'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['show'], 'condition' => ['preselect' => 'yes'], 'default' => '', ] ); } $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'condition' => ['preselect' => 'yes'], 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $category = $settings['select_category'] === '0' ? '' : ' category=' . $settings['select_category']; $service = $settings['select_service'] === '0' ? '' : ' service=' . $settings['select_service']; $category_service = $settings['select_service'] === '0' ? $category : $service; $employee = $settings['select_employee'] === '0' ? '' : ' employee=' . $settings['select_employee']; $location = $settings['select_location'] === '0' ? '' : ' location=' . $settings['select_location']; $employee_location = $settings['select_employee'] === '0' ? $location : $employee; $show = empty($settings['select_show']) ? '' : ' show=' . $settings['select_show']; if ($settings['preselect']) { echo esc_html('[ameliabooking' . $show . $trigger . $category_service . $employee_location . ']'); } else { echo '[ameliabooking]'; } } public static function amelia_elementor_get_data() { $data = GutenbergBlock::getEntitiesData()['data']; $elementorData = []; $elementorData['categories'] = []; $elementorData['categories'][0] = BackendStrings::getWordPressStrings()['show_all_categories']; foreach ($data['categories'] as $category) { $elementorData['categories'][$category['id']] = $category['name'] . ' (id: ' . $category['id'] . ')'; } $elementorData['services'] = []; $elementorData['services'][0] = BackendStrings::getWordPressStrings()['show_all_services']; foreach ($data['servicesList'] as $service) { if ($service) { $elementorData['services'][$service['id']] = $service['name'] . ' (id: ' . $service['id'] . ')'; } } $elementorData['employees'] = []; $elementorData['employees'][0] = BackendStrings::getWordPressStrings()['show_all_employees']; foreach ($data['employees'] as $provider) { $elementorData['employees'][$provider['id']] = $provider['firstName'] . $provider['lastName'] . ' (id: ' . $provider['id'] . ')'; } $elementorData['locations'] = []; $elementorData['locations'][0] = BackendStrings::getWordPressStrings()['show_all_locations']; foreach ($data['locations'] as $location) { $elementorData['locations'][$location['id']] = $location['name'] . ' (id: ' . $location['id'] . ')'; } $elementorData['show'] = $data['packages'] ? [ '' => BackendStrings::getWordPressStrings()['show_all'], 'services' => BackendStrings::getCommonStrings()['services'], 'packages' => BackendStrings::getCommonStrings()['packages'] ] : []; return $elementorData; } } WP/Elementor/AmeliaCatalogBookingElementorWidget.php 0000666 00000024121 15165376447 0016576 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace Elementor; use AmeliaBooking\Infrastructure\WP\GutenbergBlock\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaCatalogBookingElementorWidget * * @package AmeliaBooking\Infrastructure\WP\Elementor */ class AmeliaCatalogBookingElementorWidget extends Widget_Base { protected $controls_data; public function get_name() { return 'catalogbooking'; } public function get_title() { return BackendStrings::getWordPressStrings()['catalog_booking_gutenberg_block']['title']; } public function get_icon() { return 'amelia-logo-beta'; } public function get_categories() { return [ 'amelia-elementor' ]; } protected function _register_controls() { $controls_data = self::amelia_elementor_get_data(); $this->start_controls_section( 'amelia_catalog_section', [ 'label' => '<div class="amelia-elementor-content-beta"><p class="amelia-elementor-content-title">' . BackendStrings::getWordPressStrings()['catalog_booking_gutenberg_block']['title'] . '</p><br><p class="amelia-elementor-content-p">' . BackendStrings::getWordPressStrings()['catalog_booking_gutenberg_block']['description'] . '</p>', ] ); $options = [ 'show_catalog' => BackendStrings::getWordPressStrings()['show_catalog'], 'show_category' => BackendStrings::getWordPressStrings()['show_category'], 'show_service' => BackendStrings::getWordPressStrings()['show_service'], ]; if ($controls_data['packages']) { $options['show_package'] = BackendStrings::getWordPressStrings()['show_package']; } $this->add_control( 'select_catalog', [ 'label' => BackendStrings::getWordPressStrings()['select_catalog_view'], 'type' => Controls_Manager::SELECT, 'label_block' => true, 'options' => $options, 'default' => 'show_catalog', ] ); $this->add_control( 'select_category', [ 'label' => BackendStrings::getWordPressStrings()['select_category'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['categories'], 'condition' => ['select_catalog' => 'show_category'], 'default' => array_keys($controls_data['categories']) ? array_keys($controls_data['categories'])[0] : 0, ] ); $this->add_control( 'select_service', [ 'label' => BackendStrings::getWordPressStrings()['select_service'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['services'], 'condition' => ['select_catalog' => 'show_service'], 'default' => array_keys($controls_data['services']) ? array_keys($controls_data['services'])[0] : 0, ] ); if ($controls_data['packages']) { $this->add_control( 'select_package', [ 'label' => BackendStrings::getWordPressStrings()['select_package'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['packages'], 'condition' => ['select_catalog' => 'show_package'], 'default' => array_keys($controls_data['packages']) ? array_keys($controls_data['packages'])[0] : 0, ] ); } $this->add_control( 'preselect', [ 'label' => BackendStrings::getWordPressStrings()['filter'], 'type' => Controls_Manager::SWITCHER, 'default' => false, 'label_on' => BackendStrings::getCommonStrings()['yes'], 'label_off' => BackendStrings::getCommonStrings()['no'], ] ); $this->add_control( 'select_employee', [ 'label' => BackendStrings::getWordPressStrings()['select_employee'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['employees'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); $this->add_control( 'select_location', [ 'label' => BackendStrings::getWordPressStrings()['select_location'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['locations'], 'condition' => ['preselect' => 'yes'], 'default' => '0', ] ); if ($controls_data['show']) { $this->add_control( 'select_show', [ 'label' => BackendStrings::getWordPressStrings()['show_all'], 'type' => Controls_Manager::SELECT, 'options' => $controls_data['show'], 'condition' => ['preselect' => 'yes'], 'default' => '', ] ); } $this->add_control( 'load_manually', [ 'label' => BackendStrings::getWordPressStrings()['manually_loading'], 'label_block' => true, 'type' => Controls_Manager::TEXT, 'placeholder' => '', 'description' => BackendStrings::getWordPressStrings()['manually_loading_description'], ] ); $this->add_control( 'trigger_type', [ 'label' => BackendStrings::getWordPressStrings()['trigger_type'], 'type' => Controls_Manager::SELECT, 'description' => BackendStrings::getWordPressStrings()['trigger_type_tooltip'], 'options' => $controls_data['trigger_types'], 'default' => 'id' ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); if ($settings['select_catalog'] === 'show_package') { $this->remove_control('select_show'); } $trigger = $settings['load_manually'] !== '' ? ' trigger=' . $settings['load_manually'] : ''; $trigger_type = $settings['load_manually'] && $settings['trigger_type'] !== '' ? ' trigger_type=' . $settings['trigger_type'] : ''; $show = ''; if ($settings['select_catalog'] === 'show_catalog') { $category_service = ''; $show = empty($settings['select_show']) ? '' : ' show=' . $settings['select_show']; } elseif ($settings['select_catalog'] === 'show_category') { $category_service = ' category=' . $settings['select_category']; $show = empty($settings['select_show']) ? '' : ' show=' . $settings['select_show']; } elseif ($settings['select_catalog'] === 'show_service') { $category_service = ' service=' . $settings['select_service']; $show = empty($settings['select_show']) || $settings['select_show'] === 'packages' ? '' : ' show=' . $settings['select_show']; } elseif ($settings['select_catalog'] === 'show_package') { $category_service = ' package=' . $settings['select_package']; } else { $category_service = ''; } if ($settings['preselect']) { $employee = $settings['select_employee'] === '0' ? '' : ' employee=' . $settings['select_employee']; $location = $settings['select_location'] === '0' ? '' : ' location=' . $settings['select_location']; } else { $employee = ''; $location = ''; } echo esc_html('[ameliacatalogbooking' . $show . $trigger . $trigger_type . $category_service . $employee . $location . ']'); } public static function amelia_elementor_get_data() { $data = GutenbergBlock::getEntitiesData()['data']; $elementorData = []; $elementorData['categories'] = []; foreach ($data['categories'] as $category) { $elementorData['categories'][$category['id']] = $category['name'] . ' (id: ' . $category['id'] . ')'; } $elementorData['services'] = []; foreach ($data['servicesList'] as $service) { if ($service) { $elementorData['services'][$service['id']] = $service['name'] . ' (id: ' . $service['id'] . ')'; } } $elementorData['packages'] = []; foreach ($data['packages'] as $package) { $elementorData['packages'][$package['id']] = $package['name'] . ' (id: ' . $package['id'] . ')'; } $elementorData['employees'] = []; $elementorData['employees'][0] = BackendStrings::getWordPressStrings()['show_all_employees']; foreach ($data['employees'] as $provider) { $elementorData['employees'][$provider['id']] = $provider['firstName'] . $provider['lastName'] . ' (id: ' . $provider['id'] . ')'; } $elementorData['locations'] = []; $elementorData['locations'][0] = BackendStrings::getWordPressStrings()['show_all_locations']; foreach ($data['locations'] as $location) { $elementorData['locations'][$location['id']] = $location['name'] . ' (id: ' . $location['id'] . ')'; } $elementorData['show'] = $data['packages'] ? [ '' => BackendStrings::getWordPressStrings()['show_all'], 'services' => BackendStrings::getCommonStrings()['services'], 'packages' => BackendStrings::getCommonStrings()['packages'] ] : []; $elementorData['trigger_types'] = [ 'id' => BackendStrings::getWordPressStrings()['trigger_type_id'], 'class' => BackendStrings::getWordPressStrings()['trigger_type_class'] ]; return $elementorData; } } WP/UserService/CreateWPUser.php 0000666 00000004125 15165376447 0012403 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\UserService; /** * Class CreateWPUser * * @package AmeliaBooking\Infrastructure\WP\UserService */ class CreateWPUser { /** * @param string $email * @param string $firstName * @param string $lastName * @param string|null $role * * @return mixed */ public function create($email, $firstName, $lastName, $role = null) { if (username_exists($email)) { $user = get_user_by('login', $email); if ($user) { $user->add_role($role); return $user->ID; } return null; } else if (email_exists($email)) { $user = get_user_by('email', $email); if ($user) { $user->add_role($role); return $user->ID; } return null; } $userId = wp_create_user($email, wp_generate_password(), $email); wp_update_user([ 'ID' => $userId, 'first_name' => $firstName, 'last_name' => $lastName, ]); if ($userId instanceof WP_Error) { return null; } $this->setRole($role, $userId); wp_new_user_notification($userId, null, 'user'); return (int)$userId; } /** * @param int $id * @param string|null $role * * @return mixed */ public function update($id, $role = null) { $this->addRole($role, $id); } /** * @param string $role * @param int $userId */ private function setRole($role, $userId) { if ($role) { $user = new \WP_User($userId); if (get_role($role)) { $user->set_role($role); } } } /** * @param string $role * @param int $userId */ private function addRole($role, $userId) { if ($role) { $user = new \WP_User($userId); if (get_role($role)) { $user->add_role($role); } } } } WP/UserService/UserAvatar.php 0000666 00000000522 15165376447 0012144 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\UserService; /** * Class UserAvatar * * @package AmeliaBooking\Infrastructure\WP\UserService */ class UserAvatar { /** * @param int $wpUserId * * @return mixed */ public function getAvatar($wpUserId) { return get_avatar_url($wpUserId); } } WP/UserService/UserService.php 0000666 00000012353 15165376447 0012333 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\UserService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Factory\User\UserFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\User\UserRepository; use AmeliaBooking\Infrastructure\WP\UserRoles\UserRoles; use Slim\Container; /** * Class UserService * * @package AmeliaBooking\Infrastructure\WP\UserService */ class UserService { /** * @var UserRepository $usersRepository */ private $usersRepository; /** * UserService constructor. * * @param Container $container * * @throws \Interop\Container\Exception\ContainerException */ public function __construct($container) { $this->usersRepository = $container->get('domain.users.repository'); } /** * Return the user entity for currently logged in user * * @return AbstractUser|bool|null * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getCurrentUser() { // Return null user if WP user id is guest id (0) $uid = get_current_user_id(); if ($uid === 0) { return null; } try { // First try to get from repository $currentUserEntity = $this->usersRepository->findByExternalId($uid); if (!$currentUserEntity instanceof AbstractUser) { throw new NotFoundException('User not found'); } return $currentUserEntity; } catch (NotFoundException $e) { // If user not found creating an entity based on WordPress user data $userType = UserRoles::getUserAmeliaRole($wpUser = wp_get_current_user()) ?: 'customer'; if (empty($wpUser->ID)) { return null; } $firstName = $wpUser->get('first_name') !== '' ? $wpUser->get('first_name') : $wpUser->get('user_nicename'); $lastName = $wpUser->get('last_name') !== '' ? $wpUser->get('last_name') : $wpUser->get('user_nicename'); $email = $wpUser->get('user_email'); $currentUserEntity = UserFactory::create([ 'type' => $userType, 'firstName' => $firstName, 'lastName' => $lastName, 'email' => $email ?: 'guest@example.com', 'externalId' => $wpUser->ID ]); return $currentUserEntity; } } /** * Return the user entity for currently logged in user * * @param $userId * * @return AbstractUser|bool|null * @throws InvalidArgumentException */ public function getWpUserById($userId) { $userType = UserRoles::getUserAmeliaRole($wpUser = get_user_by('id', $userId)) ?: 'customer'; if (!$wpUser || empty($wpUser->ID)) { return null; } return UserFactory::create( [ 'type' => $userType, 'firstName' => $wpUser->get('first_name') !== '' ? $wpUser->get('first_name') : $wpUser->get('user_nicename'), 'lastName' => $wpUser->get('last_name') !== '' ? $wpUser->get('last_name') : $wpUser->get('user_nicename'), 'email' => $wpUser->get('user_email') ?: 'guest@example.com', 'externalId' => $wpUser->ID ] ); } /** * Return all amelia role user ids * * @param $roles * * @return array */ public function getWpUserIdsByRoles($roles) { $ids = []; $wpUsers = get_users(['role__in' => $roles]); foreach ($wpUsers as $user) { $ids[] = $user->ID; } return $ids; } /** * Return authenticated user * * @param $username * @param $password * * @return mixed * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getAuthenticatedUser($username, $password) { if (($wpUser = wp_authenticate($username, $password)) instanceof WP_Error) { return null; } if (empty($wpUser->ID)) { return null; } $currentUserEntity = $this->usersRepository->findByExternalId($wpUser->ID); if (!($currentUserEntity instanceof AbstractUser)) { return null; } return $currentUserEntity; } /** * login user * * @param $username * @param $password * * @return mixed */ public function loginWordPressUser($username, $password) { $user = wp_signon( [ 'user_login' => sanitize_user($username), 'user_password' => trim($password), 'remember' => true, ], true ); wp_set_current_user($user->ID); } /** * logout user * * @return mixed */ public function logoutWordPressUser() { wp_logout(); } } WP/Services/Location/CurrentLocationLite.php 0000666 00000002134 15165376447 0015115 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\Services\Location; use AmeliaBooking\Domain\Services\Location\CurrentLocationInterface; /** * Class CurrentLocationLite * * @package AmeliaBooking\Infrastructure\WP\Services\Location */ class CurrentLocationLite implements CurrentLocationInterface { /** * Get country ISO code by public IP address * * @return string * * @SuppressWarnings(PHPMD.Superglobals) */ public function getCurrentLocationCountryIso() { try { $response = wp_remote_get('https://www.iplocate.io/api/lookup/' . $_SERVER['REMOTE_ADDR'], []); if (is_array($response) && isset($response['body'])) { $result = json_decode($response['body']); return !property_exists($result, 'country_code') ? '' : strtolower($result->country_code ?: ''); } else { return ''; } } catch (\Exception $e) { return ''; } } } WP/Services/Notification/SMSAPIServiceLite.php 0000666 00000003062 15165376447 0015176 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\Services\Notification; use AmeliaBooking\Application\Services\Notification\AbstractSMSAPIService; use AmeliaBooking\Domain\Services\Settings\SettingsService; /** * Class SMSAPIServiceLite * * @package AmeliaBooking\Infrastructure\WP\Services\Notification */ class SMSAPIServiceLite extends AbstractSMSAPIService { /** * @param $route * @param $authorize * @param $data * * @return mixed * * @throws \Interop\Container\Exception\ContainerException */ public function sendRequest($route, $authorize, $data = null) { $params = [ 'method' => 'GET', 'blocking' => true, 'timeout' => 10 ]; // If there is data, request will be POST request, otherwise it will be GET if ($data) { $params['method'] = 'POST'; $params['body'] = $data; } // If authorization is needed, send token to the request header if ($authorize) { /** @var SettingsService $settingsService */ $settingsService = $this->getContainer()->get('domain.settings.service'); $params['headers']['Authorization'] = "Bearer {$settingsService->getSetting('notifications', 'smsApiToken')}"; } $response = wp_remote_post(AMELIA_SMS_API_URL . $route, $params); return !is_wp_error($response) ? json_decode($response['body']) : ''; } } WP/GutenbergBlock/AmeliaEventsListBookingGutenbergBlock.php 0000666 00000003037 15165376447 0020071 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaEventsListBookingGutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class AmeliaEventsListBookingGutenbergBlock extends GutenbergBlock { /** * Register Amelia Events block for Gutenberg */ public static function registerBlockType() { wp_enqueue_script( 'amelia_events_list_booking_gutenberg_block', AMELIA_URL . 'public/js/gutenberg/amelia-events-list-booking/amelia-events-list-booking-gutenberg.js', array('wp-blocks', 'wp-components', 'wp-element', 'wp-editor') ); wp_localize_script( 'amelia_events_list_booking_gutenberg_block', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getWordPressStrings(), self::getEntitiesData() ) ); wp_enqueue_style( 'amelia_booking_gutenberg_styles', AMELIA_URL . 'public/js/gutenberg/amelia-events-list-booking/amelia-gutenberg-styles.css', [], AMELIA_VERSION ); register_block_type( 'amelia/events-list-booking-gutenberg-block', array('editor_script' => 'amelia_events_list_booking_gutenberg_block') ); } } WP/GutenbergBlock/AmeliaBookingGutenbergBlock.php 0000666 00000002335 15165376447 0016050 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaBookingGutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class AmeliaBookingGutenbergBlock extends GutenbergBlock { /** * Register Amelia Booking block for Gutenberg */ public static function registerBlockType() { wp_enqueue_script( 'amelia_booking_gutenberg_block', AMELIA_URL . 'public/js/gutenberg/amelia-booking/amelia-booking-gutenberg.js', array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-editor') ); wp_localize_script( 'amelia_booking_gutenberg_block', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getWordPressStrings(), self::getEntitiesData() ) ); register_block_type( 'amelia/booking-gutenberg-block', array('editor_script' => 'amelia_booking_gutenberg_block') ); } } WP/GutenbergBlock/GutenbergBlock.php 0000666 00000030624 15165376447 0013430 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; use AmeliaBooking\Application\Services\Bookable\BookableApplicationService; use AmeliaBooking\Application\Services\Bookable\PackageApplicationService; use AmeliaBooking\Application\Services\Booking\EventApplicationService; use AmeliaBooking\Application\Services\User\ProviderApplicationService; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Entity\User\Provider; use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory; use AmeliaBooking\Domain\Services\Booking\EventDomainService; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\CategoryRepository; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\ServiceRepository; use AmeliaBooking\Infrastructure\Repository\Booking\Event\EventRepository; use AmeliaBooking\Infrastructure\Repository\Booking\Event\EventTagsRepository; use AmeliaBooking\Infrastructure\Repository\Location\LocationRepository; use AmeliaBooking\Infrastructure\Repository\User\ProviderRepository; use Exception; use Interop\Container\Exception\ContainerException; /** * Class GutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class GutenbergBlock { /** @var Container $container */ private static $container; /** * Register WP Ajax actions. */ public static function init() { if (is_admin() && function_exists('register_block_type')) { if (substr($_SERVER['PHP_SELF'], '-8') == 'post.php' || substr($_SERVER['PHP_SELF'], '-12') == 'post-new.php' ) { if (self::isGutenbergActive()) { $class = get_called_class(); add_action('enqueue_block_editor_assets', function () use ($class) { $class::registerBlockType(); }); } } } } /** * Register block for gutenberg */ public static function registerBlockType() { } /** * Check if Block Editor is active. * * @return bool */ public static function isGutenbergActive() { // Gutenberg plugin is installed and activated. $gutenberg = !(false === has_filter('replace_editor', 'gutenberg_init')); // Block editor since 5.0. $block_editor = version_compare($GLOBALS['wp_version'], '5.0-beta', '>'); if (!$gutenberg && !$block_editor) { return false; } if (self::isClassicEditorPluginActive()) { $editor_option = get_option('classic-editor-replace'); $block_editor_active = array('no-replace', 'block'); return in_array($editor_option, $block_editor_active, true); } // Fix for conflict with Avada - Fusion builder and gutenberg blocks if (class_exists('FusionBuilder') && !(isset($_GET['gutenberg-editor']))) { return false; } // Fix for conflict with Disable Gutenberg plugin if (class_exists('DisableGutenberg')) { return false; } // Fix for conflict with WP Bakery Page Builder if (class_exists('Vc_Manager') && (isset($_GET['classic-editor']))) { return false; } // Fix for conflict with WooCommerce product page if (isset($_GET['post_type']) && $_GET['post_type'] === 'product' && class_exists('WooCommerce')) { return false; } return true; } /** * Check if Classic Editor plugin is active * * @return bool */ public static function isClassicEditorPluginActive() { if (!function_exists('is_plugin_active')) { include_once ABSPATH . 'wp-admin/includes/plugin.php'; } if (is_plugin_active('classic-editor/classic-editor.php')) { return true; } return false; } /** * Set Amelia Container * * @param $container */ public static function setContainer($container) { self::$container = $container; } /** * Get entities data for front-end */ public static function getEntitiesData() { return (new self)->getAllEntitiesForGutenbergBlocks(); } /** * Get Entities for Gutenberg blocks */ public function getAllEntitiesForGutenbergBlocks() { try { self::setContainer(require AMELIA_PATH . '/src/Infrastructure/ContainerConfig/container.php'); /** @var LocationRepository $locationRepository */ $locationRepository = self::$container->get('domain.locations.repository'); $locations = $locationRepository->getAllOrderedByName(); $resultData['locations'] = $locations->toArray(); /** @var ServiceRepository $serviceRepository */ $serviceRepository = self::$container->get('domain.bookable.service.repository'); /** @var CategoryRepository $categoryRepository */ $categoryRepository = self::$container->get('domain.bookable.category.repository'); /** @var BookableApplicationService $bookableAS */ $bookableAS = self::$container->get('application.bookable.service'); $services = $serviceRepository->getAllArrayIndexedById(); $categories = $categoryRepository->getAllIndexedById(); $bookableAS->addServicesToCategories($categories, $services); $resultData['categories'] = $categories->toArray(); /** @var ProviderRepository $providerRepository */ $providerRepository = self::$container->get('domain.users.providers.repository'); /** @var ProviderApplicationService $providerAS */ $providerAS = self::$container->get('application.user.provider.service'); /** @var Collection $providers */ $providers = $providerRepository->getByCriteriaWithSchedule([]); $providerServicesData = $providerRepository->getProvidersServices(); foreach ((array)$providerServicesData as $providerKey => $providerServices) { $provider = $providers->getItem($providerKey); $providerServiceList = new Collection(); foreach ((array)$providerServices as $serviceKey => $providerService) { $service = $services->getItem($serviceKey); if ($service && $provider) { $providerServiceList->addItem( ServiceFactory::create(array_merge($service->toArray(), $providerService)), $service->getId()->getValue() ); } } $provider->setServiceList($providerServiceList); } /** @var Provider $currentUser */ $currentUser = self::$container->get('logged.in.user'); $resultData['employees'] = $providerAS->removeAllExceptUser( $providers->toArray(), $currentUser ); $finalData = self::getOnlyCatSerLocEmp($resultData); /** @var EventRepository $eventRepository */ $eventRepository = self::$container->get('domain.booking.event.repository'); /** @var EventApplicationService $eventAS */ $eventAS = self::$container->get('application.booking.event.service'); $filteredEventIds = $eventRepository->getFilteredIds( ['dates' => [DateTimeService::getNowDateTime()]], 100 ); $eventsIds = array_column($filteredEventIds, 'id'); /** @var Collection $events */ $events = $eventsIds ? $eventAS->getEventsByIds( $eventsIds, [ 'fetchEventsPeriods' => true, 'fetchEventsTickets' => false, 'fetchEventsTags' => false, 'fetchEventsProviders' => false, 'fetchEventsImages' => false, 'fetchBookingsTickets' => false, 'fetchBookingsCoupons' => false, 'fetchApprovedBookings' => false, 'fetchBookingsPayments' => false, 'fetchBookingsUsers' => false, ] ) : new Collection(); $finalData['events'] = $events->toArray(); /** @var EventDomainService $eventDS */ $eventDS = self::$container->get('domain.booking.event.service'); $finalData['events'] = $eventDS->getShortcodeForEventList(self::$container, $finalData['events']); /** @var EventTagsRepository $eventTagsRepository */ $eventTagsRepository = self::$container->get('domain.booking.event.tag.repository'); /** @var Collection $tags * */ $tags = $eventTagsRepository->getAllDistinctByCriteria( [ 'eventIds' => array_column($finalData['events'], 'id') ] ); /** @var PackageApplicationService $packageApplicationService */ $packageApplicationService = self::$container->get('application.bookable.package'); $finalData['packages'] = $packageApplicationService->getPackagesArray(); $finalData['tags'] = $tags->toArray(); return ['data' => $finalData]; } catch (Exception $exception) { return ['data' => [ 'categories' => [], 'servicesList' => [], 'locations' => [], 'employees' => [], 'events' => [], 'tags' => [], 'packages' => [], ]]; } catch (ContainerException $e) { return ['data' => [ 'categories' => [], 'servicesList' => [], 'locations' => [], 'employees' => [], 'events' => [], 'tags' => [], 'packages' => [], ]]; } } /** * Get only Categories, Services, Employees and Locations for Gutenberg blocks */ public static function getOnlyCatSerLocEmp($resultData) { $data = []; $data['categories'] = []; $data['servicesList'] = []; if ($resultData['categories'] !== []) { for ($i = 0; $i < count($resultData['categories']); $i++) { $data['categories'][] = [ 'id' => $resultData['categories'][$i]['id'], 'name' => $resultData['categories'][$i]['name'] ]; if ($resultData['categories'][$i]['serviceList'] !== []) { for ($j = 0; $j < count($resultData['categories'][$i]['serviceList']); $j++) { if (!$resultData['categories'][$i]['serviceList'][$j]['show']) { continue; } $data['servicesList'][] = [ 'id' => $resultData['categories'][$i]['serviceList'][$j]['id'], 'name' => $resultData['categories'][$i]['serviceList'][$j]['name'] ]; } } } } else { $data['categories'] = []; $data['servicesList'] = []; } if ($resultData['locations'] !== []) { for ($i = 0; $i < count($resultData['locations']); $i++) { $data['locations'][] = [ 'id' => $resultData['locations'][$i]['id'], 'name' => $resultData['locations'][$i]['name'] ]; } } else { $data['locations'] = []; } if ($resultData['employees'] !== []) { for ($i = 0; $i < count($resultData['employees']); $i++) { $data['employees'][] = [ 'id' => $resultData['employees'][$i]['id'], 'firstName' => $resultData['employees'][$i]['firstName'], 'lastName' => $resultData['employees'][$i]['lastName'], ]; } } else { $data['employees'] = []; } return $data; } } WP/GutenbergBlock/AmeliaCatalogBookingGutenbergBlock.php 0000666 00000003021 15165376447 0017334 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaCatalogBookingGutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class AmeliaCatalogBookingGutenbergBlock extends GutenbergBlock { /** * Register Amelia Booking block for Gutenberg */ public static function registerBlockType() { wp_enqueue_script( 'amelia_catalog_booking_gutenberg_block', AMELIA_URL . 'public/js/gutenberg/amelia-catalog-booking/amelia-catalog-booking-gutenberg.js', array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-editor') ); wp_localize_script( 'amelia_catalog_booking_gutenberg_block', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getWordPressStrings(), self::getEntitiesData() ) ); wp_enqueue_style( 'amelia_catalog_booking_gutenberg_styles', AMELIA_URL . 'public/js/gutenberg/amelia-catalog-booking/amelia-catalog-booking-gutenberg.css', [], AMELIA_VERSION ); register_block_type( 'amelia/catalog-booking-gutenberg-block', array('editor_script' => 'amelia_catalog_booking_gutenberg_block') ); } } WP/GutenbergBlock/AmeliaEventsGutenbergBlock.php 0000666 00000002325 15165376447 0015723 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaEventsGutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class AmeliaEventsGutenbergBlock extends GutenbergBlock { /** * Register Amelia Events block for Gutenberg */ public static function registerBlockType() { wp_enqueue_script( 'amelia_events_gutenberg_block', AMELIA_URL . 'public/js/gutenberg/amelia-events/amelia-events-gutenberg.js', array('wp-blocks', 'wp-components', 'wp-element', 'wp-editor') ); wp_localize_script( 'amelia_booking_gutenberg_block', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getWordPressStrings(), self::getEntitiesData() ) ); register_block_type( 'amelia/events-gutenberg-block', array('editor_script' => 'amelia_events_gutenberg_block') ); } } WP/GutenbergBlock/AmeliaStepBookingGutenbergBlock.php 0000666 00000002745 15165376447 0016711 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class AmeliaStepBookingGutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class AmeliaStepBookingGutenbergBlock extends GutenbergBlock { /** * Register Amelia Booking block for Gutenberg */ public static function registerBlockType() { wp_enqueue_script( 'amelia_step_booking_gutenberg_block', AMELIA_URL . 'public/js/gutenberg/amelia-step-booking/amelia-step-booking-gutenberg.js', array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-editor') ); wp_localize_script( 'amelia_step_booking_gutenberg_block', 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getWordPressStrings(), self::getEntitiesData() ) ); wp_enqueue_style( 'amelia_booking_gutenberg_styles', AMELIA_URL . 'public/js/gutenberg/amelia-step-booking/amelia-gutenberg-styles.css', [], AMELIA_VERSION ); register_block_type( 'amelia/step-booking-gutenberg-block', array('editor_script' => 'amelia_step_booking_gutenberg_block') ); } } WP/GutenbergBlock/AmeliaCatalogGutenbergBlock.php 0000666 00000001555 15165376447 0016035 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\GutenbergBlock; /** * Class AmeliaCatalogGutenbergBlock * * @package AmeliaBooking\Infrastructure\WP\GutenbergBlock */ class AmeliaCatalogGutenbergBlock extends GutenbergBlock { /** * Register Amelia Catalog block for gutenberg */ public static function registerBlockType() { wp_enqueue_script( 'amelia_catalog_gutenberg_block', AMELIA_URL . 'public/js/gutenberg/amelia-catalog/amelia-catalog-gutenberg.js', array('wp-blocks', 'wp-components', 'wp-element', 'wp-editor') ); register_block_type( 'amelia/catalog-gutenberg-block', array('editor_script' => 'amelia_catalog_gutenberg_block') ); } } WP/InstallActions/ActivationNewSiteMultisite.php 0000666 00000001261 15165376447 0016060 0 ustar 00 <?php /** * Multisite hook on new site activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; /** * Class ActivationNewSiteMultisite * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class ActivationNewSiteMultisite { /** * Activate the plugin for every newly created site if the plugin is network activated * * @param $siteId */ public static function init($siteId) { if (is_plugin_active_for_network(AMELIA_PLUGIN_SLUG)) { switch_to_blog($siteId); //Create database table if not exists ActivationDatabaseHook::init(); restore_current_blog(); } } } WP/InstallActions/DeletionMultisite.php 0000666 00000001535 15165376447 0014227 0 ustar 00 <?php /** * Network activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; /** * Class DeletionMultisite * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class DeletionMultisite { /** * Delete the plugin tables for every sub-site separately * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public static function delete() { global $wpdb; // Get current blog id $oldSite = $wpdb->blogid; // Get all blog ids $siteIds = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs"); foreach ($siteIds as $siteId) { switch_to_blog($siteId); // Delete database tables if exists DeleteDatabaseHook::delete(); } // Returns to current blog switch_to_blog($oldSite); } } WP/InstallActions/ActivationMultisite.php 0000666 00000001417 15165376447 0014564 0 ustar 00 <?php /** * Network activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; /** * Class ActivationMultisite * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class ActivationMultisite { /** * Activate the plugin for every sub-site separately */ public static function init() { global $wpdb; // Get current blog id $oldSite = $wpdb->blogid; // Get all blog ids $siteIds = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs"); foreach ($siteIds as $siteId) { switch_to_blog($siteId); // Create database table if not exists ActivationDatabaseHook::init(); } // Returns to current blog switch_to_blog($oldSite); } } WP/InstallActions/ActivationRolesHook.php 0000666 00000001346 15165376447 0014513 0 ustar 00 <?php /** * Role hook for activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; use AmeliaBooking\Infrastructure\WP\config\Roles; use AmeliaBooking\Infrastructure\WP\UserRoles\UserRoles; /** * Class ActivationRolesHook * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class ActivationRolesHook { /** * Add new custom roles and add capabilities to administrator role */ public static function init() { $roles = new Roles(); UserRoles::init($roles()); $adminRole = get_role('administrator'); if ($adminRole !== null) { foreach (Roles::$rolesList as $role) { $adminRole->add_cap($role); } } } } WP/InstallActions/AutoUpdateHook.php 0000666 00000020657 15165376447 0013466 0 ustar 00 <?php /** @noinspection PhpUnusedParameterInspection */ /** * Database hook for activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\HelperService\HelperService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; use WP_Error; use WP_Upgrader; /** * Class AutoUpdateHook * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class AutoUpdateHook { /** * Add our self-hosted auto update plugin to the filter transient * * @param $transient * * @return object $ transient */ public static function checkUpdate($transient) { if (empty($transient->checked)) { return $transient; } $settingsService = new SettingsService(new SettingsStorage()); /** @var string $purchaseCode */ $purchaseCode = $settingsService->getSetting('activation', 'purchaseCodeStore'); /** @var string $envatoTokenEmail */ $envatoTokenEmail = $settingsService->getSetting('activation', 'envatoTokenEmail'); // Get the remote info $remoteInformation = self::getRemoteInformation($purchaseCode, $envatoTokenEmail); // If a newer version is available, add the update if ($remoteInformation && version_compare(AMELIA_VERSION, $remoteInformation->new_version, '<')) { $transient->response[AMELIA_PLUGIN_SLUG] = $remoteInformation; } return $transient; } /** * Add our self-hosted description to the filter * * @param bool $response * @param array $action * @param $args * * @return bool|object */ public static function checkInfo($response, $action, $args) { if ('plugin_information' !== $action) { return $response; } if (empty($args->slug)) { return $response; } $settingsService = new SettingsService(new SettingsStorage()); /** @var string $purchaseCode */ $purchaseCode = $settingsService->getSetting('activation', 'purchaseCodeStore'); /** @var string $envatoTokenEmail */ $envatoTokenEmail = $settingsService->getSetting('activation', 'envatoTokenEmail'); if ($args->slug === AMELIA_PLUGIN_SLUG) { return self::getRemoteInformation($purchaseCode, $envatoTokenEmail); } return $response; } /** * Add a message for unavailable auto update on plugins page if plugin is not activated */ public static function addMessageOnPluginsPage() { /** @var SettingsService $settingsService */ $settingsService = new SettingsService(new SettingsStorage()); /** @var bool $activated */ $activated = $settingsService->getSetting('activation', 'active'); /** @var array $settingsStrings */ $settingsStrings = BackendStrings::getSettingsStrings(); /** @var string $url */ $url = AMELIA_SITE_URL . '/wp-admin/admin.php?page=wpamelia-settings&activeSetting=activation'; /** @var string $redirect */ $redirect = '<a href="' . $url . '" target="_blank">' . $settingsStrings['settings_lower'] . '</a>'; if (!$activated) { echo sprintf(' ' . $settingsStrings['plugin_not_activated'], $redirect); } } /** * Add error message on plugin update if plugin is not activated * * @param bool $reply * @param string $package * @param WP_Upgrader $updater * * @return WP_Error|string|bool * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public static function addMessageOnUpdate($reply, $package, $updater) { /** @var array $settingsStrings */ $settingsStrings = BackendStrings::getSettingsStrings(); /** @var string $url */ $url = AMELIA_SITE_URL . '/wp-admin/admin.php?page=wpamelia-settings&activeSetting=activation'; /** @var string $redirect */ $redirect = '<a href="' . $url . '" target="_blank">' . $settingsStrings['settings_lower'] . '</a>'; if (!$package) { return new WP_Error( 'amelia_not_activated', sprintf(' ' . $settingsStrings['plugin_not_activated'], $redirect) ); } return $reply; } /** * Get information about the remote version * * @param string $purchaseCode * @param string $envatoTokenEmail * * @return bool|object */ private static function getRemoteInformation($purchaseCode, $envatoTokenEmail) { $serverName = (defined('WP_CLI') && WP_CLI) ? php_uname('n') : $_SERVER['SERVER_NAME']; $request = wp_remote_post( AMELIA_STORE_API_URL . 'autoupdate/info', [ 'body' => [ 'slug' => 'ameliabooking', 'purchaseCode' => trim($purchaseCode), 'envatoTokenEmail' => trim($envatoTokenEmail), 'domain' => self::getDomain( $serverName ), 'subdomain' => self::getSubDomain( $serverName ) ] ] ); if ((!is_wp_error($request) || wp_remote_retrieve_response_code($request) === 200) && isset($request['body'])) { $body = json_decode($request['body']); return $body && isset($body->info) ? unserialize($body->info) : false; } return false; } /** * @param $domain * * @return mixed */ public static function extractDomain($domain) { $topLevelDomainsJSON = require( AMELIA_PATH . '/view/backend/top-level-domains.php'); $topLevelDomains = json_decode($topLevelDomainsJSON, true) ; $tempDomain= ''; $extractDomainArray = explode('.', $domain); for ($i = 0; $i <= count($extractDomainArray); $i++) { $slicedDomainArray = array_slice($extractDomainArray, $i); $slicedDomainString = implode('.', $slicedDomainArray); if (in_array($slicedDomainString, $topLevelDomains)) { $tempDomain = array_slice($extractDomainArray, $i-1); break; } } if ($tempDomain == '') { $tempDomain = $extractDomainArray; } return implode( '.', $tempDomain); } /** * @param $domain * * @return string */ public static function extractSubdomain($domain) { $host = explode('.', $domain); $domain = self::extractDomain($domain); $domain = explode('.', $domain); return implode( '.', array_diff($host, $domain)); } /** * Check if serve name is IPv4 or Ipv6 * * @param $domain * * @return boolean */ public static function isIP($domain) { if (preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $domain) || preg_match("/^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$/", $domain)) { return true; } else { return false; } } /** * Remove www from server name * * @param $url * * @return string */ public static function removeWWW($url) { if (in_array(substr( $url, 0, 5 ),['www1.','www2.','www3.','www4.'])) { return substr_replace ($url,"", 0,5 ); } else if (substr( $url, 0, 4 ) ==='www.') { return substr_replace($url, "", 0, 4); } return $url; } /** * Get filtered domain * * @param $domain * * @return string */ public static function getDomain($domain) { $domain = self::isIP($domain) ? $domain : self::extractDomain( self::removeWWW($domain) ); return $domain; } /** * Get filtered subdomain * * @param $subdomain * * @return string */ public static function getSubDomain($subdomain) { $subdomain = self::isIP($subdomain) ? '' : self::extractSubdomain( self::removeWWW($subdomain) ); return $subdomain; } } WP/InstallActions/ActivationSettingsHook.php 0000666 00000231647 15165376447 0015240 0 ustar 00 <?php /** * Settings hook for activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\String\Token; use AmeliaBooking\Infrastructure\Services\Frontend\LessParserService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use Exception; /** * Class ActivationSettingsHook * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class ActivationSettingsHook { /** * Initialize the plugin * * @throws Exception */ public static function init() { self::initDBSettings(); self::initGeneralSettings(); self::initCompanySettings(); self::initNotificationsSettings(); self::initDaysOffSettings(); self::initWeekScheduleSettings(); self::initGoogleCalendarSettings(); self::initOutlookCalendarSettings(); self::initPaymentsSettings(); self::initActivationSettings(); self::initCustomizationSettings(); self::initLabelsSettings(); self::initRolesSettings(); self::initAppointmentsSettings(); self::initWebHooksSettings(); self::initZoomSettings(); self::initLessonSpaceSettings(); self::initIcsSettings(); self::initFacebookPixelSettings(); self::initGoogleTagSettings(); } /** * @param string $category * @param array $settings * @param bool $replace */ public static function initSettings($category, $settings, $replace = false) { $settingsService = new SettingsService(new SettingsStorage()); if (!$settingsService->getCategorySettings($category)) { $settingsService->setCategorySettings( $category, [] ); } foreach ($settings as $key => $value) { if ($replace || null === $settingsService->getSetting($category, $key)) { $settingsService->setSetting( $category, $key, $value ); } } } /** * Init General Settings */ private static function initGeneralSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('general'); $settings = [ 'timeSlotLength' => 1800, 'serviceDurationAsSlot' => false, 'bufferTimeInSlot' => true, 'defaultAppointmentStatus' => 'approved', 'minimumTimeRequirementPriorToBooking' => 0, 'minimumTimeRequirementPriorToCanceling' => 0, 'minimumTimeRequirementPriorToRescheduling' => isset($savedSettings['minimumTimeRequirementPriorToCanceling']) && !isset($savedSettings['minimumTimeRequirementPriorToRescheduling']) ? $savedSettings['minimumTimeRequirementPriorToCanceling'] : 0, 'numberOfDaysAvailableForBooking' => SettingsService::NUMBER_OF_DAYS_AVAILABLE_FOR_BOOKING, 'backendSlotsDaysInFuture' => SettingsService::NUMBER_OF_DAYS_AVAILABLE_FOR_BOOKING, 'backendSlotsDaysInPast' => SettingsService::NUMBER_OF_DAYS_AVAILABLE_FOR_BOOKING, 'phoneDefaultCountryCode' => 'auto', 'requiredPhoneNumberField' => false, 'requiredEmailField' => true, 'itemsPerPage' => 12, 'appointmentsPerPage' => 100, 'servicesPerPage' => 100, 'customersFilterLimit' => 100, 'calendarEmployeesPreselected' => 0, 'gMapApiKey' => '', 'addToCalendar' => true, 'defaultPageOnBackend' => 'Dashboard', 'showClientTimeZone' => false, 'redirectUrlAfterAppointment' => '', 'customFieldsUploadsPath' => '', 'backLink' => self::getBackLinkSetting(), 'runInstantPostBookingActions' => false, 'sortingPackages' => 'nameAsc', 'sortingServices' => 'nameAsc', 'calendarLocaleSubstitutes' => [ ], 'googleRecaptcha' => [ 'enabled' => false, 'invisible' => true, 'siteKey' => '', 'secret' => '', ], 'usedLanguages' => [], ]; self::initSettings('general', $settings); self::setNewSettingsToExistingSettings( 'general', [ ['backLink', 'url'], ], $settings ); } /** * Init DB Settings */ private static function initDBSettings() { $settings = [ 'mysqliEnabled' => false, 'pdoEmulatePrepares' => false, 'pdoBigSelect' => false, 'ssl' => [ 'enable' => false, 'key' => null, 'cert' => null, 'ca' => null, 'verify_cert' => null, ], 'wpTablesPrefix' => '', ]; self::initSettings('db', $settings); } /** * Init Company Settings */ private static function initCompanySettings() { $settings = [ 'pictureFullPath' => '', 'pictureThumbPath' => '', 'name' => '', 'address' => '', 'phone' => '', 'countryPhoneIso' => '', 'website' => '', 'translations' => '', ]; self::initSettings('company', $settings); } /** * Init Notification Settings */ private static function initNotificationsSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('notifications'); $settings = [ 'mailService' => 'php', 'smtpHost' => '', 'smtpPort' => '', 'smtpSecure' => 'ssl', 'smtpUsername' => '', 'smtpPassword' => '', 'mailgunApiKey' => '', 'mailgunDomain' => '', 'mailgunEndpoint' => '', 'senderName' => '', 'senderEmail' => '', 'notifyCustomers' => true, 'sendAllCF' => true, 'smsAlphaSenderId' => 'Amelia', 'smsSignedIn' => false, 'smsApiToken' => '', 'bccEmail' => '', 'bccSms' => '', 'cancelSuccessUrl' => '', 'cancelErrorUrl' => '', 'breakReplacement' => '<br>', 'pendingReminder' => false, 'whatsAppEnabled' => $savedSettings && !empty($savedSettings['whatsAppPhoneID']) && !empty($savedSettings['whatsAppAccessToken']) && !empty($savedSettings['whatsAppBusinessID']) ? true : false, 'whatsAppPhoneID' => '', 'whatsAppAccessToken' => '', 'whatsAppBusinessID' => '', 'whatsAppLanguage' => '', 'whatsAppReplyEnabled' => false, 'whatsAppReplyMsg' => 'Dear %customer_full_name%, This message does not have an option for responding. If you need additional information about your booking, please contact us at %company_phone%', 'whatsAppReplyToken' => (new Token(null, 20))->getValue(), ]; self::initSettings('notifications', $settings); } /** * Init Days Off Settings */ private static function initDaysOffSettings() { self::initSettings('daysOff', []); } /** * Init Work Schedule Settings */ private static function initWeekScheduleSettings() { self::initSettings('weekSchedule', [ [ 'day' => 'Monday', 'time' => ['09:00', '17:00'], 'breaks' => [], 'periods' => [] ], [ 'day' => 'Tuesday', 'time' => ['09:00', '17:00'], 'breaks' => [], 'periods' => [] ], [ 'day' => 'Wednesday', 'time' => ['09:00', '17:00'], 'breaks' => [], 'periods' => [] ], [ 'day' => 'Thursday', 'time' => ['09:00', '17:00'], 'breaks' => [], 'periods' => [] ], [ 'day' => 'Friday', 'time' => ['09:00', '17:00'], 'breaks' => [], 'periods' => [] ], [ 'day' => 'Saturday', 'time' => [], 'breaks' => [], 'periods' => [] ], [ 'day' => 'Sunday', 'time' => [], 'breaks' => [], 'periods' => [] ] ]); } /** * Init Google Calendar Settings */ private static function initGoogleCalendarSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('googleCalendar'); $settings = [ 'clientID' => '', 'clientSecret' => '', 'redirectURI' => AMELIA_SITE_URL . '/wp-admin/admin.php?page=wpamelia-employees', 'showAttendees' => false, 'insertPendingAppointments' => false, 'addAttendees' => false, 'sendEventInvitationEmail' => false, 'removeGoogleCalendarBusySlots' => false, 'maximumNumberOfEventsReturned' => 50, 'eventTitle' => '%service_name%', 'eventDescription' => '', 'includeBufferTimeGoogleCalendar' => false, 'status' => 'tentative', 'enableGoogleMeet' => false, 'title' => [ 'appointment' => $savedSettings && !empty($savedSettings['eventTitle']) ? $savedSettings['eventTitle'] : '%service_name%', 'event' => '%event_name%' ], 'description' => [ 'appointment' => $savedSettings && !empty($savedSettings['eventDescription']) ? $savedSettings['eventDescription'] : '', 'event' => '' ], ]; self::initSettings('googleCalendar', $settings); } /** * Init Outlook Calendar Settings */ private static function initOutlookCalendarSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('outlookCalendar'); $settings = [ 'clientID' => '', 'clientSecret' => '', 'redirectURI' => AMELIA_SITE_URL . '/wp-admin/', 'insertPendingAppointments' => false, 'addAttendees' => false, 'sendEventInvitationEmail' => false, 'removeOutlookCalendarBusySlots' => false, 'maximumNumberOfEventsReturned' => 50, 'eventTitle' => '%service_name%', 'eventDescription' => '', 'includeBufferTimeOutlookCalendar' => false, 'title' => [ 'appointment' => $savedSettings && !empty($savedSettings['eventTitle']) ? $savedSettings['eventTitle'] : '%service_name%', 'event' => '%event_name%' ], 'description' => [ 'appointment' => $savedSettings && !empty($savedSettings['eventDescription']) ? $savedSettings['eventDescription'] : '', 'event' => '' ], ]; self::initSettings('outlookCalendar', $settings); } /** * Init Zoom Settings */ private static function initZoomSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('zoom'); $settings = [ 'enabled' => true, 'apiKey' => '', 'apiSecret' => '', 'meetingTitle' => '%reservation_name%', 'meetingAgenda' => '%reservation_description%', 'pendingAppointmentsMeetings' => false, 'maxUsersCount' => 300, 's2sEnabled' => !$savedSettings || (!$savedSettings['apiKey'] && !$savedSettings['apiSecret']), 'accountId' => '', 'clientId' => '', 'clientSecret' => '', 'accessToken' => '', ]; self::initSettings('zoom', $settings); } /** * Init Lesson Space Settings */ private static function initLessonSpaceSettings() { $settings = [ 'enabled' => true, 'apiKey' => '', 'spaceNameAppointments' => '%reservation_name%', 'spaceNameEvents' => '%reservation_name%', 'pendingAppointments' => false, 'companyId' => '' ]; self::initSettings('lessonSpace', $settings); } /** * Init FacebookPixel Settings */ private static function initFacebookPixelSettings() { $settings = [ 'id' => '', 'tracking' => [ 'appointment' => [], 'event' => [], 'package' => [], ], ]; self::initSettings('facebookPixel', $settings); } /** * Init GoogleTag Settings */ private static function initGoogleTagSettings() { $settings = [ 'id' => '', 'tracking' => [ 'appointment' => [], 'event' => [], 'package' => [], ], ]; self::initSettings('googleTag', $settings); } /** * Init Ics Settings */ private static function initIcsSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('general'); $settings = [ 'sendIcsAttachment' => isset($savedSettings['sendIcsAttachment']) ? $savedSettings['sendIcsAttachment'] : false, 'sendIcsAttachmentPending' => false, 'description' => [ 'appointment' => '', 'event' => '', 'translations' => [ 'appointment' => null, 'event' => null, ], ], ]; self::initSettings('ics', $settings); } /** * Init Payments Settings */ private static function initPaymentsSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('payments'); $settings = [ 'currency' => 'USD', 'symbol' => '$', 'priceSymbolPosition' => 'before', 'priceNumberOfDecimals' => 2, 'priceSeparator' => 1, 'hideCurrencySymbolFrontend' => false, 'defaultPaymentMethod' => 'onSite', 'onSite' => true, 'coupons' => AMELIA_LITE_VERSION ? false : true, 'paymentLinks' => [ 'enabled' => false, 'changeBookingStatus' => false, 'redirectUrl' => AMELIA_SITE_URL ], 'payPal' => [ 'enabled' => false, 'sandboxMode' => false, 'liveApiClientId' => '', 'liveApiSecret' => '', 'testApiClientId' => '', 'testApiSecret' => '', 'description' => [ 'enabled' => false, 'appointment' => '', 'package' => '', 'event' => '' ], ], 'stripe' => [ 'enabled' => false, 'testMode' => false, 'livePublishableKey' => '', 'liveSecretKey' => '', 'testPublishableKey' => '', 'testSecretKey' => '', 'description' => [ 'enabled' => false, 'appointment' => '', 'package' => '', 'event' => '' ], 'metaData' => [ 'enabled' => false, 'appointment' => null, 'package' => null, 'event' => null ], 'manualCapture' => false, ], 'wc' => [ 'enabled' => false, 'productId' => '', 'onSiteIfFree' => false, 'page' => 'cart', 'dashboard' => true, 'checkoutData' => [ 'appointment' => '', 'package' => '', 'event' => '', 'translations' => [ 'appointment' => null, 'event' => null, 'package' => null, ], ], 'skipCheckoutGetValueProcessing' => isset($savedSettings['wc']['skipCheckoutGetValueProcessing']) ? $savedSettings['wc']['skipCheckoutGetValueProcessing'] : true, 'skipGetItemDataProcessing' => !isset($savedSettings['wc']), 'redirectPage' => 1, 'rules' => [ 'appointment' => [ [ 'order' => 'on-hold', 'booking' => 'default', 'payment' => 'paid', 'update' => false, ], [ 'order' => 'processing', 'booking' => 'default', 'payment' => 'paid', 'update' => false, ], [ 'order' => 'completed', 'booking' => 'default', 'payment' => 'paid', 'update' => false, ], ], 'package' => [ [ 'order' => 'on-hold', 'booking' => 'approved', 'payment' => 'paid', 'update' => false, ], [ 'order' => 'processing', 'booking' => 'approved', 'payment' => 'paid', 'update' => false, ], [ 'order' => 'completed', 'booking' => 'approved', 'payment' => 'paid', 'update' => false, ], ], 'event' => [ [ 'order' => 'on-hold', 'booking' => 'approved', 'payment' => 'paid', 'update' => false, ], [ 'order' => 'processing', 'booking' => 'approved', 'payment' => 'paid', 'update' => false, ], [ 'order' => 'completed', 'booking' => 'approved', 'payment' => 'paid', 'update' => false, ], ], ], ], 'mollie' => [ 'enabled' => false, 'testMode' => false, 'liveApiKey' => '', 'testApiKey' => '', 'description' => [ 'enabled' => false, 'appointment' => '', 'package' => '', 'event' => '' ], 'metaData' => [ 'enabled' => false, 'appointment' => null, 'package' => null, 'event' => null ], 'method' => [], ], 'razorpay' => [ 'enabled' => false, 'testMode' => false, 'liveKeyId' => '', 'liveKeySecret' => '', 'testKeyId' => '', 'testKeySecret' => '', 'description' => [ 'enabled' => false, 'appointment' => '', 'package' => '', 'event' => '' ], 'name' => [ 'enabled' => false, 'appointment' => '', 'package' => '', 'event' => '' ], 'metaData' => [ 'enabled' => false, 'appointment' => null, 'package' => null, 'event' => null ], ] ]; self::initSettings('payments', $settings); self::setNewSettingsToExistingSettings( 'payments', [ ['stripe', 'description'], ['stripe', 'description', 'package'], ['stripe', 'metaData'], ['stripe', 'metaData', 'package'], ['stripe', 'manualCapture'], ['payPal', 'description'], ['payPal', 'description', 'package'], ['wc', 'onSiteIfFree'], ['wc', 'page'], ['wc', 'dashboard'], ['wc', 'skipCheckoutGetValueProcessing'], ['wc', 'skipGetItemDataProcessing'], ['wc', 'rules'], ['wc', 'redirectPage'], ['wc', 'checkoutData'], ['wc', 'checkoutData', 'package'], ['wc', 'checkoutData', 'translations'], ['wc', 'checkoutData', 'translations', 'appointment'], ['wc', 'checkoutData', 'translations', 'event'], ['wc', 'checkoutData', 'translations', 'package'], ['razorpay', 'name'] ], $settings ); } /** * Init Purchase Code Settings */ private static function initActivationSettings() { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings('activation'); $settings = $savedSettings ? array_merge( $savedSettings, [ 'stash' => !empty($savedSettings['stash']) ? $savedSettings['stash'] : false, 'enableAmeliaPromoBanner' => true, 'enableAmeliaQAPromoBanner' => true, ] ) : [ 'showActivationSettings' => true, 'active' => false, 'purchaseCodeStore' => '', 'envatoTokenEmail' => '', 'version' => '', 'deleteTables' => false, 'showAmeliaPromoCustomizePopup' => true, 'showAmeliaSurvey' => true, 'stash' => false, 'responseErrorAsConflict' => $savedSettings ? false : true, 'enablePolyfill' => $savedSettings ? true : false, 'disableUrlParams' => $savedSettings ? false : true, 'enableThriveItems' => false, 'customUrl' => [ 'enabled' => false, 'pluginPath' => '/wp-content/plugins/ameliabooking/', 'ajaxPath' => '/wp-admin/admin-ajax.php', ], 'v3RelativePath' => false, 'v3AsyncLoading' => false, ]; self::initSettings('activation', $settings); $savedSettings['showAmeliaPromoCustomizePopup'] = true; self::initSettings('activation', $savedSettings, true); } /** * Init Customization Settings * * @throws Exception */ private static function initCustomizationSettings() { $settingsService = new SettingsService(new SettingsStorage()); $settings = $settingsService->getCategorySettings('customization'); unset($settings['hash']); $lessParserService = new LessParserService( AMELIA_PATH . '/assets/less/frontend/amelia-booking.less', AMELIA_UPLOADS_PATH . '/amelia/css', $settingsService ); if (!$settings) { $settings = [ 'primaryColor' => '#1A84EE', 'primaryGradient1' => '#1A84EE', 'primaryGradient2' => '#0454A2', 'textColor' => '#354052', 'textColorOnBackground' => '#FFFFFF', 'font' => 'Amelia Roboto', 'fontUrl' => '', 'customFontFamily' => '', 'customFontSelected' => 'unselected', 'useGenerated' => false, ]; } if (!isset($settings['fontUrl'])) { $settings = array_merge( $settings, [ 'fontUrl' => '' ] ); } if (!isset($settings['customFontFamily'])) { $settings = array_merge( $settings, [ 'customFontFamily' => '' ] ); } if (!isset($settings['customFontSelected'])) { $settings = array_merge( $settings, [ 'customFontSelected' => 'unselected' ] ); } if (!isset($settings['useGlobalColors'])) { $settings = array_merge( $settings, [ 'useGlobalColors' => [ 'stepByStepForm' => false, 'catalogForm' => false, 'eventListForm' => false, 'eventCalendarForm' => false, ] ] ); } if (!isset($settings['globalColors'])) { $settings = array_merge( $settings, [ 'globalColors' => [ 'primaryColor' => $settings['primaryColor'], 'formBackgroundColor' => '#FFFFFF', 'formTextColor' => $settings['textColor'], 'formInputColor' => '#FFFFFF', 'formInputTextColor' => $settings['textColor'], 'formDropdownColor' => '#FFFFFF', 'formDropdownTextColor' => $settings['textColor'], 'formGradientColor1' => $settings['primaryGradient1'], 'formGradientColor2' => $settings['primaryGradient2'], 'formGradientAngle' => 135, 'formImageColor' => $settings['primaryColor'], 'textColorOnBackground' => $settings['textColorOnBackground'], ] ] ); } if (empty($settings['primaryColor'])) { $settings['primaryColor']= 'rgba(255,255,255,0)'; $settings['globalColors']['primaryColor'] = 'rgba(255,255,255,0)'; $settings['globalColors']['formImageColor'] = 'rgba(255,255,255,0)'; } if (empty($settings['primaryGradient1'])) { $settings['primaryGradient1']= 'rgba(255,255,255,0)'; $settings['globalColors']['formGradientColor1'] = 'rgba(255,255,255,0)'; } if (empty($settings['primaryGradient2'])) { $settings['primaryGradient2']= 'rgba(255,255,255,0)'; $settings['globalColors']['formGradientColor2'] = 'rgba(255,255,255,0)'; } if (empty($settings['textColor'])) { $settings['textColor']= 'rgba(255,255,255,0)'; $settings['globalColors']['formTextColor'] = 'rgba(255,255,255,0)'; $settings['globalColors']['formInputTextColor'] = 'rgba(255,255,255,0)'; $settings['globalColors']['formDropdownTextColor'] = 'rgba(255,255,255,0)'; } if (empty($settings['textColorOnBackground'])) { $settings['textColorOnBackground']= 'rgba(255,255,255,0)'; $settings['globalColors']['textColorOnBackground'] = 'rgba(255,255,255,0)'; } $globalColors = $settings['globalColors']; $settingsForm = []; if (isset($settings['forms']['stepByStepForm'])) { $useGlobalSbs = $settings['useGlobalColors']['stepByStepForm']; $colorSbsSsf = $settings['forms']['stepByStepForm']['selectServiceForm']['globalSettings']; $colorSbsCf = $settings['forms']['stepByStepForm']['calendarDateTimeForm']['globalSettings']; $colorSbsRsf = $settings['forms']['stepByStepForm']['recurringSetupForm']['globalSettings']; $colorSbsRdf = $settings['forms']['stepByStepForm']['recurringDatesForm']['globalSettings']; $colorSbsCaf = $settings['forms']['stepByStepForm']['confirmBookingForm']['appointment']['globalSettings']; $colorSbsSpf = $settings['forms']['stepByStepForm']['selectPackageForm']['globalSettings']; $colorSbsPif = $settings['forms']['stepByStepForm']['packageInfoForm']['globalSettings']; $colorSbsPsf = $settings['forms']['stepByStepForm']['packageSetupForm']['globalSettings']; $colorSbsPlf = $settings['forms']['stepByStepForm']['packageListForm']['globalSettings']; $colorSbsCpf = $settings['forms']['stepByStepForm']['confirmBookingForm']['package']['globalSettings']; $colorSbsCoa = $settings['forms']['stepByStepForm']['congratulationsForm']['appointment']['globalSettings']; $colorSbsCop = $settings['forms']['stepByStepForm']['congratulationsForm']['package']['globalSettings']; $settingsForm = array_merge( $settingsForm, [ 'sbs-ssf-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] :$colorSbsSsf['formBackgroundColor'], 'sbs-ssf-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsSsf['formTextColor'], 'sbs-ssf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsSsf['formInputColor'], 'sbs-ssf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsSsf['formInputTextColor'], 'sbs-ssf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsSsf['formDropdownColor'], 'sbs-ssf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsSsf['formDropdownTextColor'], 'sbs-cf-gradient1' => $useGlobalSbs ? $globalColors['formGradientColor1'] : $colorSbsCf['formGradientColor1'], 'sbs-cf-gradient2' => $useGlobalSbs ? $globalColors['formGradientColor2'] : $colorSbsCf['formGradientColor2'], 'sbs-cf-gradient-angle' => $useGlobalSbs ? $globalColors['formGradientAngle'].'deg' : $colorSbsCf['formGradientAngle'].'deg', 'sbs-cf-text-color' => $useGlobalSbs ? $globalColors['textColorOnBackground'] : $colorSbsCf['formTextColor'], 'sbs-rsf-gradient1' => $useGlobalSbs ? $globalColors['formGradientColor1'] : $colorSbsRsf['formGradientColor1'], 'sbs-rsf-gradient2' => $useGlobalSbs ? $globalColors['formGradientColor2'] : $colorSbsRsf['formGradientColor2'], 'sbs-rsf-gradient-angle' => $useGlobalSbs ? $globalColors['formGradientAngle'].'deg' : $colorSbsRsf['formGradientAngle'].'deg', 'sbs-rsf-text-color' => $useGlobalSbs ? $globalColors['textColorOnBackground'] : $colorSbsRsf['formTextColor'], 'sbs-rsf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsRsf['formInputColor'], 'sbs-rsf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsRsf['formInputTextColor'], 'sbs-rsf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsRsf['formDropdownColor'], 'sbs-rsf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsRsf['formDropdownTextColor'], 'sbs-rdf-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsRdf['formBackgroundColor'], 'sbs-rdf-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsRdf['formTextColor'], 'sbs-rdf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsRdf['formInputColor'], 'sbs-rdf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsRdf['formInputTextColor'], 'sbs-rdf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsRdf['formDropdownColor'], 'sbs-rdf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsRdf['formDropdownTextColor'], 'sbs-caf-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsCaf['formBackgroundColor'], 'sbs-caf-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsCaf['formTextColor'], 'sbs-caf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsCaf['formInputColor'], 'sbs-caf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsCaf['formInputTextColor'], 'sbs-caf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsCaf['formDropdownColor'], 'sbs-caf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsCaf['formDropdownTextColor'], 'sbs-spf-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsSpf['formBackgroundColor'], 'sbs-spf-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsSpf['formTextColor'], 'sbs-spf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsSpf['formInputColor'], 'sbs-spf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsSpf['formInputTextColor'], 'sbs-spf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsSpf['formDropdownColor'], 'sbs-spf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsSpf['formDropdownTextColor'], 'sbs-pif-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsPif['formBackgroundColor'], 'sbs-pif-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsPif['formTextColor'], 'sbs-psf-gradient1' => $useGlobalSbs ? $globalColors['formGradientColor1'] : $colorSbsPsf['formGradientColor1'], 'sbs-psf-gradient2' => $useGlobalSbs ? $globalColors['formGradientColor2'] : $colorSbsPsf['formGradientColor2'], 'sbs-psf-gradient-angle' => $useGlobalSbs ? $globalColors['formGradientAngle'].'deg' : $colorSbsPsf['formGradientAngle'].'deg', 'sbs-psf-text-color' => $useGlobalSbs ? $globalColors['textColorOnBackground'] : $colorSbsPsf['formTextColor'], 'sbs-psf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsPsf['formInputColor'], 'sbs-psf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsPsf['formInputTextColor'], 'sbs-psf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsPsf['formDropdownColor'], 'sbs-psf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsPsf['formDropdownTextColor'], 'sbs-plf-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsPlf['formBackgroundColor'], 'sbs-plf-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsPlf['formTextColor'], 'sbs-cpf-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsCpf['formBackgroundColor'], 'sbs-cpf-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsCpf['formTextColor'], 'sbs-cpf-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsCpf['formInputColor'], 'sbs-cpf-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsCpf['formInputTextColor'], 'sbs-cpf-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsCpf['formDropdownColor'], 'sbs-cpf-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsCpf['formDropdownTextColor'], 'sbs-coa-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsCoa['formBackgroundColor'], 'sbs-coa-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsCoa['formTextColor'], 'sbs-coa-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsCoa['formInputColor'], 'sbs-coa-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsCoa['formInputTextColor'], 'sbs-coa-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsCoa['formDropdownColor'], 'sbs-coa-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsCoa['formDropdownTextColor'], 'sbs-cop-bgr-color' => $useGlobalSbs ? $globalColors['formBackgroundColor'] : $colorSbsCop['formBackgroundColor'], 'sbs-cop-text-color' => $useGlobalSbs ? $globalColors['formTextColor'] : $colorSbsCop['formTextColor'], 'sbs-cop-input-color' => $useGlobalSbs ? $globalColors['formInputColor'] : $colorSbsCop['formInputColor'], 'sbs-cop-input-text-color' => $useGlobalSbs ? $globalColors['formInputTextColor'] : $colorSbsCop['formInputTextColor'], 'sbs-cop-dropdown-color' => $useGlobalSbs ? $globalColors['formDropdownColor'] : $colorSbsCop['formDropdownColor'], 'sbs-cop-dropdown-text-color' => $useGlobalSbs ? $globalColors['formDropdownTextColor'] : $colorSbsCop['formDropdownTextColor'], ] ); } else { $settingsForm = array_merge( $settingsForm, [ 'sbs-ssf-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-ssf-text-color' => $globalColors['formTextColor'], 'sbs-ssf-input-color' => $globalColors['formInputColor'], 'sbs-ssf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-ssf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-ssf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-cf-gradient1' => $globalColors['formGradientColor1'], 'sbs-cf-gradient2' => $globalColors['formGradientColor2'], 'sbs-cf-gradient-angle' => $globalColors['formGradientAngle'].'deg', 'sbs-cf-text-color' => $globalColors['textColorOnBackground'], 'sbs-rsf-gradient1' => $globalColors['formGradientColor1'], 'sbs-rsf-gradient2' => $globalColors['formGradientColor2'], 'sbs-rsf-gradient-angle' => $globalColors['formGradientAngle'].'deg', 'sbs-rsf-text-color' => $globalColors['textColorOnBackground'], 'sbs-rsf-input-color' => $globalColors['formInputColor'], 'sbs-rsf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-rsf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-rsf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-rdf-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-rdf-text-color' => $globalColors['formTextColor'], 'sbs-rdf-input-color' => $globalColors['formInputColor'], 'sbs-rdf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-rdf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-rdf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-caf-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-caf-text-color' => $globalColors['formTextColor'], 'sbs-caf-input-color' => $globalColors['formInputColor'], 'sbs-caf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-caf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-caf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-spf-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-spf-text-color' => $globalColors['formTextColor'], 'sbs-spf-input-color' => $globalColors['formInputColor'], 'sbs-spf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-spf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-spf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-pif-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-pif-text-color' => $globalColors['formTextColor'], 'sbs-psf-gradient1' => $globalColors['formGradientColor1'], 'sbs-psf-gradient2' => $globalColors['formGradientColor2'], 'sbs-psf-gradient-angle' => $globalColors['formGradientAngle'].'deg', 'sbs-psf-text-color' => $globalColors['textColorOnBackground'], 'sbs-psf-input-color' => $globalColors['formInputColor'], 'sbs-psf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-psf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-psf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-plf-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-plf-text-color' => $globalColors['formTextColor'], 'sbs-cpf-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-cpf-text-color' => $globalColors['formTextColor'], 'sbs-cpf-input-color' => $globalColors['formInputColor'], 'sbs-cpf-input-text-color' => $globalColors['formInputTextColor'], 'sbs-cpf-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-cpf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-coa-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-coa-text-color' => $globalColors['formTextColor'], 'sbs-coa-input-color' => $globalColors['formInputColor'], 'sbs-coa-input-text-color' => $globalColors['formInputTextColor'], 'sbs-coa-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-coa-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'sbs-cop-bgr-color' => $globalColors['formBackgroundColor'], 'sbs-cop-text-color' => $globalColors['formTextColor'], 'sbs-cop-input-color' => $globalColors['formInputColor'], 'sbs-cop-input-text-color' => $globalColors['formInputTextColor'], 'sbs-cop-dropdown-color' => $globalColors['formDropdownColor'], 'sbs-cop-dropdown-text-color' => $globalColors['formDropdownTextColor'], ] ); } if (isset($settings['forms']['catalogForm'])) { $useGlobalCf = $settings['useGlobalColors']['catalogForm']; $colorCfSsf = $settings['forms']['catalogForm']['selectServiceForm']['globalSettings']; $colorCfCf = $settings['forms']['catalogForm']['calendarDateTimeForm']['globalSettings']; $colorCfRsf = $settings['forms']['catalogForm']['recurringSetupForm']['globalSettings']; $colorCfRdf = $settings['forms']['catalogForm']['recurringDatesForm']['globalSettings']; $colorCfCaf = $settings['forms']['catalogForm']['confirmBookingForm']['appointment']['globalSettings']; $colorCfPsf = $settings['forms']['catalogForm']['packageSetupForm']['globalSettings']; $colorCfPlf = $settings['forms']['catalogForm']['packageListForm']['globalSettings']; $colorCfCpf = $settings['forms']['catalogForm']['confirmBookingForm']['package']['globalSettings']; $colorCfCoa = $settings['forms']['catalogForm']['congratulationsForm']['appointment']['globalSettings']; $colorCfCop = $settings['forms']['catalogForm']['congratulationsForm']['package']['globalSettings']; $settingsForm = array_merge( $settingsForm, [ 'cf-ssf-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfSsf['formBackgroundColor'], 'cf-ssf-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfSsf['formTextColor'], 'cf-ssf-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfSsf['formInputColor'], 'cf-ssf-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfSsf['formInputTextColor'], 'cf-ssf-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfSsf['formDropdownColor'], 'cf-ssf-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfSsf['formDropdownTextColor'], 'cf-cf-gradient1' => $useGlobalCf ? $globalColors['formGradientColor1'] : $colorCfCf['formGradientColor1'], 'cf-cf-gradient2' => $useGlobalCf ? $globalColors['formGradientColor2'] : $colorCfCf['formGradientColor2'], 'cf-cf-gradient-angle' => $useGlobalCf ? $globalColors['formGradientAngle'].'deg' : $colorCfCf['formGradientAngle'].'deg', 'cf-cf-text-color' => $useGlobalCf ? $globalColors['textColorOnBackground'] : $colorCfCf['formTextColor'], 'cf-rsf-gradient1' => $useGlobalCf ? $globalColors['formGradientColor1'] : $colorCfRsf['formGradientColor1'], 'cf-rsf-gradient2' => $useGlobalCf ? $globalColors['formGradientColor2'] : $colorCfRsf['formGradientColor2'], 'cf-rsf-gradient-angle' => $useGlobalCf ? $globalColors['formGradientAngle'].'deg' : $colorCfRsf['formGradientAngle'].'deg', 'cf-rsf-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfRsf['formTextColor'], 'cf-rsf-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfRsf['formInputColor'], 'cf-rsf-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfRsf['formInputTextColor'], 'cf-rsf-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfRsf['formDropdownColor'], 'cf-rsf-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfRsf['formDropdownTextColor'], 'cf-rdf-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfRdf['formBackgroundColor'], 'cf-rdf-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfRdf['formTextColor'], 'cf-rdf-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfRdf['formInputColor'], 'cf-rdf-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfRdf['formInputTextColor'], 'cf-rdf-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfRdf['formDropdownColor'], 'cf-rdf-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfRdf['formDropdownTextColor'], 'cf-caf-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfCaf['formBackgroundColor'], 'cf-caf-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfCaf['formTextColor'], 'cf-caf-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfCaf['formInputColor'], 'cf-caf-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfCaf['formInputTextColor'], 'cf-caf-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfCaf['formDropdownColor'], 'cf-caf-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfCaf['formDropdownTextColor'], 'cf-psf-gradient1' => $useGlobalCf ? $globalColors['formGradientColor1'] : $colorCfPsf['formGradientColor1'], 'cf-psf-gradient2' => $useGlobalCf ? $globalColors['formGradientColor2'] : $colorCfPsf['formGradientColor2'], 'cf-psf-gradient-angle' => $useGlobalCf ? $globalColors['formGradientAngle'].'deg' : $colorCfPsf['formGradientAngle'].'deg', 'cf-psf-text-color' => $useGlobalCf ? $globalColors['textColorOnBackground'] : $colorCfPsf['formTextColor'], 'cf-psf-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfPsf['formInputColor'], 'cf-psf-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfPsf['formInputTextColor'], 'cf-psf-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfPsf['formDropdownColor'], 'cf-psf-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfPsf['formDropdownTextColor'], 'cf-plf-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfPlf['formBackgroundColor'], 'cf-plf-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfPlf['formTextColor'], 'cf-cpf-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfCpf['formBackgroundColor'], 'cf-cpf-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfCpf['formTextColor'], 'cf-cpf-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfCpf['formInputColor'], 'cf-cpf-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfCpf['formInputTextColor'], 'cf-cpf-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfCpf['formDropdownColor'], 'cf-cpf-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfCpf['formDropdownTextColor'], 'cf-coa-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfCoa['formBackgroundColor'], 'cf-coa-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfCoa['formTextColor'], 'cf-coa-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfCoa['formInputColor'], 'cf-coa-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfCoa['formInputTextColor'], 'cf-coa-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfCoa['formDropdownColor'], 'cf-coa-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfCoa['formDropdownTextColor'], 'cf-cop-bgr-color' => $useGlobalCf ? $globalColors['formBackgroundColor'] : $colorCfCop['formBackgroundColor'], 'cf-cop-text-color' => $useGlobalCf ? $globalColors['formTextColor'] : $colorCfCop['formTextColor'], 'cf-cop-input-color' => $useGlobalCf ? $globalColors['formInputColor'] : $colorCfCop['formInputColor'], 'cf-cop-input-text-color' => $useGlobalCf ? $globalColors['formInputTextColor'] : $colorCfCop['formInputTextColor'], 'cf-cop-dropdown-color' => $useGlobalCf ? $globalColors['formDropdownColor'] : $colorCfCop['formDropdownColor'], 'cf-cop-dropdown-text-color' => $useGlobalCf ? $globalColors['formDropdownTextColor'] : $colorCfCop['formDropdownTextColor'], ] ); } else { $settingsForm = array_merge( $settingsForm, [ 'cf-ssf-bgr-color' => $globalColors['formBackgroundColor'], 'cf-ssf-text-color' => $globalColors['formTextColor'], 'cf-ssf-input-color' => $globalColors['formInputColor'], 'cf-ssf-input-text-color' => $globalColors['formInputTextColor'], 'cf-ssf-dropdown-color' => $globalColors['formDropdownColor'], 'cf-ssf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-cf-gradient1' => $globalColors['formGradientColor1'], 'cf-cf-gradient2' => $globalColors['formGradientColor2'], 'cf-cf-gradient-angle' => $globalColors['formGradientAngle'].'deg', 'cf-cf-text-color' => $globalColors['textColorOnBackground'], 'cf-rsf-gradient1' => $globalColors['formGradientColor1'], 'cf-rsf-gradient2' => $globalColors['formGradientColor2'], 'cf-rsf-gradient-angle' => $globalColors['formGradientAngle'].'deg', 'cf-rsf-text-color' => $globalColors['textColorOnBackground'], 'cf-rsf-input-color' => $globalColors['formInputColor'], 'cf-rsf-input-text-color' => $globalColors['formInputTextColor'], 'cf-rsf-dropdown-color' => $globalColors['formDropdownColor'], 'cf-rsf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-rdf-bgr-color' => $globalColors['formBackgroundColor'], 'cf-rdf-text-color' => $globalColors['formTextColor'], 'cf-rdf-input-color' => $globalColors['formInputColor'], 'cf-rdf-input-text-color' => $globalColors['formInputTextColor'], 'cf-rdf-dropdown-color' => $globalColors['formDropdownColor'], 'cf-rdf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-caf-bgr-color' => $globalColors['formBackgroundColor'], 'cf-caf-text-color' => $globalColors['formTextColor'], 'cf-caf-input-color' => $globalColors['formInputColor'], 'cf-caf-input-text-color' => $globalColors['formInputTextColor'], 'cf-caf-dropdown-color' => $globalColors['formDropdownColor'], 'cf-caf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-psf-gradient1' => $globalColors['formGradientColor1'], 'cf-psf-gradient2' => $globalColors['formGradientColor2'], 'cf-psf-gradient-angle' => $globalColors['formGradientAngle'].'deg', 'cf-psf-text-color' => $globalColors['textColorOnBackground'], 'cf-psf-input-color' => $globalColors['formInputColor'], 'cf-psf-input-text-color' => $globalColors['formInputTextColor'], 'cf-psf-dropdown-color' => $globalColors['formDropdownColor'], 'cf-psf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-plf-bgr-color' => $globalColors['formBackgroundColor'], 'cf-plf-text-color' => $globalColors['formTextColor'], 'cf-cpf-bgr-color' => $globalColors['formBackgroundColor'], 'cf-cpf-text-color' => $globalColors['formTextColor'], 'cf-cpf-input-color' => $globalColors['formInputColor'], 'cf-cpf-input-text-color' => $globalColors['formInputTextColor'], 'cf-cpf-dropdown-color' => $globalColors['formDropdownColor'], 'cf-cpf-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-coa-bgr-color' => $globalColors['formBackgroundColor'], 'cf-coa-text-color' => $globalColors['formTextColor'], 'cf-coa-input-color' => $globalColors['formInputColor'], 'cf-coa-input-text-color' => $globalColors['formInputTextColor'], 'cf-coa-dropdown-color' => $globalColors['formDropdownColor'], 'cf-coa-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'cf-cop-bgr-color' => $globalColors['formBackgroundColor'], 'cf-cop-text-color' => $globalColors['formTextColor'], 'cf-cop-input-color' => $globalColors['formInputColor'], 'cf-cop-input-text-color' => $globalColors['formInputTextColor'], 'cf-cop-dropdown-color' => $globalColors['formDropdownColor'], 'cf-cop-dropdown-text-color' => $globalColors['formDropdownTextColor'], ] ); } if (isset($settings['forms']['eventListForm'])) { $useGlobaElf = $settings['useGlobalColors']['eventListForm']; $colorElf = $settings['forms']['eventListForm']['globalSettings']; $settingsForm = array_merge( $settingsForm, [ 'elf-bgr-color' => $useGlobaElf ? $globalColors['formBackgroundColor'] : $colorElf['formBackgroundColor'], 'elf-text-color' => $useGlobaElf ? $globalColors['formTextColor'] : $colorElf['formTextColor'], 'elf-input-color' => $useGlobaElf ? $globalColors['formInputColor'] : $colorElf['formInputColor'], 'elf-input-text-color' => $useGlobaElf ? $globalColors['formInputTextColor'] : $colorElf['formInputTextColor'], 'elf-dropdown-color' => $useGlobaElf ? $globalColors['formDropdownColor'] : $colorElf['formDropdownColor'], 'elf-dropdown-text-color' => $useGlobaElf ? $globalColors['formDropdownTextColor'] : $colorElf['formDropdownTextColor'], ] ); } else { $settingsForm = array_merge( $settingsForm, [ 'elf-bgr-color' => $globalColors['formBackgroundColor'], 'elf-text-color' => $globalColors['formTextColor'], 'elf-input-color' => $globalColors['formInputColor'], 'elf-input-text-color' => $globalColors['formInputTextColor'], 'elf-dropdown-color' => $globalColors['formDropdownColor'], 'elf-dropdown-text-color' => $globalColors['formDropdownTextColor'], ] ); } if (isset($settings['forms']['eventCalendarForm'])) { $useGlobalEcf = $settings['useGlobalColors']['eventCalendarForm']; $colorEcfCef = $settings['forms']['eventCalendarForm']['confirmBookingForm']['event']['globalSettings']; $colorEcfCoe = $settings['forms']['eventCalendarForm']['congratulationsForm']['event']['globalSettings']; $settingsForm = array_merge( $settingsForm, [ 'ecf-cef-bgr-color' => $useGlobalEcf ? $globalColors['formBackgroundColor'] : $colorEcfCef['formBackgroundColor'], 'ecf-cef-text-color' => $useGlobalEcf ? $globalColors['formTextColor'] : $colorEcfCef['formTextColor'], 'ecf-cef-input-color' => $useGlobalEcf ? $globalColors['formInputColor'] : $colorEcfCef['formInputColor'], 'ecf-cef-input-text-color' => $useGlobalEcf ? $globalColors['formInputTextColor'] : $colorEcfCef['formInputTextColor'], 'ecf-cef-dropdown-color' => $useGlobalEcf ? $globalColors['formDropdownColor'] : $colorEcfCef['formDropdownColor'], 'ecf-cef-dropdown-text-color' => $useGlobalEcf ? $globalColors['formDropdownTextColor'] : $colorEcfCef['formDropdownTextColor'], 'ecf-coe-bgr-color' => $useGlobalEcf ? $globalColors['formBackgroundColor'] : $colorEcfCoe['formBackgroundColor'], 'ecf-coe-text-color' => $useGlobalEcf ? $globalColors['formTextColor'] : $colorEcfCoe['formTextColor'], 'ecf-coe-input-color' => $useGlobalEcf ? $globalColors['formInputColor'] : $colorEcfCoe['formInputColor'], 'ecf-coe-input-text-color' => $useGlobalEcf ? $globalColors['formInputTextColor'] : $colorEcfCoe['formInputTextColor'], 'ecf-coe-dropdown-color' => $useGlobalEcf ? $globalColors['formDropdownColor'] : $colorEcfCoe['formDropdownColor'], 'ecf-coe-dropdown-text-color' => $useGlobalEcf ? $globalColors['formDropdownTextColor'] : $colorEcfCoe['formDropdownTextColor'], ] ); } else { $settingsForm = array_merge( $settingsForm, [ 'ecf-cef-bgr-color' => $globalColors['formBackgroundColor'], 'ecf-cef-text-color' => $globalColors['formTextColor'], 'ecf-cef-input-color' => $globalColors['formInputColor'], 'ecf-cef-input-text-color' => $globalColors['formInputTextColor'], 'ecf-cef-dropdown-color' => $globalColors['formDropdownColor'], 'ecf-cef-dropdown-text-color' => $globalColors['formDropdownTextColor'], 'ecf-coe-bgr-color' => $globalColors['formBackgroundColor'], 'ecf-coe-text-color' => $globalColors['formTextColor'], 'ecf-coe-input-color' => $globalColors['formInputColor'], 'ecf-coe-input-text-color' => $globalColors['formInputTextColor'], 'ecf-coe-dropdown-color' => $globalColors['formDropdownColor'], 'ecf-coe-dropdown-text-color' => $globalColors['formDropdownTextColor'], ] ); } $hash = $lessParserService->compileAndSave( array_merge( [ 'color-accent' => $globalColors['primaryColor'], 'color-white' => $globalColors['textColorOnBackground'], 'color-text-prime' => $globalColors['formTextColor'], 'color-text-second' => $globalColors['formTextColor'], 'color-bgr' => $globalColors['formBackgroundColor'], 'color-gradient1' => $globalColors['formGradientColor1'], 'color-gradient2' => $globalColors['formGradientColor2'], 'color-dropdown' => $globalColors['formDropdownColor'], 'color-dropdown-text' => $globalColors['formDropdownTextColor'], 'color-input' => $globalColors['formInputColor'], 'color-input-text' => $globalColors['formInputTextColor'], 'font' => !empty($settings['font']) ? $settings['font'] : '', 'custom-font-selected' => $settings['customFontSelected'], 'font-url' => !empty($settings['fontUrl']) ? $settings['fontUrl'] : '', ], $settingsForm ) ); $settings['hash'] = $hash; $settingsService->fixCustomization($settings); self::initSettings('customization', $settings, true); } /** * Init Labels Settings */ private static function initLabelsSettings() { $settings = [ 'enabled' => true, 'employee' => 'employee', 'employees' => 'employees', 'service' => 'service', 'services' => 'services' ]; self::initSettings('labels', $settings); } /** * Init Roles Settings */ private static function initRolesSettings() { $settings = [ 'allowConfigureSchedule' => false, 'allowConfigureDaysOff' => false, 'allowConfigureSpecialDays' => false, 'allowConfigureServices' => false, 'allowWriteAppointments' => false, 'automaticallyCreateCustomer' => true, 'inspectCustomerInfo' => false, 'allowCustomerReschedule' => false, 'allowCustomerCancelPackages' => true, 'allowCustomerDeleteProfile' => false, 'allowWriteEvents' => false, 'allowAdminBookAtAnyTime' => false, 'enabledHttpAuthorization' => true, 'customerCabinet' => [ 'enabled' => false, 'headerJwtSecret' => (new Token(null, 20))->getValue(), 'urlJwtSecret' => (new Token(null, 20))->getValue(), 'tokenValidTime' => 2592000, 'pageUrl' => '', 'loginEnabled' => true, 'filterDate' => false, 'translations' => [], ], 'providerCabinet' => [ 'enabled' => false, 'headerJwtSecret' => (new Token(null, 20))->getValue(), 'urlJwtSecret' => (new Token(null, 20))->getValue(), 'tokenValidTime' => 2592000, 'pageUrl' => '', 'loginEnabled' => true, 'filterDate' => false, ], 'urlAttachment' => [ 'enabled' => true, 'headerJwtSecret' => (new Token(null, 20))->getValue(), 'urlJwtSecret' => (new Token(null, 20))->getValue(), 'tokenValidTime' => 2592000, 'pageUrl' => '', 'loginEnabled' => true, 'filterDate' => false, ], 'limitPerCustomerService' => [ 'enabled' => false, 'numberOfApp' => 1, 'timeFrame' => 'day', 'period' => 1, 'from' => 'bookingDate' ], 'limitPerCustomerPackage' => [ 'enabled' => false, 'numberOfApp' => 1, 'timeFrame' => 'day', 'period' => 1, ], 'limitPerCustomerEvent' => [ 'enabled' => false, 'numberOfApp' => 1, 'timeFrame' => 'day', 'period' => 1, 'from' => 'bookingDate' ], ]; self::initSettings('roles', $settings); self::setNewSettingsToExistingSettings( 'roles', [ ['customerCabinet', 'filterDate'], ['customerCabinet', 'translations'], ], $settings ); } /** * Init Appointments Settings */ private static function initAppointmentsSettings() { $settings = [ 'isGloballyBusySlot' => false, 'bookMultipleTimes' => false, 'allowBookingIfPending' => true, 'allowBookingIfNotMin' => true, 'openedBookingAfterMin' => false, 'recurringPlaceholders' => 'DateTime: %appointment_date_time%', 'recurringPlaceholdersSms' => 'DateTime: %appointment_date_time%', 'recurringPlaceholdersCustomer' => 'DateTime: %appointment_date_time%', 'recurringPlaceholdersCustomerSms' => 'DateTime: %appointment_date_time%', 'packagePlaceholders' => 'DateTime: %appointment_date_time%', 'packagePlaceholdersSms' => 'DateTime: %appointment_date_time%', 'packagePlaceholdersCustomer' => 'DateTime: %appointment_date_time%', 'packagePlaceholdersCustomerSms' => 'DateTime: %appointment_date_time%', 'groupAppointmentPlaceholder' => 'Name: %customer_full_name%', 'groupEventPlaceholder' => 'Name: %customer_full_name%', 'groupAppointmentPlaceholderSms' => 'Name: %customer_full_name%', 'groupEventPlaceholderSms' => 'Name: %customer_full_name%', 'translations' => [ 'recurringPlaceholdersCustomer' => null, 'recurringPlaceholdersCustomerSms' => null, 'packagePlaceholdersCustomer' => null, 'packagePlaceholdersCustomerSms' => null, 'groupAppointmentPlaceholder' => 'Name: %customer_full_name%', 'groupEventPlaceholder' => 'Name: %customer_full_name%', 'groupAppointmentPlaceholderSms' => 'Name: %customer_full_name%', 'groupEventPlaceholderSms' => 'Name: %customer_full_name%', ], ]; self::initSettings('appointments', $settings); } /** * Init Web Hooks Settings */ private static function initWebHooksSettings() { $settings = []; self::initSettings('webHooks', $settings); } /** * get Back Link Setting */ private static function getBackLinkSetting() { $settingsService = new SettingsService(new SettingsStorage()); $backLinksLabels = [ 'Generated with Amelia - WordPress Booking Plugin', 'Powered by Amelia - WordPress Booking Plugin', 'Booking by Amelia - WordPress Booking Plugin', 'Powered by Amelia - Appointment and Events Booking Plugin', 'Powered by Amelia - Appointment and Event Booking Plugin', 'Powered by Amelia - WordPress Booking Plugin', 'Generated with Amelia - Appointment and Event Booking Plugin', 'Booking Enabled by Amelia - Appointment and Event Booking Plugin', ]; $backLinksUrls = [ 'https://wpamelia.com/?utm_source=lite&utm_medium=websites&utm_campaign=powerdby', 'https://wpamelia.com/demos/?utm_source=lite&utm_medium=website&utm_campaign=powerdby#Features-list', 'https://wpamelia.com/pricing/?utm_source=lite&utm_medium=website&utm_campaign=powerdby', 'https://wpamelia.com/documentation/?utm_source=lite&utm_medium=website&utm_campaign=powerdby', ]; return [ 'enabled' => $settingsService->getCategorySettings('general') === null, 'label' => $backLinksLabels[rand(0, 7)], 'url' => $backLinksUrls[rand(0, 3)], ]; } /** * Add new settings ti global parent settings * * @param string $category * @param array $pathsKeys * @param array $initSettings */ private static function setNewSettingsToExistingSettings($category, $pathsKeys, $initSettings) { $settingsService = new SettingsService(new SettingsStorage()); $savedSettings = $settingsService->getCategorySettings($category); $setSettings = false; foreach ($pathsKeys as $keys) { $current = &$savedSettings; $currentInit = &$initSettings; foreach ((array)$keys as $key) { if (!isset($current[$key])) { $current[$key] = !empty($currentInit[$key]) ? $currentInit[$key] : null; $setSettings = true; continue 2; } $current = &$current[$key]; $currentInit = &$initSettings[$key]; } } if ($setSettings) { self::initSettings($category, $savedSettings, true); } } } WP/InstallActions/DeleteDatabaseHook.php 0000666 00000017131 15165376447 0014233 0 ustar 00 <?php /** * Database hook for activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesCustomersServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesCustomersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesLocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ResourcesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ResourcesToEntitiesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\CategoriesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ServicesViewsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToEventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingToEventsTicketsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTagsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTicketsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Cache\CacheTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToEventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToPackagesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsEventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsOptionsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery\GalleriesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsViewsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsLogTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsSMSHistoryTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsTableInsertRows; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsToEntitiesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersGoogleCalendarTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersOutlookCalendarTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersPeriodLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersPeriodServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersPeriodTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayPeriodLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayPeriodServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayPeriodTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersViewsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersWeekDayTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersTimeOutTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersDayOffTable; /** * Class DeleteDatabaseHook * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class DeleteDatabaseHook { /** * Delete the plugin tables * * @throws InvalidArgumentException */ public static function delete() { CustomFieldsEventsTable::delete(); CustomFieldsServicesTable::delete(); CustomFieldsOptionsTable::delete(); CustomFieldsTable::delete(); NotificationsSMSHistoryTable::delete(); NotificationsLogTable::delete(); LocationsViewsTable::delete(); PaymentsTable::delete(); CustomerBookingsToEventsPeriodsTable::delete(); CustomerBookingsToExtrasTable::delete(); CustomerBookingToEventsTicketsTable::delete(); CustomerBookingsTable::delete(); CouponsToEventsTable::delete(); CouponsToPackagesTable::delete(); EventsProvidersTable::delete(); EventsPeriodsTable::delete(); EventsTagsTable::delete(); EventsTicketsTable::delete(); EventsTable::delete(); AppointmentsTable::delete(); ExtrasTable::delete(); PackagesTable::delete(); PackagesServicesTable::delete(); PackagesServicesProvidersTable::delete(); PackagesServicesLocationsTable::delete(); PackagesCustomersTable::delete(); PackagesCustomersServicesTable::delete(); ResourcesToEntitiesTable::delete(); ResourcesTable::delete(); ProvidersServiceTable::delete(); CouponsToServicesTable::delete(); ServicesViewsTable::delete(); ProvidersSpecialDayPeriodServiceTable::delete(); ProvidersSpecialDayPeriodLocationTable::delete(); ProvidersPeriodServiceTable::delete(); ProvidersPeriodLocationTable::delete(); ServicesTable::delete(); CategoriesTable::delete(); ProvidersOutlookCalendarTable::delete(); ProvidersGoogleCalendarTable::delete(); ProvidersViewsTable::delete(); ProvidersSpecialDayPeriodTable::delete(); ProvidersPeriodTable::delete(); ProvidersTimeOutTable::delete(); ProvidersSpecialDayTable::delete(); ProvidersWeekDayTable::delete(); ProvidersLocationTable::delete(); ProvidersDayOffTable::delete(); NotificationsTableInsertRows::delete(); NotificationsTable::delete(); NotificationsToEntitiesTable::delete(); LocationsTable::delete(); CouponsTable::delete(); GalleriesTable::delete(); UsersTable::delete(); CacheTable::delete(); } } WP/InstallActions/ActivationDatabaseHook.php 0000666 00000016561 15165376447 0015140 0 ustar 00 <?php /** * Database hook for activation */ namespace AmeliaBooking\Infrastructure\WP\InstallActions; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesCustomersServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesCustomersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesLocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ResourcesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ResourcesToEntitiesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\CategoriesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ServicesViewsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToEventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingToEventsTicketsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTagsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTicketsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Cache\CacheTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToEventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToPackagesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsEventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsOptionsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField\CustomFieldsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery\GalleriesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsViewsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsLogTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsSMSHistoryTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsTableInsertRows; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsToEntitiesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersGoogleCalendarTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersOutlookCalendarTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersPeriodLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersPeriodServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersPeriodTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayPeriodLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayPeriodServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayPeriodTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersSpecialDayTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersViewsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersWeekDayTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersTimeOutTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersDayOffTable; /** * Class ActivationHook * * @package AmeliaBooking\Infrastructure\WP\InstallActions */ class ActivationDatabaseHook { /** * Initialize the plugin */ public static function init() { UsersTable::init(); GalleriesTable::init(); CouponsTable::init(); LocationsTable::init(); NotificationsTable::init(); NotificationsTableInsertRows::init(); ProvidersDayOffTable::init(); ProvidersLocationTable::init(); ProvidersWeekDayTable::init(); ProvidersSpecialDayTable::init(); ProvidersTimeOutTable::init(); ProvidersPeriodTable::init(); ProvidersSpecialDayPeriodTable::init(); ProvidersViewsTable::init(); ProvidersGoogleCalendarTable::init(); ProvidersOutlookCalendarTable::init(); CategoriesTable::init(); ServicesTable::init(); ProvidersPeriodServiceTable::init(); ProvidersPeriodLocationTable::init(); ProvidersSpecialDayPeriodServiceTable::init(); ProvidersSpecialDayPeriodLocationTable::init(); ServicesViewsTable::init(); CouponsToServicesTable::init(); ProvidersServiceTable::init(); ExtrasTable::init(); PackagesTable::init(); PackagesServicesTable::init(); PackagesServicesProvidersTable::init(); PackagesServicesLocationsTable::init(); PackagesCustomersTable::init(); PackagesCustomersServicesTable::init(); ResourcesTable::init(); ResourcesToEntitiesTable::init(); AppointmentsTable::init(); EventsTable::init(); EventsTagsTable::init(); EventsTicketsTable::init(); EventsPeriodsTable::init(); EventsProvidersTable::init(); CouponsToEventsTable::init(); CouponsToPackagesTable::init(); CustomerBookingsTable::init(); CustomerBookingsToExtrasTable::init(); CustomerBookingsToEventsPeriodsTable::init(); CustomerBookingToEventsTicketsTable::init(); PaymentsTable::init(); LocationsViewsTable::init(); NotificationsToEntitiesTable::init(); NotificationsLogTable::init(); NotificationsSMSHistoryTable::init(); CustomFieldsTable::init(); CustomFieldsOptionsTable::init(); CustomFieldsServicesTable::init(); CustomFieldsEventsTable::init(); CacheTable::init(); } } WP/InstallActions/DB/Cache/CacheTable.php 0000666 00000002011 15165376447 0014015 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Cache; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CacheTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Cache */ class CacheTable extends AbstractDatabaseTable { const TABLE = 'cache'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `paymentId` INT(11) DEFAULT NULL, `data` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Gallery/GalleriesTable.php 0000666 00000002410 15165376447 0015320 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\Picture; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class GalleriesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery */ class GalleriesTable extends AbstractDatabaseTable { const TABLE = 'galleries'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $picture = Picture::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `entityId` int(11) NOT NULL, `entityType` ENUM('service', 'event', 'package') NOT NULL, `pictureFullPath` varchar ({$picture}) NULL, `pictureThumbPath` varchar ({$picture}) NULL, `position` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/CustomField/CustomFieldsServicesTable.php 0000666 00000001640 15165376447 0020341 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomFieldsServicesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField */ class CustomFieldsServicesTable extends AbstractDatabaseTable { const TABLE = 'custom_fields_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `customFieldId` int(11) NOT NULL, `serviceId` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/CustomField/CustomFieldsEventsTable.php 0000666 00000001630 15165376447 0020021 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomFieldsEventsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField */ class CustomFieldsEventsTable extends AbstractDatabaseTable { const TABLE = 'custom_fields_events'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `customFieldId` int(11) NOT NULL, `eventId` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/CustomField/CustomFieldsOptionsTable.php 0000666 00000002030 15165376447 0020203 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomFieldsOptionsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField */ class CustomFieldsOptionsTable extends AbstractDatabaseTable { const TABLE = 'custom_fields_options'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `customFieldId` int(11) NOT NULL, `label` VARCHAR(255) NOT NULL DEFAULT '', `position` int(11) NOT NULL, `translations` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/CustomField/CustomFieldsTable.php 0000666 00000002426 15165376447 0016640 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomFieldsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\CustomField */ class CustomFieldsTable extends AbstractDatabaseTable { const TABLE = 'custom_fields'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `label` TEXT NOT NULL DEFAULT '', `type` ENUM('text', 'text-area', 'select', 'checkbox', 'radio', 'content', 'file', 'datepicker', 'address') NOT NULL DEFAULT 'text', `required` TINYINT(1) NOT NULL DEFAULT 0, `position` int(11) NOT NULL, `translations` TEXT NULL DEFAULT NULL, `allServices` TINYINT(1) NULL DEFAULT NULL, `allEvents` TINYINT(1) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Notification/NotificationsSMSHistoryTable.php 0000666 00000005134 15165376447 0021224 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Phone; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class NotificationsSMSHistoryTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification * * @codingStandardsIgnoreFile */ class NotificationsSMSHistoryTable extends AbstractDatabaseTable { const TABLE = 'notifications_sms_history'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { global $wpdb; $table = self::getTableName(); $phone = Phone::MAX_LENGTH; if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") === $table) { if ($wpdb->query("SHOW KEYS FROM {$table} WHERE Key_name = 'notificationId'")) { $wpdb->query("ALTER TABLE {$table} DROP FOREIGN KEY {$table}_ibfk_1"); $wpdb->query("ALTER TABLE {$table} DROP INDEX notificationId"); } if ($wpdb->query("SHOW KEYS FROM {$table} WHERE Key_name = 'userId'")) { $wpdb->query("ALTER TABLE {$table} DROP FOREIGN KEY {$table}_ibfk_2"); $wpdb->query("ALTER TABLE {$table} DROP INDEX userId"); } if ($wpdb->query("SHOW KEYS FROM {$table} WHERE Key_name = 'appointmentId'")) { $wpdb->query("ALTER TABLE {$table} DROP FOREIGN KEY {$table}_ibfk_3"); $wpdb->query("ALTER TABLE {$table} DROP INDEX appointmentId"); } } return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `notificationId` INT(11) NOT NULL, `userId` INT(11) NULL, `appointmentId` INT(11) NULL, `eventId` INT(11) NULL, `packageCustomerId` INT(11) NULL, `logId` INT(11) NULL, `dateTime` DATETIME NULL, `text` VARCHAR(1600) NOT NULL, `phone` VARCHAR({$phone}) NOT NULL, `alphaSenderId` VARCHAR(11) NOT NULL, `status` ENUM('prepared', 'accepted', 'queued', 'sent', 'failed', 'delivered', 'undelivered') NOT NULL DEFAULT 'prepared', `price` DOUBLE NULL, `segments` TINYINT(2) NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Notification/NotificationsLogTable.php 0000666 00000002641 15165376447 0017721 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class NotificationsLogTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification */ class NotificationsLogTable extends AbstractDatabaseTable { const TABLE = 'notifications_log'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `notificationId` INT(11) NOT NULL, `userId` INT(11) NULL, `appointmentId` INT(11) NULL, `eventId` INT(11) NULL, `packageCustomerId` INT(11) NULL, `sentDateTime` DATETIME NOT NULL, `sent` TINYINT(1) NULL, `data` TEXT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } /** * @return array * @throws InvalidArgumentException */ public static function alterTable() { $table = self::getTableName(); return ["ALTER TABLE {$table} MODIFY userId INT(11) NULL"]; } } WP/InstallActions/DB/Notification/NotificationsTableInsertRows.php 0000666 00000017060 15165376447 0021320 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; use AmeliaBooking\Infrastructure\WP\Translations\NotificationsStrings; /** * Class NotificationsTableInsertRows * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification */ class NotificationsTableInsertRows extends AbstractDatabaseTable { const TABLE = 'notifications'; /** * @return array * @throws InvalidArgumentException */ public static function buildTable() { global $wpdb; $table = self::getTableName(); $rows = []; $addEmail = !(int)$wpdb->get_row("SELECT COUNT(*) AS count FROM {$table} WHERE type = 'email'")->count; if ($addEmail) { $rows = array_merge($rows, NotificationsStrings::getAppointmentCustomerNonTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getAppointmentCustomerTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getAppointmentProviderNonTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getAppointmentProviderTimeBasedEmailNotifications()); } $addSMS = !(int)$wpdb->get_row("SELECT COUNT(*) AS count FROM {$table} WHERE type = 'sms'")->count; if ($addSMS) { $rows = array_merge($rows, NotificationsStrings::getAppointmentCustomerNonTimeBasedSMSNotifications()); $rows = array_merge($rows, NotificationsStrings::getAppointmentCustomerTimeBasedSMSNotifications()); $rows = array_merge($rows, NotificationsStrings::getAppointmentProviderNonTimeBasedSMSNotifications()); $rows = array_merge($rows, NotificationsStrings::getAppointmentProviderTimeBasedSMSNotifications()); } $addEvent = !(int)$wpdb->get_row("SELECT COUNT(*) AS count FROM {$table} WHERE entity = 'event'")->count; if ($addEvent) { $rows = array_merge($rows, NotificationsStrings::getEventCustomerNonTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventCustomerTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventProviderNonTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventProviderTimeBasedEmailNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventCustomerNonTimeBasedSMSNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventCustomerTimeBasedSMSNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventProviderNonTimeBasedSMSNotifications()); $rows = array_merge($rows, NotificationsStrings::getEventProviderTimeBasedSMSNotifications()); } $addAccountRecovery = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'customer_account_recovery'" )->count; if ($addAccountRecovery) { $rows = array_merge($rows, [NotificationsStrings::getAccountRecoveryNotification()]); } $addEmployeePanelAccess = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'provider_panel_access'" )->count; if ($addEmployeePanelAccess) { $rows = array_merge($rows, [NotificationsStrings::getEmployeePanelAccessNotification()]); } $addEmployeePanelRecovery = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'provider_panel_recovery'" )->count; if ($addEmployeePanelRecovery) { $rows = array_merge($rows, [NotificationsStrings::getEmployeeAccountRecoveryNotification()]); } $customerPackagePurchased = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'customer_package_purchased'" )->count; if ($customerPackagePurchased) { $rows = array_merge($rows, [NotificationsStrings::getCustomerPackagePurchasedEmailNotification()]); $rows = array_merge($rows, [NotificationsStrings::getCustomerPackagePurchasedSmsNotification()]); } $providerPackagePurchased = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'provider_package_purchased'" )->count; if ($providerPackagePurchased) { $rows = array_merge($rows, [NotificationsStrings::getProviderPackagePurchasedEmailNotification()]); $rows = array_merge($rows, [NotificationsStrings::getProviderPackagePurchasedSmsNotification()]); } $customerPackageCanceled = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'customer_package_canceled'" )->count; if ($customerPackageCanceled) { $rows = array_merge($rows, [NotificationsStrings::getCustomerPackageCanceledEmailNotification()]); $rows = array_merge($rows, [NotificationsStrings::getCustomerPackageCanceledSmsNotification()]); } $providerPackageCanceled = !(int)$wpdb->get_row( "SELECT COUNT(*) AS count FROM {$table} WHERE name = 'provider_package_canceled'" )->count; if ($providerPackageCanceled) { $rows = array_merge($rows, [NotificationsStrings::getProviderPackageCanceledEmailNotification()]); $rows = array_merge($rows, [NotificationsStrings::getProviderPackageCanceledSmsNotification()]); } $addWhatsApp = !(int)$wpdb->get_row("SELECT COUNT(*) AS count FROM {$table} WHERE type = 'whatsapp'")->count; if (false) { $rows = array_merge($rows, NotificationsStrings::getWhatsAppNotifications()); } $appointmentUpdated = !(int)$wpdb->get_row("SELECT COUNT(*) AS count FROM {$table} WHERE name LIKE '%appointment_updated'")->count; if ($appointmentUpdated) { $rows = array_merge($rows, NotificationsStrings::getAppointmentUpdatedNotifications($addEmail)); } $eventUpdated = !(int)$wpdb->get_row("SELECT COUNT(*) AS count FROM {$table} WHERE name LIKE '%event_updated'")->count; if ($eventUpdated) { $rows = array_merge($rows, NotificationsStrings::getEventUpdatedNotifications($addEmail)); } $result = []; foreach ($rows as $row) { $status = !empty($row['status']) ? $row['status'] : 'enabled'; $result[] = "INSERT INTO {$table} ( `name`, `type`, `time`, `timeBefore`, `timeAfter`, `sendTo`, `subject`, `content`, `entity`, `status` ) VALUES ( '{$row['name']}', '{$row['type']}', {$row['time']}, {$row['timeBefore']}, {$row['timeAfter']}, '{$row['sendTo']}', '{$row['subject']}', '{$row['content']}', '{$row['entity']}', '{$status}' )"; } return $result; } } WP/InstallActions/DB/Notification/NotificationsToEntitiesTable.php 0000666 00000001777 15165376447 0021300 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class NotificationsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification */ class NotificationsToEntitiesTable extends AbstractDatabaseTable { const TABLE = 'notifications_to_entities'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `notificationId` INT(11) NOT NULL, `entityId` INT(11) NOT NULL, `entity` ENUM('appointment', 'event') NOT NULL DEFAULT 'appointment', PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Notification/NotificationsTable.php 0000666 00000004633 15165376447 0017262 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Domain\ValueObjects\String\NotificationSendTo; use AmeliaBooking\Domain\ValueObjects\String\NotificationType; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class NotificationsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification */ class NotificationsTable extends AbstractDatabaseTable { const TABLE = 'notifications'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { global $wpdb; $table = self::getTableName(); $name = Name::MAX_LENGTH; $typeEmail = NotificationType::EMAIL; $typeSms = NotificationType::SMS; $typeWhatsApp = NotificationType::WHATSAPP; $sendToCustomer = NotificationSendTo::CUSTOMER; $sendToProvider = NotificationSendTo::PROVIDER; if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") === $table && $wpdb->query("SHOW KEYS FROM {$table} WHERE Key_name = 'name'") ) { $wpdb->query("ALTER TABLE {$table} DROP INDEX name"); } return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR({$name}) NOT NULL DEFAULT '', `customName` VARCHAR(255) DEFAULT NULL, `status` ENUM('enabled', 'disabled') NOT NULL DEFAULT 'enabled', `type` ENUM('{$typeEmail}', '{$typeSms}', '{$typeWhatsApp}') NOT NULL, `entity` ENUM('appointment', 'event') NOT NULL DEFAULT 'appointment', `time` TIME NULL DEFAULT NULL, `timeBefore` INT(11) NULL DEFAULT NULL, `timeAfter` INT(11) NULL DEFAULT NULL, `sendTo` ENUM('{$sendToCustomer}', '{$sendToProvider}') NOT NULL, `subject` VARCHAR(255) NOT NULL DEFAULT '', `content` TEXT NULL, `translations` TEXT NULL DEFAULT NULL, `sendOnlyMe` TINYINT(1) DEFAULT 0, `whatsAppTemplate` VARCHAR(255) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/AbstractDatabaseTable.php 0000666 00000003147 15165376447 0015212 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; /** * Class AbstractDatabaseTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB */ class AbstractDatabaseTable { const TABLE = ''; /** * @return string * @throws InvalidArgumentException */ public static function getTableName() { if (!static::TABLE) { throw new InvalidArgumentException('Table name is not provided'); } global $wpdb; return $wpdb->prefix . 'amelia_' . static::TABLE; } /** * Create new table in the database */ public static function init() { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta(static::buildTable()); global $wpdb; foreach (static::alterTable() as $command) { $wpdb->query($command); } } /** * Delete table table from the database * * @throws InvalidArgumentException */ public static function delete() { global $wpdb; $table = self::getTableName(); $sql = "DROP TABLE IF EXISTS {$table};"; $wpdb->query($sql); } /** * @return boolean */ public static function isValidTablePrefix() { global $wpdb; return strlen($wpdb->prefix) <= 16; } /** * @return array */ public static function alterTable() { return []; } } WP/InstallActions/DB/Payment/PaymentsTable.php 0000666 00000003647 15165376447 0015244 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class PaymentsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment */ class PaymentsTable extends AbstractDatabaseTable { const TABLE = 'payments'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `customerBookingId` int(11) NULL, `amount` DOUBLE NOT NULL default 0, `dateTime` datetime NULL, `status` ENUM('paid', 'pending', 'partiallyPaid', 'refunded') NOT NULL, `gateway` ENUM('onSite', 'payPal', 'stripe', 'wc', 'mollie', 'razorpay') NOT NULL, `gatewayTitle` varchar(255) NULL, `data` text NULL, `packageCustomerId` int(11) NULL, `parentId` int(11) DEFAULT NULL, `entity` ENUM('appointment', 'event', 'package') NULL, `created` DATETIME NULL, `actionsCompleted` TINYINT(1) NULL, `wcOrderId` bigint(20) NULL, `transactionId` varchar(255) NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } /** * @return array * @throws InvalidArgumentException */ public static function alterTable() { $table = self::getTableName(); return ["ALTER TABLE {$table} MODIFY customerBookingId INT(11) NULL"]; } } WP/InstallActions/DB/Location/LocationsViewsTable.php 0000666 00000001723 15165376447 0016541 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class LocationsViewsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location */ class LocationsViewsTable extends AbstractDatabaseTable { const TABLE = 'locations_views'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `locationId` INT(11) NOT NULL, `date` DATE NOT NULL, `views` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Location/LocationsTable.php 0000666 00000003750 15165376447 0015525 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\Picture; use AmeliaBooking\Domain\ValueObjects\String\Address; use AmeliaBooking\Domain\ValueObjects\String\Description; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Domain\ValueObjects\String\Phone; use AmeliaBooking\Domain\ValueObjects\String\Url; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class LocationsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location */ class LocationsTable extends AbstractDatabaseTable { const TABLE = 'locations'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; $description = Description::MAX_LENGTH; $address = Address::MAX_LENGTH; $phone = Phone::MAX_LENGTH; $picture = Picture::MAX_LENGTH; $url = Url::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `status` ENUM('hidden', 'visible', 'disabled') NOT NULL default 'visible', `name` varchar ({$name}) NOT NULL default '', `description` text({$description}) NULL, `address` varchar ({$address}) NOT NULL, `phone` varchar ({$phone}) NOT NULL, `latitude` decimal(8, 6) NOT NULL, `longitude` decimal(9, 6) NOT NULL, `pictureFullPath` varchar ({$picture}) NULL, `pictureThumbPath` varchar ({$picture}) NULL, `pin` varchar ({$url}) NULL, `translations` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/UsersTable.php 0000666 00000004626 15165376447 0014044 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\Picture; use AmeliaBooking\Domain\ValueObjects\String\Email; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Domain\ValueObjects\String\Password; use AmeliaBooking\Domain\ValueObjects\String\Phone; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class UsersTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User */ class UsersTable extends AbstractDatabaseTable { const TABLE = 'users'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; $email = Email::MAX_LENGTH; $phone = Phone::MAX_LENGTH; $picture = Picture::MAX_LENGTH; $password = Password::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `status` ENUM('hidden', 'visible', 'disabled') NOT NULL default 'visible', `type` ENUM('customer', 'provider', 'manager', 'admin') NOT NULL, `externalId` bigint(20) DEFAULT NULL, `firstName` varchar({$name}) NOT NULL DEFAULT '', `lastName` varchar({$name}) NOT NULL DEFAULT '', `email` varchar({$email}) DEFAULT NULL, `birthday` date DEFAULT NULL, `phone` varchar({$phone}) DEFAULT NULL, `gender` ENUM('male', 'female') DEFAULT NULL, `note` text, `description` text NULL DEFAULT NULL, `pictureFullPath` varchar ({$picture}) NULL, `pictureThumbPath` varchar ({$picture}) NULL, `password` varchar ({$password}) NULL, `usedTokens` text NULL, `zoomUserId` varchar({$name}) DEFAULT NULL, `countryPhoneIso` varchar(2) DEFAULT NULL, `translations` TEXT NULL DEFAULT NULL, `timeZone` varchar({$name}) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;"; } } WP/InstallActions/DB/User/Provider/ProvidersWeekDayTable.php 0000666 00000002031 15165376447 0017750 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersWeekDayTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersWeekDayTable extends AbstractDatabaseTable { const TABLE = 'providers_to_weekdays'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `dayIndex` tinyint(2) NOT NULL, `startTime` time NOT NULL, `endTime` time NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersGoogleCalendarTable.php 0000666 00000002132 15165376447 0021267 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Email; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersGoogleCalendarTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersGoogleCalendarTable extends AbstractDatabaseTable { const TABLE = 'providers_to_google_calendar'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $email = Email::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `userId` INT(11) NOT NULL, `token` TEXT NOT NULL, `calendarId` TEXT({$email}) NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersSpecialDayPeriodServiceTable.php 0000666 00000001765 15165376447 0023136 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersSpecialDayPeriodServiceTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersSpecialDayPeriodServiceTable extends AbstractDatabaseTable { const TABLE = 'providers_to_specialdays_periods_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `periodId` int(11) NOT NULL, `serviceId` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersSpecialDayTable.php 0000666 00000001760 15165376447 0020445 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersSpecialDayTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersSpecialDayTable extends AbstractDatabaseTable { const TABLE = 'providers_to_specialdays'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `startDate` date NOT NULL, `endDate` date NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersServiceTable.php 0000666 00000004054 15165376447 0020026 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersServiceTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersServiceTable extends AbstractDatabaseTable { const TABLE = 'providers_to_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `serviceId` int(11) NOT NULL, `price` double NOT NULL, `minCapacity` int(11) NOT NULL, `maxCapacity` int(11) NOT NULL, `customPricing` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } /** * @return array * @throws InvalidArgumentException */ public static function alterTable() { $table = self::getTableName(); global $wpdb; $duplicatedRowsIds = $wpdb->get_col( "SELECT t1.id AS id FROM {$table} t1 INNER JOIN {$table} t2 ON t1.userId = t2.userId AND t1.serviceId = t2.serviceId WHERE t1.id > t2.id AND t1.userId = t2.userId AND t1.serviceId = t2.serviceId GROUP BY t1.id" ); foreach ($duplicatedRowsIds as $key => $id) { $duplicatedRowsIds[$key] = (int)$duplicatedRowsIds[$key]; } if ($duplicatedRowsIds) { $duplicatedRowsIdsQuery = implode(', ', $duplicatedRowsIds); $wpdb->query("DELETE FROM {$table} WHERE id IN ({$duplicatedRowsIdsQuery})"); } return []; } } WP/InstallActions/DB/User/Provider/ProvidersPeriodTable.php 0000666 00000002143 15165376447 0017645 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsTable; /** * Class ProvidersPeriodTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersPeriodTable extends AbstractDatabaseTable { const TABLE = 'providers_to_periods'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `weekDayId` int(11) NOT NULL, `locationId` int(11) NULL, `startTime` time NOT NULL, `endTime` time NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersSpecialDayPeriodTable.php 0000666 00000002067 15165376447 0021611 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersSpecialDayPeriodTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersSpecialDayPeriodTable extends AbstractDatabaseTable { const TABLE = 'providers_to_specialdays_periods'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `specialDayId` int(11) NOT NULL, `locationId` int(11) NULL, `startTime` time NOT NULL, `endTime` time NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersOutlookCalendarTable.php 0000666 00000002135 15165376447 0021512 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Email; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersOutlookCalendarTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersOutlookCalendarTable extends AbstractDatabaseTable { const TABLE = 'providers_to_outlook_calendar'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $email = Email::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `userId` INT(11) NOT NULL, `token` TEXT NOT NULL, `calendarId` TEXT({$email}) NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersLocationTable.php 0000666 00000001703 15165376447 0020174 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersLocationTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersLocationTable extends AbstractDatabaseTable { const TABLE = 'providers_to_locations'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `locationId` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersViewsTable.php 0000666 00000001731 15165376447 0017522 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersViewsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersViewsTable extends AbstractDatabaseTable { const TABLE = 'providers_views'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `userId` INT(11) NOT NULL, `date` DATE NOT NULL, `views` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersTimeOutTable.php 0000666 00000001752 15165376447 0020016 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersTimeOutTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersTimeOutTable extends AbstractDatabaseTable { const TABLE = 'providers_to_timeouts'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `weekDayId` int(11) NOT NULL, `startTime` time NOT NULL, `endTime` time NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersPeriodServiceTable.php 0000666 00000001725 15165376447 0021173 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersPeriodServiceTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersPeriodServiceTable extends AbstractDatabaseTable { const TABLE = 'providers_to_periods_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `periodId` int(11) NOT NULL, `serviceId` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersDayOffTable.php 0000666 00000002236 15165376447 0017576 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; use AmeliaBooking\Domain\ValueObjects\String\Name; /** * Class ProvidersDayOffTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersDayOffTable extends AbstractDatabaseTable { const TABLE = 'providers_to_daysoff'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `name` varchar({$name}) NOT NULL, `startDate` date NOT NULL, `endDate` date NOT NULL, `repeat` tinyint(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersSpecialDayPeriodLocationTable.php 0000666 00000001770 15165376447 0023302 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersSpecialDayPeriodLocationTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersSpecialDayPeriodLocationTable extends AbstractDatabaseTable { const TABLE = 'providers_to_specialdays_periods_location'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `periodId` int(11) NOT NULL, `locationId` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/Provider/ProvidersPeriodLocationTable.php 0000666 00000001730 15165376447 0021337 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ProvidersPeriodLocationTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider */ class ProvidersPeriodLocationTable extends AbstractDatabaseTable { const TABLE = 'providers_to_periods_location'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `periodId` int(11) NOT NULL, `locationId` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/User/WPUsersTable.php 0000666 00000003036 15165376447 0014305 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\User; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; /** * Class WPUsersTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\User */ class WPUsersTable extends AbstractDatabaseTable { const TABLE = 'users'; const META_TABLE = 'usermeta'; /** * @return string */ public static function getTableName() { return self::getDatabaseBasePrefix() . static::TABLE; } /** * @return string */ public static function getMetaTableName() { return self::getDatabaseBasePrefix() . static::META_TABLE; } /** * @return string */ public static function getDatabasePrefix() { $settingsService = new SettingsService(new SettingsStorage()); $prefix = $settingsService->getSetting('db', 'wpTablesPrefix'); global $wpdb; return !$prefix ? $wpdb->prefix : $prefix; } /** * @return string */ public static function getDatabaseBasePrefix() { $settingsService = new SettingsService(new SettingsStorage()); $prefix = $settingsService->getSetting('db', 'wpTablesPrefix'); global $wpdb; return !$prefix ? $wpdb->base_prefix : $prefix; } } WP/InstallActions/DB/Booking/CustomerBookingToEventsTicketsTable.php 0000666 00000002047 15165376447 0021541 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomerBookingToEventsTicketsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class CustomerBookingToEventsTicketsTable extends AbstractDatabaseTable { const TABLE = 'customer_bookings_to_events_tickets'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `customerBookingId` INT(11) NOT NULL, `eventTicketId` INT(11) NOT NULL, `price` double DEFAULT 0, `persons` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/EventsProvidersTable.php 0000666 00000001605 15165376447 0016551 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class EventsPeriodsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class EventsProvidersTable extends AbstractDatabaseTable { const TABLE = 'events_to_providers'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `eventId` INT(11) NOT NULL, `userId` INT(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/CustomerBookingsTable.php 0000666 00000004051 15165376447 0016702 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Token; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomerBookingsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class CustomerBookingsTable extends AbstractDatabaseTable { const TABLE = 'customer_bookings'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $token = Token::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `appointmentId` INT(11) NULL, `customerId` INT(11) NOT NULL, `status` ENUM('approved', 'pending', 'canceled', 'rejected', 'no-show') NULL, `price` DOUBLE NOT NULL, `persons` INT(11) NOT NULL, `couponId` INT(11) NULL, `token` VARCHAR({$token}) NULL, `customFields` TEXT NULL, `info` TEXT NULL, `utcOffset` INT(3) NULL, `aggregatedPrice` TINYINT(1) DEFAULT 1, `packageCustomerServiceId` INT(11) NULL, `duration` int(11) DEFAULT NULL, `created` DATETIME NULL, `actionsCompleted` TINYINT(1) NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } /** * @return array * @throws InvalidArgumentException */ public static function alterTable() { $table = self::getTableName(); global $wpdb; return ($wpdb->get_var("SHOW COLUMNS FROM `{$table}` LIKE 'eventId'") !== 'eventId') ? [ "ALTER TABLE {$table} MODIFY appointmentId INT(11) NULL", ] : []; } } WP/InstallActions/DB/Booking/AppointmentsTable.php 0000666 00000003351 15165376447 0016070 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Description; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class AppointmentsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class AppointmentsTable extends AbstractDatabaseTable { const TABLE = 'appointments'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $description = Description::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `status` ENUM('approved', 'pending', 'canceled', 'rejected', 'no-show') NULL, `bookingStart` DATETIME NOT NULL, `bookingEnd` DATETIME NOT NULL, `notifyParticipants` TINYINT(1) NOT NULL, `serviceId` INT(11) NOT NULL, `packageId` INT(11) DEFAULT NULL, `providerId` INT(11) NOT NULL, `locationId` INT(11) NULL, `internalNotes` TEXT({$description}) NULL, `googleCalendarEventId` VARCHAR(255) NULL, `googleMeetUrl` VARCHAR(255) NULL, `outlookCalendarEventId` VARCHAR(255) NULL, `zoomMeeting` TEXT({$description}) NULL, `lessonSpace` TEXT({$description}) NULL, `parentId` INT(11) NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/EventsTicketsTable.php 0000666 00000002335 15165376447 0016203 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class EventsTicketsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class EventsTicketsTable extends AbstractDatabaseTable { const TABLE = 'events_to_tickets'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `eventId` INT(11) NOT NULL, `enabled` TINYINT(1) DEFAULT 1, `name` varchar({$name}) NOT NULL, `price` double DEFAULT 0, `dateRanges` TEXT NULL DEFAULT NULL, `spots` int(11) NOT NULL, `translations` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/EventsTagsTable.php 0000666 00000001722 15165376447 0015472 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class EventsTagsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class EventsTagsTable extends AbstractDatabaseTable { const TABLE = 'events_tags'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `eventId` INT(11) NOT NULL, `name` varchar({$name}) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/CustomerBookingsToExtrasTable.php 0000666 00000002234 15165376447 0020375 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomerBookingsToExtrasTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class CustomerBookingsToExtrasTable extends AbstractDatabaseTable { const TABLE = 'customer_bookings_to_extras'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `customerBookingId` INT(11) NOT NULL, `extraId` INT(11) NOT NULL, `quantity` INT(11) NOT NULL, `price` DOUBLE NOT NULL, `aggregatedPrice` TINYINT(1) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `bookingExtra` (`customerBookingId` ,`extraId`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/EventsTable.php 0000666 00000007524 15165376447 0014661 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Color; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; use AmeliaBooking\Domain\ValueObjects\String\Description; /** * Class EventsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class EventsTable extends AbstractDatabaseTable { const TABLE = 'events'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; $description = Description::MAX_LENGTH; $color = Color::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `parentId` INT(11), `name` varchar({$name}) NOT NULL default '', `status` ENUM('approved','pending','canceled','rejected') NOT NULL, `bookingOpens` DATETIME NULL, `bookingCloses` DATETIME NULL, `bookingOpensRec` ENUM('same', 'calculate') DEFAULT 'same', `bookingClosesRec` ENUM('same', 'calculate') DEFAULT 'same', `ticketRangeRec` ENUM('same', 'calculate') DEFAULT 'calculate', `recurringCycle` ENUM('daily', 'weekly', 'monthly', 'yearly') NULL, `recurringOrder` int(11) NULL, `recurringInterval` int(11) DEFAULT 1, `recurringMonthly` ENUM('each' , 'on') DEFAULT 'each', `monthlyDate` DATETIME NULL, `monthlyOnRepeat` ENUM('first', 'second', 'third', 'fourth', 'last') DEFAULT NULL, `monthlyOnDay` ENUM('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday') DEFAULT NULL, `recurringUntil` DATETIME NULL, `maxCapacity` int(11) NOT NULL, `maxCustomCapacity` int(11) NULL DEFAULT NULL, `maxExtraPeople` int(11) NULL DEFAULT NULL, `price` double NOT NULL, `locationId` INT(11) NULL, `customLocation` VARCHAR({$name}) NULL, `description` TEXT({$description}) NULL, `color` varchar({$color}) NULL NULL, `show` TINYINT(1) NOT NULL DEFAULT 1, `notifyParticipants` TINYINT(1) NOT NULL, `created` DATETIME NOT NULL, `settings` text({$description}) NULL DEFAULT NULL, `zoomUserId` varchar({$name}) DEFAULT NULL, `bringingAnyone` TINYINT(1) NULL DEFAULT 1, `bookMultipleTimes` TINYINT(1) NULL DEFAULT 1, `translations` TEXT NULL DEFAULT NULL, `depositPayment` ENUM('disabled' , 'fixed', 'percentage') DEFAULT 'disabled', `depositPerPerson` TINYINT(1) DEFAULT 1, `fullPayment` TINYINT(1) DEFAULT 0, `deposit` double DEFAULT 0, `customPricing` TINYINT(1) DEFAULT 0, `organizerId` INT(11) NULL, `closeAfterMin` INT(11) NULL DEFAULT NULL, `closeAfterMinBookings` TINYINT(1) DEFAULT 0, `aggregatedPrice` TINYINT(1) DEFAULT 1, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } /** * @return array * @throws InvalidArgumentException */ public static function alterTable() { $table = self::getTableName(); return ["ALTER TABLE {$table} MODIFY recurringInterval int(11) DEFAULT 1"]; } } WP/InstallActions/DB/Booking/CustomerBookingsToEventsPeriodsTable.php 0000666 00000002047 15165376447 0021723 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CustomerBookingsToEventsPeriodsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class CustomerBookingsToEventsPeriodsTable extends AbstractDatabaseTable { const TABLE = 'customer_bookings_to_events_periods'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `customerBookingId` INT(11) NOT NULL, `eventPeriodId` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `bookingEventPeriod` (`customerBookingId` ,`eventPeriodId`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Booking/EventsPeriodsTable.php 0000666 00000002514 15165376447 0016201 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Description; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class EventsPeriodsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking */ class EventsPeriodsTable extends AbstractDatabaseTable { const TABLE = 'events_periods'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $description = Description::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `eventId` INT(11) NOT NULL, `periodStart` DATETIME NOT NULL, `periodEnd` DATETIME NOT NULL, `zoomMeeting` TEXT({$description}) NULL, `lessonSpace` TEXT({$description}) NULL, `googleCalendarEventId` VARCHAR(255) NULL, `googleMeetUrl` VARCHAR(255) NULL, `outlookCalendarEventId` VARCHAR(255) NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Coupon/CouponsToPackagesTable.php 0000666 00000001772 15165376447 0016657 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CouponsToPackagesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon */ class CouponsToPackagesTable extends AbstractDatabaseTable { const TABLE = 'coupons_to_packages'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `couponId` int(11) NOT NULL, `packageId` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Coupon/CouponsToServicesTable.php 0000666 00000001772 15165376447 0016724 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CouponsToServicesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon */ class CouponsToServicesTable extends AbstractDatabaseTable { const TABLE = 'coupons_to_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `couponId` int(11) NOT NULL, `serviceId` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Coupon/CouponsToEventsTable.php 0000666 00000001764 15165376447 0016406 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CouponsToServicesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon */ class CouponsToEventsTable extends AbstractDatabaseTable { const TABLE = 'coupons_to_events'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `couponId` int(11) NOT NULL, `eventId` int(11) NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Coupon/CouponsTable.php 0000666 00000002607 15165376447 0014713 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CouponsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon */ class CouponsTable extends AbstractDatabaseTable { const TABLE = 'coupons'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` VARCHAR(255) NOT NULL COLLATE utf8_bin, `discount` DOUBLE NOT NULL, `deduction` DOUBLE NOT NULL, `limit` DOUBLE NOT NULL, `customerLimit` DOUBLE NOT NULL DEFAULT 0, `status` ENUM('hidden', 'visible') NOT NULL, `notificationInterval` INT(11) NOT NULL DEFAULT 0, `notificationRecurring` TINYINT(1) NOT NULL DEFAULT 0, `expirationDate` DATETIME NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/PackagesServicesTable.php 0000666 00000002153 15165376447 0016756 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class PackagesServicesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class PackagesServicesTable extends AbstractDatabaseTable { const TABLE = 'packages_to_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `serviceId` INT(11) NOT NULL, `packageId` INT(11) NOT NULL, `quantity` INT(11) NOT NULL, `minimumScheduled` INT(5) DEFAULT 1, `maximumScheduled` INT(5) DEFAULT 1, `allowProviderSelection` TINYINT(1) DEFAULT 1, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/ServicesViewsTable.php 0000666 00000001717 15165376447 0016342 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ServicesViewsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class ServicesViewsTable extends AbstractDatabaseTable { const TABLE = 'services_views'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `serviceId` INT(11) NOT NULL, `date` DATE NOT NULL, `views` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/PackagesServicesLocationsTable.php 0000666 00000001733 15165376447 0020635 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class PackagesServicesLocationsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class PackagesServicesLocationsTable extends AbstractDatabaseTable { const TABLE = 'packages_services_to_locations'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `packageServiceId` INT(11) NOT NULL, `locationId` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/CategoriesTable.php 0000666 00000002170 15165376447 0015620 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class CategoriesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class CategoriesTable extends AbstractDatabaseTable { const TABLE = 'categories'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `status` enum('hidden', 'visible', 'disabled') NOT NULL default 'visible', `name` varchar ({$name}) NOT NULL default '', `position` int(11) NOT NULL, `translations` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/PackagesCustomersTable.php 0000666 00000002404 15165376447 0017156 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class PackagesCustomersTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class PackagesCustomersTable extends AbstractDatabaseTable { const TABLE = 'packages_to_customers'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `packageId` INT(11) NOT NULL, `customerId` INT(11) NOT NULL, `price` DOUBLE NOT NULL, `start` DATETIME NULL, `end` DATETIME NULL, `purchased` DATETIME NOT NULL, `status` ENUM('approved', 'pending', 'canceled', 'rejected') DEFAULT NULL, `bookingsCount` INT(5) DEFAULT NULL, `couponId` INT(11) DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/PackagesCustomersServicesTable.php 0000666 00000003721 15165376447 0020665 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class PackagesCustomersServicesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class PackagesCustomersServicesTable extends AbstractDatabaseTable { const TABLE = 'packages_customers_to_services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `packageCustomerId` INT(11) NOT NULL, `serviceId` INT(11) NOT NULL, `providerId` INT(11) NULL, `locationId` INT(11) NULL, `bookingsCount` INT(5) DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } /** * @return array * @throws InvalidArgumentException */ public static function alterTable() { $table = self::getTableName(); $usersTable = UsersTable::getTableName(); global $wpdb; $deletedProviderIds = $wpdb->get_col( "SELECT t1.providerId FROM {$table} t1 WHERE t1.providerId NOT IN (SELECT t2.id FROM {$usersTable} t2)" ); foreach ($deletedProviderIds as $key => $id) { $deletedProviderIds[$key] = (int)$deletedProviderIds[$key]; } if ($deletedProviderIds) { $deletedProvidersIdsQuery = implode(', ', $deletedProviderIds); $wpdb->query("UPDATE {$table} SET providerId = NULL WHERE providerId IN ({$deletedProvidersIdsQuery})"); } return []; } } WP/InstallActions/DB/Bookable/ResourcesToEntitiesTable.php 0000666 00000001772 15165376447 0017524 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class NotificationsTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification */ class ResourcesToEntitiesTable extends AbstractDatabaseTable { const TABLE = 'resources_to_entities'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `resourceId` INT(11) NOT NULL, `entityId` INT(11) NOT NULL, `entityType` ENUM('service', 'location', 'employee') NOT NULL DEFAULT 'service', PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/PackagesServicesProvidersTable.php 0000666 00000001727 15165376447 0020662 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class PackagesServicesProvidersTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class PackagesServicesProvidersTable extends AbstractDatabaseTable { const TABLE = 'packages_services_to_providers'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `packageServiceId` INT(11) NOT NULL, `userId` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/ExtrasTable.php 0000666 00000002655 15165376447 0015011 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Description; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ExtrasTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class ExtrasTable extends AbstractDatabaseTable { const TABLE = 'extras'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; $description = Description::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar({$name}) NOT NULL default '', `description` text({$description}) NULL, `price` double NOT NULL, `maxQuantity` int(11) NOT NULL, `duration` int(11) NULL, `serviceId` int(11) NOT NULL, `position` int(11) NOT NULL, `aggregatedPrice` TINYINT(1) DEFAULT NULL, `translations` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/ServicesTable.php 0000666 00000006215 15165376447 0015322 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\Picture; use AmeliaBooking\Domain\ValueObjects\String\Color; use AmeliaBooking\Domain\ValueObjects\String\Description; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class ServiceTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class ServicesTable extends AbstractDatabaseTable { const TABLE = 'services'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; $description = Description::MAX_LENGTH; $color = Color::MAX_LENGTH; $picture = Picture::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar({$name}) NOT NULL default '', `description` text({$description}) NULL, `color` varchar({$color}) NOT NULL default '', `price` double NOT NULL, `status` ENUM('hidden', 'visible', 'disabled') NOT NULL default 'visible', `categoryId` int(11) NOT NULL, `minCapacity` int(11) NOT NULL, `maxCapacity` int(11) NOT NULL, `duration` int(11) NOT NULL, `timeBefore` int(11) NULL DEFAULT 0, `timeAfter` int(11) NULL DEFAULT 0, `bringingAnyone` TINYINT(1) NULL DEFAULT 1, `priority` ENUM('least_expensive', 'most_expensive', 'least_occupied', 'most_occupied') NOT NULL, `pictureFullPath` varchar ({$picture}) NULL, `pictureThumbPath` varchar ({$picture}) NULL, `position` int(11) default 0, `show` TINYINT(1) DEFAULT 1, `aggregatedPrice` TINYINT(1) DEFAULT 1, `settings` text({$description}) NULL DEFAULT NULL, `recurringCycle` ENUM('disabled', 'all', 'daily', 'weekly', 'monthly') DEFAULT 'disabled', `recurringSub` ENUM('disabled' ,'past', 'future', 'both') DEFAULT 'future', `recurringPayment` int(3) DEFAULT 0, `translations` TEXT NULL DEFAULT NULL, `depositPayment` ENUM('disabled' , 'fixed', 'percentage') DEFAULT 'disabled', `depositPerPerson` TINYINT(1) DEFAULT 1, `deposit` double DEFAULT 0, `fullPayment` TINYINT(1) DEFAULT 0, `mandatoryExtra` TINYINT(1) DEFAULT 0, `minSelectedExtras` int(11) NULL DEFAULT 0, `customPricing` TEXT NULL DEFAULT NULL, `maxExtraPeople` int(11) NULL DEFAULT NULL, `limitPerCustomer` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/PackagesTable.php 0000666 00000004607 15165376447 0015260 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\Picture; use AmeliaBooking\Domain\ValueObjects\String\Color; use AmeliaBooking\Domain\ValueObjects\String\Description; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; /** * Class PackagesTable * * @package AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable */ class PackagesTable extends AbstractDatabaseTable { const TABLE = 'packages'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; $description = Description::MAX_LENGTH; $color = Color::MAX_LENGTH; $picture = Picture::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR({$name}) NOT NULL DEFAULT '', `description` TEXT({$description}) NULL, `color` VARCHAR({$color}) NOT NULL DEFAULT '', `price` DOUBLE NOT NULL, `status` ENUM('hidden', 'visible', 'disabled') NOT NULL DEFAULT 'visible', `pictureFullPath` VARCHAR ({$picture}) NULL, `pictureThumbPath` VARCHAR ({$picture}) NULL, `position` INT(11) DEFAULT 0, `calculatedPrice` TINYINT(1) DEFAULT 1, `discount` DOUBLE NOT NULL, `endDate` DATETIME NULL, `durationType` ENUM('day', 'week', 'month') DEFAULT NULL, `durationCount` INT(4) DEFAULT NULL, `settings` TEXT({$description}) NULL DEFAULT NULL, `translations` TEXT NULL DEFAULT NULL, `depositPayment` ENUM('disabled' , 'fixed', 'percentage') DEFAULT 'disabled', `deposit` DOUBLE DEFAULT 0, `fullPayment` TINYINT(1) DEFAULT 0, `sharedCapacity` TINYINT(1) DEFAULT 0, `quantity` INT(11) DEFAULT 1, `limitPerCustomer` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/InstallActions/DB/Bookable/ResourcesTable.php 0000666 00000002130 15165376447 0015501 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\ValueObjects\String\Name; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\AbstractDatabaseTable; class ResourcesTable extends AbstractDatabaseTable { const TABLE = 'resources'; /** * @return string * @throws InvalidArgumentException */ public static function buildTable() { $table = self::getTableName(); $name = Name::MAX_LENGTH; return "CREATE TABLE {$table} ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar({$name}) NOT NULL DEFAULT '', `quantity` INT(11) DEFAULT 1, `shared` ENUM('service', 'location') DEFAULT NULL, `status` ENUM('hidden', 'visible', 'disabled') NOT NULL DEFAULT 'visible', `countAdditionalPeople` TINYINT(1) DEFAULT 0, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE utf8_general_ci"; } } WP/ShortcodeService/EventsListBookingShortcodeService.php 0000666 00000002500 15165376447 0017706 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; /** * Class EventsListBookingShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class EventsListBookingShortcodeService extends AmeliaBookingShortcodeService { /** * @param array $params * @return string * @throws InvalidArgumentException */ public static function shortcodeHandler($params) { $params = shortcode_atts( [ 'trigger' => '', 'counter' => self::$counter, 'event' => null, 'recurring' => null, 'employee' => null, 'tag' => null, 'today' => null, ], $params ); if (!empty($params['tag'])) { $params['tag'] = htmlspecialchars_decode($params['tag']); } self::prepareScriptsAndStyles(); ob_start(); include AMELIA_PATH . '/view/frontend/events-list-booking.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/StepBookingShortcodeService.php 0000666 00000002332 15165376447 0016524 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; /** * Class StepBookingShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class StepBookingShortcodeService extends AmeliaBookingShortcodeService { /** * @param array $params * @return string * @throws InvalidArgumentException */ public static function shortcodeHandler($params) { $params = shortcode_atts( [ 'trigger' => '', 'trigger_type' => '', 'show' => '', 'category' => null, 'service' => null, 'employee' => null, 'location' => null, 'package' => null, 'counter' => self::$counter ], $params ); self::prepareScriptsAndStyles(); ob_start(); include AMELIA_PATH . '/view/frontend/step-booking.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/BookingShortcodeService.php 0000666 00000002236 15165376447 0015673 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Entities; /** * Class BookingShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class BookingShortcodeService extends AmeliaShortcodeService { /** * @param array $atts * @return string * @throws InvalidArgumentException */ public static function shortcodeHandler($atts) { $atts = shortcode_atts( [ 'trigger' => '', 'show' => '', 'category' => null, 'service' => null, 'employee' => null, 'location' => null, 'counter' => self::$counter ], $atts ); self::prepareScriptsAndStyles(); ob_start(); include AMELIA_PATH . '/view/frontend/booking.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/CabinetEmployeeShortcodeService.php 0000666 00000003741 15165376447 0017352 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\Integrations\WooCommerce\WooCommerceService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; /** * Class CabinetEmployeeShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class CabinetEmployeeShortcodeService extends AmeliaShortcodeService { /** * @param array $atts * @return string * @throws InvalidArgumentException * @throws \Interop\Container\Exception\ContainerException */ public static function shortcodeHandler($atts) { $atts = shortcode_atts( [ 'trigger' => '', 'counter' => self::$counter, 'appointments' => null, 'events' => null, 'profile-hidden' => null ], $atts ); self::prepareScriptsAndStyles(); // Enqueue Styles wp_enqueue_style( 'amelia_booking_styles_quill', AMELIA_URL . 'public/css/frontend/quill.css', [], AMELIA_VERSION ); $settingsService = new SettingsService(new SettingsStorage()); $wcSettings = $settingsService->getSetting('payments', 'wc'); if ($wcSettings['enabled'] && WooCommerceService::isEnabled()) { wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaWcProducts', WooCommerceService::getInitialProducts() ); } ob_start(); include AMELIA_PATH . '/view/frontend/cabinet-employee.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/EventsShortcodeService.php 0000666 00000002533 15165376447 0015547 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Entities; /** * Class EventsShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class EventsShortcodeService extends AmeliaShortcodeService { /** * @param array $atts * @return string * @throws InvalidArgumentException */ public static function shortcodeHandler($atts) { $atts = shortcode_atts( [ 'trigger' => '', 'counter' => self::$counter, 'event' => null, 'recurring' => null, 'employee' => null, 'tag' => null, 'today' => null, 'type' => null, ], $atts ); if (!empty($atts['tag'])) { $atts['tag'] = htmlspecialchars_decode($atts['tag']); } self::prepareScriptsAndStyles(); ob_start(); include AMELIA_PATH . '/view/frontend/events.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/CatalogShortcodeService.php 0000666 00000004013 15165376447 0015650 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Entities; /** * Class CatalogShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class CatalogShortcodeService extends AmeliaShortcodeService { /** * @param array $atts * @return string * @throws InvalidArgumentException */ public static function shortcodeHandler($atts) { $atts = shortcode_atts( [ 'trigger' => '', 'show' => '', 'package' => null, 'category' => null, 'service' => null, 'employee' => null, 'location' => null, 'counter' => self::$counter ], $atts ); self::prepareScriptsAndStyles(); // Single Category View if ($atts['category'] !== null) { ob_start(); include AMELIA_PATH . '/view/frontend/category.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } // Single Service View if ($atts['service'] !== null) { ob_start(); include AMELIA_PATH . '/view/frontend/service.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } // Single Package View if ($atts['package'] !== null) { ob_start(); include AMELIA_PATH . '/view/frontend/package.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } // All Categories View ob_start(); include AMELIA_PATH . '/view/frontend/catalog.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/CabinetCustomerShortcodeService.php 0000666 00000002502 15165376447 0017366 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; /** * Class CabinetCustomerShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class CabinetCustomerShortcodeService extends AmeliaShortcodeService { /** * @param array $atts * @return string * @throws InvalidArgumentException * @throws \Interop\Container\Exception\ContainerException */ public static function shortcodeHandler($atts) { $atts = shortcode_atts( [ 'trigger' => '', 'counter' => self::$counter, 'appointments' => null, 'events' => null ], $atts ); self::prepareScriptsAndStyles(); // Enqueue Styles wp_enqueue_style( 'amelia_booking_styles_quill', AMELIA_URL . 'public/css/frontend/quill.css', [], AMELIA_VERSION ); ob_start(); include AMELIA_PATH . '/view/frontend/cabinet-customer.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/ShortcodeService/AmeliaBookingShortcodeService.php 0000666 00000016773 15165376447 0017017 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Application\Services\Cache\CacheApplicationService; use AmeliaBooking\Application\Services\Stash\StashApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use AmeliaBooking\Infrastructure\WP\Translations\FrontendStrings; use Interop\Container\Exception\ContainerException; /** * Class AmeliaBookingShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class AmeliaBookingShortcodeService { public static $counter = 1000; /** * Prepare scripts and styles * @throws ContainerException * @throws InvalidArgumentException */ public static function prepareScriptsAndStyles() { $container = null; self::$counter++; if (self::$counter > 1001) { return; } $settingsService = new SettingsService(new SettingsStorage()); if ($settingsService->getSetting('payments', 'payPal')['enabled'] === true) { wp_enqueue_script('amelia_paypal_script', 'https://www.paypalobjects.com/api/checkout.js'); } if ($settingsService->getSetting('payments', 'stripe')['enabled'] === true) { wp_enqueue_script('amelia_stripe_script', 'https://js.stripe.com/v3/'); } if ($settingsService->getSetting('payments', 'razorpay')['enabled'] === true) { wp_enqueue_script('amelia_razorpay_script', 'https://checkout.razorpay.com/v1/checkout.js'); } $gmapApiKey = $settingsService->getSetting('general', 'gMapApiKey'); if ($gmapApiKey) { wp_enqueue_script( 'amelia_google_maps_api', "https://maps.googleapis.com/maps/api/js?key={$gmapApiKey}&libraries=places" ); } $scriptId = AMELIA_DEV ? 'amelia_booking_scripts_dev_vite' : 'amelia_booking_script_index'; if (AMELIA_DEV) { wp_enqueue_script( $scriptId, 'http://localhost:3000/@vite/client', [], null, false ); wp_enqueue_script( 'amelia_booking_scripts_dev_main', 'http://localhost:3000/src/assets/js/public/public.js', [], null, true ); } else { wp_enqueue_script( $scriptId, AMELIA_URL . 'v3/public/assets/public.0ec828d8.js', [], AMELIA_VERSION, true ); } wp_localize_script( $scriptId, 'localeLanguage', [AMELIA_LOCALE] ); wp_localize_script( $scriptId, 'wpAmeliaSettings', $settingsService->getFrontendSettings() ); // Strings Localization wp_localize_script( $scriptId, 'wpAmeliaLabels', FrontendStrings::getAllStrings() ); $ameliaUrl = AMELIA_URL; $ameliaActionUrl = AMELIA_ACTION_URL; if (strpos($ameliaUrl, 'http://') === 0) { $ameliaUrl = substr($ameliaUrl, strpos(substr($ameliaUrl, 7), '/') + 7); $ameliaActionUrl = substr($ameliaActionUrl, strpos(substr($ameliaActionUrl, 7), '/') + 7); } else if (strpos($ameliaUrl, 'https://') === 0) { $ameliaUrl = substr($ameliaUrl, strpos(substr($ameliaUrl, 8), '/') + 8); $ameliaActionUrl = substr($ameliaActionUrl, strpos(substr($ameliaActionUrl, 8), '/') + 8); } wp_localize_script( $scriptId, 'wpAmeliaUrls', [ 'wpAmeliaUseUploadsAmeliaPath' => AMELIA_UPLOADS_FILES_PATH_USE, 'wpAmeliaPluginURL' => $ameliaUrl, 'wpAmeliaPluginAjaxURL' => $ameliaActionUrl, ] ); if (!empty($_GET['ameliaCache']) || !empty($_GET['ameliaWcCache'])) { $container = $container ?: require AMELIA_PATH . '/src/Infrastructure/ContainerConfig/container.php'; /** @var CacheApplicationService $cacheAS */ $cacheAS = $container->get('application.cache.service'); try { $cacheData = !empty($_GET['ameliaCache']) ? $cacheAS->getCacheByName($_GET['ameliaCache']) : $cacheAS->getWcCacheByName($_GET['ameliaWcCache']); wp_localize_script( $scriptId, 'ameliaCache', [$cacheData ? str_replace('"', '\\"', json_encode($cacheData)) : ''] ); } catch (QueryExecutionException $e) { } } if ($settingsService->getSetting('activation', 'stash')) { $container = $container ?: require AMELIA_PATH . '/src/Infrastructure/ContainerConfig/container.php'; /** @var StashApplicationService $stashAS */ $stashAS = $container->get('application.stash.service'); wp_localize_script( $scriptId, 'ameliaEntities', $stashAS->getStash() ); } } /** * @param string $tag * @param string $handle * @param string $src * * @return string */ public static function prepareScripts($tag, $handle, $src) { switch ($handle) { case ('amelia_booking_scripts_dev_vite'): case ('amelia_booking_scripts_dev_main'): return "<script type='module' src='{$src}'></script>"; case ('amelia_booking_script_index'): $settingsService = new SettingsService(new SettingsStorage()); if ($settingsService->getSetting('activation', 'v3RelativePath')) { $customUrl = $settingsService->getSetting('activation', 'customUrl'); $position = strpos($src, $customUrl['pluginPath'] . 'v3/public/assets/public.'); if ($position !== false) { $src = substr($src, $position); } } else if (strpos($src, 'http://') === 0) { $src = substr($src, strpos(substr($src, 7), '/') + 7); } else if (strpos($src, 'https://') === 0) { $src = substr($src, strpos(substr($src, 8), '/') + 8); } $asyncLoading = $settingsService->getSetting('activation', 'v3AsyncLoading') ? 'async' : ''; return "<script type='module' {$asyncLoading} crossorigin src='{$src}'></script>"; case ('amelia_booking_script_vendor'): return "<link rel='modulepreload' href='{$src}'>"; default: return $tag; } } /** * @param string $tag * @param string $handle * @param string $href * * @return string */ public static function prepareStyles($tag, $handle, $href) { switch ($handle) { case ('amelia_booking_style_index'): case ('amelia_booking_style_vendor'): return "<link rel='stylesheet' href='{$href}'>"; default: return $tag; } } } WP/ShortcodeService/AmeliaShortcodeService.php 0000666 00000016141 15165376447 0015473 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Application\Services\Cache\CacheApplicationService; use AmeliaBooking\Application\Services\CustomField\CustomFieldApplicationService; use AmeliaBooking\Application\Services\Stash\StashApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use AmeliaBooking\Infrastructure\WP\Translations\FrontendStrings; /** * Class AmeliaShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class AmeliaShortcodeService { public static $counter = 0; /** * Prepare scripts and styles * @throws InvalidArgumentException * @throws \Interop\Container\Exception\ContainerException */ public static function prepareScriptsAndStyles() { $container = null; self::$counter++; if (self::$counter > 1) { return; } $settingsService = new SettingsService(new SettingsStorage()); // Enqueue Scripts if ($settingsService->getSetting('payments', 'payPal')['enabled'] === true) { wp_enqueue_script('amelia_paypal_script', 'https://www.paypalobjects.com/api/checkout.js'); } if ($settingsService->getSetting('payments', 'razorpay')['enabled'] === true) { wp_enqueue_script('amelia_razorpay_script', 'https://checkout.razorpay.com/v1/checkout.js'); } if ($settingsService->getSetting('activation', 'enablePolyfill')) { wp_enqueue_script('amelia_polyfill', 'https://polyfill.io/v2/polyfill.js?features=Intl.~locale.en'); } $gmapApiKey = $settingsService->getSetting('general', 'gMapApiKey'); if ($gmapApiKey) { wp_enqueue_script( 'amelia_google_maps_api', "https://maps.googleapis.com/maps/api/js?key={$gmapApiKey}&libraries=places" ); } // Fix for Divi theme. // Don't enqueue script if it's activated Divi Visual Page Builder if (empty($_GET['et_fb'])) { wp_enqueue_script( 'amelia_booking_scripts', AMELIA_URL . 'public/js/frontend/amelia-booking.js', [], AMELIA_VERSION, true ); } if ($settingsService->getSetting('payments', 'stripe')['enabled'] === true) { wp_enqueue_script('amelia_stripe_js', 'https://js.stripe.com/v3/'); } // Enqueue Styles wp_enqueue_style( 'amelia_booking_styles_vendor', AMELIA_URL . 'public/css/frontend/vendor.css', [], AMELIA_VERSION ); if ($settingsService->getSetting('customization', 'useGenerated') === null || $settingsService->getSetting('customization', 'useGenerated') ) { wp_enqueue_style( 'amelia_booking_styles', AMELIA_UPLOADS_URL . '/amelia/css/amelia-booking.' . $settingsService->getSetting('customization', 'hash') . '.css', [], AMELIA_VERSION ); } else { wp_enqueue_style( 'amelia_booking_styles', AMELIA_URL . 'public/css/frontend/amelia-booking-' . str_replace('.', '-', AMELIA_VERSION) . '.css', [], AMELIA_VERSION ); } // Underscore wp_enqueue_script('undescore', includes_url('js') . '/underscore.min.js'); // Strings Localization wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaLabels', FrontendStrings::getAllStrings() ); // Settings Localization wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaSettings', $settingsService->getFrontendSettings() ); $customUrl = $settingsService->getSetting('activation', 'customUrl'); wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaUrls', [ 'wpAmeliaUseUploadsAmeliaPath' => AMELIA_UPLOADS_FILES_PATH_USE, 'wpAmeliaPluginURL' => empty($customUrl['enabled']) ? AMELIA_URL : AMELIA_HOME_URL . $customUrl['pluginPath'], 'wpAmeliaPluginAjaxURL' => empty($customUrl['enabled']) ? AMELIA_ACTION_URL : AMELIA_HOME_URL . $customUrl['ajaxPath'] . '?' . AMELIA_ACTION_SLUG . '', ] ); wp_localize_script( 'amelia_booking_scripts', 'localeLanguage', [AMELIA_LOCALE] ); $localeSubstitutes = $settingsService->getSetting('general', 'calendarLocaleSubstitutes'); if (isset($localeSubstitutes[AMELIA_LOCALE])) { wp_localize_script( 'amelia_booking_scripts', 'ameliaCalendarLocale', [$localeSubstitutes[AMELIA_LOCALE]] ); } wp_localize_script( 'amelia_booking_scripts', 'fileUploadExtensions', array_keys(CustomFieldApplicationService::$allowedUploadedFileExtensions) ); if ($settingsService->getSetting('activation', 'stash') && self::$counter === 1) { $container = $container ?: require AMELIA_PATH . '/src/Infrastructure/ContainerConfig/container.php'; /** @var StashApplicationService $stashAS */ $stashAS = $container->get('application.stash.service'); wp_localize_script( 'amelia_booking_scripts', 'ameliaEntities', $stashAS->getStash() ); } if (!empty($_GET['ameliaCache']) || !empty($_GET['ameliaWcCache'])) { $container = $container ?: require AMELIA_PATH . '/src/Infrastructure/ContainerConfig/container.php'; /** @var CacheApplicationService $cacheAS */ $cacheAS = $container->get('application.cache.service'); try { $cacheData = !empty($_GET['ameliaCache']) ? $cacheAS->getCacheByName(sanitize_text_field($_GET['ameliaCache'])) : $cacheAS->getWcCacheByName(sanitize_text_field($_GET['ameliaWcCache'])); wp_localize_script( 'amelia_booking_scripts', 'ameliaCache', [$cacheData ? str_replace('"', '\\"', json_encode($cacheData)) : ''] ); } catch (QueryExecutionException $e) { } } wp_localize_script( 'amelia_booking_scripts', 'wpAmeliaTimeZone', [DateTimeService::getTimeZone()->getName()] ); do_action('ameliaScriptsLoaded'); } } WP/ShortcodeService/CatalogBookingShortcodeService.php 0000666 00000002343 15165376447 0017165 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ShortcodeService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; /** * Class CatalogBookingShortcodeService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class CatalogBookingShortcodeService extends AmeliaBookingShortcodeService { /** * @param array $params * @return string * @throws InvalidArgumentException */ public static function shortcodeHandler($params) { $params = shortcode_atts( [ 'trigger' => '', 'trigger_type' => '', 'show' => '', 'package' => null, 'category' => null, 'service' => null, 'employee' => null, 'location' => null, 'counter' => self::$counter ], $params ); self::prepareScriptsAndStyles(); ob_start(); include AMELIA_PATH . '/view/frontend/catalog-booking.inc.php'; $html = ob_get_contents(); ob_end_clean(); return $html; } } WP/UserRoles/UserRoles.php 0000666 00000002153 15165376447 0011500 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\UserRoles; /** * Class UserRoles * * @package AmeliaBooking\Infrastructure\WP */ class UserRoles { /** * @param $roles */ public static function init($roles) { /** @var array $roles */ foreach ($roles as $role) { if (!wp_roles()->is_role($role['name'])) { add_role($role['name'], $role['label'], $role['capabilities']); } } } /** * Return the current user amelia role * * @param $wpUser * @return bool|null */ public static function getUserAmeliaRole($wpUser) { if (in_array('administrator', $wpUser->roles, true) || is_super_admin($wpUser->ID)) { return 'admin'; } if (in_array('wpamelia-manager', $wpUser->roles, true)) { return 'manager'; } if (in_array('wpamelia-provider', $wpUser->roles, true)) { return 'provider'; } if (in_array('wpamelia-customer', $wpUser->roles, true)) { return 'customer'; } return null; } } WP/SettingsService/SettingsStorage.php 0000666 00000046757 15165376447 0014122 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\SettingsService; use AmeliaBooking\Application\Services\Location\CurrentLocation; use AmeliaBooking\Infrastructure\WP\Services\Location\CurrentLocationLite; use AmeliaBooking\Domain\Services\Location\CurrentLocationInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\Services\Settings\SettingsStorageInterface; /** * Class SettingsStorage * * @package AmeliaBooking\Infrastructure\WP\SettingsService */ class SettingsStorage implements SettingsStorageInterface { /** @var array|mixed */ private $settingsCache; /** @var CurrentLocationInterface */ private $locationService; private static $wpSettings = [ 'dateFormat' => 'date_format', 'timeFormat' => 'time_format', 'startOfWeek' => 'start_of_week', 'timeZoneString' => 'timezone_string', 'gmtOffset' => 'gmt_offset' ]; /** * SettingsStorage constructor. */ public function __construct() { $this->locationService = new CurrentLocationLite(); $this->settingsCache = json_decode(get_option('amelia_settings'), true); foreach (self::$wpSettings as $ameliaSetting => $wpSetting) { $this->settingsCache['wordpress'][$ameliaSetting] = get_option($wpSetting); } DateTimeService::setTimeZone($this->getAllSettings()); } /** * @param $settingCategoryKey * @param $settingKey * * @return mixed */ public function getSetting($settingCategoryKey, $settingKey) { return isset($this->settingsCache[$settingCategoryKey][$settingKey]) ? $this->settingsCache[$settingCategoryKey][$settingKey] : null; } /** * @param $settingCategoryKey * * @return mixed */ public function getCategorySettings($settingCategoryKey) { return isset($this->settingsCache[$settingCategoryKey]) ? $this->settingsCache[$settingCategoryKey] : null; } /** * @return array|mixed|null */ public function getAllSettings() { $settings = []; if (null !== $this->settingsCache) { foreach ((array)$this->settingsCache as $settingsCategoryName => $settingsCategory) { if ($settingsCategoryName !== 'daysOff') { foreach ((array)$settingsCategory as $settingName => $settingValue) { $settings[$settingName] = $settingValue; } } } return $settings; } return null; } /** * @return array|mixed|null */ public function getAllSettingsCategorized() { return isset($this->settingsCache) ? $this->settingsCache : null; } /** * Return settings for frontend * * @return array|mixed */ public function getFrontendSettings() { $phoneCountryCode = $this->getSetting('general', 'phoneDefaultCountryCode'); $capabilities = []; $additionalCapabilities = []; if (is_admin()) { $currentScreenId = get_current_screen()->id; $currentScreen = substr($currentScreenId, strrpos($currentScreenId, '-') + 1); $capabilities = [ 'canRead' => current_user_can('amelia_read_' . $currentScreen), 'canReadOthers' => current_user_can('amelia_read_others_' . $currentScreen), 'canWrite' => current_user_can('amelia_write_' . $currentScreen), 'canWriteOthers' => current_user_can('amelia_write_others_' . $currentScreen), 'canDelete' => current_user_can('amelia_delete_' . $currentScreen), 'canWriteStatus' => current_user_can('amelia_write_status_' . $currentScreen), ]; $additionalCapabilities = [ 'canWriteCustomers' => current_user_can('amelia_write_customers'), ]; } $wpUser = wp_get_current_user(); $userType = 'customer'; if (in_array('administrator', $wpUser->roles, true) || is_super_admin($wpUser->ID)) { $userType = 'admin'; } elseif (in_array('wpamelia-manager', $wpUser->roles, true)) { $userType = 'manager'; } elseif (in_array('wpamelia-provider', $wpUser->roles, true)) { $userType = 'provider'; } return [ 'capabilities' => $capabilities, 'additionalCapabilities' => $additionalCapabilities, 'daysOff' => $this->getCategorySettings('daysOff'), 'general' => [ 'itemsPerPage' => $this->getSetting('general', 'itemsPerPage'), 'appointmentsPerPage' => $this->getSetting('general', 'appointmentsPerPage'), 'servicesPerPage' => $this->getSetting('general', 'servicesPerPage'), 'customersFilterLimit' => $this->getSetting('general', 'customersFilterLimit'), 'calendarEmployeesPreselected' => $this->getSetting('general', 'calendarEmployeesPreselected'), 'phoneDefaultCountryCode' => $phoneCountryCode === 'auto' ? $this->locationService->getCurrentLocationCountryIso() : $phoneCountryCode, 'timeSlotLength' => $this->getSetting('general', 'timeSlotLength'), 'serviceDurationAsSlot' => $this->getSetting('general', 'serviceDurationAsSlot'), 'defaultAppointmentStatus' => $this->getSetting('general', 'defaultAppointmentStatus'), 'gMapApiKey' => $this->getSetting('general', 'gMapApiKey'), 'addToCalendar' => $this->getSetting('general', 'addToCalendar'), 'requiredPhoneNumberField' => $this->getSetting('general', 'requiredPhoneNumberField'), 'requiredEmailField' => $this->getSetting('general', 'requiredEmailField'), 'numberOfDaysAvailableForBooking' => $this->getSetting('general', 'numberOfDaysAvailableForBooking'), 'minimumTimeRequirementPriorToBooking' => $this->getSetting('general', 'minimumTimeRequirementPriorToBooking'), 'minimumTimeRequirementPriorToCanceling' => $this->getSetting('general', 'minimumTimeRequirementPriorToCanceling'), 'minimumTimeRequirementPriorToRescheduling' => $this->getSetting('general', 'minimumTimeRequirementPriorToRescheduling'), 'showClientTimeZone' => $this->getSetting('general', 'showClientTimeZone'), 'redirectUrlAfterAppointment' => $this->getSetting('general', 'redirectUrlAfterAppointment'), 'customFieldsUploadsPath' => $this->getSetting('general', 'customFieldsUploadsPath'), 'runInstantPostBookingActions' => $this->getSetting('general', 'runInstantPostBookingActions'), 'sortingPackages' => $this->getSetting('general', 'sortingPackages'), 'backLink' => $this->getSetting('general', 'backLink'), 'sortingServices' => $this->getSetting('general', 'sortingServices'), 'googleRecaptcha' => [ 'enabled' => $this->getSetting('general', 'googleRecaptcha')['enabled'], 'invisible' => $this->getSetting('general', 'googleRecaptcha')['invisible'], 'siteKey' => $this->getSetting('general', 'googleRecaptcha')['siteKey'], ], 'usedLanguages' => $this->getSetting('general', 'usedLanguages'), ], 'googleCalendar' => !AMELIA_LITE_VERSION && $this->getSetting('googleCalendar', 'clientID') && $this->getSetting('googleCalendar', 'clientSecret'), 'outlookCalendar' => !AMELIA_LITE_VERSION && $this->getSetting('outlookCalendar', 'clientID') && $this->getSetting('outlookCalendar', 'clientSecret'), 'zoom' => [ 'enabled' => !AMELIA_LITE_VERSION && ( $this->getSetting('zoom', 'enabled') && $this->getSetting('zoom', 's2sEnabled') ? ( $this->getSetting('zoom', 'accountId') && $this->getSetting('zoom', 'clientId') && $this->getSetting('zoom', 'clientSecret') ) : ( $this->getSetting('zoom', 'apiKey') && $this->getSetting('zoom', 'apiSecret') ) ) ], 'facebookPixel' => $this->getCategorySettings('facebookPixel'), 'googleTag' => $this->getCategorySettings('googleTag'), 'lessonSpace' => [ 'enabled' => $this->getSetting('lessonSpace', 'enabled') && $this->getSetting('lessonSpace', 'apiKey') ], 'notifications' => [ 'senderName' => $this->getSetting('notifications', 'senderName'), 'senderEmail' => $this->getSetting('notifications', 'senderEmail'), 'notifyCustomers' => $this->getSetting('notifications', 'notifyCustomers'), 'sendAllCF' => $this->getSetting('notifications', 'sendAllCF'), 'cancelSuccessUrl' => $this->getSetting('notifications', 'cancelSuccessUrl'), 'cancelErrorUrl' => $this->getSetting('notifications', 'cancelErrorUrl'), 'smsSignedIn' => $this->getSetting('notifications', 'smsSignedIn'), 'bccEmail' => $this->getSetting('notifications', 'bccEmail'), 'bccSms' => $this->getSetting('notifications', 'bccSms'), 'whatsAppPhoneID' => $this->getSetting('notifications', 'whatsAppPhoneID'), 'whatsAppAccessToken' => $this->getSetting('notifications', 'whatsAppAccessToken'), 'whatsAppBusinessID' => $this->getSetting('notifications', 'whatsAppBusinessID'), 'whatsAppLanguage' => $this->getSetting('notifications', 'whatsAppLanguage'), 'whatsAppEnabled' => $this->getSetting('notifications', 'whatsAppEnabled'), ], 'payments' => [ 'currency' => $this->getSetting('payments', 'symbol'), 'currencyCode' => $this->getSetting('payments', 'currency'), 'priceSymbolPosition' => $this->getSetting('payments', 'priceSymbolPosition'), 'priceNumberOfDecimals' => $this->getSetting('payments', 'priceNumberOfDecimals'), 'priceSeparator' => $this->getSetting('payments', 'priceSeparator'), 'hideCurrencySymbolFrontend' => $this->getSetting('payments', 'hideCurrencySymbolFrontend'), 'defaultPaymentMethod' => $this->getSetting('payments', 'defaultPaymentMethod'), 'onSite' => $this->getSetting('payments', 'onSite'), 'coupons' => $this->getSetting('payments', 'coupons'), 'paymentLinks' => [ 'enabled' => $this->getSetting('payments', 'paymentLinks')['enabled'], 'changeBookingStatus' => $this->getSetting('payments', 'paymentLinks')['changeBookingStatus'], 'redirectUrl' => $this->getSetting('payments', 'paymentLinks')['redirectUrl'] ], 'payPal' => [ 'enabled' => $this->getSetting('payments', 'payPal')['enabled'], 'sandboxMode' => $this->getSetting('payments', 'payPal')['sandboxMode'], 'testApiClientId' => $this->getSetting('payments', 'payPal')['testApiClientId'], 'liveApiClientId' => $this->getSetting('payments', 'payPal')['liveApiClientId'], ], 'stripe' => [ 'enabled' => $this->getSetting('payments', 'stripe')['enabled'], 'testMode' => $this->getSetting('payments', 'stripe')['testMode'], 'livePublishableKey' => $this->getSetting('payments', 'stripe')['livePublishableKey'], 'testPublishableKey' => $this->getSetting('payments', 'stripe')['testPublishableKey'] ], 'wc' => [ 'enabled' => $this->getSetting('payments', 'wc')['enabled'], 'productId' => $this->getSetting('payments', 'wc')['productId'], 'page' => $this->getSetting('payments', 'wc')['page'], 'onSiteIfFree' => $this->getSetting('payments', 'wc')['onSiteIfFree'] ], 'mollie' => [ 'enabled' => $this->getSetting('payments', 'mollie')['enabled'], ], 'razorpay' => [ 'enabled' => $this->getSetting('payments', 'razorpay')['enabled'], ], ], 'role' => $userType, 'weekSchedule' => $this->getCategorySettings('weekSchedule'), 'wordpress' => [ 'dateFormat' => $this->getSetting('wordpress', 'dateFormat'), 'timeFormat' => $this->getSetting('wordpress', 'timeFormat'), 'startOfWeek' => (int)$this->getSetting('wordpress', 'startOfWeek'), 'timezone' => $this->getSetting('wordpress', 'timeZoneString'), 'locale' => get_locale() ], 'labels' => [ 'enabled' => $this->getSetting('labels', 'enabled') ], 'activation' => [ 'enableAmeliaQAPromoBanner' => $this->getSetting('activation', 'enableAmeliaQAPromoBanner'), 'enableAmeliaPromoBanner' => $this->getSetting('activation', 'enableAmeliaPromoBanner'), 'showAmeliaPromoCustomizePopup' => $this->getSetting('activation', 'showAmeliaPromoCustomizePopup'), 'showActivationSettings' => $this->getSetting('activation', 'showActivationSettings'), 'stash' => $this->getSetting('activation', 'stash'), 'disableUrlParams' => $this->getSetting('activation', 'disableUrlParams'), ], 'roles' => [ 'allowAdminBookAtAnyTime' => $this->getSetting('roles', 'allowAdminBookAtAnyTime'), 'allowConfigureSchedule' => $this->getSetting('roles', 'allowConfigureSchedule'), 'allowConfigureDaysOff' => $this->getSetting('roles', 'allowConfigureDaysOff'), 'allowConfigureSpecialDays' => $this->getSetting('roles', 'allowConfigureSpecialDays'), 'allowConfigureServices' => $this->getSetting('roles', 'allowConfigureServices'), 'allowWriteAppointments' => $this->getSetting('roles', 'allowWriteAppointments'), 'automaticallyCreateCustomer' => $this->getSetting('roles', 'automaticallyCreateCustomer'), 'inspectCustomerInfo' => $this->getSetting('roles', 'inspectCustomerInfo'), 'allowCustomerReschedule' => $this->getSetting('roles', 'allowCustomerReschedule'), 'allowCustomerCancelPackages' => $this->getSetting('roles', 'allowCustomerCancelPackages'), 'allowCustomerDeleteProfile' => $this->getSetting('roles', 'allowCustomerDeleteProfile'), 'allowWriteEvents' => $this->getSetting('roles', 'allowWriteEvents'), 'customerCabinet' => [ 'enabled' => $this->getSetting('roles', 'customerCabinet')['enabled'], 'loginEnabled' => $this->getSetting('roles', 'customerCabinet')['loginEnabled'], 'tokenValidTime' => $this->getSetting('roles', 'customerCabinet')['tokenValidTime'], 'pageUrl' => $this->getSetting('roles', 'customerCabinet')['pageUrl'], ], 'providerCabinet' => [ 'enabled' => $this->getSetting('roles', 'providerCabinet')['enabled'], 'loginEnabled' => $this->getSetting('roles', 'providerCabinet')['loginEnabled'], 'tokenValidTime' => $this->getSetting('roles', 'providerCabinet')['tokenValidTime'], ], 'limitPerCustomerService' => $this->getSetting('roles', 'limitPerCustomerService'), 'limitPerCustomerPackage' => $this->getSetting('roles', 'limitPerCustomerPackage'), 'limitPerCustomerEvent' => $this->getSetting('roles', 'limitPerCustomerEvent'), ], 'customization' => $this->getCategorySettings('customization'), 'customizedData' => $this->getCategorySettings('customizedData'), 'appointments' => $this->getCategorySettings('appointments'), 'slotDateConstraints' => [ 'minDate' => DateTimeService::getNowDateTimeObject() ->modify("+{$this->getSetting('general', 'minimumTimeRequirementPriorToBooking')} seconds") ->format('Y-m-d H:i:s'), 'maxDate' => DateTimeService::getNowDateTimeObject() ->modify("+{$this->getSetting('general', 'numberOfDaysAvailableForBooking')} day") ->format('Y-m-d H:i:s') ], 'company' => [ 'email' => $this->getSetting('company', 'email'), 'phone' => $this->getSetting('company', 'phone'), ] ]; } /** * @param $settingCategoryKey * @param $settingKey * @param $settingValue * * @return mixed|void */ public function setSetting($settingCategoryKey, $settingKey, $settingValue) { $this->settingsCache[$settingCategoryKey][$settingKey] = $settingValue; $settingsCopy = $this->settingsCache; unset($settingsCopy['wordpress']); update_option('amelia_settings', json_encode($settingsCopy)); } /** * @param $settingCategoryKey * @param $settingValues * * @return mixed|void */ public function setCategorySettings($settingCategoryKey, $settingValues) { $this->settingsCache[$settingCategoryKey] = $settingValues; $settingsCopy = $this->settingsCache; unset($settingsCopy['wordpress']); update_option('amelia_settings', json_encode($settingsCopy)); } /** * @param array $settings * * @return mixed|void */ public function setAllSettings($settings) { foreach ($settings as $settingCategoryKey => $settingValues) { $this->settingsCache[$settingCategoryKey] = $settingValues; } $settingsCopy = $this->settingsCache; unset($settingsCopy['wordpress']); update_option('amelia_settings', json_encode($settingsCopy)); } } WP/config/Database.php 0000666 00000001776 15165376447 0010615 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\config; use InvalidArgumentException; /** * Class Database * * @package AmeliaBooking\Infrastructure\WP\config */ class Database { private $database; private $username; private $password; private $host; private $charset; private $collate; /** * Database constructor. */ public function __construct() { $this->database = DB_NAME; $this->username = DB_USER; $this->password = DB_PASSWORD; $this->host = DB_HOST ? DB_HOST : 'localhost'; $this->charset = DB_CHARSET; $this->collate = DB_COLLATE; } /**\ * @param $property * * @return mixed * @throws \InvalidArgumentException */ public function __invoke($property) { if (!isset($this->$property)) { throw new InvalidArgumentException( "Property \"{$property}\" does not exists. " ); } return $this->$property; } } WP/config/Menu.php 0000666 00000013200 15165376447 0007776 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\config; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class Menu */ class Menu { /** @var SettingsService $settingsService */ private $settingsService; /** * Menu constructor. * * @param SettingsService $settingsService */ public function __construct(SettingsService $settingsService) { $this->settingsService = $settingsService; } /** * @return array */ public function __invoke() { $defaultPageOnBackend = $this->settingsService->getSetting( 'general', 'defaultPageOnBackend' ); $defaultPages = [ [ 'parentSlug' => 'amelia', 'pageTitle' => 'Dashboard', 'menuTitle' => BackendStrings::getDashboardStrings()['dashboard'], 'capability' => 'amelia_read_dashboard', 'menuSlug' => 'wpamelia-dashboard', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Calendar', 'menuTitle' => BackendStrings::getCalendarStrings()['calendar'], 'capability' => 'amelia_read_calendar', 'menuSlug' => 'wpamelia-calendar', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Appointments', 'menuTitle' => BackendStrings::getCommonStrings()['appointments'], 'capability' => 'amelia_read_appointments', 'menuSlug' => 'wpamelia-appointments', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Events', 'menuTitle' => BackendStrings::getCommonStrings()['events'], 'capability' => 'amelia_read_events', 'menuSlug' => 'wpamelia-events', ] ]; $defaultPageKey = array_search($defaultPageOnBackend, array_column($defaultPages, 'pageTitle'), true); $defaultPageElement = array_splice($defaultPages, $defaultPageKey, 1); return array_merge( $defaultPageElement, $defaultPages, [ !AMELIA_LITE_VERSION ? [ 'parentSlug' => 'amelia', 'pageTitle' => 'Employees', 'menuTitle' => BackendStrings::getCommonStrings()['employees'], 'capability' => 'amelia_read_employees', 'menuSlug' => 'wpamelia-employees', ] : [], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Services', 'menuTitle' => BackendStrings::getCommonStrings()['services'], 'capability' => 'amelia_read_services', 'menuSlug' => 'wpamelia-services', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Locations', 'menuTitle' => BackendStrings::getCommonStrings()['locations'], 'capability' => 'amelia_read_locations', 'menuSlug' => 'wpamelia-locations', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Customers', 'menuTitle' => BackendStrings::getCustomerStrings()['customers'], 'capability' => 'amelia_read_customers', 'menuSlug' => 'wpamelia-customers', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Finance', 'menuTitle' => BackendStrings::getPaymentStrings()['finance'], 'capability' => 'amelia_read_finance', 'menuSlug' => 'wpamelia-finance', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Notifications', 'menuTitle' => BackendStrings::getNotificationsStrings()['notifications'], 'capability' => 'amelia_read_notifications', 'menuSlug' => 'wpamelia-notifications', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Customize', 'menuTitle' => BackendStrings::getCustomizeStrings()['customize'], 'capability' => 'amelia_read_customize', 'menuSlug' => 'wpamelia-customize', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Customize New', 'menuTitle' => BackendStrings::getCustomizeStrings()['customize'] . ' New', 'capability' => 'amelia_read_customize', 'menuSlug' => 'wpamelia-customize-new', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Custom Fields', 'menuTitle' => BackendStrings::getCustomizeStrings()['custom_fields'], 'capability' => 'amelia_read_customize', 'menuSlug' => 'wpamelia-cf', ], [ 'parentSlug' => 'amelia', 'pageTitle' => 'Settings', 'menuTitle' => BackendStrings::getSettingsStrings()['settings'], 'capability' => 'amelia_read_settings', 'menuSlug' => 'wpamelia-settings', ], ] ); } } WP/config/Roles.php 0000666 00000017470 15165376447 0010173 0 ustar 00 <?php /** * @author Alexander Gilmanov * Defining the user roles and capabilities */ namespace AmeliaBooking\Infrastructure\WP\config; /** * Class Roles * * @package AmeliaBooking\Infrastructure\WP\config */ class Roles { /** * Array of all Amelia roles capabilities * * @var array */ public static $rolesList = [ 'amelia_read_menu', 'amelia_read_dashboard', 'amelia_read_calendar', 'amelia_read_appointments', 'amelia_read_events', 'amelia_read_employees', 'amelia_read_services', 'amelia_read_packages', 'amelia_read_locations', 'amelia_read_coupons', 'amelia_read_customers', 'amelia_read_finance', 'amelia_read_notifications', 'amelia_read_customize', 'amelia_read_custom_fields', 'amelia_read_settings', 'amelia_read_others_settings', 'amelia_read_others_dashboard', 'amelia_read_others_calendar', 'amelia_read_others_appointments', 'amelia_read_others_services', 'amelia_read_others_employees', 'amelia_read_others_customers', 'amelia_write_dashboard', 'amelia_write_calendar', 'amelia_write_appointments', 'amelia_write_events', 'amelia_write_employees', 'amelia_write_services', 'amelia_write_packages', 'amelia_write_locations', 'amelia_write_coupons', 'amelia_write_customers', 'amelia_write_finance', 'amelia_write_notifications', 'amelia_write_customize', 'amelia_write_custom_fields', 'amelia_write_settings', 'amelia_write_status', 'amelia_write_others_settings', 'amelia_write_others_calendar', 'amelia_write_others_appointments', 'amelia_write_others_services', 'amelia_write_others_employees', 'amelia_write_others_events', 'amelia_write_others_finance', 'amelia_write_others_dashboard', 'amelia_delete_dashboard', 'amelia_delete_calendar', 'amelia_delete_appointments', 'amelia_delete_events', 'amelia_delete_employees', 'amelia_delete_services', 'amelia_delete_packages', 'amelia_delete_locations', 'amelia_delete_coupons', 'amelia_delete_customers', 'amelia_delete_finance', 'amelia_delete_notifications', 'amelia_delete_customize', 'amelia_delete_custom_fields', 'amelia_delete_settings', 'amelia_write_status_appointments', 'amelia_write_status_events', 'amelia_write_time_appointments', ]; /** * Array of all amelia roles with capabilities * * @return array */ public function __invoke() { return [ // Customer [ 'name' => 'wpamelia-customer', 'label' => __('Amelia Customer', 'amelia'), 'capabilities' => [ 'read' => true, 'amelia_read_menu' => true, 'amelia_read_calendar' => true, 'amelia_read_appointments' => true, 'amelia_read_events' => true, 'amelia_write_time_appointments' => true, ] ], // Provider [ 'name' => 'wpamelia-provider', 'label' => __('Amelia Employee', 'amelia'), 'capabilities' => [ 'read' => true, 'amelia_delete_events' => true, 'amelia_read_menu' => true, 'amelia_read_calendar' => true, 'amelia_read_appointments' => true, 'amelia_read_events' => true, 'amelia_read_employees' => true, 'amelia_read_others_customers' => true, 'amelia_read_others_services' => false, 'amelia_write_employees' => true, 'amelia_write_status_appointments' => true, 'amelia_write_status_events' => true, 'amelia_write_time_appointments' => true, 'amelia_write_others_appointments' => false, 'amelia_write_others_services' => false, 'amelia_write_appointments' => true, 'amelia_write_events' => true, 'amelia_write_others_events' => false, ] ], // Manager [ 'name' => 'wpamelia-manager', 'label' => __('Amelia Manager', 'amelia'), 'capabilities' => [ 'read' => true, 'amelia_delete_events' => true, 'amelia_read_menu' => true, 'amelia_read_dashboard' => true, 'amelia_read_calendar' => true, 'amelia_read_appointments' => true, 'amelia_read_events' => true, 'amelia_read_employees' => true, 'amelia_read_services' => true, 'amelia_read_resources' => true, 'amelia_read_packages' => true, 'amelia_read_locations' => true, 'amelia_read_coupons' => true, 'amelia_read_customers' => true, 'amelia_read_finance' => true, 'amelia_read_notifications' => true, 'amelia_read_others_dashboard' => true, 'amelia_read_others_calendar' => true, 'amelia_read_others_appointments' => true, 'amelia_read_others_services' => true, 'amelia_read_others_employees' => true, 'amelia_read_others_customers' => true, 'amelia_write_dashboard' => true, 'amelia_write_calendar' => true, 'amelia_write_appointments' => true, 'amelia_write_events' => true, 'amelia_write_employees' => true, 'amelia_write_services' => true, 'amelia_write_resources' => true, 'amelia_write_packages' => true, 'amelia_write_locations' => true, 'amelia_write_coupons' => true, 'amelia_write_customers' => true, 'amelia_write_finance' => true, 'amelia_write_notifications' => true, 'amelia_write_others_calendar' => true, 'amelia_write_others_appointments' => true, 'amelia_write_others_services' => true, 'amelia_write_others_employees' => true, 'amelia_write_others_events' => true, 'amelia_write_others_finance' => true, 'amelia_write_others_dashboard' => true, 'amelia_write_status_appointments' => true, 'amelia_write_status_events' => true, 'amelia_write_time_appointments' => true, 'upload_files' => true, ] ], ]; } } WP/EventListeners/Booking/Appointment/AppointmentEventsListener.php 0000666 00000013460 15165376447 0021666 0 ustar 00 <?php /** * Handle WP part of appointment-related events */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\WP\Integrations\ThriveAutomator\ThriveAutomatorService; use League\Event\ListenerInterface; use League\Event\EventInterface; /** * Class AppointmentEventsListener * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class AppointmentEventsListener implements ListenerInterface { /** @var Container */ private $container; /** * AppointmentEventsListener constructor. * * @param Container $container */ public function __construct($container) { $this->container = $container; } /** * Check if provided argument is the listener * * @param mixed $listener * * @return bool */ public function isListener($listener) { return $listener === $this; } /** * @param EventInterface $event * @param CommandResult|null $param * * @throws \Slim\Exception\ContainerValueNotFoundException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException * @throws \Interop\Container\Exception\ContainerException * @throws \Exception * @throws \Exception */ public function handle(EventInterface $event, $param = null) { // Handling the events if ($param->getResult() !== 'error') { if (!AMELIA_LITE_VERSION) { ThriveAutomatorService::initItems(); } switch ($event->getName()) { case 'AppointmentAdded': AppointmentAddedEventHandler::handle($param, $this->container); break; case 'AppointmentDeleted': foreach (["appointment", "event", "booking"] as $type) { if (isset($param->getData()[$type]) && in_array($param->getData()[$type]["status"], ["canceled", "rejected", "deleted"]) ) { return; } } AppointmentDeletedEventHandler::handle($param, $this->container); break; case 'AppointmentEdited': AppointmentEditedEventHandler::handle($param, $this->container); break; case 'AppointmentStatusUpdated': foreach (["appointment", "event", "booking"] as $type) { if (AMELIA_LITE_VERSION && isset($param->getData()[$type]) && in_array($param->getData()[$type]["status"], ["canceled", "rejected", "deleted"]) ) { return; } } AppointmentStatusUpdatedEventHandler::handle($param, $this->container); break; case 'BookingTimeUpdated': if (!AMELIA_LITE_VERSION) { AppointmentTimeUpdatedEventHandler::handle($param, $this->container); } break; case 'BookingAdded': do_action('AmeliaBookingAddedBeforeNotify', $param->getData(), $this->container); BookingAddedEventHandler::handle($param, $this->container); break; case 'BookingCanceled': foreach (["appointment", "event", "booking"] as $type) { if (AMELIA_LITE_VERSION && isset($param->getData()[$type]) && in_array($param->getData()[$type]["status"], ["canceled", "rejected", "deleted"]) ) { return; } } BookingCanceledEventHandler::handle($param, $this->container); break; case 'BookingEdited': BookingEditedEventHandler::handle($param, $this->container); break; case 'BookingReassigned': BookingReassignedEventHandler::handle($param, $this->container); break; case 'BookingDeleted': if ($param->getData()['appointmentDeleted']) { AppointmentDeletedEventHandler::handle($param, $this->container); } else if ($param->getData()['bookingDeleted']) { AppointmentEditedEventHandler::handle($param, $this->container); } break; case 'PackageCustomerUpdated': PackageCustomerUpdatedEventHandler::handle($param, $this->container); break; case 'PackageCustomerAdded': PackageCustomerAddedEventHandler::handle($param, $this->container); break; case 'PackageCustomerDeleted': $appointmentUpdatedResult = new CommandResult(); foreach ($param->getData()['appointments']['updatedAppointments'] as $item) { $appointmentUpdatedResult->setData($item); AppointmentEditedEventHandler::handle($appointmentUpdatedResult, $this->container); } PackageCustomerDeletedEventHandler::handle($param, $this->container); break; } } } } WP/EventListeners/Booking/Appointment/PackageCustomerDeletedEventHandler.php 0000666 00000007610 15165376447 0023341 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageRepository; use AmeliaBooking\Infrastructure\Repository\User\CustomerRepository; use Exception; use Slim\Exception\ContainerValueNotFoundException; /** * Class PackageCustomerDeletedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class PackageCustomerDeletedEventHandler { /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws InvalidArgumentException * @throws QueryExecutionException * @throws Exception */ public static function handle($commandResult, $container) { /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var PackageRepository $packageRepository */ $packageRepository = $container->get('domain.bookable.package.repository'); /** @var CustomerRepository $customerRepository */ $customerRepository = $container->get('domain.users.customers.repository'); /** @var Package $package */ $package = $packageRepository->getById($commandResult->getData()['packageCustomer']['packageId']); /** @var AbstractUser $customer */ $customer = $customerRepository->getById($commandResult->getData()['packageCustomer']['customerId']); $packageReservation = array_merge( array_merge( $package->toArray(), [ 'status' => 'canceled', 'customer' => $customer->toArray(), 'icsFiles' => [], 'packageCustomerId' => $commandResult->getData()['packageCustomer']['packageId'], 'isRetry' => null, 'recurring' => array_merge( $commandResult->getData()['appointments']['updatedAppointments'], $commandResult->getData()['appointments']['deletedAppointments'] ) ] ) ); $emailNotificationService->sendPackageNotifications($packageReservation, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendPackageNotifications($packageReservation, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendPackageNotifications($packageReservation, true); } } } WP/EventListeners/Booking/Appointment/PackageCustomerUpdatedEventHandler.php 0000666 00000016042 15165376447 0023360 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Entity\Bookable\Service\PackageCustomerService; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Booking\Appointment\CustomerBooking; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Entity\User\Customer; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageCustomerServiceRepository; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageRepository; use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\AppointmentRepository; use AmeliaBooking\Infrastructure\Repository\User\CustomerRepository; use Exception; use Slim\Exception\ContainerValueNotFoundException; /** * Class PackageCustomerUpdatedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class PackageCustomerUpdatedEventHandler { /** @var string */ const PACKAGE_CANCELED = 'packageCanceled'; /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws InvalidArgumentException * @throws QueryExecutionException * @throws Exception */ public static function handle($commandResult, $container) { /** @var AppointmentRepository $appointmentRepository */ $appointmentRepository = $container->get('domain.booking.appointment.repository'); /** @var PackageCustomerServiceRepository $packageCustomerServiceRepository */ $packageCustomerServiceRepository = $container->get('domain.bookable.packageCustomerService.repository'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var PackageRepository $packageRepository */ $packageRepository = $container->get('domain.bookable.package.repository'); /** @var Collection $packageCustomerServices */ $packageCustomerServices = $packageCustomerServiceRepository->getByCriteria( [ 'packagesCustomers' => [$commandResult->getData()['packageCustomerId']] ] ); if ($packageCustomerServices->length()) { /** @var PackageCustomerService $packageCustomerService */ $packageCustomerService = $packageCustomerServices->getItem($packageCustomerServices->keys()[0]); /** @var CustomerRepository $customerRepository */ $customerRepository = $container->get('domain.users.customers.repository'); /** @var Customer $customer */ $customer = $customerRepository->getById( $packageCustomerService->getPackageCustomer()->getCustomerId()->getValue() ); /** @var Package $package */ $package = $packageRepository->getById( $packageCustomerService->getPackageCustomer()->getPackageId()->getValue() ); /** @var Collection $appointments */ $appointments = $appointmentRepository->getFiltered( [ 'packageCustomerId' => $commandResult->getData()['packageCustomerId'] ] ); $packageReservationData = []; /** @var Appointment $appointment */ foreach ($appointments->getItems() as $appointment) { /** @var CustomerBooking $customerBooking */ foreach ($appointment->getBookings()->getItems() as $customerBooking) { if ($customerBooking->getPackageCustomerService() && in_array( $customerBooking->getPackageCustomerService()->getId()->getValue(), $packageCustomerServices->keys(), false ) ) { $packageReservationData[] = [ 'type' => Entities::APPOINTMENT, Entities::APPOINTMENT => $appointment->toArray(), Entities::BOOKING => $customerBooking->toArray(), 'appointmentStatusChanged' => false, ]; break; } } } $packageReservation = array_merge( array_merge( $package->toArray(), [ 'status' => $commandResult->getData()['status'] === 'approved' ? 'purchased' : $commandResult->getData()['status'], 'customer' => $customer->toArray(), 'icsFiles' => [], 'packageCustomerId' => $commandResult->getData()['packageCustomerId'], 'isRetry' => null, 'recurring' => $packageReservationData ] ) ); $emailNotificationService->sendPackageNotifications($packageReservation, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendPackageNotifications($packageReservation, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendPackageNotifications($packageReservation, true); } $webHookService->process(self::PACKAGE_CANCELED, $packageReservation, null); } } } WP/EventListeners/Booking/Appointment/AppointmentAddedEventHandler.php 0000666 00000025617 15165376447 0022224 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Booking\IcsApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use Interop\Container\Exception\ContainerException; /** * Class AppointmentAddedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class AppointmentAddedEventHandler { /** @var string */ const APPOINTMENT_ADDED = 'appointmentAdded'; /** @var string */ const BOOKING_ADDED = 'bookingAdded'; /** * @param CommandResult $commandResult * @param Container $container * * @throws NotFoundException * @throws QueryExecutionException * @throws ContainerException * @throws InvalidArgumentException */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var PaymentApplicationService $paymentAS */ $paymentAS = $container->get('application.payment.service'); $recurringData = $commandResult->getData()['recurring']; $appointment = $commandResult->getData()[Entities::APPOINTMENT]; $appointmentObject = AppointmentFactory::create($appointment); $bookingApplicationService->setReservationEntities($appointmentObject); $pastAppointment = $appointmentObject->getBookingStart()->getValue() < DateTimeService::getNowDateTimeObject(); if ($zoomService && !$pastAppointment) { $zoomService->handleAppointmentMeeting($appointmentObject, self::APPOINTMENT_ADDED); if ($appointmentObject->getZoomMeeting()) { $appointment['zoomMeeting'] = $appointmentObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService && !$pastAppointment) { $lessonSpaceService->handle($appointmentObject, Entities::APPOINTMENT); if ($appointmentObject->getLessonSpace()) { $appointment['lessonSpace'] = $appointmentObject->getLessonSpace(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($appointmentObject, self::APPOINTMENT_ADDED); } catch (\Exception $e) { } if ($appointmentObject->getGoogleCalendarEventId() !== null) { $appointment['googleCalendarEventId'] = $appointmentObject->getGoogleCalendarEventId()->getValue(); } if ($appointmentObject->getGoogleMeetUrl() !== null) { $appointment['googleMeetUrl'] = $appointmentObject->getGoogleMeetUrl(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($appointmentObject, self::APPOINTMENT_ADDED); } catch (\Exception $e) { } if ($appointmentObject->getOutlookCalendarEventId() !== null) { $appointment['outlookCalendarEventId'] = $appointmentObject->getOutlookCalendarEventId()->getValue(); } } foreach ($recurringData as $key => $recurringReservationData) { $recurringReservationObject = AppointmentFactory::create($recurringReservationData[Entities::APPOINTMENT]); $bookingApplicationService->setReservationEntities($recurringReservationObject); if ($zoomService && !$pastAppointment) { $zoomService->handleAppointmentMeeting($recurringReservationObject, self::BOOKING_ADDED); if ($recurringReservationObject->getZoomMeeting()) { $recurringData[$key][Entities::APPOINTMENT]['zoomMeeting'] = $recurringReservationObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService && !$pastAppointment) { $lessonSpaceService->handle($recurringReservationObject, Entities::APPOINTMENT); if ($recurringReservationObject->getLessonSpace()) { $recurringData[$key][Entities::APPOINTMENT]['lessonSpace'] = $recurringReservationObject->getLessonSpace(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($recurringReservationObject, self::BOOKING_ADDED); } catch (\Exception $e) { } if ($recurringReservationObject->getGoogleCalendarEventId() !== null) { $recurringData[$key][Entities::APPOINTMENT]['googleCalendarEventId'] = $recurringReservationObject->getGoogleCalendarEventId()->getValue(); } if ($recurringReservationObject->getGoogleMeetUrl() !== null) { $recurringData[$key][Entities::APPOINTMENT]['googleMeetUrl'] = $recurringReservationObject->getGoogleMeetUrl(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($recurringReservationObject, self::BOOKING_ADDED); } catch (\Exception $e) { } if ($recurringReservationObject->getOutlookCalendarEventId() !== null) { $recurringData[$key][Entities::APPOINTMENT]['outlookCalendarEventId'] = $recurringReservationObject->getOutlookCalendarEventId()->getValue(); } } } $appointment['recurring'] = $recurringData; if (!$pastAppointment) { /** @var IcsApplicationService $icsService */ $icsService = $container->get('application.ics.service'); $recurringIds = []; foreach ($appointment['recurring'] as $recurringAppointment) { foreach ($recurringAppointment[Entities::APPOINTMENT]['bookings'] as $booking) { $recurringIds[] = $booking['id']; } } foreach ($appointment['bookings'] as $index => $booking) { if ($booking['status'] === BookingStatus::APPROVED || $booking['status'] === BookingStatus::PENDING) { $appointment['bookings'][$index]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $booking['id'], $recurringIds, true ); $paymentId = $booking['payments'][0]['id']; $data = [ 'booking' => $booking, 'type' => Entities::APPOINTMENT, 'appointment' => $appointmentObject->toArray(), 'paymentId' => $paymentId, 'bookable' => $appointmentObject->getService()->toArray(), 'customer' => $booking['customer'] ]; if (!empty($paymentId)) { $appointment['bookings'][$index]['payments'][0]['paymentLinks'] = $paymentAS->createPaymentLink($data, $index); } } } $emailNotificationService->sendAppointmentStatusNotifications($appointment, false, true, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($appointment, false, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($appointment, false, true); } } if ($webHookService) { $webHookService->process(self::BOOKING_ADDED, $appointment, $appointment['bookings']); foreach ($recurringData as $key => $recurringReservationData) { $webHookService->process( self::BOOKING_ADDED, $recurringReservationData[Entities::APPOINTMENT], $recurringReservationData[Entities::APPOINTMENT]['bookings'] ); } } } } WP/EventListeners/Booking/Appointment/BookingAddedEventHandler.php 0000666 00000056751 15165376447 0021321 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Booking\IcsApplicationService; use AmeliaBooking\Application\Services\Helper\HelperService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Domain\Services\Payment\PaymentServiceInterface; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\BooleanValueObject; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageRepository; use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\CustomerBookingRepository; use AmeliaBooking\Infrastructure\Repository\Coupon\CouponRepository; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use AmeliaBooking\Infrastructure\Repository\Payment\PaymentRepository; use Exception; use Interop\Container\Exception\ContainerException; use Slim\Exception\ContainerValueNotFoundException; /** * Class BookingAddedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class BookingAddedEventHandler { /** @var string */ const BOOKING_ADDED = 'bookingAdded'; /** @var string */ const PACKAGE_PURCHASED = 'packagePurchased'; /** * @param CommandResult $commandResult * @param Container $container * * @throws NotFoundException * @throws InvalidArgumentException * @throws ContainerValueNotFoundException * @throws QueryExecutionException * @throws ContainerException * @throws Exception */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var PaymentRepository $paymentRepository */ $paymentRepository = $container->get('domain.payment.repository'); /** @var CustomerBookingRepository $bookingRepository */ $bookingRepository = $container->get('domain.booking.customerBooking.repository'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var PaymentApplicationService $paymentAS */ $paymentAS = $container->get('application.payment.service'); /** @var SettingsService $settingsDS */ $settingsDS = $container->get('domain.settings.service'); $type = $commandResult->getData()['type']; $booking = $commandResult->getData()[Entities::BOOKING]; $appointmentStatusChanged = $commandResult->getData()['appointmentStatusChanged']; $paymentId = $commandResult->getData()['paymentId']; if (!empty($booking['couponId']) && empty($booking['coupon'])) { /** @var CouponRepository $couponRepository */ $couponRepository = $container->get('domain.coupon.repository'); $coupon = $couponRepository->getById($booking['couponId']); if ($coupon) { $booking['coupon'] = $coupon->toArray(); unset($booking['coupon']['serviceList']); unset($booking['coupon']['eventList']); unset($booking['coupon']['packageList']); } } $recurringData = $commandResult->getData()['recurring']; if ($commandResult->getData()['packageId']) { /** @var PackageRepository $packageRepository */ $packageRepository = $container->get('domain.bookable.package.repository'); /** @var Package $package */ $package = $packageRepository->getById($commandResult->getData()['packageId']); $packageReservation = array_merge( array_merge($package->toArray(), ['customer' => $commandResult->getData()['customer']]), [ 'status' => 'purchased', 'packageCustomerId' => !empty($commandResult->getData()['packageCustomerId']) ? $commandResult->getData()['packageCustomerId'] : null, 'isRetry' => !empty($commandResult->getData()['isRetry']) ? $commandResult->getData()['isRetry'] : null, 'recurring' => [] ] ); if (!empty($paymentId) && empty($commandResult->getData()['fromLink'])) { $data = $commandResult->getData(); $data['booking'] = $booking; $data['type'] = Entities::PACKAGE; $data['package'] = $package->toArray(); $data['bookable'] = $package->toArray(); $data['packageReservations'] = $booking === null ? [] : array_merge([$data['appointment']], array_column($data['recurring'], 'appointment')); $packageReservation['paymentLinks'] = $paymentAS->createPaymentLink($data); } if ($booking === null) { $emailNotificationService->sendPackageNotifications($packageReservation, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendPackageNotifications($packageReservation, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendPackageNotifications($packageReservation, true); } /** @var HelperService $helperService */ $helperService = $container->get('application.helper.service'); $packageReservation['customer']['customerPanelUrl'] = $helperService->getCustomerCabinetUrl( $packageReservation['customer']['email'], 'email', null, null, '' ); $webHookService->process(self::PACKAGE_PURCHASED, $packageReservation, null); if (!empty($paymentId)) { $paymentRepository->updateFieldById($paymentId, 1, 'actionsCompleted'); } return; } } $booking['isLastBooking'] = true; /** @var Appointment|Event $reservationObject */ $reservationObject = null; if ($type === Entities::APPOINTMENT) { $reservationObject = AppointmentFactory::create($commandResult->getData()[$type]); } if ($type === Entities::EVENT) { $reservationObject = EventFactory::create($commandResult->getData()[$type]); } $reservation = $reservationObject->toArray(); $reservation['isRetry'] = !empty($commandResult->getData()['isRetry']) ? $commandResult->getData()['isRetry'] : false; $data = $commandResult->getData(); $data['booking'] = $booking; if ($type === Entities::APPOINTMENT) { $bookingApplicationService->setReservationEntities($reservationObject); $data['bookable'] = $reservationObject->getService()->toArray(); } else { $data['bookable'] = $reservationObject->toArray(); } $currentBookingIndex = 0; foreach ($reservation['bookings'] as $index => $reservationBooking) { if ($booking['id'] === $reservationBooking['id']) { $reservation['bookings'][$index]['isLastBooking'] = true; $reservationObject->getBookings()->getItem($index)->setLastBooking(new BooleanValueObject(true)); $currentBookingIndex = $index; if (!empty($paymentId) && !$commandResult->getData()['packageId'] && empty($commandResult->getData()['fromLink'])) { $reservation['bookings'][$index]['payments'][0]['paymentLinks'] = $paymentAS->createPaymentLink($data, $index); } } } if ($type === Entities::APPOINTMENT) { $reservation['provider'] = $reservationObject->getProvider()->toArray(); if ($zoomService) { $zoomService->handleAppointmentMeeting($reservationObject, self::BOOKING_ADDED); if ($reservationObject->getZoomMeeting()) { $reservation['zoomMeeting'] = $reservationObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService) { $lessonSpaceService->handle($reservationObject, Entities::APPOINTMENT, null, $booking); if ($reservationObject->getLessonSpace()) { $reservation['lessonSpace'] = $reservationObject->getLessonSpace(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($reservationObject, self::BOOKING_ADDED); } catch (Exception $e) { } if ($reservationObject->getGoogleCalendarEventId() !== null) { $reservation['googleCalendarEventId'] = $reservationObject->getGoogleCalendarEventId()->getValue(); } } if ($reservationObject->getGoogleMeetUrl() !== null) { $reservation['googleMeetUrl'] = $reservationObject->getGoogleMeetUrl(); } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($reservationObject, self::BOOKING_ADDED); } catch (Exception $e) { } if ($reservationObject->getOutlookCalendarEventId() !== null) { $reservation['outlookCalendarEventId'] = $reservationObject->getOutlookCalendarEventId()->getValue(); } } } if ($type === Entities::EVENT) { if ($zoomService) { $zoomService->handleEventMeeting( $reservationObject, $reservationObject->getPeriods(), self::BOOKING_ADDED ); $reservation['periods'] = $reservationObject->getPeriods()->toArray(); } if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($reservationObject, self::BOOKING_ADDED, $reservationObject->getPeriods()); } catch (Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($reservationObject, self::BOOKING_ADDED, $reservationObject->getPeriods()); } catch (Exception $e) { } } } foreach ($recurringData as $key => $recurringReservationData) { $recurringReservationObject = AppointmentFactory::create($recurringReservationData[$type]); $bookingApplicationService->setReservationEntities($recurringReservationObject); $recurringData[$key][$type]['provider'] = $recurringReservationObject->getProvider()->toArray(); if ($zoomService) { $zoomService->handleAppointmentMeeting($recurringReservationObject, self::BOOKING_ADDED); if ($recurringReservationObject->getZoomMeeting()) { $recurringData[$key][$type]['zoomMeeting'] = $recurringReservationObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService) { $lessonSpaceService->handle($recurringReservationObject, Entities::APPOINTMENT); if ($recurringReservationObject->getLessonSpace()) { $recurringData[$key][Entities::APPOINTMENT]['lessonSpace'] = $recurringReservationObject->getLessonSpace(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($recurringReservationObject, self::BOOKING_ADDED); } catch (Exception $e) { } if ($recurringReservationObject->getGoogleCalendarEventId() !== null) { $recurringData[$key][$type]['googleCalendarEventId'] = $recurringReservationObject->getGoogleCalendarEventId()->getValue(); } if ($recurringReservationObject->getGoogleMeetUrl() !== null) { $recurringData[$key][$type]['googleMeetUrl'] = $recurringReservationObject->getGoogleMeetUrl(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($recurringReservationObject, self::BOOKING_ADDED); } catch (Exception $e) { } if ($recurringReservationObject->getOutlookCalendarEventId() !== null) { $recurringData[$key][$type]['outlookCalendarEventId'] = $recurringReservationObject->getOutlookCalendarEventId()->getValue(); } } if (!$commandResult->getData()['packageId'] && empty($commandResult->getData()['fromLink'])) { $dataRecurring = $recurringReservationData; $dataRecurring['bookable'] = $data['bookable']; $dataRecurring['customer'] = $data['customer']; $dataRecurring['recurring'] = array_column($recurringData, 'appointment'); $recurringData[$key][$type]['bookings'][$currentBookingIndex]['payments'][0]['paymentLinks'] = $paymentAS->createPaymentLink($dataRecurring, $currentBookingIndex, $key); } } /** @var IcsApplicationService $icsService */ $icsService = $container->get('application.ics.service'); $recurringBookingIds = []; $icsFiles = []; foreach ($recurringData as $recurringReservation) { $recurringBookingIds[] = $recurringReservation[Entities::BOOKING]['id']; } foreach ($reservation['bookings'] as $index => $reservationBooking) { if ($reservationBooking['id'] === $booking['id'] && ($booking['status'] === BookingStatus::APPROVED || $booking['status'] === BookingStatus::PENDING)) { $icsFiles = $icsService->getIcsData( $type, $booking['id'], $recurringBookingIds, true ); $reservation['bookings'][$index]['icsFiles'] = $icsFiles; } } $reservation['recurring'] = $recurringData; if ($appointmentStatusChanged === true && !$commandResult->getData()['packageId']) { foreach ($reservation['bookings'] as $bookingKey => $bookingArray) { if ($bookingArray['id'] !== $booking['id'] && $bookingArray['status'] === BookingStatus::APPROVED && $reservation['status'] === BookingStatus::APPROVED ) { $reservation['bookings'][$bookingKey]['isChangedStatus'] = true; } } } if ($appointmentStatusChanged === true && !$commandResult->getData()['packageId']) { $emailNotificationService->sendAppointmentStatusNotifications($reservation, empty($commandResult->getData()['fromLink']), true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($reservation, empty($commandResult->getData()['fromLink']), true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($reservation, empty($commandResult->getData()['fromLink']), true); } } if ($appointmentStatusChanged !== true && !$commandResult->getData()['packageId']) { $emailNotificationService->sendBookingAddedNotifications($reservation, $booking, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendBookingAddedNotifications($reservation, $booking, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendBookingAddedNotifications($reservation, $booking, true); } } if ($commandResult->getData()['packageId']) { $packageReservation = array_merge( $packageReservation, [ 'icsFiles' => $icsFiles, 'recurring' => array_merge( [ [ 'type' => Entities::APPOINTMENT, Entities::APPOINTMENT => $reservation, Entities::BOOKING => $booking, 'appointmentStatusChanged' => $appointmentStatusChanged, ] ], $reservation['recurring'] ) ] ); $emailNotificationService->sendPackageNotifications($packageReservation, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendPackageNotifications($packageReservation, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendPackageNotifications($packageReservation, true); } } foreach ($recurringData as $key => $recurringReservationData) { if ($recurringReservationData['appointmentStatusChanged'] === true) { foreach ($recurringData[$key][$type]['bookings'] as $bookingKey => $recurringReservationBooking) { if ($recurringReservationBooking['customerId'] === $booking['customerId']) { $recurringData[$key][$type]['bookings'][$bookingKey]['skipNotification'] = true; } if ($recurringReservationBooking['id'] !== $booking['id'] && $recurringReservationBooking['status'] === BookingStatus::APPROVED && $recurringData[$key][$type]['status'] === BookingStatus::APPROVED ) { $recurringData[$key][$type]['bookings'][$bookingKey]['isChangedStatus'] = true; } } $emailNotificationService->sendAppointmentStatusNotifications( $recurringData[$key][$type], true, true ); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications( $recurringData[$key][$type], true, true ); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications( $recurringData[$key][$type], true, true ); } } } if ($webHookService) { $webHookService->process( self::BOOKING_ADDED, $reservation, [ array_merge( $booking, [ 'isRecurringBooking' => $recurringData && !$commandResult->getData()['packageId'], 'isPackageBooking' => !!$commandResult->getData()['packageId'], ] ) ] ); foreach ($recurringData as $key => $recurringReservationData) { $webHookService->process( self::BOOKING_ADDED, $recurringReservationData[$type], [ array_merge( $recurringReservationData['booking'], [ 'isRecurringBooking' => !$commandResult->getData()['packageId'], 'isPackageBooking' => !!$commandResult->getData()['packageId'], ] ) ] ); $bookingRepository->updateFieldById($recurringReservationData['booking']['id'], 1, 'actionsCompleted'); } } if (!empty($commandResult->getData()['paymentId'])) { $paymentRepository->updateFieldById($commandResult->getData()['paymentId'], 1, 'actionsCompleted'); } if (!empty($booking['id'])) { $bookingRepository->updateFieldById($booking['id'], 1, 'actionsCompleted'); } } } WP/EventListeners/Booking/Appointment/BookingReassignedEventHandler.php 0000666 00000045241 15165376447 0022374 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Booking\IcsApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use Exception; use Interop\Container\Exception\ContainerException; use Slim\Exception\ContainerValueNotFoundException; /** * Class BookingReassignedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class BookingReassignedEventHandler { /** @var string */ const TIME_UPDATED = 'bookingTimeUpdated'; /** @var string */ const APPOINTMENT_DELETED = 'appointmentDeleted'; /** @var string */ const APPOINTMENT_ADDED = 'appointmentAdded'; /** @var string */ const BOOKING_ADDED = 'bookingAdded'; /** @var string */ const BOOKING_CANCELED = 'bookingCanceled'; /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws NotFoundException * @throws QueryExecutionException * @throws ContainerException * @throws InvalidArgumentException * @throws Exception */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var IcsApplicationService $icsService */ $icsService = $container->get('application.ics.service'); $booking = $commandResult->getData()['booking']; $booking['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $booking['id'], [], true ); $oldAppointment = $commandResult->getData()['oldAppointment']; $oldAppointmentStatusChanged = $commandResult->getData()['oldAppointmentStatusChanged']; /** @var Appointment $oldAppointmentObject */ $oldAppointmentObject = AppointmentFactory::create($oldAppointment); $bookingApplicationService->setReservationEntities($oldAppointmentObject); $newAppointment = $commandResult->getData()['newAppointment']; /** @var Appointment $newAppointmentObject */ $newAppointmentObject = null; if ($newAppointment !== null) { $newAppointmentObject = AppointmentFactory::create($newAppointment); $bookingApplicationService->setReservationEntities($newAppointmentObject); } $existingAppointment = $commandResult->getData()['existingAppointment']; $existingAppointmentStatusChanged = $commandResult->getData()['existingAppointmentStatusChanged']; /** @var Appointment $existingAppointmentObject */ $existingAppointmentObject = null; if ($existingAppointment !== null) { $existingAppointmentObject = AppointmentFactory::create($existingAppointment); $bookingApplicationService->setReservationEntities($existingAppointmentObject); } // appointment is rescheduled if ($existingAppointment === null && $newAppointment === null) { foreach ($oldAppointment['bookings'] as $bookingKey => $bookingArray) { if ($booking['id'] === $bookingArray['id'] && ($bookingArray['status'] === BookingStatus::APPROVED || $bookingArray['status'] === BookingStatus::PENDING)) { $oldAppointment['bookings'][$bookingKey]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $bookingArray['id'], [], true ); } } if ($zoomService) { $zoomService->handleAppointmentMeeting($oldAppointmentObject, self::TIME_UPDATED); if ($oldAppointmentObject->getZoomMeeting()) { $oldAppointment['zoomMeeting'] = $oldAppointmentObject->getZoomMeeting()->toArray(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($oldAppointmentObject, self::TIME_UPDATED); } catch (Exception $e) { } if ($oldAppointmentObject->getGoogleCalendarEventId() !== null) { $oldAppointment['googleCalendarEventId'] = $oldAppointmentObject->getGoogleCalendarEventId()->getValue(); } if ($oldAppointmentObject->getGoogleMeetUrl() !== null) { $oldAppointment['googleMeetUrl'] = $oldAppointmentObject->getGoogleMeetUrl(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($oldAppointmentObject, self::TIME_UPDATED); } catch (Exception $e) { } if ($oldAppointmentObject->getOutlookCalendarEventId() !== null) { $oldAppointment['outlookCalendarEventId'] = $oldAppointmentObject->getOutlookCalendarEventId()->getValue(); } } $oldAppointment['initialAppointmentDateTime'] = $commandResult->getData()['initialAppointmentDateTime']; $emailNotificationService->sendAppointmentRescheduleNotifications($oldAppointment); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentRescheduleNotifications($oldAppointment); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentRescheduleNotifications($oldAppointment); } if ($webHookService) { $webHookService->process(self::TIME_UPDATED, $oldAppointment, []); } } // old appointment got status changed to Cancelled because booking is rescheduled to new OR existing appointment if ($oldAppointmentObject->getStatus()->getValue() === BookingStatus::CANCELED) { if ($zoomService) { $zoomService->handleAppointmentMeeting($oldAppointmentObject, self::APPOINTMENT_DELETED); if ($oldAppointmentObject->getZoomMeeting()) { $oldAppointment['zoomMeeting'] = $oldAppointmentObject->getZoomMeeting()->toArray(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($oldAppointmentObject, self::APPOINTMENT_DELETED); } catch (\Exception $e) { } if ($oldAppointmentObject->getGoogleCalendarEventId() !== null) { $oldAppointment['googleCalendarEventId'] = $oldAppointmentObject->getGoogleCalendarEventId()->getValue(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($oldAppointmentObject, self::APPOINTMENT_DELETED); } catch (\Exception $e) { } if ($oldAppointmentObject->getOutlookCalendarEventId() !== null) { $oldAppointment['outlookCalendarEventId'] = $oldAppointmentObject->getOutlookCalendarEventId()->getValue(); } } } // booking is rescheduled to new OR existing appointment if (($newAppointment !== null || $existingAppointment !== null) && $oldAppointmentObject->getStatus()->getValue() !== BookingStatus::CANCELED ) { if ($zoomService) { if ($oldAppointmentObject->getZoomMeeting()) { $oldAppointment['zoomMeeting'] = $oldAppointmentObject->getZoomMeeting()->toArray(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($oldAppointmentObject, self::BOOKING_CANCELED); } catch (\Exception $e) { } if ($oldAppointmentObject->getGoogleCalendarEventId() !== null) { $oldAppointment['googleCalendarEventId'] = $oldAppointmentObject->getGoogleCalendarEventId()->getValue(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($oldAppointmentObject, self::BOOKING_CANCELED); } catch (\Exception $e) { } if ($oldAppointmentObject->getOutlookCalendarEventId() !== null) { $oldAppointment['outlookCalendarEventId'] = $oldAppointmentObject->getOutlookCalendarEventId()->getValue(); } } if ($oldAppointmentStatusChanged) { foreach ($oldAppointment['bookings'] as $bookingKey => $bookingArray) { if ($bookingArray['status'] === BookingStatus::APPROVED || $bookingArray['status'] === BookingStatus::PENDING) { $oldAppointment['bookings'][$bookingKey]['isChangedStatus'] = true; if ($booking['id'] === $bookingArray['id']) { $oldAppointment['bookings'][$bookingKey]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $bookingArray['id'], [], true ); } } } $emailNotificationService->sendAppointmentStatusNotifications($oldAppointment, true, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($oldAppointment, true, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($oldAppointment, true, true); } } } if ($newAppointment !== null) { if ($zoomService) { $zoomService->handleAppointmentMeeting($newAppointmentObject, self::APPOINTMENT_ADDED); if ($newAppointmentObject->getZoomMeeting()) { $newAppointment['zoomMeeting'] = $newAppointmentObject->getZoomMeeting()->toArray(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($newAppointmentObject, self::APPOINTMENT_ADDED); } catch (\Exception $e) { } if ($newAppointmentObject->getGoogleCalendarEventId() !== null) { $newAppointment['googleCalendarEventId'] = $newAppointmentObject->getGoogleCalendarEventId()->getValue(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($newAppointmentObject, self::APPOINTMENT_ADDED); } catch (\Exception $e) { } if ($newAppointmentObject->getOutlookCalendarEventId() !== null) { $newAppointment['outlookCalendarEventId'] = $newAppointmentObject->getOutlookCalendarEventId()->getValue(); } } foreach ($newAppointment['bookings'] as $bookingKey => $bookingArray) { if ($booking['id'] === $bookingArray['id'] && ($bookingArray['status'] === BookingStatus::APPROVED || $bookingArray['status'] === BookingStatus::PENDING)) { $newAppointment['bookings'][$bookingKey]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $bookingArray['id'], [], true ); } } $newAppointment['initialAppointmentDateTime'] = $commandResult->getData()['initialAppointmentDateTime']; $emailNotificationService->sendAppointmentRescheduleNotifications($newAppointment); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentRescheduleNotifications($newAppointment); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentRescheduleNotifications($newAppointment); } if ($webHookService) { $webHookService->process(self::TIME_UPDATED, $newAppointment, []); } } else if ($existingAppointment !== null) { if ($zoomService) { $zoomService->handleAppointmentMeeting($existingAppointmentObject, self::BOOKING_ADDED); if ($existingAppointmentObject->getZoomMeeting()) { $existingAppointment['zoomMeeting'] = $existingAppointmentObject->getZoomMeeting()->toArray(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($existingAppointmentObject, self::BOOKING_ADDED); } catch (Exception $e) { } if ($existingAppointmentObject->getGoogleCalendarEventId() !== null) { $existingAppointment['googleCalendarEventId'] = $existingAppointmentObject->getGoogleCalendarEventId()->getValue(); } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($existingAppointmentObject, self::BOOKING_ADDED); } catch (Exception $e) { } if ($existingAppointmentObject->getOutlookCalendarEventId() !== null) { $existingAppointment['outlookCalendarEventId'] = $existingAppointmentObject->getOutlookCalendarEventId()->getValue(); } } $booking['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $booking['id'], [], true ); $existingAppointment['initialAppointmentDateTime'] = $commandResult->getData()['initialAppointmentDateTime']; $emailNotificationService->sendAppointmentRescheduleNotifications( array_merge( $existingAppointment, ['bookings' => [$booking]] ) ); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentRescheduleNotifications( array_merge( $existingAppointment, ['bookings' => [$booking]] ) ); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentRescheduleNotifications( array_merge( $existingAppointment, ['bookings' => [$booking]] ) ); } if ($existingAppointmentStatusChanged) { foreach ($existingAppointment['bookings'] as $bookingKey => $bookingArray) { if ($bookingArray['status'] === BookingStatus::APPROVED && $existingAppointment['status'] === BookingStatus::APPROVED && $bookingArray['id'] !== $booking['id'] ) { $existingAppointment['bookings'][$bookingKey]['isChangedStatus'] = true; } } $emailNotificationService->sendAppointmentStatusNotifications($existingAppointment, true, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($existingAppointment, true, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($existingAppointment, true, true); } } } } } WP/EventListeners/Booking/Appointment/BookingEditedEventHandler.php 0000666 00000014357 15165376447 0021512 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Repository\Booking\Event\EventRepository; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use AmeliaPHPMailer\PHPMailer\Exception; /** * Class BookingEditedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class BookingEditedEventHandler { /** @var string */ const BOOKING_STATUS_UPDATED = 'bookingStatusUpdated'; /** @var string */ const BOOKING_CANCELED = 'bookingCanceled'; /** @var string */ const BOOKING_ADDED = 'bookingAdded'; /** * @param CommandResult $commandResult * @param Container $container * * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws \Slim\Exception\ContainerValueNotFoundException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException * @throws \Interop\Container\Exception\ContainerException * @throws \Exception */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var PaymentApplicationService $paymentAS */ $paymentAS = $container->get('application.payment.service'); $appointment = $commandResult->getData()[$commandResult->getData()['type']]; $booking = $commandResult->getData()[Entities::BOOKING]; $bookingStatusChanged = $commandResult->getData()['bookingStatusChanged']; if ($bookingStatusChanged) { /** @var EventRepository $eventRepository */ $eventRepository = $container->get('domain.booking.event.repository'); $reservationObject = $eventRepository->getById($appointment['id']); if ($commandResult->getData()['createPaymentLinks']) { $paymentId = $booking['payments'][0]['id']; $paymentData = [ 'booking' => $booking, 'type' => Entities::EVENT, 'event' => $appointment, 'paymentId' => $paymentId, 'bookable' => $reservationObject->toArray(), 'customer' => $booking['customer'] ]; $bookingIndex = array_search($booking['id'], array_column($appointment['bookings'], 'id')); if ($bookingIndex !== false && !empty($paymentId)) { $appointment['bookings'][$bookingIndex]['payments'][0]['paymentLinks'] = $paymentAS->createPaymentLink($paymentData, $bookingIndex); } } if ($googleCalendarService) { if ($booking['status'] === BookingStatus::APPROVED) { $googleCalendarService->handleEventPeriodsChange($reservationObject, self::BOOKING_ADDED, $reservationObject->getPeriods()); } else if ($booking['status'] === BookingStatus::CANCELED || $booking['status'] === BookingStatus::REJECTED) { $googleCalendarService->handleEventPeriodsChange($reservationObject, self::BOOKING_CANCELED, $reservationObject->getPeriods()); } } if ($outlookCalendarService) { if ($booking['status'] === BookingStatus::APPROVED) { $outlookCalendarService->handleEventPeriod($reservationObject, self::BOOKING_ADDED, $reservationObject->getPeriods()); } else if ($booking['status'] === BookingStatus::CANCELED || $booking['status'] === BookingStatus::REJECTED) { $outlookCalendarService->handleEventPeriod($reservationObject, self::BOOKING_CANCELED, $reservationObject->getPeriods()); } } $emailNotificationService->sendCustomerBookingNotification($appointment, $booking); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendCustomerBookingNotification($appointment, $booking); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendCustomerBookingNotification($appointment, $booking); } if ($webHookService) { $webHookService->process(self::BOOKING_STATUS_UPDATED, $appointment, [$booking]); } } } } WP/EventListeners/Booking/Appointment/AppointmentStatusUpdatedEventHandler.php 0000666 00000017227 15165376447 0024013 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Booking\IcsApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use Exception; use Interop\Container\Exception\ContainerException; use Slim\Exception\ContainerValueNotFoundException; /** * Class AppointmentStatusUpdatedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class AppointmentStatusUpdatedEventHandler { /** @var string */ const APPOINTMENT_STATUS_UPDATED = 'appointmentStatusUpdated'; /** @var string */ const BOOKING_STATUS_UPDATED = 'bookingStatusUpdated'; /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws InvalidArgumentException * @throws NotFoundException * @throws QueryExecutionException * @throws ContainerException * @throws Exception */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); $appointment = $commandResult->getData()[Entities::APPOINTMENT]; $oldStatus = $commandResult->getData()['oldStatus']; /** @var Appointment|Event $reservationObject */ $reservationObject = AppointmentFactory::create($appointment); $bookingApplicationService->setReservationEntities($reservationObject); if ($zoomService) { $zoomService->handleAppointmentMeeting($reservationObject, self::APPOINTMENT_STATUS_UPDATED); if ($reservationObject->getZoomMeeting()) { $appointment['zoomMeeting'] = $reservationObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService) { $lessonSpaceService->handle($reservationObject, Entities::APPOINTMENT); if ($reservationObject->getLessonSpace()) { $appointment['lessonSpace'] = $reservationObject->getLessonSpace(); } } $bookings = $commandResult->getData()['bookingsWithChangedStatus']; if ($appointment['status'] !== BookingStatus::NO_SHOW) { if ($googleCalendarService) { try { $googleCalendarService->handleEvent($reservationObject, self::APPOINTMENT_STATUS_UPDATED); } catch (Exception $e) { } } if ($reservationObject->getGoogleCalendarEventId() !== null) { $appointment['googleCalendarEventId'] = $reservationObject->getGoogleCalendarEventId()->getValue(); } if ($reservationObject->getGoogleMeetUrl() !== null) { $appointment['googleMeetUrl'] = $reservationObject->getGoogleMeetUrl(); } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($reservationObject, self::APPOINTMENT_STATUS_UPDATED, $oldStatus); } catch (Exception $e) { } } if ($reservationObject->getOutlookCalendarEventId() !== null) { $appointment['outlookCalendarEventId'] = $reservationObject->getOutlookCalendarEventId()->getValue(); } } // if appointment approved add ics file to bookings if ($appointment['status'] === BookingStatus::APPROVED || $appointment['status'] === BookingStatus::PENDING) { /** @var IcsApplicationService $icsService */ $icsService = $container->get('application.ics.service'); foreach ($appointment['bookings'] as $index => $booking) { if ($appointment['bookings'][$index]['isChangedStatus'] === true) { $appointment['bookings'][$index]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $booking['id'], [], true ); } } } $emailNotificationService->sendAppointmentStatusNotifications($appointment, false, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($appointment, false, true); } if ($whatsAppNotificationService && $whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($appointment, false, true); } if ($webHookService && $bookings) { if ($appointment['status'] === BookingStatus::CANCELED) { $webHookService->process(BookingCanceledEventHandler::BOOKING_CANCELED, $appointment, $bookings); } else { $webHookService->process(self::BOOKING_STATUS_UPDATED, $appointment, $bookings); } } } } WP/EventListeners/Booking/Appointment/PackageCustomerAddedEventHandler.php 0000666 00000015107 15165376447 0022774 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Helper\HelperService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Entity\Bookable\Service\PackageCustomerService; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Booking\Appointment\CustomerBooking; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Entity\User\Customer; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageCustomerServiceRepository; use AmeliaBooking\Infrastructure\Repository\Bookable\Service\PackageRepository; use AmeliaBooking\Infrastructure\Repository\Booking\Appointment\AppointmentRepository; use AmeliaBooking\Infrastructure\Repository\User\CustomerRepository; use Exception; use Slim\Exception\ContainerValueNotFoundException; /** * Class PackageCustomerAddedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class PackageCustomerAddedEventHandler { /** @var string */ const PACKAGE_PURCHASED = 'packagePurchased'; /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws InvalidArgumentException * @throws QueryExecutionException * @throws Exception */ public static function handle($commandResult, $container) { /** @var PackageCustomerServiceRepository $packageCustomerServiceRepository */ $packageCustomerServiceRepository = $container->get('domain.bookable.packageCustomerService.repository'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var PackageRepository $packageRepository */ $packageRepository = $container->get('domain.bookable.package.repository'); /** @var Collection $packageCustomerServices */ $packageCustomerServices = $packageCustomerServiceRepository->getByCriteria( [ 'packagesCustomers' => [$commandResult->getData()['packageCustomerId']] ] ); /** @var SettingsService $settingsDS */ $settingsDS = $container->get('domain.settings.service'); /** @var PaymentApplicationService $paymentAS */ $paymentAS = $container->get('application.payment.service'); if ($packageCustomerServices->length()) { /** @var PackageCustomerService $packageCustomerService */ $packageCustomerService = $packageCustomerServices->getItem($packageCustomerServices->keys()[0]); /** @var CustomerRepository $customerRepository */ $customerRepository = $container->get('domain.users.customers.repository'); /** @var Customer $customer */ $customer = $customerRepository->getById( $packageCustomerService->getPackageCustomer()->getCustomerId()->getValue() ); /** @var Package $package */ $package = $packageRepository->getById( $packageCustomerService->getPackageCustomer()->getPackageId()->getValue() ); $packageReservation = array_merge( array_merge( $package->toArray(), [ 'status' => 'purchased', 'customer' => $customer->toArray(), 'icsFiles' => [], 'packageCustomerId' => $commandResult->getData()['packageCustomerId'], 'isRetry' => null, 'recurring' => [] ] ), [] ); $paymentId = $commandResult->getData()['paymentId']; if (!empty($paymentId)) { $data = [ 'type' => Entities::PACKAGE, 'package' => $package->toArray(), 'bookable' => $package->toArray(), 'packageReservations' => [], 'customer' => $customer->toArray(), 'paymentId' => $paymentId, 'packageCustomerId' => $commandResult->getData()['packageCustomerId'], 'booking' => null ]; $packageReservation['paymentLinks'] = $paymentAS->createPaymentLink($data); } $packageReservation['onlyOneEmployee'] = $commandResult->getData()['onlyOneEmployee']; $emailNotificationService->sendPackageNotifications($packageReservation, true, $commandResult->getData()['notify']); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendPackageNotifications($packageReservation, true, $commandResult->getData()['notify']); } /** @var HelperService $helperService */ $helperService = $container->get('application.helper.service'); $packageReservation['customer']['customerPanelUrl'] = $helperService->getCustomerCabinetUrl( $packageReservation['customer']['email'], 'email', null, null, '' ); $webHookService->process(self::PACKAGE_PURCHASED, $packageReservation, null); } } } WP/EventListeners/Booking/Appointment/AppointmentEditedEventHandler.php 0000666 00000040275 15165376447 0022416 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Booking\IcsApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Booking\Appointment\CustomerBooking; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\Number\Integer\Id; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use Exception; use Interop\Container\Exception\ContainerException; use Slim\Exception\ContainerValueNotFoundException; /** * Class AppointmentEditedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class AppointmentEditedEventHandler { /** @var string */ const APPOINTMENT_EDITED = 'appointmentEdited'; /** @var string */ const APPOINTMENT_ADDED = 'appointmentAdded'; /** @var string */ const APPOINTMENT_DELETED = 'appointmentDeleted'; /** @var string */ const APPOINTMENT_STATUS_AND_TIME_UPDATED = 'appointmentStatusAndTimeUpdated'; /** @var string */ const TIME_UPDATED = 'bookingTimeUpdated'; /** @var string */ const BOOKING_STATUS_UPDATED = 'bookingStatusUpdated'; /** @var string */ const ZOOM_USER_CHANGED = 'zoomUserChanged'; /** @var string */ const ZOOM_LICENCED_USER_CHANGED = 'zoomLicencedUserChanged'; /** @var string */ const APPOINTMENT_STATUS_AND_ZOOM_LICENCED_USER_CHANGED = 'appointmentStatusAndZoomLicencedUserChanged'; /** @var string */ const BOOKING_ADDED = 'bookingAdded'; /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws NotFoundException * @throws QueryExecutionException * @throws ContainerException * @throws InvalidArgumentException * @throws Exception */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); /** @var PaymentApplicationService $paymentAS */ $paymentAS = $container->get('application.payment.service'); $appointment = $commandResult->getData()[Entities::APPOINTMENT]; $bookings = $commandResult->getData()['bookingsWithChangedStatus']; $appointmentStatusChanged = $commandResult->getData()['appointmentStatusChanged']; $appointmentRescheduled = $commandResult->getData()['appointmentRescheduled']; $appointmentEmployeeChanged = $commandResult->getData()['appointmentEmployeeChanged']; $appointmentZoomUserChanged = $commandResult->getData()['appointmentZoomUserChanged']; $bookingAdded = $commandResult->getData()['bookingAdded']; $appointmentZoomUsersLicenced = $commandResult->getData()['appointmentZoomUsersLicenced']; $createPaymentLinks = $commandResult->getData()['createPaymentLinks']; /** @var Appointment $reservationObject */ $reservationObject = AppointmentFactory::create($appointment); $bookingApplicationService->setReservationEntities($reservationObject); /** @var CustomerBooking $bookingObject */ foreach ($reservationObject->getBookings()->getItems() as $bookingObject) { foreach ($appointment['bookings'] as $index => $bookingArray) { if ($bookingArray['id'] === $bookingObject->getId()->getValue()) { $appointment['bookings'][$index]['customer'] = $bookingObject->getCustomer()->toArray(); } } } if ($zoomService) { $commandSlug = self::APPOINTMENT_EDITED; if ($appointmentEmployeeChanged && $appointmentZoomUserChanged && $appointmentZoomUsersLicenced && $appointmentStatusChanged) { $commandSlug = self::APPOINTMENT_STATUS_AND_ZOOM_LICENCED_USER_CHANGED; } elseif ($appointmentEmployeeChanged && $appointmentZoomUserChanged && $appointmentZoomUsersLicenced) { $commandSlug = self::ZOOM_LICENCED_USER_CHANGED; } elseif ($appointmentEmployeeChanged && $appointmentZoomUserChanged) { $commandSlug = self::ZOOM_USER_CHANGED; } elseif ($appointmentStatusChanged && $appointmentRescheduled) { $commandSlug = self::APPOINTMENT_STATUS_AND_TIME_UPDATED; } elseif ($appointmentStatusChanged) { $commandSlug = self::BOOKING_STATUS_UPDATED; } elseif ($appointmentRescheduled) { $commandSlug = self::TIME_UPDATED; } if ($commandSlug || !$reservationObject->getZoomMeeting()) { $zoomService->handleAppointmentMeeting($reservationObject, $commandSlug); } if ($reservationObject->getZoomMeeting()) { $appointment['zoomMeeting'] = $reservationObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService) { $lessonSpaceService->handle($reservationObject, Entities::APPOINTMENT); if ($reservationObject->getLessonSpace()) { $appointment['lessonSpace'] = $reservationObject->getLessonSpace(); } } if ($googleCalendarService && !$appointmentEmployeeChanged && $reservationObject->getProvider()) { try { $googleCalendarService->handleEvent($reservationObject, self::APPOINTMENT_EDITED); } catch (Exception $e) { } } elseif ($googleCalendarService) { $newProviderId = $reservationObject->getProviderId()->getValue(); $reservationObject->setProviderId(new Id($appointmentEmployeeChanged)); try { $googleCalendarService->handleEvent($reservationObject, self::APPOINTMENT_DELETED); } catch (Exception $e) { } $reservationObject->setGoogleCalendarEventId(null); $reservationObject->setProviderId(new Id($newProviderId)); try { $googleCalendarService->handleEvent($reservationObject, self::APPOINTMENT_ADDED); } catch (Exception $e) { } } if ($reservationObject->getGoogleCalendarEventId() !== null) { $appointment['googleCalendarEventId'] = $reservationObject->getGoogleCalendarEventId()->getValue(); } if ($reservationObject->getGoogleMeetUrl() !== null) { $appointment['googleMeetUrl'] = $reservationObject->getGoogleMeetUrl(); } if ($outlookCalendarService && !$appointmentEmployeeChanged && $reservationObject->getProvider()) { try { $outlookCalendarService->handleEvent($reservationObject, self::APPOINTMENT_EDITED); } catch (Exception $e) { } } elseif ($outlookCalendarService) { $newProviderId = $reservationObject->getProviderId()->getValue(); $reservationObject->setProviderId(new Id($appointmentEmployeeChanged)); try { $outlookCalendarService->handleEvent($reservationObject, self::APPOINTMENT_DELETED); } catch (Exception $e) { } $reservationObject->setOutlookCalendarEventId(null); $reservationObject->setProviderId(new Id($newProviderId)); try { $outlookCalendarService->handleEvent($reservationObject, self::APPOINTMENT_ADDED); } catch (Exception $e) { } } if ($reservationObject->getOutlookCalendarEventId() !== null) { $appointment['outlookCalendarEventId'] = $reservationObject->getOutlookCalendarEventId()->getValue(); } foreach ($appointment['bookings'] as $index => $booking) { $newBookingKey = array_search($booking['id'], array_column($bookings, 'id'), true); if ($createPaymentLinks || $newBookingKey !== false) { $paymentId = $booking['payments'][0]['id']; $data = [ 'booking' => $booking, 'type' => Entities::APPOINTMENT, 'appointment' => $appointment, 'paymentId' => $paymentId, 'bookable' => $reservationObject->getService()->toArray(), 'customer' => $booking['customer'] ]; if (!empty($paymentId)) { $paymentLinks = $paymentAS->createPaymentLink($data, $index); $appointment['bookings'][$index]['payments'][0]['paymentLinks'] = $paymentLinks; if ($newBookingKey !== false) { $bookings[$newBookingKey]['payments'][0]['paymentLinks'] = $paymentLinks; } } } } if ($appointmentStatusChanged === true) { $emailNotificationService->sendAppointmentStatusNotifications($appointment, true, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($appointment, true, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($appointment, true, true); } } /** @var IcsApplicationService $icsService */ $icsService = $container->get('application.ics.service'); $appointment['initialAppointmentDateTime'] = $commandResult->getData()['initialAppointmentDateTime']; $appointment['employee_changed'] = $appointmentEmployeeChanged; if ($appointmentRescheduled === true) { foreach ($appointment['bookings'] as $index => $booking) { if ($booking['status'] === BookingStatus::APPROVED || $booking['status'] === BookingStatus::PENDING) { $appointment['bookings'][$index]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $booking['id'], [], true ); } } if (!AMELIA_LITE_VERSION) { $emailNotificationService->sendAppointmentRescheduleNotifications($appointment); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentRescheduleNotifications($appointment); } } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentRescheduleNotifications($appointment); } } // check bookings with changed status for ICS files if ($bookings) { foreach ($bookings as $index => $booking) { if ($booking['status'] === BookingStatus::APPROVED || $booking['status'] === BookingStatus::PENDING) { $bookings[$index]['icsFiles'] = $icsService->getIcsData( Entities::APPOINTMENT, $booking['id'], [], true ); } } } if (!$appointmentRescheduled || !empty($appointment['employee_changed'])) { $emailNotificationService->sendAppointmentEditedNotifications( $appointment, $bookings, $appointmentStatusChanged ); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService ->sendAppointmentEditedNotifications($appointment, $bookings, $appointmentStatusChanged); } if ($whatsAppNotificationService && $whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentEditedNotifications($appointment, $bookings, $appointmentStatusChanged); } if (!$appointmentStatusChanged) { $emailNotificationService->sendAppointmentUpdatedNotifications( $appointment, $appointmentRescheduled ); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService ->sendAppointmentUpdatedNotifications($appointment, $appointmentRescheduled); } if ($whatsAppNotificationService && $whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentUpdatedNotifications($appointment, $appointmentRescheduled); } } } if ($webHookService && $appointmentRescheduled === true) { $webHookService->process(self::TIME_UPDATED, $appointment, []); } if ($webHookService && $bookings) { $canceledBookings = []; $otherBookings = []; foreach ($bookings as $booking) { if ($booking['status'] === BookingStatus::CANCELED) { $canceledBookings[] = $booking; } else { $otherBookings[] = $booking; } } if (count($canceledBookings) > 0) { $webHookService->process(BookingCanceledEventHandler::BOOKING_CANCELED, $appointment, $canceledBookings); } if (count($otherBookings) > 0) { $webHookService->process(($bookingAdded ? self::BOOKING_ADDED : self::BOOKING_STATUS_UPDATED), $appointment, $otherBookings); } } } } WP/EventListeners/Booking/Appointment/AppointmentTimeUpdatedEventHandler.php 0000666 00000014232 15165376447 0023417 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use Exception; use Interop\Container\Exception\ContainerException; use Slim\Exception\ContainerValueNotFoundException; /** * Class AppointmentTimeUpdatedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment */ class AppointmentTimeUpdatedEventHandler { /** @var string */ const TIME_UPDATED = 'bookingTimeUpdated'; /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerValueNotFoundException * @throws NotFoundException * @throws QueryExecutionException * @throws ContainerException * @throws InvalidArgumentException * @throws Exception */ public static function handle($commandResult, $container) { /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); $appointment = $commandResult->getData()[Entities::APPOINTMENT]; /** @var Appointment|Event $reservationObject */ $reservationObject = AppointmentFactory::create($appointment); $bookingApplicationService->setReservationEntities($reservationObject); if ($zoomService) { $zoomService->handleAppointmentMeeting($reservationObject, self::TIME_UPDATED); if ($reservationObject->getZoomMeeting()) { $appointment['zoomMeeting'] = $reservationObject->getZoomMeeting()->toArray(); } } if ($lessonSpaceService) { $lessonSpaceService->handle($reservationObject, Entities::APPOINTMENT); if ($reservationObject->getLessonSpace()) { $appointment['lessonSpace'] = $reservationObject->getLessonSpace(); } } if ($googleCalendarService) { try { $googleCalendarService->handleEvent($reservationObject, self::TIME_UPDATED); } catch (Exception $e) { } if ($reservationObject->getGoogleCalendarEventId() !== null) { $appointment['googleCalendarEventId'] = $reservationObject->getGoogleCalendarEventId()->getValue(); } } if ($reservationObject->getGoogleMeetUrl() !== null) { $appointment['googleMeetUrl'] = $reservationObject->getGoogleMeetUrl(); } if ($outlookCalendarService) { try { $outlookCalendarService->handleEvent($reservationObject, self::TIME_UPDATED); } catch (Exception $e) { } if ($reservationObject->getOutlookCalendarEventId() !== null) { $appointment['outlookCalendarEventId'] = $reservationObject->getOutlookCalendarEventId()->getValue(); } } $appointment['initialAppointmentDateTime'] = $commandResult->getData()['initialAppointmentDateTime']; $emailNotificationService->sendAppointmentRescheduleNotifications($appointment); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentRescheduleNotifications($appointment); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentRescheduleNotifications($appointment); } if ($webHookService) { $webHookService->process(self::TIME_UPDATED, $appointment, []); } } } WP/EventListeners/Booking/Event/EventAddedEventHandler.php 0000666 00000006754 15165376447 0017573 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; /** * Class EventAddedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event */ class EventAddedEventHandler { /** @var string */ const EVENT_ADDED = 'eventAdded'; /** * @param CommandResult $commandResult * @param Container $container * * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws \Slim\Exception\ContainerValueNotFoundException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException * @throws \Interop\Container\Exception\ContainerException * @throws \Exception */ public static function handle($commandResult, $container) { /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); $events = $commandResult->getData()[Entities::EVENTS]; foreach ($events as $event) { /** @var Event $reservationObject */ $reservationObject = EventFactory::create($event); $bookingApplicationService->setReservationEntities($reservationObject); if ($zoomService) { $zoomService->handleEventMeeting($reservationObject, $reservationObject->getPeriods(), self::EVENT_ADDED); } if ($lessonSpaceService) { $lessonSpaceService->handle($reservationObject, Entities::EVENT, $reservationObject->getPeriods()); } if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($reservationObject, self::EVENT_ADDED, $reservationObject->getPeriods()); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($reservationObject, self::EVENT_ADDED, $reservationObject->getPeriods()); } catch (\Exception $e) { } } } } } WP/EventListeners/Booking/Event/EventEditedEventHandler.php 0000666 00000046535 15165376447 0017771 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\IcsApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\WebHook\WebHookApplicationService; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Booking\Event\EventPeriod; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Domain\Factory\Zoom\ZoomFactory; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Domain\ValueObjects\Number\Integer\Id; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; /** * Class EventEditedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event */ class EventEditedEventHandler { /** @var string */ const TIME_UPDATED = 'bookingTimeUpdated'; /** @var string */ const EVENT_DELETED = 'eventDeleted'; /** @var string */ const EVENT_ADDED = 'eventAdded'; /** @var string */ const EVENT_PERIOD_DELETED = 'eventPeriodDeleted'; /** @var string */ const EVENT_PERIOD_ADDED = 'eventPeriodAdded'; /** @var string */ const ZOOM_USER_CHANGED = 'zoomUserChanged'; /** @var string */ const ZOOM_LICENCED_USER_CHANGED = 'zoomLicencedUserChanged'; /** @var string */ const PROVIDER_CHANGED = 'providerChanged'; /** * @param CommandResult $commandResult * @param Container $container * * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws \Slim\Exception\ContainerValueNotFoundException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException * @throws \Interop\Container\Exception\ContainerException * @throws \Exception */ public static function handle($commandResult, $container) { /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var WebHookApplicationService $webHookService */ $webHookService = $container->get('application.webHook.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var LessonSpaceService $lessonSpaceService */ $lessonSpaceService = $container->get('infrastructure.lesson.space.service'); /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); /** @var PaymentApplicationService $paymentAS */ $paymentAS = $container->get('application.payment.service'); $eventsData = $commandResult->getData()[Entities::EVENTS]; /** @var Collection $deletedEvents */ $deletedEvents = self::getCollection($eventsData['deleted']); /** @var Collection $rescheduledEvents */ $rescheduledEvents = self::getCollection($eventsData['rescheduled']); /** @var Collection $addedEvents */ $addedEvents = self::getCollection($eventsData['added']); /** @var Collection $clonedEvents */ $clonedEvents = self::getCollection($eventsData['cloned']); /** @var Event $event */ foreach ($deletedEvents->getItems() as $event) { $eventId = $event->getId()->getValue(); if ($zoomService && $clonedEvents->keyExists($eventId) && $clonedEvents->getItem($eventId)->getStatus()->getValue() === BookingStatus::APPROVED ) { $zoomService->handleEventMeeting($event, $event->getPeriods(), self::EVENT_DELETED); } if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($event, self::EVENT_DELETED, $event->getPeriods()); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($event, self::EVENT_DELETED, $event->getPeriods()); } catch (\Exception $e) { } } } /** @var Event $event */ foreach ($addedEvents->getItems() as $event) { if ($zoomService) { $zoomService->handleEventMeeting($event, $event->getPeriods(), self::EVENT_ADDED); } if ($lessonSpaceService) { $lessonSpaceService->handle($event, Entities::EVENT, $event->getPeriods()); } if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($event, self::EVENT_ADDED, $event->getPeriods()); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($event, self::EVENT_ADDED, $event->getPeriods()); } catch (\Exception $e) { } } } /** @var Event $event */ foreach ($clonedEvents->getItems() as $event) { if ($lessonSpaceService) { $lessonSpaceService->handle($event, Entities::EVENT, $event->getPeriods()); } } /** @var Event $event */ foreach ($rescheduledEvents->getItems() as $event) { $eventId = $event->getId()->getValue(); /** @var Event $clonedEvent */ $clonedEvent = $clonedEvents->keyExists($eventId) ? $clonedEvents->getItem($eventId) : null; if ($lessonSpaceService) { $lessonSpaceService->handle($event, Entities::EVENT, $event->getPeriods()); } if ($zoomService && $clonedEvent && $clonedEvent->getStatus()->getValue() === BookingStatus::APPROVED) { /** @var Collection $rescheduledPeriods */ $rescheduledPeriods = new Collection(); /** @var Collection $addedPeriods */ $addedPeriods = new Collection(); /** @var Collection $deletedPeriods */ $deletedPeriods = new Collection(); /** @var EventPeriod $eventPeriod */ foreach ($event->getPeriods()->getItems() as $eventPeriod) { $eventPeriodId = $eventPeriod->getId()->getValue(); /** @var EventPeriod $clonedEventPeriod */ $clonedEventPeriod = $clonedEvent->getPeriods()->keyExists($eventPeriodId) ? $clonedEvent->getPeriods()->getItem($eventPeriodId) : null; if ($clonedEventPeriod && $clonedEventPeriod->toArray() !== $eventPeriod->toArray()) { $rescheduledPeriods->addItem($eventPeriod, $eventPeriodId); } elseif (!$clonedEventPeriod) { $addedPeriods->addItem($eventPeriod, $eventPeriodId); } } /** @var EventPeriod $clonedEventPeriod */ foreach ($clonedEvent->getPeriods()->getItems() as $clonedEventPeriod) { $eventPeriodId = $clonedEventPeriod->getId()->getValue(); if (!$event->getPeriods()->keyExists($eventPeriodId)) { $deletedPeriods->addItem($clonedEventPeriod, $clonedEventPeriod->getId()->getValue()); } } if ($rescheduledPeriods->length()) { $zoomService->handleEventMeeting($event, $rescheduledPeriods, self::TIME_UPDATED); if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($event, self::TIME_UPDATED, $rescheduledPeriods); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($event, self::TIME_UPDATED, $rescheduledPeriods); } catch (\Exception $e) { } } } if ($addedPeriods->length()) { $zoomService->handleEventMeeting($event, $addedPeriods, self::EVENT_PERIOD_ADDED); if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($event, self::EVENT_PERIOD_ADDED, $addedPeriods); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($event, self::EVENT_PERIOD_ADDED, $addedPeriods); } catch (\Exception $e) { } } } if ($deletedPeriods->length()) { $zoomService->handleEventMeeting($event, $deletedPeriods, self::EVENT_PERIOD_DELETED); if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($event, self::EVENT_PERIOD_DELETED, $deletedPeriods); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($event, self::EVENT_PERIOD_DELETED, $deletedPeriods); } catch (\Exception $e) { } } } } } $zoomUserChange = $commandResult->getData()['zoomUserChanged']; if ($zoomUserChange) { if ($zoomService && !$rescheduledEvents->length()) { $command = $commandResult->getData()['zoomUsersLicenced'] ? self::ZOOM_LICENCED_USER_CHANGED : self::ZOOM_USER_CHANGED; /** @var Event $event */ foreach ($clonedEvents->getItems() as $event) { $zoomService->handleEventMeeting($event, $event->getPeriods(), $command, $zoomUserChange); } } } if ($commandResult->getData()['newInfo']) { if (!$rescheduledEvents->length()) { /** @var Event $event */ foreach ($clonedEvents->getItems() as $event) { $zoomService->handleEventMeeting($event, $event->getPeriods(), EventStatusUpdatedEventHandler::EVENT_STATUS_UPDATED); } } } $newProviders = $commandResult->getData()['newProviders']; $removeProviders = $commandResult->getData()['removeProviders']; $newInfo = $commandResult->getData()['newInfo']; $organizerChange = $commandResult->getData()['organizerChanged']; $newOrganizer = $commandResult->getData()['newOrganizer']; /** @var Event $event */ foreach ($clonedEvents->getItems() as $event) { if ($organizerChange) { $googleCalendarService->handleEventPeriodsChange($event, self::EVENT_PERIOD_DELETED, $event->getPeriods()); $outlookCalendarService->handleEventPeriod($event, self::EVENT_PERIOD_DELETED, $event->getPeriods()); if ($newOrganizer) { $event->setOrganizerId(new Id($newOrganizer)); $googleCalendarService->handleEventPeriodsChange($event, self::EVENT_PERIOD_ADDED, $event->getPeriods()); $outlookCalendarService->handleEventPeriod($event, self::EVENT_PERIOD_ADDED, $event->getPeriods()); } } if ($newInfo) { $event->setName($newInfo['name']); $event->setDescription($newInfo['description']); } if (($newProviders || $removeProviders || $newInfo) && (!$organizerChange || $newOrganizer)) { $googleCalendarService->handleEventPeriodsChange($event, self::PROVIDER_CHANGED, $event->getPeriods(), $newProviders, $removeProviders); $outlookCalendarService->handleEventPeriod($event, self::PROVIDER_CHANGED, $event->getPeriods(), $newProviders, $removeProviders); } } if (count($eventsData['edited']) > 0 && !$addedEvents->length() && !$rescheduledEvents->length() && !$deletedEvents->length()) { foreach ($clonedEvents->getItems() as $event) { foreach ($event->getPeriods()->toArray() as $index => $eventPeriod) { if (!empty($eventsData['edited'][$event->getId()->getValue()])) { /** @var EventPeriod $changedPeriod */ $changedPeriod = $eventsData['edited'][$event->getId()->getValue()]->getPeriods()->getItem($index); if (!empty($changedPeriod)) { if (!empty($eventPeriod['zoomMeeting']) && !empty($eventPeriod['zoomMeeting']['id']) && !empty($eventPeriod['zoomMeeting']['joinUrl']) && !empty($eventPeriod['zoomMeeting']['startUrl'])) { $zoomMeeting = ZoomFactory::create( $eventPeriod['zoomMeeting'] ); $changedPeriod->setZoomMeeting($zoomMeeting); } else { $changedPeriod->setZoomMeeting(ZoomFactory::create([])); } $changedPeriod->setGoogleMeetUrl($eventPeriod['googleMeetUrl']); } } } } foreach ($eventsData['edited'] as $event) { $eventArray = $event->toArray(); foreach ($eventArray['bookings'] as $index => $booking) { $paymentId = $booking['payments'][0]['id']; $paymentData = [ 'booking' => $booking, 'type' => Entities::EVENT, 'event' => $eventArray, 'paymentId' => $paymentId, 'bookable' => $eventArray, 'customer' => $booking['customer'] ]; if (!empty($paymentId)) { $eventArray['bookings'][$index]['payments'][0]['paymentLinks'] = $paymentAS->createPaymentLink($paymentData, $index); } } $emailNotificationService->sendAppointmentUpdatedNotifications($eventArray); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentUpdatedNotifications($eventArray); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentUpdatedNotifications($eventArray); } } } foreach ($eventsData['rescheduled'] as $eventArray) { foreach ($eventArray['bookings'] as $index => $booking) { $paymentId = $booking['payments'][0]['id']; $paymentData = [ 'booking' => $booking, 'type' => Entities::EVENT, 'event' => $eventArray, 'paymentId' => $paymentId, 'bookable' => $eventArray, 'customer' => $booking['customer'] ]; if (!empty($paymentId)) { $eventArray['bookings'][$index]['payments'][0]['paymentLinks'] = $paymentAS->createPaymentLink($paymentData, $index); } } /** @var IcsApplicationService $icsService */ $icsService = $container->get('application.ics.service'); foreach ($eventArray['bookings'] as $index => $booking) { if ($booking['status'] === BookingStatus::APPROVED || $booking['status'] === BookingStatus::PENDING) { $eventArray['bookings'][$index]['icsFiles'] = $icsService->getIcsData( Entities::EVENT, $booking['id'], [], true ); } } $emailNotificationService->sendAppointmentRescheduleNotifications($eventArray); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentRescheduleNotifications($eventArray); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentRescheduleNotifications($eventArray); } if ($webHookService) { $webHookService->process(self::TIME_UPDATED, $eventArray, []); } } } /** * @param array $eventsArray * * @return Collection * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ private static function getCollection($eventsArray) { /** @var Collection $events */ $events = new Collection(); foreach ($eventsArray as $eventArray) { /** @var Event $eventObject */ $eventObject = EventFactory::create($eventArray); /** @var Collection $eventPeriods */ $eventPeriods = new Collection(); /** @var EventPeriod $period */ foreach ($eventObject->getPeriods()->getItems() as $period) { $eventPeriods->addItem($period, $period->getId()->getValue()); } $eventObject->setPeriods($eventPeriods); $events->addItem($eventObject, $eventObject->getId()->getValue()); } return $events; } } WP/EventListeners/Booking/Event/EventEventsListener.php 0000666 00000004310 15165376447 0017226 0 ustar 00 <?php /** * Handle WP part of appointment-related events */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\WP\Integrations\ThriveAutomator\ThriveAutomatorService; use League\Event\ListenerInterface; use League\Event\EventInterface; /** * Class EventEventsListener * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event */ class EventEventsListener implements ListenerInterface { /** @var Container */ private $container; /** * AppointmentEventsListener constructor. * * @param Container $container */ public function __construct($container) { $this->container = $container; } /** * Check if provided argument is the listener * * @param mixed $listener * * @return bool */ public function isListener($listener) { return $listener === $this; } /** * @param EventInterface $event * @param CommandResult|null $param * * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException * @throws \Interop\Container\Exception\ContainerException */ public function handle(EventInterface $event, $param = null) { // Handling the events if ($param->getResult() !== 'error' && !AMELIA_LITE_VERSION) { if (!AMELIA_LITE_VERSION) { ThriveAutomatorService::initItems(); } switch ($event->getName()) { case 'EventStatusUpdated': EventStatusUpdatedEventHandler::handle($param, $this->container); break; case 'EventEdited': EventEditedEventHandler::handle($param, $this->container); break; case 'EventAdded': EventAddedEventHandler::handle($param, $this->container); break; } } } } WP/EventListeners/Booking/Event/EventStatusUpdatedEventHandler.php 0000666 00000011127 15165376447 0021352 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\SMSNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Application\Services\Zoom\ZoomApplicationService; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; /** * Class EventStatusUpdatedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event */ class EventStatusUpdatedEventHandler { /** @var string */ const EVENT_STATUS_UPDATED = 'eventStatusUpdated'; /** * @param CommandResult $commandResult * @param Container $container * * @throws \Slim\Exception\ContainerValueNotFoundException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException * @throws \Interop\Container\Exception\ContainerException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws \AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException */ public static function handle($commandResult, $container) { /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var SMSNotificationService $smsNotificationService */ $smsNotificationService = $container->get('application.smsNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); /** @var SettingsService $settingsService */ $settingsService = $container->get('domain.settings.service'); /** @var ZoomApplicationService $zoomService */ $zoomService = $container->get('application.zoom.service'); /** @var BookingApplicationService $bookingApplicationService */ $bookingApplicationService = $container->get('application.booking.booking.service'); /** @var GoogleCalendarService $googleCalendarService */ $googleCalendarService = $container->get('infrastructure.google.calendar.service'); /** @var OutlookCalendarService $outlookCalendarService */ $outlookCalendarService = $container->get('infrastructure.outlook.calendar.service'); $events = $commandResult->getData()[Entities::EVENTS]; foreach ($events as $event) { /** @var Event $reservationObject */ $reservationObject = EventFactory::create($event); $bookingApplicationService->setReservationEntities($reservationObject); if ($zoomService) { $zoomService->handleEventMeeting($reservationObject, $reservationObject->getPeriods(), self::EVENT_STATUS_UPDATED); $events['periods'] = $reservationObject->getPeriods()->toArray(); } if ($googleCalendarService) { try { $googleCalendarService->handleEventPeriodsChange($reservationObject, self::EVENT_STATUS_UPDATED, $reservationObject->getPeriods()); } catch (\Exception $e) { } } if ($outlookCalendarService) { try { $outlookCalendarService->handleEventPeriod($reservationObject, self::EVENT_STATUS_UPDATED, $reservationObject->getPeriods()); } catch (\Exception $e) { } } $emailNotificationService->sendAppointmentStatusNotifications($event, false, true); if ($settingsService->getSetting('notifications', 'smsSignedIn') === true) { $smsNotificationService->sendAppointmentStatusNotifications($event, false, true); } if ($whatsAppNotificationService->checkRequiredFields()) { $whatsAppNotificationService->sendAppointmentStatusNotifications($event, false, true); } } } } WP/EventListeners/User/UserAddedEventHandler.php 0000666 00000001736 15165376447 0015670 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\EventListeners\User; use AmeliaBooking\Application\Commands\CommandResult; /** * Class UserAddedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\User */ class UserAddedEventHandler { /** * @param CommandResult $commandResult */ public static function handle($commandResult) { // Performing any actions only if the result is successful if ($commandResult->getResult() === CommandResult::RESULT_SUCCESS) { // Check if a WP user is linked $commandData = $commandResult->getData(); if (!empty($commandData['user']['externalId'])) { $wpUser = new \WP_User((int)$commandData['user']['externalId']); // Set the user role $wpUser->set_role('wpamelia-' . $commandData['user']['type']); // Persist the changes wp_update_user($wpUser); } } } } WP/EventListeners/User/UserDeletedEventHandler.php 0000666 00000001750 15165376447 0016231 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\EventListeners\User; use AmeliaBooking\Application\Commands\CommandResult; /** * Class UserDeletedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\User */ class UserDeletedEventHandler { /** * @param CommandResult $commandResult */ public static function handle($commandResult) { // Performing any actions only if the result is successful if ($commandResult->getResult() === CommandResult::RESULT_SUCCESS) { // Check if a WP user is linked $commandData = $commandResult->getData(); if (!empty($commandData['user']['externalId'])) { $wpUser = new \WP_User((int)$commandData['user']['externalId']); // Remove the user role $wpUser->remove_role('wpamelia-' . $commandData['user']['type']); // Persist the changes wp_update_user($wpUser); } } } } WP/EventListeners/User/Provider/ProviderUpdatedEventHandler.php 0000666 00000004001 15165376447 0020707 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\EventListeners\User\Provider; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use Interop\Container\Exception\ContainerException; /** * Class ProviderUpdatedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\User\Provdier */ class ProviderUpdatedEventHandler { /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerException * @throws QueryExecutionException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public static function handle($commandResult, $container) { if ($commandResult->getResult() === CommandResult::RESULT_SUCCESS && $commandResult->getData()['sendEmployeePanelAccessEmail'] === true) { /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); $emailNotificationService->sendEmployeePanelAccess( $commandResult->getData()['user'], $commandResult->getData()['password'] ); if (!empty($commandResult->getData()['user']) && $whatsAppNotificationService->checkRequiredFields() && !empty($commandResult->getData()['user']['phone'])) { $whatsAppNotificationService->sendEmployeePanelAccess( $commandResult->getData()['user'], $commandResult->getData()['password'] ); } } } } WP/EventListeners/User/Provider/ProviderAddedEventHandler.php 0000666 00000003744 15165376447 0020337 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\WP\EventListeners\User\Provider; use AmeliaBooking\Application\Commands\CommandResult; use AmeliaBooking\Application\Services\Notification\EmailNotificationService; use AmeliaBooking\Application\Services\Notification\WhatsAppNotificationService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use Interop\Container\Exception\ContainerException; /** * Class ProviderAddedEventHandler * * @package AmeliaBooking\Infrastructure\WP\EventListeners\User\Provider */ class ProviderAddedEventHandler { /** * @param CommandResult $commandResult * @param Container $container * * @throws ContainerException * @throws QueryExecutionException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public static function handle($commandResult, $container) { if (!is_string($commandResult->getData()) && $commandResult->getData()['sendEmployeePanelAccessEmail'] === true) { /** @var EmailNotificationService $emailNotificationService */ $emailNotificationService = $container->get('application.emailNotification.service'); /** @var WhatsAppNotificationService $whatsAppNotificationService */ $whatsAppNotificationService = $container->get('application.whatsAppNotification.service'); $emailNotificationService->sendEmployeePanelAccess( $commandResult->getData()['user'], $commandResult->getData()['password'] ); if (!empty($commandResult->getData()['user']) && $whatsAppNotificationService->checkRequiredFields() && !empty($commandResult->getData()['user']['phone'])) { $whatsAppNotificationService->sendEmployeePanelAccess( $commandResult->getData()['user'], $commandResult->getData()['password'] ); } } } } WP/EventListeners/User/UserEventsListener.php 0000666 00000003601 15165376447 0015332 0 ustar 00 <?php /** * Handle WP part of user-related events */ namespace AmeliaBooking\Infrastructure\WP\EventListeners\User; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\EventListeners\User\Provider\ProviderAddedEventHandler; use AmeliaBooking\Infrastructure\WP\EventListeners\User\Provider\ProviderUpdatedEventHandler; use Interop\Container\Exception\ContainerException; use League\Event\ListenerInterface; use League\Event\EventInterface; /** * Class UserEventsListener * * @package AmeliaBooking\Infrastructure\WP\EventListeners\User */ class UserEventsListener implements ListenerInterface { /** @var Container */ private $container; /** * AppointmentEventsListener constructor. * * @param Container $container */ public function __construct($container) { $this->container = $container; } /** * Check if provided argument is the listener * * @param mixed $listener * * @return bool */ public function isListener($listener) { return $listener === $this; } /** * Handle events * * @param EventInterface $event * @param mixed $param * * @throws QueryExecutionException * @throws ContainerException */ public function handle(EventInterface $event, $param = null) { // Handling the event switch ($event->getName()) { case 'user.added': UserAddedEventHandler::handle($param); break; case 'provider.updated': ProviderUpdatedEventHandler::handle($param, $this->container); break; case 'provider.added': ProviderAddedEventHandler::handle($param, $this->container); break; } } } WP/EventListeners/EventSubscribers.php 0000666 00000004614 15165376447 0014100 0 ustar 00 <?php /** * Subscribe to domain events */ namespace AmeliaBooking\Infrastructure\WP\EventListeners; use AmeliaBooking\Domain\Events\DomainEventBus; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Appointment\AppointmentEventsListener; use AmeliaBooking\Infrastructure\WP\EventListeners\Booking\Event\EventEventsListener; use AmeliaBooking\Infrastructure\WP\EventListeners\User\UserEventsListener; /** * Class EventSubscribers * * @package AmeliaBooking\Infrastructure\WP\EventListeners */ class EventSubscribers { /** * Subscribe WP infrastructure to domain events * * @param DomainEventBus $eventBus * @param Container $container */ public static function subscribe($eventBus, $container) { $userListener = new UserEventsListener($container); $eventBus->addListener('user.added', $userListener); $eventBus->addListener('user.deleted', $userListener); $eventBus->addListener('provider.updated', $userListener); $eventBus->addListener('provider.added', $userListener); $appointmentListener = new AppointmentEventsListener($container); $eventBus->addListener('AppointmentAdded', $appointmentListener); $eventBus->addListener('AppointmentDeleted', $appointmentListener); $eventBus->addListener('AppointmentEdited', $appointmentListener); $eventBus->addListener('AppointmentStatusUpdated', $appointmentListener); $eventBus->addListener('BookingTimeUpdated', $appointmentListener); $eventBus->addListener('BookingAdded', $appointmentListener); $eventBus->addListener('BookingCanceled', $appointmentListener); $eventBus->addListener('BookingEdited', $appointmentListener); $eventBus->addListener('BookingReassigned', $appointmentListener); $eventBus->addListener('PackageCustomerUpdated', $appointmentListener); $eventBus->addListener('PackageCustomerAdded', $appointmentListener); $eventBus->addListener('PackageCustomerDeleted', $appointmentListener); $eventBus->addListener('BookingDeleted', $appointmentListener); $eventListener = new EventEventsListener($container); $eventBus->addListener('EventStatusUpdated', $eventListener); $eventBus->addListener('EventEdited', $eventListener); $eventBus->addListener('EventAdded', $eventListener); } } WP/PermissionsService/PermissionsChecker.php 0000666 00000002746 15165376447 0015276 0 ustar 00 <?php /** * WP Infrastructure layer implementation of the permissions service. */ namespace AmeliaBooking\Infrastructure\WP\PermissionsService; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Entity\User\Admin; use AmeliaBooking\Domain\Services\Permissions\PermissionsCheckerInterface; /** * Class PermissionsChecker * * @package AmeliaBooking\Infrastructure\WP\PermissionsService */ class PermissionsChecker implements PermissionsCheckerInterface { /** * @param AbstractUser $user * @param string $object * @param string $permission * * @return bool */ public function checkPermissions($user, $object, $permission) { // Admin can do all if ($user instanceof Admin) { return true; } // Get the WP role name of the user, rollback to customer by default $wpRoleName = $user !== null ? 'wpamelia-' . $user->getType() : 'wpamelia-customer'; // Get the wp name of capability we are looking for. $wpCapability = "amelia_{$permission}_{$object}"; if ($user !== null && $user->getExternalId() !== null) { return user_can($user->getExternalId()->getValue(), $wpCapability); } // If user is guest check does it have capability $wpRole = get_role($wpRoleName); return $wpRole !== null && isset($wpRole->capabilities[$wpCapability]) ? (bool)$wpRole->capabilities[$wpCapability] : false; } } WP/ButtonService/ButtonService.php 0000666 00000005721 15165376447 0013226 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\WP\ButtonService; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\HelperService\HelperService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings; /** * Class ButtonService * * @package AmeliaBooking\Infrastructure\WP\ShortcodeService */ class ButtonService { /** * Function that adds shortcode button to WordPress TinyMCE editor on Page and Post pages */ public static function renderButton() { if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) { return; } if (get_user_option('rich_editing') !== 'true') { return; } add_filter('mce_external_plugins', [self::class, 'addButton']); add_filter('mce_buttons', [self::class, 'registerButton']); // Export JS variables for classic editor add_action('after_wp_tiny_mce', [self::class, 'exportVars']); // Export JS variables for Gutenberg editor add_action('admin_enqueue_scripts', [self::class, 'exportVars']); } /** * Function that add buttons for MCE editor * * @param $pluginArray * * @return mixed */ public static function addButton($pluginArray) { $pluginArray['ameliaBookingPlugin'] = AMELIA_URL . 'public/js/tinymce/amelia-mce.js'; return $pluginArray; } /** * Function that register buttons for MCE editor * * @param $buttons * * @return mixed */ public static function registerButton($buttons) { $buttons[] = 'ameliaButton'; return $buttons; } public static function exportVars() { HelperService::exportJSVar('wpAmeliaLiteVersion', AMELIA_LITE_VERSION); HelperService::exportJSVar('wpAmeliaPluginURL', AMELIA_URL); wp_enqueue_script('wp-deactivation-amelia', AMELIA_URL . 'public/js/plugins/delete-plugin.js', []); wp_enqueue_style('amelia_booking_tinymce_styles', AMELIA_URL . 'public/js/tinymce/amelia-tinymce-styles.css', array(), AMELIA_VERSION); $settingsService = new SettingsService(new SettingsStorage()); HelperService::exportJSVar( 'wpAmeliaDeleteSettings', $settingsService->getSetting('activation', 'deleteTables') ? 1 : 0 ); HelperService::exportJSVar( 'wpAmeliaNonce', wp_create_nonce('ajax-nonce') ); HelperService::exportJSVar('wpAmeliaActionURL', AMELIA_ACTION_URL); HelperService::exportJSVar( 'wpAmeliaLabels', array_merge( BackendStrings::getCommonStrings(), BackendStrings::getWordPressStrings() ) ); HelperService::printJSVars(); } } ContainerConfig/repositories.php 0000666 00000042542 15165376447 0013111 0 ustar 00 <?php /** * Assembling repositories: * Instantiating infrastructure-layer repositories implementing the Domain layer interfaces */ use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\WP\InstallActions\DB; use AmeliaBooking\Infrastructure\Repository; defined('ABSPATH') or die('No script kiddies please!'); $entries['domain.bookable.category.repository'] = function (Container $c) { return new Repository\Bookable\Service\CategoryRepository( $c->getDatabaseConnection(), DB\Bookable\CategoriesTable::getTableName() ); }; $entries['domain.bookable.extra.repository'] = function (Container $c) { return new Repository\Bookable\Service\ExtraRepository( $c->getDatabaseConnection(), DB\Bookable\ExtrasTable::getTableName() ); }; $entries['domain.bookable.service.repository'] = function (Container $c) { return new Repository\Bookable\Service\ServiceRepository( $c->getDatabaseConnection(), DB\Bookable\ServicesTable::getTableName(), DB\User\Provider\ProvidersServiceTable::getTableName(), DB\Bookable\ExtrasTable::getTableName(), DB\Bookable\ServicesViewsTable::getTableName(), DB\Gallery\GalleriesTable::getTableName() ); }; $entries['domain.bookable.package.repository'] = function (Container $c) { return new Repository\Bookable\Service\PackageRepository( $c->getDatabaseConnection(), DB\Bookable\PackagesTable::getTableName() ); }; $entries['domain.bookable.package.packageService.repository'] = function (Container $c) { return new Repository\Bookable\Service\PackageServiceRepository( $c->getDatabaseConnection(), DB\Bookable\PackagesServicesTable::getTableName() ); }; $entries['domain.bookable.package.packageServiceLocation.repository'] = function (Container $c) { return new Repository\Bookable\Service\PackageServiceLocationRepository( $c->getDatabaseConnection(), DB\Bookable\PackagesServicesLocationsTable::getTableName() ); }; $entries['domain.bookable.package.packageServiceProvider.repository'] = function (Container $c) { return new Repository\Bookable\Service\PackageServiceProviderRepository( $c->getDatabaseConnection(), DB\Bookable\PackagesServicesProvidersTable::getTableName() ); }; $entries['domain.bookable.packageCustomer.repository'] = function (Container $c) { return new Repository\Bookable\Service\PackageCustomerRepository( $c->getDatabaseConnection(), DB\Bookable\PackagesCustomersTable::getTableName() ); }; $entries['domain.bookable.packageCustomerService.repository'] = function (Container $c) { return new Repository\Bookable\Service\PackageCustomerServiceRepository( $c->getDatabaseConnection(), DB\Bookable\PackagesCustomersServicesTable::getTableName() ); }; $entries['domain.bookable.resource.repository'] = function (Container $c) { return new Repository\Bookable\Service\ResourceRepository( $c->getDatabaseConnection(), DB\Bookable\ResourcesTable::getTableName() ); }; $entries['domain.bookable.resourceEntities.repository'] = function (Container $c) { return new Repository\Bookable\Service\ResourceEntitiesRepository( $c->getDatabaseConnection(), DB\Bookable\ResourcesToEntitiesTable::getTableName() ); }; $entries['domain.coupon.repository'] = function (Container $c) { return new Repository\Coupon\CouponRepository( $c->getDatabaseConnection(), DB\Coupon\CouponsTable::getTableName(), DB\Bookable\ServicesTable::getTableName(), DB\Coupon\CouponsToServicesTable::getTableName(), DB\Booking\EventsTable::getTableName(), DB\Coupon\CouponsToEventsTable::getTableName(), DB\Bookable\PackagesTable::getTableName(), DB\Coupon\CouponsToPackagesTable::getTableName(), DB\Booking\CustomerBookingsTable::getTableName() ); }; $entries['domain.coupon.service.repository'] = function (Container $c) { return new Repository\Coupon\CouponServiceRepository( $c->getDatabaseConnection(), DB\Coupon\CouponsToServicesTable::getTableName() ); }; $entries['domain.coupon.event.repository'] = function (Container $c) { return new Repository\Coupon\CouponEventRepository( $c->getDatabaseConnection(), DB\Coupon\CouponsToEventsTable::getTableName() ); }; $entries['domain.coupon.package.repository'] = function (Container $c) { return new Repository\Coupon\CouponPackageRepository( $c->getDatabaseConnection(), DB\Coupon\CouponsToPackagesTable::getTableName() ); }; $entries['domain.locations.repository'] = function (Container $c) { return new Repository\Location\LocationRepository( $c->getDatabaseConnection(), DB\Location\LocationsTable::getTableName(), DB\User\Provider\ProvidersLocationTable::getTableName(), DB\User\Provider\ProvidersServiceTable::getTableName(), DB\Bookable\ServicesTable::getTableName(), DB\Location\LocationsViewsTable::getTableName() ); }; $entries['domain.notification.repository'] = function (Container $c) { return new Repository\Notification\NotificationRepository( $c->getDatabaseConnection(), DB\Notification\NotificationsTable::getTableName() ); }; $entries['domain.notificationEntities.repository'] = function (Container $c) { return new Repository\Notification\NotificationsToEntitiesRepository( $c->getDatabaseConnection(), DB\Notification\NotificationsToEntitiesTable::getTableName() ); }; $entries['domain.notificationLog.repository'] = function (Container $c) { return new Repository\Notification\NotificationLogRepository( $c->getDatabaseConnection(), DB\Notification\NotificationsLogTable::getTableName(), DB\Notification\NotificationsTable::getTableName(), DB\Booking\AppointmentsTable::getTableName(), DB\Booking\CustomerBookingsTable::getTableName(), DB\User\UsersTable::getTableName() ); }; $entries['domain.notificationSMSHistory.repository'] = function (Container $c) { return new Repository\Notification\NotificationSMSHistoryRepository( $c->getDatabaseConnection(), DB\Notification\NotificationsSMSHistoryTable::getTableName() ); }; $entries['domain.payment.repository'] = function (Container $c) { return new Repository\Payment\PaymentRepository( $c->getDatabaseConnection(), DB\Payment\PaymentsTable::getTableName(), DB\Booking\AppointmentsTable::getTableName(), DB\Booking\CustomerBookingsTable::getTableName(), DB\Bookable\ServicesTable::getTableName(), DB\User\UsersTable::getTableName(), DB\Booking\EventsTable::getTableName(), DB\Booking\EventsProvidersTable::getTableName(), DB\Booking\EventsPeriodsTable::getTableName(), DB\Booking\CustomerBookingsToEventsPeriodsTable::getTableName(), DB\Bookable\PackagesTable::getTableName(), DB\Bookable\PackagesCustomersTable::getTableName() ); }; $entries['domain.users.repository'] = function (Container $c) { return new Repository\User\UserRepository( $c->getDatabaseConnection(), DB\User\UsersTable::getTableName() ); }; $entries['domain.bookable.service.providerService.repository'] = function (Container $c) { return new Repository\Bookable\Service\ProviderServiceRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersServiceTable::getTableName() ); }; $entries['domain.bookable.service.providerLocation.repository'] = function (Container $c) { return new Repository\Location\ProviderLocationRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersLocationTable::getTableName() ); }; $entries['domain.schedule.dayOff.repository'] = function (Container $c) { return new Repository\Schedule\DayOffRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersDayOffTable::getTableName() ); }; $entries['domain.schedule.weekDay.repository'] = function (Container $c) { return new Repository\Schedule\WeekDayRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersWeekDayTable::getTableName() ); }; $entries['domain.schedule.timeOut.repository'] = function (Container $c) { return new Repository\Schedule\TimeOutRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersTimeOutTable::getTableName() ); }; $entries['domain.schedule.period.repository'] = function (Container $c) { return new Repository\Schedule\PeriodRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersPeriodTable::getTableName() ); }; $entries['domain.schedule.period.service.repository'] = function (Container $c) { return new Repository\Schedule\PeriodServiceRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersPeriodServiceTable::getTableName() ); }; $entries['domain.schedule.period.location.repository'] = function (Container $c) { return new Repository\Schedule\PeriodLocationRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersPeriodLocationTable::getTableName() ); }; $entries['domain.schedule.specialDay.repository'] = function (Container $c) { return new Repository\Schedule\SpecialDayRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersSpecialDayTable::getTableName() ); }; $entries['domain.schedule.specialDay.period.repository'] = function (Container $c) { return new Repository\Schedule\SpecialDayPeriodRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersSpecialDayPeriodTable::getTableName() ); }; $entries['domain.schedule.specialDay.period.service.repository'] = function (Container $c) { return new Repository\Schedule\SpecialDayPeriodServiceRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersSpecialDayPeriodServiceTable::getTableName() ); }; $entries['domain.schedule.specialDay.period.location.repository'] = function (Container $c) { return new Repository\Schedule\SpecialDayPeriodLocationRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersSpecialDayPeriodLocationTable::getTableName() ); }; $entries['domain.users.providers.repository'] = function (Container $c) { return new Repository\User\ProviderRepository( $c->getDatabaseConnection(), DB\User\UsersTable::getTableName(), DB\User\Provider\ProvidersWeekDayTable::getTableName(), DB\User\Provider\ProvidersPeriodTable::getTableName(), DB\User\Provider\ProvidersPeriodServiceTable::getTableName(), DB\User\Provider\ProvidersPeriodLocationTable::getTableName(), DB\User\Provider\ProvidersTimeOutTable::getTableName(), DB\User\Provider\ProvidersSpecialDayTable::getTableName(), DB\User\Provider\ProvidersSpecialDayPeriodTable::getTableName(), DB\User\Provider\ProvidersSpecialDayPeriodServiceTable::getTableName(), DB\User\Provider\ProvidersSpecialDayPeriodLocationTable::getTableName(), DB\User\Provider\ProvidersDayOffTable::getTableName(), DB\User\Provider\ProvidersServiceTable::getTableName(), DB\User\Provider\ProvidersLocationTable::getTableName(), DB\Bookable\ServicesTable::getTableName(), DB\Location\LocationsTable::getTableName(), DB\User\Provider\ProvidersViewsTable::getTableName(), DB\User\Provider\ProvidersGoogleCalendarTable::getTableName(), DB\User\Provider\ProvidersOutlookCalendarTable::getTableName() ); }; $entries['domain.users.customers.repository'] = function (Container $c) { return new Repository\User\CustomerRepository( $c->getDatabaseConnection(), DB\User\UsersTable::getTableName() ); }; $entries['domain.wpUsers.repository'] = function (Container $c) { return new Repository\User\WPUserRepository( $c->getDatabaseConnection(), DB\User\WPUsersTable::getTableName(), DB\User\WPUsersTable::getMetaTableName(), DB\User\WPUsersTable::getDatabasePrefix() ); }; $entries['domain.booking.appointment.repository'] = function (Container $c) { return new Repository\Booking\Appointment\AppointmentRepository( $c->getDatabaseConnection(), DB\Booking\AppointmentsTable::getTableName(), DB\Bookable\ServicesTable::getTableName(), DB\Booking\CustomerBookingsTable::getTableName(), DB\Booking\CustomerBookingsToExtrasTable::getTableName(), DB\Bookable\ExtrasTable::getTableName(), DB\User\UsersTable::getTableName(), DB\Payment\PaymentsTable::getTableName(), DB\Coupon\CouponsTable::getTableName(), DB\User\Provider\ProvidersLocationTable::getTableName(), DB\User\Provider\ProvidersServiceTable::getTableName(), DB\Bookable\PackagesCustomersTable::getTableName(), DB\Bookable\PackagesCustomersServicesTable::getTableName() ); }; $entries['domain.booking.customerBooking.repository'] = function (Container $c) { return new Repository\Booking\Appointment\CustomerBookingRepository( $c->getDatabaseConnection(), DB\Booking\CustomerBookingsTable::getTableName() ); }; $entries['domain.booking.customerBookingExtra.repository'] = function (Container $c) { return new Repository\Booking\Appointment\CustomerBookingExtraRepository( $c->getDatabaseConnection(), DB\Booking\CustomerBookingsToExtrasTable::getTableName() ); }; $entries['domain.booking.customerBookingEventPeriod.repository'] = function (Container $c) { return new Repository\Booking\Event\CustomerBookingEventPeriodRepository( $c->getDatabaseConnection(), DB\Booking\CustomerBookingsToEventsPeriodsTable::getTableName() ); }; $entries['domain.booking.customerBookingEventTicket.repository'] = function (Container $c) { return new Repository\Booking\Event\CustomerBookingEventTicketRepository( $c->getDatabaseConnection(), DB\Booking\CustomerBookingToEventsTicketsTable::getTableName() ); }; $entries['domain.galleries.repository'] = function (Container $c) { return new Repository\Gallery\GalleryRepository( $c->getDatabaseConnection(), DB\Gallery\GalleriesTable::getTableName() ); }; $entries['domain.google.calendar.repository'] = function (Container $c) { return new Repository\Google\GoogleCalendarRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersGoogleCalendarTable::getTableName() ); }; $entries['domain.outlook.calendar.repository'] = function (Container $c) { return new Repository\Outlook\OutlookCalendarRepository( $c->getDatabaseConnection(), DB\User\Provider\ProvidersOutlookCalendarTable::getTableName() ); }; $entries['domain.customField.repository'] = function (Container $c) { return new Repository\CustomField\CustomFieldRepository( $c->getDatabaseConnection(), DB\CustomField\CustomFieldsTable::getTableName(), DB\CustomField\CustomFieldsOptionsTable::getTableName(), DB\CustomField\CustomFieldsServicesTable::getTableName(), DB\Bookable\ServicesTable::getTableName(), DB\CustomField\CustomFieldsEventsTable::getTableName(), DB\Booking\EventsTable::getTableName() ); }; $entries['domain.customFieldOption.repository'] = function (Container $c) { return new Repository\CustomField\CustomFieldOptionRepository( $c->getDatabaseConnection(), DB\CustomField\CustomFieldsOptionsTable::getTableName() ); }; $entries['domain.customFieldService.repository'] = function (Container $c) { return new Repository\CustomField\CustomFieldServiceRepository( $c->getDatabaseConnection(), DB\CustomField\CustomFieldsServicesTable::getTableName() ); }; $entries['domain.customFieldEvent.repository'] = function (Container $c) { return new Repository\CustomField\CustomFieldEventRepository( $c->getDatabaseConnection(), DB\CustomField\CustomFieldsEventsTable::getTableName() ); }; $entries['domain.booking.event.repository'] = function (Container $c) { return new Repository\Booking\Event\EventRepository( $c->getDatabaseConnection(), DB\Booking\EventsTable::getTableName() ); }; $entries['domain.booking.event.period.repository'] = function (Container $c) { return new Repository\Booking\Event\EventPeriodsRepository( $c->getDatabaseConnection(), DB\Booking\EventsPeriodsTable::getTableName() ); }; $entries['domain.booking.event.tag.repository'] = function (Container $c) { return new Repository\Booking\Event\EventTagsRepository( $c->getDatabaseConnection(), DB\Booking\EventsTagsTable::getTableName() ); }; $entries['domain.booking.event.ticket.repository'] = function (Container $c) { return new Repository\Booking\Event\EventTicketRepository( $c->getDatabaseConnection(), DB\Booking\EventsTicketsTable::getTableName() ); }; $entries['domain.booking.event.provider.repository'] = function (Container $c) { return new Repository\Booking\Event\EventProvidersRepository( $c->getDatabaseConnection(), DB\Booking\EventsProvidersTable::getTableName() ); }; $entries['domain.cache.repository'] = function (Container $c) { return new Repository\Cache\CacheRepository( $c->getDatabaseConnection(), DB\Cache\CacheTable::getTableName() ); }; ContainerConfig/domain.event.bus.php 0000666 00000001021 15165376447 0013524 0 ustar 00 <?php defined('ABSPATH') or die('No script kiddies please!'); use AmeliaBooking\Infrastructure\Common\Container; use League\Event\Emitter; use AmeliaBooking\Domain\Events\DomainEventBus; use AmeliaBooking\Infrastructure\WP\EventListeners\EventSubscribers; /** * @param Container $c * * @return DomainEventBus */ $entries['domain.event.bus'] = function ($c) { $eventBus = new DomainEventBus(new Emitter()); // Subscribe the WP event listeners EventSubscribers::subscribe($eventBus, $c); return $eventBus; }; ContainerConfig/command.bus.php 0000666 00000050733 15165376447 0012571 0 ustar 00 <?php defined('ABSPATH') or die('No script kiddies please!'); use AmeliaBooking\Application\Commands\Activation; use AmeliaBooking\Application\Commands\Bookable; use AmeliaBooking\Application\Commands\Booking; use AmeliaBooking\Application\Commands\Coupon; use AmeliaBooking\Application\Commands\CustomField; use AmeliaBooking\Application\Commands\Entities; use AmeliaBooking\Application\Commands\Stash; use AmeliaBooking\Application\Commands\Google; use AmeliaBooking\Application\Commands\Location; use AmeliaBooking\Application\Commands\Notification; use AmeliaBooking\Application\Commands\Outlook; use AmeliaBooking\Application\Commands\Payment; use AmeliaBooking\Application\Commands\PaymentGateway; use AmeliaBooking\Application\Commands\Report; use AmeliaBooking\Application\Commands\Import; use AmeliaBooking\Application\Commands\Search; use AmeliaBooking\Application\Commands\Settings; use AmeliaBooking\Application\Commands\Stats; use AmeliaBooking\Application\Commands\User; use AmeliaBooking\Application\Commands\Zoom; // @codingStandardsIgnoreStart $entries['command.bus'] = function ($c) { $commands = [ // Stash Stash\UpdateStashCommand::class => new Stash\UpdateStashCommandHandler($c), // Bookable/Category Bookable\Category\AddCategoryCommand::class => new Bookable\Category\AddCategoryCommandHandler($c), Bookable\Category\DeleteCategoryCommand::class => new Bookable\Category\DeleteCategoryCommandHandler($c), Bookable\Category\GetCategoriesCommand::class => new Bookable\Category\GetCategoriesCommandHandler($c), Bookable\Category\GetCategoryCommand::class => new Bookable\Category\GetCategoryCommandHandler($c), Bookable\Category\UpdateCategoriesPositionsCommand::class => new Bookable\Category\UpdateCategoriesPositionsCommandHandler($c), Bookable\Category\UpdateCategoryCommand::class => new Bookable\Category\UpdateCategoryCommandHandler($c), // Bookable/Service Bookable\Service\AddServiceCommand::class => new Bookable\Service\AddServiceCommandHandler($c), Bookable\Service\DeleteServiceCommand::class => new Bookable\Service\DeleteServiceCommandHandler($c), Bookable\Service\GetServiceCommand::class => new Bookable\Service\GetServiceCommandHandler($c), Bookable\Service\GetServiceDeleteEffectCommand::class => new Bookable\Service\GetServiceDeleteEffectCommandHandler($c), Bookable\Service\GetServicesCommand::class => new Bookable\Service\GetServicesCommandHandler($c), Bookable\Service\UpdateServiceCommand::class => new Bookable\Service\UpdateServiceCommandHandler($c), Bookable\Service\UpdateServiceStatusCommand::class => new Bookable\Service\UpdateServiceStatusCommandHandler($c), Bookable\Service\UpdateServicesPositionsCommand::class => new Bookable\Service\UpdateServicesPositionsCommandHandler($c), // Booking/Appointment Booking\Appointment\AddAppointmentCommand::class => new Booking\Appointment\AddAppointmentCommandHandler($c), Booking\Appointment\AddBookingCommand::class => new Booking\Appointment\AddBookingCommandHandler($c), Booking\Appointment\CancelBookingCommand::class => new Booking\Appointment\CancelBookingCommandHandler($c), Booking\Appointment\CancelBookingRemotelyCommand::class => new Booking\Appointment\CancelBookingRemotelyCommandHandler($c), Booking\Appointment\DeleteAppointmentCommand::class => new Booking\Appointment\DeleteAppointmentCommandHandler($c), Booking\Appointment\GetAppointmentCommand::class => new Booking\Appointment\GetAppointmentCommandHandler($c), Booking\Appointment\GetAppointmentsCommand::class => new Booking\Appointment\GetAppointmentsCommandHandler($c), Booking\Appointment\GetTimeSlotsCommand::class => new Booking\Appointment\GetTimeSlotsCommandHandler($c), Booking\Appointment\UpdateAppointmentCommand::class => new Booking\Appointment\UpdateAppointmentCommandHandler($c), Booking\Appointment\UpdateAppointmentStatusCommand::class => new Booking\Appointment\UpdateAppointmentStatusCommandHandler($c), Booking\Appointment\UpdateAppointmentTimeCommand::class => new Booking\Appointment\UpdateAppointmentTimeCommandHandler($c), Booking\Appointment\ReassignBookingCommand::class => new Booking\Appointment\ReassignBookingCommandHandler($c), Booking\Appointment\SuccessfulBookingCommand::class => new Booking\Appointment\SuccessfulBookingCommandHandler($c), Booking\Appointment\GetIcsCommand::class => new Booking\Appointment\GetIcsCommandHandler($c), // Booking/Event Booking\Event\AddEventCommand::class => new Booking\Event\AddEventCommandHandler($c), Booking\Event\GetEventCommand::class => new Booking\Event\GetEventCommandHandler($c), Booking\Event\GetEventsCommand::class => new Booking\Event\GetEventsCommandHandler($c), Booking\Event\UpdateEventCommand::class => new Booking\Event\UpdateEventCommandHandler($c), Booking\Event\UpdateEventStatusCommand::class => new Booking\Event\UpdateEventStatusCommandHandler($c), Booking\Event\DeleteEventBookingCommand::class => new Booking\Event\DeleteEventBookingCommandHandler($c), Booking\Event\UpdateEventBookingCommand::class => new Booking\Event\UpdateEventBookingCommandHandler($c), Booking\Event\DeleteEventCommand::class => new Booking\Event\DeleteEventCommandHandler($c), Booking\Event\GetEventDeleteEffectCommand::class => new Booking\Event\GetEventDeleteEffectCommandHandler($c), Booking\Event\GetCalendarEventsCommand::class => new Booking\Event\GetCalendarEventsCommandHandler($c), // Entities Entities\GetEntitiesCommand::class => new Entities\GetEntitiesCommandHandler($c), // Notification Notification\GetNotificationsCommand::class => new Notification\GetNotificationsCommandHandler($c), Notification\SendTestEmailCommand::class => new Notification\SendTestEmailCommandHandler($c), Notification\UpdateNotificationCommand::class => new Notification\UpdateNotificationCommandHandler($c), Notification\SendAmeliaSmsApiRequestCommand::class => new Notification\SendAmeliaSmsApiRequestCommandHandler($c), Notification\UpdateSMSNotificationHistoryCommand::class => new Notification\UpdateSMSNotificationHistoryCommandHandler($c), Notification\GetSMSNotificationsHistoryCommand::class => new Notification\GetSMSNotificationsHistoryCommandHandler($c), Notification\SendUndeliveredNotificationsCommand::class => new Notification\SendUndeliveredNotificationsCommandHandler($c), Notification\UpdateNotificationStatusCommand::class => new Notification\UpdateNotificationStatusCommandHandler($c), // Payment Payment\AddPaymentCommand::class => new Payment\AddPaymentCommandHandler($c), Payment\DeletePaymentCommand::class => new Payment\DeletePaymentCommandHandler($c), Payment\GetPaymentCommand::class => new Payment\GetPaymentCommandHandler($c), Payment\GetPaymentsCommand::class => new Payment\GetPaymentsCommandHandler($c), Payment\UpdatePaymentCommand::class => new Payment\UpdatePaymentCommandHandler($c), // Settings Settings\GetSettingsCommand::class => new Settings\GetSettingsCommandHandler($c), Settings\UpdateSettingsCommand::class => new Settings\UpdateSettingsCommandHandler($c), // User/Customer User\Customer\AddCustomerCommand::class => new User\Customer\AddCustomerCommandHandler($c), User\Customer\GetCustomerCommand::class => new User\Customer\GetCustomerCommandHandler($c), User\Customer\GetCustomersCommand::class => new User\Customer\GetCustomersCommandHandler($c), User\Customer\UpdateCustomerCommand::class => new User\Customer\UpdateCustomerCommandHandler($c), // User User\DeleteUserCommand::class => new User\DeleteUserCommandHandler($c), User\GetCurrentUserCommand::class => new User\GetCurrentUserCommandHandler($c), User\GetUserDeleteEffectCommand::class => new User\GetUserDeleteEffectCommandHandler($c), User\GetWPUsersCommand::class => new User\GetWPUsersCommandHandler($c), // User/Provider User\Provider\AddProviderCommand::class => new User\Provider\AddProviderCommandHandler($c), User\Provider\GetProviderCommand::class => new User\Provider\GetProviderCommandHandler($c), User\Provider\GetProvidersCommand::class => new User\Provider\GetProvidersCommandHandler($c), User\Provider\UpdateProviderCommand::class => new User\Provider\UpdateProviderCommandHandler($c), User\Provider\UpdateProviderStatusCommand::class => new User\Provider\UpdateProviderStatusCommandHandler($c), // Status Stats\AddStatsCommand::class => new AmeliaBooking\Application\Commands\Stats\AddStatsCommandHandler($c), Stats\GetStatsCommand::class => new AmeliaBooking\Application\Commands\Stats\GetStatsCommandHandler($c), Import\ImportCustomersCommand::class => new Import\ImportCustomersCommandHandler($c), ]; if (!AMELIA_LITE_VERSION) { $commands = array_merge($commands, [ // Activation Activation\ActivatePluginCommand::class => new Activation\ActivatePluginCommandHandler($c), Activation\DeactivatePluginCommand::class => new Activation\DeactivatePluginCommandHandler($c), Activation\DeactivatePluginEnvatoCommand::class => new Activation\DeactivatePluginEnvatoCommandHandler($c), // Bookable/Package Bookable\Package\AddPackageCommand::class => new Bookable\Package\AddPackageCommandHandler($c), Bookable\Package\DeletePackageCommand::class => new Bookable\Package\DeletePackageCommandHandler($c), Bookable\Package\GetPackagesCommand::class => new Bookable\Package\GetPackagesCommandHandler($c), Bookable\Package\GetPackageDeleteEffectCommand::class => new Bookable\Package\GetPackageDeleteEffectCommandHandler($c), Bookable\Package\UpdatePackageCommand::class => new Bookable\Package\UpdatePackageCommandHandler($c), Bookable\Package\UpdatePackageStatusCommand::class => new Bookable\Package\UpdatePackageStatusCommandHandler($c), Bookable\Package\DeletePackageCustomerCommand::class => new Bookable\Package\DeletePackageCustomerCommandHandler($c), Bookable\Package\UpdatePackageCustomerCommand::class => new Bookable\Package\UpdatePackageCustomerCommandHandler($c), Bookable\Package\UpdatePackagesPositionsCommand::class => new Bookable\Package\UpdatePackagesPositionsCommandHandler($c), // Bookable/Resource Bookable\Resource\AddResourceCommand::class => new Bookable\Resource\AddResourceCommandHandler($c), Bookable\Resource\UpdateResourceCommand::class => new Bookable\Resource\UpdateResourceCommandHandler($c), Bookable\Resource\UpdateResourceStatusCommand::class => new Bookable\Resource\UpdateResourceStatusCommandHandler($c), Bookable\Resource\DeleteResourceCommand::class => new Bookable\Resource\DeleteResourceCommandHandler($c), Bookable\Resource\GetResourcesCommand::class => new Bookable\Resource\GetResourcesCommandHandler($c), // Bookable/Extra Bookable\Extra\AddExtraCommand::class => new Bookable\Extra\AddExtraCommandHandler($c), Bookable\Extra\DeleteExtraCommand::class => new Bookable\Extra\DeleteExtraCommandHandler($c), Bookable\Extra\GetExtraCommand::class => new Bookable\Extra\GetExtraCommandHandler($c), Bookable\Extra\GetExtrasCommand::class => new Bookable\Extra\GetExtrasCommandHandler($c), Bookable\Extra\UpdateExtraCommand::class => new Bookable\Extra\UpdateExtraCommandHandler($c), // Coupon Coupon\AddCouponCommand::class => new Coupon\AddCouponCommandHandler($c), Coupon\DeleteCouponCommand::class => new Coupon\DeleteCouponCommandHandler($c), Coupon\GetCouponCommand::class => new Coupon\GetCouponCommandHandler($c), Coupon\GetCouponsCommand::class => new Coupon\GetCouponsCommandHandler($c), Coupon\GetValidCouponCommand::class => new Coupon\GetValidCouponCommandHandler($c), Coupon\UpdateCouponCommand::class => new Coupon\UpdateCouponCommandHandler($c), Coupon\UpdateCouponStatusCommand::class => new Coupon\UpdateCouponStatusCommandHandler($c), // CustomField CustomField\GetCustomFieldsCommand::class => new CustomField\GetCustomFieldsCommandHandler($c), CustomField\GetCustomFieldFileCommand::class => new CustomField\GetCustomFieldFileCommandHandler($c), CustomField\AddCustomFieldCommand::class => new CustomField\AddCustomFieldCommandHandler($c), CustomField\DeleteCustomFieldCommand::class => new CustomField\DeleteCustomFieldCommandHandler($c), CustomField\UpdateCustomFieldCommand::class => new CustomField\UpdateCustomFieldCommandHandler($c), CustomField\UpdateCustomFieldsPositionsCommand::class => new CustomField\UpdateCustomFieldsPositionsCommandHandler($c), // Google Google\DisconnectFromGoogleAccountCommand::class => new Google\DisconnectFromGoogleAccountCommandHandler($c), Google\FetchAccessTokenWithAuthCodeCommand::class => new Google\FetchAccessTokenWithAuthCodeCommandHandler($c), Google\GetGoogleAuthURLCommand::class => new Google\GetGoogleAuthURLCommandHandler($c), // Outlook Outlook\DisconnectFromOutlookAccountCommand::class => new Outlook\DisconnectFromOutlookAccountCommandHandler($c), Outlook\GetOutlookAuthURLCommand::class => new Outlook\GetOutlookAuthURLCommandHandler($c), Outlook\FetchAccessTokenWithAuthCodeOutlookCommand::class => new Outlook\FetchAccessTokenWithAuthCodeOutlookCommandHandler($c), // Location Location\AddLocationCommand::class => new Location\AddLocationCommandHandler($c), Location\DeleteLocationCommand::class => new Location\DeleteLocationCommandHandler($c), Location\GetLocationCommand::class => new Location\GetLocationCommandHandler($c), Location\GetLocationDeleteEffectCommand::class => new Location\GetLocationDeleteEffectCommandHandler($c), Location\GetLocationsCommand::class => new Location\GetLocationsCommandHandler($c), Location\UpdateLocationCommand::class => new Location\UpdateLocationCommandHandler($c), Location\UpdateLocationStatusCommand::class => new Location\UpdateLocationStatusCommandHandler($c), // Notification Notification\SendScheduledNotificationsCommand::class => new Notification\SendScheduledNotificationsCommandHandler($c), Notification\SendTestWhatsAppCommand::class => new Notification\SendTestWhatsAppCommandHandler($c), Notification\UpdateNotificationCommand::class => new Notification\UpdateNotificationCommandHandler($c), Notification\AddNotificationCommand::class => new Notification\AddNotificationCommandHandler($c), Notification\DeleteNotificationCommand::class => new Notification\DeleteNotificationCommandHandler($c), Notification\UpdateNotificationStatusCommand::class => new Notification\UpdateNotificationStatusCommandHandler($c), // Payment PaymentGateway\PayPalPaymentCallbackCommand::class => new PaymentGateway\PayPalPaymentCallbackCommandHandler($c), PaymentGateway\PayPalPaymentCommand::class => new PaymentGateway\PayPalPaymentCommandHandler($c), PaymentGateway\WooCommercePaymentCommand::class => new PaymentGateway\WooCommercePaymentCommandHandler($c), PaymentGateway\WooCommerceProductsCommand::class => new PaymentGateway\WooCommerceProductsCommandHandler($c), PaymentGateway\MolliePaymentNotifyCommand::class => new PaymentGateway\MolliePaymentNotifyCommandHandler($c), PaymentGateway\MolliePaymentCommand::class => new PaymentGateway\MolliePaymentCommandHandler($c), PaymentGateway\RazorpayPaymentCommand::class => new PaymentGateway\RazorpayPaymentCommandHandler($c), Payment\PaymentCallbackCommand::class => new Payment\PaymentCallbackCommandHandler($c), Payment\PaymentLinkCommand::class => new Payment\PaymentLinkCommandHandler($c), // Report Report\GetAppointmentsCommand::class => new Report\GetAppointmentsCommandHandler($c), Report\GetCouponsCommand::class => new Report\GetCouponsCommandHandler($c), Report\GetCustomersCommand::class => new Report\GetCustomersCommandHandler($c), Report\GetPaymentsCommand::class => new Report\GetPaymentsCommandHandler($c), Report\GetEventAttendeesCommand::class => new Report\GetEventAttendeesCommandHandler($c), // Search Search\GetSearchCommand::class => new Search\GetSearchCommandHandler($c), // User/Customer User\Customer\AddCustomerCommand::class => new User\Customer\AddCustomerCommandHandler($c), User\Customer\GetCustomerCommand::class => new User\Customer\GetCustomerCommandHandler($c), User\Customer\GetCustomersCommand::class => new User\Customer\GetCustomersCommandHandler($c), User\Customer\UpdateCustomerCommand::class => new User\Customer\UpdateCustomerCommandHandler($c), User\Customer\ReauthorizeCommand::class => new User\Customer\ReauthorizeCommandHandler($c), User\LoginCabinetCommand::class => new User\LoginCabinetCommandHandler($c), User\LogoutCabinetCommand::class => new User\LogoutCabinetCommandHandler($c), // User/Provider User\Provider\AddProviderCommand::class => new User\Provider\AddProviderCommandHandler($c), User\Provider\GetProviderCommand::class => new User\Provider\GetProviderCommandHandler($c), User\Provider\GetProvidersCommand::class => new User\Provider\GetProvidersCommandHandler($c), User\Provider\UpdateProviderCommand::class => new User\Provider\UpdateProviderCommandHandler($c), User\Provider\UpdateProviderStatusCommand::class => new User\Provider\UpdateProviderStatusCommandHandler($c), Zoom\GetUsersCommand::class => new Zoom\GetUsersCommandHandler($c), ]); } return League\Tactician\Setup\QuickStart::create($commands); }; // @codingStandardsIgnoreEnd ContainerConfig/infrastructure.user.php 0000666 00000002117 15165376447 0014411 0 ustar 00 <?php /** * Assembling domain services: * Returning the current user entity based on WP user */ defined('ABSPATH') or die('No script kiddies please!'); /** * Permissions service * * @param $c * * @return \AmeliaBooking\Domain\Entity\User\AbstractUser|bool|null */ $entries['logged.in.user'] = function ($c) { $wpUserService = new AmeliaBooking\Infrastructure\WP\UserService\UserService($c); return $wpUserService->getCurrentUser(); }; /** * @param $c * * @return \AmeliaBooking\Infrastructure\WP\UserService\UserService */ $entries['users.service'] = function ($c) { return new AmeliaBooking\Infrastructure\WP\UserService\UserService($c); }; /** * @return \AmeliaBooking\Infrastructure\WP\UserService\UserAvatar */ $entries['user.avatar'] = function () { return new AmeliaBooking\Infrastructure\WP\UserService\UserAvatar(); }; /** * Create WordPress user service * * @return \AmeliaBooking\Infrastructure\WP\UserService\CreateWPUser */ $entries['user.create.wp.user'] = function () { return new AmeliaBooking\Infrastructure\WP\UserService\CreateWPUser(); }; ContainerConfig/request.php 0000666 00000002261 15165376447 0012044 0 ustar 00 <?php use Slim\Http\Request; use Slim\Http\Uri; $entries['request'] = function (AmeliaBooking\Infrastructure\Common\Container $c) { $curUri = Uri::createFromEnvironment($c->get('environment')); // fix callback url for Razorpay payment through link since Razorpay encodes callback urls $newRoute = str_replace( '__payments__callback', '/payments/callback', $curUri->getQuery() ); // fix callback url for whatsapp webhooks $newRoute = str_replace( '__notifications__whatsapp__webhook', '/notifications/whatsapp/webhook', $newRoute ); $newRoute = str_replace( ['XDEBUG_SESSION_START=PHPSTORM&' . AMELIA_ACTION_SLUG, AMELIA_ACTION_SLUG], '', $newRoute ); $newPath = strpos($newRoute, '&') ? substr( $newRoute, 0, strpos($newRoute, '&') ) : $newRoute; $newQuery = strpos($newRoute, '&') ? substr( $newRoute, strpos($newRoute, '&') + 1 ) : ''; return Request::createFromEnvironment($c->get('environment')) ->withUri( $curUri ->withPath($newPath) ->withQuery($newQuery) ); }; ContainerConfig/infrastructure.services.php 0000666 00000011602 15165376447 0015255 0 ustar 00 <?php /** * Assembling infrastructure services: * Instantiating infrastructure services */ use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService; use AmeliaBooking\Infrastructure\Services\LessonSpace\LessonSpaceService; use AmeliaBooking\Infrastructure\Services\Notification\MailerFactory; use AmeliaBooking\Infrastructure\Services\Notification\MailgunService; use AmeliaBooking\Infrastructure\Services\Notification\PHPMailService; use AmeliaBooking\Infrastructure\Services\Notification\SMTPService; use AmeliaBooking\Infrastructure\Services\Notification\WpMailService; use AmeliaBooking\Infrastructure\Services\Outlook\OutlookCalendarService; use AmeliaBooking\Infrastructure\Services\Recaptcha\RecaptchaService; use AmeliaBooking\Infrastructure\Services\Zoom\ZoomService; defined('ABSPATH') or die('No script kiddies please!'); /** * Mailer Service * * @param Container $c * * @return MailgunService|PHPMailService|SMTPService|WpMailService */ $entries['infrastructure.mail.service'] = function ($c) { return MailerFactory::create($c->get('domain.settings.service')); }; /** * Report Service * * @return AmeliaBooking\Infrastructure\Services\Report\Spout\CsvService */ $entries['infrastructure.report.csv.service'] = function () { return new AmeliaBooking\Infrastructure\Services\Report\Spout\CsvService(); }; /** * PayPal Payment Service * * @param Container $c * * @return AmeliaBooking\Infrastructure\Services\Payment\PayPalService */ $entries['infrastructure.payment.payPal.service'] = function ($c) { return new AmeliaBooking\Infrastructure\Services\Payment\PayPalService( $c->get('domain.settings.service') ); }; /** * Stripe Payment Service * * @param Container $c * * @return AmeliaBooking\Infrastructure\Services\Payment\StripeService */ $entries['infrastructure.payment.stripe.service'] = function ($c) { return new AmeliaBooking\Infrastructure\Services\Payment\StripeService( $c->get('domain.settings.service') ); }; /** * Mollie Payment Service * * @param Container $c * * @return AmeliaBooking\Infrastructure\Services\Payment\MollieService */ $entries['infrastructure.payment.mollie.service'] = function ($c) { return new AmeliaBooking\Infrastructure\Services\Payment\MollieService( $c->get('domain.settings.service') ); }; /** * Razorpay Payment Service * * @param Container $c * * @return AmeliaBooking\Infrastructure\Services\Payment\RazorpayService */ $entries['infrastructure.payment.razorpay.service'] = function ($c) { return new AmeliaBooking\Infrastructure\Services\Payment\RazorpayService( $c->get('domain.settings.service') ); }; /** * Currency Service * * @param Container $c * * @return AmeliaBooking\Infrastructure\Services\Payment\CurrencyService */ $entries['infrastructure.payment.currency.service'] = function ($c) { return new AmeliaBooking\Infrastructure\Services\Payment\CurrencyService( $c->get('domain.settings.service') ); }; /** * Less Parser Service * * @param Container $c * * @return AmeliaBooking\Infrastructure\Services\Frontend\LessParserService */ $entries['infrastructure.frontend.lessParser.service'] = function ($c) { return new AmeliaBooking\Infrastructure\Services\Frontend\LessParserService( AMELIA_PATH . '/assets/less/frontend/amelia-booking.less', AMELIA_UPLOADS_PATH . '/amelia/css', $c->get('domain.settings.service') ); }; /** * Google Calendar Service * * @param Container $c * * @return GoogleCalendarService */ $entries['infrastructure.google.calendar.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Infrastructure\Services\Google\GoogleCalendarService($c); } : function () {}; /** * Zoom Service * * @param Container $c * * @return ZoomService */ $entries['infrastructure.zoom.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Infrastructure\Services\Zoom\ZoomService( $c->get('domain.settings.service') ); } : function () {}; /** * Lesson Space Service * * @param Container $c * * @return LessonSpaceService */ $entries['infrastructure.lesson.space.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new LessonSpaceService( $c, $c->get('domain.settings.service') ); } : function () {}; /** * Outlook Service * * @param Container $c * * @return OutlookCalendarService */ $entries['infrastructure.outlook.calendar.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new OutlookCalendarService($c); } : function () {}; /** * Recaptcha Service * * @param Container $c * * @return RecaptchaService */ $entries['infrastructure.recaptcha.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Infrastructure\Services\Recaptcha\RecaptchaService( $c->get('domain.settings.service') ); } : function () {}; ContainerConfig/application.services.php 0000666 00000027214 15165376447 0014506 0 ustar 00 <?php /** * Assembling application services: * Instantiating application services and injecting the Infrastructure layer implementations */ use AmeliaBooking\Application\Services\Bookable\AbstractPackageApplicationService; use AmeliaBooking\Application\Services\Bookable\BookableApplicationService; use AmeliaBooking\Application\Services\Booking\BookingApplicationService; use AmeliaBooking\Application\Services\Booking\AppointmentApplicationService; use AmeliaBooking\Application\Services\Booking\EventApplicationService; use AmeliaBooking\Application\Services\Cache\CacheApplicationService; use AmeliaBooking\Application\Services\Coupon\CouponApplicationService; use AmeliaBooking\Application\Services\Gallery\GalleryApplicationService; use AmeliaBooking\Application\Services\Location\LocationApplicationService; use AmeliaBooking\Application\Services\Payment\PaymentApplicationService; use AmeliaBooking\Application\Services\Reservation\ReservationService; use AmeliaBooking\Application\Services\TimeSlot\TimeSlotService; use AmeliaBooking\Application\Services\User\CustomerApplicationService; use AmeliaBooking\Application\Services\User\ProviderApplicationService; use AmeliaBooking\Application\Services\User\UserApplicationService; use AmeliaBooking\Domain\Entity\Booking\Reservation; use AmeliaBooking\Infrastructure\Common\Container; defined('ABSPATH') or die('No script kiddies please!'); /** * Customer service * * @param Container $c * * @return UserApplicationService */ $entries['application.user.service'] = function ($c) { return new AmeliaBooking\Application\Services\User\UserApplicationService($c); }; /** * Provider service * * @param Container $c * * @return ProviderApplicationService */ $entries['application.user.provider.service'] = function ($c) { return new AmeliaBooking\Application\Services\User\ProviderApplicationService($c); }; /** * Customer service * * @param Container $c * * @return CustomerApplicationService */ $entries['application.user.customer.service'] = function ($c) { return new AmeliaBooking\Application\Services\User\CustomerApplicationService($c); }; /** * Location service * * @return \AmeliaBooking\Domain\Services\Location\CurrentLocationInterface */ $entries['application.currentLocation.service'] = function () { return new AmeliaBooking\Infrastructure\WP\Services\Location\CurrentLocationLite(); }; /** * Appointment service * * @param Container $c * * @return AppointmentApplicationService */ $entries['application.booking.appointment.service'] = function ($c) { return new AmeliaBooking\Application\Services\Booking\AppointmentApplicationService($c); }; /** * Event service * * @param Container $c * * @return EventApplicationService */ $entries['application.booking.event.service'] = function ($c) { return new AmeliaBooking\Application\Services\Booking\EventApplicationService($c); }; /** * Reservation service * * @param Container $c * * @return ReservationService */ $entries['application.reservation.service'] = function ($c) { return new AmeliaBooking\Application\Services\Reservation\ReservationService($c); }; /** * Reservation * * @param bool $validate * * @return Reservation */ $entries['application.reservation'] = function ($validate) { return new AmeliaBooking\Domain\Entity\Booking\Reservation($validate); }; /** * Appointment Reservation service * * @param Container $c * * @return AmeliaBooking\Application\Services\Reservation\AppointmentReservationService */ $entries['application.reservation.appointment.service'] = function ($c) { return new AmeliaBooking\Application\Services\Reservation\AppointmentReservationService($c); }; /** * Package Reservation service * * @param Container $c * * @return AmeliaBooking\Application\Services\Reservation\AppointmentReservationService */ $entries['application.reservation.appointment.service'] = function ($c) { return new AmeliaBooking\Application\Services\Reservation\AppointmentReservationService($c); }; /** * Event Reservation service * * @param Container $c * * @return AmeliaBooking\Application\Services\Reservation\EventReservationService */ $entries['application.reservation.event.service'] = function ($c) { return new AmeliaBooking\Application\Services\Reservation\EventReservationService($c); }; /** * Booking service * * @param Container $c * * @return BookingApplicationService */ $entries['application.booking.booking.service'] = function ($c) { return new AmeliaBooking\Application\Services\Booking\BookingApplicationService($c); }; /** * Bookable service * * @param Container $c * * @return BookableApplicationService */ $entries['application.bookable.service'] = function ($c) { return new AmeliaBooking\Application\Services\Bookable\BookableApplicationService($c); }; /** * Bookable package * * @param Container $c * * @return AbstractPackageApplicationService */ $entries['application.bookable.package'] = function ($c) { return new AmeliaBooking\Application\Services\Bookable\BasicPackageApplicationService($c); }; /** * Gallery service * * @param Container $c * * @return GalleryApplicationService */ $entries['application.gallery.service'] = function ($c) { return new AmeliaBooking\Application\Services\Gallery\GalleryApplicationService($c); }; /** * Calendar service * * @param Container $c * * @return TimeSlotService */ $entries['application.timeSlot.service'] = function ($c) { return new AmeliaBooking\Application\Services\TimeSlot\TimeSlotService($c); }; /** * Cache service * * @param Container $c * * @return CacheApplicationService */ $entries['application.cache.service'] = function ($c) { return new AmeliaBooking\Application\Services\Cache\CacheApplicationService($c); }; /** * Coupon service * * @param Container $c * * @return CouponApplicationService */ $entries['application.coupon.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Application\Services\Coupon\CouponApplicationService($c); } : function () { return null; }; /** * Location service * * @param Container $c * * @return LocationApplicationService */ $entries['application.location.service'] = function ($c) { return new AmeliaBooking\Application\Services\Location\LocationApplicationService($c); }; /** * Email Notification Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Notification\EmailNotificationService */ $entries['application.emailNotification.service'] = function ($c) { return new AmeliaBooking\Application\Services\Notification\EmailNotificationService($c, 'email'); }; /** * Notification Helper Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Notification\NotificationHelperService */ $entries['application.notificationHelper.service'] = function ($c) { return new AmeliaBooking\Application\Services\Notification\NotificationHelperService($c); }; /** * SMS Notification Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Notification\SMSNotificationService */ $entries['application.smsNotification.service'] = function ($c) { return new AmeliaBooking\Application\Services\Notification\SMSNotificationService($c, 'sms'); }; /** * WhatsApp Notification Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Notification\BasicWhatsAppNotificationService */ $entries['application.whatsAppNotification.service'] = function ($c) { return new AmeliaBooking\Application\Services\Notification\BasicWhatsAppNotificationService($c, 'whatsapp'); }; /** * Appointment Notification Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Placeholder\AppointmentPlaceholderService */ $entries['application.placeholder.appointment.service'] = function ($c) { return new AmeliaBooking\Application\Services\Placeholder\AppointmentPlaceholderService($c); }; /** * Package Notification Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Placeholder\AppointmentPlaceholderService */ $entries['application.placeholder.appointment.service'] = function ($c) { return new AmeliaBooking\Application\Services\Placeholder\AppointmentPlaceholderService($c); }; /** * Event Notification Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Placeholder\EventPlaceholderService */ $entries['application.placeholder.event.service'] = function ($c) { return new AmeliaBooking\Application\Services\Placeholder\EventPlaceholderService($c); }; /** * Stats Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Stats\StatsService */ $entries['application.stats.service'] = function ($c) { return new AmeliaBooking\Application\Services\Stats\StatsService($c); }; /** * Helper Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Helper\HelperService */ $entries['application.helper.service'] = function ($c) { return new AmeliaBooking\Application\Services\Helper\HelperService($c); }; /** * Settings Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Settings\SettingsService */ $entries['application.settings.service'] = function ($c) { return new AmeliaBooking\Application\Services\Settings\SettingsService($c); }; /** * SMS API Service * * @param Container $c * * @return \AmeliaBooking\Domain\Services\Notification\SMSAPIServiceInterface */ $entries['application.smsApi.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Application\Services\Notification\SMSAPIService($c); } : function ($c) { return new AmeliaBooking\Infrastructure\WP\Services\Notification\SMSAPIServiceLite($c); }; /** * WhatsApp Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Notification\WhatsAppService */ $entries['application.whatsApp.service'] = function ($c) { return new AmeliaBooking\Application\Services\Notification\WhatsAppService($c); }; /** * Payment service * * @param Container $c * * @return PaymentApplicationService */ $entries['application.payment.service'] = function ($c) { return new AmeliaBooking\Application\Services\Payment\PaymentApplicationService($c); }; /** * Upload File Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\CustomField\CustomFieldApplicationService */ $entries['application.customField.service'] = function ($c) { return new AmeliaBooking\Application\Services\CustomField\CustomFieldApplicationService($c); }; /** * Web Hook Service * * @param Container $c * * @return AmeliaBooking\Application\Services\WebHook\WebHookApplicationService */ $entries['application.webHook.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Application\Services\WebHook\WebHookApplicationService($c); } : function () { return null; }; /** * Zoom Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Zoom\ZoomApplicationService */ $entries['application.zoom.service'] = !AMELIA_LITE_VERSION ? function ($c) { return new AmeliaBooking\Application\Services\Zoom\ZoomApplicationService($c); } : function () { return null; }; /** * ICS File Service * * @param Container $c * * @return \AmeliaBooking\Application\Services\Booking\IcsApplicationService */ $entries['application.ics.service'] = function ($c) { return new AmeliaBooking\Application\Services\Booking\IcsApplicationService($c); }; /** * Stash Service * * @param Container $c * * @return AmeliaBooking\Application\Services\Stash\StashApplicationService */ $entries['application.stash.service'] = function ($c) { return new AmeliaBooking\Application\Services\Stash\StashApplicationService($c); }; ContainerConfig/domain.services.php 0000666 00000012452 15165376447 0013450 0 ustar 00 <?php /** * Assembling domain services: * Instantiating domain services and injecting the Infrastructure layer implementations */ defined('ABSPATH') or die('No script kiddies please!'); /** * Permissions service * * @param $c * * @return \AmeliaBooking\Domain\Services\Permissions\PermissionsService */ $entries['domain.permissions.service'] = function ($c) { return new AmeliaBooking\Domain\Services\Permissions\PermissionsService( $c, new AmeliaBooking\Infrastructure\WP\PermissionsService\PermissionsChecker() ); }; /** * Appointment service * * @return \AmeliaBooking\Domain\Services\Booking\AppointmentDomainService */ $entries['domain.booking.appointment.service'] = function () { return new AmeliaBooking\Domain\Services\Booking\AppointmentDomainService(); }; /** * Event service * * @return \AmeliaBooking\Domain\Services\Booking\EventDomainService */ $entries['domain.booking.event.service'] = function () { return new AmeliaBooking\Domain\Services\Booking\EventDomainService(); }; /** * Settings service * * @return \AmeliaBooking\Domain\Services\Settings\SettingsService */ $entries['domain.settings.service'] = function () { return new AmeliaBooking\Domain\Services\Settings\SettingsService( new AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage() ); }; /** * @return \AmeliaBooking\Domain\Services\Interval\IntervalService */ $entries['domain.interval.service'] = function () { return new AmeliaBooking\Domain\Services\Interval\IntervalService(); }; /** * @return \AmeliaBooking\Domain\Services\User\ProviderService */ $entries['domain.user.provider.service'] = function () { return new AmeliaBooking\Domain\Services\User\ProviderService( new AmeliaBooking\Domain\Services\Interval\IntervalService() ); }; /** * @return \AmeliaBooking\Domain\Services\Location\LocationService */ $entries['domain.location.service'] = function () { return new AmeliaBooking\Domain\Services\Location\LocationService(); }; /** * @return \AmeliaBooking\Domain\Services\Schedule\ScheduleService */ $entries['domain.schedule.service'] = function () { $intervalService = new AmeliaBooking\Domain\Services\Interval\IntervalService(); $locationService = new AmeliaBooking\Domain\Services\Location\LocationService(); $providerService = new AmeliaBooking\Domain\Services\User\ProviderService( $intervalService ); return new AmeliaBooking\Domain\Services\Schedule\ScheduleService( $intervalService, $providerService, $locationService ); }; /** * @return \AmeliaBooking\Domain\Services\Resource\AbstractResourceService */ $entries['domain.resource.service'] = function () { $intervalService = new AmeliaBooking\Domain\Services\Interval\IntervalService(); $locationService = new AmeliaBooking\Domain\Services\Location\LocationService(); $providerService = new AmeliaBooking\Domain\Services\User\ProviderService( $intervalService ); $scheduleService = new AmeliaBooking\Domain\Services\Schedule\ScheduleService( $intervalService, $providerService, $locationService ); // Change for Basic Licence - BasicResourceService return new AmeliaBooking\Domain\Services\Resource\BasicResourceService( $intervalService, $scheduleService ); }; /** * @return \AmeliaBooking\Domain\Services\Entity\EntityService */ $entries['domain.entity.service'] = function () { $intervalService = new AmeliaBooking\Domain\Services\Interval\IntervalService(); $locationService = new AmeliaBooking\Domain\Services\Location\LocationService(); $providerService = new AmeliaBooking\Domain\Services\User\ProviderService( $intervalService ); $scheduleService = new AmeliaBooking\Domain\Services\Schedule\ScheduleService( $intervalService, $providerService, $locationService ); // Change for Basic Licence - BasicResourceService $resourceService = new AmeliaBooking\Domain\Services\Resource\BasicResourceService( $intervalService, $scheduleService ); return new AmeliaBooking\Domain\Services\Entity\EntityService( $providerService, $resourceService ); }; /** * @return \AmeliaBooking\Domain\Services\TimeSlot\TimeSlotService */ $entries['domain.timeSlot.service'] = function () { $intervalService = new AmeliaBooking\Domain\Services\Interval\IntervalService(); $locationService = new AmeliaBooking\Domain\Services\Location\LocationService(); $providerService = new AmeliaBooking\Domain\Services\User\ProviderService( $intervalService ); $scheduleService = new AmeliaBooking\Domain\Services\Schedule\ScheduleService( $intervalService, $providerService, $locationService ); // Change for Basic Licence - BasicResourceService $resourceService = new AmeliaBooking\Domain\Services\Resource\BasicResourceService( $intervalService, $scheduleService ); $entityService = new AmeliaBooking\Domain\Services\Entity\EntityService( $providerService, $resourceService ); return new AmeliaBooking\Domain\Services\TimeSlot\TimeSlotService( $intervalService, $scheduleService, $providerService, $resourceService, $entityService ); }; ContainerConfig/container.php 0000666 00000010174 15165376447 0012340 0 ustar 00 <?php use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\Common\Container; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; // Handle the 404 API calls $entries['notFoundHandler'] = function () { return function ($request, \Slim\Http\Response $response) { return $response->withStatus(404); }; }; // Handle the Method Not Allowed API calls $entries['notAllowedHandler'] = function () { return function ($request, \Slim\Http\Response $response) { return $response->withStatus(405); }; }; // Handle the errors $entries['errorHandler'] = function (Container $c) { return function ($request, \Slim\Http\Response $response, $exception) use ($c) { /** @var Exception $exception */ switch (get_class($exception)) { case \AmeliaBooking\Application\Common\Exceptions\AccessDeniedException::class: $status = \AmeliaBooking\Application\Controller\Controller::STATUS_FORBIDDEN; break; default: $status = \AmeliaBooking\Application\Controller\Controller::STATUS_INTERNAL_SERVER_ERROR; } $responseMessage = ['message' => $exception->getMessage()]; if (method_exists($request, 'getParam') && $request->getParam('showAmeliaSqlExceptions')) { $responseMessage['exception'] = $exception->getPrevious() ? $exception->getPrevious()->getMessage() : ''; } return $response->withStatus($status) ->withHeader('Content-Type', 'text/html') ->write(json_encode($responseMessage)); }; }; // Disabled for now for easier debug //// Handle PHP errors //$entries['phpErrorHandler'] = function (Container $c) { // return function ($request, \Slim\Http\Response $response, $exception) use ($c) { // /** @var Exception $exception */ // // return $response->withStatus(500) // ->withHeader('Content-Type', 'text/html') // ->write($exception->getMessage()); // }; //}; ########################################################################## ########################################################################## # App common ########################################################################## ########################################################################## // $entries['app.connection'] = function () { $config = new \AmeliaBooking\Infrastructure\WP\config\Database(); $settingsService = new SettingsService(new SettingsStorage()); $mysqliEnabled = $settingsService->getSetting('db', 'mysqliEnabled'); if (!extension_loaded('pdo_mysql') || $mysqliEnabled) { return new \AmeliaBooking\Infrastructure\DB\MySQLi\Connection( $config('host'), $config('database'), $config('username'), $config('password'), $config('charset') ); } return new \AmeliaBooking\Infrastructure\DB\PDO\Connection( $config('host'), $config('database'), $config('username'), $config('password'), $config('charset') ); }; ################ # Repositories # ################ require 'repositories.php'; ############################ # Currently logged in user # ############################ require 'infrastructure.user.php'; ################### # Domain Services # ################### require 'domain.services.php'; ######################## # Application Services # ######################## require 'application.services.php'; ######################## # Infrastructure Services # ######################## require 'infrastructure.services.php'; ############### # Command bus # ############### require 'command.bus.php'; #################### # Domain event bus # #################### require 'domain.event.bus.php'; $entries['settings'] = [ // Slim Settings 'determineRouteBeforeAppMiddleware' => true, 'displayErrorDetails' => true, 'addContentLengthHeader' => false, //added due to error on dev server (check the cause) ]; ###################### # Request overriding # ###################### require 'request.php'; return new Container($entries); Routes/Entities/Entities.php 0000666 00000001013 15165376447 0012127 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Entities; use AmeliaBooking\Application\Controller\Entities\GetEntitiesController; use Slim\App; /** * Class Entities * * @package AmeliaBooking\Infrastructure\Routes\Entities */ class Entities { /** * @param App $app */ public static function routes(App $app) { $app->get('/entities', GetEntitiesController::class); } } Routes/Activation/Activation.php 0000666 00000002026 15165376447 0012766 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Activation; use AmeliaBooking\Application\Controller\Activation\ActivatePluginController; use AmeliaBooking\Application\Controller\Activation\DeactivatePluginController; use AmeliaBooking\Application\Controller\Activation\DeactivatePluginEnvatoController; use AmeliaBooking\Application\Controller\Activation\ParseDomainController; use Slim\App; /** * Class Activation * * @package AmeliaBooking\Infrastructure\Routes\Activation */ class Activation { /** * @param App $app */ public static function routes(App $app) { $app->get('/activation/code', ActivatePluginController::class); $app->get('/activation/code/deactivate', DeactivatePluginController::class); $app->get('/activation/envato/deactivate', DeactivatePluginEnvatoController::class); $app->post('/activation/parse-domain', ParseDomainController::class); } } Routes/Bookable/Resource.php 0000666 00000002263 15165376447 0012074 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Bookable; use AmeliaBooking\Application\Controller\Bookable\Resource\AddResourceController; use AmeliaBooking\Application\Controller\Bookable\Resource\DeleteResourceController; use AmeliaBooking\Application\Controller\Bookable\Resource\GetResourcesController; use AmeliaBooking\Application\Controller\Bookable\Resource\UpdateResourceController; use AmeliaBooking\Application\Controller\Bookable\Resource\UpdateResourceStatusController; use Slim\App; /** * Class Resource * * @package AmeliaBooking\Infrastructure\Routes\Bookable */ class Resource { /** * @param App $app */ public static function routes(App $app) { $app->get('/resources', GetResourcesController::class); $app->post('/resources', AddResourceController::class); $app->post('/resources/delete/{id:[0-9]+}', DeleteResourceController::class); $app->post('/resources/{id:[0-9]+}', UpdateResourceController::class); $app->post('/resources/status/{id:[0-9]+}', UpdateResourceStatusController::class); } } Routes/Bookable/Service.php 0000666 00000003243 15165376447 0011704 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Bookable; use AmeliaBooking\Application\Controller\Bookable\Service\AddServiceController; use AmeliaBooking\Application\Controller\Bookable\Service\DeleteServiceController; use AmeliaBooking\Application\Controller\Bookable\Service\GetServiceController; use AmeliaBooking\Application\Controller\Bookable\Service\GetServiceDeleteEffectController; use AmeliaBooking\Application\Controller\Bookable\Service\GetServicesController; use AmeliaBooking\Application\Controller\Bookable\Service\UpdateServiceController; use AmeliaBooking\Application\Controller\Bookable\Service\UpdateServicesPositionsController; use AmeliaBooking\Application\Controller\Bookable\Service\UpdateServiceStatusController; use Slim\App; /** * Class Service * * @package AmeliaBooking\Infrastructure\Routes\Bookable */ class Service { /** * @param App $app */ public static function routes(App $app) { $app->get('/services', GetServicesController::class); $app->get('/services/{id:[0-9]+}', GetServiceController::class); $app->post('/services', AddServiceController::class); $app->post('/services/delete/{id:[0-9]+}', DeleteServiceController::class); $app->post('/services/{id:[0-9]+}', UpdateServiceController::class); $app->get('/services/effect/{id:[0-9]+}', GetServiceDeleteEffectController::class); $app->post('/services/status/{id:[0-9]+}', UpdateServiceStatusController::class); $app->post('/services/positions', UpdateServicesPositionsController::class); } } Routes/Bookable/Category.php 0000666 00000002532 15165376447 0012061 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Bookable; use AmeliaBooking\Application\Controller\Bookable\Category\AddCategoryController; use AmeliaBooking\Application\Controller\Bookable\Category\DeleteCategoryController; use AmeliaBooking\Application\Controller\Bookable\Category\GetCategoriesController; use AmeliaBooking\Application\Controller\Bookable\Category\GetCategoryController; use AmeliaBooking\Application\Controller\Bookable\Category\UpdateCategoriesPositionsController; use AmeliaBooking\Application\Controller\Bookable\Category\UpdateCategoryController; use Slim\App; /** * Class Category * * @package AmeliaBooking\Infrastructure\Routes\Bookable */ class Category { /** * @param App $app */ public static function routes(App $app) { $app->get('/categories', GetCategoriesController::class); $app->get('/categories/{id:[0-9]+}', GetCategoryController::class); $app->post('/categories', AddCategoryController::class); $app->post('/categories/delete/{id:[0-9]+}', DeleteCategoryController::class); $app->post('/categories/{id:[0-9]+}', UpdateCategoryController::class); $app->post('/categories/positions', UpdateCategoriesPositionsController::class); } } Routes/Bookable/Package.php 0000666 00000004177 15165376447 0011646 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Bookable; use AmeliaBooking\Application\Controller\Bookable\Package\AddPackageController; use AmeliaBooking\Application\Controller\Bookable\Package\AddPackageCustomerController; use AmeliaBooking\Application\Controller\Bookable\Package\DeletePackageController; use AmeliaBooking\Application\Controller\Bookable\Package\DeletePackageCustomerController; use AmeliaBooking\Application\Controller\Bookable\Package\GetPackageDeleteEffectController; use AmeliaBooking\Application\Controller\Bookable\Package\GetPackagesController; use AmeliaBooking\Application\Controller\Bookable\Package\GetPackageController; use AmeliaBooking\Application\Controller\Bookable\Package\UpdatePackageController; use AmeliaBooking\Application\Controller\Bookable\Package\UpdatePackageCustomerController; use AmeliaBooking\Application\Controller\Bookable\Package\UpdatePackagesPositionsController; use AmeliaBooking\Application\Controller\Bookable\Package\UpdatePackageStatusController; use Slim\App; /** * Class Package * * @package AmeliaBooking\Infrastructure\Routes\Bookable */ class Package { /** * @param App $app */ public static function routes(App $app) { $app->get('/packages', GetPackagesController::class); $app->post('/packages', AddPackageController::class); $app->post('/packages/delete/{id:[0-9]+}', DeletePackageController::class); $app->post('/packages/{id:[0-9]+}', UpdatePackageController::class); $app->get('/packages/effect/{id:[0-9]+}', GetPackageDeleteEffectController::class); $app->post('/packages/status/{id:[0-9]+}', UpdatePackageStatusController::class); $app->post('/packages/positions', UpdatePackagesPositionsController::class); $app->post('/packages/customers', AddPackageCustomerController::class); $app->post('/packages/customers/{id:[0-9]+}', UpdatePackageCustomerController::class); $app->post('/packages/customers/delete/{id:[0-9]+}', DeletePackageCustomerController::class); } } Routes/Zoom/Zoom.php 0000666 00000000763 15165376447 0010442 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Zoom; use AmeliaBooking\Application\Controller\Zoom\GetUsersController; use Slim\App; /** * Class Zoom * * @package AmeliaBooking\Infrastructure\Routes\Zoom */ class Zoom { /** * @param App $app */ public static function routes(App $app) { $app->get('/zoom/users', GetUsersController::class); } } Routes/Notification/Notification.php 0000666 00000005515 15165376447 0013646 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Notification; use AmeliaBooking\Application\Controller\Notification\AddNotificationController; use AmeliaBooking\Application\Controller\Notification\DeleteNotificationController; use AmeliaBooking\Application\Controller\Notification\GetNotificationsController; use AmeliaBooking\Application\Controller\Notification\GetSMSNotificationsHistoryController; use AmeliaBooking\Application\Controller\Notification\SendAmeliaSmsApiRequestController; use AmeliaBooking\Application\Controller\Notification\SendScheduledNotificationsController; use AmeliaBooking\Application\Controller\Notification\SendTestEmailController; use AmeliaBooking\Application\Controller\Notification\SendTestWhatsAppController; use AmeliaBooking\Application\Controller\Notification\SendUndeliveredNotificationsController; use AmeliaBooking\Application\Controller\Notification\UpdateNotificationController; use AmeliaBooking\Application\Controller\Notification\UpdateNotificationStatusController; use AmeliaBooking\Application\Controller\Notification\UpdateSMSNotificationHistoryController; use AmeliaBooking\Application\Controller\Notification\WhatsAppWebhookController; use AmeliaBooking\Application\Controller\Notification\WhatsAppWebhookRegisterController; use Slim\App; /** * Class Notification * * @package AmeliaBooking\Infrastructure\Routes\Notification */ class Notification { /** * @param App $app */ public static function routes(App $app) { $app->get('/notifications', GetNotificationsController::class); $app->post('/notifications', AddNotificationController::class); $app->post('/notifications/{id:[0-9]+}', UpdateNotificationController::class); $app->post('/notifications/status/{id:[0-9]+}', UpdateNotificationStatusController::class); $app->post('/notifications/email/test', SendTestEmailController::class); $app->post('/notifications/whatsapp/test', SendTestWhatsAppController::class); $app->get('/notifications/whatsapp/webhook', WhatsAppWebhookRegisterController::class); $app->post('/notifications/whatsapp/webhook', WhatsAppWebhookController::class); $app->get('/notifications/scheduled/send', SendScheduledNotificationsController::class); $app->get('/notifications/undelivered/send', SendUndeliveredNotificationsController::class); $app->post('/notifications/sms', SendAmeliaSmsApiRequestController::class); $app->post('/notifications/sms/history/{id:[0-9]+}', UpdateSMSNotificationHistoryController::class); $app->get('/notifications/sms/history', GetSMSNotificationsHistoryController::class); $app->post('/notifications/delete/{id:[0-9]+}', DeleteNotificationController::class); } } Routes/Stash/Stash.php 0000666 00000000772 15165376447 0010736 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Stash; use AmeliaBooking\Application\Controller\Stash\UpdateStashController; use Slim\App; /** * Class Stash * * @package AmeliaBooking\Infrastructure\Routes\Stash */ class Stash { /** * @param App $app */ public static function routes(App $app) { $app->post('/stash', UpdateStashController::class); } } Routes/Stats/Stats.php 0000666 00000001160 15165376447 0010756 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Stats; use AmeliaBooking\Application\Controller\Stats\AddStatsController; use AmeliaBooking\Application\Controller\Stats\GetStatsController; use Slim\App; /** * Class Stats * * @package AmeliaBooking\Infrastructure\Routes\Stats */ class Stats { /** * @param App $app */ public static function routes(App $app) { $app->get('/stats', GetStatsController::class); $app->post('/stats', AddStatsController::class); } } Routes/Routes.php 0000666 00000006013 15165376447 0010045 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes; use AmeliaBooking\Infrastructure\Routes\Activation\Activation; use AmeliaBooking\Infrastructure\Routes\Bookable\Category; use AmeliaBooking\Infrastructure\Routes\Bookable\Extra; use AmeliaBooking\Infrastructure\Routes\Bookable\Package; use AmeliaBooking\Infrastructure\Routes\Bookable\Resource; use AmeliaBooking\Infrastructure\Routes\Bookable\Service; use AmeliaBooking\Infrastructure\Routes\Booking\Appointment\Appointment; use AmeliaBooking\Infrastructure\Routes\Booking\Booking; use AmeliaBooking\Infrastructure\Routes\Booking\Event\Event; use AmeliaBooking\Infrastructure\Routes\Coupon\Coupon; use AmeliaBooking\Infrastructure\Routes\Import\Import; use AmeliaBooking\Infrastructure\Routes\Outlook\Outlook; use AmeliaBooking\Infrastructure\Routes\Payment\Refund; use AmeliaBooking\Infrastructure\Routes\Stash\Stash; use AmeliaBooking\Infrastructure\Routes\Stats\Stats; use AmeliaBooking\Infrastructure\Routes\Location\Location; use AmeliaBooking\Infrastructure\Routes\Notification\Notification; use AmeliaBooking\Infrastructure\Routes\Payment\Payment; use AmeliaBooking\Infrastructure\Routes\PaymentGateway\PaymentGateway; use AmeliaBooking\Infrastructure\Routes\Search\Search; use AmeliaBooking\Infrastructure\Routes\Settings\Settings; use AmeliaBooking\Infrastructure\Routes\Entities\Entities; use AmeliaBooking\Infrastructure\Routes\TimeSlots\TimeSlots; use AmeliaBooking\Infrastructure\Routes\User\User; use AmeliaBooking\Infrastructure\Routes\Report\Report; use AmeliaBooking\Infrastructure\Routes\Google\Google; use AmeliaBooking\Infrastructure\Routes\CustomField\CustomField; use AmeliaBooking\Infrastructure\Routes\Zoom\Zoom; use Slim\App; /** * Class Routes * * API Routes for the Amelia app * * @package AmeliaBooking\Infrastructure\Routes */ class Routes { /** * @param App $app * * @throws \InvalidArgumentException */ public static function routes(App $app) { Activation::routes($app); Booking::routes($app); Appointment::routes($app); Event::routes($app); Category::routes($app); Entities::routes($app); Notification::routes($app); Payment::routes($app); Service::routes($app); Resource::routes($app); Settings::routes($app); TimeSlots::routes($app); User::routes($app); Stats::routes($app); Stash::routes($app); if (!AMELIA_LITE_VERSION) { Coupon::routes($app); Extra::routes($app); Google::routes($app); Outlook::routes($app); Location::routes($app); PaymentGateway::routes($app); Refund::routes($app); Report::routes($app); Search::routes($app); CustomField::routes($app); Package::routes($app); } Import::routes($app); Zoom::routes($app); } } Routes/User/User.php 0000666 00000006056 15165376447 0010427 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\User; use AmeliaBooking\Application\Controller\User\Customer\ReauthorizeController; use AmeliaBooking\Application\Controller\User\Customer\GetCustomersController; use AmeliaBooking\Application\Controller\User\Customer\GetCustomerController; use AmeliaBooking\Application\Controller\User\Customer\AddCustomerController; use AmeliaBooking\Application\Controller\User\Customer\UpdateCustomerController; use AmeliaBooking\Application\Controller\User\DeleteUserController; use AmeliaBooking\Application\Controller\User\GetCurrentUserController; use AmeliaBooking\Application\Controller\User\GetUserDeleteEffectController; use AmeliaBooking\Application\Controller\User\GetWPUsersController; use AmeliaBooking\Application\Controller\User\LoginCabinetController; use AmeliaBooking\Application\Controller\User\LogoutCabinetController; use AmeliaBooking\Application\Controller\User\Provider\UpdateProviderStatusController; use AmeliaBooking\Application\Controller\User\Provider\GetProviderController; use AmeliaBooking\Application\Controller\User\Provider\GetProvidersController; use AmeliaBooking\Application\Controller\User\Provider\AddProviderController; use AmeliaBooking\Application\Controller\User\Provider\UpdateProviderController; use Slim\App; /** * Class User * * @package AmeliaBooking\Infrastructure\Routes\User */ class User { /** * @param App $app */ public static function routes(App $app) { $app->get('/users/wp-users', GetWPUsersController::class); $app->post('/users/authenticate', LoginCabinetController::class); $app->post('/users/logout', LogoutCabinetController::class); // Customers $app->get('/users/customers/{id:[0-9]+}', GetCustomerController::class); $app->get('/users/customers', GetCustomersController::class); $app->post('/users/customers', AddCustomerController::class); $app->post('/users/customers/{id:[0-9]+}', UpdateCustomerController::class); $app->post('/users/customers/delete/{id:[0-9]+}', DeleteUserController::class); $app->get('/users/customers/effect/{id:[0-9]+}', GetUserDeleteEffectController::class); $app->post('/users/customers/reauthorize', ReauthorizeController::class); // Providers $app->get('/users/providers/{id:[0-9]+}', GetProviderController::class); $app->get('/users/providers', GetProvidersController::class); $app->post('/users/providers', AddProviderController::class); $app->post('/users/providers/{id:[0-9]+}', UpdateProviderController::class); $app->post('/users/providers/status/{id:[0-9]+}', UpdateProviderStatusController::class); $app->post('/users/providers/delete/{id:[0-9]+}', DeleteUserController::class); $app->get('/users/providers/effect/{id:[0-9]+}', GetUserDeleteEffectController::class); // Current User $app->get('/users/current', GetCurrentUserController::class); } } Routes/Settings/Settings.php 0000666 00000001232 15165376447 0012162 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Settings; use AmeliaBooking\Application\Controller\Settings\GetSettingsController; use AmeliaBooking\Application\Controller\Settings\UpdateSettingsController; use Slim\App; /** * Class Settings * * @package AmeliaBooking\Infrastructure\Routes\Settings */ class Settings { /** * @param App $app */ public static function routes(App $app) { $app->get('/settings', GetSettingsController::class); $app->post('/settings', UpdateSettingsController::class); } } Routes/Booking/Appointment/Appointment.php 0000666 00000003234 15165376447 0014752 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Booking\Appointment; use AmeliaBooking\Application\Controller\Booking\Appointment\AddAppointmentController; use AmeliaBooking\Application\Controller\Booking\Appointment\DeleteAppointmentController; use AmeliaBooking\Application\Controller\Booking\Appointment\GetAppointmentController; use AmeliaBooking\Application\Controller\Booking\Appointment\GetAppointmentsController; use AmeliaBooking\Application\Controller\Booking\Appointment\UpdateAppointmentController; use AmeliaBooking\Application\Controller\Booking\Appointment\UpdateAppointmentStatusController; use AmeliaBooking\Application\Controller\Booking\Appointment\UpdateAppointmentTimeController; use Slim\App; /** * Class Appointment * * @package AmeliaBooking\Infrastructure\Routes\Booking\Appointment */ class Appointment { /** * @param App $app * * @throws \InvalidArgumentException */ public static function routes(App $app) { $app->get('/appointments', GetAppointmentsController::class); $app->get('/appointments/{id:[0-9]+}', GetAppointmentController::class); $app->post('/appointments', AddAppointmentController::class); $app->post('/appointments/delete/{id:[0-9]+}', DeleteAppointmentController::class); $app->post('/appointments/{id:[0-9]+}', UpdateAppointmentController::class); $app->post('/appointments/status/{id:[0-9]+}', UpdateAppointmentStatusController::class); $app->post('/appointments/time/{id:[0-9]+}', UpdateAppointmentTimeController::class); } } Routes/Booking/Event/Event.php 0000666 00000003755 15165376447 0012330 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Booking\Event; use AmeliaBooking\Application\Controller\Booking\Event\AddEventController; use AmeliaBooking\Application\Controller\Booking\Event\DeleteEventBookingController; use AmeliaBooking\Application\Controller\Booking\Event\DeleteEventController; use AmeliaBooking\Application\Controller\Booking\Event\GetEventController; use AmeliaBooking\Application\Controller\Booking\Event\GetEventDeleteEffectController; use AmeliaBooking\Application\Controller\Booking\Event\GetEventsController; use AmeliaBooking\Application\Controller\Booking\Event\GetCalendarEventsController; use AmeliaBooking\Application\Controller\Booking\Event\UpdateEventBookingController; use AmeliaBooking\Application\Controller\Booking\Event\UpdateEventController; use AmeliaBooking\Application\Controller\Booking\Event\UpdateEventStatusController; use Slim\App; /** * Class Event * * @package AmeliaBooking\Infrastructure\Routes\Booking\Event */ class Event { /** * @param App $app * * @throws \InvalidArgumentException */ public static function routes(App $app) { $app->get('/events', GetEventsController::class); $app->get('/events/{id:[0-9]+}', GetEventController::class); $app->post('/events', AddEventController::class); $app->post('/events/delete/{id:[0-9]+}', DeleteEventController::class); $app->post('/events/{id:[0-9]+}', UpdateEventController::class); $app->get('/events/effect/{id:[0-9]+}', GetEventDeleteEffectController::class); $app->post('/events/bookings/delete/{id:[0-9]+}', DeleteEventBookingController::class); $app->post('/events/bookings/{id:[0-9]+}', UpdateEventBookingController::class); $app->post('/events/status/{id:[0-9]+}', UpdateEventStatusController::class); $app->post('/events/calendar', GetCalendarEventsController::class); } } Routes/Booking/Booking.php 0000666 00000003154 15165376447 0011547 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Booking; use AmeliaBooking\Application\Controller\Booking\Appointment\CancelBookingController; use AmeliaBooking\Application\Controller\Booking\Appointment\CancelBookingRemotelyController; use AmeliaBooking\Application\Controller\Booking\Appointment\DeleteBookingController; use AmeliaBooking\Application\Controller\Booking\Appointment\GetIcsController; use AmeliaBooking\Application\Controller\Booking\Appointment\ReassignBookingController; use AmeliaBooking\Application\Controller\Booking\Appointment\SuccessfulBookingController; use AmeliaBooking\Application\Controller\Booking\Appointment\AddBookingController; use Slim\App; /** * Class Booking * * @package AmeliaBooking\Infrastructure\Routes\Booking */ class Booking { /** * @param App $app * * @throws \InvalidArgumentException */ public static function routes(App $app) { $app->post('/bookings/cancel/{id:[0-9]+}', CancelBookingController::class); $app->get('/bookings/cancel/{id:[0-9]+}', CancelBookingRemotelyController::class); $app->post('/bookings/delete/{id:[0-9]+}', DeleteBookingController::class); $app->post('/bookings/reassign/{id:[0-9]+}', ReassignBookingController::class); $app->post('/bookings', AddBookingController::class); $app->get('/bookings/ics/{id:[0-9]+}', GetIcsController::class)->setOutputBuffering(false); $app->post('/bookings/success/{id:[0-9]+}', SuccessfulBookingController::class); } } Routes/TimeSlots/TimeSlots.php 0000666 00000001031 15165376447 0012425 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\TimeSlots; use AmeliaBooking\Application\Controller\Booking\Appointment\GetTimeSlotsController; use Slim\App; /** * Class TimeSlots * * @package AmeliaBooking\Infrastructure\Routes\TimeSlots */ class TimeSlots { /** * @param App $app */ public static function routes(App $app) { $app->get('/slots', GetTimeSlotsController::class); } } Routes/Import/Import.php 0000666 00000001140 15165376447 0011304 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Import; use AmeliaBooking\Application\Controller\Import\ImportCustomersController; use Slim\App; /** * * Class Import * * @package AmeliaBooking\Infrastructure\Routes\Import */ class Import { /** * @param App $app * * @throws \InvalidArgumentException */ public static function routes(App $app) { $app->post('/import/customers', ImportCustomersController::class)->setOutputBuffering(false); } } Routes/Payment/Payment.php 0000666 00000003664 15165376447 0011627 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Payment; use AmeliaBooking\Application\Controller\Payment\AddPaymentController; use AmeliaBooking\Application\Controller\Payment\CreatePaymentLinkController; use AmeliaBooking\Application\Controller\Payment\DeletePaymentController; use AmeliaBooking\Application\Controller\Payment\CalculatePaymentAmountController; use AmeliaBooking\Application\Controller\Payment\GetPaymentController; use AmeliaBooking\Application\Controller\Payment\GetPaymentsController; use AmeliaBooking\Application\Controller\Payment\GetTransactionAmountController; use AmeliaBooking\Application\Controller\Payment\PaymentCallbackController; use AmeliaBooking\Application\Controller\Payment\PaymentLinkController; use AmeliaBooking\Application\Controller\Payment\RefundPaymentController; use AmeliaBooking\Application\Controller\Payment\UpdatePaymentController; use Slim\App; /** * Class Payment * * @package AmeliaBooking\Infrastructure\Routes\Payment */ class Payment { /** * @param App $app */ public static function routes(App $app) { $app->get('/payments', GetPaymentsController::class); $app->get('/payments/{id:[0-9]+}', GetPaymentController::class); $app->post('/payments', AddPaymentController::class); $app->post('/payments/delete/{id:[0-9]+}', DeletePaymentController::class); $app->post('/payments/{id:[0-9]+}', UpdatePaymentController::class); $app->post('/payments/amount', CalculatePaymentAmountController::class); $app->get('/payments/transaction/{id:[0-9]+}', GetTransactionAmountController::class); $app->get('/payments/callback', PaymentCallbackController::class); $app->post('/payments/callback', PaymentCallbackController::class); $app->post('/payments/link', PaymentLinkController::class); } } Routes/Payment/Refund.php 0000666 00000001034 15165376447 0011422 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See COPYING.md for license details. */ namespace AmeliaBooking\Infrastructure\Routes\Payment; use AmeliaBooking\Application\Controller\Payment\RefundPaymentController; use Slim\App; /** * Class Refund * * @package AmeliaBooking\Infrastructure\Routes\Payment */ class Refund { /** * @param App $app */ public static function routes(App $app) { $app->post('/payments/refund/{id:[0-9]+}', RefundPaymentController::class); } } Repository/Schedule/SpecialDayPeriodServiceRepository.php 0000666 00000004706 15165376447 0020027 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\SpecialDayPeriodService; use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodServiceFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class SpecialDayPeriodServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class SpecialDayPeriodServiceRepository extends AbstractRepository { const FACTORY = SpecialDayPeriodServiceFactory::class; /** * @param SpecialDayPeriodService $entity * @param int $periodId * * @return bool * @throws QueryExecutionException */ public function add($entity, $periodId) { $data = $entity->toArray(); $params = [ ':periodId' => $periodId, ':serviceId' => $data['serviceId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`periodId`, `serviceId`) VALUES (:periodId, :serviceId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param SpecialDayPeriodService $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':serviceId' => $data['serviceId'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `serviceId` = :serviceId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/SpecialDayPeriodLocationRepository.php 0000666 00000004727 15165376447 0020202 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\SpecialDayPeriodLocation; use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodLocationFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class SpecialDayPeriodLocationRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class SpecialDayPeriodLocationRepository extends AbstractRepository { const FACTORY = SpecialDayPeriodLocationFactory::class; /** * @param SpecialDayPeriodLocation $entity * @param int $periodId * * @return bool * @throws QueryExecutionException */ public function add($entity, $periodId) { $data = $entity->toArray(); $params = [ ':periodId' => $periodId, ':locationId' => $data['locationId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`periodId`, `locationId`) VALUES (:periodId, :locationId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param SpecialDayPeriodLocation $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':locationId' => $data['locationId'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `locationId` = :locationId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/SpecialDayRepository.php 0000666 00000004735 15165376447 0015345 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\SpecialDay; use AmeliaBooking\Domain\Factory\Schedule\SpecialDayFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class SpecialDayRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class SpecialDayRepository extends AbstractRepository { const FACTORY = SpecialDayFactory::class; /** * @param SpecialDay $entity * @param int $userId * * @return int * @throws QueryExecutionException */ public function add($entity, $userId) { $data = $entity->toArray(); $params = [ ':userId' => $userId, ':startDate' => $data['startDate'], ':endDate' => $data['endDate'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `startDate`, `endDate`) VALUES (:userId, :startDate, :endDate)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param SpecialDay $entity * @param int $id * * @return bool * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':startDate' => $data['startDate'], ':endDate' => $data['endDate'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `startDate` = :startDate, `endDate` = :endDate WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/PeriodLocationRepository.php 0000666 00000004575 15165376447 0016244 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\PeriodLocation; use AmeliaBooking\Domain\Factory\Schedule\PeriodLocationFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PeriodLocationRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class PeriodLocationRepository extends AbstractRepository { const FACTORY = PeriodLocationFactory::class; /** * @param PeriodLocation $entity * @param int $periodId * * @return bool * @throws QueryExecutionException */ public function add($entity, $periodId) { $data = $entity->toArray(); $params = [ ':periodId' => $periodId, ':locationId' => $data['locationId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`periodId`, `locationId`) VALUES (:periodId, :locationId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param PeriodLocation $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':locationId' => $data['locationId'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `locationId` = :locationId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/DayOffRepository.php 0000666 00000005256 15165376447 0014476 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\DayOff; use AmeliaBooking\Domain\Factory\Schedule\DayOffFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class DayOffRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class DayOffRepository extends AbstractRepository { const FACTORY = DayOffFactory::class; /** * @param DayOff $entity * @param int $userId * * @return int * @throws QueryExecutionException */ public function add($entity, $userId) { $data = $entity->toArray(); $params = [ ':userId' => $userId, ':name' => $data['name'], ':startDate' => $data['startDate'], ':endDate' => $data['endDate'], ':repeat' => $data['repeat'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `name`, `startDate`, `endDate`, `repeat`) VALUES (:userId, :name, :startDate, :endDate, :repeat)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param DayOff $entity * @param int $id * * @return bool * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':name' => $data['name'], ':startDate' => $data['startDate'], ':endDate' => $data['endDate'], ':repeat' => $data['repeat'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `name` = :name, `startDate` = :startDate, `endDate` = :endDate, `repeat` = :repeat WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to add save in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/WeekDayRepository.php 0000666 00000005010 15165376447 0014643 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\WeekDay; use AmeliaBooking\Domain\Factory\Schedule\WeekDayFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class WeekDayRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class WeekDayRepository extends AbstractRepository { const FACTORY = WeekDayFactory::class; /** * @param WeekDay $entity * @param int $userId * * @return int * @throws QueryExecutionException */ public function add($entity, $userId) { $data = $entity->toArray(); $params = [ ':userId' => $userId, ':dayIndex' => $data['dayIndex'], ':startTime' => $data['startTime'], ':endTime' => $data['endTime'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `dayIndex`, `startTime`, `endTime`) VALUES (:userId, :dayIndex, :startTime, :endTime)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param WeekDay $entity * @param int $id * * @return bool * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `startTime` = :startTime, `endTime` = :endTime WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/TimeOutRepository.php 0000666 00000004701 15165376447 0014706 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\TimeOut; use AmeliaBooking\Domain\Factory\Schedule\TimeOutFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class TimeOutRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class TimeOutRepository extends AbstractRepository { const FACTORY = TimeOutFactory::class; /** * @param TimeOut $entity * @param int $weekDayId * * @return bool * @throws QueryExecutionException */ public function add($entity, $weekDayId) { $data = $entity->toArray(); $params = [ ':weekDayId' => $weekDayId, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`weekDayId`, `startTime`, `endTime`) VALUES (:weekDayId, :startTime, :endTime)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param TimeOut $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `startTime` = :startTime, `endTime` = :endTime WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/PeriodRepository.php 0000666 00000005223 15165376447 0014542 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\Period; use AmeliaBooking\Domain\Factory\Schedule\PeriodFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PeriodRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class PeriodRepository extends AbstractRepository { const FACTORY = PeriodFactory::class; /** * @param Period $entity * @param int $weekDayId * * @return bool * @throws QueryExecutionException */ public function add($entity, $weekDayId) { $data = $entity->toArray(); $params = [ ':weekDayId' => $weekDayId, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'], ':locationId' => $data['locationId'] ? $data['locationId'] : null, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`weekDayId`, `startTime`, `endTime`, `locationId`) VALUES (:weekDayId, :startTime, :endTime, :locationId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param Period $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'], ':locationId' => $data['locationId'] ? $data['locationId'] : null, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `startTime` = :startTime, `endTime` = :endTime, `locationId` = :locationId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/PeriodServiceRepository.php 0000666 00000004554 15165376447 0016071 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\PeriodService; use AmeliaBooking\Domain\Factory\Schedule\PeriodServiceFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PeriodServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class PeriodServiceRepository extends AbstractRepository { const FACTORY = PeriodServiceFactory::class; /** * @param PeriodService $entity * @param int $periodId * * @return bool * @throws QueryExecutionException */ public function add($entity, $periodId) { $data = $entity->toArray(); $params = [ ':periodId' => $periodId, ':serviceId' => $data['serviceId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`periodId`, `serviceId`) VALUES (:periodId, :serviceId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param PeriodService $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':serviceId' => $data['serviceId'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `serviceId` = :serviceId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Schedule/SpecialDayPeriodRepository.php 0000666 00000005402 15165376447 0016500 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Schedule; use AmeliaBooking\Domain\Entity\Schedule\SpecialDayPeriod; use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class SpecialDayPeriodRepository * * @package AmeliaBooking\Infrastructure\Repository\Schedule */ class SpecialDayPeriodRepository extends AbstractRepository { const FACTORY = SpecialDayPeriodFactory::class; /** * @param SpecialDayPeriod $entity * @param int $specialDayId * * @return bool * @throws QueryExecutionException */ public function add($entity, $specialDayId) { $data = $entity->toArray(); $params = [ ':specialDayId' => $specialDayId, ':locationId' => $data['locationId'] ? $data['locationId'] : null, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`specialDayId`, `startTime`, `endTime`, `locationId`) VALUES (:specialDayId, :startTime, :endTime, :locationId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param SpecialDayPeriod $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':locationId' => $data['locationId'] ? $data['locationId'] : null, ':startTime' => $data['startTime'], ':endTime' => $data['endTime'] ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `startTime` = :startTime, `endTime` = :endTime, `locationId` = :locationId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Google/GoogleCalendarRepository.php 0000666 00000006423 15165376447 0015651 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Google; use AmeliaBooking\Domain\Entity\Google\GoogleCalendar; use AmeliaBooking\Domain\Factory\Google\GoogleCalendarFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class GoogleRepository * * @package AmeliaBooking\Infrastructure\Repository\Google */ class GoogleCalendarRepository extends AbstractRepository { const FACTORY = GoogleCalendarFactory::class; /** * @param GoogleCalendar $googleCalendar * @param int $userId * * @return string * @throws QueryExecutionException */ public function add($googleCalendar, $userId) { $data = $googleCalendar->toArray(); $params = [ ':userId' => $userId, ':token' => $data['token'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `token`) VALUES (:userId, :token)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param GoogleCalendar $googleCalendar * @param int $id * * @return mixed * @throws QueryExecutionException */ public function update($googleCalendar, $id) { $data = $googleCalendar->toArray(); $params = [ ':token' => $data['token'], ':calendarId' => $data['calendarId'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `token` = :token, `calendarId` = :calendarId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $userId * * @return mixed * @throws NotFoundException * @throws QueryExecutionException */ public function getByProviderId($userId) { try { $statement = $this->connection->prepare($this->selectQuery() . " WHERE {$this->table}.userId = :userId"); $statement->bindParam(':userId', $userId); $statement->execute(); $row = $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } if (!$row) { throw new NotFoundException('Data not found in ' . __CLASS__); } return call_user_func([static::FACTORY, 'create'], $row); } } Repository/Gallery/GalleryRepository.php 0000666 00000010261 15165376447 0014560 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Gallery; use AmeliaBooking\Domain\Entity\Gallery\GalleryImage; use AmeliaBooking\Domain\Repository\Gallery\GalleryRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class GalleryRepository * * @package AmeliaBooking\Infrastructure\Repository */ class GalleryRepository extends AbstractRepository implements GalleryRepositoryInterface { /** * @param GalleryImage $entity * * @return int * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':entityId' => $data['entityId'], ':entityType' => $data['entityType'], ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':position' => $data['position'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `entityId`, `entityType`, `pictureFullPath`, `pictureThumbPath`, `position` ) VALUES ( :entityId, :entityType, :pictureFullPath, :pictureThumbPath, :position )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param int $id * @param GalleryImage $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':position' => $data['position'] ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `pictureFullPath` = :pictureFullPath, `pictureThumbPath` = :pictureThumbPath, `position` = :position WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * * It will delete all relations for one entity except ones that are sent in images array * * @param array $imagesIds * @param int $entityId * @param string $entityType * * @return bool * @throws QueryExecutionException */ public function deleteAllNotInImagesArray($imagesIds, $entityId, $entityType) { $images = ' '; if (!empty($imagesIds)) { foreach ($imagesIds as $index => $value) { ++$index; $images .= ':id' . $index . ', '; $params[':id' . $index] = $value; } $images = 'AND `id` NOT IN (' . rtrim($images, ', ') . ')'; } $params[':entityType'] = $entityType; $params[':entityId'] = $entityId; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE entityType = :entityType AND entityId = :entityId $images" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Outlook/OutlookCalendarRepository.php 0000666 00000006470 15165376447 0016313 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Outlook; use AmeliaBooking\Domain\Entity\Outlook\OutlookCalendar; use AmeliaBooking\Domain\Factory\Outlook\OutlookCalendarFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use Exception; /** * Class OutlookCalendarRepository * * @package AmeliaBooking\Infrastructure\Repository\Outlook */ class OutlookCalendarRepository extends AbstractRepository { const FACTORY = OutlookCalendarFactory::class; /** * @param OutlookCalendar $outlookCalendar * @param int $userId * * @return string * @throws QueryExecutionException */ public function add($outlookCalendar, $userId) { $data = $outlookCalendar->toArray(); $params = [ ':userId' => $userId, ':token' => $data['token'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `token`) VALUES (:userId, :token)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param OutlookCalendar $outlookCalendar * @param int $id * * @return mixed * @throws QueryExecutionException */ public function update($outlookCalendar, $id) { $data = $outlookCalendar->toArray(); $params = [ ':token' => $data['token'], ':calendarId' => $data['calendarId'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `token` = :token, `calendarId` = :calendarId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $userId * * @return mixed * @throws NotFoundException * @throws QueryExecutionException */ public function getByProviderId($userId) { try { $statement = $this->connection->prepare($this->selectQuery() . " WHERE {$this->table}.userId = :userId"); $statement->bindParam(':userId', $userId); $statement->execute(); $row = $statement->fetch(); } catch (Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } if (!$row) { throw new NotFoundException('Data not found in ' . __CLASS__); } return call_user_func([static::FACTORY, 'create'], $row); } } Repository/AbstractRepository.php 0000666 00000020454 15165376447 0013332 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Service; use AmeliaBooking\Domain\Entity\Coupon\Coupon; use AmeliaBooking\Domain\Entity\Location\Location; use AmeliaBooking\Domain\Entity\Notification\Notification; use AmeliaBooking\Domain\Entity\Payment\Payment; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; /** * Class AbstractRepository * * @package AmeliaBooking\Infrastructure\Repository */ class AbstractRepository { const FACTORY = ''; /** @var \PDO */ protected $connection; /** @var string */ protected $table; /** * @param Connection $connection * @param string $table */ public function __construct(Connection $connection, $table) { $this->connection = $connection(); $this->table = $table; } /** * @param int $id * * @return Payment|Coupon|Service|Notification|AbstractUser|Location * @throws NotFoundException * @throws QueryExecutionException */ public function getById($id) { try { $statement = $this->connection->prepare($this->selectQuery() . " WHERE {$this->table}.id = :id"); $statement->bindParam(':id', $id); $statement->execute(); $row = $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } if (!$row) { throw new NotFoundException('Data not found in ' . __CLASS__); } return call_user_func([static::FACTORY, 'create'], $row); } /** * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getAll() { try { $statement = $this->connection->query($this->selectQuery()); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getAllIndexedById() { try { $statement = $this->connection->query($this->selectQuery()); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $collection = new Collection(); foreach ($rows as $row) { $collection->addItem( call_user_func([static::FACTORY, 'create'], $row), $row['id'] ); } return $collection; } /** * @param int $id * * @return bool * @throws QueryExecutionException */ public function delete($id) { try { $statement = $this->connection->prepare("DELETE FROM {$this->table} WHERE id = :id"); $statement->bindParam(':id', $id); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $entityId * @param String $entityColumnName * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByEntityId($entityId, $entityColumnName) { $params = [ ":$entityColumnName" => $entityId, ]; try { $statement = $this->connection->prepare( "SELECT * FROM {$this->table} WHERE {$entityColumnName} = :{$entityColumnName}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * @param int $entityId * @param String $entityColumnName * * @return mixed * @throws QueryExecutionException */ public function deleteByEntityId($entityId, $entityColumnName) { $params = [ ":$entityColumnName" => $entityId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE {$entityColumnName} = :{$entityColumnName}" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $entityId * @param String $entityColumnValue * @param String $entityColumnName * * @return mixed * @throws QueryExecutionException */ public function updateByEntityId($entityId, $entityColumnValue, $entityColumnName) { $params = [ ":$entityColumnName" => $entityId, ]; if ($entityColumnValue !== null) { $updateSql = "`{$entityColumnName}` = :value"; $params[':value'] = $entityColumnValue; } else { $updateSql = "`{$entityColumnName}` = NULL"; } try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET {$updateSql} WHERE {$entityColumnName} = :{$entityColumnName}" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param mixed $fieldValue * @param string $fieldName * * @return mixed * @throws QueryExecutionException */ public function updateFieldById($id, $fieldValue, $fieldName) { $params = [ ':id' => (int)$id, ":$fieldName" => $fieldValue ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `$fieldName` = :$fieldName WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @return string */ protected function selectQuery() { return "SELECT * FROM {$this->table}"; } /** * @return bool */ public function beginTransaction() { return $this->connection->beginTransaction(); } /** * @return bool */ public function commit() { return $this->connection->commit(); } /** * @return bool */ public function rollback() { return $this->connection->rollBack(); } /** * @param int $page * @param int $itemsPerPage * * @return string */ protected function getLimit($page, $itemsPerPage) { return $page && $itemsPerPage ? 'LIMIT ' . (int)(($page - 1) * $itemsPerPage) . ', ' . (int)$itemsPerPage : ''; } } Repository/Location/ProviderLocationRepository.php 0000666 00000005501 15165376447 0016616 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Location; use AmeliaBooking\Domain\Entity\Location\ProviderLocation; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class ProviderLocationRepository * * @package AmeliaBooking\Infrastructure\Repository\Location */ class ProviderLocationRepository extends AbstractRepository { const FACTORY = ProviderLocationRepository::class; /** * @param ProviderLocation $entity * * @return int * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':userId' => $data['userId'], ':locationId' => $data['locationId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `locationId`) VALUES (:userId, :locationId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param int $userId * * @return bool * @throws QueryExecutionException */ public function delete($userId) { try { $statement = $this->connection->prepare("DELETE FROM {$this->table} WHERE userId = :userId"); $statement->bindParam(':userId', $userId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param ProviderLocation $entity * * @return int * @throws QueryExecutionException */ public function update($entity) { $data = $entity->toArray(); $params = [ ':userId' => $data['userId'], ':locationId' => $data['locationId'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `locationId` = :locationId WHERE userId = :userId" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } } Repository/Location/LocationRepository.php 0000666 00000046336 15165376447 0015116 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Location; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Location\Location; use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory; use AmeliaBooking\Domain\Repository\Location\LocationRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\ValueObjects\String\Status; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Domain\Factory\Location\LocationFactory; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersLocationTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersServiceTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class LocationRepositoryInterface * * @package AmeliaBooking\Infrastructure\Repository */ class LocationRepository extends AbstractRepository implements LocationRepositoryInterface { const FACTORY = LocationFactory::class; const SERVICE_FACTORY = ServiceFactory::class; /** @var string */ protected $providerServicesTable; /** @var string */ protected $providerLocationTable; /** @var string */ protected $servicesTable; /** @var string */ protected $locationViewsTable; /** * @param Connection $connection * @param string $table * @param string $providerLocationTable * @param string $providerServicesTable * @param string $servicesTable * @param $locationViewsTable */ public function __construct( Connection $connection, $table, $providerLocationTable, $providerServicesTable, $servicesTable, $locationViewsTable ) { parent::__construct($connection, $table); $this->providerServicesTable = $providerServicesTable; $this->providerLocationTable = $providerLocationTable; $this->servicesTable = $servicesTable; $this->locationViewsTable = $locationViewsTable; } /** * @param Location $location * * @return bool * @throws QueryExecutionException */ public function add($location) { $data = $location->toArray(); $params = [ ':status' => $data['status'], ':name' => $data['name'], ':description' => $data['description'], ':address' => $data['address'], ':phone' => $data['phone'], ':latitude' => $data['latitude'], ':longitude' => $data['longitude'], ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':pin' => $data['pin'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `status`, `name`, `description`, `address`, `phone`, `latitude`, `longitude`, `pictureFullPath`, `pictureThumbPath`, `pin`, `translations` ) VALUES ( :status, :name, :description, :address, :phone, :latitude, :longitude, :pictureFullPath, :pictureThumbPath, :pin, :translations )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param int $id * @param Location $location * * @return bool * @throws QueryExecutionException */ public function update($id, $location) { $data = $location->toArray(); $params = [ ':status' => $data['status'], ':name' => $data['name'], ':description' => $data['description'], ':address' => $data['address'], ':phone' => $data['phone'], ':latitude' => $data['latitude'], ':longitude' => $data['longitude'], ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':pin' => $data['pin'], ':translations' => $data['translations'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status, `name` = :name, `description` = :description, `address` = :address, `phone` = :phone, `latitude` = :latitude, `longitude` = :longitude, `pictureFullPath` = :pictureFullPath, `pictureThumbPath` = :pictureThumbPath, `pin` = :pin, `translations` = :translations WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param string $status * * @return mixed * @throws QueryExecutionException */ public function updateStatusById($id, $status) { $params = [ ':id' => $id, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getAllOrderedByName() { try { $statement = $this->connection->query( "SELECT * FROM {$this->table} ORDER BY name" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = new Collection(); foreach ($rows as $row) { $items->addItem(call_user_func([static::FACTORY, 'create'], $row), $row['id']); } return $items; } /** * @param array $criteria * @param int $itemsPerPage * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getFiltered($criteria, $itemsPerPage) { $params = []; $order = ''; if (!empty($criteria['sort'])) { $orderColumn = $criteria['sort'][0] === '-' ? substr($criteria['sort'], 1) : $criteria['sort']; $orderDirection = $criteria['sort'][0] === '-' ? 'DESC' : 'ASC'; $order = "ORDER BY {$orderColumn} {$orderDirection}"; } $search = ''; if (!empty($criteria['search'])) { $params[':search1'] = $params[':search2'] = "%{$criteria['search']}%"; $search = ' AND (l.name LIKE :search1 OR l.address LIKE :search2)'; } $services = ''; if (!empty($criteria['services'])) { foreach ((array)$criteria['services'] as $index => $value) { ++$index; $services .= ':service' . $index . ', '; $params[':service' . $index] = $value; } $services = ' AND s.id IN (' . rtrim($services, ', ') . ')'; } $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); try { $statement = $this->connection->prepare( "SELECT l.id, l.status, l.name, l.description, l.address, l.phone, l.latitude, l.longitude, l.pictureFullPath, l.pictureThumbPath, l.pin, l.translations FROM {$this->table} l LEFT JOIN {$this->providerLocationTable} pl ON pl.locationId = l.id LEFT JOIN {$this->providerServicesTable} ps ON ps.userId = pl.userId LEFT JOIN {$this->servicesTable} s ON s.id = ps.serviceId WHERE 1 = 1 $search $services GROUP BY l.id {$order} {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * @param $criteria * * @return array * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getCount($criteria) { $providerLocationTable = ProvidersLocationTable::getTableName(); $providerServicesTable = ProvidersServiceTable::getTableName(); $servicesTable = ServicesTable::getTableName(); $params = []; $search = ''; if (!empty($criteria['search'])) { $params[':search1'] = $params[':search2'] = "%{$criteria['search']}%"; $search = ' AND (l.name LIKE :search1 OR l.address LIKE :search2)'; } $services = ''; if (!empty($criteria['services'])) { foreach ((array)$criteria['services'] as $index => $value) { ++$index; $services .= ':service' . $index . ', '; $params[':service' . $index] = $value; } $services = ' AND s.id IN (' . rtrim($services, ', ') . ')'; } try { $statement = $this->connection->prepare( "SELECT COUNT(*) as count FROM ( SELECT l.id FROM {$this->table} l LEFT JOIN {$providerLocationTable} pl ON pl.locationId = l.id LEFT JOIN {$providerServicesTable} ps ON ps.userId = pl.userId LEFT JOIN {$servicesTable} s ON s.id = ps.serviceId WHERE l.status IN (:visibleStatus, :hiddenStatus) $search $services GROUP BY l.id ) as t" ); $params[':visibleStatus'] = Status::VISIBLE; $params[':hiddenStatus'] = Status::HIDDEN; $statement->execute($params); $rows = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param $id * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getServicesById($id) { $params = [ ':id' => $id ]; try { $statement = $this->connection->prepare(" SELECT s.* FROM {$this->table} l INNER JOIN {$this->providerLocationTable} pl ON pl.locationId = l.id INNER JOIN {$this->providerServicesTable} ps ON ps.userId = pl.userId INNER JOIN {$this->servicesTable} s ON s.id = ps.serviceId WHERE l.id = :id GROUP BY s.id"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::SERVICE_FACTORY, 'create'], $row); } return new Collection($items); } /** * Return an array of locations with the number of appointments for the given date period. * Keys of the array are Locations IDs. * * @param $criteria * * @return array * @throws QueryExecutionException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public function getAllNumberOfAppointments($criteria) { $userTable = UsersTable::getTableName(); $appointmentTable = AppointmentsTable::getTableName(); $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (isset($criteria['status'])) { $where[] = 'l.status = :status'; $params[':status'] = $criteria['status']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT l.id, l.name, COUNT(l.id) AS appointments FROM {$this->table} l INNER JOIN {$this->providerLocationTable} pl ON pl.locationId = l.id INNER JOIN {$userTable} u ON u.id = pl.userId INNER JOIN {$appointmentTable} a ON u.id = a.providerId $where GROUP BY l.id"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * Return an array of locations with the number of views for the given date period. * Keys of the array are Locations IDs. * * @param $criteria * * @return array * @throws QueryExecutionException */ public function getAllNumberOfViews($criteria) { $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(lv.date, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (isset($criteria['status'])) { $where[] = 'l.status = :status'; $params[':status'] = $criteria['status']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT l.id, l.name, SUM(lv.views) AS views FROM {$this->table} l INNER JOIN {$this->locationViewsTable} lv ON lv.locationId = l.id $where GROUP BY l.id"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * @param $locationId * * @return string * @throws QueryExecutionException */ public function addViewStats($locationId) { $date = DateTimeService::getNowDate(); $params = [ ':locationId' => $locationId, ':date' => $date, ':views' => 1 ]; try { // Check if there is already data for this provider for this date $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->locationViewsTable} AS pv WHERE pv.locationId = :locationId AND pv.date = :date" ); $statement->bindParam(':locationId', $locationId); $statement->bindParam(':date', $date); $statement->execute(); $count = $statement->fetch()['count']; if (!$count) { $statement = $this->connection->prepare( "INSERT INTO {$this->locationViewsTable} (`locationId`, `date`, `views`) VALUES (:locationId, :date, :views)" ); } else { $statement = $this->connection->prepare( "UPDATE {$this->locationViewsTable} pv SET pv.views = pv.views + :views WHERE pv.locationId = :locationId AND pv.date = :date" ); } $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return true; } /** * @param int $locationId * * @return mixed * @throws QueryExecutionException */ public function deleteViewStats($locationId) { $params = [ ':locationId' => $locationId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->locationViewsTable} WHERE locationId = :locationId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Coupon/CouponServiceRepository.php 0000666 00000004371 15165376447 0015616 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Coupon; use AmeliaBooking\Domain\Entity\Bookable\Service\Service; use AmeliaBooking\Domain\Entity\Coupon\Coupon; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class CouponServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Coupon */ class CouponServiceRepository extends AbstractRepository { /** * @param Coupon $coupon * @param Service $service * * @return mixed * @throws QueryExecutionException */ public function add($coupon, $service) { $couponData = $coupon->toArray(); $serviceData = $service->toArray(); $params = [ ':couponId' => $couponData['id'], ':serviceId' => $serviceData['id'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `couponId`, `serviceId` ) VALUES ( :couponId, :serviceId )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $couponId * @param int $serviceId * * @return mixed * @throws QueryExecutionException */ public function deleteForService($couponId, $serviceId) { $params = [ ':couponId' => $couponId, ':serviceId' => $serviceId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE couponId = :couponId AND serviceId = :serviceId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Coupon/CouponEventRepository.php 0000666 00000004321 15165376447 0015272 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Coupon; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\Coupon\Coupon; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class CouponEventRepository * * @package AmeliaBooking\Infrastructure\Repository\Coupon */ class CouponEventRepository extends AbstractRepository { /** * @param Coupon $coupon * @param Event $event * * @return mixed * @throws QueryExecutionException */ public function add($coupon, $event) { $couponData = $coupon->toArray(); $eventData = $event->toArray(); $params = [ ':couponId' => $couponData['id'], ':eventId' => $eventData['id'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `couponId`, `eventId` ) VALUES ( :couponId, :eventId )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $couponId * @param int $eventId * * @return mixed * @throws QueryExecutionException */ public function deleteForEvent($couponId, $eventId) { $params = [ ':couponId' => $couponId, ':eventId' => $eventId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE couponId = :couponId AND eventId = :eventId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Coupon/CouponPackageRepository.php 0000666 00000004372 15165376447 0015552 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Coupon; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Entity\Coupon\Coupon; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class CouponPackageRepository * * @package AmeliaBooking\Infrastructure\Repository\Coupon */ class CouponPackageRepository extends AbstractRepository { /** * @param Coupon $coupon * @param Package $package * * @return mixed * @throws QueryExecutionException */ public function add($coupon, $package) { $couponData = $coupon->toArray(); $packageData = $package->toArray(); $params = [ ':couponId' => $couponData['id'], ':packageId' => $packageData['id'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `couponId`, `packageId` ) VALUES ( :couponId, :packageId )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $couponId * @param int $packageId * * @return mixed * @throws QueryExecutionException */ public function deleteForPackage($couponId, $packageId) { $params = [ ':couponId' => $couponId, ':packageId' => $packageId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE couponId = :couponId AND packageId = :packageId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Coupon/CouponRepository.php 0000666 00000054275 15165376447 0014305 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Coupon; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Entity\Coupon\Coupon; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Factory\Coupon\CouponFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\NotFoundException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Domain\Repository\Coupon\CouponRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; /** * Class CouponRepository * * @package AmeliaBooking\Infrastructure\Repository\Coupon */ class CouponRepository extends AbstractRepository implements CouponRepositoryInterface { const FACTORY = CouponFactory::class; /** @var string */ protected $servicesTable; /** @var string */ protected $couponToServicesTable; /** @var string */ protected $eventsTable; /** @var string */ protected $couponToEventsTable; /** @var string */ protected $packagesTable; /** @var string */ protected $couponToPackagesTable; /** @var string */ protected $bookingsTable; /** * @param Connection $connection * @param string $table * @param string $servicesTable * @param string $couponToServicesTable * @param string $eventsTable * @param string $couponToEventsTable * @param string $packagesTable * @param string $couponToPackagesTable * @param string $bookingsTable */ public function __construct( Connection $connection, $table, $servicesTable, $couponToServicesTable, $eventsTable, $couponToEventsTable, $packagesTable, $couponToPackagesTable, $bookingsTable ) { parent::__construct($connection, $table); $this->servicesTable = $servicesTable; $this->couponToServicesTable = $couponToServicesTable; $this->eventsTable = $eventsTable; $this->couponToEventsTable = $couponToEventsTable; $this->packagesTable = $packagesTable; $this->couponToPackagesTable = $couponToPackagesTable; $this->bookingsTable = $bookingsTable; } /** * @param Coupon $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':code' => $data['code'], ':discount' => $data['discount'], ':deduction' => $data['deduction'], ':limit' => (int)$data['limit'], ':customerLimit' => (int)$data['customerLimit'], ':status' => $data['status'], ':notificationInterval' => $data['notificationInterval'], ':notificationRecurring' => $data['notificationRecurring'] ? 1 : 0, ':expirationDate' => $data['expirationDate'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `code`, `discount`, `deduction`, `limit`, `customerLimit`, `status`, `notificationInterval`, `notificationRecurring`, `expirationDate` ) VALUES ( :code, :discount, :deduction, :limit, :customerLimit, :status, :notificationInterval, :notificationRecurring, :expirationDate )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param Coupon $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':code' => $data['code'], ':discount' => $data['discount'], ':deduction' => $data['deduction'], ':limit' => (int)$data['limit'], ':customerLimit' => (int)$data['customerLimit'], ':status' => $data['status'], ':notificationInterval' => $data['notificationInterval'], ':notificationRecurring' => $data['notificationRecurring'] ? 1 : 0, ':id' => $id, ':expirationDate' => $data['expirationDate'] ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `code` = :code, `discount` = :discount, `deduction` = :deduction, `limit` = :limit, `customerLimit` = :customerLimit, `status` = :status, `notificationInterval` = :notificationInterval, `notificationRecurring` = :notificationRecurring, `expirationDate` = :expirationDate WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__ . $e->getMessage()); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $response; } /** * @param int $id * * @return Coupon * @throws QueryExecutionException * @throws NotFoundException */ public function getById($id) { try { $statement = $this->connection->prepare( "SELECT c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.notificationInterval AS coupon_notificationInterval, c.notificationRecurring AS coupon_notificationRecurring, c.status AS coupon_status, c.expirationDate AS coupon_expirationDate, s.id AS service_id, s.price AS service_price, s.minCapacity AS service_minCapacity, s.maxCapacity AS service_maxCapacity, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, e.id AS event_id, e.price AS event_price, e.name AS event_name, p.id AS package_id, p.price AS package_price, p.name AS package_name FROM {$this->table} c LEFT JOIN {$this->couponToServicesTable} cs ON cs.couponId = c.id LEFT JOIN {$this->couponToEventsTable} ce ON ce.couponId = c.id LEFT JOIN {$this->couponToPackagesTable} cp ON cp.couponId = c.id LEFT JOIN {$this->servicesTable} s ON cs.serviceId = s.id LEFT JOIN {$this->eventsTable} e ON ce.eventId = e.id LEFT JOIN {$this->packagesTable} p ON cp.packageId = p.id WHERE c.id = :couponId" ); $statement->bindParam(':couponId', $id); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } if (!$rows) { throw new NotFoundException('Data not found in ' . __CLASS__); } return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($id); } /** * @param array $criteria * @param int $itemsPerPage * * @return Collection * @throws QueryExecutionException */ public function getFiltered($criteria, $itemsPerPage) { try { $params = []; $where = []; if (!empty($criteria['search'])) { $params[':search'] = "%{$criteria['search']}%"; $where[] = 'UPPER(c.code) LIKE UPPER(:search)'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = "c.id IN ( SELECT couponId FROM {$this->couponToServicesTable} WHERE serviceId IN (" . implode(', ', $queryServices) . ') )'; } if (!empty($criteria['events'])) { $queryEvents = []; foreach ((array)$criteria['events'] as $index => $value) { $param = ':event' . $index; $queryEvents[] = $param; $params[$param] = $value; } $where[] = "c.id IN ( SELECT couponId FROM {$this->couponToEventsTable} WHERE eventId IN (" . implode(', ', $queryEvents) . ') )'; } if (!empty($criteria['packages'])) { $queryPackages = []; foreach ((array)$criteria['packages'] as $index => $value) { $param = ':package' . $index; $queryPackages[] = $param; $params[$param] = $value; } $where[] = "c.id IN ( SELECT couponId FROM {$this->couponToPackagesTable} WHERE packageId IN (" . implode(', ', $queryPackages) . ') )'; } $where = $where ? ' WHERE ' . implode(' AND ', $where) : ''; $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); $statement = $this->connection->prepare( "SELECT c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.notificationInterval AS coupon_notificationInterval, c.notificationRecurring AS coupon_notificationRecurring, c.status AS coupon_status, c.expirationDate AS coupon_expirationDate FROM {$this->table} c {$where} {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $criteria * * @return mixed * @throws QueryExecutionException */ public function getCount($criteria) { try { $params = []; $where = []; if (!empty($criteria['search'])) { $params[':search'] = "%{$criteria['search']}%"; $where[] = 'c.code LIKE :search'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = "c.id IN (SELECT couponId FROM {$this->couponToServicesTable} WHERE serviceId IN (" . implode(', ', $queryServices) . '))'; } $where = $where ? ' WHERE ' . implode(' AND ', $where) : ''; $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->table} c $where" ); $statement->execute($params); $row = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $row; } /** * @param int $id * @param string $status * * @return mixed * @throws QueryExecutionException */ public function updateStatusById($id, $status) { $params = [ ':id' => $id, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException */ public function getAllByCriteria($criteria) { try { $params = []; $where = []; if (!empty($criteria['code'])) { $where[] = 'c.code = :code'; $params[':code'] = $criteria['code']; } if (!empty($criteria['couponIds'])) { $couponIdsParams = []; foreach ((array)$criteria['couponIds'] as $key => $id) { $couponIdsParams[":id$key"] = $id; } if ($couponIdsParams) { $where[] = '(c.id IN ( ' . implode(', ', array_keys($couponIdsParams)) . '))'; $params = array_merge($params, $couponIdsParams); } } $entitiesFields = ''; $entitiesJoin = ''; if (!empty($criteria['entityType']) && $criteria['entityType'] === Entities::SERVICE) { $entitiesFields = ' s.id AS service_id, s.price AS service_price, s.minCapacity AS service_minCapacity, s.maxCapacity AS service_maxCapacity, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, '; $entitiesJoin = " LEFT JOIN {$this->couponToServicesTable} cs ON cs.couponId = c.id LEFT JOIN {$this->servicesTable} s ON cs.serviceId = s.id "; if (!empty($criteria['entityIds'])) { $queryIds = []; foreach ($criteria['entityIds'] as $index => $value) { $param = ':serviceId' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = '(cs.serviceId IN (' . implode(', ', $queryIds) . '))'; } } else if (!empty($criteria['entityType']) && $criteria['entityType'] === Entities::EVENT) { $entitiesFields = ' e.id AS event_id, e.price AS event_price, e.name AS event_name, '; $entitiesJoin = " LEFT JOIN {$this->couponToEventsTable} ce ON ce.couponId = c.id LEFT JOIN {$this->eventsTable} e ON ce.eventId = e.id "; if (!empty($criteria['entityIds'])) { $queryIds = []; foreach ($criteria['entityIds'] as $index => $value) { $param = ':eventId' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = '(ce.eventId IN (' . implode(', ', $queryIds) . '))'; } } else if (!empty($criteria['entityType']) && $criteria['entityType'] === Entities::PACKAGE) { $entitiesFields = ' p.id AS package_id, p.price AS package_price, p.name AS package_name, '; $entitiesJoin = " LEFT JOIN {$this->couponToPackagesTable} cp ON cp.couponId = c.id LEFT JOIN {$this->packagesTable} p ON cp.packageId = p.id "; if (!empty($criteria['entityIds'])) { $queryIds = []; foreach ($criteria['entityIds'] as $index => $value) { $param = ':packageId' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = '(cp.packageId IN (' . implode(', ', $queryIds) . '))'; } } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $statement = $this->connection->prepare( "SELECT c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.notificationInterval AS coupon_notificationInterval, c.notificationRecurring AS coupon_notificationRecurring, c.status AS coupon_status, c.expirationDate AS coupon_expirationDate, {$entitiesFields} cb.id AS booking_id FROM {$this->table} c LEFT JOIN {$this->bookingsTable} cb ON cb.couponId = c.id {$entitiesJoin} $where" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $couponIds * * @return array * * @throws QueryExecutionException */ public function getCouponsServicesIds($couponIds) { $params = []; $where = ''; if ($couponIds) { foreach ($couponIds as $key => $couponId) { $params[":id$key"] = $couponId; } $where = 'WHERE couponId IN (' . implode(', ', array_keys($params)) . ')'; } try { $statement = $this->connection->prepare( "SELECT serviceId, couponId FROM {$this->couponToServicesTable} $where GROUP BY serviceId, couponId" ); $statement->execute($params); return $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $couponIds * * @return array * * @throws QueryExecutionException */ public function getCouponsEventsIds($couponIds) { $params = []; $where = ''; if ($couponIds) { foreach ($couponIds as $key => $couponId) { $params[":id$key"] = $couponId; } $where = 'WHERE couponId IN (' . implode(', ', array_keys($params)) . ')'; } try { $statement = $this->connection->prepare( "SELECT eventId, couponId FROM {$this->couponToEventsTable} $where GROUP BY eventId, couponId" ); $statement->execute($params); return $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $couponIds * * @return array * * @throws QueryExecutionException */ public function getCouponsPackagesIds($couponIds) { $params = []; $where = ''; if ($couponIds) { foreach ($couponIds as $key => $couponId) { $params[":id$key"] = $couponId; } $where = 'WHERE couponId IN (' . implode(', ', array_keys($params)) . ')'; } try { $statement = $this->connection->prepare( "SELECT packageId, couponId FROM {$this->couponToPackagesTable} $where GROUP BY packageId, couponId" ); $statement->execute($params); return $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/CustomField/CustomFieldOptionRepository.php 0000666 00000006250 15165376447 0017412 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\CustomField; use AmeliaBooking\Domain\Entity\CustomField\CustomFieldOption; use AmeliaBooking\Domain\Factory\CustomField\CustomFieldOptionFactory; use AmeliaBooking\Domain\Repository\CustomField\CustomFieldOptionRepositoryInterface; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; /** * Class CustomFieldOptionRepository * * @package AmeliaBooking\Infrastructure\Repository\CustomField */ class CustomFieldOptionRepository extends AbstractRepository implements CustomFieldOptionRepositoryInterface { const FACTORY = CustomFieldOptionFactory::class; /** * @param CustomFieldOption $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':customFieldId' => $data['customFieldId'], ':label' => $data['label'], ':position' => $data['position'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `customFieldId`, `label`, `position`, `translations` ) VALUES ( :customFieldId, :label, :position, :translations )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param CustomFieldOption $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':customFieldId' => $data['customFieldId'], ':label' => $data['label'], ':position' => $data['position'], ':translations' => $data['translations'], ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `customFieldId` = :customFieldId, `label` = :label, `position` = :position, `translations` = :translations WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $response; } } Repository/CustomField/CustomFieldEventRepository.php 0000666 00000010264 15165376447 0017223 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\CustomField; use AmeliaBooking\Domain\Entity\CustomField\CustomFieldOption; use AmeliaBooking\Domain\Factory\CustomField\CustomFieldOptionFactory; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; /** * Class CustomFieldEventRepository * * @package AmeliaBooking\Infrastructure\Repository\CustomField */ class CustomFieldEventRepository extends AbstractRepository { const FACTORY = CustomFieldOptionFactory::class; /** * @param int $customFieldId * @param int $eventId * * @return bool * @throws QueryExecutionException */ public function add($customFieldId, $eventId) { $params = [ ':customFieldId' => $customFieldId, ':eventId' => $eventId ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `customFieldId`, `eventId` ) VALUES ( :customFieldId, :eventId )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param CustomFieldOption $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':customFieldId' => $data['customFieldId'], ':label' => $data['label'], ':position' => $data['position'], ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `customFieldId` = :customFieldId, `label` = :label, `position` = :position WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $response; } /** * @param int $customFieldId * * @return array * @throws QueryExecutionException */ public function getByCustomFieldId($customFieldId) { try { $statement = $this->connection->query( "SELECT cfs.id, cfs.customFieldId, cfs.eventId FROM {$this->table} cfs WHERE cfs.customFieldId = {$customFieldId}" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param int $customFieldId * @param int $eventId * * @return bool * @throws QueryExecutionException */ public function deleteByCustomFieldIdAndEventId($customFieldId, $eventId) { try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE customFieldId = :customFieldId AND eventId = :eventId" ); $statement->bindParam(':customFieldId', $customFieldId); $statement->bindParam(':eventId', $eventId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/CustomField/CustomFieldServiceRepository.php 0000666 00000010311 15165376447 0017533 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\CustomField; use AmeliaBooking\Domain\Entity\CustomField\CustomFieldOption; use AmeliaBooking\Domain\Factory\CustomField\CustomFieldOptionFactory; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; /** * Class CustomFieldOptionRepository * * @package AmeliaBooking\Infrastructure\Repository\CustomField */ class CustomFieldServiceRepository extends AbstractRepository { const FACTORY = CustomFieldOptionFactory::class; /** * @param $customFieldId * @param $serviceId * * @return bool * @throws QueryExecutionException */ public function add($customFieldId, $serviceId) { $params = [ ':customFieldId' => $customFieldId, ':serviceId' => $serviceId ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `customFieldId`, `serviceId` ) VALUES ( :customFieldId, :serviceId )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param CustomFieldOption $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':customFieldId' => $data['customFieldId'], ':label' => $data['label'], ':position' => $data['position'], ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `customFieldId` = :customFieldId, `label` = :label, `position` = :position WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $response; } /** * @param int $customFieldId * * @return array * @throws QueryExecutionException */ public function getByCustomFieldId($customFieldId) { try { $statement = $this->connection->query( "SELECT cfs.id, cfs.customFieldId, cfs.serviceId FROM {$this->table} cfs WHERE cfs.customFieldId = {$customFieldId}" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param int $customFieldId * @param $serviceId * * @return bool * @throws QueryExecutionException */ public function deleteByCustomFieldIdAndServiceId($customFieldId, $serviceId) { try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE customFieldId = :customFieldId AND serviceId = :serviceId" ); $statement->bindParam(':customFieldId', $customFieldId); $statement->bindParam(':serviceId', $serviceId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/CustomField/CustomFieldRepository.php 0000666 00000015461 15165376447 0016225 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\CustomField; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Entity\CustomField\CustomField; use AmeliaBooking\Domain\Factory\CustomField\CustomFieldFactory; use AmeliaBooking\Domain\Repository\CustomField\CustomFieldRepositoryInterface; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; /** * Class CouponRepository * * @package AmeliaBooking\Infrastructure\Repository\Coupon */ class CustomFieldRepository extends AbstractRepository implements CustomFieldRepositoryInterface { const FACTORY = CustomFieldFactory::class; /** @var string */ private $customFieldsOptionsTable; /** @var string */ private $customFieldsServicesTable; /** @var string */ private $customFieldsEventsTable; /** @var string */ private $servicesTable; /** @var string */ private $eventsTable; /** * @param Connection $connection * @param string $table * @param string $customFieldsOptionsTable * @param string $customFieldsServicesTable * @param string $serviceTable * @param string $customFieldsEventsTable * @param string $eventTable */ public function __construct( Connection $connection, $table, $customFieldsOptionsTable, $customFieldsServicesTable, $serviceTable, $customFieldsEventsTable, $eventTable ) { parent::__construct($connection, $table); $this->customFieldsOptionsTable = $customFieldsOptionsTable; $this->customFieldsServicesTable = $customFieldsServicesTable; $this->servicesTable = $serviceTable; $this->customFieldsEventsTable = $customFieldsEventsTable; $this->eventsTable = $eventTable; } /** * @param CustomField $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':label' => $data['label'], ':type' => $data['type'], ':required' => $data['required'] ? 1 : 0, ':position' => $data['position'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `label`, `type`, `required`, `position`, `translations` ) VALUES ( :label, :type, :required, :position, :translations )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param CustomField $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':label' => $data['label'], ':required' => $data['required'] ? 1 : 0, ':position' => $data['position'], ':translations' => $data['translations'], ':allServices' => $data['allServices'] ? 1 : 0, ':allEvents' => $data['allEvents'] ? 1 : 0, ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `label` = :label, `required` = :required, `position` = :position, `translations` = :translations, `allServices` = :allServices, `allEvents` = :allEvents WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $response; } /** * @return Collection|mixed * @throws QueryExecutionException */ public function getAll() { try { $statement = $this->connection->query( "SELECT cf.id AS cf_id, cf.label AS cf_label, cf.type AS cf_type, cf.required AS cf_required, cf.position AS cf_position, cf.translations AS cf_translations, cf.allServices AS cf_allServices, cf.allEvents AS cf_allEvents, cfo.id AS cfo_id, cfo.customFieldId AS cfo_custom_field_id, cfo.label AS cfo_label, cfo.position AS cfo_position, cfo.translations AS cfo_translations, s.id AS s_id, s.name AS s_name, s.description AS s_description, s.color AS s_color, s.price AS s_price, s.status AS s_status, s.categoryId AS s_categoryId, s.minCapacity AS s_minCapacity, s.maxCapacity AS s_maxCapacity, s.duration AS s_duration, e.id AS e_id, e.name AS e_name, e.price AS e_price, e.parentId AS e_parentId FROM {$this->table} cf LEFT JOIN {$this->customFieldsOptionsTable} cfo ON cfo.customFieldId = cf.id LEFT JOIN {$this->customFieldsServicesTable} cfs ON cfs.customFieldId = cf.id LEFT JOIN {$this->customFieldsEventsTable} cfe ON cfe.customFieldId = cf.id LEFT JOIN {$this->servicesTable} s ON s.id = cfs.serviceId LEFT JOIN {$this->eventsTable} e ON e.id = cfe.eventId ORDER BY cf.position, cfo.position, cf.position" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } } Repository/Payment/PaymentRepository.php 0000666 00000117663 15165376447 0014632 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Payment; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Payment\Payment; use AmeliaBooking\Domain\Factory\Payment\PaymentFactory; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Domain\Repository\Payment\PaymentRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesCustomersServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; /** * Class PaymentRepository * * @package AmeliaBooking\Infrastructure\Repository\Payment */ class PaymentRepository extends AbstractRepository implements PaymentRepositoryInterface { /** @var string */ protected $appointmentsTable; /** @var string */ protected $bookingsTable; /** @var string */ protected $servicesTable; /** @var string */ protected $usersTable; /** @var string */ protected $eventsTable; /** @var string */ protected $eventsProvidersTable; /** @var string */ protected $eventsPeriodsTable; /** @var string */ protected $customerBookingsToEventsPeriodsTable; /** @var string */ protected $packagesTable; /** @var string */ protected $packagesCustomersTable; /** @var string */ protected $packagesCustomersServiceTable; /** * @param Connection $connection * @param string $table * @param string $appointmentsTable * @param string $bookingsTable * @param string $servicesTable * @param string $usersTable * @param string $eventsTable * @param string $eventsProvidersTable * @param string $eventsPeriodsTable * @param string $customerBookingsToEventsPeriodsTable * @param string $packagesTable * @param string $packagesCustomersTable */ public function __construct( Connection $connection, $table, $appointmentsTable, $bookingsTable, $servicesTable, $usersTable, $eventsTable, $eventsProvidersTable, $eventsPeriodsTable, $customerBookingsToEventsPeriodsTable, $packagesTable, $packagesCustomersTable ) { parent::__construct($connection, $table); $this->appointmentsTable = $appointmentsTable; $this->bookingsTable = $bookingsTable; $this->servicesTable = $servicesTable; $this->usersTable = $usersTable; $this->eventsTable = $eventsTable; $this->eventsProvidersTable = $eventsProvidersTable; $this->eventsPeriodsTable = $eventsPeriodsTable; $this->customerBookingsToEventsPeriodsTable = $customerBookingsToEventsPeriodsTable; $this->packagesTable = $packagesTable; $this->packagesCustomersTable = $packagesCustomersTable; $this->packagesCustomersServiceTable = PackagesCustomersServicesTable::getTableName(); } const FACTORY = PaymentFactory::class; /** * @param Payment $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':customerBookingId' => $data['customerBookingId'] ? $data['customerBookingId'] : null, ':packageCustomerId' => $data['packageCustomerId'] ? $data['packageCustomerId'] : null, ':parentId' => $data['parentId'] ? $data['parentId'] : null, ':amount' => $data['amount'], ':dateTime' => DateTimeService::getCustomDateTimeInUtc($data['dateTime']), ':status' => $data['status'], ':gateway' => $data['gateway'], ':gatewayTitle' => $data['gatewayTitle'], ':data' => $data['data'], ':entity' => $data['entity'], ':created' => DateTimeService::getNowDateTimeInUtc(), ':wcOrderId' => !empty($data['wcOrderId']) ? $data['wcOrderId'] : null, ':transactionId' => !empty($data['transactionId']) ? $data['transactionId'] : null, ]; if ($data['parentId']) { $params[':actionsCompleted'] = null; } else { $params[':actionsCompleted'] = !empty($data['actionsCompleted']) ? 1 : 0; } try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `customerBookingId`, `packageCustomerId`, `parentId`, `amount`, `dateTime`, `status`, `gateway`, `gatewayTitle`, `data`, `entity`, `actionsCompleted`, `created`, `wcOrderId`, `transactionId` ) VALUES ( :customerBookingId, :packageCustomerId, :parentId, :amount, :dateTime, :status, :gateway, :gatewayTitle, :data, :entity, :actionsCompleted, :created, :wcOrderId, :transactionId )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param Payment $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':customerBookingId' => $data['customerBookingId'] ? $data['customerBookingId'] : null, ':packageCustomerId' => $data['packageCustomerId'] ? $data['packageCustomerId'] : null, ':parentId' => $data['parentId'] ? $data['parentId'] : null, ':amount' => $data['amount'], ':dateTime' => DateTimeService::getCustomDateTimeInUtc($data['dateTime']), ':status' => $data['status'], ':gateway' => $data['gateway'], ':gatewayTitle' => $data['gatewayTitle'], ':data' => $data['data'], ':transactionId' => $data['transactionId'], ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `customerBookingId` = :customerBookingId, `packageCustomerId` = :packageCustomerId, `parentId` = :parentId, `amount` = :amount, `dateTime` = :dateTime, `status` = :status, `gateway` = :gateway, `gatewayTitle` = :gatewayTitle, `data` = :data, `transactionId` = :transactionId WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $response; } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException */ public function getByCriteria($criteria) { $result = new Collection(); $params = []; $where = []; if (!empty($criteria['bookingIds'])) { $queryBookings = []; foreach ($criteria['bookingIds'] as $index => $value) { $param = ':id' . $index; $queryBookings[] = $param; $params[$param] = $value; } $where[] = 'customerBookingId IN (' . implode(', ', $queryBookings) . ')'; } if (!empty($criteria['ids'])) { $queryIds = []; foreach ($criteria['ids'] as $index => $value) { $param = ':id' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = 'id IN (' . implode(', ', $queryIds) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT id AS id, customerBookingId AS customerBookingId, packageCustomerId AS packageCustomerId, parentId AS parentId, amount AS amount, dateTime AS dateTime, status AS status, gateway AS gateway, gatewayTitle AS gatewayTitle, data AS data FROM {$this->table} {$where}" ); $statement->execute($params); while ($row = $statement->fetch()) { $result->addItem(call_user_func([static::FACTORY, 'create'], $row), $row['id']); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $result; } /** * @param array $criteria * @param int $itemsPerPage * * @return array * @throws QueryExecutionException */ public function getFiltered($criteria, $itemsPerPage = null) { $params = []; $appointmentParams1 = []; $appointmentParams2 = []; $eventParams = []; $whereAppointment1 = []; $whereAppointment2 = []; $whereEvent = []; if ($criteria['dates']) { $whereAppointment1[] = "(DATE_FORMAT(p.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :paymentAppointmentFrom1 AND :paymentAppointmentTo1)"; $whereAppointment2[] = "(DATE_FORMAT(p.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :paymentAppointmentFrom2 AND :paymentAppointmentTo2)"; $appointmentParams1[':paymentAppointmentFrom1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $appointmentParams2[':paymentAppointmentFrom2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $appointmentParams1[':paymentAppointmentTo1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); $appointmentParams2[':paymentAppointmentTo2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); $whereEvent[] = "(DATE_FORMAT(p.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :paymentEventFrom AND :paymentEventTo)"; $eventParams[':paymentEventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $eventParams[':paymentEventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (!empty($criteria['customerId'])) { $appointmentParams1[':customerAppointmentId1'] = $criteria['customerId']; $appointmentParams2[':customerAppointmentId2'] = $criteria['customerId']; $whereAppointment1[] = 'cb.customerId = :customerAppointmentId1'; $whereAppointment2[] = 'pc.customerId = :customerAppointmentId2'; $eventParams[':customerEventId'] = $criteria['customerId']; $whereEvent[] = 'cb.customerId = :customerEventId'; } if (!empty($criteria['providerId'])) { $appointmentParams1[':providerAppointmentId1'] = $criteria['providerId']; $appointmentParams1[':providerAppointmentId2'] = $criteria['providerId']; $whereAppointment1[] = 'a.providerId = :providerAppointmentId1'; $whereAppointment2[] = 'a.providerId = :providerAppointmentId2'; $eventParams[':providerEventId'] = $criteria['providerId']; $whereEvent[] = 'epu.userId = :providerEventId'; } if (!empty($criteria['services'])) { $queryServices1 = []; $queryServices2 = []; foreach ((array)$criteria['services'] as $index => $value) { $param1 = ':service0' . $index; $param2 = ':service1' . $index; $queryServices1[] = $param1; $queryServices2[] = $param2; $appointmentParams1[$param1] = $value; $appointmentParams2[$param2] = $value; } $whereAppointment1[] = 'a.serviceId IN (' . implode(', ', $queryServices1) . ')'; $whereAppointment2[] = 'a.serviceId IN (' . implode(', ', $queryServices2) . ')'; } if (!empty($criteria['status'])) { $appointmentParams1[':statusAppointment1'] = $criteria['status']; $appointmentParams2[':statusAppointment2'] = $criteria['status']; $whereAppointment1[] = 'p.status = :statusAppointment1'; $whereAppointment2[] = 'p.status = :statusAppointment2'; $eventParams[':statusEvent'] = $criteria['status']; $whereEvent[] = 'p.status = :statusEvent'; } if (!empty($criteria['events'])) { $queryEvents = []; foreach ((array)$criteria['events'] as $index => $value) { $param = ':event' . $index; $queryEvents[] = $param; $eventParams[$param] = $value; } $whereEvent[] = "p.customerBookingId IN (SELECT cbe.customerBookingId FROM {$this->eventsTable} e INNER JOIN {$this->eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$this->customerBookingsToEventsPeriodsTable} cbe ON cbe.eventPeriodId = ep.id WHERE e.id IN (" . implode(', ', $queryEvents) . '))'; } $whereAppointment1 = $whereAppointment1 ? ' AND ' . implode(' AND ', $whereAppointment1) : ''; $whereAppointment2 = $whereAppointment2 ? ' AND ' . implode(' AND ', $whereAppointment2) : ''; $whereEvent = $whereEvent ? ' AND ' . implode(' AND ', $whereEvent) : ''; $customerBookingsExtrasTable = CustomerBookingsToExtrasTable::getTableName(); $couponsTable = CouponsTable::getTableName(); $appointmentQuery1 = "SELECT p.id AS id, p.customerBookingId AS customerBookingId, NULL AS packageCustomerId, p.amount AS amount, p.dateTime AS dateTime, p.status AS status, p.wcOrderId AS wcOrderId, p.gateway AS gateway, p.gatewayTitle AS gatewayTitle, p.transactionId AS transactionId, NULL AS packageId, cb.price AS bookedPrice, a.providerId AS providerId, cb.customerId AS customerId, cb.persons AS persons, cb.aggregatedPrice AS aggregatedPrice, cb.info AS info, (SUM(CASE WHEN cbe.aggregatedPrice = 1 THEN cb.persons*cbe.quantity*cbe.price ELSE cbe.quantity*cbe.price END)/COUNT(DISTINCT p.id)) as bookingExtrasSum, c.id AS coupon_id, c.discount AS coupon_discount, c.deduction AS coupon_deduction, a.serviceId AS serviceId, a.id AS appointmentId, a.bookingStart AS bookingStart, s.name AS bookableName, cu.firstName AS customerFirstName, cu.lastName AS customerLastName, cu.email AS customerEmail, pu.firstName AS providerFirstName, pu.lastName AS providerLastName, pu.email AS providerEmail FROM {$this->table} p INNER JOIN {$this->bookingsTable} cb ON cb.id = p.customerBookingId LEFT JOIN {$customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$couponsTable} c ON c.id = cb.couponId INNER JOIN {$this->appointmentsTable} a ON a.id = cb.appointmentId INNER JOIN {$this->servicesTable} s ON s.id = a.serviceId INNER JOIN {$this->usersTable} cu ON cu.id = cb.customerId INNER JOIN {$this->usersTable} pu ON pu.id = a.providerId WHERE 1=1 {$whereAppointment1} GROUP BY p.customerBookingId ORDER BY p.id ASC"; $appointmentQuery2 = "SELECT p.id AS id, NULL AS customerBookingId, p.packageCustomerId AS packageCustomerId, p.amount AS amount, p.dateTime AS dateTime, p.status AS status, p.wcOrderId AS wcOrderId, p.gateway AS gateway, p.gatewayTitle AS gatewayTitle, p.transactionId AS transactionId, pc.packageId AS packageId, pc.price AS bookedPrice, NULL AS providerId, pc.customerId AS customerId, NULL AS persons, NULL AS aggregatedPrice, cb.info AS info, NULL as bookingExtrasSum, c.id AS coupon_id, c.discount AS coupon_discount, c.deduction AS coupon_deduction, NULL AS serviceId, NULL AS appointmentId, NULL AS bookingStart, pa.name AS bookableName, cu.firstName AS customerFirstName, cu.lastName AS customerLastName, cu.email AS customerEmail, '' AS providerFirstName, '' AS providerLastName, '' AS providerEmail FROM {$this->table} p INNER JOIN {$this->packagesCustomersTable} pc ON p.packageCustomerId = pc.id INNER JOIN {$this->usersTable} cu ON cu.id = pc.customerId LEFT JOIN {$couponsTable} c ON c.id = pc.couponId INNER JOIN {$this->packagesTable} pa ON pa.id = pc.packageId INNER JOIN {$this->packagesCustomersServiceTable} pcs ON pc.id = pcs.packageCustomerId LEFT JOIN {$this->bookingsTable} cb ON cb.packageCustomerServiceId = pcs.id LEFT JOIN {$this->appointmentsTable} a ON a.id = cb.appointmentId WHERE 1=1 {$whereAppointment2} GROUP BY p.packageCustomerId ORDER BY p.id ASC"; $eventQuery = "SELECT p.id AS id, p.customerBookingId AS customerBookingId, NULL AS packageCustomerId, p.amount AS amount, p.dateTime AS dateTime, p.status AS status, p.wcOrderId AS wcOrderId, p.gateway AS gateway, p.gatewayTitle AS gatewayTitle, p.transactionId AS transactionId, NULL AS packageId, cb.price AS bookedPrice, NULL AS providerId, cb.customerId AS customerId, cb.persons AS persons, cb.aggregatedPrice AS aggregatedPrice, cb.info AS info, NULL as bookingExtrasSum, c.id AS coupon_id, c.discount AS coupon_discount, c.deduction AS coupon_deduction, NULL AS serviceId, NULL AS appointmentId, NULL AS bookingStart, NULL AS bookableName, cu.firstName AS customerFirstName, cu.lastName AS customerLastName, cu.email AS customerEmail, NULL AS providerFirstName, NULL AS providerLastName, NULL AS providerEmail FROM {$this->table} p INNER JOIN {$this->bookingsTable} cb ON cb.id = p.customerBookingId LEFT JOIN {$couponsTable} c ON c.id = cb.couponId INNER JOIN {$this->usersTable} cu ON cu.id = cb.customerId INNER JOIN {$this->customerBookingsToEventsPeriodsTable} cbe ON cbe.customerBookingId = cb.id INNER JOIN {$this->eventsPeriodsTable} ep ON ep.id = cbe.eventPeriodId LEFT JOIN {$this->eventsProvidersTable} epu ON epu.eventId = ep.eventId WHERE 1=1 {$whereEvent} GROUP BY p.customerBookingId ORDER BY p.id ASC"; if (isset($criteria['events'], $criteria['services'])) { return []; } elseif (isset($criteria['services'])) { $paymentQuery = "({$appointmentQuery1}) UNION ALL ({$appointmentQuery2})"; $params = array_merge($params, $appointmentParams1, $appointmentParams2); } elseif (isset($criteria['events'])) { $paymentQuery = "{$eventQuery}"; $params = array_merge($params, $eventParams); } else { $paymentQuery = "({$appointmentQuery1}) UNION ALL ({$appointmentQuery2}) UNION ALL ({$eventQuery})"; $params = array_merge($params, $appointmentParams1, $appointmentParams2, $eventParams); } $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); try { $statement = $this->connection->prepare( "{$paymentQuery} ORDER BY dateTime, id {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as &$row) { $customerInfo = $row['info'] ? json_decode($row['info'], true) : null; $result[(int)$row['id']] = [ 'id' => (int)$row['id'], 'dateTime' => DateTimeService::getCustomDateTimeFromUtc($row['dateTime']), 'bookingStart' => DateTimeService::getCustomDateTimeFromUtc($row['bookingStart']), 'status' => $row['status'], 'wcOrderId' => $row['wcOrderId'], 'gateway' => $row['gateway'], 'gatewayTitle' => $row['gatewayTitle'], 'transactionId' => $row['transactionId'], 'name' => $row['bookableName'], 'customerBookingId' => (int)$row['customerBookingId'] ? (int)$row['customerBookingId'] : null, 'packageCustomerId' => (int)$row['packageCustomerId'] ? (int)$row['packageCustomerId'] : null, 'amount' => (float)$row['amount'], 'providers' => (int)$row['providerId'] ? [ [ 'id' => (int)$row['providerId'], 'fullName' => $row['providerFirstName'] . ' ' . $row['providerLastName'], 'email' => $row['providerEmail'], ] ] : [], 'customerId' => (int)$row['customerId'], 'serviceId' => (int)$row['serviceId'] ? (int)$row['serviceId'] : null, 'appointmentId' => (int)$row['appointmentId'] ? (int)$row['appointmentId'] : null, 'packageId' => (int)$row['packageId'] ? (int)$row['packageId'] : null, 'bookedPrice' => $row['bookedPrice'] ? $row['bookedPrice'] : null, 'bookableName' => $row['bookableName'], 'customerFirstName' => $customerInfo ? $customerInfo['firstName'] : $row['customerFirstName'], 'customerLastName' => $customerInfo ? $customerInfo['lastName'] : $row['customerLastName'], 'info' => $row['info'], 'customerEmail' => $row['customerEmail'], 'coupon' => !empty($row['coupon_id']) ? [ 'id' => $row['coupon_id'], 'discount' => $row['coupon_discount'], 'deduction' => $row['coupon_deduction'] ] : null, 'persons' => $row['persons'], 'aggregatedPrice' => $row['aggregatedPrice'], //calculated extras sum in the backend with aggregate so that the number of rows(payments) returned will be equal to the set limit per page 'bookingExtrasSum' => $row['bookingExtrasSum'] ?: 0 ]; } return $result; } /** * @param array $criteria * * @return mixed * @throws QueryExecutionException */ public function getCount($criteria) { $params = []; $appointmentParams1 = []; $appointmentParams2 = []; $eventParams = []; $whereAppointment1 = []; $whereAppointment2 = []; $whereEvent = []; if (isset($criteria['dates'])) { $whereAppointment1[] = "(DATE_FORMAT(p.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :paymentAppointmentFrom1 AND :paymentAppointmentTo1)"; $whereAppointment2[] = "(DATE_FORMAT(p.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :paymentAppointmentFrom2 AND :paymentAppointmentTo2)"; $appointmentParams1[':paymentAppointmentFrom1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $appointmentParams1[':paymentAppointmentTo1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); $appointmentParams2[':paymentAppointmentFrom2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $appointmentParams2[':paymentAppointmentTo2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); $whereEvent[] = "(DATE_FORMAT(p.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :paymentEventFrom AND :paymentEventTo)"; $eventParams[':paymentEventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $eventParams[':paymentEventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (!empty($criteria['customerId'])) { $appointmentParams1[':customerAppointmentId1'] = $criteria['customerId']; $appointmentParams2[':customerAppointmentId2'] = $criteria['customerId']; $whereAppointment1[] = 'cb.customerId = :customerAppointmentId1'; $whereAppointment2[] = 'pc.customerId = :customerAppointmentId2'; $eventParams[':customerEventId'] = $criteria['customerId']; $whereEvent[] = 'cb.customerId = :customerEventId'; } if (!empty($criteria['providerId'])) { $appointmentParams1[':providerAppointmentId'] = $criteria['providerId']; $whereAppointment1[] = 'a.providerId = :providerAppointmentId'; $eventParams[':providerEventId'] = $criteria['providerId']; $whereEvent[] = 'epu.userId = :providerEventId'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $appointmentParams1[$param] = $value; } $whereAppointment1[] = 'a.serviceId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['status'])) { $appointmentParams1[':statusAppointment1'] = $criteria['status']; $appointmentParams2[':statusAppointment2'] = $criteria['status']; $whereAppointment1[] = 'p.status = :statusAppointment1'; $whereAppointment2[] = 'p.status = :statusAppointment2'; $eventParams[':statusEvent'] = $criteria['status']; $whereEvent[] = 'p.status = :statusEvent'; } if (!empty($criteria['events'])) { $queryEvents = []; foreach ((array)$criteria['events'] as $index => $value) { $param = ':event' . $index; $queryEvents[] = $param; $eventParams[$param] = $value; } $whereEvent[] = "p.customerBookingId IN (SELECT cbe.customerBookingId FROM {$this->eventsTable} e INNER JOIN {$this->eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$this->customerBookingsToEventsPeriodsTable} cbe ON cbe.eventPeriodId = ep.id WHERE e.id IN (" . implode(', ', $queryEvents) . '))'; } $whereAppointment1 = $whereAppointment1 ? ' AND ' . implode(' AND ', $whereAppointment1) : ''; $whereAppointment2 = $whereAppointment2 ? ' AND ' . implode(' AND ', $whereAppointment2) : ''; $whereEvent = $whereEvent ? ' AND ' . implode(' AND ', $whereEvent) : ''; $appointmentQuery1 = "SELECT COUNT(DISTINCT(p.customerBookingId)) AS appointmentsCount1, 0 AS appointmentsCount2, 0 AS eventsCount FROM {$this->table} p INNER JOIN {$this->bookingsTable} cb ON cb.id = p.customerBookingId INNER JOIN {$this->appointmentsTable} a ON a.id = cb.appointmentId INNER JOIN {$this->servicesTable} s ON s.id = a.serviceId INNER JOIN {$this->usersTable} cu ON cu.id = cb.customerId INNER JOIN {$this->usersTable} pu ON pu.id = a.providerId WHERE 1=1 $whereAppointment1"; $appointmentQuery2 = "SELECT 0 AS appointmentsCount1, COUNT(DISTINCT(p.packageCustomerId)) AS appointmentsCount2, 0 AS eventsCount FROM {$this->table} p INNER JOIN {$this->packagesCustomersTable} pc ON p.packageCustomerId = pc.id INNER JOIN {$this->usersTable} cu ON cu.id = pc.customerId INNER JOIN {$this->packagesTable} pa ON pa.id = pc.packageId WHERE 1=1 $whereAppointment2"; $eventQuery = "SELECT 0 AS appointmentsCount1, 0 AS appointmentsCount2, COUNT(DISTINCT(p.customerBookingId)) AS eventsCount FROM {$this->table} p INNER JOIN {$this->bookingsTable} cb ON cb.id = p.customerBookingId INNER JOIN {$this->usersTable} cu ON cu.id = cb.customerId INNER JOIN {$this->customerBookingsToEventsPeriodsTable} cbe ON cbe.customerBookingId = cb.id INNER JOIN {$this->eventsPeriodsTable} ep ON ep.id = cbe.eventPeriodId LEFT JOIN {$this->eventsProvidersTable} epu ON epu.eventId = ep.eventId WHERE 1=1 $whereEvent"; if (isset($criteria['events'], $criteria['services'])) { return []; } elseif (isset($criteria['services'])) { $paymentQuery = "({$appointmentQuery1}) UNION ALL ({$appointmentQuery2})"; $params = array_merge($params, $appointmentParams1, $appointmentParams2); } elseif (isset($criteria['events'])) { $paymentQuery = "{$eventQuery}"; $params = array_merge($params, $eventParams); } else { $paymentQuery = "({$appointmentQuery1}) UNION ALL ({$appointmentQuery2}) UNION ALL ({$eventQuery})"; $params = array_merge($params, $appointmentParams1, $appointmentParams2, $eventParams); } try { $statement = $this->connection->prepare( "{$paymentQuery}" ); $statement->execute($params); $statementResult1 = $statement->fetch(); $statementResult2 = $statement->fetch(); $statementResult3 = $statement->fetch(); $appointmentsCount1 = !empty($statementResult1['appointmentsCount1']) ? $statementResult1['appointmentsCount1'] : 0; $appointmentsCount2 = !empty($statementResult2['appointmentsCount2']) ? $statementResult2['appointmentsCount2'] : 0; $eventsCount = !empty($statementResult3['eventsCount']) ? $statementResult3['eventsCount'] : 0; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $appointmentsCount1 + $appointmentsCount2 + $eventsCount; } /** * Returns a collection of customers that have birthday on today's date and where notification is not sent * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getUncompletedActionsForPayments() { $params = []; $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')"; $pastDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeObjectInUtc()->modify('-1 day')->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; try { $statement = $this->connection->prepare( "SELECT * FROM {$this->table} WHERE actionsCompleted = 0 AND {$currentDateTime} > DATE_ADD(created, INTERVAL 300 SECOND) AND {$pastDateTime} < created AND entity IS NOT NULL" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * @param int $status */ public function findByStatus($status) { // TODO: Implement findByStatus() method. } /** * @param int $bookingId * @param int $firstPaymentId * @param bool $isPackage * * @return array * @throws QueryExecutionException */ public function getSecondaryPayments($bookingId, $firstPaymentId, $isPackage) { $result = []; $params = [ ':paymentId' => $firstPaymentId, ':bookingId' => $bookingId ]; $where = 'WHERE id <> :paymentId AND ' . ($isPackage ? 'packageCustomerId' : 'customerBookingId') . ' = :bookingId'; try { $statement = $this->connection->prepare( "SELECT id AS id, customerBookingId AS customerBookingId, packageCustomerId AS packageCustomerId, parentId AS parentId, amount AS amount, entity AS entity, created AS created, dateTime AS dateTime, status AS status, gateway AS gateway, gatewayTitle AS gatewayTitle, data AS data, transactionId AS transactionId, wcOrderId AS wcOrderId FROM {$this->table} {$where}" ); $statement->execute($params); $rows = $statement->fetchAll(); foreach ($rows as $row) { //getting wc tax /** @var Payment $paymentObject **/ $paymentObject = call_user_func([static::FACTORY, 'create'], $row); if ($paymentObject) { $paymentArray = $paymentObject->toArray(); $paymentArray['dateTime'] = DateTimeService::getCustomDateTimeFromUtc($paymentArray['dateTime']); $result[] = $paymentArray; } } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $result; } /** * @param Payment $payment * * @return array * @throws QueryExecutionException */ public function getRelatedPayments($payment) { $result = []; $params = [ ':paymentId1' => $payment->getId()->getValue(), ':paymentId2' => $payment->getId()->getValue(), ]; $where = "WHERE id <> :paymentId1 AND (status = 'paid' OR status = 'partiallyPaid') AND (parentId = :paymentId2"; if ($payment->getParentId()) { $params[':parentId2'] = $params[':parentId1'] = $payment->getParentId()->getValue(); $where .= ' OR parentId= :parentId1 OR id = :parentId2)'; } else { $where .= ')'; } try { $statement = $this->connection->prepare( "SELECT id AS id, customerBookingId AS customerBookingId, packageCustomerId AS packageCustomerId, parentId AS parentId, amount AS amount, entity AS entity, created AS created, dateTime AS dateTime, status AS status, gateway AS gateway, gatewayTitle AS gatewayTitle, data AS data, transactionId AS transactionId, wcOrderId AS wcOrderId FROM {$this->table} {$where}" ); $statement->execute($params); $rows = $statement->fetchAll(); foreach ($rows as $row) { //getting wc tax /** @var Payment $paymentObject **/ $paymentObject = call_user_func([static::FACTORY, 'create'], $row); if ($paymentObject) { $paymentArray = $paymentObject->toArray(); $paymentArray['dateTime'] = DateTimeService::getCustomDateTimeFromUtc($paymentArray['dateTime']); $result[] = $paymentArray; } } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in related payments ' . __CLASS__, $e->getCode(), $e); } return $result; } /** * @param array $ids * @param mixed $fieldValue * @param string $fieldName * * @return mixed * @throws QueryExecutionException */ public function updateFieldByIds($ids, $fieldName, $fieldValue) { $queryParams = []; $params = [ ":$fieldName" => $fieldValue ]; foreach ($ids as $index => $value) { $param = ':id' . $index; $queryParams[] = $param; $params[$param] = $value; } $where = 'WHERE id IN (' . implode(', ', $queryParams) . ')'; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `$fieldName` = :$fieldName {$where}" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $paymentId * @param string $transactionId * * @throws QueryExecutionException */ public function updateTransactionId($paymentId, $transactionId) { $params = [ ':transactionId' => $transactionId, ':paymentId1' => $paymentId, ':paymentId2' => $paymentId ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `transactionId` = :transactionId WHERE id = :paymentId1 OR parentId = :paymentId2" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to update data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to update data in ' . __CLASS__); } return $response; } } Repository/Notification/NotificationSMSHistoryRepository.php 0000666 00000016307 15165376447 0020612 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Notification; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class NotificationSMSHistoryRepository * * @package AmeliaBooking\Infrastructure\Repository\Notification */ class NotificationSMSHistoryRepository extends AbstractRepository { /** * @param $data * * @return bool * * @throws QueryExecutionException * @throws \Exception */ public function add($data) { $params = [ ':notificationId' => $data['notificationId'], ':userId' => $data['userId'], ':appointmentId' => !empty($data['appointmentId']) ? $data['appointmentId'] : null, ':eventId' => !empty($data['eventId']) ? $data['eventId'] : null, ':packageCustomerId' => !empty($data['packageCustomerId']) ? $data['packageCustomerId'] : null, ':text' => $data['text'], ':phone' => $data['phone'], ':alphaSenderId' => $data['alphaSenderId'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `notificationId`, `userId`, `appointmentId`, `eventId`, `packageCustomerId`, `text`, `phone`, `alphaSenderId` ) VALUES ( :notificationId, :userId, :appointmentId, :eventId, :packageCustomerId, :text, :phone, :alphaSenderId )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $id * @param $data * * @return bool * @throws QueryExecutionException */ public function update($id, $data) { $params = [ ':logId' => $data['logId'], ':dateTime' => $data['dateTime'], ':status' => $data['status'], ':price' => $data['price'], ':segments' => $data['segments'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `logId` = COALESCE(:logId, `logId`), `dateTime` = COALESCE(:dateTime, `dateTime`), `status` = COALESCE(:status, `status`), `price` = COALESCE(:price, `price`), `segments` = COALESCE(:segments, `segments`) WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * * @return array * @throws QueryExecutionException */ public function getById($id) { try { $statement = $this->connection->prepare( $this->selectQuery() . " WHERE id = :id" ); $params = [ ':id' => $id, ]; $statement->execute($params); $row = $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } if (!$row) { return null; } return $row; } /** * @param $criteria * @param $itemsPerPage * * @return array * @throws QueryExecutionException */ public function getFiltered($criteria, $itemsPerPage) { try { $params = []; $where = []; if (!empty($criteria['dates'])) { $where[] = "(DATE_FORMAT(h.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :dateFrom AND :dateTo)"; $params[':dateFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':dateTo'] = DateTimeService::getCustomDateTimeObjectInUtc( $criteria['dates'][1] )->modify('+1 day')->format('Y-m-d H:i:s'); } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); $usersTable = UsersTable::getTableName(); $statement = $this->connection->prepare( "SELECT h.*, CONCAT(u.firstName, ' ', u.lastName) as userFullName FROM {$this->table} h LEFT JOIN {$usersTable} u ON h.userId = u.id WHERE 1=1 $where ORDER BY h.id DESC {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); foreach ($rows as &$row) { $row['dateTime'] = DateTimeService::getCustomDateTimeFromUtc($row['dateTime']); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param $criteria * * @return mixed * @throws QueryExecutionException */ public function getCount($criteria) { try { $params = []; $where = []; if (!empty($criteria['dates'])) { $where[] = "(DATE_FORMAT(h.dateTime, '%Y-%m-%d %H:%i:%s') BETWEEN :dateFrom AND :dateTo)"; $params[':dateFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':dateTo'] = DateTimeService::getCustomDateTimeObjectInUtc( $criteria['dates'][1] )->modify('+1 day')->format('Y-m-d H:i:s'); } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->table} h WHERE 1=1 {$where}" ); $statement->execute($params); $row = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $row; } } Repository/Notification/NotificationRepository.php 0000666 00000014725 15165376447 0016647 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Notification; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Notification\Notification; use AmeliaBooking\Domain\Factory\Notification\NotificationFactory; use AmeliaBooking\Domain\Repository\Notification\NotificationRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Repository\Booking\Event\EventRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsToEntitiesTable; /** * Class NotificationRepository * * @package AmeliaBooking\Infrastructure\Repository\Notification */ class NotificationRepository extends AbstractRepository implements NotificationRepositoryInterface { const FACTORY = NotificationFactory::class; /** * @param Notification $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':customName' => $data['customName'], ':sendTo' => $data['sendTo'], ':status' => $data['status'], ':type' => $data['type'], ':entity' => $data['entity'], ':time' => $data['time'], ':timeBefore' => $data['timeBefore'], ':timeAfter' => $data['timeAfter'], ':subject' => $data['subject'], ':content' => $data['content'], ':translations' => $data['translations'], ':sendOnlyMe' => $data['sendOnlyMe'] ? 1 : 0, ':whatsAppTemplate' => $data['whatsAppTemplate'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`name`, `customName`, `sendTo`, `status`, `type`, `entity`, `time`, `timeBefore`, `timeAfter`, `subject`, `content`, `translations`, `sendOnlyMe`, `whatsAppTemplate`) VALUES (:name, :customName, :sendTo, :status, :type, :entity, :time, :timeBefore, :timeAfter, :subject, :content, :translations, :sendOnlyMe, :whatsAppTemplate)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Notification $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':customName' => $data['customName'], ':status' => $data['status'], ':time' => $data['time'], ':timeBefore' => $data['timeBefore'], ':timeAfter' => $data['timeAfter'], ':subject' => $data['subject'], ':content' => $data['content'], ':translations' => $data['translations'], ':sendOnlyMe' => $data['sendOnlyMe'] ? 1 : 0, ':whatsAppTemplate' => $data['whatsAppTemplate'], ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `name` = :name, `customName` = :customName, `status` = :status, `time` = :time, `timeBefore` = :timeBefore, `timeAfter` = :timeAfter, `subject` = :subject, `content` = :content, `translations` = :translations, `sendOnlyMe` = :sendOnlyMe, `whatsAppTemplate` = :whatsAppTemplate WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $name * @param $type * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByNameAndType($name, $type) { try { $statement = $this->connection->prepare( $this->selectQuery() . " WHERE {$this->table}.name LIKE :name AND {$this->table}.type = :type" ); $params = [ ':name' => $name, ':type' => $type ]; $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by name and type in ' . __CLASS__, $e->getCode(), $e); } $items = new Collection(); foreach ($rows as $row) { $items->addItem(call_user_func([static::FACTORY, 'create'], $row), $row['id']); } return $items; } /** * @param int $notificationId * * @return bool * @throws QueryExecutionException * @throws InvalidArgumentException */ public function delete($notificationId) { $notificationsToEntities = NotificationsToEntitiesTable::getTableName(); $params = [ ':id' => $notificationId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE id = :id" ); $success1 = $statement->execute($params); $statement = $this->connection->prepare( "DELETE FROM {$notificationsToEntities} WHERE notificationId = :id" ); $success2 = $statement->execute($params); return $success1 && $success2; } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Notification/NotificationsToEntitiesRepository.php 0000666 00000010202 15165376447 0021024 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Notification; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Notification\NotificationsToEntitiesTable; class NotificationsToEntitiesRepository extends AbstractRepository { /** * @param $notificationId * * @return array * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getEntities($notificationId) { try { $statement = $this->connection->prepare( "SELECT entityId FROM {$this->table} WHERE notificationId = :id" ); $params = [ ':id' => $notificationId ]; $statement->execute($params); $entityRows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get entities in ' . __CLASS__, $e->getCode(), $e); } return array_column($entityRows, 'entityId'); } /** * @param int $notificationId * @param int $entityId * @param string $entity * * @return bool * @throws QueryExecutionException * @throws InvalidArgumentException */ public function removeEntity($notificationId, $entityId, $entity) { $params = [ ':notificationId' => $notificationId, ':entity' => $entity, ':entityId' => $entityId ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE notificationId = :notificationId AND entity = :entity AND entityId = :entityId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param $entityId * * @return bool * @throws QueryExecutionException * @throws InvalidArgumentException */ public function removeIfOnly($entityId) { $notificationsTable = NotificationsTable::getTableName(); try { $statement = $this->connection->prepare( "DELETE n FROM {$notificationsTable} n INNER JOIN {$this->table} ne ON n.id = ne.notificationId WHERE ne.entityId = :id AND NOT EXISTS (SELECT * FROM {$this->table} ne2 WHERE ne2.entityId <> ne.entityId AND ne2.notificationId = n.id)" ); $params = [ ':id' => $entityId ]; $success1 = $statement->execute($params); $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE entityId = :id" ); $success2 = $statement->execute($params); return $success1 && $success2; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get entities in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $notificationId * @param int $entityId * @param string $entity * * @return bool * @throws QueryExecutionException * @throws InvalidArgumentException */ public function addEntity($notificationId, $entityId, $entity) { $params = [ ':notificationId' => $notificationId, ':entity' => $entity, ':entityId' => $entityId ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`notificationId`, `entity`, `entityId`) VALUES (:notificationId, :entity, :entityId)" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Notification/NotificationLogRepository.php 0000666 00000124120 15165376447 0017300 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Notification; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Entities; use AmeliaBooking\Domain\Entity\Notification\Notification; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Domain\Factory\Notification\NotificationLogFactory; use AmeliaBooking\Domain\Factory\User\UserFactory; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\ValueObjects\String\Status; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToEventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable; /** * Class NotificationLogRepository * * @package AmeliaBooking\Infrastructure\Repository\Notification */ class NotificationLogRepository extends AbstractRepository { const FACTORY = NotificationLogFactory::class; /** @var string */ protected $notificationsTable; /** @var string */ protected $appointmentsTable; /** @var string */ protected $bookingsTable; /** @var string */ protected $usersTable; /** * NotificationLogRepository constructor. * * @param Connection $connection * @param string $table * @param string $notificationsTable * @param string $appointmentsTable * @param string $bookingsTable * @param string $usersTable */ public function __construct( Connection $connection, $table, $notificationsTable, $appointmentsTable, $bookingsTable, $usersTable ) { parent::__construct($connection, $table); $this->notificationsTable = $notificationsTable; $this->appointmentsTable = $appointmentsTable; $this->bookingsTable = $bookingsTable; $this->usersTable = $usersTable; } /** * @param Notification $notification * @param int|null $userId * @param int|null $appointmentId * @param int|null $eventId * @param int|null $packageCustomerId * @param string|null $data * * @return int * * @throws QueryExecutionException * @throws \Exception */ public function add($notification, $userId, $appointmentId = null, $eventId = null, $packageCustomerId = null, $data = null) { $notificationData = $notification->toArray(); $params = [ ':notificationId' => $notificationData['id'], ':userId' => $userId, ':appointmentId' => $appointmentId, ':packageCustomerId' => $packageCustomerId, ':eventId' => $eventId, ':sentDateTime' => DateTimeService::getNowDateTimeInUtc(), ':data' => $data, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`notificationId`, `userId`, `appointmentId`, `eventId`, `packageCustomerId`, `sentDateTime`, `sent`, `data`) VALUES (:notificationId, :userId, :appointmentId, :eventId, :packageCustomerId, :sentDateTime, 0, :data)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * Return a collection of tomorrow appointments where customer notification is not sent and should be. * * @param int $notificationId * @param bool $nextDay * @param array $statuses * * @return Collection * * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getCustomersNextDayAppointments($notificationId, $nextDay = true, $statuses = []) { $couponsTable = CouponsTable::getTableName(); $customerBookingsExtrasTable = CustomerBookingsToExtrasTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); $startDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(0, 0, 0)->format('Y-m-d H:i:s') ); $endDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(23, 59, 59)->format('Y-m-d H:i:s') ); if ($nextDay) { $startDate = $startDate->modify('+1 day'); $endDate = $endDate->modify('+1 day'); } $startCurrentDate = "STR_TO_DATE('" . $startDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; $endCurrentDate = "STR_TO_DATE('" . $endDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; $whereStatuses = []; foreach ($statuses as $key => $status) { $whereStatuses[] = "cb.status = '$status'"; } $whereStatuses = $whereStatuses ? 'AND (' . implode(' OR ', $whereStatuses) . ')' : ''; try { $statement = $this->connection->query( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, a.googleMeetUrl AS appointment_google_meet_url, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.persons AS booking_persons, cb.duration AS booking_duration, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.data AS payment_data, cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->appointmentsTable} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$couponsTable} c ON c.id = cb.couponId WHERE a.bookingStart BETWEEN $startCurrentDate AND $endCurrentDate {$whereStatuses} AND a.notifyParticipants = 1 AND a.id NOT IN ( SELECT nl.appointmentId FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.id = {$notificationId} AND (nl.sent IS NULL OR nl.sent = 1) AND nl.appointmentId IS NOT NULL )" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } return AppointmentFactory::createCollection($rows); } /** * Return a collection of tomorrow events where customer notification is not sent and should be. * * @param $notificationId * * @return Collection * * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getCustomersNextDayEvents($notificationId, $nextDay = true) { $couponsTable = CouponsTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); $eventsTable = EventsTable::getTableName(); $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $startDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(0, 0, 0)->format('Y-m-d H:i:s') ); $endDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(23, 59, 59)->format('Y-m-d H:i:s') ); if ($nextDay) { $startDate = $startDate->modify('+1 day'); $endDate = $endDate->modify('+1 day'); } $startCurrentDate = "STR_TO_DATE('" . $startDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; $endCurrentDate = "STR_TO_DATE('" . $endDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; try { $statement = $this->connection->query( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringUntil AS event_recurringUntil, e.maxCapacity AS event_maxCapacity, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.notifyParticipants AS event_notifyParticipants, e.zoomUserId AS event_zoomUserId, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.organizerId AS event_organizerId, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleMeetUrl AS event_googleMeetUrl, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.persons AS booking_persons, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.data AS payment_data, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.translations AS provider_translations, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$eventsTable} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id INNER JOIN {$this->bookingsTable} cb ON cb.id = cbe.customerBookingId LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$this->usersTable} pu ON pu.id = epr.userId LEFT JOIN {$couponsTable} c ON c.id = cb.couponId WHERE ep.periodStart BETWEEN {$startCurrentDate} AND {$endCurrentDate} AND cb.status = 'approved' AND e.notifyParticipants = 1 AND e.id NOT IN ( SELECT nl.eventId FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.id = {$notificationId} AND (nl.sent IS NULL OR nl.sent = 1) AND nl.eventId IS NOT NULL )" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } return EventFactory::createCollection($rows); } /** * Return a collection of tomorrow appointments where provider notification is not sent and should be. * * @param int $notificationId * @param bool $nextDay * @param array $statuses * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getProvidersNextDayAppointments($notificationId, $nextDay, $statuses) { $couponsTable = CouponsTable::getTableName(); $customerBookingsExtrasTable = CustomerBookingsToExtrasTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); $startDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(0, 0, 0)->format('Y-m-d H:i:s') ); $endDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(23, 59, 59)->format('Y-m-d H:i:s') ); if ($nextDay) { $startDate = $startDate->modify('+1 day'); $endDate = $endDate->modify('+1 day'); } $startCurrentDate = "STR_TO_DATE('" . $startDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; $endCurrentDate = "STR_TO_DATE('" . $endDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; $whereStatuses = []; foreach ($statuses as $key => $status) { $whereStatuses[] = "cb.status = '$status'"; } $whereStatuses = $whereStatuses ? 'AND (' . implode(' OR ', $whereStatuses) . ')' : ''; try { $statement = $this->connection->query( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, a.googleMeetUrl AS appointment_google_meet_url, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.customFields AS booking_customFields, cb.persons AS booking_persons, cb.aggregatedPrice AS booking_aggregatedPrice, cb.duration AS booking_duration, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.data AS payment_data, cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->appointmentsTable} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$couponsTable} c ON c.id = cb.couponId WHERE a.bookingStart BETWEEN $startCurrentDate AND $endCurrentDate {$whereStatuses} AND a.id NOT IN ( SELECT nl.appointmentId FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.id = {$notificationId} AND (nl.sent IS NULL OR nl.sent = 1) AND nl.appointmentId IS NOT NULL )" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } return AppointmentFactory::createCollection($rows); } /** * Return a collection of tomorrow events where provider notification is not sent and should be. * * @param $notificationId * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getProvidersNextDayEvents($notificationId, $nextDay) { $couponsTable = CouponsTable::getTableName(); $eventsTable = EventsTable::getTableName(); $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); $startDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(0, 0, 0)->format('Y-m-d H:i:s') ); $endDate = DateTimeService::getCustomDateTimeObjectInUtc( DateTimeService::getNowDateTimeObject()->setTime(23, 59, 59)->format('Y-m-d H:i:s') ); if ($nextDay) { $startDate = $startDate->modify('+1 day'); $endDate = $endDate->modify('+1 day'); } $startCurrentDate = "STR_TO_DATE('" . $startDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; $endCurrentDate = "STR_TO_DATE('" . $endDate->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; try { $statement = $this->connection->query( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringUntil AS event_recurringUntil, e.maxCapacity AS event_maxCapacity, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.notifyParticipants AS event_notifyParticipants, e.zoomUserId AS event_zoomUserId, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.organizerId AS event_organizerId, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleMeetUrl AS event_googleMeetUrl, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.timeZone AS provider_timeZone, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.customFields AS booking_customFields, cb.persons AS booking_persons, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.data AS payment_data, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$eventsTable} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id INNER JOIN {$this->bookingsTable} cb ON cb.id = cbe.customerBookingId LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$couponsTable} c ON c.id = cb.couponId LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$this->usersTable} pu ON pu.id = epr.userId WHERE ep.periodStart BETWEEN {$startCurrentDate} AND {$endCurrentDate} AND cb.status = 'approved' AND e.id NOT IN ( SELECT nl.eventId FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.id = {$notificationId} AND (nl.sent IS NULL OR nl.sent = 1) AND nl.eventId IS NOT NULL )" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find events in ' . __CLASS__, $e->getCode(), $e); } return EventFactory::createCollection($rows); } /** * Return a collection of today's past appointments where follow up notification is not sent and should be. * * @param Notification $notification * @param array $statuses * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getScheduledAppointments($notification, $statuses = []) { $couponsTable = CouponsTable::getTableName(); $customerBookingsExtrasTable = CustomerBookingsToExtrasTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); try { $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')"; $where = ''; if ($notification->getTimeAfter()) { $timeAfter = $notification->getTimeAfter()->getValue(); $lastTime = $timeAfter + 259200; $where = "{$currentDateTime} BETWEEN DATE_ADD(a.bookingEnd, INTERVAL {$timeAfter} SECOND) AND DATE_ADD(a.bookingEnd, INTERVAL {$lastTime} SECOND)"; } else if ($notification->getTimeBefore()) { $timeBefore = $notification->getTimeBefore()->getValue(); $where = "({$currentDateTime} BETWEEN DATE_SUB(a.bookingStart, INTERVAL {$timeBefore} SECOND) AND a.bookingStart) AND (a.bookingStart >= DATE_ADD(p.created, INTERVAL {$timeBefore} SECOND))"; } $whereStatuses = []; foreach ($statuses as $key => $status) { $whereStatuses[] = "cb.status = '$status'"; } $whereStatuses = $whereStatuses ? ($where ? ' AND ' : '') . '(' . implode(' OR ', $whereStatuses) . ')' : ''; $statement = $this->connection->query( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.googleMeetUrl AS appointment_google_meet_url, a.lessonSpace AS appointment_lesson_space, a.zoomMeeting AS appointment_zoom_meeting, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.persons AS booking_persons, cb.duration AS booking_duration, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.data AS payment_data, cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->appointmentsTable} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$couponsTable} c ON c.id = cb.couponId WHERE {$where} AND a.notifyParticipants = 1 {$whereStatuses} AND a.id NOT IN ( SELECT nl.appointmentId FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.id = {$notification->getId()->getValue()} AND (nl.sent IS NULL OR nl.sent = 1) AND nl.appointmentId IS NOT NULL )" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } return AppointmentFactory::createCollection($rows); } /** * Return a collection of today's past appointments where follow up notification is not sent and should be. * * @param Notification $notification * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getScheduledEvents($notification) { $couponsTable = CouponsTable::getTableName(); $eventsTable = EventsTable::getTableName(); $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); try { $statement = $this->connection->query( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringUntil AS event_recurringUntil, e.maxCapacity AS event_maxCapacity, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.notifyParticipants AS event_notifyParticipants, e.zoomUserId AS event_zoomUserId, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.organizerId AS event_organizerId, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.lessonSpace AS event_periodLessonSpace, ep.zoomMeeting AS event_periodZoomMeeting, ep.googleMeetUrl AS event_googleMeetUrl, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.timeZone AS provider_timeZone, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.persons AS booking_persons, cb.duration AS booking_duration, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.data AS payment_data, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$eventsTable} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id INNER JOIN {$this->bookingsTable} cb ON cb.id = cbe.customerBookingId LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$couponsTable} c ON c.id = cb.couponId LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$this->usersTable} pu ON pu.id = epr.userId WHERE e.notifyParticipants = 1 AND cb.status = 'approved' AND e.id NOT IN ( SELECT nl.eventId FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.id = {$notification->getId()->getValue()} AND (nl.sent IS NULL OR nl.sent = 1) AND nl.eventId IS NOT NULL )" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find events in ' . __CLASS__, $e->getCode(), $e); } return EventFactory::createCollection($rows); } /** * Returns a collection of customers that have birthday on today's date and where notification is not sent * * @param $notificationType * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getBirthdayCustomers($notificationType) { $currentDate = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d')"; $params = [ ':type' => AbstractUser::USER_ROLE_CUSTOMER, ':statusVisible' => Status::VISIBLE, ]; try { $statement = $this->connection->prepare( "SELECT * FROM {$this->usersTable} as u WHERE u.type = :type AND u.status = :statusVisible AND MONTH(birthday) = MONTH({$currentDate}) AND DAY(u.birthday) = DAY({$currentDate}) AND u.id NOT IN ( SELECT nl.userID FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE n.name = 'customer_birthday_greeting' AND n.type = '{$notificationType}' )" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([UserFactory::class, 'create'], $row); } return new Collection($items); } /** * Returns a collection of undelivered notifications * * @param string $type * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getUndeliveredNotifications($type) { $params = [ ':type' => $type, ]; $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')"; $pastDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeObjectInUtc()->modify('-1 day')->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; try { $statement = $this->connection->prepare( "SELECT nl.* FROM {$this->table} nl INNER JOIN {$this->notificationsTable} n ON nl.notificationId = n.id WHERE nl.sent = 0 AND {$currentDateTime} > DATE_ADD(nl.sentDateTime, INTERVAL 300 SECOND) AND {$pastDateTime} < nl.sentDateTime AND nl.data IS NOT NULL AND n.type = :type" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * @param int $userId * @param string $type * @param string $entityType * @param int $entityId * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getSentNotificationsByUserAndEntity($userId, $type, $entityType, $entityId) { $entityColumn = ''; switch ($entityType) { case (Entities::APPOINTMENT): $entityColumn = 'nl.appointmentId'; break; case (Entities::EVENT): $entityColumn = 'nl.eventId'; break; case (Entities::PACKAGE): $entityColumn = 'nl.packageCustomerId'; break; } $params = [ ':entityId' => $entityId, ':userId' => $userId, ':type' => $type, ]; try { $statement = $this->connection->prepare( "SELECT * FROM {$this->table} nl WHERE nl.userId = :userId AND {$entityColumn} = :entityId AND nl.notificationId IN (SELECT id FROM {$this->notificationsTable} WHERE type = :type) ORDER BY nl.sentDateTime DESC" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } } Repository/Bookable/Service/ExtraRepository.php 0000666 00000010262 15165376447 0015764 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Entity\Bookable\Service\Extra; use AmeliaBooking\Domain\Factory\Bookable\Service\ExtraFactory; use AmeliaBooking\Domain\Repository\Bookable\Service\ExtraRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class ExtraRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class ExtraRepository extends AbstractRepository implements ExtraRepositoryInterface { const FACTORY = ExtraFactory::class; /** * @param Extra $entity * * @return mixed * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':description' => $data['description'], ':price' => $data['price'], ':maxQuantity' => $data['maxQuantity'], ':duration' => $data['duration'], ':serviceId' => $data['serviceId'], ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0, ':position' => $data['position'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `name`, `description`, `price`, `maxQuantity`, `duration`, `serviceId`, `aggregatedPrice`, `position`, `translations` ) VALUES ( :name, :description, :price, :maxQuantity, :duration, :serviceId, :aggregatedPrice, :position, :translations )" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Extra $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':description' => $data['description'], ':price' => $data['price'], ':maxQuantity' => $data['maxQuantity'], ':duration' => $data['duration'], ':serviceId' => $data['serviceId'], ':aggregatedPrice' => $data['aggregatedPrice'] === null ? $data['aggregatedPrice'] : ((int)$data['aggregatedPrice']), ':position' => $data['position'], ':translations' => $data['translations'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `name` = :name, `description` = :description, `price` = :price, `maxQuantity` = :maxQuantity, `duration` = :duration, `serviceId` = :serviceId, `aggregatedPrice` = :aggregatedPrice, `position` = :position, `translations` = :translations WHERE id = :id" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $result; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/PackageRepository.php 0000666 00000047103 15165376447 0016240 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Factory\Bookable\Service\PackageFactory; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesLocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery\GalleriesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class PackageRepository * * @package AmeliaBooking\Infrastructure\Repository\Service */ class PackageRepository extends AbstractRepository { const FACTORY = PackageFactory::class; /** * @param Connection $connection * @param string $table */ public function __construct( Connection $connection, $table ) { parent::__construct($connection, $table); } /** * @param Package $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':description' => $data['description'], ':color' => $data['color'], ':price' => $data['price'], ':status' => $data['status'], ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':position' => $data['position'], ':calculatedPrice' => $data['calculatedPrice'] ? 1 : 0, ':discount' => $data['discount'], ':settings' => $data['settings'], ':endDate' => $data['endDate'], ':durationCount' => $data['durationCount'], ':durationType' => $data['durationType'], ':translations' => $data['translations'], ':deposit' => $data['deposit'], ':depositPayment' => $data['depositPayment'], ':fullPayment' => $data['fullPayment'] ? 1 : 0, ':sharedCapacity' => $data['sharedCapacity'] ? 1 : 0, ':quantity' => $data['quantity'], ':limitPerCustomer' => $data['limitPerCustomer'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `name`, `description`, `color`, `price`, `status`, `pictureFullPath`, `pictureThumbPath`, `calculatedPrice`, `discount`, `position`, `settings`, `endDate`, `durationCount`, `durationType`, `translations`, `deposit`, `depositPayment`, `fullPayment`, `sharedCapacity`, `quantity`, `limitPerCustomer` ) VALUES ( :name, :description, :color, :price, :status, :pictureFullPath, :pictureThumbPath, :calculatedPrice, :discount, :position, :settings, :endDate, :durationCount, :durationType, :translations, :deposit, :depositPayment, :fullPayment, :sharedCapacity, :quantity, :limitPerCustomer )" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $packageId * @param Package $entity * * @throws QueryExecutionException */ public function update($packageId, $entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':description' => $data['description'], ':color' => $data['color'], ':price' => $data['price'], ':status' => $data['status'], ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':position' => $data['position'], ':calculatedPrice' => $data['calculatedPrice'] ? 1 : 0, ':discount' => $data['discount'], ':settings' => $data['settings'], ':endDate' => $data['endDate'], ':durationCount' => $data['durationCount'], ':durationType' => $data['durationType'], ':translations' => $data['translations'], ':deposit' => $data['deposit'], ':depositPayment' => $data['depositPayment'], ':fullPayment' => $data['fullPayment'] ? 1 : 0, ':sharedCapacity' => $data['sharedCapacity'] ? 1 : 0, ':quantity' => $data['quantity'], ':limitPerCustomer' => $data['limitPerCustomer'], ':id' => $packageId ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `name` = :name, `description` = :description, `color` = :color, `price` = :price, `status` = :status, `pictureFullPath` = :pictureFullPath, `pictureThumbPath` = :pictureThumbPath, `position` = :position, `calculatedPrice` = :calculatedPrice, `discount` = :discount, `settings` = :settings, `endDate` = :endDate, `durationCount` = :durationCount, `durationType` = :durationType, `translations` = :translations, `deposit` = :deposit, `depositPayment` = :depositPayment, `fullPayment` = :fullPayment, `sharedCapacity` = :sharedCapacity, `quantity` = :quantity, `limitPerCustomer` = :limitPerCustomer WHERE id = :id" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByCriteria($criteria) { $params = []; $where = []; $order = 'ORDER BY p.name, ps.id ASC'; if (isset($criteria['sort'])) { if ($criteria['sort'] === '') { $order = 'ORDER BY p.position'; } else { $orderColumn = strpos($criteria['sort'], 'name') !== false ? 'p.name' : 'p.price'; $orderDirection = $criteria['sort'][0] === '-' ? 'DESC' : 'ASC'; $order = "ORDER BY {$orderColumn} {$orderDirection}"; } } if (!empty($criteria['search'])) { $params[':search'] = "%{$criteria['search']}%"; $where[] = 'p.name LIKE :search'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 's.id IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['packages'])) { $queryPackages = []; foreach ((array)$criteria['packages'] as $index => $value) { $param = ':package' . $index; $queryPackages[] = $param; $params[$param] = $value; } $where[] = 'p.id IN (' . implode(', ', $queryPackages) . ')'; } if (!empty($criteria['status'])) { $params[':status'] = $criteria['status']; $where[] = 's.status = :status'; } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $servicesTable = ServicesTable::getTableName(); $usersTable = UsersTable::getTableName(); $locationsTable = LocationsTable::getTableName(); $packageServicesTable = PackagesServicesTable::getTableName(); $packageServicesProvidersTable = PackagesServicesProvidersTable::getTableName(); $packageServicesLocationsTable = PackagesServicesLocationsTable::getTableName(); $galleriesTable = GalleriesTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT p.id AS package_id, p.name AS package_name, p.description AS package_description, p.color AS package_color, p.price AS package_price, p.status AS package_status, p.pictureFullPath AS package_picture_full, p.pictureThumbPath AS package_picture_thumb, p.calculatedPrice AS package_calculated_price, p.discount AS package_discount, p.position AS package_position, p.settings AS package_settings, p.endDate AS package_endDate, p.durationCount AS package_durationCount, p.durationType AS package_durationType, p.translations AS package_translations, p.deposit AS package_deposit, p.depositPayment AS package_depositPayment, p.fullPayment AS package_fullPayment, p.sharedCapacity AS package_sharedCapacity, p.quantity AS package_quantity, p.limitPerCustomer AS package_limitPerCustomer, ps.id AS package_service_id, ps.quantity AS package_service_quantity, ps.minimumScheduled AS package_service_minimumScheduled, ps.maximumScheduled AS package_service_maximumScheduled, ps.allowProviderSelection AS package_service_allowProviderSelection, s.id AS service_id, s.price AS service_price, s.minCapacity AS service_minCapacity, s.maxCapacity AS service_maxCapacity, s.name AS service_name, s.description AS service_description, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.translations AS service_translations, s.show AS service_show, l.id AS location_id, l.name AS location_name, l.address AS location_address, l.phone AS location_phone, l.latitude AS location_latitude, l.longitude AS location_longitude, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.status AS provider_status, pu.translations AS provider_translations, g.id AS gallery_id, g.pictureFullPath AS gallery_picture_full, g.pictureThumbPath AS gallery_picture_thumb, g.position AS gallery_position FROM {$this->table} p LEFT JOIN {$packageServicesTable} ps ON ps.packageId = p.id LEFT JOIN {$servicesTable} s ON ps.serviceId = s.id LEFT JOIN {$packageServicesProvidersTable} psp ON psp.packageServiceId = ps.id LEFT JOIN {$packageServicesLocationsTable} psl ON psl.packageServiceId = ps.id LEFT JOIN {$usersTable} pu ON pu.id = psp.userId LEFT JOIN {$locationsTable} l ON l.id = psl.locationId LEFT JOIN {$galleriesTable} g ON g.entityId = p.id AND g.entityType = 'package' WHERE 1 = 1 {$where} {$order}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param $id * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getById($id) { $params[':id'] = $id; $servicesTable = ServicesTable::getTableName(); $usersTable = UsersTable::getTableName(); $locationsTable = LocationsTable::getTableName(); $packageServicesTable = PackagesServicesTable::getTableName(); $packageServicesProvidersTable = PackagesServicesProvidersTable::getTableName(); $packageServicesLocationsTable = PackagesServicesLocationsTable::getTableName(); $galleriesTable = GalleriesTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT p.id AS package_id, p.name AS package_name, p.description AS package_description, p.color AS package_color, p.price AS package_price, p.status AS package_status, p.pictureFullPath AS package_picture_full, p.pictureThumbPath AS package_picture_thumb, p.calculatedPrice AS package_calculated_price, p.discount AS package_discount, p.position AS package_position, p.settings AS package_settings, p.endDate AS package_endDate, p.durationCount AS package_durationCount, p.durationType AS package_durationType, p.translations AS package_translations, p.deposit AS package_deposit, p.depositPayment AS package_depositPayment, p.fullPayment AS package_fullPayment, p.sharedCapacity AS package_sharedCapacity, p.quantity AS package_quantity, p.limitPerCustomer AS package_limitPerCustomer, ps.id AS package_service_id, ps.quantity AS package_service_quantity, ps.minimumScheduled AS package_service_minimumScheduled, ps.maximumScheduled AS package_service_maximumScheduled, ps.allowProviderSelection AS package_service_allowProviderSelection, s.id AS service_id, s.price AS service_price, s.minCapacity AS service_minCapacity, s.maxCapacity AS service_maxCapacity, s.name AS service_name, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.show AS service_show, l.id AS location_id, l.name AS location_name, l.address AS location_address, l.phone AS location_phone, l.latitude AS location_latitude, l.longitude AS location_longitude, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.translations AS provider_translations, g.id AS gallery_id, g.pictureFullPath AS gallery_picture_full, g.pictureThumbPath AS gallery_picture_thumb, g.position AS gallery_position FROM {$this->table} p LEFT JOIN {$packageServicesTable} ps ON ps.packageId = p.id LEFT JOIN {$servicesTable} s ON ps.serviceId = s.id LEFT JOIN {$packageServicesProvidersTable} psp ON psp.packageServiceId = ps.id LEFT JOIN {$packageServicesLocationsTable} psl ON psl.packageServiceId = ps.id LEFT JOIN {$usersTable} pu ON pu.id = psp.userId LEFT JOIN {$locationsTable} l ON l.id = psl.locationId LEFT JOIN {$galleriesTable} g ON g.entityId = p.id AND g.entityType = 'package' WHERE p.id = :id" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($id); } /** * @param $serviceId * @param $status * * @throws QueryExecutionException */ public function updateStatusById($serviceId, $status) { $params = [ ':id' => $serviceId, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/PackageCustomerRepository.php 0000666 00000011630 15165376447 0017756 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Entity\Bookable\Service\Package; use AmeliaBooking\Domain\Entity\Bookable\Service\PackageCustomer; use AmeliaBooking\Domain\Factory\Bookable\Service\PackageCustomerFactory; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PackageCustomerRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class PackageCustomerRepository extends AbstractRepository { const FACTORY = PackageCustomerFactory::class; /** * @param PackageCustomer $entity * * @return int * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':packageId' => $data['packageId'], ':customerId' => $data['customerId'], ':price' => $data['price'], ':start' => $data['start'], ':end' => $data['end'], ':purchased' => $data['purchased'], ':bookingsCount' => $data['bookingsCount'], ':couponId' => $data['couponId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`packageId`, `customerId`, `price`, `start`, `end`, `purchased`, `status`, `bookingsCount`, `couponId`) VALUES (:packageId, :customerId, :price, :start, :end, :purchased, 'approved', :bookingsCount, :couponId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param Package $package * @param int $customerId * @param array $limitPerCustomer * @param boolean $packageSpecific * @return int * @throws QueryExecutionException */ public function getUserPackageCount($package, $customerId, $limitPerCustomer, $packageSpecific) { $params = [ ':customerId' => $customerId ]; $startDate = DateTimeService::getNowDateTimeObject()->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i'); $intervalString = "interval " . $limitPerCustomer['period'] . " " . $limitPerCustomer['timeFrame']; $where = "(STR_TO_DATE('" . $startDate . "', '%Y-%m-%d %H:%i:%s') BETWEEN " . "(pc.purchased - " . $intervalString . " + interval 1 second) AND " . "(pc.purchased + " . $intervalString . " - interval 1 second))"; //+ interval 2 day if ($packageSpecific) { $where .= " AND pc.packageId = :packageId"; $params[':packageId'] = $package->getId()->getValue(); } try { $statement = $this->connection->prepare( "SELECT COUNT(DISTINCT pc.id) AS count FROM {$this->table} pc WHERE pc.customerId = :customerId AND {$where} AND pc.status = 'approved' " ); $statement->execute($params); $rows = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param array $criteria * * @return array * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFiltered($criteria) { $params = []; $where = []; if ($criteria['customerId']) { $params[':customerId'] = $criteria['customerId']; $where[] = 'pc.customerId = :customerId'; } if (array_key_exists('bookingStatus', $criteria)) { $where[] = 'pc.status = :bookingStatus'; $params[':bookingStatus'] = $criteria['bookingStatus']; } if (isset($criteria['couponId'])) { $where[] = "pc.couponId = {$criteria['couponId']}"; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT pc.customerId FROM {$this->table} pc $where" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } } Repository/Bookable/Service/PackageCustomerServiceRepository.php 0000666 00000020511 15165376447 0021275 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\PackageCustomerService; use AmeliaBooking\Domain\Factory\Bookable\Service\PackageCustomerServiceFactory; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesCustomersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable; /** * Class PackageCustomerServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class PackageCustomerServiceRepository extends AbstractRepository { const FACTORY = PackageCustomerServiceFactory::class; /** @var string */ protected $packagesCustomersTable; /** @var string */ protected $paymentsTable; /** * @param Connection $connection * @param string $table * * @throws InvalidArgumentException */ public function __construct( Connection $connection, $table ) { parent::__construct($connection, $table); $this->packagesCustomersTable = PackagesCustomersTable::getTableName(); $this->paymentsTable = PaymentsTable::getTableName(); } /** * @param PackageCustomerService $entity * * @return int * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':packageCustomerId' => $data['packageCustomer']['id'], ':serviceId' => $data['serviceId'], ':providerId' => $data['providerId'], ':locationId' => $data['locationId'], ':bookingsCount' => $data['bookingsCount'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`packageCustomerId`, `serviceId`, `providerId`, `locationId`, `bookingsCount`) VALUES (:packageCustomerId, :serviceId, :providerId, :locationId, :bookingsCount)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param array $criteria * @param bool $empty * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getByCriteria($criteria, $empty = false) { $bookingsTable = CustomerBookingsTable::getTableName(); $params = []; $where = []; if (!empty($criteria['ids'])) { $queryIds = []; foreach ($criteria['ids'] as $index => $value) { $param = ':id' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = 'pcs.id IN (' . implode(', ', $queryIds) . ')'; } if (!empty($criteria['purchased'])) { $where[] = "(DATE_FORMAT(pc.purchased, '%Y-%m-%d %H:%i:%s') BETWEEN :purchasedFrom AND :purchasedTo)"; $params[':purchasedFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['purchased'][0]); $params[':purchasedTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['purchased'][1]); } if (!empty($criteria['dates'])) { $where[] = "((:from1 >= DATE_FORMAT(pc.start, '%Y-%m-%d %H:%i:%s') AND :from2 <= DATE_FORMAT(pc.end, '%Y-%m-%d %H:%i:%s') ) OR ( :from3 <= DATE_FORMAT(pc.start, '%Y-%m-%d %H:%i:%s') AND :to1 >= DATE_FORMAT(pc.start, '%Y-%m-%d %H:%i:%s'))) "; $params[':from1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':from2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':from3'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':to1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (!empty($criteria['customerId'])) { $params[':customerId'] = $criteria['customerId']; $where[] = 'pc.customerId = :customerId'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ($criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'pcs.serviceId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['packages'])) { $queryServices = []; foreach ($criteria['packages'] as $index => $value) { $param = ':package' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'pc.packageId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['packagesCustomers'])) { $queryServices = []; foreach ($criteria['packagesCustomers'] as $index => $value) { $param = ':packageCustomerId' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'pc.id IN (' . implode(', ', $queryServices) . ')'; } if ($empty) { $where[] = 'pcs.id NOT IN (SELECT packageCustomerServiceId FROM ' . $bookingsTable . ' WHERE packageCustomerServiceId IS NOT NULL)'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT pc.id AS package_customer_id, pc.packageId AS package_customer_packageId, pc.customerId AS package_customer_customerId, pc.price AS package_customer_price, pc.end AS package_customer_end, pc.start AS package_customer_start, pc.purchased AS package_customer_purchased, pc.status AS package_customer_status, pc.bookingsCount AS package_customer_bookingsCount, pc.couponId AS package_customer_couponId, pcs.id AS package_customer_service_id, pcs.serviceId AS package_customer_service_serviceId, pcs.providerId AS package_customer_service_providerId, pcs.locationId AS package_customer_service_locationId, pcs.bookingsCount AS package_customer_service_bookingsCount, p.id AS payment_id, p.packageCustomerId AS payment_packageCustomerId, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId FROM {$this->table} pcs INNER JOIN {$this->packagesCustomersTable} pc ON pcs.packageCustomerId = pc.id LEFT JOIN {$this->paymentsTable} p ON p.packageCustomerId = pc.id {$where}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } } Repository/Bookable/Service/ProviderServiceRepository.php 0000666 00000024577 15165376447 0020032 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Application\Services\Bookable\PackageApplicationService; use AmeliaBooking\Domain\Entity\Bookable\Service\Service; use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\PackagesServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class ProviderServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class ProviderServiceRepository extends AbstractRepository { const FACTORY = ServiceFactory::class; /** * @param Service $entity * @param int $userId * * @return int * @throws QueryExecutionException */ public function add($entity, $userId) { $data = $entity->toArray(); $params = [ ':userId' => $userId, ':serviceId' => $data['id'], ':minCapacity' => $data['minCapacity'], ':maxCapacity' => $data['maxCapacity'], ':price' => $data['price'], ':customPricing' => $data['customPricing'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`userId`, `serviceId`, `minCapacity`, `maxCapacity`, `price`, `customPricing`) VALUES (:userId, :serviceId, :minCapacity, :maxCapacity, :price, :customPricing)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param Service $entity * @param int $id * * @return int * @throws QueryExecutionException */ public function update($entity, $id) { $data = $entity->toArray(); $params = [ ':id' => $id, ':minCapacity' => $data['minCapacity'], ':maxCapacity' => $data['maxCapacity'], ':price' => $data['price'], ':customPricing' => $data['customPricing'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `minCapacity` = :minCapacity, `maxCapacity` = :maxCapacity, `price` = :price, `customPricing` = :customPricing WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param $serviceId * * @return array * @throws QueryExecutionException */ public function getAllForService($serviceId) { try { $statement = $this->connection->prepare( "SELECT ps.id, ps.userId, ps.serviceId, ps.minCapacity, ps.maxCapacity, ps.price, ps.customPricing FROM {$this->table} ps WHERE ps.serviceId = :serviceId" ); $params = [ ':serviceId' => $serviceId ]; $statement->execute($params); $rows = $statement->fetchAll(); foreach ($rows as &$row) { $row['id'] = (int)$row['id']; $row['userId'] = (int)$row['userId']; $row['serviceId'] = (int)$row['serviceId']; $row['minCapacity'] = (int)$row['minCapacity']; $row['maxCapacity'] = (int)$row['maxCapacity']; } return $rows; } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $providerId * * @return array * @throws QueryExecutionException */ public function getAllForProvider($providerId) { try { $statement = $this->connection->prepare( "SELECT ps.id, ps.userId, ps.serviceId, ps.minCapacity, ps.maxCapacity, ps.price, ps.customPricing FROM {$this->table} ps WHERE ps.userId = :providerId" ); $params = array( ':providerId' => $providerId ); $statement->execute($params); $rows = $statement->fetchAll(); foreach ($rows as &$row) { $row['id'] = (int)$row['id']; $row['userId'] = (int)$row['userId']; $row['serviceId'] = (int)$row['serviceId']; $row['minCapacity'] = (int)$row['minCapacity']; $row['maxCapacity'] = (int)$row['maxCapacity']; } return $rows; } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } } /** * * It will delete all relations for one service except ones that are sent in providers array * * @param array $providersIds * @param int $serviceId * * @return bool * @throws QueryExecutionException */ public function deleteAllNotInProvidersArrayForService($providersIds, $serviceId) { $providers = ' '; if (!empty($providersIds)) { foreach ($providersIds as $index => $value) { ++$index; $providers .= ':providerId' . $index . ', '; $params[':providerId' . $index] = (int)$value; } $providers = 'AND `userId` NOT IN (' . rtrim($providers, ', ') . ')'; } $params[':serviceId'] = $serviceId; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE 1 = 1 $providers AND serviceId = :serviceId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * * It will delete all relations for one service except ones that are sent in providers array * * @param array $servicesIds * @param int $providerId * * @return bool * @throws QueryExecutionException */ public function deleteAllNotInServicesArrayForProvider($servicesIds, $providerId) { $services = ' '; if (!empty($servicesIds)) { foreach ($servicesIds as $index => $value) { ++$index; $services .= ':serviceId' . $index . ', '; $params[':serviceId' . $index] = $value; } $services = 'AND `serviceId` NOT IN (' . rtrim($services, ', ') . ')'; } $params[':providerId'] = $providerId; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE 1 = 1 $services AND userId = :providerId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param Service $entity * @param int $serviceId * * @return boolean * @throws QueryExecutionException */ public function updateServiceForAllProviders($entity, $serviceId) { $data = $entity->toArray(); $params = [ ':serviceId' => $serviceId, ':minCapacity' => $data['minCapacity'], ':maxCapacity' => $data['maxCapacity'], ':price' => $data['price'], ':customPricing' => $data['customPricing'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `minCapacity` = :minCapacity, `maxCapacity` = :maxCapacity, `price` = :price, `customPricing` = :customPricing WHERE serviceId = :serviceId" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } return true; } /** * @param Service $entity * @param int $serviceId * @param int $providerId * * @return boolean * @throws QueryExecutionException */ public function updateServiceForProvider($entity, $serviceId, $providerId) { $data = $entity->toArray(); $params = [ ':serviceId' => $serviceId, ':providerId' => $providerId, ':minCapacity' => $data['minCapacity'], ':maxCapacity' => $data['maxCapacity'], ':price' => $data['price'], ':customPricing' => $data['customPricing'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `minCapacity` = :minCapacity, `maxCapacity` = :maxCapacity, `price` = :price, `customPricing` = :customPricing WHERE serviceId = :serviceId AND userId = :providerId" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } return true; } } Repository/Bookable/Service/PackageServiceRepository.php 0000666 00000010630 15165376447 0017554 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Entity\Bookable\Service\PackageService; use AmeliaBooking\Domain\Factory\Bookable\Service\PackageServiceFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PackageServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class PackageServiceRepository extends AbstractRepository { const FACTORY = PackageServiceFactory::class; /** * @param PackageService $entity * @param int $packageId * * @return int * @throws QueryExecutionException */ public function add($entity, $packageId) { $data = $entity->toArray(); $params = [ ':packageId' => $packageId, ':serviceId' => $data['service']['id'], ':quantity' => $data['quantity'], ':minimumScheduled' => $data['minimumScheduled'], ':maximumScheduled' => $data['maximumScheduled'], ':allowProviderSelection' => $data['allowProviderSelection'] ? 1 : 0, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`packageId`, `serviceId`, `quantity`, `minimumScheduled`, `maximumScheduled`, `allowProviderSelection`) VALUES (:packageId, :serviceId, :quantity, :minimumScheduled, :maximumScheduled, :allowProviderSelection)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param int $id * @param PackageService $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':quantity' => $data['quantity'], ':minimumScheduled' => $data['minimumScheduled'], ':maximumScheduled' => $data['maximumScheduled'], ':allowProviderSelection' => $data['allowProviderSelection'] ? 1 : 0, ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `quantity` = :quantity, `minimumScheduled` = :minimumScheduled, `maximumScheduled` = :maximumScheduled, `allowProviderSelection` = :allowProviderSelection WHERE id = :id" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $result; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * * It will delete all relations for one package except ones that are sent in services array * * @param array $servicesIds * @param int $packageId * * @return bool * @throws QueryExecutionException */ public function deleteAllNotInServicesArrayForPackage($servicesIds, $packageId) { $services = ' '; if (!empty($servicesIds)) { foreach ($servicesIds as $index => $value) { ++$index; $services .= ':serviceId' . $index . ', '; $params[':serviceId' . $index] = (int)$value; } $services = 'AND `serviceId` NOT IN (' . rtrim($services, ', ') . ')'; } $params[':packageId'] = $packageId; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE 1 = 1 {$services} AND packageId = :packageId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/ResourceRepository.php 0000666 00000023712 15165376447 0016474 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Resource; use AmeliaBooking\Domain\Factory\Bookable\Service\ResourceFactory; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ResourcesToEntitiesTable; /** * Class ResourceRepository * * @package AmeliaBooking\Infrastructure\Repository\Service */ class ResourceRepository extends AbstractRepository { const FACTORY = ResourceFactory::class; /** * @param Connection $connection * @param string $table */ public function __construct( Connection $connection, $table ) { parent::__construct($connection, $table); } /** * @param Resource $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':quantity' => $data['quantity'], ':status' => $data['status'], ':shared' => $data['shared'] ? $data['shared'] : null, ':countAdditionalPeople' => $data['countAdditionalPeople'] ? 1 : 0 ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `name`, `quantity`, `status`, `shared`, `countAdditionalPeople` ) VALUES ( :name, :quantity, :status, :shared, :countAdditionalPeople )" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $resourceId * @param Resource $entity * * @throws QueryExecutionException */ public function update($resourceId, $entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':quantity' => $data['quantity'], ':status' => $data['status'], ':shared' => $data['shared'] ? $data['shared'] : null, ':countAdditionalPeople' => $data['countAdditionalPeople'] ? 1 : 0, ':id' => $resourceId ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `name` = :name, `quantity` = :quantity, `status` = :status, `shared` = :shared, `countAdditionalPeople` = :countAdditionalPeople WHERE id = :id" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $resourceId * @param int $status * * @return bool * @throws QueryExecutionException */ public function updateStatusById($resourceId, $status) { $params = [ ':id' => $resourceId, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByCriteria($criteria) { $params = []; $where = []; if (!empty($criteria['search'])) { $params[':search'] = "%{$criteria['search']}%"; $where[] = 'r.name LIKE :search'; } if (!empty($criteria['services'])) { $query = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $query[] = $param; $params[$param] = $value; } $where[] = 're.entityId IN (' . implode(', ', $query) . ') AND re.entityType="service"'; } if (!empty($criteria['locations'])) { $query = []; foreach ((array)$criteria['locations'] as $index => $value) { $param = ':location' . $index; $query[] = $param; $params[$param] = $value; } $where[] = 're.entityId IN (' . implode(', ', $query) . ') AND re.entityType="location"'; } if (!empty($criteria['employees'])) { $query = []; foreach ((array)$criteria['employees'] as $index => $value) { $param = ':employee' . $index; $query[] = $param; $params[$param] = $value; } $where[] = 're.entityId IN (' . implode(', ', $query) . ') AND re.entityType="employee"'; } if (!empty($criteria['status'])) { $params[':status'] = $criteria['status']; $where[] = 'r.status = :status'; } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $resourceEntitiesTable = ResourcesToEntitiesTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT r.id AS resource_id, r.name AS resource_name, r.quantity AS resource_quantity, r.status AS resource_status, r.shared AS resource_shared, r.countAdditionalPeople AS resource_countAdditionalPeople, re.id AS resource_entity_id, re.resourceId AS resource_entity_resourceId, re.entityId AS resource_entity_entityId, re.entityType AS resource_entity_entityType FROM {$this->table} r LEFT JOIN {$resourceEntitiesTable} re ON re.resourceId = r.id WHERE 1 = 1 {$where} " ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by criteria in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param $id * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getById($id) { $params[':id'] = $id; $resourceEntitiesTable = ResourcesToEntitiesTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT r.id AS resource_id, r.name AS resource_name, r.quantity AS resource_quantity, r.status AS resource_status, r.shared AS resource_shared, r.countAdditionalPeople AS resource_countAdditionalPeople, re.id AS resource_entity_id, re.resourceId AS resource_entity_resourceId, re.entityId AS resource_entity_entityId, re.entityType AS resource_entity_entityType FROM {$this->table} r LEFT JOIN {$resourceEntitiesTable} re ON re.resourceId = r.id WHERE r.id = :id" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($id); } /** * @param int $id * * @return bool * @throws QueryExecutionException|InvalidArgumentException */ public function delete($id) { $resourceToEntities = ResourcesToEntitiesTable::getTableName(); $params = [ ':id' => $id, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE id = :id" ); $success1 = $statement->execute($params); $statement = $this->connection->prepare( "DELETE FROM {$resourceToEntities} WHERE resourceId = :id" ); $success2 = $statement->execute($params); return $success1 && $success2; } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/PackageServiceProviderRepository.php 0000666 00000005443 15165376447 0021275 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Entity\Location\Location; use AmeliaBooking\Domain\Entity\User\Provider; use AmeliaBooking\Domain\Factory\Bookable\Service\PackageServiceFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PackageServiceProviderRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class PackageServiceProviderRepository extends AbstractRepository { const FACTORY = PackageServiceFactory::class; /** * @param Provider $entity * @param int $packageServiceId * * @return int * @throws QueryExecutionException */ public function add($entity, $packageServiceId) { $data = $entity->toArray(); $params = [ ':packageServiceId' => $packageServiceId, ':userId' => $data['id'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`packageServiceId`, `userId`) VALUES (:packageServiceId, :userId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * * It will delete all relations for one package service except ones that are sent in providers array * * @param array $providersIds * @param int $packageServiceId * * @return bool * @throws QueryExecutionException */ public function deleteAllNotInProvidersServicesArrayForPackage($providersIds, $packageServiceId) { $providers = ' '; if (!empty($providersIds)) { foreach ($providersIds as $index => $value) { ++$index; $providers .= ':userId' . $index . ', '; $params[':userId' . $index] = (int)$value; } $providers = 'AND `userId` NOT IN (' . rtrim($providers, ', ') . ')'; } $params[':packageServiceId'] = $packageServiceId; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE 1 = 1 {$providers} AND packageServiceId = :packageServiceId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/ResourceEntitiesRepository.php 0000666 00000012167 15165376447 0020203 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; /** * Class ResourceEntitiesRepository * * @package AmeliaBooking\Infrastructure\Repository\Service */ class ResourceEntitiesRepository extends AbstractRepository { /** * @param Connection $connection * @param string $table */ public function __construct( Connection $connection, $table ) { parent::__construct($connection, $table); } /** * @param array $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $params = [ ':resourceId' => $entity['resourceId'], ':entityId' => $entity['entityId'], ':entityType' => $entity['entityType'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `resourceId`, `entityId`, `entityType` ) VALUES ( :resourceId, :entityId, :entityType )" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $resourceEntityId * @param array $entity * * @throws QueryExecutionException */ public function update($resourceEntityId, $entity) { $params = [ ':resourceId' => $entity['resourceId'], ':entityId' => $entity['entityId'], ':entityType' => $entity['entityType'], ':id' => $resourceEntityId ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `resourceId` = :resourceId, `entityId` = :entityId, `entityType` = :entityType, WHERE id = :id" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $id * * @return array * @throws QueryExecutionException */ public function getByResourceId($id) { try { $statement = $this->connection->prepare( "SELECT * FROM {$this->table} WHERE resourceId = :resourceId" ); $params = [ ':resourceId' => $id ]; $statement->execute($params); $entityRows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get entities in ' . __CLASS__, $e->getCode(), $e); } return $entityRows; } /** * @param int $entityId * @param string $entityType * * @return bool * @throws QueryExecutionException */ public function deleteByEntityIdAndEntityType($entityId, $entityType) { $params = [ ':entityId' => $entityId, ':entityType' => $entityType, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE entityId = :entityId AND entityType = :entityType" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete entities in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $entityId * @param string $entityType * @param int $resourceId * * @return bool * @throws QueryExecutionException */ public function deleteByEntityIdAndEntityTypeAndResourceId($entityId, $entityType, $resourceId) { $params = [ ':entityId' => $entityId, ':entityType' => $entityType, ':resourceId' => $resourceId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE entityId = :entityId AND entityType = :entityType AND resourceId = :resourceId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete entities in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/PackageServiceLocationRepository.php 0000666 00000005410 15165376447 0021245 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Entity\Location\Location; use AmeliaBooking\Domain\Factory\Bookable\Service\PackageServiceFactory; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class PackageServiceLocationRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class PackageServiceLocationRepository extends AbstractRepository { const FACTORY = PackageServiceFactory::class; /** * @param Location $entity * @param int $packageServiceId * * @return int * @throws QueryExecutionException */ public function add($entity, $packageServiceId) { $data = $entity->toArray(); $params = [ ':packageServiceId' => $packageServiceId, ':locationId' => $data['id'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`packageServiceId`, `locationId`) VALUES (:packageServiceId, :locationId)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * * It will delete all relations for one package service except ones that are sent in locations array * * @param array $locationsIds * @param int $packageServiceId * * @return bool * @throws QueryExecutionException */ public function deleteAllNotInLocationsServicesArrayForPackage($locationsIds, $packageServiceId) { $locations = ' '; if (!empty($locationsIds)) { foreach ($locationsIds as $index => $value) { ++$index; $locations .= ':locationId' . $index . ', '; $params[':locationId' . $index] = (int)$value; } $locations = 'AND `locationId` NOT IN (' . rtrim($locations, ', ') . ')'; } $params[':packageServiceId'] = $packageServiceId; try { $statement = $this->connection->prepare( "DELETE FROM {$this->table} WHERE 1 = 1 {$locations} AND packageServiceId = :packageServiceId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/ServiceRepository.php 0000666 00000114254 15165376447 0016307 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Domain\Entity\Bookable\Service\Service; use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Domain\Repository\Bookable\Service\ServiceRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; /** * Class ServiceRepository * * @package AmeliaBooking\Infrastructure\Repository\Service */ class ServiceRepository extends AbstractRepository implements ServiceRepositoryInterface { const FACTORY = ServiceFactory::class; /** @var string */ protected $providerServicesTable; /** @var string */ protected $extrasTable; /** @var string */ protected $serviceViewsTable; /** @var string */ protected $galleriesTable; /** * @param Connection $connection * @param string $table * @param string $providerServicesTable * @param string $extrasTable * @param string $serviceViewsTable * @param string $galleriesTable */ public function __construct( Connection $connection, $table, $providerServicesTable, $extrasTable, $serviceViewsTable, $galleriesTable ) { parent::__construct($connection, $table); $this->providerServicesTable = $providerServicesTable; $this->extrasTable = $extrasTable; $this->serviceViewsTable = $serviceViewsTable; $this->galleriesTable = $galleriesTable; } /** * @return Collection * @throws QueryExecutionException */ public function getAllArrayIndexedById() { try { $statement = $this->connection->query("SELECT s.id AS service_id, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.price AS service_price, s.customPricing AS service_customPricing, s.limitPerCustomer AS service_limitPerCustomer, s.status AS service_status, s.categoryId AS service_categoryId, s.maxCapacity AS service_maxCapacity, s.maxExtraPeople AS service_maxExtraPeople, s.minCapacity AS service_minCapacity, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.bringingAnyone as service_bringingAnyone, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.position AS service_position, s.show AS service_show, s.aggregatedPrice AS service_aggregatedPrice, s.settings AS service_settings, s.recurringCycle AS service_recurringCycle, s.recurringSub AS service_recurringSub, s.recurringPayment AS service_recurringPayment, s.translations AS service_translations, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, s.fullPayment AS service_fullPayment, s.mandatoryExtra AS service_mandatoryExtra, s.minSelectedExtras AS service_minSelectedExtras, e.id AS extra_id, e.name AS extra_name, e.price AS extra_price, e.maxQuantity AS extra_maxQuantity, e.duration AS extra_duration, e.position AS extra_position, e.aggregatedPrice AS extra_aggregatedPrice, e.description AS extra_description, e.translations AS extra_translations, g.id AS gallery_id, g.pictureFullPath AS gallery_picture_full, g.pictureThumbPath AS gallery_picture_thumb, g.position AS gallery_position FROM {$this->table} s LEFT JOIN {$this->extrasTable} e ON e.serviceId = s.id LEFT JOIN {$this->galleriesTable} g ON g.entityId = s.id AND g.entityType = 'service' ORDER BY s.position, s.name ASC, e.position ASC, g.position ASC"); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $services */ $services = call_user_func([static::FACTORY, 'createCollection'], $rows); /** @var Service $service */ foreach ($services->getItems() as $service) { if ($service->getSettings() && json_decode($service->getSettings()->getValue(), true) === null) { $service->setSettings(null); } } return $services; } /** * @param Service $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':description' => $data['description'], ':color' => $data['color'], ':price' => $data['price'], ':status' => $data['status'], ':categoryId' => $data['categoryId'], ':minCapacity' => $data['minCapacity'], ':maxCapacity' => $data['maxCapacity'], ':maxExtraPeople' => $data['maxExtraPeople'], ':duration' => $data['duration'], ':timeBefore' => $data['timeBefore'], ':timeAfter' => $data['timeAfter'], ':bringingAnyone' => $data['bringingAnyone'] ? 1 : 0, ':show' => $data['show'] ? 1 : 0, ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0, ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':position' => $data['position'], ':settings' => $data['settings'], ':recurringCycle' => $data['recurringCycle'], ':recurringSub' => $data['recurringSub'], ':recurringPayment' => $data['recurringPayment'], ':translations' => $data['translations'], ':deposit' => $data['deposit'], ':depositPayment' => $data['depositPayment'], ':depositPerPerson' => $data['depositPerPerson'] ? 1 : 0, ':fullPayment' => $data['fullPayment'] ? 1 : 0, ':mandatoryExtra' => $data['mandatoryExtra'] ? 1 : 0, ':minSelectedExtras'=> $data['minSelectedExtras'], ':customPricing' => $data['customPricing'], ':limitPerCustomer' => $data['limitPerCustomer'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `name`, `description`, `color`, `price`, `status`, `categoryId`, `minCapacity`, `maxCapacity`, `maxExtraPeople`, `duration`, `timeBefore`, `timeAfter`, `bringingAnyone`, `show`, `aggregatedPrice`, `pictureFullPath`, `pictureThumbPath`, `position`, `settings`, `recurringCycle`, `recurringSub`, `recurringPayment`, `translations`, `deposit`, `depositPayment`, `depositPerPerson`, `fullPayment`, `mandatoryExtra`, `minSelectedExtras`, `customPricing`, `limitPerCustomer` ) VALUES ( :name, :description, :color, :price, :status, :categoryId, :minCapacity, :maxCapacity, :maxExtraPeople, :duration, :timeBefore, :timeAfter, :bringingAnyone, :show, :aggregatedPrice, :pictureFullPath, :pictureThumbPath, :position, :settings, :recurringCycle, :recurringSub, :recurringPayment, :translations, :deposit, :depositPayment, :depositPerPerson, :fullPayment, :mandatoryExtra, :minSelectedExtras, :customPricing, :limitPerCustomer )" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Service $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':description' => $data['description'], ':color' => $data['color'], ':price' => $data['price'], ':status' => $data['status'], ':categoryId' => $data['categoryId'], ':minCapacity' => $data['minCapacity'], ':maxCapacity' => $data['maxCapacity'], ':maxExtraPeople' => $data['maxExtraPeople'], ':duration' => $data['duration'], ':timeBefore' => $data['timeBefore'], ':timeAfter' => $data['timeAfter'], ':bringingAnyone' => $data['bringingAnyone'] ? 1 : 0, ':show' => $data['show'] ? 1 : 0, ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0, ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':position' => $data['position'], ':settings' => $data['settings'], ':recurringCycle' => $data['recurringCycle'], ':recurringSub' => $data['recurringSub'], ':recurringPayment' => $data['recurringPayment'], ':translations' => $data['translations'], ':deposit' => $data['deposit'], ':depositPayment' => $data['depositPayment'], ':depositPerPerson' => $data['depositPerPerson'] ? 1 : 0, ':fullPayment' => $data['fullPayment'] ? 1 : 0, ':mandatoryExtra' => $data['mandatoryExtra'] ? 1 : 0, ':minSelectedExtras'=> $data['minSelectedExtras'], ':customPricing' => $data['customPricing'], ':limitPerCustomer' => $data['limitPerCustomer'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `name` = :name, `description` = :description, `color` = :color, `price` = :price, `status` = :status, `categoryId` = :categoryId, `minCapacity` = :minCapacity, `maxCapacity` = :maxCapacity, `maxExtraPeople` = :maxExtraPeople, `duration` = :duration, `timeBefore` = :timeBefore, `timeAfter` = :timeAfter, `bringingAnyone` = :bringingAnyone, `show` = :show, `aggregatedPrice` = :aggregatedPrice, `pictureFullPath` = :pictureFullPath, `pictureThumbPath` = :pictureThumbPath, `position` = :position, `settings` = :settings, `recurringCycle` = :recurringCycle, `recurringSub` = :recurringSub, `recurringPayment` = :recurringPayment, `translations` = :translations, `deposit` = :deposit, `depositPayment` = :depositPayment, `depositPerPerson` = :depositPerPerson, `fullPayment` = :fullPayment, `mandatoryExtra` = :mandatoryExtra, `minSelectedExtras` = :minSelectedExtras, `customPricing` = :customPricing, `limitPerCustomer` = :limitPerCustomer WHERE id = :id" ); $result = $statement->execute($params); if (!$result) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $result; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $criteria * @param int $itemsPerPage * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFiltered($criteria, $itemsPerPage = null) { $params = []; $where = []; $orderColumn = 's.position, s.id'; $orderDirection = 'ASC'; if (!empty($criteria['sort'])) { switch ($criteria['sort']) { case ('nameAsc'): $orderColumn = 's.name'; $orderDirection = 'ASC'; break; case ('nameDesc'): $orderColumn = 's.name'; $orderDirection = 'DESC'; break; case ('priceAsc'): $orderColumn = 's.price'; $orderDirection = 'ASC'; break; case ('priceDesc'): $orderColumn = 's.price'; $orderDirection = 'DESC'; break; case ('custom'): $orderColumn = 's.position, s.id'; $orderDirection = 'ASC'; break; } } if (!empty($criteria['categoryId'])) { $params[':categoryId'] = $criteria['categoryId']; $where[] = 's.categoryId = :categoryId'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $order = "ORDER BY {$orderColumn} {$orderDirection}"; $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); try { $statement = $this->connection->prepare( "SELECT s.* FROM {$this->table} s {$where} {$order} {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by ids in ' . __CLASS__, $e->getCode(), $e); } $items = new Collection(); foreach ($rows as $row) { $items->addItem(call_user_func([static::FACTORY, 'create'], $row), $row['id']); } return $items; } /** * @param array $criteria * * @return mixed * @throws QueryExecutionException */ public function getCount($criteria) { $params = []; $where = []; if (!empty($criteria['categoryId'])) { $params[':categoryId'] = $criteria['categoryId']; $where[] = 's.categoryId = :categoryId'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT COUNT(*) as count FROM {$this->table} s {$where} ORDER BY s.position, s.id" ); $statement->execute($params); $row = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $row; } /** * @param int $serviceId * @param int $userId * * @return Collection * @throws QueryExecutionException */ public function getProviderServicesWithExtras($serviceId, $userId) { try { $statement = $this->connection->prepare("SELECT s.id AS service_id, s.name AS service_name, s.description AS service_description, s.color AS service_color, ps.price AS service_price, s.status AS service_status, s.categoryId AS service_categoryId, ps.minCapacity AS service_minCapacity, ps.maxCapacity AS service_maxCapacity, ps.customPricing AS service_customPricing, s.limitPerCustomer AS service_limitPerCustomer, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.bringingAnyone as service_bringingAnyone, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.aggregatedPrice AS service_aggregatedPrice, s.settings AS service_settings, s.recurringPayment AS service_recurringPayment, s.translations AS service_translations, s.show AS service_show, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, s.fullPayment AS service_fullPayment, e.id AS extra_id, e.name AS extra_name, e.price AS extra_price, e.maxQuantity AS extra_maxQuantity, e.duration AS extra_duration, e.aggregatedPrice AS extra_aggregatedPrice, e.position AS extra_position, e.translations AS extra_translations FROM {$this->table} s INNER JOIN {$this->providerServicesTable} ps ON s.id = ps.serviceId LEFT JOIN {$this->extrasTable} e ON e.serviceId = s.id WHERE ps.userId = :userId AND ps.serviceId = :serviceId"); $statement->bindParam(':userId', $userId); $statement->bindParam(':serviceId', $serviceId); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by ids in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param $criteria * * @return Collection * @throws QueryExecutionException */ public function getByCriteria($criteria) { $params = []; $where = []; $order = 'ORDER BY s.name ASC'; if (isset($criteria['sort'])) { if ($criteria['sort'] === '') { $order = 'ORDER BY s.position'; } else { $orderColumn = strpos($criteria['sort'], 'name') !== false ? 's.name' : 's.price'; $orderDirection = $criteria['sort'][0] === '-' ? 'DESC' : 'ASC'; $order = "ORDER BY {$orderColumn} {$orderDirection}"; } } if (!empty($criteria['search'])) { $params[':search'] = "%{$criteria['search']}%"; $where[] = 's.name LIKE :search'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 's.id IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['categories'])) { $queryCategories = []; foreach ((array)$criteria['categories'] as $index => $value) { $param = ':category' . $index; $queryCategories[] = $param; $params[$param] = $value; } $where[] = 's.categoryId IN (' . implode(', ', $queryCategories) . ')'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'ps.userId IN (' . implode(', ', $queryProviders) . ')'; } if (!empty($criteria['status'])) { $params[':status'] = $criteria['status']; $where[] = 's.status = :status'; } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT s.id AS service_id, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.price AS service_price, s.status AS service_status, s.categoryId AS service_categoryId, s.maxCapacity AS service_maxCapacity, s.maxExtraPeople AS service_maxExtraPeople, s.minCapacity AS service_minCapacity, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.bringingAnyone AS service_bringingAnyone, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.show AS service_show, s.position AS service_position, s.aggregatedPrice AS service_aggregatedPrice, s.settings AS service_settings, s.translations AS service_translations, s.recurringCycle AS service_recurringCycle, s.recurringSub AS service_recurringSub, s.recurringPayment AS service_recurringPayment, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, s.fullPayment AS service_fullPayment, s.mandatoryExtra AS service_mandatoryExtra, s.minSelectedExtras AS service_minSelectedExtras, s.customPricing AS service_customPricing, s.limitPerCustomer AS service_limitPerCustomer, e.id AS extra_id, e.name AS extra_name, e.price AS extra_price, e.maxQuantity AS extra_maxQuantity, e.duration AS extra_duration, e.position AS extra_position, e.aggregatedPrice AS extra_aggregatedPrice, e.description AS extra_description, e.translations AS extra_translations, g.id AS gallery_id, g.pictureFullPath AS gallery_picture_full, g.pictureThumbPath AS gallery_picture_thumb, g.position AS gallery_position FROM {$this->table} s LEFT JOIN {$this->extrasTable} e ON e.serviceId = s.id LEFT JOIN {$this->providerServicesTable} ps ON ps.serviceId = s.id LEFT JOIN {$this->galleriesTable} g ON g.entityId = s.id AND g.entityType = 'service' WHERE 1 = 1 $where $order" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param int $serviceId * * @return Service * @throws QueryExecutionException */ public function getByIdWithExtras($serviceId) { try { $statement = $this->connection->prepare( "SELECT s.id AS service_id, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.price AS service_price, s.customPricing AS service_customPricing, s.limitPerCustomer AS service_limitPerCustomer, s.status AS service_status, s.categoryId AS service_categoryId, s.maxCapacity AS service_maxCapacity, s.maxExtraPeople AS service_maxExtraPeople, s.minCapacity AS service_minCapacity, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.bringingAnyone AS service_bringingAnyone, s.priority AS service_priority, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.aggregatedPrice AS service_aggregatedPrice, s.settings AS service_settings, s.translations AS service_translations, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, s.fullPayment AS servie_fullPayment, e.id AS extra_id, e.name AS extra_name, e.description AS extra_description, e.price AS extra_price, e.maxQuantity AS extra_maxQuantity, e.duration AS extra_duration, e.aggregatedPrice AS extra_aggregatedPrice, e.position AS extra_position, e.translations AS extra_translations FROM {$this->table} s LEFT JOIN {$this->extrasTable} e ON e.serviceId = s.id WHERE s.id = :serviceId ORDER BY s.id, e.id" ); $statement->bindParam(':serviceId', $serviceId); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($serviceId); } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException */ public function getWithExtras($criteria) { $order = ''; $where = []; if (isset($criteria['sort'])) { if ($criteria['sort'] === '') { $order = 'ORDER BY s.position'; } else { $orderColumn = strpos($criteria['sort'], 'name') !== false ? 's.name' : 's.price'; $orderDirection = $criteria['sort'][0] === '-' ? 'DESC' : 'ASC'; $order = "ORDER BY {$orderColumn} {$orderDirection}"; } } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->query( "SELECT s.id AS service_id, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.price AS service_price, s.customPricing AS service_customPricing, s.status AS service_status, s.categoryId AS service_categoryId, s.maxCapacity AS service_maxCapacity, s.maxExtraPeople AS service_maxExtraPeople, s.minCapacity AS service_minCapacity, s.duration AS service_duration, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.bringingAnyone as service_bringingAnyone, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.position AS service_position, s.show AS service_show, s.aggregatedPrice AS service_aggregatedPrice, s.settings AS service_settings, s.recurringCycle AS service_recurringCycle, s.recurringSub AS service_recurringSub, s.recurringPayment AS service_recurringPayment, s.translations AS service_translations, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, s.fullPayment AS service_fullPayment, s.mandatoryExtra AS service_mandatoryExtra, s.minSelectedExtras AS service_minSelectedExtras, e.id AS extra_id, e.name AS extra_name, e.price AS extra_price, e.maxQuantity AS extra_maxQuantity, e.duration AS extra_duration, e.position AS extra_position, e.aggregatedPrice AS extra_aggregatedPrice, e.description AS extra_description, e.translations AS extra_translations FROM {$this->table} s LEFT JOIN {$this->extrasTable} e ON e.serviceId = s.id {$where} {$order}" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $services */ $services = call_user_func([static::FACTORY, 'createCollection'], $rows); /** @var Service $service */ foreach ($services->getItems() as $service) { if ($service->getSettings() && json_decode($service->getSettings()->getValue(), true) === null) { $service->setSettings(null); } } return $services; } /** * @param $serviceId * @param $status * * @return bool * @throws QueryExecutionException */ public function updateStatusById($serviceId, $status) { $params = [ ':id' => $serviceId, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * Return an array of services with the number of appointments for the given date period. * Keys of the array are Services IDs. * * @param $criteria * * @return array * @throws QueryExecutionException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public function getAllNumberOfAppointments($criteria) { $appointmentTable = AppointmentsTable::getTableName(); $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (isset($criteria['status'])) { $where[] = 's.status = :status'; $params[':status'] = $criteria['status']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT s.id, s.name, COUNT(a.providerId) AS appointments FROM {$this->table} s INNER JOIN {$appointmentTable} a ON s.id = a.serviceId $where GROUP BY serviceId"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * Return an array of services with the number of views for the given date period. * Keys of the array are Services IDs. * * @param $criteria * * @return array * @throws QueryExecutionException */ public function getAllNumberOfViews($criteria) { $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(sv.date, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (isset($criteria['status'])) { $where[] = 's.status = :status'; $params[':status'] = $criteria['status']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT s.id, s.name, SUM(sv.views) AS views FROM {$this->table} s INNER JOIN {$this->serviceViewsTable} sv ON sv.serviceId = s.id $where GROUP BY s.id"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * @param $serviceId * * @return string * @throws QueryExecutionException */ public function addViewStats($serviceId) { $date = DateTimeService::getNowDate(); $params = [ ':serviceId' => $serviceId, ':date' => $date, ':views' => 1 ]; try { // Check if there is already data for this provider for this date $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->serviceViewsTable} AS pv WHERE pv.serviceId = :serviceId AND pv.date = :date" ); $statement->bindParam(':serviceId', $serviceId); $statement->bindParam(':date', $date); $statement->execute(); $count = $statement->fetch()['count']; if (!$count) { $statement = $this->connection->prepare( "INSERT INTO {$this->serviceViewsTable} (`serviceId`, `date`, `views`) VALUES (:serviceId, :date, :views)" ); } else { $statement = $this->connection->prepare( "UPDATE {$this->serviceViewsTable} pv SET pv.views = pv.views + :views WHERE pv.serviceId = :serviceId AND pv.date = :date" ); } $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return true; } /** * @param int $serviceId * * @return mixed * @throws QueryExecutionException */ public function deleteViewStats($serviceId) { $params = [ ':serviceId' => $serviceId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->serviceViewsTable} WHERE serviceId = :serviceId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Bookable/Service/CategoryRepository.php 0000666 00000007175 15165376447 0016467 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Bookable\Service; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Bookable\Service\Category; use AmeliaBooking\Domain\Factory\Bookable\Service\CategoryFactory; use AmeliaBooking\Domain\Repository\Bookable\Service\CategoryRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class CategoryRepository * * @package AmeliaBooking\Infrastructure\Repository\Bookable\Service */ class CategoryRepository extends AbstractRepository implements CategoryRepositoryInterface { const FACTORY = CategoryFactory::class; /** * @param Category $entity * * @return int * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':status' => $data['status'], ':name' => $data['name'], ':position' => $data['position'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} (`status`, `name`, `position`, `translations`) VALUES (:status, :name, :position, :translations)" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Category $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':status' => $data['status'], ':name' => $data['name'], ':position' => $data['position'], ':translations' => $data['translations'], ':id' => $id ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status, `name` = :name, `position` = :position, `translations` = :translations WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getAllIndexedById() { try { $statement = $this->connection->query($this->selectQuery() . ' ORDER BY position ASC'); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $collection = new Collection(); foreach ($rows as $row) { $collection->addItem( call_user_func([static::FACTORY, 'create'], $row), $row['id'] ); } return $collection; } } Repository/Booking/Appointment/CustomerBookingRepository.php 0000666 00000043744 15165376447 0020576 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Appointment; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Appointment\CustomerBooking; use AmeliaBooking\Domain\Factory\Booking\Appointment\CustomerBookingFactory; use AmeliaBooking\Domain\Repository\Booking\Appointment\CustomerBookingRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToEventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; use Exception; /** * Class CustomerBookingRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Appointment */ class CustomerBookingRepository extends AbstractRepository implements CustomerBookingRepositoryInterface { const FACTORY = CustomerBookingFactory::class; /** * @param CustomerBooking $entity * * @return mixed * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':appointmentId' => $data['appointmentId'], ':customerId' => $data['customerId'], ':status' => $data['status'], ':price' => $data['price'], ':persons' => $data['persons'], ':couponId' => !empty($data['coupon']) ? $data['coupon']['id'] : null, ':token' => $data['token'], ':customFields' => $data['customFields'] && json_decode($data['customFields']) !== false ? $data['customFields'] : null, ':info' => $data['info'], ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0, ':utcOffset' => $data['utcOffset'], ':packageCustomerServiceId' => !empty($data['packageCustomerService']['id']) ? $data['packageCustomerService']['id'] : null, ':duration' => !empty($data['duration']) ? $data['duration'] : null, ':created' => !empty($data['created']) ? DateTimeService::getCustomDateTimeInUtc($data['created']) : DateTimeService::getNowDateTimeInUtc(), ':actionsCompleted' => $data['actionsCompleted'] ? 1 : 0, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `appointmentId`, `customerId`, `status`, `price`, `persons`, `couponId`, `token`, `customFields`, `info`, `aggregatedPrice`, `utcOffset`, `packageCustomerServiceId`, `duration`, `created`, `actionsCompleted` ) VALUES ( :appointmentId, :customerId, :status, :price, :persons, :couponId, :token, :customFields, :info, :aggregatedPrice, :utcOffset, :packageCustomerServiceId, :duration, :created, :actionsCompleted )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param CustomerBooking $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':customerId' => $data['customerId'], ':status' => $data['status'], ':duration' => !empty($data['duration']) ? $data['duration'] : null, ':persons' => $data['persons'], ':couponId' => !empty($data['coupon']) ? $data['coupon']['id'] : null, ':customFields' => $data['customFields'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `customerId` = :customerId, `status` = :status, `duration` = :duration, `persons` = :persons, `couponId` = :couponId, `customFields` = :customFields WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param CustomerBooking $entity * * @return mixed * @throws QueryExecutionException */ public function updatePrice($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':price' => $data['price'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `price` = :price WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param int $status * * @return mixed * @throws QueryExecutionException */ public function updateStatusByAppointmentId($id, $status) { $params = [ ':appointmentId' => $id, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE appointmentId = :appointmentId" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param int $status * * @return mixed * @throws QueryExecutionException */ public function updateStatusById($id, $status) { $params = [ ':id' => $id, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * Returns an array of Customers Id's who have at least one booking until passed date * * @param $criteria * * @return array * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getReturningCustomers($criteria) { $appointmentTable = AppointmentsTable::getTableName(); $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d') < :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT customerId, COUNT(*) AS occurrences FROM {$this->table} cb INNER JOIN {$appointmentTable} a ON a.id = cb.appointmentId $where GROUP BY customerId" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (Exception $e) { throw new QueryExecutionException('Unable to return customer bookings from' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * Returns an array of Customers Id's bookings in selected period * * @param $criteria * * @return array * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFilteredDistinctCustomersIds($criteria) { $appointmentTable = AppointmentsTable::getTableName(); $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT DISTINCT cb.customerId FROM {$this->table} cb INNER JOIN {$appointmentTable} a ON a.id = cb.appointmentId $where" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (Exception $e) { throw new QueryExecutionException('Unable to return customer bookings from' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * Returns token for given id * * @param $id * * @return array * @throws QueryExecutionException */ public function getToken($id) { try { $statement = $this->connection->prepare( "SELECT cb.token FROM {$this->table} cb WHERE cb.id = :id" ); $statement->execute([':id' => $id]); $row = $statement->fetch(); } catch (Exception $e) { throw new QueryExecutionException('Unable to return customer booking from' . __CLASS__, $e->getCode(), $e); } return $row; } /** * Returns tokens for given event id * * @param $id * * @return array * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getTokensByEventId($id) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT cb.id, cb.token FROM {$this->table} cb INNER JOIN {$customerBookingsEventsPeriods} cbep ON cbep.customerBookingId = cb.id INNER JOIN {$eventsPeriodsTable} ep ON ep.id = cbep.eventPeriodId WHERE ep.eventId = :id" ); $statement->execute([':id' => $id]); $rows = $statement->fetchAll(); } catch (Exception $e) { throw new QueryExecutionException('Unable to return customer booking from' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param int $customerId * @param string $info * * @return mixed * @throws QueryExecutionException */ public function updateInfoByCustomerId($customerId, $info) { $params = [ ':customerId' => $customerId, ':info' => $info ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `info` = :info WHERE customerId = :customerId" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * * @return mixed * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getById($id) { $params = [ ':id' => $id, ]; $paymentsTable = PaymentsTable::getTableName(); $usersTable = UsersTable::getTableName(); $couponsTable = CouponsTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT cb.id AS booking_id, cb.appointmentId AS booking_appointmentId, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.couponId AS booking_couponId, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.duration AS booking_duration, cb.created AS booking_created, cu.id AS customer_id, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, cu.birthday AS customer_birthday, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.expirationDate AS coupon_expirationDate, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->table} cb INNER JOIN {$usersTable} cu ON cu.id = cb.customerId LEFT JOIN {$couponsTable} c ON c.id = cb.couponId LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id WHERE cb.id = :id" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (Exception $e) { throw new QueryExecutionException('Unable to find booking by id in ' . __CLASS__, $e->getCode(), $e); } $reformattedData = call_user_func([static::FACTORY, 'reformat'], $rows); return !empty($reformattedData[$id]) ? call_user_func([static::FACTORY, 'create'], $reformattedData[$id]) : null; } /** * Returns a collection of bookings where actions on booking are not completed * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException * @throws \Exception */ public function getUncompletedActionsForBookings() { $params = []; $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')"; $pastDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeObjectInUtc()->modify('-1 day')->format('Y-m-d H:i:s') . "', '%Y-%m-%d %H:%i:%s')"; try { $statement = $this->connection->prepare( "SELECT * FROM {$this->table} WHERE actionsCompleted = 0 AND {$currentDateTime} > DATE_ADD(created, INTERVAL 300 SECOND) AND {$pastDateTime} < created" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } } Repository/Booking/Appointment/AppointmentRepository.php 0000666 00000164101 15165376447 0017751 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Appointment; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Entity\Bookable\Service\Service; use AmeliaBooking\Domain\Entity\Booking\Appointment\Appointment; use AmeliaBooking\Domain\Factory\Booking\Appointment\AppointmentFactory; use AmeliaBooking\Domain\Factory\Booking\Appointment\CustomerBookingFactory; use AmeliaBooking\Domain\Repository\Booking\Appointment\AppointmentRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class AppointmentRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Appointment */ class AppointmentRepository extends AbstractRepository implements AppointmentRepositoryInterface { const FACTORY = AppointmentFactory::class; /** @var string */ protected $servicesTable; /** @var string */ protected $bookingsTable; /** @var string */ protected $customerBookingsExtrasTable; /** @var string */ protected $extrasTable; /** @var string */ protected $usersTable; /** @var string */ protected $paymentsTable; /** @var string */ protected $couponsTable; /** @var string */ protected $providersLocationTable; /** @var string */ protected $providerServicesTable; /** @var string */ protected $packagesCustomersTable; /** @var string */ protected $packagesCustomersServicesTable; /** * @param Connection $connection * @param string $table * @param string $servicesTable * @param string $bookingsTable * @param string $customerBookingsExtrasTable * @param string $extrasTable * @param string $usersTable * @param string $paymentsTable * @param string $couponsTable * @param string $providersLocationTable * @param string $providerServicesTable * @param string $packagesCustomersTable * @param string $packagesCustomersServicesTable */ public function __construct( Connection $connection, $table, $servicesTable, $bookingsTable, $customerBookingsExtrasTable, $extrasTable, $usersTable, $paymentsTable, $couponsTable, $providersLocationTable, $providerServicesTable, $packagesCustomersTable, $packagesCustomersServicesTable ) { parent::__construct($connection, $table); $this->servicesTable = $servicesTable; $this->bookingsTable = $bookingsTable; $this->customerBookingsExtrasTable = $customerBookingsExtrasTable; $this->extrasTable = $extrasTable; $this->usersTable = $usersTable; $this->paymentsTable = $paymentsTable; $this->couponsTable = $couponsTable; $this->providersLocationTable = $providersLocationTable; $this->providerServicesTable = $providerServicesTable; $this->packagesCustomersTable = $packagesCustomersTable; $this->packagesCustomersServicesTable = $packagesCustomersServicesTable; } /** * @param int $id * * @return Appointment * @throws QueryExecutionException */ public function getById($id) { try { $statement = $this->connection->prepare( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.googleCalendarEventId AS appointment_google_calendar_event_id, a.googleMeetUrl AS appointment_google_meet_url, a.outlookCalendarEventId AS appointment_outlook_calendar_event_id, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, a.parentId AS appointment_parentId, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.aggregatedPrice AS booking_aggregatedPrice, cb.utcOffset AS booking_utcOffset, cb.packageCustomerServiceId AS booking_packageCustomerServiceId, cb.duration AS booking_duration, cb.created AS booking_created, cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, p.id AS payment_id, p.packageCustomerId AS payment_packageCustomerId, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.parentId AS payment_parentId, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.expirationDate AS coupon_expirationDate, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status, pc.id AS package_customer_id, pc.packageId AS package_customer_packageId, pc.price AS package_customer_price, pc.couponId AS package_customer_couponId FROM {$this->table} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id LEFT JOIN {$this->packagesCustomersServicesTable} pcs ON pcs.id = cb.packageCustomerServiceId LEFT JOIN {$this->packagesCustomersTable} pc ON pcs.packageCustomerId = pc.id LEFT JOIN {$this->paymentsTable} p ON ((p.customerBookingId = cb.id AND cb.packageCustomerServiceId IS NULL) OR (p.packageCustomerId = pc.id AND cb.packageCustomerServiceId IS NOT NULL AND cb.packageCustomerServiceId = pcs.id)) LEFT JOIN {$this->customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$this->couponsTable} c ON (pc.couponId IS NOT NULL AND c.id = pc.couponId) OR (c.id = cb.couponId) WHERE a.id = :appointmentId ORDER BY a.bookingStart" ); $statement->bindParam(':appointmentId', $id); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointment by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($id); } /** * @param int $id * * @return Appointment * @throws QueryExecutionException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public function getByBookingId($id) { try { $statement = $this->connection->prepare( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.googleCalendarEventId AS appointment_google_calendar_event_id, a.googleMeetUrl AS appointment_google_meet_url, a.outlookCalendarEventId AS appointment_outlook_calendar_event_id, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.couponId AS booking_couponId, cb.duration AS booking_duration, cb.created AS booking_created, cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, p.id AS payment_id, p.packageCustomerId AS payment_packageCustomerId, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.parentId AS payment_parentId, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.expirationDate AS coupon_expirationDate, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->table} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id LEFT JOIN {$this->packagesCustomersTable} pc ON pc.customerId = cb.customerId LEFT JOIN {$this->packagesCustomersServicesTable} pcs ON pcs.id = cb.packageCustomerServiceId LEFT JOIN {$this->paymentsTable} p ON ((p.customerBookingId = cb.id AND cb.packageCustomerServiceId IS NULL) OR (p.packageCustomerId = pc.id AND cb.packageCustomerServiceId IS NOT NULL AND cb.packageCustomerServiceId = pcs.id)) LEFT JOIN {$this->customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$this->couponsTable} c ON c.id = cb.couponId WHERE a.id = ( SELECT cb2.appointmentId FROM {$this->bookingsTable} cb2 WHERE cb2.id = :customerBookingId ) ORDER BY a.bookingStart" ); $statement->bindParam(':customerBookingId', $id); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointment by id in ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $appointments */ $appointments = call_user_func([static::FACTORY, 'createCollection'], $rows); return $appointments->length() ? $appointments->getItem($appointments->keys()[0]) : null; } /** * @param int $id * * @return Appointment * @throws QueryExecutionException * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException */ public function getByPaymentId($id) { try { $statement = $this->connection->prepare( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.googleCalendarEventId AS appointment_google_calendar_event_id, a.googleMeetUrl AS appointment_google_meet_url, a.outlookCalendarEventId AS appointment_outlook_calendar_event_id, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cb.couponId AS booking_couponId, cb.duration AS booking_duration, cb.created AS booking_created, cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, p.id AS payment_id, p.packageCustomerId AS payment_packageCustomerId, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.parentId AS payment_parentId, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.expirationDate AS coupon_expirationDate, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->table} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id LEFT JOIN {$this->packagesCustomersTable} pc ON pc.customerId = cb.customerId LEFT JOIN {$this->packagesCustomersServicesTable} pcs ON pcs.id = cb.packageCustomerServiceId LEFT JOIN {$this->paymentsTable} p ON ((p.customerBookingId = cb.id AND cb.packageCustomerServiceId IS NULL) OR (p.packageCustomerId = pc.id AND cb.packageCustomerServiceId IS NOT NULL AND cb.packageCustomerServiceId = pcs.id)) LEFT JOIN {$this->customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id LEFT JOIN {$this->couponsTable} c ON c.id = cb.couponId WHERE a.id IN ( SELECT cb2.appointmentId FROM {$this->paymentsTable} p2 INNER JOIN {$this->bookingsTable} cb2 ON cb2.id = p2.customerBookingId WHERE p2.id = :paymentId ) ORDER BY a.bookingStart" ); $statement->bindParam(':paymentId', $id); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointment by id in ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $appointments */ $appointments = call_user_func([static::FACTORY, 'createCollection'], $rows); return $appointments->length() ? $appointments->getItem($appointments->keys()[0]) : null; } /** * @param Appointment $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':bookingStart' => DateTimeService::getCustomDateTimeInUtc($data['bookingStart']), ':bookingEnd' => DateTimeService::getCustomDateTimeInUtc($data['bookingEnd']), ':notifyParticipants' => $data['notifyParticipants'], ':internalNotes' => $data['internalNotes'] ?: '', ':status' => $data['status'], ':serviceId' => $data['serviceId'], ':providerId' => $data['providerId'], ':locationId' => $data['locationId'], ':parentId' => $data['parentId'], ':lessonSpace' => !empty($data['lessonSpace']) ? $data['lessonSpace'] : null, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `bookingStart`, `bookingEnd`, `notifyParticipants`, `internalNotes`, `status`, `locationId`, `serviceId`, `providerId`, `parentId`, `lessonSpace` ) VALUES ( :bookingStart, :bookingEnd, :notifyParticipants, :internalNotes, :status, :locationId, :serviceId, :providerId, :parentId, :lessonSpace )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Appointment $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':bookingStart' => DateTimeService::getCustomDateTimeInUtc($data['bookingStart']), ':bookingEnd' => DateTimeService::getCustomDateTimeInUtc($data['bookingEnd']), ':notifyParticipants' => $data['notifyParticipants'], ':internalNotes' => $data['internalNotes'], ':status' => $data['status'], ':locationId' => $data['locationId'], ':serviceId' => $data['serviceId'], ':providerId' => $data['providerId'], ':googleCalendarEventId' => $data['googleCalendarEventId'], ':googleMeetUrl' => $data['googleMeetUrl'], ':outlookCalendarEventId' => $data['outlookCalendarEventId'], ':lessonSpace' => $data['lessonSpace'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `bookingStart` = :bookingStart, `bookingEnd` = :bookingEnd, `notifyParticipants` = :notifyParticipants, `internalNotes` = :internalNotes, `status` = :status, `locationId` = :locationId, `serviceId` = :serviceId, `providerId` = :providerId, `googleCalendarEventId` = :googleCalendarEventId, `googleMeetUrl` = :googleMeetUrl, `outlookCalendarEventId` = :outlookCalendarEventId, `lessonSpace` = :lessonSpace WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param int $status * * @return mixed * @throws QueryExecutionException */ public function updateStatusById($id, $status) { $params = [ ':id' => $id, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * Returns array of current appointments where keys are Provider ID's * and array values are Appointments Data (modified by service padding time) * * @return array * @throws QueryExecutionException */ public function getCurrentAppointments() { try { $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTimeInUtc() . "', '%Y-%m-%d %H:%i:%s')"; $statement = $this->connection->query( "SELECT a.bookingStart AS bookingStart, a.bookingEnd AS bookingEnd, a.providerId AS providerId, a.serviceId AS serviceId, s.timeBefore AS timeBefore, s.timeAfter AS timeAfter FROM {$this->table} a INNER JOIN {$this->servicesTable} s ON s.id = a.serviceId WHERE {$currentDateTime} >= a.bookingStart AND {$currentDateTime} <= a.bookingEnd ORDER BY a.bookingStart" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $row['bookingStart'] = DateTimeService::getCustomDateTimeObjectFromUtc($row['bookingStart']) ->modify('-' . ($row['timeBefore'] ?: '0') . ' seconds') ->format('Y-m-d H:i:s'); $row['bookingEnd'] = DateTimeService::getCustomDateTimeObjectFromUtc($row['bookingEnd']) ->modify('+' . ($row['timeAfter'] ?: '0') . ' seconds') ->format('Y-m-d H:i:s'); $result[$row['providerId']] = $row; } return $result; } /** * @param Collection $collection * @param array $providerIds * @param string $startDateTime * @param string $endDateTime * @return void * @throws QueryExecutionException */ public function getFutureAppointments($collection, $providerIds, $startDateTime, $endDateTime) { $params = []; $where = [ "a.status IN ('approved', 'pending')", "cb.status IN ('approved', 'pending')", "a.bookingStart >= STR_TO_DATE('{$startDateTime}', '%Y-%m-%d %H:%i:%s')", ]; if ($endDateTime) { $where[] = "a.bookingStart <= STR_TO_DATE('{$endDateTime}', '%Y-%m-%d %H:%i:%s')"; } if (!empty($providerIds)) { $queryProviders = []; foreach ($providerIds as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'a.providerId IN (' . implode(', ', $queryProviders) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT a.id AS id, a.bookingStart AS bookingStart, a.bookingEnd AS bookingEnd, a.providerId AS providerId, a.serviceId AS serviceId, a.locationId AS locationId, a.status AS status, cb.id AS bookingId, cb.customerId AS customerId, cb.status AS bookingStatus, cb.persons AS persons FROM {$this->table} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id {$where} ORDER BY a.bookingStart " ); $statement->execute($params); while ($row = $statement->fetch()) { $id = (int)$row['id']; $bookingId = (int)$row['bookingId']; if (!$collection->keyExists($id)) { $collection->addItem( AppointmentFactory::create( [ 'id' => $id, 'bookingStart' => DateTimeService::getCustomDateTimeFromUtc( $row['bookingStart'] ), 'bookingEnd' => DateTimeService::getCustomDateTimeFromUtc( $row['bookingEnd'] ), 'providerId' => $row['providerId'], 'serviceId' => $row['serviceId'], 'locationId' => $row['locationId'], 'status' => $row['status'], 'bookings' => [], 'notifyParticipants' => false ] ), $id ); } if (!$collection->getItem($id)->getBookings()->keyExists($bookingId)) { $collection->getItem($id)->getBookings()->addItem( CustomerBookingFactory::create( [ 'id' => $bookingId, 'customerId' => $row['customerId'], 'status' => $row['bookingStatus'], 'persons' => $row['persons'], ] ), $bookingId ); } } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $providerIds * @param string $startDateTime * @param string $endDateTime * @return array * @throws QueryExecutionException */ public function getFutureAppointmentsServicesIds($providerIds, $startDateTime, $endDateTime) { $params = []; $where = []; if ($startDateTime) { $where = ["bookingStart >= STR_TO_DATE('{$startDateTime}', '%Y-%m-%d %H:%i:%s')"]; } if ($endDateTime) { $where = ["bookingStart <= STR_TO_DATE('{$endDateTime}', '%Y-%m-%d %H:%i:%s')"]; } if (!empty($providerIds)) { $queryProviders = []; foreach ($providerIds as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'providerId IN (' . implode(', ', $queryProviders) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT DISTINCT(serviceId) FROM {$this->table} {$where}"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } return $rows ? array_column($rows, 'serviceId') : []; } /** * @param array $serviceIds * @param string $startDateTime * @param string $endDateTime * @return array * @throws QueryExecutionException */ public function getFutureAppointmentsProvidersIds($serviceIds, $startDateTime, $endDateTime) { $params = []; $where = []; if ($startDateTime) { $where = ["bookingStart >= STR_TO_DATE('{$startDateTime}', '%Y-%m-%d %H:%i:%s')"]; } if ($endDateTime) { $where = ["bookingStart <= STR_TO_DATE('{$endDateTime}', '%Y-%m-%d %H:%i:%s')"]; } if (!empty($serviceIds)) { $queryServices = []; foreach ($serviceIds as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'serviceId IN (' . implode(', ', $queryServices) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT DISTINCT(providerId) FROM {$this->table} {$where}"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find appointments in ' . __CLASS__, $e->getCode(), $e); } return $rows ? array_column($rows, 'providerId') : []; } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException */ public function getFiltered($criteria) { try { $params = []; $where = []; if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') >= :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') <= :bookingTo)"; $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') > :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getNowDateTimeInUtc(); } } if (!empty($criteria['ids'])) { $queryAppointments = []; foreach ((array)$criteria['ids'] as $index => $value) { $param = ':id' . $index; $queryAppointments[] = $param; $params[$param] = $value; } $where[] = 'a.id IN (' . implode(', ', $queryAppointments) . ')'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'a.serviceId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'a.providerId IN (' . implode(', ', $queryProviders) . ')'; } if (!empty($criteria['customers'])) { $queryCustomers = []; foreach ((array)$criteria['customers'] as $index => $value) { $param = ':customer' . $index; $queryCustomers[] = $param; $params[$param] = $value; } $where[] = 'cb.customerId IN (' . implode(', ', $queryCustomers) . ')'; } if (isset($criteria['customerId'])) { $where[] = 'cb.customerId = :customerId'; $params[':customerId'] = $criteria['customerId']; } if (isset($criteria['providerId'])) { $where[] = 'a.providerId = :providerId'; $params[':providerId'] = $criteria['providerId']; } if (array_key_exists('status', $criteria)) { $where[] = 'a.status = :status'; $params[':status'] = $criteria['status']; } if (!empty($criteria['statuses'])) { $queryStatuses = []; foreach ($criteria['statuses'] as $index => $value) { $param = ':statuses' . $index; $queryStatuses[] = $param; $params[$param] = $value; } $where[] = 'a.status IN (' . implode(', ', $queryStatuses) . ')'; } if (array_key_exists('bookingStatus', $criteria)) { $where[] = 'cb.status = :bookingStatus'; $params[':bookingStatus'] = $criteria['bookingStatus']; } if (array_key_exists('bookingStatuses', $criteria)) { $queryStatuses = []; foreach ($criteria['bookingStatuses'] as $index => $value) { $param = ':bookingStatuses' . $index; $queryStatuses[] = $param; $params[$param] = $value; } $where[] = 'cb.status IN (' . implode(', ', $queryStatuses) . ')'; } if (!empty($criteria['locations'])) { $queryLocations = []; foreach ((array)$criteria['locations'] as $index => $value) { $param = ':location' . $index; $queryLocations[] = $param; $params[$param] = $value; } $where[] = 'a.locationId IN (' . implode(', ', $queryLocations) . ')'; } if (isset($criteria['bookingId'])) { $where[] = 'cb.id = :bookingId'; $params[':bookingId'] = $criteria['bookingId']; } if (isset($criteria['bookingCouponId'])) { $where[] = 'cb.couponId = :bookingCouponId'; $params[':bookingCouponId'] = $criteria['bookingCouponId']; } if (isset($criteria['parentId'])) { $where[] = 'a.parentId = :parentId'; $params[':parentId'] = $criteria['parentId']; } if (!empty($criteria['packageCustomerServices'])) { $queryLocations = []; foreach ($criteria['packageCustomerServices'] as $index => $value) { $param = ':packageCustomerServices' . $index; $queryLocations[] = $param; $params[$param] = $value; } $where[] = 'cb.packageCustomerServiceId IN (' . implode(', ', $queryLocations) . ')'; } $packagesJoin = ''; if (isset($criteria['packageId'])) { $where[] = 'pc.packageId = :packageId'; $params[':packageId'] = $criteria['packageId']; $packagesJoin = "LEFT JOIN {$this->packagesCustomersServicesTable} pcs ON pcs.id = cb.packageCustomerServiceId LEFT JOIN {$this->packagesCustomersTable} pc ON pcs.packageCustomerId = pc.id"; } elseif (!empty($criteria['packageCustomerId'])) { $where[] = 'pc.id = :packageCustomerId'; $params[':packageCustomerId'] = $criteria['packageCustomerId']; $packagesJoin = "LEFT JOIN {$this->packagesCustomersServicesTable} pcs ON pcs.id = cb.packageCustomerServiceId LEFT JOIN {$this->packagesCustomersTable} pc ON pcs.packageCustomerId = pc.id"; } $servicesFields = ' s.id AS service_id, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.price AS service_price, s.status AS service_status, s.categoryId AS service_categoryId, s.minCapacity AS service_minCapacity, s.maxCapacity AS service_maxCapacity, s.timeAfter AS service_timeAfter, s.timeBefore AS service_timeBefore, s.duration AS service_duration, s.settings AS service_settings, '; $servicesJoin = "INNER JOIN {$this->servicesTable} s ON s.id = a.serviceId"; if (!empty($criteria['skipServices'])) { $servicesFields = ''; $servicesJoin = ''; } $providersFields = ' pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.translations AS provider_translations, pu.timeZone AS provider_timeZone, '; $providersJoin = "INNER JOIN {$this->usersTable} pu ON pu.id = a.providerId"; if (!empty($criteria['skipProviders'])) { $providersFields = ''; $providersJoin = ''; } $customersFields = ' cu.id AS customer_id, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, cu.status AS customer_status, '; $customersJoin = "INNER JOIN {$this->usersTable} cu ON cu.id = cb.customerId"; if (!empty($criteria['skipCustomers'])) { $customersFields = ''; $customersJoin = ''; } $paymentsFields = ' p.id AS payment_id, p.packageCustomerId AS payment_packageCustomerId, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.parentId AS payment_parentId, p.wcOrderId AS payment_wcOrderId, p.created AS payment_created, '; $paymentsJoin = "LEFT JOIN {$this->paymentsTable} p ON p.customerBookingId = cb.id"; if (!empty($criteria['skipPayments'])) { $paymentsFields = ''; $paymentsJoin = ''; } $bookingExtrasFields = ' cbe.id AS bookingExtra_id, cbe.extraId AS bookingExtra_extraId, cbe.customerBookingId AS bookingExtra_customerBookingId, cbe.quantity AS bookingExtra_quantity, cbe.price AS bookingExtra_price, cbe.aggregatedPrice AS bookingExtra_aggregatedPrice, '; $bookingExtrasJoin = "LEFT JOIN {$this->customerBookingsExtrasTable} cbe ON cbe.customerBookingId = cb.id"; if (!empty($criteria['skipExtras'])) { $bookingExtrasFields = ''; $bookingExtrasJoin = ''; } $couponsFields = ' c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.expirationDate AS coupon_expirationDate, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status, '; $couponsJoin = "LEFT JOIN {$this->couponsTable} c ON c.id = cb.couponId"; if (!empty($criteria['skipCoupons'])) { $couponsFields = ''; $couponsJoin = ''; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $statement = $this->connection->prepare( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.googleCalendarEventId AS appointment_google_calendar_event_id, a.googleMeetUrl AS appointment_google_meet_url, a.outlookCalendarEventId AS appointment_outlook_calendar_event_id, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, a.parentId AS appointment_parentId, {$customersFields} {$bookingExtrasFields} {$providersFields} {$servicesFields} {$paymentsFields} {$couponsFields} cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.aggregatedPrice AS booking_aggregatedPrice, cb.packageCustomerServiceId AS booking_packageCustomerServiceId, cb.duration AS booking_duration, cb.created AS booking_created FROM {$this->table} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id {$packagesJoin} {$customersJoin} {$providersJoin} {$servicesJoin} {$paymentsJoin} {$bookingExtrasJoin} {$couponsJoin} {$where} ORDER BY a.bookingStart" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @return Collection $criteria * @throws QueryExecutionException */ public function getAppointmentsWithoutBookings() { try { $statement = $this->connection->query( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.providerId AS appointment_providerId, a.serviceId AS appointment_serviceId, a.status AS appointment_status, a.googleCalendarEventId as appointment_google_calendar_event_id, a.googleMeetUrl AS appointment_google_meet_url, a.outlookCalendarEventId AS appointment_outlook_calendar_event_id, a.notifyParticipants AS appointment_notifyParticipants FROM {$this->table} a WHERE ( SELECT COUNT(*) FROM {$this->bookingsTable} cb WHERE a.id = cb.appointmentId ) = 0" ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find data from ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $criteria * @param null $itemsPerPage * @return Collection * @throws QueryExecutionException */ public function getPeriodAppointments($criteria, $itemsPerPage = null) { $params = []; $where = []; if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') >= :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') <= :bookingTo)"; $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') > :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getNowDateTimeInUtc(); } } $whereOr = []; if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $whereOr[] = 'a.serviceId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $whereOr[] = 'a.providerId IN (' . implode(', ', $queryProviders) . ')'; } $bookingsJoin = "INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id"; if (!empty($criteria['skipBookings'])) { $bookingsJoin = ''; } if (empty($criteria['skipBookings']) && !empty($criteria['customers'])) { $queryCustomers = []; foreach ((array)$criteria['customers'] as $index => $value) { $param = ':customer' . $index; $queryCustomers[] = $param; $params[$param] = $value; } $whereOr[] = 'cb.customerId IN (' . implode(', ', $queryCustomers) . ')'; } if (empty($criteria['skipBookings']) && isset($criteria['customerId'])) { $where[] = 'cb.customerId = :customerId'; $params[':customerId'] = $criteria['customerId']; } if (isset($criteria['providerId'])) { $where[] = 'a.providerId = :providerId'; $params[':providerId'] = $criteria['providerId']; } if (array_key_exists('status', $criteria)) { $where[] = 'a.status = :status'; $params[':status'] = $criteria['status']; } $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); if (!empty($whereOr)) { $where[] = '(' . implode(' OR ', $whereOr) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT a.id AS appointment_id, a.bookingStart AS appointment_bookingStart, a.bookingEnd AS appointment_bookingEnd, a.notifyParticipants AS appointment_notifyParticipants, a.internalNotes AS appointment_internalNotes, a.status AS appointment_status, a.serviceId AS appointment_serviceId, a.providerId AS appointment_providerId, a.locationId AS appointment_locationId, a.googleCalendarEventId AS appointment_google_calendar_event_id, a.googleMeetUrl AS appointment_google_meet_url, a.outlookCalendarEventId AS appointment_outlook_calendar_event_id, a.zoomMeeting AS appointment_zoom_meeting, a.lessonSpace AS appointment_lesson_space, a.parentId AS appointment_parentId FROM {$this->table} a {$bookingsJoin} {$where} GROUP BY a.id ORDER BY a.bookingStart {$limit} " ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $criteria * @return int * @throws QueryExecutionException */ public function getPeriodAppointmentsCount($criteria) { $params = []; $where = []; if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') >= :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') <= :bookingTo)"; $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d %H:%i:%s') > :bookingFrom)"; $params[':bookingFrom'] = DateTimeService::getNowDateTimeInUtc(); } } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'a.serviceId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'a.providerId IN (' . implode(', ', $queryProviders) . ')'; } if (!empty($criteria['customers'])) { $queryCustomers = []; foreach ((array)$criteria['customers'] as $index => $value) { $param = ':customer' . $index; $queryCustomers[] = $param; $params[$param] = $value; } $where[] = 'cb.customerId IN (' . implode(', ', $queryCustomers) . ')'; } if (isset($criteria['customerId'])) { $where[] = 'cb.customerId = :customerId'; $params[':customerId'] = $criteria['customerId']; } if (isset($criteria['providerId'])) { $where[] = 'a.providerId = :providerId'; $params[':providerId'] = $criteria['providerId']; } if (array_key_exists('status', $criteria)) { $where[] = 'a.status = :status'; $params[':status'] = $criteria['status']; } $customerBookingJoin = !empty($criteria['customers']) || isset($criteria['customerId']) ? "INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id" : ''; $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->table} a {$customerBookingJoin} {$where} ORDER BY a.bookingStart " ); $statement->execute($params); $rows = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param Service $service * @param int $customerId * @param \DateTime $appointmentStart * @return Collection * @throws QueryExecutionException */ public function getRelevantAppointmentsCount($service, $customerId, $appointmentStart, $limitPerCustomer, $serviceSpecific) { $params = [ ':customerId' => $customerId ]; $paymentTableJoin = ''; $compareToDate = 'a.bookingStart'; if ($limitPerCustomer['from'] === 'bookingDate') { $appointmentStart = DateTimeService::getCustomDateTimeObject( $appointmentStart->format('Y-m-d H:i') )->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i'); } else { $paymentTableJoin = 'INNER JOIN ' . $this->paymentsTable . ' p ON p.customerBookingId = cb.id'; $appointmentStart = DateTimeService::getNowDateTimeObject()->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i'); $compareToDate = 'p.created'; } $intervalString = "interval " . $limitPerCustomer['period'] . " " . $limitPerCustomer['timeFrame']; $where = "(STR_TO_DATE('" . $appointmentStart . "', '%Y-%m-%d %H:%i:%s') BETWEEN " . "(" . $compareToDate . " - " . $intervalString . " + interval 1 second)" . " AND (". $compareToDate . " + " . $intervalString . " - interval 1 second))"; //+ interval 2 day if ($serviceSpecific) { $where .= " AND a.serviceId = :serviceId"; $params[':serviceId'] = $service->getId()->getValue(); } try { $statement = $this->connection->prepare( "SELECT COUNT(DISTINCT a.id) AS count FROM {$this->table} a INNER JOIN {$this->bookingsTable} cb ON cb.appointmentId = a.id {$paymentTableJoin} WHERE cb.customerId = :customerId AND {$where} AND (a.status = 'approved' OR a.status = 'pending') AND (cb.status = 'approved' OR cb.status = 'pending') " ); $statement->execute($params); $rows = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } } Repository/Booking/Appointment/CustomerBookingExtraRepository.php 0000666 00000006634 15165376447 0021577 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Appointment; use AmeliaBooking\Domain\Entity\Booking\Appointment\CustomerBookingExtra; use AmeliaBooking\Domain\Factory\Booking\Appointment\CustomerBookingExtraFactory; use AmeliaBooking\Domain\Repository\Booking\Appointment\CustomerBookingExtraRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class CustomerBookingExtraRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Appointment */ class CustomerBookingExtraRepository extends AbstractRepository implements CustomerBookingExtraRepositoryInterface { const FACTORY = CustomerBookingExtraFactory::class; /** * @param CustomerBookingExtra $entity * * @return mixed * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':customerBookingId' => $data['customerBookingId'], ':extraId' => $data['extraId'], ':quantity' => $data['quantity'], ':price' => $data['price'], ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `customerBookingId`, `extraId`, `quantity`, `aggregatedPrice`, `price` ) VALUES ( :customerBookingId, :extraId, :quantity, :aggregatedPrice, :price )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param CustomerBookingExtra $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':customerBookingId' => $data['customerBookingId'], ':extraId' => $data['extraId'], ':quantity' => $data['quantity'], ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `customerBookingId` = :customerBookingId, `extraId` = :extraId, `aggregatedPrice` = :aggregatedPrice, `quantity` = :quantity WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Booking/Event/CustomerBookingEventPeriodRepository.php 0000666 00000005441 15165376447 0021516 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Entity\Booking\Event\CustomerBookingEventPeriod; use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class CustomerBookingEventPeriodRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class CustomerBookingEventPeriodRepository extends AbstractRepository implements EventRepositoryInterface { const FACTORY = CustomerBookingEventPeriod::class; /** * @param CustomerBookingEventPeriod $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':eventPeriodId' => $data['eventPeriodId'], ':customerBookingId' => $data['customerBookingId'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `eventPeriodId`, `customerBookingId` ) VALUES ( :eventPeriodId, :customerBookingId )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param CustomerBookingEventPeriod $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':eventPeriodId' => $data['eventPeriodId'], ':customerBookingId' => $data['customerBookingId'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `eventPeriodId` = :eventPeriodId, `customerBookingId` = :customerBookingId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Booking/Event/CustomerBookingEventTicketRepository.php 0000666 00000012011 15165376447 0021506 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Entity\Booking\Event\CustomerBookingEventTicket; use AmeliaBooking\Domain\Factory\Booking\Event\CustomerBookingEventTicketFactory; use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; /** * Class CustomerBookingEventTicketRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class CustomerBookingEventTicketRepository extends AbstractRepository implements EventRepositoryInterface { const FACTORY = CustomerBookingEventTicketFactory::class; /** * @param CustomerBookingEventTicket $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':eventTicketId' => $data['eventTicketId'], ':customerBookingId' => $data['customerBookingId'], ':price' => $data['price'], ':persons' => $data['persons'] ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `eventTicketId`, `customerBookingId`, `price`, `persons` ) VALUES ( :eventTicketId, :customerBookingId, :price, :persons )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Event $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity; $params = [ ':id' => $id, ':eventTicketId' => $data['eventTicketId'], ':customerBookingId' => $data['customerBookingId'], ':price' => $data['price'], ':persons' => $data['persons'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `eventTicketId` = :eventTicketId, `customerBookingId` = :customerBookingId, `price` = :price, `persons` = :persons WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int eventId * * @return bool * @throws QueryExecutionException */ public function deleteByEventId($eventId) { try { $statement = $this->connection->prepare("DELETE FROM {$this->table} WHERE eventId = :eventId"); $statement->bindParam(':eventId', $eventId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $customerBookingId * * @return bool * @throws QueryExecutionException */ public function calculateTotalPrice($customerBookingId) { try { $bookingsTable = CustomerBookingsTable::getTableName(); // CHANGE WHEN ADDING AGGREGATED PRICE PROPERTY TO EVENTS $statement = $this->connection->prepare( "SELECT cbt.customerBookingId, SUM(CASE WHEN cb.aggregatedPrice = 1 THEN cbt.persons*cbt.price ELSE cbt.price END) as totalPrice FROM {$this->table} cbt INNER JOIN {$bookingsTable} cb ON cb.id = cbt.customerBookingId WHERE cbt.customerBookingId = :customerBookingId GROUP BY cbt.customerBookingId " ); $statement->execute([':customerBookingId' => $customerBookingId]); $rows = $statement->fetchAll(); return $rows ? $rows[0]['totalPrice'] : null; } catch (\Exception $e) { throw new QueryExecutionException('Unable to calculate total price in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Booking/Event/EventTicketRepository.php 0000666 00000010172 15165376447 0016461 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Entity\Booking\Event\EventTicket; use AmeliaBooking\Domain\Factory\Booking\Event\EventTicketFactory; use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class EventTicketRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class EventTicketRepository extends AbstractRepository implements EventRepositoryInterface { const FACTORY = EventTicketFactory::class; /** * @param EventTicket $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':eventId' => $data['eventId'], ':name' => $data['name'], ':enabled' => $data['enabled'] ? 1 : 0, ':price' => $data['price'], ':spots' => $data['spots'], ':dateRanges' => $data['dateRanges'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `eventId`, `name`, `enabled`, `price`, `spots`, `dateRanges`, `translations` ) VALUES ( :eventId, :name, :enabled, :price, :spots, :dateRanges, :translations )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param EventTicket $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':eventId' => $data['eventId'], ':name' => $data['name'], ':enabled' => $data['enabled'] ? 1 : 0, ':price' => $data['price'], ':spots' => $data['spots'], ':dateRanges' => $data['dateRanges'], ':translations' => $data['translations'], ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `eventId` = :eventId, `name` = :name, `enabled` = :enabled, `price` = :price, `spots` = :spots, `dateRanges` = :dateRanges, `translations` = :translations WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int eventId * * @return bool * @throws QueryExecutionException */ public function deleteByEventId($eventId) { try { $statement = $this->connection->prepare("DELETE FROM {$this->table} WHERE eventId = :eventId"); $statement->bindParam(':eventId', $eventId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Booking/Event/EventProvidersRepository.php 0000666 00000004124 15165376447 0017213 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Entity\User\Provider; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class EventProvidersRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class EventProvidersRepository extends AbstractRepository { /** * @param Event $event * @param Provider $provider * * @return mixed * @throws QueryExecutionException */ public function add($event, $provider) { $eventData = $event->toArray(); $providerData = $provider->toArray(); $params = [ ':userId' => $providerData['id'], ':eventId' => $eventData['id'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `userId`, `eventId` ) VALUES ( :userId, :eventId )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int eventId * * @return bool * @throws QueryExecutionException */ public function deleteByEventId($eventId) { try { $statement = $this->connection->prepare("DELETE FROM {$this->table} WHERE eventId = :eventId"); $statement->bindParam(':eventId', $eventId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/Booking/Event/EventTagsRepository.php 0000666 00000011041 15165376447 0016130 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Event\EventTag; use AmeliaBooking\Domain\Factory\Booking\Event\EventTagFactory; use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class EventTagsRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class EventTagsRepository extends AbstractRepository implements EventRepositoryInterface { const FACTORY = EventTagFactory::class; /** * @param EventTag $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':eventId' => $data['eventId'], ':name' => $data['name'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `eventId`, `name` ) VALUES ( :eventId, :name )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param EventTag $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':eventId' => $data['eventId'], ':name' => $data['name'] ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `eventId` = :eventId, `name` = :name WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int eventId * * @return bool * @throws QueryExecutionException */ public function deleteByEventId($eventId) { try { $statement = $this->connection->prepare("DELETE FROM {$this->table} WHERE eventId = :eventId"); $statement->bindParam(':eventId', $eventId); return $statement->execute(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $criteria * * @return Collection * @throws \AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException * @throws QueryExecutionException */ public function getAllDistinctByCriteria($criteria) { $params = []; $where = []; if (!empty($criteria['eventIds'])) { $queryIds = []; foreach ((array)$criteria['eventIds'] as $index => $value) { $param = ':id' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = 'eventId IN (' . implode(', ', $queryIds) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT DISTINCT(name) FROM {$this->table} {$where} ORDER BY name" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } } Repository/Booking/Event/EventPeriodsRepository.php 0000666 00000006074 15165376447 0016651 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Entity\Booking\Event\EventPeriod; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Domain\Factory\Booking\Event\EventPeriodFactory; use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; /** * Class EventPeriodsRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class EventPeriodsRepository extends AbstractRepository implements EventRepositoryInterface { const FACTORY = EventPeriodFactory::class; /** * @param EventPeriod $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':eventId' => $data['eventId'], ':periodStart' => DateTimeService::getCustomDateTimeInUtc($data['periodStart']), ':periodEnd' => DateTimeService::getCustomDateTimeInUtc($data['periodEnd']), ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `eventId`, `periodStart`, `periodEnd` ) VALUES ( :eventId, :periodStart, :periodEnd )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param EventPeriod $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':periodStart' => DateTimeService::getCustomDateTimeInUtc($data['periodStart']), ':periodEnd' => DateTimeService::getCustomDateTimeInUtc($data['periodEnd']) ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `periodStart` = :periodStart, `periodEnd` = :periodEnd WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/Booking/Event/EventRepository.php 0000666 00000272636 15165376447 0015334 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\Booking\Event; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Booking\Event\Event; use AmeliaBooking\Domain\Factory\Booking\Appointment\CustomerBookingFactory; use AmeliaBooking\Domain\Factory\Booking\Event\EventFactory; use AmeliaBooking\Domain\Factory\User\ProviderFactory; use AmeliaBooking\Domain\Repository\Booking\Event\EventRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\ValueObjects\String\Status; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsToEventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingToEventsTicketsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsPeriodsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsProvidersTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTagsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\EventsTicketsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToEventsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Gallery\GalleriesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Payment\PaymentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersGoogleCalendarTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\Provider\ProvidersOutlookCalendarTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class EventRepository * * @package AmeliaBooking\Infrastructure\Repository\Booking\Event */ class EventRepository extends AbstractRepository implements EventRepositoryInterface { const FACTORY = EventFactory::class; /** * @param Event $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':bookingOpens' => $data['bookingOpens'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingOpens']) : null, ':bookingCloses' => $data['bookingCloses'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingCloses']) : null, ':bookingOpensRec' => $data['bookingOpensRec'], ':bookingClosesRec' => $data['bookingClosesRec'], ':status' => $data['status'], ':name' => $data['name'], ':description' => $data['description'], ':color' => $data['color'], ':price' => $data['price'], ':recurringCycle' => $data['recurring'] && $data['recurring']['cycle'] ? $data['recurring']['cycle'] : null, ':recurringOrder' => $data['recurring'] && $data['recurring']['order'] ? $data['recurring']['order'] : null, ':recurringInterval' => $data['recurring'] && $data['recurring']['cycleInterval'] ? $data['recurring']['cycleInterval'] : null, ':recurringMonthly' => $data['recurring'] && $data['recurring']['monthlyRepeat'] ? $data['recurring']['monthlyRepeat'] : null, ':monthlyDate' => $data['recurring'] && $data['recurring']['monthDate'] ? DateTimeService::getCustomDateTimeInUtc($data['recurring']['monthDate']) : null, ':monthlyOnRepeat' => $data['recurring'] && $data['recurring']['monthlyOnRepeat'] ? $data['recurring']['monthlyOnRepeat'] : null, ':monthlyOnDay' => $data['recurring'] && $data['recurring']['monthlyOnDay'] ? $data['recurring']['monthlyOnDay'] : null, ':recurringUntil' => $data['recurring'] && $data['recurring']['until'] ? DateTimeService::getCustomDateTimeInUtc($data['recurring']['until']) : null, ':bringingAnyone' => $data['bringingAnyone'] ? 1 : 0, ':bookMultipleTimes' => $data['bookMultipleTimes'] ? 1 : 0, ':maxCapacity' => $data['maxCapacity'], ':maxCustomCapacity' => $data['maxCustomCapacity'], ':maxExtraPeople' => $data['maxExtraPeople'], ':show' => $data['show'] ? 1 : 0, ':notifyParticipants' => $data['notifyParticipants'], ':locationId' => $data['locationId'], ':customLocation' => $data['customLocation'], ':parentId' => $data['parentId'], ':created' => $data['created'], ':settings' => $data['settings'], ':zoomUserId' => $data['zoomUserId'], ':organizerId' => $data['organizerId'], ':translations' => $data['translations'], ':deposit' => $data['deposit'], ':depositPayment' => $data['depositPayment'], ':depositPerPerson' => $data['depositPerPerson'] ? 1 : 0, ':fullPayment' => $data['fullPayment'] ? 1 : 0, ':customPricing' => $data['customPricing'] ? 1 : 0, ':closeAfterMin' => $data['closeAfterMin'], ':closeAfterMinBookings' => $data['closeAfterMinBookings'] ? 1 : 0, ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0 ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `bookingOpens`, `bookingCloses`, `bookingOpensRec`, `bookingClosesRec`, `status`, `name`, `description`, `color`, `price`, `recurringCycle`, `recurringOrder`, `recurringInterval`, `recurringMonthly`, `monthlyDate`, `monthlyOnRepeat`, `monthlyOnDay`, `recurringUntil`, `bringingAnyone`, `bookMultipleTimes`, `maxCapacity`, `maxCustomCapacity`, `maxExtraPeople`, `show`, `notifyParticipants`, `locationId`, `customLocation`, `parentId`, `created`, `settings`, `zoomUserId`, `organizerId`, `translations`, `deposit`, `depositPayment`, `depositPerPerson`, `fullPayment`, `customPricing`, `closeAfterMin`, `closeAfterMinBookings`, `aggregatedPrice` ) VALUES ( :bookingOpens, :bookingCloses, :bookingOpensRec, :bookingClosesRec, :status, :name, :description, :color, :price, :recurringCycle, :recurringOrder, :recurringInterval, :recurringMonthly, :monthlyDate, :monthlyOnRepeat, :monthlyOnDay, :recurringUntil, :bringingAnyone, :bookMultipleTimes, :maxCapacity, :maxCustomCapacity, :maxExtraPeople, :show, :notifyParticipants, :locationId, :customLocation, :parentId, :created, :settings, :zoomUserId, :organizerId, :translations, :deposit, :depositPayment, :depositPerPerson, :fullPayment, :customPricing, :closeAfterMin, :closeAfterMinBookings, :aggregatedPrice )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param Event $entity * * @return mixed * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':id' => $id, ':bookingOpens' => $data['bookingOpens'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingOpens']) : null, ':bookingCloses' => $data['bookingCloses'] ? DateTimeService::getCustomDateTimeInUtc($data['bookingCloses']) : null, ':bookingOpensRec' => $data['bookingOpensRec'], ':bookingClosesRec' => $data['bookingClosesRec'], ':status' => $data['status'], ':name' => $data['name'], ':description' => $data['description'], ':color' => $data['color'], ':price' => $data['price'], ':recurringCycle' => $data['recurring'] ? $data['recurring']['cycle'] : null, ':recurringOrder' => $data['recurring'] ? $data['recurring']['order'] : null, ':recurringInterval' => $data['recurring'] ? $data['recurring']['cycleInterval'] : null, ':monthlyDate' => $data['recurring'] && $data['recurring']['monthDate'] ? DateTimeService::getCustomDateTimeInUtc($data['recurring']['monthDate']) : null, ':recurringUntil' => $data['recurring'] ? DateTimeService::getCustomDateTimeInUtc($data['recurring']['until']) : null, ':bringingAnyone' => $data['bringingAnyone'] ? 1 : 0, ':bookMultipleTimes' => $data['bookMultipleTimes'] ? 1 : 0, ':maxCapacity' => $data['maxCapacity'], ':maxCustomCapacity' => $data['maxCustomCapacity'], ':maxExtraPeople' => $data['maxExtraPeople'], ':show' => $data['show'] ? 1 : 0, ':notifyParticipants' => $data['notifyParticipants'] ? 1 : 0, ':locationId' => $data['locationId'], ':customLocation' => $data['customLocation'], ':parentId' => $data['parentId'], ':settings' => $data['settings'], ':zoomUserId' => $data['zoomUserId'], ':organizerId' => $data['organizerId'], ':translations' => $data['translations'], ':deposit' => $data['deposit'], ':depositPayment' => $data['depositPayment'], ':depositPerPerson' => $data['depositPerPerson'] ? 1 : 0, ':fullPayment' => $data['fullPayment'] ? 1 : 0, ':customPricing' => $data['customPricing'] ? 1 : 0, ':closeAfterMin' => $data['closeAfterMin'], ':closeAfterMinBookings' => $data['closeAfterMinBookings'] ? 1 : 0, ':aggregatedPrice' => $data['aggregatedPrice'] ? 1 : 0 ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `bookingOpens` = :bookingOpens, `bookingCloses` = :bookingCloses, `bookingOpensRec` = :bookingOpensRec, `bookingClosesRec` = :bookingClosesRec, `status` = :status, `name` = :name, `description` = :description, `color` = :color, `price` = :price, `recurringCycle` = :recurringCycle, `recurringOrder` = :recurringOrder, `recurringInterval` = :recurringInterval, `monthlyDate` = :monthlyDate, `recurringUntil` = :recurringUntil, `bringingAnyone` = :bringingAnyone, `bookMultipleTimes` = :bookMultipleTimes, `maxCapacity` = :maxCapacity, `maxCustomCapacity` = :maxCustomCapacity, `maxExtraPeople` = :maxExtraPeople, `show` = :show, `notifyParticipants` = :notifyParticipants, `locationId` = :locationId, `customLocation` = :customLocation, `parentId` = :parentId, `settings` = :settings, `zoomUserId` = :zoomUserId, `organizerId` = :organizerId, `translations` = :translations, `deposit` = :deposit, `depositPayment` = :depositPayment, `depositPerPerson` = :depositPerPerson, `fullPayment` = :fullPayment, `customPricing` = :customPricing, `closeAfterMin` = :closeAfterMin, `closeAfterMinBookings` = :closeAfterMinBookings, `aggregatedPrice` = :aggregatedPrice WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param int $status * * @return mixed * @throws QueryExecutionException */ public function updateStatusById($id, $status) { $params = [ ':id' => $id, ':status' => $status ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `status` = :status WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param int $parentId * * @return mixed * @throws QueryExecutionException */ public function updateParentId($id, $parentId) { $params = [ ':id' => $id, ':parentId' => $parentId, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `parentId` = :parentId WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFiltered($criteria) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $eventsTagsTable = EventsTagsTable::getTableName(); $eventsTicketTable = EventsTicketsTable::getTableName(); $galleriesTable = GalleriesTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $params = []; $where = []; if (!empty($criteria['ids'])) { $queryIds = []; foreach ((array)$criteria['ids'] as $index => $value) { $param = ':id' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = 'e.id IN (' . implode(', ', $queryIds) . ')'; } if (isset($criteria['parentId'])) { $params[':parentId'] = $criteria['parentId']; $params[':originParentId'] = $criteria['parentId']; $where[] = 'e.parentId = :parentId OR e.id = :originParentId'; } if (isset($criteria['search'])) { $params[':search'] = "%{$criteria['search']}%"; $where[] = 'e.name LIKE :search'; } if (isset($criteria['status'])) { $params[':status'] = $criteria['status']; $where[] = 'e.status = :status'; } if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom AND :eventTo)"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') >= :eventTo))"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)"; $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)"; $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc(); } } if (!empty($criteria['locations'])) { $queryLocations = []; foreach ((array)$criteria['locations'] as $index => $value) { $param = ':location' . $index; $queryLocations[] = $param; $params[$param] = $value; } $where[] = 'e.locationId IN (' . implode(', ', $queryLocations) . ')'; } $providerJoin = ''; $providerFields = ''; if (!empty($criteria['providers']) || !empty($criteria['allProviders'])) { $joinType = !empty($criteria['providers']) ? 'INNER' : 'LEFT'; $providerJoin = " LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id $joinType JOIN {$usersTable} pu ON pu.id = epr.userId OR pu.id = e.organizerId"; $queryProviders = []; $providerFields = ' pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.translations AS provider_translations, '; if (!empty($criteria['providers'])) { foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where1 = 'epr.userId IN (' . implode(', ', $queryProviders) . ')'; $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':organizer' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where2 = 'e.organizerId IN (' . implode(', ', $queryProviders) . ')'; $where[] = '(' . $where1 . ' OR ' . $where2 . ')'; } } if (isset($criteria['tag'])) { $params[':tag'] = $criteria['tag']; $tagJoin = "INNER JOIN {$eventsTagsTable} et ON et.eventId = e.id AND et.name = :tag"; } else { $tagJoin = "LEFT JOIN {$eventsTagsTable} et ON et.eventId = e.id"; } if (isset($criteria['bookingCouponId'])) { $where[] = "cb.couponId = {$criteria['bookingCouponId']}"; } $paymentJoin = ''; $paymentFields = ''; if (!empty($criteria['fetchPayments'])) { $paymentFields = ' p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, '; $paymentJoin = "LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id"; } $couponJoin = ''; $couponFields = ''; if (!empty($criteria['fetchCoupons'])) { $couponsTable = CouponsTable::getTableName(); $couponFields = ' c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status, '; $couponJoin = "LEFT JOIN {$couponsTable} c ON c.id = cb.couponId"; } if (!empty($criteria['customerId'])) { $params[':customerId'] = $criteria['customerId']; $where[] = 'cb.customerId = :customerId'; } if (array_key_exists('bookingStatus', $criteria)) { $where[] = 'cb.status = :bookingStatus'; $params[':bookingStatus'] = $criteria['bookingStatus']; } if (array_key_exists('show', $criteria)) { $where[] = 'e.show = :show'; $params[':show'] = $criteria['show']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.bookingOpensRec AS event_bookingOpensRec, e.bookingClosesRec AS event_bookingClosesRec, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringMonthly AS event_recurringMonthly, e.monthlyDate AS event_monthlyDate, e.monthlyOnRepeat AS event_monthlyOnRepeat, e.monthlyOnDay AS event_monthlyOnDay, e.recurringUntil AS event_recurringUntil, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.notifyParticipants AS event_notifyParticipants, e.settings AS event_settings, e.zoomUserId AS event_zoomUserId, e.organizerId AS event_organizerId, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.customPricing AS event_customPricing, e.closeAfterMin AS event_closeAfterMin, e.closeAfterMinBookings AS event_closeAfterMinBookings, e.aggregatedPrice AS event_aggregatedPrice, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleCalendarEventId AS event_googleCalendarEventId, ep.googleMeetUrl AS event_googleMeetUrl, ep.outlookCalendarEventId AS event_outlookCalendarEventId, et.id AS event_tagId, et.name AS event_tagName, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.aggregatedPrice AS booking_aggregatedPrice, cb.couponId AS booking_couponId, cu.id AS customer_id, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, t.id AS ticket_id, t.name AS ticket_name, t.enabled AS ticket_enabled, t.price AS ticket_price, t.spots AS ticket_spots, t.dateRanges AS ticket_dateRanges, t.translations AS ticket_translations, {$couponFields} {$paymentFields} {$providerFields} g.id AS gallery_id, g.pictureFullPath AS gallery_picture_full, g.pictureThumbPath AS gallery_picture_thumb, g.position AS gallery_position FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id LEFT JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id LEFT JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId LEFT JOIN {$usersTable} cu ON cu.id = cb.customerId LEFT JOIN {$galleriesTable} g ON g.entityId = e.id AND g.entityType = 'event' LEFT JOIN {$eventsTicketTable} t ON t.eventId = e.id {$providerJoin} {$couponJoin} {$paymentJoin} {$tagJoin} {$where} ORDER BY ep.periodStart" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getProvidersEvents($criteria) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $params = []; $where = []; if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom AND :eventTo)"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom)"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)"; $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)"; $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc(); } } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'epr.userId IN (' . implode(', ', $queryProviders) . ')'; } if (!empty($criteria['status'])) { $params[':status'] = $criteria['status']; $where[] = 'e.status = :status'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringUntil AS event_recurringUntil, e.recurringMonthly AS event_recurringMonthly, e.monthlyDate AS event_monthlyDate, e.monthlyOnRepeat AS event_monthlyOnRepeat, e.monthlyOnDay AS event_monthlyOnDay, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.notifyParticipants AS event_notifyParticipants, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.customPricing AS event_customPricing, e.aggregatedPrice AS event_aggregatedPrice, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.translations AS provider_translations FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id INNER JOIN {$usersTable} pu ON pu.id = epr.userId {$where} ORDER BY ep.periodStart" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $criteria * @param int $itemsPerPage * * @return array * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFilteredIds($criteria, $itemsPerPage) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $eventsTagsTable = EventsTagsTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $params = []; $where = []; if (!empty($criteria['search'])) { $where[] = "(e.name LIKE '%" . $criteria['search'] . "%' OR e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%\"description\":{%' OR e.translations LIKE '{\"description\":{%\"name\":{%" . $criteria['search'] . "%' OR (e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%' AND e.translations NOT LIKE '%\"description\":{%'))"; } if (isset($criteria['show'])) { $where[] = 'e.show = 1'; } if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "((DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom1 AND :eventTo1) OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom2 AND :eventTo2))"; $params[':eventFrom1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo1'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); $params[':eventFrom2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo2'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') >= :eventTo))"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)"; $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)"; $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc(); } } $tagJoin = ''; if (isset($criteria['tag'])) { $params[':tag'] = $criteria['tag']; $tagJoin = "INNER JOIN {$eventsTagsTable} et ON et.eventId = e.id AND et.name = :tag"; } if (!empty($criteria['id'])) { if ($criteria['recurring']) { $params[':id1'] = (int)$criteria['id']; $params[':id2'] = (int)$criteria['id']; $params[':id3'] = (int)$criteria['id']; $params[':id4'] = (int)$criteria['id']; $where[] = "((e.id = :id1 AND e.parentId IS NULL) OR (e.parentId IN (SELECT parentId FROM {$this->table} WHERE parentId = :id2)) OR (e.id >= :id3 AND e.parentId IN (SELECT parentId FROM {$this->table} WHERE id = :id4)))"; } else { $params[':id'] = (int)$criteria['id']; $where[] = 'e.id = :id'; } } $customerJoin = ''; if (!empty($criteria['customerId'])) { $customerJoin = " LEFT JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id LEFT JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId"; $params[':customerId'] = $criteria['customerId']; $where[] = 'cb.customerId = :customerId'; } if (!empty($criteria['locationId'])) { $params[':locationId'] = $criteria['locationId']; $where[] = 'e.locationId = :locationId'; } $providerJoin = ''; if (!empty($criteria['providers'])) { $providerJoin = " LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id INNER JOIN {$usersTable} pu ON pu.id = epr.userId OR pu.id = e.organizerId"; $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where1 = 'epr.userId IN (' . implode(', ', $queryProviders) . ')'; $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':organizer' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where2 = 'e.organizerId IN (' . implode(', ', $queryProviders) . ')'; $where[] = '(' . $where1 . ' OR ' . $where2 . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); try { $statement = $this->connection->prepare( "SELECT e.id FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id {$tagJoin} {$providerJoin} {$customerJoin} {$where} GROUP BY e.id ORDER BY ep.periodStart, e.id {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param array $criteria * * @return int * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFilteredIdsCount($criteria) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $eventsTagsTable = EventsTagsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $params = []; $where = []; if (!empty($criteria['search'])) { $where[] = "(e.name LIKE '%" . $criteria['search'] . "%' OR e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%\"description\":{%' OR e.translations LIKE '{\"description\":{%\"name\":{%" . $criteria['search'] . "%' OR (e.translations LIKE '{\"name\":{%" . $criteria['search'] . "%' AND e.translations NOT LIKE '%\"description\":{%'))"; } if (isset($criteria['show'])) { $where[] = 'e.show = 1'; } if (!empty($criteria['dates'])) { if (isset($criteria['dates'][0], $criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') BETWEEN :eventFrom AND :eventTo)"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } elseif (isset($criteria['dates'][0])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') >= :eventFrom OR (DATE_FORMAT(ep.periodEnd, '%Y-%m-%d %H:%i:%s') >= :eventTo))"; $params[':eventFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); } elseif (isset($criteria['dates'][1])) { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') <= :eventTo)"; $params[':eventTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } else { $where[] = "(DATE_FORMAT(ep.periodStart, '%Y-%m-%d %H:%i:%s') > :eventFrom)"; $params[':eventFrom'] = DateTimeService::getNowDateTimeInUtc(); } } if (!empty($criteria['locationId'])) { $params[':locationId'] = $criteria['locationId']; $where[] = 'e.locationId = :locationId'; } $tagJoin = ''; if (isset($criteria['tag'])) { $params[':tag'] = $criteria['tag']; $tagJoin = "INNER JOIN {$eventsTagsTable} et ON et.eventId = e.id AND et.name = :tag"; } if (!empty($criteria['id'])) { if ($criteria['recurring']) { $params[':id1'] = (int)$criteria['id']; $params[':id2'] = (int)$criteria['id']; $params[':id3'] = (int)$criteria['id']; $params[':id4'] = (int)$criteria['id']; $where[] = "((e.id = :id1 AND e.parentId IS NULL) OR (e.parentId IN (SELECT parentId FROM {$this->table} WHERE parentId = :id2)) OR (e.id >= :id3 AND e.parentId IN (SELECT parentId FROM {$this->table} WHERE id = :id4)))"; } else { $params[':id'] = (int)$criteria['id']; $where[] = 'e.id = :id'; } } $providerJoin = ''; if (!empty($criteria['providers'])) { $providerJoin = " LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id INNER JOIN {$usersTable} pu ON pu.id = epr.userId OR pu.id = e.organizerId"; $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where1 = 'epr.userId IN (' . implode(', ', $queryProviders) . ')'; $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':organizer' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where2 = 'e.organizerId IN (' . implode(', ', $queryProviders) . ')'; $where[] = '(' . $where1 . ' OR ' . $where2 . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT e.id FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id {$tagJoin} {$providerJoin} {$where} GROUP BY e.id ORDER BY ep.periodStart" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return sizeOf($rows); } /** * @param int $id * * @return Event * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getById($id) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $eventsTagsTable = EventsTagsTable::getTableName(); $eventsTicketTable = EventsTicketsTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); $paymentsTable = PaymentsTable::getTableName(); $usersTable = UsersTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $galleriesTable = GalleriesTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $couponsTable = CouponsTable::getTableName(); try { $statement = $this->connection->prepare( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.bookingOpensRec AS event_bookingOpensRec, e.bookingClosesRec AS event_bookingClosesRec, e.ticketRangeRec AS event_ticketRangeRec, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringMonthly AS event_recurringMonthly, e.monthlyDate AS event_monthlyDate, e.monthlyOnRepeat AS event_monthlyOnRepeat, e.monthlyOnDay AS event_monthlyOnDay, e.recurringUntil AS event_recurringUntil, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.notifyParticipants AS event_notifyParticipants, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.settings AS event_settings, e.zoomUserId AS event_zoomUserId, e.organizerId AS event_organizerId, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.customPricing AS event_customPricing, e.aggregatedPrice AS event_aggregatedPrice, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleCalendarEventId AS event_googleCalendarEventId, ep.googleMeetUrl AS event_googleMeetUrl, ep.outlookCalendarEventId AS event_outlookCalendarEventId, et.id AS event_tagId, et.name AS event_tagName, cb.id AS booking_id, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.aggregatedPrice AS booking_aggregatedPrice, cb.token AS booking_token, cb.utcOffset AS booking_utcOffset, cu.id AS customer_id, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, cu.birthday AS customer_birthday, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.translations AS provider_translations, pu.timeZone AS provider_timeZone, g.id AS gallery_id, g.pictureFullPath AS gallery_picture_full, g.pictureThumbPath AS gallery_picture_thumb, g.position AS gallery_position, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status, t.id AS ticket_id, t.name AS ticket_name, t.enabled AS ticket_enabled, t.price AS ticket_price, t.spots AS ticket_spots, t.dateRanges AS ticket_dateRanges, t.translations AS ticket_translations FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id LEFT JOIN {$eventsTagsTable} et ON et.eventId = e.id LEFT JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id LEFT JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId LEFT JOIN {$usersTable} cu ON cu.id = cb.customerId LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$usersTable} pu ON pu.id = epr.userId LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$galleriesTable} g ON g.entityId = e.id AND g.entityType = 'event' LEFT JOIN {$couponsTable} c ON c.id = cb.couponId LEFT JOIN {$eventsTicketTable} t ON t.eventId = e.id WHERE e.id = :eventId" ); $statement->bindParam(':eventId', $id); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows)->getItem($id); } /** * @param int $id * * @return mixed * @throws QueryExecutionException */ public function isRecurring($id) { try { $statement = $this->connection->prepare( "SELECT e.recurringOrder AS event_recurringOrder, e.parentId AS event_parentId FROM {$this->table} e WHERE e.id = :eventId" ); $statement->bindParam(':eventId', $id); $statement->execute(); return $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e); } } /** * @param int $id * @param int $parentId * * @return mixed * @throws QueryExecutionException */ public function getRecurringIds($id, $parentId) { $whereParent = empty($parentId) ? '' : ' OR e.parentId = :parentId'; try { $statement = $this->connection->prepare( "SELECT e.id AS eventId FROM {$this->table} e WHERE e.parentId = :eventId" . $whereParent ); $statement->bindParam(':eventId', $id); if ($parentId) { $statement->bindParam(':parentId', $parentId); } $statement->execute(); $events = $statement->fetchAll(); return array_column($events, 'eventId'); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e); } } /** * @param array $ids * * @return Event * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByBookingIds($ids) { $paymentsTable = PaymentsTable::getTableName(); $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $eventsTagsTable = EventsTagsTable::getTableName(); $providersGoogleCalendarTable = ProvidersGoogleCalendarTable::getTableName(); $usersTable = UsersTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $couponsTable = CouponsTable::getTableName(); $providersOutlookCalendarTable = ProvidersOutlookCalendarTable::getTableName(); $params = []; $where = []; foreach ($ids as $key => $id) { $params[":customerBookingId$key"] = $id; $where[] = "cb.id = :customerBookingId$key"; } $where = $where ? 'WHERE ' . implode(' OR ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringUntil AS event_recurringUntil, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.notifyParticipants AS event_notifyParticipants, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.settings AS event_settings, e.zoomUserId AS event_zoomUserId, e.organizerId AS event_organizerId, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.customPricing AS event_customPricing, e.aggregatedPrice AS event_aggregatedPrice, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleCalendarEventId AS event_googleCalendarEventId, ep.googleMeetUrl AS event_googleMeetUrl, ep.outlookCalendarEventId AS event_outlookCalendarEventId, et.id AS event_tagId, et.name AS event_tagName, cb.id AS booking_id, cb.appointmentId AS booking_appointmentId, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.persons AS booking_couponId, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, cu.id AS customer_id, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, cu.birthday AS customer_birthday, p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.translations AS provider_translations, gd.id AS google_calendar_id, gd.token AS google_calendar_token, gd.calendarId AS google_calendar_calendar_id, od.id AS outlook_calendar_id, od.token AS outlook_calendar_token, od.calendarId AS outlook_calendar_calendar_id, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id INNER JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId INNER JOIN {$usersTable} cu ON cu.id = cb.customerId LEFT JOIN {$couponsTable} c ON c.id = cb.couponId LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$usersTable} pu ON pu.id = epr.userId LEFT JOIN {$providersGoogleCalendarTable} gd ON gd.userId = pu.id LEFT JOIN {$providersOutlookCalendarTable} od ON od.userId = pu.id LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id LEFT JOIN {$eventsTagsTable} et ON et.eventId = e.id {$where}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param $criteria * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getWithCoupons($criteria) { $couponToEventsTable = CouponsToEventsTable::getTableName(); $couponsTable = CouponsTable::getTableName(); $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $eventsTicketTable = EventsTicketsTable::getTableName(); $params = []; $where = []; foreach ((array)$criteria as $index => $value) { $params[':event' . $index] = $value['eventId']; if ($value['couponId']) { $params[':coupon' . $index] = $value['couponId']; $params[':couponStatus' . $index] = Status::VISIBLE; } $where[] = "(e.id = :event$index" . ($value['couponId'] ? " AND c.id = :coupon$index AND c.status = :couponStatus$index" : '') . ')'; } $where = $where ? 'WHERE ' . implode(' OR ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringUntil AS event_recurringUntil, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.notifyParticipants AS event_notifyParticipants, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.customPricing AS event_customPricing, e.aggregatedPrice AS event_aggregatedPrice, pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.translations AS provider_translations, t.id AS ticket_id, t.name AS ticket_name, t.enabled AS ticket_enabled, t.price AS ticket_price, t.spots AS ticket_spots, t.dateRanges AS ticket_dateRanges, t.translations AS ticket_translations, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->table} e LEFT JOIN {$couponToEventsTable} ce ON ce.eventId = e.id LEFT JOIN {$couponsTable} c ON c.id = ce.couponId LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$usersTable} pu ON pu.id = epr.userId LEFT JOIN {$eventsTicketTable} t ON t.eventId = e.id {$where}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param int $bookingId * @param array $criteria * * @return Event * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByBookingId($bookingId, $criteria = []) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $fields = ''; $joins = ''; if (!empty($criteria['fetchEventsCoupons'])) { $couponsTable = CouponsTable::getTableName(); $fields .= ' ec.id AS coupon_id, ec.code AS coupon_code, ec.discount AS coupon_discount, ec.deduction AS coupon_deduction, ec.limit AS coupon_limit, ec.customerLimit AS coupon_customerLimit, ec.status AS coupon_status, '; $joins .= " LEFT JOIN {$couponsTable} ec ON ec.id = cb.couponId "; } if (!empty($criteria['fetchEventsTickets'])) { $ticketsTable = EventsTicketsTable::getTableName(); $fields .= ' eti.id AS ticket_id, eti.name AS ticket_name, eti.enabled AS ticket_enabled, eti.price AS ticket_price, eti.spots AS ticket_spots, eti.dateRanges AS ticket_dateRanges, eti.translations AS ticket_translations, '; $joins .= " LEFT JOIN {$ticketsTable} eti ON eti.eventId = e.id "; } if (!empty($criteria['fetchEventsTags'])) { $tagsTable = EventsTagsTable::getTableName(); $fields .= ' eta.id AS event_tagId, eta.name AS event_tagName, '; $joins .= " LEFT JOIN {$tagsTable} eta ON eta.eventId = e.id "; } if (!empty($criteria['fetchEventsImages'])) { $galleriesTable = GalleriesTable::getTableName(); $fields .= ' eg.id AS gallery_id, eg.pictureFullPath AS gallery_picture_full, eg.pictureThumbPath AS gallery_picture_thumb, eg.position AS gallery_position, '; $joins .= " LEFT JOIN {$galleriesTable} eg ON eg.entityId = e.id AND eg.entityType = 'event' "; } if (!empty($criteria['fetchEventsProviders'])) { $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $joins .= " LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$usersTable} pu ON pu.id = epr.userId "; $fields .= ' pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.translations AS provider_translations, pu.timeZone AS provider_timeZone, '; } $fields .= " e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringUntil AS event_recurringUntil, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.notifyParticipants AS event_notifyParticipants, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.customPricing AS event_customPricing, e.parentId AS event_parentId, e.created AS event_created, e.settings AS event_settings, e.zoomUserId AS event_zoomUserId, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.organizerId AS event_organizerId, e.aggregatedPrice AS event_aggregatedPrice, ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleCalendarEventId AS event_googleCalendarEventId, ep.googleMeetUrl AS event_googleMeetUrl, ep.outlookCalendarEventId AS event_outlookCalendarEventId "; $params = [ ':customerBookingId' => $bookingId, ]; try { $statement = $this->connection->prepare( "SELECT {$fields} FROM {$customerBookingsEventsPeriods} cbe INNER JOIN {$eventsPeriodsTable} ep ON ep.id = cbe.eventPeriodId INNER JOIN {$this->table} e ON e.id = ep.eventId {$joins} WHERE cbe.customerBookingId = :customerBookingId" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by booking id in ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $events */ $events = call_user_func([static::FACTORY, 'createCollection'], $rows); return $events->length() ? $events->getItem($events->keys()[0]) : null; } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getByCriteria($criteria = []) { $params = []; $where = []; $fields = ''; $joins = ''; $orderBy = ''; if (!empty($criteria['fetchBookings']) || !empty($criteria['fetchEventsPeriods'])) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $fields .= ' ep.id AS event_periodId, ep.periodStart AS event_periodStart, ep.periodEnd AS event_periodEnd, ep.zoomMeeting AS event_periodZoomMeeting, ep.lessonSpace AS event_periodLessonSpace, ep.googleCalendarEventId AS event_googleCalendarEventId, ep.googleMeetUrl AS event_googleMeetUrl, ep.outlookCalendarEventId AS event_outlookCalendarEventId, '; $joins .= " INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id "; $orderBy = 'ORDER BY ep.periodStart'; } if (!empty($criteria['fetchBookings'])) { $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); $fields .= ' cb.id AS booking_id, cb.appointmentId AS booking_appointmentId, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.couponId AS booking_couponId, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice, '; if (!empty($criteria['fetchApprovedBookings'])) { $where[] = "cb.status = 'approved'"; } if (!empty($criteria['customerBookingId'])) { $params[':customerBookingId'] = $criteria['customerBookingId']; $where[] = 'cb.id = :customerBookingId'; } $joins .= " INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id INNER JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId "; if (!empty($criteria['fetchBookingsPayments'])) { $paymentsTable = PaymentsTable::getTableName(); $fields .= ' p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, '; $joins .= " LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id "; } if (!empty($criteria['fetchBookingsCoupons'])) { $couponsTable = CouponsTable::getTableName(); $fields .= ' c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status, '; $joins .= " LEFT JOIN {$couponsTable} c ON c.id = cb.couponId "; } if (!empty($criteria['fetchBookingsUsers'])) { $usersTable = UsersTable::getTableName(); $fields .= ' cu.id AS customer_id, cu.type AS customer_type, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, cu.birthday AS customer_birthday, '; $joins .= " INNER JOIN {$usersTable} cu ON cu.id = cb.customerId "; } if (!empty($criteria['fetchBookingsTickets'])) { $bookingsTicketsTable = CustomerBookingToEventsTicketsTable::getTableName(); $fields .= ' cbt.id AS booking_ticket_id, cbt.eventTicketId AS booking_ticket_eventTicketId, cbt.price AS booking_ticket_price, cbt.persons AS booking_ticket_persons, '; $joins .= " LEFT JOIN {$bookingsTicketsTable} cbt ON cbt.customerBookingId = cb.id "; } } if (!empty($criteria['fetchEventsCoupons'])) { $couponsTable = CouponsTable::getTableName(); $fields .= ' ec.id AS coupon_id, ec.code AS coupon_code, ec.discount AS coupon_discount, ec.deduction AS coupon_deduction, ec.limit AS coupon_limit, ec.customerLimit AS coupon_customerLimit, ec.status AS coupon_status, '; $joins .= " LEFT JOIN {$couponsTable} ec ON ec.id = cb.couponId "; } if (!empty($criteria['fetchEventsTickets'])) { $ticketsTable = EventsTicketsTable::getTableName(); $fields .= ' eti.id AS ticket_id, eti.name AS ticket_name, eti.enabled AS ticket_enabled, eti.price AS ticket_price, eti.spots AS ticket_spots, eti.dateRanges AS ticket_dateRanges, eti.translations AS ticket_translations, '; $joins .= " LEFT JOIN {$ticketsTable} eti ON eti.eventId = e.id "; } if (!empty($criteria['fetchEventsTags'])) { $tagsTable = EventsTagsTable::getTableName(); $fields .= ' eta.id AS event_tagId, eta.name AS event_tagName, '; $joins .= " LEFT JOIN {$tagsTable} eta ON eta.eventId = e.id "; } if (!empty($criteria['fetchEventsImages'])) { $galleriesTable = GalleriesTable::getTableName(); $fields .= ' eg.id AS gallery_id, eg.pictureFullPath AS gallery_picture_full, eg.pictureThumbPath AS gallery_picture_thumb, eg.position AS gallery_position, '; $joins .= " LEFT JOIN {$galleriesTable} eg ON eg.entityId = e.id AND eg.entityType = 'event' "; } if (!empty($criteria['fetchEventsProviders'])) { $eventsProvidersTable = EventsProvidersTable::getTableName(); $usersTable = UsersTable::getTableName(); $joins .= " LEFT JOIN {$eventsProvidersTable} epr ON epr.eventId = e.id LEFT JOIN {$usersTable} pu ON pu.id = epr.userId "; $fields .= ' pu.id AS provider_id, pu.firstName AS provider_firstName, pu.lastName AS provider_lastName, pu.email AS provider_email, pu.note AS provider_note, pu.description AS provider_description, pu.phone AS provider_phone, pu.gender AS provider_gender, pu.pictureFullPath AS provider_pictureFullPath, pu.pictureThumbPath AS provider_pictureThumbPath, pu.translations AS provider_translations, pu.timeZone AS provider_timeZone, '; } $fields .= " e.id AS event_id, e.name AS event_name, e.status AS event_status, e.bookingOpens AS event_bookingOpens, e.bookingCloses AS event_bookingCloses, e.bookingOpensRec AS event_bookingOpensRec, e.bookingClosesRec AS event_bookingClosesRec, e.ticketRangeRec AS event_ticketRangeRec, e.recurringCycle AS event_recurringCycle, e.recurringOrder AS event_recurringOrder, e.recurringInterval AS event_recurringInterval, e.recurringMonthly AS event_recurringMonthly, e.monthlyDate AS event_monthlyDate, e.monthlyOnRepeat AS event_monthlyOnRepeat, e.monthlyOnDay AS event_monthlyOnDay, e.recurringUntil AS event_recurringUntil, e.bringingAnyone AS event_bringingAnyone, e.bookMultipleTimes AS event_bookMultipleTimes, e.maxCapacity AS event_maxCapacity, e.maxCustomCapacity AS event_maxCustomCapacity, e.maxExtraPeople AS event_maxExtraPeople, e.price AS event_price, e.description AS event_description, e.color AS event_color, e.show AS event_show, e.notifyParticipants AS event_notifyParticipants, e.locationId AS event_locationId, e.customLocation AS event_customLocation, e.parentId AS event_parentId, e.created AS event_created, e.settings AS event_settings, e.zoomUserId AS event_zoomUserId, e.organizerId AS event_organizerId, e.translations AS event_translations, e.deposit AS event_deposit, e.depositPayment AS event_depositPayment, e.depositPerPerson AS event_depositPerPerson, e.fullPayment AS event_fullPayment, e.customPricing AS event_customPricing, e.closeAfterMin AS event_closeAfterMin, e.closeAfterMinBookings AS event_closeAfterMinBookings, e.aggregatedPrice AS event_aggregatedPrice "; if (!empty($criteria['ids'])) { $queryIds = []; foreach ($criteria['ids'] as $index => $value) { $param = ':id' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = 'e.id IN (' . implode(', ', $queryIds) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT {$fields} FROM {$this->table} e {$joins} {$where} {$orderBy}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $rows); } /** * @param array $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getBookingsByCriteria($criteria = []) { $params = []; $where = []; $fields = ''; $joins = ''; $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); if (!empty($criteria['fetchApprovedBookings'])) { $where[] = "cb.status = 'approved'"; } if (!empty($criteria['customerBookingId'])) { $params[':customerBookingId'] = $criteria['customerBookingId']; $where[] = 'cb.id = :customerBookingId'; } if (!empty($criteria['fetchBookingsPayments'])) { $paymentsTable = PaymentsTable::getTableName(); $fields .= ' p.id AS payment_id, p.amount AS payment_amount, p.dateTime AS payment_dateTime, p.status AS payment_status, p.gateway AS payment_gateway, p.gatewayTitle AS payment_gatewayTitle, p.transactionId AS payment_transactionId, p.data AS payment_data, p.wcOrderId AS payment_wcOrderId, '; $joins .= " LEFT JOIN {$paymentsTable} p ON p.customerBookingId = cb.id "; } if (!empty($criteria['fetchBookingsCoupons'])) { $couponsTable = CouponsTable::getTableName(); $fields .= ' c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status, '; $joins .= " LEFT JOIN {$couponsTable} c ON c.id = cb.couponId "; } if (!empty($criteria['fetchBookingsUsers'])) { $usersTable = UsersTable::getTableName(); $fields .= ' cu.id AS customer_id, cu.type AS customer_type, cu.firstName AS customer_firstName, cu.lastName AS customer_lastName, cu.email AS customer_email, cu.note AS customer_note, cu.phone AS customer_phone, cu.gender AS customer_gender, cu.birthday AS customer_birthday, '; $joins .= " INNER JOIN {$usersTable} cu ON cu.id = cb.customerId "; } if (!empty($criteria['fetchBookingsTickets'])) { $bookingsTicketsTable = CustomerBookingToEventsTicketsTable::getTableName(); $fields .= ' cbt.id AS booking_ticket_id, cbt.eventTicketId AS booking_ticket_eventTicketId, cbt.price AS booking_ticket_price, cbt.persons AS booking_ticket_persons, '; $joins .= " LEFT JOIN {$bookingsTicketsTable} cbt ON cbt.customerBookingId = cb.id "; } $fields .= ' ep.eventId AS eventId, cb.id AS booking_id, cb.appointmentId AS booking_appointmentId, cb.customerId AS booking_customerId, cb.status AS booking_status, cb.price AS booking_price, cb.persons AS booking_persons, cb.couponId AS booking_couponId, cb.customFields AS booking_customFields, cb.info AS booking_info, cb.utcOffset AS booking_utcOffset, cb.aggregatedPrice AS booking_aggregatedPrice '; if (!empty($criteria['ids'])) { $queryIds = []; foreach ($criteria['ids'] as $index => $value) { $param = ':id' . $index; $queryIds[] = $param; $params[$param] = $value; } $where[] = 'ep.eventId IN (' . implode(', ', $queryIds) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT {$fields} FROM {$eventsPeriodsTable} ep INNER JOIN {$customerBookingsEventsPeriods} cbe ON cbe.eventPeriodId = ep.id INNER JOIN {$customerBookingsTable} cb ON cb.id = cbe.customerBookingId {$joins} {$where} ORDER BY cb.id" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find event by id in ' . __CLASS__, $e->getCode(), $e); } $reformattedData = []; foreach ($rows as $row) { if (empty($reformattedData[$row['eventId']])) { $reformattedData[$row['eventId']] = []; } $reformattedData[$row['eventId']][] = $row; } $result = new Collection(); foreach ($reformattedData as $eventId => $bookingsData) { $reformattedBookingsData = CustomerBookingFactory::reformat($bookingsData); $eventBookings = new Collection(); foreach ($reformattedBookingsData as $bookingId => $data) { $eventBookings->addItem(CustomerBookingFactory::create($data), $bookingId); } $result->addItem($eventBookings, $eventId); } return $result; } /** * @param Event $event * @param array $booking * @param array $limitPerCustomer * @return int * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getRelevantBookingsCount($event, $booking, $limitPerCustomer) { $eventsPeriodsTable = EventsPeriodsTable::getTableName(); $customerBookingsEventsPeriods = CustomerBookingsToEventsPeriodsTable::getTableName(); $customerBookingsTable = CustomerBookingsTable::getTableName(); $params = [ ':customerId' => $booking['customerId'] ]; $paymentTableJoin = ''; $compareToDate = 'ep.periodStart'; if ($limitPerCustomer['from'] === 'bookingDate') { $eventStartDate = $event->getPeriods()->getItems()[0]->getPeriodStart()->getValue()->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i'); } else { $paymentTableJoin = 'INNER JOIN ' . PaymentsTable::getTableName() . ' p ON p.customerBookingId = cb.id'; $eventStartDate = DateTimeService::getNowDateTimeObject()->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i'); $compareToDate = 'p.created'; } $intervalString = "interval " . $limitPerCustomer['period'] . " " . $limitPerCustomer['timeFrame']; $where = "(STR_TO_DATE('". $eventStartDate ."', '%Y-%m-%d %H:%i:%s') BETWEEN " . "(" . $compareToDate . " - " . $intervalString . " + interval 1 second)" . " AND (". $compareToDate . " + " . $intervalString . " - interval 1 second))"; try { $statement = $this->connection->prepare( "SELECT COUNT(DISTINCT cb.id) AS count FROM {$this->table} e INNER JOIN {$eventsPeriodsTable} ep ON ep.eventId = e.id INNER JOIN {$customerBookingsEventsPeriods} cbep ON cbep.eventPeriodId = ep.id INNER JOIN {$customerBookingsTable} cb ON cb.id = cbep.customerBookingId {$paymentTableJoin} WHERE cb.customerId = :customerId AND {$where} AND e.status = 'approved' AND cb.status = 'approved' " ); $statement->execute($params); $rows = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $rows; } } Repository/Cache/CacheRepository.php 0000666 00000007112 15165376447 0013571 0 ustar 00 <?php /** * @copyright © TMS-Plugins. All rights reserved. * @licence See LICENCE.md for license details. */ namespace AmeliaBooking\Infrastructure\Repository\Cache; use AmeliaBooking\Domain\Entity\Cache\Cache; use AmeliaBooking\Domain\Factory\Cache\CacheFactory; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; /** * Class CacheRepository * * @package AmeliaBooking\Infrastructure\Repository\Cache */ class CacheRepository extends AbstractRepository { /** * @param Connection $connection * @param string $table */ public function __construct( Connection $connection, $table ) { parent::__construct($connection, $table); } const FACTORY = CacheFactory::class; /** * @param Cache $entity * * @return bool * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':name' => $data['name'], ':data' => $data['data'], ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `name`, `data` ) VALUES ( :name, :data )" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return $this->connection->lastInsertId(); } /** * @param int $id * @param Cache $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':paymentId' => $data['paymentId'], ':data' => $data['data'], ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `paymentId` = :paymentId, `data` = :data WHERE id = :id" ); $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return true; } /** * @param int $id * @param string $name * * @return Cache * @throws QueryExecutionException */ public function getByIdAndName($id, $name) { try { $statement = $this->connection->prepare( $this->selectQuery() . " WHERE id = :id AND name = :name" ); $params = [ ':id' => $id, ':name' => $name ]; $statement->execute($params); $row = $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } if (!$row) { return null; } return call_user_func([static::FACTORY, 'create'], $row); } } Repository/User/UserRepository.php 0000666 00000035342 15165376447 0013425 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\User; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Entity\User\Admin; use AmeliaBooking\Domain\Entity\User\Customer; use AmeliaBooking\Domain\Entity\User\Manager; use AmeliaBooking\Domain\Entity\User\Provider; use AmeliaBooking\Domain\Factory\User\UserFactory; use AmeliaBooking\Domain\Repository\User\UserRepositoryInterface; use AmeliaBooking\Domain\ValueObjects\Json; use AmeliaBooking\Domain\ValueObjects\String\Password; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Repository\AbstractRepository; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; /** * Class UserRepository * * @package AmeliaBooking\Infrastructure\Repository */ class UserRepository extends AbstractRepository implements UserRepositoryInterface { const FACTORY = UserFactory::class; /** * @param AbstractUser $entity * * @return int * @throws QueryExecutionException */ public function add($entity) { $data = $entity->toArray(); $params = [ ':type' => $data['type'], ':status' => $data['status'] ?: 'visible', ':externalId' => $data['externalId'] ?: null, ':firstName' => $data['firstName'], ':lastName' => $data['lastName'], ':email' => $data['email'], ':note' => isset($data['note']) ? $data['note'] : null, ':description' => isset($data['description']) ? $data['description'] : null, ':phone' => isset($data['phone']) ? $data['phone'] : null, ':gender' => isset($data['gender']) ? $data['gender'] : null, ':birthday' => $data['birthday'] ? $data['birthday']->format('Y-m-d') : null, ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':password' => isset($data['password']) ? $data['password'] : null, ':usedTokens' => isset($data['usedTokens']) ? $data['usedTokens'] : null, ':zoomUserId' => isset($data['zoomUserId']) ? $data['zoomUserId'] : null, ':countryPhoneIso' => isset($data['countryPhoneIso']) ? $data['countryPhoneIso'] : null, ':translations' => isset($data['translations']) ? $data['translations'] : null, ':timeZone' => isset($data['timeZone']) ? $data['timeZone'] : null, ]; try { $statement = $this->connection->prepare( "INSERT INTO {$this->table} ( `type`, `status`, `externalId`, `firstName`, `lastName`, `email`, `note`, `description`, `phone`, `gender`, `birthday`, `pictureFullPath`, `pictureThumbPath`, `zoomUserId`, `countryPhoneIso`, `usedTokens`, `password`, `translations`, `timeZone` ) VALUES ( :type, :status, :externalId, :firstName, :lastName, :email, :note, :description, :phone, :gender, STR_TO_DATE(:birthday, '%Y-%m-%d'), :pictureFullPath, :pictureThumbPath, :zoomUserId, :countryPhoneIso, :usedTokens, :password, :translations, :timeZone )" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } return $this->connection->lastInsertId(); } /** * @param int $id * @param AbstractUser $entity * * @return bool * @throws QueryExecutionException */ public function update($id, $entity) { $data = $entity->toArray(); $params = [ ':externalId' => $data['externalId'] ?: null, ':firstName' => $data['firstName'], ':lastName' => $data['lastName'], ':email' => isset($data['email']) ? $data['email'] : null, ':note' => isset($data['note']) ? $data['note'] : null, ':description' => isset($data['description']) ? $data['description'] : null, ':phone' => isset($data['phone']) ? $data['phone'] : null, ':gender' => isset($data['gender']) ? $data['gender'] : null, ':birthday' => isset($data['birthday']) ? $data['birthday']->format('Y-m-d') : null, ':pictureFullPath' => $data['pictureFullPath'], ':pictureThumbPath' => $data['pictureThumbPath'], ':zoomUserId' => isset($data['zoomUserId']) ? $data['zoomUserId'] : null, ':countryPhoneIso' => isset($data['countryPhoneIso']) ? $data['countryPhoneIso'] : null, ':password' => isset($data['password']) ? $data['password'] : null, ':translations' => isset($data['translations']) ? $data['translations'] : null, ':timeZone' => isset($data['timeZone']) ? $data['timeZone'] : null, ':id' => $id, ]; try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET `externalId` = :externalId, `firstName` = :firstName, `lastName` = :lastName, `email` = :email, `note` = :note, `description` = :description, `phone` = :phone, `gender` = :gender, `birthday` = STR_TO_DATE(:birthday, '%Y-%m-%d'), `zoomUserId` = :zoomUserId, `countryPhoneIso` = :countryPhoneIso, `pictureFullPath` = :pictureFullPath, `pictureThumbPath` = :pictureThumbPath, `password` = IFNULL(:password, `password`), `translations` = :translations, `timeZone` = :timeZone WHERE id = :id" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return $res; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } /** * @param $externalId * * @return Admin|Customer|Manager|Provider|bool * @throws InvalidArgumentException * @throws QueryExecutionException */ public function findByExternalId($externalId) { try { $statement = $this->connection->prepare("SELECT * FROM {$this->table} WHERE externalId = :id"); $statement->bindParam(':id', $externalId); $statement->execute(); $row = $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by external id in ' . __CLASS__, $e->getCode(), $e); } if (!$row) { return false; } return UserFactory::create($row); } /** * @param $type * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getAllByType($type) { $params = [ ':type' => $type, ]; try { $statement = $this->connection->prepare($this->selectQuery() . ' WHERE type = :type'); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * Returns Collection of all customers and other users that have at least one booking * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getAllWithAllowedBooking() { try { $bookingsTable = CustomerBookingsTable::getTableName(); $statement = $this->connection->query( " SELECT u.id AS id, u.firstName AS firstName, u.lastName AS lastName, u.email AS email, u.note AS note, u.description AS description, u.phone AS phone, u.gender AS gender, u.status AS status, u.translations AS translations FROM {$this->table} u LEFT JOIN {$bookingsTable} cb ON cb.customerId = u.id WHERE u.type = 'customer' OR (cb.id IS NOT NULL AND u.type IN ('admin', 'provider', 'manager')) GROUP BY u.id ORDER BY CONCAT(firstName, ' ', lastName) " ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[$row['id']] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * Returns Collection of all customers and other users that have at least one booking * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getAllWithoutBookings() { $bookingsTable = CustomerBookingsTable::getTableName(); try { $statement = $this->connection->query( " SELECT u.id AS id, u.firstName AS firstName, u.lastName AS lastName, u.email AS email, u.note AS note, u.phone AS phone, u.gender AS gender, u.status AS status, u.translations AS translations FROM {$this->table} u LEFT JOIN {$bookingsTable} cb ON cb.customerId = u.id WHERE (u.type = 'customer' OR (cb.id IS NOT NULL AND u.type IN ('admin', 'provider', 'manager'))) AND cb.appointmentId IS NULL AND u.id NOT IN ( SELECT u2.id FROM {$this->table} u2 INNER JOIN {$bookingsTable} cb2 ON cb2.customerId = u2.id WHERE cb2.appointmentId IS NOT NULL ) GROUP BY u.id ORDER BY CONCAT(firstName, ' ', lastName) " ); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $items[$row['id']] = call_user_func([static::FACTORY, 'create'], $row); } return new Collection($items); } /** * @param string $email * @param boolean $setPassword * @param boolean $setUsedTokens * * @return Admin|Customer|Manager|Provider * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getByEmail($email, $setPassword = false, $setUsedTokens = false) { try { $statement = $this->connection->prepare($this->selectQuery() . ' WHERE LOWER(email) = LOWER(:email)'); $statement->execute( array( ':email' => $email ) ); $row = $statement->fetch(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } if (!$row) { return null; } /** @var Admin|Customer|Manager|Provider $user */ $user = UserFactory::create($row); if ($setPassword) { $user->setPassword(Password::createFromHashedPassword($row['password'])); } if ($setUsedTokens) { $user->setUsedTokens(new Json($row['usedTokens'])); } return $user; } /** * @return array * @throws QueryExecutionException */ public function getAllEmailsByType($type) { try { $params[':type'] = $type; $statement = $this->connection->prepare( " SELECT DISTINCT u.email AS email FROM {$this->table} u WHERE u.type = :type " ); $statement->execute($params); $rows = $statement->fetchAll(\PDO::FETCH_COLUMN); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param string $email * @param array $data * * @return bool * @throws QueryExecutionException */ public function updateFieldsByEmail($email, $data) { $fields = []; $params = [':email' => $email]; foreach ($data as $key => $item) { $params[":$key"] = $item; $fields[] = "`$key` = :$key"; } $fields = implode(', ', $fields); try { $statement = $this->connection->prepare( "UPDATE {$this->table} SET {$fields} WHERE email = :email" ); $res = $statement->execute($params); if (!$res) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__); } return true; } catch (\Exception $e) { throw new QueryExecutionException('Unable to save data in ' . __CLASS__, $e->getCode(), $e); } } } Repository/User/ProviderRepository.php 0000666 00000251075 15165376447 0014304 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\User; use AmeliaBooking\Domain\Collection\Collection; use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException; use AmeliaBooking\Domain\Entity\Schedule\Period; use AmeliaBooking\Domain\Entity\Schedule\SpecialDay; use AmeliaBooking\Domain\Entity\Schedule\WeekDay; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Entity\User\Provider; use AmeliaBooking\Domain\Factory\User\ProviderFactory; use AmeliaBooking\Domain\Repository\User\ProviderRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\ValueObjects\String\Status; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Bookable\ExtrasTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Coupon\CouponsToServicesTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Location\LocationsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\WPUsersTable; /** * Class ProviderRepository * * @package AmeliaBooking\Infrastructure\Repository */ class ProviderRepository extends UserRepository implements ProviderRepositoryInterface { const FACTORY = ProviderFactory::class; /** @var string */ protected $providerWeekDayTable; /** @var string */ protected $providerPeriodTable; /** @var string */ protected $providerPeriodServiceTable; /** @var string */ protected $providerPeriodLocationTable; /** @var string */ protected $providerTimeOutTable; /** @var string */ protected $providerSpecialDayTable; /** @var string */ protected $providerSpecialDayPeriodTable; /** @var string */ protected $providerSpecialDayPeriodServiceTable; /** @var string */ protected $providerSpecialDayPeriodLocationTable; /** @var string */ protected $providerDayOffTable; /** @var string */ protected $providerServicesTable; /** @var string */ protected $providerLocationTable; /** @var string */ protected $serviceTable; /** @var string */ protected $locationTable; /** @var string */ protected $providerViewsTable; /** @var string */ protected $providersGoogleCalendarTable; /** @var string */ protected $providersOutlookCalendarTable; /** * @param Connection $connection * @param string $table * @param string $providerWeekDayTable * @param string $providerPeriodTable * @param string $providerPeriodServiceTable * @param string $providerPeriodLocationTable * @param string $providerTimeOutTable * @param string $providerSpecialDayTable * @param string $providerSpecialDayPeriodTable * @param string $providerSpecialDayPeriodServiceTable * @param string $providerSpecialDayPeriodLocationTable * @param string $providerDayOffTable * @param string $providerServicesTable * @param string $providerLocationTable * @param string $serviceTable * @param string $locationTable * @param string $providerViewsTable * @param string $providersGoogleCalendarTable * @param string $providersOutlookCalendarTable */ public function __construct( Connection $connection, $table, $providerWeekDayTable, $providerPeriodTable, $providerPeriodServiceTable, $providerPeriodLocationTable, $providerTimeOutTable, $providerSpecialDayTable, $providerSpecialDayPeriodTable, $providerSpecialDayPeriodServiceTable, $providerSpecialDayPeriodLocationTable, $providerDayOffTable, $providerServicesTable, $providerLocationTable, $serviceTable, $locationTable, $providerViewsTable, $providersGoogleCalendarTable, $providersOutlookCalendarTable ) { parent::__construct($connection, $table); $this->providerWeekDayTable = $providerWeekDayTable; $this->providerPeriodTable = $providerPeriodTable; $this->providerPeriodServiceTable = $providerPeriodServiceTable; $this->providerPeriodLocationTable = $providerPeriodLocationTable; $this->providerTimeOutTable = $providerTimeOutTable; $this->providerSpecialDayTable = $providerSpecialDayTable; $this->providerSpecialDayPeriodTable = $providerSpecialDayPeriodTable; $this->providerSpecialDayPeriodServiceTable = $providerSpecialDayPeriodServiceTable; $this->providerSpecialDayPeriodLocationTable = $providerSpecialDayPeriodLocationTable; $this->providerDayOffTable = $providerDayOffTable; $this->providerServicesTable = $providerServicesTable; $this->providerLocationTable = $providerLocationTable; $this->serviceTable = $serviceTable; $this->locationTable = $locationTable; $this->providerViewsTable = $providerViewsTable; $this->providersGoogleCalendarTable = $providersGoogleCalendarTable; $this->providersOutlookCalendarTable = $providersOutlookCalendarTable; } /** * @param int $id * * @return Provider * @throws QueryExecutionException */ public function getById($id) { try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.status AS user_status, u.externalId AS external_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.note AS note, u.phone AS phone, u.pictureFullPath AS picture_full_path, u.pictureThumbPath AS picture_thumb_path, u.zoomUserId AS user_zoom_user_id, u.translations AS user_translations, gd.id AS google_calendar_id, gd.token AS google_calendar_token, gd.calendarId AS google_calendar_calendar_id, od.id AS outlook_calendar_id, od.token AS outlook_calendar_token, od.calendarId AS outlook_calendar_calendar_id FROM {$this->table} u LEFT JOIN {$this->providersGoogleCalendarTable} gd ON gd.userId = u.id LEFT JOIN {$this->providersOutlookCalendarTable} od ON od.userId = u.id WHERE u.type = :type AND u.id = :userId ORDER BY u.id" ); $type = AbstractUser::USER_ROLE_PROVIDER; $statement->bindParam(':type', $type); $statement->bindParam(':userId', $id); $statement->execute(); $providerRows = []; $serviceRows = []; $providerServiceRows = []; if ($statement->rowCount() === 0) { return null; } while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows)->getItem($id); } /** * * @return Collection * @throws QueryExecutionException */ public function getAll() { try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.status AS user_status, u.externalId AS external_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.note AS note, u.phone AS phone, u.pictureFullPath AS picture_full_path, u.pictureThumbPath AS picture_thumb_path, u.translations AS user_translations, lt.locationId AS user_locationId FROM {$this->table} u LEFT JOIN {$this->providerLocationTable} lt ON lt.userId = u.id WHERE u.type = :type ORDER BY CONCAT(u.firstName, ' ', u.lastName)" ); $type = AbstractUser::USER_ROLE_PROVIDER; $statement->bindParam(':type', $type); $statement->execute(); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows); } /** * @param array $criteria * @param int $itemsPerPage * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getFiltered($criteria, $itemsPerPage) { try { $wpUserTable = WPUsersTable::getTableName(); $params[':type'] = AbstractUser::USER_ROLE_PROVIDER; $order = ''; if (!empty($criteria['sort'])) { $orderColumn = 'CONCAT(u.firstName, " ", u.lastName)'; $orderDirection = $criteria['sort'][0] === '-' ? 'DESC' : 'ASC'; $order = "ORDER BY {$orderColumn} {$orderDirection}"; } $where = []; if (!empty($criteria['search'])) { $params[':search1'] = $params[':search2'] = $params[':search3'] = $params[':search4'] = "%{$criteria['search']}%"; $where[] = "u.id IN( SELECT DISTINCT(user.id) FROM {$this->table} user LEFT JOIN {$wpUserTable} wpUser ON user.externalId = wpUser.ID WHERE (CONCAT(user.firstName, ' ', user.lastName) LIKE :search1 OR wpUser.display_name LIKE :search2 OR user.email LIKE :search3 OR user.note LIKE :search4) )"; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = "u.id IN ( SELECT pst.userId FROM {$this->providerServicesTable} pst WHERE pst.userId = u.id AND pst.serviceId IN (" . implode(', ', $queryServices) . ') )'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'u.id IN (' . implode(', ', $queryProviders) . ')'; } if (!empty($criteria['location'])) { $params[':location'] = $criteria['location']; $where[] = "u.id IN ( SELECT plt.userId FROM {$this->providerLocationTable} plt WHERE plt.userId = u.id AND plt.locationId = :location)"; } $where[] = "u.status NOT LIKE 'disabled'"; $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); $statement = $this->connection->prepare( "SELECT u.* FROM {$this->table} u WHERE u.type = :type $where {$order} {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = new Collection(); foreach ($rows as $row) { $items->addItem(call_user_func([static::FACTORY, 'create'], $row), $row['id']); } return $items; } /** * * @return Collection * @throws QueryExecutionException */ public function getAllWithServices() { try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.status AS user_status, u.externalId AS external_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.note AS note, u.description AS description, u.phone AS phone, u.pictureFullPath AS picture_full_path, u.pictureThumbPath AS picture_thumb_path, u.zoomUserId AS user_zoom_user_id, u.translations AS user_translations, lt.locationId AS user_locationId, st.serviceId AS service_id, st.price AS service_price, st.customPricing AS service_customPricing, st.minCapacity AS service_minCapacity, st.maxCapacity AS service_maxCapacity, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, s.bringingAnyone AS service_bringingAnyone, s.show AS service_show, s.aggregatedPrice AS service_aggregatedPrice, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.recurringCycle AS service_recurringCycle, s.recurringSub AS service_recurringSub, s.recurringPayment AS service_recurringPayment, s.settings AS service_settings, s.translations AS service_translations, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, gd.id AS google_calendar_id, gd.token AS google_calendar_token, gd.calendarId AS google_calendar_calendar_id, od.id AS outlook_calendar_id, od.token AS outlook_calendar_token, od.calendarId AS outlook_calendar_calendar_id FROM {$this->table} u LEFT JOIN {$this->providersGoogleCalendarTable} gd ON gd.userId = u.id LEFT JOIN {$this->providersOutlookCalendarTable} od ON od.userId = u.id LEFT JOIN {$this->providerLocationTable} lt ON lt.userId = u.id LEFT JOIN {$this->providerServicesTable} st ON st.userId = u.id LEFT JOIN {$this->serviceTable} s ON s.id = st.serviceId WHERE u.type = :type ORDER BY CONCAT(u.firstName, ' ', u.lastName)" ); $type = AbstractUser::USER_ROLE_PROVIDER; $statement->bindParam(':type', $type); $statement->execute(); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } $providers = ProviderFactory::createCollection($providerRows, $serviceRows, $providerServiceRows); if (!$providers->length()) { return new Collection(); } $providerIds = implode(', ', $providers->keys()); $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.translations AS user_translations, wdt.id AS weekDay_id, wdt.dayIndex AS weekDay_dayIndex, wdt.startTime AS weekDay_startTime, wdt.endTime As weekDay_endTime, pt.id AS period_id, pt.startTime AS period_startTime, pt.endTime AS period_endTime, pt.locationId AS period_locationId, pst.id AS periodService_id, pst.serviceId AS periodService_serviceId, sdt.id AS specialDay_id, sdt.startDate AS specialDay_startDate, sdt.endDate As specialDay_endDate, sdpt.id AS specialDayPeriod_id, sdpt.startTime AS specialDayPeriod_startTime, sdpt.endTime AS specialDayPeriod_endTime, sdpt.locationId AS specialDayPeriod_locationId, sdpst.id AS specialDayPeriodService_id, sdpst.serviceId AS specialDayPeriodService_serviceId FROM {$this->table} u LEFT JOIN {$this->providerWeekDayTable} wdt ON wdt.userId = u.id LEFT JOIN {$this->providerPeriodTable} pt ON pt.weekDayId = wdt.id LEFT JOIN {$this->providerPeriodServiceTable} pst ON pst.periodId = pt.id LEFT JOIN {$this->providerSpecialDayTable} sdt ON sdt.userId = u.id LEFT JOIN {$this->providerSpecialDayPeriodTable} sdpt ON sdpt.specialDayId = sdt.id LEFT JOIN {$this->providerSpecialDayPeriodServiceTable} sdpst ON sdpst.periodId = sdpt.id WHERE u.id IN ({$providerIds}) ORDER BY CONCAT(u.firstName, ' ', u.lastName)" ); $statement->execute(); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } /** @var Provider $provider */ foreach (ProviderFactory::createCollection($providerRows, [], [])->getItems() as $provider) { $providers->getItem( $provider->getId()->getValue() )->setWeekDayList($provider->getWeekDayList()); $providers->getItem( $provider->getId()->getValue() )->setSpecialDayList($provider->getSpecialDayList()); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $providers; } /** * * @param array $criteria * * @return Collection * @throws QueryExecutionException * @throws InvalidArgumentException */ public function getWithSchedule($criteria) { $providerRows = []; $serviceRows = []; $providerServiceRows = []; $where = ['u.type = :type']; $userParams = []; $params[':type'] = AbstractUser::USER_ROLE_PROVIDER; $queryProviders = []; if (!empty($criteria['providerStatus'])) { $params[':providerStatus'] = $criteria['providerStatus']; $where[] = 'u.status = :providerStatus'; } if (!empty($criteria['providers'])) { foreach ($criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $userParams[$param] = $value; } } if ($queryProviders) { $where[] = 'u.id IN (' . implode(', ', $queryProviders) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.status AS user_status, u.externalId AS external_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.zoomUserId AS user_zoom_user_id, u.countryPhoneIso AS user_countryPhoneIso, u.note AS note, u.description AS description, u.phone AS phone, u.pictureFullPath AS picture_full_path, u.pictureThumbPath AS picture_thumb_path, u.translations AS user_translations, u.timeZone AS user_timeZone, plt.locationId AS user_locationId, pst.serviceId AS service_id, pst.price AS service_price, pst.customPricing AS service_customPricing, pst.minCapacity AS service_minCapacity, pst.maxCapacity AS service_maxCapacity, gd.id AS google_calendar_id, gd.token AS google_calendar_token, gd.calendarId AS google_calendar_calendar_id, od.id AS outlook_calendar_id, od.token AS outlook_calendar_token, od.calendarId AS outlook_calendar_calendar_id, dot.id AS dayOff_id, dot.name AS dayOff_name, dot.startDate AS dayOff_startDate, dot.endDate AS dayOff_endDate, dot.repeat AS dayOff_repeat FROM {$this->table} u LEFT JOIN {$this->providerServicesTable} pst ON pst.userId = u.id LEFT JOIN {$this->providerLocationTable} plt ON plt.userId = u.id LEFT JOIN {$this->providersGoogleCalendarTable} gd ON gd.userId = u.id LEFT JOIN {$this->providersOutlookCalendarTable} od ON od.userId = u.id LEFT JOIN {$this->providerDayOffTable} dot ON dot.userId = u.id {$where} ORDER BY CONCAT(u.firstName, ' ', u.lastName), u.id" ); $statement->execute(array_merge($params, $userParams)); while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $providers */ $providers = call_user_func( [static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows ); if (!$providers->length()) { return new Collection(); } $where = 'WHERE wdt.userId IN (' . implode(', ', $providers->keys()) . ')'; try { $statement = $this->connection->prepare( "SELECT wdt.id AS weekDay_id, wdt.userId AS user_id, wdt.dayIndex AS weekDay_dayIndex, wdt.startTime AS weekDay_startTime, wdt.endTime As weekDay_endTime, tot.id AS timeOut_id, tot.startTime AS timeOut_startTime, tot.endTime AS timeOut_endTime, pt.id AS period_id, pt.startTime AS period_startTime, pt.endTime AS period_endTime, pt.locationId AS period_locationId, pst.id AS periodService_id, pst.serviceId AS periodService_serviceId, plt.id AS periodLocation_id, plt.locationId AS periodLocation_locationId FROM {$this->providerWeekDayTable} wdt LEFT JOIN {$this->providerTimeOutTable} tot ON tot.weekDayId = wdt.id LEFT JOIN {$this->providerPeriodTable} pt ON pt.weekDayId = wdt.id LEFT JOIN {$this->providerPeriodServiceTable} pst ON pst.periodId = pt.id LEFT JOIN {$this->providerPeriodLocationTable} plt ON plt.periodId = pt.id {$where}" ); $statement->execute(); while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $providersWithWeekDays */ $providersWithWeekDays = call_user_func( [static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows ); /** @var Provider $provider */ foreach ($providersWithWeekDays->getItems() as $provider) { $providers->getItem( $provider->getId()->getValue() )->setWeekDayList($provider->getWeekDayList()); } $where = 'WHERE sdt.userId IN (' . implode(', ', $providers->keys()) . ')'; try { $statement = $this->connection->prepare( "SELECT sdt.id AS specialDay_id, sdt.userId AS user_id, sdt.startDate AS specialDay_startDate, sdt.endDate As specialDay_endDate, sdpt.id AS specialDayPeriod_id, sdpt.startTime AS specialDayPeriod_startTime, sdpt.endTime AS specialDayPeriod_endTime, sdpt.locationId AS specialDayPeriod_locationId, sdpst.id AS specialDayPeriodService_id, sdpst.serviceId AS specialDayPeriodService_serviceId, sdplt.id AS specialDayPeriodLocation_id, sdplt.locationId AS specialDayPeriodLocation_locationId FROM {$this->providerSpecialDayTable} sdt LEFT JOIN {$this->providerSpecialDayPeriodTable} sdpt ON sdpt.specialDayId = sdt.id LEFT JOIN {$this->providerSpecialDayPeriodServiceTable} sdpst ON sdpst.periodId = sdpt.id LEFT JOIN {$this->providerSpecialDayPeriodLocationTable} sdplt ON sdplt.periodId = sdpt.id {$where}" ); $statement->execute(); while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } /** @var Collection $providersWithSpecialDays */ $providersWithSpecialDays = call_user_func( [static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows ); /** @var Provider $provider */ foreach ($providersWithSpecialDays->getItems() as $provider) { $providers->getItem( $provider->getId()->getValue() )->setSpecialDayList($provider->getSpecialDayList()); } return $providers; } /** * * @param array $criteria * * @return Collection * @throws QueryExecutionException */ public function getByCriteriaWithSchedule($criteria) { $where = ['u.type = :type']; $params[':type'] = AbstractUser::USER_ROLE_PROVIDER; if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'u.id IN (' . implode(', ', $queryProviders) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.status AS user_status, u.externalId AS external_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.zoomUserId AS user_zoom_user_id, u.countryPhoneIso AS user_countryPhoneIso, u.note AS note, u.description AS description, u.phone AS phone, u.pictureFullPath AS picture_full_path, u.pictureThumbPath AS picture_thumb_path, u.translations AS user_translations, u.timeZone AS user_timeZone, lt.locationId AS user_locationId, wdt.id AS weekDay_id, wdt.dayIndex AS weekDay_dayIndex, wdt.startTime AS weekDay_startTime, wdt.endTime As weekDay_endTime, pt.id AS period_id, pt.startTime AS period_startTime, pt.endTime AS period_endTime, pt.locationId AS period_locationId, pst.id AS periodService_id, pst.serviceId AS periodService_serviceId, tot.id AS timeOut_id, tot.startTime AS timeOut_startTime, tot.endTime AS timeOut_endTime, gd.id AS google_calendar_id, gd.token AS google_calendar_token, gd.calendarId AS google_calendar_calendar_id, od.id AS outlook_calendar_id, od.token AS outlook_calendar_token, od.calendarId AS outlook_calendar_calendar_id FROM {$this->table} u LEFT JOIN {$this->providerLocationTable} lt ON lt.userId = u.id LEFT JOIN {$this->providersGoogleCalendarTable} gd ON gd.userId = u.id LEFT JOIN {$this->providersOutlookCalendarTable} od ON od.userId = u.id LEFT JOIN {$this->providerWeekDayTable} wdt ON wdt.userId = u.id LEFT JOIN {$this->providerPeriodTable} pt ON pt.weekDayId = wdt.id LEFT JOIN {$this->providerPeriodServiceTable} pst ON pst.periodId = pt.id LEFT JOIN {$this->providerSpecialDayTable} sdt ON sdt.userId = u.id LEFT JOIN {$this->providerSpecialDayPeriodTable} sdpt ON sdpt.specialDayId = sdt.id LEFT JOIN {$this->providerTimeOutTable} tot ON tot.weekDayId = wdt.id $where ORDER BY CONCAT(u.firstName, ' ', u.lastName), u.id, tot.weekDayId, wdt.dayIndex, pt.id" ); $statement->execute($params); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } /** @var Collection $providers */ $providers = call_user_func([static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows); $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.status AS user_status, u.externalId AS external_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.note AS note, u.description AS description, u.phone AS phone, u.pictureFullPath AS picture_full_path, u.pictureThumbPath AS picture_thumb_path, u.translations AS user_translations, sdt.id AS specialDay_id, sdt.startDate AS specialDay_startDate, sdt.endDate As specialDay_endDate, sdpt.id AS specialDayPeriod_id, sdpt.startTime AS specialDayPeriod_startTime, sdpt.endTime AS specialDayPeriod_endTime, sdpt.locationId AS specialDayPeriod_locationId, sdpst.id AS specialDayPeriodService_id, sdpst.serviceId AS specialDayPeriodService_serviceId, dot.id AS dayOff_id, dot.name AS dayOff_name, dot.startDate AS dayOff_startDate, dot.endDate AS dayOff_endDate, dot.repeat AS dayOff_repeat FROM {$this->table} u LEFT JOIN {$this->providerSpecialDayTable} sdt ON sdt.userId = u.id LEFT JOIN {$this->providerSpecialDayPeriodTable} sdpt ON sdpt.specialDayId = sdt.id LEFT JOIN {$this->providerSpecialDayPeriodServiceTable} sdpst ON sdpst.periodId = sdpt.id LEFT JOIN {$this->providerDayOffTable} dot ON dot.userId = u.id $where" ); $providerRows = []; $serviceRows = []; $providerServiceRows = []; $statement->execute($params); while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } /** @var Collection $providersWithSpecialDays */ $providersWithSpecialDays = call_user_func([static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows); /** @var Provider $provider */ foreach ($providersWithSpecialDays->getItems() as $provider) { $providers->getItem( $provider->getId()->getValue() )->setDayOffList($provider->getDayOffList()); $providers->getItem( $provider->getId()->getValue() )->setSpecialDayList($provider->getSpecialDayList()); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $providers; } /** * @param array $criteria * * @return mixed * @throws QueryExecutionException */ public function getCount($criteria) { $params = [ ':type' => AbstractUser::USER_ROLE_PROVIDER, ':visibleStatus' => Status::VISIBLE, ':hiddenStatus' => Status::HIDDEN, ]; try { $wpUserTable = WPUsersTable::getTableName(); $where = []; if (!empty($criteria['search'])) { $params[':search1'] = $params[':search2'] = $params[':search3'] = $params[':search4'] = "%{$criteria['search']}%"; $where[] = "u.id IN( SELECT DISTINCT(user.id) FROM {$this->table} user LEFT JOIN {$wpUserTable} wpUser ON user.externalId = wpUser.ID WHERE (CONCAT(user.firstName, ' ', user.lastName) LIKE :search1 OR wpUser.display_name LIKE :search2 OR user.email LIKE :search3 OR user.note LIKE :search4) )"; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = "u.id IN ( SELECT pst.userId FROM {$this->providerServicesTable} pst WHERE pst.userId = u.id AND pst.serviceId IN (" . implode(', ', $queryServices) . ') )'; } if (!empty($criteria['location'])) { $params[':location'] = $criteria['location']; $where[] = "u.id IN ( SELECT plt.userId FROM {$this->providerLocationTable} plt WHERE plt.userId = u.id AND plt.locationId = :location)"; } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->table} u WHERE u.type = :type AND u.status IN (:visibleStatus, :hiddenStatus) $where" ); $statement->execute($params); $row = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $row; } /** * @param $criteria * * @return Collection * * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getByCriteria($criteria) { $locationsTable = LocationsTable::getTableName(); $params = [ ':type' => AbstractUser::USER_ROLE_PROVIDER, ]; $where = []; if (!empty($criteria['providerStatus'])) { $params[':providerStatus'] = $criteria['providerStatus']; $where[] = 'u.status = :providerStatus'; } if (!empty($criteria['serviceStatus'])) { $params[':serviceStatus'] = $criteria['serviceStatus']; $where[] = 's.status = :serviceStatus'; } if (!empty($criteria['services'])) { $queryServices = []; foreach ((array)$criteria['services'] as $index => $value) { $param = ':service' . $index; $queryServices[] = $param; $params[$param] = $value; } $where[] = 'st.serviceId IN (' . implode(', ', $queryServices) . ')'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'u.id IN (' . implode(', ', $queryProviders) . ')'; } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.translations AS user_translations, u.timeZone AS user_timeZone, lt.locationId AS user_locationId, wdt.id AS weekDay_id, wdt.dayIndex AS weekDay_dayIndex, wdt.startTime AS weekDay_startTime, wdt.endTime As weekDay_endTime, pt.id AS period_id, pt.startTime AS period_startTime, pt.endTime AS period_endTime, pt.locationId AS period_locationId, pst.id AS periodService_id, pst.serviceId AS periodService_serviceId, tot.id AS timeOut_id, tot.startTime AS timeOut_startTime, tot.endTime AS timeOut_endTime, st.serviceId AS service_id, st.price AS service_price, st.customPricing AS service_customPricing, st.minCapacity AS service_minCapacity, st.maxCapacity AS service_maxCapacity, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, s.aggregatedPrice AS service_aggregatedPrice, s.bringingAnyone AS service_bringingAnyone, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.settings AS service_settings, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, gd.id AS google_calendar_id, gd.token AS google_calendar_token, gd.calendarId AS google_calendar_calendar_id, od.id AS outlook_calendar_id, od.token AS outlook_calendar_token, od.calendarId AS outlook_calendar_calendar_id FROM {$this->table} u INNER JOIN {$this->providerServicesTable} st ON st.userId = u.id LEFT JOIN {$this->serviceTable} s ON s.id = st.serviceId LEFT JOIN {$this->providerLocationTable} lt ON lt.userId = u.id LEFT JOIN {$locationsTable} l ON (lt.locationId = l.id AND l.status = 'visible') LEFT JOIN {$this->providersGoogleCalendarTable} gd ON gd.userId = u.id LEFT JOIN {$this->providersOutlookCalendarTable} od ON od.userId = u.id LEFT JOIN {$this->providerWeekDayTable} wdt ON wdt.userId = u.id LEFT JOIN {$this->providerPeriodTable} pt ON pt.weekDayId = wdt.id LEFT JOIN {$this->providerPeriodServiceTable} pst ON pst.periodId = pt.id LEFT JOIN {$this->providerTimeOutTable} tot ON tot.weekDayId = wdt.id WHERE u.type = :type {$where} ORDER BY tot.weekDayId, wdt.dayIndex" ); $statement->execute($params); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } /** @var Collection $providers */ $providers = call_user_func([static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows); $params = [ ':type' => AbstractUser::USER_ROLE_PROVIDER, ]; $where = []; if (!empty($criteria['providerStatus'])) { $params[':providerStatus'] = $criteria['providerStatus']; $where[] = 'u.status = :providerStatus'; } if (!empty($criteria['providers'])) { $queryProviders = []; foreach ((array)$criteria['providers'] as $index => $value) { $param = ':provider' . $index; $queryProviders[] = $param; $params[$param] = $value; } $where[] = 'u.id IN (' . implode(', ', $queryProviders) . ')'; } $where = $where ? ' AND ' . implode(' AND ', $where) : ''; $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.translations AS user_translations, sdt.id AS specialDay_id, sdt.startDate AS specialDay_startDate, sdt.endDate As specialDay_endDate, sdpt.id AS specialDayPeriod_id, sdpt.startTime AS specialDayPeriod_startTime, sdpt.endTime AS specialDayPeriod_endTime, sdpt.locationId AS specialDayPeriod_locationId, sdpst.id AS specialDayPeriodService_id, sdpst.serviceId AS specialDayPeriodService_serviceId, dot.id AS dayOff_id, dot.name AS dayOff_name, dot.startDate AS dayOff_startDate, dot.endDate AS dayOff_endDate, dot.repeat AS dayOff_repeat FROM {$this->table} u LEFT JOIN {$this->providerSpecialDayTable} sdt ON sdt.userId = u.id LEFT JOIN {$this->providerSpecialDayPeriodTable} sdpt ON sdpt.specialDayId = sdt.id LEFT JOIN {$this->providerSpecialDayPeriodServiceTable} sdpst ON sdpst.periodId = sdpt.id LEFT JOIN {$this->providerDayOffTable} dot ON dot.userId = u.id WHERE u.type = :type {$where}" ); $statement->execute($params); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } /** @var Collection $providers2 */ $providersWithChanges = call_user_func( [static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows ); /** @var Provider $provider */ foreach ($providersWithChanges->getItems() as $provider) { if ($providers->keyExists($provider->getId()->getValue())) { $providers->getItem( $provider->getId()->getValue() )->setDayOffList($provider->getDayOffList()); $providers->getItem( $provider->getId()->getValue() )->setSpecialDayList($provider->getSpecialDayList()); } } /** @var Provider $provider */ foreach ($providers->getItems() as $provider) { if (!empty($criteria['location']) && $provider->getLocationId() && $provider->getLocationId()->getValue() !== (int)$criteria['location'] ) { $hasLocation = false; /** @var WeekDay $weekDay */ foreach ($provider->getWeekDayList()->getItems() as $weekDay) { /** @var Period $period */ foreach ($weekDay->getPeriodList()->getItems() as $period) { if ($period->getLocationId() && $period->getLocationId()->getValue() === (int)$criteria['location'] ) { $hasLocation = true; break; } } } /** @var SpecialDay $specialDay */ foreach ($provider->getSpecialDayList()->getItems() as $specialDay) { /** @var Period $period */ foreach ($specialDay->getPeriodList()->getItems() as $period) { if ($period->getLocationId() && $period->getLocationId()->getValue() === (int)$criteria['location'] ) { $hasLocation = true; break; } } } if (!$hasLocation) { $providers->deleteItem($provider->getId()->getValue()); } } } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return $providers; } /** * @param $criteria * * @return Collection * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getWithServicesAndExtrasAndCoupons($criteria) { $extrasTable = ExtrasTable::getTableName(); $couponToServicesTable = CouponsToServicesTable::getTableName(); $couponsTable = CouponsTable::getTableName(); $params = [ ':type' => AbstractUser::USER_ROLE_PROVIDER, ':userStatus' => Status::VISIBLE, ':serviceStatus' => Status::VISIBLE ]; $where = []; foreach ((array)$criteria as $index => $value) { $params[':service' . $index] = $value['serviceId']; $params[':provider' . $index] = $value['providerId']; if ($value['couponId']) { $params[':coupon' . $index] = $value['couponId']; $params[':couponStatus' . $index] = Status::VISIBLE; } $where[] = "(s.id = :service$index AND u.id = :provider$index" . ($value['couponId'] ? " AND c.id = :coupon$index AND c.status = :couponStatus$index" : '') . ')'; } $where = $where ? ' AND ' . implode(' OR ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.email AS user_email, u.translations AS user_translations, st.serviceId AS service_id, st.price AS service_price, st.customPricing AS service_customPricing, st.minCapacity AS service_minCapacity, st.maxCapacity AS service_maxCapacity, s.name AS service_name, s.description AS service_description, s.color AS service_color, s.status AS service_status, s.categoryId AS service_categoryId, s.duration AS service_duration, s.bringingAnyone AS service_bringingAnyone, s.pictureFullPath AS service_picture_full, s.pictureThumbPath AS service_picture_thumb, s.aggregatedPrice AS service_aggregatedPrice, s.recurringPayment AS service_recurringPayment, s.translations AS service_translations, s.timeBefore AS service_timeBefore, s.timeAfter AS service_timeAfter, s.deposit AS service_deposit, s.depositPayment AS service_depositPayment, s.depositPerPerson AS service_depositPerPerson, e.id AS extra_id, e.name AS extra_name, e.price AS extra_price, e.maxQuantity AS extra_maxQuantity, e.duration AS extra_duration, e.description AS extra_description, e.position AS extra_position, e.aggregatedPrice AS extra_aggregatedPrice, c.id AS coupon_id, c.code AS coupon_code, c.discount AS coupon_discount, c.deduction AS coupon_deduction, c.limit AS coupon_limit, c.customerLimit AS coupon_customerLimit, c.status AS coupon_status FROM {$this->table} u INNER JOIN {$this->providerServicesTable} st ON st.userId = u.id INNER JOIN {$this->serviceTable} s ON s.id = st.serviceId LEFT JOIN {$extrasTable} e ON e.serviceId = s.id LEFT JOIN {$couponToServicesTable} cs ON cs.serviceId = s.id LEFT JOIN {$couponsTable} c ON c.id = cs.couponId WHERE u.status = :userStatus AND s.status = :serviceStatus AND u.type = :type $where" ); $statement->execute($params); $providerRows = []; $serviceRows = []; $providerServiceRows = []; while ($row = $statement->fetch()) { $this->parseUserRow($row, $providerRows, $serviceRows, $providerServiceRows); } } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } return call_user_func([static::FACTORY, 'createCollection'], $providerRows, $serviceRows, $providerServiceRows); } /** * Returns array of available (currently working) Providers where keys are Provider ID's and array values are * Working Hours Data * * @param $dayIndex * * @return array * @throws QueryExecutionException */ public function getAvailable($dayIndex) { $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTime() . "', '%Y-%m-%d %H:%i:%s')"; $params = [ ':dayIndex' => $dayIndex === 0 ? 7 : $dayIndex, ':type' => AbstractUser::USER_ROLE_PROVIDER ]; try { $statement = $this->connection->prepare("SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, u.translations AS user_translations, wdt.id AS weekDay_id, wdt.dayIndex AS weekDay_dayIndex, wdt.startTime AS weekDay_startTime, wdt.endTime AS weekDay_endTime, pt.id AS period_id, pt.startTime AS period_startTime, pt.endTime AS period_endTime FROM {$this->table} u LEFT JOIN {$this->providerWeekDayTable} wdt ON wdt.userId = u.id LEFT JOIN {$this->providerPeriodTable} pt ON pt.weekDayId = wdt.id WHERE u.type = :type AND wdt.dayIndex = :dayIndex AND (( {$currentDateTime} >= wdt.startTime AND {$currentDateTime} <= wdt.endTime AND pt.startTime IS NULL AND pt.endTime IS NULL ) OR ( {$currentDateTime} >= pt.startTime AND {$currentDateTime} <= pt.endTime AND pt.startTime IS NOT NULL AND pt.endTime IS NOT NULL ))"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { if (!array_key_exists($row['user_id'], $result)) { $result[$row['user_id']] = $row; } $result[$row['user_id']]['periods'][$row['period_id']] = [ 'startTime' => $row['period_startTime'], 'endTime' => $row['period_endTime'] ]; } return $result; } /** * Returns array of available (currently working) Providers where keys are Provider ID's and array values are * Working Hours Data on special day * * @return array * @throws QueryExecutionException */ public function getOnSpecialDay() { $dateTimeNowString = DateTimeService::getNowDateTime(); $currentDateTime = "STR_TO_DATE('" . $dateTimeNowString . "', '%Y-%m-%d %H:%i:%s')"; $currentDateString = DateTimeService::getNowDate(); $params = [ ':type' => AbstractUser::USER_ROLE_PROVIDER ]; try { $statement = $this->connection->prepare("SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, sdpt.startTime AS sdp_startTime, sdpt.endTime AS sdp_endTime, IF ( {$currentDateTime} >= STR_TO_DATE(CONCAT(DATE_FORMAT(sdt.startDate, '%Y-%m-%d'), ' 00:00:00'), '%Y-%m-%d %H:%i:%s') AND {$currentDateTime} <= DATE_ADD(STR_TO_DATE(CONCAT(DATE_FORMAT(sdt.endDate, '%Y-%m-%d'), ' 00:00:00'), '%Y-%m-%d %H:%i:%s'), INTERVAL 1 DAY) AND {$currentDateTime} >= STR_TO_DATE(CONCAT('{$currentDateString}', ' ', DATE_FORMAT(sdpt.startTime, '%H:%i:%s')), '%Y-%m-%d %H:%i:%s') AND {$currentDateTime} <= STR_TO_DATE(CONCAT('{$currentDateString}', ' ', DATE_FORMAT(sdpt.endTime, '%H:%i:%s')), '%Y-%m-%d %H:%i:%s'), 1, 0 ) AS available FROM {$this->table} u INNER JOIN {$this->providerSpecialDayTable} sdt ON sdt.userId = u.id INNER JOIN {$this->providerSpecialDayPeriodTable} sdpt ON sdpt.specialDayId = sdt.id WHERE u.type = :type AND STR_TO_DATE('{$currentDateString}', '%Y-%m-%d') BETWEEN sdt.startDate AND sdt.endDate "); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } $result = []; $dateTimeNow = DateTimeService::getNowDateTimeObject(); foreach ($rows as $row) { $dateTimeEnd = DateTimeService::getCustomDateTimeObject($currentDateString . " " . $row['sdp_endTime']); if (!array_key_exists($row['user_id'], $result) && $dateTimeNow <= $dateTimeEnd) { $result[$row['user_id']] = $row; } } return $result; } /** * @param $dayIndex * * @return array * @throws QueryExecutionException */ public function getOnBreak($dayIndex) { $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTime() . "', '%Y-%m-%d %H:%i:%s')"; $params = [ ':dayIndex' => $dayIndex === 0 ? 7 : $dayIndex, ':type' => AbstractUser::USER_ROLE_PROVIDER ]; try { $statement = $this->connection->prepare("SELECT u.id AS user_id, u.firstName AS user_firstName, u.lastName AS user_lastName, wdt.id AS weekDay_id, wdt.dayIndex AS weekDay_dayIndex, wdt.startTime AS weekDay_startTime, wdt.endTime As weekDay_endTime, tot.id AS timeOut_id, tot.startTime AS timeOut_startTime, tot.endTime AS timeOut_endTime FROM {$this->table} u LEFT JOIN {$this->providerWeekDayTable} wdt ON wdt.userId = u.id LEFT JOIN {$this->providerTimeOutTable} tot ON tot.weekDayId = wdt.id WHERE u.type = :type AND wdt.dayIndex = :dayIndex AND {$currentDateTime} >= wdt.startTime AND {$currentDateTime} <= wdt.endTime AND {$currentDateTime} >= tot.startTime AND {$currentDateTime} <= tot.endTime"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['user_id']] = $row; } return $result; } /** * @return array * @throws QueryExecutionException */ public function getOnVacation() { $currentDateTime = "STR_TO_DATE('" . DateTimeService::getNowDateTime() . "', '%Y-%m-%d %H:%i:%s')"; $params = [ ':type' => AbstractUser::USER_ROLE_PROVIDER ]; try { $statement = $this->connection->prepare("SELECT u.id, u.firstName, u.lastName, dot.startDate, dot.endDate, dot.name FROM {$this->table} u LEFT JOIN {$this->providerDayOffTable} dot ON dot.userId = u.id WHERE u.type = :type AND DATE_FORMAT({$currentDateTime}, '%Y-%m-%d') BETWEEN dot.startDate AND dot.endDate"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * Return an array of providers with the number of appointments for the given date period. * Keys of the array are Provider IDs. * * @param $criteria * * @return array * @throws InvalidArgumentException * @throws QueryExecutionException */ public function getAllNumberOfAppointments($criteria) { $appointmentTable = AppointmentsTable::getTableName(); $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(a.bookingStart, '%Y-%m-%d') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (isset($criteria['status'])) { $where[] = 'u.status = :status'; $params[':status'] = $criteria['status']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT u.id, CONCAT(u.firstName, ' ', u.lastName) AS name, COUNT(a.providerId) AS appointments FROM {$this->table} u INNER JOIN {$appointmentTable} a ON u.id = a.providerId $where GROUP BY providerId"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * Return an array of providers with the number of views for the given date period. * Keys of the array are Providers IDs. * * @param $criteria * * @return array * @throws QueryExecutionException */ public function getAllNumberOfViews($criteria) { $params = []; $where = []; if ($criteria['dates']) { $where[] = "(DATE_FORMAT(pv.date, '%Y-%m-%d') BETWEEN :bookingFrom AND :bookingTo)"; $params[':bookingFrom'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][0]); $params[':bookingTo'] = DateTimeService::getCustomDateTimeInUtc($criteria['dates'][1]); } if (isset($criteria['status'])) { $where[] = 'u.status = :status'; $params[':status'] = $criteria['status']; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare("SELECT u.id, CONCAT(u.firstName, ' ', u.lastName) as name, SUM(pv.views) AS views FROM {$this->table} u INNER JOIN {$this->providerViewsTable} pv ON pv.userId = u.id $where GROUP BY u.id"); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $result[$row['id']] = $row; } return $result; } /** * @param $providerId * * @return string * @throws QueryExecutionException */ public function addViewStats($providerId) { $date = DateTimeService::getNowDate(); $params = [ ':userId' => $providerId, ':date' => $date, ':views' => 1 ]; try { // Check if there is already data for this provider for this date $statement = $this->connection->prepare( "SELECT COUNT(*) AS count FROM {$this->providerViewsTable} AS pv WHERE pv.userId = :userId AND pv.date = :date" ); $statement->bindParam(':userId', $providerId); $statement->bindParam(':date', $date); $statement->execute(); $count = $statement->fetch()['count']; if (!$count) { $statement = $this->connection->prepare( "INSERT INTO {$this->providerViewsTable} (`userId`, `date`, `views`) VALUES (:userId, :date, :views)" ); } else { $statement = $this->connection->prepare( "UPDATE {$this->providerViewsTable} pv SET pv.views = pv.views + :views WHERE pv.userId = :userId AND pv.date = :date" ); } $response = $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__, $e->getCode(), $e); } if (!$response) { throw new QueryExecutionException('Unable to add data in ' . __CLASS__); } return true; } /** * * @return array * @throws QueryExecutionException */ public function getProvidersServices() { try { $statement = $this->connection->prepare( "SELECT u.id AS user_id, st.serviceId AS service_id, st.price AS service_price, st.customPricing AS service_customPricing, st.minCapacity AS service_minCapacity, st.maxCapacity AS service_maxCapacity FROM {$this->table} u INNER JOIN {$this->providerServicesTable} st ON st.userId = u.id WHERE u.type = :type ORDER BY CONCAT(u.firstName, ' ', u.lastName)" ); $type = AbstractUser::USER_ROLE_PROVIDER; $statement->bindParam(':type', $type); $statement->execute(); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to find by id in ' . __CLASS__, $e->getCode(), $e); } $result = []; foreach ($rows as $row) { $userId = (int)$row['user_id']; $serviceId = (int)$row['service_id']; if (!array_key_exists($userId, $result) || !array_key_exists($serviceId, $result[$userId])) { $result[$userId][$serviceId] = [ 'price' => $row['service_price'], 'customPricing' => $row['service_customPricing'], 'minCapacity' => (int)$row['service_minCapacity'], 'maxCapacity' => (int)$row['service_maxCapacity'], ]; } } return $result; } /** @noinspection MoreThanThreeArgumentsInspection */ /** * @param array $row * @param array $providerRows * @param array $serviceRows * @param array $providerServiceRows * * @return void */ private function parseUserRow($row, &$providerRows, &$serviceRows, &$providerServiceRows) { $userId = (int)$row['user_id']; $serviceId = isset($row['service_id']) ? (int)$row['service_id'] : null; $extraId = isset($row['extra_id']) ? $row['extra_id'] : null; $couponId = isset($row['coupon_id']) ? $row['coupon_id'] : null; $googleCalendarId = isset($row['google_calendar_id']) ? $row['google_calendar_id'] : null; $outlookCalendarId = isset($row['outlook_calendar_id']) ? $row['outlook_calendar_id'] : null; $weekDayId = isset($row['weekDay_id']) ? $row['weekDay_id'] : null; $timeOutId = isset($row['timeOut_id']) ? $row['timeOut_id'] : null; $periodId = isset($row['period_id']) ? $row['period_id'] : null; $periodServiceId = isset($row['periodService_id']) ? $row['periodService_id'] : null; $periodLocationId = isset($row['periodLocation_id']) ? $row['periodLocation_id'] : null; $specialDayId = isset($row['specialDay_id']) ? $row['specialDay_id'] : null; $specialDayPeriodId = isset($row['specialDayPeriod_id']) ? $row['specialDayPeriod_id'] : null; $specialDayPeriodServiceId = isset($row['specialDayPeriodService_id']) ? $row['specialDayPeriodService_id'] : null; $specialDayPeriodLocationId = isset($row['specialDayPeriodLocation_id']) ? $row['specialDayPeriodLocation_id'] : null; $dayOffId = isset($row['dayOff_id']) ? $row['dayOff_id'] : null; if (!array_key_exists($userId, $providerRows)) { $providerRows[$userId] = [ 'id' => $userId, 'type' => 'provider', 'status' => isset($row['user_status']) ? $row['user_status'] : null, 'externalId' => isset($row['external_id']) ? $row['external_id'] : null, 'firstName' => $row['user_firstName'], 'lastName' => $row['user_lastName'], 'email' => $row['user_email'], 'note' => isset($row['note']) ? $row['note'] : null, 'description' => isset($row['description']) ? $row['description'] : null, 'phone' => isset($row['phone']) ? $row['phone'] : null, 'zoomUserId' => isset($row['user_zoom_user_id']) ? $row['user_zoom_user_id'] : null, 'countryPhoneIso' => isset($row['user_countryPhoneIso']) ? $row['user_countryPhoneIso'] : null, 'locationId' => isset($row['user_locationId']) ? $row['user_locationId'] : null, 'pictureFullPath' => isset($row['picture_full_path']) ? $row['picture_full_path'] : null, 'pictureThumbPath' => isset($row['picture_thumb_path']) ? $row['picture_thumb_path'] : null, 'translations' => $row['user_translations'], 'googleCalendar' => [], 'weekDayList' => [], 'dayOffList' => [], 'specialDayList' => [], 'serviceList' => [], 'timeZone' => isset($row['user_timeZone']) ? $row['user_timeZone'] : null, ]; } if ($googleCalendarId && array_key_exists($userId, $providerRows) && empty($providerRows[$userId]['googleCalendar']) ) { $providerRows[$userId]['googleCalendar']['id'] = $row['google_calendar_id']; $providerRows[$userId]['googleCalendar']['token'] = $row['google_calendar_token']; $providerRows[$userId]['googleCalendar']['calendarId'] = isset($row['google_calendar_calendar_id']) ? $row['google_calendar_calendar_id'] : null; } if ($outlookCalendarId && array_key_exists($userId, $providerRows) && empty($providerRows[$userId]['outlookCalendar']) ) { $providerRows[$userId]['outlookCalendar']['id'] = $row['outlook_calendar_id']; $providerRows[$userId]['outlookCalendar']['token'] = $row['outlook_calendar_token']; $providerRows[$userId]['outlookCalendar']['calendarId'] = isset($row['outlook_calendar_calendar_id']) ? $row['outlook_calendar_calendar_id'] : null; } if ($weekDayId && array_key_exists($userId, $providerRows) && !array_key_exists($weekDayId, $providerRows[$userId]['weekDayList']) ) { $providerRows[$userId]['weekDayList'][$weekDayId] = [ 'id' => $weekDayId, 'dayIndex' => $row['weekDay_dayIndex'], 'startTime' => $row['weekDay_startTime'], 'endTime' => $row['weekDay_endTime'], 'timeOutList' => [], 'periodList' => [], ]; } if ($periodId && $weekDayId && array_key_exists($userId, $providerRows) && array_key_exists($weekDayId, $providerRows[$userId]['weekDayList']) && !array_key_exists($periodId, $providerRows[$userId]['weekDayList'][$weekDayId]['periodList']) ) { $providerRows[$userId]['weekDayList'][$weekDayId]['periodList'][$periodId] = [ 'id' => $periodId, 'startTime' => $row['period_startTime'], 'endTime' => $row['period_endTime'], 'locationId' => $row['period_locationId'], 'periodServiceList' => [], 'periodLocationList' => [], ]; } if ($periodServiceId && $periodId && $weekDayId && array_key_exists($userId, $providerRows) && array_key_exists($weekDayId, $providerRows[$userId]['weekDayList']) && array_key_exists($periodId, $providerRows[$userId]['weekDayList'][$weekDayId]['periodList']) && !array_key_exists($periodServiceId, $providerRows[$userId]['weekDayList'][$weekDayId]['periodList'][$periodId]['periodServiceList']) ) { $providerRows[$userId]['weekDayList'][$weekDayId]['periodList'][$periodId]['periodServiceList'][$periodServiceId] = [ 'id' => $periodServiceId, 'serviceId' => $row['periodService_serviceId'], ]; } if ($periodLocationId && $periodId && $weekDayId && array_key_exists($userId, $providerRows) && array_key_exists($weekDayId, $providerRows[$userId]['weekDayList']) && array_key_exists($periodId, $providerRows[$userId]['weekDayList'][$weekDayId]['periodList']) && !array_key_exists($periodLocationId, $providerRows[$userId]['weekDayList'][$weekDayId]['periodList'][$periodId]['periodLocationList']) ) { $providerRows[$userId]['weekDayList'][$weekDayId]['periodList'][$periodId]['periodLocationList'][$periodLocationId] = [ 'id' => $periodLocationId, 'locationId' => $row['periodLocation_locationId'], ]; } if ($timeOutId && $weekDayId && array_key_exists($userId, $providerRows) && array_key_exists($weekDayId, $providerRows[$userId]['weekDayList']) && !array_key_exists($timeOutId, $providerRows[$userId]['weekDayList'][$weekDayId]['timeOutList']) ) { $providerRows[$userId]['weekDayList'][$weekDayId]['timeOutList'][$timeOutId] = [ 'id' => $timeOutId, 'startTime' => $row['timeOut_startTime'], 'endTime' => $row['timeOut_endTime'], ]; } if ($specialDayId && array_key_exists($userId, $providerRows) && !array_key_exists($specialDayId, $providerRows[$userId]['specialDayList']) ) { $providerRows[$userId]['specialDayList'][$specialDayId] = [ 'id' => $specialDayId, 'startDate' => $row['specialDay_startDate'], 'endDate' => $row['specialDay_endDate'], 'periodList' => [], ]; } if ($specialDayPeriodId && $specialDayId && array_key_exists($userId, $providerRows) && array_key_exists($specialDayId, $providerRows[$userId]['specialDayList']) && !array_key_exists($specialDayPeriodId, $providerRows[$userId]['specialDayList'][$specialDayId]['periodList']) ) { $providerRows[$userId]['specialDayList'][$specialDayId]['periodList'][$specialDayPeriodId] = [ 'id' => $specialDayPeriodId, 'startTime' => $row['specialDayPeriod_startTime'], 'endTime' => $row['specialDayPeriod_endTime'], 'locationId' => $row['specialDayPeriod_locationId'], 'periodServiceList' => [], 'periodLocationList' => [], ]; } if ($specialDayPeriodServiceId && $specialDayPeriodId && $specialDayId && array_key_exists($userId, $providerRows) && array_key_exists($specialDayId, $providerRows[$userId]['specialDayList']) && array_key_exists($specialDayPeriodId, $providerRows[$userId]['specialDayList'][$specialDayId]['periodList']) && !array_key_exists($specialDayPeriodServiceId, $providerRows[$userId]['specialDayList'][$specialDayId]['periodList'][$specialDayPeriodId]['periodServiceList']) ) { $providerRows[$userId]['specialDayList'][$specialDayId]['periodList'][$specialDayPeriodId]['periodServiceList'][$specialDayPeriodServiceId] = [ 'id' => $specialDayPeriodServiceId, 'serviceId' => $row['specialDayPeriodService_serviceId'], ]; } if ($specialDayPeriodLocationId && $specialDayPeriodId && $specialDayId && array_key_exists($userId, $providerRows) && array_key_exists($specialDayId, $providerRows[$userId]['specialDayList']) && array_key_exists($specialDayPeriodId, $providerRows[$userId]['specialDayList'][$specialDayId]['periodList']) && !array_key_exists($specialDayPeriodLocationId, $providerRows[$userId]['specialDayList'][$specialDayId]['periodList'][$specialDayPeriodId]['periodLocationList']) ) { $providerRows[$userId]['specialDayList'][$specialDayId]['periodList'][$specialDayPeriodId]['periodLocationList'][$specialDayPeriodLocationId] = [ 'id' => $specialDayPeriodLocationId, 'locationId' => $row['specialDayPeriodLocation_locationId'], ]; } if ($dayOffId && array_key_exists($userId, $providerRows) && !array_key_exists($dayOffId, $providerRows[$userId]['dayOffList']) ) { $providerRows[$userId]['dayOffList'][$dayOffId] = [ 'id' => $dayOffId, 'name' => $row['dayOff_name'], 'startDate' => $row['dayOff_startDate'], 'endDate' => $row['dayOff_endDate'], 'repeat' => $row['dayOff_repeat'], ]; } if ($serviceId && !array_key_exists($serviceId, $serviceRows) ) { $serviceRows[$serviceId] = [ 'id' => $serviceId, 'customPricing' => isset($row['service_customPricing']) ? $row['service_customPricing'] : null, 'price' => $row['service_price'], 'minCapacity' => $row['service_minCapacity'], 'maxCapacity' => $row['service_maxCapacity'], 'name' => isset($row['service_name']) ? $row['service_name'] : null, 'description' => isset($row['service_description']) ? $row['service_description'] : null, 'color' => isset($row['service_color']) ? $row['service_color'] : null, 'status' => isset($row['service_status']) ? $row['service_status'] : null, 'categoryId' => isset($row['service_categoryId']) ? (int)$row['service_categoryId'] : null, 'duration' => isset($row['service_duration']) ? $row['service_duration'] : null, 'bringingAnyone' => isset($row['service_bringingAnyone']) ? $row['service_bringingAnyone'] : null, 'show' => isset($row['service_show']) ? $row['service_show'] : null, 'aggregatedPrice' => isset($row['service_aggregatedPrice']) ? $row['service_aggregatedPrice'] : null, 'pictureFullPath' => isset($row['service_picture_full']) ? $row['service_picture_full'] : null, 'pictureThumbPath' => isset($row['service_picture_thumb']) ? $row['service_picture_thumb'] : null, 'timeBefore' => isset($row['service_timeBefore']) ? $row['service_timeBefore'] : null, 'timeAfter' => isset($row['service_timeAfter']) ? $row['service_timeAfter'] : null, 'extras' => [], 'coupons' => [], 'settings' => isset($row['service_settings']) ? $row['service_settings'] : null, 'recurringCycle' => isset($row['service_recurringCycle']) ? $row['service_recurringCycle'] : null, 'recurringSub' => isset($row['service_recurringSub']) ? $row['service_recurringSub'] : null, 'recurringPayment' => isset($row['service_recurringPayment']) ? $row['service_recurringPayment'] : null, 'translations' => isset($row['service_translations']) ? $row['service_translations'] : null, 'deposit' => isset($row['service_deposit']) ? $row['service_deposit'] : null, 'depositPayment' => isset($row['service_depositPayment']) ? $row['service_depositPayment'] : null, 'depositPerPerson' => isset($row['service_depositPerPerson']) ? $row['service_depositPerPerson'] : null, ]; } if ($extraId && $serviceId && array_key_exists($serviceId, $serviceRows) && !array_key_exists($extraId, $serviceRows[$serviceId]['extras']) ) { $serviceRows[$serviceId]['extras'][$extraId] = [ 'id' => $extraId, 'name' => $row['extra_name'], 'price' => $row['extra_price'], 'maxQuantity' => $row['extra_maxQuantity'], 'position' => $row['extra_position'], 'aggregatedPrice' => $row['extra_aggregatedPrice'], 'description' => $row['extra_description'] ]; } if ($couponId && $serviceId && array_key_exists($serviceId, $serviceRows) && !array_key_exists($couponId, $serviceRows[$serviceId]['coupons']) ) { $serviceRows[$serviceId]['coupons'][$couponId] = [ 'id' => $couponId, 'code' => $row['coupon_code'], 'discount' => $row['coupon_discount'], 'deduction' => $row['coupon_deduction'], 'limit' => $row['coupon_limit'], 'customerLimit' => $row['coupon_customerLimit'], 'status' => $row['coupon_status'] ]; } if ($serviceId && (!array_key_exists($userId, $providerServiceRows) || !array_key_exists($serviceId, $providerServiceRows[$userId]))) { $providerServiceRows[$userId][$serviceId] = [ 'price' => $row['service_price'], 'customPricing' => $row['service_customPricing'], 'minCapacity' => (int)$row['service_minCapacity'], 'maxCapacity' => (int)$row['service_maxCapacity'] ]; } } /** * @param int $userId * * @return mixed * @throws QueryExecutionException */ public function deleteViewStats($userId) { $params = [ ':userId' => $userId, ]; try { $statement = $this->connection->prepare( "DELETE FROM {$this->providerViewsTable} WHERE userId = :userId" ); return $statement->execute($params); } catch (\Exception $e) { throw new QueryExecutionException('Unable to delete data from ' . __CLASS__, $e->getCode(), $e); } } } Repository/User/CustomerRepository.php 0000666 00000021357 15165376447 0014311 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\User; use AmeliaBooking\Domain\Entity\User\AbstractUser; use AmeliaBooking\Domain\Repository\User\CustomerRepositoryInterface; use AmeliaBooking\Domain\Services\DateTime\DateTimeService; use AmeliaBooking\Domain\ValueObjects\String\BookingStatus; use AmeliaBooking\Domain\ValueObjects\String\Status; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\AppointmentsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\Booking\CustomerBookingsTable; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\WPUsersTable; /** * Class UserRepository * * @package AmeliaBooking\Infrastructure\Repository */ class CustomerRepository extends UserRepository implements CustomerRepositoryInterface { /** * @param $criteria * @param int $itemsPerPage * * @return array * @throws QueryExecutionException * @throws \Exception */ public function getFiltered($criteria, $itemsPerPage = null) { try { $wpUserTable = WPUsersTable::getTableName(); $bookingsTable = CustomerBookingsTable::getTableName(); $appointmentsTable = AppointmentsTable::getTableName(); $params = [ ':type_customer' => AbstractUser::USER_ROLE_CUSTOMER, ':type_admin' => AbstractUser::USER_ROLE_ADMIN, ]; $joinWithBookings = empty($criteria['ignoredBookings']); $where = [ 'u.type IN (:type_customer, :type_admin)', ]; $order = ''; if (!empty($criteria['sort'])) { $column = $criteria['sort'][0] === '-' ? substr($criteria['sort'], 1) : $criteria['sort']; $orderColumn = $column === 'customer' ? 'CONCAT(u.firstName, " ", u.lastName)' : 'lastAppointment'; $orderDirection = $criteria['sort'][0] === '-' ? 'DESC' : 'ASC'; $order = "ORDER BY {$orderColumn} {$orderDirection}"; $joinWithBookings = $column !== 'customer' ? true : $joinWithBookings; } if (!empty($criteria['search'])) { $params[':search1'] = $params[':search2'] = $params[':search3'] = $params[':search4'] = "%{$criteria['search']}%"; $where[] = "((CONCAT(u.firstName, ' ', u.lastName) LIKE :search1 OR wpu.display_name LIKE :search2 OR u.email LIKE :search3 OR u.note LIKE :search4))"; } if (!empty($criteria['customers'])) { $customersCriteria = []; foreach ((array)$criteria['customers'] as $key => $customerId) { $params[":customerId$key"] = $customerId; $customersCriteria[] = ":customerId$key"; } $where[] = 'u.id IN (' . implode(', ', $customersCriteria) . ')'; } $statsFields = ' NULL as lastAppointment, 0 as totalAppointments, 0 as countPendingAppointments, '; $statsJoins = ''; if ($joinWithBookings) { $params[':bookingPendingStatus'] = BookingStatus::PENDING; $statsFields = ' MAX(app.bookingStart) as lastAppointment, COUNT(cb.id) as totalAppointments, SUM(case when cb.status = :bookingPendingStatus then 1 else 0 end) as countPendingAppointments, '; $statsJoins = " LEFT JOIN {$bookingsTable} cb ON u.id = cb.customerId LEFT JOIN {$appointmentsTable} app ON app.id = cb.appointmentId "; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $limit = $this->getLimit( !empty($criteria['page']) ? (int)$criteria['page'] : 0, (int)$itemsPerPage ); $statement = $this->connection->prepare( "SELECT u.id as id, u.status as status, u.firstName as firstName, u.lastName as lastName, u.email as email, u.phone as phone, u.countryPhoneIso AS countryPhoneIso, u.gender as gender, u.externalId as externalId, u.translations as translations, IF(u.birthday IS NOT NULL, u.birthday , '') as birthday, u.note as note, {$statsFields} IF(wpu.display_name IS NOT NULL, wpu.display_name , '') as wpName FROM {$this->table} as u LEFT JOIN {$wpUserTable} wpu ON u.externalId = wpu.id {$statsJoins} {$where} GROUP BY u.id {$order} {$limit}" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $row['id'] = (int)$row['id']; $row['externalId'] = $row['externalId'] === null ? $row['externalId'] : (int)$row['externalId']; $row['lastAppointment'] = $row['lastAppointment'] ? DateTimeService::getCustomDateTimeFromUtc($row['lastAppointment']) : $row['lastAppointment']; $items[(int)$row['id']] = $row; } return $items; } /** * @param $criteria * * @return mixed * @throws QueryExecutionException */ public function getCount($criteria) { $wpUserTable = WPUsersTable::getTableName(); $params = [ ':type_customer' => AbstractUser::USER_ROLE_CUSTOMER, ':type_admin' => AbstractUser::USER_ROLE_ADMIN, ':statusVisible' => Status::VISIBLE, ]; $where = [ 'u.type IN (:type_customer, :type_admin)', 'u.status = :statusVisible' ]; if (!empty($criteria['search'])) { $params[':search1'] = $params[':search2'] = $params[':search3'] = $params[':search4'] = "%{$criteria['search']}%"; $where[] = "((CONCAT(u.firstName, ' ', u.lastName) LIKE :search1 OR wpu.display_name LIKE :search2 OR u.email LIKE :search3 OR u.note LIKE :search4))"; } if (!empty($criteria['customers'])) { $customersCriteria = []; foreach ((array)$criteria['customers'] as $key => $customerId) { $params[":customerId$key"] = $customerId; $customersCriteria[] = ":customerId$key"; } $where[] = 'u.id IN (' . implode(', ', $customersCriteria) . ')'; } $where = $where ? 'WHERE ' . implode(' AND ', $where) : ''; try { $statement = $this->connection->prepare( "SELECT COUNT(*) as count FROM {$this->table} as u LEFT JOIN {$wpUserTable} wpu ON u.externalId = wpu.id $where" ); $statement->execute($params); $rows = $statement->fetch()['count']; } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $rows; } /** * @param string $phone * * @return array * @throws QueryExecutionException * @throws \Exception */ public function getByPhoneNumber($phone) { try { $params[':phone'] = '+' . $phone; $statement = $this->connection->prepare( "SELECT u.id as id, u.status as status, u.firstName as firstName, u.lastName as lastName, u.email as email, u.phone as phone, u.countryPhoneIso AS countryPhoneIso, u.gender as gender, u.externalId as externalId, IF(u.birthday IS NOT NULL, u.birthday , '') as birthday, u.note as note FROM {$this->table} as u WHERE u.type = 'customer' AND phone = :phone" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } return $rows; } } Repository/User/WPUserRepository.php 0000666 00000005573 15165376447 0013677 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\Repository\User; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use AmeliaBooking\Infrastructure\Connection; use AmeliaBooking\Infrastructure\WP\InstallActions\DB\User\UsersTable; /** * Class WPUserRepository * * @package AmeliaBooking\Infrastructure\Repository\User */ class WPUserRepository { /** @var \PDO */ protected $connection; /** @var string */ protected $table; /** @var string */ protected $metaTable; /** @var string */ protected $prefix; /** * WPUserRepository constructor. * * @param Connection $connection * @param $table * @param $metaTable * @param $prefix */ public function __construct(Connection $connection, $table, $metaTable, $prefix) { $this->connection = $connection(); $this->table = $table; $this->metaTable = $metaTable; $this->prefix = $prefix; } /** * @param array $params * @param array $excludeUserIds * * @return array * @throws QueryExecutionException */ public function getAllNonRelatedWPUsers($params, $excludeUserIds) { $excludeIdParams = []; try { $params = [ ':id' => $params['id'], ':role' => '%wpamelia-' . $params['role'] . '%', ]; foreach ((array)$excludeUserIds as $key => $id) { $excludeIdParams[":id$key"] = $id; } $whereExcludeIds = $excludeIdParams ? ' AND wp_user.ID NOT IN (' . implode(',', $excludeIdParams) . ')' : ''; $usersTable = UsersTable::getTableName(); global $wpdb; $statement = $this->connection->prepare( "SELECT wp_user.ID AS value, wp_user.display_name AS label FROM {$this->table} AS wp_user INNER JOIN {$this->metaTable} AS wp_usermeta ON wp_user.ID = wp_usermeta.user_id WHERE wp_user.ID NOT IN ( SELECT externalId FROM $usersTable WHERE externalId IS NOT NULL AND externalId != :id ) {$whereExcludeIds} AND wp_usermeta.meta_key = '{$wpdb->prefix}capabilities' AND wp_usermeta.meta_value LIKE :role GROUP BY wp_user.ID" ); $statement->execute($params); $rows = $statement->fetchAll(); } catch (\Exception $e) { throw new QueryExecutionException('Unable to get data from ' . __CLASS__, $e->getCode(), $e); } $items = []; foreach ($rows as $row) { $row['value'] = (int)$row['value']; $items[] = $row; } return $items; } } DB/PDO/Connection.php 0000666 00000006764 15165376447 0010326 0 ustar 00 <?php /** * @author Slavko Babic * @date 2017-08-21 */ namespace AmeliaBooking\Infrastructure\DB\PDO; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use \PDO; /** * Class Connection * * @package AmeliaBooking\Infrastructure\DB\PDO */ class Connection extends \AmeliaBooking\Infrastructure\Connection { /** @var PDO $pdo */ protected $pdo; /** @var string $dns */ private $dns; /** @var string $driver */ private $driver = 'mysql'; /** * Connection constructor. * * @param string $database * @param string $username * @param string $password * @param string $host * @param int $port * @param string $charset */ public function __construct( $host, $database, $username, $password, $charset = 'utf8', $port = 3306 ) { parent::__construct( $host, $database, $username, $password, $charset, $port ); $this->handler = new PDO( $this->dns(), $this->username, $this->password, $this->getOptions() ); $settingsService = new SettingsService(new SettingsStorage()); $emulatePrepares = $settingsService->getSetting('db', 'pdoEmulatePrepares'); $this->handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->handler->setAttribute( PDO::ATTR_EMULATE_PREPARES, $emulatePrepares !== null ? $emulatePrepares : false ); $this->handler->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $this->handler->exec('SET SESSION sql_mode = "TRADITIONAL"'); $this->handler->exec('SET FOREIGN_KEY_CHECKS = 0'); if ($settingsService->getSetting('db', 'pdoBigSelect')) { $this->handler->exec('SET SQL_BIG_SELECTS = 1'); } } /** * @return string */ private function dns() { if ($this->dns) { return $this->dns; } $this->socketHandler(); $socketPath = property_exists($this, 'socketPath') && $this->socketPath ? ";unix_socket=$this->socketPath" : ''; return $this->dns = "{$this->driver}:host={$this->host};port={$this->port}';dbname={$this->database}{$socketPath}"; } /** * @return array */ private function getOptions() { $options = [ PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, ]; if (defined('DB_CHARSET')) { $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'set names ' . DB_CHARSET; } $settingsService = new SettingsService(new SettingsStorage()); $ssl = $settingsService->getSetting('db', 'ssl'); if ($ssl['enable']) { if ($ssl['enable']) { if ($ssl['key'] !== null) { $options[PDO::MYSQL_ATTR_SSL_KEY] = $ssl['key']; } if ($ssl['cert'] !== null) { $options[PDO::MYSQL_ATTR_SSL_CERT] = $ssl['cert']; } if ($ssl['ca'] !== null) { $options[PDO::MYSQL_ATTR_SSL_CA] = $ssl['ca']; } if ($ssl['verify_cert'] !== null) { $options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = $ssl['verify_cert']; } } } return $options; } } DB/MySQLi/Query.php 0000666 00000000635 15165376447 0010017 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\DB\MySQLi; /** * Class Query * * @package AmeliaBooking\Infrastructure\DB\MySQLi */ class Query { private $value; /** * @param string $value */ public function setValue($value) { $this->value = $value; } /** * * @return mixed */ public function getValue() { return $this->value; } } DB/MySQLi/Connection.php 0000666 00000006527 15165376447 0011017 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\DB\MySQLi; use AmeliaBooking\Domain\Services\Settings\SettingsService; use AmeliaBooking\Infrastructure\WP\SettingsService\SettingsStorage; use mysqli; /** * Class Connection * * @package AmeliaBooking\Infrastructure\DB\MySQLi */ class Connection extends \AmeliaBooking\Infrastructure\Connection { /** @var Statement $statement */ public $statement; /** @var Result $result */ private $result; /** @var Query $query */ private $query; /** @var mysqli $mysqli */ private $mysqli; /** * Connection constructor. * * @param string $database * @param string $username * @param string $password * @param string $host * @param int $port * @param string $charset */ public function __construct( $host, $database, $username, $password, $charset = 'utf8', $port = 3306 ) { parent::__construct( $host, $database, $username, $password, $charset, $port ); $this->socketHandler(); $this->result = new Result(); $this->query = new Query(); if (property_exists($this, 'socketPath') && $this->socketPath) { $this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->database, $this->port, $this->socketPath); } else { $this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->database, $this->port); } $settingsService = new SettingsService(new SettingsStorage()); $ssl = $settingsService->getSetting('db', 'ssl'); if ($ssl['enable']) { $this->mysqli->ssl_set($ssl['key'], $ssl['cert'], $ssl['ca'], null, null); } $this->mysqli->set_charset($this->charset); $stmt = $this->mysqli->prepare('SET SESSION sql_mode = "TRADITIONAL"'); $stmt->execute(); $stmt = $this->mysqli->prepare('SET FOREIGN_KEY_CHECKS = 0'); $stmt->execute(); $settingsService = new SettingsService(new SettingsStorage()); if ($settingsService->getSetting('db', 'pdoBigSelect')) { $stmt = $this->mysqli->prepare('SET SQL_BIG_SELECTS = 1'); $stmt->execute(); } $this->statement = new Statement($this->mysqli, $this->result, $this->query); $this->handler = $this; } /** * @param string $query * * @return mixed */ public function query($query) { $this->result->setValue($this->mysqli->query($query)); return $this->statement; } /** * @param string $query * * @return mixed */ public function prepare($query) { $this->query->setValue($query); return $this->statement; } /** * * @return mixed */ public function lastInsertId() { return $this->mysqli->insert_id; } /** * * @return mixed */ public function beginTransaction() { return $this->mysqli->begin_transaction(); } /** * @return bool */ public function commit() { return $this->mysqli->commit(); } /** * @return bool */ public function rollback() { return $this->mysqli->rollback(); } } DB/MySQLi/Result.php 0000666 00000000673 15165376447 0010172 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\DB\MySQLi; /** * Class Result * * @package AmeliaBooking\Infrastructure\DB\MySQLi */ class Result { private $value; /** * @param string $value * * @return mixed */ public function setValue($value) { $this->value = $value; } /** * * @return mixed */ public function getValue() { return $this->value; } } DB/MySQLi/Statement.php 0000666 00000005602 15165376447 0010655 0 ustar 00 <?php namespace AmeliaBooking\Infrastructure\DB\MySQLi; use AmeliaBooking\Infrastructure\Common\Exceptions\QueryExecutionException; use mysqli; /** * Class Statement * * @package AmeliaBooking\Infrastructure\DB\MySQLi */ class Statement { /** @var mysqli $mysqli */ private $mysqli; /** @var Query $query */ private $query; /** @var Result $result */ private $result; /** @var array $params */ private $params = []; /** * @param mysqli $mysqli * @param Result $result * @param Query $query */ public function __construct($mysqli, $result, $query) { $this->mysqli = $mysqli; $this->result = $result; $this->query = $query; } /** * * @return mixed */ public function fetch() { return $this->result->getValue()->fetch_assoc(); } /** * * @return mixed */ public function fetchAll() { $rows = []; while ($row = $this->result->getValue()->fetch_assoc()) { $rows[] = $row; } return $rows; } /** * * @return mixed */ public function rowCount() { return $this->result->getValue()->num_rows; } /** * @param array $params * * @return mixed */ public function execute($params = []) { $this->params = array_merge($this->params, $params); $paramsKeys = []; $paramsValues = []; $paramsTypes = []; foreach ($this->params as $key => $value) { $index = strpos($this->query->getValue(), $key); $paramsKeys[$index] = $key; $paramsValues[$index] = $value; $paramsTypes[$index] = gettype($this->params[$key])[0]; } usort($paramsKeys, function ($a, $b) { return strlen($b) - strlen($a); }); ksort($paramsValues); ksort($paramsTypes); $referencedQueryParams = []; foreach ($paramsValues as $key => &$value) { $referencedQueryParams[$key] = &$value; } $parsedQuery = str_replace($paramsKeys, '?', $this->query->getValue()); if ($stmt = $this->mysqli->prepare($parsedQuery)) { if ($referencedQueryParams) { call_user_func_array( array($stmt, 'bind_param'), array_merge([str_replace('N', 'i', implode('', $paramsTypes))], $referencedQueryParams) ); } $success = $stmt->execute(); $this->result->setValue($stmt->get_result()); } else { throw new \Exception(); } $this->params = []; return $stmt && $success; } /** * @param string $key * @param string $value * * @return mixed */ public function bindParam($key, $value) { $this->params[$key] = $value; } }
| ver. 1.4 |
Github
|
.
| PHP 5.4.45 | Generation time: 0.05 |
proxy
|
phpinfo
|
Settings