Skip to content

Commit

Permalink
Merge pull request #345 from mageplaza/2.3-develop
Browse files Browse the repository at this point in the history
2.3 develop
  • Loading branch information
Victor-Mageplaza authored Nov 3, 2021
2 parents c3c0f4f + a117812 commit fd69420
Show file tree
Hide file tree
Showing 8 changed files with 184 additions and 136 deletions.
96 changes: 76 additions & 20 deletions Helper/EmailMarketing.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Exception;
use IntlDateFormatter;
use Magento\Bundle\Helper\Catalog\Product\Configuration as BundleConfiguration;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Helper\Data as CatalogHelper;
use Magento\Catalog\Helper\Product\Configuration as CatalogConfiguration;
use Magento\Catalog\Model\Product;
Expand Down Expand Up @@ -54,6 +55,7 @@
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\Quote\Address;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\Quote\ItemFactory;
use Magento\Sales\Model\Order\Item as OrderItem;
use Magento\Quote\Model\ResourceModel\Quote as ResourceQuote;
use Magento\Reports\Model\ResourceModel\Order\CollectionFactory as ReportOrderCollectionFactory;
Expand Down Expand Up @@ -260,6 +262,16 @@ class EmailMarketing extends Data
*/
protected $abandonedCartCollection;

/**
* @var ItemFactory
*/
protected $quoteItemFactory;

/**
* @var bool
*/
protected $isPUT = false;

