PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.18
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.18
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 1.9.13 All 162 releases
woocommerce-pos / includes / API / V2 / Write_Controller.php

Write_Controller.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.18, at includes/API/V2/Write_Controller.php

893 lines 38.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WCPOS sync write surface.
4 *
5 * @package WCPOS\WooCommercePOS\API\V2
6 */
7
8 namespace WCPOS\WooCommercePOS\API\V2;
9
10 use WCPOS\WooCommercePOS\API\V2\Writers\Collection_Writer_Resolver;
11 use WCPOS\WooCommercePOS\Services\Permission_Rules;
12 use WCPOS\WooCommercePOS\Services\Tax_Id_Types;
13 use WCPOS\WooCommercePOS\Sync\Api;
14 use WCPOS\WooCommercePOS\Sync\Collections;
15 use WCPOS\WooCommercePOS\Sync\Endpoint_Permissions;
16 use WCPOS\WooCommercePOS\Sync\Header_Mirror;
17 use WCPOS\WooCommercePOS\Sync\Meta_Normalizer;
18 use WCPOS\WooCommercePOS\Sync\Mutation_Store;
19 use WCPOS\WooCommercePOS\Sync\Order_Serializer;
20 use WCPOS\WooCommercePOS\Sync\Pos_Uuid;
21 use WCPOS\WooCommercePOS\Sync\Product_Serializer;
22 use WCPOS\WooCommercePOS\Sync\Revision;
23 use WCPOS\WooCommercePOS\Sync\Store_Scope;
24 use WP_Error;
25 use WP_REST_Controller;
26 use WP_REST_Request;
27 use WP_REST_Response;
28 use WP_REST_Server;
29
30 // phpcs:disable Squiz.Commenting, Generic.Commenting -- Ported lab documentation is preserved verbatim.
31
32 /**
33 * The generic server write surface (P1-0) — ONE controller for EVERY collection's
34 * writes (guardrail G1), the server half of the client push path. Registered at
35 * `POST /{API_NAMESPACE}/push/{collection}`; it dispatches on the envelope's
36 * `operation` (not the HTTP verb — the client always POSTs the envelope) and
37 * applies each create/update/delete through the collection's Woo write seam:
38 * every collection forwards to its `wc/v3` controller, including the nested,
39 * parent-aware variation routes. The generic identity, lock, CAS and ack pipeline
40 * remains shared across every collection.
41 *
42 * Identity is the client uuid (DECIDED): the server resolves the record by its
43 * `_woocommerce_pos_uuid`, reuses it, and NEVER re-keys. Idempotency + resolution
44 * live in an injected mutation store, so the apply logic is unit-testable with a
45 * fake store + a stubbed `rest_do_request`.
46 */
47 class Write_Controller extends WP_REST_Controller {
48
49 // Our gate (capability + F13 health); forwarded writes scope the client-tier grant below.
50 use Endpoint_Permissions;
51
52
53 /** @var mixed Duck-typed mutation store; tests inject an in-memory implementation. */
54 private $store;
55
56
57 /**
58 * collection => wc/v3 route + how its uuid→id is resolved. ONE table, not
59 * per-collection controllers. Only collections whose resolver is correct AND
60 * exercised are exposed; the rest stay out until their phase:
61 * - orders: RESOLVED — HPOS keeps orders in WooCommerce's own table, so id_type=>'order'
62 * resolves via wc_get_orders by the uuid meta (not post meta). This superseded (and
63 * replaced) the deleted orders-specific legacy /orders/push.
64 * - tax_rates: RESOLVED — intentionally NOT in the uuid write-path. Tax rates are
65 * pure-server-pull and have no native meta store, so they are the single principled
66 * G1 exception (ADR 0009): they key by their Woo id, not a uuid. Variations carry
67 * their parent on create and derive it from the stored object thereafter.
68 */
69 /**
70 * The write map — a PROJECTION of the registry's write capability (#421
71 * increments 6+7): route from the write group; id_type and the
72 * collection's OWN scalar resolver scope (post_type / taxonomy — what
73 * resolve_id_by_uuid gets; never the backfill scan scope) from the
74 * identity group. Only rows with BOTH write and identity are pushable;
75 * adding one is a registry-row edit. The mutation store's per-kind meta
76 * operations (persist_uuid / resolve_id_by_uuid, incl. the two-step term
77 * taxonomy re-check and the trash-exclusion live-owner rule) are
78 * unchanged — this projection is what FEEDS them.
79 */
80 private static function collections(): array {
81 $map = array();
82 foreach ( Collections::with( 'write' ) as $collection => $row ) {
83 if ( ! isset( $row['identity'] ) ) {
84 continue; // tax_rates-shaped: writeable would need an id-space first
85 }
86 $entry = array(
87 'route' => $row['write']['route'],
88 'id_type' => $row['identity']['id_type'],
89 );
90 if ( isset( $row['identity']['post_type'] ) ) {
91 $entry['post_type'] = $row['identity']['post_type'];
92 }
93 if ( isset( $row['identity']['taxonomy'] ) ) {
94 $entry['taxonomy'] = $row['identity']['taxonomy'];
95 }
96 $map[ $collection ] = $entry;
97 }
98 return $map;
99 }
100
101 public function __construct( $store = null ) {
102 $this->store = $store ? $store : new Mutation_Store();
103 }
104
105 /** Resolve the collection-specific writer for registry metadata. */
106 private function writer( array $meta ) {
107 return ( new Collection_Writer_Resolver( $this->store ) )->resolve( $meta );
108 }
109
110 public function register_routes(): void {
111 register_rest_route(
112 Api::ROUTE_NAMESPACE,
113 '/push/(?P<collection>[a-z0-9_]+)',
114 array(
115 'methods' => WP_REST_Server::CREATABLE,
116 'callback' => array( $this, 'push' ),
117 'permission_callback' => array( $this, 'permissions_check' ),
118 'args' => array( 'collection' => array( 'sanitize_callback' => 'sanitize_key' ) ),
119 )
120 );
121 }
122
123 /** POST /push/{collection} — apply one mutation envelope idempotently. */
124 public function push( WP_REST_Request $request ) {
125 $content_type = strtolower( trim( (string) $request->get_header( 'Content-Type' ) ) );
126 if ( 'application/json' !== trim( explode( ';', $content_type, 2 )[0] ) ) {
127 return new WP_Error( 'woo_rxdb_sync_json_required', 'Content-Type must be application/json.', array( 'status' => 415 ) );
128 }
129 $collection = (string) ( $request->get_url_params()['collection'] ?? $request->get_param( 'collection' ) );
130 $meta = self::collections()[ $collection ] ?? null;
131 if ( null === $meta ) {
132 return new WP_Error( 'woo_rxdb_sync_unknown_collection', 'Unknown collection.', array( 'status' => 400 ) );
133 }
134
135 $m = $this->envelope( $request );
136 $err = $this->validate_envelope( $m, $collection );
137 if ( $err instanceof WP_Error ) {
138 return $err;
139 }
140
141 // Standard-header MIRROR (ADR 0011) — Idempotency-Key (= mutationId) + If-Match (= baseRevision) are an
142 // optional cross-check over the canonical body; 422 on divergence. Same helper as the orders push path.
143 $mirror = Header_Mirror::assert( $request, $m['mutationId'], $m['baseRevision'] );
144 if ( is_wp_error( $mirror ) ) {
145 return $mirror;
146 }
147 $fingerprint = $this->envelope_fingerprint( $m );
148
149 // Idempotent replay: a mutationId already APPLIED returns its canonical result.
150 $settled = $this->replay_or_conflict( $collection, $meta, $m, $fingerprint );
151 if ( null !== $settled ) {
152 return $settled;
153 }
154
155 // Atomically CLAIM the mutationId before the non-idempotent forward, so two
156 // concurrent retries (e.g. a timeout-retry overlapping its own in-flight push)
157 // can't both create. The loser replays if it's done, else reports in-progress;
158 // a crashed winner's stale reservation is reclaimed after the TTL.
159 if ( ! $this->store->reserve( $collection, $m['mutationId'], $m['recordId'], $m['operation'], $fingerprint ) ) {
160 $settled = $this->replay_or_conflict( $collection, $meta, $m, $fingerprint );
161 if ( null !== $settled ) {
162 return $settled;
163 }
164 if ( ! $this->reclaim_and_reserve( $collection, $m, $fingerprint ) ) {
165 return new WP_REST_Response(
166 array(
167 'code' => 'woo_rxdb_sync_in_progress',
168 'message' => 'Mutation is being applied; retry shortly.',
169 ),
170 409
171 );
172 }
173 }
174
175 // We hold the mutationId reservation (same-mutation idempotency). Now serialise on
176 // the RECORD so two DISTINCT mutations on the same collection+uuid can't both
177 // read-current → pass the baseRevision compare → forward (a silent lost update):
178 // the loser waits, then re-reads the now-updated revision and gets a real 409.
179 if ( ! $this->store->acquire_record_lock( $collection, $m['recordId'] ) ) {
180 $this->store->release( $m['mutationId'] ); // couldn't serialise in time — let a retry re-claim
181 return new WP_REST_Response(
182 array(
183 'code' => 'woo_rxdb_sync_record_locked',
184 'message' => 'Record is being written; retry shortly.',
185 ),
186 409
187 );
188 }
189 try {
190 // Apply, and RELEASE the reservation on any failure so a retry can re-claim
191 // immediately (a crash leaves it pending for the TTL reclaim instead).
192 $result = $this->apply( $m['operation'], $collection, $meta, $m );
193 } finally {
194 $this->store->release_record_lock( $collection, $m['recordId'] );
195 }
196 $checkpoint = $this->store->lookup( $collection, $m['mutationId'] );
197 if ( $this->is_failure( $result ) && ! $this->retains_mutation( $result ) && ! in_array( ( $checkpoint['status'] ?? '' ), array( 'poison', 'blocked' ), true ) ) {
198 $this->store->release( $m['mutationId'] );
199 }
200 return $result;
201 }
202
203 /**
204 * Settle a mutationId that the store already knows about.
205 *
206 * Rejects an envelope that reuses the id for a different write, re-stamps a poisoned
207 * retry, and replays the canonical result of an applied/done mutation.
208 *
209 * @param string $collection The collection being written to.
210 * @param array $meta The collection metadata.
211 * @param array $m The mutation envelope.
212 * @param string $fingerprint The canonical fingerprint of the envelope.
213 * @return WP_Error|WP_REST_Response|null The settled result, or null to keep applying.
214 */
215 private function replay_or_conflict( string $collection, array $meta, array $m, string $fingerprint ) {
216 $hit = $this->store->lookup( $collection, $m['mutationId'] );
217 if ( is_array( $hit ) ) {
218 $mismatch = $this->replay_target_mismatch( $hit, $collection, $fingerprint );
219 if ( $mismatch ) {
220 return $mismatch;
221 }
222 }
223 if ( is_array( $hit ) && 'poison' === ( $hit['status'] ?? '' ) ) {
224 return $this->retry_identity_stamp( $meta, $m, $hit );
225 }
226 if ( is_array( $hit ) && in_array( ( $hit['status'] ?? '' ), array( 'done', 'applied' ), true ) ) {
227 if ( 'applied' === $hit['status'] && ! $this->store->finalize( $m['mutationId'], (int) $hit['remote_id'] ) ) {
228 return $this->finalize_error();
229 }
230 return $this->replay( $meta, $hit );
231 }
232 return null;
233 }
234
235 /**
236 * Reclaim a crashed pending reservation, then atomically claim it again.
237 */
238 private function reclaim_and_reserve( string $collection, array $mutation, string $fingerprint ): bool {
239 if ( ! $this->store->reclaim_stale( $mutation['mutationId'], $this->store->reservation_ttl() ) ) {
240 return false;
241 }
242
243 return $this->store->reserve( $collection, $mutation['mutationId'], $mutation['recordId'], $mutation['operation'], $fingerprint );
244 }
245
246 /**
247 * A stored mutationId must be replayed only for its original envelope.
248 *
249 * @param array $hit The stored mutation row.
250 * @return WP_Error|null An envelope rejection on mismatch, null when aligned.
251 */
252 private function replay_target_mismatch( array $hit, string $collection, string $fingerprint ) {
253 $stored_fingerprint = (string) ( $hit['fingerprint'] ?? '' );
254 $stored_collection = (string) ( $hit['collection'] ?? '' );
255 if ( '' !== $stored_fingerprint && hash_equals( $stored_fingerprint, $fingerprint ) && ( '' === $stored_collection || $collection === $stored_collection ) ) {
256 return null;
257 }
258 return new WP_Error( 'woo_rxdb_sync_bad_mutation_id', 'mutationId was already used for a different envelope.', array( 'status' => 422 ) );
259 }
260
261 private function envelope_fingerprint( array $envelope ): string {
262 return hash( 'sha256', (string) wp_json_encode( $this->sort_envelope_keys( $envelope ) ) );
263 }
264
265 private function sort_envelope_keys( array $value ): array {
266 if ( array_values( $value ) !== $value ) {
267 ksort( $value );
268 }
269 foreach ( $value as $key => $item ) {
270 if ( is_array( $item ) ) {
271 $value[ $key ] = $this->sort_envelope_keys( $item );
272 }
273 }
274 return $value;
275 }
276
277 private function apply( string $operation, string $collection, array $meta, array $m ) {
278 switch ( $operation ) {
279 case 'create':
280 return $this->apply_create( $collection, $meta, $m );
281 case 'update':
282 return $this->apply_update( $collection, $meta, $m );
283 case 'delete':
284 return $this->apply_delete( $collection, $meta, $m );
285 }
286 return new WP_Error( 'woo_rxdb_sync_invalid_operation', 'Invalid operation.', array( 'status' => 400 ) );
287 }
288
289 private function is_failure( $result ): bool {
290 if ( $result instanceof WP_Error ) {
291 return true;
292 }
293 if ( $result instanceof WP_REST_Response ) {
294 return $result->get_status() >= 400;
295 }
296 return false;
297 }
298
299 private function retains_mutation( $result ): bool {
300 return $result instanceof WP_Error
301 && in_array( $result->get_error_code(), array( 'woo_rxdb_sync_finalize_failed', 'woo_rxdb_sync_create_no_id' ), true );
302 }
303
304 private function envelope( WP_REST_Request $request ): array {
305 // Prefer the parsed JSON body (the pattern push/fixtures controllers use) so a
306 // nested `payload` object is read reliably; fall back to get_param otherwise.
307 $json = method_exists( $request, 'get_json_params' ) ? $request->get_json_params() : null;
308 $src = ( is_array( $json ) && ! empty( $json ) ) ? $json : null;
309 $get = static function ( string $key ) use ( $request, $src ) {
310 return null !== $src ? ( $src[ $key ] ?? null ) : $request->get_param( $key );
311 };
312 if ( null !== $src ) {
313 return $src;
314 }
315 return array(
316 'mutationId' => $get( 'mutationId' ),
317 'operation' => $get( 'operation' ),
318 'collection' => $get( 'collection' ),
319 'recordId' => $get( 'recordId' ),
320 'baseRevision' => $get( 'baseRevision' ),
321 'payload' => $get( 'payload' ),
322 );
323 }
324
325 private function validate_envelope( array $m, string $path_collection ) {
326 $allowed = array( 'mutationId', 'operation', 'collection', 'recordId', 'baseRevision', 'payload', 'force' );
327 if ( array_diff( array_keys( $m ), $allowed ) ) {
328 return new WP_Error( 'woo_rxdb_sync_bad_envelope', 'Envelope contains unknown properties.', array( 'status' => 400 ) );
329 }
330 if ( ! isset( $m['mutationId'] ) || ! is_string( $m['mutationId'] ) || ! Pos_Uuid::is_uuid( $m['mutationId'] ) ) {
331 return new WP_Error( 'woo_rxdb_sync_bad_mutation_id', 'mutationId must be a uuid.', array( 'status' => 400 ) );
332 }
333 if ( ! isset( $m['operation'] ) || ! is_string( $m['operation'] ) || ! in_array( $m['operation'], array( 'create', 'update', 'delete' ), true ) ) {
334 return new WP_Error( 'woo_rxdb_sync_bad_operation', 'operation must be create|update|delete.', array( 'status' => 400 ) );
335 }
336 // Tighten the server to the published envelope contract. The production adapter already
337 // sends this field equal to the route, so no legitimate client traffic changes.
338 if ( ! isset( $m['collection'] ) || ! is_string( $m['collection'] ) || '' === $m['collection'] || $m['collection'] !== $path_collection ) {
339 return new WP_Error( 'woo_rxdb_sync_bad_collection', 'collection must match the path collection.', array( 'status' => 400 ) );
340 }
341 if ( ! isset( $m['recordId'] ) || ! is_string( $m['recordId'] ) || ! Pos_Uuid::is_uuid( $m['recordId'] ) ) {
342 return new WP_Error( 'woo_rxdb_sync_bad_record_id', 'recordId must be a uuid.', array( 'status' => 400 ) );
343 }
344 if ( ! array_key_exists( 'baseRevision', $m ) || ( ! is_string( $m['baseRevision'] ) && null !== $m['baseRevision'] ) ) {
345 return new WP_Error( 'woo_rxdb_sync_bad_base_revision', 'baseRevision must be a string or null.', array( 'status' => 400 ) );
346 }
347 if ( 'delete' === $m['operation'] ) {
348 if ( array_key_exists( 'force', $m ) && ! is_bool( $m['force'] ) ) {
349 return new WP_Error( 'woo_rxdb_sync_bad_payload', 'force must be a boolean.', array( 'status' => 400 ) );
350 }
351 if ( array_key_exists( 'payload', $m ) ) {
352 return new WP_Error( 'woo_rxdb_sync_bad_payload', 'payload is forbidden for delete.', array( 'status' => 400 ) );
353 }
354 } else {
355 if ( array_key_exists( 'force', $m ) ) {
356 return new WP_Error( 'woo_rxdb_sync_bad_payload', 'force is only allowed for delete.', array( 'status' => 400 ) );
357 }
358 if ( ! isset( $m['payload'] ) || ! is_array( $m['payload'] ) || ( ! empty( $m['payload'] ) && array_values( $m['payload'] ) === $m['payload'] ) ) {
359 return new WP_Error( 'woo_rxdb_sync_bad_payload', 'payload must be an object.', array( 'status' => 400 ) );
360 }
361 // A payload that carries its own uuid must agree with recordId — never re-key.
362 $payload_uuid = Pos_Uuid::read_valid_uuid_from_meta(
363 isset( $m['payload']['meta_data'] ) && is_array( $m['payload']['meta_data'] ) ? $m['payload']['meta_data'] : array()
364 );
365 if ( '' !== $payload_uuid && $payload_uuid !== $m['recordId'] ) {
366 return new WP_Error( 'woo_rxdb_sync_identity_conflict', 'payload uuid disagrees with recordId.', array( 'status' => 422 ) );
367 }
368 }
369 return null;
370 }
371
372 private function apply_create( string $collection, array $meta, array $m ) {
373 $writer = $this->writer( $meta );
374 $prepared = $writer->prepare_create( $meta, $m['payload'], \Closure::fromCallable( array( $this, 'validate_tax_ids_payload' ) ) );
375 if ( ! is_array( $prepared ) ) {
376 return $prepared;
377 }
378
379 // Born-twice guard: reuse the record that already owns this uuid.
380 $existing = $this->store->resolve_id_by_uuid( $meta['id_type'], $m['recordId'], $meta );
381 if ( is_wp_error( $existing ) ) {
382 return $existing;
383 }
384 if ( $existing > 0 ) {
385 $valid = $writer->validate_existing_create( $existing, $m['payload'], $prepared );
386 if ( null !== $valid ) {
387 return $valid;
388 }
389 $finalized = $this->checkpoint_and_finalize( $m['mutationId'], $existing, 200 );
390 if ( is_wp_error( $finalized ) ) {
391 return $finalized;
392 }
393 return $this->envelope_document( $this->document_for( $meta, $existing ), $m['recordId'], $meta, $existing, null, $writer );
394 }
395
396 $response = $writer->forward( $prepared, \Closure::fromCallable( array( $this, 'forward' ) ) );
397 if ( is_wp_error( $response ) ) {
398 return $response;
399 }
400 $data = $response->get_data();
401 if ( $response->get_status() >= 400 ) {
402 return new WP_REST_Response( $data, $response->get_status() );
403 }
404 $new_id = (int) ( is_array( $data ) ? ( $data['id'] ?? 0 ) : 0 );
405 if ( $new_id <= 0 ) {
406 $this->store->mark_indeterminate( $m['mutationId'], 0, $response->get_status() );
407 return new WP_Error( 'woo_rxdb_sync_create_no_id', 'Create returned no server id.', array( 'status' => 502 ) );
408 }
409
410 // Poison checkpoint, UUID persistence, and finalization remain shared here.
411 $checkpointed = $this->store->mark_poison( $m['mutationId'], $new_id, $response->get_status() );
412 $writer->persist( 'create_before_identity', $new_id, $m['payload'] );
413 $identity_error = null;
414 if ( ! $this->store->persist_uuid( $meta['id_type'], $new_id, $m['recordId'] ) ) {
415 $identity_error = new WP_Error( 'woo_rxdb_sync_identity_persistence_failed', 'Unable to persist created record identity.', array( 'status' => 500 ) );
416 } else {
417 $resolved = $this->store->resolve_id_by_uuid( $meta['id_type'], $m['recordId'], $meta );
418 if ( is_wp_error( $resolved ) ) {
419 $identity_error = $resolved;
420 } elseif ( $resolved !== $new_id ) {
421 $identity_error = new WP_Error( 'woo_rxdb_sync_identity_persistence_failed', 'Unable to persist created record identity.', array( 'status' => 500 ) );
422 }
423 }
424 if ( ! $checkpointed ) {
425 $this->store->mark_indeterminate( $m['mutationId'], $new_id, $response->get_status() );
426 return $this->finalize_error();
427 }
428 if ( $identity_error ) {
429 return $identity_error;
430 }
431 $writer->persist( 'create_after_identity', $new_id, $m['payload'] );
432 if ( ! $this->store->finalize_poison( $m['mutationId'], $new_id ) ) {
433 return $this->finalize_error();
434 }
435 return $this->envelope_document( $this->document_for( $meta, $new_id ), $m['recordId'], $meta, $new_id, $response->get_status(), $writer );
436 }
437
438 /**
439 * The pre-CAS post-type capability gate shared by the update and delete paths.
440 *
441 * Only the WP-post-backed collections carry a Woo capability check of their own;
442 * every other collection is gated by the endpoint permission callback alone, so
443 * this is a no-op for them.
444 *
445 * @param array $meta Resolved collection metadata (carries the post_type, if any).
446 * @param int $id Resolved record id.
447 * @param string $verb Woo permission context: 'edit' or 'delete'.
448 *
449 * @return WP_Error|null The refusal to return, or null when the write may proceed.
450 */
451 private function post_permission_error( array $meta, int $id, string $verb ): ?WP_Error {
452 $post_type = (string) ( $meta['post_type'] ?? '' );
453 if ( ! \in_array( $post_type, array( 'product', 'product_variation', 'shop_coupon' ), true )
454 || wc_rest_check_post_permissions( $post_type, $verb, $id ) ) {
455 return null;
456 }
457 $status = array( 'status' => rest_authorization_required_code() );
458 if ( 'delete' === $verb ) {
459 return new WP_Error( 'woocommerce_rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'woocommerce' ), $status );
460 }
461 return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'woocommerce' ), $status );
462 }
463
464 private function apply_update( string $collection, array $meta, array $m ) {
465 $id = $this->store->resolve_id_by_uuid( $meta['id_type'], $m['recordId'], $meta );
466 if ( is_wp_error( $id ) ) {
467 return $id;
468 }
469 if ( 0 === $id ) {
470 return new WP_Error( 'woo_rxdb_sync_record_not_found', 'No record for recordId.', array( 'status' => 404 ) );
471 }
472 $permission_error = $this->post_permission_error( $meta, $id, 'edit' );
473 if ( $permission_error ) {
474 return $permission_error;
475 }
476
477 $writer = $this->writer( $meta );
478 $prepared = $writer->prepare_update( $meta, $id, $m['payload'], \Closure::fromCallable( array( $this, 'validate_tax_ids_payload' ) ) );
479 if ( ! is_array( $prepared ) ) {
480 return $prepared;
481 }
482 if ( null === $m['baseRevision'] ) {
483 return new WP_REST_Response(
484 array(
485 'code' => 'woo_rxdb_sync_revision_required',
486 'message' => 'Updating an existing record requires an If-Match / baseRevision precondition.',
487 ),
488 428
489 );
490 }
491
492 $current = $this->document_for( $meta, $id );
493 if ( ! ( $current instanceof WP_REST_Response ) || $current->get_status() >= 400 ) {
494 return $current;
495 }
496 $current_bare = is_array( $current->get_data() ) ? $current->get_data() : array();
497 $current_revision = $this->revision_for( $meta, $id, $current_bare );
498 if ( $m['baseRevision'] !== $current_revision ) {
499 return new WP_REST_Response(
500 array(
501 'code' => 'woo_rxdb_sync_conflict',
502 'message' => 'baseRevision is stale.',
503 'current' => $current->get_data(),
504 'currentRevision' => $current_revision,
505 ),
506 409
507 );
508 }
509 if ( isset( $prepared['context_factory'] ) && is_callable( $prepared['context_factory'] ) ) {
510 $late = $prepared['context_factory']();
511 $prepared['payload'] = $late['payload'];
512 $prepared['context'] = $late['context'];
513 }
514
515 $response = $writer->forward( $prepared, \Closure::fromCallable( array( $this, 'forward' ) ) );
516 if ( is_wp_error( $response ) ) {
517 return $response;
518 }
519 if ( $response->get_status() >= 400 ) {
520 return new WP_REST_Response( $response->get_data(), $response->get_status() );
521 }
522 $data = $response->get_data();
523 $writer->persist( 'update', $id, $m['payload'], $current_bare, is_array( $data ) ? $data : array(), $prepared['context'] );
524
525 $this->store->persist_uuid( $meta['id_type'], $id, $m['recordId'] );
526 $finalized = $this->checkpoint_and_finalize( $m['mutationId'], $id, $response->get_status() );
527 if ( is_wp_error( $finalized ) ) {
528 return $finalized;
529 }
530 return $this->envelope_document( $this->document_for( $meta, $id ), $m['recordId'], $meta, $id, null, $writer );
531 }
532
533 private function apply_delete( string $collection, array $meta, array $m ) {
534 $id = $this->store->resolve_id_by_uuid( $meta['id_type'], $m['recordId'], $meta );
535 if ( is_wp_error( $id ) ) {
536 return $id;
537 }
538 if ( 0 === $id ) {
539 $finalized = $this->checkpoint_and_finalize( $m['mutationId'], 0, 200 );
540 return is_wp_error( $finalized ) ? $finalized : new WP_REST_Response( (object) array(), 200 );
541 }
542 $permission_error = $this->post_permission_error( $meta, $id, 'delete' );
543 if ( $permission_error ) {
544 return $permission_error;
545 }
546 if ( null === $m['baseRevision'] ) {
547 return new WP_REST_Response(
548 array(
549 'code' => 'woo_rxdb_sync_precondition_required',
550 'message' => 'Deleting an existing record requires an If-Match / baseRevision precondition.',
551 ),
552 428
553 );
554 }
555
556 $writer = $this->writer( $meta );
557 $current = $this->document_for( $meta, $id );
558 if ( ! ( $current instanceof WP_REST_Response ) || $current->get_status() >= 400 ) {
559 return $current;
560 }
561 $current_bare = is_array( $current->get_data() ) ? $current->get_data() : array();
562 $current_revision = $this->revision_for( $meta, $id, $current_bare );
563 if ( $m['baseRevision'] !== $current_revision ) {
564 return new WP_REST_Response(
565 array(
566 'code' => 'woo_rxdb_sync_conflict',
567 'message' => 'baseRevision is stale.',
568 'current' => $current->get_data(),
569 'currentRevision' => $current_revision,
570 ),
571 409
572 );
573 }
574
575 $response = $writer->delete( $meta, $id, $m, \Closure::fromCallable( array( $this, 'dispatch_write' ) ), \Closure::fromCallable( array( $this, 'can_forward_delete' ) ) );
576 if ( is_wp_error( $response ) ) {
577 return $response;
578 }
579 if ( $response->get_status() >= 400 ) {
580 return new WP_REST_Response( $response->get_data(), $response->get_status() );
581 }
582 $finalized = $this->checkpoint_and_finalize( $m['mutationId'], $id, $response->get_status() );
583 return is_wp_error( $finalized ) ? $finalized : new WP_REST_Response( (object) array(), 200 );
584 }
585
586 /**
587 * Whether the forwarded wc/v3 order delete would pass its capability gate.
588 *
589 * Asks the SAME question the forward will, under the same
590 * `woocommerce_rest_check_permissions` filter `dispatch_write()` installs, so the
591 * pre-flight and the forward can never disagree. Used only to keep the stock
592 * pre-restore off a delete that is going to be refused.
593 *
594 * @param int $id The order id.
595 */
596 private function can_forward_delete( int $id ): bool {
597 Permission_Rules::install_wc_filter();
598 try {
599 return (bool) wc_rest_check_post_permissions( 'shop_order', 'delete', $id );
600 } finally {
601 Permission_Rules::uninstall_wc_filter();
602 }
603 }
604
605 private function checkpoint_and_finalize( string $mutation_id, int $remote_id, int $response_status ) {
606 if ( ! $this->store->mark_applied( $mutation_id, $remote_id, $response_status ) ) {
607 return $this->finalize_error();
608 }
609 if ( ! $this->store->finalize( $mutation_id, $remote_id ) ) {
610 return $this->finalize_error();
611 }
612 return null;
613 }
614
615 private function finalize_error(): WP_Error {
616 return new WP_Error( 'woo_rxdb_sync_finalize_failed', 'Woo write succeeded but mutation finalization failed; retry the same mutationId.', array( 'status' => 500 ) );
617 }
618
619 private function replay( array $meta, array $hit ) {
620 if ( 'delete' === ( $hit['operation'] ?? '' ) || 0 === (int) ( $hit['remote_id'] ?? 0 ) ) {
621 return new WP_REST_Response( (object) array(), 200 );
622 }
623 $remote_id = (int) $hit['remote_id'];
624 $expected = (string) ( $hit['record_uuid'] ?? '' );
625 // Verify the recorded record still EXISTS and still owns this uuid. We check
626 // via the uuid→id resolver (not the wc/v3 response, which omits the protected
627 // _woocommerce_pos_uuid meta): if the uuid no longer maps to the recorded id,
628 // the record was deleted out-of-band / its id was reused — return 410.
629 if ( '' !== $expected ) {
630 $resolved = $this->store->resolve_id_by_uuid( $meta['id_type'], $expected, $meta );
631 if ( is_wp_error( $resolved ) ) {
632 return $resolved; // ambiguous identity (uuid now on >1 record) — surface 409, not a false 410-orphan
633 }
634 if ( $resolved !== $remote_id ) {
635 return new WP_Error( 'woo_rxdb_sync_orphaned_mutation', 'Recorded mutation no longer matches its record.', array( 'status' => 410 ) );
636 }
637 }
638 $status = isset( $hit['response_status'] )
639 ? (int) $hit['response_status']
640 : ( 'create' === ( $hit['operation'] ?? '' ) ? 201 : null );
641 $writer = $this->writer( $meta );
642 return $this->envelope_document( $this->document_for( $meta, $remote_id ), $expected, $meta, $remote_id, $status, $writer );
643 }
644
645 private function retry_identity_stamp( array $meta, array $m, array $hit ) {
646 $remote_id = (int) ( $hit['remote_id'] ?? 0 );
647 $record_uuid = (string) ( $hit['record_uuid'] ?? '' );
648 if ( $record_uuid !== $m['recordId'] ) {
649 return new WP_Error( 'woo_rxdb_sync_identity_conflict', 'recordId disagrees with the stored mutation identity.', array( 'status' => 422 ) );
650 }
651 if ( 'create' !== ( $hit['operation'] ?? '' ) || $remote_id <= 0 ) {
652 return new WP_Error( 'woo_rxdb_sync_identity_persistence_failed', 'Created record identity cannot be recovered safely.', array( 'status' => 500 ) );
653 }
654 $resolved = $this->store->resolve_id_by_uuid( $meta['id_type'], $record_uuid, $meta );
655 if ( is_wp_error( $resolved ) ) {
656 return $resolved;
657 }
658 if ( $resolved > 0 && $resolved !== $remote_id ) {
659 return new WP_Error( 'woo_rxdb_sync_identity_persistence_failed', 'Stored create identity points at a different record.', array( 'status' => 500 ) );
660 }
661 if ( ! $this->store->persist_uuid( $meta['id_type'], $remote_id, $record_uuid ) ) {
662 return new WP_Error( 'woo_rxdb_sync_identity_persistence_failed', 'Unable to persist created record identity.', array( 'status' => 500 ) );
663 }
664 $verified = $this->store->resolve_id_by_uuid( $meta['id_type'], $record_uuid, $meta );
665 if ( is_wp_error( $verified ) ) {
666 return $verified;
667 }
668 if ( $verified !== $remote_id ) {
669 return new WP_Error( 'woo_rxdb_sync_identity_persistence_failed', 'Unable to persist created record identity.', array( 'status' => 500 ) );
670 }
671 $writer = $this->writer( $meta );
672 $writer->persist( 'create_recovery', $remote_id, $m['payload'] );
673 if ( ! $this->store->finalize_poison( $m['mutationId'], $remote_id ) ) {
674 return $this->finalize_error();
675 }
676 $status = isset( $hit['response_status'] ) ? (int) $hit['response_status'] : 201;
677 return $this->envelope_document( $this->document_for( $meta, $remote_id ), $record_uuid, $meta, $remote_id, $status, $writer );
678 }
679
680 /**
681 * Validate a client-submitted `tax_ids` payload against the v1 schema.
682 *
683 * tax_ids is unknown to the stock wc/v3 controllers and is stripped before the forward,
684 * so wc/v3 never validates it. The v1 controllers (Orders_Controller::wcpos_get_item_schema,
685 * Customers_Controller) exposed a TaxId[] schema (typed enum, string value, nullable
686 * country/label) that WordPress enforced on every create/update; reproduce that check here
687 * for both orders and customers so malformed or unsupported entries are rejected with a
688 * 400 instead of being silently dropped by Tax_Id_Writer.
689 *
690 * @param array $payload Mutation payload.
691 *
692 * @return null|WP_Error null when tax_ids is absent or valid; WP_Error (400) otherwise.
693 */
694 private function validate_tax_ids_payload( array $payload ) {
695 if ( ! array_key_exists( 'tax_ids', $payload ) ) {
696 return null;
697 }
698 $schema = array(
699 'type' => 'array',
700 'items' => array(
701 'type' => 'object',
702 // value/type are required: Tax_Id_Writer silently drops an entry with no value and
703 // rewrites a missing type to `other`, so an accepted-but-mutated ack would diverge
704 // from the submitted IDs. Require them so the API returns a 400 instead.
705 'required' => array( 'value', 'type' ),
706 'properties' => array(
707 'type' => array(
708 'type' => 'string',
709 'enum' => Tax_Id_Types::all_types(),
710 ),
711 'value' => array(
712 'type' => 'string',
713 ),
714 'country' => array(
715 'type' => array( 'string', 'null' ),
716 ),
717 'label' => array(
718 'type' => array( 'string', 'null' ),
719 ),
720 ),
721 ),
722 );
723 $valid = rest_validate_value_from_schema( $payload['tax_ids'], $schema, 'tax_ids' );
724 if ( is_wp_error( $valid ) ) {
725 return new WP_Error( 'woocommerce_pos_rest_invalid_tax_ids', $valid->get_error_message(), array( 'status' => 400 ) );
726 }
727 return null;
728 }
729 private function forward( string $method, string $route, $payload ) {
730 $request = new WP_REST_Request( $method, $route );
731 if ( is_array( $payload ) ) {
732 // The route id (resolved server-side from the uuid) is authoritative — never
733 // let a client-supplied body `id` override it or pin a create's id. The
734 // v2 header is likewise the only authority for the legacy store param.
735 unset( $payload['id'], $payload[ Store_Scope::PARAM ] );
736 $request->set_body_params( $payload );
737 }
738 return $this->dispatch_write( $request );
739 }
740
741 /**
742 * Dispatch one raw WooCommerce mutation with the client-tier grant scoped to it.
743 *
744 * @return WP_REST_Response
745 */
746 private function dispatch_write( WP_REST_Request $request ) {
747 // Stamp here so direct callers (notably deletes) carry the scope too.
748 Store_Scope::stamp( $request );
749 Permission_Rules::install_wc_filter();
750 try {
751 // Marked as OUR traffic for the duration of the forward, so a consumer
752 // keyed on store scope can act on a till write without also claiming
753 // every stock wc/v3 product write on the site (pro#425 review).
754 return Store_Scope::in_v2_lane(
755 static function () use ( $request ) {
756 return rest_do_request( $request );
757 }
758 );
759 } finally {
760 Permission_Rules::uninstall_wc_filter();
761 }
762 }
763
764 /** @deprecated Use Permission_Rules::wc_filter(). */
765 public function wcpos_check_permissions( $permission, $context, $object_id, $post_type ) {
766 return Permission_Rules::wc_filter( $permission, $context, $object_id, $post_type, 'writes' );
767 }
768
769 /**
770 * Read this collection's document for one record, through its writer.
771 *
772 * The single place the writer's document step is invoked. Kept as a named
773 * method rather than inlined at each call site because it is also the seam
774 * Test_Rest_Dispatch_Write_Contract and Test_Sync_Hook_Isolation reach for
775 * to pin the variation parent-route and re-read-price behaviours.
776 *
777 * @param array $meta Collection meta for the record.
778 * @param int $id Record id.
779 *
780 * @return mixed
781 */
782 private function document_for( array $meta, int $id ) {
783 return $this->writer( $meta )->document( $meta, $id, \Closure::fromCallable( array( $this, 'default_document_for' ) ) );
784 }
785
786 /** Read and normalize a generic wc/v3 response document. */
787 private function default_document_for( array $meta, int $id, array $params = array() ) {
788 $request = new WP_REST_Request( 'GET', $meta['route'] . '/' . $id );
789 Store_Scope::stamp( $request );
790 foreach ( $params as $key => $value ) {
791 $request->set_param( $key, $value );
792 }
793 $response = Store_Scope::in_v2_lane(
794 static function () use ( $request ) {
795 return rest_do_request( $request );
796 }
797 );
798 $data = $response->get_data();
799 if ( is_array( $data ) ) {
800 $response->set_data( Meta_Normalizer::normalize( $data ) );
801 }
802 return $response;
803 }
804
805 /** Apply generic product augmentation and inject the client UUID. */
806 private function default_response_document( array $bare, string $record_id, array $meta, int $id ): array {
807 if ( 'product' === ( $meta['post_type'] ?? '' ) ) {
808 $product = wc_get_product( $id );
809 if ( $product ) {
810 $bare = Product_Serializer::augment( $bare, $product, new WP_REST_Request( 'GET', $meta['route'] . '/' . $id ) );
811 }
812 }
813 return Pos_Uuid::ensure_in_payload( $bare, $record_id );
814 }
815
816 /** Wrap a collection document in the unchanged mutation response envelope. */
817 private function respond( array $bare, string $record_id, int $status, array $meta, int $id, $writer ) {
818 $current_revision = $this->revision_for( $meta, $id, $bare );
819 $document = $writer->build_response_document(
820 $bare,
821 $record_id,
822 $meta,
823 $id,
824 \Closure::fromCallable( array( $this, 'default_response_document' ) )
825 );
826 return new WP_REST_Response(
827 array(
828 'document' => $document,
829 'currentRevision' => $current_revision,
830 ),
831 $status
832 );
833 }
834
835 /**
836 * Wrap a collection document in the write-ack envelope.
837 *
838 * $status and $writer default so the four-argument form still resolves —
839 * Test_Sync_Hook_Isolation reaches this method by reflection to pin the
840 * variation re-read price behaviour.
841 *
842 * @param mixed $document Document to envelope.
843 * @param string $record_id Client record id.
844 * @param array $meta Collection meta for the record.
845 * @param int $id Record id.
846 * @param int|null $status Status to report, or null to use the document's.
847 * @param object|null $writer Writer for the collection, resolved from $meta when null.
848 *
849 * @return mixed
850 */
851 private function envelope_document( $document, string $record_id, array $meta, int $id, ?int $status = null, $writer = null ) {
852 if ( ! ( $document instanceof WP_REST_Response ) || $document->get_status() >= 400 ) {
853 return $document;
854 }
855 $writer = $writer ?? $this->writer( $meta );
856 $bare = $document->get_data();
857 return $this->respond( is_array( $bare ) ? $bare : array(), $record_id, $status ?? $document->get_status(), $meta, $id, $writer );
858 }
859
860 private function revision_for( array $meta, int $id, array $bare ): string {
861 if ( 'product_variation' === ( $meta['post_type'] ?? '' ) ) {
862 /*
863 * A variation's revision is its `date_modified_gmt`, deliberately: the client's targeted
864 * pull synthesizes exactly that as `sync.revision`, so both sides agree without the
865 * variations lane needing a stamped `_rxdb_revision`.
866 *
867 * Read the date from WHEREVER it is — nested under `payload` in today's
868 * `{ id, parent_id, payload }` wrapper, or top level once that wrapper is dropped.
869 *
870 * This used to read `$bare['payload']['date_modified_gmt']` only, with `$bare['id']` as
871 * the fallback. Against a FLAT document that silently degrades to the variation's own
872 * ID — a value that never changes again. The failure would be total and invisible:
873 * the ack would hand the client the id as `currentRevision`, and from then on every
874 * stale baseRevision would equal every recomputed one — the strict revision
875 * comparison would pass every queued write. Two tills editing the same
876 * variation hours apart would both pass the precondition; the per-record lock would
877 * serialize them, so there would be no error — just a lost update, every time.
878 *
879 * The `$bare['id']` fallback is kept ONLY for a document carrying no date at all, and is
880 * now unreachable for any real variation serialization.
881 */
882 $payload = isset( $bare['payload'] ) && is_array( $bare['payload'] ) ? $bare['payload'] : array();
883 $date = $payload['date_modified_gmt'] ?? $bare['date_modified_gmt'] ?? null;
884
885 return (string) ( $date ?? $bare['id'] ?? $id );
886 }
887 if ( 'order' === ( $meta['id_type'] ?? '' ) && $id > 0 ) {
888 return Order_Serializer::canonical_revision( $bare );
889 }
890 return Revision::compute( $bare );
891 }
892 }
893