Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions src/Controller/Api/ReviewSummaryController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php declare(strict_types=1);

namespace Frosh\AI\Controller\Api;

use Frosh\AI\Exception\AiException;
use Frosh\AI\Exception\NoProviderAvailableException;
use Frosh\AI\Feature\ReviewSummary\ReviewSummaryGenerator;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Routing\ApiRouteScope;
use Shopware\Core\PlatformRequest;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route(defaults: [PlatformRequest::ATTRIBUTE_ROUTE_SCOPE => [ApiRouteScope::ID]])]
class ReviewSummaryController extends AbstractController
{
public function __construct(
private readonly ReviewSummaryGenerator $generator,
) {
}

#[Route(
path: '/api/_action/frosh-ai/product/review-summary',
name: 'api.action.frosh_ai.product.review_summary',
methods: ['POST'],
)]
public function summarize(Request $request, Context $context): JsonResponse
{
/** @var array<string, mixed> $payload */
$payload = $request->toArray();
$productId = trim((string) ($payload['productId'] ?? ''));

if ($productId === '') {
return new JsonResponse(['success' => false, 'error' => 'productId is required.'], 400);
}

try {
$result = $this->generator->summarize($productId, $context);
} catch (NoProviderAvailableException $e) {
return $this->providerError($e);
} catch (AiException $e) {
return new JsonResponse(['success' => false, 'error' => $e->getMessage()], 400);
} catch (\Throwable $e) {
return new JsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
}

return new JsonResponse([
'success' => true,
'summary' => $result['summary'],
'pros' => $result['pros'],
'cons' => $result['cons'],
'themes' => $result['themes'],
'reviewCount' => $result['reviewCount'],
'averageRating' => $result['averageRating'],
'provider' => $result['provider'],
'model' => $result['model'],
]);
}

#[Route(
path: '/api/_action/frosh-ai/product/review-summary-status',
name: 'api.action.frosh_ai.product.review_summary_status',
methods: ['GET'],
)]
public function status(): JsonResponse
{
return new JsonResponse([
'enabled' => $this->generator->isEnabled(),
]);
}

private function providerError(NoProviderAvailableException $e): JsonResponse
{
return new JsonResponse([
'success' => false,
'error' => $e->getMessage() !== ''
? $e->getMessage()
: 'No AI provider is configured. Open Settings → Frosh AI.',
], 400);
}
}
3 changes: 3 additions & 0 deletions src/Feature/FeatureId.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ enum FeatureId: string
case ProductSeo = 'product_seo';
case CategoryDescription = 'category_description';
case ManufacturerDescription = 'manufacturer_description';
case ReviewSummary = 'review_summary';
case ImageGeneration = 'image_generation';
case ImageEdit = 'image_edit';

Expand All @@ -24,6 +25,7 @@ public function configKey(): string
self::ProductSeo => 'FroshAI.config.featureProductSeo',
self::CategoryDescription => 'FroshAI.config.featureCategoryDescription',
self::ManufacturerDescription => 'FroshAI.config.featureManufacturerDescription',
self::ReviewSummary => 'FroshAI.config.featureReviewSummary',
self::ImageGeneration => 'FroshAI.config.featureImageGeneration',
self::ImageEdit => 'FroshAI.config.featureImageEdit',
};
Expand All @@ -37,6 +39,7 @@ public function label(): string
self::ProductSeo => 'Product SEO fields',
self::CategoryDescription => 'Category description',
self::ManufacturerDescription => 'Manufacturer description',
self::ReviewSummary => 'Review summary',
self::ImageGeneration => 'Image generation',
self::ImageEdit => 'Image editing',
};
Expand Down
210 changes: 210 additions & 0 deletions src/Feature/ReviewSummary/ReviewSummaryGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
<?php declare(strict_types=1);

namespace Frosh\AI\Feature\ReviewSummary;

use Frosh\AI\Client\AiClient;
use Frosh\AI\Exception\AiException;
use Frosh\AI\Exception\NoProviderAvailableException;
use Frosh\AI\Feature\FeatureFlags;
use Frosh\AI\Feature\FeatureId;
use Frosh\AI\Message\ChatMessage;
use Shopware\Core\Content\Product\Aggregate\ProductReview\ProductReviewEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\System\SystemConfig\SystemConfigService;

