/**
  * Edit an order
  *
  * @since 2.2
  * @param int $id the order ID
  * @param array $data
  * @return array
  */
 public function edit_order($id, $data)
 {
     try {
         if (!isset($data['order'])) {
             throw new WC_API_Exception('woocommerce_api_missing_order_data', sprintf(__('No %1$s data specified to edit %1$s', 'woocommerce'), 'order'), 400);
         }
         $data = $data['order'];
         $update_totals = false;
         $id = $this->validate_request($id, $this->post_type, 'edit');
         if (is_wp_error($id)) {
             return $id;
         }
         $data = apply_filters('woocommerce_api_edit_order_data', $data, $id, $this);
         $order = wc_get_order($id);
         if (empty($order)) {
             throw new WC_API_Exception('woocommerce_api_invalid_order_id', __('Order ID is invalid', 'woocommerce'), 400);
         }
         $order_args = array('order_id' => $order->get_id());
         // Customer note.
         if (isset($data['note'])) {
             $order_args['customer_note'] = $data['note'];
         }
         // Customer ID.
         if (isset($data['customer_id']) && $data['customer_id'] != $order->get_user_id()) {
             // Make sure customer exists.
             if (false === get_user_by('id', $data['customer_id'])) {
                 throw new WC_API_Exception('woocommerce_api_invalid_customer_id', __('Customer ID is invalid', 'woocommerce'), 400);
             }
             update_post_meta($order->get_id(), '_customer_user', $data['customer_id']);
         }
         // Billing/shipping address.
         $this->set_order_addresses($order, $data);
         $lines = array('line_item' => 'line_items', 'shipping' => 'shipping_lines', 'fee' => 'fee_lines', 'coupon' => 'coupon_lines');
         foreach ($lines as $line_type => $line) {
             if (isset($data[$line]) && is_array($data[$line])) {
                 $update_totals = true;
                 foreach ($data[$line] as $item) {
                     // Item ID is always required.
                     if (!array_key_exists('id', $item)) {
                         $item['id'] = null;
                     }
                     // Create item.
                     if (is_null($item['id'])) {
                         $this->set_item($order, $line_type, $item, 'create');
                     } elseif ($this->item_is_null($item)) {
                         // Delete item.
                         wc_delete_order_item($item['id']);
                     } else {
                         // Update item.
                         $this->set_item($order, $line_type, $item, 'update');
                     }
                 }
             }
         }
         // Payment method (and payment_complete() if `paid` == true and order needs payment).
         if (isset($data['payment_details']) && is_array($data['payment_details'])) {
             // Method ID.
             if (isset($data['payment_details']['method_id'])) {
                 update_post_meta($order->get_id(), '_payment_method', $data['payment_details']['method_id']);
             }
             // Method title.
             if (isset($data['payment_details']['method_title'])) {
                 update_post_meta($order->get_id(), '_payment_method_title', $data['payment_details']['method_title']);
             }
             // Mark as paid if set.
             if ($order->needs_payment() && isset($data['payment_details']['paid']) && true === $data['payment_details']['paid']) {
                 $order->payment_complete(isset($data['payment_details']['transaction_id']) ? $data['payment_details']['transaction_id'] : '');
             }
         }
         // Set order currency.
         if (isset($data['currency'])) {
             if (!array_key_exists($data['currency'], get_woocommerce_currencies())) {
                 throw new WC_API_Exception('woocommerce_invalid_order_currency', __('Provided order currency is invalid', 'woocommerce'), 400);
             }
             update_post_meta($order->get_id(), '_order_currency', $data['currency']);
         }
         // If items have changed, recalculate order totals.
         if ($update_totals) {
             $order->calculate_totals();
         }
         // Update order meta.
         if (isset($data['order_meta']) && is_array($data['order_meta'])) {
             $this->set_order_meta($order->get_id(), $data['order_meta']);
         }
         // Update the order post to set customer note/modified date.
         wc_update_order($order_args);
         // Order status.
         if (!empty($data['status'])) {
             $order->update_status($data['status'], isset($data['status_note']) ? $data['status_note'] : '', true);
         }
         wc_delete_shop_order_transients($order->get_id());
         do_action('woocommerce_api_edit_order', $order->get_id(), $data, $this);
         return $this->get_order($id);
     } catch (WC_Data_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => 400));
     } catch (WC_API_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
 /**
  * Update order.
  *
  * @param WP_REST_Request $request Full details about the request.
  * @param WP_Post $post Post data.
  * @return int|WP_Error
  */
 protected function update_order($request, $post)
 {
     try {
         $update_totals = false;
         $order = wc_get_order($post);
         $order_args = array('order_id' => $order->id);
         // Customer note.
         if (isset($request['customer_note'])) {
             $order_args['customer_note'] = $request['customer_note'];
         }
         // Customer ID.
         if (isset($request['customer_id']) && $request['customer_id'] != $order->get_user_id()) {
             // Make sure customer exists.
             if (false === get_user_by('id', $request['customer_id'])) {
                 throw new WC_REST_Exception('woocommerce_rest_invalid_customer_id', __('Customer ID is invalid.', 'woocommerce'), 400);
             }
             update_post_meta($order->id, '_customer_user', $request['customer_id']);
         }
         // Update addresses.
         if (is_array($request['billing'])) {
             $this->update_address($order, $request['billing'], 'billing');
         }
         if (is_array($request['shipping'])) {
             $this->update_address($order, $request['shipping'], 'shipping');
         }
         $lines = array('line_item' => 'line_items', 'shipping' => 'shipping_lines', 'fee' => 'fee_lines', 'coupon' => 'coupon_lines');
         foreach ($lines as $line_type => $line) {
             if (isset($request[$line]) && is_array($request[$line])) {
                 $update_totals = true;
                 foreach ($request[$line] as $item) {
                     // Item ID is always required.
                     if (!array_key_exists('id', $item)) {
                         throw new WC_REST_Exception('woocommerce_rest_invalid_item_id', __('Order item ID is required.', 'woocommerce'), 400);
                     }
                     // Create item.
                     if (is_null($item['id'])) {
                         $this->set_item($order, $line_type, $item, 'create');
                     } elseif ($this->item_is_null($item)) {
                         // Delete item.
                         wc_delete_order_item($item['id']);
                     } else {
                         // Update item.
                         $this->set_item($order, $line_type, $item, 'update');
                     }
                 }
             }
         }
         // Set payment method.
         if (!empty($request['payment_method'])) {
             update_post_meta($order->id, '_payment_method', $request['payment_method']);
         }
         if (!empty($request['payment_method_title'])) {
             update_post_meta($order->id, '_payment_method_title', $request['payment_method']);
         }
         if ($order->needs_payment() && isset($request['set_paid']) && true === $request['set_paid']) {
             $order->payment_complete(!empty($request['transaction_id']) ? $request['transaction_id'] : '');
         }
         // Set order currency.
         if (isset($request['currency'])) {
             update_post_meta($order->id, '_order_currency', $request['currency']);
         }
         // If items have changed, recalculate order totals.
         if ($update_totals) {
             $order->calculate_totals();
         }
         // Update meta data.
         if (!empty($request['meta_data']) && is_array($request['meta_data'])) {
             $this->update_meta_data($order->id, $request['meta_data']);
         }
         // Update the order post to set customer note/modified date.
         wc_update_order($order_args);
         // Order status.
         if (!empty($request['status'])) {
             $order->update_status($request['status'], isset($request['status_note']) ? $request['status_note'] : '');
         }
         return $order->id;
     } catch (WC_REST_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
 /**
  * Update an order.
  *
  * ## OPTIONS
  *
  * <id>
  * : Product ID
  *
  * [--<field>=<value>]
  * : One or more fields to update.
  *
  * ## AVAILABLE FIELDS
  *
  * For available fields, see: wp wc order create --help
  *
  * ## EXAMPLES
  *
  *    wp wc order update 123 --status=completed
  *
  * @todo  gedex
  * @since 2.5.0
  */
 public function update($args, $assoc_args)
 {
     try {
         $id = $args[0];
         $data = apply_filters('woocommerce_cli_update_order_data', $this->unflatten_array($assoc_args));
         $update_totals = false;
         $order = wc_get_order($id);
         if (empty($order)) {
             throw new WC_CLI_Exception('woocommerce_cli_invalid_order_id', __('Order ID is invalid', 'woocommerce'));
         }
         $order_args = array('order_id' => $order->id);
         // customer note
         if (isset($data['note'])) {
             $order_args['customer_note'] = $data['note'];
         }
         // order status
         if (!empty($data['status'])) {
             $order->update_status($data['status'], isset($data['status_note']) ? $data['status_note'] : '');
         }
         // customer ID
         if (isset($data['customer_id']) && $data['customer_id'] != $order->get_user_id()) {
             // make sure customer exists
             if (false === get_user_by('id', $data['customer_id'])) {
                 throw new WC_CLI_Exception('woocommerce_cli_invalid_customer_id', __('Customer ID is invalid', 'woocommerce'));
             }
             update_post_meta($order->id, '_customer_user', $data['customer_id']);
         }
         // billing/shipping address
         $this->set_order_addresses($order, $data);
         $lines = array('line_item' => 'line_items', 'shipping' => 'shipping_lines', 'fee' => 'fee_lines', 'coupon' => 'coupon_lines');
         foreach ($lines as $line_type => $line) {
             if (isset($data[$line]) && is_array($data[$line])) {
                 $update_totals = true;
                 foreach ($data[$line] as $item) {
                     // item ID is always required
                     if (!array_key_exists('id', $item)) {
                         throw new WC_CLI_Exception('woocommerce_invalid_item_id', __('Order item ID is required', 'woocommerce'));
                     }
                     // create item
                     if (is_null($item['id'])) {
                         $this->set_item($order, $line_type, $item, 'create');
                     } elseif ($this->item_is_null($item)) {
                         // delete item
                         wc_delete_order_item($item['id']);
                     } else {
                         // update item
                         $this->set_item($order, $line_type, $item, 'update');
                     }
                 }
             }
         }
         // payment method (and payment_complete() if `paid` == true and order needs payment)
         if (isset($data['payment_details']) && is_array($data['payment_details'])) {
             // method ID
             if (isset($data['payment_details']['method_id'])) {
                 update_post_meta($order->id, '_payment_method', $data['payment_details']['method_id']);
             }
             // method title
             if (isset($data['payment_details']['method_title'])) {
                 update_post_meta($order->id, '_payment_method_title', $data['payment_details']['method_title']);
             }
             // mark as paid if set
             if ($order->needs_payment() && isset($data['payment_details']['paid']) && $this->is_true($data['payment_details']['paid'])) {
                 $order->payment_complete(isset($data['payment_details']['transaction_id']) ? $data['payment_details']['transaction_id'] : '');
             }
         }
         // set order currency
         if (isset($data['currency'])) {
             if (!array_key_exists($data['currency'], get_woocommerce_currencies())) {
                 throw new WC_CLI_Exception('woocommerce_invalid_order_currency', __('Provided order currency is invalid', 'woocommerce'));
             }
             update_post_meta($order->id, '_order_currency', $data['currency']);
         }
         // set order number
         if (isset($data['order_number'])) {
             update_post_meta($order->id, '_order_number', $data['order_number']);
         }
         // if items have changed, recalculate order totals
         if ($update_totals) {
             $order->calculate_totals();
         }
         // update order meta
         if (isset($data['order_meta']) && is_array($data['order_meta'])) {
             $this->set_order_meta($order->id, $data['order_meta']);
         }
         // update the order post to set customer note/modified date
         wc_update_order($order_args);
         wc_delete_shop_order_transients($order->id);
         do_action('woocommerce_cli_update_order', $order->id, $data);
         WP_CLI::success("Updated order {$order->id}.");
     } catch (WC_CLI_Exception $e) {
         WP_CLI::error($e->getMessage());
     }
 }
 /**
  * Create an order. Error codes:
  * 		520 - Cannot insert order into the database.
  * 		521 - Cannot get order after creation.
  * 		522 - Cannot update order.
  * 		525 - Cannot create line item.
  * 		526 - Cannot create fee item.
  * 		527 - Cannot create shipping item.
  * 		528 - Cannot create tax item.
  * 		529 - Cannot create coupon item.
  * @access public
  * @throws Exception
  * @return int|WP_ERROR
  */
 public function create_order()
 {
     global $wpdb;
     // Give plugins the opportunity to create an order themselves
     if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
         return $order_id;
     }
     try {
         // Start transaction if available
         wc_transaction_query('start');
         $order_data = array('status' => apply_filters('woocommerce_default_order_status', 'pending'), 'customer_id' => $this->customer_id, 'customer_note' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '', 'cart_hash' => md5(json_encode(WC()->cart->get_cart_for_session()) . WC()->cart->total), 'created_via' => 'checkout');
         // Insert or update the post data
         $order_id = absint(WC()->session->order_awaiting_payment);
         /**
          * If there is an order pending payment, we can resume it here so
          * long as it has not changed. If the order has changed, i.e.
          * different items or cost, create a new order. We use a hash to
          * detect changes which is based on cart items + order total.
          */
         if ($order_id && $order_data['cart_hash'] === get_post_meta($order_id, '_cart_hash', true) && ($order = wc_get_order($order_id)) && $order->has_status(array('pending', 'failed'))) {
             $order_data['order_id'] = $order_id;
             $order = wc_update_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 522));
             } else {
                 $order->remove_order_items();
                 do_action('woocommerce_resume_order', $order_id);
             }
         } else {
             $order = wc_create_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 520));
             } elseif (false === $order) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 521));
             } else {
                 $order_id = $order->id;
                 do_action('woocommerce_new_order', $order_id);
             }
         }
         // Store the line items to the new/resumed order
         foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
             $item_id = $order->add_product($values['data'], $values['quantity'], array('variation' => $values['variation'], 'totals' => array('subtotal' => $values['line_subtotal'], 'subtotal_tax' => $values['line_subtotal_tax'], 'total' => $values['line_total'], 'tax' => $values['line_tax'], 'tax_data' => $values['line_tax_data'])));
             if (!$item_id) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 525));
             }
             // Allow plugins to add order item meta
             do_action('woocommerce_add_order_item_meta', $item_id, $values, $cart_item_key);
         }
         // Store fees
         foreach (WC()->cart->get_fees() as $fee_key => $fee) {
             $item_id = $order->add_fee($fee);
             if (!$item_id) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 526));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order_id, $item_id, $fee, $fee_key);
         }
         // Store shipping for all packages
         foreach (WC()->shipping->get_packages() as $package_key => $package) {
             if (isset($package['rates'][$this->shipping_methods[$package_key]])) {
                 $item_id = $order->add_shipping($package['rates'][$this->shipping_methods[$package_key]]);
                 if (!$item_id) {
                     throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 527));
                 }
                 // Allows plugins to add order item meta to shipping
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $package_key);
             }
         }
         // Store tax rows
         foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $tax_rate_id) {
             if ($tax_rate_id && !$order->add_tax($tax_rate_id, WC()->cart->get_tax_amount($tax_rate_id), WC()->cart->get_shipping_tax_amount($tax_rate_id)) && apply_filters('woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated') !== $tax_rate_id) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 528));
             }
         }
         // Store coupons
         foreach (WC()->cart->get_coupons() as $code => $coupon) {
             if (!$order->add_coupon($code, WC()->cart->get_coupon_discount_amount($code), WC()->cart->get_coupon_discount_tax_amount($code))) {
                 throw new Exception(sprintf(__('Error %d: Unable to create order. Please try again.', 'woocommerce'), 529));
             }
         }
         // Billing address
         $billing_address = array();
         if ($this->checkout_fields['billing']) {
             foreach (array_keys($this->checkout_fields['billing']) as $field) {
                 $field_name = str_replace('billing_', '', $field);
                 $billing_address[$field_name] = $this->get_posted_address_data($field_name);
             }
         }
         // Shipping address.
         $shipping_address = array();
         if ($this->checkout_fields['shipping']) {
             foreach (array_keys($this->checkout_fields['shipping']) as $field) {
                 $field_name = str_replace('shipping_', '', $field);
                 $shipping_address[$field_name] = $this->get_posted_address_data($field_name, 'shipping');
             }
         }
         $order->set_address($billing_address, 'billing');
         $order->set_address($shipping_address, 'shipping');
         $order->set_payment_method($this->payment_method);
         $order->set_total(WC()->cart->shipping_total, 'shipping');
         $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
         $order->set_total(WC()->cart->get_cart_discount_tax_total(), 'cart_discount_tax');
         $order->set_total(WC()->cart->tax_total, 'tax');
         $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
         $order->set_total(WC()->cart->total);
         // Update user meta
         if ($this->customer_id) {
             if (apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 foreach ($billing_address as $key => $value) {
                     update_user_meta($this->customer_id, 'billing_' . $key, $value);
                 }
                 if (WC()->cart->needs_shipping()) {
                     foreach ($shipping_address as $key => $value) {
                         update_user_meta($this->customer_id, 'shipping_' . $key, $value);
                     }
                 }
             }
             do_action('woocommerce_checkout_update_user_meta', $this->customer_id, $this->posted);
         }
         // Let plugins add meta
         do_action('woocommerce_checkout_update_order_meta', $order_id, $this->posted);
         // If we got here, the order was created without problems!
         wc_transaction_query('commit');
     } catch (Exception $e) {
         // There was an error adding order data!
         wc_transaction_query('rollback');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $order_id;
 }
 /**
  * create_order function.
  * @access public
  * @throws Exception
  * @return int|WP_ERROR
  */
 public function create_order()
 {
     global $wpdb;
     // Give plugins the opportunity to create an order themselves
     if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
         return $order_id;
     }
     try {
         // Start transaction if available
         $wpdb->query('START TRANSACTION');
         $order_data = array('status' => apply_filters('woocommerce_default_order_status', 'pending'), 'customer_id' => $this->customer_id, 'customer_note' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '');
         // Insert or update the post data
         $order_id = absint(WC()->session->order_awaiting_payment);
         // Resume the unpaid order if its pending
         if ($order_id > 0 && ($order = wc_get_order($order_id)) && $order->has_status(array('pending', 'failed'))) {
             $order_data['order_id'] = $order_id;
             $order = wc_update_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order->remove_order_items();
                 do_action('woocommerce_resume_order', $order_id);
             }
         } else {
             $order = wc_create_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order_id = $order->id;
                 do_action('woocommerce_new_order', $order_id);
             }
         }
         // Store the line items to the new/resumed order
         foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
             $item_id = $order->add_product($values['data'], $values['quantity'], array('variation' => $values['variation'], 'totals' => array('subtotal' => $values['line_subtotal'], 'subtotal_tax' => $values['line_subtotal_tax'], 'total' => $values['line_total'], 'tax' => $values['line_tax'], 'tax_data' => $values['line_tax_data'])));
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // Allow plugins to add order item meta
             do_action('woocommerce_add_order_item_meta', $item_id, $values, $cart_item_key);
         }
         // Store fees
         foreach (WC()->cart->get_fees() as $fee_key => $fee) {
             $item_id = $order->add_fee($fee);
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order_id, $item_id, $fee, $fee_key);
         }
         // Store shipping for all packages
         foreach (WC()->shipping->get_packages() as $package_key => $package) {
             if (isset($package['rates'][$this->shipping_methods[$package_key]])) {
                 $item_id = $order->add_shipping($package['rates'][$this->shipping_methods[$package_key]]);
                 if (!$item_id) {
                     throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
                 }
                 // Allows plugins to add order item meta to shipping
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $package_key);
             }
         }
         // Store tax rows
         foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $tax_rate_id) {
             if (!$order->add_tax($tax_rate_id, WC()->cart->get_tax_amount($tax_rate_id), WC()->cart->get_shipping_tax_amount($tax_rate_id)) && 'zero-rated' !== $tax_rate_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Store coupons
         foreach (WC()->cart->get_coupons() as $code => $coupon) {
             if (!$order->add_coupon($code, WC()->cart->get_coupon_discount_amount($code))) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Billing address
         $billing_address = array();
         if ($this->checkout_fields['billing']) {
             foreach (array_keys($this->checkout_fields['billing']) as $field) {
                 $field_name = str_replace('billing_', '', $field);
                 $billing_address[$field_name] = $this->get_posted_address_data($field_name);
             }
         }
         // Shipping address.
         $shipping_address = array();
         if ($this->checkout_fields['shipping']) {
             foreach (array_keys($this->checkout_fields['shipping']) as $field) {
                 $field_name = str_replace('shipping_', '', $field);
                 $shipping_address[$field_name] = $this->get_posted_address_data($field_name, 'shipping');
             }
         }
         $order->set_address($billing_address, 'billing');
         $order->set_address($shipping_address, 'shipping');
         $order->set_payment_method($this->payment_method);
         $order->set_total(WC()->cart->shipping_total, 'shipping');
         $order->set_total(WC()->cart->get_order_discount_total(), 'order_discount');
         $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
         $order->set_total(WC()->cart->tax_total, 'tax');
         $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
         $order->set_total(WC()->cart->total);
         // Update user meta
         if ($this->customer_id) {
             if (apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                 foreach ($billing_address as $key => $value) {
                     update_user_meta($this->customer_id, 'billing_' . $key, $value);
                 }
                 foreach ($shipping_address as $key => $value) {
                     update_user_meta($this->customer_id, 'shipping_' . $key, $value);
                 }
             }
             do_action('woocommerce_checkout_update_user_meta', $this->customer_id, $this->posted);
         }
         // Let plugins add meta
         do_action('woocommerce_checkout_update_order_meta', $order_id, $this->posted);
         // If we got here, the order was created without problems!
         $wpdb->query('COMMIT');
     } catch (Exception $e) {
         // There was an error adding order data!
         $wpdb->query('ROLLBACK');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $order_id;
 }
Example #6
0
function wc1c_replace_document($document)
{
    global $wpdb;
    if ($document['ХозОперация'] != "Заказ товара" || $document['Роль'] != "Продавец") {
        return;
    }
    $order = wc_get_order($document['Номер']);
    if (!$order) {
        $args = array('status' => 'on-hold', 'customer_note' => @$document['Комментарий']);
        $contragent_name = @$document['Контрагенты'][0]['Наименование'];
        if ($contragent_name == "Гость") {
            $user_id = 0;
        } elseif (strpos($contragent_name, ' ') !== false) {
            list($first_name, $last_name) = explode(' ', $contragent_name, 2);
            $result = $wpdb->get_var($wpdb->prepare("SELECT u1.user_id FROM {$wpdb->usermeta} u1 JOIN {$wpdb->usermeta} u2 ON u1.user_id = u2.user_id WHERE (u1.meta_key = 'billing_first_name' AND u1.meta_value = %s AND u2.meta_key = 'billing_last_name' AND u2.meta_value = %s) OR (u1.meta_key = 'shipping_first_name' AND u1.meta_value = %s AND u2.meta_key = 'shipping_last_name' AND u2.meta_value = %s)", $first_name, $last_name, $first_name, $last_name));
            wc1c_check_wpdb_error();
            if ($result) {
                $user_id = $result;
            }
        }
        if (isset($user_id)) {
            $args['customer_id'] = $user_id;
        }
        $order = wc_create_order($args);
        wc1c_check_wp_error($order);
        if (!isset($user_id)) {
            update_post_meta($order->id, 'wc1c_contragent', $contragent_name);
        }
        $args = array('ID' => $order->id);
        $date = @$document['Дата'];
        if ($date && !empty($document['Время'])) {
            $date .= " {$document['Время']}";
        }
        $timestamp = strtotime($date);
        $args['post_date'] = date("Y-m-d H:i:s", $timestamp);
        $result = wp_update_post($args);
        wc1c_check_wp_error($result);
        if (!$result) {
            wc1c_error("Failed to update order post");
        }
        update_post_meta($order->id, '_wc1c_guid', $document['Ид']);
    } else {
        $args = array('order_id' => $order->id, 'status' => 'on-hold');
        $is_paid = false;
        foreach ($document['ЗначенияРеквизитов'] as $requisite) {
            if (!in_array($requisite['Наименование'], array("Дата оплаты по 1С", "Дата отгрузки по 1С"))) {
                continue;
            }
            $is_paid = true;
            break;
        }
        if ($is_paid) {
            $args['status'] = 'processing';
        }
        $is_passed = false;
        foreach ($document['ЗначенияРеквизитов'] as $requisite) {
            if ($requisite['Наименование'] != 'Проведен' || $requisite['Значение'] != 'true') {
                continue;
            }
            $is_passed = true;
            break;
        }
        if ($is_passed) {
            $args['status'] = 'completed';
        }
        $order = wc_update_order($args);
        wc1c_check_wp_error($order);
    }
    $is_deleted = false;
    foreach ($document['ЗначенияРеквизитов'] as $requisite) {
        if ($requisite['Наименование'] != 'ПометкаУдаления' || $requisite['Значение'] != 'true') {
            continue;
        }
        $is_deleted = true;
        break;
    }
    if ($is_deleted && $order->post_status != 'trash') {
        wp_trash_post($order->id);
    } elseif (!$is_deleted && $order->post_status == 'trash') {
        wp_untrash_post($order->id);
    }
    $post_meta = array();
    if (isset($document['Валюта'])) {
        $post_meta['_order_currency'] = $document['Валюта'];
    }
    if (isset($document['Сумма'])) {
        $post_meta['_order_total'] = wc1c_parse_decimal($document['Сумма']);
    }
    $document_products = array();
    $document_services = array();
    foreach ($document['Товары'] as $i => $document_product) {
        foreach ($document_product['ЗначенияРеквизитов'] as $document_product_requisite) {
            if ($document_product_requisite['Наименование'] != 'ТипНоменклатуры') {
                continue;
            }
            if ($document_product_requisite['Значение'] == 'Услуга') {
                $document_services[] = $document_product;
            } else {
                $document_products[] = $document_product;
            }
            break;
        }
    }
    wc1c_replace_document_products($order, $document_products);
    $post_meta['_order_shipping'] = wc1c_replace_document_services($order, $document_services);
    $current_post_meta = get_post_meta($order->id);
    foreach ($current_post_meta as $meta_key => $meta_value) {
        $current_post_meta[$meta_key] = $meta_value[0];
    }
    foreach ($post_meta as $meta_key => $meta_value) {
        $current_meta_value = @$current_post_meta[$meta_key];
        if ($current_meta_value == $meta_value) {
            continue;
        }
        update_post_meta($order->id, $meta_key, $meta_value);
    }
}
 protected function update_customer_order($customerID)
 {
     global $json_api;
     $order_data = array("status" => apply_filters("woocommerce_default_order_status", "pending"), "customer_id" => $customerID, "customer_user" => $customerID, "customer_note" => $json_api->query->order_comments ? $json_api->query->order_comments : "", "created_via" => "checkout", "billing_first_name" => $json_api->query->billing_first_name, "billing_last_name" => $json_api->query->billing_last_name, "billing_email" => $json_api->query->billing_email, "billing_phone" => $json_api->query->billing_phone, "order_id" => WC()->checkout()->create_order());
     $orderId = $order_data["order_id"];
     if (is_wp_error($order_id)) {
         $json_api->error("No order created.");
     } else {
         wc_update_order($order_data);
         WC()->cart->empty_cart();
     }
     return array("status" => "ok", "message" => "Order " . $orderId . " successfully created.");
 }
 /**
  * Create new order for WooCommerce version 2.2+
  * @return int|WP_ERROR 
  */
 public function create_order_2_2()
 {
     global $woocommerce, $wpdb;
     $this->shipping_methods = WC()->session->get('chosen_shipping_methods');
     if (sizeof($woocommerce->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href="%s">Return to homepage &rarr;</a>', 'hygglig'), home_url()), 'error');
     }
     // Recheck cart items so that they are in stock
     $result = $woocommerce->cart->check_cart_item_stock();
     if (is_wp_error($result)) {
         return $result->get_error_message();
         exit;
     }
     // Update cart totals
     $woocommerce->cart->calculate_totals();
     // Customer accounts
     $this->customer_id = apply_filters('woocommerce_checkout_customer_id', get_current_user_id());
     // Give plugins the opportunity to create an order themselves
     if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
         return $order_id;
     }
     try {
         // Start transaction if available
         $wpdb->query('START TRANSACTION');
         $order_data = array('status' => apply_filters('woocommerce_default_order_status', 'pending'), 'customer_id' => $this->customer_id, 'customer_note' => isset($this->posted['order_comments']) ? $this->posted['order_comments'] : '');
         // Insert or update the post data
         $order_id = absint(WC()->session->order_awaiting_payment);
         // Resume the unpaid order if its pending
         if ($order_id > 0 && ($order = wc_get_order($order_id)) && $order->has_status(array('pending', 'failed'))) {
             $order_data['order_id'] = $order_id;
             $order = wc_update_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order->remove_order_items();
                 do_action('woocommerce_resume_order', $order_id);
             }
         } else {
             $order = wc_create_order($order_data);
             if (is_wp_error($order)) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             } else {
                 $order_id = $order->id;
                 do_action('woocommerce_new_order', $order_id);
             }
         }
         // Store the line items to the new/resumed order
         foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
             $item_id = $order->add_product($values['data'], $values['quantity'], array('variation' => $values['variation'], 'totals' => array('subtotal' => $values['line_subtotal'], 'subtotal_tax' => $values['line_subtotal_tax'], 'total' => $values['line_total'], 'tax' => $values['line_tax'], 'tax_data' => $values['line_tax_data'])));
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // Allow plugins to add order item meta
             do_action('woocommerce_add_order_item_meta', $item_id, $values, $cart_item_key);
         }
         // Store fees
         foreach (WC()->cart->get_fees() as $fee_key => $fee) {
             $item_id = $order->add_fee($fee);
             if (!$item_id) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
             // Allow plugins to add order item meta to fees
             do_action('woocommerce_add_order_fee_meta', $order_id, $item_id, $fee, $fee_key);
         }
         // Store shipping for all packages
         foreach (WC()->shipping->get_packages() as $package_key => $package) {
             if (isset($package['rates'][$this->shipping_methods[$package_key]])) {
                 $item_id = $order->add_shipping($package['rates'][$this->shipping_methods[$package_key]]);
                 if (!$item_id) {
                     throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
                 }
                 // Allows plugins to add order item meta to shipping
                 do_action('woocommerce_add_shipping_order_item', $order_id, $item_id, $package_key);
             }
         }
         // Store tax rows
         foreach (array_keys(WC()->cart->taxes + WC()->cart->shipping_taxes) as $tax_rate_id) {
             if (!$order->add_tax($tax_rate_id, WC()->cart->get_tax_amount($tax_rate_id), WC()->cart->get_shipping_tax_amount($tax_rate_id))) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Store coupons
         foreach (WC()->cart->get_coupons() as $code => $coupon) {
             if (!$order->add_coupon($code, WC()->cart->get_coupon_discount_amount($code))) {
                 throw new Exception(__('Error: Unable to create order. Please try again.', 'woocommerce'));
             }
         }
         // Payment Method
         $available_gateways = WC()->payment_gateways->payment_gateways();
         $this->payment_method = $available_gateways['hygglig_checkout'];
         $order->set_payment_method($this->payment_method);
         $order->set_total(WC()->cart->shipping_total, 'shipping');
         $order->set_total(WC()->cart->get_total_discount(), 'order_discount');
         $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
         $order->set_total(WC()->cart->tax_total, 'tax');
         $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
         $order->set_total(WC()->cart->total);
         // Let plugin add meta
         do_action('woocommerce_checkout_update_order_meta', $order_id, array());
         // If we got here, the order was created without problems!
         $wpdb->query('COMMIT');
     } catch (Exception $e) {
         // There was an error adding order data!
         $wpdb->query('ROLLBACK');
         return new WP_Error('checkout-error', $e->getMessage());
     }
     return $order_id;
 }
 /**
  * Update an order
  *
  * Based on WC_API_Orders::update_order
  *
  * @since 3.0.0
  * @param int $id
  * @param array $data
  * @param array $options
  * @return int|WP_Error
  */
 private function update_order($id, $data, $options)
 {
     try {
         $order = wc_get_order($id);
         $order_args = array('order_id' => $order->id);
         // customer note
         if (isset($data['note'])) {
             $order_args['customer_note'] = $data['note'];
         }
         // update the order post to set customer note/modified date
         $order = wc_update_order($order_args);
         if (is_wp_error($order)) {
             $messages = $this->implode_wp_error_messages($order);
             $order_identifier = $this->get_item_identifier($data);
             /* translators: Placeholders: %1$s - order identifier, %2$s - error message(s) */
             throw new WC_CSV_Import_Suite_Import_Exception('wc_csv_import_suite_cannot_update_order', sprintf(__('Failed to update order %1$s: %2$s;', 'woocommerce-csv-import-suite'), esc_html($order_identifier), esc_html($messages)));
         }
         // order status
         if (!empty($data['status'])) {
             $order->update_status($data['status'], isset($data['status_note']) ? $data['status_note'] : '');
         }
         // customer ID
         if (isset($data['customer_id']) && $data['customer_id'] != $order->get_user_id()) {
             update_post_meta($order->id, '_customer_user', $data['customer_id']);
         }
         // update order data, such as meta and items
         $this->update_order_data($order, $data, $options);
         // calculate totals and set them
         if ($options['recalculate_totals']) {
             $order->calculate_taxes();
             $order->calculate_totals();
         }
         /**
          * Triggered after an order has been updated via CSV import
          *
          * @since 3.0.0
          * @param int $id Order ID
          * @param array $data Data from CSV
          * @param array $options Import options
          */
         do_action('wc_csv_import_suite_update_order', $order->id, $data, $options);
     } catch (WC_CSV_Import_Suite_Import_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage());
     }
 }