Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
ngovanvinh committed Aug 20, 2020
2 parents 9d013e8 + eb0471d commit c5f5125
Show file tree
Hide file tree
Showing 12 changed files with 418 additions and 257 deletions.
116 changes: 68 additions & 48 deletions Model/Resolver/CreateReview.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,27 @@

namespace Mageplaza\BetterProductReviewsGraphQl\Model\Resolver;

use Exception;
use Magento\Catalog\Model\Product;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;
use Magento\Framework\GraphQl\Query\Resolver\Value;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Review\Model\Rating;
use Magento\Review\Model\Rating\Option;
use Magento\Review\Model\RatingFactory;
use Magento\Review\Model\Review;
use Magento\Review\Model\ReviewFactory;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item;
use Magento\Sales\Model\OrderFactory;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\BetterProductReviews\Helper\Data;
use Mageplaza\BetterProductReviews\Model\Config\Source\BuyerType;
use Mageplaza\BetterProductReviews\Model\Config\Source\System\CustomerRestriction;

/**
Expand Down Expand Up @@ -80,13 +82,19 @@ class CreateReview implements ResolverInterface
*/
protected $_orderFactory;

/**
* @var StoreManagerInterface
*/
protected $storeManager;

/**
* CreateReview constructor.
*
* @param RatingFactory $ratingFactory
* @param Product $productModel
* @param CustomerRepositoryInterface $customerRepositoryInterface
* @param Data $helperData
* @param StoreManagerInterface $storeManager
* @param OrderFactory $orderFactory
* @param ReviewFactory $reviewFactory
*/
Expand All @@ -95,28 +103,21 @@ public function __construct(
Product $productModel,
CustomerRepositoryInterface $customerRepositoryInterface,
Data $helperData,
StoreManagerInterface $storeManager,
OrderFactory $orderFactory,
ReviewFactory $reviewFactory
) {
$this->_rating = $ratingFactory;
$this->_review = $reviewFactory;
$this->_product = $productModel;
$this->_orderFactory = $orderFactory;
$this->storeManager = $storeManager;
$this->_helperData = $helperData;
$this->_customerRepositoryInterface = $customerRepositoryInterface;
}

/**
* Fetches the data from persistence models and format it according to the GraphQL schema.
*
* @param Field $field
* @param ContextInterface $context
* @param ResolveInfo $info
* @param array|null $value
* @param array|null $args
*
* @return mixed|Value
* @throws Exception
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
Expand All @@ -131,40 +132,50 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value
throw new GraphQlInputException(__('The Product does not exit.'));
}

$storeId = isset($data['store_id']) ? $data['store_id'] : 1;
$customerId = $this->isUserGuest($context->getUserId(), $productId);
$avgValue = isset($data['avg_value']) ? (int) $data['avg_value'] : 5;
$storeId = $this->storeManager->getStore()->getId();
$customerId = $context->getUserId() ?: null;
$avgValue = (int) $data['avg_value'];

if ($this->isUserGuest($customerId, $productId) === false) {
$noticeMessage = $this->_helperData->getWriteReviewConfig('notice_message') ?? __('The current customer isn\'t authorized.');
throw new GraphQlAuthorizationException($noticeMessage);
}

if ($customerId === false || $avgValue > 5 || $avgValue <= 0) {
throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
if ($avgValue > 5 || $avgValue <= 0) {
throw new GraphQlAuthorizationException(__('The avg_value value must be between 0 and 5.'));
}

$status = isset($data['status_id']) ? $data['status_id'] : Review::STATUS_PENDING;
$ratings = $this->getRatingCollection($storeId);
$object = $this->_review->create()->setData($data);
$object->unsetData('review_id');
$status = isset($data['status_id']) ? $data['status_id'] : Review::STATUS_PENDING;
$data['mp_bpr_verified_buyer'] = $this->checkIsBuyer($customerId, $productId)
? BuyerType::VERIFIED_BUYER : BuyerType::NOT_VERIFIED_BUYER;
$ratings = $this->getRatingCollection($storeId);
/** @var \Magento\Review\Model\Review $reviewModel */
$reviewModel = $this->_review->create()->setData($data);
$reviewModel->unsetData('review_id');

