init
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Block\Adminhtml\Inquiry;
|
||||
|
||||
use Esun\ProductInquiry\Model\Inquiry;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
|
||||
class View extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly Json $json,
|
||||
private readonly TimezoneInterface $timezone,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getInquiry(): Inquiry
|
||||
{
|
||||
return $this->registry->registry('current_product_inquiry');
|
||||
}
|
||||
|
||||
public function getSelectedOptions(): array
|
||||
{
|
||||
try {
|
||||
return (array)$this->json->unserialize((string)$this->getInquiry()->getData('selected_options'));
|
||||
} catch (\InvalidArgumentException) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public function getStatusOptions(): array
|
||||
{
|
||||
return Inquiry::getStatuses();
|
||||
}
|
||||
|
||||
public function getAvailabilityLabel(): string
|
||||
{
|
||||
return match ((string)$this->getInquiry()->getData('availability_reason')) {
|
||||
'manual_out_of_stock' => (string)__('Out of Stock'),
|
||||
'msi_not_salable' => (string)__('MSI Not Salable'),
|
||||
'both' => (string)__('Out of Stock and MSI Not Salable'),
|
||||
default => (string)__('Unknown'),
|
||||
};
|
||||
}
|
||||
|
||||
public function getFormattedCreatedAt(): string
|
||||
{
|
||||
$timezoneName = (string)$this->timezone->getConfigTimezone() ?: 'UTC';
|
||||
$createdAt = new \DateTimeImmutable(
|
||||
(string)$this->getInquiry()->getData('created_at'),
|
||||
new \DateTimeZone('UTC')
|
||||
);
|
||||
$localCreatedAt = $createdAt->setTimezone(new \DateTimeZone($timezoneName));
|
||||
$formattedDate = $this->timezone->formatDateTime(
|
||||
$createdAt,
|
||||
\IntlDateFormatter::MEDIUM,
|
||||
\IntlDateFormatter::MEDIUM,
|
||||
null,
|
||||
$timezoneName
|
||||
);
|
||||
|
||||
return sprintf('%s (%s, UTC%s)', $formattedDate, $timezoneName, $localCreatedAt->format('P'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Block;
|
||||
|
||||
use Esun\ProductInquiry\Model\AvailabilityResolver;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Catalog\Model\Product\Attribute\Source\Status;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\Directory\Model\ResourceModel\Country\CollectionFactory as CountryCollectionFactory;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class ProductInquiry extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly Registry $registry,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly CountryCollectionFactory $countryCollectionFactory,
|
||||
private readonly AvailabilityResolver $availabilityResolver,
|
||||
private readonly Json $json,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getProduct(): ?Product
|
||||
{
|
||||
$product = $this->registry->registry('current_product');
|
||||
return $product instanceof Product ? $product : null;
|
||||
}
|
||||
|
||||
public function canRender(): bool
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
return $product && $product->getTypeId() === Configurable::TYPE_CODE;
|
||||
}
|
||||
|
||||
public function getCountryOptions(): array
|
||||
{
|
||||
return $this->countryCollectionFactory->create()->loadByStore()->toOptionArray(false);
|
||||
}
|
||||
|
||||
public function getJsonConfig(): string
|
||||
{
|
||||
$parent = $this->getProduct();
|
||||
if (!$parent || !$this->canRender()) {
|
||||
return '{}';
|
||||
}
|
||||
|
||||
$children = [];
|
||||
$website = $this->storeManager->getStore()->getWebsite();
|
||||
foreach ($parent->getTypeInstance()->getUsedProducts($parent) as $child) {
|
||||
if ((int)$child->getStatus() !== Status::STATUS_ENABLED) {
|
||||
continue;
|
||||
}
|
||||
$availability = $this->availabilityResolver->resolve($child, $website);
|
||||
$optionLabels = [];
|
||||
foreach ($parent->getTypeInstance()->getConfigurableAttributes($parent) as $configurableAttribute) {
|
||||
$attribute = $configurableAttribute->getProductAttribute();
|
||||
$text = $child->getAttributeText((string)$attribute->getAttributeCode());
|
||||
$optionLabels[] = [
|
||||
'label' => (string)$attribute->getStoreLabel(),
|
||||
'value' => is_array($text) ? implode(', ', $text) : (string)$text,
|
||||
];
|
||||
}
|
||||
$children[(string)$child->getId()] = [
|
||||
'id' => (int)$child->getId(),
|
||||
'sku' => (string)$child->getSku(),
|
||||
'name' => (string)$child->getName(),
|
||||
'options' => $optionLabels,
|
||||
'requiresInquiry' => (bool)$availability['requires_inquiry'],
|
||||
'availabilityReason' => (string)$availability['reason'],
|
||||
];
|
||||
}
|
||||
|
||||
return $this->json->serialize([
|
||||
'parentId' => (int)$parent->getId(),
|
||||
'parentName' => (string)$parent->getName(),
|
||||
'children' => $children,
|
||||
'submitUrl' => $this->getUrl('product-inquiry/index/post'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Controller\Adminhtml\Inquiry;
|
||||
|
||||
use Esun\ProductInquiry\Model\InquiryFactory;
|
||||
use Esun\ProductInquiry\Model\ResourceModel\Inquiry as InquiryResource;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\App\Action\HttpPostActionInterface;
|
||||
|
||||
class Delete extends Action implements HttpPostActionInterface
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_ProductInquiry::delete';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly InquiryFactory $inquiryFactory,
|
||||
private readonly InquiryResource $inquiryResource
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$inquiry = $this->inquiryFactory->create();
|
||||
$this->inquiryResource->load($inquiry, (int)$this->getRequest()->getParam('id'));
|
||||
if ($inquiry->getId()) {
|
||||
try {
|
||||
$this->inquiryResource->delete($inquiry);
|
||||
$this->messageManager->addSuccessMessage(__('The inquiry has been deleted.'));
|
||||
} catch (\Throwable $exception) {
|
||||
$this->messageManager->addExceptionMessage($exception, __('Unable to delete the inquiry.'));
|
||||
}
|
||||
}
|
||||
return $this->resultRedirectFactory->create()->setPath('*/*/index');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Controller\Adminhtml\Inquiry;
|
||||
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\View\Result\Page;
|
||||
use Magento\Framework\View\Result\PageFactory;
|
||||
|
||||
class Index extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_ProductInquiry::inquiries';
|
||||
|
||||
public function __construct(Context $context, private readonly PageFactory $pageFactory)
|
||||
{
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Page
|
||||
{
|
||||
$page = $this->pageFactory->create();
|
||||
$page->setActiveMenu('Esun_ProductInquiry::inquiries');
|
||||
$page->getConfig()->getTitle()->prepend(__('Product Inquiries'));
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Controller\Adminhtml\Inquiry;
|
||||
|
||||
use Esun\ProductInquiry\Model\Inquiry;
|
||||
use Esun\ProductInquiry\Model\InquiryFactory;
|
||||
use Esun\ProductInquiry\Model\ResourceModel\Inquiry as InquiryResource;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\App\Action\HttpPostActionInterface;
|
||||
|
||||
class SaveStatus extends Action implements HttpPostActionInterface
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_ProductInquiry::manage';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly InquiryFactory $inquiryFactory,
|
||||
private readonly InquiryResource $inquiryResource
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$id = (int)$this->getRequest()->getParam('id');
|
||||
$status = (string)$this->getRequest()->getParam('status');
|
||||
$inquiry = $this->inquiryFactory->create();
|
||||
$this->inquiryResource->load($inquiry, $id);
|
||||
if (!$inquiry->getId() || !array_key_exists($status, Inquiry::getStatuses())) {
|
||||
$this->messageManager->addErrorMessage(__('Unable to update the inquiry status.'));
|
||||
return $this->resultRedirectFactory->create()->setPath('*/*/index');
|
||||
}
|
||||
try {
|
||||
$inquiry->setData('status', $status);
|
||||
$this->inquiryResource->save($inquiry);
|
||||
$this->messageManager->addSuccessMessage(__('The inquiry status has been updated.'));
|
||||
} catch (\Throwable $exception) {
|
||||
$this->messageManager->addExceptionMessage($exception, __('Unable to update the inquiry status.'));
|
||||
}
|
||||
return $this->resultRedirectFactory->create()->setPath('*/*/view', ['id' => $id]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Controller\Adminhtml\Inquiry;
|
||||
|
||||
use Esun\ProductInquiry\Model\InquiryFactory;
|
||||
use Esun\ProductInquiry\Model\ResourceModel\Inquiry as InquiryResource;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\Framework\View\Result\PageFactory;
|
||||
|
||||
class View extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Esun_ProductInquiry::inquiries';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly PageFactory $pageFactory,
|
||||
private readonly InquiryFactory $inquiryFactory,
|
||||
private readonly InquiryResource $inquiryResource,
|
||||
private readonly Registry $registry
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$inquiry = $this->inquiryFactory->create();
|
||||
$this->inquiryResource->load($inquiry, (int)$this->getRequest()->getParam('id'));
|
||||
if (!$inquiry->getId()) {
|
||||
$this->messageManager->addErrorMessage(__('The inquiry no longer exists.'));
|
||||
return $this->resultRedirectFactory->create()->setPath('*/*/index');
|
||||
}
|
||||
$this->registry->register('current_product_inquiry', $inquiry);
|
||||
$page = $this->pageFactory->create();
|
||||
$page->setActiveMenu('Esun_ProductInquiry::inquiries');
|
||||
$page->getConfig()->getTitle()->prepend(__('Product Inquiry #%1', $inquiry->getId()));
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Controller\Index;
|
||||
|
||||
use Esun\ProductInquiry\Model\SubmissionService;
|
||||
use Magento\Framework\App\Action\HttpPostActionInterface;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class Post implements HttpPostActionInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RequestInterface $request,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly FormKeyValidator $formKeyValidator,
|
||||
private readonly SubmissionService $submissionService,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
if (!$this->formKeyValidator->validate($this->request)) {
|
||||
return $this->error($result, __('Your session has expired. Refresh the page and try again.'), 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$submission = $this->submissionService->submit($this->request);
|
||||
} catch (LocalizedException $exception) {
|
||||
return $this->error($result, $exception->getMessage(), 422);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->critical($exception);
|
||||
return $this->error($result, __('Unable to submit your inquiry. Please try again later.'), 500);
|
||||
}
|
||||
|
||||
return $result->setData([
|
||||
'success' => true,
|
||||
'duplicate' => (bool)$submission['duplicate'],
|
||||
'message' => (string)($submission['duplicate']
|
||||
? __('This inquiry has already been submitted. We will contact you as soon as possible.')
|
||||
: __('Thank you. Your inquiry has been submitted.')),
|
||||
]);
|
||||
}
|
||||
|
||||
private function error(Json $result, \Stringable|string $message, int $statusCode): Json
|
||||
{
|
||||
return $result->setHttpResponseCode($statusCode)->setData([
|
||||
'success' => false,
|
||||
'message' => (string)$message,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Model;
|
||||
|
||||
use Magento\Catalog\Api\Data\ProductInterface;
|
||||
use Magento\CatalogInventory\Api\StockRegistryInterface;
|
||||
use Magento\InventorySalesApi\Api\Data\SalesChannelInterface;
|
||||
use Magento\InventorySalesApi\Api\IsProductSalableInterface;
|
||||
use Magento\InventorySalesApi\Api\StockResolverInterface;
|
||||
use Magento\Store\Api\Data\WebsiteInterface;
|
||||
|
||||
class AvailabilityResolver
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockRegistryInterface $stockRegistry,
|
||||
private readonly StockResolverInterface $stockResolver,
|
||||
private readonly IsProductSalableInterface $isProductSalable
|
||||
) {
|
||||
}
|
||||
|
||||
public function resolve(ProductInterface $product, WebsiteInterface $website): array
|
||||
{
|
||||
$stockItem = $this->stockRegistry->getStockItem((int)$product->getId(), (int)$website->getId());
|
||||
$stock = $this->stockResolver->execute(SalesChannelInterface::TYPE_WEBSITE, (string)$website->getCode());
|
||||
$legacyInStock = (bool)$stockItem->getIsInStock();
|
||||
$msiSalable = $this->isProductSalable->execute((string)$product->getSku(), (int)$stock->getStockId());
|
||||
|
||||
if (!$legacyInStock && !$msiSalable) {
|
||||
$reason = 'both';
|
||||
} elseif (!$legacyInStock) {
|
||||
$reason = 'manual_out_of_stock';
|
||||
} elseif (!$msiSalable) {
|
||||
$reason = 'msi_not_salable';
|
||||
} else {
|
||||
$reason = 'salable';
|
||||
}
|
||||
|
||||
return [
|
||||
'stock_status' => (int)$legacyInStock,
|
||||
'is_salable' => (int)$msiSalable,
|
||||
'stock_id' => (int)$stock->getStockId(),
|
||||
'reason' => $reason,
|
||||
'requires_inquiry' => !$legacyInStock || !$msiSalable,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
|
||||
class Inquiry extends AbstractModel
|
||||
{
|
||||
public const STATUS_NEW = 'new';
|
||||
public const STATUS_PROCESSING = 'processing';
|
||||
public const STATUS_RESOLVED = 'resolved';
|
||||
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(\Esun\ProductInquiry\Model\ResourceModel\Inquiry::class);
|
||||
}
|
||||
|
||||
public static function getStatuses(): array
|
||||
{
|
||||
return [
|
||||
self::STATUS_NEW => __('New'),
|
||||
self::STATUS_PROCESSING => __('Processing'),
|
||||
self::STATUS_RESOLVED => __('Resolved'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class Inquiry extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_product_inquiry', 'entity_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Model\ResourceModel\Inquiry;
|
||||
|
||||
use Esun\ProductInquiry\Model\Inquiry as InquiryModel;
|
||||
use Esun\ProductInquiry\Model\ResourceModel\Inquiry as InquiryResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(InquiryModel::class, InquiryResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Model\Source;
|
||||
|
||||
use Esun\ProductInquiry\Model\Inquiry;
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class Status implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
$options = [];
|
||||
foreach (Inquiry::getStatuses() as $value => $label) {
|
||||
$options[] = ['value' => $value, 'label' => $label];
|
||||
}
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Model;
|
||||
|
||||
use Esun\ProductInquiry\Model\ResourceModel\Inquiry as InquiryResource;
|
||||
use Esun\ProductInquiry\Model\ResourceModel\Inquiry\CollectionFactory;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Catalog\Model\Product\Attribute\Source\Status as ProductStatus;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable as ConfigurableResource;
|
||||
use Magento\Customer\Model\Session as CustomerSession;
|
||||
use Magento\Directory\Model\CountryFactory;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\Stdlib\DateTime\DateTime;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class SubmissionService
|
||||
{
|
||||
private const MAX_DAILY_SUBMISSIONS = 3;
|
||||
private const MAX_DAILY_IP_SUBMISSIONS = 20;
|
||||
|
||||
public function __construct(
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly ConfigurableResource $configurableResource,
|
||||
private readonly AvailabilityResolver $availabilityResolver,
|
||||
private readonly CountryFactory $countryFactory,
|
||||
private readonly InquiryFactory $inquiryFactory,
|
||||
private readonly InquiryResource $inquiryResource,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly CustomerSession $customerSession,
|
||||
private readonly RemoteAddress $remoteAddress,
|
||||
private readonly DateTime $dateTime,
|
||||
private readonly Json $json
|
||||
) {
|
||||
}
|
||||
|
||||
public function submit(RequestInterface $request): array
|
||||
{
|
||||
$data = $this->validateContactData($request);
|
||||
$store = $this->storeManager->getStore();
|
||||
$website = $store->getWebsite();
|
||||
$parent = $this->productRepository->getById((int)$request->getParam('parent_product_id'), false, (int)$store->getId());
|
||||
$product = $this->productRepository->getById((int)$request->getParam('product_id'), false, (int)$store->getId());
|
||||
|
||||
if (!$parent instanceof Product || $parent->getTypeId() !== Configurable::TYPE_CODE) {
|
||||
throw new LocalizedException(__('The inquiry product is invalid.'));
|
||||
}
|
||||
if (!$product instanceof Product || (int)$product->getStatus() !== ProductStatus::STATUS_ENABLED) {
|
||||
throw new LocalizedException(__('The selected product is unavailable.'));
|
||||
}
|
||||
if (!in_array((int)$parent->getId(), array_map('intval', $this->configurableResource->getParentIdsByChild((int)$product->getId())), true)) {
|
||||
throw new LocalizedException(__('The selected product does not belong to this product.'));
|
||||
}
|
||||
|
||||
$availability = $this->availabilityResolver->resolve($product, $website);
|
||||
if (!$availability['requires_inquiry']) {
|
||||
throw new LocalizedException(__('This product is currently available for purchase.'));
|
||||
}
|
||||
|
||||
$messageHash = hash('sha256', $data['email'] . '|' . $product->getId() . '|' . $this->normalizeMessage($data['message']));
|
||||
$remoteIpHash = $this->getRemoteIpHash();
|
||||
if ($this->isExactDuplicate($messageHash)) {
|
||||
return ['duplicate' => true];
|
||||
}
|
||||
$this->assertWithinRateLimit($data['email'], $remoteIpHash);
|
||||
|
||||
$country = $this->countryFactory->create()->loadByCode($data['country_id']);
|
||||
if (!$country->getId()) {
|
||||
throw new LocalizedException(__('Select a valid country.'));
|
||||
}
|
||||
|
||||
$inquiry = $this->inquiryFactory->create();
|
||||
$inquiry->setData([
|
||||
'parent_product_id' => (int)$parent->getId(),
|
||||
'parent_sku' => (string)$parent->getSku(),
|
||||
'parent_name' => (string)$parent->getName(),
|
||||
'product_id' => (int)$product->getId(),
|
||||
'product_sku' => (string)$product->getSku(),
|
||||
'product_name' => (string)$product->getName(),
|
||||
'selected_options' => $this->json->serialize($this->getSelectedOptions($parent, $product)),
|
||||
'store_id' => (int)$store->getId(),
|
||||
'website_id' => (int)$website->getId(),
|
||||
'stock_id' => (int)$availability['stock_id'],
|
||||
'customer_id' => $this->customerSession->isLoggedIn() ? (int)$this->customerSession->getCustomerId() : null,
|
||||
'name' => $data['name'],
|
||||
'email' => $data['email'],
|
||||
'country_id' => (string)$country->getId(),
|
||||
'country_name' => (string)$country->getName(),
|
||||
'company' => $data['company'],
|
||||
'telephone' => $data['telephone'],
|
||||
'message' => $data['message'],
|
||||
'status' => Inquiry::STATUS_NEW,
|
||||
'stock_status' => (int)$availability['stock_status'],
|
||||
'is_salable' => (int)$availability['is_salable'],
|
||||
'availability_reason' => (string)$availability['reason'],
|
||||
'message_hash' => $messageHash,
|
||||
'remote_ip_hash' => $remoteIpHash,
|
||||
]);
|
||||
$this->inquiryResource->save($inquiry);
|
||||
|
||||
return ['duplicate' => false, 'inquiry_id' => (int)$inquiry->getId()];
|
||||
}
|
||||
|
||||
private function validateContactData(RequestInterface $request): array
|
||||
{
|
||||
if (trim((string)$request->getParam('hideit', '')) !== '') {
|
||||
throw new LocalizedException(__('Unable to submit the form.'));
|
||||
}
|
||||
|
||||
$data = [
|
||||
'name' => trim((string)$request->getParam('name', '')),
|
||||
'email' => mb_strtolower(trim((string)$request->getParam('email', ''))),
|
||||
'country_id' => strtoupper(trim((string)$request->getParam('country_id', ''))),
|
||||
'company' => trim((string)$request->getParam('company', '')),
|
||||
'telephone' => trim((string)$request->getParam('telephone', '')),
|
||||
'message' => trim((string)$request->getParam('message', '')),
|
||||
];
|
||||
|
||||
if ($data['name'] === '' || $data['message'] === '' || $data['country_id'] === '') {
|
||||
throw new LocalizedException(__('Complete all required fields.'));
|
||||
}
|
||||
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
throw new LocalizedException(__('Enter a valid email address.'));
|
||||
}
|
||||
if (mb_strlen($data['name']) > 255 || mb_strlen($data['email']) > 255 || mb_strlen($data['company']) > 255 || mb_strlen($data['telephone']) > 64) {
|
||||
throw new LocalizedException(__('One or more fields are too long.'));
|
||||
}
|
||||
if (mb_strlen($data['message']) > 5000 || strlen($data['country_id']) !== 2) {
|
||||
throw new LocalizedException(__('The submitted information is invalid.'));
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function getSelectedOptions(Product $parent, Product $product): array
|
||||
{
|
||||
$options = [];
|
||||
foreach ($parent->getTypeInstance()->getConfigurableAttributes($parent) as $configurableAttribute) {
|
||||
$attribute = $configurableAttribute->getProductAttribute();
|
||||
$value = $product->getAttributeText((string)$attribute->getAttributeCode());
|
||||
$options[] = [
|
||||
'label' => (string)$attribute->getStoreLabel(),
|
||||
'value' => is_array($value) ? implode(', ', $value) : (string)$value,
|
||||
];
|
||||
}
|
||||
return $options;
|
||||
}
|
||||
|
||||
private function isExactDuplicate(string $messageHash): bool
|
||||
{
|
||||
return $this->collectionFactory->create()
|
||||
->addFieldToFilter('message_hash', $messageHash)
|
||||
->addFieldToFilter('created_at', ['gteq' => $this->dateTime->gmtDate('Y-m-d H:i:s', time() - 600)])
|
||||
->getSize() > 0;
|
||||
}
|
||||
|
||||
private function assertWithinRateLimit(string $email, string $remoteIpHash): void
|
||||
{
|
||||
$since = $this->dateTime->gmtDate('Y-m-d H:i:s', time() - 86400);
|
||||
$emailCount = $this->collectionFactory->create()
|
||||
->addFieldToFilter('email', $email)
|
||||
->addFieldToFilter('created_at', ['gteq' => $since])
|
||||
->getSize();
|
||||
$ipCount = $remoteIpHash === '' ? 0 : $this->collectionFactory->create()
|
||||
->addFieldToFilter('remote_ip_hash', $remoteIpHash)
|
||||
->addFieldToFilter('created_at', ['gteq' => $since])
|
||||
->getSize();
|
||||
|
||||
if ($emailCount >= self::MAX_DAILY_SUBMISSIONS || $ipCount >= self::MAX_DAILY_IP_SUBMISSIONS) {
|
||||
throw new LocalizedException(__('Too many inquiries have been submitted. Please try again later.'));
|
||||
}
|
||||
}
|
||||
|
||||
private function normalizeMessage(string $message): string
|
||||
{
|
||||
return mb_strtolower((string)preg_replace('/\s+/u', ' ', trim($message)));
|
||||
}
|
||||
|
||||
private function getRemoteIpHash(): string
|
||||
{
|
||||
$ip = trim((string)$this->remoteAddress->getRemoteAddress());
|
||||
return $ip === '' ? '' : hash('sha256', $ip);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Plugin\ConfigurableProduct\Helper;
|
||||
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\ConfigurableProduct\Helper\Data;
|
||||
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
||||
use Magento\Framework\App\RequestInterface;
|
||||
|
||||
/**
|
||||
* Keeps configurable variation data available for product inquiries.
|
||||
*/
|
||||
class DataPlugin
|
||||
{
|
||||
private const PRODUCT_VIEW_ACTION = 'catalog_product_view';
|
||||
|
||||
/**
|
||||
* @param RequestInterface $request
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly RequestInterface $request
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Include enabled out-of-stock variations in the PDP configuration only.
|
||||
*
|
||||
* Magento normally removes these options when the global "Display Out of
|
||||
* Stock Products" setting is disabled. Inquiry selection needs the complete
|
||||
* variation matrix without changing that setting for category/search pages.
|
||||
*
|
||||
* @param Data $subject
|
||||
* @param array $result
|
||||
* @param Product $currentProduct
|
||||
* @param array $allowedProducts
|
||||
* @return array
|
||||
*/
|
||||
public function afterGetOptions(
|
||||
Data $subject,
|
||||
array $result,
|
||||
Product $currentProduct,
|
||||
array $allowedProducts
|
||||
): array {
|
||||
if ($this->request->getFullActionName() !== self::PRODUCT_VIEW_ACTION
|
||||
|| $currentProduct->getTypeId() !== Configurable::TYPE_CODE
|
||||
) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$options = [
|
||||
'index' => [],
|
||||
'salable' => [],
|
||||
'canDisplayShowOutOfStockStatus' => true,
|
||||
];
|
||||
$allowAttributes = $subject->getAllowAttributes($currentProduct);
|
||||
|
||||
foreach ($allowAttributes as $attribute) {
|
||||
$attributeId = (int)$attribute->getProductAttribute()->getId();
|
||||
$options['salable'][$attributeId] = [];
|
||||
}
|
||||
|
||||
foreach ($allowedProducts as $product) {
|
||||
$productId = (int)$product->getId();
|
||||
foreach ($allowAttributes as $attribute) {
|
||||
$productAttribute = $attribute->getProductAttribute();
|
||||
$attributeId = (int)$productAttribute->getId();
|
||||
$attributeValue = $product->getData($productAttribute->getAttributeCode());
|
||||
|
||||
$options[$attributeId][$attributeValue][] = $productId;
|
||||
$options['index'][$productId][$attributeId] = $attributeValue;
|
||||
if ($product->isSalable()) {
|
||||
$options['salable'][$attributeId][$attributeValue][] = $productId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Test\Unit\Model;
|
||||
|
||||
use Esun\ProductInquiry\Model\AvailabilityResolver;
|
||||
use Magento\Catalog\Api\Data\ProductInterface;
|
||||
use Magento\CatalogInventory\Api\Data\StockItemInterface;
|
||||
use Magento\CatalogInventory\Api\StockRegistryInterface;
|
||||
use Magento\InventoryApi\Api\Data\StockInterface;
|
||||
use Magento\InventorySalesApi\Api\IsProductSalableInterface;
|
||||
use Magento\InventorySalesApi\Api\StockResolverInterface;
|
||||
use Magento\Store\Api\Data\WebsiteInterface;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class AvailabilityResolverTest extends TestCase
|
||||
{
|
||||
private StockRegistryInterface&MockObject $stockRegistry;
|
||||
private StockResolverInterface&MockObject $stockResolver;
|
||||
private IsProductSalableInterface&MockObject $isProductSalable;
|
||||
private ProductInterface&MockObject $product;
|
||||
private WebsiteInterface&MockObject $website;
|
||||
private StockItemInterface&MockObject $stockItem;
|
||||
private StockInterface&MockObject $stock;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->stockRegistry = $this->createMock(StockRegistryInterface::class);
|
||||
$this->stockResolver = $this->createMock(StockResolverInterface::class);
|
||||
$this->isProductSalable = $this->createMock(IsProductSalableInterface::class);
|
||||
$this->product = $this->createMock(ProductInterface::class);
|
||||
$this->website = $this->createMock(WebsiteInterface::class);
|
||||
$this->stockItem = $this->createMock(StockItemInterface::class);
|
||||
$this->stock = $this->createMock(StockInterface::class);
|
||||
|
||||
$this->product->method('getId')->willReturn(100);
|
||||
$this->product->method('getSku')->willReturn('TEST-SKU');
|
||||
$this->website->method('getId')->willReturn(2);
|
||||
$this->website->method('getCode')->willReturn('base');
|
||||
$this->stock->method('getStockId')->willReturn(1);
|
||||
$this->stockRegistry->method('getStockItem')->with(100, 2)->willReturn($this->stockItem);
|
||||
$this->stockResolver->method('execute')->with('website', 'base')->willReturn($this->stock);
|
||||
}
|
||||
|
||||
#[DataProvider('availabilityProvider')]
|
||||
public function testLegacyAndMsiAvailabilityAreBothRespected(
|
||||
bool $legacyInStock,
|
||||
bool $msiSalable,
|
||||
string $expectedReason,
|
||||
bool $requiresInquiry
|
||||
): void {
|
||||
$this->stockItem->method('getIsInStock')->willReturn($legacyInStock);
|
||||
$this->isProductSalable->method('execute')->with('TEST-SKU', 1)->willReturn($msiSalable);
|
||||
|
||||
$result = (new AvailabilityResolver(
|
||||
$this->stockRegistry,
|
||||
$this->stockResolver,
|
||||
$this->isProductSalable
|
||||
))->resolve($this->product, $this->website);
|
||||
|
||||
self::assertSame((int)$legacyInStock, $result['stock_status']);
|
||||
self::assertSame((int)$msiSalable, $result['is_salable']);
|
||||
self::assertSame(1, $result['stock_id']);
|
||||
self::assertSame($expectedReason, $result['reason']);
|
||||
self::assertSame($requiresInquiry, $result['requires_inquiry']);
|
||||
}
|
||||
|
||||
public static function availabilityProvider(): array
|
||||
{
|
||||
return [
|
||||
'available in both systems' => [true, true, 'salable', false],
|
||||
'manually out of stock' => [false, true, 'manual_out_of_stock', true],
|
||||
'not salable in MSI' => [true, false, 'msi_not_salable', true],
|
||||
'unavailable in both systems' => [false, false, 'both', true],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Ui\Component\Listing\Column;
|
||||
|
||||
use Magento\Ui\Component\Listing\Columns\Date;
|
||||
|
||||
class DateWithTimezone extends Date
|
||||
{
|
||||
public function prepare(): void
|
||||
{
|
||||
parent::prepare();
|
||||
|
||||
$config = $this->getData('config');
|
||||
$config['timezoneField'] = $this->getData('name') . '_timezone';
|
||||
$this->setData('config', $config);
|
||||
}
|
||||
|
||||
public function prepareDataSource(array $dataSource): array
|
||||
{
|
||||
if (!isset($dataSource['data']['items'])) {
|
||||
return parent::prepareDataSource($dataSource);
|
||||
}
|
||||
|
||||
$columnName = (string)$this->getData('name');
|
||||
$timezoneName = (string)$this->timezone->getConfigTimezone() ?: 'UTC';
|
||||
$timezone = new \DateTimeZone($timezoneName);
|
||||
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
$value = (string)($item[$columnName] ?? '');
|
||||
if ($value === '' || $value === '0000-00-00 00:00:00') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$date = new \DateTimeImmutable($value, new \DateTimeZone('UTC'));
|
||||
$item[$columnName . '_timezone'] = sprintf(
|
||||
'%s, UTC%s',
|
||||
$timezoneName,
|
||||
$date->setTimezone($timezone)->format('P')
|
||||
);
|
||||
}
|
||||
unset($item);
|
||||
|
||||
return parent::prepareDataSource($dataSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ProductInquiry\Ui\Component\Listing\Column;
|
||||
|
||||
use Magento\Backend\Model\UrlInterface;
|
||||
use Magento\Framework\View\Element\UiComponent\ContextInterface;
|
||||
use Magento\Framework\View\Element\UiComponentFactory;
|
||||
use Magento\Ui\Component\Listing\Columns\Column;
|
||||
|
||||
class InquiryActions extends Column
|
||||
{
|
||||
public function __construct(
|
||||
ContextInterface $context,
|
||||
UiComponentFactory $uiComponentFactory,
|
||||
private readonly UrlInterface $urlBuilder,
|
||||
array $components = [],
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $uiComponentFactory, $components, $data);
|
||||
}
|
||||
|
||||
public function prepareDataSource(array $dataSource): array
|
||||
{
|
||||
if (!isset($dataSource['data']['items'])) {
|
||||
return $dataSource;
|
||||
}
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
$id = (int)($item['entity_id'] ?? 0);
|
||||
if (!$id) {
|
||||
continue;
|
||||
}
|
||||
$item[$this->getData('name')] = [
|
||||
'view' => [
|
||||
'href' => $this->urlBuilder->getUrl('esun_product_inquiry/inquiry/view', ['id' => $id]),
|
||||
'label' => __('View'),
|
||||
],
|
||||
'delete' => [
|
||||
'href' => $this->urlBuilder->getUrl('esun_product_inquiry/inquiry/delete', ['id' => $id]),
|
||||
'label' => __('Delete'),
|
||||
'post' => true,
|
||||
'confirm' => [
|
||||
'title' => __('Delete Inquiry'),
|
||||
'message' => __('Are you sure you want to delete this inquiry?'),
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
unset($item);
|
||||
return $dataSource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
|
||||
<acl>
|
||||
<resources>
|
||||
<resource id="Magento_Backend::admin">
|
||||
<resource id="Esun_ImageManager::esun">
|
||||
<resource id="Esun_ProductInquiry::inquiries" title="Product Inquiries" sortOrder="70">
|
||||
<resource id="Esun_ProductInquiry::manage" title="Manage Product Inquiries" sortOrder="10"/>
|
||||
<resource id="Esun_ProductInquiry::delete" title="Delete Product Inquiries" sortOrder="20"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
|
||||
<menu>
|
||||
<add id="Esun_ProductInquiry::inquiries"
|
||||
title="Product Inquiries"
|
||||
module="Esun_ProductInquiry"
|
||||
sortOrder="70"
|
||||
parent="Esun_ImageManager::esun"
|
||||
action="esun_product_inquiry/inquiry/index"
|
||||
resource="Esun_ProductInquiry::inquiries"/>
|
||||
</menu>
|
||||
</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="admin">
|
||||
<route id="esun_product_inquiry" frontName="esun_product_inquiry">
|
||||
<module name="Esun_ProductInquiry" before="Magento_Backend"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?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="esun_product_inquiry" resource="default" engine="innodb" comment="eSUN Product Inquiries">
|
||||
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
|
||||
<column xsi:type="int" name="parent_product_id" unsigned="true" nullable="false" comment="Parent Product ID"/>
|
||||
<column xsi:type="varchar" name="parent_sku" nullable="false" length="64" comment="Parent SKU Snapshot"/>
|
||||
<column xsi:type="varchar" name="parent_name" nullable="false" length="255" comment="Parent Name Snapshot"/>
|
||||
<column xsi:type="int" name="product_id" unsigned="true" nullable="false" comment="Selected Product ID"/>
|
||||
<column xsi:type="varchar" name="product_sku" nullable="false" length="64" comment="Selected SKU Snapshot"/>
|
||||
<column xsi:type="varchar" name="product_name" nullable="false" length="255" comment="Selected Product Name Snapshot"/>
|
||||
<column xsi:type="text" name="selected_options" nullable="false" comment="Selected Options Snapshot"/>
|
||||
<column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" comment="Store ID"/>
|
||||
<column xsi:type="smallint" name="website_id" unsigned="true" nullable="false" comment="Website ID"/>
|
||||
<column xsi:type="int" name="stock_id" unsigned="true" nullable="false" comment="MSI Stock ID"/>
|
||||
<column xsi:type="int" name="customer_id" unsigned="true" nullable="true" comment="Customer ID"/>
|
||||
<column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/>
|
||||
<column xsi:type="varchar" name="email" nullable="false" length="255" comment="Email"/>
|
||||
<column xsi:type="varchar" name="country_id" nullable="false" length="2" comment="Country Code"/>
|
||||
<column xsi:type="varchar" name="country_name" nullable="false" length="255" comment="Country Name Snapshot"/>
|
||||
<column xsi:type="varchar" name="company" nullable="false" length="255" default="" comment="Company Name"/>
|
||||
<column xsi:type="varchar" name="telephone" nullable="false" length="64" default="" comment="Telephone"/>
|
||||
<column xsi:type="text" name="message" nullable="false" comment="Message"/>
|
||||
<column xsi:type="varchar" name="status" nullable="false" length="32" default="new" comment="Processing Status"/>
|
||||
<column xsi:type="smallint" name="stock_status" unsigned="true" nullable="false" comment="Legacy Stock Status Snapshot"/>
|
||||
<column xsi:type="smallint" name="is_salable" unsigned="true" nullable="false" comment="MSI Salable Snapshot"/>
|
||||
<column xsi:type="varchar" name="availability_reason" nullable="false" length="32" comment="Availability Reason"/>
|
||||
<column xsi:type="varchar" name="message_hash" nullable="false" length="64" comment="Duplicate Detection Hash"/>
|
||||
<column xsi:type="varchar" name="remote_ip_hash" nullable="false" length="64" default="" comment="Rate Limit IP Hash"/>
|
||||
<column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
|
||||
<column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="Updated At"/>
|
||||
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entity_id"/></constraint>
|
||||
<index referenceId="ESUN_PRODUCT_INQUIRY_PRODUCT_EMAIL" indexType="btree">
|
||||
<column name="product_id"/><column name="email"/>
|
||||
</index>
|
||||
<index referenceId="ESUN_PRODUCT_INQUIRY_STATUS_CREATED" indexType="btree">
|
||||
<column name="status"/><column name="created_at"/>
|
||||
</index>
|
||||
<index referenceId="ESUN_PRODUCT_INQUIRY_MESSAGE_HASH" indexType="btree"><column name="message_hash"/></index>
|
||||
<index referenceId="ESUN_PRODUCT_INQUIRY_REMOTE_IP_HASH" indexType="btree"><column name="remote_ip_hash"/></index>
|
||||
</table>
|
||||
</schema>
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"esun_product_inquiry": {
|
||||
"column": {
|
||||
"entity_id": true,
|
||||
"parent_product_id": true,
|
||||
"parent_sku": true,
|
||||
"parent_name": true,
|
||||
"product_id": true,
|
||||
"product_sku": true,
|
||||
"product_name": true,
|
||||
"selected_options": true,
|
||||
"store_id": true,
|
||||
"website_id": true,
|
||||
"stock_id": true,
|
||||
"customer_id": true,
|
||||
"name": true,
|
||||
"email": true,
|
||||
"country_id": true,
|
||||
"country_name": true,
|
||||
"company": true,
|
||||
"telephone": true,
|
||||
"message": true,
|
||||
"status": true,
|
||||
"stock_status": true,
|
||||
"is_salable": true,
|
||||
"availability_reason": true,
|
||||
"message_hash": true,
|
||||
"remote_ip_hash": true,
|
||||
"created_at": true,
|
||||
"updated_at": true
|
||||
},
|
||||
"index": {
|
||||
"ESUN_PRODUCT_INQUIRY_PRODUCT_ID_EMAIL": true,
|
||||
"ESUN_PRODUCT_INQUIRY_STATUS_CREATED_AT": true,
|
||||
"ESUN_PRODUCT_INQUIRY_MESSAGE_HASH": true,
|
||||
"ESUN_PRODUCT_INQUIRY_REMOTE_IP_HASH": true
|
||||
},
|
||||
"constraint": {
|
||||
"PRIMARY": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?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\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
|
||||
<arguments>
|
||||
<argument name="collections" xsi:type="array">
|
||||
<item name="esun_product_inquiry_listing_data_source" xsi:type="string">EsunProductInquiryGridCollection</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</type>
|
||||
<virtualType name="EsunProductInquiryGridCollection"
|
||||
type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
|
||||
<arguments>
|
||||
<argument name="mainTable" xsi:type="string">esun_product_inquiry</argument>
|
||||
<argument name="resourceModel" xsi:type="string">Esun\ProductInquiry\Model\ResourceModel\Inquiry</argument>
|
||||
</arguments>
|
||||
</virtualType>
|
||||
</config>
|
||||
@@ -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\ConfigurableProduct\Helper\Data">
|
||||
<plugin name="esun_product_inquiry_include_out_of_stock_options"
|
||||
type="Esun\ProductInquiry\Plugin\ConfigurableProduct\Helper\DataPlugin"/>
|
||||
</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="product_inquiry" frontName="product-inquiry">
|
||||
<module name="Esun_ProductInquiry"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?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_ProductInquiry">
|
||||
<sequence>
|
||||
<module name="Magento_Catalog"/>
|
||||
<module name="Magento_CatalogInventory"/>
|
||||
<module name="Magento_ConfigurableProduct"/>
|
||||
<module name="Magento_Directory"/>
|
||||
<module name="Magento_InventorySalesApi"/>
|
||||
<module name="Magento_Swatches"/>
|
||||
<module name="Esun_ImageManager"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Esun_ProductInquiry',
|
||||
__DIR__
|
||||
);
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<?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">
|
||||
<body>
|
||||
<referenceContainer name="content">
|
||||
<uiComponent name="esun_product_inquiry_listing"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<?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">
|
||||
<body>
|
||||
<referenceContainer name="content">
|
||||
<block class="Esun\ProductInquiry\Block\Adminhtml\Inquiry\View"
|
||||
name="esun.product.inquiry.view"
|
||||
template="Esun_ProductInquiry::inquiry/view.phtml"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
/** @var \Esun\ProductInquiry\Block\Adminhtml\Inquiry\View $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
$inquiry = $block->getInquiry();
|
||||
?>
|
||||
<div class="admin__page-section">
|
||||
<div class="admin__page-section-title"><span class="title"><?= $escaper->escapeHtml(__('Product')) ?></span></div>
|
||||
<div class="admin__page-section-content">
|
||||
<table class="admin__table-secondary">
|
||||
<tr><th><?= $escaper->escapeHtml(__('Product')) ?></th><td><?= $escaper->escapeHtml((string)$inquiry->getData('parent_name')) ?> (<?= $escaper->escapeHtml((string)$inquiry->getData('parent_sku')) ?>)</td></tr>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Selected SKU')) ?></th><td><?= $escaper->escapeHtml((string)$inquiry->getData('product_sku')) ?></td></tr>
|
||||
<?php foreach ($block->getSelectedOptions() as $option): ?>
|
||||
<tr><th><?= $escaper->escapeHtml((string)($option['label'] ?? '')) ?></th><td><?= $escaper->escapeHtml((string)($option['value'] ?? '')) ?></td></tr>
|
||||
<?php endforeach; ?>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Availability at Submission')) ?></th><td><?= $escaper->escapeHtml($block->getAvailabilityLabel()) ?></td></tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin__page-section">
|
||||
<div class="admin__page-section-title"><span class="title"><?= $escaper->escapeHtml(__('Contact Information')) ?></span></div>
|
||||
<div class="admin__page-section-content">
|
||||
<table class="admin__table-secondary">
|
||||
<tr><th><?= $escaper->escapeHtml(__('Name')) ?></th><td><?= $escaper->escapeHtml((string)$inquiry->getData('name')) ?></td></tr>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Email')) ?></th><td><a href="mailto:<?= $escaper->escapeHtmlAttr((string)$inquiry->getData('email')) ?>"><?= $escaper->escapeHtml((string)$inquiry->getData('email')) ?></a></td></tr>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Country')) ?></th><td><?= $escaper->escapeHtml((string)$inquiry->getData('country_name')) ?></td></tr>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Company Name')) ?></th><td><?= $escaper->escapeHtml((string)$inquiry->getData('company')) ?: '—' ?></td></tr>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Telephone')) ?></th><td><?= $escaper->escapeHtml((string)$inquiry->getData('telephone')) ?: '—' ?></td></tr>
|
||||
<tr><th><?= $escaper->escapeHtml(__('Inquiry Time')) ?></th><td><?= $escaper->escapeHtml($block->getFormattedCreatedAt()) ?></td></tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin__page-section">
|
||||
<div class="admin__page-section-title"><span class="title"><?= $escaper->escapeHtml(__('Message')) ?></span></div>
|
||||
<div class="admin__page-section-content">
|
||||
<div style="white-space:pre-wrap;max-width:1000px"><?= $escaper->escapeHtml((string)$inquiry->getData('message')) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin__page-section">
|
||||
<form method="post" action="<?= $escaper->escapeUrl($block->getUrl('esun_product_inquiry/inquiry/saveStatus')) ?>">
|
||||
<?= /* @noEscape */ $block->getBlockHtml('formkey') ?>
|
||||
<input type="hidden" name="id" value="<?= (int)$inquiry->getId() ?>"/>
|
||||
<label class="admin__field-label" for="inquiry-status"><span><?= $escaper->escapeHtml(__('Status')) ?></span></label>
|
||||
<select class="admin__control-select" id="inquiry-status" name="status">
|
||||
<?php foreach ($block->getStatusOptions() as $value => $label): ?>
|
||||
<option value="<?= $escaper->escapeHtmlAttr($value) ?>" <?= $inquiry->getData('status') === $value ? 'selected' : '' ?>><?= $escaper->escapeHtml($label) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<button type="submit" class="action-primary"><span><?= $escaper->escapeHtml(__('Save Status')) ?></span></button>
|
||||
<a class="action-secondary" href="<?= $escaper->escapeUrl($block->getUrl('esun_product_inquiry/inquiry/index')) ?>"><?= $escaper->escapeHtml(__('Back')) ?></a>
|
||||
</form>
|
||||
</div>
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
<?xml version="1.0"?>
|
||||
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
|
||||
<argument name="data" xsi:type="array">
|
||||
<item name="js_config" xsi:type="array">
|
||||
<item name="provider" xsi:type="string">esun_product_inquiry_listing.esun_product_inquiry_listing_data_source</item>
|
||||
</item>
|
||||
</argument>
|
||||
<settings>
|
||||
<spinner>esun_product_inquiry_columns</spinner>
|
||||
<deps><dep>esun_product_inquiry_listing.esun_product_inquiry_listing_data_source</dep></deps>
|
||||
</settings>
|
||||
<dataSource name="esun_product_inquiry_listing_data_source" component="Magento_Ui/js/grid/provider">
|
||||
<settings>
|
||||
<storageConfig><param name="indexField" xsi:type="string">entity_id</param></storageConfig>
|
||||
<updateUrl path="mui/index/render"/>
|
||||
</settings>
|
||||
<aclResource>Esun_ProductInquiry::inquiries</aclResource>
|
||||
<dataProvider class="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider"
|
||||
name="esun_product_inquiry_listing_data_source">
|
||||
<settings><requestFieldName>id</requestFieldName><primaryFieldName>entity_id</primaryFieldName></settings>
|
||||
</dataProvider>
|
||||
</dataSource>
|
||||
<listingToolbar name="listing_top">
|
||||
<settings><sticky>true</sticky></settings>
|
||||
<bookmark name="bookmarks"/>
|
||||
<columnsControls name="columns_controls"/>
|
||||
<filters name="listing_filters"/>
|
||||
<paging name="listing_paging"/>
|
||||
</listingToolbar>
|
||||
<columns name="esun_product_inquiry_columns">
|
||||
<column name="entity_id">
|
||||
<settings><filter>textRange</filter><label translate="true">ID</label><sorting>desc</sorting></settings>
|
||||
</column>
|
||||
<column name="status" component="Magento_Ui/js/grid/columns/select">
|
||||
<settings>
|
||||
<filter>select</filter><dataType>select</dataType>
|
||||
<options class="Esun\ProductInquiry\Model\Source\Status"/>
|
||||
<label translate="true">Status</label>
|
||||
</settings>
|
||||
</column>
|
||||
<column name="parent_name"><settings><filter>text</filter><label translate="true">Product</label></settings></column>
|
||||
<column name="product_sku"><settings><filter>text</filter><label translate="true">Selected SKU</label></settings></column>
|
||||
<column name="name"><settings><filter>text</filter><label translate="true">Name</label></settings></column>
|
||||
<column name="email"><settings><filter>text</filter><label translate="true">Email</label></settings></column>
|
||||
<column name="country_name"><settings><filter>text</filter><label translate="true">Country</label></settings></column>
|
||||
<column name="company"><settings><filter>text</filter><label translate="true">Company Name</label></settings></column>
|
||||
<column name="telephone"><settings><filter>text</filter><label translate="true">Telephone</label></settings></column>
|
||||
<column name="created_at"
|
||||
class="Esun\ProductInquiry\Ui\Component\Listing\Column\DateWithTimezone"
|
||||
component="Esun_ProductInquiry/js/grid/columns/date-with-timezone">
|
||||
<settings><filter>dateRange</filter><dataType>date</dataType><label translate="true">Inquiry Time</label></settings>
|
||||
</column>
|
||||
<actionsColumn name="actions" class="Esun\ProductInquiry\Ui\Component\Listing\Column\InquiryActions">
|
||||
<settings><indexField>entity_id</indexField><resizeEnabled>false</resizeEnabled><resizeDefaultWidth>100</resizeDefaultWidth></settings>
|
||||
</actionsColumn>
|
||||
</columns>
|
||||
</listing>
|
||||
@@ -0,0 +1,14 @@
|
||||
define([
|
||||
'Magento_Ui/js/grid/columns/date'
|
||||
], function (DateColumn) {
|
||||
'use strict';
|
||||
|
||||
return DateColumn.extend({
|
||||
getLabel: function (value, format) {
|
||||
var label = this._super(value, format),
|
||||
timezone = value[this.timezoneField];
|
||||
|
||||
return label && timezone ? label + ' (' + timezone + ')' : label;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
<?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_ProductInquiry::css/product-inquiry.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<referenceContainer name="before.body.end">
|
||||
<block class="Esun\ProductInquiry\Block\ProductInquiry"
|
||||
name="esun.product.inquiry.modal"
|
||||
template="Esun_ProductInquiry::product/inquiry.phtml"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<?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">
|
||||
<body>
|
||||
<referenceBlock name="product.info"
|
||||
template="Esun_ProductInquiry::product/view/form.phtml"/>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,12 @@
|
||||
var config = {
|
||||
config: {
|
||||
mixins: {
|
||||
'Magento_Swatches/js/swatch-renderer': {
|
||||
'Esun_ProductInquiry/js/swatch-renderer-mixin': true
|
||||
},
|
||||
'Magento_ConfigurableProduct/js/configurable': {
|
||||
'Esun_ProductInquiry/js/configurable-mixin': true
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
/** @var \Esun\ProductInquiry\Block\ProductInquiry $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
if (!$block->canRender()) {
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<div class="esun-product-inquiry" data-role="product-inquiry-modal" style="display:none">
|
||||
<form class="esun-product-inquiry__form"
|
||||
action="<?= $escaper->escapeUrl($block->getUrl('product-inquiry/index/post')) ?>"
|
||||
method="post"
|
||||
novalidate>
|
||||
<?= /* @noEscape */ $block->getBlockHtml('formkey') ?>
|
||||
<input type="hidden" name="parent_product_id" value="<?= (int)$block->getProduct()->getId() ?>"/>
|
||||
<input type="hidden" name="product_id" value="" data-role="product-inquiry-product-id"/>
|
||||
|
||||
<div class="esun-product-inquiry__status" data-role="product-inquiry-status" role="status" aria-live="polite"></div>
|
||||
<div class="esun-product-inquiry__product">
|
||||
<strong data-role="product-inquiry-product-name"></strong>
|
||||
<span data-role="product-inquiry-product-options"></span>
|
||||
</div>
|
||||
|
||||
<div class="esun-product-inquiry__grid">
|
||||
<div class="field required">
|
||||
<label for="product-inquiry-name">
|
||||
<span><?= $escaper->escapeHtml(__('Name')) ?></span>
|
||||
<span class="esun-product-inquiry__required" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<input class="input-text" id="product-inquiry-name" name="name" type="text"
|
||||
maxlength="255" autocomplete="name" required data-validate="{required:true}"/>
|
||||
</div>
|
||||
<div class="field required">
|
||||
<label for="product-inquiry-email">
|
||||
<span><?= $escaper->escapeHtml(__('Email')) ?></span>
|
||||
<span class="esun-product-inquiry__required" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<input class="input-text" id="product-inquiry-email" name="email" type="email"
|
||||
maxlength="255" autocomplete="email" required
|
||||
data-validate="{required:true, 'validate-email':true}"/>
|
||||
</div>
|
||||
<div class="field required">
|
||||
<label for="product-inquiry-country">
|
||||
<span><?= $escaper->escapeHtml(__('Country')) ?></span>
|
||||
<span class="esun-product-inquiry__required" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<select id="product-inquiry-country" name="country_id" required data-validate="{required:true}">
|
||||
<option value=""><?= $escaper->escapeHtml(__('Please select a country.')) ?></option>
|
||||
<?php foreach ($block->getCountryOptions() as $country): ?>
|
||||
<option value="<?= $escaper->escapeHtmlAttr((string)$country['value']) ?>">
|
||||
<?= $escaper->escapeHtml((string)$country['label']) ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="product-inquiry-company"><span><?= $escaper->escapeHtml(__('Company Name')) ?></span></label>
|
||||
<input class="input-text" id="product-inquiry-company" name="company" type="text"
|
||||
maxlength="255" autocomplete="organization"/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="product-inquiry-telephone"><span><?= $escaper->escapeHtml(__('Telephone')) ?></span></label>
|
||||
<input class="input-text" id="product-inquiry-telephone" name="telephone" type="tel"
|
||||
maxlength="64" autocomplete="tel"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field required esun-product-inquiry__message">
|
||||
<label for="product-inquiry-message">
|
||||
<span><?= $escaper->escapeHtml(__('Message')) ?></span>
|
||||
<span class="esun-product-inquiry__required" aria-hidden="true">*</span>
|
||||
</label>
|
||||
<textarea id="product-inquiry-message" name="message" rows="6" maxlength="5000"
|
||||
required data-validate="{required:true}"></textarea>
|
||||
</div>
|
||||
<input type="text" name="hideit" class="esun-product-inquiry__trap" tabindex="-1" autocomplete="off"/>
|
||||
<button type="submit" class="action primary esun-product-inquiry__submit">
|
||||
<span><?= $escaper->escapeHtml(__('Submit Inquiry')) ?></span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script type="text/x-magento-init">
|
||||
{
|
||||
"[data-role=product-inquiry-modal]": {
|
||||
"Esun_ProductInquiry/js/product-inquiry": <?= /* @noEscape */ $block->getJsonConfig() ?>
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* Product view form with configurable options kept visible for inquiry when
|
||||
* every associated product is out of stock.
|
||||
*
|
||||
* @var $block \Magento\Catalog\Block\Product\View
|
||||
* @var $escaper \Magento\Framework\Escaper
|
||||
*/
|
||||
|
||||
// phpcs:disable Magento2.Templates.ThisInTemplate.FoundThis
|
||||
|
||||
$_product = $block->getProduct();
|
||||
$isConfigurable = $_product->getTypeId()
|
||||
=== \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE;
|
||||
$hasOptions = $block->hasOptions() || $isConfigurable;
|
||||
$canRenderOptions = $_product->isSaleable() || $isConfigurable;
|
||||
?>
|
||||
<div class="product-add-form">
|
||||
<form data-product-sku="<?= $escaper->escapeHtmlAttr($_product->getSku()) ?>"
|
||||
action="<?= $escaper->escapeUrl($block->getSubmitUrl($_product)) ?>"
|
||||
method="post"
|
||||
id="product_addtocart_form"<?php if ($_product->getOptions()): ?>
|
||||
enctype="multipart/form-data"<?php endif; ?>>
|
||||
<input type="hidden" name="product" value="<?= (int)$_product->getId() ?>" />
|
||||
<input type="hidden" name="selected_configurable_option" value="" />
|
||||
<input type="hidden" name="related_product" id="related-products-field" value="" />
|
||||
<input type="hidden"
|
||||
name="return_url"
|
||||
value="<?= $escaper->escapeUrl(
|
||||
$block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true])
|
||||
) ?>" />
|
||||
<input type="hidden" name="item" value="<?= (int)$block->getRequest()->getParam('id') ?>" />
|
||||
<?= $block->getBlockHtml('formkey') ?>
|
||||
<?= $block->getChildHtml('form_top') ?>
|
||||
<?php if (!$hasOptions): ?>
|
||||
<?= $block->getChildHtml('product_info_form_content') ?>
|
||||
<?php elseif ($canRenderOptions && $block->getOptionsContainer() === 'container1'): ?>
|
||||
<?= $block->getChildChildHtml('options_container') ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($canRenderOptions && $hasOptions && $block->getOptionsContainer() === 'container2'): ?>
|
||||
<?= $block->getChildChildHtml('options_container') ?>
|
||||
<?php endif; ?>
|
||||
<?= $block->getChildHtml('form_bottom') ?>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script type="text/x-magento-init">
|
||||
{
|
||||
"[data-role=priceBox][data-price-box=product-id-<?= $escaper->escapeHtmlAttr($_product->getId()) ?>]": {
|
||||
"priceBox": {
|
||||
"priceConfig": <?= /* @noEscape */ $block->getJsonConfig() ?>
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,207 @@
|
||||
.esun-product-inquiry__trigger {
|
||||
align-items: center;
|
||||
background: #18a957;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
box-shadow: none;
|
||||
color: #fff;
|
||||
display: inline-flex;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
justify-content: center;
|
||||
letter-spacing: 0;
|
||||
line-height: 1.2;
|
||||
min-height: 56px;
|
||||
max-width: 300px;
|
||||
padding: 0 34px;
|
||||
text-transform: none;
|
||||
transition:
|
||||
background-color 0.16s ease,
|
||||
opacity 0.16s ease;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__trigger:hover,
|
||||
.esun-product-inquiry__trigger:focus {
|
||||
background: #129347;
|
||||
border: 0;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.esun-product-inquiry-modal .modal-inner-wrap {
|
||||
width: min(700px, calc(100% - 32px));
|
||||
border-radius: 18px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.esun-product-inquiry-modal .modal-header {
|
||||
padding: 24px 32px;
|
||||
background: #1e9e5a;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.esun-product-inquiry-modal .modal-title,
|
||||
.esun-product-inquiry-modal .action-close:before {
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.esun-product-inquiry-modal .modal-content {
|
||||
padding: 28px 32px 34px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__product {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin-bottom: 24px;
|
||||
padding: 14px 18px;
|
||||
border-radius: 10px;
|
||||
background: #f1f8f4;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry .field {
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry input,
|
||||
.esun-product-inquiry select,
|
||||
.esun-product-inquiry textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.esun-product-inquiry input.input-text,
|
||||
.esun-product-inquiry select,
|
||||
.esun-product-inquiry textarea {
|
||||
border: 1px solid #d9dde1;
|
||||
background: #fff;
|
||||
color: #1f2933;
|
||||
box-shadow: none;
|
||||
transition:
|
||||
border-color 0.16s ease,
|
||||
box-shadow 0.16s ease;
|
||||
}
|
||||
|
||||
.esun-product-inquiry input.input-text,
|
||||
.esun-product-inquiry select {
|
||||
height: 48px;
|
||||
padding: 0 20px;
|
||||
border-radius: 24px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry select {
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
appearance: none;
|
||||
padding-right: 52px;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='8' viewBox='0 0 14 8'%3E%3Cpath d='M1 1l6 6 6-6' fill='none' stroke='%23303030' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 22px center;
|
||||
background-size: 10px 8px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry textarea {
|
||||
min-height: 160px;
|
||||
padding: 16px 20px;
|
||||
border-radius: 18px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.esun-product-inquiry input.input-text:focus,
|
||||
.esun-product-inquiry select:focus,
|
||||
.esun-product-inquiry textarea:focus {
|
||||
border-color: #1e9e5a;
|
||||
outline: 0;
|
||||
box-shadow: 0 0 0 3px rgba(30, 158, 90, 0.12);
|
||||
}
|
||||
|
||||
.esun-product-inquiry__message {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__required {
|
||||
color: #e02b27;
|
||||
margin-left: 3px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry .esun-product-inquiry__submit.action.primary {
|
||||
align-items: center;
|
||||
background: #18a957;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
box-shadow: none;
|
||||
color: #fff;
|
||||
display: flex;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
justify-content: center;
|
||||
letter-spacing: 0;
|
||||
line-height: 1.2;
|
||||
margin: 8px 0 0 auto;
|
||||
max-width: 300px;
|
||||
min-height: 56px;
|
||||
padding: 0 34px;
|
||||
text-transform: none;
|
||||
transition:
|
||||
background-color 0.16s ease,
|
||||
opacity 0.16s ease;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.esun-product-inquiry .esun-product-inquiry__submit.action.primary:hover,
|
||||
.esun-product-inquiry .esun-product-inquiry__submit.action.primary:focus,
|
||||
.esun-product-inquiry .esun-product-inquiry__submit.action.primary:active {
|
||||
background: #129347;
|
||||
border: 0;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__status {
|
||||
display: none;
|
||||
margin-bottom: 18px;
|
||||
padding: 12px 16px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__status.success,
|
||||
.esun-product-inquiry__status.error {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__status.success {
|
||||
background: #edf8f2;
|
||||
color: #167746;
|
||||
}
|
||||
.esun-product-inquiry__status.error {
|
||||
background: #fff1f0;
|
||||
color: #c62828;
|
||||
}
|
||||
|
||||
.esun-product-inquiry__trap {
|
||||
position: absolute !important;
|
||||
left: -10000px !important;
|
||||
width: 1px !important;
|
||||
height: 1px !important;
|
||||
opacity: 0 !important;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.esun-product-inquiry__grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0;
|
||||
}
|
||||
.esun-product-inquiry-modal .modal-content {
|
||||
padding: 24px 20px 28px;
|
||||
}
|
||||
.esun-product-inquiry .esun-product-inquiry__submit.action.primary {
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
define(['jquery', 'mage/utils/wrapper'], function ($, wrapper) {
|
||||
'use strict';
|
||||
|
||||
return function (Widget) {
|
||||
Widget.prototype._fillSelect = wrapper.wrapSuper(Widget.prototype._fillSelect, function (element) {
|
||||
var config = this.options.spConfig || {},
|
||||
attributeId = element.id.replace(/[a-z]*/, ''),
|
||||
result;
|
||||
|
||||
if (config.canDisplayShowOutOfStockStatus) {
|
||||
config.salable = config.salable || {};
|
||||
config.salable[attributeId] = config.salable[attributeId] || {};
|
||||
}
|
||||
|
||||
result = this._super(element);
|
||||
|
||||
if (config.canDisplayShowOutOfStockStatus) {
|
||||
$(element).find('option').each(function () {
|
||||
var wasDisabled = this.disabled;
|
||||
if (this.config && this.config.allowedProducts && this.config.allowedProducts.length) {
|
||||
this.disabled = false;
|
||||
$(this).toggleClass('esun-out-of-stock-option', wasDisabled);
|
||||
}
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
return Widget;
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
define([
|
||||
'jquery',
|
||||
'Magento_Ui/js/modal/modal',
|
||||
'mage/validation',
|
||||
'mage/translate'
|
||||
], function ($, modal, validation, $t) {
|
||||
'use strict';
|
||||
|
||||
return function (config, element) {
|
||||
var $modal = $(element),
|
||||
$form = $modal.find('form'),
|
||||
$trigger = $('[data-role="product-inquiry-trigger"]').first(),
|
||||
$addToCart = $('#product-addtocart-button'),
|
||||
$buyNow = $('[data-role="esun-buy-now"]'),
|
||||
$qty = $('.box-tocart .field.qty'),
|
||||
$status = $modal.find('[data-role="product-inquiry-status"]'),
|
||||
$submit = $form.find('[type="submit"]'),
|
||||
closeTimer = null,
|
||||
selectedChild = null;
|
||||
|
||||
if (!$trigger.length) {
|
||||
$trigger = $('<button>', {
|
||||
type: 'button',
|
||||
'class': 'action primary tocart esun-product-inquiry__trigger',
|
||||
'data-role': 'product-inquiry-trigger'
|
||||
}).append($('<span>', {text: $t('Inquiry')})).hide();
|
||||
if (!$('.esun-product-actions').length) {
|
||||
$('<div>', {
|
||||
'class': 'box-tocart esun-product-inquiry-actions'
|
||||
}).append(
|
||||
$('<div>', {'class': 'fieldset'}).append(
|
||||
$('<div>', {'class': 'actions esun-product-actions'})
|
||||
)
|
||||
).appendTo($('.product-options-bottom').first().length ?
|
||||
$('.product-options-bottom').first() : $('#product_addtocart_form'));
|
||||
}
|
||||
$('.esun-product-actions').first().append($trigger);
|
||||
}
|
||||
|
||||
modal({
|
||||
type: 'popup',
|
||||
responsive: true,
|
||||
innerScroll: true,
|
||||
modalClass: 'esun-product-inquiry-modal',
|
||||
title: $t('Inquiry'),
|
||||
buttons: []
|
||||
}, $modal);
|
||||
$form.validation();
|
||||
|
||||
function getSwatchWidget() {
|
||||
var $swatch = $('.swatch-opt');
|
||||
return $swatch.data('mageSwatchRenderer') || $swatch.data('mage-SwatchRenderer');
|
||||
}
|
||||
|
||||
function getSelectedProductId() {
|
||||
var selected = $('[name="selected_configurable_option"]').val(),
|
||||
widget,
|
||||
selectedOptions = {},
|
||||
match = null;
|
||||
|
||||
if (selected && config.children[String(selected)]) {
|
||||
return String(selected);
|
||||
}
|
||||
widget = getSwatchWidget();
|
||||
if (widget && typeof widget.getProductId === 'function') {
|
||||
selected = widget.getProductId();
|
||||
if (selected && config.children[String(selected)]) {
|
||||
return String(selected);
|
||||
}
|
||||
}
|
||||
$('.swatch-attribute').each(function () {
|
||||
var $attribute = $(this),
|
||||
attributeId = String($attribute.attr('attribute-id') || $attribute.data('attribute-id') || ''),
|
||||
optionId = $attribute.find('.swatch-option.selected').attr('option-id') ||
|
||||
$attribute.find('.swatch-option.selected').data('option-id') ||
|
||||
$attribute.find('.super-attribute-select').val();
|
||||
if (attributeId && optionId) {
|
||||
selectedOptions[attributeId] = String(optionId);
|
||||
}
|
||||
});
|
||||
if (widget && widget.options && widget.options.jsonConfig) {
|
||||
$.each(widget.options.jsonConfig.index || {}, function (productId, options) {
|
||||
var matches = Object.keys(selectedOptions).length > 0;
|
||||
$.each(selectedOptions, function (attributeId, optionId) {
|
||||
if (String(options[attributeId]) !== optionId) {
|
||||
matches = false;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (matches && Object.keys(options).length === Object.keys(selectedOptions).length) {
|
||||
match = String(productId);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
function ensureStickyInquiryButtons() {
|
||||
$('.esun-sticky-product-bar__actions').each(function () {
|
||||
var $actions = $(this);
|
||||
if (!$actions.find('[data-role="esun-sticky-product-inquiry"]').length) {
|
||||
$('<button>', {
|
||||
type: 'button',
|
||||
'class': 'action primary esun-sticky-product-inquiry',
|
||||
'data-role': 'esun-sticky-product-inquiry',
|
||||
text: $t('Inquiry')
|
||||
}).hide().appendTo($actions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setInquiryState(enabled) {
|
||||
ensureStickyInquiryButtons();
|
||||
$trigger.toggle(enabled);
|
||||
$addToCart.toggle(!enabled).prop('disabled', enabled);
|
||||
$buyNow.closest('.esun-buy-now-row').toggle(!enabled);
|
||||
$qty.toggle(!enabled);
|
||||
$('[data-role="esun-sticky-add-to-cart"], [data-role="esun-sticky-buy-now"]').toggle(!enabled);
|
||||
$('[data-role="esun-sticky-product-inquiry"]').toggle(enabled);
|
||||
}
|
||||
|
||||
function refreshState() {
|
||||
var productId = getSelectedProductId();
|
||||
selectedChild = productId ? config.children[String(productId)] : null;
|
||||
setInquiryState(Boolean(selectedChild && selectedChild.requiresInquiry));
|
||||
}
|
||||
|
||||
function fillProductSummary() {
|
||||
var options = [];
|
||||
if (!selectedChild) {
|
||||
return;
|
||||
}
|
||||
$.each(selectedChild.options || [], function (index, option) {
|
||||
if (option.value) {
|
||||
options.push(option.label + ': ' + option.value);
|
||||
}
|
||||
});
|
||||
$form.find('[data-role="product-inquiry-product-id"]').val(selectedChild.id);
|
||||
$modal.find('[data-role="product-inquiry-product-name"]').text(
|
||||
config.parentName
|
||||
);
|
||||
$modal.find('[data-role="product-inquiry-product-options"]').text(options.join(' / '));
|
||||
}
|
||||
|
||||
function closeAfterSuccess() {
|
||||
window.clearTimeout(closeTimer);
|
||||
closeTimer = window.setTimeout(function () {
|
||||
$modal.modal('closeModal');
|
||||
if ($form[0]) {
|
||||
$form[0].reset();
|
||||
}
|
||||
$status.removeClass('success error').empty();
|
||||
$submit.prop('disabled', false).removeClass('disabled');
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
$trigger.on('click', function (event) {
|
||||
event.preventDefault();
|
||||
refreshState();
|
||||
if (!selectedChild || !selectedChild.requiresInquiry) {
|
||||
return;
|
||||
}
|
||||
fillProductSummary();
|
||||
$status.removeClass('success error').empty();
|
||||
$modal.modal('openModal');
|
||||
});
|
||||
|
||||
$(document).on('click', '[data-role="esun-sticky-product-inquiry"]', function () {
|
||||
$trigger.trigger('click');
|
||||
});
|
||||
|
||||
$form.on('submit.esunProductInquiry', function (event) {
|
||||
var closeOnSuccess = false;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (!$form.validation('isValid')) {
|
||||
return;
|
||||
}
|
||||
$submit.prop('disabled', true).addClass('disabled');
|
||||
$status.removeClass('success error').empty();
|
||||
$.ajax({
|
||||
url: config.submitUrl,
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: $form.serialize()
|
||||
}).done(function (response) {
|
||||
if (response.success) {
|
||||
if (!response.duplicate) {
|
||||
$(document).trigger('esun:generateLead', {leadType: 'product_inquiry'});
|
||||
}
|
||||
closeOnSuccess = true;
|
||||
$status.addClass('success').text(response.message);
|
||||
closeAfterSuccess();
|
||||
} else {
|
||||
$status.addClass('error').text(response.message);
|
||||
}
|
||||
}).fail(function (xhr) {
|
||||
var response = xhr.responseJSON || {};
|
||||
$status.addClass('error').text(response.message || $t('Unable to submit your inquiry.'));
|
||||
}).always(function () {
|
||||
if (!closeOnSuccess) {
|
||||
$submit.prop('disabled', false).removeClass('disabled');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on(
|
||||
'click change configurable.initialized swatch.initialized',
|
||||
'.swatch-option, .super-attribute-select, [name="selected_configurable_option"]',
|
||||
function () {
|
||||
window.setTimeout(refreshState, 20);
|
||||
window.setTimeout(refreshState, 150);
|
||||
}
|
||||
);
|
||||
[0, 100, 300, 800, 1200].forEach(function (delay) {
|
||||
window.setTimeout(refreshState, delay);
|
||||
});
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
define(['jquery', 'mage/utils/wrapper'], function ($, wrapper) {
|
||||
'use strict';
|
||||
|
||||
return function (Widget) {
|
||||
Widget.prototype._RenderControls = wrapper.wrapSuper(Widget.prototype._RenderControls, function () {
|
||||
var config = this.options.jsonConfig || {},
|
||||
widget = this,
|
||||
result;
|
||||
|
||||
if (config.canDisplayShowOutOfStockStatus) {
|
||||
config.salable = config.salable || {};
|
||||
Object.keys(config.attributes || {}).forEach(function (key) {
|
||||
var attributeId = config.attributes[key].id || key;
|
||||
config.salable[attributeId] = config.salable[attributeId] || {};
|
||||
});
|
||||
}
|
||||
|
||||
result = this._super();
|
||||
|
||||
if (config.canDisplayShowOutOfStockStatus) {
|
||||
Object.keys(config.attributes || {}).forEach(function (key) {
|
||||
var attribute = config.attributes[key],
|
||||
attributeId = attribute.id || key;
|
||||
|
||||
(attribute.options || []).forEach(function (option) {
|
||||
if (widget.optionsMap[attributeId] && widget.optionsMap[attributeId][option.id]) {
|
||||
widget.optionsMap[attributeId][option.id].products = (option.products || []).slice();
|
||||
}
|
||||
});
|
||||
});
|
||||
this._Rewind(this.element);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
Widget.prototype.disableSwatchForOutOfStockProducts = function () {
|
||||
var widget = this,
|
||||
config = this.options.jsonConfig || {},
|
||||
container = this.element;
|
||||
|
||||
if (!config.canDisplayShowOutOfStockStatus) {
|
||||
return;
|
||||
}
|
||||
Object.keys(config.attributes || {}).forEach(function (key) {
|
||||
var attributeId = config.attributes[key].id || key,
|
||||
salable = (config.salable || {})[attributeId] || {};
|
||||
widget.element.find('[data-attribute-id="' + attributeId + '"] .swatch-option').each(function () {
|
||||
var option = String($(this).data('option-id'));
|
||||
$(this).toggleClass('esun-out-of-stock-option', !Object.prototype.hasOwnProperty.call(salable, option));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return Widget;
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user