Example #1
0
 /**
  * Creates new order properly based on POST variable data.
  *
  * @param $id int Post ID to create object for.
  *
  * @return Entity
  */
 public function create($id)
 {
     $post = $this->wp->getPost($id);
     // Support for our own post types and "Publish" button.
     if (isset($_POST['original_post_status'])) {
         $post->post_status = $_POST['original_post_status'];
     }
     $order = $this->fetch($post);
     $data = array('updated_at' => time());
     if (isset($_POST['jigoshop_order']['status'])) {
         $order->setStatus($_POST['jigoshop_order']['status']);
     }
     if (isset($_POST['post_excerpt'])) {
         $data['customer_note'] = trim($_POST['post_excerpt']);
     }
     if (isset($_POST['jigoshop_order'])) {
         $data = array_merge($data, $_POST['jigoshop_order']);
     }
     $data['items'] = $this->getItems($id);
     if (isset($_POST['order']['shipping'])) {
         $data['shipping'] = array('method' => null, 'rate' => null, 'price' => -1);
         $method = $this->shippingService->get($_POST['order']['shipping']);
         if ($method instanceof MultipleMethod && isset($_POST['order']['shipping_rate'])) {
             $method->setShippingRate($_POST['order']['shipping_rate']);
             $data['shipping']['rate'] = $method->getShippingRate();
         }
         $data['shipping']['method'] = $method;
     }
     return $order = $this->wp->applyFilters('jigoshop\\factory\\order\\create', $this->fill($order, $data));
 }
Example #2
0
 public function ajaxChangeShippingMethod()
 {
     try {
         /** @var \Jigoshop\Entity\Order $order */
         $order = $this->orderService->find((int) $_POST['order']);
         if ($order->getId() === null) {
             throw new Exception(__('Order not found.', 'jigoshop'));
         }
         $shippingMethod = $this->shippingService->get($_POST['method']);
         if ($shippingMethod instanceof Shipping\MultipleMethod) {
             if (!isset($_POST['rate'])) {
                 throw new Exception(__('Method rate is required.', 'jigoshop'));
             }
             $shippingMethod->setShippingRate((int) $_POST['rate']);
         }
         $order->setShippingMethod($shippingMethod);
         $order = $this->rebuildOrder($order);
         $this->orderService->save($order);
         $result = $this->getAjaxResponse($order);
     } catch (Exception $e) {
         $result = array('success' => false, 'error' => $e->getMessage());
     }
     echo json_encode($result);
     exit;
 }
Example #3
0
 private function getStateFromCheckout($state)
 {
     $state['customer_note'] = $_POST['jigoshop_order']['customer_note'];
     $state['billing_address'] = $_POST['jigoshop_order']['billing_address'];
     if ($_POST['jigoshop_order']['different_shipping_address'] == 'on') {
         $state['shipping_address'] = $_POST['jigoshop_order']['shipping_address'];
     } else {
         $state['shipping_address'] = $state['billing_address'];
     }
     if (isset($_POST['jigoshop_order']['payment_method'])) {
         $payment = $this->paymentService->get($_POST['jigoshop_order']['payment_method']);
         $this->wp->doAction('jigoshop\\service\\cart\\payment', $payment);
         $state['payment'] = $payment;
     }
     if (isset($_POST['jigoshop_order']['shipping_method'])) {
         $shipping = $this->shippingService->get($_POST['jigoshop_order']['shipping_method']);
         $this->wp->doAction('jigoshop\\service\\cart\\shipping', $shipping);
         $state['shipping'] = array('method' => $shipping, 'rate' => isset($_POST['jigoshop_order']['shipping_method_rate']) ? $_POST['jigoshop_order']['shipping_method_rate'] : null, 'price' => -1);
     }
     return $state;
 }