if ($object->validate()) {
$object->setEntityId($object->getEntityIdByCode(Review::ENTITY_PRODUCT_CODE))
if ($reviewModel->validate()) {
$reviewModel->setEntityId($reviewModel->getEntityIdByCode(Review::ENTITY_PRODUCT_CODE))
->setEntityPkValue($productId)
->setStatusId($status)
->setCustomerId($customerId)
->setStoreId($storeId)
->setStores([$storeId])
->save();
foreach ($ratings as $ratingId => $rating) {
/** @var Rating $rating */
foreach ($rating->getOptions() as $option) {
/** @var Option $option */
if ((int) $option->getValue() === $avgValue) {
$this->_rating->create()
->setRatingId($ratingId)
->setReviewId($object->getId())
->setReviewId($reviewModel->getId())
->setCustomerId($customerId)
->addOptionVote($option->getId(), $productId);
}
}
}
$object->aggregate();
$collection = $object->getCollection();
$reviewModel->aggregate();
$collection = $reviewModel->getCollection();
$collection->getSelect()->join(
['mp_detail' => $collection->getTable('review_detail')],
'main_table.review_id = mp_detail.review_id',
Expand All @@ -173,7 +184,9 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value
['mp_vote' => $collection->getTable('rating_option_vote')],
'main_table.review_id = mp_vote.review_id',
['avg_value' => 'mp_vote.value']
)->where('main_table.review_id = ?', $object->getId())->group('main_table.review_id');
)->where('main_table.review_id = ?', $reviewModel->getId())
->group('main_table.review_id')
->limit(1);

return $collection->getFirstItem();
}
Expand All @@ -184,10 +197,9 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value
/**
* @param $storeId
*
* @return mixed
* @throws LocalizedException
* @return AbstractCollection
*/
public function getRatingCollection($storeId)
public function getRatingCollection($storeId): AbstractCollection
{
return $this->_rating->create()->getResourceCollection()->addEntityFilter(
'product'
Expand All @@ -201,24 +213,24 @@ public function getRatingCollection($storeId)
}

/**
* @param $currentUserId
* @param string $currentUserId
* @param $productId
*
* @return bool|null
* @return bool
* @throws LocalizedException
*/
public function isUserGuest($currentUserId, $productId)
public function isUserGuest($currentUserId, $productId): bool
{
if ($this->_helperData->isEnabled() && $this->isEnableWrite($currentUserId, $productId)) {
$mpGroupArray = explode(',', $this->_helperData->getWriteReviewConfig('customer_group'));
$allowCustomerGroup = explode(',', $this->_helperData->getWriteReviewConfig('customer_group'));
try {
$customerGroup = $this->_customerRepositoryInterface->getById($currentUserId)->getGroupId();
} catch (NoSuchEntityException $exception) {
$customerGroup = '0';
}

if (in_array($customerGroup, $mpGroupArray, true)) {
return $currentUserId ?: null;
if (in_array($customerGroup, $allowCustomerGroup, true)) {
return true;
}
}

Expand All @@ -231,14 +243,8 @@ public function isUserGuest($currentUserId, $productId)
*
* @return bool
*/
public function isEnableWrite($customerId, $productId)
protected function checkIsBuyer($customerId, $productId): bool
{
if ((int) $this->_helperData->getWriteReviewConfig('enabled') !== CustomerRestriction::PURCHASERS_ONLY) {
return (bool) $this->_helperData->getWriteReviewConfig('enabled');
}

$result = false;

if ($customerId) {
$orders = $this->_orderFactory->create()->getCollection()
->addFieldToFilter('customer_id', $customerId)
Expand All @@ -249,14 +255,28 @@ public function isEnableWrite($customerId, $productId)
*/
foreach ($order->getAllVisibleItems() as $item) {
/** @var Item $item */
if ($productId == $item->getProductId()) {
$result = true;
break;
if ($productId === (int) $item->getProductId()) {
return true;
}
}
}
}

return $result;
return false;
}

/**
* @param $customerId
* @param $productId
*
* @return bool
*/
public function isEnableWrite($customerId, $productId): bool
{
if ((int) $this->_helperData->getWriteReviewConfig('enabled') !== CustomerRestriction::PURCHASERS_ONLY) {
return (bool) $this->_helperData->getWriteReviewConfig('enabled');
}

return $this->checkIsBuyer($customerId, $productId);
}
}
6 changes: 3 additions & 3 deletions Model/Resolver/Filter/DataProvider/Review.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@

namespace Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\DataProvider;

use Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SearchResultsInterface;
use Mageplaza\BetterProductReviews\Helper\Data;
use Mageplaza\BetterProductReviews\Model\ResourceModel\Review\CollectionFactory;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
use Mageplaza\BetterProductReviews\Model\ResourceModel\Review\CollectionFactory;
use Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory;
use Magento\Framework\Api\SearchResultsInterface;

/**
* Product field data provider, used for GraphQL resolver processing.
Expand Down
4 changes: 2 additions & 2 deletions Model/Resolver/Filter/Query/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@
namespace Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\Query;

use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Review\Model\Review as ReviewModel;
use Mageplaza\BetterProductReviews\Helper\Data;
use Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\DataProvider\Review;
use Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\SearchResult;
use Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\SearchResultFactory;
use Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\DataProvider\Review;
use Magento\Review\Model\Review as ReviewModel;

/**
* Retrieve filtered product data based off given search criteria in a format that GraphQL can interpret.
Expand Down
6 changes: 3 additions & 3 deletions Model/Resolver/Filter/SearchResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class SearchResult
*/
public function __construct(int $totalCount, array $itemsSearchResult)
{
$this->totalCount = $totalCount;
$this->totalCount = $totalCount;
$this->itemsSearchResult = $itemsSearchResult;
}

Expand All @@ -55,7 +55,7 @@ public function __construct(int $totalCount, array $itemsSearchResult)
*
* @return int
*/
public function getTotalCount(): int
public function getTotalCount() : int
{
return $this->totalCount;
}
Expand All @@ -65,7 +65,7 @@ public function getTotalCount(): int
*
* @return array
*/
public function getItemsSearchResult(): array
public function getItemsSearchResult() : array
{
return $this->itemsSearchResult;
}
Expand Down
3 changes: 1 addition & 2 deletions Model/Resolver/Filter/SearchResultFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ public function __construct(ObjectManagerInterface $objectManager)
*
* @param int $totalCount
* @param array $itemsSearchResult
*
* @return SearchResult
*/
public function create(int $totalCount, array $itemsSearchResult): SearchResult
public function create(int $totalCount, array $itemsSearchResult) : SearchResult
{
return $this->objectManager->create(
SearchResult::class,
Expand Down
23 changes: 19 additions & 4 deletions Model/Resolver/Review/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Mageplaza\BetterProductReviewsGraphQl\Model\Resolver\Filter\SearchResultFactory;

/**
* Class Topic
Expand All @@ -39,24 +40,38 @@ class Product implements ResolverInterface
*/
protected $_product;

/**
* @var SearchResultFactory
*/
protected $searchResultFactory;

/**
* Product constructor.
*
* @param ProductModel $product
* @param SearchResultFactory $searchResultFactory
*/
public function __construct(
ProductModel $product
ProductModel $product,
SearchResultFactory $searchResultFactory
) {
$this->_product = $product;
$this->_product = $product;
$this->searchResultFactory = $searchResultFactory;
}

/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$productId = $value['entity_pk_value'];
$productId = $value['entity_pk_value'];
$product = $this->_product->load($productId);
$listArray = [];
$listArray[$productId] = $product->getData();
$listArray[$productId]['model'] = $product;

$searchResult = $this->searchResultFactory->create(1, $listArray);

return $this->_product->load($productId);
return $searchResult->getItemsSearchResult()[$productId];
}
}
Loading

0 comments on commit c5f5125

Please sign in to comment.