This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Block\Account;
use Esun\CustomerMessage\Model\MessageProvider;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Element\Template;
class Messages extends Template
{
private ?int $unreadCount = null;
public function __construct(Template\Context $context, private readonly Session $session, private readonly MessageProvider $provider, private readonly ConversationService $conversations, array $data = [])
{
parent::__construct($context, $data);
}
public function getMessages(): array
{
return $this->provider->getForCustomer((int)$this->session->getCustomerId(), (int)$this->_storeManager->getStore()->getId(), (int)($this->getData('limit') ?: 50));
}
public function getThreads(): array
{
return $this->conversations->getThreadsForCustomer((int)$this->session->getCustomerId(), (int)($this->getData('limit') ?: 100));
}
public function getUnreadCount(): int
{
if ($this->unreadCount === null) {
$customerId = (int)$this->session->getCustomerId();
$this->unreadCount = $customerId > 0
? $this->conversations->getCustomerUnreadTotal($customerId)
: 0;
}
return $this->unreadCount;
}
public function getSelectedThread(): ?array
{
if ((int)$this->getRequest()->getParam('new') === 1) {
return null;
}
$threadId = (int)$this->getRequest()->getParam('thread_id');
if ($threadId) {
return $this->conversations->getThreadForCustomer($threadId, (int)$this->session->getCustomerId());
}
$orderId = (int)$this->getRequest()->getParam('order_id');
if ($orderId) {
return $this->conversations->getOrderThreadForCustomer($orderId, (int)$this->session->getCustomerId());
}
$threads = $this->getThreads();
return $threads ? $this->conversations->getThreadForCustomer((int)$threads[0]['thread_id'], (int)$this->session->getCustomerId()) : null;
}
public function getConversationMessages(?array $thread): array
{
return $thread ? $this->conversations->getMessages((int)$thread['thread_id']) : [];
}
public function getOrderId(): int
{
return (int)$this->getRequest()->getParam('order_id');
}
public function getOrderIncrementId(): string
{
return (string)$this->getRequest()->getParam('order_increment_id');
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Block\Account;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Block\Account\SortLink;
use Magento\Customer\Model\Session;
use Magento\Framework\App\DefaultPathInterface;
use Magento\Framework\View\Element\Template\Context;
class NavigationLink extends SortLink
{
private ?int $unreadCount = null;
public function __construct(Context $context, DefaultPathInterface $defaultPath, private readonly Session $session, private readonly ConversationService $conversations, array $data = [])
{
parent::__construct($context, $defaultPath, $data);
}
public function getUnreadCount(): int
{
if ($this->unreadCount === null) {
$customerId = (int)$this->session->getCustomerId();
$this->unreadCount = $customerId > 0
? $this->conversations->getCustomerUnreadTotal($customerId)
: 0;
}
return $this->unreadCount;
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Block\Adminhtml\Message;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Backend\Block\Template;
use Magento\Sales\Api\OrderRepositoryInterface;
class Index extends Template
{
public function __construct(Template\Context $context, private readonly ConversationService $conversations, private readonly OrderRepositoryInterface $orders, array $data = [])
{
parent::__construct($context, $data);
}
public function getThreads(): array
{
return $this->conversations->getThreadsForAdmin();
}
public function getSelectedThread(): ?array
{
$threadId = (int)$this->getRequest()->getParam('thread_id');
if ($threadId) {
return $this->conversations->getThreadForAdmin($threadId);
}
$orderId = (int)$this->getRequest()->getParam('order_id');
return $orderId ? $this->conversations->getOrderThreadForAdmin($orderId) : null;
}
public function getMessages(?array $thread): array
{
return $thread ? $this->conversations->getMessages((int)$thread['thread_id']) : [];
}
public function getOrder(): ?\Magento\Sales\Api\Data\OrderInterface
{
$orderId = (int)$this->getRequest()->getParam('order_id');
if (!$orderId) {
return null;
}
try {
return $this->orders->get($orderId);
} catch (\Throwable) {
return null;
}
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Account;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultFactory;
class Index extends AbstractAccount implements HttpGetActionInterface
{
public function __construct(Context $context, private readonly Session $session, private readonly ConversationService $conversations)
{
parent::__construct($context);
}
public function execute()
{
$customerId = (int)$this->session->getCustomerId();
$threadId = (int)$this->getRequest()->getParam('thread_id');
$orderId = (int)$this->getRequest()->getParam('order_id');
if (!$threadId && $orderId) {
$thread = $this->conversations->getOrderThreadForCustomer($orderId, $customerId);
$threadId = $thread ? (int)$thread['thread_id'] : 0;
}
if (!$threadId && !$orderId && (int)$this->getRequest()->getParam('new') !== 1) {
$threads = $this->conversations->getThreadsForCustomer($customerId, 1);
$threadId = $threads ? (int)$threads[0]['thread_id'] : 0;
}
if ($threadId && $this->conversations->getThreadForCustomer($threadId, $customerId)) {
$this->conversations->markCustomerRead($threadId, $customerId);
}
$page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
$page->getConfig()->getTitle()->set(__('Messages'));
return $page;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Account;
use Esun\CustomerMessage\Model\MessageProvider;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Data\Form\FormKey\Validator;
class Read extends AbstractAccount implements HttpPostActionInterface
{
public function __construct(
Context $context,
private readonly RequestInterface $request,
private readonly RedirectFactory $redirects,
private readonly Validator $formKey,
private readonly Session $session,
private readonly MessageProvider $provider
) {
parent::__construct($context);
}
public function execute()
{
if ($this->formKey->validate($this->request)) {
$this->provider->markRead(
(int)$this->request->getParam('recipient_id'),
(int)$this->session->getCustomerId()
);
}
return $this->redirects->create()->setPath('customer-message/account/index');
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Adminhtml\Attachment;
use Esun\CustomerMessage\Model\AttachmentStorage;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\RawFactory;
class View extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'Esun_CustomerMessage::messages';
public function __construct(Context $context, private readonly ConversationService $conversations, private readonly AttachmentStorage $storage, private readonly RawFactory $rawFactory)
{
parent::__construct($context);
}
public function execute()
{
$result = $this->rawFactory->create();
try {
$attachment = $this->conversations->getAttachmentForAdmin((int)$this->getRequest()->getParam('id'));
if (!$attachment) {
throw new \Magento\Framework\Exception\LocalizedException(__('The requested image is not available.'));
}
$filename = str_replace(["\r", "\n"], '', (string)$attachment['original_name']);
return $result->setHeader('Content-Type', (string)$attachment['mime_type'], true)
->setHeader('Content-Length', (string)$attachment['file_size'], true)
->setHeader('Content-Disposition', 'inline; filename="' . addcslashes($filename, '"\\') . '"', true)
->setHeader('X-Content-Type-Options', 'nosniff', true)
->setContents((string)file_get_contents($this->storage->getAbsolutePath((string)$attachment['storage_path'])));
} catch (\Throwable) {
return $result->setHttpResponseCode(404)->setContents('Not found');
}
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Adminhtml\Message;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\ResourceConnection;
class Delete extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE='Esun_CustomerMessage::messages';
public function __construct(Action\Context $context, private readonly ResourceConnection $resource)
{
parent::__construct($context);
} public function execute()
{
$id=(int)$this->getRequest()->getParam('message_id');
if ($id) {
$this->resource->getConnection()->delete($this->resource->getTableName('esun_customer_message'), ['message_id=?'=>$id]);
$this->messageManager->addSuccessMessage(__('The message was deleted.'));
} return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Adminhtml\Message;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultFactory;
class Index extends Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE='Esun_CustomerMessage::messages';
public function __construct(Context $context, private readonly ConversationService $conversations)
{
parent::__construct($context);
}
public function execute()
{
$threadId = (int)$this->getRequest()->getParam('thread_id');
if (!$threadId) {
$orderId = (int)$this->getRequest()->getParam('order_id');
$thread = $orderId
? $this->conversations->getOrderThreadForAdmin($orderId)
: null;
$threadId = $thread ? (int)$thread['thread_id'] : 0;
}
if ($threadId && $this->conversations->getThreadForAdmin($threadId)) {
$this->conversations->markAdminRead($threadId);
}
$page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
$page->setActiveMenu(self::ADMIN_RESOURCE);
$page->getConfig()->getTitle()->prepend(__('Customer Messages'));
return $page;
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Adminhtml\Message;
use Magento\Backend\App\Action;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\LocalizedException;
class Save extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Esun_CustomerMessage::messages';
public function __construct(
Action\Context $context,
private readonly ResourceConnection $resource,
private readonly CollectionFactory $customers
) {
parent::__construct($context);
}
public function execute()
{
$result = $this->resultRedirectFactory->create()->setPath('*/*/index');
try {
$title = trim((string)$this->getRequest()->getParam('title'));
$content = trim((string)$this->getRequest()->getParam('content'));
$rawEmails = preg_split('/[\s,;]+/', (string)$this->getRequest()->getParam('customer_emails'));
$emails = array_values(array_unique(array_filter(array_map('trim', $rawEmails ?: []))));
if ($title === '' || $content === '' || !$emails) {
throw new LocalizedException(__('Title, content and at least one customer email are required.'));
}
$customerIds = $this->customers->create()->addFieldToFilter('email', ['in' => $emails])->getAllIds();
if (!$customerIds) {
throw new LocalizedException(__('No matching customers were found.'));
}
$connection = $this->resource->getConnection();
$connection->beginTransaction();
$connection->insert($this->resource->getTableName('esun_customer_message'), [
'title' => $title,
'content' => $content,
'message_type' => (string)$this->getRequest()->getParam('message_type', 'notice'),
'store_id' => (int)$this->getRequest()->getParam('store_id', 0),
'is_active' => 1,
'expires_at' => trim((string)$this->getRequest()->getParam('expires_at')) ?: null,
]);
$messageId = (int)$connection->lastInsertId();
foreach ($customerIds as $customerId) {
$connection->insert($this->resource->getTableName('esun_customer_message_recipient'), [
'message_id' => $messageId,
'customer_id' => (int)$customerId,
]);
}
$connection->commit();
$this->messageManager->addSuccessMessage(__('The message was sent to %1 customer(s).', count($customerIds)));
} catch (\Throwable $e) {
if ($this->resource->getConnection()->getTransactionLevel() > 0) {
$this->resource->getConnection()->rollBack();
}
$this->messageManager->addErrorMessage(
$e instanceof LocalizedException ? $e->getMessage() : __('The message could not be saved.')
);
}
return $result;
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Adminhtml\Thread;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Data\Form\FormKey\Validator;
class Reply extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Esun_CustomerMessage::messages';
public function __construct(Context $context, private readonly Validator $formKey, private readonly ConversationService $conversations)
{
parent::__construct($context);
}
public function execute()
{
$threadId = (int)$this->getRequest()->getParam('thread_id');
$orderId = (int)$this->getRequest()->getParam('order_id');
$redirect = $this->resultRedirectFactory->create();
if (!$this->formKey->validate($this->getRequest())) {
$this->messageManager->addErrorMessage(__('Your session has expired. Please try again.'));
return $redirect->setPath('esun_customer_message/message/index', $threadId ? ['thread_id' => $threadId] : ['order_id' => $orderId]);
}
try {
$threadId = $this->conversations->sendAsAdmin(
(int)$this->_auth->getUser()->getId(),
(string)$this->getRequest()->getParam('content'),
(array)$this->getRequest()->getFiles('images', []),
$threadId,
$orderId
);
$this->messageManager->addSuccessMessage(__('The reply has been sent.'));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception instanceof \Magento\Framework\Exception\LocalizedException ? $exception->getMessage() : __('The reply could not be sent.'));
}
return $redirect->setPath('esun_customer_message/message/index', ['thread_id' => $threadId]);
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Attachment;
use Esun\CustomerMessage\Model\AttachmentStorage;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\RawFactory;
class View extends AbstractAccount implements HttpGetActionInterface
{
public function __construct(Context $context, private readonly Session $session, private readonly ConversationService $conversations, private readonly AttachmentStorage $storage, private readonly RawFactory $rawFactory)
{
parent::__construct($context);
}
public function execute()
{
$result = $this->rawFactory->create();
try {
$attachment = $this->conversations->getAttachmentForCustomer((int)$this->getRequest()->getParam('id'), (int)$this->session->getCustomerId());
if (!$attachment) {
throw new \Magento\Framework\Exception\LocalizedException(__('The requested image is not available.'));
}
$filename = str_replace(["\r", "\n"], '', (string)$attachment['original_name']);
$result->setHeader('Content-Type', (string)$attachment['mime_type'], true)
->setHeader('Content-Length', (string)$attachment['file_size'], true)
->setHeader('Content-Disposition', 'inline; filename="' . addcslashes($filename, '"\\') . '"', true)
->setHeader('X-Content-Type-Options', 'nosniff', true)
->setContents((string)file_get_contents($this->storage->getAbsolutePath((string)$attachment['storage_path'])));
} catch (\Throwable) {
$result->setHttpResponseCode(404)->setContents('Not found');
}
return $result;
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Order;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
class Contact extends AbstractAccount implements HttpGetActionInterface
{
public function __construct(
Context $context,
private readonly Session $session,
private readonly OrderRepositoryInterface $orders,
private readonly ConversationService $conversations
) {
parent::__construct($context);
}
public function execute()
{
$orderId = (int)$this->getRequest()->getParam('order_id');
try {
$order = $this->orders->get($orderId);
if ((int)$order->getCustomerId() !== (int)$this->session->getCustomerId()) {
throw new \Magento\Framework\Exception\LocalizedException(__('The requested order is not available.'));
}
$this->getRequest()->setParam('order_increment_id', (string)$order->getIncrementId());
$thread = $this->conversations->getOrderThreadForCustomer($orderId, (int)$this->session->getCustomerId());
if ($thread) {
$this->conversations->markCustomerRead((int)$thread['thread_id'], (int)$this->session->getCustomerId());
}
$page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
$page->getConfig()->getTitle()->set(__('Order Messages #%1', $order->getIncrementId()));
return $page;
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(__('The requested order is not available.'));
/** @var Redirect $redirect */
$redirect = $this->resultRedirectFactory->create();
return $redirect->setPath('sales/order/history');
}
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Controller\Thread;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Data\Form\FormKey\Validator;
class Send extends AbstractAccount implements HttpPostActionInterface
{
public function __construct(
Context $context,
private readonly Session $session,
private readonly Validator $formKey,
private readonly ConversationService $conversations
) {
parent::__construct($context);
}
public function execute()
{
$redirect = $this->resultRedirectFactory->create();
$orderId = (int)$this->getRequest()->getParam('order_id');
if (!$this->formKey->validate($this->getRequest())) {
$this->messageManager->addErrorMessage(__('Your session has expired. Please try again.'));
return $redirect->setPath($orderId ? 'customer-message/order/contact' : 'customer-message/account/index', $orderId ? ['order_id' => $orderId] : []);
}
try {
$threadId = $this->conversations->sendAsCustomer(
(int)$this->session->getCustomerId(),
(int)$this->session->getCustomer()->getStoreId(),
(string)$this->getRequest()->getParam('content'),
(array)$this->getRequest()->getFiles('images', []),
(int)$this->getRequest()->getParam('thread_id'),
$orderId,
(string)$this->getRequest()->getParam('subject')
);
$this->messageManager->addSuccessMessage(__('Your message has been sent.'));
return $orderId
? $redirect->setPath('customer-message/order/contact', ['order_id' => $orderId])
: $redirect->setPath('customer-message/account/index', ['thread_id' => $threadId]);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception instanceof \Magento\Framework\Exception\LocalizedException ? $exception->getMessage() : __('The message could not be sent.'));
return $redirect->setPath($orderId ? 'customer-message/order/contact' : 'customer-message/account/index', $orderId ? ['order_id' => $orderId] : []);
}
}
}
@@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\Driver\File;
class AttachmentStorage
{
private const MAX_FILES = 5;
private const MAX_SIZE = 5242880;
private const MIME_EXTENSIONS = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
];
public function __construct(
private readonly DirectoryList $directoryList,
private readonly File $fileDriver
) {
}
public function saveUploads(array $files, int $threadId, int $entryId): array
{
$uploads = $this->normalize($files);
if (count($uploads) > self::MAX_FILES) {
throw new LocalizedException(__('You can upload up to %1 images per message.', self::MAX_FILES));
}
$saved = [];
try {
foreach ($uploads as $upload) {
if ((int)$upload['error'] === UPLOAD_ERR_NO_FILE) {
continue;
}
if ((int)$upload['error'] !== UPLOAD_ERR_OK) {
throw new LocalizedException(__('One of the images could not be uploaded.'));
}
if ((int)$upload['size'] <= 0 || (int)$upload['size'] > self::MAX_SIZE) {
throw new LocalizedException(__('Each image must be no larger than 5 MB.'));
}
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file((string)$upload['tmp_name']);
if (!isset(self::MIME_EXTENSIONS[$mime])) {
throw new LocalizedException(__('Only JPG, PNG and WebP images are allowed.'));
}
$relativeDirectory = sprintf('esun_customer_message/%d/%d', $threadId, $entryId);
$absoluteDirectory = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/' . $relativeDirectory;
$this->fileDriver->createDirectory($absoluteDirectory, 0750);
$filename = bin2hex(random_bytes(20)) . '.' . self::MIME_EXTENSIONS[$mime];
$absolutePath = $absoluteDirectory . '/' . $filename;
if (!move_uploaded_file((string)$upload['tmp_name'], $absolutePath)) {
throw new LocalizedException(__('The image could not be stored.'));
}
chmod($absolutePath, 0640);
$saved[] = [
'original_name' => mb_substr(basename((string)$upload['name']), 0, 255),
'storage_path' => $relativeDirectory . '/' . $filename,
'mime_type' => $mime,
'file_size' => (int)$upload['size'],
];
}
} catch (\Throwable $exception) {
$this->delete(array_column($saved, 'storage_path'));
throw $exception;
}
return $saved;
}
public function hasUploads(array $files): bool
{
foreach ($this->normalize($files) as $upload) {
if ((int)$upload['error'] !== UPLOAD_ERR_NO_FILE) {
return true;
}
}
return false;
}
public function getAbsolutePath(string $relativePath): string
{
$base = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/esun_customer_message';
$path = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/' . ltrim($relativePath, '/');
$realBase = realpath($base);
$realPath = realpath($path);
if ($realBase === false || $realPath === false || !str_starts_with($realPath, $realBase . DIRECTORY_SEPARATOR)) {
throw new LocalizedException(__('The requested image is not available.'));
}
return $realPath;
}
public function delete(array $relativePaths): void
{
foreach ($relativePaths as $relativePath) {
try {
$path = $this->getAbsolutePath((string)$relativePath);
if ($this->fileDriver->isExists($path)) {
$this->fileDriver->deleteFile($path);
}
} catch (\Throwable) {
// Best-effort cleanup after a failed transaction.
}
}
}
private function normalize(array $files): array
{
if (!$files) {
return [];
}
if (isset($files['name']) && is_array($files['name'])) {
$result = [];
foreach ($files['name'] as $index => $name) {
$result[] = [
'name' => $name,
'type' => $files['type'][$index] ?? '',
'tmp_name' => $files['tmp_name'][$index] ?? '',
'error' => $files['error'][$index] ?? UPLOAD_ERR_NO_FILE,
'size' => $files['size'][$index] ?? 0,
];
}
return $result;
}
if (isset($files['name'])) {
return [$files];
}
return array_values(array_filter($files, 'is_array'));
}
}
@@ -0,0 +1,345 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Model;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\OrderRepositoryInterface;
class ConversationService
{
public function __construct(
private readonly ResourceConnection $resource,
private readonly OrderRepositoryInterface $orders,
private readonly AttachmentStorage $attachments
) {
}
public function getThreadsForCustomer(int $customerId, int $limit = 100): array
{
$connection = $this->resource->getConnection();
return $connection->fetchAll(
$connection->select()->from(['thread' => $this->table('esun_customer_message_thread')])
->joinLeft(['entry' => $this->table('esun_customer_message_entry')], 'entry.entry_id=thread.last_message_id', ['last_content' => 'content', 'last_sender_type' => 'sender_type'])
->joinLeft(['orders' => $this->table('sales_order')], 'orders.entity_id=thread.order_id', ['order_increment_id' => 'increment_id'])
->where('thread.customer_id=?', $customerId)
->order('thread.last_message_at DESC')
->limit(max(1, min(100, $limit)))
);
}
public function getCustomerUnreadTotal(int $customerId): int
{
$connection = $this->resource->getConnection();
return (int)$connection->fetchOne(
$connection->select()->from($this->table('esun_customer_message_thread'), ['total' => new \Zend_Db_Expr('COALESCE(SUM(customer_unread_count), 0)')])
->where('customer_id=?', $customerId)
);
}
/**
* Return unread message totals keyed by order entity ID.
*
* @param int[] $orderIds
* @return array<int, int>
*/
public function getCustomerUnreadByOrderIds(int $customerId, array $orderIds): array
{
$orderIds = array_values(array_unique(array_filter(array_map('intval', $orderIds))));
if ($customerId <= 0 || !$orderIds) {
return [];
}
$connection = $this->resource->getConnection();
$rows = $connection->fetchPairs(
$connection->select()
->from(
$this->table('esun_customer_message_thread'),
['order_id', 'customer_unread_count']
)
->where('customer_id=?', $customerId)
->where('order_id IN (?)', $orderIds)
->where('customer_unread_count > ?', 0)
);
$counts = [];
foreach ($rows as $orderId => $count) {
$counts[(int)$orderId] = (int)$count;
}
return $counts;
}
/**
* Return administrator unread message totals keyed by order entity ID.
*
* @param int[] $orderIds
* @return array<int, int>
*/
public function getAdminUnreadByOrderIds(array $orderIds): array
{
$orderIds = array_values(array_unique(array_filter(array_map('intval', $orderIds))));
if (!$orderIds) {
return [];
}
$connection = $this->resource->getConnection();
$rows = $connection->fetchPairs(
$connection->select()
->from(
$this->table('esun_customer_message_thread'),
['order_id', 'admin_unread_count']
)
->where('order_id IN (?)', $orderIds)
->where('admin_unread_count > ?', 0)
);
$counts = [];
foreach ($rows as $orderId => $count) {
$counts[(int)$orderId] = (int)$count;
}
return $counts;
}
public function getThreadsForAdmin(int $limit = 200): array
{
$connection = $this->resource->getConnection();
return $connection->fetchAll(
$connection->select()->from(['thread' => $this->table('esun_customer_message_thread')])
->joinInner(['customer' => $this->table('customer_entity')], 'customer.entity_id=thread.customer_id', ['customer_email' => 'email', 'customer_firstname' => 'firstname', 'customer_lastname' => 'lastname'])
->joinLeft(['entry' => $this->table('esun_customer_message_entry')], 'entry.entry_id=thread.last_message_id', ['last_content' => 'content'])
->joinLeft(['orders' => $this->table('sales_order')], 'orders.entity_id=thread.order_id', ['order_increment_id' => 'increment_id'])
->order('thread.admin_unread_count DESC')
->order('thread.last_message_at DESC')
->limit(max(1, min(500, $limit)))
);
}
public function getThreadForCustomer(int $threadId, int $customerId): ?array
{
return $this->fetchThread(['thread.thread_id=?' => $threadId, 'thread.customer_id=?' => $customerId]);
}
public function getThreadForAdmin(int $threadId): ?array
{
return $this->fetchThread(['thread.thread_id=?' => $threadId]);
}
public function getOrderThreadForCustomer(int $orderId, int $customerId): ?array
{
return $this->fetchThread(['thread.order_id=?' => $orderId, 'thread.customer_id=?' => $customerId]);
}
public function getOrderThreadForAdmin(int $orderId): ?array
{
return $this->fetchThread(['thread.order_id=?' => $orderId]);
}
public function getMessages(int $threadId): array
{
$connection = $this->resource->getConnection();
$messages = $connection->fetchAll(
$connection->select()->from($this->table('esun_customer_message_entry'))
->where('thread_id=?', $threadId)->order('entry_id ASC')
);
if (!$messages) {
return [];
}
$entryIds = array_column($messages, 'entry_id');
$attachmentRows = $connection->fetchAll(
$connection->select()->from($this->table('esun_customer_message_attachment'))
->where('entry_id IN (?)', $entryIds)->order('attachment_id ASC')
);
$attachments = [];
foreach ($attachmentRows as $attachment) {
$attachments[(int)$attachment['entry_id']][] = $attachment;
}
foreach ($messages as &$message) {
$message['attachments'] = $attachments[(int)$message['entry_id']] ?? [];
}
unset($message);
return $messages;
}
public function sendAsCustomer(int $customerId, int $storeId, string $content, array $files, int $threadId = 0, int $orderId = 0, string $subject = ''): int
{
$content = mb_substr(trim($content), 0, 10000);
if ($content === '' && !$this->attachments->hasUploads($files)) {
throw new LocalizedException(__('Please enter a message or upload an image.'));
}
$createdThread = false;
if ($threadId) {
$thread = $this->getThreadForCustomer($threadId, $customerId);
if (!$thread) {
throw new LocalizedException(__('The requested conversation is not available.'));
}
} elseif ($orderId) {
$order = $this->orders->get($orderId);
if ((int)$order->getCustomerId() !== $customerId) {
throw new LocalizedException(__('The requested order is not available.'));
}
$thread = $this->getOrderThreadForCustomer($orderId, $customerId);
if (!$thread) {
$threadId = $this->createThread('order', $customerId, $storeId, (string)__('Order #%1', $order->getIncrementId()), $orderId);
$createdThread = true;
} else {
$threadId = (int)$thread['thread_id'];
}
} else {
$subject = mb_substr(trim($subject), 0, 255);
if ($subject === '') {
throw new LocalizedException(__('Please enter a subject.'));
}
$threadId = $this->createThread('general', $customerId, $storeId, $subject, null);
$createdThread = true;
}
try {
return $this->append($threadId, 'customer', $customerId, $content, $files);
} catch (\Throwable $exception) {
if ($createdThread) {
$this->resource->getConnection()->delete($this->table('esun_customer_message_thread'), ['thread_id=?' => $threadId]);
}
throw $exception;
}
}
public function sendAsAdmin(int $adminId, string $content, array $files, int $threadId = 0, int $orderId = 0): int
{
$content = mb_substr(trim($content), 0, 10000);
if ($content === '' && !$this->attachments->hasUploads($files)) {
throw new LocalizedException(__('Please enter a message or upload an image.'));
}
$createdThread = false;
if ($threadId) {
$thread = $this->getThreadForAdmin($threadId);
if (!$thread) {
throw new LocalizedException(__('The requested conversation is not available.'));
}
} elseif ($orderId) {
$order = $this->orders->get($orderId);
if (!(int)$order->getCustomerId()) {
throw new LocalizedException(__('This order is not associated with a customer account.'));
}
$thread = $this->getOrderThreadForAdmin($orderId);
if ($thread) {
$threadId = (int)$thread['thread_id'];
} else {
$threadId = $this->createThread('order', (int)$order->getCustomerId(), (int)$order->getStoreId(), (string)__('Order #%1', $order->getIncrementId()), $orderId);
$createdThread = true;
}
} else {
throw new LocalizedException(__('An order or conversation is required.'));
}
try {
return $this->append($threadId, 'admin', $adminId, $content, $files);
} catch (\Throwable $exception) {
if ($createdThread) {
$this->resource->getConnection()->delete($this->table('esun_customer_message_thread'), ['thread_id=?' => $threadId]);
}
throw $exception;
}
}
public function markCustomerRead(int $threadId, int $customerId): void
{
$this->resource->getConnection()->update($this->table('esun_customer_message_thread'), ['customer_unread_count' => 0], ['thread_id=?' => $threadId, 'customer_id=?' => $customerId]);
}
public function markAdminRead(int $threadId): void
{
$this->resource->getConnection()->update($this->table('esun_customer_message_thread'), ['admin_unread_count' => 0], ['thread_id=?' => $threadId]);
}
public function getAttachmentForCustomer(int $attachmentId, int $customerId): ?array
{
return $this->fetchAttachment($attachmentId, $customerId);
}
public function getAttachmentForAdmin(int $attachmentId): ?array
{
return $this->fetchAttachment($attachmentId, null);
}
private function createThread(string $type, int $customerId, int $storeId, string $subject, ?int $orderId): int
{
$connection = $this->resource->getConnection();
$connection->insert($this->table('esun_customer_message_thread'), [
'thread_type' => $type,
'customer_id' => $customerId,
'order_id' => $orderId,
'store_id' => $storeId,
'subject' => (string)$subject,
]);
return (int)$connection->lastInsertId();
}
private function append(int $threadId, string $senderType, int $senderId, string $content, array $files): int
{
$connection = $this->resource->getConnection();
$savedPaths = [];
$connection->beginTransaction();
try {
$connection->insert($this->table('esun_customer_message_entry'), [
'thread_id' => $threadId,
'sender_type' => $senderType,
'sender_id' => $senderId,
'content' => $content,
]);
$entryId = (int)$connection->lastInsertId();
$saved = $this->attachments->saveUploads($files, $threadId, $entryId);
$savedPaths = array_column($saved, 'storage_path');
foreach ($saved as $attachment) {
$connection->insert($this->table('esun_customer_message_attachment'), ['entry_id' => $entryId] + $attachment);
}
$now = gmdate('Y-m-d H:i:s');
$data = [
'last_message_id' => $entryId,
'last_message_at' => $now,
'status' => $senderType === 'customer' ? 'awaiting_admin' : 'awaiting_customer',
];
$data[$senderType === 'customer' ? 'admin_unread_count' : 'customer_unread_count'] = new \Zend_Db_Expr(($senderType === 'customer' ? 'admin_unread_count' : 'customer_unread_count') . '+1');
$data[$senderType === 'customer' ? 'customer_unread_count' : 'admin_unread_count'] = 0;
$connection->update($this->table('esun_customer_message_thread'), $data, ['thread_id=?' => $threadId]);
$connection->commit();
return $threadId;
} catch (\Throwable $exception) {
$connection->rollBack();
$this->attachments->delete($savedPaths);
throw $exception;
}
}
private function fetchThread(array $conditions): ?array
{
$connection = $this->resource->getConnection();
$select = $connection->select()->from(['thread' => $this->table('esun_customer_message_thread')])
->joinInner(['customer' => $this->table('customer_entity')], 'customer.entity_id=thread.customer_id', ['customer_email' => 'email', 'customer_firstname' => 'firstname', 'customer_lastname' => 'lastname'])
->joinLeft(['orders' => $this->table('sales_order')], 'orders.entity_id=thread.order_id', ['order_increment_id' => 'increment_id']);
foreach ($conditions as $condition => $value) {
$select->where($condition, $value);
}
$row = $connection->fetchRow($select);
return $row ?: null;
}
private function fetchAttachment(int $attachmentId, ?int $customerId): ?array
{
$connection = $this->resource->getConnection();
$select = $connection->select()->from(['attachment' => $this->table('esun_customer_message_attachment')])
->joinInner(['entry' => $this->table('esun_customer_message_entry')], 'entry.entry_id=attachment.entry_id', [])
->joinInner(['thread' => $this->table('esun_customer_message_thread')], 'thread.thread_id=entry.thread_id', ['thread_id', 'customer_id']);
$select->where('attachment.attachment_id=?', $attachmentId);
if ($customerId !== null) {
$select->where('thread.customer_id=?', $customerId);
}
$row = $connection->fetchRow($select);
return $row ?: null;
}
private function table(string $name): string
{
return $this->resource->getTableName($name);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Model;
use Magento\Framework\App\ResourceConnection;
class MessageProvider
{
public function __construct(private readonly ResourceConnection $resource)
{
}
public function getForCustomer(int $customerId, int $storeId, int $limit = 50): array
{
$connection = $this->resource->getConnection();
return $connection->fetchAll($connection->select()->from(['recipient'=>$this->resource->getTableName('esun_customer_message_recipient')], ['recipient_id','is_read','read_at'])
->joinInner(['message'=>$this->resource->getTableName('esun_customer_message')], 'message.message_id=recipient.message_id', ['message_id','title','content','message_type','created_at','expires_at'])
->where('recipient.customer_id=?', $customerId)->where('message.is_active=?', 1)
->where('message.store_id IN (?)', [0,$storeId])->where('(message.expires_at IS NULL OR message.expires_at > UTC_TIMESTAMP())')
->order('recipient.is_read ASC')->order('message.created_at DESC')->limit(max(1, min(100, $limit))));
}
public function markRead(int $recipientId, int $customerId): bool
{
return (bool)$this->resource->getConnection()->update($this->resource->getTableName('esun_customer_message_recipient'), ['is_read'=>1,'read_at'=>gmdate('Y-m-d H:i:s')], ['recipient_id=?'=>$recipientId,'customer_id=?'=>$customerId]);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Plugin\Adminhtml;
use Magento\Backend\Model\UrlInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Block\Adminhtml\Order\View;
class OrderViewMessagesButton
{
public function __construct(private readonly UrlInterface $url)
{
}
public function beforeSetLayout(View $subject, LayoutInterface $layout): array
{
$order = $subject->getOrder();
if ($order && (int)$order->getCustomerId()) {
$subject->addButton('esun_order_messages', [
'label' => __('Messages'),
'class' => 'esun-order-messages',
'onclick' => "setLocation('" . $this->url->getUrl('esun_customer_message/message/index', ['order_id' => (int)$order->getId()]) . "')",
]);
}
return [$layout];
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Test\Unit\Plugin\Adminhtml;
use Esun\CustomerMessage\Plugin\Adminhtml\OrderViewMessagesButton;
use Magento\Backend\Model\UrlInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Sales\Block\Adminhtml\Order\View;
use Magento\Sales\Model\Order;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class OrderViewMessagesButtonTest extends TestCase
{
private UrlInterface&MockObject $url;
private OrderViewMessagesButton $plugin;
protected function setUp(): void
{
$this->url = $this->createMock(UrlInterface::class);
$this->plugin = new OrderViewMessagesButton($this->url);
}
public function testAddsMessagesButtonAndPreservesLayoutArgument(): void
{
$layout = $this->createMock(LayoutInterface::class);
$order = $this->createMock(Order::class);
$order->method('getCustomerId')->willReturn(3);
$order->method('getId')->willReturn(16);
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()
->onlyMethods(['getOrder', 'addButton'])
->getMock();
$view->method('getOrder')->willReturn($order);
$this->url->expects(self::once())
->method('getUrl')
->with('esun_customer_message/message/index', ['order_id' => 16])
->willReturn('https://esun3d.test/admin/messages/order/16');
$view->expects(self::once())
->method('addButton')
->with(
'esun_order_messages',
self::callback(static fn(array $button): bool =>
(string)$button['label'] === 'Messages'
&& str_contains($button['onclick'], '/messages/order/16')
)
);
self::assertSame([$layout], $this->plugin->beforeSetLayout($view, $layout));
}
public function testPreservesLayoutWithoutAddingButtonForGuestOrder(): void
{
$layout = $this->createMock(LayoutInterface::class);
$order = $this->createMock(Order::class);
$order->method('getCustomerId')->willReturn(null);
$view = $this->getMockBuilder(View::class)
->disableOriginalConstructor()
->onlyMethods(['getOrder', 'addButton'])
->getMock();
$view->method('getOrder')->willReturn($order);
$view->expects(self::never())->method('addButton');
self::assertSame([$layout], $this->plugin->beforeSetLayout($view, $layout));
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\Ui\Component\Listing\Column;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Framework\Escaper;
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 AdminUnread extends Column
{
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
private readonly ConversationService $conversations,
private readonly UrlInterface $urlBuilder,
private readonly Escaper $escaper,
array $components = [],
array $data = []
) {
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource): array
{
if (empty($dataSource['data']['items'])) {
return $dataSource;
}
$orderIds = array_map(
'intval',
array_column($dataSource['data']['items'], 'entity_id')
);
$counts = $this->conversations->getAdminUnreadByOrderIds($orderIds);
$columnName = (string)$this->getData('name');
foreach ($dataSource['data']['items'] as &$item) {
$orderId = (int)($item['entity_id'] ?? 0);
$count = $counts[$orderId] ?? 0;
$item[$columnName] = $count > 0
? $this->renderUnreadLink($orderId, $count)
: '<span class="esun-admin-order-unread-empty">&#8212;</span>';
}
unset($item);
return $dataSource;
}
private function renderUnreadLink(int $orderId, int $count): string
{
$url = $this->urlBuilder->getUrl(
'esun_customer_message/message/index',
['order_id' => $orderId]
);
return sprintf(
'<a class="esun-admin-order-unread" href="%s" aria-label="%s">'
. '<span class="esun-admin-order-unread__badge">%d</span>'
. '<span>%s</span></a>',
$this->escaper->escapeUrl($url),
$this->escaper->escapeHtmlAttr(__('%1 unread messages', $count)),
$count,
$this->escaper->escapeHtml(__('View'))
);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\CustomerMessage\ViewModel;
use Esun\CustomerMessage\Model\ConversationService;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Element\Block\ArgumentInterface;
class OrderUnread implements ArgumentInterface
{
public function __construct(
private readonly Session $session,
private readonly ConversationService $conversations
) {
}
/**
* @param int[] $orderIds
* @return array<int, int>
*/
public function getUnreadCounts(array $orderIds): array
{
return $this->conversations->getCustomerUnreadByOrderIds(
(int)$this->session->getCustomerId(),
$orderIds
);
}
}
@@ -0,0 +1,2 @@
<?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="Magento_Customer::customer"><resource id="Esun_CustomerMessage::messages" title="Customer Messages" sortOrder="90"/></resource></resource></resources></acl></config>
@@ -0,0 +1,6 @@
<?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\Sales\Block\Adminhtml\Order\View">
<plugin name="esun_customer_message_order_button" type="Esun\CustomerMessage\Plugin\Adminhtml\OrderViewMessagesButton" sortOrder="50"/>
</type>
</config>
@@ -0,0 +1,2 @@
<?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_CustomerMessage::messages" title="Customer Messages" module="Esun_CustomerMessage" sortOrder="90" parent="Magento_Customer::customer" action="esun_customer_message/message/index" resource="Esun_CustomerMessage::messages"/></menu></config>
@@ -0,0 +1,2 @@
<?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_customer_message" frontName="esun_customer_message"><module name="Esun_CustomerMessage" before="Magento_Backend"/></route></router></config>
@@ -0,0 +1,71 @@
<?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_customer_message" resource="default" engine="innodb" comment="Customer Messages">
<column xsi:type="int" name="message_id" unsigned="true" nullable="false" identity="true" comment="Message ID"/>
<column xsi:type="varchar" name="title" nullable="false" length="255" comment="Title"/>
<column xsi:type="text" name="content" nullable="false" comment="Content"/>
<column xsi:type="varchar" name="message_type" nullable="false" length="32" default="notice" comment="Message Type"/>
<column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" default="0" comment="Store ID"/>
<column xsi:type="smallint" name="is_active" unsigned="true" nullable="false" default="1" comment="Is Active"/>
<column xsi:type="timestamp" name="expires_at" nullable="true" on_update="false" comment="Expires At"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="message_id"/></constraint>
<index referenceId="ESUN_CUSTOMER_MESSAGE_ACTIVE_STORE" indexType="btree"><column name="is_active"/><column name="store_id"/><column name="created_at"/></index>
</table>
<table name="esun_customer_message_recipient" resource="default" engine="innodb" comment="Customer Message Recipients">
<column xsi:type="int" name="recipient_id" unsigned="true" nullable="false" identity="true" comment="Recipient ID"/>
<column xsi:type="int" name="message_id" unsigned="true" nullable="false" comment="Message ID"/>
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
<column xsi:type="smallint" name="is_read" unsigned="true" nullable="false" default="0" comment="Is Read"/>
<column xsi:type="timestamp" name="read_at" nullable="true" on_update="false" comment="Read At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="recipient_id"/></constraint>
<constraint xsi:type="unique" referenceId="ESUN_CUSTOMER_MESSAGE_RECIPIENT_UNQ"><column name="message_id"/><column name="customer_id"/></constraint>
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_MESSAGE_RECIPIENT_MESSAGE_FK" table="esun_customer_message_recipient" column="message_id" referenceTable="esun_customer_message" referenceColumn="message_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_MESSAGE_RECIPIENT_CUSTOMER_FK" table="esun_customer_message_recipient" column="customer_id" referenceTable="customer_entity" referenceColumn="entity_id" onDelete="CASCADE"/>
<index referenceId="ESUN_CUSTOMER_MESSAGE_RECIPIENT_CUSTOMER_READ" indexType="btree"><column name="customer_id"/><column name="is_read"/></index>
</table>
<table name="esun_customer_message_thread" resource="default" engine="innodb" comment="Customer Message Conversations">
<column xsi:type="int" name="thread_id" unsigned="true" nullable="false" identity="true" comment="Thread ID"/>
<column xsi:type="varchar" name="thread_type" nullable="false" length="16" default="general" comment="Thread Type"/>
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
<column xsi:type="int" name="order_id" unsigned="true" nullable="true" comment="Order ID"/>
<column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" default="0" comment="Store ID"/>
<column xsi:type="varchar" name="subject" nullable="false" length="255" comment="Subject"/>
<column xsi:type="varchar" name="status" nullable="false" length="24" default="awaiting_admin" comment="Conversation Status"/>
<column xsi:type="int" name="last_message_id" unsigned="true" nullable="true" comment="Last Message ID"/>
<column xsi:type="int" name="customer_unread_count" unsigned="true" nullable="false" default="0" comment="Customer Unread Count"/>
<column xsi:type="int" name="admin_unread_count" unsigned="true" nullable="false" default="0" comment="Admin Unread Count"/>
<column xsi:type="timestamp" name="last_message_at" nullable="true" on_update="false" comment="Last Message At"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="thread_id"/></constraint>
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_MESSAGE_THREAD_CUSTOMER_FK" table="esun_customer_message_thread" column="customer_id" referenceTable="customer_entity" referenceColumn="entity_id" onDelete="CASCADE"/>
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_MESSAGE_THREAD_ORDER_FK" table="esun_customer_message_thread" column="order_id" referenceTable="sales_order" referenceColumn="entity_id" onDelete="CASCADE"/>
<constraint xsi:type="unique" referenceId="ESUN_CUSTOMER_MESSAGE_THREAD_ORDER_UNQ"><column name="order_id"/></constraint>
<index referenceId="ESUN_CUSTOMER_MESSAGE_THREAD_CUSTOMER_ACTIVITY" indexType="btree"><column name="customer_id"/><column name="last_message_at"/></index>
<index referenceId="ESUN_CUSTOMER_MESSAGE_THREAD_ADMIN_QUEUE" indexType="btree"><column name="admin_unread_count"/><column name="last_message_at"/></index>
</table>
<table name="esun_customer_message_entry" resource="default" engine="innodb" comment="Customer Conversation Messages">
<column xsi:type="int" name="entry_id" unsigned="true" nullable="false" identity="true" comment="Entry ID"/>
<column xsi:type="int" name="thread_id" unsigned="true" nullable="false" comment="Thread ID"/>
<column xsi:type="varchar" name="sender_type" nullable="false" length="16" comment="Sender Type"/>
<column xsi:type="int" name="sender_id" unsigned="true" nullable="false" default="0" comment="Sender ID"/>
<column xsi:type="text" name="content" nullable="false" comment="Message Content"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="entry_id"/></constraint>
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_MESSAGE_ENTRY_THREAD_FK" table="esun_customer_message_entry" column="thread_id" referenceTable="esun_customer_message_thread" referenceColumn="thread_id" onDelete="CASCADE"/>
<index referenceId="ESUN_CUSTOMER_MESSAGE_ENTRY_THREAD_CREATED" indexType="btree"><column name="thread_id"/><column name="created_at"/></index>
</table>
<table name="esun_customer_message_attachment" resource="default" engine="innodb" comment="Customer Message Attachments">
<column xsi:type="int" name="attachment_id" unsigned="true" nullable="false" identity="true" comment="Attachment ID"/>
<column xsi:type="int" name="entry_id" unsigned="true" nullable="false" comment="Entry ID"/>
<column xsi:type="varchar" name="original_name" nullable="false" length="255" comment="Original File Name"/>
<column xsi:type="varchar" name="storage_path" nullable="false" length="512" comment="Private Storage Path"/>
<column xsi:type="varchar" name="mime_type" nullable="false" length="64" comment="MIME Type"/>
<column xsi:type="int" name="file_size" unsigned="true" nullable="false" comment="File Size"/>
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Created At"/>
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="attachment_id"/></constraint>
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_MESSAGE_ATTACHMENT_ENTRY_FK" table="esun_customer_message_attachment" column="entry_id" referenceTable="esun_customer_message_entry" referenceColumn="entry_id" onDelete="CASCADE"/>
<index referenceId="ESUN_CUSTOMER_MESSAGE_ATTACHMENT_ENTRY" indexType="btree"><column name="entry_id"/></index>
</table>
</schema>
@@ -0,0 +1,100 @@
{
"esun_customer_message": {
"column": {
"message_id": true,
"title": true,
"content": true,
"message_type": true,
"store_id": true,
"is_active": true,
"expires_at": true,
"created_at": true
},
"index": {
"ESUN_CUSTOMER_MESSAGE_IS_ACTIVE_STORE_ID_CREATED_AT": true
},
"constraint": {
"PRIMARY": true
}
},
"esun_customer_message_recipient": {
"column": {
"recipient_id": true,
"message_id": true,
"customer_id": true,
"is_read": true,
"read_at": true
},
"index": {
"ESUN_CUSTOMER_MESSAGE_RECIPIENT_CUSTOMER_ID_IS_READ": true
},
"constraint": {
"PRIMARY": true,
"ESUN_CUSTOMER_MESSAGE_RECIPIENT_MESSAGE_ID_CUSTOMER_ID": true,
"FK_FA1F9D6D6857DA4089E6B19102455BC3": true,
"ESUN_CSTR_MESSAGE_RECIPIENT_CSTR_ID_CSTR_ENTT_ENTT_ID": true
}
},
"esun_customer_message_thread": {
"column": {
"thread_id": true,
"thread_type": true,
"customer_id": true,
"order_id": true,
"store_id": true,
"subject": true,
"status": true,
"last_message_id": true,
"customer_unread_count": true,
"admin_unread_count": true,
"last_message_at": true,
"created_at": true,
"updated_at": true
},
"index": {
"ESUN_CUSTOMER_MESSAGE_THREAD_CUSTOMER_ID_LAST_MESSAGE_AT": true,
"ESUN_CUSTOMER_MESSAGE_THREAD_ADMIN_UNREAD_COUNT_LAST_MESSAGE_AT": true
},
"constraint": {
"PRIMARY": true,
"ESUN_CSTR_MESSAGE_THREAD_CSTR_ID_CSTR_ENTT_ENTT_ID": true,
"ESUN_CUSTOMER_MESSAGE_THREAD_ORDER_ID_SALES_ORDER_ENTITY_ID": true,
"ESUN_CUSTOMER_MESSAGE_THREAD_ORDER_ID": true
}
},
"esun_customer_message_entry": {
"column": {
"entry_id": true,
"thread_id": true,
"sender_type": true,
"sender_id": true,
"content": true,
"created_at": true
},
"index": {
"ESUN_CUSTOMER_MESSAGE_ENTRY_THREAD_ID_CREATED_AT": true
},
"constraint": {
"PRIMARY": true,
"FK_07689EF6ABC3F370CA3CEF592CBAAFE2": true
}
},
"esun_customer_message_attachment": {
"column": {
"attachment_id": true,
"entry_id": true,
"original_name": true,
"storage_path": true,
"mime_type": true,
"file_size": true,
"created_at": true
},
"index": {
"ESUN_CUSTOMER_MESSAGE_ATTACHMENT_ENTRY_ID": true
},
"constraint": {
"PRIMARY": true,
"FK_89AAD325176E4D6C941006B549BD21FA": true
}
}
}
@@ -0,0 +1,2 @@
<?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="customer_message" frontName="customer-message"><module name="Esun_CustomerMessage"/></route></router></config>
@@ -0,0 +1,4 @@
<?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_CustomerMessage"><sequence><module name="Magento_Customer"/><module name="Esun_Customer"/></sequence></module>
</config>
@@ -0,0 +1,4 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_CustomerMessage', __DIR__);
@@ -0,0 +1,2 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><head><css src="Esun_CustomerMessage::css/admin-messages.css"/></head><body><referenceContainer name="content"><block class="Esun\CustomerMessage\Block\Adminhtml\Message\Index" name="esun.customer.message.admin" template="Esun_CustomerMessage::message/index.phtml" cacheable="false"/></referenceContainer></body></page>
@@ -0,0 +1,7 @@
<?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_CustomerMessage::css/admin-order-unread.css"/>
</head>
</page>
@@ -0,0 +1,60 @@
<?php
/** @var \Esun\CustomerMessage\Block\Adminhtml\Message\Index $block */
/** @var \Magento\Framework\Escaper $escaper */
$threads = $block->getThreads();
$thread = $block->getSelectedThread();
$entries = $block->getMessages($thread);
$order = $block->getOrder();
$orderId = $order ? (int)$order->getEntityId() : (int)($thread['order_id'] ?? 0);
$customerName = trim(implode(' ', array_filter([
(string)($thread['customer_firstname'] ?? ($order ? $order->getCustomerFirstname() : '')),
(string)($thread['customer_lastname'] ?? ($order ? $order->getCustomerLastname() : '')),
])));
$customerName = $customerName
?: (string)($thread['customer_email'] ?? ($order ? $order->getCustomerEmail() : ''))
?: (string)__('Customer');
?>
<div class="esun-admin-inbox">
<aside class="esun-admin-inbox__threads">
<div class="esun-admin-inbox__search"><input class="admin__control-text" type="search" placeholder="<?= $escaper->escapeHtmlAttr(__('Search conversations')) ?>" data-role="thread-search"></div>
<?php foreach ($threads as $item): ?>
<a class="esun-admin-thread <?= $thread && (int)$thread['thread_id'] === (int)$item['thread_id'] ? 'is-active' : '' ?>" data-search="<?= $escaper->escapeHtmlAttr(strtolower($item['customer_email'] . ' ' . $item['subject'] . ' ' . ($item['order_increment_id'] ?? ''))) ?>" href="<?= $escaper->escapeUrl($block->getUrl('esun_customer_message/message/index', ['thread_id' => (int)$item['thread_id']])) ?>">
<strong><?= $escaper->escapeHtml($item['customer_email']) ?></strong>
<span><?= $escaper->escapeHtml($item['subject']) ?></span>
<small><?= $escaper->escapeHtml(mb_substr((string)$item['last_content'], 0, 70)) ?></small>
<?php if ((int)$item['admin_unread_count']): ?><b><?= (int)$item['admin_unread_count'] ?></b><?php endif; ?>
</a>
<?php endforeach; ?>
</aside>
<section class="esun-admin-inbox__conversation">
<?php if ($thread || $order): ?>
<header><div><h1><?= $escaper->escapeHtml($thread['subject'] ?? __('Order #%1', $order->getIncrementId())) ?></h1><span><?= $escaper->escapeHtml($thread['customer_email'] ?? $order->getCustomerEmail()) ?></span></div><?php if ($orderId): ?><a href="<?= $escaper->escapeUrl($block->getUrl('sales/order/view', ['order_id' => $orderId])) ?>"><?= $escaper->escapeHtml(__('View Order')) ?></a><?php endif; ?></header>
<div class="esun-admin-inbox__entries">
<?php if ($entries): foreach ($entries as $entry): ?>
<article class="esun-admin-entry is-<?= $escaper->escapeHtmlAttr($entry['sender_type']) ?>">
<small><?= $escaper->escapeHtml($entry['sender_type'] === 'admin' ? __('Manager') : $customerName) ?> · <?= $escaper->escapeHtml($block->formatDate($entry['created_at'], \IntlDateFormatter::MEDIUM, true)) ?></small>
<div><?= nl2br($escaper->escapeHtml($entry['content'])) ?><?php if ($entry['attachments']): ?><div class="esun-admin-entry__images"><?php foreach ($entry['attachments'] as $attachment): ?><a href="<?= $escaper->escapeUrl($block->getUrl('esun_customer_message/attachment/view', ['id' => (int)$attachment['attachment_id']])) ?>" target="_blank" rel="noopener"><img src="<?= $escaper->escapeUrl($block->getUrl('esun_customer_message/attachment/view', ['id' => (int)$attachment['attachment_id']])) ?>" alt="<?= $escaper->escapeHtmlAttr($attachment['original_name']) ?>"></a><?php endforeach; ?></div><?php endif; ?></div>
</article>
<?php endforeach; else: ?><p class="esun-admin-inbox__empty"><?= $escaper->escapeHtml(__('Start an order conversation with this customer.')) ?></p><?php endif; ?>
</div>
<form class="esun-admin-reply" method="post" enctype="multipart/form-data" action="<?= $escaper->escapeUrl($block->getUrl('esun_customer_message/thread/reply')) ?>">
<?= $block->getBlockHtml('formkey') ?>
<?php if ($thread): ?><input type="hidden" name="thread_id" value="<?= (int)$thread['thread_id'] ?>"><?php endif; ?>
<?php if ($orderId): ?><input type="hidden" name="order_id" value="<?= $orderId ?>"><?php endif; ?>
<textarea class="admin__control-textarea" name="content" rows="4" placeholder="<?= $escaper->escapeHtmlAttr(__('Enter a reply...')) ?>"></textarea>
<div><label class="action-secondary"><span><?= $escaper->escapeHtml(__('Add Images')) ?></span><input type="file" name="images[]" accept="image/jpeg,image/png,image/webp" multiple hidden></label><small><?= $escaper->escapeHtml(__('Up to 5 JPG, PNG or WebP images, 5 MB each.')) ?></small><button class="action-primary" type="submit"><?= $escaper->escapeHtml(__('Send')) ?></button></div>
</form>
<?php else: ?>
<div class="esun-admin-inbox__placeholder"><h2><?= $escaper->escapeHtml(__('Customer Messages')) ?></h2><p><?= $escaper->escapeHtml(__('Select a conversation to view and reply.')) ?></p></div>
<?php endif; ?>
</section>
</div>
<script>
require(['jquery'], function ($) {
'use strict';
$('[data-role=thread-search]').on('input', function () {
var query = this.value.toLowerCase();
$('.esun-admin-thread').each(function () { $(this).toggle($(this).data('search').indexOf(query) !== -1); });
});
});
</script>
@@ -0,0 +1,19 @@
<?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">
<columns name="sales_order_columns">
<column name="esun_message_unread"
class="Esun\CustomerMessage\Ui\Component\Listing\Column\AdminUnread"
component="Esun_CustomerMessage/js/grid/columns/admin-unread"
sortOrder="85">
<settings>
<bodyTmpl>ui/grid/cells/html</bodyTmpl>
<disableAction>true</disableAction>
<label translate="true">Unread Messages</label>
<sortable>false</sortable>
<filter>false</filter>
<visible>true</visible>
</settings>
</column>
</columns>
</listing>
@@ -0,0 +1 @@
.esun-admin-inbox{background:#fff;border:1px solid #ddd;display:grid;grid-template-columns:360px minmax(0,1fr);height:calc(100vh - 180px);min-height:620px}.esun-admin-inbox__threads{border-right:1px solid #ddd;overflow-y:auto}.esun-admin-inbox__search{border-bottom:1px solid #ddd;padding:18px}.esun-admin-thread{border-bottom:1px solid #eee;color:#333;display:block;min-height:76px;padding:15px 45px 15px 18px;position:relative;text-decoration:none}.esun-admin-thread:hover,.esun-admin-thread.is-active{background:#f4faf7;color:#111;text-decoration:none}.esun-admin-thread strong,.esun-admin-thread span,.esun-admin-thread small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.esun-admin-thread span{margin-top:5px}.esun-admin-thread small{color:#999;margin-top:4px}.esun-admin-thread b{background:#18aa59;border-radius:99px;color:#fff;min-width:20px;padding:2px 6px;position:absolute;right:15px;text-align:center;top:18px}.esun-admin-inbox__conversation{display:flex;flex-direction:column;min-width:0}.esun-admin-inbox__conversation>header{align-items:center;border-bottom:1px solid #ddd;display:flex;justify-content:space-between;padding:18px 24px}.esun-admin-inbox__conversation h1{font-size:22px;margin:0 0 5px}.esun-admin-inbox__entries{flex:1;overflow-y:auto;padding:25px}.esun-admin-entry{margin:0 0 24px;max-width:70%}.esun-admin-entry.is-admin{margin-left:auto}.esun-admin-entry>small{color:#888;display:block;margin-bottom:7px}.esun-admin-entry.is-admin>small{text-align:right}.esun-admin-entry>div{background:#f5f5f5;border-radius:20px;padding:16px 20px}.esun-admin-entry.is-admin>div{background:#dff5ea}.esun-admin-entry__images{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px}.esun-admin-entry__images img{background:#fff;height:100px;object-fit:cover;width:100px}.esun-admin-reply{border-top:1px solid #ddd;padding:18px 24px}.esun-admin-reply>.admin__control-textarea{box-sizing:border-box;display:block;min-height:120px;width:100%}.esun-admin-reply>div{align-items:center;display:flex;gap:14px;margin-top:12px}.esun-admin-reply button{margin-left:auto}.esun-admin-inbox__placeholder{color:#999;margin:auto;text-align:center}@media(max-width:900px){.esun-admin-inbox{grid-template-columns:280px minmax(0,1fr)}.esun-admin-entry{max-width:90%}}
@@ -0,0 +1,26 @@
.esun-admin-order-unread {
align-items: center;
display: inline-flex;
gap: 7px;
white-space: nowrap;
}
.esun-admin-order-unread__badge {
align-items: center;
background: #e22626;
border-radius: 999px;
box-sizing: border-box;
color: #fff;
display: inline-flex;
font-size: 12px;
font-weight: 700;
height: 22px;
justify-content: center;
line-height: 22px;
min-width: 22px;
padding: 0 7px;
}
.esun-admin-order-unread-empty {
color: #adadad;
}
@@ -0,0 +1,16 @@
define([
'Magento_Ui/js/grid/columns/column'
], function (Column) {
'use strict';
return Column.extend({
/**
* Keep the order grid's default cell action away from message links.
*
* @returns {undefined}
*/
getFieldHandler: function () {
return undefined;
}
});
});
@@ -0,0 +1,20 @@
<?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_CustomerMessage::css/unread-badges.css"/>
</head>
<body>
<referenceBlock name="customer_account_navigation">
<block class="Esun\CustomerMessage\Block\Account\NavigationLink"
name="customer-account-navigation-messages"
template="Esun_CustomerMessage::account/navigation-link.phtml">
<arguments>
<argument name="path" xsi:type="string">customer-message/account/index</argument>
<argument name="label" xsi:type="string" translate="true">Message</argument>
<argument name="sortOrder" xsi:type="number">230</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
@@ -0,0 +1,2 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><body><referenceBlock name="esun.customer.dashboard"><block class="Esun\CustomerMessage\Block\Account\Messages" name="esun.customer.dashboard.messages" as="messages" template="Esun_CustomerMessage::account/preview.phtml" cacheable="false"><arguments><argument name="limit" xsi:type="number">3</argument></arguments></block></referenceBlock></body></page>
@@ -0,0 +1,2 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><update handle="customer_account"/><head><css src="Esun_CustomerMessage::css/messages.css"/></head><body><referenceBlock name="page.main.title" remove="true"/><referenceContainer name="content"><block class="Esun\CustomerMessage\Block\Account\Messages" name="customer.messages.list" template="Esun_CustomerMessage::account/messages.phtml" cacheable="false"/></referenceContainer></body></page>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<update handle="customer_account"/>
<head><css src="Esun_CustomerMessage::css/messages.css"/></head>
<body>
<referenceBlock name="page.main.title" remove="true"/>
<referenceContainer name="content"><block class="Esun\CustomerMessage\Block\Account\Messages" name="customer.order.messages" template="Esun_CustomerMessage::account/messages.phtml" cacheable="false"/></referenceContainer>
</body>
</page>
@@ -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>
<referenceBlock name="esun.sales.order.history">
<arguments>
<argument name="message_unread_view_model" xsi:type="object">Esun\CustomerMessage\ViewModel\OrderUnread</argument>
</arguments>
</referenceBlock>
</body>
</page>
@@ -0,0 +1,73 @@
<?php
/** @var \Esun\CustomerMessage\Block\Account\Messages $block */
/** @var \Magento\Framework\Escaper $escaper */
$threads = $block->getThreads();
$thread = $block->getSelectedThread();
$entries = $block->getConversationMessages($thread);
$orderId = $block->getOrderId();
$conversationOrderId = $orderId ?: (int)($thread['order_id'] ?? 0);
$orderIncrementId = (string)($thread['order_increment_id'] ?? $block->getOrderIncrementId());
$isNewGeneral = !$orderId && !$thread;
?>
<div class="esun-conversation-layout <?= $orderId ? 'is-order-conversation' : '' ?>">
<?php if (!$orderId): ?>
<aside class="esun-conversation-sidebar">
<a class="action primary esun-conversation-new" href="<?= $escaper->escapeUrl($block->getUrl('customer-message/account/index', ['new' => 1])) ?>"><?= $escaper->escapeHtml(__('New Message')) ?></a>
<div class="esun-conversation-thread-list">
<?php foreach ($threads as $item): ?>
<a class="esun-conversation-thread <?= $thread && (int)$thread['thread_id'] === (int)$item['thread_id'] ? 'is-active' : '' ?>" href="<?= $escaper->escapeUrl($block->getUrl('customer-message/account/index', ['thread_id' => (int)$item['thread_id']])) ?>">
<strong><?= $escaper->escapeHtml($item['subject']) ?></strong>
<?php if ($item['thread_type'] === 'order' && $item['order_increment_id']): ?><small>#<?= $escaper->escapeHtml($item['order_increment_id']) ?></small><?php endif; ?>
<span><?= $escaper->escapeHtml(mb_substr((string)$item['last_content'], 0, 70)) ?></span>
<?php if ((int)$item['customer_unread_count']): ?><b><?= (int)$item['customer_unread_count'] ?></b><?php endif; ?>
</a>
<?php endforeach; ?>
</div>
</aside>
<?php endif; ?>
<section class="esun-conversation-main">
<header>
<h1><?= $escaper->escapeHtml($thread ? $thread['subject'] : ($orderId ? __('Order Messages') : __('New Message'))) ?></h1>
<?php if ($conversationOrderId && $orderIncrementId): ?><a href="<?= $escaper->escapeUrl($block->getUrl('sales/order/view', ['order_id' => $conversationOrderId])) ?>"><?= $escaper->escapeHtml(__('Order Number: %1', $orderIncrementId)) ?></a><?php endif; ?>
</header>
<div class="esun-conversation-messages">
<?php if ($entries): foreach ($entries as $entry): ?>
<article class="esun-conversation-entry is-<?= $escaper->escapeHtmlAttr($entry['sender_type']) ?>">
<small><?= $escaper->escapeHtml($entry['sender_type'] === 'customer' ? __('You') : __('Manager')) ?> · <?= $escaper->escapeHtml($block->formatDate($entry['created_at'], \IntlDateFormatter::MEDIUM, true)) ?></small>
<div class="esun-conversation-bubble"><?= nl2br($escaper->escapeHtml($entry['content'])) ?>
<?php if ($entry['attachments']): ?><div class="esun-conversation-images"><?php foreach ($entry['attachments'] as $attachment): ?><a href="<?= $escaper->escapeUrl($block->getUrl('customer-message/attachment/view', ['id' => (int)$attachment['attachment_id']])) ?>" target="_blank" rel="noopener"><img src="<?= $escaper->escapeUrl($block->getUrl('customer-message/attachment/view', ['id' => (int)$attachment['attachment_id']])) ?>" alt="<?= $escaper->escapeHtmlAttr($attachment['original_name']) ?>" loading="lazy"></a><?php endforeach; ?></div><?php endif; ?>
</div>
</article>
<?php endforeach; elseif (!$isNewGeneral): ?>
<p class="esun-conversation-empty"><?= $escaper->escapeHtml(__('No messages have been sent for this order yet.')) ?></p>
<?php endif; ?>
</div>
<form class="esun-conversation-compose" method="post" enctype="multipart/form-data" action="<?= $escaper->escapeUrl($block->getUrl('customer-message/thread/send')) ?>">
<?= $block->getBlockHtml('formkey') ?>
<?php if ($thread): ?><input type="hidden" name="thread_id" value="<?= (int)$thread['thread_id'] ?>"><?php endif; ?>
<?php if ($orderId): ?><input type="hidden" name="order_id" value="<?= $orderId ?>"><?php endif; ?>
<?php if ($isNewGeneral): ?><label><span><?= $escaper->escapeHtml(__('Subject')) ?></span><input class="input-text" type="text" name="subject" maxlength="255" required></label><?php endif; ?>
<label><span><?= $escaper->escapeHtml(__('Message')) ?></span><textarea name="content" rows="4" placeholder="<?= $escaper->escapeHtmlAttr(__('Please enter your message...')) ?>"></textarea></label>
<div class="esun-conversation-compose__actions">
<label class="esun-conversation-upload"><i class="iconfont icon-picture1" aria-hidden="true"></i><span><?= $escaper->escapeHtml(__('Add Images')) ?></span><input type="file" name="images[]" accept="image/jpeg,image/png,image/webp" multiple></label>
<small><?= $escaper->escapeHtml(__('JPG, PNG or WebP. Up to 5 images, 5 MB each.')) ?></small>
<button class="action primary" type="submit"><?= $escaper->escapeHtml(__('Send')) ?></button>
</div>
<div class="esun-conversation-preview" aria-live="polite"></div>
</form>
</section>
</div>
<script>
require(['jquery'], function ($) {
'use strict';
$('.esun-conversation-compose input[type=file]').on('change', function () {
var preview = $(this).closest('form').find('.esun-conversation-preview').empty();
Array.prototype.slice.call(this.files, 0, 5).forEach(function (file) {
if (!file.type.match(/^image\/(jpeg|png|webp)$/)) { return; }
var reader = new FileReader();
reader.onload = function (event) { $('<img>').attr('src', event.target.result).attr('alt', file.name).appendTo(preview); };
reader.readAsDataURL(file);
});
});
});
</script>
@@ -0,0 +1,18 @@
<?php
/** @var \Esun\CustomerMessage\Block\Account\NavigationLink $block */
/** @var \Magento\Framework\Escaper $escaper */
$unreadCount = $block->getUnreadCount();
$label = __((string)$block->getLabel());
?>
<li class="nav item<?= $block->isCurrent() ? ' current' : '' ?>">
<?php if ($block->isCurrent()): ?>
<strong aria-current="page">
<?php else: ?>
<a href="<?= $escaper->escapeUrl($block->getHref()) ?>"<?= $block->getTitle() ? ' title="' . $escaper->escapeHtmlAttr(__((string)$block->getTitle())) . '"' : '' ?>>
<?php endif; ?>
<span><?= $escaper->escapeHtml($label) ?></span>
<?php if ($unreadCount): ?>
<b class="esun-unread-badge" aria-label="<?= $escaper->escapeHtmlAttr(__('%1 unread messages', $unreadCount)) ?>"><?= (int)$unreadCount ?></b>
<?php endif; ?>
<?= $block->isCurrent() ? '</strong>' : '</a>' ?>
</li>
@@ -0,0 +1,17 @@
<?php
/** @var \Esun\CustomerMessage\Block\Account\Messages $block */
/** @var \Magento\Framework\Escaper $escaper */
$threads = $block->getThreads();
$notices = $block->getMessages();
$unreadCount = $block->getUnreadCount();
?>
<article class="esun-service-card">
<a class="esun-service-card__link" href="<?= $escaper->escapeUrl($block->getUrl('customer-message/account/index')) ?>"><i class="iconfont icon-chat1" aria-hidden="true"></i><span><?= $escaper->escapeHtml(__('Messages')) ?></span><?php if ($unreadCount): ?><b class="esun-unread-badge" aria-label="<?= $escaper->escapeHtmlAttr(__('%1 unread messages', $unreadCount)) ?>"><?= (int)$unreadCount ?></b><?php endif; ?></a>
<?php if ($threads): foreach (array_slice($threads, 0, 3) as $thread): ?>
<a class="esun-dashboard-row <?= (int)$thread['customer_unread_count'] ? 'is-unread' : 'is-read' ?>" href="<?= $escaper->escapeUrl($block->getUrl('customer-message/account/index', ['thread_id' => (int)$thread['thread_id']])) ?>"><strong><?= $escaper->escapeHtml($thread['subject']) ?></strong><span><?= $escaper->escapeHtml($block->formatDate($thread['last_message_at'])) ?></span></a>
<?php endforeach; elseif ($notices): foreach ($notices as $message): ?>
<a class="esun-dashboard-row <?= $message['is_read'] ? 'is-read' : 'is-unread' ?>" href="<?= $escaper->escapeUrl($block->getUrl('customer-message/account/index')) ?>"><strong><?= $escaper->escapeHtml($message['title']) ?></strong><span><?= $escaper->escapeHtml($block->formatDate($message['created_at'])) ?></span></a>
<?php endforeach; else: ?>
<p class="esun-empty-note"><?= $escaper->escapeHtml(__('You have no messages.')) ?></p>
<?php endif; ?>
</article>
@@ -0,0 +1,233 @@
.account.customer-message-account-index .column.main,
.account.customer-message-order-contact .column.main {
background: transparent;
padding: 0 !important;
}
.esun-conversation-layout {
background: #fff;
border-radius: 7px;
display: grid;
grid-template-columns: 330px minmax(0, 1fr);
min-height: 720px;
overflow: hidden;
}
.esun-conversation-layout.is-order-conversation {
display: block;
}
.esun-conversation-sidebar {
border-right: 1px solid #e1e1e1;
min-width: 0;
}
.esun-conversation-new {
display: block;
margin: 22px;
text-align: center;
}
.esun-conversation-thread {
border-top: 1px solid #ededed;
color: #333;
display: block;
min-height: 78px;
padding: 17px 48px 17px 22px;
position: relative;
text-decoration: none;
}
.esun-conversation-thread:hover,
.esun-conversation-thread.is-active {
background: #f3faf6;
color: #222;
text-decoration: none;
}
.esun-conversation-thread strong,
.esun-conversation-thread span,
.esun-conversation-thread small {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.esun-conversation-thread span,
.esun-conversation-thread small {
color: #999;
font-size: 13px;
margin-top: 5px;
}
.esun-conversation-thread b {
background: #18aa59;
border-radius: 99px;
color: #fff;
font-size: 12px;
min-width: 19px;
padding: 2px 6px;
position: absolute;
right: 17px;
text-align: center;
top: 18px;
}
.esun-conversation-main {
display: flex;
flex-direction: column;
min-width: 0;
}
.esun-conversation-main > header {
align-items: center;
border-bottom: 1px solid #e1e1e1;
display: flex;
justify-content: space-between;
padding: 24px 30px;
}
.esun-conversation-main > header h1 {
font-size: 27px;
font-weight: 500;
margin: 0;
}
.esun-conversation-main > header a {
color: #18aa59;
}
.esun-conversation-messages {
flex: 1;
max-height: 650px;
min-height: 420px;
overflow-y: auto;
padding: 30px;
}
.esun-conversation-entry {
margin-bottom: 27px;
max-width: 72%;
}
.esun-conversation-entry.is-customer {
margin-left: auto;
}
.esun-conversation-entry > small {
color: #888;
display: block;
margin-bottom: 8px;
}
.esun-conversation-entry.is-customer > small {
text-align: right;
}
.esun-conversation-bubble {
background: #f5f5f5;
border-radius: 26px;
line-height: 1.6;
min-height: 24px;
padding: 18px 23px;
}
.esun-conversation-entry.is-customer .esun-conversation-bubble {
background: #e4f6ed;
}
.esun-conversation-images {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 13px;
}
.esun-conversation-images img {
background: #fff;
border-radius: 7px;
height: 110px;
object-fit: cover;
width: 110px;
}
.esun-conversation-empty {
color: #999;
padding: 80px 20px;
text-align: center;
}
.esun-conversation-compose {
border-top: 1px solid #e1e1e1;
padding: 22px 30px 25px;
}
.esun-conversation-compose > label > span {
display: block;
margin-bottom: 7px;
}
.esun-conversation-compose input.input-text,
.esun-conversation-compose textarea {
box-sizing: border-box;
margin-bottom: 15px;
width: 100%;
}
.esun-conversation-compose__actions {
align-items: center;
display: flex;
gap: 13px;
}
.esun-conversation-compose__actions > button {
margin-left: auto;
min-width: 120px;
}
.esun-conversation-upload {
align-items: center;
color: #18aa59;
cursor: pointer;
display: inline-flex;
gap: 7px;
}
.esun-conversation-upload input {
height: 1px;
opacity: 0;
overflow: hidden;
position: absolute;
width: 1px;
}
.esun-conversation-preview {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.esun-conversation-preview img {
border-radius: 5px;
height: 72px;
object-fit: cover;
width: 72px;
}
@media (max-width: 900px) {
.esun-conversation-layout { grid-template-columns: 260px minmax(0, 1fr); }
.esun-conversation-entry { max-width: 88%; }
}
@media (max-width: 767px) {
.esun-conversation-layout { display: block; min-height: 0; }
.esun-conversation-sidebar { border-bottom: 1px solid #ddd; border-right: 0; max-height: 300px; overflow-y: auto; }
.esun-conversation-main > header { padding: 20px; }
.esun-conversation-main > header h1 { font-size: 22px; }
.esun-conversation-messages { min-height: 330px; padding: 20px; }
.esun-conversation-compose { padding: 20px; }
.esun-conversation-compose__actions { align-items: flex-start; flex-wrap: wrap; }
.esun-conversation-compose__actions > button { width: 100%; }
}
@@ -0,0 +1,42 @@
.esun-unread-badge {
align-items: center;
background: #f45f5a;
border-radius: 999px;
box-sizing: border-box;
color: #fff;
display: inline-flex;
flex: 0 0 auto;
font-size: 12px;
font-weight: 700;
height: 20px;
justify-content: center;
line-height: 20px;
min-width: 20px;
padding: 0 6px;
}
.account-nav .nav.item > a,
.account-nav .nav.item > strong {
align-items: center;
display: flex;
gap: 8px;
}
.account-nav .esun-unread-badge {
margin-left: auto;
}
.esun-service-card__link .esun-unread-badge {
margin-left: 2px;
}
.esun-order-contact-link {
align-items: center;
display: flex !important;
gap: 8px;
justify-content: center;
}
.esun-order-more > summary .esun-unread-badge {
margin-left: 8px;
}