CYS - Move the `ai/store-title` endpoint to woocommerce admin api (#50352)

* CYS - Move the ai/store-title endpoint to woocommerce admin api

* Add middleware and callback

* Add changefile(s) from automation for the following project(s): woocommerce

* Fix lint error

* Use constant and normalize site title values

* Add base AI Endpoint class

* Fix lint error

* Extract the ai title option name

---------

Co-authored-by: github-actions <github-actions@github.com>
This commit is contained in:
Alba Rincón 2024-08-08 10:27:29 +02:00 committed by GitHub
parent 8aba7eebde
commit ff89ce7494
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 274 additions and 214 deletions

View File

@ -322,7 +322,7 @@ export const updateStorePatterns = async (
},
} ),
apiFetch( {
path: '/wc/private/ai/store-title',
path: '/wc-admin/ai/store-title',
method: 'POST',
data: {
business_description:

View File

@ -0,0 +1,4 @@
Significance: minor
Type: dev
CYS - Move the ai/store-title endpoint to woocommerce admin API

View File

@ -0,0 +1,55 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Admin\API\AI;
/**
* AI Endpoint base controller
*
* @internal
*/
abstract class AIEndpoint {
/**
* Endpoint namespace.
*
* @var string
*/
protected $namespace = 'wc-admin';
/**
* Route base.
*
* @var string
*/
protected $rest_base = 'ai';
/**
* Endpoint.
*
* @var string
*/
protected $endpoint;
/**
* Register routes.
*
* @param array $args Optional. Either an array of options for the endpoint,
* or an array of arrays for multiple methods. Default empty array.
*/
public function register( $args ) {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/' . $this->endpoint,
$args
);
}
/**
* Return schema properties.
*
* @return array
*/
abstract public function get_schema();
}

View File

@ -0,0 +1,51 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Admin\API\AI;
use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
use WP_Error;
/**
* Middleware class.
*
* @internal
*/
class Middleware {
/**
* Ensure that the user is allowed to make this request.
*
* @return boolean|WP_Error
* @throws RouteException If the user is not allowed to make this request.
*/
public static function is_authorized() {
try {
if ( ! current_user_can( 'manage_options' ) ) {
throw new RouteException( 'woocommerce_rest_invalid_user', __( 'You are not allowed to make this request. Please make sure you are logged in.', 'woocommerce' ), 403 );
}
} catch ( RouteException $error ) {
return new WP_Error(
$error->getErrorCode(),
$error->getMessage(),
array( 'status' => $error->getCode() )
);
}
$allow_ai_connection = get_option( 'woocommerce_blocks_allow_ai_connection' );
if ( ! $allow_ai_connection ) {
try {
throw new RouteException( 'ai_connection_not_allowed', __( 'AI content generation is not allowed on this store. Update your store settings if you wish to enable this feature.', 'woocommerce' ), 403 );
} catch ( RouteException $error ) {
return new WP_Error(
$error->getErrorCode(),
$error->getMessage(),
array( 'status' => $error->getCode() )
);
}
}
return true;
}
}

View File

@ -0,0 +1,156 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Admin\API\AI;
use Automattic\WooCommerce\Blocks\AI\Connection;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
defined( 'ABSPATH' ) || exit;
/**
* Store Title controller
*
* @internal
*/
class StoreTitle extends AIEndpoint {
/**
* The store title option name.
*
* @var string
*/
const STORE_TITLE_OPTION_NAME = 'blogname';
/**
* The AI generated store title option name.
*
* @var string
*/
const AI_STORE_TITLE_OPTION_NAME = 'ai_generated_site_title';
/**
* The default store title.
*
* @var string
*/
const DEFAULT_TITLE = 'Site Title';
/**
* Endpoint.
*
* @var string
*/
protected $endpoint = 'store-title';
/**
* Register routes.
*/
public function register_routes() {
$this->register(
array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( $this, 'update_store_title' ),
'permission_callback' => array( Middleware::class, 'is_authorized' ),
'args' => array(
'business_description' => array(
'description' => __( 'The business description for a given store.', 'woocommerce' ),
'type' => 'string',
),
),
),
'schema' => array( $this, 'get_schema' ),
)
);
}
/**
* Update the store title powered by AI.
*
* @param WP_REST_Request $request Request object.
*
* @return WP_Error|WP_REST_Response
*/
public function update_store_title( $request ) {
$business_description = $request->get_param( 'business_description' );
if ( ! $business_description ) {
return new WP_Error(
'invalid_business_description',
__( 'Invalid business description.', 'woocommerce' )
);
}
$store_title = html_entity_decode( get_option( self::STORE_TITLE_OPTION_NAME ) );
$previous_ai_generated_title = html_entity_decode( get_option( self::AI_STORE_TITLE_OPTION_NAME ) );
if ( strtolower( trim( self::DEFAULT_TITLE ) ) === strtolower( trim( $store_title ) ) || ( ! empty( $store_title ) && $previous_ai_generated_title !== $store_title ) ) {
return rest_ensure_response( array( 'ai_content_generated' => false ) );
}
$ai_generated_title = $this->generate_ai_title( $business_description );
if ( is_wp_error( $ai_generated_title ) ) {
return $ai_generated_title;
}
update_option( self::AI_STORE_TITLE_OPTION_NAME, $ai_generated_title );
update_option( self::STORE_TITLE_OPTION_NAME, $ai_generated_title );
return rest_ensure_response(
array(
'ai_content_generated' => true,
)
);
}
/**
* Generate the store title powered by AI.
*
* @param string $business_description The business description for a given store.
*
* @return string|WP_Error|WP_REST_Response The store title generated by AI.
*/
private function generate_ai_title( $business_description ) {
$ai_connection = new Connection();
$site_id = $ai_connection->get_site_id();
if ( is_wp_error( $site_id ) ) {
return $site_id;
}
$token = $ai_connection->get_jwt_token( $site_id );
if ( is_wp_error( $token ) ) {
return $token;
}
$prompt = "Generate a store title for a store that has the following: '$business_description'. The length of the title should be 1 and 3 words. The result should include only the store title without any other explanation, number or punctuation marks";
$ai_response = $ai_connection->fetch_ai_response( $token, $prompt );
if ( is_wp_error( $ai_response ) ) {
return $ai_response;
}
if ( ! isset( $ai_response['completion'] ) ) {
return '';
}
return $ai_response['completion'];
}
/**
* Get the Business Description response.
*
* @return array
*/
public function get_schema() {
return array(
'ai_content_generated' => true,
);
}
}

