get_status() === 'draft' || // ...or if draft !get_option('aikanen_auto_export_product', false) || // ...or auto-sync not enabled isset(self::$queued[$productId]) // ...or product already queued on this request ) { return; } self::$queued[$productId] = true; // Mark as queued for this request // Cancel any pending job for this product and enqueue a fresh one with latest changes as_unschedule_action('aikanen_export_product', ['product_id' => $productId]); as_enqueue_async_action('aikanen_export_product', ['product_id' => $productId]); } // Handle export public function exportProduct(int $productId): void { $product = wc_get_product($productId); if (!$product) { // Product (no longer) found on WooCommerce return; } $aikanenId = $product->get_meta('_aikanen_service_id'); $payload = $this->productMapper->toAikanen($product); if ($aikanenId) { // Is synced - update try { $this->api->put("/services/{$aikanenId}", $payload); } catch (\RuntimeException $e) { return; // Service no longer exists in Aikanen } } else { // Not synced - save as new $response = $this->api->post('/services', $payload); $product->update_meta_data('_aikanen_service_id', $response['data']['id']); $product->save_meta_data(); $aikanenId = $response['data']['id']; // Attach to service groups on initial export if any categories of product are linked to a group (handled by onProductTermsSet for existing products) $groupIds = $this->productMapper->getServiceGroupIds($product); if (!empty($groupIds)) { try { $this->api->put("/services/{$aikanenId}/service-groups", ['service_group_ids' => $groupIds]); } catch (\RuntimeException $e) { // Service group no longer exists in Aikanen } } } $product->update_meta_data('_aikanen_last_synced', time()); $product->save_meta_data(); } // Export products to Aikanen in bulk public function handleBulkExport(string $redirectTo, string $action, array $productIds): string { if ($action !== 'export_to_aikanen') { return $redirectTo; } foreach ($productIds as $productId) { // Schedule export for products as_enqueue_async_action('aikanen_export_product', ['product_id' => (int) $productId]); } return add_query_arg('aikanen_exported', count($productIds), $redirectTo); } public function addBulkAction(array $actions): array { $actions['export_to_aikanen'] = __('Export to Aikanen', 'aikanen'); return $actions; } }