PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.2
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.2
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 / API / V2 / Write_Controller.php

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

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