Example #4
0
 public function action()
 {
     if (isset($_REQUEST['action'])) {
         switch ($_REQUEST['action']) {
             case 'cancel_order':
                 if ($this->wp->getHelpers()->verifyNonce($_REQUEST['nonce'], 'cancel_order')) {
                     /** @var Order $order */
                     $order = $this->orderService->find((int) $_REQUEST['id']);
                     if ($order->getKey() != $_REQUEST['key']) {
                         $this->messages->addError(__('Invalid order key.', 'jigoshop'));
                         return;
                     }
                     if ($order->getStatus() != Status::PENDING) {
                         $this->messages->addError(__('Unable to cancel order.', 'jigoshop'));
                         return;
                     }
                     $order->setStatus(Status::CANCELLED);
                     $cart = $this->cartService->createFromOrder($this->cartService->getCartIdForCurrentUser(), $order);
                     $this->orderService->save($order);
                     $this->cartService->save($cart);
                     $this->messages->addNotice(__('The order has been cancelled', 'jigoshop'));
                 }
                 break;
             case 'update-shipping':
                 $customer = $this->customerService->getCurrent();
                 $this->updateCustomer($customer);
                 break;
             case 'checkout':
                 try {
                     $cart = $this->cartService->getCurrent();
                     // Update quantities
                     $this->updateQuantities($cart);
                     // Update customer (if needed)
                     if ($this->options->get('shipping.calculator')) {
                         $customer = $this->customerService->getCurrent();
                         $this->updateCustomer($customer);
                     }
                     if (isset($_POST['jigoshop_order']['shipping_method'])) {
                         // Select shipping method
                         $method = $this->shippingService->get($_POST['jigoshop_order']['shipping_method']);
                         $cart->setShippingMethod($method);
                     }
                     if ($cart->getShippingMethod() && !$cart->getShippingMethod()->isEnabled()) {
                         $cart->removeShippingMethod();
                         $this->messages->addWarning(__('Previous shipping method is unavailable. Please select different one.', 'jigoshop'));
                     }
                     if ($this->options->get('shopping.validate_zip')) {
                         $address = $cart->getCustomer()->getShippingAddress();
                         if ($address->getPostcode() && !Validation::isPostcode($address->getPostcode(), $address->getCountry())) {
                             throw new Exception(__('Postcode is not valid!', 'jigoshop'));
                         }
                     }
                     do_action('jigoshop\\cart\\before_checkout', $cart);
                     $this->cartService->save($cart);
                     $this->messages->preserveMessages();
                     $this->wp->redirectTo($this->options->getPageId(Pages::CHECKOUT));
                 } catch (Exception $e) {
                     $this->messages->addError(sprintf(__('Error occurred while updating cart: %s', 'jigoshop'), $e->getMessage()));
                 }
                 break;
             case 'update-cart':
                 if (isset($_POST['cart']) && is_array($_POST['cart'])) {
                     try {
                         $cart = $this->cartService->getCurrent();
                         $this->updateQuantities($cart);
                         $this->cartService->save($cart);
                         $this->messages->addNotice(__('Successfully updated the cart.', 'jigoshop'));
                     } catch (Exception $e) {
                         $this->messages->addError(sprintf(__('Error occurred while updating cart: %s', 'jigoshop'), $e->getMessage()));
                     }
                 }
         }
     }
     if (isset($_GET['action']) && isset($_GET['item']) && $_GET['action'] === 'remove-item' && is_numeric($_GET['item'])) {
         $cart = $this->cartService->getCurrent();
         $cart->removeItem((int) $_GET['item']);
         $this->cartService->save($cart);
         $this->messages->addNotice(__('Successfully removed item from cart.', 'jigoshop'), false);
     }
 }