/**
* EmailMarketing constructor.
*
Expand Down Expand Up @@ -292,6 +304,7 @@ class EmailMarketing extends Data
* @param ResourceConnection $resourceConnection
* @param Region $region
* @param Collection $abandonedCartCollection
* @param ItemFactory $quoteItemFactory
*/
public function __construct(
Context $context,
Expand Down Expand Up @@ -322,7 +335,8 @@ public function __construct(
CountryFactory $countryFactory,
ResourceConnection $resourceConnection,
Region $region,
Collection $abandonedCartCollection
Collection $abandonedCartCollection,
ItemFactory $quoteItemFactory
) {
$this->frontendUrl = $frontendUrl;
$this->escaper = $escaper;
Expand Down Expand Up @@ -350,6 +364,7 @@ public function __construct(
$this->resourceConnection = $resourceConnection;
$this->region = $region;
$this->abandonedCartCollection = $abandonedCartCollection;
$this->quoteItemFactory = $quoteItemFactory;

parent::__construct($context, $objectManager, $storeManager);
}
Expand All @@ -359,8 +374,11 @@ public function __construct(
*/
public function initCurl()
{
if (!$this->_curl) {
$this->_curl = $this->curlFactory->create();
$this->_curl = $this->curlFactory->create();

if ($this->isPUT) {
$this->_curl->setOption(CURLOPT_CUSTOMREQUEST, 'PUT');
$this->isPUT = false;
}

return $this->_curl;
Expand Down Expand Up @@ -718,8 +736,7 @@ public function sendOrderRequest($object, $url = '')
*/
public function updateOrderStatusRequest($data)
{
$this->initCurl();
$this->_curl->setOption(CURLOPT_CUSTOMREQUEST, 'PUT');
$this->setIsUpdateRequest(true);

return $this->sendRequest($data, self::ORDER_URL);
}
Expand Down Expand Up @@ -876,6 +893,17 @@ public function getShipmentOrCreditmemoItems($object)
foreach ($object->getItems() as $item) {
$orderItem = $item->getOrderItem();
$product = $this->getProductFromItem($orderItem);
$createdAt = $item->getCreatedAt();
$updatedAt = $item->getUpdatedAt();

if (!$createdAt) {
$createdAt = $object->getCreatedAt();
}

if (!$updatedAt) {
$updatedAt = $object->getUpdatedAt();
}

if ($orderItem->getParentItemId() && isset($items[$orderItem->getParentItemId()]['bundle_items'])) {
$items[$orderItem->getParentItemId()]['bundle_items'][] = [
'title' => $item->getName(),
Expand All @@ -886,8 +914,8 @@ public function getShipmentOrCreditmemoItems($object)
'quantity' => $item->getQty(),
'price' => (float) $item->getBasePrice(),
'is_utc' => true,
'created_at' => $this->formatDate($product->getCreatedAt()),
'updated_at' => $this->formatDate($product->getUpdatedAt()),
'created_at' => $this->formatDate($createdAt),
'updated_at' => $this->formatDate($updatedAt),
'categories' => $product->getCategoryIds()
];

Expand Down Expand Up @@ -916,9 +944,9 @@ public function getShipmentOrCreditmemoItems($object)
'image' => $this->getProductImage($product),
'frontend_link' => $product->getProductUrl(),
'is_utc' => true,
'created_at' => $this->formatDate($item->getProduct()->getCreatedAt()),
'updated_at' => $this->formatDate($item->getProduct()->getUpdatedAt()),
'categories' => $item->getProduct()->getCategoryIds()
'created_at' => $this->formatDate($createdAt),
'updated_at' => $this->formatDate($updatedAt),
'categories' => $product->getCategoryIds()
];

if ($productType === 'bundle') {
Expand Down Expand Up @@ -996,7 +1024,22 @@ public function getItemOptions($orderItem)
*/
public function getProductFromItem($item)
{
return $item->getProduct() ?: new DataObject([]);
return $item->getProduct() ?: ($this->getProductById($item->getProductId()) ?: new DataObject([]));
}

/**
* @param int $productId
*
* @return ProductInterface|mixed|null
*/
public function getProductById($productId)
{
try {
/** @var Product $product */
return $this->productRepository->getById($productId);
} catch (Exception $e) {
return null;
}
}

/**
Expand All @@ -1016,6 +1059,14 @@ public function getCartItems($object)
continue;
}

$createdAt = $item->getCreatedAt();
$updatedAt = $item->getUpdatedAt();
if ($isQuote && (!$createdAt || !$updatedAt)) {
$quoteItem = $this->quoteItemFactory->create()->load($item->getItemId(), 'item_id');
$createdAt = $quoteItem->getCreatedAt();
$updatedAt = $quoteItem->getUpdatedAt();
}

/**
* @var Product $product
*/
Expand Down Expand Up @@ -1056,9 +1107,9 @@ public function getCartItems($object)
'frontend_link' => $product->getProductUrl() ?: '#',
'vendor' => $vendorValue,
'is_utc' => true,
'created_at' => $this->formatDate($item->getProduct()->getCreatedAt()),
'updated_at' => $this->formatDate($item->getProduct()->getUpdatedAt()),
'categories' => $item->getProduct()->getCategoryIds()
'created_at' => $this->formatDate($createdAt),
'updated_at' => $this->formatDate($updatedAt),
'categories' => $product->getCategoryIds()
];

if ($isQuote) {
Expand Down Expand Up @@ -1086,8 +1137,8 @@ public function getCartItems($object)
'quantity' => (int) ($isQuote ? $child->getQty() : $child->getQtyOrdered()),
'price' => (float) $child->getBasePrice(),
'is_utc' => true,
'created_at' => $this->formatDate($product->getCreatedAt()),
'updated_at' => $this->formatDate($product->getUpdatedAt()),
'created_at' => $this->formatDate($createdAt),
'updated_at' => $this->formatDate($updatedAt),
'categories' => $product->getCategoryIds()
];
}
Expand Down Expand Up @@ -1156,6 +1207,14 @@ public function sendRequest($data, $url = '', $appID = '', $secretKey = '', $isT
return $bodyData;
}

/**
* @param bool $flag
*/
public function setIsUpdateRequest($flag)
{
$this->isPUT = $flag;
}

/**
* @param array $data
* @param string $url
Expand Down Expand Up @@ -1523,10 +1582,7 @@ public function getConfigData($path, $scope = ScopeInterface::SCOPE_STORES, $sco
*/
public function syncCustomer($data, $isCreate = true)
{
$this->initCurl();
if (!$isCreate) {
$this->_curl->setOption(CURLOPT_CUSTOMREQUEST, 'PUT');
}
$this->setIsUpdateRequest(!$isCreate);

return $this->sendRequest($data, self::CUSTOMER_URL);
}
Expand Down
47 changes: 43 additions & 4 deletions Observer/Order/InvoiceCommitAfter.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@

namespace Mageplaza\Smtp\Observer\Order;

use Exception;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Model\Order\Invoice;
use Mageplaza\Smtp\Helper\EmailMarketing;
use Magento\Sales\Model\ResourceModel\Order as ResourceOrder;
use Psr\Log\LoggerInterface;

/**
* Class InvoiceCommitAfter
Expand All @@ -39,15 +42,31 @@ class InvoiceCommitAfter implements ObserverInterface
*/
protected $helperEmailMarketing;

/**
* @var LoggerInterface
*/
protected $logger;

/**
* @var ResourceOrder
*/
protected $resourceOrder;

/**
* InvoiceCommitAfter constructor.
*
* @param EmailMarketing $helperEmailMarketing
* @param LoggerInterface $logger
* @param ResourceOrder $resourceOrder
*/
public function __construct(
EmailMarketing $helperEmailMarketing
EmailMarketing $helperEmailMarketing,
LoggerInterface $logger,
ResourceOrder $resourceOrder
) {
$this->helperEmailMarketing = $helperEmailMarketing;
$this->logger = $logger;
$this->resourceOrder = $resourceOrder;
}

/**
Expand All @@ -64,11 +83,31 @@ public function execute(Observer $observer)
) {
/* @var Invoice $order */
$invoice = $observer->getEvent()->getDataObject();
$order = $invoice->getOrder();

try {
if (!$order->getData('mp_smtp_email_marketing_order_created') &&
$order->getCreatedAt() === $order->getUpdatedAt()) {
$this->helperEmailMarketing->sendOrderRequest($order);
$this->helperEmailMarketing->updateCustomer($order->getCustomerId());
$order->setData('mp_smtp_email_marketing_order_created', true);
$resource = $this->resourceOrder;
$resource->getConnection()->update(
$resource->getMainTable(),
['mp_smtp_email_marketing_order_created' => 1],
['entity_id = ?' => $order->getId()]
);
}

if ($invoice->getId() && $invoice->getCreatedAt() == $invoice->getUpdatedAt()) {
$this->helperEmailMarketing->sendOrderRequest($invoice, EmailMarketing::INVOICE_URL);
}

$this->helperEmailMarketing->updateCustomer($order->getCustomerId());

if ($invoice->getId() && $invoice->getCreatedAt() == $invoice->getUpdatedAt()) {
$this->helperEmailMarketing->sendOrderRequest($invoice, EmailMarketing::INVOICE_URL);
} catch (Exception $e) {
$this->logger->critical($e->getMessage());
}
$this->helperEmailMarketing->updateCustomer($invoice->getOrder()->getCustomerId());
}
}
}
70 changes: 52 additions & 18 deletions Observer/Order/OrderComplete.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,33 +80,67 @@ public function execute(Observer $observer)
try {
/* @var Order $order */
$order = $observer->getEvent()->getOrder();
$isSynced = $order->getData('mp_smtp_email_marketing_synced');
if (!in_array($order->getState(), [Order::STATE_NEW, Order::STATE_COMPLETE], true)) {
$data = [
'id' => $order->getId(),
'status' => $order->getStatus(),
'state' => $order->getState(),
'email' => $order->getCustomerEmail(),
'is_utc' => true,
'created_at' => $this->helperEmailMarketing->formatDate($order->getCreatedAt()),
'updated_at' => $this->helperEmailMarketing->formatDate($order->getUpdatedAt())
];
$this->helperEmailMarketing->updateOrderStatusRequest($data);
if (!$order->getData('mp_smtp_email_marketing_order_created') &&
$order->getCreatedAt() === $order->getUpdatedAt()
) {
$this->syncOrder($order);
$this->helperEmailMarketing->updateCustomer($order->getCustomerId());
$order->setData('mp_smtp_email_marketing_order_created', true);
$this->updateFlag($order->getId(), 'mp_smtp_email_marketing_order_created');

} else {
if (!in_array($order->getState(), [Order::STATE_NEW, Order::STATE_COMPLETE], true)) {
$data = [
'id' => $order->getId(),
'status' => $order->getStatus(),
'state' => $order->getState(),
'email' => $order->getCustomerEmail(),
'is_utc' => true,
'created_at' => $this->helperEmailMarketing->formatDate($order->getCreatedAt()),
'updated_at' => $this->helperEmailMarketing->formatDate($order->getUpdatedAt())
];
$this->helperEmailMarketing->updateOrderStatusRequest($data);
}
}

$isSynced = $order->getData('mp_smtp_email_marketing_synced');

if ($order->getState() === Order::STATE_COMPLETE &&
!$isSynced) {
$this->helperEmailMarketing->sendOrderRequest($order, EmailMarketing::ORDER_COMPLETE_URL);
$resource = $this->resourceOrder;
$resource->getConnection()->update(
$resource->getMainTable(),
['mp_smtp_email_marketing_synced' => 1],
['entity_id = ?' => $order->getId()]
);
$this->updateFlag($order->getId(), 'mp_smtp_email_marketing_synced');
}
} catch (Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}

/**
* @param int|string $orderId
* @param string $field
*
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function updateFlag($orderId, $field)
{
$resource = $this->resourceOrder;
$resource->getConnection()->update(
$resource->getMainTable(),
[$field => 1],
['entity_id = ?' => $orderId]
);
}

/**
* @param Order $order
*/
public function syncOrder($order)
{
try {
$this->helperEmailMarketing->sendOrderRequest($order);
} catch (Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
Loading

0 comments on commit fd69420

Please sign in to comment.