PageRenderTime 44ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/woocommerce/includes/api/v2/class-wc-api-orders.php

https://gitlab.com/webkod3r/tripolis
PHP | 1546 lines | 888 code | 323 blank | 335 comment | 163 complexity | 72542fb4346f109d6f26cd139d69774c MD5 | raw file
  1. <?php
  2. /**
  3. * WooCommerce API Orders Class
  4. *
  5. * Handles requests to the /orders endpoint
  6. *
  7. * @author WooThemes
  8. * @category API
  9. * @package WooCommerce/API
  10. * @since 2.1
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit; // Exit if accessed directly
  14. }
  15. class WC_API_Orders extends WC_API_Resource {
  16. /** @var string $base the route base */
  17. protected $base = '/orders';
  18. /** @var string $post_type the custom post type */
  19. protected $post_type = 'shop_order';
  20. /**
  21. * Register the routes for this class
  22. *
  23. * GET|POST /orders
  24. * GET /orders/count
  25. * GET|PUT|DELETE /orders/<id>
  26. * GET /orders/<id>/notes
  27. *
  28. * @since 2.1
  29. * @param array $routes
  30. * @return array
  31. */
  32. public function register_routes( $routes ) {
  33. # GET|POST /orders
  34. $routes[ $this->base ] = array(
  35. array( array( $this, 'get_orders' ), WC_API_Server::READABLE ),
  36. array( array( $this, 'create_order' ), WC_API_Server::CREATABLE | WC_API_Server::ACCEPT_DATA ),
  37. );
  38. # GET /orders/count
  39. $routes[ $this->base . '/count' ] = array(
  40. array( array( $this, 'get_orders_count' ), WC_API_Server::READABLE ),
  41. );
  42. # GET /orders/statuses
  43. $routes[ $this->base . '/statuses' ] = array(
  44. array( array( $this, 'get_order_statuses' ), WC_API_Server::READABLE ),
  45. );
  46. # GET|PUT|DELETE /orders/<id>
  47. $routes[ $this->base . '/(?P<id>\d+)' ] = array(
  48. array( array( $this, 'get_order' ), WC_API_Server::READABLE ),
  49. array( array( $this, 'edit_order' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  50. array( array( $this, 'delete_order' ), WC_API_Server::DELETABLE ),
  51. );
  52. # GET|POST /orders/<id>/notes
  53. $routes[ $this->base . '/(?P<order_id>\d+)/notes' ] = array(
  54. array( array( $this, 'get_order_notes' ), WC_API_Server::READABLE ),
  55. array( array( $this, 'create_order_note' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
  56. );
  57. # GET|PUT|DELETE /orders/<order_id>/notes/<id>
  58. $routes[ $this->base . '/(?P<order_id>\d+)/notes/(?P<id>\d+)' ] = array(
  59. array( array( $this, 'get_order_note' ), WC_API_Server::READABLE ),
  60. array( array( $this, 'edit_order_note' ), WC_API_SERVER::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  61. array( array( $this, 'delete_order_note' ), WC_API_SERVER::DELETABLE ),
  62. );
  63. # GET|POST /orders/<order_id>/refunds
  64. $routes[ $this->base . '/(?P<order_id>\d+)/refunds' ] = array(
  65. array( array( $this, 'get_order_refunds' ), WC_API_Server::READABLE ),
  66. array( array( $this, 'create_order_refund' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),
  67. );
  68. # GET|PUT|DELETE /orders/<order_id>/refunds/<id>
  69. $routes[ $this->base . '/(?P<order_id>\d+)/refunds/(?P<id>\d+)' ] = array(
  70. array( array( $this, 'get_order_refund' ), WC_API_Server::READABLE ),
  71. array( array( $this, 'edit_order_refund' ), WC_API_SERVER::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  72. array( array( $this, 'delete_order_refund' ), WC_API_SERVER::DELETABLE ),
  73. );
  74. # POST|PUT /orders/bulk
  75. $routes[ $this->base . '/bulk' ] = array(
  76. array( array( $this, 'bulk' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
  77. );
  78. return $routes;
  79. }
  80. /**
  81. * Get all orders
  82. *
  83. * @since 2.1
  84. * @param string $fields
  85. * @param array $filter
  86. * @param string $status
  87. * @param int $page
  88. * @return array
  89. */
  90. public function get_orders( $fields = null, $filter = array(), $status = null, $page = 1 ) {
  91. if ( ! empty( $status ) ) {
  92. $filter['status'] = $status;
  93. }
  94. $filter['page'] = $page;
  95. $query = $this->query_orders( $filter );
  96. $orders = array();
  97. foreach ( $query->posts as $order_id ) {
  98. if ( ! $this->is_readable( $order_id ) ) {
  99. continue;
  100. }
  101. $orders[] = current( $this->get_order( $order_id, $fields, $filter ) );
  102. }
  103. $this->server->add_pagination_headers( $query );
  104. return array( 'orders' => $orders );
  105. }
  106. /**
  107. * Get the order for the given ID
  108. *
  109. * @since 2.1
  110. * @param int $id the order ID
  111. * @param array $fields
  112. * @param array $filter
  113. * @return array
  114. */
  115. public function get_order( $id, $fields = null, $filter = array() ) {
  116. // ensure order ID is valid & user has permission to read
  117. $id = $this->validate_request( $id, $this->post_type, 'read' );
  118. if ( is_wp_error( $id ) ) {
  119. return $id;
  120. }
  121. // Get the decimal precession
  122. $dp = ( isset( $filter['dp'] ) ? intval( $filter['dp'] ) : 2 );
  123. $order = wc_get_order( $id );
  124. $order_post = get_post( $id );
  125. $order_data = array(
  126. 'id' => $order->id,
  127. 'order_number' => $order->get_order_number(),
  128. 'created_at' => $this->server->format_datetime( $order_post->post_date_gmt ),
  129. 'updated_at' => $this->server->format_datetime( $order_post->post_modified_gmt ),
  130. 'completed_at' => $this->server->format_datetime( $order->completed_date, true ),
  131. 'status' => $order->get_status(),
  132. 'currency' => $order->get_order_currency(),
  133. 'total' => wc_format_decimal( $order->get_total(), $dp ),
  134. 'subtotal' => wc_format_decimal( $order->get_subtotal(), $dp ),
  135. 'total_line_items_quantity' => $order->get_item_count(),
  136. 'total_tax' => wc_format_decimal( $order->get_total_tax(), $dp ),
  137. 'total_shipping' => wc_format_decimal( $order->get_total_shipping(), $dp ),
  138. 'cart_tax' => wc_format_decimal( $order->get_cart_tax(), $dp ),
  139. 'shipping_tax' => wc_format_decimal( $order->get_shipping_tax(), $dp ),
  140. 'total_discount' => wc_format_decimal( $order->get_total_discount(), $dp ),
  141. 'shipping_methods' => $order->get_shipping_method(),
  142. 'payment_details' => array(
  143. 'method_id' => $order->payment_method,
  144. 'method_title' => $order->payment_method_title,
  145. 'paid' => isset( $order->paid_date ),
  146. ),
  147. 'billing_address' => array(
  148. 'first_name' => $order->billing_first_name,
  149. 'last_name' => $order->billing_last_name,
  150. 'company' => $order->billing_company,
  151. 'address_1' => $order->billing_address_1,
  152. 'address_2' => $order->billing_address_2,
  153. 'city' => $order->billing_city,
  154. 'state' => $order->billing_state,
  155. 'postcode' => $order->billing_postcode,
  156. 'country' => $order->billing_country,
  157. 'email' => $order->billing_email,
  158. 'phone' => $order->billing_phone,
  159. ),
  160. 'shipping_address' => array(
  161. 'first_name' => $order->shipping_first_name,
  162. 'last_name' => $order->shipping_last_name,
  163. 'company' => $order->shipping_company,
  164. 'address_1' => $order->shipping_address_1,
  165. 'address_2' => $order->shipping_address_2,
  166. 'city' => $order->shipping_city,
  167. 'state' => $order->shipping_state,
  168. 'postcode' => $order->shipping_postcode,
  169. 'country' => $order->shipping_country,
  170. ),
  171. 'note' => $order->customer_note,
  172. 'customer_ip' => $order->customer_ip_address,
  173. 'customer_user_agent' => $order->customer_user_agent,
  174. 'customer_id' => $order->get_user_id(),
  175. 'view_order_url' => $order->get_view_order_url(),
  176. 'line_items' => array(),
  177. 'shipping_lines' => array(),
  178. 'tax_lines' => array(),
  179. 'fee_lines' => array(),
  180. 'coupon_lines' => array(),
  181. );
  182. // add line items
  183. foreach ( $order->get_items() as $item_id => $item ) {
  184. $product = $order->get_product_from_item( $item );
  185. $product_id = null;
  186. $product_sku = null;
  187. // Check if the product exists.
  188. if ( is_object( $product ) ) {
  189. $product_id = ( isset( $product->variation_id ) ) ? $product->variation_id : $product->id;
  190. $product_sku = $product->get_sku();
  191. }
  192. $meta = new WC_Order_Item_Meta( $item, $product );
  193. $item_meta = array();
  194. $hideprefix = ( isset( $filter['all_item_meta'] ) && $filter['all_item_meta'] === 'true' ) ? null : '_';
  195. foreach ( $meta->get_formatted( $hideprefix ) as $meta_key => $formatted_meta ) {
  196. $item_meta[] = array(
  197. 'key' => $formatted_meta['key'],
  198. 'label' => $formatted_meta['label'],
  199. 'value' => $formatted_meta['value'],
  200. );
  201. }
  202. $order_data['line_items'][] = array(
  203. 'id' => $item_id,
  204. 'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item, false, false ), $dp ),
  205. 'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], $dp ),
  206. 'total' => wc_format_decimal( $order->get_line_total( $item, false, false ), $dp ),
  207. 'total_tax' => wc_format_decimal( $item['line_tax'], $dp ),
  208. 'price' => wc_format_decimal( $order->get_item_total( $item, false, false ), $dp ),
  209. 'quantity' => wc_stock_amount( $item['qty'] ),
  210. 'tax_class' => ( ! empty( $item['tax_class'] ) ) ? $item['tax_class'] : null,
  211. 'name' => $item['name'],
  212. 'product_id' => $product_id,
  213. 'sku' => $product_sku,
  214. 'meta' => $item_meta,
  215. );
  216. }
  217. // add shipping
  218. foreach ( $order->get_shipping_methods() as $shipping_item_id => $shipping_item ) {
  219. $order_data['shipping_lines'][] = array(
  220. 'id' => $shipping_item_id,
  221. 'method_id' => $shipping_item['method_id'],
  222. 'method_title' => $shipping_item['name'],
  223. 'total' => wc_format_decimal( $shipping_item['cost'], $dp ),
  224. );
  225. }
  226. // add taxes
  227. foreach ( $order->get_tax_totals() as $tax_code => $tax ) {
  228. $order_data['tax_lines'][] = array(
  229. 'id' => $tax->id,
  230. 'rate_id' => $tax->rate_id,
  231. 'code' => $tax_code,
  232. 'title' => $tax->label,
  233. 'total' => wc_format_decimal( $tax->amount, $dp ),
  234. 'compound' => (bool) $tax->is_compound,
  235. );
  236. }
  237. // add fees
  238. foreach ( $order->get_fees() as $fee_item_id => $fee_item ) {
  239. $order_data['fee_lines'][] = array(
  240. 'id' => $fee_item_id,
  241. 'title' => $fee_item['name'],
  242. 'tax_class' => ( ! empty( $fee_item['tax_class'] ) ) ? $fee_item['tax_class'] : null,
  243. 'total' => wc_format_decimal( $order->get_line_total( $fee_item ), $dp ),
  244. 'total_tax' => wc_format_decimal( $order->get_line_tax( $fee_item ), $dp ),
  245. );
  246. }
  247. // add coupons
  248. foreach ( $order->get_items( 'coupon' ) as $coupon_item_id => $coupon_item ) {
  249. $order_data['coupon_lines'][] = array(
  250. 'id' => $coupon_item_id,
  251. 'code' => $coupon_item['name'],
  252. 'amount' => wc_format_decimal( $coupon_item['discount_amount'], $dp ),
  253. );
  254. }
  255. return array( 'order' => apply_filters( 'woocommerce_api_order_response', $order_data, $order, $fields, $this->server ) );
  256. }
  257. /**
  258. * Get the total number of orders
  259. *
  260. * @since 2.4
  261. * @param string $status
  262. * @param array $filter
  263. * @return array
  264. */
  265. public function get_orders_count( $status = null, $filter = array() ) {
  266. try {
  267. if ( ! current_user_can( 'read_private_shop_orders' ) ) {
  268. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_orders_count', __( 'You do not have permission to read the orders count', 'woocommerce' ), 401 );
  269. }
  270. if ( ! empty( $status ) ) {
  271. if ( $status == 'any' ) {
  272. $order_statuses = array();
  273. foreach ( wc_get_order_statuses() as $slug => $name ) {
  274. $filter['status'] = str_replace( 'wc-', '', $slug );
  275. $query = $this->query_orders( $filter );
  276. $order_statuses[ str_replace( 'wc-', '', $slug ) ] = (int) $query->found_posts;
  277. }
  278. return array( 'count' => $order_statuses );
  279. } else {
  280. $filter['status'] = $status;
  281. }
  282. }
  283. $query = $this->query_orders( $filter );
  284. return array( 'count' => (int) $query->found_posts );
  285. } catch ( WC_API_Exception $e ) {
  286. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  287. }
  288. }
  289. /**
  290. * Get a list of valid order statuses
  291. *
  292. * Note this requires no specific permissions other than being an authenticated
  293. * API user. Order statuses (particularly custom statuses) could be considered
  294. * private information which is why it's not in the API index.
  295. *
  296. * @since 2.1
  297. * @return array
  298. */
  299. public function get_order_statuses() {
  300. $order_statuses = array();
  301. foreach ( wc_get_order_statuses() as $slug => $name ) {
  302. $order_statuses[ str_replace( 'wc-', '', $slug ) ] = $name;
  303. }
  304. return array( 'order_statuses' => apply_filters( 'woocommerce_api_order_statuses_response', $order_statuses, $this ) );
  305. }
  306. /**
  307. * Create an order
  308. *
  309. * @since 2.2
  310. * @param array $data raw order data
  311. * @return array
  312. */
  313. public function create_order( $data ) {
  314. global $wpdb;
  315. wc_transaction_query( 'start' );
  316. try {
  317. if ( ! isset( $data['order'] ) ) {
  318. throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order' ), 400 );
  319. }
  320. $data = $data['order'];
  321. // permission check
  322. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  323. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order', __( 'You do not have permission to create orders', 'woocommerce' ), 401 );
  324. }
  325. $data = apply_filters( 'woocommerce_api_create_order_data', $data, $this );
  326. // default order args, note that status is checked for validity in wc_create_order()
  327. $default_order_args = array(
  328. 'status' => isset( $data['status'] ) ? $data['status'] : '',
  329. 'customer_note' => isset( $data['note'] ) ? $data['note'] : null,
  330. );
  331. // if creating order for existing customer
  332. if ( ! empty( $data['customer_id'] ) ) {
  333. // make sure customer exists
  334. if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
  335. throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid', 'woocommerce' ), 400 );
  336. }
  337. $default_order_args['customer_id'] = $data['customer_id'];
  338. }
  339. // create the pending order
  340. $order = $this->create_base_order( $default_order_args, $data );
  341. if ( is_wp_error( $order ) ) {
  342. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order', sprintf( __( 'Cannot create order: %s', 'woocommerce' ), implode( ', ', $order->get_error_messages() ) ), 400 );
  343. }
  344. // billing/shipping addresses
  345. $this->set_order_addresses( $order, $data );
  346. $lines = array(
  347. 'line_item' => 'line_items',
  348. 'shipping' => 'shipping_lines',
  349. 'fee' => 'fee_lines',
  350. 'coupon' => 'coupon_lines',
  351. );
  352. foreach ( $lines as $line_type => $line ) {
  353. if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
  354. $set_item = "set_{$line_type}";
  355. foreach ( $data[ $line ] as $item ) {
  356. $this->$set_item( $order, $item, 'create' );
  357. }
  358. }
  359. }
  360. // calculate totals and set them
  361. $order->calculate_totals();
  362. // payment method (and payment_complete() if `paid` == true)
  363. if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
  364. // method ID & title are required
  365. if ( empty( $data['payment_details']['method_id'] ) || empty( $data['payment_details']['method_title'] ) ) {
  366. throw new WC_API_Exception( 'woocommerce_invalid_payment_details', __( 'Payment method ID and title are required', 'woocommerce' ), 400 );
  367. }
  368. update_post_meta( $order->id, '_payment_method', $data['payment_details']['method_id'] );
  369. update_post_meta( $order->id, '_payment_method_title', $data['payment_details']['method_title'] );
  370. // mark as paid if set
  371. if ( isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
  372. $order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
  373. }
  374. }
  375. // set order currency
  376. if ( isset( $data['currency'] ) ) {
  377. if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
  378. throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid', 'woocommerce'), 400 );
  379. }
  380. update_post_meta( $order->id, '_order_currency', $data['currency'] );
  381. }
  382. // set order meta
  383. if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
  384. $this->set_order_meta( $order->id, $data['order_meta'] );
  385. }
  386. // HTTP 201 Created
  387. $this->server->send_status( 201 );
  388. wc_delete_shop_order_transients( $order->id );
  389. do_action( 'woocommerce_api_create_order', $order->id, $data, $this );
  390. wc_transaction_query( 'commit' );
  391. return $this->get_order( $order->id );
  392. } catch ( WC_API_Exception $e ) {
  393. wc_transaction_query( 'rollback' );
  394. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  395. }
  396. }
  397. /**
  398. * Creates new WC_Order.
  399. *
  400. * Requires a separate function for classes that extend WC_API_Orders.
  401. *
  402. * @since 2.3
  403. * @param $args array
  404. * @return WC_Order
  405. */
  406. protected function create_base_order( $args, $data ) {
  407. return wc_create_order( $args );
  408. }
  409. /**
  410. * Edit an order
  411. *
  412. * @since 2.2
  413. * @param int $id the order ID
  414. * @param array $data
  415. * @return array
  416. */
  417. public function edit_order( $id, $data ) {
  418. try {
  419. if ( ! isset( $data['order'] ) ) {
  420. throw new WC_API_Exception( 'woocommerce_api_missing_order_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order' ), 400 );
  421. }
  422. $data = $data['order'];
  423. $update_totals = false;
  424. $id = $this->validate_request( $id, $this->post_type, 'edit' );
  425. if ( is_wp_error( $id ) ) {
  426. return $id;
  427. }
  428. $data = apply_filters( 'woocommerce_api_edit_order_data', $data, $id, $this );
  429. $order = wc_get_order( $id );
  430. if ( empty( $order ) ) {
  431. throw new WC_API_Exception( 'woocommerce_api_invalid_order_id', __( 'Order ID is invalid', 'woocommerce' ), 400 );
  432. }
  433. $order_args = array( 'order_id' => $order->id );
  434. // Customer note.
  435. if ( isset( $data['note'] ) ) {
  436. $order_args['customer_note'] = $data['note'];
  437. }
  438. // Customer ID.
  439. if ( isset( $data['customer_id'] ) && $data['customer_id'] != $order->get_user_id() ) {
  440. // Make sure customer exists.
  441. if ( false === get_user_by( 'id', $data['customer_id'] ) ) {
  442. throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Customer ID is invalid', 'woocommerce' ), 400 );
  443. }
  444. update_post_meta( $order->id, '_customer_user', $data['customer_id'] );
  445. }
  446. // Billing/shipping address.
  447. $this->set_order_addresses( $order, $data );
  448. $lines = array(
  449. 'line_item' => 'line_items',
  450. 'shipping' => 'shipping_lines',
  451. 'fee' => 'fee_lines',
  452. 'coupon' => 'coupon_lines',
  453. );
  454. foreach ( $lines as $line_type => $line ) {
  455. if ( isset( $data[ $line ] ) && is_array( $data[ $line ] ) ) {
  456. $update_totals = true;
  457. foreach ( $data[ $line ] as $item ) {
  458. // Item ID is always required.
  459. if ( ! array_key_exists( 'id', $item ) ) {
  460. throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID is required', 'woocommerce' ), 400 );
  461. }
  462. // Create item.
  463. if ( is_null( $item['id'] ) ) {
  464. $this->set_item( $order, $line_type, $item, 'create' );
  465. } elseif ( $this->item_is_null( $item ) ) {
  466. // Delete item.
  467. wc_delete_order_item( $item['id'] );
  468. } else {
  469. // Update item.
  470. $this->set_item( $order, $line_type, $item, 'update' );
  471. }
  472. }
  473. }
  474. }
  475. // Payment method (and payment_complete() if `paid` == true and order needs payment).
  476. if ( isset( $data['payment_details'] ) && is_array( $data['payment_details'] ) ) {
  477. // Method ID.
  478. if ( isset( $data['payment_details']['method_id'] ) ) {
  479. update_post_meta( $order->id, '_payment_method', $data['payment_details']['method_id'] );
  480. }
  481. // Method title.
  482. if ( isset( $data['payment_details']['method_title'] ) ) {
  483. update_post_meta( $order->id, '_payment_method_title', $data['payment_details']['method_title'] );
  484. }
  485. // Mark as paid if set.
  486. if ( $order->needs_payment() && isset( $data['payment_details']['paid'] ) && true === $data['payment_details']['paid'] ) {
  487. $order->payment_complete( isset( $data['payment_details']['transaction_id'] ) ? $data['payment_details']['transaction_id'] : '' );
  488. }
  489. }
  490. // Set order currency.
  491. if ( isset( $data['currency'] ) ) {
  492. if ( ! array_key_exists( $data['currency'], get_woocommerce_currencies() ) ) {
  493. throw new WC_API_Exception( 'woocommerce_invalid_order_currency', __( 'Provided order currency is invalid', 'woocommerce' ), 400 );
  494. }
  495. update_post_meta( $order->id, '_order_currency', $data['currency'] );
  496. }
  497. // If items have changed, recalculate order totals.
  498. if ( $update_totals ) {
  499. $order->calculate_totals();
  500. }
  501. // Update order meta.
  502. if ( isset( $data['order_meta'] ) && is_array( $data['order_meta'] ) ) {
  503. $this->set_order_meta( $order->id, $data['order_meta'] );
  504. }
  505. // Update the order post to set customer note/modified date.
  506. wc_update_order( $order_args );
  507. // Order status.
  508. if ( ! empty( $data['status'] ) ) {
  509. $order->update_status( $data['status'], isset( $data['status_note'] ) ? $data['status_note'] : '' );
  510. }
  511. wc_delete_shop_order_transients( $order->id );
  512. do_action( 'woocommerce_api_edit_order', $order->id, $data, $this );
  513. return $this->get_order( $id );
  514. } catch ( WC_API_Exception $e ) {
  515. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  516. }
  517. }
  518. /**
  519. * Delete an order
  520. *
  521. * @param int $id the order ID
  522. * @param bool $force true to permanently delete order, false to move to trash
  523. * @return array
  524. */
  525. public function delete_order( $id, $force = false ) {
  526. $id = $this->validate_request( $id, $this->post_type, 'delete' );
  527. if ( is_wp_error( $id ) ) {
  528. return $id;
  529. }
  530. wc_delete_shop_order_transients( $id );
  531. do_action( 'woocommerce_api_delete_order', $id, $this );
  532. return $this->delete( $id, 'order', ( 'true' === $force ) );
  533. }
  534. /**
  535. * Helper method to get order post objects
  536. *
  537. * @since 2.1
  538. * @param array $args request arguments for filtering query
  539. * @return WP_Query
  540. */
  541. protected function query_orders( $args ) {
  542. // set base query arguments
  543. $query_args = array(
  544. 'fields' => 'ids',
  545. 'post_type' => $this->post_type,
  546. 'post_status' => array_keys( wc_get_order_statuses() )
  547. );
  548. // add status argument
  549. if ( ! empty( $args['status'] ) ) {
  550. $statuses = 'wc-' . str_replace( ',', ',wc-', $args['status'] );
  551. $statuses = explode( ',', $statuses );
  552. $query_args['post_status'] = $statuses;
  553. unset( $args['status'] );
  554. }
  555. $query_args = $this->merge_query_args( $query_args, $args );
  556. return new WP_Query( $query_args );
  557. }
  558. /**
  559. * Helper method to set/update the billing & shipping addresses for
  560. * an order
  561. *
  562. * @since 2.1
  563. * @param \WC_Order $order
  564. * @param array $data
  565. */
  566. protected function set_order_addresses( $order, $data ) {
  567. $address_fields = array(
  568. 'first_name',
  569. 'last_name',
  570. 'company',
  571. 'email',
  572. 'phone',
  573. 'address_1',
  574. 'address_2',
  575. 'city',
  576. 'state',
  577. 'postcode',
  578. 'country',
  579. );
  580. $billing_address = $shipping_address = array();
  581. // billing address
  582. if ( isset( $data['billing_address'] ) && is_array( $data['billing_address'] ) ) {
  583. foreach ( $address_fields as $field ) {
  584. if ( isset( $data['billing_address'][ $field ] ) ) {
  585. $billing_address[ $field ] = wc_clean( $data['billing_address'][ $field ] );
  586. }
  587. }
  588. unset( $address_fields['email'] );
  589. unset( $address_fields['phone'] );
  590. }
  591. // shipping address
  592. if ( isset( $data['shipping_address'] ) && is_array( $data['shipping_address'] ) ) {
  593. foreach ( $address_fields as $field ) {
  594. if ( isset( $data['shipping_address'][ $field ] ) ) {
  595. $shipping_address[ $field ] = wc_clean( $data['shipping_address'][ $field ] );
  596. }
  597. }
  598. }
  599. $order->set_address( $billing_address, 'billing' );
  600. $order->set_address( $shipping_address, 'shipping' );
  601. // update user meta
  602. if ( $order->get_user_id() ) {
  603. foreach ( $billing_address as $key => $value ) {
  604. update_user_meta( $order->get_user_id(), 'billing_' . $key, $value );
  605. }
  606. foreach ( $shipping_address as $key => $value ) {
  607. update_user_meta( $order->get_user_id(), 'shipping_' . $key, $value );
  608. }
  609. }
  610. }
  611. /**
  612. * Helper method to add/update order meta, with two restrictions:
  613. *
  614. * 1) Only non-protected meta (no leading underscore) can be set
  615. * 2) Meta values must be scalar (int, string, bool)
  616. *
  617. * @since 2.2
  618. * @param int $order_id valid order ID
  619. * @param array $order_meta order meta in array( 'meta_key' => 'meta_value' ) format
  620. */
  621. protected function set_order_meta( $order_id, $order_meta ) {
  622. foreach ( $order_meta as $meta_key => $meta_value ) {
  623. if ( is_string( $meta_key) && ! is_protected_meta( $meta_key ) && is_scalar( $meta_value ) ) {
  624. update_post_meta( $order_id, $meta_key, $meta_value );
  625. }
  626. }
  627. }
  628. /**
  629. * Helper method to check if the resource ID associated with the provided item is null
  630. *
  631. * Items can be deleted by setting the resource ID to null
  632. *
  633. * @since 2.2
  634. * @param array $item item provided in the request body
  635. * @return bool true if the item resource ID is null, false otherwise
  636. */
  637. protected function item_is_null( $item ) {
  638. $keys = array( 'product_id', 'method_id', 'title', 'code' );
  639. foreach ( $keys as $key ) {
  640. if ( array_key_exists( $key, $item ) && is_null( $item[ $key ] ) ) {
  641. return true;
  642. }
  643. }
  644. return false;
  645. }
  646. /**
  647. * Wrapper method to create/update order items
  648. *
  649. * When updating, the item ID provided is checked to ensure it is associated
  650. * with the order.
  651. *
  652. * @since 2.2
  653. * @param \WC_Order $order order
  654. * @param string $item_type
  655. * @param array $item item provided in the request body
  656. * @param string $action either 'create' or 'update'
  657. * @throws WC_API_Exception if item ID is not associated with order
  658. */
  659. protected function set_item( $order, $item_type, $item, $action ) {
  660. global $wpdb;
  661. $set_method = "set_{$item_type}";
  662. // verify provided line item ID is associated with order
  663. if ( 'update' === $action ) {
  664. $result = $wpdb->get_row(
  665. $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_id = %d AND order_id = %d",
  666. absint( $item['id'] ),
  667. absint( $order->id )
  668. ) );
  669. if ( is_null( $result ) ) {
  670. throw new WC_API_Exception( 'woocommerce_invalid_item_id', __( 'Order item ID provided is not associated with order', 'woocommerce' ), 400 );
  671. }
  672. }
  673. $this->$set_method( $order, $item, $action );
  674. }
  675. /**
  676. * Create or update a line item
  677. *
  678. * @since 2.2
  679. * @param \WC_Order $order
  680. * @param array $item line item data
  681. * @param string $action 'create' to add line item or 'update' to update it
  682. * @throws WC_API_Exception invalid data, server error
  683. */
  684. protected function set_line_item( $order, $item, $action ) {
  685. $creating = ( 'create' === $action );
  686. $item_args = array();
  687. // product is always required
  688. if ( ! isset( $item['product_id'] ) && ! isset( $item['sku'] ) ) {
  689. throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID or SKU is required', 'woocommerce' ), 400 );
  690. }
  691. // when updating, ensure product ID provided matches
  692. if ( 'update' === $action ) {
  693. $item_product_id = wc_get_order_item_meta( $item['id'], '_product_id' );
  694. $item_variation_id = wc_get_order_item_meta( $item['id'], '_variation_id' );
  695. if ( $item['product_id'] != $item_product_id && $item['product_id'] != $item_variation_id ) {
  696. throw new WC_API_Exception( 'woocommerce_api_invalid_product_id', __( 'Product ID provided does not match this line item', 'woocommerce' ), 400 );
  697. }
  698. }
  699. if ( isset( $item['product_id'] ) ) {
  700. $product_id = $item['product_id'];
  701. } elseif ( isset( $item['sku'] ) ) {
  702. $product_id = wc_get_product_id_by_sku( $item['sku'] );
  703. }
  704. // variations must each have a key & value
  705. $variation_id = 0;
  706. if ( isset( $item['variations'] ) && is_array( $item['variations'] ) ) {
  707. foreach ( $item['variations'] as $key => $value ) {
  708. if ( ! $key || ! $value ) {
  709. throw new WC_API_Exception( 'woocommerce_api_invalid_product_variation', __( 'The product variation is invalid', 'woocommerce' ), 400 );
  710. }
  711. }
  712. $item_args['variation'] = $item['variations'];
  713. $variation_id = $this->get_variation_id( wc_get_product( $product_id ), $item_args['variation'] );
  714. }
  715. $product = wc_get_product( $variation_id ? $variation_id : $product_id );
  716. // must be a valid WC_Product
  717. if ( ! is_object( $product ) ) {
  718. throw new WC_API_Exception( 'woocommerce_api_invalid_product', __( 'Product is invalid', 'woocommerce' ), 400 );
  719. }
  720. // quantity must be positive float
  721. if ( isset( $item['quantity'] ) && floatval( $item['quantity'] ) <= 0 ) {
  722. throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity must be a positive float', 'woocommerce' ), 400 );
  723. }
  724. // quantity is required when creating
  725. if ( $creating && ! isset( $item['quantity'] ) ) {
  726. throw new WC_API_Exception( 'woocommerce_api_invalid_product_quantity', __( 'Product quantity is required', 'woocommerce' ), 400 );
  727. }
  728. // quantity
  729. if ( isset( $item['quantity'] ) ) {
  730. $item_args['qty'] = $item['quantity'];
  731. }
  732. // total
  733. if ( isset( $item['total'] ) ) {
  734. $item_args['totals']['total'] = floatval( $item['total'] );
  735. }
  736. // total tax
  737. if ( isset( $item['total_tax'] ) ) {
  738. $item_args['totals']['tax'] = floatval( $item['total_tax'] );
  739. }
  740. // subtotal
  741. if ( isset( $item['subtotal'] ) ) {
  742. $item_args['totals']['subtotal'] = floatval( $item['subtotal'] );
  743. }
  744. // subtotal tax
  745. if ( isset( $item['subtotal_tax'] ) ) {
  746. $item_args['totals']['subtotal_tax'] = floatval( $item['subtotal_tax'] );
  747. }
  748. if ( $creating ) {
  749. $item_id = $order->add_product( $product, $item_args['qty'], $item_args );
  750. if ( ! $item_id ) {
  751. throw new WC_API_Exception( 'woocommerce_cannot_create_line_item', __( 'Cannot create line item, try again', 'woocommerce' ), 500 );
  752. }
  753. } else {
  754. $item_id = $order->update_product( $item['id'], $product, $item_args );
  755. if ( ! $item_id ) {
  756. throw new WC_API_Exception( 'woocommerce_cannot_update_line_item', __( 'Cannot update line item, try again', 'woocommerce' ), 500 );
  757. }
  758. }
  759. }
  760. /**
  761. * Given a product ID & API provided variations, find the correct variation ID to use for calculation
  762. * We can't just trust input from the API to pass a variation_id manually, otherwise you could pass
  763. * the cheapest variation ID but provide other information so we have to look up the variation ID.
  764. * @param int $product_id main product ID
  765. * @return int returns an ID if a valid variation was found for this product
  766. */
  767. function get_variation_id( $product, $variations = array() ) {
  768. $variation_id = null;
  769. $variations_normalized = array();
  770. if ( $product->is_type( 'variable' ) && $product->has_child() ) {
  771. if ( isset( $variations ) && is_array( $variations ) ) {
  772. // start by normalizing the passed variations
  773. foreach ( $variations as $key => $value ) {
  774. $key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) ); // from get_attributes in class-wc-api-products.php
  775. $variations_normalized[ $key ] = strtolower( $value );
  776. }
  777. // now search through each product child and see if our passed variations match anything
  778. foreach ( $product->get_children() as $variation ) {
  779. $meta = array();
  780. foreach ( get_post_meta( $variation ) as $key => $value ) {
  781. $value = $value[0];
  782. $key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) );
  783. $meta[ $key ] = strtolower( $value );
  784. }
  785. // if the variation array is a part of the $meta array, we found our match
  786. if ( $this->array_contains( $variations_normalized, $meta ) ) {
  787. $variation_id = $variation;
  788. break;
  789. }
  790. }
  791. }
  792. }
  793. return $variation_id;
  794. }
  795. /**
  796. * Utility function to see if the meta array contains data from variations
  797. */
  798. protected function array_contains( $needles, $haystack ) {
  799. foreach ( $needles as $key => $value ) {
  800. if ( $haystack[ $key ] !== $value ) {
  801. return false;
  802. }
  803. }
  804. return true;
  805. }
  806. /**
  807. * Create or update an order shipping method
  808. *
  809. * @since 2.2
  810. * @param \WC_Order $order
  811. * @param array $shipping item data
  812. * @param string $action 'create' to add shipping or 'update' to update it
  813. * @throws WC_API_Exception invalid data, server error
  814. */
  815. protected function set_shipping( $order, $shipping, $action ) {
  816. // total must be a positive float
  817. if ( isset( $shipping['total'] ) && floatval( $shipping['total'] ) < 0 ) {
  818. throw new WC_API_Exception( 'woocommerce_invalid_shipping_total', __( 'Shipping total must be a positive amount', 'woocommerce' ), 400 );
  819. }
  820. if ( 'create' === $action ) {
  821. // method ID is required
  822. if ( ! isset( $shipping['method_id'] ) ) {
  823. throw new WC_API_Exception( 'woocommerce_invalid_shipping_item', __( 'Shipping method ID is required', 'woocommerce' ), 400 );
  824. }
  825. $rate = new WC_Shipping_Rate( $shipping['method_id'], isset( $shipping['method_title'] ) ? $shipping['method_title'] : '', isset( $shipping['total'] ) ? floatval( $shipping['total'] ) : 0, array(), $shipping['method_id'] );
  826. $shipping_id = $order->add_shipping( $rate );
  827. if ( ! $shipping_id ) {
  828. throw new WC_API_Exception( 'woocommerce_cannot_create_shipping', __( 'Cannot create shipping method, try again', 'woocommerce' ), 500 );
  829. }
  830. } else {
  831. $shipping_args = array();
  832. if ( isset( $shipping['method_id'] ) ) {
  833. $shipping_args['method_id'] = $shipping['method_id'];
  834. }
  835. if ( isset( $shipping['method_title'] ) ) {
  836. $shipping_args['method_title'] = $shipping['method_title'];
  837. }
  838. if ( isset( $shipping['total'] ) ) {
  839. $shipping_args['cost'] = floatval( $shipping['total'] );
  840. }
  841. $shipping_id = $order->update_shipping( $shipping['id'], $shipping_args );
  842. if ( ! $shipping_id ) {
  843. throw new WC_API_Exception( 'woocommerce_cannot_update_shipping', __( 'Cannot update shipping method, try again', 'woocommerce' ), 500 );
  844. }
  845. }
  846. }
  847. /**
  848. * Create or update an order fee
  849. *
  850. * @since 2.2
  851. * @param \WC_Order $order
  852. * @param array $fee item data
  853. * @param string $action 'create' to add fee or 'update' to update it
  854. * @throws WC_API_Exception invalid data, server error
  855. */
  856. protected function set_fee( $order, $fee, $action ) {
  857. if ( 'create' === $action ) {
  858. // fee title is required
  859. if ( ! isset( $fee['title'] ) ) {
  860. throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee title is required', 'woocommerce' ), 400 );
  861. }
  862. $order_fee = new stdClass();
  863. $order_fee->id = sanitize_title( $fee['title'] );
  864. $order_fee->name = $fee['title'];
  865. $order_fee->amount = isset( $fee['total'] ) ? floatval( $fee['total'] ) : 0;
  866. $order_fee->taxable = false;
  867. $order_fee->tax = 0;
  868. $order_fee->tax_data = array();
  869. $order_fee->tax_class = '';
  870. // if taxable, tax class and total are required
  871. if ( isset( $fee['taxable'] ) && $fee['taxable'] ) {
  872. if ( ! isset( $fee['tax_class'] ) ) {
  873. throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee tax class is required when fee is taxable', 'woocommerce' ), 400 );
  874. }
  875. $order_fee->taxable = true;
  876. $order_fee->tax_class = $fee['tax_class'];
  877. if ( isset( $fee['total_tax'] ) ) {
  878. $order_fee->tax = isset( $fee['total_tax'] ) ? wc_format_refund_total( $fee['total_tax'] ) : 0;
  879. }
  880. if ( isset( $fee['tax_data'] ) ) {
  881. $order_fee->tax = wc_format_refund_total( array_sum( $fee['tax_data'] ) );
  882. $order_fee->tax_data = array_map( 'wc_format_refund_total', $fee['tax_data'] );
  883. }
  884. }
  885. $fee_id = $order->add_fee( $order_fee );
  886. if ( ! $fee_id ) {
  887. throw new WC_API_Exception( 'woocommerce_cannot_create_fee', __( 'Cannot create fee, try again', 'woocommerce' ), 500 );
  888. }
  889. } else {
  890. $fee_args = array();
  891. if ( isset( $fee['title'] ) ) {
  892. $fee_args['name'] = $fee['title'];
  893. }
  894. if ( isset( $fee['tax_class'] ) ) {
  895. $fee_args['tax_class'] = $fee['tax_class'];
  896. }
  897. if ( isset( $fee['total'] ) ) {
  898. $fee_args['line_total'] = floatval( $fee['total'] );
  899. }
  900. if ( isset( $fee['total_tax'] ) ) {
  901. $fee_args['line_tax'] = floatval( $fee['total_tax'] );
  902. }
  903. $fee_id = $order->update_fee( $fee['id'], $fee_args );
  904. if ( ! $fee_id ) {
  905. throw new WC_API_Exception( 'woocommerce_cannot_update_fee', __( 'Cannot update fee, try again', 'woocommerce' ), 500 );
  906. }
  907. }
  908. }
  909. /**
  910. * Create or update an order coupon
  911. *
  912. * @since 2.2
  913. * @param \WC_Order $order
  914. * @param array $coupon item data
  915. * @param string $action 'create' to add coupon or 'update' to update it
  916. * @throws WC_API_Exception invalid data, server error
  917. */
  918. protected function set_coupon( $order, $coupon, $action ) {
  919. // coupon amount must be positive float
  920. if ( isset( $coupon['amount'] ) && floatval( $coupon['amount'] ) < 0 ) {
  921. throw new WC_API_Exception( 'woocommerce_invalid_coupon_total', __( 'Coupon discount total must be a positive amount', 'woocommerce' ), 400 );
  922. }
  923. if ( 'create' === $action ) {
  924. // coupon code is required
  925. if ( empty( $coupon['code'] ) ) {
  926. throw new WC_API_Exception( 'woocommerce_invalid_coupon_coupon', __( 'Coupon code is required', 'woocommerce' ), 400 );
  927. }
  928. $coupon_id = $order->add_coupon( $coupon['code'], isset( $coupon['amount'] ) ? floatval( $coupon['amount'] ) : 0 );
  929. if ( ! $coupon_id ) {
  930. throw new WC_API_Exception( 'woocommerce_cannot_create_order_coupon', __( 'Cannot create coupon, try again', 'woocommerce' ), 500 );
  931. }
  932. } else {
  933. $coupon_args = array();
  934. if ( isset( $coupon['code'] ) ) {
  935. $coupon_args['code'] = $coupon['code'];
  936. }
  937. if ( isset( $coupon['amount'] ) ) {
  938. $coupon_args['discount_amount'] = floatval( $coupon['amount'] );
  939. }
  940. $coupon_id = $order->update_coupon( $coupon['id'], $coupon_args );
  941. if ( ! $coupon_id ) {
  942. throw new WC_API_Exception( 'woocommerce_cannot_update_order_coupon', __( 'Cannot update coupon, try again', 'woocommerce' ), 500 );
  943. }
  944. }
  945. }
  946. /**
  947. * Get the admin order notes for an order
  948. *
  949. * @since 2.1
  950. * @param string $order_id order ID
  951. * @param string|null $fields fields to include in response
  952. * @return array
  953. */
  954. public function get_order_notes( $order_id, $fields = null ) {
  955. // ensure ID is valid order ID
  956. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  957. if ( is_wp_error( $order_id ) ) {
  958. return $order_id;
  959. }
  960. $args = array(
  961. 'post_id' => $order_id,
  962. 'approve' => 'approve',
  963. 'type' => 'order_note'
  964. );
  965. remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  966. $notes = get_comments( $args );
  967. add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  968. $order_notes = array();
  969. foreach ( $notes as $note ) {
  970. $order_notes[] = current( $this->get_order_note( $order_id, $note->comment_ID, $fields ) );
  971. }
  972. return array( 'order_notes' => apply_filters( 'woocommerce_api_order_notes_response', $order_notes, $order_id, $fields, $notes, $this->server ) );
  973. }
  974. /**
  975. * Get an order note for the given order ID and ID
  976. *
  977. * @since 2.2
  978. * @param string $order_id order ID
  979. * @param string $id order note ID
  980. * @param string|null $fields fields to limit response to
  981. * @return array
  982. */
  983. public function get_order_note( $order_id, $id, $fields = null ) {
  984. try {
  985. // Validate order ID
  986. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  987. if ( is_wp_error( $order_id ) ) {
  988. return $order_id;
  989. }
  990. $id = absint( $id );
  991. if ( empty( $id ) ) {
  992. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  993. }
  994. $note = get_comment( $id );
  995. if ( is_null( $note ) ) {
  996. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  997. }
  998. $order_note = array(
  999. 'id' => $note->comment_ID,
  1000. 'created_at' => $this->server->format_datetime( $note->comment_date_gmt ),
  1001. 'note' => $note->comment_content,
  1002. 'customer_note' => get_comment_meta( $note->comment_ID, 'is_customer_note', true ) ? true : false,
  1003. );
  1004. return array( 'order_note' => apply_filters( 'woocommerce_api_order_note_response', $order_note, $id, $fields, $note, $order_id, $this ) );
  1005. } catch ( WC_API_Exception $e ) {
  1006. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1007. }
  1008. }
  1009. /**
  1010. * Create a new order note for the given order
  1011. *
  1012. * @since 2.2
  1013. * @param string $order_id order ID
  1014. * @param array $data raw request data
  1015. * @return WP_Error|array error or created note response data
  1016. */
  1017. public function create_order_note( $order_id, $data ) {
  1018. try {
  1019. if ( ! isset( $data['order_note'] ) ) {
  1020. throw new WC_API_Exception( 'woocommerce_api_missing_order_note_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'order_note' ), 400 );
  1021. }
  1022. $data = $data['order_note'];
  1023. // permission check
  1024. if ( ! current_user_can( 'publish_shop_orders' ) ) {
  1025. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_order_note', __( 'You do not have permission to create order notes', 'woocommerce' ), 401 );
  1026. }
  1027. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1028. if ( is_wp_error( $order_id ) ) {
  1029. return $order_id;
  1030. }
  1031. $order = wc_get_order( $order_id );
  1032. $data = apply_filters( 'woocommerce_api_create_order_note_data', $data, $order_id, $this );
  1033. // note content is required
  1034. if ( ! isset( $data['note'] ) ) {
  1035. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note', __( 'Order note is required', 'woocommerce' ), 400 );
  1036. }
  1037. $is_customer_note = ( isset( $data['customer_note'] ) && true === $data['customer_note'] );
  1038. // create the note
  1039. $note_id = $order->add_order_note( $data['note'], $is_customer_note );
  1040. if ( ! $note_id ) {
  1041. throw new WC_API_Exception( 'woocommerce_api_cannot_create_order_note', __( 'Cannot create order note, please try again', 'woocommerce' ), 500 );
  1042. }
  1043. // HTTP 201 Created
  1044. $this->server->send_status( 201 );
  1045. do_action( 'woocommerce_api_create_order_note', $note_id, $order_id, $this );
  1046. return $this->get_order_note( $order->id, $note_id );
  1047. } catch ( WC_API_Exception $e ) {
  1048. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1049. }
  1050. }
  1051. /**
  1052. * Edit the order note
  1053. *
  1054. * @since 2.2
  1055. * @param string $order_id order ID
  1056. * @param string $id note ID
  1057. * @param array $data parsed request data
  1058. * @return WP_Error|array error or edited note response data
  1059. */
  1060. public function edit_order_note( $order_id, $id, $data ) {
  1061. try {
  1062. if ( ! isset( $data['order_note'] ) ) {
  1063. throw new WC_API_Exception( 'woocommerce_api_missing_order_note_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'order_note' ), 400 );
  1064. }
  1065. $data = $data['order_note'];
  1066. // Validate order ID
  1067. $order_id = $this->validate_request( $order_id, $this->post_type, 'edit' );
  1068. if ( is_wp_error( $order_id ) ) {
  1069. return $order_id;
  1070. }
  1071. $order = wc_get_order( $order_id );
  1072. // Validate note ID
  1073. $id = absint( $id );
  1074. if ( empty( $id ) ) {
  1075. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1076. }
  1077. // Ensure note ID is valid
  1078. $note = get_comment( $id );
  1079. if ( is_null( $note ) ) {
  1080. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1081. }
  1082. // Ensure note ID is associated with given order
  1083. if ( $note->comment_post_ID != $order->id ) {
  1084. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
  1085. }
  1086. $data = apply_filters( 'woocommerce_api_edit_order_note_data', $data, $note->comment_ID, $order->id, $this );
  1087. // Note content
  1088. if ( isset( $data['note'] ) ) {
  1089. wp_update_comment(
  1090. array(
  1091. 'comment_ID' => $note->comment_ID,
  1092. 'comment_content' => $data['note'],
  1093. )
  1094. );
  1095. }
  1096. // Customer note
  1097. if ( isset( $data['customer_note'] ) ) {
  1098. update_comment_meta( $note->comment_ID, 'is_customer_note', true === $data['customer_note'] ? 1 : 0 );
  1099. }
  1100. do_action( 'woocommerce_api_edit_order_note', $note->comment_ID, $order->id, $this );
  1101. return $this->get_order_note( $order->id, $note->comment_ID );
  1102. } catch ( WC_API_Exception $e ) {
  1103. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1104. }
  1105. }
  1106. /**
  1107. * Delete order note
  1108. *
  1109. * @since 2.2
  1110. * @param string $order_id order ID
  1111. * @param string $id note ID
  1112. * @return WP_Error|array error or deleted message
  1113. */
  1114. public function delete_order_note( $order_id, $id ) {
  1115. try {
  1116. $order_id = $this->validate_request( $order_id, $this->post_type, 'delete' );
  1117. if ( is_wp_error( $order_id ) ) {
  1118. return $order_id;
  1119. }
  1120. // Validate note ID
  1121. $id = absint( $id );
  1122. if ( empty( $id ) ) {
  1123. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'Invalid order note ID', 'woocommerce' ), 400 );
  1124. }
  1125. // Ensure note ID is valid
  1126. $note = get_comment( $id );
  1127. if ( is_null( $note ) ) {
  1128. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'An order note with the provided ID could not be found', 'woocommerce' ), 404 );
  1129. }
  1130. // Ensure note ID is associated with given order
  1131. if ( $note->comment_post_ID != $order_id ) {
  1132. throw new WC_API_Exception( 'woocommerce_api_invalid_order_note_id', __( 'The order note ID provided is not associated with the order', 'woocommerce' ), 400 );
  1133. }
  1134. // Force delete since trashed order notes could not be managed through comments list table
  1135. $result = wp_delete_comment( $note->comment_ID, true );
  1136. if ( ! $result ) {
  1137. throw new WC_API_Exception( 'woocommerce_api_cannot_delete_order_note', __( 'This order note cannot be deleted', 'woocommerce' ), 500 );
  1138. }
  1139. do_action( 'woocommerce_api_delete_order_note', $note->comment_ID, $order_id, $this );
  1140. return array( 'message' => __( 'Permanently deleted order note', 'woocommerce' ) );
  1141. } catch ( WC_API_Exception $e ) {
  1142. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  1143. }
  1144. }
  1145. /**
  1146. * Get the order refunds for an order
  1147. *
  1148. * @since 2.2
  1149. * @param string $order_id order ID
  1150. * @param string|null $fields fields to include in response
  1151. * @return array
  1152. */
  1153. public function get_order_refunds( $order_id, $fields = null ) {
  1154. // Ensure ID is valid order ID
  1155. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1156. if ( is_wp_error( $order_id ) ) {
  1157. return $order_id;
  1158. }
  1159. $refund_items = get_posts(
  1160. array(
  1161. 'post_type' => 'shop_order_refund',
  1162. 'post_parent' => $order_id,
  1163. 'posts_per_page' => -1,
  1164. 'post_status' => 'any',
  1165. 'fields' => 'ids'
  1166. )
  1167. );
  1168. $order_refunds = array();
  1169. foreach ( $refund_items as $refund_id ) {
  1170. $order_refunds[] = current( $this->get_order_refund( $order_id, $refund_id, $fields ) );
  1171. }
  1172. return array( 'order_refunds' => apply_filters( 'woocommerce_api_order_refunds_response', $order_refunds, $order_id, $fields, $refund_items, $this ) );
  1173. }
  1174. /**
  1175. * Get an order refund for the given order ID and ID
  1176. *
  1177. * @since 2.2
  1178. * @param string $order_id order ID
  1179. * @param string|null $fields fields to limit response to
  1180. * @return array
  1181. */
  1182. public function get_order_refund( $order_id, $id, $fields = null ) {
  1183. try {
  1184. // Validate order ID
  1185. $order_id = $this->validate_request( $order_id, $this->post_type, 'read' );
  1186. if ( is_wp_error( $order_id ) ) {
  1187. return $order_id;
  1188. }
  1189. $id = absint( $id );
  1190. if ( empty( $id ) ) {
  1191. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'Invalid order refund ID', 'woocommerce' ), 400 );
  1192. }
  1193. $order = wc_get_order( $id );
  1194. $refund = wc_get_order( $id );
  1195. if ( ! $refund ) {
  1196. throw new WC_API_Exception( 'woocommerce_api_invalid_order_refund_id', __( 'An order refund with the provided ID could not be found', 'woocommerce' ), 404 );
  1197. }
  1198. $line_items = array();
  1199. // Add line items
  1200. foreach ( $refund->get_items( 'line_item' ) as $item_id => $item ) {
  1201. $product = $order->get_product_from_item( $item );
  1202. $meta = new WC_Order_Item_Meta( $item, $product );
  1203. $item_meta = array();
  1204. foreach ( $meta->get_formatted() as $meta_key => $formatted_meta ) {
  1205. $item_meta[] = array(
  1206. 'key' => $meta_key,
  1207. 'label' => $formatted_meta['label'],
  1208. 'value' => $formatted_meta['value'],
  1209. );
  1210. }
  1211. $line_items[] = array(
  1212. 'id' => $item_id,
  1213. 'subtotal' => wc_format_decimal( $order->get_line_subtotal( $item ), 2 ),
  1214. 'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], 2 ),
  1215. 'total' => wc_format_decimal( $order->get_line_total( $item ), 2 ),
  1216. 'total_tax' => wc_format_decimal( $order->get_line_tax( $item ), 2 ),
  1217. 'price' => wc_format_decimal( $order->get_item_total( $item ), 2 ),
  1218. 'quantity' => (int) $item['qty'],
  1219. 'tax_class' => ( ! empty( $item['tax_class'] ) ) ? $item['tax_class'] : null,
  1220. 'name' => $item['name'],
  1221. 'product_id' => ( isset( $product->variation_id ) ) ? $product->variation_id : $product->id,
  1222. 'sku' => is_object( $product ) ? $product->get_sku() : null,
  1223. 'meta'