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,17 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Block\Adminhtml;
use Esun\EmailPreview\Model\TemplateTypes;
use Magento\Backend\Block\Template;
use Magento\Store\Model\System\Store;
class Preview extends Template
{
public function __construct(Template\Context $context, private readonly Store $systemStore, array $data = []) { parent::__construct($context, $data); }
public function getTypes(): array { return TemplateTypes::TYPES; }
public function getStoreOptions(): array { return $this->systemStore->getStoreValuesForForm(false, true); }
public function getPreviewUrl(): string { return $this->getUrl('esun_email_preview/preview/render'); }
public function getSendUrl(): string { return $this->getUrl('esun_email_preview/preview/send'); }
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Block\Order\Email\Items;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Api\ProductRepositoryInterface;
class DefaultItems extends \Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder
{
public function __construct(\Magento\Framework\View\Element\Template\Context $context, private readonly Image $imageHelper, private readonly ProductRepositoryInterface $products, array $data = []) { parent::__construct($context, $data); }
public function getProductImageUrl(): string
{
$item = $this->getItem();
try {
$product = $item->getProductId()
? $this->products->getById((int)$item->getProductId(), false, (int)$item->getStoreId())
: $this->products->get((string)$item->getSku(), false, (int)$item->getStoreId());
$image = (string)($product->getThumbnail() ?: $product->getSmallImage() ?: $product->getImage());
if ($image === '' || $image === 'no_selection') {
return '';
}
return (string)$this->imageHelper->init($product, 'product_thumbnail_image')->resize(96, 96)->getUrl();
} catch (\Throwable) {
return '';
}
}
}
@@ -0,0 +1,6 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Controller\Adminhtml\Preview;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action { public const ADMIN_RESOURCE='Esun_EmailPreview::preview'; public function __construct(Action\Context $context, private readonly PageFactory $pages){parent::__construct($context);} public function execute(){ $page=$this->pages->create(); $page->getConfig()->getTitle()->prepend(__('Email Preview')); return $page; } }
@@ -0,0 +1,7 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Controller\Adminhtml\Preview;
use Esun\EmailPreview\Model\PreviewService;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\RawFactory;
class Render extends Action { public const ADMIN_RESOURCE='Esun_EmailPreview::preview'; public function __construct(Action\Context $context, private readonly PreviewService $service, private readonly RawFactory $rawFactory){parent::__construct($context);} public function execute(){ $result=$this->rawFactory->create(); try{$email=$this->service->render($this->getRequest()->getParams()); return $result->setHeader('Content-Type','text/html; charset=UTF-8',true)->setContents($email['html']);}catch(\Throwable $e){return $result->setHeader('Content-Type','text/html; charset=UTF-8',true)->setHttpResponseCode(400)->setContents('<div style="font:16px Arial;padding:24px;color:#b30000">'.htmlspecialchars($e->getMessage(),ENT_QUOTES,'UTF-8').'</div>');}} }
@@ -0,0 +1,6 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Controller\Adminhtml\Preview;
use Esun\EmailPreview\Model\PreviewService;
use Magento\Backend\App\Action;
class Send extends Action { public const ADMIN_RESOURCE='Esun_EmailPreview::preview'; public function __construct(Action\Context $context, private readonly PreviewService $service){parent::__construct($context);} public function execute(){try{$this->service->send($this->getRequest()->getParams(),(string)$this->getRequest()->getParam('recipient'));$this->messageManager->addSuccessMessage(__('The test email was sent.'));}catch(\Throwable $e){$this->messageManager->addErrorMessage($e->getMessage());}return $this->_redirect('esun_email_preview/preview/index');} }
@@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Model;
use Magento\Email\Model\TemplateFactory;
use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Payment\Helper\Data as PaymentHelper;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Address\Renderer as AddressRenderer;
use Magento\Sales\Model\OrderFactory;
use Magento\Sales\Model\ResourceModel\Order\Creditmemo\CollectionFactory as CreditmemoCollectionFactory;
use Magento\Sales\Model\ResourceModel\Order\Invoice\CollectionFactory as InvoiceCollectionFactory;
use Magento\Sales\Model\ResourceModel\Order\Shipment\CollectionFactory as ShipmentCollectionFactory;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
class PreviewService
{
public function __construct(
private readonly StoreManagerInterface $storeManager,
private readonly ScopeConfigInterface $scopeConfig,
private readonly TemplateFactory $templateFactory,
private readonly TransportBuilder $transportBuilder,
private readonly OrderFactory $orderFactory,
private readonly ShipmentCollectionFactory $shipments,
private readonly CreditmemoCollectionFactory $creditmemos,
private readonly InvoiceCollectionFactory $invoices,
private readonly AddressRenderer $addressRenderer,
private readonly PaymentHelper $paymentHelper
) {}
public function render(array $request): array
{
[$identifier, $variables, $storeId] = $this->prepare($request);
$template = $this->templateFactory->create();
$template->setDesignConfig(['area' => Area::AREA_FRONTEND, 'store' => $storeId]);
$template->setId($identifier);
$template->setVars($variables);
$html = $template->processTemplate();
return ['html' => $html, 'subject' => $template->getProcessedTemplateSubject($variables)];
}
public function send(array $request, string $recipient): void
{
if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
throw new LocalizedException(__('Enter a valid test recipient email address.'));
}
[$identifier, $variables, $storeId] = $this->prepare($request);
$this->transportBuilder
->setTemplateIdentifier($identifier)
->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => $storeId])
->setTemplateVars($variables)
->setFromByScope('general', $storeId)
->addTo($recipient)
->getTransport()->sendMessage();
}
private function prepare(array $request): array
{
$type = (string)($request['type'] ?? '');
if (!isset(TemplateTypes::TYPES[$type])) {
throw new LocalizedException(__('Select a supported email type.'));
}
$storeId = (int)($request['store_id'] ?? 0);
$store = $this->storeManager->getStore($storeId);
$definition = TemplateTypes::TYPES[$type];
$identifier = '';
$variables = [];
if (in_array($type, ['order', 'order_update', 'invoice', 'invoice_update', 'shipment', 'shipment_update', 'creditmemo', 'creditmemo_update'], true)) {
$order = $this->loadOrder((string)($request['increment_id'] ?? ''), $storeId);
if ($identifier === '') {
$default = $order->getCustomerIsGuest() && isset($definition['guest']) ? $definition['guest'] : $definition['template'];
$configPath = $order->getCustomerIsGuest() ? str_replace('/template', '/guest_template', $definition['config']) : $definition['config'];
$identifier = (string)($this->scopeConfig->getValue($configPath, ScopeInterface::SCOPE_STORE, $storeId) ?: $default);
}
$variables = $this->orderVariables($order);
$variables['comment'] = 'This is a preview of the latest customer notification.';
if (in_array($type, ['invoice', 'invoice_update'], true)) {
$entity = $this->invoices->create()->setOrderFilter($order)->setOrder('entity_id', 'DESC');
$number = trim((string)($request['entity_id'] ?? ''));
if ($number !== '') { $entity->addFieldToFilter('increment_id', $number); }
$invoice = $entity->getFirstItem();
if (!$invoice->getId()) { throw new LocalizedException(__('No invoice was found for this order.')); }
$variables += ['invoice' => $invoice, 'invoice_id' => $invoice->getId()];
} elseif (in_array($type, ['shipment', 'shipment_update'], true)) {
$entity = $this->shipments->create()->setOrderFilter($order)->setOrder('entity_id', 'DESC');
$number = trim((string)($request['entity_id'] ?? ''));
if ($number !== '') { $entity->addFieldToFilter('increment_id', $number); }
$shipment = $entity->getFirstItem();
if (!$shipment->getId()) { throw new LocalizedException(__('No shipment was found for this order.')); }
$variables += ['shipment' => $shipment, 'shipment_id' => $shipment->getId(), 'comment' => ''];
} elseif (in_array($type, ['creditmemo', 'creditmemo_update'], true)) {
$entity = $this->creditmemos->create()->setOrderFilter($order)->setOrder('entity_id', 'DESC');
$number = trim((string)($request['entity_id'] ?? ''));
if ($number !== '') { $entity->addFieldToFilter('increment_id', $number); }
$creditmemo = $entity->getFirstItem();
if (!$creditmemo->getId()) { throw new LocalizedException(__('No credit memo was found for this order.')); }
$variables += ['creditmemo' => $creditmemo, 'creditmemo_id' => $creditmemo->getId(), 'comment' => ''];
}
} else {
if ($identifier === '') {
$identifier = (string)($this->scopeConfig->getValue($definition['config'], ScopeInterface::SCOPE_STORE, $storeId) ?: $definition['template']);
}
$customer = new DataObject([
'id' => 0, 'firstname' => 'Preview', 'lastname' => 'Customer',
'name' => 'Preview Customer', 'email' => 'customer@example.com',
'rp_token' => 'preview-only-token'
]);
$customer->setData('confirmation', 'preview-confirmation-key');
$variables = ['store' => $store, 'customer' => $customer, 'back_url' => ''];
}
return [$identifier, $variables + $this->storeVariables($storeId), $storeId];
}
private function loadOrder(string $incrementId, int $storeId): Order
{
if (trim($incrementId) === '') { throw new LocalizedException(__('Enter an order number for this email type.')); }
$order = $this->orderFactory->create()->loadByIncrementId(trim($incrementId));
if (!$order->getId() || (int)$order->getStoreId() !== $storeId) { throw new LocalizedException(__('The order was not found in the selected Store View.')); }
return $order;
}
private function orderVariables(Order $order): array
{
return [
'order' => $order, 'order_id' => $order->getId(), 'billing' => $order->getBillingAddress(),
'payment_html' => $this->paymentHelper->getInfoBlockHtml($order->getPayment(), (int)$order->getStoreId()),
'store' => $order->getStore(),
'formattedShippingAddress' => $order->getIsVirtual() ? '' : $this->addressRenderer->format($order->getShippingAddress(), 'html'),
'formattedBillingAddress' => $this->addressRenderer->format($order->getBillingAddress(), 'html'),
'created_at_formatted' => $order->getCreatedAtFormatted(2),
'order_data' => new DataObject(['customer_name' => $order->getCustomerName(), 'is_not_virtual' => $order->getIsNotVirtual(), 'email_customer_note' => $order->getEmailCustomerNote(), 'frontend_status_label' => $order->getFrontendStatusLabel()])
];
}
private function storeVariables(int $storeId): array
{
return [
'store_email' => (string)$this->scopeConfig->getValue('trans_email/ident_general/email', ScopeInterface::SCOPE_STORE, $storeId),
'store_phone' => (string)$this->scopeConfig->getValue('general/store_information/phone', ScopeInterface::SCOPE_STORE, $storeId),
'store_hours' => (string)$this->scopeConfig->getValue('general/store_information/hours', ScopeInterface::SCOPE_STORE, $storeId),
];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\EmailPreview\Model;
final class TemplateTypes
{
public const TYPES = [
'welcome' => ['label' => 'Welcome / New account', 'template' => 'customer_create_account_email_template', 'config' => 'customer/create_account/email_template'],
'password' => ['label' => 'Password recovery', 'template' => 'customer_password_forgot_email_template', 'config' => 'customer/password/forgot_email_template'],
'account_no_password' => ['label' => 'New account without password', 'template' => 'customer_create_account_email_no_password_template', 'config' => 'customer/create_account/email_no_password_template'],
'account_confirmation' => ['label' => 'Account confirmation', 'template' => 'customer_create_account_email_confirmation_template', 'config' => 'customer/create_account/email_confirmation_template'],
'account_confirmed' => ['label' => 'Account confirmed', 'template' => 'customer_create_account_email_confirmed_template', 'config' => 'customer/create_account/email_confirmed_template'],
'change_email' => ['label' => 'Email changed', 'template' => 'customer_account_information_change_email_template', 'config' => 'customer/account_information/change_email_template'],
'change_email_password' => ['label' => 'Email and password changed', 'template' => 'customer_account_information_change_email_and_password_template', 'config' => 'customer/account_information/change_email_and_password_template'],
'password_changed' => ['label' => 'Password changed', 'template' => 'customer_password_reset_password_template', 'config' => 'customer/password/reset_password_template'],
'order' => ['label' => 'Order confirmation', 'template' => 'sales_email_order_template', 'guest' => 'sales_email_order_guest_template', 'config' => 'sales_email/order/template'],
'order_update' => ['label' => 'Order update', 'template' => 'sales_email_order_comment_template', 'guest' => 'sales_email_order_comment_guest_template', 'config' => 'sales_email/order_comment/template'],
'invoice' => ['label' => 'Invoice', 'template' => 'sales_email_invoice_template', 'guest' => 'sales_email_invoice_guest_template', 'config' => 'sales_email/invoice/template'],
'invoice_update' => ['label' => 'Invoice update', 'template' => 'sales_email_invoice_comment_template', 'guest' => 'sales_email_invoice_comment_guest_template', 'config' => 'sales_email/invoice_comment/template'],
'shipment' => ['label' => 'Shipment notification', 'template' => 'sales_email_shipment_template', 'guest' => 'sales_email_shipment_guest_template', 'config' => 'sales_email/shipment/template'],
'shipment_update' => ['label' => 'Shipment update', 'template' => 'sales_email_shipment_comment_template', 'guest' => 'sales_email_shipment_comment_guest_template', 'config' => 'sales_email/shipment_comment/template'],
'creditmemo' => ['label' => 'Refund notification', 'template' => 'sales_email_creditmemo_template', 'guest' => 'sales_email_creditmemo_guest_template', 'config' => 'sales_email/creditmemo/template'],
'creditmemo_update' => ['label' => 'Refund update', 'template' => 'sales_email_creditmemo_comment_template', 'guest' => 'sales_email_creditmemo_comment_guest_template', 'config' => 'sales_email/creditmemo_comment/template'],
];
}
+4
View File
@@ -0,0 +1,4 @@
<?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_EmailPreview::preview" title="Preview and test email templates" sortOrder="90"/></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:module:Magento_Backend:etc/menu.xsd">
<menu>
<add id="Esun_EmailPreview::preview" title="Email Preview" translate="title" module="Esun_EmailPreview" sortOrder="20" parent="Magento_Backend::marketing_communications" action="esun_email_preview/preview/index" resource="Esun_EmailPreview::preview"/>
</menu>
</config>
@@ -0,0 +1,4 @@
<?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_email_preview" frontName="esun_email_preview"><module name="Esun_EmailPreview" before="Magento_Backend"/></route></router>
</config>
@@ -0,0 +1,6 @@
<?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_EmailPreview">
<sequence><module name="Magento_Backend"/><module name="Magento_Email"/><module name="Magento_Sales"/><module name="Magento_Customer"/><module name="Esun_ImageManager"/></sequence>
</module>
</config>
@@ -0,0 +1,4 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_EmailPreview', __DIR__);
@@ -0,0 +1,4 @@
<?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">
<update handle="styles"/><body><referenceContainer name="content"><block class="Esun\EmailPreview\Block\Adminhtml\Preview" name="esun.email.preview" template="Esun_EmailPreview::preview.phtml"/></referenceContainer></body>
</page>
@@ -0,0 +1,14 @@
<?php /** @var \Esun\EmailPreview\Block\Adminhtml\Preview $block */ ?>
<div class="admin__fieldset-wrapper-content">
<form id="esun-email-preview" method="post" target="email-preview-frame" action="<?= $block->escapeUrl($block->getPreviewUrl()) ?>">
<?= $block->getBlockHtml('formkey') ?>
<fieldset class="admin__fieldset">
<div class="admin__field"><label class="admin__field-label" for="type"><span><?= $block->escapeHtml(__('Email type')) ?></span></label><div class="admin__field-control"><select class="admin__control-select" id="type" name="type"><?php foreach($block->getTypes() as $key=>$type): ?><option value="<?= $block->escapeHtmlAttr($key) ?>"><?= $block->escapeHtml($type['label']) ?></option><?php endforeach ?></select></div></div>
<div class="admin__field"><label class="admin__field-label" for="store_id"><span><?= $block->escapeHtml(__('Store View')) ?></span></label><div class="admin__field-control"><select class="admin__control-select" id="store_id" name="store_id"><?php foreach($block->getStoreOptions() as $group): ?><?php if (isset($group['value']) && is_array($group['value'])): ?><optgroup label="<?= $block->escapeHtmlAttr($group['label']) ?>"><?php foreach($group['value'] as $store): ?><option value="<?= (int)$store['value'] ?>"><?= $block->escapeHtml($store['label']) ?></option><?php endforeach ?></optgroup><?php endif ?><?php endforeach ?></select></div></div>
<div class="admin__field"><label class="admin__field-label" for="increment_id"><span><?= $block->escapeHtml(__('Order number')) ?></span></label><div class="admin__field-control"><input class="admin__control-text" id="increment_id" name="increment_id" placeholder="Required for order, shipment and refund"/></div></div>
<div class="admin__field"><label class="admin__field-label" for="entity_id"><span><?= $block->escapeHtml(__('Invoice / shipment / credit memo number')) ?></span></label><div class="admin__field-control"><input class="admin__control-text" id="entity_id" name="entity_id" placeholder="Optional; latest matching record is used"/></div></div>
<div class="admin__field"><label class="admin__field-label" for="recipient"><span><?= $block->escapeHtml(__('Test recipient')) ?></span></label><div class="admin__field-control"><input type="email" class="admin__control-text" id="recipient" name="recipient"/></div></div>
<div class="admin__field"><div class="admin__field-control"><button class="action-primary" type="submit"><span><?= $block->escapeHtml(__('Preview theme template')) ?></span></button> <button class="action-secondary" type="submit" formaction="<?= $block->escapeUrl($block->getSendUrl()) ?>" formtarget="_self"><span><?= $block->escapeHtml(__('Send test email')) ?></span></button></div></div>
</fieldset></form>
</div>
<iframe name="email-preview-frame" title="<?= $block->escapeHtmlAttr(__('Email preview')) ?>" style="width:100%;min-height:780px;border:1px solid #ccc;background:#fff"></iframe>