init
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Sales\Model\Order\Email\Attachment;
|
||||
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\Exception\FileSystemException;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\Framework\UrlInterface;
|
||||
use \PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\Reader\Exception;
|
||||
use Magento\Framework\App\ObjectManager;
|
||||
use Magento\Framework\Filesystem;
|
||||
use Magento\Sales\Model\ResourceModel\Order\Item;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Stemcell\Customer\Api\Data\SalespersonInterface;
|
||||
use Stemcell\Sales\Model\Order\Email\Sender\OrderSender;
|
||||
|
||||
class Order
|
||||
{
|
||||
private Item\Collection $itemCollection;
|
||||
private Filesystem\DirectoryList $directoryList;
|
||||
private Filesystem\Directory\WriteInterface $directory;
|
||||
private \Magento\Store\Model\StoreManagerInterface $storeManager;
|
||||
|
||||
protected SalespersonInterface $salesperson;
|
||||
|
||||
protected OrderSender $orderSender;
|
||||
|
||||
protected \Magento\Sales\Model\Order $order;
|
||||
|
||||
/**
|
||||
* @var \Magento\Sales\Model\Order\Item[]
|
||||
*/
|
||||
protected array $orderItems;
|
||||
/**
|
||||
* @throws FileSystemException
|
||||
*/
|
||||
public function __construct(
|
||||
Filesystem $filesystem,
|
||||
Item\Collection $itemCollection,
|
||||
Filesystem\DirectoryList $directoryList,
|
||||
\Magento\Store\Model\StoreManagerInterface $storeManager,
|
||||
protected LoggerInterface $logger,
|
||||
protected TimezoneInterface $timezone
|
||||
) {
|
||||
$this->itemCollection = $itemCollection;
|
||||
$this->directoryList = $directoryList;
|
||||
$this->storeManager = $storeManager;
|
||||
$this->directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function getHeaders() {
|
||||
return [
|
||||
'订单编号',
|
||||
'订单金额',
|
||||
'经销商',
|
||||
'销售',
|
||||
'下单时间',
|
||||
'订单状态',
|
||||
'货号',
|
||||
'商品名称',
|
||||
'经销商价格(¥)',
|
||||
'数量',
|
||||
'CD号',
|
||||
'Quote号',
|
||||
'折扣',
|
||||
'总金额(¥)',
|
||||
'订货账户',
|
||||
'账户名称',
|
||||
'PI SAP ID',
|
||||
// '最终用户单位',
|
||||
// 'PI',
|
||||
// '最终使用人',
|
||||
// '联系电话',
|
||||
// '邮箱地址',
|
||||
'终端类型',
|
||||
'备注',
|
||||
'订单备注',
|
||||
];
|
||||
}
|
||||
|
||||
protected function getOrderStatusLabel(\Magento\Sales\Model\Order $order)
|
||||
{
|
||||
try {
|
||||
return $order->getStatusLabel();
|
||||
} catch (LocalizedException $e) {
|
||||
$this->logger->critical(
|
||||
sprintf(
|
||||
'获取订单:: %s 的status: %s label失败, 原因:%s',
|
||||
$order->getIncrementId(),
|
||||
$order->getStatus(),
|
||||
$e->getMessage()
|
||||
)
|
||||
);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getCurrentTimezoneTime(string $time)
|
||||
{
|
||||
try {
|
||||
$time = $this->timezone->date(new \DateTime($time))->format('Y-m-d H:i:s');
|
||||
} catch (\Exception $e) {
|
||||
$this->logger->critical('发给销售的邮件附件在做数据转换时异常: ' . $e->getMessage());
|
||||
}
|
||||
return $time;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同一笔订单,可能因为用户在购物车给不同商品选择的账户(lab)不一样,这时对应的销售(salesperson)可能不一样,
|
||||
* 因此同一个订单需要根据销售来拆分,这就导致同一个订单可能发多个邮件给不同的销售。因此这个的order_items并不是订单的全部items。
|
||||
* 此数据来源于\Stemcell\Sales\Observer\SalespersonNotify。
|
||||
* 故此,grand_total的不能用order的grand total
|
||||
* @param \Magento\Sales\Model\Order\Item $orderItem
|
||||
* @param array $fields
|
||||
* @return array
|
||||
*/
|
||||
public function getRowData(\Magento\Sales\Model\Order\Item $orderItem, array $fields): array
|
||||
{
|
||||
$row = [];
|
||||
foreach ($fields as $column) {
|
||||
|
||||
$value = match ($column) {
|
||||
'booking_account' => $orderItem->getData('booking_account'),
|
||||
'user_type' => $orderItem->getData('user_type') == 0 ? '终端' : '二级经销商',
|
||||
'customer_discount_percent' => $this->getCustomerDiscountPercent($orderItem),
|
||||
'grand_total' => $this->getGrandTotal(),
|
||||
'price' => number_format($orderItem->getData('price'), 2),
|
||||
'row_total' => $this->getRowTotal($orderItem),
|
||||
'status' => $this->getOrderStatusLabel($orderItem->getOrder()),
|
||||
'salesperson_name' => $orderItem->getData('salesperson_name'),
|
||||
'created_at' => $this->getCurrentTimezoneTime($orderItem->getData('created_at')),
|
||||
'name' => $this->getProductName($orderItem),
|
||||
default => $orderItem->getData($column),
|
||||
};
|
||||
|
||||
if ($value!=null && trim($value)=='-') $value = null;
|
||||
$row[] = $value;
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
protected function getProductName(\Magento\Sales\Model\Order\Item $orderItem): string
|
||||
{
|
||||
return $orderItem->getProductOptionByCode('simple_name')?? $orderItem->getName();
|
||||
}
|
||||
protected function getCustomerDiscountPercent(\Magento\Sales\Model\Order\Item $orderItem): string
|
||||
{
|
||||
$discountPercent = $orderItem->getData('customer_discount_percent');
|
||||
return $discountPercent == 0 ? '' : number_format($discountPercent, 2).'%';
|
||||
}
|
||||
|
||||
protected function getRowTotal(\Magento\Sales\Model\Order\Item $orderItem): string
|
||||
{
|
||||
return number_format($orderItem->getRowTotal(), 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
protected function getOrderItemsId(): array
|
||||
{
|
||||
return array_map(function (\Magento\Sales\Model\Order\Item $item){
|
||||
return $item->getItemId();
|
||||
}, $this->order->getAllVisibleItems());
|
||||
}
|
||||
|
||||
protected function getGrandTotal(): string
|
||||
{
|
||||
return '¥'.number_format($this->order->getGrandTotal(), 2);
|
||||
}
|
||||
/**
|
||||
* @return Item\Collection
|
||||
*/
|
||||
protected function getCollection(array $ordersId) {
|
||||
$this->itemCollection->addFieldToSelect([
|
||||
'sku', 'name', 'price', 'qty_ordered', 'cd', 'quote', 'customer_discount_percent', 'row_total', 'lab_code',
|
||||
// 'company', 'user',
|
||||
'pi_sap_id',
|
||||
// 'user_tel', 'user_email',
|
||||
'note', 'user_type', 'order_id', 'product_options'
|
||||
])
|
||||
->addFieldToFilter('main_table.item_id', ['in'=>$this->getOrderItemsId()])
|
||||
->addFieldToFilter('main_table.parent_item_id', ['null' => true])
|
||||
->getSelect()
|
||||
->join(
|
||||
'sales_order',
|
||||
'main_table.order_id=sales_order.entity_id',
|
||||
[
|
||||
'increment_id', 'grand_total', 'customer_firstname', 'created_at', 'status', 'sales_order.salesperson_id',
|
||||
'customer_note'
|
||||
]
|
||||
)
|
||||
->joinLeft(
|
||||
'salesperson',
|
||||
'salesperson.salesperson_id=sales_order.salesperson_id',
|
||||
[
|
||||
'salesperson_name' => 'salesperson.name'
|
||||
|
||||
]
|
||||
)->joinLeft(
|
||||
'lab',
|
||||
'lab.lab_id=main_table.lab_id',
|
||||
[
|
||||
'lab_code' => 'lab.lab_code',
|
||||
'booking_account' => 'lab.booking_account',
|
||||
'pi_sap_id' => 'lab.pi_sap_id',
|
||||
]
|
||||
);
|
||||
$this->logger->debug('create order attachment sql: '.$this->itemCollection->getSelectSql(true));
|
||||
return $this->itemCollection;
|
||||
}
|
||||
|
||||
protected function getFields() {
|
||||
return [
|
||||
'increment_id', 'grand_total', 'customer_firstname', 'salesperson_name', 'created_at', 'status', 'sku',
|
||||
'name', 'price', 'qty_ordered', 'cd', 'quote', 'customer_discount_percent',
|
||||
'row_total', 'lab_code', 'booking_account', 'pi_sap_id',
|
||||
// 'company', 'pi', 'user', 'user_tel', 'user_email',
|
||||
'user_type', 'note', 'customer_note'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Magento\Sales\Model\Order $order
|
||||
* @return string
|
||||
*/
|
||||
protected function getShippingAddress(\Magento\Sales\Model\Order $order)
|
||||
{
|
||||
$address = $order->getShippingAddress();
|
||||
return '收货地址: '.$address->getRegion() . ' ' . $address->getCity() . ' '
|
||||
. implode(' ', $address->getStreet());
|
||||
}
|
||||
/**
|
||||
* @param \Magento\Sales\Model\Order $order
|
||||
* @param OrderSender $orderSender
|
||||
* @return string
|
||||
* @throws FileSystemException
|
||||
* @throws \PhpOffice\PhpSpreadsheet\Exception
|
||||
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
|
||||
*/
|
||||
public function getFile(\Magento\Sales\Model\Order $order, OrderSender $orderSender)
|
||||
{
|
||||
$this->order = $order;
|
||||
$this->orderSender = $orderSender;
|
||||
$name = md5(microtime());
|
||||
$file = 'attachment/'. $name . '.xlsx';
|
||||
|
||||
$fields = $this->getFields();
|
||||
|
||||
$this->directory->create('attachment');
|
||||
$filePath = $this->directoryList->getPath(UrlInterface::URL_TYPE_MEDIA).'/'.$file;
|
||||
|
||||
$ordersId = [$order->getId()];
|
||||
|
||||
$collection = $this->getCollection($ordersId);
|
||||
|
||||
$dataGroupByOrderId = [];
|
||||
foreach ($collection as $item) {
|
||||
/* @var $item \Magento\Sales\Model\Order\Item */
|
||||
$dataGroupByOrderId[$item->getData('salesperson_id')][] = $this->getRowData($item, $fields);
|
||||
}
|
||||
$styles = [
|
||||
'alignment' => [
|
||||
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
|
||||
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
|
||||
],
|
||||
];
|
||||
$rowIndex = 2;
|
||||
$spreadSheet = new Spreadsheet();
|
||||
$writer = IOFactory::createWriter($spreadSheet, IOFactory::WRITER_XLSX);
|
||||
$worksheet = $spreadSheet->getActiveSheet();
|
||||
$columnIndex = 'A';
|
||||
foreach ($this->getHeaders() as $row) {
|
||||
$cell = $worksheet->getCell($columnIndex.'1');
|
||||
$cell->getAppliedStyle()->applyFromArray($styles);
|
||||
$cell->setValue($row);
|
||||
$columnIndex++;
|
||||
}
|
||||
$worksheet->getRowDimension(1)->setRowHeight(20);
|
||||
foreach ($dataGroupByOrderId as $rows) {
|
||||
$rowCount = count($rows);
|
||||
$mergeColumnsIndex = ['A', 'B', 'C', 'D', 'E', 'F', 'T'];
|
||||
foreach ($mergeColumnsIndex as $index) {
|
||||
$worksheet->mergeCells($index.$rowIndex.':'.$index.$rowIndex+$rowCount-1);
|
||||
}
|
||||
foreach ($rows as $row) {
|
||||
$columnIndex = 'A';
|
||||
foreach ($row as $value) {
|
||||
$worksheet->getColumnDimension($columnIndex)->setWidth(15);
|
||||
$worksheet->getRowDimension($rowIndex)->setRowHeight(20);
|
||||
$cell = $worksheet->getCell($columnIndex.$rowIndex);
|
||||
$cell->getAppliedStyle()->applyFromArray($styles);
|
||||
$cell->setValue($value);
|
||||
$columnIndex++;
|
||||
}
|
||||
$rowIndex++;
|
||||
}
|
||||
}
|
||||
$worksheet->mergeCells("A{$rowIndex}:$columnIndex{$rowIndex}");
|
||||
$worksheet->setCellValue("A{$rowIndex}", $this->getShippingAddress($order));
|
||||
$writer->save($filePath);
|
||||
$content = $this->directory->readFile($filePath);
|
||||
$this->directory->delete($filePath);
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Sales\Model\Order\Email\Container;
|
||||
|
||||
class OrderIdentity extends \Magento\Sales\Model\Order\Email\Container\OrderIdentity
|
||||
{
|
||||
protected array $cc = [];
|
||||
|
||||
public function getEmailCopyTo()
|
||||
{
|
||||
return empty($this->cc)? false:$this->cc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $emailCopyTo
|
||||
* @return $this
|
||||
*/
|
||||
public function setEmailCopyTo(array $emailCopyTo): static
|
||||
{
|
||||
$this->cc = $emailCopyTo;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getTemplateId(): string
|
||||
{
|
||||
return 'sales_email_order_new_salesperson_template';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stemcell\Sales\Model\Order\Email\Sender;
|
||||
|
||||
use Magento\Framework\Exception\FileSystemException;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Payment\Helper\Data as PaymentHelper;
|
||||
use Magento\Sales\Model\Order;
|
||||
use Magento\Sales\Model\Order\Email\Container\Template;
|
||||
use Magento\Sales\Model\Order\Email\Sender;
|
||||
use PhpOffice\PhpSpreadsheet\Exception;
|
||||
use Stemcell\Customer\Api\Data\SalespersonInterface;
|
||||
use Stemcell\Sales\Model\Order\Email\SenderBuilder;
|
||||
use Stemcell\Sales\Model\Order\Email\SenderBuilderFactory;
|
||||
use Magento\Sales\Model\ResourceModel\Order as OrderResource;
|
||||
use Magento\Sales\Model\Order\Address\Renderer;
|
||||
use Magento\Framework\Event\ManagerInterface;
|
||||
use Magento\Framework\DataObject;
|
||||
use Stemcell\Customer\Api\SalespersonRepositoryInterface;
|
||||
use Stemcell\Sales\Model\Order\Email\Container\OrderIdentity;
|
||||
|
||||
/**
|
||||
* Sends order email to the customer.
|
||||
*
|
||||
* @api
|
||||
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
|
||||
*/
|
||||
class OrderSender extends Sender
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Renderer
|
||||
*/
|
||||
protected $addressRenderer;
|
||||
|
||||
/**
|
||||
* Application Event Dispatcher
|
||||
*
|
||||
* @var ManagerInterface
|
||||
*/
|
||||
protected ManagerInterface $eventManager;
|
||||
private SalespersonRepositoryInterface $salespersonRepository;
|
||||
private \Stemcell\Sales\Model\Order\Email\Attachment\Order $orderAttachment;
|
||||
private string $file;
|
||||
|
||||
/**
|
||||
* @var \Magento\Sales\Model\Order\Item[]
|
||||
*/
|
||||
protected array $orderItems = [];
|
||||
|
||||
protected SalespersonInterface $salesperson;
|
||||
|
||||
protected \Magento\Sales\Model\Order $order;
|
||||
|
||||
/**
|
||||
* @param Template $templateContainer
|
||||
* @param OrderIdentity $identityContainer
|
||||
* @param SenderBuilderFactory $senderBuilderFactory
|
||||
* @param \Psr\Log\LoggerInterface $logger
|
||||
* @param Renderer $addressRenderer
|
||||
* @param PaymentHelper $paymentHelper
|
||||
* @param OrderResource $orderResource
|
||||
* @param \Magento\Framework\App\Config\ScopeConfigInterface $globalConfig
|
||||
* @param ManagerInterface $eventManager
|
||||
*/
|
||||
public function __construct(
|
||||
Template $templateContainer,
|
||||
OrderIdentity $identityContainer,
|
||||
SenderBuilderFactory $senderBuilderFactory,
|
||||
\Psr\Log\LoggerInterface $logger,
|
||||
Renderer $addressRenderer,
|
||||
SalespersonRepositoryInterface $salespersonRepository,
|
||||
\Stemcell\Sales\Model\Order\Email\Attachment\Order $orderAttachment
|
||||
) {
|
||||
parent::__construct($templateContainer, $identityContainer, $senderBuilderFactory, $logger, $addressRenderer);
|
||||
$this->salespersonRepository = $salespersonRepository;
|
||||
$this->orderAttachment = $orderAttachment;
|
||||
}
|
||||
|
||||
/**
|
||||
* inject $salesperson
|
||||
* @param SalespersonInterface $salesperson
|
||||
* @return $this
|
||||
*/
|
||||
public function setSalesperson(SalespersonInterface $salesperson): static
|
||||
{
|
||||
$this->salesperson = $salesperson;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getSalesperson(): SalespersonInterface
|
||||
{
|
||||
return $this->salesperson;
|
||||
}
|
||||
/**
|
||||
* inject $salesperson
|
||||
* @param SalespersonInterface $salesperson
|
||||
* @return $this
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function setOrderItems(array $orderItems): static
|
||||
{
|
||||
foreach ($orderItems as $item) {
|
||||
if (!$item instanceof \Magento\Sales\Model\Order\Item) {
|
||||
throw new LocalizedException(__('One of item in parameter orderItems array are not instance of \Magento\Sales\Model\Order\Item class'));
|
||||
}
|
||||
}
|
||||
$this->orderItems = $orderItems;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Order\Item[]
|
||||
*/
|
||||
public function getOrderItems(): array
|
||||
{
|
||||
return $this->orderItems;
|
||||
}
|
||||
/**
|
||||
* @param Order $order
|
||||
* @return bool
|
||||
*/
|
||||
protected function checkAndSend(Order $order): bool
|
||||
{
|
||||
$this->identityContainer->setStore($order->getStore());
|
||||
|
||||
// if (!$this->identityContainer->isEnabled()) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
$this->prepareTemplate($order);
|
||||
|
||||
/** @var SenderBuilder $sender */
|
||||
$sender = $this->getSender();
|
||||
try {
|
||||
$sender->setAttachmentFile($this->orderAttachment->getFile($order, $this));
|
||||
$sender->send();
|
||||
} catch (\Exception $e) {
|
||||
$this->logger->error($e->getMessage(), $e->getTrace());
|
||||
return false;
|
||||
}
|
||||
// if ($this->identityContainer->getCopyMethod() == 'copy') {
|
||||
// try {
|
||||
// $sender->sendCopyTo();
|
||||
// } catch (\Exception $e) {
|
||||
// $this->logger->error($e->getMessage(), $e->getTrace());
|
||||
// }
|
||||
// }
|
||||
return true;
|
||||
}
|
||||
|
||||
public function send(Order $order)
|
||||
{
|
||||
$this->order = $order;
|
||||
return $this->checkAndSend($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare email template with variables
|
||||
*
|
||||
* @param Order $order
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareTemplate(Order $order)
|
||||
{
|
||||
try {
|
||||
$transport = [
|
||||
'order' => $order,
|
||||
'orderItems' => $this->orderItems,
|
||||
'salesperson' => $this->salesperson,
|
||||
'order_id' => $order->getId(),
|
||||
'file' => $this->file = $this->orderAttachment->getFile($order, $this),
|
||||
'order_data' => [
|
||||
'customer_name' => $order->getCustomerName(),
|
||||
'is_not_virtual' => $order->getIsNotVirtual(),
|
||||
'order_id' => $order->getId(),
|
||||
'order_item' => $order->getAllVisibleItems(),
|
||||
'frontend_status_label' => $order->getFrontendStatusLabel()
|
||||
]
|
||||
];
|
||||
|
||||
$this->identityContainer->setEmailCopyTo($this->getEmailCopyTo($order));
|
||||
$this->templateContainer->setTemplateVars($transport);
|
||||
|
||||
parent::prepareTemplate($order);
|
||||
} catch (FileSystemException | \PhpOffice\PhpSpreadsheet\Writer\Exception | Exception $e) {
|
||||
$this->logger->critical($e->getMessage(), $e->getTrace());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected function getEmailCopyTo(Order $order): array
|
||||
{
|
||||
$cc = [$order->getCustomerEmail()];
|
||||
|
||||
$fields = ['email', 'rsm_email', 'sisr_email', 'csr_email'];
|
||||
foreach ($fields as $field) {
|
||||
if ($email = $this->salesperson->getData($field)) {
|
||||
$email = strval($email);
|
||||
$email = trim($email, ',');
|
||||
$temp = array_map('trim', explode(',', $email));
|
||||
$cc = array_merge($cc, $temp);
|
||||
}
|
||||
}
|
||||
return $cc;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Sales\Model\Order\Email;
|
||||
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Exception\MailException;
|
||||
use Stemcell\Sales\Model\Order\Template\TransportBuilder;
|
||||
use Magento\Framework\Mail\Template\TransportBuilderByStore;
|
||||
use Magento\Sales\Model\Order\Email\Container\IdentityInterface;
|
||||
use Magento\Sales\Model\Order\Email\Container\Template;
|
||||
|
||||
class SenderBuilder extends \Magento\Sales\Model\Order\Email\SenderBuilder
|
||||
{
|
||||
protected string $filePath;
|
||||
|
||||
public function __construct(Template $templateContainer, IdentityInterface $identityContainer, TransportBuilder $transportBuilder, TransportBuilderByStore $transportBuilderByStore = null)
|
||||
{
|
||||
parent::__construct($templateContainer, $identityContainer, $transportBuilder, $transportBuilderByStore);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws MailException
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function send()
|
||||
{
|
||||
$this->configureEmailTemplate();
|
||||
$copyTo = $this->identityContainer->getEmailCopyTo();
|
||||
$this->transportBuilder->addTo(
|
||||
$this->identityContainer->getCustomerEmail(),
|
||||
$this->identityContainer->getCustomerName()
|
||||
);
|
||||
|
||||
if (!empty($copyTo)) {
|
||||
$this->transportBuilder->addTo($copyTo);
|
||||
$this->transportBuilder->setMessageData('to', $copyTo);
|
||||
}
|
||||
if (isset($this->filePath)) {
|
||||
$attachmentMime = [
|
||||
'type' => 'application/vnd.ms-excel',
|
||||
'content' => $this->filePath,
|
||||
'disposition' => \Laminas\Mime\Mime::DISPOSITION_ATTACHMENT,
|
||||
'encoding' => \Laminas\Mime\Mime::ENCODING_BASE64,
|
||||
'fileName' => 'order.xlsx'
|
||||
];
|
||||
$this->transportBuilder->setAttachmentMimePart($attachmentMime);
|
||||
}
|
||||
|
||||
$transport = $this->transportBuilder->getTransport();
|
||||
$transport->sendMessage();
|
||||
}
|
||||
|
||||
public function setAttachmentFile(string $filePath): static
|
||||
{
|
||||
$this->filePath = $filePath;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Sales\Model\Order\Email;
|
||||
|
||||
class SenderBuilderFactory extends \Magento\Sales\Model\Order\Email\SenderBuilderFactory
|
||||
{
|
||||
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Stemcell\\Sales\Model\\Order\\Email\\SenderBuilder')
|
||||
{
|
||||
parent::__construct($objectManager, $instanceName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Sales\Model\Order;
|
||||
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Sales\Model\Order\Item;
|
||||
|
||||
class ShipmentFactory extends \Magento\Sales\Model\Order\ShipmentFactory
|
||||
{
|
||||
/**
|
||||
* Serializer data
|
||||
*
|
||||
* @var Json
|
||||
*/
|
||||
private Json $serializer;
|
||||
|
||||
/**
|
||||
* Validate order item before shipment
|
||||
*
|
||||
* @param Item $orderItem
|
||||
* @param array $items
|
||||
* @return bool
|
||||
*/
|
||||
private function validateItem(\Magento\Sales\Model\Order\Item $orderItem, array $items)
|
||||
{
|
||||
if (!$this->canShipItem($orderItem, $items)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove from shipment items without qty or with qty=0
|
||||
if (!$orderItem->isDummy(true)
|
||||
&& (!isset($items[$orderItem->getId()]) || (float) $items[$orderItem->getId()] <= 0)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set prepared items to shipment document
|
||||
*
|
||||
* @param \Magento\Sales\Api\Data\ShipmentInterface $shipment
|
||||
* @param array $shipmentItems
|
||||
* @return \Magento\Sales\Api\Data\ShipmentInterface
|
||||
*/
|
||||
private function setItemsToShipment(\Magento\Sales\Api\Data\ShipmentInterface $shipment, $shipmentItems)
|
||||
{
|
||||
$totalQty = 0;
|
||||
|
||||
/**
|
||||
* Verify that composite products shipped separately has children, if not -> remove from collection
|
||||
*/
|
||||
/** @var \Magento\Sales\Model\Order\Shipment\Item $shipmentItem */
|
||||
foreach ($shipmentItems as $key => $shipmentItem) {
|
||||
if ($shipmentItem->getOrderItem()->getHasChildren()
|
||||
&& $shipmentItem->getOrderItem()->isShipSeparately()
|
||||
) {
|
||||
$containerId = $shipmentItem->getOrderItem()->getId();
|
||||
$childItems = array_filter($shipmentItems, function ($item) use ($containerId) {
|
||||
return $containerId == $item->getOrderItem()->getParentItemId();
|
||||
});
|
||||
|
||||
if (count($childItems) <= 0) {
|
||||
unset($shipmentItems[$key]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
$totalQty += $shipmentItem->getQty();
|
||||
$shipment->addItem($shipmentItem);
|
||||
}
|
||||
return $shipment->setTotalQty($totalQty);
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts Qty to float or integer type
|
||||
*
|
||||
* @param Item $item
|
||||
* @param string|int|float $qty
|
||||
* @return float|int
|
||||
*/
|
||||
private function castQty(\Magento\Sales\Model\Order\Item $item, $qty)
|
||||
{
|
||||
if ($item->getIsQtyDecimal()) {
|
||||
$qty = (double)$qty;
|
||||
} else {
|
||||
$qty = (int)$qty;
|
||||
}
|
||||
|
||||
return $qty > 0 ? $qty : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds tracks to the shipment.
|
||||
*
|
||||
* @param \Magento\Sales\Api\Data\ShipmentInterface $shipment
|
||||
* @param array $tracks
|
||||
* @throws \Magento\Framework\Exception\LocalizedException
|
||||
* @return \Magento\Sales\Api\Data\ShipmentInterface
|
||||
*/
|
||||
protected function prepareTracks(\Magento\Sales\Api\Data\ShipmentInterface $shipment, array $tracks)
|
||||
{
|
||||
foreach ($tracks as $data) {
|
||||
if (empty($data['number'])) {
|
||||
throw new \Magento\Framework\Exception\LocalizedException(
|
||||
__('Please enter a tracking number.')
|
||||
);
|
||||
}
|
||||
|
||||
$shipment->addTrack(
|
||||
$this->trackFactory->create()->addData($data)
|
||||
);
|
||||
}
|
||||
|
||||
return $shipment;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Stemcell\Sales\Model\Order\Template;
|
||||
|
||||
use Magento\Framework\App\TemplateTypesInterface;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Mail\AddressConverter;
|
||||
use Magento\Framework\Mail\EmailMessageInterfaceFactory;
|
||||
use Magento\Framework\Mail\MessageInterface;
|
||||
use Magento\Framework\Mail\MessageInterfaceFactory;
|
||||
use Magento\Framework\Mail\MimeInterface;
|
||||
use Magento\Framework\Mail\MimeMessageInterfaceFactory;
|
||||
use Magento\Framework\Mail\MimePartInterfaceFactory;
|
||||
use Magento\Framework\Mail\Template\FactoryInterface;
|
||||
use Magento\Framework\Mail\Template\SenderResolverInterface;
|
||||
use Magento\Framework\Mail\TransportInterfaceFactory;
|
||||
use Magento\Framework\ObjectManagerInterface;
|
||||
use Magento\Framework\Phrase;
|
||||
|
||||
class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
|
||||
{
|
||||
/**
|
||||
* Param that used for storing all message data until it will be used
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected array $messageData = [];
|
||||
|
||||
/**
|
||||
* @var EmailMessageInterfaceFactory
|
||||
*/
|
||||
protected EmailMessageInterfaceFactory $emailMessageInterfaceFactory;
|
||||
|
||||
/**
|
||||
* @var MimeMessageInterfaceFactory
|
||||
*/
|
||||
protected MimeMessageInterfaceFactory $mimeMessageInterfaceFactory;
|
||||
|
||||
protected ?\Magento\Framework\Mail\MimePartInterface $attachmentMimePart = null;
|
||||
|
||||
/**
|
||||
* @var MimePartInterfaceFactory
|
||||
*/
|
||||
protected MimePartInterfaceFactory $mimePartInterfaceFactory;
|
||||
|
||||
public function __construct(FactoryInterface $templateFactory, MessageInterface $message, SenderResolverInterface $senderResolver, ObjectManagerInterface $objectManager, TransportInterfaceFactory $mailTransportFactory, MessageInterfaceFactory $messageFactory = null, EmailMessageInterfaceFactory $emailMessageInterfaceFactory = null, MimeMessageInterfaceFactory $mimeMessageInterfaceFactory = null, MimePartInterfaceFactory $mimePartInterfaceFactory = null, AddressConverter $addressConverter = null)
|
||||
{
|
||||
parent::__construct($templateFactory, $message, $senderResolver, $objectManager, $mailTransportFactory, $messageFactory, $emailMessageInterfaceFactory, $mimeMessageInterfaceFactory, $mimePartInterfaceFactory, $addressConverter);
|
||||
$this->emailMessageInterfaceFactory = $emailMessageInterfaceFactory ?: $this->objectManager
|
||||
->get(EmailMessageInterfaceFactory::class);
|
||||
$this->mimeMessageInterfaceFactory = $mimeMessageInterfaceFactory ?: $this->objectManager
|
||||
->get(MimeMessageInterfaceFactory::class);
|
||||
$this->mimePartInterfaceFactory = $mimePartInterfaceFactory ?: $this->objectManager
|
||||
->get(MimePartInterfaceFactory::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $messageData
|
||||
*/
|
||||
public function setMessageData(string $key, array $emails): static
|
||||
{
|
||||
$data = [];
|
||||
foreach ($emails as $email) {
|
||||
if (is_string($email)) {
|
||||
$data[] = new \Magento\Framework\Mail\Address($email, $email);
|
||||
}
|
||||
}
|
||||
if (!empty($data))
|
||||
$this->messageData[$key] = $data;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare message.
|
||||
*
|
||||
* @return $this
|
||||
* @throws LocalizedException if template type is unknown
|
||||
*/
|
||||
protected function prepareMessage()
|
||||
{
|
||||
$template = $this->getTemplate();
|
||||
$content = $template->processTemplate();
|
||||
|
||||
switch ($template->getType()) {
|
||||
case TemplateTypesInterface::TYPE_TEXT:
|
||||
$partType = MimeInterface::TYPE_TEXT;
|
||||
break;
|
||||
|
||||
case TemplateTypesInterface::TYPE_HTML:
|
||||
$partType = MimeInterface::TYPE_HTML;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new LocalizedException(
|
||||
new Phrase('Unknown template type')
|
||||
);
|
||||
}
|
||||
|
||||
/** @var \Magento\Framework\Mail\MimePartInterface $mimePart */
|
||||
$mimePart = $this->mimePartInterfaceFactory->create(
|
||||
[
|
||||
'content' => $content,
|
||||
'type' => $partType
|
||||
]
|
||||
);
|
||||
|
||||
$this->messageData['sender'] = $mimePart->getCharset();
|
||||
$this->messageData['encoding'] = $mimePart->getCharset();
|
||||
$parts = [$mimePart];
|
||||
if ($this->attachmentMimePart!=null) {
|
||||
$parts[] = $this->attachmentMimePart;
|
||||
}
|
||||
$this->messageData['body'] = $this->mimeMessageInterfaceFactory->create(
|
||||
['parts' => $parts]
|
||||
);
|
||||
|
||||
$this->messageData['subject'] = html_entity_decode(
|
||||
(string)$template->getSubject(),
|
||||
ENT_QUOTES
|
||||
);
|
||||
$this->messageData['sender'] = new \Magento\Framework\Mail\Address('no-reply@stemcellmart.com.cn', 'STEMCELL在线商城');
|
||||
$this->messageData['form'] = $this->messageData['sender'];
|
||||
|
||||
|
||||
$this->message = $this->emailMessageInterfaceFactory->create($this->messageData);
|
||||
$this->message->setFromAddress('no-reply@stemcellmart.com.cn', 'STEMCELL经销商下单系统');
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function setAttachmentMimePart(array $attachment): static
|
||||
{
|
||||
$this->attachmentMimePart = $this->mimePartInterfaceFactory->create($attachment);
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user