From a4d2fe02048f22ad2503840684dcee1b955ee57b Mon Sep 17 00:00:00 2001 From: devSviat Date: Sat, 29 Aug 2026 15:54:55 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BF=D0=BE=D0=BA=D0=B0=D0=B7=D1=83?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D0=B8=20=D0=BE=D1=86=D1=96=D0=BD=D0=BA=D1=83?= =?UTF-8?q?=20=D0=B2=20=D1=81=D0=BF=D0=BE=D0=B2=D1=96=D1=89=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D1=96=20=D0=BF=D1=80=D0=BE=20=D0=BA=D0=BE=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Оцінки може не бути: у стоковій OkayCMS колонки rating немає взагалі, а до статей вона не обовʼязкова — рядок додається лише тоді, коли оцінка є. Значення поза шкалою затискається, інакше зіпсувало б рядок зірок. v1.0.8 --- Helpers/ExampleMessageHelper.php | 12 +++++- Helpers/FormatterHelper.php | 24 +++++++++++ Init/module.json | 2 +- tests/FormatterHelperTest.php | 68 ++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 2 deletions(-) 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 оцінки" + ); + } }