View File

@ -86,6 +86,7 @@ class Init {
'Automattic\WooCommerce\Admin\API\NavigationFavorites',
'Automattic\WooCommerce\Admin\API\MobileAppMagicLink',
'Automattic\WooCommerce\Admin\API\ShippingPartnerSuggestions',
'Automattic\WooCommerce\Admin\API\AI\StoreTitle',
);
}

View File

@ -1,158 +0,0 @@
<?php
namespace Automattic\WooCommerce\StoreApi\Routes\V1\AI;
use Automattic\WooCommerce\Blocks\AI\Connection;
use Automattic\WooCommerce\StoreApi\Routes\V1\AbstractRoute;
/**
* StoreTitle class.
*
* @internal
*/
class StoreTitle extends AbstractRoute {
/**
* The route identifier.
*
* @var string
*/
const IDENTIFIER = 'ai/store-title';
/**
* The schema item identifier.
*
* @var string
*/
const SCHEMA_TYPE = 'ai/store-title';
/**
* The store title option name.
*
* @var string
*/
const STORE_TITLE_OPTION_NAME = 'blogname';
/**
* The default store title.
*
* @var string
*/
const DEFAULT_TITLE = 'Site Title';
/**
* Get the path of this REST route.
*
* @return string
*/
public function get_path() {
return self::get_path_regex();
}
/**
* Get the path of this rest route.
*
* @return string
*/
public static function get_path_regex() {
return '/ai/store-title';
}
/**
* Get method arguments for this REST route.
*
* @return array An array of endpoints.
*/
public function get_args() {
return array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( $this, 'get_response' ),
'permission_callback' => array( Middleware::class, 'is_authorized' ),
'args' => array(
'business_description' => array(
'description' => __( 'The business description for a given store.', 'woocommerce' ),
'type' => 'string',
),
),
),
'schema' => array( $this->schema, 'get_public_item_schema' ),
'allow_batch' => array( 'v1' => true ),
);
}
/**
* Update the store title powered by AI.
*
* @param \WP_REST_Request $request Request object.
*
* @return bool|string|\WP_Error|\WP_REST_Response
*/
protected function get_route_post_response( \WP_REST_Request $request ) {
$business_description = $request->get_param( 'business_description' );
if ( ! $business_description ) {
return $this->error_to_response(
new \WP_Error(
'invalid_business_description',
__( 'Invalid business description.', 'woocommerce' )
)
);
}
$store_title = html_entity_decode( get_option( 'blogname' ) );
$previous_ai_generated_title = html_entity_decode( get_option( 'ai_generated_site_title' ) );
if ( self::DEFAULT_TITLE === $store_title || ( ! empty( $store_title ) && $previous_ai_generated_title !== $store_title ) ) {
return rest_ensure_response( array( 'ai_content_generated' => false ) );
}
$ai_generated_title = $this->generate_ai_title( $business_description );
if ( is_wp_error( $ai_generated_title ) ) {
return $this->error_to_response( $ai_generated_title );
}
update_option( 'ai_generated_site_title', $ai_generated_title );
update_option( self::STORE_TITLE_OPTION_NAME, $ai_generated_title );
return rest_ensure_response(
array(
'ai_content_generated' => true,
)
);
}
/**
* Generate the store title powered by AI.
*
* @param string $business_description The business description for a given store.
*
* @return string|\WP_Error|\WP_REST_Response The store title generated by AI.
*/
private function generate_ai_title( $business_description ) {
$ai_connection = new Connection();
$site_id = $ai_connection->get_site_id();
if ( is_wp_error( $site_id ) ) {
return $this->error_to_response( $site_id );
}
$token = $ai_connection->get_jwt_token( $site_id );
if ( is_wp_error( $token ) ) {
return $this->error_to_response( $token );
}
$prompt = "Generate a store title for a store that has the following: '$business_description'. The length of the title should be 1 and 3 words. The result should include only the store title without any other explanation, number or punctuation marks";
$ai_response = $ai_connection->fetch_ai_response( $token, $prompt );
if ( is_wp_error( $ai_response ) ) {
return $this->error_to_response( $ai_response );
}
if ( ! isset( $ai_response['completion'] ) ) {
return '';
}
return $ai_response['completion'];
}
}

