class-wc-api-taxes.php
19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
<?php
/**
* WooCommerce API Taxes Class
*
* Handles requests to the /taxes endpoint
*
* @author WooThemes
* @category API
* @package WooCommerce/API
* @since 2.5.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class WC_API_Taxes extends WC_API_Resource {
/** @var string $base the route base */
protected $base = '/taxes';
/**
* Register the routes for this class
*
* GET /taxes
* GET /taxes/count
* GET /taxes/<id>
*
* @since 2.1
* @param array $routes
* @return array
*/
public function register_routes( $routes ) {
# GET/POST /taxes
$routes[ $this->base ] = array(
array( array( $this, 'get_taxes' ), WC_API_Server::READABLE ),
array( array( $this, 'create_tax' ), WC_API_Server::CREATABLE | WC_API_Server::ACCEPT_DATA ),
);
# GET /taxes/count
$routes[ $this->base . '/count'] = array(
array( array( $this, 'get_taxes_count' ), WC_API_Server::READABLE ),
);
# GET/PUT/DELETE /taxes/<id>
$routes[ $this->base . '/(?P<id>\d+)' ] = array(
array( array( $this, 'get_tax' ), WC_API_Server::READABLE ),
array( array( $this, 'edit_tax' ), WC_API_SERVER::EDITABLE | WC_API_SERVER::ACCEPT_DATA ),
array( array( $this, 'delete_tax' ), WC_API_SERVER::DELETABLE ),
);
# GET/POST /taxes/classes
$routes[ $this->base . '/classes' ] = array(
array( array( $this, 'get_tax_classes' ), WC_API_Server::READABLE ),
array( array( $this, 'create_tax_class' ), WC_API_Server::CREATABLE | WC_API_Server::ACCEPT_DATA ),
);
# GET /taxes/classes/count
$routes[ $this->base . '/classes/count'] = array(
array( array( $this, 'get_tax_classes_count' ), WC_API_Server::READABLE ),
);
# GET /taxes/classes/<slug>
$routes[ $this->base . '/classes/(?P<slug>\w[\w\s\-]*)' ] = array(
array( array( $this, 'delete_tax_class' ), WC_API_SERVER::DELETABLE ),
);
# POST|PUT /taxes/bulk
$routes[ $this->base . '/bulk' ] = array(
array( array( $this, 'bulk' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),
);
return $routes;
}
/**
* Get all taxes
*
* @since 2.5.0
*
* @param string $fields
* @param array $filter
* @param string $class
* @param int $page
*
* @return array
*/
public function get_taxes( $fields = null, $filter = array(), $class = null, $page = 1 ) {
if ( ! empty( $class ) ) {
$filter['tax_rate_class'] = $class;
}
$filter['page'] = $page;
$query = $this->query_tax_rates( $filter );
$taxes = array();
foreach ( $query['results'] as $tax ) {
$taxes[] = current( $this->get_tax( $tax->tax_rate_id, $fields ) );
}
// Set pagination headers
$this->server->add_pagination_headers( $query['headers'] );
return array( 'taxes' => $taxes );
}
/**
* Get the tax for the given ID
*
* @since 2.5.0
*
* @param int $id The tax ID
* @param string $fields fields to include in response
*
* @return array|WP_Error
*/
public function get_tax( $id, $fields = null ) {
global $wpdb;
try {
$id = absint( $id );
// Permissions check
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_tax', __( 'You do not have permission to read tax rate', 'woocommerce' ), 401 );
}
// Get tax rate details
$tax = WC_Tax::_get_tax_rate( $id );
if ( is_wp_error( $tax ) || empty( $tax ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_tax_id', __( 'A tax rate with the provided ID could not be found', 'woocommerce' ), 404 );
}
$tax_data = array(
'id' => (int) $tax['tax_rate_id'],
'country' => $tax['tax_rate_country'],
'state' => $tax['tax_rate_state'],
'postcode' => '',
'city' => '',
'rate' => $tax['tax_rate'],
'name' => $tax['tax_rate_name'],
'priority' => (int) $tax['tax_rate_priority'],
'compound' => (bool) $tax['tax_rate_compound'],
'shipping' => (bool) $tax['tax_rate_shipping'],
'order' => (int) $tax['tax_rate_order'],
'class' => $tax['tax_rate_class'] ? $tax['tax_rate_class'] : 'standard'
);
// Get locales from a tax rate
$locales = $wpdb->get_results( $wpdb->prepare( "
SELECT location_code, location_type
FROM {$wpdb->prefix}woocommerce_tax_rate_locations
WHERE tax_rate_id = %d
", $id ) );
if ( ! is_wp_error( $tax ) && ! is_null( $tax ) ) {
foreach ( $locales as $locale ) {
$tax_data[ $locale->location_type ] = $locale->location_code;
}
}
return array( 'tax' => apply_filters( 'woocommerce_api_tax_response', $tax_data, $tax, $fields, $this ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Create a tax
*
* @since 2.5.0
*
* @param array $data
*
* @return array
*/
public function create_tax( $data ) {
try {
if ( ! isset( $data['tax'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_tax_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'tax' ), 400 );
}
// Check permissions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_tax', __( 'You do not have permission to create tax rates', 'woocommerce' ), 401 );
}
$data = apply_filters( 'woocommerce_api_create_tax_data', $data['tax'], $this );
$tax_data = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '',
'tax_rate_name' => '',
'tax_rate_priority' => 1,
'tax_rate_compound' => 0,
'tax_rate_shipping' => 1,
'tax_rate_order' => 0,
'tax_rate_class' => '',
);
foreach ( $tax_data as $key => $value ) {
$new_key = str_replace( 'tax_rate_', '', $key );
$new_key = 'tax_rate' === $new_key ? 'rate' : $new_key;
if ( isset( $data[ $new_key ] ) ) {
if ( in_array( $new_key, array( 'compound', 'shipping' ) ) ) {
$tax_data[ $key ] = $data[ $new_key ] ? 1 : 0;
} else {
$tax_data[ $key ] = $data[ $new_key ];
}
}
}
// Create tax rate
$id = WC_Tax::_insert_tax_rate( $tax_data );
// Add locales
if ( ! empty( $data['postcode'] ) ) {
WC_Tax::_update_tax_rate_postcodes( $id, wc_clean( $data['postcode'] ) );
}
if ( ! empty( $data['city'] ) ) {
WC_Tax::_update_tax_rate_cities( $id, wc_clean( $data['city'] ) );
}
do_action( 'woocommerce_api_create_tax', $id, $data );
$this->server->send_status( 201 );
return $this->get_tax( $id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Edit a tax
*
* @since 2.5.0
*
* @param int $id The tax ID
* @param array $data
*
* @return array
*/
public function edit_tax( $id, $data ) {
try {
if ( ! isset( $data['tax'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_tax_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'tax' ), 400 );
}
// Check permissions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_edit_tax', __( 'You do not have permission to edit tax rates', 'woocommerce' ), 401 );
}
$data = $data['tax'];
// Get current tax rate data
$tax = $this->get_tax( $id );
if ( is_wp_error( $tax ) ) {
$error_data = $tax->get_error_data();
throw new WC_API_Exception( $tax->get_error_code(), $tax->get_error_message(), $error_data['status'] );
}
$current_data = $tax['tax'];
$data = apply_filters( 'woocommerce_api_edit_tax_data', $data, $this );
$tax_data = array();
$default_fields = array(
'tax_rate_country',
'tax_rate_state',
'tax_rate',
'tax_rate_name',
'tax_rate_priority',
'tax_rate_compound',
'tax_rate_shipping',
'tax_rate_order',
'tax_rate_class'
);
foreach ( $data as $key => $value ) {
$new_key = 'rate' === $key ? 'tax_rate' : 'tax_rate_' . $key;
// Check if the key is valid
if ( ! in_array( $new_key, $default_fields ) ) {
continue;
}
// Test new data against current data
if ( $value === $current_data[ $key ] ) {
continue;
}
// Fix compund and shipping values
if ( in_array( $key, array( 'compound', 'shipping' ) ) ) {
$value = $value ? 1 : 0;
}
$tax_data[ $new_key ] = $value;
}
// Update tax rate
WC_Tax::_update_tax_rate( $id, $tax_data );
// Update locales
if ( ! empty( $data['postcode'] ) && $current_data['postcode'] != $data['postcode'] ) {
WC_Tax::_update_tax_rate_postcodes( $id, wc_clean( $data['postcode'] ) );
}
if ( ! empty( $data['city'] ) && $current_data['city'] != $data['city'] ) {
WC_Tax::_update_tax_rate_cities( $id, wc_clean( $data['city'] ) );
}
do_action( 'woocommerce_api_edit_tax_rate', $id, $data );
return $this->get_tax( $id );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Delete a tax
*
* @since 2.5.0
*
* @param int $id The tax ID
*
* @return array
*/
public function delete_tax( $id ) {
global $wpdb;
try {
// Check permissions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_delete_tax', __( 'You do not have permission to delete tax rates', 'woocommerce' ), 401 );
}
$id = absint( $id );
WC_Tax::_delete_tax_rate( $id );
if ( 0 === $wpdb->rows_affected ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_delete_tax', __( 'Could not delete the tax rate', 'woocommerce' ), 401 );
}
return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), 'tax' ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Get the total number of taxes
*
* @since 2.5.0
*
* @param string $class
* @param array $filter
*
* @return array
*/
public function get_taxes_count( $class = null, $filter = array() ) {
try {
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_taxes_count', __( 'You do not have permission to read the taxes count', 'woocommerce' ), 401 );
}
if ( ! empty( $class ) ) {
$filter['tax_rate_class'] = $class;
}
$query = $this->query_tax_rates( $filter, true );
return array( 'count' => (int) $query['headers']->total );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Helper method to get tax rates objects
*
* @since 2.5.0
*
* @param array $args
* @param bool $count_only
*
* @return array
*/
protected function query_tax_rates( $args, $count_only = false ) {
global $wpdb;
$results = '';
// Set args
$args = $this->merge_query_args( $args, array() );
$query = "
SELECT tax_rate_id
FROM {$wpdb->prefix}woocommerce_tax_rates
WHERE 1 = 1
";
// Filter by tax class
if ( ! empty( $args['tax_rate_class'] ) ) {
$tax_rate_class = 'standard' !== $args['tax_rate_class'] ? sanitize_title( $args['tax_rate_class'] ) : '';
$query .= " AND tax_rate_class = '$tax_rate_class'";
}
// Order tax rates
$order_by = ' ORDER BY tax_rate_order';
// Pagination
$per_page = isset( $args['posts_per_page'] ) ? $args['posts_per_page'] : get_option( 'posts_per_page' );
$offset = 1 < $args['paged'] ? ( $args['paged'] - 1 ) * $per_page : 0;
$pagination = sprintf( ' LIMIT %d, %d', $offset, $per_page );
if ( ! $count_only ) {
$results = $wpdb->get_results( $query . $order_by . $pagination );
}
$wpdb->get_results( $query );
$headers = new stdClass;
$headers->page = $args['paged'];
$headers->total = (int) $wpdb->num_rows;
$headers->is_single = $per_page > $headers->total;
$headers->total_pages = ceil( $headers->total / $per_page );
return array(
'results' => $results,
'headers' => $headers
);
}
/**
* Bulk update or insert taxes
* Accepts an array with taxes in the formats supported by
* WC_API_Taxes->create_tax() and WC_API_Taxes->edit_tax()
*
* @since 2.5.0
*
* @param array $data
*
* @return array
*/
public function bulk( $data ) {
try {
if ( ! isset( $data['taxes'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_taxes_data', sprintf( __( 'No %1$s data specified to create/edit %1$s', 'woocommerce' ), 'taxes' ), 400 );
}
$data = $data['taxes'];
$limit = apply_filters( 'woocommerce_api_bulk_limit', 100, 'taxes' );
// Limit bulk operation
if ( count( $data ) > $limit ) {
throw new WC_API_Exception( 'woocommerce_api_taxes_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request', 'woocommerce' ), $limit ), 413 );
}
$taxes = array();
foreach ( $data as $_tax ) {
$tax_id = 0;
// Try to get the tax rate ID
if ( isset( $_tax['id'] ) ) {
$tax_id = intval( $_tax['id'] );
}
// Tax rate exists / edit tax rate
if ( $tax_id ) {
$edit = $this->edit_tax( $tax_id, array( 'tax' => $_tax ) );
if ( is_wp_error( $edit ) ) {
$taxes[] = array(
'id' => $tax_id,
'error' => array( 'code' => $edit->get_error_code(), 'message' => $edit->get_error_message() )
);
} else {
$taxes[] = $edit['tax'];
}
}
// Tax rate don't exists / create tax rate
else {
$new = $this->create_tax( array( 'tax' => $_tax ) );
if ( is_wp_error( $new ) ) {
$taxes[] = array(
'id' => $tax_id,
'error' => array( 'code' => $new->get_error_code(), 'message' => $new->get_error_message() )
);
} else {
$taxes[] = $new['tax'];
}
}
}
return array( 'taxes' => apply_filters( 'woocommerce_api_taxes_bulk_response', $taxes, $this ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Get all tax classes
*
* @since 2.5.0
*
* @param string $fields
*
* @return array
*/
public function get_tax_classes( $fields = null ) {
try {
// Permissions check
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_tax_classes', __( 'You do not have permission to read tax classes', 'woocommerce' ), 401 );
}
$tax_classes = array();
// Add standard class
$tax_classes[] = array(
'slug' => 'standard',
'name' => __( 'Standard Rate', 'woocommerce' )
);
$classes = WC_Tax::get_tax_classes();
foreach ( $classes as $class ) {
$tax_classes[] = apply_filters( 'woocommerce_api_tax_class_response', array(
'slug' => sanitize_title( $class ),
'name' => $class
), $class, $fields, $this );
}
return array( 'tax_classes' => apply_filters( 'woocommerce_api_tax_classes_response', $tax_classes, $classes, $fields, $this ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Create a tax class.
*
* @since 2.5.0
*
* @param array $data
*
* @return array
*/
public function create_tax_class( $data ) {
try {
if ( ! isset( $data['tax_class'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_tax_class_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'tax_class' ), 400 );
}
// Check permissions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_tax_class', __( 'You do not have permission to create tax classes', 'woocommerce' ), 401 );
}
$data = $data['tax_class'];
if ( empty( $data['name'] ) ) {
throw new WC_API_Exception( 'woocommerce_api_missing_tax_class_name', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'name' ), 400 );
}
$name = sanitize_text_field( $data['name'] );
$slug = sanitize_title( $name );
$classes = WC_Tax::get_tax_classes();
$exists = false;
// Check if class exists.
foreach ( $classes as $key => $class ) {
if ( sanitize_title( $class ) === $slug ) {
$exists = true;
break;
}
}
// Return error if tax class already exists.
if ( $exists ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_create_tax_class', __( 'Tax class already exists', 'woocommerce' ), 401 );
}
// Add the new class.
$classes[] = $name;
update_option( 'woocommerce_tax_classes', implode( "\n", $classes ) );
do_action( 'woocommerce_api_create_tax_class', $slug, $data );
$this->server->send_status( 201 );
return array(
'tax_class' => array(
'slug' => $slug,
'name' => $name
)
);
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Delete a tax class
*
* @since 2.5.0
*
* @param int $slug The tax class slug
*
* @return array
*/
public function delete_tax_class( $slug ) {
global $wpdb;
try {
// Check permissions
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_delete_tax_class', __( 'You do not have permission to delete tax classes', 'woocommerce' ), 401 );
}
$slug = sanitize_title( $slug );
$classes = WC_Tax::get_tax_classes();
$deleted = false;
foreach ( $classes as $key => $class ) {
if ( sanitize_title( $class ) === $slug ) {
unset( $classes[ $key ] );
$deleted = true;
break;
}
}
if ( ! $deleted ) {
throw new WC_API_Exception( 'woocommerce_api_cannot_delete_tax_class', __( 'Could not delete the tax class', 'woocommerce' ), 401 );
}
update_option( 'woocommerce_tax_classes', implode( "\n", $classes ) );
// Delete tax rate locations locations from the selected class.
$wpdb->query( $wpdb->prepare( "
DELETE locations.*
FROM {$wpdb->prefix}woocommerce_tax_rate_locations AS locations
INNER JOIN
{$wpdb->prefix}woocommerce_tax_rates AS rates
ON rates.tax_rate_id = locations.tax_rate_id
WHERE rates.tax_rate_class = '%s'
", $slug ) );
// Delete tax rates in the selected class.
$wpdb->delete( $wpdb->prefix . 'woocommerce_tax_rates', array( 'tax_rate_class' => $slug ), array( '%s' ) );
return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), 'tax_class' ) );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Get the total number of tax classes
*
* @since 2.5.0
*
* @return array
*/
public function get_tax_classes_count() {
try {
if ( ! current_user_can( 'manage_woocommerce' ) ) {
throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_tax_classes_count', __( 'You do not have permission to read the tax classes count', 'woocommerce' ), 401 );
}
$total = count( WC_Tax::get_tax_classes() ) + 1; // +1 for Standard Rate
return array( 'count' => $total );
} catch ( WC_API_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
}