/**
  * @param $request
  * @return AB_Query
  */
 public function createQuery($request)
 {
     $query = AB_Payment::query()->select('r.*, c.name customer, st.full_name provider, s.title service, ca.coupon_code coupon, a.start_date')->leftJoin('AB_CustomerAppointment', 'ca', 'ca.id = r.customer_appointment_id')->leftJoin('AB_Customer', 'c', 'c.id = ca.customer_id')->leftJoin('AB_Appointment', 'a', 'a.id = ca.appointment_id')->leftJoin('AB_Service', 's', 's.id = a.service_id')->leftJoin('AB_Staff', 'st', 'st.id = a.staff_id');
     if (isset($request['type']) && $request['type'] != -1) {
         $query->where('r.type', $request['type']);
     }
     if (isset($request['customer']) && $request['customer'] != -1) {
         $query->where('c.name', $request['customer']);
     }
     if (isset($request['provider']) && $request['provider'] != -1) {
         $query->where('st.full_name', $request['provider']);
     }
     if (isset($request['service']) && $request['service'] != -1) {
         $query->where('s.title', $request['service']);
     }
     if (isset($request['range']) && !empty($request['range'])) {
         $dates = explode(' - ', $request['range'], 2);
         $start_date_timestamp = strtotime($dates[0]);
         $end_date_timestamp = strtotime($dates[1]);
         $start = date('Y-m-d', $start_date_timestamp);
         $end = date('Y-m-d', strtotime('+1 day', $end_date_timestamp));
         $query->whereBetween('r.created', $start, $end);
     }
     if (!empty($request['sort_order']) && in_array($request['order_by'], array('created', 'type', 'customer', 'provider', 'service', 'total', 'start_date', 'coupon'))) {
         $query->sortBy($request['order_by'])->order($request['sort_order'] == 'desc' ? AB_Query::ORDER_DESCENDING : AB_Query::ORDER_ASCENDING);
     }
     return $query;
 }
 /**
  * Do AIM payment.
  */
 public function executeAuthorizeNetAIM()
 {
     include_once AB_PATH . '/lib/payment/authorize.net/autoload.php';
     $response = null;
     $userData = new AB_UserBookingData($this->getParameter('form_id'));
     if ($userData->load()) {
         define("AUTHORIZENET_API_LOGIN_ID", get_option('ab_authorizenet_api_login_id'));
         define("AUTHORIZENET_TRANSACTION_KEY", get_option('ab_authorizenet_transaction_key'));
         define("AUTHORIZENET_SANDBOX", (bool) get_option('ab_authorizenet_sandbox'));
         $price = $userData->getFinalServicePrice() * $userData->get('number_of_persons');
         $sale = new AuthorizeNetAIM();
         $sale->amount = $price;
         $sale->card_num = $this->getParameter('ab_card_number');
         $sale->card_code = $this->getParameter('ab_card_code');
         $sale->exp_date = $this->getParameter('ab_card_month') . '/' . $this->getParameter('ab_card_year');
         $sale->first_name = $userData->get('name');
         $sale->email = $userData->get('email');
         $sale->phone = $userData->get('phone');
         $response = $sale->authorizeAndCapture();
         if ($response->approved) {
             /** @var AB_Appointment $appointment */
             $appointment = $userData->save();
             $customer_appointment = new AB_CustomerAppointment();
             $customer_appointment->loadBy(array('appointment_id' => $appointment->get('id'), 'customer_id' => $userData->getCustomerId()));
             $payment = new AB_Payment();
             $payment->set('total', $price);
             $payment->set('type', 'authorizeNet');
             $payment->set('customer_appointment_id', $customer_appointment->get('id'));
             $payment->set('created', current_time('mysql'));
             $payment->save();
             $response = array('state' => 'success');
         } else {
             $response = array('status' => 'error', 'error' => $response->response_reason_text);
         }
     } else {
         $response = array('status' => 'error', 'error' => __('Session error.', 'bookly'));
     }
     wp_send_json($response);
 }
 public function executeStripe()
 {
     $response = null;
     $userData = new AB_UserBookingData($this->getParameter('form_id'));
     if ($userData->load()) {
         if ($userData->get('service_id')) {
             Stripe::setApiKey(get_option('ab_stripe_secret_key'));
             Stripe::setApiVersion("2014-10-07");
             $price = $userData->getFinalServicePrice() * $userData->get('number_of_persons');
             $stripe_data = array('number' => $this->getParameter('ab_card_number'), 'exp_month' => $this->getParameter('ab_card_month'), 'exp_year' => $this->getParameter('ab_card_year'), 'cvc' => $this->getParameter('ab_card_code'));
             try {
                 $charge = Stripe_Charge::create(array('card' => $stripe_data, 'amount' => intval($price * 100), 'currency' => get_option('ab_paypal_currency'), 'description' => "Charge for " . $userData->get('email')));
                 if ($charge->paid) {
                     $appointment = $userData->save();
                     $customer_appointment = new AB_CustomerAppointment();
                     $customer_appointment->loadBy(array('appointment_id' => $appointment->get('id'), 'customer_id' => $userData->getCustomerId()));
                     $payment = new AB_Payment();
                     $payment->set('total', $price);
                     $payment->set('type', 'stripe');
                     $payment->set('customer_appointment_id', $customer_appointment->get('id'));
                     $payment->set('created', current_time('mysql'));
                     $payment->save();
                     $response = array('status' => 'success');
                 } else {
                     $response = array('status' => 'error', 'error' => 'unknown error');
                 }
             } catch (Exception $e) {
                 $response = array('status' => 'error', 'error' => $e->getMessage());
             }
         }
     } else {
         $response = array('status' => 'error', 'error' => __('Session error.', 'bookly'));
     }
     // Output JSON response.
     wp_send_json($response);
 }
