few large files"); this class * has no REST concerns of its own. * * @package AIPT\Core\ContentStructure\Rest * @since 2.8.0 */ namespace AIPT\Core\ContentStructure\Rest; use AIPT\Core\ContentStructure\Domain\DefinitionHasher; use AIPT\Core\ContentStructure\Domain\Generators; use AIPT\Core\ContentStructure\Domain\SectionCatalog; use AIPT\Core\ContentStructure\Storage\AssignmentStore; use AIPT\Core\ContentStructure\Storage\BlueprintStore; use AIPT\Core\ContentStructure\Storage\BrandProfileStore; use AIPT\Core\ContentStructure\Storage\SourceStore; use AIPT\Core\ContentStructure\Templates\TemplateCatalog; defined( 'ABSPATH' ) || exit; /** * Stateless shape builders for the BlueprintController responses. */ final class BlueprintShapes { /** * Automation job rows scanned per delete-impact call when looking for * non-terminal jobs whose pinned settings reference the Blueprint — * bounded, mirroring {@see \AIPT\Core\ContentStructure\Cleanup\BlueprintCleanup::PROTECTED_JOB_SCAN_LIMIT}. */ private const RUNNING_JOB_SCAN_LIMIT = 2000; /** * Running-job rows returned in one delete-impact response. */ private const RUNNING_JOB_RESULT_LIMIT = 50; /** * @param array $row Raw BlueprintStore row. * @param BrandProfileStore $brand_profiles Brand profile store. * @param AssignmentStore $assignments Assignment store. * @param array &$profile_cache Per-page brand-profile name cache (pass a fresh `array()` for a single row). * @return array BlueprintSummary. */ public static function summaryShape( array $row, BrandProfileStore $brand_profiles, AssignmentStore $assignments, array &$profile_cache ): array { $brand_profile = null; $brand_profile_id = (int) $row['brandProfileId']; if ( $brand_profile_id > 0 ) { if ( ! array_key_exists( $brand_profile_id, $profile_cache ) ) { $profile = $brand_profiles->get( $brand_profile_id ); $profile_cache[ $brand_profile_id ] = null !== $profile ? $profile['name'] : null; } if ( null !== $profile_cache[ $brand_profile_id ] ) { $brand_profile = array( 'id' => $brand_profile_id, 'name' => $profile_cache[ $brand_profile_id ] ); } } return array( 'id' => (int) $row['id'], 'name' => (string) $row['name'], 'generator' => (string) $row['generator'], 'status' => (string) $row['status'], 'brandProfile' => $brand_profile, 'usage' => self::usageShape( $assignments->listByBlueprint( (int) $row['id'] ), (string) $row['generator'] ), 'revision' => (int) $row['revision'], 'updatedAt' => self::isoDate( (string) $row['updatedAt'] ), 'updatedBy' => self::userSummary( (int) $row['updatedBy'] ), 'origin' => (string) $row['origin'], ); } /** * @param array $row Raw BlueprintStore row. * @param BrandProfileStore $brand_profiles Brand profile store. * @param AssignmentStore $assignments Assignment store. * @return array Blueprint (extends BlueprintSummary). */ public static function fullShape( array $row, BrandProfileStore $brand_profiles, AssignmentStore $assignments ): array { $profile_cache = array(); return self::summaryShape( $row, $brand_profiles, $assignments, $profile_cache ) + array( 'schemaVersion' => (int) $row['schemaVersion'], 'definition' => $row['definition'], 'definitionHash' => (string) $row['definitionHash'], 'createdAt' => self::isoDate( (string) $row['createdAt'] ), ); } /** * @param array> $assignment_rows Every row referencing this Blueprint (any generator). * @param string $generator The Blueprint's own generator. * @return array{storeDefault:bool,tagsSlot:bool,categories:int,products:int,terms:int,label:string} */ public static function usageShape( array $assignment_rows, string $generator ): array { $store_default = false; $tags_slot = false; $categories = 0; $products = 0; $terms = 0; foreach ( $assignment_rows as $row ) { if ( ( $row['generator'] ?? '' ) !== $generator ) { continue; } switch ( $row['targetType'] ?? '' ) { case 'store': $store_default = true; break; case 'taxonomy': $tags_slot = true; break; case 'category': $categories++; break; case 'product': $products++; break; case 'term': $terms++; break; } } $parts = array(); if ( $store_default ) { $parts[] = __( 'Store default', 'ai-product-tools' ); } if ( $tags_slot ) { $parts[] = __( 'Product tags', 'ai-product-tools' ); } if ( $categories > 0 ) { /* translators: %d: number of categories. */ $parts[] = sprintf( _n( '%d category', '%d categories', $categories, 'ai-product-tools' ), $categories ); } if ( $products > 0 ) { /* translators: %d: number of products. */ $parts[] = sprintf( _n( '%d product', '%d products', $products, 'ai-product-tools' ), $products ); } if ( $terms > 0 ) { /* translators: %d: number of terms. */ $parts[] = sprintf( _n( '%d term', '%d terms', $terms, 'ai-product-tools' ), $terms ); } return array( 'storeDefault' => $store_default, 'tagsSlot' => $tags_slot, 'categories' => $categories, 'products' => $products, 'terms' => $terms, 'label' => ! empty( $parts ) ? implode( ' · ', $parts ) : __( 'Not assigned', 'ai-product-tools' ), ); } /** * @param array $blueprint Raw BlueprintStore row. * @param AssignmentStore $assignments Assignment store. * @param SourceStore $sources Source store. * @param BlueprintStore $blueprints Blueprint store (names the Blueprint each row would fall back to). * @return array DeleteImpact. */ public static function computeImpact( array $blueprint, AssignmentStore $assignments, SourceStore $sources, BlueprintStore $blueprints ): array { $id = (int) $blueprint['id']; $generator = (string) $blueprint['generator']; $assignment_rows = $assignments->listByBlueprint( $id ); $remaining_rows = array_values( array_filter( $assignments->listForGenerator( $generator ), static function ( array $row ) use ( $id ): bool { return (int) ( $row['blueprintId'] ?? 0 ) !== $id; } ) ); $store_default_for = null; $tags_slot = false; $categories = array(); $products = array(); $terms = array(); foreach ( $assignment_rows as $row ) { if ( ( $row['generator'] ?? '' ) !== $generator ) { continue; } switch ( $row['targetType'] ?? '' ) { case 'store': $store_default_for = $generator; break; case 'taxonomy': $tags_slot = true; break; case 'category': $target_id = (int) $row['targetId']; $categories[] = array( 'id' => $target_id, 'label' => self::termLabel( $target_id, 'product_cat' ), 'fallbackAfterDelete' => self::fallbackForCategory( $generator, $target_id, $remaining_rows, $blueprints ), ); break; case 'product': $target_id = (int) $row['targetId']; $products[] = array( 'id' => $target_id, 'label' => self::productLabel( $target_id ), 'fallbackAfterDelete' => self::fallbackForProduct( $generator, $target_id, $remaining_rows, $blueprints ), ); break; case 'term': $target_id = (int) $row['targetId']; $taxonomy = (string) ( $row['taxonomy'] ?? '' ); $terms[] = array( 'id' => $target_id, 'label' => self::termLabel( $target_id, $taxonomy ), 'fallbackAfterDelete' => self::fallbackForTerm( $generator, $target_id, $taxonomy, $remaining_rows, $blueprints ), ); break; } } $source_rows = $sources->listByScope( 'blueprint', $id ); $source_list = array_map( static function ( array $source ): array { return array( 'id' => (int) $source['id'], 'name' => (string) $source['name'] ); }, $source_rows ); $impact_without_hash = array( 'blueprintId' => $id, 'storeDefaultFor' => $store_default_for, 'storeDefaultFallback' => null !== $store_default_for ? self::fallbackForBuiltinDefault( $generator ) : null, 'tagsSlot' => $tags_slot, 'tagsSlotFallback' => $tags_slot ? self::renderBroaderFallback( $generator, array(), '', $remaining_rows, $blueprints ) : null, 'categories' => $categories, 'products' => $products, 'terms' => $terms, 'sources' => $source_list, 'runningJobs' => self::runningJobsFor( $id ), ); $impact_without_hash['impactHash'] = hash( 'sha256', DefinitionHasher::canonicalJson( $impact_without_hash ) ); return $impact_without_hash; } /** * What a CATEGORY assignment falls back to once this Blueprint's own * rows (including this one) are deleted: the same "next matching * assignment, else the store default, else the built-in default * template" precedence * {@see \AIPT\Core\ContentStructure\Assignment\AssignmentResolver} * applies when resolving a real product — here restricted to the * tier that remains for this exact category once its own direct row is * gone: an ANCESTOR category assignment with `includeChildren` (a * sibling or child category assignment can never reach this one). * * @param string $generator Generator key. * @param int $category_id The category this Blueprint is directly assigned to. * @param array> $remaining_rows Every OTHER assignment row for this generator (this Blueprint's own rows already excluded). * @param BlueprintStore $blueprints Blueprint store, for the fallback Blueprint's name. * @return string */ private static function fallbackForCategory( string $generator, int $category_id, array $remaining_rows, BlueprintStore $blueprints ): string { $ancestors = function_exists( 'get_ancestors' ) ? array_map( 'intval', get_ancestors( $category_id, 'product_cat', 'taxonomy' ) ) : array(); $candidates = array_values( array_filter( $remaining_rows, static function ( array $row ) use ( $ancestors ): bool { return 'category' === ( $row['targetType'] ?? '' ) && ! empty( $row['includeChildren'] ) && in_array( (int) ( $row['targetId'] ?? 0 ), $ancestors, true ); } ) ); return self::renderBroaderFallback( $generator, $candidates, __( 'parent category', 'ai-product-tools' ), $remaining_rows, $blueprints ); } /** * What a PRODUCT assignment falls back to once this Blueprint's own * direct row is deleted: the product's own category tier — a category * it is directly in, or an ancestor category assigned with * `includeChildren` — exactly the "broader" tier * {@see \AIPT\Core\ContentStructure\Assignment\AssignmentResolver::broadRows()} * computes, else the store default, else the built-in default template. * * @param string $generator Generator key. * @param int $product_id The product this Blueprint is directly assigned to. * @param array> $remaining_rows Every OTHER assignment row for this generator. * @param BlueprintStore $blueprints Blueprint store. * @return string */ private static function fallbackForProduct( string $generator, int $product_id, array $remaining_rows, BlueprintStore $blueprints ): string { $category_ids = function_exists( 'wp_get_post_terms' ) ? array_map( 'intval', (array) wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) ) ) : array(); $ancestor_cache = array(); $candidates = array(); foreach ( $remaining_rows as $row ) { if ( 'category' !== ( $row['targetType'] ?? '' ) ) { continue; } $target_id = (int) ( $row['targetId'] ?? 0 ); if ( in_array( $target_id, $category_ids, true ) ) { $candidates[] = $row; continue; } if ( empty( $row['includeChildren'] ) ) { continue; } foreach ( $category_ids as $cat_id ) { if ( ! array_key_exists( $cat_id, $ancestor_cache ) ) { $ancestor_cache[ $cat_id ] = function_exists( 'get_ancestors' ) ? array_map( 'intval', get_ancestors( $cat_id, 'product_cat', 'taxonomy' ) ) : array(); } if ( in_array( $target_id, $ancestor_cache[ $cat_id ], true ) ) { $candidates[] = $row; break; } } } return self::renderBroaderFallback( $generator, $candidates, __( 'category', 'ai-product-tools' ), $remaining_rows, $blueprints ); } /** * What a TERM assignment (taxonomy generator) falls back to once this * Blueprint's own row is deleted — the term-tree equivalent of * {@see self::fallbackForCategory()}. * * @param string $generator Generator key. * @param int $term_id The term this Blueprint is directly assigned to. * @param string $taxonomy The term's taxonomy. * @param array> $remaining_rows Every OTHER assignment row for this generator. * @param BlueprintStore $blueprints Blueprint store. * @return string */ private static function fallbackForTerm( string $generator, int $term_id, string $taxonomy, array $remaining_rows, BlueprintStore $blueprints ): string { $ancestors = function_exists( 'get_ancestors' ) ? array_map( 'intval', get_ancestors( $term_id, $taxonomy, 'taxonomy' ) ) : array(); $candidates = array_values( array_filter( $remaining_rows, static function ( array $row ) use ( $taxonomy, $ancestors ): bool { return 'term' === ( $row['targetType'] ?? '' ) && (string) ( $row['taxonomy'] ?? '' ) === $taxonomy && ! empty( $row['includeChildren'] ) && in_array( (int) ( $row['targetId'] ?? 0 ), $ancestors, true ); } ) ); return self::renderBroaderFallback( $generator, $candidates, __( 'parent category', 'ai-product-tools' ), $remaining_rows, $blueprints ); } /** * Shared "broader tier -> store default -> built-in default" renderer * for the three fallback*() methods above. * * @param string $generator Generator key. * @param array> $candidates Broader-tier rows that could still reach this subject once this Blueprint's own row is gone. * @param string $tier_label The delete-impact sentence's parenthetical for a broader-tier win: 'category' or 'parent category'. * @param array> $remaining_rows Every OTHER assignment row for this generator (searched here for a store-default row). * @param BlueprintStore $blueprints Blueprint store. * @return string */ private static function renderBroaderFallback( string $generator, array $candidates, string $tier_label, array $remaining_rows, BlueprintStore $blueprints ): string { if ( ! empty( $candidates ) ) { $min_priority = min( array_map( static function ( array $row ): int { return (int) ( $row['priority'] ?? 10 ); }, $candidates ) ); $at_min = array_values( array_filter( $candidates, static function ( array $row ) use ( $min_priority ): bool { return (int) ( $row['priority'] ?? 10 ) === $min_priority; } ) ); $distinct_ids = array_values( array_unique( array_map( static function ( array $row ): int { return (int) $row['blueprintId']; }, $at_min ) ) ); if ( count( $distinct_ids ) > 1 ) { return __( 'More than one assignment would then apply at the same priority. Review assignments after deleting.', 'ai-product-tools' ); } $name = self::blueprintNameFor( $distinct_ids[0], $blueprints ); if ( '' !== $name ) { /* translators: 1: the template this falls back to, 2: "category" or "parent category". */ return sprintf( __( 'Falls back to %1$s (%2$s).', 'ai-product-tools' ), $name, $tier_label ); } } foreach ( $remaining_rows as $row ) { if ( 'store' === ( $row['targetType'] ?? '' ) ) { $name = self::blueprintNameFor( (int) $row['blueprintId'], $blueprints ); if ( '' !== $name ) { /* translators: %s: the template this falls back to. */ return sprintf( __( 'Falls back to %s (store default).', 'ai-product-tools' ), $name ); } break; } } return self::fallbackForBuiltinDefault( $generator ); } /** * @param string $generator Generator key. * @return string */ private static function fallbackForBuiltinDefault( string $generator ): string { $template = TemplateCatalog::get( $generator, TemplateCatalog::defaultKey( $generator ) ); $name = null !== $template ? (string) $template['name'] : TemplateCatalog::defaultKey( $generator ); /* translators: %s: the built-in template's name. */ return sprintf( __( 'Falls back to the built-in %s template.', 'ai-product-tools' ), $name ); } /** * @param int $blueprint_id Blueprint id. * @param BlueprintStore $blueprints Blueprint store. * @return string '' when the Blueprint has no row (should not happen for an id taken from a live assignment row, but defensive — the caller falls through to the next tier). */ private static function blueprintNameFor( int $blueprint_id, BlueprintStore $blueprints ): string { $row = $blueprints->get( $blueprint_id ); return null !== $row ? (string) $row['name'] : ''; } /** * Non-terminal Automation jobs whose pinned `settings.blueprint` * references this Blueprint. * 'completed' is the only status treated as terminal here, matching * {@see \AIPT\Core\ContentStructure\Cleanup\BlueprintCleanup::protectedSnapshotIds()}'s * documented reasoning ('failed' can still resume via retry). * * @param int $blueprint_id Blueprint id. * @return array */ public static function runningJobsFor( int $blueprint_id ): array { global $wpdb; $table = $wpdb->prefix . 'aipt_automation_jobs'; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, name, status, settings FROM {$table} WHERE status != 'completed' LIMIT %d", self::RUNNING_JOB_SCAN_LIMIT ), ARRAY_A ); if ( ! is_array( $rows ) ) { return array(); } $found = array(); foreach ( $rows as $row ) { if ( count( $found ) >= self::RUNNING_JOB_RESULT_LIMIT ) { break; } $settings = json_decode( (string) ( $row['settings'] ?? '' ), true ); if ( ! is_array( $settings ) || empty( $settings['blueprint'] ) || ! is_array( $settings['blueprint'] ) ) { continue; } $pin = $settings['blueprint']; $manual_id = isset( $pin['manualBlueprintId'] ) ? (int) $pin['manualBlueprintId'] : 0; $references = $manual_id === $blueprint_id; if ( ! $references && isset( $pin['blueprints'] ) && is_array( $pin['blueprints'] ) ) { foreach ( $pin['blueprints'] as $entry ) { if ( is_array( $entry ) && (int) ( $entry['id'] ?? 0 ) === $blueprint_id ) { $references = true; break; } } } if ( $references ) { $found[] = array( 'id' => (int) $row['id'], 'name' => (string) $row['name'], 'status' => (string) $row['status'], ); } } return $found; } /** * Regenerate every section/part/token/group id in a duplicated * definition, remapping `overflowDropPartId` to the new id of the same * part (duplication must generate new ids). * * @param string $generator Generator key. * @param array $definition Source definition (already normalized). * @return array */ public static function regenerateStructureIds( string $generator, array $definition ): array { switch ( $generator ) { case Generators::DESCRIPTION: case Generators::TAXONOMY: if ( isset( $definition['structure']['sections'] ) && is_array( $definition['structure']['sections'] ) ) { foreach ( $definition['structure']['sections'] as &$section ) { if ( is_array( $section ) ) { $section['id'] = SectionCatalog::generateId( 'sec' ); } } unset( $section ); } break; case Generators::TITLE: if ( isset( $definition['structure']['parts'] ) && is_array( $definition['structure']['parts'] ) ) { $map = array(); foreach ( $definition['structure']['parts'] as &$part ) { if ( is_array( $part ) ) { $old_id = (string) ( $part['id'] ?? '' ); $new_id = SectionCatalog::generateId( 'part' ); $map[ $old_id ] = $new_id; $part['id'] = $new_id; } } unset( $part ); $drop = (string) ( $definition['structure']['overflowDropPartId'] ?? '' ); if ( '' !== $drop && isset( $map[ $drop ] ) ) { $definition['structure']['overflowDropPartId'] = $map[ $drop ]; } } break; case Generators::SEO_META: foreach ( array( 'title', 'description' ) as $section ) { if ( isset( $definition['structure'][ $section ]['tokens'] ) && is_array( $definition['structure'][ $section ]['tokens'] ) ) { foreach ( $definition['structure'][ $section ]['tokens'] as &$token ) { if ( is_array( $token ) ) { $token['id'] = SectionCatalog::generateId( 'tok' ); } } unset( $token ); } } break; case Generators::FAQ: if ( isset( $definition['structure']['groups'] ) && is_array( $definition['structure']['groups'] ) ) { foreach ( $definition['structure']['groups'] as &$group ) { if ( is_array( $group ) ) { $group['id'] = SectionCatalog::generateId( 'grp' ); } } unset( $group ); } break; } return $definition; } /** * @param int $product_id Parent product id. * @param int $attachment_id Attachment id. * @return int 0-based position, or 0 when the attachment is not one of the product's recognised images. */ public static function attachmentPosition( int $product_id, int $attachment_id ): int { if ( ! function_exists( 'wc_get_product' ) ) { return 0; } $product = wc_get_product( $product_id ); if ( ! $product instanceof \WC_Product ) { return 0; } foreach ( ( new \AIPT\Api\ContentStructure\Engine\Context\AttachmentContextBuilder() )->imagesForProduct( $product ) as $image ) { if ( (int) $image['attachmentId'] === $attachment_id ) { return (int) $image['position']; } } return 0; } /** * @param int $term_id Term id. * @param string $taxonomy Taxonomy name ('' uses the term-id-only lookup). * @return string */ public static function termLabel( int $term_id, string $taxonomy ): string { if ( $term_id <= 0 || ! function_exists( 'get_term' ) ) { /* translators: %d: category (term) id. */ return sprintf( __( 'Category #%d', 'ai-product-tools' ), $term_id ); } $term = '' !== $taxonomy ? get_term( $term_id, $taxonomy ) : get_term( $term_id ); if ( $term instanceof \WP_Term ) { return (string) $term->name; } /* translators: %d: category (term) id. */ return sprintf( __( 'Category #%d', 'ai-product-tools' ), $term_id ); } /** * @param int $product_id Product id. * @return string */ public static function productLabel( int $product_id ): string { if ( ! function_exists( 'wc_get_product' ) ) { /* translators: %d: product id. */ return sprintf( __( 'Product #%d', 'ai-product-tools' ), $product_id ); } $product = wc_get_product( $product_id ); if ( $product instanceof \WC_Product ) { return (string) $product->get_name(); } /* translators: %d: product id. */ return sprintf( __( 'Product #%d', 'ai-product-tools' ), $product_id ); } /** * Convert a store's MySQL UTC datetime string to ISO 8601. Duplicated * (rather than borrowed) from {@see RestSupportTrait::isoDate()} since a * trait method is only callable through a class that composes the * trait, and this class intentionally has no REST/permission concerns * of its own. * * @param string $mysql_utc MySQL UTC datetime, or '' for "unset". * @return string */ private static function isoDate( string $mysql_utc ): string { if ( '' === $mysql_utc ) { return ''; } $timestamp = strtotime( $mysql_utc . ' UTC' ); return false !== $timestamp ? gmdate( 'c', $timestamp ) : ''; } /** * `{id,name}` summary for a user id. Duplicated from * {@see RestSupportTrait::userSummary()}; see {@see self::isoDate()}'s * docblock for why. * * @param int $user_id User id. * @return array{id:int,name:string}|null */ private static function userSummary( int $user_id ): ?array { if ( $user_id <= 0 ) { return null; } $user = get_userdata( $user_id ); if ( false === $user ) { return null; } return array( 'id' => $user_id, 'name' => (string) $user->display_name ); } }