PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.17
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.17
1.10.19 1.10.18 1.10.17 1.10.16 1.10.15 1.10.13 1.10.14 1.10.12 1.10.11 1.10.10 1.10.9 1.10.8 untagged-3d9b7ccddc54df87c672 1.10.7 1.10.6 1.10.5 1.10.3 1.10.4 1.10.2 1.10.1 1.10.0 1.9.17 1.9.15 1.9.16 1.9.14 All 163 releases
woocommerce-pos / includes / Integrations / WooCommerce_Tax.php

WooCommerce_Tax.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.17, at includes/Integrations/WooCommerce_Tax.php

427 lines 16.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WooCommerce Tax (automated taxes) integration.
4 *
5 * @package WCPOS\WooCommercePOS
6 */
7
8 namespace WCPOS\WooCommercePOS\Integrations;
9
10 use WC_Abstract_Order;
11 use WC_Order;
12 use WP_REST_Request;
13
14 /**
15 * Keep WooCommerce Tax from restoring stale tax lines onto open POS orders.
16 *
17 * WooCommerce Tax (wp.org slug `woocommerce-services`, formerly WooCommerce
18 * Shipping & Tax) 3.6.8 and later snapshots an order's tax lines on
19 * `woocommerce_order_before_calculate_taxes` and writes them back on
20 * `woocommerce_order_after_calculate_totals`, rebasing the order total on the
21 * old tax. Its premise is that a placed order's tax is a record of what was
22 * charged. An open till order is not: every WCPOS save of a `pos-open` order can
23 * change the line items, and WooCommerce's REST controller recalculates totals
24 * for them. With the snapshot restored, the server answers with the previous
25 * save's tax while the POS has computed tax for the current lines, and the
26 * client shows the totals-disagree banner. See
27 * https://github.com/wcpos/woocommerce-pos/issues/1896.
28 *
29 * The plugin primes TaxJar rates only from the cart and wp-admin, while POS
30 * writes arrive through REST. Prime rates for the current order before WooCommerce
31 * matches them, so POS tax does not depend on an earlier checkout at that address.
32 *
33 * The plugin has no filter and no status gate, and its integration object is
34 * held privately by its loader, so its callbacks are located on the hooks
35 * themselves. When a WCPOS request recalculates an order that is open, or that
36 * the request is putting back into an open status, both of the plugin's
37 * callbacks are unhooked for that one recalculation and hooked again as soon as
38 * it finishes. Paid orders and non-POS requests keep the plugin's behaviour.
39 */
40 class WooCommerce_Tax {
41 /**
42 * The plugin's integration class.
43 */
44 const TAXJAR_CLASS = 'WC_Connect_TaxJar_Integration';
45
46 /**
47 * Hook the plugin snapshots on.
48 */
49 const BEFORE_HOOK = 'woocommerce_order_before_calculate_taxes';
50
51 /**
52 * Hook the plugin restores on, and where its callbacks are hooked again.
53 */
54 const AFTER_HOOK = 'woocommerce_order_after_calculate_totals';
55
56 /**
57 * Priority the callbacks are hooked again at on AFTER_HOOK.
58 *
59 * WP_Hook runs a callback added during dispatch if its priority has not been
60 * passed yet. Re-adding the plugin's restore at 10 from priority 9 would run
61 * it in the same pass, and a snapshot left over from an earlier bare
62 * calculate_taxes() on the same order would be written over the fresh tax.
63 * Re-adding from the last priority keeps it for the next recalculation.
64 */
65 const RESUME_PRIORITY = PHP_INT_MAX;
66
67 /**
68 * The plugin's callbacks, by hook. Both are suspended together so a snapshot
69 * taken by the first can never be written back by the second.
70 *
71 * @var array<string, string>
72 */
73 const PLUGIN_CALLBACKS = array(
74 self::BEFORE_HOOK => 'preserve_order_taxes_on_recalculation',
75 self::AFTER_HOOK => 'restore_order_taxes_after_recalculation',
76 );
77
78 /**
79 * Statuses whose tax is not yet a record of what was charged.
80 *
81 * @var string[]
82 */
83 const OPEN_STATUSES = array( 'pending', 'pos-open', 'pos-partial' );
84
85 /**
86 * Plugin callbacks removed for the recalculation in progress.
87 *
88 * @var array<int, array{hook: string, callback: array, priority: int, accepted_args: int}>
89 */
90 private $suspended = array();
91
92 /**
93 * The order a WCPOS REST write is about to save, and the status it asked for.
94 *
95 * WooCommerce's REST controller recalculates totals before it applies the
96 * requested status, so a request that reopens a paid order and changes its
97 * lines recalculates while the persisted status is still paid.
98 *
99 * @var array{order: WC_Abstract_Order, status: string}|null
100 */
101 private $requested = null;
102
103 /**
104 * Constructor.
105 *
106 * Suspend at priority 9, before the plugin's snapshot callback at 10; resume
107 * from the last priority so nothing re-added runs in the same pass.
108 */
109 public function __construct() {
110 add_filter( 'woocommerce_rest_pre_insert_shop_order_object', array( $this, 'note_requested_status' ), 10, 2 );
111 add_action( self::BEFORE_HOOK, array( $this, 'prime_tax_rates' ), 8, 2 );
112 add_action( self::BEFORE_HOOK, array( $this, 'suspend_tax_preservation' ), 9, 2 );
113 add_action( self::AFTER_HOOK, array( $this, 'resume_tax_preservation' ), self::RESUME_PRIORITY );
114 }
115
116 /**
117 * Remember the status a REST write asked for, for the recalculation it triggers.
118 *
119 * @param mixed $order The order about to be saved.
120 * @param WP_REST_Request|null $request The request.
121 *
122 * @return mixed The order, unchanged.
123 */
124 public function note_requested_status( $order, $request = null ) {
125 $this->requested = null;
126 if ( $order instanceof WC_Abstract_Order && $request instanceof WP_REST_Request ) {
127 $this->requested = array(
128 'order' => $order,
129 'status' => (string) $request->get_param( 'status' ),
130 );
131 }
132
133 return $order;
134 }
135
136 /**
137 * Prime the plugin's rates for the order before WooCommerce matches them.
138 *
139 * Mirrors the request the plugin's protected get_backend_line_items() builds
140 * (woocommerce-services 3.6.14), with one deliberate difference: items
141 * WooCommerce will not tax are left out. The plugin sends them as exempt and
142 * skips their 0% breakdown line through a private list only its own builders
143 * fill; without that list the 0% would be written over the shared rate row
144 * for the item's tax class. Their rates are never needed here.
145 *
146 * @param array $args Calculation arguments. Unused.
147 * @param WC_Abstract_Order|null $order The order being recalculated.
148 */
149 public function prime_tax_rates( $args = array(), $order = null ): void {
150 // A leftover suspension would hide the plugin's callbacks from the lookup below.
151 $this->restore_suspended();
152
153 if ( ! $order instanceof WC_Abstract_Order || ! \wcpos_request() || ! $this->is_open_pos_order( $order ) ) {
154 return;
155 }
156 $callbacks = $this->find_plugin_callbacks( self::BEFORE_HOOK, self::PLUGIN_CALLBACKS[ self::BEFORE_HOOK ] );
157 if ( empty( $callbacks ) ) {
158 return;
159 }
160 $taxjar = $callbacks[0]['callback'][0];
161
162 // get_taxable_location() is public since WooCommerce 7.6. Older stores keep
163 // today's behaviour rather than a warning on every save.
164 if ( version_compare( WC_VERSION, '7.6.0', '<' ) ) {
165 return;
166 }
167
168 try {
169 $location = $order->get_taxable_location();
170 $options = array(
171 'to_country' => $location['country'] ?? '',
172 'to_state' => $location['state'] ?? '',
173 'to_zip' => $location['postcode'] ?? '',
174 'to_city' => $location['city'] ?? '',
175 'to_street' => $this->street_for_location( $order, $location ),
176 'shipping_amount' => $order->get_shipping_total(),
177 'line_items' => array(),
178 );
179 foreach ( $order->get_items( 'line_item' ) as $item ) {
180 if ( 'taxable' !== $item->get_tax_status() ) {
181 continue;
182 }
183 $quantity = $item->get_quantity();
184 $unit_price = empty( $quantity ) ? $item->get_subtotal() : wc_format_decimal( $item->get_subtotal() / $quantity );
185 if ( empty( $unit_price ) ) {
186 continue;
187 }
188 $tax_class = explode( '-', $item->get_tax_class() );
189 $options['line_items'][] = array(
190 'id' => (string) ( $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id() ),
191 'quantity' => $quantity,
192 'unit_price' => $unit_price,
193 'discount' => wc_format_decimal( $item->get_subtotal() - $item->get_total() ),
194 'product_tax_code' => isset( $tax_class[1] ) && is_numeric( $tax_class[1] ) ? $tax_class[1] : '',
195 );
196 }
197 if ( empty( $options['line_items'] ) && empty( (float) $options['shipping_amount'] ) ) {
198 return;
199 }
200 // WooCommerce does not initialise the customer on REST requests, and the
201 // plugin reads it for its VAT-exemption check.
202 if ( ! WC()->customer instanceof \WC_Customer ) {
203 wc_load_cart();
204 }
205 add_filter( 'woocommerce_services_override_tax_rate', array( $this, 'preserve_tax_rate_order' ), PHP_INT_MAX, 3 );
206 if ( false === $taxjar->calculate_tax( $options ) ) {
207 \WCPOS\WooCommercePOS\Logger::log( 'WooCommerce Tax returned no rates for the POS order', array( 'order_id' => $order->get_id() ) );
208 }
209 } catch ( \Throwable $e ) {
210 \WCPOS\WooCommercePOS\Logger::warning(
211 'WooCommerce Tax rate priming failed',
212 array(
213 'order_id' => $order->get_id(),
214 'error' => $e->getMessage(),
215 )
216 );
217 } finally {
218 remove_filter( 'woocommerce_services_override_tax_rate', array( $this, 'preserve_tax_rate_order' ), PHP_INT_MAX );
219 }
220 }
221
222 /**
223 * Preserve WooCommerce rate IDs when TaxJar jurisdiction fields change order.
224 *
225 * WooCommerce Tax assigns rows by response position, not jurisdiction. Only
226 * reorder an exact label bijection; new/renamed jurisdictions keep upstream
227 * behaviour. Values are untouched, including genuine rate changes. This hook
228 * exposes the mutable response object before the plugin writes its rate rows.
229 *
230 * @param mixed $rate Overall rate, returned unchanged.
231 * @param object $tax TaxJar tax response.
232 * @param array $body Normalized TaxJar request address.
233 * @return mixed
234 */
235 public function preserve_tax_rate_order( $rate, $tax, $body ) {
236 $lines = \is_array( $tax->breakdown->line_items ?? null ) ? $tax->breakdown->line_items : array();
237 if ( isset( $tax->breakdown->shipping ) ) {
238 $lines[] = $tax->breakdown->shipping;
239 }
240 foreach ( $lines as $line ) {
241 if ( ! \is_object( $line ) ) {
242 continue;
243 }
244 $keys = array();
245 foreach ( $line as $key => $value ) {
246 if ( 'combined_tax_rate' === $key || false === strpos( $key, '_tax_rate' ) ) {
247 continue;
248 }
249 // Mirrors the plugin's private generate_itemized_tax_rate_name().
250 $label = ucwords( str_replace( '_', ' ', str_replace( '_tax_rate', '', $key ) ) ) . ' ' . __( 'Tax', 'woocommerce-services' ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch -- Match the third-party rate labels.
251 $place = trim( trim( $tax->jurisdictions->county ?? '' ) . ' ' . trim( $tax->jurisdictions->city ?? '' ) );
252 $label = 'US' === $body['to_country'] ? ( '' === $place ? $label : $place . ' : ' . $label ) : strtoupper( $label );
253 if ( isset( $keys[ $label ] ) ) {
254 continue 2;
255 }
256 $keys[ $label ] = $key;
257 }
258 $product = wc_get_product( (int) ( $line->id ?? 0 ) );
259 $rates = \WC_Tax::find_rates(
260 array(
261 'country' => $body['to_country'],
262 'state' => $body['to_state'],
263 'postcode' => $body['to_zip'],
264 'city' => $body['to_city'],
265 'tax_class' => $product ? $product->get_tax_class() : '',
266 )
267 );
268 if ( \count( $rates ) !== \count( $keys ) ) {
269 continue;
270 }
271 $ordered = array();
272 foreach ( $rates as $existing ) {
273 if ( ! isset( $keys[ $existing['label'] ] ) ) {
274 continue 2;
275 }
276 $key = $keys[ $existing['label'] ];
277 $ordered[ $key ] = $line->$key;
278 unset( $keys[ $existing['label'] ] );
279 }
280 foreach ( $ordered as $key => $value ) {
281 unset( $line->$key );
282 $line->$key = $value;
283 }
284 }
285 return $rate;
286 }
287
288 /**
289 * Unhook the plugin's callbacks for an open POS order.
290 *
291 * @param array $args Args passed to calculate_taxes(). Unused.
292 * @param WC_Abstract_Order|null $order The order being recalculated.
293 */
294 public function suspend_tax_preservation( $args = array(), $order = null ): void {
295 // A recalculation that never reached AFTER_HOOK (a direct calculate_taxes()
296 // call) leaves the callbacks suspended. Hook them back before deciding
297 // about this order, so a suspension never outlives one recalculation.
298 $this->restore_suspended();
299
300 if ( ! $order instanceof WC_Abstract_Order || ! $this->is_open_pos_order( $order ) || ! \wcpos_request() ) {
301 return;
302 }
303
304 foreach ( self::PLUGIN_CALLBACKS as $hook => $method ) {
305 foreach ( $this->find_plugin_callbacks( $hook, $method ) as $entry ) {
306 remove_action( $hook, $entry['callback'], $entry['priority'] );
307 $this->suspended[] = $entry;
308 }
309 }
310 }
311
312 /**
313 * Hook the plugin's callbacks again once the recalculation is done.
314 */
315 public function resume_tax_preservation(): void {
316 $this->restore_suspended();
317 }
318
319 /**
320 * Re-add every suspended callback where it was.
321 */
322 private function restore_suspended(): void {
323 foreach ( $this->suspended as $entry ) {
324 add_action( $entry['hook'], $entry['callback'], $entry['priority'], $entry['accepted_args'] );
325 }
326 $this->suspended = array();
327 }
328
329 /**
330 * Whether the order is, or is being put back to, still being built up at the till.
331 *
332 * @param WC_Abstract_Order $order The order.
333 *
334 * @return bool
335 */
336 private function is_open_pos_order( WC_Abstract_Order $order ): bool {
337 if ( \in_array( $order->get_status(), self::OPEN_STATUSES, true ) ) {
338 return true;
339 }
340
341 return null !== $this->requested
342 && $this->requested['order'] === $order
343 && \in_array( $this->requested['status'], self::OPEN_STATUSES, true );
344 }
345
346 /**
347 * The street line that belongs to the address WooCommerce is taxing.
348 *
349 * The declared basis (the POS meta, else WooCommerce's setting) is tried first
350 * so two addresses that share a country, state, postcode and city are told
351 * apart — including the store's own address, which a local customer's billing
352 * or shipping address can match exactly; the tuple check keeps the street
353 * consistent with the location that was actually resolved, which a filter may
354 * have changed.
355 *
356 * @param WC_Abstract_Order $order The order.
357 * @param array $location Country, state, postcode and city from get_taxable_location().
358 *
359 * @return string
360 */
361 private function street_for_location( WC_Abstract_Order $order, array $location ): string {
362 if ( $order instanceof WC_Order ) {
363 $basis = (string) $order->get_meta( '_woocommerce_pos_tax_based_on' );
364 if ( '' === $basis ) {
365 $basis = (string) get_option( 'woocommerce_tax_based_on', 'shipping' );
366 }
367 // The store address is a candidate too, but LAST unless it is the
368 // declared basis: when a filter moves the taxed location to the other
369 // customer address, that address must win over a store that happens
370 // to share its country, state, postcode and city.
371 $countries = WC()->countries;
372 $candidates = array(
373 'billing' => array( $order->get_billing_address_1(), array( $order->get_billing_country(), $order->get_billing_state(), $order->get_billing_postcode(), $order->get_billing_city() ) ),
374 'shipping' => array( $order->get_shipping_address_1(), array( $order->get_shipping_country(), $order->get_shipping_state(), $order->get_shipping_postcode(), $order->get_shipping_city() ) ),
375 'base' => array( $countries->get_base_address(), array( $countries->get_base_country(), $countries->get_base_state(), $countries->get_base_postcode(), $countries->get_base_city() ) ),
376 );
377 if ( isset( $candidates[ $basis ] ) ) {
378 $candidates = array( $basis => $candidates[ $basis ] ) + $candidates;
379 }
380 $taxed = array( $location['country'] ?? '', $location['state'] ?? '', $location['postcode'] ?? '', $location['city'] ?? '' );
381 foreach ( $candidates as $candidate ) {
382 if ( $candidate[1] === $taxed ) {
383 return (string) $candidate[0];
384 }
385 }
386 }
387
388 return (string) WC()->countries->get_base_address();
389 }
390
391 /**
392 * Locate the plugin's callback for a method on a hook, at whatever priority.
393 *
394 * @param string $hook The hook.
395 * @param string $method The plugin method name.
396 *
397 * @return array<int, array{hook: string, callback: array, priority: int, accepted_args: int}>
398 */
399 private function find_plugin_callbacks( string $hook, string $method ): array {
400 global $wp_filter;
401 $found = array();
402 if ( ! isset( $wp_filter[ $hook ] ) ) {
403 return $found;
404 }
405
406 foreach ( $wp_filter[ $hook ]->callbacks as $priority => $callbacks ) {
407 foreach ( $callbacks as $entry ) {
408 $callback = $entry['function'];
409 if ( \is_array( $callback )
410 && isset( $callback[0], $callback[1] )
411 && \is_object( $callback[0] )
412 && is_a( $callback[0], self::TAXJAR_CLASS )
413 && $method === $callback[1] ) {
414 $found[] = array(
415 'hook' => $hook,
416 'callback' => $callback,
417 'priority' => (int) $priority,
418 'accepted_args' => (int) $entry['accepted_args'],
419 );
420 }
421 }
422 }
423
424 return $found;
425 }
426 }
427