View File

@ -68,14 +68,13 @@ class RoutesController {
],
// @todo Migrate internal AI routes to WooCommerce Core codebase.
'private' => [
Routes\V1\AI\StoreTitle::IDENTIFIER => Routes\V1\AI\StoreTitle::class,
Routes\V1\AI\Images::IDENTIFIER => Routes\V1\AI\Images::class,
Routes\V1\AI\Patterns::IDENTIFIER => Routes\V1\AI\Patterns::class,
Routes\V1\AI\Product::IDENTIFIER => Routes\V1\AI\Product::class,
Routes\V1\AI\Products::IDENTIFIER => Routes\V1\AI\Products::class,
Routes\V1\AI\Images::IDENTIFIER => Routes\V1\AI\Images::class,
Routes\V1\AI\Patterns::IDENTIFIER => Routes\V1\AI\Patterns::class,
Routes\V1\AI\Product::IDENTIFIER => Routes\V1\AI\Product::class,
Routes\V1\AI\Products::IDENTIFIER => Routes\V1\AI\Products::class,
Routes\V1\AI\BusinessDescription::IDENTIFIER => Routes\V1\AI\BusinessDescription::class,
Routes\V1\AI\StoreInfo::IDENTIFIER => Routes\V1\AI\StoreInfo::class,
Routes\V1\Patterns::IDENTIFIER => Routes\V1\Patterns::class,
Routes\V1\AI\StoreInfo::IDENTIFIER => Routes\V1\AI\StoreInfo::class,
Routes\V1\Patterns::IDENTIFIER => Routes\V1\Patterns::class,
],
];
}

View File

@ -54,7 +54,6 @@ class SchemaController {
Schemas\V1\ProductCategorySchema::IDENTIFIER => Schemas\V1\ProductCategorySchema::class,
Schemas\V1\ProductCollectionDataSchema::IDENTIFIER => Schemas\V1\ProductCollectionDataSchema::class,
Schemas\V1\ProductReviewSchema::IDENTIFIER => Schemas\V1\ProductReviewSchema::class,
Schemas\V1\AI\StoreTitleSchema::IDENTIFIER => Schemas\V1\AI\StoreTitleSchema::class,
Schemas\V1\AI\ImagesSchema::IDENTIFIER => Schemas\V1\AI\ImagesSchema::class,
Schemas\V1\AI\PatternsSchema::IDENTIFIER => Schemas\V1\AI\PatternsSchema::class,
Schemas\V1\AI\ProductSchema::IDENTIFIER => Schemas\V1\AI\ProductSchema::class,

View File

@ -1,47 +0,0 @@
<?php
namespace Automattic\WooCommerce\StoreApi\Schemas\V1\AI;
use Automattic\WooCommerce\StoreApi\Schemas\V1\AbstractSchema;
/**
* StoreTitleSchema class.
*
* @internal
*/
class StoreTitleSchema extends AbstractSchema {
/**
* The schema item name.
*
* @var string
*/
protected $title = 'ai/store-title';
/**
* The schema item identifier.
*
* @var string
*/
const IDENTIFIER = 'ai/store-title';
/**
* Business Description schema properties.
*
* @return array
*/
public function get_properties() {
return [];
}
/**
* Get the Business Description response.
*
* @param array $item Item to get response for.
*
* @return array
*/
public function get_item_response( $item ) {
return [
'ai_content_generated' => true,
];
}
}