'GET', 'callback' => array( __CLASS__, 'get_structures' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'generator' => array( 'sanitize_callback' => 'sanitize_key' ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/structures/default', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_default' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/structures/exceptions', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_exception' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/structures/exceptions/(?P\d+)', array( array( 'methods' => 'PUT', 'callback' => array( __CLASS__, 'update_exception' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), array( 'methods' => 'DELETE', 'callback' => array( __CLASS__, 'delete_exception' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/structures/order', array( array( 'methods' => 'PUT', 'callback' => array( __CLASS__, 'save_order' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/structures/tags', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_tags' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), array( 'methods' => 'DELETE', 'callback' => array( __CLASS__, 'delete_tags' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'generator' => array( 'sanitize_callback' => 'sanitize_key' ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/structure-prefs', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_prefs' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'save_prefs' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); } /** * GET /content-structure/structures?generator=&counts= * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_structures( WP_REST_Request $request ) { $generator = (string) $request->get_param( 'generator' ); if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } $rows = static::assignmentStore()->listForGenerator( $generator ); $state = static::stateBuilder()->build( $generator, $rows ); if ( self::wantsCounts( $request ) ) { $tallies = static::counter()->tally( $generator, self::blueprintIdBySlot( $state['slots'] ), $rows ); $state['slots'] = self::mergeTallies( $state['slots'], $tallies ); } return self::success( $state ); } /** * @param WP_REST_Request $request Request object. * @return bool Default true ("counts=" omitted means "yes"); false only for an explicit falsy value. */ private static function wantsCounts( WP_REST_Request $request ): bool { $raw = $request->get_param( 'counts' ); if ( null === $raw || '' === $raw ) { return true; } return (bool) rest_sanitize_boolean( $raw ); } /** * @param array> $slots Built StructureSlot list. * @return array Slot key => its Blueprint id, or null for a built-in slot. */ private static function blueprintIdBySlot( array $slots ): array { $map = array(); foreach ( $slots as $slot ) { $map[ $slot['key'] ] = null !== $slot['blueprint'] ? (int) $slot['blueprint']['id'] : null; } return $map; } /** * @param array> $slots Built StructureSlot list. * @param array> $tallies StructureCounter::tally() result. * @return array> */ private static function mergeTallies( array $slots, array $tallies ): array { foreach ( $slots as $i => $slot ) { $tally = $tallies[ $slot['key'] ] ?? null; if ( null === $tally ) { continue; } $slots[ $i ]['counts'] = array( 'subjects' => $tally['subjects'], 'approximate' => $tally['approximate'], 'automationJobs' => $tally['automationJobs'], ); $slots[ $i ]['sample'] = $tally['sample']; } return $slots; } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function create_default( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } if ( null !== static::assignmentStore()->storeDefault( $generator ) ) { return self::defaultExistsError(); } $definition_input = is_array( $body['definition'] ?? null ) ? $body['definition'] : array(); $normalized = ( new DefinitionNormalizer( static::fieldCatalog() ) )->normalize( $generator, $definition_input, self::normalizerContext( $definition_input ) ); $errors = $normalized['errors']; $brand_profile_id = self::validatedBrandProfileId( $body['brandProfileId'] ?? 0, $errors ); if ( ! empty( $errors ) ) { return self::invalidDefinitionError( $errors, $normalized['notices'] ); } $normalized['definition'] = self::enforceAllowedDomains( $normalized['definition'], null ); $blueprint_id = static::blueprintStore()->create( array( 'name' => __( 'Store default', 'ai-product-tools' ), 'generator' => $generator, 'status' => 'active', 'schemaVersion' => (int) $normalized['definition']['schemaVersion'], 'definition' => $normalized['definition'], 'definitionHash' => DefinitionHasher::hash( $normalized['definition'] ), 'brandProfileId' => $brand_profile_id, 'origin' => '', 'createdBy' => get_current_user_id(), ) ); if ( $blueprint_id <= 0 ) { return self::createFailedError(); } $result = static::assignmentStore()->setStoreDefault( $generator, $blueprint_id, null, get_current_user_id() ); if ( ! $result['ok'] ) { static::blueprintStore()->delete( $blueprint_id ); return self::defaultExistsError(); } return self::success( array( 'state' => static::stateBuilder()->build( $generator ), 'createdKey' => 'default' ) ); } /** * Adding a category exception is Business. This route only refuses * it; the Business build registers its own handler in its place * (`Premium\ContentStructure\ExtraSlotsController`). * * @param WP_REST_Request $request Request object. * @return WP_Error */ public static function create_exception( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } if ( Generators::TAXONOMY === $generator ) { return self::productGeneratorsOnlyError(); } return self::extraSlotsRequiredError( __( 'Adding a category exception is part of the Business plan.', 'ai-product-tools' ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function update_exception( WP_REST_Request $request ) { $blueprint_id = (int) $request->get_param( 'id' ); $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } if ( Generators::TAXONOMY === $generator ) { return self::productGeneratorsOnlyError(); } $rows = static::assignmentStore()->listForGenerator( $generator ); $existing_rows = self::categoryRowsForBlueprint( $rows, $blueprint_id ); if ( empty( $existing_rows ) ) { return self::error( 'aipt_structure_not_an_exception', __( 'This is not a current category exception.', 'ai-product-tools' ), 400 ); } $category_ids = self::sanitizeCategoryIds( $body['categoryIds'] ?? array() ); if ( empty( $category_ids ) || count( $category_ids ) > self::MAX_EXCEPTION_CATEGORIES ) { return self::invalidCategoriesError(); } $state = static::stateBuilder()->build( $generator, $rows ); $taken = self::categoriesInOtherExceptions( $state['slots'], $blueprint_id ); $check = self::checkCategoryIds( $category_ids, $taken ); if ( is_wp_error( $check ) ) { return $check; } $priority = (int) $existing_rows[0]['priority']; $old_row_by_category = array(); foreach ( $existing_rows as $row ) { $old_row_by_category[ (int) $row['targetId'] ] = $row; } foreach ( $old_row_by_category as $old_category_id => $row ) { if ( ! in_array( $old_category_id, $category_ids, true ) ) { static::assignmentStore()->delete( (int) $row['id'] ); } } $user_id = get_current_user_id(); foreach ( $category_ids as $category_id ) { if ( isset( $old_row_by_category[ $category_id ] ) ) { continue; } $result = static::assignmentStore()->create( array( 'generator' => $generator, 'blueprintId' => $blueprint_id, 'targetType' => 'category', 'taxonomy' => 'product_cat', 'targetId' => $category_id, 'includeChildren' => true, 'priority' => $priority, 'createdBy' => $user_id, ) ); if ( ! $result['ok'] ) { return self::error( 'aipt_structure_category_taken', __( 'One or more categories are already used by another exception.', 'ai-product-tools' ), 409, array( 'categoryIds' => array( $category_id ), 'state' => static::stateBuilder()->build( $generator ), ) ); } } return self::success( array( 'state' => static::stateBuilder()->build( $generator ) ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function delete_exception( WP_REST_Request $request ) { $blueprint_id = (int) $request->get_param( 'id' ); $generator = (string) $request->get_param( 'generator' ); if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } foreach ( self::categoryRowsForBlueprint( static::assignmentStore()->listForGenerator( $generator ), $blueprint_id ) as $row ) { static::assignmentStore()->delete( (int) $row['id'] ); } return self::success( array( 'state' => static::stateBuilder()->build( $generator ) ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function save_order( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } if ( Generators::TAXONOMY === $generator ) { return self::productGeneratorsOnlyError(); } $requested_order = array(); foreach ( (array) ( $body['order'] ?? array() ) as $key ) { if ( is_string( $key ) ) { $requested_order[] = $key; } } $rows = static::assignmentStore()->listForGenerator( $generator ); $state = static::stateBuilder()->build( $generator, $rows ); if ( ! self::sameKeySet( $requested_order, $state['order'] ) ) { return self::error( 'aipt_structure_order_stale', __( 'The category exceptions changed since you loaded them. Reload and try again.', 'ai-product-tools' ), 409, array( 'state' => $state ) ); } $priority = 10; foreach ( $requested_order as $key ) { $blueprint_id = (int) str_replace( 'exception:', '', $key ); foreach ( self::categoryRowsForBlueprint( $rows, $blueprint_id ) as $row ) { $result = static::assignmentStore()->update( (int) $row['id'], array( 'priority' => $priority ), (int) $row['version'] ); if ( ! $result['ok'] ) { return self::error( 'aipt_structure_order_stale', __( 'The category exceptions changed since you loaded them. Reload and try again.', 'ai-product-tools' ), 409, array( 'state' => static::stateBuilder()->build( $generator ) ) ); } } $priority += 10; } return self::success( array( 'state' => static::stateBuilder()->build( $generator ) ) ); } /** * @param array $a First key list. * @param array $b Second key list. * @return bool Whether $a and $b contain exactly the same keys (order and duplicates ignored for the comparison itself; a duplicate still changes the count and so still fails). */ private static function sameKeySet( array $a, array $b ): bool { if ( count( $a ) !== count( $b ) ) { return false; } sort( $a ); sort( $b ); return $a === $b; } /** * A separate Product tags structure is Business. This route only * refuses it; the Business build registers its own handler in its place * (`Premium\ContentStructure\ExtraSlotsController`). * * @param WP_REST_Request $request Request object. * @return WP_Error */ public static function create_tags( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( Generators::TAXONOMY !== $generator ) { return self::taxonomyOnlyError(); } return self::extraSlotsRequiredError( __( 'A separate Product tags template is part of the Business plan.', 'ai-product-tools' ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function delete_tags( WP_REST_Request $request ) { $generator = (string) $request->get_param( 'generator' ); if ( Generators::TAXONOMY !== $generator ) { return self::taxonomyOnlyError(); } $row = self::tagsRow( static::assignmentStore()->listForGenerator( $generator ) ); if ( null !== $row ) { static::assignmentStore()->delete( (int) $row['id'] ); } return self::success( array( 'state' => static::stateBuilder()->build( $generator ) ) ); } /** * @param array> $rows Every row for this generator. * @return array|null The 'Product tags' row, if any. */ protected static function tagsRow( array $rows ): ?array { foreach ( $rows as $row ) { if ( 'taxonomy' === ( $row['targetType'] ?? '' ) && StructureStateBuilder::TAGS_TAXONOMY === (string) ( $row['taxonomy'] ?? '' ) ) { return $row; } } return null; } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public static function get_prefs( WP_REST_Request $request ): WP_REST_Response { unset( $request ); return self::success( array( 'prefs' => static::prefsStore()->getAll( get_current_user_id() ) ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function save_prefs( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } $raw = array( 'keep' => ! empty( $body['keep'] ), 'seen' => array_key_exists( 'seen', $body ) ? $body['seen'] : null, ); $result = static::prefsStore()->save( get_current_user_id(), $generator, $raw ); if ( ! $result['ok'] ) { return self::error( 'aipt_structure_prefs_too_large', __( 'Your preferences could not be saved.', 'ai-product-tools' ), 400 ); } return self::success( array( 'prefs' => $result['prefs'] ) ); } /** * @param array> $slots Built StructureSlot list. * @param string $key Slot key to find. * @return array|null */ protected static function findSlot( array $slots, string $key ): ?array { foreach ( $slots as $slot ) { if ( $slot['key'] === $key ) { return $slot; } } return null; } /** * Every category id currently claimed by an exception other than * $excluding_blueprint_id (null excludes nothing — the create path, * where no exception owns itself yet). * * @param array> $slots Built StructureSlot list. * @param int|null $excluding_blueprint_id An exception's own Blueprint id, allowed to keep its current categories. * @return array Category id => true. */ protected static function categoriesInOtherExceptions( array $slots, ?int $excluding_blueprint_id ): array { $taken = array(); foreach ( $slots as $slot ) { if ( 'exception' !== $slot['kind'] ) { continue; } if ( null !== $excluding_blueprint_id && (int) $slot['blueprint']['id'] === $excluding_blueprint_id ) { continue; } foreach ( $slot['categories'] as $category ) { $taken[ $category['id'] ] = true; } } return $taken; } /** * Validate a set of category ids: each must be a real product_cat term * and not already claimed by another exception. * * @param array $category_ids Candidate category ids. * @param array $taken Category id => true for ids claimed by another exception. * @return array|WP_Error Decoded category names (same order as $category_ids) on success. */ protected static function checkCategoryIds( array $category_ids, array $taken ) { $conflicting = array(); $names = array(); foreach ( $category_ids as $category_id ) { $term = function_exists( 'get_term' ) ? get_term( $category_id, 'product_cat' ) : null; if ( ! $term instanceof \WP_Term ) { return self::invalidCategoriesError(); } if ( isset( $taken[ $category_id ] ) ) { $conflicting[] = $category_id; continue; } $names[] = html_entity_decode( (string) $term->name, ENT_QUOTES, 'UTF-8' ); } if ( ! empty( $conflicting ) ) { return self::error( 'aipt_structure_category_taken', __( 'One or more categories are already used by another exception.', 'ai-product-tools' ), 409, array( 'categoryIds' => $conflicting ) ); } return $names; } /** * @param array> $rows Every row for this generator. * @param int $blueprint_id Blueprint id. * @return array> This blueprint's 'category' rows. */ protected static function categoryRowsForBlueprint( array $rows, int $blueprint_id ): array { return array_values( array_filter( $rows, static function ( array $row ) use ( $blueprint_id ): bool { return 'category' === ( $row['targetType'] ?? '' ) && (int) $row['blueprintId'] === $blueprint_id; } ) ); } /** * @param mixed $raw_ids Raw `categoryIds` request value. * @return int[] Distinct positive ids, in first-seen order. */ protected static function sanitizeCategoryIds( $raw_ids ): array { if ( ! is_array( $raw_ids ) ) { return array(); } $ids = array(); foreach ( $raw_ids as $raw_id ) { $id = absint( $raw_id ); if ( $id > 0 ) { $ids[ $id ] = true; } } return array_keys( $ids ); } /** * @param array $definition Raw submitted BlueprintDefinition, used to find every 'src:' it references. * @return array */ private static function normalizerContext( array $definition = array() ): array { return array( 'knownSourceIds' => static::knownSourceIds( $definition ), 'allowCustomFields' => static::fieldCatalog()->customFieldsAllowed(), 'validateOnSave' => true, ); } /** * Ids valid for a 'src:' reference: SourceStore::list()'s first 500 * rows sorted by name (an existing, bounded "known sources" baseline) * plus every id the submitted definition itself references, checked * directly against the store — so a structure referencing a source * outside that first page is still recognized as known instead of * rejected as "Unknown source reference". * * @param array $definition Raw submitted BlueprintDefinition. * @return int[] */ private static function knownSourceIds( array $definition ): array { $first_page = array_map( static function ( array $source ): int { return (int) $source['id']; }, static::sourceStore()->list( array(), 500 ) ); $referenced = static::sourceStore()->existingIds( self::referencedSourceIds( $definition ) ); return array_values( array_unique( array_merge( $first_page, $referenced ) ) ); } /** * Every id referenced as 'src:' anywhere in a raw (not yet * validated) BlueprintDefinition — the structure's per-section source * selections and the top-level source policy alike — without * depending on DefinitionNormalizer's own traversal of that shape. * * @param array $definition Raw submitted BlueprintDefinition. * @return int[] */ private static function referencedSourceIds( array $definition ): array { $ids = array(); array_walk_recursive( $definition, static function ( $value ) use ( &$ids ): void { if ( is_string( $value ) && 1 === preg_match( '/^src:(\d+)$/', $value, $match ) ) { $ids[] = (int) $match[1]; } } ); return array_values( array_unique( $ids ) ); } /** * @param mixed $raw Raw brandProfileId input. * @param array &$errors Collected errors (appended to on an unknown id). * @return int */ private static function validatedBrandProfileId( $raw, array &$errors ): int { $id = is_numeric( $raw ) ? (int) $raw : 0; if ( $id <= 0 ) { return 0; } if ( null === static::brandProfileStore()->get( $id ) ) { $errors[] = DefinitionPrimitives::issue( 'brandProfileId', 'not_found', __( 'The selected voice does not exist.', 'ai-product-tools' ) ); return 0; } return $id; } /** * @return WP_Error */ protected static function invalidGeneratorError(): WP_Error { return self::error( 'aipt_blueprint_invalid_generator', __( 'Unknown content type.', 'ai-product-tools' ), 400 ); } /** * @return WP_Error */ protected static function productGeneratorsOnlyError(): WP_Error { return self::error( 'aipt_structure_invalid_generator', __( 'Category exceptions are only available for product generators.', 'ai-product-tools' ), 400 ); } /** * @return WP_Error */ protected static function taxonomyOnlyError(): WP_Error { return self::error( 'aipt_structure_invalid_generator', __( 'The Product tags template is only available for Category descriptions.', 'ai-product-tools' ), 400 ); } /** * Content structure extra structure slots (Business, 2026-10-18): the * 403 for create_exception()/create_tags() on a site without * {@see \AIPT\Api\ContentStructure\Engine\Policy\ExtraSlotsPolicy::extraSlotsAllowed()}. * Only creation is gated; update/delete/reorder stay role-only (no live * effect to prevent once a row's application is already clamped at run * time). * * @param string $message Action-specific translated message. * @return WP_Error */ protected static function extraSlotsRequiredError( string $message ): WP_Error { $reason = PlanDenial::reason( 'contentStructureExtraSlots', PlanDenial::PLAN_PAID ); return self::error( 'aipt_structure_extra_slots_required', PlanDenial::message( $reason, $message ), 403, array( 'reason' => $reason ) ); } /** * @return WP_Error */ private static function defaultExistsError(): WP_Error { return self::error( 'aipt_structure_default_exists', __( 'A store default already exists for this generator.', 'ai-product-tools' ), 409 ); } /** * @return WP_Error */ protected static function createFailedError(): WP_Error { return self::error( 'aipt_structure_create_failed', __( 'This template could not be saved.', 'ai-product-tools' ), 500 ); } /** * @return WP_Error */ protected static function invalidCategoriesError(): WP_Error { return self::error( 'aipt_structure_invalid_categories', __( 'Choose 1 to 50 existing categories.', 'ai-product-tools' ), 400 ); } /** * @param array $errors Validation errors. * @param array $notices Validation notices. * @return WP_Error */ private static function invalidDefinitionError( array $errors, array $notices ): WP_Error { return self::error( 'aipt_blueprint_invalid_definition', __( 'This template is not valid.', 'ai-product-tools' ), 400, array( 'errors' => $errors, 'notices' => $notices ) ); } /** * @return array */ private static function idArgs(): array { return array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ), ); } /** * @return AssignmentStore */ protected static function assignmentStore(): AssignmentStore { return new AssignmentStore(); } /** * @return BlueprintStore */ protected static function blueprintStore(): BlueprintStore { return new BlueprintStore(); } /** * @return SourceStore */ protected static function sourceStore(): SourceStore { return new SourceStore(); } /** * @return BrandProfileStore */ protected static function brandProfileStore(): BrandProfileStore { return new BrandProfileStore(); } /** * @return FieldCatalog */ protected static function fieldCatalog(): FieldCatalog { return new FieldCatalog(); } /** * @return StructureStateBuilder */ protected static function stateBuilder(): StructureStateBuilder { return new StructureStateBuilder(); } /** * @return StructureCounter */ protected static function counter(): StructureCounter { return new StructureCounter(); } /** * @return StructurePrefsStore */ protected static function prefsStore(): StructurePrefsStore { return new StructurePrefsStore(); } }