wc-order-functions.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. <?php
  2. /**
  3. * WooCommerce Order Functions
  4. *
  5. * Functions for order specific things.
  6. *
  7. * @package WooCommerce/Functions
  8. * @version 3.4.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Standard way of retrieving orders based on certain parameters.
  13. *
  14. * This function should be used for order retrieval so that when we move to
  15. * custom tables, functions still work.
  16. *
  17. * Args and usage: https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query
  18. *
  19. * @since 2.6.0
  20. * @param array $args Array of args (above).
  21. * @return WC_Order[]|stdClass Number of pages and an array of order objects if
  22. * paginate is true, or just an array of values.
  23. */
  24. function wc_get_orders( $args ) {
  25. $map_legacy = array(
  26. 'numberposts' => 'limit',
  27. 'post_type' => 'type',
  28. 'post_status' => 'status',
  29. 'post_parent' => 'parent',
  30. 'author' => 'customer',
  31. 'email' => 'billing_email',
  32. 'posts_per_page' => 'limit',
  33. 'paged' => 'page',
  34. );
  35. foreach ( $map_legacy as $from => $to ) {
  36. if ( isset( $args[ $from ] ) ) {
  37. $args[ $to ] = $args[ $from ];
  38. }
  39. }
  40. // Map legacy date args to modern date args.
  41. $date_before = false;
  42. $date_after = false;
  43. if ( ! empty( $args['date_before'] ) ) {
  44. $datetime = wc_string_to_datetime( $args['date_before'] );
  45. $date_before = strpos( $args['date_before'], ':' ) ? $datetime->getOffsetTimestamp() : $datetime->date( 'Y-m-d' );
  46. }
  47. if ( ! empty( $args['date_after'] ) ) {
  48. $datetime = wc_string_to_datetime( $args['date_after'] );
  49. $date_after = strpos( $args['date_after'], ':' ) ? $datetime->getOffsetTimestamp() : $datetime->date( 'Y-m-d' );
  50. }
  51. if ( $date_before && $date_after ) {
  52. $args['date_created'] = $date_after . '...' . $date_before;
  53. } elseif ( $date_before ) {
  54. $args['date_created'] = '<' . $date_before;
  55. } elseif ( $date_after ) {
  56. $args['date_created'] = '>' . $date_after;
  57. }
  58. $query = new WC_Order_Query( $args );
  59. return $query->get_orders();
  60. }
  61. /**
  62. * Main function for returning orders, uses the WC_Order_Factory class.
  63. *
  64. * @since 2.2
  65. *
  66. * @param mixed $the_order Post object or post ID of the order.
  67. *
  68. * @return bool|WC_Order|WC_Refund
  69. */
  70. function wc_get_order( $the_order = false ) {
  71. if ( ! did_action( 'woocommerce_after_register_post_type' ) ) {
  72. wc_doing_it_wrong( __FUNCTION__, 'wc_get_order should not be called before post types are registered (woocommerce_after_register_post_type action)', '2.5' );
  73. return false;
  74. }
  75. return WC()->order_factory->get_order( $the_order );
  76. }
  77. /**
  78. * Get all order statuses.
  79. *
  80. * @since 2.2
  81. * @used-by WC_Order::set_status
  82. * @return array
  83. */
  84. function wc_get_order_statuses() {
  85. $order_statuses = array(
  86. 'wc-pending' => _x( 'Pending payment', 'Order status', 'woocommerce' ),
  87. 'wc-processing' => _x( 'Processing', 'Order status', 'woocommerce' ),
  88. 'wc-on-hold' => _x( 'On hold', 'Order status', 'woocommerce' ),
  89. 'wc-completed' => _x( 'Completed', 'Order status', 'woocommerce' ),
  90. 'wc-cancelled' => _x( 'Cancelled', 'Order status', 'woocommerce' ),
  91. 'wc-refunded' => _x( 'Refunded', 'Order status', 'woocommerce' ),
  92. 'wc-failed' => _x( 'Failed', 'Order status', 'woocommerce' ),
  93. );
  94. return apply_filters( 'wc_order_statuses', $order_statuses );
  95. }
  96. /**
  97. * See if a string is an order status.
  98. *
  99. * @param string $maybe_status Status, including any wc- prefix.
  100. * @return bool
  101. */
  102. function wc_is_order_status( $maybe_status ) {
  103. $order_statuses = wc_get_order_statuses();
  104. return isset( $order_statuses[ $maybe_status ] );
  105. }
  106. /**
  107. * Get list of statuses which are consider 'paid'.
  108. *
  109. * @since 3.0.0
  110. * @return array
  111. */
  112. function wc_get_is_paid_statuses() {
  113. return apply_filters( 'woocommerce_order_is_paid_statuses', array( 'processing', 'completed' ) );
  114. }
  115. /**
  116. * Get the nice name for an order status.
  117. *
  118. * @since 2.2
  119. * @param string $status Status.
  120. * @return string
  121. */
  122. function wc_get_order_status_name( $status ) {
  123. $statuses = wc_get_order_statuses();
  124. $status = 'wc-' === substr( $status, 0, 3 ) ? substr( $status, 3 ) : $status;
  125. $status = isset( $statuses[ 'wc-' . $status ] ) ? $statuses[ 'wc-' . $status ] : $status;
  126. return $status;
  127. }
  128. /**
  129. * Finds an Order ID based on an order key.
  130. *
  131. * @param string $order_key An order key has generated by.
  132. * @return int The ID of an order, or 0 if the order could not be found.
  133. */
  134. function wc_get_order_id_by_order_key( $order_key ) {
  135. $data_store = WC_Data_Store::load( 'order' );
  136. return $data_store->get_order_id_by_order_key( $order_key );
  137. }
  138. /**
  139. * Get all registered order types.
  140. *
  141. * @since 2.2
  142. * @param string $for Optionally define what you are getting order types for so
  143. * only relevant types are returned.
  144. * e.g. for 'order-meta-boxes', 'order-count'.
  145. * @return array
  146. */
  147. function wc_get_order_types( $for = '' ) {
  148. global $wc_order_types;
  149. if ( ! is_array( $wc_order_types ) ) {
  150. $wc_order_types = array();
  151. }
  152. $order_types = array();
  153. switch ( $for ) {
  154. case 'order-count':
  155. foreach ( $wc_order_types as $type => $args ) {
  156. if ( ! $args['exclude_from_order_count'] ) {
  157. $order_types[] = $type;
  158. }
  159. }
  160. break;
  161. case 'order-meta-boxes':
  162. foreach ( $wc_order_types as $type => $args ) {
  163. if ( $args['add_order_meta_boxes'] ) {
  164. $order_types[] = $type;
  165. }
  166. }
  167. break;
  168. case 'view-orders':
  169. foreach ( $wc_order_types as $type => $args ) {
  170. if ( ! $args['exclude_from_order_views'] ) {
  171. $order_types[] = $type;
  172. }
  173. }
  174. break;
  175. case 'reports':
  176. foreach ( $wc_order_types as $type => $args ) {
  177. if ( ! $args['exclude_from_order_reports'] ) {
  178. $order_types[] = $type;
  179. }
  180. }
  181. break;
  182. case 'sales-reports':
  183. foreach ( $wc_order_types as $type => $args ) {
  184. if ( ! $args['exclude_from_order_sales_reports'] ) {
  185. $order_types[] = $type;
  186. }
  187. }
  188. break;
  189. case 'order-webhooks':
  190. foreach ( $wc_order_types as $type => $args ) {
  191. if ( ! $args['exclude_from_order_webhooks'] ) {
  192. $order_types[] = $type;
  193. }
  194. }
  195. break;
  196. default:
  197. $order_types = array_keys( $wc_order_types );
  198. break;
  199. }
  200. return apply_filters( 'wc_order_types', $order_types, $for );
  201. }
  202. /**
  203. * Get an order type by post type name.
  204. *
  205. * @param string $type Post type name.
  206. * @return bool|array Details about the order type.
  207. */
  208. function wc_get_order_type( $type ) {
  209. global $wc_order_types;
  210. if ( isset( $wc_order_types[ $type ] ) ) {
  211. return $wc_order_types[ $type ];
  212. } else {
  213. return false;
  214. }
  215. }
  216. /**
  217. * Register order type. Do not use before init.
  218. *
  219. * Wrapper for register post type, as well as a method of telling WC which.
  220. * post types are types of orders, and having them treated as such.
  221. *
  222. * $args are passed to register_post_type, but there are a few specific to this function:
  223. * - exclude_from_orders_screen (bool) Whether or not this order type also get shown in the main.
  224. * orders screen.
  225. * - add_order_meta_boxes (bool) Whether or not the order type gets shop_order meta boxes.
  226. * - exclude_from_order_count (bool) Whether or not this order type is excluded from counts.
  227. * - exclude_from_order_views (bool) Whether or not this order type is visible by customers when.
  228. * viewing orders e.g. on the my account page.
  229. * - exclude_from_order_reports (bool) Whether or not to exclude this type from core reports.
  230. * - exclude_from_order_sales_reports (bool) Whether or not to exclude this type from core sales reports.
  231. *
  232. * @since 2.2
  233. * @see register_post_type for $args used in that function
  234. * @param string $type Post type. (max. 20 characters, can not contain capital letters or spaces).
  235. * @param array $args An array of arguments.
  236. * @return bool Success or failure
  237. */
  238. function wc_register_order_type( $type, $args = array() ) {
  239. if ( post_type_exists( $type ) ) {
  240. return false;
  241. }
  242. global $wc_order_types;
  243. if ( ! is_array( $wc_order_types ) ) {
  244. $wc_order_types = array();
  245. }
  246. // Register as a post type.
  247. if ( is_wp_error( register_post_type( $type, $args ) ) ) {
  248. return false;
  249. }
  250. // Register for WC usage.
  251. $order_type_args = array(
  252. 'exclude_from_orders_screen' => false,
  253. 'add_order_meta_boxes' => true,
  254. 'exclude_from_order_count' => false,
  255. 'exclude_from_order_views' => false,
  256. 'exclude_from_order_webhooks' => false,
  257. 'exclude_from_order_reports' => false,
  258. 'exclude_from_order_sales_reports' => false,
  259. 'class_name' => 'WC_Order',
  260. );
  261. $args = array_intersect_key( $args, $order_type_args );
  262. $args = wp_parse_args( $args, $order_type_args );
  263. $wc_order_types[ $type ] = $args;
  264. return true;
  265. }
  266. /**
  267. * Return the count of processing orders.
  268. *
  269. * @access public
  270. * @return int
  271. */
  272. function wc_processing_order_count() {
  273. return wc_orders_count( 'processing' );
  274. }
  275. /**
  276. * Return the orders count of a specific order status.
  277. *
  278. * @param string $status Status.
  279. * @return int
  280. */
  281. function wc_orders_count( $status ) {
  282. $count = 0;
  283. $status = 'wc-' . $status;
  284. $order_statuses = array_keys( wc_get_order_statuses() );
  285. if ( ! in_array( $status, $order_statuses, true ) ) {
  286. return 0;
  287. }
  288. $cache_key = WC_Cache_Helper::get_cache_prefix( 'orders' ) . $status;
  289. $cached_count = wp_cache_get( $cache_key, 'counts' );
  290. if ( false !== $cached_count ) {
  291. return $cached_count;
  292. }
  293. foreach ( wc_get_order_types( 'order-count' ) as $type ) {
  294. $data_store = WC_Data_Store::load( 'shop_order' === $type ? 'order' : $type );
  295. if ( $data_store ) {
  296. $count += $data_store->get_order_count( $status );
  297. }
  298. }
  299. wp_cache_set( $cache_key, $count, 'counts' );
  300. return $count;
  301. }
  302. /**
  303. * Grant downloadable product access to the file identified by $download_id.
  304. *
  305. * @param string $download_id File identifier.
  306. * @param int|WC_Product $product Product instance or ID.
  307. * @param WC_Order $order Order data.
  308. * @param int $qty Quantity purchased.
  309. * @return int|bool insert id or false on failure.
  310. */
  311. function wc_downloadable_file_permission( $download_id, $product, $order, $qty = 1 ) {
  312. if ( is_numeric( $product ) ) {
  313. $product = wc_get_product( $product );
  314. }
  315. $download = new WC_Customer_Download();
  316. $download->set_download_id( $download_id );
  317. $download->set_product_id( $product->get_id() );
  318. $download->set_user_id( $order->get_customer_id() );
  319. $download->set_order_id( $order->get_id() );
  320. $download->set_user_email( $order->get_billing_email() );
  321. $download->set_order_key( $order->get_order_key() );
  322. $download->set_downloads_remaining( 0 > $product->get_download_limit() ? '' : $product->get_download_limit() * $qty );
  323. $download->set_access_granted( current_time( 'timestamp', true ) );
  324. $download->set_download_count( 0 );
  325. $expiry = $product->get_download_expiry();
  326. if ( $expiry > 0 ) {
  327. $from_date = $order->get_date_completed() ? $order->get_date_completed()->format( 'Y-m-d' ) : current_time( 'mysql', true );
  328. $download->set_access_expires( strtotime( $from_date . ' + ' . $expiry . ' DAY' ) );
  329. }
  330. return $download->save();
  331. }
  332. /**
  333. * Order Status completed - give downloadable product access to customer.
  334. *
  335. * @param int $order_id Order ID.
  336. * @param bool $force Force downloadable permissions.
  337. */
  338. function wc_downloadable_product_permissions( $order_id, $force = false ) {
  339. $order = wc_get_order( $order_id );
  340. if ( ! $order || ( $order->get_data_store()->get_download_permissions_granted( $order ) && ! $force ) ) {
  341. return;
  342. }
  343. if ( $order->has_status( 'processing' ) && 'no' === get_option( 'woocommerce_downloads_grant_access_after_payment' ) ) {
  344. return;
  345. }
  346. if ( count( $order->get_items() ) > 0 ) {
  347. foreach ( $order->get_items() as $item ) {
  348. $product = $item->get_product();
  349. if ( $product && $product->exists() && $product->is_downloadable() ) {
  350. $downloads = $product->get_downloads();
  351. foreach ( array_keys( $downloads ) as $download_id ) {
  352. wc_downloadable_file_permission( $download_id, $product, $order, $item->get_quantity() );
  353. }
  354. }
  355. }
  356. }
  357. $order->get_data_store()->set_download_permissions_granted( $order, true );
  358. do_action( 'woocommerce_grant_product_download_permissions', $order_id );
  359. }
  360. add_action( 'woocommerce_order_status_completed', 'wc_downloadable_product_permissions' );
  361. add_action( 'woocommerce_order_status_processing', 'wc_downloadable_product_permissions' );
  362. /**
  363. * Clear all transients cache for order data.
  364. *
  365. * @param int|WC_Order $order Order instance or ID.
  366. */
  367. function wc_delete_shop_order_transients( $order = 0 ) {
  368. if ( is_numeric( $order ) ) {
  369. $order = wc_get_order( $order );
  370. }
  371. $reports = WC_Admin_Reports::get_reports();
  372. $transients_to_clear = array(
  373. 'wc_admin_report',
  374. );
  375. foreach ( $reports as $report_group ) {
  376. foreach ( $report_group['reports'] as $report_key => $report ) {
  377. $transients_to_clear[] = 'wc_report_' . $report_key;
  378. }
  379. }
  380. foreach ( $transients_to_clear as $transient ) {
  381. delete_transient( $transient );
  382. }
  383. // Clear money spent for user associated with order.
  384. if ( is_a( $order, 'WC_Order' ) ) {
  385. $order_id = $order->get_id();
  386. delete_user_meta( $order->get_customer_id(), '_money_spent' );
  387. delete_user_meta( $order->get_customer_id(), '_order_count' );
  388. } else {
  389. $order_id = 0;
  390. }
  391. // Increments the transient version to invalidate cache.
  392. WC_Cache_Helper::get_transient_version( 'orders', true );
  393. // Do the same for regular cache.
  394. WC_Cache_Helper::incr_cache_prefix( 'orders' );
  395. do_action( 'woocommerce_delete_shop_order_transients', $order_id );
  396. }
  397. /**
  398. * See if we only ship to billing addresses.
  399. *
  400. * @return bool
  401. */
  402. function wc_ship_to_billing_address_only() {
  403. return 'billing_only' === get_option( 'woocommerce_ship_to_destination' );
  404. }
  405. /**
  406. * Create a new order refund programmatically.
  407. *
  408. * Returns a new refund object on success which can then be used to add additional data.
  409. *
  410. * @since 2.2
  411. * @throws Exception Throws exceptions when fail to create, but returns WP_Error instead.
  412. * @param array $args New refund arguments.
  413. * @return WC_Order_Refund|WP_Error
  414. */
  415. function wc_create_refund( $args = array() ) {
  416. $default_args = array(
  417. 'amount' => 0,
  418. 'reason' => null,
  419. 'order_id' => 0,
  420. 'refund_id' => 0,
  421. 'line_items' => array(),
  422. 'refund_payment' => false,
  423. 'restock_items' => false,
  424. );
  425. try {
  426. $args = wp_parse_args( $args, $default_args );
  427. $order = wc_get_order( $args['order_id'] );
  428. if ( ! $order ) {
  429. throw new Exception( __( 'Invalid order ID.', 'woocommerce' ) );
  430. }
  431. $remaining_refund_amount = $order->get_remaining_refund_amount();
  432. $remaining_refund_items = $order->get_remaining_refund_items();
  433. $refund_item_count = 0;
  434. $refund = new WC_Order_Refund( $args['refund_id'] );
  435. if ( 0 > $args['amount'] || $args['amount'] > $remaining_refund_amount ) {
  436. throw new Exception( __( 'Invalid refund amount.', 'woocommerce' ) );
  437. }
  438. $refund->set_currency( $order->get_currency() );
  439. $refund->set_amount( $args['amount'] );
  440. $refund->set_parent_id( absint( $args['order_id'] ) );
  441. $refund->set_refunded_by( get_current_user_id() ? get_current_user_id() : 1 );
  442. if ( ! is_null( $args['reason'] ) ) {
  443. $refund->set_reason( $args['reason'] );
  444. }
  445. // Negative line items.
  446. if ( count( $args['line_items'] ) > 0 ) {
  447. $items = $order->get_items( array( 'line_item', 'fee', 'shipping' ) );
  448. foreach ( $items as $item_id => $item ) {
  449. if ( ! isset( $args['line_items'][ $item_id ] ) ) {
  450. continue;
  451. }
  452. $qty = isset( $args['line_items'][ $item_id ]['qty'] ) ? $args['line_items'][ $item_id ]['qty'] : 0;
  453. $refund_total = $args['line_items'][ $item_id ]['refund_total'];
  454. $refund_tax = isset( $args['line_items'][ $item_id ]['refund_tax'] ) ? array_filter( (array) $args['line_items'][ $item_id ]['refund_tax'] ) : array();
  455. if ( empty( $qty ) && empty( $refund_total ) && empty( $args['line_items'][ $item_id ]['refund_tax'] ) ) {
  456. continue;
  457. }
  458. $class = get_class( $item );
  459. $refunded_item = new $class( $item );
  460. $refunded_item->set_id( 0 );
  461. $refunded_item->add_meta_data( '_refunded_item_id', $item_id, true );
  462. $refunded_item->set_total( wc_format_refund_total( $refund_total ) );
  463. $refunded_item->set_taxes(
  464. array(
  465. 'total' => array_map( 'wc_format_refund_total', $refund_tax ),
  466. 'subtotal' => array_map( 'wc_format_refund_total', $refund_tax ),
  467. )
  468. );
  469. if ( is_callable( array( $refunded_item, 'set_subtotal' ) ) ) {
  470. $refunded_item->set_subtotal( wc_format_refund_total( $refund_total ) );
  471. }
  472. if ( is_callable( array( $refunded_item, 'set_quantity' ) ) ) {
  473. $refunded_item->set_quantity( $qty * -1 );
  474. }
  475. $refund->add_item( $refunded_item );
  476. $refund_item_count += $qty;
  477. }
  478. }
  479. $refund->update_taxes();
  480. $refund->calculate_totals( false );
  481. $refund->set_total( $args['amount'] * -1 );
  482. // this should remain after update_taxes(), as this will save the order, and write the current date to the db
  483. // so we must wait until the order is persisted to set the date.
  484. if ( isset( $args['date_created'] ) ) {
  485. $refund->set_date_created( $args['date_created'] );
  486. }
  487. /**
  488. * Action hook to adjust refund before save.
  489. *
  490. * @since 3.0.0
  491. */
  492. do_action( 'woocommerce_create_refund', $refund, $args );
  493. if ( $refund->save() ) {
  494. if ( $args['refund_payment'] ) {
  495. $result = wc_refund_payment( $order, $refund->get_amount(), $refund->get_reason() );
  496. if ( is_wp_error( $result ) ) {
  497. $refund->delete();
  498. return $result;
  499. }
  500. $refund->set_refunded_payment( true );
  501. $refund->save();
  502. }
  503. if ( $args['restock_items'] ) {
  504. wc_restock_refunded_items( $order, $args['line_items'] );
  505. }
  506. // Trigger notification emails.
  507. if ( ( $remaining_refund_amount - $args['amount'] ) > 0 || ( $order->has_free_item() && ( $remaining_refund_items - $refund_item_count ) > 0 ) ) {
  508. do_action( 'woocommerce_order_partially_refunded', $order->get_id(), $refund->get_id() );
  509. } else {
  510. do_action( 'woocommerce_order_fully_refunded', $order->get_id(), $refund->get_id() );
  511. $parent_status = apply_filters( 'woocommerce_order_fully_refunded_status', 'refunded', $order->get_id(), $refund->get_id() );
  512. if ( $parent_status ) {
  513. $order->update_status( $parent_status );
  514. }
  515. }
  516. }
  517. do_action( 'woocommerce_refund_created', $refund->get_id(), $args );
  518. do_action( 'woocommerce_order_refunded', $order->get_id(), $refund->get_id() );
  519. } catch ( Exception $e ) {
  520. if ( isset( $refund ) && is_a( $refund, 'WC_Order_Refund' ) ) {
  521. wp_delete_post( $refund->get_id(), true );
  522. }
  523. return new WP_Error( 'error', $e->getMessage() );
  524. }
  525. return $refund;
  526. }
  527. /**
  528. * Try to refund the payment for an order via the gateway.
  529. *
  530. * @since 3.0.0
  531. * @throws Exception Throws exceptions when fail to refund, but returns WP_Error instead.
  532. * @param WC_Order $order Order instance.
  533. * @param string $amount Amount to refund.
  534. * @param string $reason Refund reason.
  535. * @return bool|WP_Error
  536. */
  537. function wc_refund_payment( $order, $amount, $reason = '' ) {
  538. try {
  539. if ( ! is_a( $order, 'WC_Order' ) ) {
  540. throw new Exception( __( 'Invalid order.', 'woocommerce' ) );
  541. }
  542. $gateway_controller = WC_Payment_Gateways::instance();
  543. $all_gateways = $gateway_controller->payment_gateways();
  544. $payment_method = $order->get_payment_method();
  545. $gateway = isset( $all_gateways[ $payment_method ] ) ? $all_gateways[ $payment_method ] : false;
  546. if ( ! $gateway ) {
  547. throw new Exception( __( 'The payment gateway for this order does not exist.', 'woocommerce' ) );
  548. }
  549. if ( ! $gateway->supports( 'refunds' ) ) {
  550. throw new Exception( __( 'The payment gateway for this order does not support automatic refunds.', 'woocommerce' ) );
  551. }
  552. $result = $gateway->process_refund( $order->get_id(), $amount, $reason );
  553. if ( ! $result ) {
  554. throw new Exception( __( 'An error occurred while attempting to create the refund using the payment gateway API.', 'woocommerce' ) );
  555. }
  556. if ( is_wp_error( $result ) ) {
  557. throw new Exception( $result->get_error_message() );
  558. }
  559. return true;
  560. } catch ( Exception $e ) {
  561. return new WP_Error( 'error', $e->getMessage() );
  562. }
  563. }
  564. /**
  565. * Restock items during refund.
  566. *
  567. * @since 3.0.0
  568. * @param WC_Order $order Order instance.
  569. * @param array $refunded_line_items Refunded items list.
  570. */
  571. function wc_restock_refunded_items( $order, $refunded_line_items ) {
  572. $line_items = $order->get_items();
  573. foreach ( $line_items as $item_id => $item ) {
  574. if ( ! isset( $refunded_line_items[ $item_id ], $refunded_line_items[ $item_id ]['qty'] ) ) {
  575. continue;
  576. }
  577. $product = $item->get_product();
  578. if ( $product && $product->managing_stock() ) {
  579. $old_stock = $product->get_stock_quantity();
  580. $new_stock = wc_update_product_stock( $product, $refunded_line_items[ $item_id ]['qty'], 'increase' );
  581. /* translators: 1: product ID 2: old stock level 3: new stock level */
  582. $order->add_order_note( sprintf( __( 'Item #%1$s stock increased from %2$s to %3$s.', 'woocommerce' ), $product->get_id(), $old_stock, $new_stock ) );
  583. do_action( 'woocommerce_restock_refunded_item', $product->get_id(), $old_stock, $new_stock, $order, $product );
  584. }
  585. }
  586. }
  587. /**
  588. * Get tax class by tax id.
  589. *
  590. * @since 2.2
  591. * @param int $tax_id Tax ID.
  592. * @return string
  593. */
  594. function wc_get_tax_class_by_tax_id( $tax_id ) {
  595. global $wpdb;
  596. return $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_class FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %d", $tax_id ) );
  597. }
  598. /**
  599. * Get payment gateway class by order data.
  600. *
  601. * @since 2.2
  602. * @param int|WC_Order $order Order instance.
  603. * @return WC_Payment_Gateway|bool
  604. */
  605. function wc_get_payment_gateway_by_order( $order ) {
  606. if ( WC()->payment_gateways() ) {
  607. $payment_gateways = WC()->payment_gateways()->payment_gateways();
  608. } else {
  609. $payment_gateways = array();
  610. }
  611. if ( ! is_object( $order ) ) {
  612. $order_id = absint( $order );
  613. $order = wc_get_order( $order_id );
  614. }
  615. return is_a( $order, 'WC_Order' ) && isset( $payment_gateways[ $order->get_payment_method() ] ) ? $payment_gateways[ $order->get_payment_method() ] : false;
  616. }
  617. /**
  618. * When refunding an order, create a refund line item if the partial refunds do not match order total.
  619. *
  620. * This is manual; no gateway refund will be performed.
  621. *
  622. * @since 2.4
  623. * @param int $order_id Order ID.
  624. */
  625. function wc_order_fully_refunded( $order_id ) {
  626. $order = wc_get_order( $order_id );
  627. $max_refund = wc_format_decimal( $order->get_total() - $order->get_total_refunded() );
  628. if ( ! $max_refund ) {
  629. return;
  630. }
  631. // Create the refund object.
  632. wc_create_refund(
  633. array(
  634. 'amount' => $max_refund,
  635. 'reason' => __( 'Order fully refunded', 'woocommerce' ),
  636. 'order_id' => $order_id,
  637. 'line_items' => array(),
  638. )
  639. );
  640. }
  641. add_action( 'woocommerce_order_status_refunded', 'wc_order_fully_refunded' );
  642. /**
  643. * Search orders.
  644. *
  645. * @since 2.6.0
  646. * @param string $term Term to search.
  647. * @return array List of orders ID.
  648. */
  649. function wc_order_search( $term ) {
  650. $data_store = WC_Data_Store::load( 'order' );
  651. return $data_store->search_orders( str_replace( 'Order #', '', wc_clean( $term ) ) );
  652. }
  653. /**
  654. * Update total sales amount for each product within a paid order.
  655. *
  656. * @since 3.0.0
  657. * @param int $order_id Order ID.
  658. */
  659. function wc_update_total_sales_counts( $order_id ) {
  660. $order = wc_get_order( $order_id );
  661. if ( ! $order || $order->get_data_store()->get_recorded_sales( $order ) ) {
  662. return;
  663. }
  664. if ( count( $order->get_items() ) > 0 ) {
  665. foreach ( $order->get_items() as $item ) {
  666. $product_id = $item->get_product_id();
  667. if ( $product_id ) {
  668. $data_store = WC_Data_Store::load( 'product' );
  669. $data_store->update_product_sales( $product_id, absint( $item['qty'] ), 'increase' );
  670. }
  671. }
  672. }
  673. $order->get_data_store()->set_recorded_sales( $order, true );
  674. /**
  675. * Called when sales for an order are recorded
  676. *
  677. * @param int $order_id order id
  678. */
  679. do_action( 'woocommerce_recorded_sales', $order_id );
  680. }
  681. add_action( 'woocommerce_order_status_completed', 'wc_update_total_sales_counts' );
  682. add_action( 'woocommerce_order_status_processing', 'wc_update_total_sales_counts' );
  683. add_action( 'woocommerce_order_status_on-hold', 'wc_update_total_sales_counts' );
  684. /**
  685. * Update used coupon amount for each coupon within an order.
  686. *
  687. * @since 3.0.0
  688. * @param int $order_id Order ID.
  689. */
  690. function wc_update_coupon_usage_counts( $order_id ) {
  691. $order = wc_get_order( $order_id );
  692. if ( ! $order ) {
  693. return;
  694. }
  695. $has_recorded = $order->get_data_store()->get_recorded_coupon_usage_counts( $order );
  696. if ( $order->has_status( 'cancelled' ) && $has_recorded ) {
  697. $action = 'reduce';
  698. $order->get_data_store()->set_recorded_coupon_usage_counts( $order, false );
  699. } elseif ( ! $order->has_status( 'cancelled' ) && ! $has_recorded ) {
  700. $action = 'increase';
  701. $order->get_data_store()->set_recorded_coupon_usage_counts( $order, true );
  702. } else {
  703. return;
  704. }
  705. if ( count( $order->get_used_coupons() ) > 0 ) {
  706. foreach ( $order->get_used_coupons() as $code ) {
  707. if ( ! $code ) {
  708. continue;
  709. }
  710. $coupon = new WC_Coupon( $code );
  711. $used_by = $order->get_user_id();
  712. if ( ! $used_by ) {
  713. $used_by = $order->get_billing_email();
  714. }
  715. switch ( $action ) {
  716. case 'reduce':
  717. $coupon->decrease_usage_count( $used_by );
  718. break;
  719. case 'increase':
  720. $coupon->increase_usage_count( $used_by );
  721. break;
  722. }
  723. }
  724. }
  725. }
  726. add_action( 'woocommerce_order_status_pending', 'wc_update_coupon_usage_counts' );
  727. add_action( 'woocommerce_order_status_completed', 'wc_update_coupon_usage_counts' );
  728. add_action( 'woocommerce_order_status_processing', 'wc_update_coupon_usage_counts' );
  729. add_action( 'woocommerce_order_status_on-hold', 'wc_update_coupon_usage_counts' );
  730. add_action( 'woocommerce_order_status_cancelled', 'wc_update_coupon_usage_counts' );
  731. /**
  732. * Cancel all unpaid orders after held duration to prevent stock lock for those products.
  733. */
  734. function wc_cancel_unpaid_orders() {
  735. $held_duration = get_option( 'woocommerce_hold_stock_minutes' );
  736. if ( $held_duration < 1 || 'yes' !== get_option( 'woocommerce_manage_stock' ) ) {
  737. return;
  738. }
  739. $data_store = WC_Data_Store::load( 'order' );
  740. $unpaid_orders = $data_store->get_unpaid_orders( strtotime( '-' . absint( $held_duration ) . ' MINUTES', current_time( 'timestamp' ) ) );
  741. if ( $unpaid_orders ) {
  742. foreach ( $unpaid_orders as $unpaid_order ) {
  743. $order = wc_get_order( $unpaid_order );
  744. if ( apply_filters( 'woocommerce_cancel_unpaid_order', 'checkout' === $order->get_created_via(), $order ) ) {
  745. $order->update_status( 'cancelled', __( 'Unpaid order cancelled - time limit reached.', 'woocommerce' ) );
  746. }
  747. }
  748. }
  749. wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
  750. wp_schedule_single_event( time() + ( absint( $held_duration ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
  751. }
  752. add_action( 'woocommerce_cancel_unpaid_orders', 'wc_cancel_unpaid_orders' );
  753. /**
  754. * Sanitize order id removing unwanted characters.
  755. *
  756. * E.g Users can sometimes try to track an order id using # with no success.
  757. * This function will fix this.
  758. *
  759. * @since 3.1.0
  760. * @param int $order_id Order ID.
  761. */
  762. function wc_sanitize_order_id( $order_id ) {
  763. return filter_var( $order_id, FILTER_SANITIZE_NUMBER_INT );
  764. }
  765. add_filter( 'woocommerce_shortcode_order_tracking_order_id', 'wc_sanitize_order_id' );
  766. /**
  767. * Get an order note.
  768. *
  769. * @since 3.2.0
  770. * @param int|WP_Comment $data Note ID (or WP_Comment instance for internal use only).
  771. * @return stdClass|null Object with order note details or null when does not exists.
  772. */
  773. function wc_get_order_note( $data ) {
  774. if ( is_numeric( $data ) ) {
  775. $data = get_comment( $data );
  776. }
  777. if ( ! is_a( $data, 'WP_Comment' ) ) {
  778. return null;
  779. }
  780. return (object) apply_filters(
  781. 'woocommerce_get_order_note', array(
  782. 'id' => (int) $data->comment_ID,
  783. 'date_created' => wc_string_to_datetime( $data->comment_date ),
  784. 'content' => $data->comment_content,
  785. 'customer_note' => (bool) get_comment_meta( $data->comment_ID, 'is_customer_note', true ),
  786. 'added_by' => __( 'WooCommerce', 'woocommerce' ) === $data->comment_author ? 'system' : $data->comment_author,
  787. ), $data
  788. );
  789. }
  790. /**
  791. * Get order notes.
  792. *
  793. * @since 3.2.0
  794. * @param array $args Query arguments {
  795. * Array of query parameters.
  796. *
  797. * @type string $limit Maximum number of notes to retrieve.
  798. * Default empty (no limit).
  799. * @type int $order_id Limit results to those affiliated with a given order ID.
  800. * Default 0.
  801. * @type array $order__in Array of order IDs to include affiliated notes for.
  802. * Default empty.
  803. * @type array $order__not_in Array of order IDs to exclude affiliated notes for.
  804. * Default empty.
  805. * @type string $orderby Define how should sort notes.
  806. * Accepts 'date_created', 'date_created_gmt' or 'id'.
  807. * Default: 'id'.
  808. * @type string $order How to order retrieved notes.
  809. * Accepts 'ASC' or 'DESC'.
  810. * Default: 'DESC'.
  811. * @type string $type Define what type of note should retrieve.
  812. * Accepts 'customer', 'internal' or empty for both.
  813. * Default empty.
  814. * }
  815. * @return stdClass[] Array of stdClass objects with order notes details.
  816. */
  817. function wc_get_order_notes( $args ) {
  818. $key_mapping = array(
  819. 'limit' => 'number',
  820. 'order_id' => 'post_id',
  821. 'order__in' => 'post__in',
  822. 'order__not_in' => 'post__not_in',
  823. );
  824. foreach ( $key_mapping as $query_key => $db_key ) {
  825. if ( isset( $args[ $query_key ] ) ) {
  826. $args[ $db_key ] = $args[ $query_key ];
  827. unset( $args[ $query_key ] );
  828. }
  829. }
  830. // Define orderby.
  831. $orderby_mapping = array(
  832. 'date_created' => 'comment_date',
  833. 'date_created_gmt' => 'comment_date_gmt',
  834. 'id' => 'comment_ID',
  835. );
  836. $args['orderby'] = ! empty( $args['orderby'] ) && in_array( $args['orderby'], array( 'date_created', 'date_created_gmt', 'id' ), true ) ? $orderby_mapping[ $args['orderby'] ] : 'comment_ID';
  837. // Set WooCommerce order type.
  838. if ( isset( $args['type'] ) && 'customer' === $args['type'] ) {
  839. $args['meta_query'] = array( // WPCS: slow query ok.
  840. array(
  841. 'key' => 'is_customer_note',
  842. 'value' => 1,
  843. 'compare' => '=',
  844. ),
  845. );
  846. } elseif ( isset( $args['type'] ) && 'internal' === $args['type'] ) {
  847. $args['meta_query'] = array( // WPCS: slow query ok.
  848. array(
  849. 'key' => 'is_customer_note',
  850. 'compare' => 'NOT EXISTS',
  851. ),
  852. );
  853. }
  854. // Set correct comment type.
  855. $args['type'] = 'order_note';
  856. // Always approved.
  857. $args['status'] = 'approve';
  858. // Does not support 'count' or 'fields'.
  859. unset( $args['count'], $args['fields'] );
  860. remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  861. $notes = get_comments( $args );
  862. add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ), 10, 1 );
  863. return array_filter( array_map( 'wc_get_order_note', $notes ) );
  864. }
  865. /**
  866. * Create an order note.
  867. *
  868. * @since 3.2.0
  869. * @param int $order_id Order ID.
  870. * @param string $note Note to add.
  871. * @param bool $is_customer_note If is a costumer note.
  872. * @param bool $added_by_user If note is create by an user.
  873. * @return int|WP_Error Integer when created or WP_Error when found an error.
  874. */
  875. function wc_create_order_note( $order_id, $note, $is_customer_note = false, $added_by_user = false ) {
  876. $order = wc_get_order( $order_id );
  877. if ( ! $order ) {
  878. return new WP_Error( 'invalid_order_id', __( 'Invalid order ID.', 'woocommerce' ), array( 'status' => 400 ) );
  879. }
  880. return $order->add_order_note( $note, (int) $is_customer_note, $added_by_user );
  881. }
  882. /**
  883. * Delete an order note.
  884. *
  885. * @since 3.2.0
  886. * @param int $note_id Order note.
  887. * @return bool True on success, false on failure.
  888. */
  889. function wc_delete_order_note( $note_id ) {
  890. return wp_delete_comment( $note_id, true );
  891. }