class-wc-discounts.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. <?php
  2. /**
  3. * Discount calculation
  4. *
  5. * @package WooCommerce/Classes
  6. * @since 3.2.0
  7. */
  8. defined( 'ABSPATH' ) || exit;
  9. /**
  10. * Discounts class.
  11. */
  12. class WC_Discounts {
  13. /**
  14. * Reference to cart or order object.
  15. *
  16. * @since 3.2.0
  17. * @var array
  18. */
  19. protected $object;
  20. /**
  21. * An array of items to discount.
  22. *
  23. * @var array
  24. */
  25. protected $items = array();
  26. /**
  27. * An array of discounts which have been applied to items.
  28. *
  29. * @var array[] Code => Item Key => Value
  30. */
  31. protected $discounts = array();
  32. /**
  33. * Constructor.
  34. *
  35. * @param array $object Cart or order object.
  36. */
  37. public function __construct( $object = array() ) {
  38. if ( is_a( $object, 'WC_Cart' ) ) {
  39. $this->set_items_from_cart( $object );
  40. } elseif ( is_a( $object, 'WC_Order' ) ) {
  41. $this->set_items_from_order( $object );
  42. }
  43. }
  44. /**
  45. * Set items directly. Used by WC_Cart_Totals.
  46. *
  47. * @since 3.2.3
  48. * @param array $items Items to set.
  49. */
  50. public function set_items( $items ) {
  51. $this->items = $items;
  52. $this->discounts = array();
  53. uasort( $this->items, array( $this, 'sort_by_price' ) );
  54. }
  55. /**
  56. * Normalise cart items which will be discounted.
  57. *
  58. * @since 3.2.0
  59. * @param WC_Cart $cart Cart object.
  60. */
  61. public function set_items_from_cart( $cart ) {
  62. $this->items = array();
  63. $this->discounts = array();
  64. if ( ! is_a( $cart, 'WC_Cart' ) ) {
  65. return;
  66. }
  67. $this->object = $cart;
  68. foreach ( $cart->get_cart() as $key => $cart_item ) {
  69. $item = new stdClass();
  70. $item->key = $key;
  71. $item->object = $cart_item;
  72. $item->product = $cart_item['data'];
  73. $item->quantity = $cart_item['quantity'];
  74. $item->price = wc_add_number_precision_deep( $item->product->get_price() * $item->quantity );
  75. $this->items[ $key ] = $item;
  76. }
  77. uasort( $this->items, array( $this, 'sort_by_price' ) );
  78. }
  79. /**
  80. * Normalise order items which will be discounted.
  81. *
  82. * @since 3.2.0
  83. * @param array $order Cart object.
  84. */
  85. public function set_items_from_order( $order ) {
  86. $this->items = array();
  87. $this->discounts = array();
  88. if ( ! is_a( $order, 'WC_Order' ) ) {
  89. return;
  90. }
  91. $this->object = $order;
  92. foreach ( $order->get_items() as $order_item ) {
  93. $item = new stdClass();
  94. $item->key = $order_item->get_id();
  95. $item->object = $order_item;
  96. $item->product = $order_item->get_product();
  97. $item->quantity = $order_item->get_quantity();
  98. $item->price = wc_add_number_precision_deep( $order_item->get_subtotal() );
  99. if ( $order->get_prices_include_tax() ) {
  100. $item->price += wc_add_number_precision_deep( $order_item->get_subtotal_tax() );
  101. }
  102. $this->items[ $order_item->get_id() ] = $item;
  103. }
  104. uasort( $this->items, array( $this, 'sort_by_price' ) );
  105. }
  106. /**
  107. * Get the object concerned.
  108. *
  109. * @since 3.3.2
  110. * @return object
  111. */
  112. public function get_object() {
  113. return $this->object;
  114. }
  115. /**
  116. * Get items.
  117. *
  118. * @since 3.2.0
  119. * @return object[]
  120. */
  121. public function get_items() {
  122. return $this->items;
  123. }
  124. /**
  125. * Get items to validate.
  126. *
  127. * @since 3.3.2
  128. * @return object[]
  129. */
  130. public function get_items_to_validate() {
  131. return apply_filters( 'woocommerce_coupon_get_items_to_validate', $this->get_items(), $this );
  132. }
  133. /**
  134. * Get discount by key with or without precision.
  135. *
  136. * @since 3.2.0
  137. * @param string $key name of discount row to return.
  138. * @param bool $in_cents Should the totals be returned in cents, or without precision.
  139. * @return array
  140. */
  141. public function get_discount( $key, $in_cents = false ) {
  142. $item_discount_totals = $this->get_discounts_by_item( $in_cents );
  143. return isset( $item_discount_totals[ $key ] ) ? $item_discount_totals[ $key ] : 0;
  144. }
  145. /**
  146. * Get all discount totals.
  147. *
  148. * @since 3.2.0
  149. * @param bool $in_cents Should the totals be returned in cents, or without precision.
  150. * @return array
  151. */
  152. public function get_discounts( $in_cents = false ) {
  153. $discounts = $this->discounts;
  154. return $in_cents ? $discounts : wc_remove_number_precision_deep( $discounts );
  155. }
  156. /**
  157. * Get all discount totals per item.
  158. *
  159. * @since 3.2.0
  160. * @param bool $in_cents Should the totals be returned in cents, or without precision.
  161. * @return array
  162. */
  163. public function get_discounts_by_item( $in_cents = false ) {
  164. $discounts = $this->discounts;
  165. $item_discount_totals = (array) array_shift( $discounts );
  166. foreach ( $discounts as $item_discounts ) {
  167. foreach ( $item_discounts as $item_key => $item_discount ) {
  168. $item_discount_totals[ $item_key ] += $item_discount;
  169. }
  170. }
  171. return $in_cents ? $item_discount_totals : wc_remove_number_precision_deep( $item_discount_totals );
  172. }
  173. /**
  174. * Get all discount totals per coupon.
  175. *
  176. * @since 3.2.0
  177. * @param bool $in_cents Should the totals be returned in cents, or without precision.
  178. * @return array
  179. */
  180. public function get_discounts_by_coupon( $in_cents = false ) {
  181. $coupon_discount_totals = array_map( 'array_sum', $this->discounts );
  182. return $in_cents ? $coupon_discount_totals : wc_remove_number_precision_deep( $coupon_discount_totals );
  183. }
  184. /**
  185. * Get discounted price of an item without precision.
  186. *
  187. * @since 3.2.0
  188. * @param object $item Get data for this item.
  189. * @return float
  190. */
  191. public function get_discounted_price( $item ) {
  192. return wc_remove_number_precision_deep( $this->get_discounted_price_in_cents( $item ) );
  193. }
  194. /**
  195. * Get discounted price of an item to precision (in cents).
  196. *
  197. * @since 3.2.0
  198. * @param object $item Get data for this item.
  199. * @return int
  200. */
  201. public function get_discounted_price_in_cents( $item ) {
  202. return absint( round( $item->price - $this->get_discount( $item->key, true ) ) );
  203. }
  204. /**
  205. * Apply a discount to all items using a coupon.
  206. *
  207. * @since 3.2.0
  208. * @param WC_Coupon $coupon Coupon object being applied to the items.
  209. * @param bool $validate Set to false to skip coupon validation.
  210. * @return bool|WP_Error True if applied or WP_Error instance in failure.
  211. */
  212. public function apply_coupon( $coupon, $validate = true ) {
  213. if ( ! is_a( $coupon, 'WC_Coupon' ) ) {
  214. return new WP_Error( 'invalid_coupon', __( 'Invalid coupon', 'woocommerce' ) );
  215. }
  216. $is_coupon_valid = $validate ? $this->is_coupon_valid( $coupon ) : true;
  217. if ( is_wp_error( $is_coupon_valid ) ) {
  218. return $is_coupon_valid;
  219. }
  220. if ( ! isset( $this->discounts[ $coupon->get_code() ] ) ) {
  221. $this->discounts[ $coupon->get_code() ] = array_fill_keys( array_keys( $this->items ), 0 );
  222. }
  223. $items_to_apply = $this->get_items_to_apply_coupon( $coupon );
  224. $coupon_type = $coupon->get_discount_type();
  225. // Core discounts are handled here as of 3.2.
  226. switch ( $coupon->get_discount_type() ) {
  227. case 'percent':
  228. $this->apply_coupon_percent( $coupon, $items_to_apply );
  229. break;
  230. case 'fixed_product':
  231. $this->apply_coupon_fixed_product( $coupon, $items_to_apply );
  232. break;
  233. case 'fixed_cart':
  234. $this->apply_coupon_fixed_cart( $coupon, $items_to_apply );
  235. break;
  236. default:
  237. $this->apply_coupon_custom( $coupon, $items_to_apply );
  238. break;
  239. }
  240. return true;
  241. }
  242. /**
  243. * Sort by price.
  244. *
  245. * @since 3.2.0
  246. * @param array $a First element.
  247. * @param array $b Second element.
  248. * @return int
  249. */
  250. protected function sort_by_price( $a, $b ) {
  251. $price_1 = $a->price * $a->quantity;
  252. $price_2 = $b->price * $b->quantity;
  253. if ( $price_1 === $price_2 ) {
  254. return 0;
  255. }
  256. return ( $price_1 < $price_2 ) ? 1 : -1;
  257. }
  258. /**
  259. * Filter out all products which have been fully discounted to 0.
  260. * Used as array_filter callback.
  261. *
  262. * @since 3.2.0
  263. * @param object $item Get data for this item.
  264. * @return bool
  265. */
  266. protected function filter_products_with_price( $item ) {
  267. return $this->get_discounted_price_in_cents( $item ) > 0;
  268. }
  269. /**
  270. * Get items which the coupon should be applied to.
  271. *
  272. * @since 3.2.0
  273. * @param object $coupon Coupon object.
  274. * @return array
  275. */
  276. protected function get_items_to_apply_coupon( $coupon ) {
  277. $items_to_apply = array();
  278. foreach ( $this->get_items_to_validate() as $item ) {
  279. $item_to_apply = clone $item; // Clone the item so changes to this item do not affect the originals.
  280. if ( 0 === $this->get_discounted_price_in_cents( $item_to_apply ) || 0 >= $item_to_apply->quantity ) {
  281. continue;
  282. }
  283. if ( ! $coupon->is_valid_for_product( $item_to_apply->product, $item_to_apply->object ) && ! $coupon->is_valid_for_cart() ) {
  284. continue;
  285. }
  286. $items_to_apply[] = $item_to_apply;
  287. }
  288. return $items_to_apply;
  289. }
  290. /**
  291. * Apply percent discount to items and return an array of discounts granted.
  292. *
  293. * @since 3.2.0
  294. * @param WC_Coupon $coupon Coupon object. Passed through filters.
  295. * @param array $items_to_apply Array of items to apply the coupon to.
  296. * @return int Total discounted.
  297. */
  298. protected function apply_coupon_percent( $coupon, $items_to_apply ) {
  299. $total_discount = 0;
  300. $cart_total = 0;
  301. $limit_usage_qty = 0;
  302. $applied_count = 0;
  303. $adjust_final_discount = true;
  304. if ( null !== $coupon->get_limit_usage_to_x_items() ) {
  305. $limit_usage_qty = $coupon->get_limit_usage_to_x_items();
  306. }
  307. $coupon_amount = $coupon->get_amount();
  308. foreach ( $items_to_apply as $item ) {
  309. // Find out how much price is available to discount for the item.
  310. $discounted_price = $this->get_discounted_price_in_cents( $item );
  311. // Get the price we actually want to discount, based on settings.
  312. $price_to_discount = ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price;
  313. // See how many and what price to apply to.
  314. $apply_quantity = $limit_usage_qty && ( $limit_usage_qty - $applied_count ) < $item->quantity ? $limit_usage_qty - $applied_count : $item->quantity;
  315. $apply_quantity = max( 0, apply_filters( 'woocommerce_coupon_get_apply_quantity', $apply_quantity, $item, $coupon, $this ) );
  316. $price_to_discount = ( $price_to_discount / $item->quantity ) * $apply_quantity;
  317. // Run coupon calculations.
  318. $discount = floor( $price_to_discount * ( $coupon_amount / 100 ) );
  319. if ( is_a( $this->object, 'WC_Cart' ) && has_filter( 'woocommerce_coupon_get_discount_amount' ) ) {
  320. // Send through the legacy filter, but not as cents.
  321. $filtered_discount = wc_add_number_precision( apply_filters( 'woocommerce_coupon_get_discount_amount', wc_remove_number_precision( $discount ), wc_remove_number_precision( $price_to_discount ), $item->object, false, $coupon ) );
  322. if ( $filtered_discount !== $discount ) {
  323. $discount = $filtered_discount;
  324. $adjust_final_discount = false;
  325. }
  326. }
  327. $discount = wc_round_discount( min( $discounted_price, $discount ), 0 );
  328. $cart_total = $cart_total + $price_to_discount;
  329. $total_discount = $total_discount + $discount;
  330. $applied_count = $applied_count + $apply_quantity;
  331. // Store code and discount amount per item.
  332. $this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
  333. }
  334. // Work out how much discount would have been given to the cart as a whole and compare to what was discounted on all line items.
  335. $cart_total_discount = wc_round_discount( $cart_total * ( $coupon_amount / 100 ), 0 );
  336. if ( $total_discount < $cart_total_discount && $adjust_final_discount ) {
  337. $total_discount += $this->apply_coupon_remainder( $coupon, $items_to_apply, $cart_total_discount - $total_discount );
  338. }
  339. return $total_discount;
  340. }
  341. /**
  342. * Apply fixed product discount to items.
  343. *
  344. * @since 3.2.0
  345. * @param WC_Coupon $coupon Coupon object. Passed through filters.
  346. * @param array $items_to_apply Array of items to apply the coupon to.
  347. * @param int $amount Fixed discount amount to apply in cents. Leave blank to pull from coupon.
  348. * @return int Total discounted.
  349. */
  350. protected function apply_coupon_fixed_product( $coupon, $items_to_apply, $amount = null ) {
  351. $total_discount = 0;
  352. $amount = $amount ? $amount : wc_add_number_precision( $coupon->get_amount() );
  353. $limit_usage_qty = 0;
  354. $applied_count = 0;
  355. if ( null !== $coupon->get_limit_usage_to_x_items() ) {
  356. $limit_usage_qty = $coupon->get_limit_usage_to_x_items();
  357. }
  358. foreach ( $items_to_apply as $item ) {
  359. // Find out how much price is available to discount for the item.
  360. $discounted_price = $this->get_discounted_price_in_cents( $item );
  361. // Get the price we actually want to discount, based on settings.
  362. $price_to_discount = ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price;
  363. // Run coupon calculations.
  364. if ( $limit_usage_qty ) {
  365. $apply_quantity = $limit_usage_qty - $applied_count < $item->quantity ? $limit_usage_qty - $applied_count : $item->quantity;
  366. $apply_quantity = max( 0, apply_filters( 'woocommerce_coupon_get_apply_quantity', $apply_quantity, $item, $coupon, $this ) );
  367. $discount = min( $amount, $item->price / $item->quantity ) * $apply_quantity;
  368. } else {
  369. $apply_quantity = apply_filters( 'woocommerce_coupon_get_apply_quantity', $item->quantity, $item, $coupon, $this );
  370. $discount = $amount * $apply_quantity;
  371. }
  372. if ( is_a( $this->object, 'WC_Cart' ) && has_filter( 'woocommerce_coupon_get_discount_amount' ) ) {
  373. // Send through the legacy filter, but not as cents.
  374. $discount = wc_add_number_precision( apply_filters( 'woocommerce_coupon_get_discount_amount', wc_remove_number_precision( $discount ), wc_remove_number_precision( $price_to_discount ), $item->object, false, $coupon ) );
  375. }
  376. $discount = min( $discounted_price, $discount );
  377. $total_discount = $total_discount + $discount;
  378. $applied_count = $applied_count + $apply_quantity;
  379. // Store code and discount amount per item.
  380. $this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
  381. }
  382. return $total_discount;
  383. }
  384. /**
  385. * Apply fixed cart discount to items.
  386. *
  387. * @since 3.2.0
  388. * @param WC_Coupon $coupon Coupon object. Passed through filters.
  389. * @param array $items_to_apply Array of items to apply the coupon to.
  390. * @param int $amount Fixed discount amount to apply in cents. Leave blank to pull from coupon.
  391. * @return int Total discounted.
  392. */
  393. protected function apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount = null ) {
  394. $total_discount = 0;
  395. $amount = $amount ? $amount : wc_add_number_precision( $coupon->get_amount() );
  396. $items_to_apply = array_filter( $items_to_apply, array( $this, 'filter_products_with_price' ) );
  397. $item_count = array_sum( wp_list_pluck( $items_to_apply, 'quantity' ) );
  398. if ( ! $item_count ) {
  399. return $total_discount;
  400. }
  401. if ( ! $amount ) {
  402. // If there is no amount we still send it through so filters are fired.
  403. $total_discount = $this->apply_coupon_fixed_product( $coupon, $items_to_apply, 0 );
  404. } else {
  405. $per_item_discount = absint( $amount / $item_count ); // round it down to the nearest cent.
  406. if ( $per_item_discount > 0 ) {
  407. $total_discount = $this->apply_coupon_fixed_product( $coupon, $items_to_apply, $per_item_discount );
  408. /**
  409. * If there is still discount remaining, repeat the process.
  410. */
  411. if ( $total_discount > 0 && $total_discount < $amount ) {
  412. $total_discount += $this->apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount - $total_discount );
  413. }
  414. } elseif ( $amount > 0 ) {
  415. $total_discount += $this->apply_coupon_remainder( $coupon, $items_to_apply, $amount );
  416. }
  417. }
  418. return $total_discount;
  419. }
  420. /**
  421. * Apply custom coupon discount to items.
  422. *
  423. * @since 3.3
  424. * @param WC_Coupon $coupon Coupon object. Passed through filters.
  425. * @param array $items_to_apply Array of items to apply the coupon to.
  426. * @return int Total discounted.
  427. */
  428. protected function apply_coupon_custom( $coupon, $items_to_apply ) {
  429. foreach ( $items_to_apply as $item ) {
  430. $discounted_price = $this->get_discounted_price_in_cents( $item );
  431. $price_to_discount = wc_remove_number_precision( ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price );
  432. $discount = wc_add_number_precision( $coupon->get_discount_amount( $price_to_discount / $item->quantity, $item->object, true ) ) * $item->quantity;
  433. $discount = min( $discounted_price, $discount );
  434. // Store code and discount amount per item.
  435. $this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
  436. }
  437. // Allow post-processing for custom coupon types (e.g. calculating discrepancy, etc).
  438. $this->discounts[ $coupon->get_code() ] = apply_filters( 'woocommerce_coupon_custom_discounts_array', $this->discounts[ $coupon->get_code() ], $coupon );
  439. return array_sum( $this->discounts[ $coupon->get_code() ] );
  440. }
  441. /**
  442. * Deal with remaining fractional discounts by splitting it over items
  443. * until the amount is expired, discounting 1 cent at a time.
  444. *
  445. * @since 3.2.0
  446. * @param WC_Coupon $coupon Coupon object if appliable. Passed through filters.
  447. * @param array $items_to_apply Array of items to apply the coupon to.
  448. * @param int $amount Fixed discount amount to apply.
  449. * @return int Total discounted.
  450. */
  451. protected function apply_coupon_remainder( $coupon, $items_to_apply, $amount ) {
  452. $total_discount = 0;
  453. foreach ( $items_to_apply as $item ) {
  454. for ( $i = 0; $i < $item->quantity; $i ++ ) {
  455. // Find out how much price is available to discount for the item.
  456. $discounted_price = $this->get_discounted_price_in_cents( $item );
  457. // Get the price we actually want to discount, based on settings.
  458. $price_to_discount = ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price;
  459. // Run coupon calculations.
  460. $discount = min( $price_to_discount, 1 );
  461. // Store totals.
  462. $total_discount += $discount;
  463. // Store code and discount amount per item.
  464. $this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
  465. if ( $total_discount >= $amount ) {
  466. break 2;
  467. }
  468. }
  469. if ( $total_discount >= $amount ) {
  470. break;
  471. }
  472. }
  473. return $total_discount;
  474. }
  475. /**
  476. * Ensure coupon exists or throw exception.
  477. *
  478. * @since 3.2.0
  479. * @throws Exception Error message.
  480. * @param WC_Coupon $coupon Coupon data.
  481. * @return bool
  482. */
  483. protected function validate_coupon_exists( $coupon ) {
  484. if ( ! $coupon->get_id() && ! $coupon->get_virtual() ) {
  485. /* translators: %s: coupon code */
  486. throw new Exception( sprintf( __( 'Coupon "%s" does not exist!', 'woocommerce' ), $coupon->get_code() ), 105 );
  487. }
  488. return true;
  489. }
  490. /**
  491. * Ensure coupon usage limit is valid or throw exception.
  492. *
  493. * @since 3.2.0
  494. * @throws Exception Error message.
  495. * @param WC_Coupon $coupon Coupon data.
  496. * @return bool
  497. */
  498. protected function validate_coupon_usage_limit( $coupon ) {
  499. if ( $coupon->get_usage_limit() > 0 && $coupon->get_usage_count() >= $coupon->get_usage_limit() ) {
  500. throw new Exception( __( 'Coupon usage limit has been reached.', 'woocommerce' ), 106 );
  501. }
  502. return true;
  503. }
  504. /**
  505. * Ensure coupon user usage limit is valid or throw exception.
  506. *
  507. * Per user usage limit - check here if user is logged in (against user IDs).
  508. * Checked again for emails later on in WC_Cart::check_customer_coupons().
  509. *
  510. * @since 3.2.0
  511. * @throws Exception Error message.
  512. * @param WC_Coupon $coupon Coupon data.
  513. * @param int $user_id User ID.
  514. * @return bool
  515. */
  516. protected function validate_coupon_user_usage_limit( $coupon, $user_id = 0 ) {
  517. if ( empty( $user_id ) ) {
  518. if ( $this->object instanceof WC_Order ) {
  519. $user_id = $this->object->get_customer_id();
  520. } else {
  521. $user_id = get_current_user_id();
  522. }
  523. }
  524. if ( $coupon && $user_id && $coupon->get_usage_limit_per_user() > 0 && $coupon->get_id() && $coupon->get_data_store() ) {
  525. $date_store = $coupon->get_data_store();
  526. $usage_count = $date_store->get_usage_by_user_id( $coupon, $user_id );
  527. if ( $usage_count >= $coupon->get_usage_limit_per_user() ) {
  528. throw new Exception( __( 'Coupon usage limit has been reached.', 'woocommerce' ), 106 );
  529. }
  530. }
  531. return true;
  532. }
  533. /**
  534. * Ensure coupon date is valid or throw exception.
  535. *
  536. * @since 3.2.0
  537. * @throws Exception Error message.
  538. * @param WC_Coupon $coupon Coupon data.
  539. * @return bool
  540. */
  541. protected function validate_coupon_expiry_date( $coupon ) {
  542. if ( $coupon->get_date_expires() && apply_filters( 'woocommerce_coupon_validate_expiry_date', current_time( 'timestamp', true ) > $coupon->get_date_expires()->getTimestamp(), $coupon, $this ) ) {
  543. throw new Exception( __( 'This coupon has expired.', 'woocommerce' ), 107 );
  544. }
  545. return true;
  546. }
  547. /**
  548. * Ensure coupon amount is valid or throw exception.
  549. *
  550. * @since 3.2.0
  551. * @throws Exception Error message.
  552. * @param WC_Coupon $coupon Coupon data.
  553. * @return bool
  554. */
  555. protected function validate_coupon_minimum_amount( $coupon ) {
  556. $subtotal = wc_remove_number_precision( $this->get_object_subtotal() );
  557. if ( $coupon->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $coupon->get_minimum_amount() > $subtotal, $coupon, $subtotal ) ) {
  558. /* translators: %s: coupon minimum amount */
  559. throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
  560. }
  561. return true;
  562. }
  563. /**
  564. * Ensure coupon amount is valid or throw exception.
  565. *
  566. * @since 3.2.0
  567. * @throws Exception Error message.
  568. * @param WC_Coupon $coupon Coupon data.
  569. * @return bool
  570. */
  571. protected function validate_coupon_maximum_amount( $coupon ) {
  572. $subtotal = wc_remove_number_precision( $this->get_object_subtotal() );
  573. if ( $coupon->get_maximum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_maximum_amount', $coupon->get_maximum_amount() < $subtotal, $coupon ) ) {
  574. /* translators: %s: coupon maximum amount */
  575. throw new Exception( sprintf( __( 'The maximum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_maximum_amount() ) ), 112 );
  576. }
  577. return true;
  578. }
  579. /**
  580. * Ensure coupon is valid for products in the list is valid or throw exception.
  581. *
  582. * @since 3.2.0
  583. * @throws Exception Error message.
  584. * @param WC_Coupon $coupon Coupon data.
  585. * @return bool
  586. */
  587. protected function validate_coupon_product_ids( $coupon ) {
  588. if ( count( $coupon->get_product_ids() ) > 0 ) {
  589. $valid = false;
  590. foreach ( $this->get_items_to_validate() as $item ) {
  591. if ( $item->product && in_array( $item->product->get_id(), $coupon->get_product_ids(), true ) || in_array( $item->product->get_parent_id(), $coupon->get_product_ids(), true ) ) {
  592. $valid = true;
  593. break;
  594. }
  595. }
  596. if ( ! $valid ) {
  597. throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
  598. }
  599. }
  600. return true;
  601. }
  602. /**
  603. * Ensure coupon is valid for product categories in the list is valid or throw exception.
  604. *
  605. * @since 3.2.0
  606. * @throws Exception Error message.
  607. * @param WC_Coupon $coupon Coupon data.
  608. * @return bool
  609. */
  610. protected function validate_coupon_product_categories( $coupon ) {
  611. if ( count( $coupon->get_product_categories() ) > 0 ) {
  612. $valid = false;
  613. foreach ( $this->get_items_to_validate() as $item ) {
  614. if ( $coupon->get_exclude_sale_items() && $item->product && $item->product->is_on_sale() ) {
  615. continue;
  616. }
  617. $product_cats = wc_get_product_cat_ids( $item->product->get_id() );
  618. if ( $item->product->get_parent_id() ) {
  619. $product_cats = array_merge( $product_cats, wc_get_product_cat_ids( $item->product->get_parent_id() ) );
  620. }
  621. // If we find an item with a cat in our allowed cat list, the coupon is valid.
  622. if ( count( array_intersect( $product_cats, $coupon->get_product_categories() ) ) > 0 ) {
  623. $valid = true;
  624. break;
  625. }
  626. }
  627. if ( ! $valid ) {
  628. throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
  629. }
  630. }
  631. return true;
  632. }
  633. /**
  634. * Ensure coupon is valid for sale items in the list is valid or throw exception.
  635. *
  636. * @since 3.2.0
  637. * @throws Exception Error message.
  638. * @param WC_Coupon $coupon Coupon data.
  639. * @return bool
  640. */
  641. protected function validate_coupon_sale_items( $coupon ) {
  642. if ( $coupon->get_exclude_sale_items() && 'fixed_product' !== $coupon->get_discount_type() ) {
  643. $valid = true;
  644. foreach ( $this->get_items_to_validate() as $item ) {
  645. if ( $item->product && $item->product->is_on_sale() ) {
  646. $valid = false;
  647. break;
  648. }
  649. }
  650. if ( ! $valid ) {
  651. throw new Exception( __( 'Sorry, this coupon is not valid for sale items.', 'woocommerce' ), 110 );
  652. }
  653. }
  654. return true;
  655. }
  656. /**
  657. * All exclusion rules must pass at the same time for a product coupon to be valid.
  658. *
  659. * @since 3.2.0
  660. * @throws Exception Error message.
  661. * @param WC_Coupon $coupon Coupon data.
  662. * @return bool
  663. */
  664. protected function validate_coupon_excluded_items( $coupon ) {
  665. $items = $this->get_items_to_validate();
  666. if ( ! empty( $items ) && $coupon->is_type( wc_get_product_coupon_types() ) ) {
  667. $valid = false;
  668. foreach ( $items as $item ) {
  669. if ( $item->product && $coupon->is_valid_for_product( $item->product, $item->object ) ) {
  670. $valid = true;
  671. break;
  672. }
  673. }
  674. if ( ! $valid ) {
  675. throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
  676. }
  677. }
  678. return true;
  679. }
  680. /**
  681. * Cart discounts cannot be added if non-eligible product is found.
  682. *
  683. * @since 3.2.0
  684. * @throws Exception Error message.
  685. * @param WC_Coupon $coupon Coupon data.
  686. * @return bool
  687. */
  688. protected function validate_coupon_eligible_items( $coupon ) {
  689. if ( ! $coupon->is_type( wc_get_product_coupon_types() ) ) {
  690. $this->validate_coupon_excluded_product_ids( $coupon );
  691. $this->validate_coupon_excluded_product_categories( $coupon );
  692. }
  693. return true;
  694. }
  695. /**
  696. * Exclude products.
  697. *
  698. * @since 3.2.0
  699. * @throws Exception Error message.
  700. * @param WC_Coupon $coupon Coupon data.
  701. * @return bool
  702. */
  703. protected function validate_coupon_excluded_product_ids( $coupon ) {
  704. // Exclude Products.
  705. if ( count( $coupon->get_excluded_product_ids() ) > 0 ) {
  706. $products = array();
  707. foreach ( $this->get_items_to_validate() as $item ) {
  708. if ( $item->product && in_array( $item->product->get_id(), $coupon->get_excluded_product_ids(), true ) || in_array( $item->product->get_parent_id(), $coupon->get_excluded_product_ids(), true ) ) {
  709. $products[] = $item->product->get_name();
  710. }
  711. }
  712. if ( ! empty( $products ) ) {
  713. /* translators: %s: products list */
  714. throw new Exception( sprintf( __( 'Sorry, this coupon is not applicable to the products: %s.', 'woocommerce' ), implode( ', ', $products ) ), 113 );
  715. }
  716. }
  717. return true;
  718. }
  719. /**
  720. * Exclude categories from product list.
  721. *
  722. * @since 3.2.0
  723. * @throws Exception Error message.
  724. * @param WC_Coupon $coupon Coupon data.
  725. * @return bool
  726. */
  727. protected function validate_coupon_excluded_product_categories( $coupon ) {
  728. if ( count( $coupon->get_excluded_product_categories() ) > 0 ) {
  729. $categories = array();
  730. foreach ( $this->get_items_to_validate() as $item ) {
  731. if ( ! $item->product ) {
  732. continue;
  733. }
  734. $product_cats = wc_get_product_cat_ids( $item->product->get_id() );
  735. if ( $item->product->get_parent_id() ) {
  736. $product_cats = array_merge( $product_cats, wc_get_product_cat_ids( $item->product->get_parent_id() ) );
  737. }
  738. $cat_id_list = array_intersect( $product_cats, $coupon->get_excluded_product_categories() );
  739. if ( count( $cat_id_list ) > 0 ) {
  740. foreach ( $cat_id_list as $cat_id ) {
  741. $cat = get_term( $cat_id, 'product_cat' );
  742. $categories[] = $cat->name;
  743. }
  744. }
  745. }
  746. if ( ! empty( $categories ) ) {
  747. /* translators: %s: categories list */
  748. throw new Exception( sprintf( __( 'Sorry, this coupon is not applicable to the categories: %s.', 'woocommerce' ), implode( ', ', array_unique( $categories ) ) ), 114 );
  749. }
  750. }
  751. return true;
  752. }
  753. /**
  754. * Get the object subtotal
  755. *
  756. * @return int
  757. */
  758. protected function get_object_subtotal() {
  759. if ( is_a( $this->object, 'WC_Cart' ) ) {
  760. return wc_add_number_precision( $this->object->get_displayed_subtotal() );
  761. } elseif ( is_a( $this->object, 'WC_Order' ) ) {
  762. return wc_add_number_precision( $this->object->get_subtotal() );
  763. } else {
  764. return array_sum( wp_list_pluck( $this->items, 'price' ) );
  765. }
  766. }
  767. /**
  768. * Check if a coupon is valid.
  769. *
  770. * Error Codes:
  771. * - 100: Invalid filtered.
  772. * - 101: Invalid removed.
  773. * - 102: Not yours removed.
  774. * - 103: Already applied.
  775. * - 104: Individual use only.
  776. * - 105: Not exists.
  777. * - 106: Usage limit reached.
  778. * - 107: Expired.
  779. * - 108: Minimum spend limit not met.
  780. * - 109: Not applicable.
  781. * - 110: Not valid for sale items.
  782. * - 111: Missing coupon code.
  783. * - 112: Maximum spend limit met.
  784. * - 113: Excluded products.
  785. * - 114: Excluded categories.
  786. *
  787. * @since 3.2.0
  788. * @throws Exception Error message.
  789. * @param WC_Coupon $coupon Coupon data.
  790. * @return bool|WP_Error
  791. */
  792. public function is_coupon_valid( $coupon ) {
  793. try {
  794. $this->validate_coupon_exists( $coupon );
  795. $this->validate_coupon_usage_limit( $coupon );
  796. $this->validate_coupon_user_usage_limit( $coupon );
  797. $this->validate_coupon_expiry_date( $coupon );
  798. $this->validate_coupon_minimum_amount( $coupon );
  799. $this->validate_coupon_maximum_amount( $coupon );
  800. $this->validate_coupon_product_ids( $coupon );
  801. $this->validate_coupon_product_categories( $coupon );
  802. $this->validate_coupon_sale_items( $coupon );
  803. $this->validate_coupon_excluded_items( $coupon );
  804. $this->validate_coupon_eligible_items( $coupon );
  805. if ( ! apply_filters( 'woocommerce_coupon_is_valid', true, $coupon, $this ) ) {
  806. throw new Exception( __( 'Coupon is not valid.', 'woocommerce' ), 100 );
  807. }
  808. } catch ( Exception $e ) {
  809. /**
  810. * Filter the coupon error message.
  811. *
  812. * @param string $error_message Error message.
  813. * @param int $error_code Error code.
  814. * @param WC_Coupon $coupon Coupon data.
  815. */
  816. $message = apply_filters( 'woocommerce_coupon_error', is_numeric( $e->getMessage() ) ? $coupon->get_coupon_error( $e->getMessage() ) : $e->getMessage(), $e->getCode(), $coupon );
  817. return new WP_Error( 'invalid_coupon', $message, array(
  818. 'status' => 400,
  819. ) );
  820. }
  821. return true;
  822. }
  823. }