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

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