diff --git a/Api/Log/LogService.php b/Api/Log/LogService.php index 382ffbe..3c80c03 100644 --- a/Api/Log/LogService.php +++ b/Api/Log/LogService.php @@ -32,5 +32,11 @@ public function debug(string $type, $data): LogService; /** * @param string|int $prefix */ - public function prefix($prefix): LogService; + public function addPrefix($prefix): LogService; + + /** + * @param string|int $prefix + * @return LogService + */ + public function removePrefix($prefix): LogService; } diff --git a/Controller/Checkout/Process.php b/Controller/Checkout/Process.php index 8c0ecc4..ea9a848 100644 --- a/Controller/Checkout/Process.php +++ b/Controller/Checkout/Process.php @@ -60,7 +60,7 @@ public function __construct( ConfigRepository $configRepository, TransactionRepository $transactionRepository, SessionHelper $sessionHelper, - LogRepository $logRepository + LogRepository $logger ) { $this->orderRepository = $orderRepository; $this->jsonFactory = $jsonFactory; @@ -71,7 +71,7 @@ public function __construct( $this->paymentSettledService = $paymentSettledService; $this->paymentFailedService = $paymentFailedService; $this->sessionHelper = $sessionHelper; - $this->logger = $logRepository->prefix('Process'); + $this->logger = $logger->addPrefix('Process'); parent::__construct($context); } diff --git a/Controller/Checkout/Redirect.php b/Controller/Checkout/Redirect.php index 5d5df56..e4b01e6 100644 --- a/Controller/Checkout/Redirect.php +++ b/Controller/Checkout/Redirect.php @@ -65,7 +65,7 @@ public function __construct( $this->hppService = $hppService; $this->transactionRepository = $transactionRepository; $this->sessionHelper = $sessionHelper; - $this->logger = $logger->prefix('RedirectToHpp'); + $this->logger = $logger->addPrefix('RedirectToHpp'); parent::__construct($context); } @@ -97,8 +97,11 @@ public function execute(): ResponseInterface private function createPaymentAndRedirect(): ResponseInterface { $order = $this->checkoutSession->getLastRealOrder(); + $this->logger->addPrefix("order {$order->getEntityId()}"); + $created = $this->paymentCreationService->createPayment($order); $url = $this->hppService->getRedirectUrl($created); + $transaction = $this->transactionRepository->getByPaymentUuid($created->getId()); $this->sessionHelper->allowQuoteRestoration($transaction->getQuoteId()); diff --git a/Gateway/Command/AuthorizePaymentCommand.php b/Gateway/Command/AuthorizePaymentCommand.php index c5af3ca..2f180ac 100644 --- a/Gateway/Command/AuthorizePaymentCommand.php +++ b/Gateway/Command/AuthorizePaymentCommand.php @@ -19,7 +19,7 @@ class AuthorizePaymentCommand extends AbstractCommand */ public function __construct(OrderRepositoryInterface $orderRepository, LogRepository $logger) { - parent::__construct($orderRepository, $logger->prefix("AuthorizePaymentCommand")); + parent::__construct($orderRepository, $logger->addPrefix("AuthorizePaymentCommand")); } /** diff --git a/Gateway/Command/RefundPaymentCommand.php b/Gateway/Command/RefundPaymentCommand.php index 6a7a700..abf4c4c 100644 --- a/Gateway/Command/RefundPaymentCommand.php +++ b/Gateway/Command/RefundPaymentCommand.php @@ -31,7 +31,7 @@ public function __construct( LogService $logger ) { $this->refundService = $refundService; - parent::__construct($orderRepository, $logger->prefix("RefundPaymentCommand")); + parent::__construct($orderRepository, $logger->addPrefix("RefundPaymentCommand")); } /** @@ -44,6 +44,7 @@ public function __construct( protected function executeCommand(array $subject): void { $order = $this->getOrder($subject); + $this->logger->addPrefix($order->getEntityId()); $this->refundService->refund($order, (float) SubjectReader::readAmount($subject)); } } \ No newline at end of file diff --git a/Model/Transaction/Refund/RefundTransactionRepository.php b/Model/Transaction/Refund/RefundTransactionRepository.php index 84a2acc..dec253f 100644 --- a/Model/Transaction/Refund/RefundTransactionRepository.php +++ b/Model/Transaction/Refund/RefundTransactionRepository.php @@ -47,7 +47,7 @@ public function __construct( $this->resource = $resource; $this->dataFactory = $dataFactory; $this->collectionFactory = $collectionFactory; - $this->logger = $logger->prefix('RefundTransactionRepository'); + $this->logger = $logger; } /** @@ -107,7 +107,7 @@ public function save(RefundTransactionDataInterface $entity): RefundTransactionD $this->resource->save($entity); return $entity; } catch (\Exception $exception) { - $this->logger->error('Save failed', $exception); + $this->logger->error('Could not save refund transaction', $exception); throw new CouldNotSaveException(__(self::COULD_NOT_SAVE_EXCEPTION, $exception->getMessage())); } } @@ -124,7 +124,7 @@ private function getByColumn(string $col, $value): RefundTransactionDataInterfac $transaction = $this->dataFactory->create()->load($value, $col); if (!$transaction->getEntityId()) { - $this->logger->error('Entity not found', $value); + $this->logger->error('Refund transaction not found', $value); throw new NoSuchEntityException(__('No record found for %1: %2.', $col, $value)); } diff --git a/Model/Webapi/Webhook.php b/Model/Webapi/Webhook.php index 3fae505..9d0f9ac 100644 --- a/Model/Webapi/Webhook.php +++ b/Model/Webapi/Webhook.php @@ -78,7 +78,7 @@ public function __construct( $this->file = $file; $this->transactionRepository = $transactionRepository; $this->quoteRepository = $quoteRepository; - $this->logger = $logger->prefix('Webhook'); + $this->logger = $logger->addPrefix('Webhook'); } /** @@ -92,13 +92,15 @@ public function __construct( */ public function processTransfer() { + $this->refundFailedService->handle('b0327151-99a4-4e38-85fc-2a6795982b4b', 'foo'); + Settings::tlAgent('truelayer-magento/' . $this->configProvider->getExtensionVersion()); $webhook = TrueLayerWebhook::configure() ->useProduction(!$this->configProvider->isSandbox($this->getStoreId())) ->create() ->handler(function (TrueLayerWebhookInterface\EventInterface $event) { - $this->logger->debug('Webhook', $event->getBody()); + $this->logger->debug('Body', $event->getBody()); }) ->handler(function (TrueLayerWebhookInterface\PaymentSettledEventInterface $event) { $this->paymentSettledService->handle($event->getPaymentId()); diff --git a/Observer/CreditMemoObserver.php b/Observer/CreditMemoObserver.php index 292dd43..c791679 100644 --- a/Observer/CreditMemoObserver.php +++ b/Observer/CreditMemoObserver.php @@ -29,7 +29,7 @@ class CreditMemoObserver implements ObserverInterface public function __construct(RefundTransactionRepositoryInterface $refundTransactionRepository, LogService $logger) { $this->refundTransactionRepository = $refundTransactionRepository; - $this->logger = $logger->prefix('CreditMemoObserver'); + $this->logger = $logger->addPrefix('CreditMemoObserver'); } /** @@ -75,6 +75,6 @@ public function execute(Observer $observer) $refundTransaction->setCreditMemoId((int)$creditMemo->getEntityId()); $this->refundTransactionRepository->save($refundTransaction); - $this->logger->debug('Refund transaction updated'); + $this->logger->debug('Transaction updated'); } } \ No newline at end of file diff --git a/Observer/OrderPlacedObserver.php b/Observer/OrderPlacedObserver.php index 4ed9658..ddc43fa 100644 --- a/Observer/OrderPlacedObserver.php +++ b/Observer/OrderPlacedObserver.php @@ -28,7 +28,7 @@ public function __construct( LogService $logger ) { $this->orderRepository = $orderRepository; - $this->logger = $logger->prefix('OrderPlacedHandler'); + $this->logger = $logger->addPrefix('OrderPlacedHandler'); } /** diff --git a/Service/Client/ClientFactory.php b/Service/Client/ClientFactory.php index b6dd6cf..090c509 100644 --- a/Service/Client/ClientFactory.php +++ b/Service/Client/ClientFactory.php @@ -30,7 +30,7 @@ public function __construct( LogService $logger ) { $this->configProvider = $configProvider; - $this->logger = $logger->prefix('ClientFactory'); + $this->logger = $logger; } /** @@ -46,7 +46,7 @@ public function create(int $storeId = 0, ?array $data = []): ?ClientInterface try { return $this->createClient($credentials); } catch (Exception $e) { - $this->logger->debug('Create Fail', $e->getMessage()); + $this->logger->debug('Client Creation Failed', $e->getMessage()); throw $e; } } diff --git a/Service/Log/LogService.php b/Service/Log/LogService.php index 601f51f..5b09cb0 100644 --- a/Service/Log/LogService.php +++ b/Service/Log/LogService.php @@ -19,7 +19,7 @@ class LogService implements LogServiceInterface private ConfigProvider $configProvider; private Logger $debugLogger; private Logger $errorLogger; - private string $prefix = ''; + private array $prefixes = []; /** * @param ConfigProvider $configProvider @@ -61,21 +61,42 @@ public function debug(string $type, $data = ''): self /** * @inheriDoc */ - public function prefix(string $prefix): self + public function addPrefix($prefix): self { - $this->prefix = $prefix; + $this->prefixes[] = $prefix; + return $this; + } + /** + * @param int|string $prefix + * @return $this + */ + public function removePrefix($prefix): LogService + { + foreach ($this->prefixes as $key => $value) { + if ($value ===$prefix) { + unset($this->prefixes[$key]); + return $this; + } + } return $this; } /** - * @param string $type + * @param string $msg * @param mixed $data * @return string */ - private function buildMessage(string $type, $data = ''): string + private function buildMessage(string $msg, $data = ''): string { - return "$this->prefix: $type: {$this->convertDataToString($data)}"; + $parts = $this->prefixes; + $parts[] = $msg; + + if ($serialisedData = $this->convertDataToString($data)) { + $parts[] = $serialisedData; + } + + return join(' > ', $parts); } /** @@ -84,10 +105,6 @@ private function buildMessage(string $type, $data = ''): string */ private function convertDataToString($data): string { - if (is_string($data)) { - return $data; - } - if ($data instanceof \Exception) { return $data->getMessage() . " " . $data->getTraceAsString(); } @@ -102,6 +119,6 @@ private function convertDataToString($data): string } } - return 'failed to serialize error message'; + return "{$data}"; } } diff --git a/Service/Order/BaseTransactionService.php b/Service/Order/BaseTransactionService.php index b730972..c3b8bdf 100644 --- a/Service/Order/BaseTransactionService.php +++ b/Service/Order/BaseTransactionService.php @@ -17,12 +17,9 @@ abstract class BaseTransactionService /** * @param LogService $logger - * @return $this */ - public function logger(LogService $logger): self - { + public function __construct(LogService $logger) { $this->logger = $logger; - return $this; } /** @@ -31,20 +28,22 @@ public function logger(LogService $logger): self */ public function execute(Callable $fn): void { + $this->logger->addPrefix('Transaction')->debug('Start'); + $transaction = $this->getTransaction(); $this->validateTransaction($transaction); if ($transaction->getIsLocked()) { - $this->logger->debug('Aborting, locked transaction'); + $this->logger->debug('Aborting, locked'); return; } if (!in_array($transaction->getStatus(), ['NULL', null])) { - $this->logger->debug('Aborting, transaction already completed'); + $this->logger->debug('Aborting, already completed'); return; } - $this->logger->debug('Locking transaction'); + $this->logger->debug('Locking'); $transaction->setIsLocked(true); $this->saveTransaction($transaction); @@ -58,6 +57,7 @@ public function execute(Callable $fn): void $transaction->setIsLocked(false); $this->saveTransaction($transaction); $this->logger->debug('Unlocked transaction'); + $this->logger->removePrefix('Transaction'); } } @@ -76,12 +76,13 @@ protected abstract function saveTransaction(BaseTransactionDataInterface $transa */ private function validateTransaction(BaseTransactionDataInterface $transaction): void { - $this->logger->debug("Transaction", [ + $this->logger->debug("Details", [ 'transaction id' => $transaction->getEntityId(), 'order id' => $transaction->getOrderId(), ]); if (!$transaction->getOrderId()) { + $this->logger->error('Transaction with missing order found'); throw new Exception('Transaction with missing order found'); } } diff --git a/Service/Order/PaymentCreationService.php b/Service/Order/PaymentCreationService.php index b9035ff..d24b359 100644 --- a/Service/Order/PaymentCreationService.php +++ b/Service/Order/PaymentCreationService.php @@ -56,7 +56,7 @@ public function __construct( $this->transactionRepository = $transactionRepository; $this->userRepository = $userRepository; $this->mathRandom = $mathRandom; - $this->logger = $logger->prefix('PaymentCreationService'); + $this->logger = $logger; } /** @@ -71,8 +71,7 @@ public function __construct( */ public function createPayment(OrderInterface $order): PaymentCreatedInterface { - $this->logger->prefix($order->getEntityId()); - $this->logger->debug('Start'); + $this->logger->addPrefix('PaymentCreationService')->debug('Start'); // Get the TL user id if we recognise the email address $customerEmail = $order->getBillingAddress()->getEmail() ?: $order->getCustomerEmail(); @@ -84,7 +83,7 @@ public function createPayment(OrderInterface $order): PaymentCreatedInterface $this->logger->debug('Create client'); $merchantAccountId = $this->getMerchantAccountId($client, $order); - $this->logger->debug('Found merchant account', $merchantAccountId); + $this->logger->debug('Merchant account', $merchantAccountId); $paymentConfig = $this->createPaymentConfig($order, $merchantAccountId, $customerEmail, $existingUserId); $payment = $client->payment()->fill($paymentConfig)->create(); @@ -113,15 +112,18 @@ public function createPayment(OrderInterface $order): PaymentCreatedInterface */ private function createPaymentConfig(OrderInterface $order, string $merchantAccId, string $customerEmail, string $existingUserId = null): array { + $countries = null; + if ($shippingAddress = $order->getShippingAddress()) { + $countries = [ $shippingAddress->getCountryId() ]; + } + $config = [ "amount_in_minor" => AmountHelper::toMinor($order->getBaseGrandTotal()), "currency" => $order->getBaseCurrencyCode(), "payment_method" => [ "provider_selection" => [ "filter" => [ - "countries" => [ - $order->getShippingAddress()->getCountryId() - ], + "countries" => $countries, "release_channel" => "general_availability", "customer_segments" => $this->configRepository->getBankingProviders(), "excludes" => [ @@ -175,7 +177,7 @@ private function getMerchantAccountId(ClientInterface $client, OrderInterface $o } } - throw new Exception(__('No merchant account found')); + throw new Exception('No merchant account found'); } /** diff --git a/Service/Order/PaymentUpdate/PaymentFailedService.php b/Service/Order/PaymentUpdate/PaymentFailedService.php index 3247723..f45fa72 100644 --- a/Service/Order/PaymentUpdate/PaymentFailedService.php +++ b/Service/Order/PaymentUpdate/PaymentFailedService.php @@ -31,7 +31,7 @@ public function __construct( ) { $this->orderRepository = $orderRepository; $this->transactionService = $transactionService; - $this->logger = $logger->prefix('PaymentFailedService'); + $this->logger = $logger; } /** @@ -41,12 +41,14 @@ public function __construct( */ public function handle(string $paymentId, string $failureReason): void { - $this->logger->prefix($paymentId); + $prefix = "PaymentFailedService $paymentId"; + $this->logger->addPrefix($prefix); $this->transactionService - ->logger($this->logger) ->paymentId($paymentId) ->execute(fn($transaction) => $this->cancelOrder($transaction, $failureReason)); + + $this->logger->removePrefix($prefix); } /** diff --git a/Service/Order/PaymentUpdate/PaymentSettledService.php b/Service/Order/PaymentUpdate/PaymentSettledService.php index d47b808..3447590 100644 --- a/Service/Order/PaymentUpdate/PaymentSettledService.php +++ b/Service/Order/PaymentUpdate/PaymentSettledService.php @@ -50,7 +50,7 @@ public function __construct( $this->invoiceSender = $invoiceSender; $this->configRepository = $configRepository; $this->transactionService = $transactionService; - $this->logger = $logger->prefix('PaymentSettledService'); + $this->logger = $logger; } /** @@ -62,10 +62,10 @@ public function __construct( */ public function handle(string $paymentId) { - $this->logger->prefix($paymentId); + $prefix = "PaymentSettledService $paymentId"; + $this->logger->addPrefix($prefix); $this->transactionService - ->logger($this->logger) ->paymentId($paymentId) ->execute(function (PaymentTransactionDataInterface $transaction) use ($paymentId) { $order = $this->orderRepository->get($transaction->getOrderId()); @@ -74,6 +74,8 @@ public function handle(string $paymentId) $this->sendOrderEmail($order); $this->sendInvoiceEmail($order); }); + + $this->logger->removePrefix($prefix); } private function updateOrder(OrderInterface $order, string $paymentId) diff --git a/Service/Order/PaymentUpdate/PaymentTransactionService.php b/Service/Order/PaymentUpdate/PaymentTransactionService.php index 0524a06..5266dae 100644 --- a/Service/Order/PaymentUpdate/PaymentTransactionService.php +++ b/Service/Order/PaymentUpdate/PaymentTransactionService.php @@ -10,6 +10,7 @@ use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; +use TrueLayer\Connect\Api\Log\LogService; use TrueLayer\Connect\Api\Transaction\BaseTransactionDataInterface; use TrueLayer\Connect\Api\Transaction\Payment\PaymentTransactionRepositoryInterface; use TrueLayer\Connect\Service\Order\BaseTransactionService; @@ -21,10 +22,12 @@ class PaymentTransactionService extends BaseTransactionService /** * @param PaymentTransactionRepositoryInterface $transactionRepository + * @param LogService $logger */ - public function __construct(PaymentTransactionRepositoryInterface $transactionRepository) + public function __construct(PaymentTransactionRepositoryInterface $transactionRepository, LogService $logger) { $this->transactionRepository = $transactionRepository; + parent::__construct($logger); } /** diff --git a/Service/Order/RefundService.php b/Service/Order/RefundService.php index ac18bdb..a1e3f1c 100644 --- a/Service/Order/RefundService.php +++ b/Service/Order/RefundService.php @@ -45,7 +45,7 @@ public function __construct( $this->clientFactory = $clientFactory; $this->paymentTransactionRepository = $paymentTransactionRepository; $this->refundTransactionRepository = $refundTransactionRepository; - $this->logger = $logger->prefix('RefundService'); + $this->logger = $logger; } /** @@ -61,7 +61,7 @@ public function __construct( */ public function refund(OrderInterface $order, float $amount): ?string { - $this->logger->prefix($order->getEntityId()); + $this->logger->addPrefix('RefundService')->debug('Start'); if ($amount == 0) { return null; @@ -83,6 +83,8 @@ public function refund(OrderInterface $order, float $amount): ?string $this->refundTransactionRepository->save($refundTransaction); $this->logger->debug('Refund transaction created', $refundTransaction->getEntityId()); + $this->logger->removePrefix('RefundService'); + return $refundId; } diff --git a/Service/Order/RefundUpdate/RefundFailedService.php b/Service/Order/RefundUpdate/RefundFailedService.php index 488b4be..c91424a 100644 --- a/Service/Order/RefundUpdate/RefundFailedService.php +++ b/Service/Order/RefundUpdate/RefundFailedService.php @@ -39,7 +39,7 @@ public function __construct( $this->orderRepository = $orderRepository; $this->creditmemoRepository = $creditmemoRepository; $this->transactionService = $transactionService; - $this->logger = $logger->prefix('RefundFailedService'); + $this->logger = $logger; } /** @@ -51,10 +51,10 @@ public function __construct( */ public function handle(string $refundId, string $failureReason) { - $this->logger->prefix($refundId); + $prefix = "RefundFailedService $refundId"; + $this->logger->addPrefix($prefix)->debug('Start'); $this->transactionService - ->logger($this->logger) ->refundId($refundId) ->execute(function (RefundTransactionDataInterface $transaction) use ($failureReason) { $order = $this->orderRepository->get($transaction->getOrderId()); @@ -63,6 +63,8 @@ public function handle(string $refundId, string $failureReason) $this->markCreditMemoRefunded($creditMemo, $failureReason); $transaction->setStatus('refund_failed'); }); + + $this->logger->removePrefix($prefix); } /** diff --git a/Service/Order/RefundUpdate/RefundTransactionService.php b/Service/Order/RefundUpdate/RefundTransactionService.php index e883509..3e4aeb2 100644 --- a/Service/Order/RefundUpdate/RefundTransactionService.php +++ b/Service/Order/RefundUpdate/RefundTransactionService.php @@ -10,6 +10,7 @@ use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; +use TrueLayer\Connect\Api\Log\LogService; use TrueLayer\Connect\Api\Transaction\BaseTransactionDataInterface; use TrueLayer\Connect\Api\Transaction\Payment\PaymentTransactionRepositoryInterface; use TrueLayer\Connect\Api\Transaction\Refund\RefundTransactionRepositoryInterface; @@ -22,10 +23,12 @@ class RefundTransactionService extends BaseTransactionService /** * @param RefundTransactionRepositoryInterface $transactionRepository + * @param LogService $logger */ - public function __construct(RefundTransactionRepositoryInterface $transactionRepository) + public function __construct(RefundTransactionRepositoryInterface $transactionRepository, LogService $logger) { $this->transactionRepository = $transactionRepository; + parent::__construct($logger); } /**