-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathclass-wc-connect-taxjar-integration.php
More file actions
2769 lines (2402 loc) · 107 KB
/
Copy pathclass-wc-connect-taxjar-integration.php
File metadata and controls
2769 lines (2402 loc) · 107 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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use Automattic\WCServices\StoreNotices\StoreNoticesNotifier;
use Automattic\WCServices\Tax\Address;
class WC_Connect_TaxJar_Integration {
/**
* @var WC_Connect_API_Client
*/
public $api_client;
/**
* @var WC_Connect_Logger
*/
public $logger;
/**
* @var StoreNoticesNotifier
*/
private $notifier;
public $wc_connect_base_url;
private $expected_options = array(
// Users can set either billing or shipping address for tax rates but not shop
'woocommerce_tax_based_on' => 'shipping',
// Rate calculations assume tax not included
'woocommerce_prices_include_tax' => 'no',
// Use no special handling on shipping taxes, our API handles that
'woocommerce_shipping_tax_class' => '',
// Rates are calculated in the cart assuming tax not included
'woocommerce_tax_display_shop' => 'excl',
// TaxJar returns one total amount, not line item amounts
'woocommerce_tax_display_cart' => 'excl',
);
/**
* Cache time.
*
* @var int
*/
private $cache_time;
/**
* Address Validation Cache time.
*
* @var int
*/
private $address_cache_time;
/**
* Error cache time.
*
* @var int
*/
private $error_cache_time;
/**
* @var array
*/
private $response_rate_ids;
/**
* @var array
*/
private $response_line_items;
/**
* Tax snapshots captured before an out-of-cart recalculation, keyed by order id,
* so they can be restored after WC recalculates the order totals.
*
* @var array
*/
private $pre_recalculation_tax_snapshots = array();
/**
* @var bool
*/
private $is_itemized_tax_display;
/**
* Backend tax classes.
*
* @var array
*/
private $backend_tax_classes;
/**
* Line items WooCommerce will not apply item tax to.
*
* Recorded while the TaxJar request is built and read back when the response is
* turned into tax rate rows, so both halves share a single taxability decision
* instead of each re-deriving one. Keyed by TaxJar line item id, values unused.
*
* @var array<string, bool>
*/
private $non_taxable_line_items = array();
/**
* Tracks instance.
*
* @var WC_Connect_Tracks
*/
protected $tracks;
const PROXY_PATH = 'taxjar/v2';
const OPTION_NAME = 'wc_connect_taxes_enabled';
const SETUP_WIZARD_OPTION_NAME = 'woocommerce_setup_automated_taxes';
/**
* WCS TaxJar integration constructor.
*
* @param WC_Connect_API_Client $api_client TaxJar API client.
* @param WC_Connect_Logger $logger Logger.
* @param string $wc_connect_base_url WC Connect base URL.
* @param WC_Connect_Tracks $tracks Tracks.
* @param StoreNoticesNotifier|null $notifier Notifier.
*/
public function __construct(
WC_Connect_API_Client $api_client,
WC_Connect_Logger $logger,
$wc_connect_base_url,
WC_Connect_Tracks $tracks,
?StoreNoticesNotifier $notifier = null
) {
$this->api_client = $api_client;
$this->logger = $logger;
$this->wc_connect_base_url = $wc_connect_base_url;
$this->notifier = $notifier;
$this->tracks = $tracks;
// Cache rates for 1 hour.
$this->cache_time = HOUR_IN_SECONDS;
// Cache address validation errors for 1 year.
$this->address_cache_time = YEAR_IN_SECONDS;
// Cache error response for 5 minutes.
$this->error_cache_time = MINUTE_IN_SECONDS * 5;
$this->is_itemized_tax_display = ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) );
}
/**
* Generates an itemized tax rate name based on the provided tax rate and country.
*
* @param string $taxjar_rate_name The tax rate name from TaxJar, typically including '_tax_rate'.
* @param string $to_country The destination country for the tax calculation.
* @param array $jurisdictions Tax jurisdictions.
*
* @return string The formatted and localized tax rate name.
*/
private static function generate_itemized_tax_rate_name( string $taxjar_rate_name, string $to_country, array $jurisdictions ) {
// Normalize the base key by stripping the trailing "_tax_rate" and converting underscores to spaces.
$base_key = str_replace( '_tax_rate', '', $taxjar_rate_name );
$label_core = ucwords( str_replace( '_', ' ', $base_key ) );
$rate_name = $label_core . ' ' . __( 'Tax', 'woocommerce-services' );
// Handle VAT countries where country-level tax should be labeled as VAT.
$is_vat_country = false;
if ( function_exists( 'WC' ) && WC() && isset( WC()->countries ) && method_exists( WC()->countries, 'get_vat_countries' ) ) {
$is_vat_country = in_array( $to_country, WC()->countries->get_vat_countries(), true );
}
if ( 'country' === $base_key && $is_vat_country ) {
return 'VAT';
}
// Default, country-agnostic formatting for non‑US destinations.
if ( 'US' !== $to_country ) {
// Preserve previous behavior of uppercasing for non‑US.
return strtoupper( $rate_name );
}
// United States specific naming enhancements.
$county = isset( $jurisdictions['county'] ) ? trim( (string) $jurisdictions['county'] ) : '';
$city = isset( $jurisdictions['city'] ) ? trim( (string) $jurisdictions['city'] ) : '';
$jurisdiction = trim( $county . ' ' . $city );
return ( '' !== $jurisdiction ? $jurisdiction . ' : ' : '' ) . $rate_name;
}
public function init() {
// Only enable WCS TaxJar integration if the official TaxJar plugin isn't active.
if ( class_exists( 'WC_Taxjar' ) ) {
return;
}
$store_settings = $this->get_store_settings();
$store_country = $store_settings['country'];
// TaxJar supports USA, Canada, Australia, and the European Union
if ( ! $this->is_supported_country( $store_country ) ) {
return;
}
// Add toggle for automated taxes to the core settings page
add_filter( 'woocommerce_tax_settings', array( $this, 'add_tax_settings' ) );
// Fix tooltip with link on older WC.
if ( version_compare( WOOCOMMERCE_VERSION, '4.4.0', '<' ) ) {
add_action( 'admin_enqueue_scripts', array( $this, 'fix_tooltip_keepalive' ), 11 );
}
// Settings values filter to handle the hardcoded settings
add_filter( 'woocommerce_admin_settings_sanitize_option', array( $this, 'sanitize_tax_option' ), 10, 2 );
// Bow out if we're not wanted
if ( ! $this->is_enabled() ) {
return;
}
// Notify developers still using the removed filter.
if ( has_filter( 'woocommerce_apply_taxjar_nexus_addresses_workaround' ) ) {
_doing_it_wrong(
'woocommerce_apply_taxjar_nexus_addresses_workaround',
esc_html__( 'The woocommerce_apply_taxjar_nexus_addresses_workaround filter has been removed. Use the woocommerce_taxjar_nexus_address filter instead.', 'woocommerce-services' ),
'3.5.2'
);
}
// Scripts / Stylesheets
add_action( 'admin_enqueue_scripts', array( $this, 'load_taxjar_admin_new_order_assets' ) );
$this->configure_tax_settings();
// Calculate Taxes at Cart / Checkout
if ( class_exists( 'WC_Cart_Totals' ) ) { // Woo 3.2+
add_action( 'woocommerce_after_calculate_totals', array( $this, 'maybe_calculate_totals' ), 20 );
} else {
add_action( 'woocommerce_calculate_totals', array( $this, 'maybe_calculate_totals' ), 20 );
}
// Calculate Taxes for Backend Orders (Woo 2.6+)
add_action( 'woocommerce_before_save_order_items', array( $this, 'calculate_backend_totals' ), 20 );
// Preserve recorded taxes when an existing order is recalculated outside the
// cart/checkout and admin flows (e.g. a REST API or programmatic order update),
// so a changed address does not wipe the stored tax lines to zero.
add_action( 'woocommerce_order_before_calculate_taxes', array( $this, 'preserve_order_taxes_on_recalculation' ), 10, 2 );
// Set customer taxable location for local pickup
add_filter( 'woocommerce_customer_taxable_address', array( $this, 'append_base_address_to_customer_taxable_address' ), 10, 1 );
add_filter( 'woocommerce_calc_tax', array( $this, 'override_woocommerce_tax_rates' ), 10, 3 );
add_filter( 'woocommerce_matched_rates', array( $this, 'allow_street_address_for_matched_rates' ), 10, 2 );
add_filter( 'woocommerce_cart_totals_get_item_tax_rates', array( $this, 'override_cart_item_tax_rates' ), 10, 3 );
add_action( 'woocommerce_order_item_after_calculate_taxes', array( $this, 'override_order_item_taxes' ), 10, 2 );
add_filter( 'woocommerce_rate_label', array( $this, 'cleanup_tax_label' ) );
add_filter( 'woocommerce_cart_tax_totals', array( $this, 'aggregate_tax_totals' ), 10, 2 );
add_filter( 'woocommerce_order_get_tax_totals', array( $this, 'aggregate_tax_totals' ), 10, 2 );
WC_Connect_Custom_Surcharge::init();
}
/**
* Are automated taxes enabled?
*
* @return bool
*/
public function is_enabled() {
// Migrate automated taxes selection from the setup wizard
if ( get_option( self::SETUP_WIZARD_OPTION_NAME ) ) {
update_option( self::OPTION_NAME, 'yes' );
delete_option( self::SETUP_WIZARD_OPTION_NAME );
return true;
}
return ( wc_tax_enabled() && 'yes' === get_option( self::OPTION_NAME ) );
}
/**
* Add our "automated taxes" setting to the core group.
*
* @param array $tax_settings WooCommerce Tax Settings
*
* @return array
*/
public function add_tax_settings( $tax_settings ) {
$enabled = $this->is_enabled();
$backedup_tax_rates_url = admin_url( '/admin.php?page=wc-status&tab=connect#tax-rate-backups' );
$powered_by_wct_notice = '<p>' . sprintf( __( 'Automated taxes take over from the WooCommerce core tax settings. This means that "Display prices" will be set to Excluding tax and tax will be Calculated using Customer shipping address. %1$sLearn more about Automated taxes here.%2$s', 'woocommerce-services' ), '<a href="https://woocommerce.com/document/woocommerce-shipping-and-tax/woocommerce-tax/#setup-and-configuration">', '</a>' ) . '</p>';
$backup_notice = ( ! empty( WC_Connect_Functions::get_backed_up_tax_rate_files() ) ) ? '<p>' . sprintf( __( 'Your previous tax rates were backed up and can be downloaded %1$shere%2$s.', 'woocommerce-services' ), '<a href="' . esc_url( $backedup_tax_rates_url ) . '">', '</a>' ) . '</p>' : '';
$desctructive_action_notice = '<p>' . __( 'Enabling this option overrides any tax rates you have manually added.', 'woocommerce-services' ) . '</p>';
$desctructive_backup_notice = '<p>' . sprintf( __( 'Your existing tax rates will be backed-up to a CSV that you can download %1$shere%2$s.', 'woocommerce-services' ), '<a href="' . esc_url( $backedup_tax_rates_url ) . '">', '</a>' ) . '</p>';
$tax_nexus_notice = '<p>' . $this->get_tax_tooltip() . '</p>';
$automated_taxes_description = join(
'',
$enabled ? array(
$powered_by_wct_notice,
$backup_notice,
$tax_nexus_notice,
) : array( $desctructive_action_notice, $desctructive_backup_notice, $tax_nexus_notice )
);
$automated_taxes = array(
'title' => __( 'Automated taxes', 'woocommerce-services' ),
'id' => self::OPTION_NAME, // TODO: save in `wc_connect_options`?
'desc_tip' => $this->get_tax_tooltip(),
'desc' => $automated_taxes_description,
'default' => 'no',
'type' => 'select',
'class' => 'wc-enhanced-select',
'options' => array(
'no' => __( 'Disable automated taxes', 'woocommerce-services' ),
'yes' => __( 'Enable automated taxes', 'woocommerce-services' ),
),
);
// Insert the "automated taxes" setting at the top (under the section title)
array_splice( $tax_settings, 1, 0, array( $automated_taxes ) );
if ( $enabled ) {
// If the automated taxes are enabled, disable the settings that would be reverted in the original plugin
foreach ( $tax_settings as $index => $tax_setting ) {
if ( empty( $tax_setting['id'] ) || ! array_key_exists( $tax_setting['id'], $this->expected_options ) ) {
continue;
}
$tax_settings[ $index ]['custom_attributes'] = array( 'disabled' => true );
}
}
return $tax_settings;
}
/**
* Get the text to show in the tooltip next to automated tax settings.
*/
private function get_tax_tooltip() {
$store_settings = $this->get_store_settings();
$all_states = WC()->countries->get_states( $store_settings['country'] );
$all_countries = WC()->countries->get_countries();
$full_country = $all_countries[ $store_settings['country'] ];
$full_state = isset( $all_states[ $store_settings['state'] ] ) ? $all_states[ $store_settings['state'] ] : '';
$country_state = ( $full_state ) ? $full_state . ', ' . $full_country : $full_country;
if ( ! $this->is_enabled() ) {
/* translators: 1: full state and country name, 2: anchor opening with tax rate link, 3: anchor closer, 4: anchor opening with tax nexus link, 5: anchor closer */
return sprintf( __( 'Your tax rates and settings will be automatically configured for %1$s. Automated taxes uses your store address as your "tax nexus". If you want to charge tax for any other state, you can add a %2$stax rate%3$s for that state in addition to using automated taxes. %4$sLearn more about Tax Nexus here%5$s.', 'woocommerce-services' ), $country_state, '<a href="https://woocommerce.com/document/setting-up-taxes-in-woocommerce/#setting-up-tax-rates">', '</a>', '<a href="https://woocommerce.com/document/woocommerce-shipping-and-tax/woocommerce-tax/#section-14">', '</a>' );
}
/* translators: 1: full state and country name, 2: anchor opening with tax rate link, 3: anchor closer, 4: anchor opening with tax nexus link, 5: anchor closer */
return sprintf( __( 'Your tax rates are now automatically calculated for %1$s. Automated taxes uses your store address as your "tax nexus". If you want to charge tax for any other state, you can add a %2$stax rate%3$s for that state in addition to using automated taxes. %4$sLearn more about Tax Nexus here%5$s.', 'woocommerce-services' ), $country_state, '<a href="https://woocommerce.com/document/setting-up-taxes-in-woocommerce/#setting-up-tax-rates">', '</a>', '<a href="https://woocommerce.com/document/woocommerce-shipping-and-tax/woocommerce-tax/#section-14">', '</a>' );
}
/**
* Hack to force keepAlive: true on tax setting tooltip.
*/
public function fix_tooltip_keepalive() {
global $pagenow;
if ( 'admin.php' !== $pagenow || ! isset( $_GET['page'] ) || 'wc-settings' !== $_GET['page'] || ! isset( $_GET['tab'] ) || 'tax' !== $_GET['tab'] || ! empty( $_GET['section'] ) ) {
return;
}
$tooltip = $this->get_tax_tooltip();
// Links in tooltips will not work unless keepAlive is true.
wp_add_inline_script(
'woocommerce_admin',
"jQuery( function () {
jQuery( 'label[for=wc_connect_taxes_enabled] .woocommerce-help-tip')
.off( 'mouseenter mouseleave' )
.tipTip( {
'fadeIn': 50,
'fadeOut': 50,
'delay': 200,
keepAlive: true,
content: '" . $tooltip . "'
} );
} );"
);
}
/**
* When automated taxes are enabled, overwrite core tax settings that might break the API integration
* This is similar to the original plugin functionality where these options were reverted on page load
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/82bf7c58/includes/class-wc-taxjar-integration.php#L66-L91
*
* @param mixed $value - option value
* @param array $option - option metadata
* @return string new option value, based on the automated taxes state or $value
*/
public function sanitize_tax_option( $value, $option ) {
// phpcs:disable WordPress.Security.NonceVerification.Missing --- Security is taken care of by WooCommerce
if (
// skip unrecognized option format
! is_array( $option )
// skip if unexpected option format
|| ! isset( $option['id'] )
// skip if not enabled or not being enabled in the current request
|| ! $this->is_enabled() && ( ! isset( $_POST[ self::OPTION_NAME ] ) || 'yes' != $_POST[ self::OPTION_NAME ] ) ) {
return $value;
}
// the option is currently being enabled - backup the rates and flush the rates table
if ( ! $this->is_enabled() && self::OPTION_NAME === $option['id'] && 'yes' === $value ) {
$this->backup_existing_tax_rates();
return $value;
}
// skip if unexpected option
if ( ! array_key_exists( $option['id'], $this->expected_options ) ) {
return $value;
}
// phpcs:enable WordPress.Security.NonceVerification.Missing
return $this->expected_options[ $option['id'] ];
}
/**
* Overwrite WooCommerce core tax settings if they are different than expected
*
* Ported from TaxJar's plugin and modified to support $this->expected_options
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/82bf7c58/includes/class-wc-taxjar-integration.php#L66-L91
*/
public function configure_tax_settings() {
foreach ( $this->expected_options as $option => $value ) {
// first check the option value - with default memory caching this should help to avoid unnecessary DB operations
if ( get_option( $option ) !== $value ) {
update_option( $option, $value );
}
}
}
/**
* TaxJar supports USA, Canada, Australia, and the European Union + Great Britain
* See: https://developers.taxjar.com/api/reference/#countries
*
* @return array Countries supported by TaxJar.
*/
public function get_supported_countries() {
// Hard code list instead of using `WC()->countries->get_european_union_countries()` just in case anyone else decides to leave the EU.
return array( 'US', 'CA', 'AU', 'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HU', 'HR', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK' );
}
/**
* Check if a given country is supported by TaxJar.
*
* @param string $country Two character country code.
*
* @return bool Whether or not the country is supported by TaxJar.
*/
public function is_supported_country( $country ) {
return in_array( $country, $this->get_supported_countries() );
}
/**
* Gets the store's location settings.
*
* Modified version of TaxJar's plugin.
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/4b481f5/includes/class-wc-taxjar-integration.php#L910
*
* The `taxjar_store_settings` return value is guaranteed to be an array carrying
* all five address keys, matching this method's documented contract. The filter is
* public and unguarded, so a callback returning null / false / a string would
* otherwise flow into callers that index it — and, since the address value object
* declares `array $settings`, into an uncaught TypeError on every cart and checkout
* render that resolves a base address. A non-array return is treated as "no
* opinion" and the unfiltered settings are used; keys missing from an array return
* are backfilled from the unfiltered settings, so callers can keep indexing the
* result directly.
*
* @return array
*/
public function get_store_settings() {
$store_settings = array(
'street' => WC()->countries->get_base_address(),
'city' => WC()->countries->get_base_city(),
'state' => WC()->countries->get_base_state(),
'country' => WC()->countries->get_base_country(),
'postcode' => WC()->countries->get_base_postcode(),
);
$filtered = apply_filters( 'taxjar_store_settings', $store_settings, array() );
if ( ! is_array( $filtered ) ) {
$this->_log( 'Warning: the taxjar_store_settings filter returned a non-array value; ignoring it and using the store address.' );
return $store_settings;
}
return array_merge( $store_settings, $filtered );
}
/**
* @param $message
*/
public function _log( $message ) {
if ( ! $this->logger->is_logging_enabled() ) {
return;
}
$formatted_message = is_scalar( $message ) ? $message : json_encode( $message );
$this->logger->log( $formatted_message, 'WCS Tax' );
}
/**
* @param $message
*/
public function _error( $message ) {
$formatted_message = is_scalar( $message ) ? $message : json_encode( $message );
// ignore error messages caused by customer input
$state_zip_mismatch = false !== strpos( $formatted_message, 'to_zip' ) && false !== strpos( $formatted_message, 'is not used within to_state' );
$invalid_postcode = false !== strpos( $formatted_message, 'isn\'t a valid postal code for' );
$malformed_postcode = false !== strpos( $formatted_message, 'zip code has incorrect format' );
if ( ! is_admin() && ( $state_zip_mismatch || $invalid_postcode || $malformed_postcode ) ) {
$fields = WC()->countries->get_address_fields();
$postcode_field_name = __( 'ZIP/Postal code', 'woocommerce-services' );
if ( isset( $fields['billing_postcode'] ) && isset( $fields['billing_postcode']['label'] ) ) {
$postcode_field_name = $fields['billing_postcode']['label'];
}
if ( $state_zip_mismatch ) {
$message = sprintf( _x( '%s does not match the selected state.', '%s - ZIP/Postal code checkout field label', 'woocommerce-services' ), $postcode_field_name );
} elseif ( $malformed_postcode ) {
$message = sprintf( _x( '%s is not formatted correctly.', '%s - ZIP/Postal code checkout field label', 'woocommerce-services' ), $postcode_field_name );
} else {
$message = sprintf( _x( 'Invalid %s entered.', '%s - ZIP/Postal code checkout field label', 'woocommerce-services' ), $postcode_field_name );
}
$this->notifier->error( $message, array(), 'taxjar' );
return;
}
$this->logger->error( $formatted_message, 'WCS Tax' );
}
/**
* Wrapper to avoid calling calculate_totals() for admin carts.
*
* @param $wc_cart_object
*/
public function maybe_calculate_totals( $wc_cart_object ) {
if ( ! WC_Connect_Functions::should_send_cart_api_request() ) {
return;
}
$this->calculate_totals( $wc_cart_object );
}
/**
* Calculate tax / totals using TaxJar at checkout
*
* Unchanged from the TaxJar plugin.
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/4b481f5/includes/class-wc-taxjar-integration.php#L471
*
* @param WC_Cart $wc_cart_object
* @return void
*/
public function calculate_totals( $wc_cart_object ) {
/*
* Don't calculate if we are outside cart and checkout page, or pages with WooCommerce Cart and Checkout blocks.
* Don't calculate if we are inside mini-cart.
* If this is an API call don't calculate unless this is store/cart request.
*/
if (
! WC_Connect_Functions::has_cart_or_checkout_block() &&
! WC_Connect_Functions::is_store_api_call() &&
(
( ! is_cart() && ! is_checkout() ) ||
( is_cart() && is_ajax() )
)
) {
return;
}
$cart_taxes = array();
$cart_tax_total = 0;
/**
* WC Coupon object.
*
* @var WC_Coupon $coupon
*/
foreach ( $wc_cart_object->coupons as $coupon ) {
if ( method_exists( $coupon, 'get_limit_usage_to_x_items' ) ) { // Woo 3.0+.
$limit_usage_qty = $coupon->get_limit_usage_to_x_items();
if ( $limit_usage_qty ) {
$coupon->set_limit_usage_to_x_items( $limit_usage_qty );
}
}
}
$line_items = $this->get_line_items( $wc_cart_object );
$shipping_amount = method_exists( $wc_cart_object, 'get_shipping_total' )
? $wc_cart_object->get_shipping_total()
: WC()->shipping->shipping_total;
// Group items by tax location and calculate taxes.
$items_by_location = $this->group_items_by_location( $line_items, $this->is_local_pickup() );
$taxes = $this->calculate_taxes_by_location( $items_by_location, $shipping_amount );
// Return if taxes could not be calculated.
if ( false === $taxes ) {
return;
}
$this->response_rate_ids = $taxes['rate_ids'];
$this->response_line_items = $taxes['line_items'];
if ( isset( $this->response_line_items ) ) {
foreach ( $this->response_line_items as $response_line_item_key => $response_line_item ) {
$line_item = $this->get_line_item( $response_line_item_key, $line_items );
if ( isset( $line_item ) ) {
$this->response_line_items[ $response_line_item_key ]->line_total = ( $line_item['unit_price'] * $line_item['quantity'] ) - $line_item['discount'];
}
}
}
foreach ( $wc_cart_object->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// get_line_items() keys by cart item key and stores the canonical TaxJar ID
// under 'id'; the response is keyed by that canonical ID.
$line_item_key = $line_items[ $cart_item_key ]['id'] ?? null;
if ( null !== $line_item_key && isset( $taxes['line_items'][ $line_item_key ] ) && ! $taxes['line_items'][ $line_item_key ]->combined_tax_rate ) {
if ( method_exists( $product, 'set_tax_status' ) ) {
$product->set_tax_status( 'none' ); // Woo 3.0+
} else {
$product->tax_status = 'none'; // Woo 2.6
}
}
}
// Recalculate shipping package rates
foreach ( $wc_cart_object->get_shipping_packages() as $package_key => $package ) {
WC()->session->set( 'shipping_for_package_' . $package_key, null );
}
if ( class_exists( 'WC_Cart_Totals' ) ) { // Woo 3.2+
do_action( 'woocommerce_cart_reset', $wc_cart_object, false );
do_action( 'woocommerce_before_calculate_totals', $wc_cart_object );
new WC_Cart_Totals( $wc_cart_object );
remove_action( 'woocommerce_after_calculate_totals', array( $this, 'maybe_calculate_totals' ), 20 );
do_action( 'woocommerce_after_calculate_totals', $wc_cart_object );
add_action( 'woocommerce_after_calculate_totals', array( $this, 'maybe_calculate_totals' ), 20 );
} else {
remove_action( 'woocommerce_calculate_totals', array( $this, 'maybe_calculate_totals' ), 20 );
$wc_cart_object->calculate_totals();
add_action( 'woocommerce_calculate_totals', array( $this, 'maybe_calculate_totals' ), 20 );
}
}
/**
* Calculate tax / totals using TaxJar for backend orders
*
* Unchanged from the TaxJar plugin.
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/96b5d57/includes/class-wc-taxjar-integration.php#L557
*
* @return void
*/
public function calculate_backend_totals( $order_id ) {
$order = wc_get_order( $order_id );
$address = $this->get_backend_address();
$line_items = $this->get_backend_line_items( $order );
if ( method_exists( $order, 'get_shipping_total' ) ) {
$shipping = $order->get_shipping_total(); // Woo 3.0+
} else {
$shipping = $order->get_total_shipping(); // Woo 2.6
}
$taxes = $this->calculate_tax(
array(
'to_country' => $address['to_country'],
'to_state' => $address['to_state'],
'to_zip' => $address['to_zip'],
'to_city' => $address['to_city'],
'to_street' => $address['to_street'],
'shipping_amount' => $shipping,
'line_items' => $line_items,
)
);
if ( class_exists( 'WC_Order_Item_Tax' ) ) { // Add tax rates manually for Woo 3.0+
/**
* @var WC_Order_Item_Product $item Product Order Item.
*/
foreach ( $order->get_items() as $item_key => $item ) {
// get_backend_line_items() keys by order item ID and stores the canonical
// TaxJar ID under 'id'; the response is keyed by that canonical ID.
$line_item_key = $line_items[ $item_key ]['id'] ?? null;
if ( null !== $line_item_key && isset( $taxes['rate_ids'][ $line_item_key ] ) ) {
$rate_id = $taxes['rate_ids'][ $line_item_key ];
$item_tax = new WC_Order_Item_Tax();
$item_tax->set_rate( $rate_id );
$item_tax->set_order_id( $order_id );
$item_tax->save();
}
}
} elseif ( class_exists( 'WC_AJAX' ) ) { // Recalculate tax for Woo 2.6 to apply new tax rates
remove_action( 'woocommerce_before_save_order_items', array( $this, 'calculate_backend_totals' ), 20 );
if ( check_ajax_referer( 'calc-totals', 'security', false ) ) {
WC_AJAX::calc_line_taxes();
}
add_action( 'woocommerce_before_save_order_items', array( $this, 'calculate_backend_totals' ), 20 );
}
}
/**
* Get formatted address for tax calculation.
*
* Empty fields come back as `false` rather than `''`. That is the historic shape of
* this array and `Address::to_legacy_options()` is the single place the choice is
* made, so `get_backend_address()` cannot drift away from it.
*
* @param string|null $location_type Location type: 'base', 'shipping', or 'billing'.
* If null, uses default behavior from get_taxable_address().
* @return array Address array with to_country, to_state, etc.
*/
protected function get_address( $location_type = null ) {
$taxable_address = $this->get_taxable_address( $location_type );
$taxable_address = is_array( $taxable_address ) ? $taxable_address : array();
return Address::from_taxable_tuple( $taxable_address )->to_legacy_options();
}
/**
* Allow street address to be passed when finding rates
*
* Despite the name, no street ever reaches `WC_Tax::find_rates()` — it takes no
* street argument, and the value this method used to unpack from the tuple was
* never read. What the callback actually does is accept a location of *four or
* more* elements where `WC_Tax::get_rates_from_location()` accepts exactly four,
* so it supplies the rates core skips when this plugin's five-element taxable
* address is in play. It is public and hooked on `woocommerce_matched_rates`,
* which core fires from the price-display, shipping-tax and coupon paths.
*
* The lookup arguments now come from the same value object `create_or_update_tax_rate()`
* writes with. Before, this method normalised the city but not the state, so it
* could not see rows that method had just written: the rate rows existed and
* these paths returned nothing for them.
*
* @param array $matched_tax_rates Rates core matched; replaced wholesale.
* @param string $tax_class Tax class slug.
* @return array
*/
public function allow_street_address_for_matched_rates( $matched_tax_rates, $tax_class = '' ) {
$tax_class = sanitize_title( $tax_class );
$location = WC_Tax::get_tax_location( $tax_class );
if ( ! is_array( $location ) || count( $location ) < 4 ) {
return array();
}
return WC_Tax::find_rates( Address::from_taxable_tuple( $location )->to_find_rates_args( $tax_class ) );
}
public function cleanup_tax_label( $rate_name ) {
if ( ! $this->is_itemized_tax_display ) {
return $rate_name;
}
$label_parts = explode( ' : ', $rate_name );
$clean_label = ! empty( $label_parts[1] ) ? $label_parts[1] : $label_parts[0];
return $clean_label;
}
/**
* Aggregate tax totals by label.
*
* When items are taxed at different locations (e.g., services at store address,
* products at customer address), this combines taxes with the same label into
* a single line for cleaner display.
*
* Example: Two "County Tax" entries ($0.25 + $0.12) become one "County Tax" ($0.37).
*
* @param array $tax_totals Array of tax total objects from WooCommerce.
* @param WC_Cart $cart The cart object.
* @return array Aggregated tax totals.
*/
public function aggregate_tax_totals( $tax_totals, $cart ) {
if ( ! is_array( $tax_totals ) || count( $tax_totals ) <= 1 ) {
return $tax_totals;
}
$aggregated = array();
foreach ( $tax_totals as $code => $tax ) {
$label = $tax->label;
if ( isset( $aggregated[ $label ] ) ) {
// Add to existing entry with same label.
$aggregated[ $label ]->amount += $tax->amount;
$aggregated[ $label ]->formatted_amount = wc_price( $aggregated[ $label ]->amount );
} else {
// First entry for this label - clone to avoid modifying original.
$aggregated[ $label ] = clone $tax;
}
}
return $aggregated;
}
/**
* Check if local pickup shipping method is selected.
*
* @return bool
*/
protected function is_local_pickup() {
if ( ! apply_filters( 'woocommerce_apply_base_tax_for_local_pickup', true ) ) {
return false;
}
$local_pickup_methods = apply_filters(
'woocommerce_local_pickup_methods',
array( 'legacy_local_pickup', 'local_pickup' )
);
if ( function_exists( 'wc_get_chosen_shipping_method_ids' ) ) {
return count( array_intersect( wc_get_chosen_shipping_method_ids(), $local_pickup_methods ) ) > 0;
}
return count(
array_intersect(
WC()->session->get( 'chosen_shipping_methods', array() ),
$local_pickup_methods
)
) > 0;
}
/**
* Group line items by their tax location.
*
* @param array $line_items Line items with 'tax_location' key.
* @param bool $is_local_pickup If true, all items grouped under 'base'.
* @return array Items grouped by location type.
*/
protected function group_items_by_location( $line_items, $is_local_pickup = false ) {
$groups = array();
$default_location = get_option( 'woocommerce_tax_based_on', 'shipping' );
foreach ( $line_items as $item ) {
$location = $is_local_pickup ? 'base' : ( $item['tax_location'] ?? $default_location );
$groups[ $location ][] = $item;
}
return $groups;
}
/**
* Calculate taxes for items grouped by location.
*
* @param array $items_by_location Items grouped by location type.
* @param float $shipping_amount Shipping amount.
* @return array|false Merged taxes or false if any calculation fails.
*/
protected function calculate_taxes_by_location( $items_by_location, $shipping_amount ) {
$merged_taxes = array(
'rate_ids' => array(),
'line_items' => array(),
);
foreach ( $items_by_location as $location_type => $items ) {
$address = $this->get_address( $location_type );
// Shipping only applies to 'shipping' location group.
// Note: Service fees could be added to 'base' group here in the future.
$group_shipping = ( 'shipping' === $location_type ) ? $shipping_amount : 0;
$taxes = $this->calculate_tax(
array(
'to_country' => $address['to_country'],
'to_state' => $address['to_state'],
'to_zip' => $address['to_zip'],
'to_city' => $address['to_city'],
'to_street' => $address['to_street'],
'shipping_amount' => $group_shipping,
'line_items' => $items,
)
);
// If any group fails, fail entire calculation.
if ( false === $taxes ) {
return false;
}
// Using += (array union) is safe here because keys are line item IDs (e.g. "42-abc123")
// and each item exists in exactly one location group, so keys can't collide across groups.
// array_merge() would be incorrect as it re-indexes numeric keys.
$merged_taxes['rate_ids'] += $taxes['rate_ids'];
$merged_taxes['line_items'] += $taxes['line_items'];
}
// If no group produced any taxes (e.g. all groups were cross-state), return false
// to preserve backward compatibility with callers that check for false.
if ( empty( $merged_taxes['rate_ids'] ) && empty( $merged_taxes['line_items'] ) ) {
return false;
}
$this->_log( $merged_taxes );
return $merged_taxes;
}
/**
* Get taxable address.
*
* The address is built through {@see Address}, so country/state casing, the
* comma-list postcode split and the city semicolon rules are applied once here
* rather than re-derived by each consumer. The return value stays WooCommerce's
* positional 5-tuple — `Address` is internal and never crosses the filter.
*
* @param string|null $location_type Location type: 'base', 'shipping', or 'billing'.
* If null, uses woocommerce_tax_based_on option with
* local pickup override. Null is kept for backward
* compatibility - internal code always passes explicit type.
* @return array
*/
public function get_taxable_address( $location_type = null ) {
if ( null === $location_type ) {
// Backward compatibility: external plugins may call without parameter.
// Internal code always passes explicit location type.
$tax_based_on = get_option( 'woocommerce_tax_based_on' );
if ( $this->is_local_pickup() ) {
$tax_based_on = 'base';
}
} else {
$tax_based_on = $location_type;
}
if ( 'base' === $tax_based_on ) {
$address = Address::from_store_settings( $this->get_store_settings() );
} elseif ( null === WC()->customer ) {
$this->_log( 'Warning: WC()->customer is null when resolving ' . $tax_based_on . ' address.' );
return array( '', '', '', '', '' );
} elseif ( 'billing' === $tax_based_on ) {
$address = Address::from_customer_billing( WC()->customer );
} else {
$address = Address::from_customer_shipping( WC()->customer );
}
return apply_filters( 'woocommerce_customer_taxable_address', $address->to_taxable_tuple() );
}
/**
* Get address details of customer for backend orders
*
* Derived from the TaxJar plugin.
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/4b481f5/includes/class-wc-taxjar-integration.php#L607
*
* Sanitization (and the `wp_unslash()` that used to be missing here) now lives in
* `Address::from_post_request()`, and the empty-field representation comes from
* `Address::to_legacy_options()` — the same one `get_address()` uses, so the cart and
* admin-recalculate paths can no longer put different values on the wire for the
* same empty input.
*
* Security: WooCommerce has already verified the nonce and capability by the time
* `woocommerce_before_save_order_items` fires.
*
* This method used to `strtoupper()` postcode, city and street on top of that,
* which `get_address()` did not — the same order recalculated from the admin and
* from the cart put differently-cased values on the wire. The casing was kept only
* because the city feeds the `wp_woocommerce_tax_rates` city column; now that the
* rate-table seam upper-cases the city at both the write and the lookup, nothing
* downstream depends on it and the two paths agree.
*
* @return array
*/
protected function get_backend_address() {
return Address::from_post_request()->to_legacy_options();
}
/**
* Get line items at checkout
*
* Based on the TaxJar plugin, with canonical line item IDs added.
* See: https://github.com/taxjar/taxjar-woocommerce-plugin/blob/96b5d57/includes/class-wc-taxjar-integration.php#L645
*
* @param WC_Cart $wc_cart_object Cart object.
*
* @return array Line items keyed by cart item key. Each item's 'id' is the
* canonical TaxJar line item ID, not the cart item key.
*/
protected function get_line_items( $wc_cart_object ) {
$line_items = array();
$this->non_taxable_line_items = array();
$default_location = get_option( 'woocommerce_tax_based_on', 'shipping' );
foreach ( $wc_cart_object->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$id = $product->get_id();
$quantity = $cart_item['quantity'];
$unit_price = wc_format_decimal( $product->get_price() );
$line_subtotal = wc_format_decimal( $cart_item['line_subtotal'] );
$discount = wc_format_decimal( $cart_item['line_subtotal'] - $cart_item['line_total'] );
$tax_class = explode( '-', $product->get_tax_class() );
$tax_code = '';
if ( isset( $tax_class ) && is_numeric( end( $tax_class ) ) ) {
$tax_code = end( $tax_class );
}
if ( 'shipping' !== $product->get_tax_status() && ( ! $product->is_taxable() || 'zero-rate' == sanitize_title( $product->get_tax_class() ) ) ) {