get_col(" SELECT pm.meta_value FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '_sku' AND pm.meta_value != '' AND p.post_type = 'product_variation' AND p.post_status IN ('publish', 'private') "); if (empty($skus)) { Log::write("BulkQuantityFetch: No WC products, skipping", Log::INFO, Log::CONTEXT_CRONJOB); return JobResult::success(); } $skuMap = array_flip($skus); unset($skus); Log::write("BulkQuantityFetch: Found " . count($skuMap) . " WC variations", Log::INFO, Log::CONTEXT_CRONJOB); // 2. Fetch API data $response = Api::external("GET", "/stockall?compress=0&output=json", ["timeout" => 300]); if ($response['code'] !== 200) { throw new ApiException($response['code'], "API error code " . $response['code']); } // 3. Parse + filter $decoded = json_decode($response['body'], true); if (!is_array($decoded)) { Log::write("BulkQuantityFetch: Invalid API response", Log::ERROR, Log::CONTEXT_CRONJOB); return JobResult::fail('Invalid API response'); } $matched = []; foreach ($decoded as $sku => $stockData) { if (isset($skuMap[$sku])) { // Only the fields BulkQuantityBatchHandler reads: keeps AS action args small $matched[] = [ 'sku' => $sku, 'available' => $stockData['available'] ?? 0, 'total_arrivals' => $stockData['total_arrivals'] ?? 0, 'supplier_1' => $stockData['supplier_1'] ?? 0, 'supplier_2' => $stockData['supplier_2'] ?? 0, ]; } } unset($skuMap); Log::write("BulkQuantityFetch: Matched " . count($matched) . " items", Log::INFO, Log::CONTEXT_CRONJOB); if (empty($matched)) { return JobResult::success(); } // 4. Chunk and create batch jobs (fresh data supersedes batches still pending from a previous run) $batches = JobQueue::chunkItemsByPayloadSize($matched); unset($matched); JobQueue::cancelByType('bulk_quantity_batch'); $queued = 0; foreach ($batches as $batch) { if (JobQueue::push('bulk_quantity_batch', ['items' => $batch], 40, null, 'quantity_sync')) { $queued++; } } Log::write("BulkQuantityFetch: Queued {$queued}/" . count($batches) . " batches", $queued === count($batches) ? Log::INFO : Log::ERROR, Log::CONTEXT_CRONJOB); update_option('_ACTIONWEAR_LAST_BULK_QUANTITY_SYNC', time()); return JobResult::success(); } }