diff --git a/Helpers/ExampleMessageHelper.php b/Helpers/ExampleMessageHelper.php
index c65ca0f..a1e6ddf 100644
--- a/Helpers/ExampleMessageHelper.php
+++ b/Helpers/ExampleMessageHelper.php
@@ -3,6 +3,7 @@
namespace Okay\Modules\Sviat\TelegramNotifier\Helpers;
use Okay\Core\Request;
+use Okay\Entities\CommentsEntity;
/**
* Генерація прикладів повідомлень для відображення в адмін-панелі
@@ -96,10 +97,19 @@ public function getExampleCommentMessage(): string
"Від: Леся Українка",
"Email: lesya.ukrainka@example.com",
"Сторінка: Смартфон Samsung Galaxy S23",
+ ];
+
+ // Прев'ю має збігатися з тим, що прийде насправді: у стоковій OkayCMS
+ // колонки `rating` немає, тож і рядка з оцінкою в повідомленні не буде.
+ if (in_array('rating', CommentsEntity::getFields(), true)) {
+ $message[] = "Оцінка: ★★★★★ (5/5)";
+ }
+
+ $message = array_merge($message, [
"",
"Коментар:",
"Чудовий товар! Дуже задоволена якістю та швидкою доставкою. Рекомендую!",
- ];
+ ]);
return implode("\n", $message);
}
diff --git a/Helpers/FormatterHelper.php b/Helpers/FormatterHelper.php
index ec1bce1..1841e4e 100644
--- a/Helpers/FormatterHelper.php
+++ b/Helpers/FormatterHelper.php
@@ -368,6 +368,10 @@ public function formatCommentMessage($comment): string
$pageUrl = $this->getCommentPageUrl($comment);
$message[] = $this->formatPageLink($pageUrl);
+ if ($rating = $this->formatRatingField($comment)) {
+ $message[] = $rating;
+ }
+
$message[] = "";
$message[] = "Коментар:";
$message[] = "" . $this->escapeHtml($comment->text ?? '') . "";
@@ -599,6 +603,26 @@ private function getEntityTitle(string $entityClass, string $url): ?string
}
}
+ /**
+ * Оцінки може не бути: у стоковій OkayCMS колонки `rating` немає взагалі,
+ * а до статей вона не обов'язкова.
+ *
+ * @param object $comment Об'єкт коментаря
+ * @return string|null Відформатований рядок з оцінкою або null
+ */
+ private function formatRatingField($comment): ?string
+ {
+ $rating = $comment->rating ?? null;
+ if (empty($rating)) {
+ return null;
+ }
+
+ // Значення поза шкалою зіпсувало б рядок зірок, тож затискаємо.
+ $rating = max(1, min(5, (int)$rating));
+
+ return "Оцінка: " . str_repeat('★', $rating) . str_repeat('☆', 5 - $rating) . " ({$rating}/5)";
+ }
+
/**
* Форматує поле Email для повідомлення
*
diff --git a/Init/module.json b/Init/module.json
index 647c5c5..cd78e0b 100644
--- a/Init/module.json
+++ b/Init/module.json
@@ -1,6 +1,6 @@
{
"Okay": "4.5.2",
- "version": "1.0.7",
+ "version": "1.0.8",
"moduleName": "Telegram сповіщення",
"vendor": {
"email": "devsviat@proton.me",
diff --git a/tests/FormatterHelperTest.php b/tests/FormatterHelperTest.php
index 42715bd..0810281 100644
--- a/tests/FormatterHelperTest.php
+++ b/tests/FormatterHelperTest.php
@@ -273,4 +273,72 @@ public function testCurrencySignFallsBackToHryvnia(): void
self::assertStringContainsString('100 ₴', $message);
}
+
+ /**
+ * Оцінки може не бути: у стоковій OkayCMS колонки `rating` немає взагалі,
+ * а до статей вона не обов'язкова. Рядок додається лише тоді, коли оцінка
+ * справді є.
+ *
+ * @dataProvider commentRatingProvider
+ */
+ #[DataProvider('commentRatingProvider')]
+ public function testRatingLineAppearsOnlyWhenThereIsARating(object $comment, ?string $expected): void
+ {
+ $message = $this->formatter->formatCommentMessage($comment);
+
+ if ($expected === null) {
+ $this->assertStringNotContainsString('Оцінка:', $message);
+
+ return;
+ }
+
+ $this->assertStringContainsString($expected, $message);
+ }
+
+ public static function commentRatingProvider(): array
+ {
+ $base = ['type' => 'product', 'name' => 'Клієнт', 'email' => 'c@example.com', 'text' => 'Текст'];
+
+ return [
+ 'товар з оцінкою' => [(object)($base + ['rating' => 5]), 'Оцінка: ★★★★★ (5/5)'],
+ 'половина шкали' => [(object)($base + ['rating' => 3]), 'Оцінка: ★★★☆☆ (3/5)'],
+ // PDO віддає tinyint рядком, тож приведення типу має бути на місці.
+ 'оцінка рядком' => [(object)($base + ['rating' => '4']), 'Оцінка: ★★★★☆ (4/5)'],
+ 'стаття без оцінки' => [(object)(['type' => 'post'] + $base + ['rating' => null]), null],
+ 'стокова CMS: поля немає' => [(object)$base, null],
+ 'нуль оцінкою не є' => [(object)($base + ['rating' => 0]), null],
+ // Значення поза шкалою зіпсувало б рядок зірок.
+ 'вище шкали' => [(object)($base + ['rating' => 99]), 'Оцінка: ★★★★★ (5/5)'],
+ 'нижче шкали' => [(object)($base + ['rating' => -3]), 'Оцінка: ★☆☆☆☆ (1/5)'],
+ ];
+ }
+
+ /**
+ * Прев'ю в адмінці показує, як виглядатиме повідомлення. Воно має
+ * збігатися з реальністю на обох CMS: там, де колонки `rating` немає,
+ * рядка з оцінкою не буде ні в прикладі, ні в справжньому сповіщенні.
+ */
+ public function testExamplePreviewMatchesWhetherRatingsExist(): void
+ {
+ // Прев'ю будує абсолютний URL через Request::getRootUrl(), а той читає
+ // $_SERVER напряму - у CLI цих ключів немає.
+ $server = $_SERVER;
+ $_SERVER += ['SERVER_PROTOCOL' => 'HTTP/1.1', 'SERVER_PORT' => 80, 'HTTP_HOST' => 'example.com'];
+
+ try {
+ $reflector = new \ReflectionClass(\Okay\Modules\Sviat\TelegramNotifier\Helpers\ExampleMessageHelper::class);
+ $example = $reflector->newInstanceWithoutConstructor();
+ $preview = $reflector->getMethod('getExampleCommentMessage')->invoke($example);
+ } finally {
+ $_SERVER = $server;
+ }
+
+ $ratingsExist = in_array('rating', \Okay\Entities\CommentsEntity::getFields(), true);
+
+ $this->assertSame(
+ $ratingsExist,
+ str_contains($preview, 'Оцінка:'),
+ "прев'ю розходиться з тим, чи підтримує ця CMS оцінки"
+ );
+ }
}