'GET', 'callback' => array( __CLASS__, 'list_profiles' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_profile' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/brand-profiles/(?P\d+)', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_profile' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), array( 'methods' => 'PUT', 'callback' => array( __CLASS__, 'update_profile' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), array( 'methods' => 'DELETE', 'callback' => array( __CLASS__, 'delete_profile' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/brand-profiles/(?P\d+)/duplicate', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'duplicate_profile' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/brand-profiles/(?P\d+)/impact', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_impact' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/brand-profiles/(?P\d+)/suggestions/(?P[a-zA-Z0-9_-]+)', array( array( 'methods' => 'DELETE', 'callback' => array( __CLASS__, 'dismiss_suggestion' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ), 'suggestionId' => array( 'required' => true, 'sanitize_callback' => 'sanitize_text_field' ), ), ), ) ); } /** * GET /content-structure/brand-profiles * * @return WP_REST_Response */ public static function list_profiles(): WP_REST_Response { $blueprints = static::blueprintStore(); $items = array_map( function ( array $row ) use ( $blueprints ): array { return self::fullShape( $row, $blueprints ); }, static::profileStore()->listAll() ); return self::success( $items ); } /** * POST /content-structure/brand-profiles * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function create_profile( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $name = isset( $body['name'] ) ? sanitize_text_field( (string) $body['name'] ) : ''; if ( '' === trim( $name ) ) { return self::error( 'aipt_blueprint_invalid_brand_profile', __( 'A voice name is required.', 'ai-product-tools' ), 400 ); } if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { return self::nameTooLongError(); } $normalized = BrandProfileSchema::normalize( is_array( $body['profile'] ?? null ) ? $body['profile'] : array() ); if ( ! empty( $normalized['errors'] ) ) { return self::invalidProfileError( $normalized['errors'] ); } $quota_error = self::enforceVoiceQuota(); if ( null !== $quota_error ) { return $quota_error; } $id = static::profileStore()->create( array( 'name' => $name, 'profile' => $normalized['profile'], 'origin' => '', 'createdBy' => get_current_user_id(), ) ); if ( $id <= 0 ) { return self::error( 'aipt_blueprint_create_failed', __( 'The voice could not be created.', 'ai-product-tools' ), 500 ); } return self::success( self::fullShape( static::profileStore()->get( $id ), static::blueprintStore() ) ); } /** * GET /content-structure/brand-profiles/{id} * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_profile( WP_REST_Request $request ) { $row = static::profileStore()->get( (int) $request->get_param( 'id' ) ); if ( null === $row ) { return self::notFoundError(); } return self::success( self::fullShape( $row, static::blueprintStore() ) ); } /** * PUT /content-structure/brand-profiles/{id} * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function update_profile( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $current = static::profileStore()->get( $id ); if ( null === $current ) { return self::notFoundError(); } $body = (array) $request->get_json_params(); $name = isset( $body['name'] ) ? sanitize_text_field( (string) $body['name'] ) : (string) $current['name']; if ( '' === trim( $name ) ) { return self::error( 'aipt_blueprint_invalid_brand_profile', __( 'A voice name is required.', 'ai-product-tools' ), 400 ); } if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { return self::nameTooLongError(); } $normalized = BrandProfileSchema::normalize( is_array( $body['profile'] ?? null ) ? $body['profile'] : $current['profile'] ); if ( ! empty( $normalized['errors'] ) ) { return self::invalidProfileError( $normalized['errors'] ); } $expected_revision = isset( $body['expectedRevision'] ) ? (int) $body['expectedRevision'] : -1; $data = array( 'name' => $name, 'profile' => $normalized['profile'], 'updatedBy' => get_current_user_id(), ); if ( isset( $body['consumedSuggestionIds'] ) && is_array( $body['consumedSuggestionIds'] ) ) { $data['consumedSuggestionIds'] = array_map( 'sanitize_text_field', $body['consumedSuggestionIds'] ); } if ( isset( $body['dismissedSuggestionIds'] ) && is_array( $body['dismissedSuggestionIds'] ) ) { $data['dismissedSuggestionIds'] = array_map( 'sanitize_text_field', $body['dismissedSuggestionIds'] ); } $result = static::profileStore()->update( $id, $data, $expected_revision ); if ( ! $result['ok'] ) { return self::revisionConflictError( $result['current'] ); } return self::success( self::fullShape( $result['current'], static::blueprintStore() ) ); } /** * POST /content-structure/brand-profiles/{id}/duplicate * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function duplicate_profile( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $source = static::profileStore()->get( $id ); if ( null === $source ) { return self::notFoundError(); } $body = (array) $request->get_json_params(); $given_name = isset( $body['name'] ) && '' !== trim( (string) $body['name'] ); $name = $given_name ? sanitize_text_field( (string) $body['name'] ) : sprintf( /* translators: %s: source profile name. */ __( 'Copy of %s', 'ai-product-tools' ), $source['name'] ); if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { if ( $given_name ) { return self::nameTooLongError(); } $name = mb_substr( $name, 0, self::NAME_MAX_LENGTH ); } $quota_error = self::enforceVoiceQuota(); if ( null !== $quota_error ) { return $quota_error; } $new_id = static::profileStore()->create( array( 'name' => $name, 'profile' => $source['profile'], 'origin' => 'duplicate:' . $id, 'createdBy' => get_current_user_id(), ) ); if ( $new_id <= 0 ) { return self::error( 'aipt_blueprint_create_failed', __( 'The voice could not be duplicated.', 'ai-product-tools' ), 500 ); } return self::success( self::fullShape( static::profileStore()->get( $new_id ), static::blueprintStore() ) ); } /** * GET /content-structure/brand-profiles/{id}/impact * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_impact( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); if ( null === static::profileStore()->get( $id ) ) { return self::notFoundError(); } return self::success( self::computeImpact( $id, static::blueprintStore() ) ); } /** * DELETE /content-structure/brand-profiles/{id}?impactHash= * * Detaches every referencing Blueprint to `brandProfileId: 0` (their * own revision-checked write, retried once on a CAS conflict) before * deleting the profile row itself, so no Blueprint is left pointing at * a profile that no longer exists. If any detach still fails after its * retry (a concurrent edit raced both attempts), the profile is NOT * deleted — that would orphan the Blueprint it could not detach — and * the request is refused the same way a stale `impactHash` is, with the * failed Blueprint ids added so the client can reload the usage and the * admin can retry. * * @since 2.8.0 Refuses the delete when `$failed` is non-empty. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function delete_profile( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); if ( null === static::profileStore()->get( $id ) ) { return self::notFoundError(); } $blueprints = static::blueprintStore(); $impact = self::computeImpact( $id, $blueprints ); $given_hash = (string) $request->get_param( 'impactHash' ); if ( '' === $given_hash || ! hash_equals( $impact['impactHash'], $given_hash ) ) { return self::error( 'aipt_blueprint_impact_changed', __( 'What this delete affects has changed since you last checked. Review the refreshed impact and try again.', 'ai-product-tools' ), 409, array( 'impact' => $impact ) ); } $detached = array(); $failed = array(); foreach ( $blueprints->listByBrandProfile( $id ) as $blueprint ) { if ( self::detachBrandProfile( $blueprints, $blueprint ) ) { $detached[] = (int) $blueprint['id']; } else { $failed[] = (int) $blueprint['id']; } } if ( ! empty( $failed ) ) { return self::error( 'aipt_blueprint_impact_changed', __( 'What this delete affects has changed since you last checked. Review the refreshed impact and try again.', 'ai-product-tools' ), 409, array( 'impact' => self::computeImpact( $id, $blueprints ), 'failed' => $failed, ) ); } static::profileStore()->delete( $id ); return self::success( array( 'deleted' => true, 'detached' => $detached, 'failed' => $failed, ) ); } /** * DELETE /content-structure/brand-profiles/{id}/suggestions/{suggestionId} * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function dismiss_suggestion( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $suggestion_id = (string) $request->get_param( 'suggestionId' ); $current = static::profileStore()->get( $id ); if ( null === $current ) { return self::notFoundError(); } $result = static::profileStore()->update( $id, array( 'dismissedSuggestionIds' => array( $suggestion_id ), 'updatedBy' => get_current_user_id() ), (int) $current['revision'] ); if ( ! $result['ok'] ) { $retry_target = $result['current']; if ( null !== $retry_target ) { $result = static::profileStore()->update( $id, array( 'dismissedSuggestionIds' => array( $suggestion_id ), 'updatedBy' => get_current_user_id() ), (int) $retry_target['revision'] ); } } if ( ! $result['ok'] ) { return self::revisionConflictError( $result['current'] ); } return self::success( self::fullShape( $result['current'], static::blueprintStore() ) ); } /** * The canonical `BrandProfile` shape. Public so * `Api\ContentStructure\Rest\BrandAssistController` (a separate file * and namespace) can reuse it for its own `suggestions` response * instead of keeping a second, separately-maintained copy. * * @param array $row Raw BrandProfileStore row. * @param BlueprintStore $blueprints Blueprint store (for usage). * @return array BrandProfile. */ public static function fullShape( array $row, BlueprintStore $blueprints ): array { $usage = array_map( static function ( array $blueprint ): array { return array( 'id' => (int) $blueprint['id'], 'name' => (string) $blueprint['name'], 'generator' => (string) $blueprint['generator'], ); }, $blueprints->listByBrandProfile( (int) $row['id'] ) ); return array( 'id' => (int) $row['id'], 'name' => (string) $row['name'], 'revision' => (int) $row['revision'], 'profile' => $row['profile'], 'draft' => $row['draft'], 'usage' => array( 'blueprints' => $usage ), 'updatedAt' => self::isoDate( (string) $row['updatedAt'] ), 'updatedBy' => self::userSummary( (int) $row['updatedBy'] ), 'lockedClaims' => BrandProfileSchema::lockedClaims(), ); } /** * @param int $id Brand profile id. * @param BlueprintStore $blueprints Blueprint store. * @return array{blueprints:array,impactHash:string} */ private static function computeImpact( int $id, BlueprintStore $blueprints ): array { $referencing = array_map( static function ( array $blueprint ): array { return array( 'id' => (int) $blueprint['id'], 'name' => (string) $blueprint['name'], 'generator' => (string) $blueprint['generator'], ); }, $blueprints->listByBrandProfile( $id ) ); $without_hash = array( 'blueprints' => $referencing ); return array( 'blueprints' => $referencing, 'impactHash' => hash( 'sha256', DefinitionHasher::canonicalJson( $without_hash ) ), ); } /** * Detach one Blueprint from this Brand profile via its own * revision-checked write, retrying once against a concurrent writer's * result. * * @param BlueprintStore $blueprints Blueprint store. * @param array $blueprint The Blueprint row to detach (its own last-known revision). * @return bool Whether the detach succeeded (after at most one retry). */ private static function detachBrandProfile( BlueprintStore $blueprints, array $blueprint ): bool { $data = array( 'brandProfileId' => 0, 'updatedBy' => get_current_user_id() ); $result = $blueprints->update( (int) $blueprint['id'], $data, (int) $blueprint['revision'] ); if ( $result['ok'] ) { return true; } if ( null === $result['current'] ) { return false; } if ( (int) $result['current']['brandProfileId'] !== (int) $blueprint['brandProfileId'] ) { return true; } $retry = $blueprints->update( (int) $blueprint['id'], $data, (int) $result['current']['revision'] ); return (bool) $retry['ok']; } /** * Free-scope voice-count cap (G9): enforced UNCONDITIONALLY, with NO * license check. The premium * {@see \AIPT\Premium\ContentStructure\VoiceQuotaService} raises the * 'aipt_max_brand_profiles' filter; on a free build it is unregistered * so FREE_MAX_VOICES (1) stands. Create-time only, mirroring * `AutomationJobsController::enforceJobCountCap()` exactly: an existing * voice is never degraded, only a further create or duplicate is * refused once the ceiling is reached. The editor's own display of this * same limit reads the identical filter through * `VoicePolicy::voiceLimit()`. * * Shared by create_profile() and duplicate_profile(): both add a new * voice row, so both must honour the cap. * * @return WP_Error|null */ private static function enforceVoiceQuota(): ?WP_Error { $max_voices = (int) apply_filters( 'aipt_max_brand_profiles', self::FREE_MAX_VOICES ); if ( $max_voices <= 0 || static::profileStore()->countAll() < $max_voices ) { return null; } $reason = PlanDenial::reason( 'contentStructureVoices', PlanDenial::PLAN_PAID ); return self::error( 'aipt_blueprint_plan_required', PlanDenial::message( $reason, __( 'A second voice is part of the Business plan.', 'ai-product-tools' ) ), 403, array( 'reason' => $reason ) ); } /** * @return WP_Error */ private static function notFoundError(): WP_Error { return self::error( 'aipt_blueprint_brand_profile_not_found', __( 'This voice no longer exists.', 'ai-product-tools' ), 404 ); } /** * @param array $errors Validation errors. * @return WP_Error */ private static function invalidProfileError( array $errors ): WP_Error { return self::error( 'aipt_blueprint_invalid_brand_profile', __( 'This voice is not valid.', 'ai-product-tools' ), 400, array( 'errors' => $errors ) ); } /** * A name past {@see NAME_MAX_LENGTH} (the `aipt_brand_profiles.name` * varchar(190) column width), using the same error code as the * "name required" check above so the client's existing handling covers * it with no new case. * * @since 2.8.0 * @return WP_Error */ private static function nameTooLongError(): WP_Error { return self::error( 'aipt_blueprint_invalid_brand_profile', __( 'Use a name of 190 characters or fewer.', 'ai-product-tools' ), 400 ); } /** * @param array|null $current Current row after a failed conditional update. * @return WP_Error */ private static function revisionConflictError( ?array $current ): WP_Error { return self::error( 'aipt_blueprint_revision_conflict', __( 'This voice changed since you loaded it. Reload and try again.', 'ai-product-tools' ), 409, array( 'currentRevision' => null !== $current ? (int) $current['revision'] : null, 'updatedBy' => null !== $current ? self::userSummary( (int) $current['updatedBy'] ) : null, 'updatedAt' => null !== $current ? self::isoDate( (string) $current['updatedAt'] ) : null, ) ); } /** * @return array */ private static function idArgs(): array { return array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ), ); } /** * @return BrandProfileStore */ protected static function profileStore(): BrandProfileStore { return new BrandProfileStore(); } /** * @return BlueprintStore */ protected static function blueprintStore(): BlueprintStore { return new BlueprintStore(); } }