resolver = $resolver ?? new AssignmentResolver(); } /** * @param string $generator Generator key. * @param array $blueprint_id_by_slot Slot key => its Blueprint id, or null for a built-in slot (the 'default' key is always present). * @param array> $rows This generator's assignment rows, already fetched by the caller (passed straight into every resolve() call). * @return array,automationJobs:int}> Slot key => its tally. */ public function tally( string $generator, array $blueprint_id_by_slot, array $rows ): array { $tallies = array(); foreach ( array_keys( $blueprint_id_by_slot ) as $slot_key ) { $tallies[ $slot_key ] = array( 'subjects' => 0, 'approximate' => false, 'sample' => array(), 'automationJobs' => 0 ); } $is_taxonomy = Generators::TAXONOMY === $generator; $pool = $is_taxonomy ? $this->termPool() : $this->productPool(); $subject_type = $is_taxonomy ? 'term' : 'product'; foreach ( array_chunk( $pool['ids'], self::PRIME_CHUNK ) as $chunk ) { if ( ! $is_taxonomy ) { $this->primeProductCaches( $chunk ); } foreach ( $chunk as $id ) { $resolution = $this->resolver->resolve( $generator, array( 'type' => $subject_type, 'id' => $id ), null, null, $rows ); if ( is_wp_error( $resolution ) || null !== $resolution['conflict'] ) { continue; } $slot_key = $this->slotKeyFor( $resolution['blueprintId'], $blueprint_id_by_slot ); ++$tallies[ $slot_key ]['subjects']; if ( count( $tallies[ $slot_key ]['sample'] ) < self::SAMPLE_LIMIT ) { $tallies[ $slot_key ]['sample'][] = array( 'id' => $id, 'name' => (string) $resolution['subject']['label'] ); } } } if ( $pool['approximate'] ) { foreach ( $tallies as $slot_key => $tally ) { $tallies[ $slot_key ]['approximate'] = true; } } foreach ( $this->automationJobCounts( $generator, $blueprint_id_by_slot ) as $slot_key => $count ) { $tallies[ $slot_key ]['automationJobs'] = $count; } return $tallies; } /** * Which slot a resolved Blueprint id belongs to. A real Blueprint id * that matches no current slot (it duplicates the default's own * Blueprint, which the slot list excludes from the exceptions it * lists) still counts as 'default': that is the structure the content * is actually written with. * * @param int|null $blueprint_id Resolution's blueprintId (null = built-in). * @param array $blueprint_id_by_slot Slot key => its Blueprint id. * @return string */ private function slotKeyFor( ?int $blueprint_id, array $blueprint_id_by_slot ): string { foreach ( $blueprint_id_by_slot as $slot_key => $slot_blueprint_id ) { if ( $slot_blueprint_id === $blueprint_id ) { return $slot_key; } } return 'default'; } /** * Warm the term and product caches for one chunk of product ids, the * same way {@see \AIPT\Core\ContentStructure\Assignment\AssignmentScope} * does before it resolves a batch. * * @param int[] $product_ids Product ids to prime. * @return void */ private function primeProductCaches( array $product_ids ): void { if ( empty( $product_ids ) ) { return; } if ( function_exists( 'update_object_term_cache' ) ) { update_object_term_cache( $product_ids, 'product' ); } if ( function_exists( 'wc_get_products' ) ) { wc_get_products( array( 'include' => $product_ids, 'return' => 'objects', 'limit' => -1, ) ); } } /** * Every published product id, bounded by SCAN_CAP. Mirrors * {@see \AIPT\Core\ContentStructure\Assignment\AssignmentScope::allPublishedProductIds()} * (kept separate rather than shared: that method is private, and this * scan always wants the full store-default-sized pool, never a * caller-supplied smaller limit). * * @return array{ids:int[],approximate:bool} */ private function productPool(): array { if ( ! function_exists( 'wc_get_products' ) ) { return array( 'ids' => array(), 'approximate' => false ); } $ids = array_map( 'intval', (array) wc_get_products( array( 'limit' => self::SCAN_CAP + 1, 'return' => 'ids', 'status' => array( 'publish' ), 'orderby' => 'ID', 'order' => 'ASC', ) ) ); $approximate = count( $ids ) > self::SCAN_CAP; if ( $approximate ) { $ids = array_slice( $ids, 0, self::SCAN_CAP ); } return array( 'ids' => $ids, 'approximate' => $approximate ); } /** * Every term id across the taxonomy generator's own taxonomies * ({@see TaxonomyDiscoveryService}, which already excludes internal and * attribute taxonomies — unlike `get_object_taxonomies('product')`), * bounded by SCAN_CAP across every taxonomy combined. * * @return array{ids:int[],approximate:bool} */ private function termPool(): array { if ( ! function_exists( 'get_terms' ) ) { return array( 'ids' => array(), 'approximate' => false ); } $ids = array(); $approximate = false; foreach ( ( new TaxonomyDiscoveryService() )->discoverTaxonomies() as $taxonomy ) { if ( count( $ids ) >= self::SCAN_CAP ) { $approximate = true; break; } $remaining = min( self::PER_TAXONOMY_FETCH_LIMIT, self::SCAN_CAP - count( $ids ) ); $found = get_terms( array( 'taxonomy' => $taxonomy['name'], 'hide_empty' => false, 'fields' => 'ids', 'number' => $remaining + 1, ) ); if ( ! is_array( $found ) ) { continue; } if ( count( $found ) > $remaining ) { $found = array_slice( $found, 0, $remaining ); $approximate = true; } foreach ( $found as $term_id ) { $ids[] = (int) $term_id; } } return array( 'ids' => $ids, 'approximate' => $approximate ); } /** * Active recurring jobs of this generator whose next cycle writes with * each slot: an own-structure job (no manual pick) counts for every * slot; a manual pick counts only for the slot naming that Blueprint; * an advanced-path job, or one with no structure choice saved, never * counts. "Active" means not failed and still due a future cycle * (`next_run` set) — a recurring job sitting at status 'completed' * between cycles is exactly that, waiting for its next tick, not done * forever (see JobScheduler::calculateNextRun()). * * @param string $generator Generator key. * @param array $blueprint_id_by_slot Slot key => its Blueprint id. * @return array Slot key => job count. */ private function automationJobCounts( string $generator, array $blueprint_id_by_slot ): array { $counts = array_fill_keys( array_keys( $blueprint_id_by_slot ), 0 ); $tool_type = Generators::automationToolType( $generator ); if ( '' === $tool_type ) { return $counts; } global $wpdb; $table = $wpdb->prefix . 'aipt_automation_jobs'; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT settings, schedule_config FROM {$table} WHERE tool_type = %s AND status != 'failed' AND next_run IS NOT NULL LIMIT %d", $tool_type, self::JOB_SCAN_LIMIT ), ARRAY_A ); foreach ( (array) $rows as $row ) { $schedule_config = json_decode( (string) ( $row['schedule_config'] ?? '' ), true ); if ( ! JobEntitlementGuard::isRecurring( is_array( $schedule_config ) ? $schedule_config : array() ) ) { continue; } $settings = json_decode( (string) ( $row['settings'] ?? '' ), true ); $blueprint = is_array( $settings ) && isset( $settings['blueprint'] ) && is_array( $settings['blueprint'] ) ? $settings['blueprint'] : null; if ( null === $blueprint || 'advanced' === (string) ( $blueprint['mode'] ?? '' ) ) { continue; } $manual_id = isset( $blueprint['manualBlueprintId'] ) && null !== $blueprint['manualBlueprintId'] ? (int) $blueprint['manualBlueprintId'] : null; if ( null === $manual_id ) { foreach ( array_keys( $counts ) as $slot_key ) { ++$counts[ $slot_key ]; } continue; } foreach ( $blueprint_id_by_slot as $slot_key => $slot_blueprint_id ) { if ( $slot_blueprint_id === $manual_id ) { ++$counts[ $slot_key ]; break; } } } return $counts; } }