Bez popisu

wc-order-functions.php 34KB

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