/**
* Summarizes a product's approved customer reviews (pros / cons / themes) via
* the merchant's configured structured-output model.
*
* Only reviews with status = true (accepted) are considered, newest first,
* capped at 50 reviews / ~500 chars of content each.
*/
final class ReviewSummaryGenerator
{
public const FEATURE = 'review-summary';

private const MAX_REVIEWS = 50;
private const MAX_CONTENT_CHARS = 500;

private const SCHEMA = [
'name' => 'review_summary',
'schema' => [
'type' => 'object',
'properties' => [
'summary' => ['type' => 'string'],
'pros' => ['type' => 'array', 'items' => ['type' => 'string']],
'cons' => ['type' => 'array', 'items' => ['type' => 'string']],
'themes' => ['type' => 'array', 'items' => ['type' => 'string']],
'reviewCount' => ['type' => 'integer'],
'averageRating' => ['type' => 'number'],
],
'required' => ['summary', 'pros', 'cons', 'themes', 'reviewCount', 'averageRating'],
],
];

/**
* @param EntityRepository<ProductReviewEntity> $reviewRepository
*/
public function __construct(
private readonly AiClient $ai,
private readonly SystemConfigService $systemConfigService,
private readonly EntityRepository $reviewRepository,
private readonly FeatureFlags $featureFlags,
) {
}

public function isEnabled(?string $salesChannelId = null): bool
{
return $this->featureFlags->isEnabled(FeatureId::ReviewSummary, $salesChannelId)
&& $this->ai->isAvailable($salesChannelId);
}

/**
* @return array{
* summary: string,
* pros: list<string>,
* cons: list<string>,
* themes: list<string>,
* reviewCount: int,
* averageRating: float,
* provider: string,
* model: string,
* }
*/
public function summarize(string $productId, ?Context $context = null, ?string $salesChannelId = null): array
{
if (!$this->featureFlags->isMasterEnabled($salesChannelId)) {
throw new AiException('Frosh AI features are disabled. Enable them under Settings → Frosh AI.');
}

if (!$this->featureFlags->isFeatureFlagOn(FeatureId::ReviewSummary, $salesChannelId)) {
throw new AiException('Review summary generation is disabled. Enable it under Settings → Frosh AI → Features.');
}

if (!$this->ai->isAvailable($salesChannelId)) {
throw new NoProviderAvailableException();
}

$reviews = $this->loadApprovedReviews($productId, $context ?? Context::createDefaultContext());
if ($reviews === []) {
throw new AiException('This product has no approved reviews to summarize.');
}

$system = implode("\n", [
'You are an e-commerce assistant summarizing customer reviews for a Shopware store.',
'Return only JSON.',
'Do not invent pros/cons not present in the reviews.',
'Set reviewCount to the number of reviews provided and averageRating to the mean of the star ratings (1-5).',
]);

$user = $this->buildUserPrompt($reviews);

$response = $this->ai->chatStructured(
[ChatMessage::system($system), ChatMessage::user($user)],
self::SCHEMA,
[
'temperature' => 0.3,
'maxTokens' => 2048,
'metadata' => [
'extension' => 'FroshAI',
'feature' => self::FEATURE,
'entity' => 'product',
'entityId' => $productId,
],
],
);

if (!$response->isValid()) {
throw new AiException('The AI returned an invalid review summary: ' . ($response->error ?? 'unknown error'));
}

$data = $response->data;

return [
'summary' => (string) ($data['summary'] ?? ''),
'pros' => $this->stringList($data['pros'] ?? []),
'cons' => $this->stringList($data['cons'] ?? []),
'themes' => $this->stringList($data['themes'] ?? []),
'reviewCount' => (int) ($data['reviewCount'] ?? \count($reviews)),
'averageRating' => (float) ($data['averageRating'] ?? 0.0),
'provider' => $response->raw->providerId,
'model' => $response->raw->model,
];
}

/**
* @return list<array{points: float|null, title: string, content: string}>
*/
private function loadApprovedReviews(string $productId, Context $context): array
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $productId));
$criteria->addFilter(new EqualsFilter('status', true));
$criteria->addSorting(new FieldSorting('createdAt', FieldSorting::DESCENDING));
$criteria->setLimit(self::MAX_REVIEWS);
$criteria->addFields(['title', 'content', 'points']);

$reviews = [];
foreach ($this->reviewRepository->search($criteria, $context)->getEntities() as $review) {
$reviews[] = [
'points' => $review->getPoints(),
'title' => trim((string) ($review->getTitle() ?? '')),
'content' => trim((string) ($review->getContent() ?? '')),
];
}

return $reviews;
}

