class-wc-rest-coupons-controller.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. <?php
  2. /**
  3. * REST API Coupons controller
  4. *
  5. * Handles requests to the /coupons endpoint.
  6. *
  7. * @author WooThemes
  8. * @category API
  9. * @package WooCommerce/API
  10. * @since 3.0.0
  11. */
  12. if ( ! defined( 'ABSPATH' ) ) {
  13. exit;
  14. }
  15. /**
  16. * REST API Coupons controller class.
  17. *
  18. * @package WooCommerce/API
  19. * @extends WC_REST_Posts_Controller
  20. */
  21. class WC_REST_Coupons_V1_Controller extends WC_REST_Posts_Controller {
  22. /**
  23. * Endpoint namespace.
  24. *
  25. * @var string
  26. */
  27. protected $namespace = 'wc/v1';
  28. /**
  29. * Route base.
  30. *
  31. * @var string
  32. */
  33. protected $rest_base = 'coupons';
  34. /**
  35. * Post type.
  36. *
  37. * @var string
  38. */
  39. protected $post_type = 'shop_coupon';
  40. /**
  41. * Coupons actions.
  42. */
  43. public function __construct() {
  44. add_filter( "woocommerce_rest_{$this->post_type}_query", array( $this, 'query_args' ), 10, 2 );
  45. }
  46. /**
  47. * Register the routes for coupons.
  48. */
  49. public function register_routes() {
  50. register_rest_route( $this->namespace, '/' . $this->rest_base, array(
  51. array(
  52. 'methods' => WP_REST_Server::READABLE,
  53. 'callback' => array( $this, 'get_items' ),
  54. 'permission_callback' => array( $this, 'get_items_permissions_check' ),
  55. 'args' => $this->get_collection_params(),
  56. ),
  57. array(
  58. 'methods' => WP_REST_Server::CREATABLE,
  59. 'callback' => array( $this, 'create_item' ),
  60. 'permission_callback' => array( $this, 'create_item_permissions_check' ),
  61. 'args' => array_merge( $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ), array(
  62. 'code' => array(
  63. 'description' => __( 'Coupon code.', 'woocommerce' ),
  64. 'required' => true,
  65. 'type' => 'string',
  66. ),
  67. ) ),
  68. ),
  69. 'schema' => array( $this, 'get_public_item_schema' ),
  70. ) );
  71. register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
  72. 'args' => array(
  73. 'id' => array(
  74. 'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
  75. 'type' => 'integer',
  76. ),
  77. ),
  78. array(
  79. 'methods' => WP_REST_Server::READABLE,
  80. 'callback' => array( $this, 'get_item' ),
  81. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  82. 'args' => array(
  83. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  84. ),
  85. ),
  86. array(
  87. 'methods' => WP_REST_Server::EDITABLE,
  88. 'callback' => array( $this, 'update_item' ),
  89. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  90. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  91. ),
  92. array(
  93. 'methods' => WP_REST_Server::DELETABLE,
  94. 'callback' => array( $this, 'delete_item' ),
  95. 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  96. 'args' => array(
  97. 'force' => array(
  98. 'default' => false,
  99. 'type' => 'boolean',
  100. 'description' => __( 'Whether to bypass trash and force deletion.', 'woocommerce' ),
  101. ),
  102. ),
  103. ),
  104. 'schema' => array( $this, 'get_public_item_schema' ),
  105. ) );
  106. register_rest_route( $this->namespace, '/' . $this->rest_base . '/batch', array(
  107. array(
  108. 'methods' => WP_REST_Server::EDITABLE,
  109. 'callback' => array( $this, 'batch_items' ),
  110. 'permission_callback' => array( $this, 'batch_items_permissions_check' ),
  111. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  112. ),
  113. 'schema' => array( $this, 'get_public_batch_schema' ),
  114. ) );
  115. }
  116. /**
  117. * Query args.
  118. *
  119. * @param array $args Query args
  120. * @param WP_REST_Request $request Request data.
  121. * @return array
  122. */
  123. public function query_args( $args, $request ) {
  124. if ( ! empty( $request['code'] ) ) {
  125. $id = wc_get_coupon_id_by_code( $request['code'] );
  126. $args['post__in'] = array( $id );
  127. }
  128. return $args;
  129. }
  130. /**
  131. * Prepare a single coupon output for response.
  132. *
  133. * @param WP_Post $post Post object.
  134. * @param WP_REST_Request $request Request object.
  135. * @return WP_REST_Response $data
  136. */
  137. public function prepare_item_for_response( $post, $request ) {
  138. $coupon = new WC_Coupon( (int) $post->ID );
  139. $_data = $coupon->get_data();
  140. $format_decimal = array( 'amount', 'minimum_amount', 'maximum_amount' );
  141. $format_date = array( 'date_created', 'date_modified' );
  142. $format_date_utc = array( 'date_expires' );
  143. $format_null = array( 'usage_limit', 'usage_limit_per_user' );
  144. // Format decimal values.
  145. foreach ( $format_decimal as $key ) {
  146. $_data[ $key ] = wc_format_decimal( $_data[ $key ], 2 );
  147. }
  148. // Format date values.
  149. foreach ( $format_date as $key ) {
  150. $_data[ $key ] = $_data[ $key ] ? wc_rest_prepare_date_response( $_data[ $key ], false ) : null;
  151. }
  152. foreach ( $format_date_utc as $key ) {
  153. $_data[ $key ] = $_data[ $key ] ? wc_rest_prepare_date_response( $_data[ $key ] ) : null;
  154. }
  155. // Format null values.
  156. foreach ( $format_null as $key ) {
  157. $_data[ $key ] = $_data[ $key ] ? $_data[ $key ] : null;
  158. }
  159. $data = array(
  160. 'id' => $_data['id'],
  161. 'code' => $_data['code'],
  162. 'date_created' => $_data['date_created'],
  163. 'date_modified' => $_data['date_modified'],
  164. 'discount_type' => $_data['discount_type'],
  165. 'description' => $_data['description'],
  166. 'amount' => $_data['amount'],
  167. 'expiry_date' => $_data['date_expires'],
  168. 'usage_count' => $_data['usage_count'],
  169. 'individual_use' => $_data['individual_use'],
  170. 'product_ids' => $_data['product_ids'],
  171. 'exclude_product_ids' => $_data['excluded_product_ids'],
  172. 'usage_limit' => $_data['usage_limit'],
  173. 'usage_limit_per_user' => $_data['usage_limit_per_user'],
  174. 'limit_usage_to_x_items' => $_data['limit_usage_to_x_items'],
  175. 'free_shipping' => $_data['free_shipping'],
  176. 'product_categories' => $_data['product_categories'],
  177. 'excluded_product_categories' => $_data['excluded_product_categories'],
  178. 'exclude_sale_items' => $_data['exclude_sale_items'],
  179. 'minimum_amount' => $_data['minimum_amount'],
  180. 'maximum_amount' => $_data['maximum_amount'],
  181. 'email_restrictions' => $_data['email_restrictions'],
  182. 'used_by' => $_data['used_by'],
  183. );
  184. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  185. $data = $this->add_additional_fields_to_object( $data, $request );
  186. $data = $this->filter_response_by_context( $data, $context );
  187. $response = rest_ensure_response( $data );
  188. $response->add_links( $this->prepare_links( $post, $request ) );
  189. /**
  190. * Filter the data for a response.
  191. *
  192. * The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being
  193. * prepared for the response.
  194. *
  195. * @param WP_REST_Response $response The response object.
  196. * @param WP_Post $post Post object.
  197. * @param WP_REST_Request $request Request object.
  198. */
  199. return apply_filters( "woocommerce_rest_prepare_{$this->post_type}", $response, $post, $request );
  200. }
  201. /**
  202. * Only return writable props from schema.
  203. * @param array $schema
  204. * @return bool
  205. */
  206. protected function filter_writable_props( $schema ) {
  207. return empty( $schema['readonly'] );
  208. }
  209. /**
  210. * Prepare a single coupon for create or update.
  211. *
  212. * @param WP_REST_Request $request Request object.
  213. * @return WP_Error|stdClass $data Post object.
  214. */
  215. protected function prepare_item_for_database( $request ) {
  216. $id = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
  217. $coupon = new WC_Coupon( $id );
  218. $schema = $this->get_item_schema();
  219. $data_keys = array_keys( array_filter( $schema['properties'], array( $this, 'filter_writable_props' ) ) );
  220. // Update to schema to make compatible with CRUD schema.
  221. if ( $request['exclude_product_ids'] ) {
  222. $request['excluded_product_ids'] = $request['exclude_product_ids'];
  223. }
  224. if ( $request['expiry_date'] ) {
  225. $request['date_expires'] = $request['expiry_date'];
  226. }
  227. // Validate required POST fields.
  228. if ( 'POST' === $request->get_method() && 0 === $coupon->get_id() ) {
  229. if ( empty( $request['code'] ) ) {
  230. return new WP_Error( 'woocommerce_rest_empty_coupon_code', sprintf( __( 'The coupon code cannot be empty.', 'woocommerce' ), 'code' ), array( 'status' => 400 ) );
  231. }
  232. }
  233. // Handle all writable props.
  234. foreach ( $data_keys as $key ) {
  235. $value = $request[ $key ];
  236. if ( ! is_null( $value ) ) {
  237. switch ( $key ) {
  238. case 'code' :
  239. $coupon_code = wc_format_coupon_code( $value );
  240. $id = $coupon->get_id() ? $coupon->get_id() : 0;
  241. $id_from_code = wc_get_coupon_id_by_code( $coupon_code, $id );
  242. if ( $id_from_code ) {
  243. return new WP_Error( 'woocommerce_rest_coupon_code_already_exists', __( 'The coupon code already exists', 'woocommerce' ), array( 'status' => 400 ) );
  244. }
  245. $coupon->set_code( $coupon_code );
  246. break;
  247. case 'description' :
  248. $coupon->set_description( wp_filter_post_kses( $value ) );
  249. break;
  250. case 'expiry_date' :
  251. $coupon->set_date_expires( $value );
  252. break;
  253. default :
  254. if ( is_callable( array( $coupon, "set_{$key}" ) ) ) {
  255. $coupon->{"set_{$key}"}( $value );
  256. }
  257. break;
  258. }
  259. }
  260. }
  261. /**
  262. * Filter the query_vars used in `get_items` for the constructed query.
  263. *
  264. * The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being
  265. * prepared for insertion.
  266. *
  267. * @param WC_Coupon $coupon The coupon object.
  268. * @param WP_REST_Request $request Request object.
  269. */
  270. return apply_filters( "woocommerce_rest_pre_insert_{$this->post_type}", $coupon, $request );
  271. }
  272. /**
  273. * Create a single item.
  274. *
  275. * @param WP_REST_Request $request Full details about the request.
  276. * @return WP_Error|WP_REST_Response
  277. */
  278. public function create_item( $request ) {
  279. if ( ! empty( $request['id'] ) ) {
  280. /* translators: %s: post type */
  281. return new WP_Error( "woocommerce_rest_{$this->post_type}_exists", sprintf( __( 'Cannot create existing %s.', 'woocommerce' ), $this->post_type ), array( 'status' => 400 ) );
  282. }
  283. $coupon_id = $this->save_coupon( $request );
  284. if ( is_wp_error( $coupon_id ) ) {
  285. return $coupon_id;
  286. }
  287. $post = get_post( $coupon_id );
  288. $this->update_additional_fields_for_object( $post, $request );
  289. $this->add_post_meta_fields( $post, $request );
  290. /**
  291. * Fires after a single item is created or updated via the REST API.
  292. *
  293. * @param WP_Post $post Post object.
  294. * @param WP_REST_Request $request Request object.
  295. * @param boolean $creating True when creating item, false when updating.
  296. */
  297. do_action( "woocommerce_rest_insert_{$this->post_type}", $post, $request, true );
  298. $request->set_param( 'context', 'edit' );
  299. $response = $this->prepare_item_for_response( $post, $request );
  300. $response = rest_ensure_response( $response );
  301. $response->set_status( 201 );
  302. $response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $post->ID ) ) );
  303. return $response;
  304. }
  305. /**
  306. * Update a single coupon.
  307. *
  308. * @param WP_REST_Request $request Full details about the request.
  309. * @return WP_Error|WP_REST_Response
  310. */
  311. public function update_item( $request ) {
  312. try {
  313. $post_id = (int) $request['id'];
  314. if ( empty( $post_id ) || get_post_type( $post_id ) !== $this->post_type ) {
  315. return new WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'ID is invalid.', 'woocommerce' ), array( 'status' => 400 ) );
  316. }
  317. $coupon_id = $this->save_coupon( $request );
  318. if ( is_wp_error( $coupon_id ) ) {
  319. return $coupon_id;
  320. }
  321. $post = get_post( $coupon_id );
  322. $this->update_additional_fields_for_object( $post, $request );
  323. /**
  324. * Fires after a single item is created or updated via the REST API.
  325. *
  326. * @param WP_Post $post Post object.
  327. * @param WP_REST_Request $request Request object.
  328. * @param boolean $creating True when creating item, false when updating.
  329. */
  330. do_action( "woocommerce_rest_insert_{$this->post_type}", $post, $request, false );
  331. $request->set_param( 'context', 'edit' );
  332. $response = $this->prepare_item_for_response( $post, $request );
  333. return rest_ensure_response( $response );
  334. } catch ( Exception $e ) {
  335. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  336. }
  337. }
  338. /**
  339. * Saves a coupon to the database.
  340. *
  341. * @since 3.0.0
  342. * @param WP_REST_Request $request Full details about the request.
  343. * @return WP_Error|int
  344. */
  345. protected function save_coupon( $request ) {
  346. try {
  347. $coupon = $this->prepare_item_for_database( $request );
  348. if ( is_wp_error( $coupon ) ) {
  349. return $coupon;
  350. }
  351. $coupon->save();
  352. return $coupon->get_id();
  353. } catch ( WC_Data_Exception $e ) {
  354. return new WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
  355. } catch ( WC_REST_Exception $e ) {
  356. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
  357. }
  358. }
  359. /**
  360. * Get the Coupon's schema, conforming to JSON Schema.
  361. *
  362. * @return array
  363. */
  364. public function get_item_schema() {
  365. $schema = array(
  366. '$schema' => 'http://json-schema.org/draft-04/schema#',
  367. 'title' => $this->post_type,
  368. 'type' => 'object',
  369. 'properties' => array(
  370. 'id' => array(
  371. 'description' => __( 'Unique identifier for the object.', 'woocommerce' ),
  372. 'type' => 'integer',
  373. 'context' => array( 'view', 'edit' ),
  374. 'readonly' => true,
  375. ),
  376. 'code' => array(
  377. 'description' => __( 'Coupon code.', 'woocommerce' ),
  378. 'type' => 'string',
  379. 'context' => array( 'view', 'edit' ),
  380. ),
  381. 'date_created' => array(
  382. 'description' => __( "The date the coupon was created, in the site's timezone.", 'woocommerce' ),
  383. 'type' => 'date-time',
  384. 'context' => array( 'view', 'edit' ),
  385. 'readonly' => true,
  386. ),
  387. 'date_modified' => array(
  388. 'description' => __( "The date the coupon was last modified, in the site's timezone.", 'woocommerce' ),
  389. 'type' => 'date-time',
  390. 'context' => array( 'view', 'edit' ),
  391. 'readonly' => true,
  392. ),
  393. 'description' => array(
  394. 'description' => __( 'Coupon description.', 'woocommerce' ),
  395. 'type' => 'string',
  396. 'context' => array( 'view', 'edit' ),
  397. ),
  398. 'discount_type' => array(
  399. 'description' => __( 'Determines the type of discount that will be applied.', 'woocommerce' ),
  400. 'type' => 'string',
  401. 'default' => 'fixed_cart',
  402. 'enum' => array_keys( wc_get_coupon_types() ),
  403. 'context' => array( 'view', 'edit' ),
  404. ),
  405. 'amount' => array(
  406. 'description' => __( 'The amount of discount. Should always be numeric, even if setting a percentage.', 'woocommerce' ),
  407. 'type' => 'string',
  408. 'context' => array( 'view', 'edit' ),
  409. ),
  410. 'expiry_date' => array(
  411. 'description' => __( 'UTC DateTime when the coupon expires.', 'woocommerce' ),
  412. 'type' => 'string',
  413. 'context' => array( 'view', 'edit' ),
  414. ),
  415. 'usage_count' => array(
  416. 'description' => __( 'Number of times the coupon has been used already.', 'woocommerce' ),
  417. 'type' => 'integer',
  418. 'context' => array( 'view', 'edit' ),
  419. 'readonly' => true,
  420. ),
  421. 'individual_use' => array(
  422. 'description' => __( 'If true, the coupon can only be used individually. Other applied coupons will be removed from the cart.', 'woocommerce' ),
  423. 'type' => 'boolean',
  424. 'default' => false,
  425. 'context' => array( 'view', 'edit' ),
  426. ),
  427. 'product_ids' => array(
  428. 'description' => __( "List of product IDs the coupon can be used on.", 'woocommerce' ),
  429. 'type' => 'array',
  430. 'items' => array(
  431. 'type' => 'integer',
  432. ),
  433. 'context' => array( 'view', 'edit' ),
  434. ),
  435. 'exclude_product_ids' => array(
  436. 'description' => __( "List of product IDs the coupon cannot be used on.", 'woocommerce' ),
  437. 'type' => 'array',
  438. 'items' => array(
  439. 'type' => 'integer',
  440. ),
  441. 'context' => array( 'view', 'edit' ),
  442. ),
  443. 'usage_limit' => array(
  444. 'description' => __( 'How many times the coupon can be used in total.', 'woocommerce' ),
  445. 'type' => 'integer',
  446. 'context' => array( 'view', 'edit' ),
  447. ),
  448. 'usage_limit_per_user' => array(
  449. 'description' => __( 'How many times the coupon can be used per customer.', 'woocommerce' ),
  450. 'type' => 'integer',
  451. 'context' => array( 'view', 'edit' ),
  452. ),
  453. 'limit_usage_to_x_items' => array(
  454. 'description' => __( 'Max number of items in the cart the coupon can be applied to.', 'woocommerce' ),
  455. 'type' => 'integer',
  456. 'context' => array( 'view', 'edit' ),
  457. ),
  458. 'free_shipping' => array(
  459. 'description' => __( 'If true and if the free shipping method requires a coupon, this coupon will enable free shipping.', 'woocommerce' ),
  460. 'type' => 'boolean',
  461. 'default' => false,
  462. 'context' => array( 'view', 'edit' ),
  463. ),
  464. 'product_categories' => array(
  465. 'description' => __( "List of category IDs the coupon applies to.", 'woocommerce' ),
  466. 'type' => 'array',
  467. 'items' => array(
  468. 'type' => 'integer',
  469. ),
  470. 'context' => array( 'view', 'edit' ),
  471. ),
  472. 'excluded_product_categories' => array(
  473. 'description' => __( "List of category IDs the coupon does not apply to.", 'woocommerce' ),
  474. 'type' => 'array',
  475. 'items' => array(
  476. 'type' => 'integer',
  477. ),
  478. 'context' => array( 'view', 'edit' ),
  479. ),
  480. 'exclude_sale_items' => array(
  481. 'description' => __( 'If true, this coupon will not be applied to items that have sale prices.', 'woocommerce' ),
  482. 'type' => 'boolean',
  483. 'default' => false,
  484. 'context' => array( 'view', 'edit' ),
  485. ),
  486. 'minimum_amount' => array(
  487. 'description' => __( 'Minimum order amount that needs to be in the cart before coupon applies.', 'woocommerce' ),
  488. 'type' => 'string',
  489. 'context' => array( 'view', 'edit' ),
  490. ),
  491. 'maximum_amount' => array(
  492. 'description' => __( 'Maximum order amount allowed when using the coupon.', 'woocommerce' ),
  493. 'type' => 'string',
  494. 'context' => array( 'view', 'edit' ),
  495. ),
  496. 'email_restrictions' => array(
  497. 'description' => __( 'List of email addresses that can use this coupon.', 'woocommerce' ),
  498. 'type' => 'array',
  499. 'items' => array(
  500. 'type' => 'string',
  501. ),
  502. 'context' => array( 'view', 'edit' ),
  503. ),
  504. 'used_by' => array(
  505. 'description' => __( 'List of user IDs (or guest email addresses) that have used the coupon.', 'woocommerce' ),
  506. 'type' => 'array',
  507. 'items' => array(
  508. 'type' => 'integer',
  509. ),
  510. 'context' => array( 'view', 'edit' ),
  511. 'readonly' => true,
  512. ),
  513. ),
  514. );
  515. return $this->add_additional_fields_schema( $schema );
  516. }
  517. /**
  518. * Get the query params for collections of attachments.
  519. *
  520. * @return array
  521. */
  522. public function get_collection_params() {
  523. $params = parent::get_collection_params();
  524. $params['code'] = array(
  525. 'description' => __( 'Limit result set to resources with a specific code.', 'woocommerce' ),
  526. 'type' => 'string',
  527. 'sanitize_callback' => 'sanitize_text_field',
  528. 'validate_callback' => 'rest_validate_request_arg',
  529. );
  530. return $params;
  531. }
  532. }