Skip to content

Commit

Permalink
Add debug log for checkout flow (#163)
Browse files Browse the repository at this point in the history
* enable debug logging for checkout flow

* Fix load order by increment_id

* Fix sonar tests

---------

Co-authored-by: andy <[email protected]>
  • Loading branch information
andykim and andykim authored May 15, 2023
1 parent de39c2d commit f5ff5df
Show file tree
Hide file tree
Showing 15 changed files with 378 additions and 127 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## 10.0.3 (2023-05-11)
Improvements:
- Implementation debug logging

## 10.0.2 (2023-03-21)
Improvements:
- Update min/max total of Akulaku
Expand Down
39 changes: 24 additions & 15 deletions Controller/Checkout/AbstractAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\DB\Transaction as DbTransaction;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Phrase;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Framework\UrlInterface;
use Magento\Multishipping\Model\Checkout\Type\Multishipping;
Expand All @@ -28,15 +29,14 @@
use Xendit\M2Invoice\Helper\Data;
use Xendit\M2Invoice\Helper\ErrorHandler;
use Xendit\M2Invoice\Helper\Metric;
use Xendit\M2Invoice\Logger\Logger as XenditLogger;

/**
* Class AbstractAction
* @package Xendit\M2Invoice\Controller\Checkout
*/
abstract class AbstractAction extends Action
{
const LOG_FILE = 'xendit.log';

/**
* @var Session
*/
Expand Down Expand Up @@ -182,7 +182,7 @@ public function __construct(
Context $context,
CategoryFactory $categoryFactory,
OrderFactory $orderFactory,
LoggerInterface $logger,
XenditLogger $logger,
Data $dataHelper,
Crypto $cryptoHelper,
Checkout $checkoutHelper,
Expand Down Expand Up @@ -433,25 +433,34 @@ protected function getRedirectFactory()
}

/**
* @param $order
* @param Order $order
* @param $failureReason
* @return Order
* @throws LocalizedException
*/
protected function cancelOrder($order, $failureReason)
protected function cancelOrder(Order $order, $failureReason)
{
$orderState = Order::STATE_CANCELED;

if ($order->getStatus() != $orderState) {
$order->setState($orderState)
try {
$message = "Order #" . $order->getIncrementId() . " was cancelled by Xendit because " . $failureReason;
$order->setState($orderState)
->setStatus($orderState)
->addStatusHistoryComment("Order #" . $order->getIncrementId() . " was cancelled by Xendit because " . $failureReason);
$order->save();

$this->getCheckoutHelper()->cancelOrderById($order->getId(), "Order #" . ($order->getId()) . " was rejected by Xendit");
$this->getCheckoutHelper()->restoreQuote(); //restore cart
->addStatusHistoryComment($message);
$this->orderRepo->save($order);

$this->getCheckoutHelper()->cancelOrderById($order->getId(), "Order #" . ($order->getId()) . " was rejected by Xendit");
$this->getCheckoutHelper()->restoreQuote(); //restore cart

$this->logger->info($message);
} catch (\Exception $ex) {
$this->logger->error('Cancel order failed:' . $ex->getMessage(), ['order_id' => $order->getIncrementId()]);
throw new LocalizedException(
new Phrase($ex->getMessage())
);
}
}

return;
return $order;
}

/**
Expand Down Expand Up @@ -497,7 +506,7 @@ protected function getMultiShippingOrderIds()
*/
protected function orderValidToCreateXenditInvoice(Order $order): bool
{
if (!empty($order) && empty($order->getXenditTransactionId())) {
if (empty($order->getXenditTransactionId())) {
return true;
}
return false;
Expand Down
100 changes: 74 additions & 26 deletions Controller/Checkout/Invoice.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,34 +27,46 @@ public function execute()

if ($order->getState() === Order::STATE_NEW) {
$this->changePendingPaymentStatus($order);

$invoice = $this->createInvoice($apiData);
$this->addInvoiceData($order, $invoice);
$redirectUrl = $this->getXenditRedirectUrl($invoice, $apiData['preferred_method']);

$redirectUrl = $this->getXenditRedirectUrl($invoice, $apiData['preferred_method']);
$this->getLogger()->info(
'Redirect customer to Xendit',
['order_id' => $order->getIncrementId(), 'redirect_url' => $redirectUrl]
);
$resultRedirect = $this->getRedirectFactory()->create();
$resultRedirect->setUrl($redirectUrl);
return $resultRedirect;
} elseif ($order->getState() === Order::STATE_CANCELED) {
$this->getLogger()->info('Order is already canceled', ['order_id' => $order->getIncrementId()]);

$this->_redirect('checkout/cart');
} else {
$this->getLogger()->debug('Order in unrecognized state: ' . $order->getState());
$this->getLogger()->info('Order in unrecognized state', ['state' => $order->getState(), 'order_id' => $order->getIncrementId()]);
$this->_redirect('checkout/cart');
}
} catch (\Throwable $e) {
$errorMessage = sprintf('xendit/checkout/invoice failed: Order #%s - %s', $order->getIncrementId(), $e->getMessage());

$this->getLogger()->error($errorMessage, ['order_id' => $order->getIncrementId()]);
$this->getLogger()->debug('Exception caught on xendit/checkout/invoice: ' . $e->getMessage());
$this->getLogger()->debug($e->getTraceAsString());

$this->cancelOrder($order, $e->getMessage());

// log metric error
$this->metricHelper->sendMetric(
'magento2_checkout',
[
'type' => 'error',
'payment_method' => $this->getPreferredMethod($order),
'error_message' => $e->getMessage()
]
);
// cancel order
try {
$this->cancelOrder($order, $e->getMessage());
$this->metricHelper->sendMetric(
'magento2_checkout',
[
'type' => 'error',
'payment_method' => $this->getPreferredMethod($order),
'error_message' => $errorMessage
]
);
} catch (\Exception $e) {
}

return $this->redirectToCart($e->getMessage());
}
Expand Down Expand Up @@ -124,6 +136,8 @@ private function createInvoice($requestData)

try {
if (isset($requestData['preferred_method'])) {
$this->getLogger()->info('createInvoice start', ['data' => $requestData]);

$invoice = $this->getApiHelper()->request(
$invoiceUrl,
$invoiceMethod,
Expand All @@ -147,6 +161,7 @@ private function createInvoice($requestData)
);
}

$this->getLogger()->info('createInvoice success', ['xendit_invoice' => $invoice]);
return $invoice;
}

Expand All @@ -163,32 +178,65 @@ private function getXenditRedirectUrl($invoice, $preferredMethod)
/**
* @param Order $order
* @return void
* @throws LocalizedException
*/
private function changePendingPaymentStatus(Order $order)
{
$order->setState(Order::STATE_PENDING_PAYMENT)->setStatus(Order::STATE_PENDING_PAYMENT);
$order->addCommentToStatusHistory("Pending Xendit payment.");
$this->getOrderRepo()->save($order);
try {
$order->setState(Order::STATE_PENDING_PAYMENT)->setStatus(Order::STATE_PENDING_PAYMENT);
$order->addCommentToStatusHistory("Pending Xendit payment.");
$this->getOrderRepo()->save($order);

$this->getLogger()->info(
'changePendingPaymentStatus success',
['order_id' => $order->getIncrementId()]
);
} catch (\Exception $e) {
$this->getLogger()->error(
sprintf('changePendingPaymentStatus failed: %s', $e->getMessage()),
['order_id' => $order->getIncrementId()]
);

throw new LocalizedException(
new Phrase($e->getMessage())
);
}
}

/**
* @param Order $order
* @param array $invoice
* @return void
* @throws \Exception
*/
private function addInvoiceData(Order $order, array $invoice)
{
$payment = $order->getPayment();
$payment->setAdditionalInformation('payment_gateway', 'xendit');
if (isset($invoice['id'])) {
$payment->setAdditionalInformation('xendit_invoice_id', $invoice['id']);
$order->setXenditTransactionId($invoice['id']);
}
if (isset($invoice['expiry_date'])) {
$payment->setAdditionalInformation('xendit_invoice_exp_date', $invoice['expiry_date']);
}
try {
$payment = $order->getPayment();
$payment->setAdditionalInformation('payment_gateway', 'xendit');
if (isset($invoice['id'])) {
$payment->setAdditionalInformation('xendit_invoice_id', $invoice['id']);
$order->setXenditTransactionId($invoice['id']);
}
if (isset($invoice['expiry_date'])) {
$payment->setAdditionalInformation('xendit_invoice_exp_date', $invoice['expiry_date']);
}

$this->getOrderRepo()->save($order);
$this->getLogger()->info(
'addInvoiceData success',
['order_id' => $order->getIncrementId(), 'xendit_transaction_id' => $invoice['id']]
);
} catch (\Exception $e) {
$this->getLogger()->error(
sprintf('addInvoiceData failed: %s', $e->getMessage()),
['order_id' => $order->getIncrementId(), 'xendit_transaction_id' => $invoice['id']]
);

$this->getOrderRepo()->save($order);
throw new LocalizedException(
new Phrase($e->getMessage())
);
}
}

/**
Expand Down
Loading

0 comments on commit f5ff5df

Please sign in to comment.