diff --git a/Controller/Checkout.php b/Controller/Checkout.php index 6207a72e..e6a13426 100644 --- a/Controller/Checkout.php +++ b/Controller/Checkout.php @@ -96,6 +96,7 @@ protected function ajaxRequestAllowed() //check if cart was updated $currkey = $this->getDibsCheckout()->getQuoteSignature(); if($currkey != $ctrlkey) { + $this->dibsCheckout->getLogger()->error('AJAX key incorrect', ['signature' => $currkey, 'ctrlkey' => $ctrlkey]); $response = array( 'reload' => 1, 'messages' =>(string)__('The cart was updated (from another location), reloading the checkout, please wait...') @@ -108,4 +109,4 @@ protected function ajaxRequestAllowed() return false; } -} \ No newline at end of file +} diff --git a/Controller/Index/Index.php b/Controller/Index/Index.php index 1bca83df..477ef84a 100644 --- a/Controller/Index/Index.php +++ b/Controller/Index/Index.php @@ -36,6 +36,16 @@ public function execute() $paymentId = $this->getRequest()->getParam("paymentid"); } + $quote = $this->getDibsCheckout()->getQuote(); + $logContext = [ + 'params' => $this->getRequest()->getParams(), + 'payment_id' => $paymentId, + 'quote_id' => $quote->getId(), + 'customer_id' => $quote->getCustomerId(), + 'shipping_method' => $quote->getShippingAddress()->getShippingMethod(), + ]; + $this->dibsCheckout->getLogger()->info('Dibs index', $logContext); + // if the customer has payed with card and is redirected back here if ($paymentId) { try { @@ -45,6 +55,7 @@ public function execute() return $this->_redirect($checkout->getHelper()->getSuccessPageUrl()); } } catch (CheckoutException $e) { + $this->dibsCheckout->getLogger()->error('Dibs index check order should be saved error - ' . $e->getMessage(), $logContext); if ($e->isReload()) { $this->messageManager->addNoticeMessage($e->getMessage()); } else { @@ -66,6 +77,7 @@ public function execute() $checkout->initCheckout(false); // magento business logic $dibsPayment = $checkout->initDibsCheckout($integrationType); // handles magento and DIBS business logic } catch (CheckoutException $e) { + $this->dibsCheckout->getLogger()->error('Dibs index init error - ' . $e->getMessage(), $logContext); if ($e->isReload()) { $this->messageManager->addNoticeMessage($e->getMessage()); } else { @@ -83,9 +95,11 @@ public function execute() return; } } catch (\Exception $e) { + $this->dibsCheckout->getLogger()->critical( + 'Dibs index init error - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); $this->messageManager->addErrorMessage($e->getMessage() ? $e->getMessage() : __('Cannot initialize Nets Easy Checkout (%1)', get_class($e))); - $checkout->getLogger()->error("[" . __METHOD__ . "] (" . get_class($e) . ") {$e->getMessage()} "); - $checkout->getLogger()->critical($e); $this->_redirect(self::cartPath); return; @@ -109,13 +123,13 @@ public function execute() $unsetPayment = false; // THIS might happen if the store owner changes integration flow, when a customer already started with the old flow!, for embedded if (!$checkoutUrl && !$useIframe) { - $checkout->getLogger()->error("Cannot initialize Nets Easy Checkout! Hosted flow chosen but no checkout URL is returned from Dibs."); + $checkout->getLogger()->error("Dibs index init error - Cannot initialize Nets Easy Checkout! Hosted flow chosen but no checkout URL is returned from Dibs.", $logContext); $unsetPayment = true; } // THIS might also happen when store owner changes integration flow, when a customer already started the old flow, but for hosted if ($useIframe && $checkoutUrl) { - $checkout->getLogger()->error("Cannot initialize Nets Easy Checkout! Embedded flow chosen but checkout URL is returned from Dibs."); + $checkout->getLogger()->error("Dibs index init error - Cannot initialize Nets Easy Checkout! Embedded flow chosen but checkout URL is returned from Dibs.", $logContext); $unsetPayment = true; } @@ -140,6 +154,7 @@ public function execute() $q = $this->getDibsCheckout()->getQuote(); if (!$q->isVirtual() && $q->getShippingAddress() && !$q->getShippingAddress()->getShippingMethod()) { + $this->dibsCheckout->getLogger()->error('Dibs index error - no shipping method', $logContext); if ($isOverlayType) { $this->_redirect(self::magentoCheckout); return; @@ -196,6 +211,7 @@ protected function checkIfOrderShouldBeSaved($paymentId) $checkout->setCheckoutContext($this->dibsCheckoutContext); if ($this->getRequest()->getParam('paymentFailed')) { + $this->dibsCheckout->getLogger()->error('Dibs index - payment failed'); throw new CheckoutException(__("The payment was canceled or failed."), '*/*'); } diff --git a/Controller/Order/GetShippingMethod.php b/Controller/Order/GetShippingMethod.php index f3576f0e..52b203d1 100644 --- a/Controller/Order/GetShippingMethod.php +++ b/Controller/Order/GetShippingMethod.php @@ -73,13 +73,20 @@ public function execute() $postalCode = (string)$this->getRequest()->getParam('postal'); $postalCode = preg_replace("/[^0-9]/", "", $postalCode); + $logContext = [ + 'country' => $countryId, + 'postcode' => $postalCode, + ]; + if (!$postalCode) { - $this->getResponse()->setBody(json_encode(array('messages' => 'Please choose a valid Postal code.'))); + $this->dibsCheckout->getLogger()->warning('Get shipping method error - no postcode', $logContext); + $this->getResponse()->setBody(json_encode(array('messages' => __('Please choose a valid Postal code.')))); return; } if (!$this->validateCountryId($countryId)) { - $this->getResponse()->setBody(json_encode(array('messages' => 'Please select a Valid Country.'))); + $this->dibsCheckout->getLogger()->warning('Get shipping method error - invalid country', $logContext); + $this->getResponse()->setBody(json_encode(array('messages' => __('Please select a Valid Country.')))); return; } @@ -89,6 +96,7 @@ public function execute() return; }*/ + $this->dibsCheckout->getLogger()->info('Get shipping method - start', $logContext); if ($postalCode) { try { $quote = $this->getDibsCheckout()->getQuote(); @@ -104,11 +112,19 @@ public function execute() // save! $quote->save(); } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->dibsCheckout->getLogger()->error( + 'Get shipping method error - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); $this->messageManager->addExceptionMessage( $e, $e->getMessage() ); } catch (\Exception $e) { + $this->dibsCheckout->getLogger()->error( + 'Get shipping method error - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); $this->messageManager->addExceptionMessage( $e, __('We can\'t update your Country / postal code.') @@ -127,4 +143,4 @@ public function validateCountryId($countryId) { return (bool)in_array($countryId, $this->dibsCartHelper->getAllowedCountriesList()); } -} \ No newline at end of file +} diff --git a/Controller/Order/SaveOrder.php b/Controller/Order/SaveOrder.php index b647a031..72c2e586 100644 --- a/Controller/Order/SaveOrder.php +++ b/Controller/Order/SaveOrder.php @@ -23,12 +23,22 @@ public function execute() //$ctrlkey = (string)$this->getRequest()->getParam('ctrlkey'); $paymentId = $this->getRequest()->getParam('pid'); + $logContext = [ + 'payment_id' => $paymentId, + ]; + $checkout->getLogger()->info('Save order start', $logContext); + try { $orderPlaced = $checkout->tryToSaveDibsPayment($paymentId); } catch (CheckoutException $e) { + $checkout->getLogger()->error( + 'Save order - try to save dibs payment soft error - ' . $e->getMessage(), $logContext); return $this->respondWithError($e->getMessage()); } catch (\Exception $e) { - $checkout->getLogger()->error($e->getMessage()); + $checkout->getLogger()->error( + 'Save order - try to save dibs payment hard error - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); return $this->respondWithError("Something went wrong."); } diff --git a/Controller/Order/SaveShippingMethod.php b/Controller/Order/SaveShippingMethod.php index 70e5e439..e17ddff2 100644 --- a/Controller/Order/SaveShippingMethod.php +++ b/Controller/Order/SaveShippingMethod.php @@ -22,17 +22,29 @@ public function execute() return; } + $logContext = [ + 'shipping_method' => $shippingMethod, + ]; if ($shippingMethod) { + $this->dibsCheckout->getLogger()->info('Update shipping method - start', $logContext); try { $checkout = $this->getDibsCheckout(); $checkout->updateShippingMethod($shippingMethod); } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->dibsCheckout->getLogger()->error( + 'Update shipping method error - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); $this->messageManager->addExceptionMessage( $e, $e->getMessage() ); } catch (\Exception $e) { + $this->dibsCheckout->getLogger()->error( + 'Update shipping method error - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); $this->messageManager->addExceptionMessage( $e, __('We can\'t update shipping method.') diff --git a/Controller/Order/Update.php b/Controller/Order/Update.php index acd17500..a542d967 100644 --- a/Controller/Order/Update.php +++ b/Controller/Order/Update.php @@ -56,6 +56,7 @@ protected function _sendResponse($blocks = null, $updateCheckout = true) $checkout->updateDibsPayment($dibsPaymentId); } } catch (CheckoutException $e) { + $this->dibsCheckout->getLogger()->error('Update response error - ' . $e->getMessage()); $this->messageManager->addExceptionMessage( $e, $e->getMessage() @@ -72,9 +73,17 @@ protected function _sendResponse($blocks = null, $updateCheckout = true) $this->messageManager->addErrorMessage($e->getMessage()); } } catch (\Magento\Framework\Exception\LocalizedException $e) { + $this->dibsCheckout->getLogger()->error( + 'Update response error - ' . $e->getMessage(), + ['trace' => (string)$e] + ); //do nothing, we will just show the message $this->messageManager->addErrorMessage($e->getMessage() ? $e->getMessage() : __('Cannot update checkout (%1)', get_class($e))); } catch (\Exception $e) { + $this->dibsCheckout->getLogger()->error( + 'Update response error - ' . $e->getMessage(), + ['trace' => (string)$e] + ); $this->messageManager->addErrorMessage($e->getMessage() ? $e->getMessage() : __('Cannot initialize Dibs Checkout (%1)', get_class($e))); } diff --git a/Controller/Order/ValidateOrder.php b/Controller/Order/ValidateOrder.php index e9abd7c5..1850d9dc 100644 --- a/Controller/Order/ValidateOrder.php +++ b/Controller/Order/ValidateOrder.php @@ -14,13 +14,20 @@ public function execute() $checkoutPaymentId = $this->getCheckoutSession()->getDibsPaymentId(); $quote = $this->getDibsCheckout()->getQuote(); + $logContext = [ + 'payment_id' => $checkoutPaymentId, + 'quote_id' => $quote->getId(), + 'customer_id' => $quote->getCustomerId(), + 'shipping_method' => $quote->getShippingAddress()->getShippingMethod(), + ]; + if (!$checkoutPaymentId) { - $checkout->getLogger()->error("Validate Order: Found no dibs payment ID."); + $checkout->getLogger()->error("Validate Order: Found no dibs payment ID.", $logContext); return $this->respondWithError("Your session has expired, found no dibs payment id."); } if (!$quote) { - $checkout->getLogger()->error("Validate Order: No quote found for this customer."); + $checkout->getLogger()->error("Validate Order: No quote found for this customer.", $logContext); return $this->respondWithError("Your session has expired, found no quote."); } @@ -28,12 +35,19 @@ public function execute() $payment = $checkout->getDibsPaymentHandler()->loadDibsPaymentById($checkoutPaymentId); } catch (ClientException $e) { if ($e->getHttpStatusCode() == 404) { - $checkout->getLogger()->error("Validate Order: The dibs payment with ID: " . $checkoutPaymentId . " was not found in dibs."); + $checkout->getLogger()->error( + "Validate Order: The dibs payment with ID: " . $checkoutPaymentId . " was not found in dibs.", + $logContext + ); return $this->respondWithError("Found no Dibs Order for this session. Please refresh the site or clear your cookies."); } else { - $checkout->getLogger()->error("Validate Order: Something went wrong when we tried to fetch the payment ID from Dibs. Http Status code: " . $e->getHttpStatusCode()); - $checkout->getLogger()->error("Validate Order: Error message:" . $e->getMessage()); - $checkout->getLogger()->debug($e->getResponseBody()); + $checkout->getLogger()->error( + "Validate Order: Something went wrong when we tried to fetch the payment ID from Dibs - " . $e->getMessage(), + $logContext + [ + 'status_code' => $e->getHttpStatusCode(), + 'response' => $e->getResponseBody(), + ] + ); return $this->respondWithError("Something went wrong when we tried to retrieve the order from Dibs. Please try again or contact an admin."); } @@ -43,12 +57,15 @@ public function execute() __('Something went wrong.') ); - $checkout->getLogger()->error("Validate Order: Something went wrong. Might have been the request parser. Payment ID: " . $checkoutPaymentId . "... Error message:" . $e->getMessage()); + $checkout->getLogger()->error( + "Validate Order: Something went wrong. Might have been the request parser. Error message: " . $e->getMessage(), + $logContext + ); return $this->respondWithError("Something went wrong... Contact site admin."); } if ($payment->getConsumer()->getShippingAddress() === null) { - $checkout->getLogger()->error("Validate Order: Consumer has no shipping address."); + $checkout->getLogger()->error("Validate Order: Consumer has no shipping address.", $logContext); return $this->respondWithError("Please add shipping information."); } @@ -62,7 +79,7 @@ public function execute() $oldCountryId = $quote->getShippingAddress()->getCountryId(); // we do nothing - /** HOTFIX + /** HOTFIX if (!($oldCountryId == $currentCountryId && $oldPostCode == $currentPostalCode)) { $checkout->getLogger()->error("Validate Order: Consumer has no shipping address."); return $this->respondWithError("The country or postal code doesn't match with the one you entered earlier. Please re-enter the new postal code for the shipping above.", true, [ @@ -72,7 +89,7 @@ public function execute() **/ if (!$quote->getShippingAddress()->getShippingMethod()) { - $checkout->getLogger()->error("Validate Order: Consumer has no shipping address."); + $checkout->getLogger()->error("Validate Order: Quote has no shipping method.", $logContext); return $this->respondWithError("Please choose a shipping method.", true, [ 'postalCode' => $currentPostalCode, 'countryId' => $currentCountryId ]); @@ -83,10 +100,15 @@ public function execute() __('Something went wrong.') ); - $checkout->getLogger()->error("Validate Order: Something went wrong... Payment ID: " . $checkoutPaymentId . "... Error message:" . $e->getMessage()); + $checkout->getLogger()->error( + "Validate Order: Something went wrong... Error message:" . $e->getMessage(), + $logContext + ); return $this->respondWithError("Something went wrong... Contact site admin."); } + $checkout->getLogger()->info('Validate order success', $logContext); + $this->getResponse()->setBody(json_encode(['chooseShippingMethod' => false, 'error' => false])); return false; } diff --git a/Controller/Order/WebhookCallback.php b/Controller/Order/WebhookCallback.php index 2fc6a254..4e3a9633 100644 --- a/Controller/Order/WebhookCallback.php +++ b/Controller/Order/WebhookCallback.php @@ -68,12 +68,26 @@ public function execute() if (!isset($data['event']) || $data['event'] !== CreatePaymentWebhook::EVENT_PAYMENT_CHECKOUT_COMPLETED || !isset($data['data']['paymentId'])){ + $this->logger->info( + 'Webhook skip', + [ + 'event' => $data['event'] ?? null, + 'payment_id' => $data['data']['paymentId'] ?? null, + 'quote_id' => $quoteId, + 'response_code' => 200, + ] + ); $result->setHttpResponseCode(200); return $result; } $paymentId = $data['data']['paymentId']; + $logContext = [ + 'payment_id' => $paymentId, + 'quote_id' => $quoteId, + ]; + $checkout = $this->getDibsCheckout(); $checkout->setCheckoutContext($this->dibsCheckoutContext); @@ -81,6 +95,7 @@ public function execute() // validate authorization $ourSecret = $checkout->getHelper()->getWebhookSecret(); if ($ourSecret && $ourSecret != $this->getRequest()->getHeader("Authorization")) { + $this->logger->warning('Webhook error - bad secret', $logContext + ['response_code' => 401]); $result->setHttpResponseCode(401); return $result; } @@ -88,6 +103,7 @@ public function execute() try { $quote = $this->loadQuote($quoteId); } catch (\Exception $e) { + $this->logger->error('Webhook error - cannot load quote - ' . $e->getMessage(), $logContext + ['response_code' => 500]); $this->logger->error($e); // maybe magento is down? @@ -98,7 +114,7 @@ public function execute() try { $dibsPayment = $checkout->getDibsPaymentHandler()->loadDibsPaymentById($paymentId); } catch (\Exception $e) { - $this->logger->error("Could not load dibs payment (id: " . $paymentId . ") for quote (id: ".$quoteId.")"); + $this->logger->error("Webhook error - Could not load dibs payment - " . $e->getMessage(), $logContext + ['response_code' => 500]); $this->logger->error($e); // maybe nets is down @@ -108,7 +124,10 @@ public function execute() // we check that its the correct quote if ($checkout->getDibsPaymentHandler()->generateReferenceByQuoteId($quoteId) !== $dibsPayment->getOrderDetails()->getReference()) { - + $this->logger->error('Webhook error - reference mismatch', $logContext + [ + 'reference' => $dibsPayment->getOrderDetails()->getReference(), + 'response_code' => 200, + ]); // either its wrong, or order has been placed already! (since we update reference when order is placed to magento order id) $result->setHttpResponseCode(200); return $result; @@ -136,36 +155,46 @@ public function execute() ->count(); if ($ordersCount > 0) { + $this->logger->info('Webhook skip - order already created', $logContext + ['response_code' => 200]); $result->setHttpResponseCode(200); return $result; } + $this->logger->info('Webhook - placing order', $logContext); try { $order = $checkout->placeOrder($dibsPayment, $quote, $weHandleConsumerData, false); } catch (\Exception $e) { - $this->logger->error("Could not place order for dibs payment with payment id: " . $dibsPayment->getPaymentId() . ", Quote ID:" . $quote->getId()); - $this->logger->error("Error message:" . $e->getMessage()); + $this->logger->error( + "Webhook error - Could not place order - " . $e->getMessage(), + $logContext + [ + 'trace' => (string)$e, + 'response_code' => 500, + ] + ); $result->setHttpResponseCode(500); return $result; } + $logContext['order_id'] = $order->getId(); + $logContext['order_increment'] = $order->getIncrementId(); + try { + $this->logger->info('Webhook - updating payment reference', $logContext); $checkout->getDibsPaymentHandler()->updateMagentoPaymentReference($order, $paymentId, $changeUrl); } catch (\Exception $e) { - $this->getLogger()->error( - " - Order created with ID: " . $order->getIncrementId() . ". - But we could not update reference ID at dibs. Please handle it manually, it has id: quote_id_: " . $quote->getId() . "... Dibs Payment ID: " . $paymentId + $this->logger->error( + 'Webhook error - cannot update payment reference - ' . $e->getMessage(), + $logContext + ['response_code' => 200] ); // lets ignore this and save it in logs! let customer see his/her order confirmation! - $this->getLogger()->error("Error message:" . $e->getMessage()); - // ... ignore this error... } + $this->logger->info('Webhook success', $logContext + ['response_code' => 200]); + $result->setHttpResponseCode(200); return $result; } @@ -188,12 +217,12 @@ protected function loadQuoteById($quoteId) */ protected function loadQuote($quoteId) { - try { +// try { $quote = $this->loadQuoteById($quoteId); - } catch (\Exception $e) { - $this->logger->error("Webhook: We found no quote for this Nets Payment."); - throw new \Exception("Found no quote object for this Nets Payment ID."); - } +// } catch (\Exception $e) { +// $this->logger->error("Webhook: We found no quote for this Nets Payment."); +// throw new \Exception("Found no quote object for this Nets Payment ID."); +// } return $quote; } diff --git a/Model/Checkout.php b/Model/Checkout.php index b06a23bf..5178d2fa 100644 --- a/Model/Checkout.php +++ b/Model/Checkout.php @@ -129,8 +129,8 @@ public function initCheckout($reloadIfCurrencyChanged = true) $billingAddress->save(); $shippingAddress->save(); - $this->totalsCollector->collectAddressTotals($quote, $shippingAddress); - $this->totalsCollector->collectQuoteTotals($quote); +// $this->totalsCollector->collectAddressTotals($quote, $shippingAddress); +// $this->totalsCollector->collectQuoteTotals($quote); $quote->collectTotals(); $this->quoteRepository->save($quote); @@ -461,35 +461,40 @@ public function tryToSaveDibsPayment($paymentId) $checkoutPaymentId = $session->getDibsPaymentId(); + $logContext = [ + 'payment_id' => $checkoutPaymentId, + ]; + if (!$quote) { + $this->_logger->warning('tryToSaveDibsPayment error - no quote', $logContext); return $this->throwRedirectToCartException(__("Your session has expired. Quote missing.")); } if (!$paymentId || !$checkoutPaymentId || ($paymentId != $checkoutPaymentId)) { - $this->getLogger()->error("Invalid request"); + $this->getLogger()->error("tryToSaveDibsPayment error - Invalid request", $logContext + [ + 'checkout_payment_id' => $checkoutPaymentId, + ]); if (!$checkoutPaymentId) { - $this->getLogger()->error("Save Order: No dibs checkout payment id in session."); return $this->throwRedirectToCartException(__("Your session has expired.")); } if ($paymentId != $checkoutPaymentId) { - return $this->getLogger()->error("Save Order: The session has expired or is wrong."); + return $this->throwRedirectToCartException("Save Order: The session has expired or is wrong."); } - return $this->getLogger()->error("Save Order: Invalid data."); + return $this->throwRedirectToCartException("Save Order: Invalid data."); } try { $payment = $this->getDibsPaymentHandler()->loadDibsPaymentById($paymentId); } catch (ClientException $e) { + $this->getLogger()->error("tryToSaveDibsPayment error - " . $e->getMessage(), $logContext + [ + 'status_code' => $e->getHttpStatusCode(), + 'response' => $e->getResponseBody(), + ]); if ($e->getHttpStatusCode() == 404) { - $this->getLogger()->error("Save Order: The dibs payment with ID: " . $paymentId . " was not found in dibs."); return $this->throwReloadException(__("Could not create an order. The payment was not found in dibs.")); } else { - $this->getLogger()->error("Save Order: Something went wrong when we tried to fetch the payment ID from Dibs. Http Status code: " . $e->getHttpStatusCode()); - $this->getLogger()->error("Error message:" . $e->getMessage()); - $this->getLogger()->debug($e->getResponseBody()); - return $this->throwReloadException(__("Could not create an order, please contact site admin. Dibs seems to be down!")); } } catch (\Exception $e) { @@ -498,7 +503,10 @@ public function tryToSaveDibsPayment($paymentId) __('Something went wrong.') ); - $this->getLogger()->error("Save Order: Something went wrong. Might have been the request parser. Payment ID: " . $checkoutPaymentId . "... Error message:" . $e->getMessage()); + $this->getLogger()->error( + "tryToSaveDibsPayment error - Something went wrong. Might have been the request parser. Payment ID: " . $checkoutPaymentId . "... Error message:" . $e->getMessage(), + $logContext + ); return $this->throwReloadException(__("Something went wrong... Contact site admin.")); } @@ -536,44 +544,75 @@ public function tryToSaveDibsPayment($paymentId) $createOrder = false; } + $logContext['has_order'] = (bool)$order; + $logContext['we_handle_consumer'] = $weHandleConsumerData; + $logContext['reference'] = $payment->getOrderDetails()->getReference(); + $logContext['reserved_amount'] = $payment->getSummary()->getReservedAmount(); + $logContext['charged_amount'] = $payment->getSummary()->getChargedAmount(); + if ($createOrder) { if ($payment->getOrderDetails()->getReference() !== $this->getDibsPaymentHandler()->generateReferenceByQuoteId($quote->getId())) { - $this->getLogger()->error("Save Order: The customer Quote ID doesn't match with the dibs payment reference: " . $payment->getOrderDetails()->getReference()); + $this->getLogger()->error("tryToSaveDibsPayment - Save Order: The customer Quote ID doesn't match with the dibs payment reference: " . $payment->getOrderDetails()->getReference(), $logContext); return $this->throwReloadException(__("Could not create an order. Invalid data. Contact admin.")); } // In Swish there is no reserved amount? if ($payment->getSummary()->getReservedAmount() === null && $payment->getSummary()->getChargedAmount() === null) { - $this->getLogger()->error("Save Order: Found no summary for the payment id: " . $payment->getPaymentId() . "... This must mean that they customer hasn't checked out yet!"); + $this->getLogger()->error("tryToSaveDibsPayment Save Order: Found no summary for the payment id: " . $payment->getPaymentId() . "... This must mean that they customer hasn't checked out yet!", $logContext); return $this->throwReloadException(__("We could not create your order... No reserved or charged amount found. Payment id: %1", $payment->getPaymentId())); } + $this->_logger->info('tryToSaveDibsPayment - placing order', $logContext); try { $order = $this->placeOrder($payment, $quote, $weHandleConsumerData); } catch (\Exception $e) { - $this->getLogger()->error("Could not place order for dibs payment with payment id: " . $payment->getPaymentId() . ", Quote ID:" . $quote->getId()); - $this->getLogger()->error("Error message:" . $e->getMessage()); + $this->getLogger()->error( + "tryToSaveDibsPayment place order error - " . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); return $this->throwReloadException(__("We could not create your order. Please contact the site admin with this error and payment id: %1", $payment->getPaymentId())); } + $logContext['order_id'] = $order->getId(); + $logContext['order_increment'] = $order->getIncrementId(); + // Handle swish orders if ($this->isSwishPaymentValid($payment)) { - $this->handleSwishOrder($payment, $order); + $this->_logger->info('tryToSaveDibsPayment - handle swish order', $logContext); + try { + $this->handleSwishOrder($payment, $order); + } catch (\Exception $e) { + $this->_logger->error( + 'tryToSaveDibsPayment error swish order - ' . $e->getMessage(), + $logContext + ['trace' => (string)$e] + ); + // don't throw. we can invoice later + } } + $logContext['order_status'] = $order->getstatus(); + try { $this->updateMagentoPaymentReference($order, $paymentId, $changeUrl); } catch (\Exception $e) { $this->getLogger()->error( - " - Order created with ID: " . $order->getIncrementId() . ". - But we could not update reference ID at dibs. Please handle it manually, it has id: quote_id_: " . $quote->getId() . "... Dibs Payment ID: " . $payment->getPaymentId() + "tryToSaveDibsPayment update reference error - " . $e->getMessage() . " + Order created with ID: " . $order->getIncrementId() . ". + But we could not update reference ID at dibs. Please handle it manually", + $logContext ); // lets ignore this and save it in logs! let customer see his/her order confirmation! $this->getLogger()->error("Error message:" . $e->getMessage()); } + + $this->_logger->info('tryToSaveDibsPayment success', $logContext); + } else { + $logContext['order_id'] = $order->getId(); + $logContext['order_increment'] = $order->getIncrementId(); + $logContext['order_status'] = $order->getStatus(); + $this->_logger->info('tryToSaveDibsPayment - already created', $logContext); } // clear old sessions @@ -596,7 +635,7 @@ public function tryToSaveDibsPayment($paymentId) * @param Quote $quote * @param bool $weHandleConsumer * @param bool $setSessionOrderId - * @return mixed + * @return \Magento\Sales\Model\Order * @throws \Exception */ public function placeOrder(GetPaymentResponse $dibsPayment, Quote $quote, $weHandleConsumer = false, $setSessionOrderId = true) @@ -707,8 +746,8 @@ public function placeOrder(GetPaymentResponse $dibsPayment, Quote $quote, $weHan $quote->collectTotals(); } - //- do not recollect totals - $quote->setTotalsCollectedFlag(true); + //- recollect totals - original price + $quote->collectTotals(); //! // Now we create the order from the quote @@ -724,7 +763,7 @@ public function placeOrder(GetPaymentResponse $dibsPayment, Quote $quote, $weHan ['order' => $order, 'quote' => $this->getQuote()] ); - if ($order->getCanSendNewEmailFlag()) { + if ($order->getCanSendNewEmailFlag() && !$order->getEmailSent()) { try { $this->orderSender->send($order); } catch (\Exception $e) { diff --git a/Model/Client/Client.php b/Model/Client/Client.php index 275d3721..c21397f7 100644 --- a/Model/Client/Client.php +++ b/Model/Client/Client.php @@ -134,13 +134,14 @@ protected function post($endpoint, AbstractRequest $request, $options = []){ if ($this->testMode) { - $this->getLogger()->info("Sending request to dibs integration: POST $endpoint"); - $this->getLogger()->info($request->toJSON()); - - $this->getLogger()->info("Response Headers from dibs:"); - $this->getLogger()->info(json_encode($result->getHeaders())); - $this->getLogger()->info("Response Body from dibbs:"); - $this->getLogger()->info($content); + $this->getLogger()->info( + "Sending request to dibs integration: POST $endpoint", + [ + 'request' => $request->toJSON(), + 'headers' => $result->getHeaders(), + 'response' => $content, + ] + ); } return $content; @@ -151,12 +152,15 @@ protected function post($endpoint, AbstractRequest $request, $options = []){ } if ($exception) { - $this->getLogger()->error("Failed sending request to dibs integration: POST $endpoint"); - $this->getLogger()->error(json_encode($this->removeAuthForLogging($options))); - $this->getLogger()->error($request->toJSON()); - $this->getLogger()->error($exception->getMessage()); - $this->getLogger()->error($exception->getHttpStatusCode()); - $this->getLogger()->error($exception->getResponseBody()); + $this->getLogger()->error( + "Failed sending request to dibs integration: POST $endpoint - " . $exception->getMessage(), + [ + 'options' => $this->removeAuthForLogging($options), + 'request' => $request->toJSON(), + 'status_code' => $exception->getHttpStatusCode(), + 'response' => $exception->getResponseBody(), + ] + ); throw $exception; } @@ -183,13 +187,14 @@ protected function put($endpoint, AbstractRequest $request, $options = []){ $content = $result->getBody()->getContents(); if ($this->testMode) { - $this->getLogger()->info("Sending request to dibs integration: PUT $endpoint"); - $this->getLogger()->info($request->toJSON()); - - $this->getLogger()->info("Response Headers from dibs:"); - $this->getLogger()->info(json_encode($result->getHeaders())); - $this->getLogger()->info("Response Body from dibbs:"); - $this->getLogger()->info($content); + $this->getLogger()->info( + "Sending request to dibs integration: PUT $endpoint", + [ + 'request' => $request->toJSON(), + 'headers' => $result->getHeaders(), + 'response' => $content, + ] + ); } return $content; @@ -200,12 +205,15 @@ protected function put($endpoint, AbstractRequest $request, $options = []){ } if ($exception) { - $this->getLogger()->error("Failed sending request to dibs integration: PUT $endpoint"); - $this->getLogger()->error(json_encode($this->removeAuthForLogging($options))); - $this->getLogger()->error($request->toJSON()); - $this->getLogger()->error($exception->getMessage()); - $this->getLogger()->error($exception->getHttpStatusCode()); - $this->getLogger()->error($exception->getResponseBody()); + $this->getLogger()->error( + "Failed sending request to dibs integration: PUT $endpoint - " . $exception->getMessage(), + [ + 'options' => $this->removeAuthForLogging($options), + 'request' => $request->toJSON(), + 'status_code' => $exception->getHttpStatusCode(), + 'response' => $exception->getResponseBody(), + ] + ); throw $exception; } } diff --git a/Model/Dibs/Items.php b/Model/Dibs/Items.php index 572604c9..19717611 100644 --- a/Model/Dibs/Items.php +++ b/Model/Dibs/Items.php @@ -38,11 +38,16 @@ class Items protected $_itemsArray = []; protected $addCustomOptionsToItemName = null; + /** + * @var \Magento\SalesRule\Api\RuleRepositoryInterface + */ + private $ruleRepository; public function __construct( \Dibs\EasyCheckout\Helper\Data $helper, \Magento\Catalog\Helper\Product\Configuration $productConfig, - \Magento\Tax\Model\Calculation $calculationTool + \Magento\Tax\Model\Calculation $calculationTool, + \Magento\SalesRule\Api\RuleRepositoryInterface $ruleRepository ) { $this->_helper = $helper; $this->_productConfig = $productConfig; @@ -50,6 +55,7 @@ public function __construct( // resets all values $this->init(); + $this->ruleRepository = $ruleRepository; } public function init($store = null) @@ -252,11 +258,11 @@ public function addItems($items) ->setName($itemName) ->setUnit("st") ->setQuantity(round($qty, 0)) - ->setTaxRate($vat) - ->setTaxAmount($this->getTotalTaxAmount($unitPrice * $qty, $vat, false)) // total tax amount + ->setTaxRate((int) $vat) + ->setTaxAmount((int) $this->getTotalTaxAmount($unitPrice * $qty, $vat, false)) // total tax amount ->setUnitPrice((int) $unitPriceExclTax) // excl. tax price per item ->setNetTotalAmount((int) ($unitPriceExclTax * $qty)) // excl. tax - ->setGrossTotalAmount((int) ($unitPrice * $qty)); // incl. tax + ->setGrossTotalAmount((int) ($this->addZeroes($item->getRowTotalInclTax()))); // incl. tax // add to array $this->_cart[$sku] = $orderItem; @@ -329,7 +335,7 @@ public function addShipping($address) ->setName((string)__('Shipping Fee (%1)', $address->getShippingDescription())) ->setUnit("st") // TODO! We need to map these somehow! ->setQuantity(1) - ->setTaxRate($vat) + ->setTaxRate((int) $vat) ->setTaxAmount($this->addZeroes($taxAmount)) // total tax amount ->setUnitPrice($this->addZeroes($exclTax)) // excl. tax price per item ->setNetTotalAmount($this->addZeroes($exclTax)) // excl. tax @@ -428,13 +434,13 @@ public function generateInvoiceFeeItem($invoiceLabel, $invoiceFee, $vatIncluded) $feeItem ->setName($invoiceLabel) ->setReference(strtolower(str_replace(" ", "_", $invoiceLabel))) - ->setTaxRate($taxRate) + ->setTaxRate((int) $taxRate) ->setGrossTotalAmount($this->addZeroes($invoiceFeeInclTax)) // incl tax ->setNetTotalAmount($this->addZeroes($invoiceFeeExclTax)) // // excl. tax ->setUnit("st") ->setQuantity(1) ->setUnitPrice($this->addZeroes($invoiceFeeExclTax)) // // excl. tax - ->setTaxAmount($taxAmount); // tax amount + ->setTaxAmount((int) $taxAmount); // tax amount return $feeItem; } @@ -466,8 +472,8 @@ public function addDiscounts($couponCode) ->setName($couponCode ? (string)__('Discount (%1)', $couponCode) : (string)__('Discount')) ->setUnit("st") ->setQuantity(1) - ->setTaxRate($vat) - ->setTaxAmount($taxAmount) // total tax amount + ->setTaxRate((int) $vat) + ->setTaxAmount((int) $taxAmount) // total tax amount ->setUnitPrice(0) // excl. tax price per item ->setNetTotalAmount(-$amountExclTax) // excl. tax ->setGrossTotalAmount(-$amountInclTax); // incl. tax @@ -478,6 +484,48 @@ public function addDiscounts($couponCode) return $this; } + /** + * Check if discount was applied for whole cart + * + * @param Quote $quote + */ + private function addDiscountByCartRule(Quote $quote) : void + { + $ruleIds = $quote->getAppliedRuleIds(); + if (!$ruleIds) { + return; + } + + foreach (explode(',', $ruleIds) as $ruleId) { + try { + $rule = $this->ruleRepository->getById($ruleId); + } catch (\Exception $e) { + continue; + } + + if ($rule->getSimpleAction() != 'cart_fixed') { + continue; + } + + $discount = $quote->getSubtotal() - $quote->getSubtotalWithDiscount(); + $discount = $this->addZeroes($discount); + $orderItem = new OrderItem(); + $reference = $rule->getName(); + $orderItem + ->setReference($reference) + ->setName($quote->getCouponCode() ? (string)__('Discount (%1)', $quote->getCouponCode()) : (string)__('Discount')) + ->setUnit("st") + ->setQuantity(1) + ->setTaxRate($this->addZeroes(0)) // the tax rate i.e 25% (2500) + ->setTaxAmount(0) // total tax amount + ->setUnitPrice(-$discount) // excl. tax price per item + ->setNetTotalAmount(-$discount) // excl. tax + ->setGrossTotalAmount(-$discount); // incl. tax + + $this->_cart[$reference] = $orderItem; + } + } + public function validateTotals($grandTotal) { //calculate Dibs total @@ -591,7 +639,12 @@ public function generateOrderItemsFromQuote(Quote $quote) $this->addShipping($shippingAddress); } - $this->addDiscounts($quote->getCouponCode()); + // If there is no discount per items, but code does exist + // it means, that discount was applied on whole cart + // @TODO: Refactor this to external model + count($this->_discounts) + ? $this->addDiscounts($quote->getCouponCode()) + : $this->addDiscountByCartRule($quote); try { $this->validateTotals($quote->getGrandTotal()); diff --git a/PATCHES.txt b/PATCHES.txt new file mode 100644 index 00000000..35ab8049 --- /dev/null +++ b/PATCHES.txt @@ -0,0 +1,7 @@ +This file was automatically generated by Composer Patches (https://github.com/cweagans/composer-patches) +Patches applied to this directory: + +Dibs translations +Source: patches/Patch-Dibs_Easycheckout-translations-v2.patch + + diff --git a/etc/di.xml b/etc/di.xml index 41fac520..db91fd5e 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -29,4 +29,10 @@ + + + + Dibs\EasyCheckout\Logger\Logger + + diff --git a/view/frontend/templates/checkout/shipping.phtml b/view/frontend/templates/checkout/shipping.phtml index 51edbf53..c296e463 100644 --- a/view/frontend/templates/checkout/shipping.phtml +++ b/view/frontend/templates/checkout/shipping.phtml @@ -29,7 +29,8 @@ $shippingAddress = $quote->getShippingAddress(); placeholder="" value="getPostcode()) ? __('') : $shippingAddress->getPostcode() ?>" autofocus /> diff --git a/view/frontend/web/js/checkout.js b/view/frontend/web/js/checkout.js index 404d39bf..d381f9ae 100644 --- a/view/frontend/web/js/checkout.js +++ b/view/frontend/web/js/checkout.js @@ -6,10 +6,10 @@ /*global alert*/ define([ "jquery", - 'Magento_Ui/js/modal/alert', + 'Convert_IdeDibsEasyCheckout/js/modal/alert',// patch 'Magento_Ui/js/modal/alert', 'Magento_Checkout/js/model/quote', 'uiRegistry', - "jquery/ui", + 'jquery-ui-modules/widget',// patch "mage/translate", "mage/mage", "mage/validation" @@ -178,6 +178,7 @@ define([ _bindEvents: function (block) { //$blocks = ['shipping_method','cart','coupon','messages', 'dibs','newsletter']; + jQuery(this.options.getShippingMethodButton).attr('disabled', false) block = block ? block : null; if (!block || block == 'shipping') { @@ -346,7 +347,7 @@ define([ window.location.reload(); } return true; - } //end redirect + } //end redirect //ctlKeyy Cookie if (response.ctrlkey) {