Example #4
0
 /**
  * Save all data and create appointment.
  *
  * @return AB_Appointment
  */
 public function save()
 {
     $user_id = get_current_user_id();
     $customer = new AB_Customer();
     if ($user_id) {
         // Try to find customer by WP user ID.
         $customer->loadBy(array('wp_user_id' => $user_id));
     }
     if (!$customer->isLoaded()) {
         // If customer with such name & e-mail exists, append new booking to him, otherwise - create new customer
         $customer->loadBy(array('name' => $this->get('name'), 'email' => $this->get('email')));
     }
     $customer->set('name', $this->get('name'));
     $customer->set('email', $this->get('email'));
     $customer->set('phone', $this->get('phone'));
     if (get_option('ab_settings_create_account', 0) && !$customer->get('wp_user_id')) {
         // Create WP user and link it to customer.
         $customer->setWPUser($user_id ?: null);
     }
     $customer->save();
     $this->customer_id = $customer->get('id');
     $service = $this->getService();
     /**
      * Get appointment, with same params.
      * If it is -> create connection to this appointment,
      * otherwise create appointment and connect customer to new appointment
      */
     $appointment = new AB_Appointment();
     $appointment->loadBy(array('staff_id' => $this->getStaffId(), 'service_id' => $this->get('service_id'), 'start_date' => $this->get('appointment_datetime')));
     if ($appointment->isLoaded() == false) {
         $appointment->set('staff_id', $this->getStaffId());
         $appointment->set('service_id', $this->get('service_id'));
         $appointment->set('start_date', $this->get('appointment_datetime'));
         $endDate = new DateTime($this->get('appointment_datetime'));
         $di = "+ {$service->get('duration')} sec";
         $endDate->modify($di);
         $appointment->set('end_date', $endDate->format('Y-m-d H:i:s'));
         $appointment->save();
     }
     $customer_appointment = new AB_CustomerAppointment();
     $customer_appointment->loadBy(array('customer_id' => $customer->get('id'), 'appointment_id' => $appointment->get('id')));
     if ($customer_appointment->isLoaded()) {
         // Add number of persons to existing booking.
         $customer_appointment->set('number_of_persons', $customer_appointment->get('number_of_persons') + $this->get('number_of_persons'));
     } else {
         $customer_appointment->set('customer_id', $customer->get('id'));
         $customer_appointment->set('appointment_id', $appointment->get('id'));
         $customer_appointment->set('number_of_persons', $this->get('number_of_persons'));
     }
     $customer_appointment->set('custom_fields', $this->get('custom_fields'));
     $customer_appointment->set('time_zone_offset', $this->get('time_zone_offset'));
     $coupon = $this->getCoupon();
     if ($coupon) {
         $customer_appointment->set('coupon_code', $coupon->get('code'));
         $customer_appointment->set('coupon_discount', $coupon->get('discount'));
         $customer_appointment->set('coupon_deduction', $coupon->get('deduction'));
         $coupon->claim();
         $coupon->save();
     }
     $customer_appointment->save();
     // Create fake payment record for 100% discount coupons.
     if ($coupon && $coupon->get('discount') == '100') {
         $payment = new AB_Payment();
         $payment->set('total', '0.00');
         $payment->set('type', 'coupon');
         $payment->set('created', current_time('mysql'));
         $payment->set('customer_appointment_id', $customer_appointment->get('id'));
         $payment->save();
     }
     // Google Calendar.
     $appointment->handleGoogleCalendar();
     // Send email notifications.
     AB_NotificationSender::send(AB_NotificationSender::INSTANT_NEW_APPOINTMENT, $customer_appointment);
     return $appointment;
 }
 /**
  * Process the Express Checkout RETURNURL
  */
 public function paypalResponseSuccess()
 {
     $form_id = $_GET['ab_fid'];
     $paypal = new AB_PayPal();
     if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
         $token = $_GET["token"];
         $payer_id = $_GET["PayerID"];
         // send the request to PayPal
         $response = $paypal->sendNvpRequest('GetExpressCheckoutDetails', sprintf('&TOKEN=%s', $token));
         if (strtoupper($response["ACK"]) == "SUCCESS") {
             $data = sprintf('&TOKEN=%s&PAYERID=%s&PAYMENTREQUEST_0_PAYMENTACTION=Sale', $token, $payer_id);
             // response keys containing useful data to send via DoExpressCheckoutPayment operation
             $response_data_keys_pattern = sprintf('/^(%s)/', implode('|', array('PAYMENTREQUEST_0_AMT', 'PAYMENTREQUEST_0_ITEMAMT', 'PAYMENTREQUEST_0_CURRENCYCODE', 'L_PAYMENTREQUEST_0')));
             foreach ($response as $key => $value) {
                 // collect product data from response using defined response keys
                 if (preg_match($response_data_keys_pattern, $key)) {
                     $data .= sprintf('&%s=%s', $key, $value);
                 }
             }
             //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
             $response = $paypal->sendNvpRequest('DoExpressCheckoutPayment', $data);
             if ("SUCCESS" == strtoupper($response["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($response["ACK"])) {
                 // get transaction info
                 $response = $paypal->sendNvpRequest('GetTransactionDetails', "&TRANSACTIONID=" . urlencode($response["PAYMENTINFO_0_TRANSACTIONID"]));
                 if ("SUCCESS" == strtoupper($response["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($response["ACK"])) {
                     // need session to get Total and Token
                     $token = $_SESSION['bookly'][$form_id]['paypal_response'][0]['TOKEN'];
                     $userData = new AB_UserBookingData($form_id);
                     $userData->load();
                     if ($userData->get('service_id')) {
                         $appointment = $userData->save();
                         $customer_appointment = new AB_CustomerAppointment();
                         $customer_appointment->loadBy(array('appointment_id' => $appointment->get('id'), 'customer_id' => $userData->getCustomerId()));
                         $payment = new AB_Payment();
                         $payment->set('token', urldecode($token));
                         $payment->set('total', $userData->getFinalServicePrice() * $userData->get('number_of_persons'));
                         $payment->set('customer_appointment_id', $customer_appointment->get('id'));
                         $payment->set('transaction', urlencode($response["TRANSACTIONID"]));
                         $payment->set('created', current_time('mysql'));
                         $payment->save();
                         $userData->setPayPalStatus('success');
                     }
                     @wp_redirect(remove_query_arg(array('action', 'token', 'PayerID', 'ab_fid'), AB_Utils::getCurrentPageURL()));
                     exit(0);
                 } else {
                     header('Location: ' . wp_sanitize_redirect(add_query_arg(array('action' => 'ab-paypal-errorurl', 'ab_fid' => $form_id, 'error_msg' => $response["L_LONGMESSAGE0"]), AB_Utils::getCurrentPageURL())));
                     exit;
                 }
             } else {
                 header('Location: ' . wp_sanitize_redirect(add_query_arg(array('action' => 'ab-paypal-errorurl', 'ab_fid' => $form_id, 'error_msg' => $response["L_LONGMESSAGE0"]), AB_Utils::getCurrentPageURL())));
                 exit;
             }
         } else {
             header('Location: ' . wp_sanitize_redirect(add_query_arg(array('action' => 'ab-paypal-errorurl', 'ab_fid' => $form_id, 'error_msg' => 'Invalid token provided'), AB_Utils::getCurrentPageURL())));
             exit;
         }
     } else {
         throw new Exception('Token parameter not found!');
     }
 }
Example #6
0
 function update_7_0()
 {
     global $wpdb;
     $wpdb->query('ALTER TABLE `ab_customer_appointment` ADD `coupon_deduction` DECIMAL(10,2) DEFAULT NULL AFTER `coupon_discount`');
     $wpdb->query('ALTER TABLE `ab_coupons` CHANGE COLUMN `used` `used` INT UNSIGNED NOT NULL DEFAULT 0,
                    ADD COLUMN `deduction` DECIMAL(10,2) NOT NULL DEFAULT 0 AFTER `discount`,
                    ADD COLUMN `usage_limit` INT UNSIGNED NOT NULL DEFAULT 1');
     $wpdb->query('ALTER TABLE `ab_notifications` CHANGE `slug` `type` VARCHAR(255) NOT NULL DEFAULT ""');
     // SMS.
     $wpdb->query('ALTER TABLE `ab_notifications` ADD `gateway` ENUM("email","sms") NOT NULL DEFAULT "email"');
     $wpdb->query('UPDATE `ab_notifications` SET `gateway` = "email"');
     $sms_notifies = array(array('type' => 'client_new_appointment', 'message' => __("Dear [[CLIENT_NAME]].\nThis is confirmation that you have booked [[SERVICE_NAME]].\nWe are waiting you at [[COMPANY_ADDRESS]] on [[APPOINTMENT_DATE]] at [[APPOINTMENT_TIME]].\nThank you for choosing our company.\n[[COMPANY_NAME]]\n[[COMPANY_PHONE]]\n[[COMPANY_WEBSITE]]", 'bookly'), 'active' => 1), array('type' => 'staff_new_appointment', 'message' => __("Hello.\nYou have new booking.\nService: [[SERVICE_NAME]]\nDate: [[APPOINTMENT_DATE]]\nTime: [[APPOINTMENT_TIME]]\nClient name: [[CLIENT_NAME]]\nClient phone: [[CLIENT_PHONE]]\nClient email: [[CLIENT_EMAIL]]", 'bookly'), 'active' => 0), array('type' => 'client_reminder', 'message' => __("Dear [[CLIENT_NAME]].\nWe would like to remind you that you have booked [[SERVICE_NAME]] tomorrow on [[APPOINTMENT_TIME]]. We are waiting you at [[COMPANY_ADDRESS]].\nThank you for choosing our company.\n[[COMPANY_NAME]]\n[[COMPANY_PHONE]]\n[[COMPANY_WEBSITE]]", 'bookly'), 'active' => 0), array('type' => 'client_follow_up', 'message' => __("Dear [[CLIENT_NAME]].\nThank you for choosing [[COMPANY_NAME]]. We hope you were satisfied with your [[SERVICE_NAME]].\nThank you and we look forward to seeing you again soon.\n[[COMPANY_NAME]]\n[[COMPANY_PHONE]]\n[[COMPANY_WEBSITE]]", 'bookly'), 'active' => 0), array('type' => 'staff_agenda', 'message' => __("Hello.\nYour agenda for tomorrow is:\n[[NEXT_DAY_AGENDA]]", 'bookly'), 'active' => 0), array('type' => 'staff_cancelled_appointment', 'message' => __("Hello.\nThe following booking has been cancelled.\nService: [[SERVICE_NAME]]\nDate: [[APPOINTMENT_DATE]]\nTime: [[APPOINTMENT_TIME]]\nClient name: [[CLIENT_NAME]]\nClient phone: [[CLIENT_PHONE]]\nClient email: [[CLIENT_EMAIL]]", 'bookly'), 'active' => 0), array('type' => 'client_new_wp_user', 'message' => __("Hello.\nAn account was created for you at [[SITE_ADDRESS]]\nYour user details:\nuser: [[NEW_USERNAME]]\npassword: [[NEW_PASSWORD]]\n\nThanks.", 'bookly'), 'active' => 1));
     // Insert notifications.
     foreach ($sms_notifies as $data) {
         $wpdb->insert('ab_notifications', array('gateway' => 'sms', 'type' => $data['type'], 'subject' => '', 'message' => $data['message'], 'active' => $data['active']));
     }
     // Rename notifications.
     $notifications = array('client_info' => 'client_new_appointment', 'provider_info' => 'staff_new_appointment', 'evening_next_day' => 'client_reminder', 'evening_after' => 'client_follow_up', 'event_next_day' => 'staff_agenda', 'cancel_appointment' => 'staff_cancelled_appointment', 'new_wp_user' => 'client_new_wp_user');
     foreach ($notifications as $from => $to) {
         $wpdb->query("UPDATE `ab_notifications` SET `type` = '{$to}' WHERE `type` = '{$from}'");
     }
     $this->drop('ab_email_notification');
     // Rename tables.
     $ab_tables = array('ab_appointment' => AB_Appointment::getTableName(), 'ab_category' => AB_Category::getTableName(), 'ab_coupons' => AB_Coupon::getTableName(), 'ab_customer' => AB_Customer::getTableName(), 'ab_customer_appointment' => AB_CustomerAppointment::getTableName(), 'ab_holiday' => AB_Holiday::getTableName(), 'ab_notifications' => AB_Notification::getTableName(), 'ab_payment' => AB_Payment::getTableName(), 'ab_schedule_item_break' => AB_ScheduleItemBreak::getTableName(), 'ab_service' => AB_Service::getTableName(), 'ab_staff' => AB_Staff::getTableName(), 'ab_staff_schedule_item' => AB_StaffScheduleItem::getTableName(), 'ab_staff_service' => AB_StaffService::getTableName());
     foreach ($ab_tables as $from => $to) {
         $wpdb->query("ALTER TABLE `{$from}` RENAME TO `{$to}`");
     }
     $wpdb->query("CREATE TABLE IF NOT EXISTS  `" . AB_SentNotification::getTableName() . "` (\n                `id`                      INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n                `customer_appointment_id` INT UNSIGNED,\n                `staff_id`                INT UNSIGNED,\n                `gateway`                 ENUM('email','sms') NOT NULL DEFAULT 'email',\n                `type`                    VARCHAR(60) NOT NULL,\n                `created`                 DATETIME NOT NULL,\n                CONSTRAINT fk_" . AB_SentNotification::getTableName() . "_" . AB_CustomerAppointment::getTableName() . "_id\n                    FOREIGN KEY (customer_appointment_id)\n                    REFERENCES  " . AB_CustomerAppointment::getTableName() . "(id)\n                    ON DELETE   CASCADE\n                    ON UPDATE   CASCADE,\n                CONSTRAINT fk_" . AB_SentNotification::getTableName() . "_" . AB_Staff::getTableName() . "_id\n                    FOREIGN KEY (staff_id)\n                    REFERENCES  " . AB_Staff::getTableName() . "(id)\n                    ON DELETE   CASCADE\n                    ON UPDATE   CASCADE\n              ) ENGINE = INNODB\n              DEFAULT CHARACTER SET = utf8\n              COLLATE = utf8_general_ci");
     // Google Calendar.
     add_option('ab_settings_google_event_title', '[[SERVICE_NAME]]');
     // Link assets.
     add_option('ab_settings_link_assets_method', 'enqueue');
     // SMS.
     add_option('ab_sms_default_country_code', '');
 }
Example #7
0
 private function _drop_tables()
 {
     /** @var wpdb $wpdb */
     global $wpdb;
     $ab_tables = array(AB_Appointment::getTableName(), AB_Category::getTableName(), AB_Coupon::getTableName(), AB_Customer::getTableName(), AB_CustomerAppointment::getTableName(), AB_Holiday::getTableName(), AB_Notification::getTableName(), AB_Payment::getTableName(), AB_ScheduleItemBreak::getTableName(), AB_SentNotification::getTableName(), AB_Service::getTableName(), AB_Staff::getTableName(), AB_StaffScheduleItem::getTableName(), AB_StaffService::getTableName());
     $this->_drop_fk($ab_tables);
     $wpdb->query('DROP TABLE IF EXISTS `' . implode('`, `', $ab_tables) . '` CASCADE;');
 }