/**
* @param list<array{points: float|null, title: string, content: string}> $reviews
*/
private function buildUserPrompt(array $reviews): string
{
$lines = [
\sprintf('Summarize the following %d customer reviews for one product:', \count($reviews)),
'',
];

foreach ($reviews as $index => $review) {
$rating = $review['points'] !== null ? \sprintf('%g/5', $review['points']) : 'unrated';
$lines[] = \sprintf('Review %d — Rating: %s', $index + 1, $rating);
if ($review['title'] !== '') {
$lines[] = 'Title: ' . $review['title'];
}
if ($review['content'] !== '') {
$lines[] = 'Content: ' . mb_substr($review['content'], 0, self::MAX_CONTENT_CHARS);
}
$lines[] = '';
}

return implode("\n", $lines);
}

/**
* @return list<string>
*/
private function stringList(mixed $value): array
{
if (!\is_array($value)) {
return [];
}

$out = [];
foreach ($value as $item) {
if (!\is_string($item) && !is_numeric($item)) {
continue;
}
$trimmed = trim((string) $item);
if ($trimmed !== '') {
$out[] = $trimmed;
}
}

return $out;
}
}
9 changes: 9 additions & 0 deletions src/Resources/config/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@
<defaultValue>true</defaultValue>
</input-field>

<input-field type="bool">
<name>featureReviewSummary</name>
<label>Review summary generation</label>
<label lang="de-DE">Bewertungszusammenfassung generieren</label>
<helpText>Product reviews: summarize approved customer reviews (pros/cons/themes) with AI. Requires master switch on.</helpText>
<helpText lang="de-DE">Produktbewertungen: freigegebene Kundenbewertungen (Pro/Contra/Themen) mit KI zusammenfassen. Benötigt aktivierten Hauptschalter.</helpText>
<defaultValue>true</defaultValue>
</input-field>

<input-field type="bool">
<name>featureImageGeneration</name>
<label>Image generation</label>
Expand Down
12 changes: 12 additions & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,18 @@
<tag name="controller.service_arguments"/>
</service>

<!-- Review summary features -->
<service id="Frosh\AI\Feature\ReviewSummary\ReviewSummaryGenerator">
<argument type="service" id="Frosh\AI\Client\AiClient"/>
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
<argument type="service" id="product_review.repository"/>
<argument type="service" id="Frosh\AI\Feature\FeatureFlags"/>
</service>
<service id="Frosh\AI\Controller\Api\ReviewSummaryController" public="true">
<argument type="service" id="Frosh\AI\Feature\ReviewSummary\ReviewSummaryGenerator"/>
<tag name="controller.service_arguments"/>
</service>

<!-- Usage tracking -->
<service id="Frosh\AI\Entity\UsageLog\UsageLogDefinition">
<tag name="shopware.entity.definition"/>
Expand Down
5 changes: 4 additions & 1 deletion tests/Unit/Feature/FeatureFlagsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public function testMasterOffDisablesAll(): void
static::assertFalse($flags->isEnabled(FeatureId::ProductSeo));
static::assertFalse($flags->isEnabled(FeatureId::CategoryDescription));
static::assertFalse($flags->isEnabled(FeatureId::ManufacturerDescription));
static::assertFalse($flags->isEnabled(FeatureId::ReviewSummary));
static::assertFalse($flags->isEnabled(FeatureId::ImageGeneration));
static::assertFalse($flags->isEnabled(FeatureId::ImageEdit));
static::assertTrue($flags->isFeatureFlagOn(FeatureId::ProductDescription));
Expand Down Expand Up @@ -47,6 +48,7 @@ public function testMissingFeatureKeyDefaultsToOn(): void
static::assertTrue($flags->isEnabled(FeatureId::ProductSeo));
static::assertTrue($flags->isEnabled(FeatureId::CategoryDescription));
static::assertTrue($flags->isEnabled(FeatureId::ManufacturerDescription));
static::assertTrue($flags->isEnabled(FeatureId::ReviewSummary));
static::assertTrue($flags->isEnabled(FeatureId::ImageGeneration));
static::assertTrue($flags->isEnabled(FeatureId::ImageEdit));
}
Expand All @@ -57,7 +59,7 @@ public function testPublicArray(): void
$public = $flags->toPublicArray();

static::assertTrue($public['master']);
static::assertCount(7, $public['features']);
static::assertCount(8, $public['features']);
$byId = [];
foreach ($public['features'] as $row) {
$byId[$row['id']] = $row;
Expand All @@ -69,6 +71,7 @@ public function testPublicArray(): void
static::assertArrayHasKey('product_seo', $byId);
static::assertArrayHasKey('category_description', $byId);
static::assertArrayHasKey('manufacturer_description', $byId);
static::assertArrayHasKey('review_summary', $byId);
static::assertArrayHasKey('image_edit', $byId);
}

Expand Down
Loading
Loading