Example #5
0
 /**
  * Migrates data from old format to new one.
  * @param array $orders
  * @return bool migration product status: success or not
  */
 public function migrate($orders)
 {
     $wpdb = $this->wp->getWPDB();
     //		Open transaction for save migration products
     $var_autocommit_sql = $wpdb->get_var("SELECT @@AUTOCOMMIT");
     try {
         $this->checkSql();
         $wpdb->query("SET AUTOCOMMIT=0");
         $this->checkSql();
         $wpdb->query("START TRANSACTION");
         $this->checkSql();
         // Register order status taxonomy to fetch old statuses
         $this->wp->registerTaxonomy('shop_order_status', array('shop_order'), array('hierarchical' => true, 'update_count_callback' => '_update_post_term_count', 'labels' => array('name' => __('Order statuses', 'jigoshop'), 'singular_name' => __('Order status', 'jigoshop'), 'search_items' => __('Search Order statuses', 'jigoshop'), 'all_items' => __('All  Order statuses', 'jigoshop'), 'parent_item' => __('Parent Order status', 'jigoshop'), 'parent_item_colon' => __('Parent Order status:', 'jigoshop'), 'edit_item' => __('Edit Order status', 'jigoshop'), 'update_item' => __('Update Order status', 'jigoshop'), 'add_new_item' => __('Add New Order status', 'jigoshop'), 'new_item_name' => __('New Order status Name', 'jigoshop')), 'public' => false, 'show_ui' => false, 'show_in_nav_menus' => false, 'query_var' => true, 'rewrite' => false));
         for ($i = 0, $endI = count($orders); $i < $endI;) {
             $order = $orders[$i];
             // Update central order data
             $status = $this->wp->getTheTerms($order->ID, 'shop_order_status');
             $this->checkSql();
             if (!empty($status)) {
                 $status = $this->_transformStatus($status[0]->slug);
             } else {
                 $status = Status::PENDING;
             }
             $query = $wpdb->prepare("UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d", $status, $order->ID);
             $wpdb->query($query);
             $this->checkSql();
             $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'number', $order->ID));
             $this->checkSql();
             $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'updated_at', time()));
             $this->checkSql();
             // Update columns
             do {
                 switch ($orders[$i]->meta_key) {
                     case '_js_completed_date':
                         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_key = %s, meta_value = %d WHERE meta_id = %d", 'completed_at', strtotime($orders[$i]->meta_value), $orders[$i]->meta_id));
                         $this->checkSql();
                         break;
                     case 'order_key':
                         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_key = %s WHERE meta_id = %d", 'key', $orders[$i]->meta_id));
                         $this->checkSql();
                         break;
                     case 'order_data':
                         $data = unserialize($orders[$i]->meta_value);
                         $data = $this->_fetchOrderData($data);
                         // Migrate customer
                         if ($this->customer == null) {
                             $customer = $this->wp->getPostMeta($order->ID, 'customer', true);
                             $this->customer = $customer;
                         }
                         $this->customer = $this->_migrateCustomer($this->customer, $data);
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'customer', serialize(serialize($this->customer))));
                         $this->checkSql();
                         // Migrate coupons
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'coupons', serialize($data['order_discount_coupons'])));
                         // TODO: HERE
                         $this->checkSql();
                         // Migrate shipping method
                         try {
                             $method = $this->shippingService->get($data['shipping_method']);
                             $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'shipping', serialize(array('method' => $method->getState(), 'price' => $data['order_shipping'], 'rate' => ''))));
                             $this->checkSql();
                         } catch (Exception $e) {
                             $this->messages->addWarning(sprintf(__('Shipping method "%s" not found. Order with ID "%d" has no shipping method now.'), $data['shipping_method'], $order->ID));
                         }
                         // Migrate payment method
                         try {
                             $method = $this->paymentService->get($data['payment_method']);
                             $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'payment', $method->getId()));
                             $this->checkSql();
                         } catch (Exception $e) {
                             $this->messages->addWarning(sprintf(__('Payment method "%s" not found. Order with ID "%d" has no payment method now.'), $data['payment_method'], $order->ID));
                         }
                         // Migrate order totals
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'subtotal', $data['order_subtotal']));
                         $this->checkSql();
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'discount', $data['order_discount']));
                         $this->checkSql();
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'total', $data['order_total']));
                         $this->checkSql();
                         // TODO: Add new meta for shipping total price
                         /*$wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)",
                               $order->ID,
                               'shipping',
                               $data['order_shipping']
                           ));
                           $this->checkSql();*/
                         break;
                     case 'customer_user':
                         if ($this->customer == null) {
                             $customer = $this->wp->getPostMeta($order->ID, 'customer', true);
                             if ($customer !== false) {
                                 /** @var Customer $customer */
                                 $customer = maybe_unserialize(maybe_unserialize($customer));
                                 if (!$customer) {
                                     $customer = new Customer();
                                 }
                             } else {
                                 $customer = new Customer();
                             }
                             $this->customer = $customer;
                         }
                         /** @var \WP_User $user */
                         if (($user = $this->wp->getUserBy('id', $orders[$i]->meta_value)) !== false) {
                             $this->checkSql();
                             $this->customer->setId($user->ID);
                             $this->customer->setLogin($user->get('login'));
                             $this->customer->setEmail($user->get('user_email'));
                             $this->customer->setName($user->get('display_name'));
                             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = %d WHERE post_id = %d AND meta_key = %s", serialize(serialize($this->customer)), $orders[$i]->meta_id, 'customer'));
                             $this->checkSql();
                             $userId = $orders[$i]->meta_value;
                         } else {
                             $userId = 0;
                             $guest = new Customer\Guest();
                             $guest->setBillingAddress($this->customer->getBillingAddress());
                             $guest->setShippingAddress($this->customer->getShippingAddress());
                             $this->customer = $guest;
                         }
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %d)", $order->ID, 'customer_id', $userId));
                         break;
                     case 'order_items':
                         $data = unserialize($orders[$i]->meta_value);
                         $globalTaxRate = 0.0;
                         foreach ($data as $itemData) {
                             /** @var Product $product */
                             $itemData = $this->_fetchItemData($itemData);
                             $product = null;
                             $productGetId = null;
                             if ($wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE ID = %d", $itemData['id'])) > 0) {
                                 $product = $this->productService->find($itemData['id']);
                                 $productGetId = $product->getId();
                             }
                             $tax = 0.0;
                             $taxRate = 0;
                             if ($itemData['qty'] == 0) {
                                 $itemData['qty'] = 1;
                             }
                             $price = $itemData['cost'] / $itemData['qty'];
                             if (!empty($itemData['taxrate']) && $itemData['taxrate'] > 0) {
                                 $tax = $price * $itemData['taxrate'] / 100;
                                 $taxRate = $itemData['taxrate'];
                             } else {
                                 if (isset($itemData['cost_inc_tax']) && $itemData['cost'] < $itemData['cost_inc_tax']) {
                                     $tax = ($itemData['cost_inc_tax'] - $itemData['cost']) / $itemData['qty'];
                                     $taxRate = $tax / $itemData['cost'];
                                 }
                             }
                             $globalTaxRate += $taxRate;
                             $productGetType = false;
                             if ($productGetId == null) {
                                 if (isset($itemData['variation_id']) && !empty($itemData['variation_id'])) {
                                     $productGetType = Product\Variable::TYPE;
                                 } else {
                                     $productGetType = Product\Simple::TYPE;
                                 }
                             } else {
                                 $productGetType = $product->getType();
                             }
                             $insertOrderData = array('order_id' => $order->ID, 'product_type' => $productGetType, 'title' => $itemData['name'], 'price' => $price, 'tax' => $tax, 'quantity' => $itemData['qty'], 'cost' => $itemData['cost']);
                             if ($productGetId != null) {
                                 $insertOrderData['product_id'] = $productGetId;
                             }
                             $wpdb->insert($wpdb->prefix . 'jigoshop_order_item', $insertOrderData);
                             $this->checkSql();
                             $itemId = $wpdb->insert_id;
                             if (isset($itemData['variation_id']) && !empty($itemData['variation_id']) && ($productGetId == null || $product instanceof Product\Variable)) {
                                 $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}jigoshop_order_item_meta (item_id, meta_key, meta_value) VALUES (%d, %s, %s)", $itemId, 'variation_id', $itemData['variation_id']));
                                 $this->checkSql();
                                 if ($productGetId !== null) {
                                     /** @var Product\Variable\Variation $variationProduct */
                                     /** @var Product\Variable $product */
                                     $variationProduct = $product->getVariation($itemData['variation_id']);
                                     if (is_array($itemData['variation']) && $variationProduct && $variationProduct instanceof Product\Variable\Variation) {
                                         foreach ($itemData['variation'] as $variation => $variationValue) {
                                             $variation = str_replace('tax_', '', $variation);
                                             $attribute = $this->getAttribute($variationProduct, $variation);
                                             if ($attribute === null) {
                                                 $this->messages->addWarning(sprintf(__('Attribute "%s" not found for variation ID "%d".', 'jigoshop'), $variation, $variationProduct->getId()));
                                                 continue;
                                             }
                                             $option = $this->getAttributeOption($attribute, $variationValue);
                                             if ($option === null) {
                                                 $this->messages->addWarning(sprintf(__('Attribute "%s" option "%s" not found for variation ID "%d".', 'jigoshop'), $variation, $variationValue, $variationProduct->getId()));
                                                 continue;
                                             }
                                             $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}jigoshop_order_item_meta (item_id, meta_key, meta_value) VALUES (%d, %s, %s)", $itemId, $attribute->getAttribute()->getId(), $option->getId()));
                                             $this->checkSql();
                                         }
                                     }
                                 }
                             }
                         }
                         $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}jigoshop_order_tax (order_id, label, tax_class, rate, is_compound) VALUES (%d, %s, %s, %d, %d)", $order->ID, __('Standard', 'jigoshop'), 'standard', $globalTaxRate / (count($data) == 0 ? 1 : count($data)), false));
                         $this->checkSql();
                         break;
                 }
                 $i++;
             } while ($i < $endI && $orders[$i]->ID == $order->ID);
         }
         //		    commit sql transation and restore value of autocommit
         $wpdb->query("COMMIT");
         $wpdb->query("SET AUTOCOMMIT=" . $var_autocommit_sql);
         return true;
     } catch (Exception $e) {
         //		    rollback sql transation and restore value of autocommit
         if (WP_DEBUG) {
             \Monolog\Registry::getInstance(JIGOSHOP_LOGGER)->addDebug($e);
         }
         $wpdb->query("ROLLBACK");
         $wpdb->query("SET AUTOCOMMIT=" . $var_autocommit_sql);
         Migration::saveLog(__('Migration orders end with error: ', 'jigoshop') . $e);
         return false;
     }
 }