PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.19
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.19
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.19, at includes/Integrations/WooCommerce_Tax.php

398 lines 15.2 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 WCPOS\WooCommercePOS\Services\Order_Write_Intent;
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 * Constructor.
94 *
95 * Prime at 8, suspend at 9 before the plugin's snapshot at 10, then resume
96 * from the last priority so nothing re-added runs in the same pass.
97 */
98 public function __construct() {
99 add_action( self::BEFORE_HOOK, array( $this, 'prime_tax_rates' ), 8, 2 );
100 add_action( self::BEFORE_HOOK, array( $this, 'suspend_tax_preservation' ), 9, 2 );
101 add_action( self::AFTER_HOOK, array( $this, 'resume_tax_preservation' ), self::RESUME_PRIORITY );
102 }
103
104 /**
105 * Prime the plugin's rates for the order before WooCommerce matches them.
106 *
107 * Mirrors the request the plugin's protected get_backend_line_items() builds
108 * (woocommerce-services 3.6.14), with one deliberate difference: items
109 * WooCommerce will not tax are left out. The plugin sends them as exempt and
110 * skips their 0% breakdown line through a private list only its own builders
111 * fill; without that list the 0% would be written over the shared rate row
112 * for the item's tax class. Their rates are never needed here.
113 *
114 * @param array $args Calculation arguments. Unused.
115 * @param WC_Abstract_Order|null $order The order being recalculated.
116 */
117 public function prime_tax_rates( $args = array(), $order = null ): void {
118 // A leftover suspension would hide the plugin's callbacks from the lookup below.
119 $this->restore_suspended();
120
121 if ( ! $order instanceof WC_Abstract_Order || ! \wcpos_request() || ! $this->is_open_pos_order( $order ) ) {
122 return;
123 }
124 $callbacks = $this->find_plugin_callbacks( self::BEFORE_HOOK, self::PLUGIN_CALLBACKS[ self::BEFORE_HOOK ] );
125 if ( empty( $callbacks ) ) {
126 return;
127 }
128 $taxjar = $callbacks[0]['callback'][0];
129
130 // get_taxable_location() is public since WooCommerce 7.6. Older stores keep
131 // today's behaviour rather than a warning on every save.
132 if ( version_compare( WC_VERSION, '7.6.0', '<' ) ) {
133 return;
134 }
135
136 try {
137 $location = $order->get_taxable_location();
138 $options = array(
139 'to_country' => $location['country'] ?? '',
140 'to_state' => $location['state'] ?? '',
141 'to_zip' => $location['postcode'] ?? '',
142 'to_city' => $location['city'] ?? '',
143 'to_street' => $this->street_for_location( $order, $location ),
144 'shipping_amount' => $order->get_shipping_total(),
145 'line_items' => array(),
146 );
147 foreach ( $order->get_items( 'line_item' ) as $item ) {
148 if ( 'taxable' !== $item->get_tax_status() ) {
149 continue;
150 }
151 $quantity = $item->get_quantity();
152 $unit_price = empty( $quantity ) ? $item->get_subtotal() : wc_format_decimal( $item->get_subtotal() / $quantity );
153 if ( empty( $unit_price ) ) {
154 continue;
155 }
156 $tax_class = explode( '-', $item->get_tax_class() );
157 $options['line_items'][] = array(
158 'id' => (string) ( $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id() ),
159 'quantity' => $quantity,
160 'unit_price' => $unit_price,
161 'discount' => wc_format_decimal( $item->get_subtotal() - $item->get_total() ),
162 'product_tax_code' => isset( $tax_class[1] ) && is_numeric( $tax_class[1] ) ? $tax_class[1] : '',
163 );
164 }
165 if ( empty( $options['line_items'] ) && empty( (float) $options['shipping_amount'] ) ) {
166 return;
167 }
168 // WooCommerce does not initialise the customer on REST requests, and the
169 // plugin reads it for its VAT-exemption check.
170 if ( ! WC()->customer instanceof \WC_Customer ) {
171 wc_load_cart();
172 }
173 add_filter( 'woocommerce_services_override_tax_rate', array( $this, 'preserve_tax_rate_order' ), PHP_INT_MAX, 3 );
174 if ( false === $taxjar->calculate_tax( $options ) ) {
175 \WCPOS\WooCommercePOS\Logger::log( 'WooCommerce Tax returned no rates for the POS order', array( 'order_id' => $order->get_id() ) );
176 }
177 } catch ( \Throwable $e ) {
178 \WCPOS\WooCommercePOS\Logger::warning(
179 'WooCommerce Tax rate priming failed',
180 array(
181 'order_id' => $order->get_id(),
182 'error' => $e->getMessage(),
183 )
184 );
185 } finally {
186 remove_filter( 'woocommerce_services_override_tax_rate', array( $this, 'preserve_tax_rate_order' ), PHP_INT_MAX );
187 }
188 }
189
190 /**
191 * Preserve WooCommerce rate IDs when TaxJar jurisdiction fields change order.
192 *
193 * WooCommerce Tax assigns rows by response position, not jurisdiction. Only
194 * reorder an exact label bijection; new/renamed jurisdictions keep upstream
195 * behaviour. Values are untouched, including genuine rate changes. This hook
196 * exposes the mutable response object before the plugin writes its rate rows.
197 *
198 * @param mixed $rate Overall rate, returned unchanged.
199 * @param object $tax TaxJar tax response.
200 * @param array $body Normalized TaxJar request address.
201 * @return mixed
202 */
203 public function preserve_tax_rate_order( $rate, $tax, $body ) {
204 $lines = \is_array( $tax->breakdown->line_items ?? null ) ? $tax->breakdown->line_items : array();
205 if ( isset( $tax->breakdown->shipping ) ) {
206 $lines[] = $tax->breakdown->shipping;
207 }
208 foreach ( $lines as $line ) {
209 if ( ! \is_object( $line ) ) {
210 continue;
211 }
212 $keys = array();
213 foreach ( $line as $key => $value ) {
214 if ( 'combined_tax_rate' === $key || false === strpos( $key, '_tax_rate' ) ) {
215 continue;
216 }
217 // Mirrors the plugin's private generate_itemized_tax_rate_name().
218 $label = ucwords( str_replace( '_', ' ', str_replace( '_tax_rate', '', $key ) ) ) . ' ' . __( 'Tax', 'woocommerce-services' ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch -- Match the third-party rate labels.
219 $place = trim( trim( $tax->jurisdictions->county ?? '' ) . ' ' . trim( $tax->jurisdictions->city ?? '' ) );
220 $label = 'US' === $body['to_country'] ? ( '' === $place ? $label : $place . ' : ' . $label ) : strtoupper( $label );
221 if ( isset( $keys[ $label ] ) ) {
222 continue 2;
223 }
224 $keys[ $label ] = $key;
225 }
226 $product = wc_get_product( (int) ( $line->id ?? 0 ) );
227 $rates = \WC_Tax::find_rates(
228 array(
229 'country' => $body['to_country'],
230 'state' => $body['to_state'],
231 'postcode' => $body['to_zip'],
232 'city' => $body['to_city'],
233 'tax_class' => $product ? $product->get_tax_class() : '',
234 )
235 );
236 if ( \count( $rates ) !== \count( $keys ) ) {
237 continue;
238 }
239 $ordered = array();
240 foreach ( $rates as $existing ) {
241 if ( ! isset( $keys[ $existing['label'] ] ) ) {
242 continue 2;
243 }
244 $key = $keys[ $existing['label'] ];
245 $ordered[ $key ] = $line->$key;
246 unset( $keys[ $existing['label'] ] );
247 }
248 foreach ( $ordered as $key => $value ) {
249 unset( $line->$key );
250 $line->$key = $value;
251 }
252 }
253 return $rate;
254 }
255
256 /**
257 * Unhook the plugin's callbacks for an open POS order.
258 *
259 * @param array $args Args passed to calculate_taxes(). Unused.
260 * @param WC_Abstract_Order|null $order The order being recalculated.
261 */
262 public function suspend_tax_preservation( $args = array(), $order = null ): void {
263 // A recalculation that never reached AFTER_HOOK (a direct calculate_taxes()
264 // call) leaves the callbacks suspended. Hook them back before deciding
265 // about this order, so a suspension never outlives one recalculation.
266 $this->restore_suspended();
267
268 if ( ! $order instanceof WC_Abstract_Order || ! $this->is_open_pos_order( $order ) || ! \wcpos_request() ) {
269 return;
270 }
271
272 foreach ( self::PLUGIN_CALLBACKS as $hook => $method ) {
273 foreach ( $this->find_plugin_callbacks( $hook, $method ) as $entry ) {
274 remove_action( $hook, $entry['callback'], $entry['priority'] );
275 $this->suspended[] = $entry;
276 }
277 }
278 }
279
280 /**
281 * Hook the plugin's callbacks again once the recalculation is done.
282 */
283 public function resume_tax_preservation(): void {
284 $this->restore_suspended();
285 }
286
287 /**
288 * Re-add every suspended callback where it was.
289 */
290 private function restore_suspended(): void {
291 foreach ( $this->suspended as $entry ) {
292 add_action( $entry['hook'], $entry['callback'], $entry['priority'], $entry['accepted_args'] );
293 }
294 $this->suspended = array();
295 }
296
297 /**
298 * Whether the order is, or is being put back to, still being built up at the till.
299 *
300 * WooCommerce recalculates totals before applying the requested status, so
301 * reopening a paid order recalculates while its persisted status is still paid.
302 *
303 * @param WC_Abstract_Order $order The order.
304 *
305 * @return bool
306 */
307 private function is_open_pos_order( WC_Abstract_Order $order ): bool {
308 if ( \in_array( $order->get_status(), self::OPEN_STATUSES, true ) ) {
309 return true;
310 }
311
312 $intent = Order_Write_Intent::current();
313 return null !== $intent && $intent->is_subject( $order )
314 && \in_array( $intent->requested_status(), self::OPEN_STATUSES, true );
315 }
316
317 /**
318 * The street line that belongs to the address WooCommerce is taxing.
319 *
320 * The declared basis (the POS meta, else WooCommerce's setting) is tried first
321 * so two addresses that share a country, state, postcode and city are told
322 * apart — including the store's own address, which a local customer's billing
323 * or shipping address can match exactly; the tuple check keeps the street
324 * consistent with the location that was actually resolved, which a filter may
325 * have changed.
326 *
327 * @param WC_Abstract_Order $order The order.
328 * @param array $location Country, state, postcode and city from get_taxable_location().
329 *
330 * @return string
331 */
332 private function street_for_location( WC_Abstract_Order $order, array $location ): string {
333 if ( $order instanceof WC_Order ) {
334 $basis = (string) $order->get_meta( '_woocommerce_pos_tax_based_on' );
335 if ( '' === $basis ) {
336 $basis = (string) get_option( 'woocommerce_tax_based_on', 'shipping' );
337 }
338 // The store address is a candidate too, but LAST unless it is the
339 // declared basis: when a filter moves the taxed location to the other
340 // customer address, that address must win over a store that happens
341 // to share its country, state, postcode and city.
342 $countries = WC()->countries;
343 $candidates = array(
344 'billing' => array( $order->get_billing_address_1(), array( $order->get_billing_country(), $order->get_billing_state(), $order->get_billing_postcode(), $order->get_billing_city() ) ),
345 'shipping' => array( $order->get_shipping_address_1(), array( $order->get_shipping_country(), $order->get_shipping_state(), $order->get_shipping_postcode(), $order->get_shipping_city() ) ),
346 'base' => array( $countries->get_base_address(), array( $countries->get_base_country(), $countries->get_base_state(), $countries->get_base_postcode(), $countries->get_base_city() ) ),
347 );
348 if ( isset( $candidates[ $basis ] ) ) {
349 $candidates = array( $basis => $candidates[ $basis ] ) + $candidates;
350 }
351 $taxed = array( $location['country'] ?? '', $location['state'] ?? '', $location['postcode'] ?? '', $location['city'] ?? '' );
352 foreach ( $candidates as $candidate ) {
353 if ( $candidate[1] === $taxed ) {
354 return (string) $candidate[0];
355 }
356 }
357 }
358
359 return (string) WC()->countries->get_base_address();
360 }
361
362 /**
363 * Locate the plugin's callback for a method on a hook, at whatever priority.
364 *
365 * @param string $hook The hook.
366 * @param string $method The plugin method name.
367 *
368 * @return array<int, array{hook: string, callback: array, priority: int, accepted_args: int}>
369 */
370 private function find_plugin_callbacks( string $hook, string $method ): array {
371 global $wp_filter;
372 $found = array();
373 if ( ! isset( $wp_filter[ $hook ] ) ) {
374 return $found;
375 }
376
377 foreach ( $wp_filter[ $hook ]->callbacks as $priority => $callbacks ) {
378 foreach ( $callbacks as $entry ) {
379 $callback = $entry['function'];
380 if ( \is_array( $callback )
381 && isset( $callback[0], $callback[1] )
382 && \is_object( $callback[0] )
383 && is_a( $callback[0], self::TAXJAR_CLASS )
384 && $method === $callback[1] ) {
385 $found[] = array(
386 'hook' => $hook,
387 'callback' => $callback,
388 'priority' => (int) $priority,
389 'accepted_args' => (int) $entry['accepted_args'],
390 );
391 }
392 }
393 }
394
395 return $found;
396 }
397 }
398