client = $client ?? new AivieClient(); $this->contactMapper = $contactMapper ?? new ContactMapper(); $this->orderMapper = $orderMapper ?? new OrderMapper(); $this->retryScheduler = $retryScheduler ?? new RetryScheduler(); $this->resolver = $resolver ?? new TrackingContactResolver(); } public function syncOrder(int $orderId, bool $force = false): SyncResult { // 1. Load order. $order = wc_get_order($orderId); if (! $order instanceof \WC_Order) { Logger::error('Order sync failed because the order could not be loaded.', [ 'order_id' => $orderId, ]); return new SyncResult('error', "Order {$orderId} not found."); } // WC_Subscription extends WC_Order, so subscription IDs pass the instanceof // check above. Bail early — subscriptions are handled by SubscriptionSyncService. if (function_exists('wcs_is_subscription') && wcs_is_subscription($order)) { Logger::debug('Skipping order sync for a subscription.', [ 'order_id' => $orderId, ]); return new SyncResult('skipped', 'Subscriptions are handled by SubscriptionSyncService.'); } // 2. Plugin enabled. if (! $force && ! Options::isEnabled()) { Logger::debug('Order sync skipped because the plugin is disabled.', [ 'order_id' => $orderId, ]); return new SyncResult('skipped', 'Aivie plugin is disabled.'); } // 3. Settings present. if ('' === Options::getBaseUrl() || '' === Options::getBearerToken()) { Logger::error('Order sync failed because API settings are incomplete.', [ 'order_id' => $orderId, 'has_base_url' => '' !== Options::getBaseUrl(), 'has_token' => '' !== Options::getBearerToken(), ]); return new SyncResult('error', 'Aivie API URL or token is not configured.'); } // 4. Determine event ID (unique per emitted order state — see OrderMapper::buildEventId). $status = $order->get_status(); $eventId = $this->orderMapper->buildEventId($order); // Snapshot upstream event identity and time before Aivie metadata is // saved because WooCommerce HPOS advances date_modified on meta writes. $occurredAt = $this->orderMapper->resolveOccurredAt($order); Logger::info('Starting order sync.', [ 'order_id' => $orderId, 'status' => $status, 'event_id' => $eventId, 'force' => $force, ]); // 5. Skip if already synced with same event ID. if (! $force && $eventId === $order->get_meta('_aivie_wc_last_sync_event_id')) { Logger::debug('Order already synced with the same event ID, skipping.', [ 'order_id' => $orderId, 'event_id' => $eventId, ]); return new SyncResult('skipped', 'Already synced with this event ID.', eventId: $eventId); } // 6. Resolve tracking contact ID. $trackingId = $this->resolver->read($order); if ($trackingId > 0) { $order->update_meta_data('_aivie_original_tracking_id', $trackingId); } Logger::debug('Resolved contact for order sync.', [ 'order_id' => $orderId, 'has_tracking_id' => $trackingId > 0, 'tracking_id' => $trackingId, ]); // 7. Contact resolution (failures do not block order sync). $alreadyInAivie = absint($order->get_meta('_aivie_wc_order_id')) > 0; $applyActions = ! $alreadyInAivie || ! Options::getBool(Options::CONTACT_ACTIONS_NEW_ORDER_ONLY); $contactId = null; try { $contactPayload = $this->contactMapper->map($order); if (! $applyActions) { $contactPayload->setTags([]); } $contactId = $this->resolveCanonicalContactId($order, $trackingId, $contactPayload); if (null !== $contactId) { $order->update_meta_data('_aivie_contact_id', $contactId); $order->save(); if ($applyActions) { (new ContactActionService($this->client))->apply($contactId, [ 'order_id' => $orderId, ]); } else { Logger::debug('Skipping contact actions (tags, segments, campaigns) because order already exists in Aivie and "new order only" is enabled.', [ 'order_id' => $orderId, 'contact_id' => $contactId, ]); } Logger::debug('Saved canonical Aivie contact ID on order.', [ 'order_id' => $orderId, 'contact_id' => $contactId, ]); } } catch (\InvalidArgumentException $invalidContact) { // The generated models validate the API contract (enums, lengths, // minimums) in their setters; a violation must not fatal the hook. Logger::error('Contact payload violates the API contract; continuing with order sync.', [ 'order_id' => $orderId, 'message' => $invalidContact->getMessage(), ]); } // 8. Order sync. Use the right verb for the phase: POST /new is create-only // (409 if the order already exists), while the by-reference PATCH endpoint // upserts. Once Aivie has recorded the order, every later sync must PATCH. try { $orderPayload = $this->orderMapper->map($order, $occurredAt, $eventId); } catch (\InvalidArgumentException $invalidOrder) { Logger::error('Order payload violates the API contract.', [ 'order_id' => $orderId, 'message' => $invalidOrder->getMessage(), ]); return new SyncResult('error', 'Invalid order payload: ' . $invalidOrder->getMessage(), eventId: $eventId); } // Guard: WooCommerce can fire order hooks before line items are committed. // Renewal orders may still have a zero total at this point, so detect // subscription-created shells separately instead of relying only on total. if (! $force && $this->shouldDeferEmptyOrderSync($order, $orderPayload)) { $isRenewalOrder = $this->isSubscriptionRenewalOrder($order); $retryScheduled = $this->retryScheduler->maybeSchedule($order); Logger::warning('Skipping order sync: order items are not available yet.', [ 'order_id' => $orderId, 'total' => $order->get_total(), 'created_via' => $order->get_created_via(), 'renewal_order' => $isRenewalOrder, 'retry_scheduled' => $retryScheduled, ]); return new SyncResult( 'skipped', 'No items available yet; awaiting retry or re-trigger.', eventId: $eventId, retryScheduled: $retryScheduled ); } Logger::debug('Sending order payload to Aivie.', ObjectSerializer::toArray($orderPayload)); if ($alreadyInAivie) { Logger::debug('Order already recorded in Aivie; updating through the by-reference PATCH endpoint.', [ 'order_id' => $orderId, 'source' => $orderPayload->getSource(), 'order_reference_id' => $orderPayload->getOrderReferenceId(), ]); $orderResponse = $this->client->updateOrder( (string) $orderPayload->getSource(), (string) $orderPayload->getOrderReferenceId(), $force ? $this->buildReplayPayload($orderPayload) : $orderPayload ); if ($orderResponse->isNotFound()) { // Order was deleted on the Aivie side; unlink the local reference and // fall back to creating a new order so the next sync succeeds cleanly. Logger::debug('Aivie order no longer exists (deleted remotely); unlinking and creating as new order.', [ 'order_id' => $orderId, ]); $order->delete_meta_data('_aivie_wc_order_id'); $order->save_meta_data(); $orderResponse = $this->client->createOrder($orderPayload); } } else { $orderResponse = $this->client->createOrder($orderPayload); if ($orderResponse->isConflict()) { // Order exists in Aivie but we had no local record of it (e.g. created // out-of-band or first-sync metadata was lost). Fall back to PATCH. Logger::debug('Order already exists in Aivie; retrying through the by-reference PATCH endpoint.', [ 'order_id' => $orderId, 'source' => $orderPayload->getSource(), 'order_reference_id' => $orderPayload->getOrderReferenceId(), ]); $orderResponse = $this->client->updateOrder( (string) $orderPayload->getSource(), (string) $orderPayload->getOrderReferenceId(), $force ? $this->buildReplayPayload($orderPayload) : $orderPayload ); } } // 9. Persist sync metadata. $syncStatus = $this->resolveStatus($orderResponse); $this->saveSyncMeta($order, $syncStatus, $eventId, $orderResponse); Logger::debug('Saved Aivie sync metadata on order.', [ 'order_id' => $orderId, 'status' => $syncStatus, 'event_id' => $eventId, ]); // 10. Order note. $note = $this->buildOrderNote($syncStatus, $orderResponse); $order->add_order_note($note); // 11. Handle retries. $retryScheduled = false; if ('error' === $syncStatus && ($orderResponse->isServerError() || 0 === $orderResponse->httpCode)) { $retryScheduled = $this->retryScheduler->maybeSchedule($order); } if ('success' === $syncStatus || 'duplicate' === $syncStatus) { $this->retryScheduler->cancelPending($order); } $logContext = [ 'order_id' => $orderId, 'status' => $syncStatus, 'event_id' => $eventId, 'http_code' => $orderResponse->httpCode, 'retry_scheduled' => $retryScheduled, ]; if ('error' === $syncStatus) { Logger::error('Order sync failed.', $logContext + [ 'message' => $orderResponse->getSafeMessage(), ]); } else { Logger::info('Order sync finished.', $logContext); } return new SyncResult( status: $syncStatus, message: $orderResponse->getSafeMessage() ?: $syncStatus, contactId: $contactId, eventId: $eventId, retryScheduled: $retryScheduled, ); } private function resolveCanonicalContactId(\WC_Order $order, int $trackingId, object $contactPayload): ?int { $email = trim((string) $order->get_billing_email()); $emailContactId = '' !== $email ? $this->findContactIdByEmail($email) : null; $trackingExists = $trackingId > 0 && $this->contactExists($trackingId); if (null !== $emailContactId && $trackingExists && $emailContactId !== $trackingId) { Logger::debug('Merging tracking contact into existing billing-email contact.', [ 'order_id' => $order->get_id(), 'winner_id' => $emailContactId, 'loser_id' => $trackingId, ]); $mergeResponse = $this->client->mergeContacts($emailContactId, $trackingId); if ($mergeResponse->success) { return $this->extractContactId($mergeResponse->body) ?? $emailContactId; } Logger::error('Contact merge failed; using existing billing-email contact for order sync.', [ 'order_id' => $order->get_id(), 'http_code' => $mergeResponse->httpCode, 'message' => $mergeResponse->getSafeMessage(), ]); return $emailContactId; } if (null !== $emailContactId) { return $emailContactId; } if ($trackingExists) { Logger::debug('No existing contact found. Updating tracked Aivie contact before order sync.', [ 'order_id' => $order->get_id(), 'contact_id' => $trackingId, ]); $contactResponse = $this->client->updateContact($trackingId, $contactPayload); if (! $contactResponse->success && ! $contactResponse->isDuplicate()) { Logger::error('Tracked contact update failed; continuing with order sync.', [ 'order_id' => $order->get_id(), 'http_code' => $contactResponse->httpCode, 'message' => $contactResponse->getSafeMessage(), ]); } return $trackingId; } Logger::debug('No existing contact found. Creating Aivie contact before order sync.', [ 'order_id' => $order->get_id(), ]); $contactResponse = $this->client->createContact($contactPayload); if (! $contactResponse->success && ! $contactResponse->isDuplicate()) { Logger::error('Contact creation failed; continuing with order sync.', [ 'order_id' => $order->get_id(), 'http_code' => $contactResponse->httpCode, 'message' => $contactResponse->getSafeMessage(), ]); return null; } return $this->extractContactId($contactResponse->body); } private function shouldDeferEmptyOrderSync(\WC_Order $order, CreateOrderRequest $orderPayload): bool { if (! empty($orderPayload->getItems())) { return false; } if ((float) $order->get_total() > 0) { return true; } return $this->isSubscriptionRenewalOrder($order); } private function isSubscriptionRenewalOrder(\WC_Order $order): bool { $orderId = $order->get_id(); if (function_exists('wcs_order_contains_subscription') && wcs_order_contains_subscription($orderId, ['renewal'])) { return true; } if (function_exists('wcs_get_subscriptions_for_order')) { $subscriptions = wcs_get_subscriptions_for_order($orderId, ['order_type' => 'renewal']); if (is_array($subscriptions) && ! empty($subscriptions)) { return true; } } if ((int) $order->get_meta('_subscription_renewal') > 0) { return true; } return 'subscription' === $order->get_created_via(); } private function findContactIdByEmail(string $email): ?int { $response = $this->client->searchContactByEmail($email); if (! $response->success) { Logger::error('Contact lookup by billing email failed.', [ 'http_code' => $response->httpCode, 'message' => $response->getSafeMessage(), ]); return null; } foreach (($response->body['contacts'] ?? []) as $id => $contact) { if (! is_array($contact)) { continue; } $contactEmail = (string) ($contact['fields']['all']['email'] ?? $contact['email'] ?? ''); if ('' !== $contactEmail && strtolower($contactEmail) !== strtolower($email)) { continue; } $contactId = absint($contact['id'] ?? $id); if ($contactId > 0) { return $contactId; } } return null; } private function contactExists(int $contactId): bool { $response = $this->client->getContact($contactId); return $response->success && null !== $this->extractContactId($response->body); } private function extractContactId(array $body): ?int { $id = absint($body['winnerId'] ?? $body['contact']['id'] ?? $body['id'] ?? 0); return $id > 0 ? $id : null; } private function resolveStatus(AivieResponse $response): string { if ($response->isDuplicate()) { return 'duplicate'; } if ($response->success) { return 'success'; } return 'error'; } /** * Build a full-state PATCH for a forced replay without inventing a new * upstream lifecycle timestamp. The Commerce API inherits occurredAt from * the stored order when the field is omitted. */ private function buildReplayPayload(CreateOrderRequest $payload): UpdateOrderRequest { $data = ObjectSerializer::toArray($payload); unset($data['occurredAt']); return new UpdateOrderRequest($data); } private function saveSyncMeta(\WC_Order $order, string $status, string $eventId, AivieResponse $response): void { $order->update_meta_data('_aivie_wc_last_sync_status', $status); $order->update_meta_data('_aivie_wc_last_sync_type', $order->get_status()); $order->update_meta_data('_aivie_wc_last_sync_at', (new \DateTime('now', new \DateTimeZone('UTC')))->format(\DateTime::ATOM)); $order->update_meta_data('_aivie_wc_last_sync_event_id', $eventId); $order->update_meta_data('_aivie_wc_last_sync_response', $response->getSafeMessage(200)); $aivieOrderId = absint($response->body['order']['id'] ?? 0); if ($aivieOrderId > 0) { $order->update_meta_data('_aivie_wc_order_id', $aivieOrderId); } $order->save_meta_data(); } private function buildOrderNote(string $status, AivieResponse $response): string { $map = [ 'success' => __('Synced to Aivie successfully.', 'aivie-for-woocommerce'), 'duplicate' => __('Aivie: duplicate event, already recorded.', 'aivie-for-woocommerce'), 'error' => sprintf( /* translators: 1: HTTP status code, 2: error message. */ __('Aivie sync failed (HTTP %1$d): %2$s', 'aivie-for-woocommerce'), $response->httpCode, $response->getSafeMessage(150) ), ]; return $map[$status] ?? __('Aivie sync status unknown.', 'aivie-for-woocommerce'); } }