Nenhuma Descrição

class-wc-coupon.php 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. <?php
  2. /**
  3. * WooCommerce coupons.
  4. *
  5. * The WooCommerce coupons class gets coupon data from storage and checks coupon validity.
  6. *
  7. * @package WooCommerce\Classes
  8. * @version 3.0.0
  9. */
  10. use Automattic\WooCommerce\Utilities\NumberUtil;
  11. defined( 'ABSPATH' ) || exit;
  12. require_once dirname( __FILE__ ) . '/legacy/class-wc-legacy-coupon.php';
  13. /**
  14. * Coupon class.
  15. */
  16. class WC_Coupon extends WC_Legacy_Coupon {
  17. /**
  18. * Data array, with defaults.
  19. *
  20. * @since 3.0.0
  21. * @var array
  22. */
  23. protected $data = array(
  24. 'code' => '',
  25. 'amount' => 0,
  26. 'date_created' => null,
  27. 'date_modified' => null,
  28. 'date_expires' => null,
  29. 'discount_type' => 'fixed_cart',
  30. 'description' => '',
  31. 'usage_count' => 0,
  32. 'individual_use' => false,
  33. 'product_ids' => array(),
  34. 'excluded_product_ids' => array(),
  35. 'usage_limit' => 0,
  36. 'usage_limit_per_user' => 0,
  37. 'limit_usage_to_x_items' => null,
  38. 'free_shipping' => false,
  39. 'product_categories' => array(),
  40. 'excluded_product_categories' => array(),
  41. 'exclude_sale_items' => false,
  42. 'minimum_amount' => '',
  43. 'maximum_amount' => '',
  44. 'email_restrictions' => array(),
  45. 'used_by' => array(),
  46. 'virtual' => false,
  47. );
  48. // Coupon message codes.
  49. const E_WC_COUPON_INVALID_FILTERED = 100;
  50. const E_WC_COUPON_INVALID_REMOVED = 101;
  51. const E_WC_COUPON_NOT_YOURS_REMOVED = 102;
  52. const E_WC_COUPON_ALREADY_APPLIED = 103;
  53. const E_WC_COUPON_ALREADY_APPLIED_INDIV_USE_ONLY = 104;
  54. const E_WC_COUPON_NOT_EXIST = 105;
  55. const E_WC_COUPON_USAGE_LIMIT_REACHED = 106;
  56. const E_WC_COUPON_EXPIRED = 107;
  57. const E_WC_COUPON_MIN_SPEND_LIMIT_NOT_MET = 108;
  58. const E_WC_COUPON_NOT_APPLICABLE = 109;
  59. const E_WC_COUPON_NOT_VALID_SALE_ITEMS = 110;
  60. const E_WC_COUPON_PLEASE_ENTER = 111;
  61. const E_WC_COUPON_MAX_SPEND_LIMIT_MET = 112;
  62. const E_WC_COUPON_EXCLUDED_PRODUCTS = 113;
  63. const E_WC_COUPON_EXCLUDED_CATEGORIES = 114;
  64. const E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK = 115;
  65. const E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST = 116;
  66. const WC_COUPON_SUCCESS = 200;
  67. const WC_COUPON_REMOVED = 201;
  68. /**
  69. * Cache group.
  70. *
  71. * @var string
  72. */
  73. protected $cache_group = 'coupons';
  74. /**
  75. * Coupon constructor. Loads coupon data.
  76. *
  77. * @param mixed $data Coupon data, object, ID or code.
  78. */
  79. public function __construct( $data = '' ) {
  80. parent::__construct( $data );
  81. // If we already have a coupon object, read it again.
  82. if ( $data instanceof WC_Coupon ) {
  83. $this->set_id( absint( $data->get_id() ) );
  84. $this->read_object_from_database();
  85. return;
  86. }
  87. // This filter allows custom coupon objects to be created on the fly.
  88. $coupon = apply_filters( 'woocommerce_get_shop_coupon_data', false, $data, $this );
  89. if ( $coupon ) {
  90. $this->read_manual_coupon( $data, $coupon );
  91. return;
  92. }
  93. // Try to load coupon using ID or code.
  94. if ( is_int( $data ) && 'shop_coupon' === get_post_type( $data ) ) {
  95. $this->set_id( $data );
  96. } elseif ( ! empty( $data ) ) {
  97. $id = wc_get_coupon_id_by_code( $data );
  98. // Need to support numeric strings for backwards compatibility.
  99. if ( ! $id && 'shop_coupon' === get_post_type( $data ) ) {
  100. $this->set_id( $data );
  101. } else {
  102. $this->set_id( $id );
  103. $this->set_code( $data );
  104. }
  105. } else {
  106. $this->set_object_read( true );
  107. }
  108. $this->read_object_from_database();
  109. }
  110. /**
  111. * If the object has an ID, read using the data store.
  112. *
  113. * @since 3.4.1
  114. */
  115. protected function read_object_from_database() {
  116. $this->data_store = WC_Data_Store::load( 'coupon' );
  117. if ( $this->get_id() > 0 ) {
  118. $this->data_store->read( $this );
  119. }
  120. }
  121. /**
  122. * Checks the coupon type.
  123. *
  124. * @param string $type Array or string of types.
  125. * @return bool
  126. */
  127. public function is_type( $type ) {
  128. return ( $this->get_discount_type() === $type || ( is_array( $type ) && in_array( $this->get_discount_type(), $type, true ) ) );
  129. }
  130. /**
  131. * Prefix for action and filter hooks on data.
  132. *
  133. * @since 3.0.0
  134. * @return string
  135. */
  136. protected function get_hook_prefix() {
  137. return 'woocommerce_coupon_get_';
  138. }
  139. /*
  140. |--------------------------------------------------------------------------
  141. | Getters
  142. |--------------------------------------------------------------------------
  143. |
  144. | Methods for getting data from the coupon object.
  145. |
  146. */
  147. /**
  148. * Get coupon code.
  149. *
  150. * @since 3.0.0
  151. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  152. * @return string
  153. */
  154. public function get_code( $context = 'view' ) {
  155. return $this->get_prop( 'code', $context );
  156. }
  157. /**
  158. * Get coupon description.
  159. *
  160. * @since 3.0.0
  161. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  162. * @return string
  163. */
  164. public function get_description( $context = 'view' ) {
  165. return $this->get_prop( 'description', $context );
  166. }
  167. /**
  168. * Get discount type.
  169. *
  170. * @since 3.0.0
  171. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  172. * @return string
  173. */
  174. public function get_discount_type( $context = 'view' ) {
  175. return $this->get_prop( 'discount_type', $context );
  176. }
  177. /**
  178. * Get coupon amount.
  179. *
  180. * @since 3.0.0
  181. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  182. * @return float
  183. */
  184. public function get_amount( $context = 'view' ) {
  185. return wc_format_decimal( $this->get_prop( 'amount', $context ) );
  186. }
  187. /**
  188. * Get coupon expiration date.
  189. *
  190. * @since 3.0.0
  191. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  192. * @return WC_DateTime|NULL object if the date is set or null if there is no date.
  193. */
  194. public function get_date_expires( $context = 'view' ) {
  195. return $this->get_prop( 'date_expires', $context );
  196. }
  197. /**
  198. * Get date_created
  199. *
  200. * @since 3.0.0
  201. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  202. * @return WC_DateTime|NULL object if the date is set or null if there is no date.
  203. */
  204. public function get_date_created( $context = 'view' ) {
  205. return $this->get_prop( 'date_created', $context );
  206. }
  207. /**
  208. * Get date_modified
  209. *
  210. * @since 3.0.0
  211. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  212. * @return WC_DateTime|NULL object if the date is set or null if there is no date.
  213. */
  214. public function get_date_modified( $context = 'view' ) {
  215. return $this->get_prop( 'date_modified', $context );
  216. }
  217. /**
  218. * Get coupon usage count.
  219. *
  220. * @since 3.0.0
  221. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  222. * @return integer
  223. */
  224. public function get_usage_count( $context = 'view' ) {
  225. return $this->get_prop( 'usage_count', $context );
  226. }
  227. /**
  228. * Get the "indvidual use" checkbox status.
  229. *
  230. * @since 3.0.0
  231. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  232. * @return bool
  233. */
  234. public function get_individual_use( $context = 'view' ) {
  235. return $this->get_prop( 'individual_use', $context );
  236. }
  237. /**
  238. * Get product IDs this coupon can apply to.
  239. *
  240. * @since 3.0.0
  241. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  242. * @return array
  243. */
  244. public function get_product_ids( $context = 'view' ) {
  245. return $this->get_prop( 'product_ids', $context );
  246. }
  247. /**
  248. * Get product IDs that this coupon should not apply to.
  249. *
  250. * @since 3.0.0
  251. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  252. * @return array
  253. */
  254. public function get_excluded_product_ids( $context = 'view' ) {
  255. return $this->get_prop( 'excluded_product_ids', $context );
  256. }
  257. /**
  258. * Get coupon usage limit.
  259. *
  260. * @since 3.0.0
  261. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  262. * @return integer
  263. */
  264. public function get_usage_limit( $context = 'view' ) {
  265. return $this->get_prop( 'usage_limit', $context );
  266. }
  267. /**
  268. * Get coupon usage limit per customer (for a single customer)
  269. *
  270. * @since 3.0.0
  271. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  272. * @return integer
  273. */
  274. public function get_usage_limit_per_user( $context = 'view' ) {
  275. return $this->get_prop( 'usage_limit_per_user', $context );
  276. }
  277. /**
  278. * Usage limited to certain amount of items
  279. *
  280. * @since 3.0.0
  281. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  282. * @return integer|null
  283. */
  284. public function get_limit_usage_to_x_items( $context = 'view' ) {
  285. return $this->get_prop( 'limit_usage_to_x_items', $context );
  286. }
  287. /**
  288. * If this coupon grants free shipping or not.
  289. *
  290. * @since 3.0.0
  291. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  292. * @return bool
  293. */
  294. public function get_free_shipping( $context = 'view' ) {
  295. return $this->get_prop( 'free_shipping', $context );
  296. }
  297. /**
  298. * Get product categories this coupon can apply to.
  299. *
  300. * @since 3.0.0
  301. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  302. * @return array
  303. */
  304. public function get_product_categories( $context = 'view' ) {
  305. return $this->get_prop( 'product_categories', $context );
  306. }
  307. /**
  308. * Get product categories this coupon cannot not apply to.
  309. *
  310. * @since 3.0.0
  311. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  312. * @return array
  313. */
  314. public function get_excluded_product_categories( $context = 'view' ) {
  315. return $this->get_prop( 'excluded_product_categories', $context );
  316. }
  317. /**
  318. * If this coupon should exclude items on sale.
  319. *
  320. * @since 3.0.0
  321. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  322. * @return bool
  323. */
  324. public function get_exclude_sale_items( $context = 'view' ) {
  325. return $this->get_prop( 'exclude_sale_items', $context );
  326. }
  327. /**
  328. * Get minimum spend amount.
  329. *
  330. * @since 3.0.0
  331. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  332. * @return float
  333. */
  334. public function get_minimum_amount( $context = 'view' ) {
  335. return $this->get_prop( 'minimum_amount', $context );
  336. }
  337. /**
  338. * Get maximum spend amount.
  339. *
  340. * @since 3.0.0
  341. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  342. * @return float
  343. */
  344. public function get_maximum_amount( $context = 'view' ) {
  345. return $this->get_prop( 'maximum_amount', $context );
  346. }
  347. /**
  348. * Get emails to check customer usage restrictions.
  349. *
  350. * @since 3.0.0
  351. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  352. * @return array
  353. */
  354. public function get_email_restrictions( $context = 'view' ) {
  355. return $this->get_prop( 'email_restrictions', $context );
  356. }
  357. /**
  358. * Get records of all users who have used the current coupon.
  359. *
  360. * @since 3.0.0
  361. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  362. * @return array
  363. */
  364. public function get_used_by( $context = 'view' ) {
  365. return $this->get_prop( 'used_by', $context );
  366. }
  367. /**
  368. * If the filter is added through the woocommerce_get_shop_coupon_data filter, it's virtual and not in the DB.
  369. *
  370. * @since 3.2.0
  371. * @param string $context What the value is for. Valid values are 'view' and 'edit'.
  372. * @return boolean
  373. */
  374. public function get_virtual( $context = 'view' ) {
  375. return (bool) $this->get_prop( 'virtual', $context );
  376. }
  377. /**
  378. * Get discount amount for a cart item.
  379. *
  380. * @param float $discounting_amount Amount the coupon is being applied to.
  381. * @param array|null $cart_item Cart item being discounted if applicable.
  382. * @param boolean $single True if discounting a single qty item, false if its the line.
  383. * @return float Amount this coupon has discounted.
  384. */
  385. public function get_discount_amount( $discounting_amount, $cart_item = null, $single = false ) {
  386. $discount = 0;
  387. $cart_item_qty = is_null( $cart_item ) ? 1 : $cart_item['quantity'];
  388. if ( $this->is_type( array( 'percent' ) ) ) {
  389. $discount = (float) $this->get_amount() * ( $discounting_amount / 100 );
  390. } elseif ( $this->is_type( 'fixed_cart' ) && ! is_null( $cart_item ) && WC()->cart->subtotal_ex_tax ) {
  391. /**
  392. * This is the most complex discount - we need to divide the discount between rows based on their price in.
  393. * proportion to the subtotal. This is so rows with different tax rates get a fair discount, and so rows.
  394. * with no price (free) don't get discounted.
  395. *
  396. * Get item discount by dividing item cost by subtotal to get a %.
  397. *
  398. * Uses price inc tax if prices include tax to work around https://github.com/woocommerce/woocommerce/issues/7669 and https://github.com/woocommerce/woocommerce/issues/8074.
  399. */
  400. if ( wc_prices_include_tax() ) {
  401. $discount_percent = ( wc_get_price_including_tax( $cart_item['data'] ) * $cart_item_qty ) / WC()->cart->subtotal;
  402. } else {
  403. $discount_percent = ( wc_get_price_excluding_tax( $cart_item['data'] ) * $cart_item_qty ) / WC()->cart->subtotal_ex_tax;
  404. }
  405. $discount = ( (float) $this->get_amount() * $discount_percent ) / $cart_item_qty;
  406. } elseif ( $this->is_type( 'fixed_product' ) ) {
  407. $discount = min( $this->get_amount(), $discounting_amount );
  408. $discount = $single ? $discount : $discount * $cart_item_qty;
  409. }
  410. return apply_filters(
  411. 'woocommerce_coupon_get_discount_amount',
  412. NumberUtil::round( min( $discount, $discounting_amount ), wc_get_rounding_precision() ),
  413. $discounting_amount,
  414. $cart_item,
  415. $single,
  416. $this
  417. );
  418. }
  419. /*
  420. |--------------------------------------------------------------------------
  421. | Setters
  422. |--------------------------------------------------------------------------
  423. |
  424. | Functions for setting coupon data. These should not update anything in the
  425. | database itself and should only change what is stored in the class
  426. | object.
  427. |
  428. */
  429. /**
  430. * Set coupon code.
  431. *
  432. * @since 3.0.0
  433. * @param string $code Coupon code.
  434. */
  435. public function set_code( $code ) {
  436. $this->set_prop( 'code', wc_format_coupon_code( $code ) );
  437. }
  438. /**
  439. * Set coupon description.
  440. *
  441. * @since 3.0.0
  442. * @param string $description Description.
  443. */
  444. public function set_description( $description ) {
  445. $this->set_prop( 'description', $description );
  446. }
  447. /**
  448. * Set discount type.
  449. *
  450. * @since 3.0.0
  451. * @param string $discount_type Discount type.
  452. */
  453. public function set_discount_type( $discount_type ) {
  454. if ( 'percent_product' === $discount_type ) {
  455. $discount_type = 'percent'; // Backwards compatibility.
  456. }
  457. if ( ! in_array( $discount_type, array_keys( wc_get_coupon_types() ), true ) ) {
  458. $this->error( 'coupon_invalid_discount_type', __( 'Invalid discount type', 'woocommerce' ) );
  459. }
  460. $this->set_prop( 'discount_type', $discount_type );
  461. }
  462. /**
  463. * Set amount.
  464. *
  465. * @since 3.0.0
  466. * @param float $amount Amount.
  467. */
  468. public function set_amount( $amount ) {
  469. $amount = wc_format_decimal( $amount );
  470. if ( ! is_numeric( $amount ) ) {
  471. $amount = 0;
  472. }
  473. if ( $amount < 0 ) {
  474. $this->error( 'coupon_invalid_amount', __( 'Invalid discount amount', 'woocommerce' ) );
  475. }
  476. if ( 'percent' === $this->get_discount_type() && $amount > 100 ) {
  477. $this->error( 'coupon_invalid_amount', __( 'Invalid discount amount', 'woocommerce' ) );
  478. }
  479. $this->set_prop( 'amount', $amount );
  480. }
  481. /**
  482. * Set expiration date.
  483. *
  484. * @since 3.0.0
  485. * @param string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if there is no date.
  486. */
  487. public function set_date_expires( $date ) {
  488. $this->set_date_prop( 'date_expires', $date );
  489. }
  490. /**
  491. * Set date_created
  492. *
  493. * @since 3.0.0
  494. * @param string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if there is no date.
  495. */
  496. public function set_date_created( $date ) {
  497. $this->set_date_prop( 'date_created', $date );
  498. }
  499. /**
  500. * Set date_modified
  501. *
  502. * @since 3.0.0
  503. * @param string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if there is no date.
  504. */
  505. public function set_date_modified( $date ) {
  506. $this->set_date_prop( 'date_modified', $date );
  507. }
  508. /**
  509. * Set how many times this coupon has been used.
  510. *
  511. * @since 3.0.0
  512. * @param int $usage_count Usage count.
  513. */
  514. public function set_usage_count( $usage_count ) {
  515. $this->set_prop( 'usage_count', absint( $usage_count ) );
  516. }
  517. /**
  518. * Set if this coupon can only be used once.
  519. *
  520. * @since 3.0.0
  521. * @param bool $is_individual_use If is for individual use.
  522. */
  523. public function set_individual_use( $is_individual_use ) {
  524. $this->set_prop( 'individual_use', (bool) $is_individual_use );
  525. }
  526. /**
  527. * Set the product IDs this coupon can be used with.
  528. *
  529. * @since 3.0.0
  530. * @param array $product_ids Products IDs.
  531. */
  532. public function set_product_ids( $product_ids ) {
  533. $this->set_prop( 'product_ids', array_filter( wp_parse_id_list( (array) $product_ids ) ) );
  534. }
  535. /**
  536. * Set the product IDs this coupon cannot be used with.
  537. *
  538. * @since 3.0.0
  539. * @param array $excluded_product_ids Exclude product IDs.
  540. */
  541. public function set_excluded_product_ids( $excluded_product_ids ) {
  542. $this->set_prop( 'excluded_product_ids', array_filter( wp_parse_id_list( (array) $excluded_product_ids ) ) );
  543. }
  544. /**
  545. * Set the amount of times this coupon can be used.
  546. *
  547. * @since 3.0.0
  548. * @param int $usage_limit Usage limit.
  549. */
  550. public function set_usage_limit( $usage_limit ) {
  551. $this->set_prop( 'usage_limit', absint( $usage_limit ) );
  552. }
  553. /**
  554. * Set the amount of times this coupon can be used per user.
  555. *
  556. * @since 3.0.0
  557. * @param int $usage_limit Usage limit.
  558. */
  559. public function set_usage_limit_per_user( $usage_limit ) {
  560. $this->set_prop( 'usage_limit_per_user', absint( $usage_limit ) );
  561. }
  562. /**
  563. * Set usage limit to x number of items.
  564. *
  565. * @since 3.0.0
  566. * @param int|null $limit_usage_to_x_items Limit usage to X items.
  567. */
  568. public function set_limit_usage_to_x_items( $limit_usage_to_x_items ) {
  569. $this->set_prop( 'limit_usage_to_x_items', is_null( $limit_usage_to_x_items ) ? null : absint( $limit_usage_to_x_items ) );
  570. }
  571. /**
  572. * Set if this coupon enables free shipping or not.
  573. *
  574. * @since 3.0.0
  575. * @param bool $free_shipping If grant free shipping.
  576. */
  577. public function set_free_shipping( $free_shipping ) {
  578. $this->set_prop( 'free_shipping', (bool) $free_shipping );
  579. }
  580. /**
  581. * Set the product category IDs this coupon can be used with.
  582. *
  583. * @since 3.0.0
  584. * @param array $product_categories List of product categories.
  585. */
  586. public function set_product_categories( $product_categories ) {
  587. $this->set_prop( 'product_categories', array_filter( wp_parse_id_list( (array) $product_categories ) ) );
  588. }
  589. /**
  590. * Set the product category IDs this coupon cannot be used with.
  591. *
  592. * @since 3.0.0
  593. * @param array $excluded_product_categories List of excluded product categories.
  594. */
  595. public function set_excluded_product_categories( $excluded_product_categories ) {
  596. $this->set_prop( 'excluded_product_categories', array_filter( wp_parse_id_list( (array) $excluded_product_categories ) ) );
  597. }
  598. /**
  599. * Set if this coupon should excluded sale items or not.
  600. *
  601. * @since 3.0.0
  602. * @param bool $exclude_sale_items If should exclude sale items.
  603. */
  604. public function set_exclude_sale_items( $exclude_sale_items ) {
  605. $this->set_prop( 'exclude_sale_items', (bool) $exclude_sale_items );
  606. }
  607. /**
  608. * Set the minimum spend amount.
  609. *
  610. * @since 3.0.0
  611. * @param float $amount Minium amount.
  612. */
  613. public function set_minimum_amount( $amount ) {
  614. $this->set_prop( 'minimum_amount', wc_format_decimal( $amount ) );
  615. }
  616. /**
  617. * Set the maximum spend amount.
  618. *
  619. * @since 3.0.0
  620. * @param float $amount Maximum amount.
  621. */
  622. public function set_maximum_amount( $amount ) {
  623. $this->set_prop( 'maximum_amount', wc_format_decimal( $amount ) );
  624. }
  625. /**
  626. * Set email restrictions.
  627. *
  628. * @since 3.0.0
  629. * @param array $emails List of emails.
  630. */
  631. public function set_email_restrictions( $emails = array() ) {
  632. $emails = array_filter( array_map( 'sanitize_email', array_map( 'strtolower', (array) $emails ) ) );
  633. foreach ( $emails as $email ) {
  634. if ( ! is_email( $email ) ) {
  635. $this->error( 'coupon_invalid_email_address', __( 'Invalid email address restriction', 'woocommerce' ) );
  636. }
  637. }
  638. $this->set_prop( 'email_restrictions', $emails );
  639. }
  640. /**
  641. * Set which users have used this coupon.
  642. *
  643. * @since 3.0.0
  644. * @param array $used_by List of user IDs.
  645. */
  646. public function set_used_by( $used_by ) {
  647. $this->set_prop( 'used_by', array_filter( $used_by ) );
  648. }
  649. /**
  650. * Set coupon virtual state.
  651. *
  652. * @param boolean $virtual Whether it is virtual or not.
  653. * @since 3.2.0
  654. */
  655. public function set_virtual( $virtual ) {
  656. $this->set_prop( 'virtual', (bool) $virtual );
  657. }
  658. /*
  659. |--------------------------------------------------------------------------
  660. | Other Actions
  661. |--------------------------------------------------------------------------
  662. */
  663. /**
  664. * Developers can programmatically return coupons. This function will read those values into our WC_Coupon class.
  665. *
  666. * @since 3.0.0
  667. * @param string $code Coupon code.
  668. * @param array $coupon Array of coupon properties.
  669. */
  670. public function read_manual_coupon( $code, $coupon ) {
  671. foreach ( $coupon as $key => $value ) {
  672. switch ( $key ) {
  673. case 'excluded_product_ids':
  674. case 'exclude_product_ids':
  675. if ( ! is_array( $coupon[ $key ] ) ) {
  676. wc_doing_it_wrong( $key, $key . ' should be an array instead of a string.', '3.0' );
  677. $coupon['excluded_product_ids'] = wc_string_to_array( $value );
  678. }
  679. break;
  680. case 'exclude_product_categories':
  681. case 'excluded_product_categories':
  682. if ( ! is_array( $coupon[ $key ] ) ) {
  683. wc_doing_it_wrong( $key, $key . ' should be an array instead of a string.', '3.0' );
  684. $coupon['excluded_product_categories'] = wc_string_to_array( $value );
  685. }
  686. break;
  687. case 'product_ids':
  688. if ( ! is_array( $coupon[ $key ] ) ) {
  689. wc_doing_it_wrong( $key, $key . ' should be an array instead of a string.', '3.0' );
  690. $coupon[ $key ] = wc_string_to_array( $value );
  691. }
  692. break;
  693. case 'individual_use':
  694. case 'free_shipping':
  695. case 'exclude_sale_items':
  696. if ( ! is_bool( $coupon[ $key ] ) ) {
  697. wc_doing_it_wrong( $key, $key . ' should be true or false instead of yes or no.', '3.0' );
  698. $coupon[ $key ] = wc_string_to_bool( $value );
  699. }
  700. break;
  701. case 'expiry_date':
  702. $coupon['date_expires'] = $value;
  703. break;
  704. }
  705. }
  706. $this->set_props( $coupon );
  707. $this->set_code( $code );
  708. $this->set_id( 0 );
  709. $this->set_virtual( true );
  710. }
  711. /**
  712. * Increase usage count for current coupon.
  713. *
  714. * @param string $used_by Either user ID or billing email.
  715. * @param WC_Order $order If provided, will clear the coupons held by this order.
  716. */
  717. public function increase_usage_count( $used_by = '', $order = null ) {
  718. if ( $this->get_id() && $this->data_store ) {
  719. $new_count = $this->data_store->increase_usage_count( $this, $used_by, $order );
  720. // Bypass set_prop and remove pending changes since the data store saves the count already.
  721. $this->data['usage_count'] = $new_count;
  722. if ( isset( $this->changes['usage_count'] ) ) {
  723. unset( $this->changes['usage_count'] );
  724. }
  725. }
  726. }
  727. /**
  728. * Decrease usage count for current coupon.
  729. *
  730. * @param string $used_by Either user ID or billing email.
  731. */
  732. public function decrease_usage_count( $used_by = '' ) {
  733. if ( $this->get_id() && $this->get_usage_count() > 0 && $this->data_store ) {
  734. $new_count = $this->data_store->decrease_usage_count( $this, $used_by );
  735. // Bypass set_prop and remove pending changes since the data store saves the count already.
  736. $this->data['usage_count'] = $new_count;
  737. if ( isset( $this->changes['usage_count'] ) ) {
  738. unset( $this->changes['usage_count'] );
  739. }
  740. }
  741. }
  742. /*
  743. |--------------------------------------------------------------------------
  744. | Validation & Error Handling
  745. |--------------------------------------------------------------------------
  746. */
  747. /**
  748. * Returns the error_message string.
  749. * @return string
  750. */
  751. public function get_error_message() {
  752. return $this->error_message;
  753. }
  754. /**
  755. * Check if a coupon is valid for the cart.
  756. *
  757. * @deprecated 3.2.0 In favor of WC_Discounts->is_coupon_valid.
  758. * @return bool
  759. */
  760. public function is_valid() {
  761. $discounts = new WC_Discounts( WC()->cart );
  762. $valid = $discounts->is_coupon_valid( $this );
  763. if ( is_wp_error( $valid ) ) {
  764. $this->error_message = $valid->get_error_message();
  765. return false;
  766. }
  767. return $valid;
  768. }
  769. /**
  770. * Check if a coupon is valid.
  771. *
  772. * @return bool
  773. */
  774. public function is_valid_for_cart() {
  775. return apply_filters( 'woocommerce_coupon_is_valid_for_cart', $this->is_type( wc_get_cart_coupon_types() ), $this );
  776. }
  777. /**
  778. * Check if a coupon is valid for a product.
  779. *
  780. * @param WC_Product $product Product instance.
  781. * @param array $values Values.
  782. * @return bool
  783. */
  784. public function is_valid_for_product( $product, $values = array() ) {
  785. if ( ! $this->is_type( wc_get_product_coupon_types() ) ) {
  786. return apply_filters( 'woocommerce_coupon_is_valid_for_product', false, $product, $this, $values );
  787. }
  788. $valid = false;
  789. $product_cats = wc_get_product_cat_ids( $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id() );
  790. $product_ids = array( $product->get_id(), $product->get_parent_id() );
  791. // Specific products get the discount.
  792. if ( count( $this->get_product_ids() ) && count( array_intersect( $product_ids, $this->get_product_ids() ) ) ) {
  793. $valid = true;
  794. }
  795. // Category discounts.
  796. if ( count( $this->get_product_categories() ) && count( array_intersect( $product_cats, $this->get_product_categories() ) ) ) {
  797. $valid = true;
  798. }
  799. // No product ids - all items discounted.
  800. if ( ! count( $this->get_product_ids() ) && ! count( $this->get_product_categories() ) ) {
  801. $valid = true;
  802. }
  803. // Specific product IDs excluded from the discount.
  804. if ( count( $this->get_excluded_product_ids() ) && count( array_intersect( $product_ids, $this->get_excluded_product_ids() ) ) ) {
  805. $valid = false;
  806. }
  807. // Specific categories excluded from the discount.
  808. if ( count( $this->get_excluded_product_categories() ) && count( array_intersect( $product_cats, $this->get_excluded_product_categories() ) ) ) {
  809. $valid = false;
  810. }
  811. // Sale Items excluded from discount.
  812. if ( $this->get_exclude_sale_items() && $product->is_on_sale() ) {
  813. $valid = false;
  814. }
  815. return apply_filters( 'woocommerce_coupon_is_valid_for_product', $valid, $product, $this, $values );
  816. }
  817. /**
  818. * Converts one of the WC_Coupon message/error codes to a message string and.
  819. * displays the message/error.
  820. *
  821. * @param int $msg_code Message/error code.
  822. */
  823. public function add_coupon_message( $msg_code ) {
  824. $msg = $msg_code < 200 ? $this->get_coupon_error( $msg_code ) : $this->get_coupon_message( $msg_code );
  825. if ( ! $msg ) {
  826. return;
  827. }
  828. if ( $msg_code < 200 ) {
  829. wc_add_notice( $msg, 'error' );
  830. } else {
  831. wc_add_notice( $msg );
  832. }
  833. }
  834. /**
  835. * Map one of the WC_Coupon message codes to a message string.
  836. *
  837. * @param integer $msg_code Message code.
  838. * @return string Message/error string.
  839. */
  840. public function get_coupon_message( $msg_code ) {
  841. switch ( $msg_code ) {
  842. case self::WC_COUPON_SUCCESS:
  843. $msg = __( 'Coupon code applied successfully.', 'woocommerce' );
  844. break;
  845. case self::WC_COUPON_REMOVED:
  846. $msg = __( 'Coupon code removed successfully.', 'woocommerce' );
  847. break;
  848. default:
  849. $msg = '';
  850. break;
  851. }
  852. return apply_filters( 'woocommerce_coupon_message', $msg, $msg_code, $this );
  853. }
  854. /**
  855. * Map one of the WC_Coupon error codes to a message string.
  856. *
  857. * @param int $err_code Message/error code.
  858. * @return string Message/error string
  859. */
  860. public function get_coupon_error( $err_code ) {
  861. switch ( $err_code ) {
  862. case self::E_WC_COUPON_INVALID_FILTERED:
  863. $err = __( 'Coupon is not valid.', 'woocommerce' );
  864. break;
  865. case self::E_WC_COUPON_NOT_EXIST:
  866. /* translators: %s: coupon code */
  867. $err = sprintf( __( 'Coupon "%s" does not exist!', 'woocommerce' ), esc_html( $this->get_code() ) );
  868. break;
  869. case self::E_WC_COUPON_INVALID_REMOVED:
  870. /* translators: %s: coupon code */
  871. $err = sprintf( __( 'Sorry, it seems the coupon "%s" is invalid - it has now been removed from your order.', 'woocommerce' ), esc_html( $this->get_code() ) );
  872. break;
  873. case self::E_WC_COUPON_NOT_YOURS_REMOVED:
  874. /* translators: %s: coupon code */
  875. $err = sprintf( __( 'Sorry, it seems the coupon "%s" is not yours - it has now been removed from your order.', 'woocommerce' ), esc_html( $this->get_code() ) );
  876. break;
  877. case self::E_WC_COUPON_ALREADY_APPLIED:
  878. $err = __( 'Coupon code already applied!', 'woocommerce' );
  879. break;
  880. case self::E_WC_COUPON_ALREADY_APPLIED_INDIV_USE_ONLY:
  881. /* translators: %s: coupon code */
  882. $err = sprintf( __( 'Sorry, coupon "%s" has already been applied and cannot be used in conjunction with other coupons.', 'woocommerce' ), esc_html( $this->get_code() ) );
  883. break;
  884. case self::E_WC_COUPON_USAGE_LIMIT_REACHED:
  885. $err = __( 'Coupon usage limit has been reached.', 'woocommerce' );
  886. break;
  887. case self::E_WC_COUPON_EXPIRED:
  888. $err = __( 'This coupon has expired.', 'woocommerce' );
  889. break;
  890. case self::E_WC_COUPON_MIN_SPEND_LIMIT_NOT_MET:
  891. /* translators: %s: coupon minimum amount */
  892. $err = sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $this->get_minimum_amount() ) );
  893. break;
  894. case self::E_WC_COUPON_MAX_SPEND_LIMIT_MET:
  895. /* translators: %s: coupon maximum amount */
  896. $err = sprintf( __( 'The maximum spend for this coupon is %s.', 'woocommerce' ), wc_price( $this->get_maximum_amount() ) );
  897. break;
  898. case self::E_WC_COUPON_NOT_APPLICABLE:
  899. $err = __( 'Sorry, this coupon is not applicable to your cart contents.', 'woocommerce' );
  900. break;
  901. case self::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK:
  902. if ( is_user_logged_in() && wc_get_page_id( 'myaccount' ) > 0 ) {
  903. /* translators: %s: myaccount page link. */
  904. $err = sprintf( __( 'Coupon usage limit has been reached. If you were using this coupon just now but order was not complete, you can retry or cancel the order by going to the <a href="%s">my account page</a>.', 'woocommerce' ), wc_get_endpoint_url( 'orders', '', wc_get_page_permalink( 'myaccount' ) ) );
  905. } else {
  906. $err = $this->get_coupon_error( self::E_WC_COUPON_USAGE_LIMIT_REACHED );
  907. }
  908. break;
  909. case self::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST:
  910. $err = __( 'Coupon usage limit has been reached. Please try again after some time, or contact us for help.', 'woocommerce' );
  911. break;
  912. case self::E_WC_COUPON_EXCLUDED_PRODUCTS:
  913. // Store excluded products that are in cart in $products.
  914. $products = array();
  915. if ( ! WC()->cart->is_empty() ) {
  916. foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
  917. if ( in_array( intval( $cart_item['product_id'] ), $this->get_excluded_product_ids(), true ) || in_array( intval( $cart_item['variation_id'] ), $this->get_excluded_product_ids(), true ) || in_array( intval( $cart_item['data']->get_parent_id() ), $this->get_excluded_product_ids(), true ) ) {
  918. $products[] = $cart_item['data']->get_name();
  919. }
  920. }
  921. }
  922. /* translators: %s: products list */
  923. $err = sprintf( __( 'Sorry, this coupon is not applicable to the products: %s.', 'woocommerce' ), implode( ', ', $products ) );
  924. break;
  925. case self::E_WC_COUPON_EXCLUDED_CATEGORIES:
  926. // Store excluded categories that are in cart in $categories.
  927. $categories = array();
  928. if ( ! WC()->cart->is_empty() ) {
  929. foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
  930. $product_cats = wc_get_product_cat_ids( $cart_item['product_id'] );
  931. $intersect = array_intersect( $product_cats, $this->get_excluded_product_categories() );
  932. if ( count( $intersect ) > 0 ) {
  933. foreach ( $intersect as $cat_id ) {
  934. $cat = get_term( $cat_id, 'product_cat' );
  935. $categories[] = $cat->name;
  936. }
  937. }
  938. }
  939. }
  940. /* translators: %s: categories list */
  941. $err = sprintf( __( 'Sorry, this coupon is not applicable to the categories: %s.', 'woocommerce' ), implode( ', ', array_unique( $categories ) ) );
  942. break;
  943. case self::E_WC_COUPON_NOT_VALID_SALE_ITEMS:
  944. $err = __( 'Sorry, this coupon is not valid for sale items.', 'woocommerce' );
  945. break;
  946. default:
  947. $err = '';
  948. break;
  949. }
  950. return apply_filters( 'woocommerce_coupon_error', $err, $err_code, $this );
  951. }
  952. /**
  953. * Map one of the WC_Coupon error codes to an error string.
  954. * No coupon instance will be available where a coupon does not exist,
  955. * so this static method exists.
  956. *
  957. * @param int $err_code Error code.
  958. * @return string Error string.
  959. */
  960. public static function get_generic_coupon_error( $err_code ) {
  961. switch ( $err_code ) {
  962. case self::E_WC_COUPON_NOT_EXIST:
  963. $err = __( 'Coupon does not exist!', 'woocommerce' );
  964. break;
  965. case self::E_WC_COUPON_PLEASE_ENTER:
  966. $err = __( 'Please enter a coupon code.', 'woocommerce' );
  967. break;
  968. default:
  969. $err = '';
  970. break;
  971. }
  972. // When using this static method, there is no $this to pass to filter.
  973. return apply_filters( 'woocommerce_coupon_error', $err, $err_code, null );
  974. }
  975. }