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

350 lines 12.8 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 if ( false === $taxjar->calculate_tax( $options ) ) {
206 \WCPOS\WooCommercePOS\Logger::log( 'WooCommerce Tax returned no rates for the POS order', array( 'order_id' => $order->get_id() ) );
207 }
208 } catch ( \Throwable $e ) {
209 \WCPOS\WooCommercePOS\Logger::warning(
210 'WooCommerce Tax rate priming failed',
211 array(
212 'order_id' => $order->get_id(),
213 'error' => $e->getMessage(),
214 )
215 );
216 }
217 }
218
219 /**
220 * Unhook the plugin's callbacks for an open POS order.
221 *
222 * @param array $args Args passed to calculate_taxes(). Unused.
223 * @param WC_Abstract_Order|null $order The order being recalculated.
224 */
225 public function suspend_tax_preservation( $args = array(), $order = null ): void {
226 // A recalculation that never reached AFTER_HOOK (a direct calculate_taxes()
227 // call) leaves the callbacks suspended. Hook them back before deciding
228 // about this order, so a suspension never outlives one recalculation.
229 $this->restore_suspended();
230
231 if ( ! $order instanceof WC_Abstract_Order || ! $this->is_open_pos_order( $order ) || ! \wcpos_request() ) {
232 return;
233 }
234
235 foreach ( self::PLUGIN_CALLBACKS as $hook => $method ) {
236 foreach ( $this->find_plugin_callbacks( $hook, $method ) as $entry ) {
237 remove_action( $hook, $entry['callback'], $entry['priority'] );
238 $this->suspended[] = $entry;
239 }
240 }
241 }
242
243 /**
244 * Hook the plugin's callbacks again once the recalculation is done.
245 */
246 public function resume_tax_preservation(): void {
247 $this->restore_suspended();
248 }
249
250 /**
251 * Re-add every suspended callback where it was.
252 */
253 private function restore_suspended(): void {
254 foreach ( $this->suspended as $entry ) {
255 add_action( $entry['hook'], $entry['callback'], $entry['priority'], $entry['accepted_args'] );
256 }
257 $this->suspended = array();
258 }
259
260 /**
261 * Whether the order is, or is being put back to, still being built up at the till.
262 *
263 * @param WC_Abstract_Order $order The order.
264 *
265 * @return bool
266 */
267 private function is_open_pos_order( WC_Abstract_Order $order ): bool {
268 if ( \in_array( $order->get_status(), self::OPEN_STATUSES, true ) ) {
269 return true;
270 }
271
272 return null !== $this->requested
273 && $this->requested['order'] === $order
274 && \in_array( $this->requested['status'], self::OPEN_STATUSES, true );
275 }
276
277 /**
278 * The street line that belongs to the address WooCommerce is taxing.
279 *
280 * The declared basis (the POS meta, else WooCommerce's setting) is tried first
281 * so two addresses that share a country, state, postcode and city are told
282 * apart; the tuple check keeps the street consistent with the location that
283 * was actually resolved, which a filter may have changed.
284 *
285 * @param WC_Abstract_Order $order The order.
286 * @param array $location Country, state, postcode and city from get_taxable_location().
287 *
288 * @return string
289 */
290 private function street_for_location( WC_Abstract_Order $order, array $location ): string {
291 if ( $order instanceof WC_Order ) {
292 $basis = (string) $order->get_meta( '_woocommerce_pos_tax_based_on' );
293 if ( '' === $basis ) {
294 $basis = (string) get_option( 'woocommerce_tax_based_on', 'shipping' );
295 }
296 $candidates = array(
297 'billing' => array( $order->get_billing_address_1(), array( $order->get_billing_country(), $order->get_billing_state(), $order->get_billing_postcode(), $order->get_billing_city() ) ),
298 'shipping' => array( $order->get_shipping_address_1(), array( $order->get_shipping_country(), $order->get_shipping_state(), $order->get_shipping_postcode(), $order->get_shipping_city() ) ),
299 );
300 if ( isset( $candidates[ $basis ] ) ) {
301 $candidates = array( $basis => $candidates[ $basis ] ) + $candidates;
302 }
303 $taxed = array( $location['country'] ?? '', $location['state'] ?? '', $location['postcode'] ?? '', $location['city'] ?? '' );
304 foreach ( $candidates as $candidate ) {
305 if ( $candidate[1] === $taxed ) {
306 return (string) $candidate[0];
307 }
308 }
309 }
310
311 return (string) WC()->countries->get_base_address();
312 }
313
314 /**
315 * Locate the plugin's callback for a method on a hook, at whatever priority.
316 *
317 * @param string $hook The hook.
318 * @param string $method The plugin method name.
319 *
320 * @return array<int, array{hook: string, callback: array, priority: int, accepted_args: int}>
321 */
322 private function find_plugin_callbacks( string $hook, string $method ): array {
323 global $wp_filter;
324 $found = array();
325 if ( ! isset( $wp_filter[ $hook ] ) ) {
326 return $found;
327 }
328
329 foreach ( $wp_filter[ $hook ]->callbacks as $priority => $callbacks ) {
330 foreach ( $callbacks as $entry ) {
331 $callback = $entry['function'];
332 if ( \is_array( $callback )
333 && isset( $callback[0], $callback[1] )
334 && \is_object( $callback[0] )
335 && is_a( $callback[0], self::TAXJAR_CLASS )
336 && $method === $callback[1] ) {
337 $found[] = array(
338 'hook' => $hook,
339 'callback' => $callback,
340 'priority' => (int) $priority,
341 'accepted_args' => (int) $entry['accepted_args'],
342 );
343 }
344 }
345 }
346
347 return $found;
348 }
349 }
350