This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Block\Adminhtml\Review;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Registry;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;
class Images extends Template
{
public function __construct(
Template\Context $context,
private readonly ResourceConnection $resourceConnection,
private readonly StoreManagerInterface $storeManager,
private readonly Registry $registry,
array $data = []
) {
parent::__construct($context, $data);
}
public function getReviewId(): int
{
$reviewId = (int)$this->getData('review_id');
if ($reviewId > 0) {
return $reviewId;
}
$review = $this->registry->registry('review_data');
return $review && $review->getId() ? (int)$review->getId() : 0;
}
public function getImages(): array
{
$reviewId = $this->getReviewId();
if ($reviewId <= 0) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$rows = $connection->fetchAll(
$connection->select()
->from($this->resourceConnection->getTableName('esun_review_image'))
->where('review_id = ?', $reviewId)
->order('sort_order ASC')
->order('image_id ASC')
);
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
return array_map(static fn (array $row): array => [
'url' => $mediaUrl . ltrim((string)$row['image_path'], '/'),
'thumb' => $mediaUrl . ltrim((string)($row['thumbnail_path'] ?: $row['image_path']), '/'),
'type' => (string)($row['media_type'] ?? 'image'),
'status' => (int)$row['status'],
], $rows);
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Block\Customer;
use Esun\Review\Model\Order\AwaitingReviewProvider;
use Magento\Catalog\Helper\Image;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Element\Template;
use Magento\Review\Model\RatingFactory;
use Magento\Sales\Model\ResourceModel\Order\Item\Collection;
class Awaiting extends Template
{
private ?Collection $items = null;
public function __construct(
Template\Context $context,
private readonly Session $session,
private readonly AwaitingReviewProvider $provider,
private readonly RatingFactory $ratings,
private readonly Image $imageHelper,
array $data = []
) {
parent::__construct($context, $data);
}
public function getItems(): Collection
{
return $this->items ??= $this->provider->getCollection((int)$this->session->getCustomerId());
}
public function getRatings(): \Magento\Review\Model\ResourceModel\Rating\Collection
{
return $this->ratings->create()->getResourceCollection()->addEntityFilter('product')
->setPositionOrder()->addRatingPerStoreName((int)$this->_storeManager->getStore()->getId())
->setStoreFilter((int)$this->_storeManager->getStore()->getId())->setActiveFilter(true)
->load()->addOptionToItems();
}
public function getImageUrl(\Magento\Sales\Model\Order\Item $item): string
{
return $item->getProduct()
? $this->imageHelper->init($item->getProduct(), 'wishlist_thumbnail')->getUrl()
: $this->imageHelper->getDefaultPlaceholderUrl('thumbnail');
}
public function getPostUrl(int $productId): string
{
return $this->getUrl('review/product/post', ['id' => $productId, '_secure' => $this->getRequest()->isSecure()]);
}
protected function _prepareLayout(): self
{
parent::_prepareLayout();
$pager = $this->getLayout()->createBlock(\Magento\Theme\Block\Html\Pager::class, 'esun.review.awaiting.pager')
->setLimit(10)
->setShowPerPage(false)
->setCollection($this->getItems());
$this->setChild('pager', $pager);
return $this;
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Block\Order;
use Esun\Review\Model\Order\ReviewEligibilityService;
use Magento\Customer\Model\Session;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Review\Model\RatingFactory;
class ReviewableItems extends Template
{
public function __construct(Template\Context $context, private readonly Registry $registry, private readonly Session $session, private readonly ReviewEligibilityService $eligibility, private readonly RatingFactory $ratings, array $data = []) { parent::__construct($context, $data); }
public function getOrder(): \Magento\Sales\Model\Order { return $this->registry->registry('current_order'); }
public function getItems(): array { return array_values(array_filter($this->getOrder()->getAllVisibleItems(), fn($item) => (float)$item->getQtyOrdered() - (float)$item->getQtyCanceled() > 0)); }
public function canReview(\Magento\Sales\Model\Order\Item $item): bool { return $this->eligibility->canReview($item, (int)$this->session->getCustomerId()); }
public function hasReviewed(\Magento\Sales\Model\Order\Item $item): bool { return $this->eligibility->hasReviewed((int)$this->session->getCustomerId(), (int)$item->getProductId()); }
public function getRatings(): \Magento\Review\Model\ResourceModel\Rating\Collection { return $this->ratings->create()->getResourceCollection()->addEntityFilter('product')->setPositionOrder()->addRatingPerStoreName((int)$this->_storeManager->getStore()->getId())->setStoreFilter((int)$this->_storeManager->getStore()->getId())->setActiveFilter(true)->load()->addOptionToItems(); }
public function getPostUrl(int $productId): string { return $this->getUrl('review/product/post', ['id' => $productId, '_secure' => $this->getRequest()->isSecure()]); }
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Block\Product;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template\Context;
use Magento\Review\Model\ResourceModel\Review\CollectionFactory;
class Review extends \Magento\Review\Block\Product\Review
{
public function __construct(
Context $context,
Registry $registry,
CollectionFactory $collectionFactory,
private readonly CustomerSession $customerSession,
array $data = []
) {
parent::__construct($context, $registry, $collectionFactory, $data);
}
public function canShowReviewForm(): bool
{
return false;
}
}
+252
View File
@@ -0,0 +1,252 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Block\Review;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Registry;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\Template;
use Magento\Review\Model\Review;
use Magento\Review\Model\ResourceModel\Review\Collection;
use Magento\Review\Model\ResourceModel\Review\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
class Data extends Template
{
public function __construct(
Template\Context $context,
private readonly ResourceConnection $resourceConnection,
private readonly StoreManagerInterface $storeManager,
private readonly CustomerSession $customerSession,
private readonly Registry $registry,
private readonly CollectionFactory $reviewCollectionFactory,
array $data = []
) {
parent::__construct($context, $data);
}
public function getCurrentProductId(?int $fallback = null): int
{
$product = $this->registry->registry('current_product');
if ($product && $product->getId()) {
return (int)$product->getId();
}
return (int)$fallback;
}
public function getSummary(int $productId): array
{
if ($productId <= 0) {
return ['score' => 0.0, 'count' => 0, 'percent' => 0];
}
$connection = $this->resourceConnection->getConnection();
$row = $connection->fetchRow(
$connection->select()
->from(['r' => $this->resourceConnection->getTableName('review')], [
'reviews_count' => new \Zend_Db_Expr('COUNT(DISTINCT r.review_id)'),
'avg_percent' => new \Zend_Db_Expr('AVG(v.percent)'),
])
->joinLeft(
['v' => $this->resourceConnection->getTableName('rating_option_vote')],
'v.review_id = r.review_id',
[]
)
->where('r.entity_pk_value = ?', $productId)
->where('r.status_id = ?', Review::STATUS_APPROVED)
) ?: [];
$percent = (float)($row['avg_percent'] ?? 0);
return [
'score' => $percent > 0 ? round($percent / 20, 1) : 0.0,
'count' => (int)($row['reviews_count'] ?? 0),
'percent' => (int)round($percent),
];
}
public function getReviewsCollection(int $productId, int $pageSize = 10): Collection
{
$collection = $this->reviewCollectionFactory->create()
->addStatusFilter(Review::STATUS_APPROVED)
->addEntityFilter('product', $productId)
->setDateOrder()
->setPageSize($pageSize)
->setCurPage((int)$this->getRequest()->getParam('p', 1));
$collection->load();
return $collection;
}
public function getReviewPercents(array $reviewIds): array
{
$reviewIds = array_values(array_filter(array_map('intval', $reviewIds)));
if (!$reviewIds) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$rows = $connection->fetchPairs(
$connection->select()
->from($this->resourceConnection->getTableName('rating_option_vote'), [
'review_id',
'percent' => new \Zend_Db_Expr('ROUND(AVG(percent))'),
])
->where('review_id IN (?)', $reviewIds)
->group('review_id')
);
return array_map('intval', $rows);
}
public function getCustomerNames(array $customerIds): array
{
$customerIds = array_values(array_filter(array_map('intval', $customerIds)));
if (!$customerIds) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$rows = $connection->fetchAll(
$connection->select()
->from($this->resourceConnection->getTableName('customer_entity'), [
'entity_id',
'firstname',
'lastname',
])
->where('entity_id IN (?)', $customerIds)
);
$names = [];
foreach ($rows as $row) {
$name = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
if ($name !== '') {
$names[(int)$row['entity_id']] = $name;
}
}
return $names;
}
public function getCustomerPhotos(int $productId): array
{
if ($productId <= 0) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$rows = $connection->fetchAll(
$connection->select()
->from(['i' => $this->resourceConnection->getTableName('esun_review_image')], [
'image_path',
'thumbnail_path',
'review_id',
])
->join(
['r' => $this->resourceConnection->getTableName('review')],
'r.review_id = i.review_id',
[]
)
->where('r.entity_pk_value = ?', $productId)
->where('r.status_id = ?', Review::STATUS_APPROVED)
->where('i.status = ?', 1)
->where('i.media_type = ?', 'image')
->order('i.created_at DESC')
->order('i.image_id DESC')
);
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
return array_map(static fn (array $row): array => [
'url' => $mediaUrl . ltrim((string)$row['image_path'], '/'),
'thumb' => $mediaUrl . ltrim((string)($row['thumbnail_path'] ?: $row['image_path']), '/'),
'review_id' => (int)$row['review_id'],
], $rows);
}
public function canWriteReview(int $productId): bool
{
$customerId = $this->getCustomerId();
if ($productId <= 0 || $customerId <= 0) {
return false;
}
$connection = $this->resourceConnection->getConnection();
$reviewId = (int)$connection->fetchOne(
$connection->select()
->from(['r' => $this->resourceConnection->getTableName('review')], ['review_id'])
->join(
['d' => $this->resourceConnection->getTableName('review_detail')],
'd.review_id = r.review_id',
[]
)
->where('r.entity_pk_value = ?', $productId)
->where('d.customer_id = ?', $customerId)
->limit(1)
);
return $reviewId <= 0;
}
public function canVote(array $review): bool
{
$customerId = $this->getCustomerId();
return $customerId > 0 && (int)($review['customer_id'] ?? 0) !== $customerId;
}
public function getCustomerId(): int
{
return $this->customerSession->isLoggedIn() ? (int)$this->customerSession->getCustomerId() : 0;
}
public function getVoteUrl(): string
{
return $this->getUrl('esun_review/review/vote');
}
public function getVotes(array $reviewIds): array
{
$reviewIds = array_values(array_filter(array_map('intval', $reviewIds)));
if (!$reviewIds) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$rows = $connection->fetchAll(
$connection->select()
->from($this->resourceConnection->getTableName('esun_review_vote'), [
'review_id',
'vote_type',
'count' => new \Zend_Db_Expr('COUNT(*)'),
])
->where('review_id IN (?)', $reviewIds)
->group(['review_id', 'vote_type'])
);
$result = [];
foreach ($reviewIds as $reviewId) {
$result[$reviewId] = ['up' => 0, 'down' => 0, 'customer_vote' => 0];
}
foreach ($rows as $row) {
$key = (int)$row['vote_type'] > 0 ? 'up' : 'down';
$result[(int)$row['review_id']][$key] = (int)$row['count'];
}
$customerId = $this->getCustomerId();
if ($customerId > 0) {
$customerRows = $connection->fetchPairs(
$connection->select()
->from($this->resourceConnection->getTableName('esun_review_vote'), ['review_id', 'vote_type'])
->where('review_id IN (?)', $reviewIds)
->where('customer_id = ?', $customerId)
);
foreach ($customerRows as $reviewId => $voteType) {
$result[(int)$reviewId]['customer_vote'] = (int)$voteType;
}
}
return $result;
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Block\Review;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;
class Images extends Template
{
public function __construct(
Template\Context $context,
private readonly ResourceConnection $resourceConnection,
private readonly StoreManagerInterface $storeManager,
array $data = []
) {
parent::__construct($context, $data);
}
public function getImages(int $reviewId): array
{
if ($reviewId <= 0) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$rows = $connection->fetchAll(
$connection->select()
->from($this->resourceConnection->getTableName('esun_review_image'))
->where('review_id = ?', $reviewId)
->where('status = ?', 1)
->order('sort_order ASC')
);
$mediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
return array_map(static fn (array $row): array => [
'url' => $mediaUrl . ltrim((string)$row['image_path'], '/'),
'thumb' => $mediaUrl . ltrim((string)($row['thumbnail_path'] ?: $row['image_path']), '/'),
'type' => (string)($row['media_type'] ?? 'image'),
], $rows);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Controller\Customer;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultFactory;
class Awaiting extends AbstractAccount implements HttpGetActionInterface
{
public function execute()
{
/** @var \Magento\Framework\View\Result\Page $page */
$page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
$page->getConfig()->getTitle()->set(__('Awaiting Review'));
return $page;
}
}
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Controller\Review;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
class Vote implements HttpPostActionInterface
{
public function __construct(
private readonly RequestInterface $request,
private readonly JsonFactory $jsonFactory,
private readonly ResourceConnection $resourceConnection,
private readonly CustomerSession $customerSession,
private readonly FormKeyValidator $formKeyValidator
) {
}
public function execute()
{
$result = $this->jsonFactory->create();
if (!$this->formKeyValidator->validate($this->request)) {
return $result->setData(['success' => false, 'message' => __('Invalid form key.')]);
}
if (!$this->customerSession->isLoggedIn()) {
return $result->setData(['success' => false, 'message' => __('Please sign in to vote.')]);
}
$reviewId = (int)$this->request->getParam('review_id');
$voteType = (int)$this->request->getParam('vote_type') > 0 ? 1 : -1;
$customerId = (int)$this->customerSession->getCustomerId();
if ($reviewId <= 0) {
return $result->setData(['success' => false, 'message' => __('Invalid review.')]);
}
$connection = $this->resourceConnection->getConnection();
$review = $connection->fetchRow(
$connection->select()
->from(['r' => $this->resourceConnection->getTableName('review')], ['review_id'])
->join(
['d' => $this->resourceConnection->getTableName('review_detail')],
'd.review_id = r.review_id',
['customer_id']
)
->where('r.review_id = ?', $reviewId)
->limit(1)
);
if (!$review) {
return $result->setData(['success' => false, 'message' => __('Invalid review.')]);
}
if ((int)$review['customer_id'] === $customerId) {
return $result->setData(['success' => false, 'message' => __('You cannot vote for your own review.')]);
}
$table = $this->resourceConnection->getTableName('esun_review_vote');
$connection->insertOnDuplicate($table, [
'review_id' => $reviewId,
'customer_id' => $customerId,
'vote_type' => $voteType,
], ['vote_type']);
$counts = ['up' => 0, 'down' => 0];
$rows = $connection->fetchAll(
$connection->select()
->from($table, ['vote_type', 'count' => new \Zend_Db_Expr('COUNT(*)')])
->where('review_id = ?', $reviewId)
->group('vote_type')
);
foreach ($rows as $row) {
$counts[(int)$row['vote_type'] > 0 ? 'up' : 'down'] = (int)$row['count'];
}
return $result->setData([
'success' => true,
'up' => $counts['up'],
'down' => $counts['down'],
'customer_vote' => $voteType,
]);
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Model\Order;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Model\ResourceModel\Order\Item\Collection;
use Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory;
class AwaitingReviewProvider
{
public function __construct(
private readonly CollectionFactory $itemCollections,
private readonly ResourceConnection $resource
) {
}
public function getCollection(int $customerId): Collection
{
$collection = $this->itemCollections->create();
$orderTable = $this->resource->getTableName('sales_order');
$reviewTable = $this->resource->getTableName('review');
$detailTable = $this->resource->getTableName('review_detail');
$itemTable = $this->resource->getTableName('sales_order_item');
$connection = $this->resource->getConnection();
$reviewExists = $connection->select()
->from(['review_pending' => $reviewTable], ['review_id'])
->joinInner(
['review_pending_detail' => $detailTable],
'review_pending_detail.review_id = review_pending.review_id',
[]
)
->where('review_pending.entity_pk_value = main_table.product_id')
->where('review_pending_detail.customer_id = ?', $customerId);
$latestEligibleItems = $connection->select()
->from(['eligible_item' => $itemTable], [new \Zend_Db_Expr('MAX(eligible_item.item_id)')])
->joinInner(['eligible_order' => $orderTable], 'eligible_order.entity_id = eligible_item.order_id', [])
->where('eligible_order.customer_id = ?', $customerId)->where('eligible_order.status = ?', 'received')
->where('eligible_item.parent_item_id IS NULL')->where('eligible_item.product_id IS NOT NULL')
->where('(eligible_item.qty_ordered - eligible_item.qty_canceled) > 0')->group('eligible_item.product_id');
$collection->addFieldToSelect('*');
$collection->getSelect()
->joinInner(
['review_order' => $orderTable],
'review_order.entity_id = main_table.order_id',
['order_increment_id' => 'increment_id', 'order_created_at' => 'created_at']
)
->where('review_order.customer_id = ?', $customerId)
->where('review_order.status = ?', 'received')
->where('main_table.parent_item_id IS NULL')
->where('main_table.product_id IS NOT NULL')
->where('(main_table.qty_ordered - main_table.qty_canceled) > 0')
->where('main_table.item_id IN (?)', $latestEligibleItems)
->where('NOT EXISTS (?)', $reviewExists)
->order('review_order.created_at DESC')
->order('main_table.item_id DESC');
return $collection;
}
public function getCount(int $customerId): int
{
return (int)$this->getCollection($customerId)->getSize();
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Model\Order;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\OrderItemRepositoryInterface;
class ReviewEligibilityService
{
public function __construct(private readonly OrderItemRepositoryInterface $items, private readonly ResourceConnection $resource)
{
}
public function getItem(int $orderItemId, int $customerId): \Magento\Sales\Api\Data\OrderItemInterface
{
return $this->loadEligibleItem($orderItemId, $customerId, true);
}
public function getItemForLink(int $orderItemId, int $customerId): \Magento\Sales\Api\Data\OrderItemInterface
{
return $this->loadEligibleItem($orderItemId, $customerId, false);
}
private function loadEligibleItem(int $orderItemId, int $customerId, bool $checkExisting): \Magento\Sales\Api\Data\OrderItemInterface
{
$item = $this->items->get($orderItemId);
$order = $item->getOrder();
if ((int)$order->getCustomerId() !== $customerId || (int)$item->getParentItemId() > 0) {
throw new LocalizedException(__('This order item cannot be reviewed.'));
}
if ((float)$item->getQtyOrdered() - (float)$item->getQtyCanceled() <= 0 || !$this->isOrderEligible($order)) {
throw new LocalizedException(__('This order is not yet eligible for review.'));
}
if ($checkExisting && $this->hasReviewed($customerId, (int)$item->getProductId())) {
throw new LocalizedException(__('You have already reviewed this product.'));
}
return $item;
}
public function canReview(\Magento\Sales\Model\Order\Item $item, int $customerId): bool
{
try {
$this->getItem((int)$item->getId(), $customerId);
return true;
} catch (\Throwable) {
return false;
}
}
public function hasReviewed(int $customerId, int $productId): bool
{
$connection = $this->resource->getConnection();
return (bool)$connection->fetchOne($connection->select()->from(['r' => $this->resource->getTableName('review')], ['review_id'])->join(['d' => $this->resource->getTableName('review_detail')], 'd.review_id = r.review_id', [])->where('r.entity_pk_value = ?', $productId)->where('d.customer_id = ?', $customerId)->limit(1));
}
private function isOrderEligible(\Magento\Sales\Model\Order $order): bool
{
return (string)$order->getStatus() === 'received';
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Plugin\Adminhtml\Review;
use Esun\Review\Block\Adminhtml\Review\Images;
use Magento\Review\Block\Adminhtml\Edit\Form;
class FormImagesPlugin
{
public function afterToHtml(Form $subject, string $html): string
{
$reviewId = (int)$subject->getRequest()->getParam('id');
if ($reviewId <= 0) {
return $html;
}
$imagesHtml = $subject->getLayout()
->createBlock(Images::class)
->setTemplate('Esun_Review::review/images.phtml')
->setData('review_id', $reviewId)
->toHtml();
return $imagesHtml ? $html . $imagesHtml : $html;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Plugin\Review;
use Closure;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Review\Controller\Product\Post;
class PostGuestGuardPlugin
{
public function __construct(
private readonly CustomerSession $customerSession,
private readonly ResultFactory $resultFactory,
private readonly ManagerInterface $messageManager,
private readonly RequestInterface $request
) {
}
public function aroundExecute(Post $subject, Closure $proceed)
{
if ($this->customerSession->isLoggedIn()) {
return $proceed();
}
$referer = (string)$this->request->getServer('HTTP_REFERER');
if ($referer !== '') {
$this->customerSession->setBeforeAuthUrl($referer);
}
$this->messageManager->addErrorMessage(__('Please sign in to write a review.'));
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('customer/account/login');
}
}
@@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Plugin\Review;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Filesystem;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Review\Model\Review;
use Magento\Customer\Model\Session as CustomerSession;
use Esun\Review\Model\Order\ReviewEligibilityService;
class SaveImagesPlugin
{
public function __construct(
private readonly RequestInterface $request,
private readonly UploaderFactory $uploaderFactory,
private readonly Filesystem $filesystem,
private readonly ResourceConnection $resourceConnection,
private readonly CustomerSession $customerSession,
private readonly ReviewEligibilityService $eligibilityService
) {
}
public function beforeValidate(Review $subject): void
{
if ($this->request->getFullActionName() !== 'review_product_post') {
return;
}
$detail = trim((string)$subject->getDetail());
if (!trim((string)$subject->getTitle())) {
$subject->setTitle($detail !== '' ? mb_substr($detail, 0, 120) : 'Review');
}
if (!trim((string)$subject->getNickname())) {
$customer = $this->customerSession->getCustomer();
$name = trim((string)$customer->getFirstname() . ' ' . (string)$customer->getLastname());
$subject->setNickname($name !== '' ? $name : 'Customer');
}
}
/**
* Frontend reviews must belong to a logged-in customer.
*
* @throws LocalizedException
*/
public function beforeSave(Review $subject): void
{
if (!(int)$subject->getCustomerId()) {
throw new LocalizedException(__('Please sign in to write a review.'));
}
if ($this->request->getFullActionName() === 'review_product_post') {
$orderItemId = (int)$this->request->getParam('order_item_id');
$item = $this->eligibilityService->getItem($orderItemId, (int)$subject->getCustomerId());
if ((int)$item->getProductId() !== (int)$subject->getEntityPkValue()) {
throw new LocalizedException(__('The reviewed product does not match the order item.'));
}
}
}
public function afterSave(Review $subject, Review $result): Review
{
$this->savePurchaseLink($subject);
if (!$subject->getId() || empty($_FILES['review_images']['name'][0])) {
return $result;
}
$files = $this->normalizeFiles($_FILES['review_images']);
$mediaDirectory = $this->filesystem->getDirectoryWrite('media');
$target = 'esun/review/' . (int)$subject->getId();
$mediaDirectory->create($target);
$connection = $this->resourceConnection->getConnection();
$table = $this->resourceConnection->getTableName('esun_review_image');
foreach ($files as $index => $file) {
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
continue;
}
$_FILES['review_image_single'] = $file;
try {
$uploader = $this->uploaderFactory->create(['fileId' => 'review_image_single']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'webm', 'mov']);
$uploader->setAllowRenameFiles(true);
$saved = $uploader->save($mediaDirectory->getAbsolutePath($target));
if (empty($saved['file'])) {
continue;
}
$path = $target . '/' . ltrim((string)$saved['file'], '/');
$connection->insert($table, [
'review_id' => (int)$subject->getId(),
'customer_id' => (int)$subject->getCustomerId() ?: null,
'image_path' => $path,
'thumbnail_path' => $path,
'media_type' => in_array(strtolower((string)pathinfo($path, PATHINFO_EXTENSION)), ['mp4', 'webm', 'mov'], true) ? 'video' : 'image',
'status' => 1,
'sort_order' => $index,
]);
} catch (\Throwable) {
continue;
}
}
unset($_FILES['review_image_single']);
return $result;
}
private function savePurchaseLink(Review $review): void
{
if ($this->request->getFullActionName() !== 'review_product_post' || !(int)$review->getId()) { return; }
$orderItemId = (int)$this->request->getParam('order_item_id');
$item = $this->eligibilityService->getItemForLink($orderItemId, (int)$review->getCustomerId());
$this->resourceConnection->getConnection()->insertOnDuplicate($this->resourceConnection->getTableName('esun_review_purchase'), [
'review_id' => (int)$review->getId(), 'customer_id' => (int)$review->getCustomerId(), 'order_id' => (int)$item->getOrderId(),
'order_item_id' => (int)$item->getItemId(), 'product_id' => (int)$item->getProductId(), 'eligibility_type' => 'payment_success'
], []);
}
private function normalizeFiles(array $files): array
{
$normalized = [];
foreach ((array)$files['name'] as $index => $name) {
$normalized[] = [
'name' => $name,
'type' => $files['type'][$index] ?? '',
'tmp_name' => $files['tmp_name'][$index] ?? '',
'error' => $files['error'][$index] ?? UPLOAD_ERR_NO_FILE,
'size' => $files['size'][$index] ?? 0,
];
}
return $normalized;
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Esun\Review\Plugin;
use Closure;
use Magento\Catalog\Block\Product\ReviewRendererInterface;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\ResourceConnection;
use Magento\Review\Block\Product\ReviewRenderer;
use Magento\Review\Model\Review;
use Magento\Store\Model\StoreManagerInterface;
class ReviewRendererPlugin
{
public function __construct(
private readonly ResourceConnection $resourceConnection,
private readonly StoreManagerInterface $storeManager
) {
}
public function aroundGetReviewsSummaryHtml(
ReviewRenderer $subject,
Closure $proceed,
Product $product,
$templateType = ReviewRendererInterface::DEFAULT_VIEW,
$displayIfNoReviews = false
): string {
$result = $proceed($product, $templateType, $displayIfNoReviews);
if ($templateType === ReviewRendererInterface::SHORT_VIEW) {
$subject->setTemplate('Esun_Review::helper/summary_short.phtml');
$subject->setProduct($product);
$subject->setDisplayIfEmpty($displayIfNoReviews);
return $subject->toHtml();
}
if (!$displayIfNoReviews) {
return $result;
}
$summary = $this->getApprovedReviewSummary((int)$product->getId());
$reviewsCount = $summary['reviews_count'] ?: (int)$subject->getReviewsCount();
$ratingSummary = $summary['rating_summary'] ?: (int)$subject->getRatingSummary();
$subject->setTemplate('Esun_Review::review/summary-empty-rating.phtml');
$subject->setProduct($product);
$subject->setDisplayIfEmpty($displayIfNoReviews);
$subject->setData('esun_reviews_count', $reviewsCount);
$subject->setData('esun_rating_summary', $ratingSummary);
return $subject->toHtml();
}
private function getApprovedReviewSummary(int $productId): array
{
$connection = $this->resourceConnection->getConnection();
$storeId = (int)$this->storeManager->getStore()->getId();
$select = $connection->select()
->from(['r' => $this->resourceConnection->getTableName('review')], [])
->join(
['rs' => $this->resourceConnection->getTableName('review_store')],
'rs.review_id = r.review_id',
[]
)
->joinLeft(
['v' => $this->resourceConnection->getTableName('rating_option_vote')],
'v.review_id = r.review_id',
[]
)
->where('r.entity_pk_value = ?', $productId)
->where('r.status_id = ?', Review::STATUS_APPROVED)
->where('rs.store_id IN (?)', [0, $storeId])
->columns([
'reviews_count' => new \Zend_Db_Expr('COUNT(DISTINCT r.review_id)'),
'rating_summary' => new \Zend_Db_Expr('ROUND(AVG(v.percent))'),
]);
$summary = $connection->fetchRow($select) ?: [];
return [
'reviews_count' => (int)($summary['reviews_count'] ?? 0),
'rating_summary' => (int)($summary['rating_summary'] ?? 0),
];
}
}
@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Review\Block\Adminhtml\Edit\Form">
<plugin name="esun_admin_review_images"
type="Esun\Review\Plugin\Adminhtml\Review\FormImagesPlugin"/>
</type>
</config>
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="sales_order" resource="sales">
<column xsi:type="timestamp" name="customer_confirmed_at" nullable="true"
on_update="false" comment="Customer Confirmed Receipt At"/>
</table>
<table name="esun_review_image" resource="default" engine="innodb" comment="Esun Review Images">
<column xsi:type="int" name="image_id" unsigned="true" nullable="false" identity="true" comment="Image ID"/>
<column xsi:type="bigint" name="review_id" unsigned="true" nullable="false" comment="Review ID"/>
<column xsi:type="int" name="customer_id" unsigned="true" nullable="true" comment="Customer ID"/>
<column xsi:type="varchar" name="image_path" nullable="false" length="1024" comment="Image Path"/>
<column xsi:type="varchar" name="thumbnail_path" nullable="true" length="1024" comment="Thumbnail Path"/>
<column xsi:type="varchar" name="media_type" nullable="false" length="16" default="image" comment="Media Type"/>
<column xsi:type="smallint" name="status" unsigned="true" nullable="false" default="1" comment="Status"/>
<column xsi:type="int" name="sort_order" nullable="false" default="0" comment="Sort Order"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="image_id"/>
</constraint>
<constraint xsi:type="foreign" referenceId="ESUN_REVIEW_IMAGE_REVIEW_ID_REVIEW_REVIEW_ID"
table="esun_review_image" column="review_id"
referenceTable="review" referenceColumn="review_id"
onDelete="CASCADE"/>
<index referenceId="ESUN_REVIEW_IMAGE_REVIEW_STATUS_SORT" indexType="btree">
<column name="review_id"/>
<column name="status"/>
<column name="sort_order"/>
</index>
</table>
<table name="esun_review_vote" resource="default" engine="innodb" comment="Esun Review Helpful Votes">
<column xsi:type="int" name="vote_id" unsigned="true" nullable="false" identity="true" comment="Vote ID"/>
<column xsi:type="bigint" name="review_id" unsigned="true" nullable="false" comment="Review ID"/>
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
<column xsi:type="smallint" name="vote_type" nullable="false" comment="Vote Type"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="vote_id"/>
</constraint>
<constraint xsi:type="unique" referenceId="ESUN_REVIEW_VOTE_REVIEW_CUSTOMER_UNQ">
<column name="review_id"/>
<column name="customer_id"/>
</constraint>
<constraint xsi:type="foreign" referenceId="ESUN_REVIEW_VOTE_REVIEW_ID_REVIEW_REVIEW_ID"
table="esun_review_vote" column="review_id"
referenceTable="review" referenceColumn="review_id"
onDelete="CASCADE"/>
<index referenceId="ESUN_REVIEW_VOTE_REVIEW_TYPE" indexType="btree">
<column name="review_id"/>
<column name="vote_type"/>
</index>
<index referenceId="ESUN_REVIEW_VOTE_CUSTOMER" indexType="btree">
<column name="customer_id"/>
</index>
</table>
<table name="esun_review_purchase" resource="default" engine="innodb" comment="eSUN Review Purchase Links">
<column xsi:type="int" name="purchase_review_id" unsigned="true" nullable="false" identity="true" comment="ID"/>
<column xsi:type="bigint" name="review_id" unsigned="true" nullable="false" comment="Review ID"/>
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
<column xsi:type="int" name="order_id" unsigned="true" nullable="false" comment="Order ID"/>
<column xsi:type="int" name="order_item_id" unsigned="true" nullable="false" comment="Order Item ID"/>
<column xsi:type="int" name="product_id" unsigned="true" nullable="false" comment="Product ID"/>
<column xsi:type="varchar" name="eligibility_type" nullable="false" length="32" default="payment_success" comment="Eligibility Type"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="purchase_review_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_REVIEW_PURCHASE_REVIEW_UNQ"><column name="review_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_REVIEW_PURCHASE_CUSTOMER_PRODUCT_UNQ"><column name="customer_id"/><column name="product_id"/></constraint>
<constraint xsi:type="foreign" referenceId="ESUN_REVIEW_PURCHASE_REVIEW_ID_REVIEW_REVIEW_ID" table="esun_review_purchase" column="review_id" referenceTable="review" referenceColumn="review_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="ESUN_REVIEW_PURCHASE_ORDER_ID_SALES_ORDER_ENTITY_ID" table="esun_review_purchase" column="order_id" referenceTable="sales_order" referenceColumn="entity_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="ESUN_REVIEW_PURCHASE_ORDER_ITEM_ID_SALES_ORDER_ITEM_ITEM_ID" table="esun_review_purchase" column="order_item_id" referenceTable="sales_order_item" referenceColumn="item_id" onDelete="CASCADE"/>
</table>
</schema>
@@ -0,0 +1,65 @@
{
"sales_order": {
"column": {
"customer_confirmed_at": true
}
},
"esun_review_image": {
"column": {
"image_id": true,
"review_id": true,
"customer_id": true,
"image_path": true,
"thumbnail_path": true,
"media_type": true,
"status": true,
"sort_order": true,
"created_at": true
},
"index": {
"ESUN_REVIEW_IMAGE_REVIEW_ID_STATUS_SORT_ORDER": true
},
"constraint": {
"PRIMARY": true,
"ESUN_REVIEW_IMAGE_REVIEW_ID_REVIEW_REVIEW_ID": true
}
},
"esun_review_vote": {
"column": {
"vote_id": true,
"review_id": true,
"customer_id": true,
"vote_type": true,
"created_at": true
},
"index": {
"ESUN_REVIEW_VOTE_REVIEW_ID_VOTE_TYPE": true,
"ESUN_REVIEW_VOTE_CUSTOMER_ID": true
},
"constraint": {
"PRIMARY": true,
"ESUN_REVIEW_VOTE_REVIEW_ID_CUSTOMER_ID": true,
"ESUN_REVIEW_VOTE_REVIEW_ID_REVIEW_REVIEW_ID": true
}
},
"esun_review_purchase": {
"column": {
"purchase_review_id": true,
"review_id": true,
"customer_id": true,
"order_id": true,
"order_item_id": true,
"product_id": true,
"eligibility_type": true,
"created_at": true
},
"constraint": {
"PRIMARY": true,
"ESUN_REVIEW_PURCHASE_REVIEW_ID": true,
"ESUN_REVIEW_PURCHASE_CUSTOMER_ID_PRODUCT_ID": true,
"ESUN_REVIEW_PURCHASE_REVIEW_ID_REVIEW_REVIEW_ID": true,
"ESUN_REVIEW_PURCHASE_ORDER_ID_SALES_ORDER_ENTITY_ID": true,
"ESUN_REVIEW_PURCHASE_ORDER_ITEM_ID_SALES_ORDER_ITEM_ITEM_ID": true
}
}
}
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Review\Block\Product\ReviewRenderer">
<plugin name="esun_review_renderer"
type="Esun\Review\Plugin\ReviewRendererPlugin"/>
</type>
<type name="Magento\Review\Model\Review">
<plugin name="esun_review_image_save"
type="Esun\Review\Plugin\Review\SaveImagesPlugin"/>
</type>
<type name="Magento\Review\Controller\Product\Post">
<plugin name="esun_review_require_customer"
type="Esun\Review\Plugin\Review\PostGuestGuardPlugin"/>
</type>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="esun_review" frontName="esun_review">
<module name="Esun_Review"/>
</route>
</router>
</config>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Esun_Review">
<sequence>
<module name="Magento_Review"/>
<module name="Magento_Customer"/>
<module name="Esun_Catalog"/>
</sequence>
</module>
</config>
+4
View File
@@ -0,0 +1,4 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_Review', __DIR__);
@@ -0,0 +1,67 @@
<?php
use Esun\Review\Block\Adminhtml\Review\Images;
use Magento\Framework\Escaper;
/**
* @var Images $block
* @var Escaper $escaper
*/
$images = $block->getImages();
if (!$images) {
return;
}
?>
<style>
.esun-admin-review-images {
background: #fff;
border: 1px solid #d6d6d6;
margin-top: 2rem;
padding: 1.8rem;
}
.esun-admin-review-images__title {
color: #303030;
font-size: 1.7rem;
font-weight: 600;
margin: 0 0 1.5rem;
}
.esun-admin-review-images__list {
display: flex;
flex-wrap: wrap;
gap: 1.2rem;
}
.esun-admin-review-images__item {
color: #303030;
display: grid;
gap: .6rem;
text-decoration: none;
width: 120px;
}
.esun-admin-review-images__item img {
border: 1px solid #d6d6d6;
height: 120px;
object-fit: cover;
width: 120px;
}
.esun-admin-review-images__status {
color: #666;
font-size: 1.2rem;
}
</style>
<div class="esun-admin-review-images">
<h2 class="esun-admin-review-images__title"><?= $escaper->escapeHtml(__('Review Media')) ?></h2>
<div class="esun-admin-review-images__list">
<?php foreach ($images as $image): ?>
<a class="esun-admin-review-images__item"
href="<?= $escaper->escapeUrl($image['url']) ?>"
target="_blank"
rel="noopener">
<?php if (($image['type'] ?? 'image') === 'video'): ?>
<video src="<?= $escaper->escapeUrl($image['url']) ?>" controls preload="metadata" style="max-width:220px;max-height:160px"></video>
<?php else: ?><img src="<?= $escaper->escapeUrl($image['thumb']) ?>" alt=""><?php endif; ?>
<span class="esun-admin-review-images__status">
<?= $escaper->escapeHtml((int)$image['status'] === 1 ? __('Visible') : __('Hidden')) ?>
</span>
</a>
<?php endforeach; ?>
</div>
</div>
@@ -0,0 +1,36 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="Esun_Review::css/review.css"/>
</head>
<body>
<referenceContainer name="content.aside">
<block class="Esun\Review\Block\Product\Review"
name="esun.product.reviews"
template="Esun_Review::product/reviews.phtml"
after="product.info.additional"
cacheable="false"
ifconfig="catalog/review/active">
<block class="Magento\Review\Block\Form"
name="product.review.form"
as="review_form"
template="Esun_Review::review/form.phtml"
ifconfig="catalog/review/active">
<arguments>
<argument name="button_lock_manager" xsi:type="object">Magento\Framework\View\Element\ButtonLockManager</argument>
<argument name="jsLayout" xsi:type="array">
<item name="components" xsi:type="array">
<item name="review-form" xsi:type="array">
<item name="component" xsi:type="string">Magento_Review/js/view/review</item>
</item>
</item>
</argument>
</arguments>
<container name="form.additional.review.info" as="form_additional_review_info"/>
<container name="product.review.form.fields.before" as="form_fields_before" label="Review Form Fields Before"/>
</block>
</block>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="customer_account"/>
<head><css src="Esun_Review::css/review.css"/><css src="Esun_Customer::css/account-dashboard.css"/></head>
<body>
<referenceContainer name="content">
<block class="Esun\Review\Block\Customer\Awaiting" name="esun.review.customer.awaiting"
template="Esun_Review::customer/awaiting.phtml" cacheable="false"/>
</referenceContainer>
</body>
</page>
@@ -0,0 +1,5 @@
<?xml version="1.0"?>
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
<referenceBlock name="product.info.product_additional_data" template="Esun_Review::product/view/list.phtml"/>
</layout>
@@ -0,0 +1,2 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><head><css src="Esun_Review::css/review.css"/></head><body><referenceContainer name="content"><block class="Esun\Review\Block\Order\ReviewableItems" name="esun.order.reviewable.items" template="Esun_Review::order/reviewable-items.phtml" after="esun.sales.order.detail" cacheable="false"/></referenceContainer></body></page>
@@ -0,0 +1,175 @@
<?php
/** @var \Esun\Review\Block\Customer\Awaiting $block */
/** @var \Magento\Framework\Escaper $escaper */
$items = $block->getItems();
$ratings = $block->getRatings();
?>
<div class="esun-awaiting-reviews">
<?php if ($items->getSize()): ?>
<?php foreach ($items as $item): ?>
<article class="esun-awaiting-review-card">
<img src="<?= $escaper->escapeUrl($block->getImageUrl($item)) ?>"
alt="<?= $escaper->escapeHtmlAttr($item->getName()) ?>" loading="lazy">
<div class="esun-awaiting-review-card__info">
<small><?= $escaper->escapeHtml(__('Order #%1', $item->getData('order_increment_id'))) ?></small>
<h3><?= $escaper->escapeHtml($item->getName()) ?></h3>
<form class="review-form esun-awaiting-review-form"
action="<?= $escaper->escapeUrl($block->getPostUrl((int)$item->getProductId())) ?>"
method="post" enctype="multipart/form-data" data-role="awaiting-review-form">
<?= $block->getBlockHtml('formkey') ?>
<input type="hidden" name="order_item_id" value="<?= (int)$item->getId() ?>">
<fieldset class="fieldset review-fieldset">
<?php foreach ($ratings as $rating): ?>
<?php $ratingLabelId = 'awaiting_' . (int)$item->getId() . '_' . (int)$rating->getId() . '_label'; ?>
<fieldset class="field required review-field-ratings">
<legend class="label" id="<?= $escaper->escapeHtmlAttr($ratingLabelId) ?>">
<span><?= $escaper->escapeHtml(__('Rating')) ?></span>
</legend>
<div class="control">
<div class="nested">
<div class="field choice review-field-rating">
<div class="control review-control-vote">
<?php $iterator = 1; ?>
<?php foreach ($rating->getOptions() as $option): ?>
<?php $optionId = 'awaiting_' . (int)$item->getId() . '_' . (int)$rating->getId() . '_' . (int)$option->getValue(); ?>
<input required type="radio"
class="radio"
name="ratings[<?= (int)$rating->getId() ?>]"
id="<?= $escaper->escapeHtmlAttr($optionId) ?>"
value="<?= (int)$option->getId() ?>"
aria-labelledby="<?= $escaper->escapeHtmlAttr($ratingLabelId . ' ' . $optionId . '_label') ?>">
<label class="rating-<?= (int)$iterator ?>"
id="<?= $escaper->escapeHtmlAttr($optionId . '_label') ?>"
for="<?= $escaper->escapeHtmlAttr($optionId) ?>"
title="<?= $escaper->escapeHtmlAttr(__('%1 %2', $iterator, $iterator > 1 ? __('stars') : __('star'))) ?>">
<span><?= $escaper->escapeHtml(__('%1 %2', $iterator, $iterator > 1 ? __('stars') : __('star'))) ?></span>
</label>
<?php $iterator++; ?>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
</fieldset>
<?php endforeach; ?>
<div class="field review-field-text required">
<label class="label" for="review_detail_<?= (int)$item->getId() ?>"><span><?= $escaper->escapeHtml(__('Review')) ?></span></label>
<div class="control"><textarea id="review_detail_<?= (int)$item->getId() ?>" name="detail" rows="3" required></textarea></div>
</div>
<div class="field review-field-images">
<span class="label"><span><?= $escaper->escapeHtml(__('Images or Video')) ?></span></span>
<div class="control">
<input class="esun-review-upload-input" id="review_images_<?= (int)$item->getId() ?>" type="file" name="review_images[]" multiple="multiple"
accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,video/quicktime">
<div class="esun-review-upload-row">
<label class="esun-review-upload-control" for="review_images_<?= (int)$item->getId() ?>">
<i class="iconfont icon-picture1" aria-hidden="true"></i>
<span><?= $escaper->escapeHtml(__('Add Images or Videos')) ?></span>
</label>
</div>
<div class="esun-review-upload-preview" data-role="review-image-preview"></div>
<p class="note esun-review-upload-note"><?= $escaper->escapeHtml(__('You can add files in multiple selections. Supports JPG, PNG, GIF, WebP, MP4, WebM and MOV.')) ?></p>
</div>
</div>
</fieldset>
<div class="actions-toolbar review-form-actions">
<div class="primary actions-primary"><button class="action submit primary" type="submit"><span><?= $escaper->escapeHtml(__('Submit Review')) ?></span></button></div>
</div>
</form>
</div>
</article>
<?php endforeach; ?>
<?= $block->getChildHtml('pager') ?>
<?php else: ?>
<div class="message info empty"><span><?= $escaper->escapeHtml(__('There are no products awaiting review.')) ?></span></div>
<?php endif; ?>
</div>
<script>
require(['jquery'], function ($) {
'use strict';
function getFileKey(file) {
return [file.name, file.size, file.lastModified].join(':');
}
function syncInputFiles(input, files) {
if (typeof DataTransfer === 'undefined') {
return;
}
var transfer = new DataTransfer();
files.forEach(function (file) { transfer.items.add(file); });
input.files = transfer.files;
}
function renderPreviews(form, files) {
var preview = form.find('[data-role=review-image-preview]').empty(),
previousPreviewUrls = form.data('previewUrls') || [],
previewUrls = [];
previousPreviewUrls.forEach(function (url) {
if (window.URL && window.URL.revokeObjectURL) {
window.URL.revokeObjectURL(url);
}
});
files.forEach(function (file) {
var key = getFileKey(file),
item = $('<span class="esun-review-upload-preview__item">').attr('data-file-key', key),
remove = $('<button class="esun-review-upload-preview__remove" type="button">')
.attr({'aria-label': '<?= $escaper->escapeJs(__('Remove')) ?>', title: '<?= $escaper->escapeJs(__('Remove')) ?>'})
.text('×');
if (file.type.match(/^video\//) && window.URL && window.URL.createObjectURL) {
var videoUrl = window.URL.createObjectURL(file);
previewUrls.push(videoUrl);
$('<video preload="metadata" muted playsinline>')
.attr({src: videoUrl, title: file.name})
.appendTo(item);
} else if (file.type.match(/^image\//)) {
var image = $('<img>').attr('alt', file.name).appendTo(item),
reader = new FileReader();
reader.onload = function (event) { image.attr('src', event.target.result); };
reader.readAsDataURL(file);
} else {
$('<span class="esun-review-upload-preview__file">').text(file.name).appendTo(item);
}
item.append(remove).appendTo(preview);
});
form.data('previewUrls', previewUrls);
}
$('.esun-awaiting-reviews').on('change', 'input[name="review_images[]"]', function () {
var input = this,
form = $(input).closest('form'),
previousFiles = $(input).data('selectedFiles') || [],
newFiles = Array.prototype.slice.call(input.files || []),
files = previousFiles.slice(),
knownFiles = {};
previousFiles.forEach(function (file) {
knownFiles[getFileKey(file)] = true;
});
newFiles.forEach(function (file) {
var key = getFileKey(file);
if (!knownFiles[key]) {
files.push(file);
knownFiles[key] = true;
}
});
syncInputFiles(input, files);
$(input).data('selectedFiles', files);
renderPreviews(form, files);
});
$('.esun-awaiting-reviews').on('click', '.esun-review-upload-preview__remove', function () {
var form = $(this).closest('form'),
input = form.find('input[name="review_images[]"]')[0],
removeKey = $(this).closest('[data-file-key]').attr('data-file-key'),
files = ($(input).data('selectedFiles') || []).filter(function (file) {
return getFileKey(file) !== removeKey;
});
syncInputFiles(input, files);
$(input).data('selectedFiles', files);
renderPreviews(form, files);
});
});
</script>
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var \Magento\Review\Block\Product\ReviewRenderer $block */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
/** @var \Magento\Framework\Escaper $escaper */
$url = $block->getReviewsUrl() . '#reviews';
$urlForm = $block->getReviewsUrl() . '#review-form';
?>
<?php if ($block->isReviewEnabled()): ?>
<?php $rating = $block->getRatingSummary(); ?>
<div class="product-reviews-summary short<?= !$rating ? ' no-rating' : '' ?>">
<?php if ($rating):?>
<div class="rating-summary">
<span class="label"><span><?= $escaper->escapeHtml(__('Rating')) ?>:</span></span>
<div class="rating-result"
id="rating-result_<?= /* @noEscape */ $block->getProduct()->getId() ?>"
title="<?= $escaper->escapeHtmlAttr($rating) ?>%">
<span style="width: <?= $escaper->escapeHtmlAttr($rating) ?>%;">
<span><?= $escaper->escapeHtml($rating) ?>%</span>
</span>
</div>
</div>
<?php endif;?>
<div class="reviews-actions">
<a class="action view"
href="<?= $escaper->escapeUrl($url) ?>"><?= $escaper->escapeHtml($block->getReviewsCount()) ?>
&nbsp;<span><?= ($block->getReviewsCount() == 1) ?
$escaper->escapeHtml(__('Review')) : $escaper->escapeHtml(__('Reviews')) ?>
</span>
</a>
</div>
</div>
<?php elseif ($block->isReviewEnabled() && $block->getDisplayIfEmpty()): ?>
<div class="product-reviews-summary short empty">
<div class="reviews-actions">
<a class="action add" href="<?= $escaper->escapeUrl($urlForm) ?>">
<?= $escaper->escapeHtml(__('Be the first to review this product')) ?>
</a>
</div>
</div>
<?php endif; ?>
@@ -0,0 +1,6 @@
<?php /** @var \Esun\Review\Block\Order\ReviewableItems $block */ /** @var \Magento\Framework\Escaper $escaper */ $ratings=$block->getRatings(); ?>
<section class="block esun-order-reviews"><div class="block-title"><strong><?= $escaper->escapeHtml(__('Review Your Purchases')) ?></strong></div><div class="block-content">
<?php foreach($block->getItems() as $item): ?><div class="esun-order-review-item"><div><strong><?= $escaper->escapeHtml($item->getName()) ?></strong><?php if($block->hasReviewed($item)):?><span class="esun-order-review-status"><?= $escaper->escapeHtml(__('Reviewed')) ?></span><?php elseif(!$block->canReview($item)):?><span class="esun-order-review-status"><?= $escaper->escapeHtml(__('Available after payment')) ?></span><?php endif;?></div>
<?php if($block->canReview($item)):?><details><summary class="action primary"><?= $escaper->escapeHtml(__('Write a Review')) ?></summary><form class="review-form" action="<?= $escaper->escapeUrl($block->getPostUrl((int)$item->getProductId())) ?>" method="post" enctype="multipart/form-data"><?= $block->getBlockHtml('formkey') ?><input type="hidden" name="order_item_id" value="<?= (int)$item->getId() ?>">
<fieldset class="fieldset"><div class="field required"><label class="label"><span><?= $escaper->escapeHtml(__('Your Rating')) ?></span></label><div class="control"><?php foreach($ratings as $rating):?><div><span><?= $escaper->escapeHtml($rating->getRatingCode()) ?></span><?php foreach($rating->getOptions() as $option):?><label><input required type="radio" name="ratings[<?= (int)$rating->getId() ?>]" value="<?= (int)$option->getId() ?>"> <?= (int)$option->getValue() ?></label><?php endforeach;?></div><?php endforeach;?></div></div>
<div class="field required"><label class="label"><span><?= $escaper->escapeHtml(__('Review')) ?></span></label><div class="control"><textarea name="detail" required></textarea></div></div><div class="field"><label class="label"><span><?= $escaper->escapeHtml(__('Images or Video')) ?></span></label><div class="control"><input type="file" name="review_images[]" multiple accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,video/quicktime"><p class="note"><?= $escaper->escapeHtml(__('Upload JPG, PNG, GIF, WebP, MP4, WebM or MOV files.')) ?></p></div></div></fieldset><button class="action primary" type="submit"><span><?= $escaper->escapeHtml(__('Submit Review')) ?></span></button></form></details><?php endif;?></div><?php endforeach;?></div></section>
@@ -0,0 +1,38 @@
<?php
/**
* @var $block \Esun\Review\Block\Product\Review
*/
$canShowReviewForm = $block->canShowReviewForm();
$mageInit = [
'*' => [
'Esun_Review/js/product-reviews' => [
'productReviewUrl' => $block->getProductReviewUrl(),
],
],
'.product-reviews-section' => [
'Esun_Review/js/review-form-modal' => [],
],
];
?>
<div class="page-main page-main-reviews" id="reviews">
<div class="columns">
<div class="column main">
<div class="product-full-width-section product-reviews-section">
<div id="product-review-container" data-role="product-review"></div>
<?php if ($canShowReviewForm): ?>
<div class="esun-review-form-modal" data-role="esun-review-form-modal" hidden>
<div class="esun-review-form-modal__overlay" data-role="esun-review-form-close"></div>
<div class="esun-review-form-modal__dialog" role="dialog" aria-modal="true" aria-label="<?= $block->escapeHtmlAttr(__('Write A Review')) ?>">
<button class="esun-review-form-modal__close" type="button" data-role="esun-review-form-close">×</button>
<?= $block->getChildHtml() ?>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<script type="text/x-magento-init">
<?= /* @noEscape */ json_encode($mageInit, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>
</script>
@@ -0,0 +1,157 @@
<?php
use Magento\Framework\Escaper;
use Magento\Framework\View\Helper\SecureHtmlRenderer;
use Magento\Review\Block\Product\View\ListView;
/**
* @var ListView $block
* @var SecureHtmlRenderer $secureRenderer
* @var Escaper $escaper
*/
$imageBlock = $block->getLayout()->createBlock(\Esun\Review\Block\Review\Images::class);
$reviewData = $block->getLayout()->createBlock(\Esun\Review\Block\Review\Data::class);
$productId = $reviewData ? $reviewData->getCurrentProductId((int)$block->getProductId()) : 0;
$collection = $reviewData ? $reviewData->getReviewsCollection($productId, 10) : $block->getReviewsCollection();
$_items = $collection->getItems();
$toolbar = $block->getChildBlock('toolbar');
if ($toolbar) {
$toolbar->setCollection($collection);
}
$summary = $reviewData ? $reviewData->getSummary($productId) : ['score' => 0.0, 'count' => 0, 'percent' => 0];
$customerPhotos = $reviewData ? $reviewData->getCustomerPhotos($productId) : [];
$canWriteReview = false;
$reviewIds = array_map(static fn ($review): int => (int)$review->getReviewId(), $_items);
$customerIds = array_map(static fn ($review): int => (int)$review->getCustomerId(), $_items);
$votes = $reviewData ? $reviewData->getVotes($reviewIds) : [];
$reviewPercents = $reviewData ? $reviewData->getReviewPercents($reviewIds) : [];
$customerNames = $reviewData ? $reviewData->getCustomerNames($customerIds) : [];
$allPhotoUrls = array_column($customerPhotos, 'url');
?>
<div class="block review-list esun-customer-reviews" id="customer-reviews"
data-mage-init='{"Esun_Review/js/review-vote":{"voteUrl":"<?= $escaper->escapeUrl($reviewData ? $reviewData->getVoteUrl() : '') ?>"}}'>
<div class="esun-customer-reviews__header">
<div class="esun-customer-reviews__summary">
<h2 class="product-section-title"><?= $escaper->escapeHtml(__('Customer Reviews')) ?></h2>
<div class="esun-review-stars" aria-label="<?= $escaper->escapeHtmlAttr(__('%1 out of 5 stars', $summary['score'])) ?>">
<span class="esun-review-stars__base">★★★★★</span>
<span class="esun-review-stars__fill" style="width: <?= (int)$summary['percent'] ?>%;">★★★★★</span>
</div>
<span class="esun-customer-reviews__score">
<?= $escaper->escapeHtml(number_format((float)$summary['score'], 1)) ?>
<span>(<?= $escaper->escapeHtml(__('%1Reviews', (int)$summary['count'])) ?>)</span>
</span>
</div>
<div class="esun-customer-reviews__actions">
<div class="esun-customer-reviews__photos-wrap">
<?php if ($customerPhotos): ?>
<div class="esun-customer-reviews__photos-title"><?= $escaper->escapeHtml(__('Customer Photos')) ?></div>
<div class="esun-customer-reviews__photos"
data-mage-init='{"Esun_Catalog/js/drag-scroll":{},"Esun_Review/js/review-images":{}}'>
<?php foreach ($customerPhotos as $index => $photo): ?>
<button class="esun-review-images__thumb esun-customer-reviews__photo"
type="button"
data-index="<?= (int)$index ?>"
data-images="<?= $escaper->escapeHtmlAttr(json_encode($allPhotoUrls)) ?>">
<img src="<?= $escaper->escapeUrl($photo['thumb']) ?>" alt="">
</button>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php if ($canWriteReview): ?>
<button class="esun-write-review-trigger" type="button" data-role="esun-write-review-trigger">
<span><?= $escaper->escapeHtml(__('Write A Review')) ?></span>
<span class="esun-write-review-trigger__arrow" aria-hidden="true"></span>
</button>
<?php endif; ?>
</div>
</div>
<div class="block-content esun-customer-reviews__content">
<?php if (count($_items)): ?>
<ol class="items review-items esun-review-items">
<?php foreach ($_items as $_review): ?>
<?php
$reviewId = (int)$_review->getReviewId();
$images = $imageBlock ? $imageBlock->getImages($reviewId) : [];
$reviewMedia = array_map(static fn (array $media): array => [
'type' => (string)($media['type'] ?? 'image'),
'url' => (string)($media['url'] ?? ''),
'thumb' => (string)($media['thumb'] ?? $media['url'] ?? ''),
], $images);
$reviewVotes = $votes[$reviewId] ?? ['up' => 0, 'down' => 0, 'customer_vote' => 0];
$percent = (int)($reviewPercents[$reviewId] ?? 0);
$reviewMeta = [
'customer_id' => (int)$_review->getCustomerId(),
];
$customerName = $customerNames[(int)$reviewMeta['customer_id']] ?? (string)$_review->getNickname();
$createdAt = $_review->getCreatedAt() ? date('Y.m.d', strtotime((string)$_review->getCreatedAt())) : '';
?>
<li class="item review-item esun-review-item" itemscope itemprop="review" itemtype="http://schema.org/Review">
<div class="esun-review-item__heading">
<span class="esun-review-item__avatar" aria-hidden="true"></span>
<div class="esun-review-item__author">
<strong itemprop="author"><?= $escaper->escapeHtml($customerName) ?></strong>
<time itemprop="datePublished" datetime="<?= $escaper->escapeHtmlAttr($createdAt) ?>">
<?= $escaper->escapeHtml($createdAt) ?>
</time>
</div>
</div>
<div class="esun-review-stars esun-review-item__stars" aria-label="<?= $escaper->escapeHtmlAttr(__('%1 out of 5 stars', round($percent / 20, 1))) ?>">
<span class="esun-review-stars__base">★★★★★</span>
<span class="esun-review-stars__fill" style="width: <?= (int)$percent ?>%;">★★★★★</span>
</div>
<div class="esun-review-item__content" itemprop="description">
<?= /* @noEscape */ nl2br($escaper->escapeHtml($_review->getDetail())) ?>
</div>
<div class="esun-review-item__media-row">
<?php if ($images): ?>
<div class="esun-review-images" data-mage-init='{"Esun_Review/js/review-images":{}}'>
<?php foreach ($images as $index => $image): ?>
<?php if (($image['type'] ?? 'image') === 'video'): ?>
<button class="esun-review-images__thumb esun-review-video-thumb"
type="button"
aria-label="<?= $escaper->escapeHtmlAttr(__('Play review video')) ?>"
data-index="<?= (int)$index ?>"
data-media="<?= $escaper->escapeHtmlAttr(json_encode($reviewMedia, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT)) ?>">
<video preload="metadata" muted playsinline src="<?= $escaper->escapeUrl($image['url']) ?>"></video>
<span class="esun-review-video-thumb__play" aria-hidden="true"></span>
</button>
<?php else: ?><button class="esun-review-images__thumb"
type="button"
data-index="<?= (int)$index ?>"
data-media="<?= $escaper->escapeHtmlAttr(json_encode($reviewMedia, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT)) ?>">
<img src="<?= $escaper->escapeUrl($image['thumb']) ?>" alt="">
</button>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="esun-review-votes"
data-review-id="<?= (int)$reviewId ?>"
data-can-vote="<?= $reviewData && $reviewData->canVote($reviewMeta) ? '1' : '0' ?>">
<button class="esun-review-vote<?= (int)$reviewVotes['customer_vote'] === 1 ? ' is-active' : '' ?>"
type="button"
data-vote-type="1"
aria-label="<?= $escaper->escapeHtmlAttr(__('Thumb up')) ?>">
<span class="esun-review-vote__icon">♡</span>
<span data-role="vote-up-count"><?= (int)$reviewVotes['up'] ?></span>
</button>
<button class="esun-review-vote<?= (int)$reviewVotes['customer_vote'] === -1 ? ' is-active' : '' ?>"
type="button"
data-vote-type="-1"
aria-label="<?= $escaper->escapeHtmlAttr(__('Thumb down')) ?>">
<span class="esun-review-vote__icon">♡</span>
<span data-role="vote-down-count"><?= (int)$reviewVotes['down'] ?></span>
</button>
</div>
</div>
</li>
<?php endforeach; ?>
</ol>
<div class="toolbar review-toolbar esun-review-toolbar"><?= $block->getChildHtml('toolbar') ?></div>
<?php else: ?>
<p class="esun-review-empty"><?= $escaper->escapeHtml(__('There are no reviews yet.')) ?></p>
<?php endif; ?>
</div>
</div>
@@ -0,0 +1,108 @@
<?php
/** @var \Magento\Review\Block\Form $block */
/** @var \Magento\Framework\Escaper $escaper */
$escaper = $escaper ?? $block;
?>
<form action="<?= $escaper->escapeUrl($block->getAction()) ?>"
class="review-form"
method="post"
id="review-form"
enctype="multipart/form-data"
data-role="product-review-form"
data-bind="scope: 'review-form'">
<?= $block->getBlockHtml('formkey') ?>
<?= $block->getChildHtml('form_fields_before') ?>
<fieldset class="fieldset review-fieldset" data-hasrequired="<?= $escaper->escapeHtmlAttr(__('* Required Fields')) ?>">
<?php if ($block->getRatings() && $block->getRatings()->getSize()): ?>
<span id="input-message-box"></span>
<fieldset class="field required review-field-ratings">
<legend class="label"><span><?= $escaper->escapeHtml(__('Your Rating')) ?></span></legend><br/>
<div class="control">
<div class="nested" id="product-review-table">
<?php foreach ($block->getRatings() as $_rating): ?>
<div class="field choice review-field-rating">
<label class="label" id="<?= $escaper->escapeHtmlAttr($_rating->getRatingCode()) ?>_rating_label"><span><?= $escaper->escapeHtml(__('Your Rating')) ?></span></label>
<div class="control review-control-vote">
<?php $options = $_rating->getOptions(); ?>
<?php $iterator = 1; foreach ($options as $_option): ?>
<input type="radio"
name="ratings[<?= $escaper->escapeHtmlAttr($_rating->getId()) ?>]"
id="<?= $escaper->escapeHtmlAttr($_rating->getRatingCode()) ?>_<?= $escaper->escapeHtmlAttr($_option->getValue()) ?>"
value="<?= $escaper->escapeHtmlAttr($_option->getId()) ?>"
class="radio"
data-validate="{'rating-required':true}"
aria-labelledby="<?= $escaper->escapeHtmlAttr($_rating->getRatingCode()) ?>_rating_label <?= $escaper->escapeHtmlAttr($_rating->getRatingCode()) ?>_<?= $escaper->escapeHtmlAttr($_option->getValue()) ?>_label" />
<label class="rating-<?= $escaper->escapeHtmlAttr($iterator) ?>" for="<?= $escaper->escapeHtmlAttr($_rating->getRatingCode()) ?>_<?= $escaper->escapeHtmlAttr($_option->getValue()) ?>" title="<?= $escaper->escapeHtmlAttr(__('%1 %2', $iterator, $iterator > 1 ? __('stars') : __('star'))) ?>" id="<?= $escaper->escapeHtmlAttr($_rating->getRatingCode()) ?>_<?= $escaper->escapeHtmlAttr($_option->getValue()) ?>_label"><span><?= $escaper->escapeHtml(__('%1 %2', $iterator, $iterator > 1 ? __('stars') : __('star'))) ?></span></label>
<?php $iterator++; ?>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<input type="hidden" name="validate_rating" class="validate-rating" value="" />
</div>
</fieldset>
<?php endif ?>
<div class="field review-field-nickname required esun-review-hidden-field">
<div class="control"><input type="hidden" name="nickname" id="nickname_field" data-bind="value: nickname()" /></div>
</div>
<div class="field review-field-summary required esun-review-hidden-field">
<div class="control"><input type="hidden" name="title" id="summary_field" /></div>
</div>
<div class="field review-field-text required">
<label for="review_field" class="label"><span><?= $escaper->escapeHtml(__('Review')) ?></span></label>
<div class="control"><textarea name="detail" id="review_field" cols="5" rows="3" data-validate="{required:true}" data-bind="value: review().detail"></textarea></div>
</div>
<div class="field review-field-images">
<label for="review_images" class="label"><span><?= $escaper->escapeHtml(__('Images or Video')) ?></span></label>
<div class="control">
<input type="file"
name="review_images[]"
id="review_images"
multiple
accept="image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,video/quicktime"
onchange="window.esunRenderReviewImagePreview && window.esunRenderReviewImagePreview(this)">
<div class="esun-review-upload-preview" data-role="review-image-preview"></div>
<p class="note"><?= $escaper->escapeHtml(__('Upload JPG, PNG, GIF, WebP, MP4, WebM or MOV files.')) ?></p>
</div>
</div>
</fieldset>
<div class="actions-toolbar review-form-actions">
<div class="primary actions-primary">
<button type="submit" class="action submit primary"><span><?= $escaper->escapeHtml(__('Submit Review')) ?></span></button>
</div>
</div>
</form>
<script>
window.esunRenderReviewImagePreview = window.esunRenderReviewImagePreview || function (input) {
var preview = input && input.form ? input.form.querySelector('[data-role="review-image-preview"]') : null,
files = input && input.files ? Array.prototype.slice.call(input.files) : [];
if (!preview) {
return;
}
preview.innerHTML = '';
files.forEach(function (file) {
var reader = new FileReader();
reader.onload = function (event) {
var image = document.createElement('img');
image.src = event.target.result;
image.alt = file.name || '';
preview.appendChild(image);
};
reader.readAsDataURL(file);
});
};
</script>
<script type="text/x-magento-init">
{
"[data-role=product-review-form]": {
"Magento_Ui/js/core/app": <?= /* @noEscape */ $block->getJsLayout() ?>
},
"#review-form": {
"Magento_Review/js/error-placement": {},
"Magento_Review/js/validate-review": {},
"Magento_Captcha/js/checkout/captcha": {}
}
}
</script>
@@ -0,0 +1,30 @@
<?php
/**
* @var \Magento\Review\Block\Product\ReviewRenderer $block
* @var \Magento\Framework\Escaper $escaper
*/
?>
<?php if ($block->isReviewEnabled()): ?>
<?php
$reviewsCount = (int)$block->getData('esun_reviews_count');
$rating = (int)$block->getData('esun_rating_summary');
$ratingValue = $rating > 0 ? number_format($rating / 20, 1) : '';
$reviewsUrl = $block->getReviewsUrl() . '#reviews';
?>
<div class="product-reviews-summary<?= !$rating ? ' no-rating' : '' ?> esun-review-summary">
<div class="rating-summary">
<span class="label"><span><?= $escaper->escapeHtml(__('Rating')) ?>:</span></span>
<div class="rating-result"
id="rating-result_<?= $escaper->escapeHtmlAttr($block->getProduct()->getId()) ?>"
title="<?= $escaper->escapeHtmlAttr((string)$rating) ?>%">
<span style="width: <?= $escaper->escapeHtmlAttr((string)$rating) ?>%;"><span></span></span>
</div>
</div>
<?php if ($reviewsCount > 0): ?>
<a class="esun-review-summary__meta" href="<?= $escaper->escapeUrl($reviewsUrl) ?>">
<span class="esun-review-summary__score"><?= $escaper->escapeHtml($ratingValue) ?></span>
<span class="esun-review-summary__count">(<?= $escaper->escapeHtml((string)$reviewsCount) ?><?= $escaper->escapeHtml($reviewsCount === 1 ? __('Review') : __('Reviews')) ?>)</span>
</a>
<?php endif; ?>
</div>
<?php endif; ?>
@@ -0,0 +1,547 @@
.catalog-product-view
.product-info-main
.product-reviews-summary.esun-review-summary {
align-items: center;
display: flex;
gap: 10px;
margin: 0 0 18px;
}
.esun-customer-reviews .action.primary,
.esun-order-review-item .action.primary,
.esun-awaiting-reviews .action.primary,
.review-form .action.primary {
background: #18aa59;
background-image: none;
border-color: #18aa59;
color: #fff;
}
.esun-customer-reviews .action.primary:hover,
.esun-customer-reviews .action.primary:focus,
.esun-order-review-item .action.primary:hover,
.esun-order-review-item .action.primary:focus,
.esun-awaiting-reviews .action.primary:hover,
.esun-awaiting-reviews .action.primary:focus,
.review-form .action.primary:hover,
.review-form .action.primary:focus {
background: #148f4b;
background-image: none;
border-color: #148f4b;
color: #fff;
}
.catalog-product-view
.product-info-main
.product-reviews-summary.esun-review-summary
.rating-summary {
display: flex;
margin: 0;
}
.catalog-product-view
.product-info-main
.product-reviews-summary.esun-review-summary
.rating-summary
.label {
display: none;
}
.catalog-product-view
.product-info-main
.product-reviews-summary.esun-review-summary
.rating-result {
margin: 0;
}
.catalog-product-view .product-info-main .esun-review-summary__meta {
color: #888;
font-size: 13px;
line-height: 1;
text-decoration: none;
}
.catalog-product-view .product-info-main .esun-review-summary__score {
margin-right: 4px;
}
.rating-summary .rating-result > span:before {
color: #ffd800;
}
.catalog-product-view .esun-review-images {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 14px 0 0;
}
.catalog-product-view .esun-review-images__thumb {
background: transparent;
border: 0;
border-radius: 6px;
cursor: pointer;
height: 72px;
overflow: hidden;
padding: 0;
position: relative;
width: 72px;
}
.catalog-product-view .esun-review-images__thumb img,
.catalog-product-view .esun-review-images__thumb video {
border-radius: 6px;
height: 100%;
object-fit: cover;
width: 100%;
}
.catalog-product-view .esun-review-video-thumb__play {
align-items: center;
background: rgba(0, 0, 0, 0.58);
border: 2px solid #fff;
border-radius: 50%;
display: inline-flex;
height: 30px;
justify-content: center;
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 30px;
}
.catalog-product-view .esun-review-video-thumb__play:after {
border-bottom: 6px solid transparent;
border-left: 9px solid #fff;
border-top: 6px solid transparent;
content: "";
margin-left: 2px;
}
.catalog-product-view .page-main-reviews {
margin: 50px auto 0;
padding: 0;;
}
.catalog-product-view .product-reviews-section .product-section-title,
.catalog-product-view .esun-customer-reviews .product-section-title {
border: 0;
color: #333;
font-size: 34px;
font-weight: 700;
letter-spacing: 8px;
line-height: 1.2;
margin: 0 0 42px;
position: relative;
text-transform: uppercase;
}
.catalog-product-view .product-reviews-section .product-section-title:after,
.catalog-product-view .esun-customer-reviews .product-section-title:after {
background: #18a957;
border-radius: 999px;
bottom: -22px;
content: "";
height: 2px;
left: 0;
position: absolute;
width: 50px;
}
.catalog-product-view .esun-customer-reviews__header {
align-items: flex-start;
display: grid;
gap: 28px;
grid-template-columns: minmax(280px, 1fr) minmax(420px, 780px);
margin-bottom: 36px;
}
.catalog-product-view .esun-customer-reviews__summary {
min-width: 0;
}
.catalog-product-view .esun-review-stars {
color: #cfcfcf;
display: inline-block;
font-size: 18px;
line-height: 1;
position: relative;
white-space: nowrap;
}
.catalog-product-view .esun-review-stars__base,
.catalog-product-view .esun-review-stars__fill {
display: block;
}
.catalog-product-view .esun-review-stars__fill {
color: #ffd800;
left: 0;
overflow: hidden;
position: absolute;
top: 0;
}
.catalog-product-view .esun-customer-reviews__score {
color: #888;
display: inline-flex;
font-size: 15px;
gap: 8px;
margin-left: 20px;
vertical-align: 2px;
}
.catalog-product-view .esun-customer-reviews__actions {
align-items: center;
display: flex;
gap: 36px;
justify-content: flex-end;
justify-self: end;
min-width: 0;
width: 100%;
}
.catalog-product-view .esun-customer-reviews__photos-wrap {
align-items: flex-end;
display: flex;
flex-direction: column;
margin-left: auto;
max-width: 580px;
min-width: 0;
text-align: right;
}
.catalog-product-view .esun-customer-reviews__photos-title {
color: #333;
font-size: 13px;
font-weight: 700;
margin-bottom: 8px;
text-align: left;
width: 100%;
}
.catalog-product-view .esun-customer-reviews__photos {
cursor: grab;
display: flex;
gap: 10px;
justify-content: flex-end;
max-width: 100%;
overflow-x: auto;
scrollbar-width: none;
user-select: none;
width: max-content;
}
.catalog-product-view .esun-customer-reviews__photos::-webkit-scrollbar {
display: none;
}
.catalog-product-view .esun-customer-reviews__photos.is-dragging {
cursor: grabbing;
}
.catalog-product-view .esun-customer-reviews__photo {
flex: 0 0 88px;
height: 88px;
width: 88px;
}
.catalog-product-view .esun-write-review-trigger {
align-items: center;
align-self: center;
background: transparent;
border: 0;
color: #18a957;
cursor: pointer;
display: inline-flex;
font-size: 14px;
font-weight: 700;
gap: 16px;
white-space: nowrap;
}
.catalog-product-view .esun-write-review-trigger:hover,
.catalog-product-view .esun-write-review-trigger:focus,
.catalog-product-view .esun-write-review-trigger:active {
background: transparent;
border: 0;
box-shadow: none;
color: #18a957;
outline: 0;
}
.catalog-product-view .esun-write-review-trigger__arrow {
border-right: 2px solid #18a957;
border-top: 2px solid #18a957;
height: 7px;
transform: rotate(45deg);
width: 7px;
}
.catalog-product-view .esun-review-items {
list-style: none;
margin: 0;
padding: 0;
}
.catalog-product-view .esun-review-item {
border-bottom: 1px solid #e1e1e1;
margin: 0;
padding: 24px 0 28px;
}
.catalog-product-view .esun-review-item__heading {
align-items: center;
display: flex;
gap: 10px;
margin-bottom: 14px;
}
.catalog-product-view .esun-review-item__avatar {
background: #b7b7b7;
border-radius: 50%;
flex: 0 0 32px;
height: 32px;
width: 32px;
}
.catalog-product-view .esun-review-item__author {
display: grid;
gap: 2px;
}
.catalog-product-view .esun-review-item__author strong {
color: #333;
font-size: 14px;
}
.catalog-product-view .esun-review-item__author time {
color: #777;
font-size: 13px;
}
.catalog-product-view .esun-review-item__stars {
display: inline-block;
margin-bottom: 12px;
}
.catalog-product-view .esun-review-item__content {
color: #333;
font-size: 16px;
line-height: 1.55;
margin-bottom: 12px;
}
.catalog-product-view .esun-review-item__media-row {
align-items: flex-end;
display: flex;
gap: 16px;
justify-content: space-between;
}
.catalog-product-view .esun-review-votes {
align-items: center;
display: inline-flex;
gap: 12px;
margin-left: auto;
}
.catalog-product-view .esun-review-vote {
align-items: center;
background: transparent;
border: 0;
color: #333;
cursor: pointer;
display: inline-flex;
font-size: 13px;
gap: 4px;
padding: 0;
}
.catalog-product-view .esun-review-votes[data-can-vote="0"] .esun-review-vote {
cursor: default;
}
.catalog-product-view .esun-review-vote.is-active {
color: #18a957;
}
.catalog-product-view
.esun-review-vote[data-vote-type="-1"]
.esun-review-vote__icon {
display: inline-block;
transform: rotate(180deg);
}
.catalog-product-view .esun-review-toolbar {
border-top: 0;
margin-top: 28px;
text-align: center;
}
.catalog-product-view .esun-review-toolbar .pages {
border-bottom: 0;
}
.catalog-product-view .esun-review-toolbar .toolbar-amount,
.catalog-product-view .esun-review-toolbar .limiter {
display: none;
}
.catalog-product-view .esun-review-toolbar .pages {
align-items: center;
display: inline-flex;
gap: 24px;
}
.catalog-product-view .esun-review-toolbar .pages-items {
align-items: center;
display: inline-flex;
gap: 20px;
list-style: none;
margin: 0;
padding: 0;
}
.catalog-product-view .esun-review-toolbar .item a,
.catalog-product-view .esun-review-toolbar .item strong {
align-items: center;
background: #cfe8dc;
border-radius: 999px;
color: transparent;
display: inline-flex;
height: 8px;
justify-content: center;
overflow: hidden;
text-decoration: none;
width: 8px;
}
.catalog-product-view .esun-review-toolbar .item.current strong {
background: #18a957;
height: 8px;
width: 30px;
}
.catalog-product-view .esun-review-toolbar .item.pages-item-previous a,
.catalog-product-view .esun-review-toolbar .item.pages-item-next a {
background: transparent;
border-right: 2px solid #18a957;
border-top: 2px solid #18a957;
border-radius: 0;
height: 10px;
width: 10px;
}
.catalog-product-view .esun-review-toolbar .item.pages-item-previous a {
transform: rotate(-135deg);
}
.catalog-product-view .esun-review-toolbar .item.pages-item-next a {
transform: rotate(45deg);
}
.catalog-product-view .esun-review-form-modal {
align-items: center;
display: flex;
inset: 0;
justify-content: center;
padding: 24px;
position: fixed;
z-index: 1002;
}
.catalog-product-view .esun-review-form-modal[hidden] {
display: none;
}
.catalog-product-view .esun-review-form-modal__overlay {
background: rgba(0, 0, 0, 0.58);
inset: 0;
position: absolute;
}
.catalog-product-view .esun-review-form-modal__dialog {
background: #fff;
border-radius: 8px;
max-height: calc(100vh - 48px);
max-width: 720px;
overflow: auto;
padding: 32px;
position: relative;
width: min(720px, 100%);
z-index: 1;
}
.catalog-product-view .esun-review-form-modal__close {
align-items: center;
background: #111;
border: 2px solid #fff;
border-radius: 50%;
color: #fff;
cursor: pointer;
display: inline-flex;
font-size: 28px;
height: 40px;
justify-content: center;
line-height: 40px;
padding: 0;
position: absolute;
right: 12px;
top: 12px;
width: 40px;
}
.catalog-product-view .esun-review-hidden-field,
.catalog-product-view .review-field-rating > .label {
display: none;
}
.catalog-product-view .esun-review-upload-preview {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.catalog-product-view .esun-review-upload-preview img {
border-radius: 6px;
height: 72px;
object-fit: cover;
width: 72px;
}
.esun-review-lightbox {
align-items: center;
background: rgba(0, 0, 0, 0.62);
display: flex;
inset: 0;
justify-content: center;
padding: 0;
position: fixed;
z-index: 1000;
}
.esun-review-lightbox[hidden] {
display: none;
}
.esun-review-lightbox__image {
border-radius: 8px;
max-height: min(90vh, 680px);
max-width: min(90vw, 680px);
object-fit: contain;
}
.esun-review-lightbox__video {
background: #000;
border-radius: 8px;
max-height: 90vh;
max-width: 90vw;
width: min(90vw, 960px);
}
.esun-review-lightbox__image[hidden],
.esun-review-lightbox__video[hidden] {
display: none;
}
.esun-review-lightbox__close,
.esun-review-lightbox__prev,
.esun-review-lightbox__next {
align-items: center;
background: #fff;
border: 1px solid #18a957;
border-radius: 999px;
color: #18a957;
cursor: pointer;
display: inline-flex;
font-size: 30px;
height: 44px;
justify-content: center;
line-height: 0.8;
position: fixed;
width: 44px;
}
.esun-review-lightbox__close {
background: #1d0e0d;
border: 3px solid #fff;
color: #fff;
right: 24px;
top: 24px;
}
.esun-review-lightbox__prev {
left: 24px;
top: 50%;
}
.esun-review-lightbox__next {
right: 24px;
top: 50%;
}
@media (max-width: 767px) {
.catalog-product-view .esun-customer-reviews__header {
grid-template-columns: 1fr;
}
.catalog-product-view .esun-customer-reviews__actions {
align-items: flex-start;
flex-direction: column;
gap: 18px;
justify-content: flex-start;
justify-self: stretch;
}
.catalog-product-view .esun-customer-reviews__photos-wrap {
align-items: flex-start;
margin-left: 0;
max-width: 100%;
text-align: left;
}
.catalog-product-view .esun-customer-reviews__photos {
justify-content: flex-start;
width: 100%;
}
.catalog-product-view .product-reviews-section .product-section-title,
.catalog-product-view .esun-customer-reviews .product-section-title {
font-size: 20px;
letter-spacing: 2px;
}
.catalog-product-view .esun-review-item__media-row {
align-items: flex-start;
flex-direction: column;
}
.catalog-product-view .esun-review-votes {
align-self: flex-end;
}
}
.catalog-product-view .esun-review-item:last-child{border-bottom:0}.esun-order-review-item{padding:16px 0;border-bottom:1px solid #ddd}.esun-order-review-status{margin-left:12px;color:#666}.esun-order-review-item details{margin-top:12px}.esun-order-review-item summary{display:inline-block;cursor:pointer}.esun-order-review-item form{margin-top:16px;max-width:720px}
@@ -0,0 +1,47 @@
define([
'jquery'
], function ($) {
'use strict';
function loadReviews(url, fromPages) {
$.ajax({
url: url,
cache: true,
dataType: 'html',
showLoader: false,
loaderContext: $('.product-reviews-section')
}).done(function (data) {
$('#product-review-container').html(data).trigger('contentUpdated');
$('[data-role="product-review"] .pages a').on('click', function (event) {
event.preventDefault();
loadReviews($(this).attr('href'), true);
});
}).always(function () {
if (fromPages) {
$('html, body').animate({
scrollTop: $('#reviews').offset().top - 50
}, 300);
}
});
}
return function (config) {
$(function () {
if (config.productReviewUrl) {
loadReviews(config.productReviewUrl, location.hash === '#reviews');
}
$('.product-info-main .reviews-actions a').on('click', function (event) {
var anchor = $(this).attr('href').replace(/^.*?(#|$)/, ''),
target = $('#' + anchor);
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top - 50
}, 300);
}
});
});
};
});
@@ -0,0 +1,73 @@
define(['jquery', 'mage/translate'], function ($, $t) {
'use strict';
return function (config, element) {
var $root = $(element),
$modal = $root.find('[data-role="esun-review-form-modal"]');
function openModal() {
if (!$modal.length) {
return;
}
$modal.removeAttr('hidden');
$('body').addClass('esun-review-form-modal-open');
}
function closeModal() {
if (!$modal.length) {
return;
}
$modal.attr('hidden', true);
$('body').removeClass('esun-review-form-modal-open');
}
$root.on('click', '[data-role="esun-write-review-trigger"]', openModal);
$root.on('click', '[data-role="esun-review-form-close"]', closeModal);
$(document).on('keyup.esunReviewFormModal', function (event) {
if (event.key === 'Escape') {
closeModal();
}
});
function renderImagePreview(input) {
var files = Array.prototype.slice.call(input.files || []),
$preview = $(input).closest('form').find('[data-role="review-image-preview"]');
$preview.empty();
$.each(files, function (index, file) {
var reader = new FileReader();
reader.onload = function (event) {
$('<img/>', {
src: event.target.result,
alt: file.name
}).appendTo($preview);
};
reader.readAsDataURL(file);
});
}
$root.on('change', '#review_images', function () {
renderImagePreview(this);
});
$(document)
.off('change.esunReviewImages', '#review_images')
.on('change.esunReviewImages', '#review_images', function () {
renderImagePreview(this);
});
$root.on('submit', '#review-form', function () {
var $form = $(this),
detail = $.trim($form.find('#review_field').val() || ''),
nickname = $.trim($form.find('#nickname_field').val() || '');
if (!nickname) {
nickname = $.trim($('.customer-name, .logged-in').first().text()) || $t('Customer');
$form.find('#nickname_field').val(nickname);
}
$form.find('#summary_field').val(detail.substring(0, 120) || $t('Review'));
});
};
});
@@ -0,0 +1,104 @@
define(['jquery'], function ($) {
'use strict';
var $modal;
function ensureModal() {
if ($modal) {
return $modal;
}
$modal = $('<div/>', {'class': 'esun-review-lightbox', hidden: true})
.append($('<button/>', {'class': 'esun-review-lightbox__close', type: 'button', text: '×'}))
.append($('<button/>', {'class': 'esun-review-lightbox__prev', type: 'button', text: '‹'}))
.append($('<img/>', {'class': 'esun-review-lightbox__image', alt: ''}))
.append($('<video/>', {
'class': 'esun-review-lightbox__video',
controls: true,
hidden: true,
playsinline: true,
preload: 'metadata'
}))
.append($('<button/>', {'class': 'esun-review-lightbox__next', type: 'button', text: '›'}))
.appendTo(document.body);
$modal.on('click', '.esun-review-lightbox__close', close);
$modal.on('click', '.esun-review-lightbox__prev', function () {
show(($modal.data('index') || 0) - 1);
});
$modal.on('click', '.esun-review-lightbox__next', function () {
show(($modal.data('index') || 0) + 1);
});
return $modal;
}
function stopVideo() {
var video = $modal && $modal.find('.esun-review-lightbox__video').get(0);
if (!video) {
return;
}
video.pause();
video.removeAttribute('src');
video.load();
}
function show(index) {
var media = $modal.data('media') || [],
item,
video;
if (!media.length) {
return;
}
index = (index + media.length) % media.length;
$modal.data('index', index);
item = media[index];
if (item.type === 'video') {
$modal.find('.esun-review-lightbox__image').attr('hidden', true).removeAttr('src');
video = $modal.find('.esun-review-lightbox__video')
.removeAttr('hidden')
.attr('src', item.url)
.get(0);
video.load();
video.play().catch(function () {});
return;
}
stopVideo();
$modal.find('.esun-review-lightbox__video').attr('hidden', true);
$modal.find('.esun-review-lightbox__image').removeAttr('hidden').attr('src', item.url);
}
function close() {
stopVideo();
$modal.attr('hidden', true);
}
function getMedia($button) {
var media = $button.data('media'),
images;
if (Array.isArray(media)) {
return media;
}
images = $button.data('images') || [];
return images.map(function (url) {
return {type: 'image', url: url, thumb: url};
});
}
return function (config, element) {
$(element).on('click', '.esun-review-images__thumb', function () {
var $button = $(this),
media = getMedia($button);
ensureModal();
$modal.data('media', media).attr('hidden', false);
show(parseInt($button.data('index'), 10) || 0);
});
};
});
@@ -0,0 +1,39 @@
define(['jquery'], function ($) {
'use strict';
return function (config, element) {
var $root = $(element),
voteUrl = config.voteUrl || '';
$root.on('click', '.esun-review-vote', function () {
var $button = $(this),
$votes = $button.closest('.esun-review-votes'),
reviewId = parseInt($votes.data('review-id'), 10) || 0,
voteType = parseInt($button.data('vote-type'), 10) || 0;
if (!voteUrl || !reviewId || $votes.data('can-vote') !== 1) {
return;
}
$.ajax({
url: voteUrl,
type: 'POST',
dataType: 'json',
data: {
review_id: reviewId,
vote_type: voteType,
form_key: $('input[name="form_key"]').first().val() || ($.mage && $.mage.cookies ? $.mage.cookies.get('form_key') : '')
}
}).done(function (response) {
if (!response || !response.success) {
return;
}
$votes.find('[data-role="vote-up-count"]').text(response.up || 0);
$votes.find('[data-role="vote-down-count"]').text(response.down || 0);
$votes.find('.esun-review-vote').removeClass('is-active');
$votes.find('[data-vote-type="' + response.customer_vote + '"]').addClass('is-active');
});
});
};
});