diff --git a/Api/CustomerPaymentTokenInterface.php b/Api/CustomerPaymentTokenInterface.php new file mode 100644 index 0000000..bd0ef6b --- /dev/null +++ b/Api/CustomerPaymentTokenInterface.php @@ -0,0 +1,16 @@ +_toHtml(); + } +} +?> \ No newline at end of file diff --git a/Block/ApplePay/Button.php b/Block/ApplePay/Button.php index ff8212d..b4bab79 100644 --- a/Block/ApplePay/Button.php +++ b/Block/ApplePay/Button.php @@ -77,24 +77,24 @@ public function isApplePayEnableonPdp() /** * Get Apple pay Button Type */ - public function isApplePayButtonType() + public function isApplePayButtonTypePdp() { - return $this->worldpayHelper->getApplePayButtonType(); + return $this->worldpayHelper->getApplePayButtonTypePdp(); } /** * Get Apple pay Button Color */ - public function isApplePayButtonColor() + public function isApplePayButtonColorPdp() { - return $this->worldpayHelper->getApplePayButtonColor(); + return $this->worldpayHelper->getApplePayButtonColorPdp(); } /** * Get Apple pay Button Locale or not */ - public function isApplePayButtonLocale() + public function isApplePayButtonLocalePdp() { - return $this->worldpayHelper->getApplePayButtonLocale(); + return $this->worldpayHelper->getApplePayButtonLocalePdp(); } } diff --git a/Block/Multishipping/Paybylink/Email/Addresses.php b/Block/Multishipping/Paybylink/Email/Addresses.php index 3c66d87..0447c09 100644 --- a/Block/Multishipping/Paybylink/Email/Addresses.php +++ b/Block/Multishipping/Paybylink/Email/Addresses.php @@ -7,6 +7,7 @@ /** * Worldpay Multishipping PayByLink Shipment address * + * @author Magento Core Team */ namespace Sapient\Worldpay\Block\Multishipping\Paybylink\Email; @@ -33,11 +34,11 @@ class Addresses extends \Magento\Framework\View\Element\Template * @var \Magento\Quote\Api\CartRepositoryInterface */ protected $quoteRepository; + /** - * constructor - * + * constructor * * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\Customer\Model\Address\Config $addressConfig + * @param \Magento\Customer\Model\Address\Config $addressConfig * @param \Sapient\Worldpay\Logger\WorldpayLogger $wplogger * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository * @param array $data diff --git a/Block/MultishippingCheckoutLink.php b/Block/MultishippingCheckoutLink.php index a70f0b4..562a3ed 100644 --- a/Block/MultishippingCheckoutLink.php +++ b/Block/MultishippingCheckoutLink.php @@ -13,9 +13,9 @@ */ class MultishippingCheckoutLink extends \Magento\Multishipping\Block\Checkout\Link { - /** - * @var \Sapient\Worldpay\Helper\Recurring - */ + /** + * @var \Sapient\Worldpay\Helper\Recurring + */ protected $_sapientHelper; /** * @param \Magento\Framework\View\Element\Template\Context $context @@ -33,13 +33,12 @@ public function __construct( parent::__construct($context, $helper, $data); } - /** - * Render Quote information and return result html - * - * @return string - */ - - public function _toHtml () + /** + * Check Multishipping checkout isavailable + * + * @return string + */ + public function _toHtml() { if (!$this->helper->isMultishippingCheckoutAvailable()) { return ''; diff --git a/Block/Recurring/Customer/Subscriptions.php b/Block/Recurring/Customer/Subscriptions.php index e17cc09..1034dfb 100644 --- a/Block/Recurring/Customer/Subscriptions.php +++ b/Block/Recurring/Customer/Subscriptions.php @@ -194,4 +194,16 @@ public function getMyAccountSpecificException($exceptioncode) { return $this->recurringHelper->getMyAccountExceptions($exceptioncode); } -} + + /** + * Get next recurring order + * + * @param int $subscriptionId + * @return array + */ + public function getNextRecurringOrder($subscriptionId) + { + $customerId = $this->customerSession->getCustomerId(); + return $this->recurringHelper->getNextRecurringOrder($subscriptionId,$customerId); + } +} \ No newline at end of file diff --git a/Block/Recurring/Customer/Subscriptions/Edit.php b/Block/Recurring/Customer/Subscriptions/Edit.php index 9964c3e..1a0827a 100644 --- a/Block/Recurring/Customer/Subscriptions/Edit.php +++ b/Block/Recurring/Customer/Subscriptions/Edit.php @@ -16,12 +16,14 @@ use Sapient\Worldpay\Model\Recurring\Plan; use Sapient\Worldpay\Model\Recurring\Subscription; use Sapient\Worldpay\Model\Recurring\SubscriptionFactory; +use Sapient\Worldpay\Model\Recurring\Subscription\Transactions; use Magento\Directory\Helper\Data; //use Sapient\Worldpay\Model\Ui\CcConfigProvider; class Edit extends Template { + public const RECURRING_ORDER_SKIP_DAYS_UPTO = 9; /** * @var \Sapient\Worldpay\Model\Recurring\Subscription|null */ @@ -34,6 +36,10 @@ class Edit extends Template * @var SubscriptionFactory */ private $subscriptionFactory; + /** + * @var CollectionFactory + */ + private $transactionCollectionFactory; /** * @var Recurring */ @@ -62,6 +68,7 @@ class Edit extends Template /** * @param Template\Context $context * @param SubscriptionFactory $subscriptionFactory + * @param Transactions $recurringTransactions * @param Recurring $recurringHelper * @param ProductFactory $productFactory * @param IconsProvider $iconsProvider @@ -73,6 +80,7 @@ class Edit extends Template public function __construct( Template\Context $context, SubscriptionFactory $subscriptionFactory, + Transactions $recurringTransactions, Recurring $recurringHelper, ProductFactory $productFactory, IconsProvider $iconsProvider, @@ -83,6 +91,7 @@ public function __construct( ) { parent::__construct($context, $data); $this->subscriptionFactory = $subscriptionFactory; + $this->transactionCollectionFactory = $recurringTransactions; $this->recurringHelper = $recurringHelper; $this->productFactory = $productFactory; $this->tokenManager = $tokenManager; @@ -149,6 +158,19 @@ public function getSaveUrl() ); } + /** + * View All Recurring Order + * + * @return string + */ + public function getViewAllRecurringOrder() + { + return $this->_urlBuilder->getUrl( + 'worldpay/recurring_order/view/', + ['_secure' => true, 'subscription_id' => $this->getSubscription()->getId()] + ); + } + /** * Retrieve product subscription plans * @@ -348,4 +370,45 @@ public function getCountriesWithOptionalZip($asJson) { return $this->helper->getCountriesWithOptionalZip($asJson); } + + /** + * Get next recurring order + * + * @return array + */ + public function getNextRecurringOrder() + { + $subscriptionId = $this->getSubscription()->getId(); + $customerId = $this->customerSession->getCustomerId(); + return $this->recurringHelper->getNextRecurringOrder($subscriptionId,$customerId); + } + + /** + * Get Next recurring order date + * + * @return string + */ + public function getNextOrderDate() + { + $nextOrder = $this->getNextRecurringOrder(); + if (!empty($nextOrder)) { + return $nextOrder->getRecurringDate(); + } + return false; + } + + /** + * Get recurring count + * + * @return int + */ + public function getRecurringOrderCollection() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + $subscriptionCount = $this->transactionCollectionFactory->getCollection() + ->addFieldToFilter('subscription_id', ['eq' => $subscriptionId]) + ->addFieldToFilter('status', ['eq' =>'completed']); + + return $subscriptionCount->getSize(); + } } diff --git a/Block/Recurring/Customer/Subscriptions/OrderInfo.php b/Block/Recurring/Customer/Subscriptions/OrderInfo.php new file mode 100644 index 0000000..3770813 --- /dev/null +++ b/Block/Recurring/Customer/Subscriptions/OrderInfo.php @@ -0,0 +1,141 @@ +addressRenderer = $addressRenderer; + $this->paymentHelper = $paymentHelper; + $this->coreRegistry = $registry; + $this->_isScopePrivate = true; + $this->_customerAddressHelper = $customerAddressHelper; + $this->addressMapper = $addressMapper; + $this->customerSession = $customerSession; + $this->_addressConfig = $addressConfig; + $this->customerRepository = $customerRepository; + + parent::__construct($context, $data); + } + + /** + * Retrieve Current Customer data + * + * @return mixed + */ + public function getCurrentCustomer() + { + return $this->customerSession->getCustomer(); + } + + /** + * Retrieve Current order model instance + * + * @return \Magento\Sales\Model\Order + */ + public function getCurrentSubscriptionOrder() + { + return $this->coreRegistry->registry('current_subscription_order'); + } + + /** + * Returns string with formatted address + * + * @param Address $address + * @return null|string + */ + public function getFormattedAddress(Address $address) + { + return $this->addressRenderer->format($address, 'html'); + } + + /** + * Retrieve Transaction Data + * + * @param Subscription $subscriptionOrder + * @return mixed + */ + public function getTransactionData(\Sapient\Worldpay\Model\Recurring\Subscription $subscriptionOrder) + { + return $subscriptionOrder->getTransactionData(); + } +} diff --git a/Block/Recurring/Customer/Subscriptions/OrderInfo/AddressInfo.php b/Block/Recurring/Customer/Subscriptions/OrderInfo/AddressInfo.php new file mode 100644 index 0000000..05e8e6f --- /dev/null +++ b/Block/Recurring/Customer/Subscriptions/OrderInfo/AddressInfo.php @@ -0,0 +1,52 @@ +getData('address_options'); + if ($options === null) { + $options = []; + $addresses = []; + + try { + $currentCustomer = $this->getCurrentCustomer(); + $addresses = $this->customerRepository->getById($currentCustomer->getId())->getAddresses(); + } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { + /** Customer does not exist */ + throw new NoSuchEntityException(__('Customer does not exist')); + } + /** @var \Magento\Customer\Api\Data\AddressInterface $address */ + foreach ($addresses as $address) { + $label = $this->_addressConfig + ->getFormatByCode(AddressConfig::DEFAULT_ADDRESS_FORMAT) + ->getRenderer() + ->renderArray($this->addressMapper->toFlatArray($address)); + + $options[] = [ + 'value' => $address->getId(), + 'label' => $label, + ]; + } + $this->setData('address_options', $options); + } + + return $options; + } +} diff --git a/Block/SavedCardLink.php b/Block/SavedCardLink.php index 884f5bd..32d534b 100644 --- a/Block/SavedCardLink.php +++ b/Block/SavedCardLink.php @@ -14,6 +14,10 @@ use Sapient\Worldpay\Model\WorldpayConfigProvider; use Sapient\Worldpay\Helper\Data; +/** + * Description of SavedCardLink + * + */ class SavedCardLink extends \Magento\Framework\View\Element\Html\Link\Current { diff --git a/Block/SubscriptionOrders.php b/Block/SubscriptionOrders.php new file mode 100644 index 0000000..f01f2cd --- /dev/null +++ b/Block/SubscriptionOrders.php @@ -0,0 +1,327 @@ +subscriptionOrder = $subscriptionOrder; + $this->recurringhelper = $recurringhelper; + $this->orderRepository = $orderRepository; + $this->urlInterface = $urlInterface; + parent::__construct($context, $data); + } + + /** + * Retrieve Subscription Order Collection + * + * @return mixed + */ + public function getsubscriptionOrderCollection() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + $timeFilter = $this->getRequest()->getParam('timeFilter'); + $timeFilterby = $this->subscriptionOrder + ->getFilterDate($timeFilter=null); + $subscriptionOrderCollection = $this->subscriptionOrder + ->getsubscriptionOrderCollection($subscriptionId, $timeFilterby); + + return $subscriptionOrderCollection; + } + + /** + * My Account Labels + * + * @param string $labelCode + * @return $this + */ + + public function getMyAccountLabels($labelCode) + { + return $this->recurringhelper->getAccountLabelbyCode($labelCode); + } + + /** + * Get subscription plan interval label + * + * @param string $interval + * @return string + */ + public function getSubscriptionIntervalLabel($interval) + { + return $this->recurringhelper->getPlanIntervalLabel($interval); + } + + /** + * Specific Exception + * + * @param string $exceptioncode + * @return string + */ + + public function getMyAccountSpecificException($exceptioncode) + { + return $this->recurringhelper->getMyAccountExceptions($exceptioncode); + } + + /** + * Return Current Url + * + * @return string + */ + public function getCurrentURL() + { + return $this->urlInterface->getCurrentUrl(); + } + + /** + * Return Order Filter URL + * + * @param string $timeVal + * @return string + */ + public function getOrderFilterURL($timeVal) + { + $link = $this->getHistoryPageURL(); + $paramsData = $this->getRequest()->getParams(); + if (count($paramsData)) { + $link .= "?"; + /* Page Number */ + if (isset($paramsData['p'])) { + $link .= "p=" . $paramsData['p'] . "&"; + } + /* Page Limit Number */ + if (isset($paramsData['limit'])) { + $link .= "limit=" . $paramsData['limit'] . "&"; + } + /* Time period */ + $link .= "timeFilter=" . $timeVal . "&"; + } + + $link = rtrim(rtrim($link, "&"), "?"); + return $link; + } + + /** + * Return history URL for Filter + * + * @return string + */ + public function getHistoryPageURL() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + return $this->_urlBuilder->getUrl( + 'worldpay/recurring_order/view/', + ['_secure' => true, 'subscription_id' => $subscriptionId] + ); + } + /** + * Return Selected Option in Filter + * + * @param string $filter + * @return bool + */ + public function checkSelectedFilter($filter) + { + $selectedFilter = $this->getRequest()->getParam('timeFilter'); + if ($filter == $selectedFilter) { + return true; + } + return false; + } + + /** + * Return cancel Url + * + * @param SubscriptionOrder $subscription + * @return string + */ + public function getCancelUrl(SubscriptionOrder $subscription) + { + return $this->getUrl( + 'worldpay/recurring_order/cancel/', + [ + 'id' => $subscription->getOriginalOrderId(), + '_secure' => true + ] + ); + } + + /** + * Return View Url + * + * @param SubscriptionOrder $subscription + * @return string + */ + public function getViewlUrl(SubscriptionOrder $subscription) + { + return $this->getUrl( + 'sales/order/view', + [ + 'order_id' => $subscription->getOriginalOrderId(), + '_secure' => true + ] + ); + } + /** + * Return Skip Orderl Url + * + * @return string + */ + public function getSkipOrderlUrl() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + return $this->_urlBuilder->getUrl( + 'worldpay/recurring_order/skiporders/', + ['_secure' => true, 'subscription_id' => $subscriptionId] + ); + } + /** + * Check Order Shipment + * + * @param Subscription $subscription + * @return bool + */ + public function checkOrderShipment(SubscriptionOrder $subscription) + { + $orderId = $subscription->getOriginalOrderId(); + $order = $this->subscriptionOrder->getOrderbyOriginalId($orderId); + + return $order->hasShipments(); + } + + /** + * Check Order Buffer Time + * + * @param Subscription $subscription + * @return bool + */ + public function checkOrderBufferTime(SubscriptionOrder $subscription) + { + $createdAt = new \DateTime($subscription->getCreatedAt()); + $current = new \DateTime(); + $dateDiff = strtotime($current->format('Y-m-d')) - strtotime($createdAt->format('Y-m-d')); + $remainigDays = floor($dateDiff/(60*60*24)); + $bufferTime = $this->recurringhelper->getRecurringOrderBufferTime(); + + return ($bufferTime >= $remainigDays) ? true : false; + } + + /** + * Check Order already Canceled + * + * @param Subscription $subscription + * @return bool + */ + public function getNotAlreadyCanceled(SubscriptionOrder $subscription) + { + $orderId = $subscription->getOriginalOrderId(); + $order = $this->subscriptionOrder->getOrderbyOriginalId($orderId); + + return ($order->getStatus() == 'canceled') ? true : false; + } + + /** + * Get order id column value + * + * @param Subscription $subscription + * @return string + */ + public function getOrderIdLabel($subscription) + { + $OrderIncrementId = ''; + if ($subscription->getOriginalOrderId()) { + $OrderIncrementId = $this->getOrgIncrementOrderId($subscription->getOriginalOrderId()); + return sprintf( + '%s', + $this->getUrl('sales/order/view', ['order_id' => $subscription->getOriginalOrderId()]), + $this->escapeHtml($OrderIncrementId) + ); + } + return $this->escapeHtml($OrderIncrementId); + } + + /** + * Retrieve OrgIncrement Order Id + * + * @param string $orderId + * @return string + */ + public function getOrgIncrementOrderId($orderId) + { + $order = $this->orderRepository->get($orderId); + return $order->getIncrementId(); + } + /** + * Prepare layout (initialise pagination block) + * + * @return $this + */ + protected function _prepareLayout() + { + parent::_prepareLayout(); + $this->pageConfig->getTitle()->set('All Recurring Order'); + + $pagination = $this->getLayout() + ->createBlock( + \Magento\Theme\Block\Html\Pager::class, + 'subscriptions_order_pagination' + ) + ->setCollection($this->getsubscriptionOrderCollection()) + ->setPath('worldpay/recurring_order/view'); + $this->setChild('pagination', $pagination); + return $this; + } + /** + * Show Pagination Html + * + * @return string + */ + public function getPaginationHtml() + { + return $this->getChildHtml('pagination'); + } +} diff --git a/Block/SubscriptionSkipOrders.php b/Block/SubscriptionSkipOrders.php new file mode 100644 index 0000000..da6fbac --- /dev/null +++ b/Block/SubscriptionSkipOrders.php @@ -0,0 +1,295 @@ +skipSubscriptionOrder = $skipSubscriptionOrder; + $this->recurringhelper = $recurringhelper; + $this->orderRepository = $orderRepository; + $this->urlInterface = $urlInterface; + parent::__construct($context, $data); + } + + /** + * Retrieve Subscription Order Collection + * + * @return mixed + */ + public function getskipSubscriptionOrderCollection() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + $timeFilter = $this->getRequest()->getParam('timeFilter'); + $timeFilterby = $this->skipSubscriptionOrder + ->getFilterDate($timeFilter=null); + $subscriptionOrderCollection = $this->skipSubscriptionOrder + ->getskipSubscriptionOrderCollection($subscriptionId, $timeFilterby); + + return $subscriptionOrderCollection; + } + + /** + * My Account Labels + * + * @param string $labelCode + * @return $this + */ + + public function getMyAccountLabels($labelCode) + { + return $this->recurringhelper->getAccountLabelbyCode($labelCode); + } + + /** + * Get subscription plan interval label + * + * @param string $interval + * @return string + */ + public function getSubscriptionIntervalLabel($interval) + { + return $this->recurringhelper->getPlanIntervalLabel($interval); + } + + /** + * Specific Exception + * + * @param string $exceptioncode + * @return string + */ + + public function getMyAccountSpecificException($exceptioncode) + { + return $this->recurringhelper->getMyAccountExceptions($exceptioncode); + } + + /** + * Return Current Url + * + * @return string + */ + public function getCurrentURL() + { + return $this->urlInterface->getCurrentUrl(); + } + + /** + * Return Order Filter URL + * + * @param string $timeVal + * @return string + */ + public function getOrderFilterURL($timeVal) + { + $link = $this->getHistoryPageURL(); + $paramsData = $this->getRequest()->getParams(); + if (count($paramsData)) { + $link .= "?"; + /* Page Number */ + if (isset($paramsData['p'])) { + $link .= "p=" . $paramsData['p'] . "&"; + } + /* Page Limit Number */ + if (isset($paramsData['limit'])) { + $link .= "limit=" . $paramsData['limit'] . "&"; + } + /* Time period */ + $link .= "timeFilter=" . $timeVal . "&"; + } + + $link = rtrim(rtrim($link, "&"), "?"); + return $link; + } + + /** + * Return history URL for Filter + * + * @return string + */ + public function getHistoryPageURL() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + return $this->_urlBuilder->getUrl( + 'worldpay/recurring_order/skiporders/', + ['_secure' => true, 'subscription_id' => $subscriptionId] + ); + } + /** + * Return Selected Option in Filter + * + * @param string $filter + * @return bool + */ + public function checkSelectedFilter($filter) + { + $selectedFilter = $this->getRequest()->getParam('timeFilter'); + if ($filter == $selectedFilter) { + return true; + } + return false; + } + + /** + * Return Complete Orderl Url + * + * @return string + */ + public function getCompleteOrderlUrl() + { + $subscriptionId = $this->getRequest()->getParam('subscription_id'); + return $this->_urlBuilder->getUrl( + 'worldpay/recurring_order/view/', + ['_secure' => true, 'subscription_id' => $subscriptionId] + ); + } + + /** + * Check Order Shipment + * + * @param Subscription $subscription + * @return bool + */ + public function checkOrderShipment(SubscriptionOrder $subscription) + { + $orderId = $subscription->getOriginalOrderId(); + $order = $this->skipSubscriptionOrder->getOrderbyOriginalId($orderId); + + return $order->hasShipments(); + } + + /** + * Check Order Buffer Time + * + * @param Subscription $subscription + * @return bool + */ + public function checkOrderBufferTime(SubscriptionOrder $subscription) + { + $createdAt = new \DateTime($subscription->getCreatedAt()); + $current = new \DateTime(); + $dateDiff = strtotime($current->format('Y-m-d')) - strtotime($createdAt->format('Y-m-d')); + $remainigDays = floor($dateDiff/(60*60*24)); + $bufferTime = $this->recurringhelper->getRecurringOrderBufferTime(); + + return ($bufferTime >= $remainigDays) ? true : false; + } + + /** + * Check Order already Canceled + * + * @param Subscription $subscription + * @return bool + */ + public function getNotAlreadyCanceled(SubscriptionOrder $subscription) + { + $orderId = $subscription->getOriginalOrderId(); + $order = $this->skipSubscriptionOrder->getOrderbyOriginalId($orderId); + + return ($order->getStatus() == 'canceled') ? true : false; + } + + /** + * Get order id column value + * + * @param Subscription $subscription + * @return string + */ + public function getOrderIdLabel($subscription) + { + $OrderIncrementId = ''; + if ($subscription->getOriginalOrderId()) { + $OrderIncrementId = $this->getOrgIncrementOrderId($subscription->getOriginalOrderId()); + return sprintf( + '%s', + $this->getUrl('sales/order/view', ['order_id' => $subscription->getOriginalOrderId()]), + $this->escapeHtml($OrderIncrementId) + ); + } + return $this->escapeHtml($OrderIncrementId); + } + + /** + * Retrieve OrgIncrement Order Id + * + * @param string $orderId + * @return string + */ + public function getOrgIncrementOrderId($orderId) + { + $order = $this->orderRepository->get($orderId); + return $order->getIncrementId(); + } + /** + * Prepare layout (initialise pagination block) + * + * @return $this + */ + protected function _prepareLayout() + { + parent::_prepareLayout(); + $this->pageConfig->getTitle()->set('All Recurring Order'); + + $pagination = $this->getLayout() + ->createBlock( + \Magento\Theme\Block\Html\Pager::class, + 'subscriptions_order_pagination' + ) + ->setCollection($this->getskipSubscriptionOrderCollection()) + ->setPath('worldpay/recurring_order/skiporders'); + $this->setChild('pagination', $pagination); + return $this; + } + /** + * Show Pagination Html + * + * @return string + */ + public function getPaginationHtml() + { + return $this->getChildHtml('pagination'); + } +} diff --git a/Block/SubscriptionsLink.php b/Block/SubscriptionsLink.php index 3445c49..4a9acfe 100644 --- a/Block/SubscriptionsLink.php +++ b/Block/SubscriptionsLink.php @@ -15,11 +15,15 @@ use Sapient\Worldpay\Helper\Recurring; use Sapient\Worldpay\Helper\Data; +/** + * Description of SubscriptionsLink + * + */ class SubscriptionsLink extends \Magento\Framework\View\Element\Html\Link\Current { /** - * @var _scopeConfig + * @var $_scopeConfig */ protected $_scopeConfig = null; /** diff --git a/Block/Wallets.php b/Block/Wallets.php index 2b308ba..b360cd9 100644 --- a/Block/Wallets.php +++ b/Block/Wallets.php @@ -179,21 +179,21 @@ public function getJsLayout(): string ['isgooglepayenabledonpdp'] = $this->isGooglePayEnableonPdp(); $this->jsLayout['components']['wp-wallet-pay']['config']['googlepayOptions'] - ['gpaybutton_color'] = $this->worldpayHelper->getGpayButtonColor(); + ['gpaybutton_color'] = $this->worldpayHelper->getGpayButtonColorPdp(); $this->jsLayout['components']['wp-wallet-pay']['config']['googlepayOptions'] - ['gpaybutton_type'] = $this->worldpayHelper->getGpayButtonType(); + ['gpaybutton_type'] = $this->worldpayHelper->getGpayButtonTypePdp(); $this->jsLayout['components']['wp-wallet-pay']['config']['googlepayOptions'] - ['gpaybutton_locale'] = $this->worldpayHelper->getGpayButtonLocale(); + ['gpaybutton_locale'] = $this->worldpayHelper->getGpayButtonLocalePdp(); $this->jsLayout['components']['wp-wallet-pay']['config']['purchaseUrl'] = $purchaseUrl; $this->jsLayout['components']['wp-wallet-pay']['config'] - ['sessionId'] = $this->session->getSessionId(); + ['sessionId'] = $this->session->getSessionId(); $this->jsLayout['components']['wp-wallet-pay']['config'] - ['store_code'] = $this->getCurrentStoreCode(); + ['store_code'] = $this->getCurrentStoreCode(); $this->jsLayout['components']['wp-wallet-pay']['config'] - ['default_country_code'] = $this->worldpayHelper->getStoreDefaultCountry(); + ['default_country_code'] = $this->worldpayHelper->getStoreDefaultCountry(); $this->jsLayout['components']['wp-wallet-pay']['config'] ['countriesHtml'] = $this->getCountriesHtml(null, 'country_id', 'country', 'Country'); @@ -215,16 +215,16 @@ public function getJsLayout(): string ['applepayOptions']['isApplePayEnableonPdp'] = $this->isApplePayEnableonPdp(); $this->jsLayout['components']['wp-wallet-pay']['config'] - ['applepayOptions']['applePayPopUpButtonText'] = $this->getApplePayPopupPlaceOrderText(); + ['applepayOptions']['applePayPopUpButtonText'] = $this->getApplePayPopupPlaceOrderTextPdp(); $this->jsLayout['components']['wp-wallet-pay']['config'] - ['applepayOptions']['applePayButtonColor'] = $this->worldpayHelper->getApplePayButtonColor(); + ['applepayOptions']['applePayButtonColor'] = $this->worldpayHelper->getApplePayButtonColorPdp(); $this->jsLayout['components']['wp-wallet-pay']['config'] - ['applepayOptions']['applePayButtonType'] = $this->worldpayHelper->getApplePayButtonType(); + ['applepayOptions']['applePayButtonType'] = $this->worldpayHelper->getApplePayButtonTypePdp(); $this->jsLayout['components']['wp-wallet-pay']['config'] - ['applepayOptions']['applePayButtonLocale'] = $this->worldpayHelper->getApplePayButtonLocale(); + ['applepayOptions']['applePayButtonLocale'] = $this->worldpayHelper->getApplePayButtonLocalePdp(); return parent::getJsLayout(); } @@ -342,11 +342,11 @@ public function isApplePayEnableonPdp() } /** - * Get Apple pay button popup text + * Get Apple pay button popup text for PDP */ - public function getApplePayPopupPlaceOrderText() + public function getApplePayPopupPlaceOrderTextPdp() { - return $this->worldpayHelper->getApplePayPopupPlaceOrderText(); + return $this->worldpayHelper->getApplePayPopupPlaceOrderTextPdp(); } /** * Check if subscription is enabled diff --git a/Block/Webpayment.php b/Block/Webpayment.php index 321ccbb..f919db8 100644 --- a/Block/Webpayment.php +++ b/Block/Webpayment.php @@ -94,11 +94,6 @@ class Webpayment extends Template */ protected $httpRequest; - /** - * @var \Magento\Customer\Helper\Session\CurrentCustomerAddress - */ - protected $currentCustomerAddress; - /** * Webpayment constructor * @@ -115,7 +110,6 @@ class Webpayment extends Template * @param SerializerInterface $serializer * @param Magento\Framework\View\Asset\Repository $assetRepo * @param Magento\Framework\App\Request\Http $httpRequest - * @param Magento\Customer\Helper\Session\CurrentCustomerAddress $currentCustomerAddress * @param array $data */ public function __construct( @@ -132,13 +126,11 @@ public function __construct( SerializerInterface $serializer, \Magento\Framework\View\Asset\Repository $assetRepo, \Magento\Framework\App\Request\Http $httpRequest, - \Magento\Customer\Helper\Session\CurrentCustomerAddress $currentCustomerAddress, array $data = [] ) { $this->_helper = $helper; $this->_cart = $cart; - $this->currentCustomerAddress = $currentCustomerAddress; parent::__construct( $context, $data @@ -209,6 +201,7 @@ public function getShippingRate() { $quote = $this->_cart->getTotalsCache(); $getShippingRate = $quote['shipping']->getData('value'); + return $getShippingRate; } /** @@ -589,34 +582,4 @@ public function isCheckoutCartPage() } return false; } - /** - * Array for Billing Address - * - * @param AddressInterface $address - * @return string - */ - public function getDefaultBillingAddress() - { - $response = []; - $response['status'] = false; - if (!$this->_customerSession->isLoggedIn()) { - $response['message'] = __('Please log in to continue.'); - return json_encode($response); - } - $address = $this->currentCustomerAddress->getDefaultBillingAddress(); - if ($address) { - $response['status'] = true; - $response['addressLine'] = $address->getStreet(); - $response['city'] = $address->getCity(); - $response['country'] = $address->getCountryId(); - $response['phone'] = $address->getTelephone(); - $response['postalCode'] = $address->getPostcode(); - $response['recipient'] = $address->getFirstname().' '.$address->getLastname(); - $response['region'] = $address->getRegion()->getRegion(); - $response['region_id'] = $address->getRegionId(); - } else { - $response['message'] = __('You have not set a default billing address.'); - } - return json_encode($response); - } } diff --git a/Controller/Adminhtml/Cancel/Index.php b/Controller/Adminhtml/Cancel/Index.php index 106a7e0..0b9565c 100644 --- a/Controller/Adminhtml/Cancel/Index.php +++ b/Controller/Adminhtml/Cancel/Index.php @@ -10,6 +10,10 @@ use Magento\Framework\Controller\Result\JsonFactory; use Exception; +/** + * Description of Index + * + */ class Index extends \Magento\Backend\App\Action { /** diff --git a/Controller/Adminhtml/Recurring/Plan/Save.php b/Controller/Adminhtml/Recurring/Plan/Save.php index 816875b..199f557 100644 --- a/Controller/Adminhtml/Recurring/Plan/Save.php +++ b/Controller/Adminhtml/Recurring/Plan/Save.php @@ -33,6 +33,11 @@ class Save extends \Sapient\Worldpay\Controller\Adminhtml\Recurring\Plan */ private $uri; + /** + * @var RedirectInterface + */ + protected $redirect; + /** * Constructor * @@ -43,6 +48,7 @@ class Save extends \Sapient\Worldpay\Controller\Adminhtml\Recurring\Plan * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Sapient\Worldpay\Helper\GeneralException $helper * @param \Laminas\Uri\Uri $uri + * @param \Magento\Framework\App\Response\RedirectInterface $redirect */ public function __construct( \Magento\Backend\App\Action\Context $context, @@ -51,7 +57,8 @@ public function __construct( \Magento\Framework\Locale\FormatInterface $localeFormat, \Magento\Store\Model\StoreManagerInterface $storeManager, \Sapient\Worldpay\Helper\GeneralException $helper, - \Laminas\Uri\Uri $uri + \Laminas\Uri\Uri $uri, + \Magento\Framework\App\Response\RedirectInterface $redirect ) { parent::__construct($context, $planFactory); $this->planGridDataProvider = $planGridDataProvider; @@ -59,6 +66,7 @@ public function __construct( $this->helper = $helper; $this->storeManager = $storeManager; $this->uri = $uri; + $this->redirect = $redirect; } /** @@ -71,8 +79,8 @@ public function execute() $data = $this->getRequest()->getPostValue(); //$productId = $this->getRequest()->getParam('product_id'); - //$url = parse_url($this->_redirect->getRefererUrl()); - $parsedUrl = $this->uri->parse($this->_redirect->getRefererUrl()); + //$url = parse_url($this->redirect->getRefererUrl()); + $parsedUrl = $this->uri->parse($this->redirect->getRefererUrl()); $path_parts=explode('/', $parsedUrl->getPath()); if (in_array('id', $path_parts)) { $key = array_search('id', $path_parts); diff --git a/Controller/Applepay/Index.php b/Controller/Applepay/Index.php index 3bc17a2..52644ee 100644 --- a/Controller/Applepay/Index.php +++ b/Controller/Applepay/Index.php @@ -14,6 +14,7 @@ class Index extends \Magento\Framework\App\Action\Action { + public const APPLEPAY_MS_CONFIG_PATH = "worldpay/multishipping/ms_wallets_config/ms_samsung_pay_wallets_config/"; /** * @var fileDriver */ @@ -111,7 +112,35 @@ public function execute() getValue('worldpay/wallets_config/apple_pay_wallets_config/merchant_name', $storeScope); $domainName = $this->scopeConfig-> getValue('worldpay/wallets_config/apple_pay_wallets_config/domain_name', $storeScope); - + /** Multishipping Apple Pay Configuration */ + if ($this->cart->getQuote()->getIsMultiShipping()) { + $msCertificateKey = $this->scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/ms_certification_key', + $storeScope + ); + $msCertificateCrt = $this->scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/ms_certification_crt', + $storeScope + ); + $msCertificationPassword = $this->scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/ms_certification_password', + $storeScope + ); + $msMerchantName = $this->scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/ms_merchant_name', + $storeScope + ); + $msDomainName = $this->scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/ms_domain_name', + $storeScope + ); + $certificateKey = !empty($msCertificateKey) ? $msCertificateKey : $certificateKey; + $certificateCrt = !empty($msCertificateCrt) ? $msCertificateCrt : $certificateCrt; + $certificationPassword = + !empty($msCertificationPassword) ? $msCertificationPassword : $certificationPassword; + $merchantName = !empty($msMerchantName) ? $msMerchantName : $merchantName; + $domainName = !empty($msDomainName) ? $msDomainName : $domainName; + } $validation_url = $this->request->getParam('u'); if ($validation_url == 'getTotal') { diff --git a/Controller/Paybylink/Multishipping/Orderplaced.php b/Controller/Paybylink/Multishipping/Orderplaced.php index fce0112..ad175ec 100644 --- a/Controller/Paybylink/Multishipping/Orderplaced.php +++ b/Controller/Paybylink/Multishipping/Orderplaced.php @@ -10,6 +10,7 @@ use Magento\Framework\App\Action\Context; use Magento\Multishipping\Model\Checkout\Type\Multishipping; use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; +use Magento\Framework\View\Result\PageFactory; use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; /** @@ -27,18 +28,26 @@ class Orderplaced extends Action implements HttpGetActionInterface */ private $multishipping; + /** + * @var $resultPageFactory + */ + protected $resultPageFactory; + /** * @param Context $context * @param State $state * @param Multishipping $multishipping + * @param PageFactory $resultPageFactory */ public function __construct( Context $context, State $state, - Multishipping $multishipping + Multishipping $multishipping, + PageFactory $resultPageFactory ) { $this->state = $state; $this->multishipping = $multishipping; + $this->resultPageFactory = $resultPageFactory; parent::__construct($context); } /** @@ -51,9 +60,10 @@ public function execute() if (!$this->state->getCompleteStep(State::STEP_OVERVIEW)) { return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } - $this->_view->loadLayout(); + $resultPage = $this->resultPageFactory->create(); $ids = $this->multishipping->getOrderIds(); $this->_eventManager->dispatch('multishipping_checkout_controller_success_action', ['order_ids' => $ids]); - $this->_view->renderLayout(); + + return $resultPage; } } diff --git a/Controller/Paybylink/Multishipping/Success.php b/Controller/Paybylink/Multishipping/Success.php index 5d38ea1..29fa60c 100644 --- a/Controller/Paybylink/Multishipping/Success.php +++ b/Controller/Paybylink/Multishipping/Success.php @@ -10,6 +10,7 @@ use Magento\Framework\App\Action\Context; use Magento\Multishipping\Model\Checkout\Type\Multishipping; use Magento\Multishipping\Model\Checkout\Type\Multishipping\State; +use Magento\Framework\View\Result\PageFactory; use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface; /** @@ -38,6 +39,11 @@ class Success extends Action implements HttpGetActionInterface * @var \Magento\Quote\Api\CartRepositoryInterface */ private $quoteRepository; + + /** + * @var $resultPageFactory + */ + protected $resultPageFactory; /** * @param Context $context @@ -46,6 +52,7 @@ class Success extends Action implements HttpGetActionInterface * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository * @param \Sapient\Worldpay\Model\ResourceModel\Multishipping\Order\Collection $wpMultishippingCollection * @param \Magento\Sales\Model\Order $order + * @param PageFactory $resultPageFactory */ public function __construct( Context $context, @@ -53,13 +60,15 @@ public function __construct( Multishipping $multishipping, \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, \Sapient\Worldpay\Model\ResourceModel\Multishipping\Order\Collection $wpMultishippingCollection, - \Magento\Sales\Model\Order $order + \Magento\Sales\Model\Order $order, + PageFactory $resultPageFactory ) { $this->state = $state; $this->multishipping = $multishipping; $this->order = $order; $this->wpMultishippingCollection = $wpMultishippingCollection; $this->quoteRepository = $quoteRepository; + $this->resultPageFactory = $resultPageFactory; parent::__construct($context); } /** @@ -84,11 +93,10 @@ public function execute() $this->messageManager->addNotice("Multishipping orders not found"); return $this->resultRedirectFactory->create()->setPath('checkout/cart', ['_current' => true]); } - $this->_view->loadLayout(); + $resultPage = $this->resultPageFactory->create(); $ids = $multiShippingOrders; $this->_eventManager->dispatch('multishipping_checkout_controller_success_action', ['order_ids' => $ids]); - $this->_view->renderLayout(); - return; + return $resultPage; } $this->messageManager->addNotice("Order not found"); return $this->resultRedirectFactory->create()->setPath('checkout/cart', ['_current' => true]); diff --git a/Controller/Payment/Pay.php b/Controller/Payment/Pay.php index 589bf29..08aec80 100644 --- a/Controller/Payment/Pay.php +++ b/Controller/Payment/Pay.php @@ -166,7 +166,7 @@ public function execute() $this->jsonGenerator($paymentManifestJson, self::PAYMENT_MANIFEST_JSON); $this->jsonGenerator($paymentAppManifestjson, self::MANIFEST_JSON); - $result->setContents(''); + $result->setContents('Pay with Chromepay'); $result->setHeader('link', '<'.$mediPathPaymentManifest.'>; rel="payment-method-manifest"'); return $result; } diff --git a/Controller/Recurring/Edit.php b/Controller/Recurring/Edit.php index f016b03..b28e2e7 100644 --- a/Controller/Recurring/Edit.php +++ b/Controller/Recurring/Edit.php @@ -1,6 +1,6 @@ customerSession = $customerSession; parent::__construct($context); @@ -63,6 +71,7 @@ public function __construct( $this->subscriptionFactory = $subscriptionFactory; $this->helper = $helper; $this->customerUrl = $customerUrl; + $this->registry = $registry; } /** @@ -113,6 +122,8 @@ public function execute() return $this->resultRedirectFactory->create()->setPath('*/*'); } + $this->registry->register('current_subscription_order', $subscription); + /** @var \Magento\Framework\View\Element\Html\Links $navigationBlock */ //$resultPage->getConfig()->getTitle()->set(__('Update Saved Card')); $navigationBlock = $resultPage->getLayout()->getBlock('customer_account_navigation'); diff --git a/Controller/Recurring/Order/Cancel.php b/Controller/Recurring/Order/Cancel.php new file mode 100644 index 0000000..948440b --- /dev/null +++ b/Controller/Recurring/Order/Cancel.php @@ -0,0 +1,121 @@ +customerSession = $customerSession; + $this->exceptionhelper = $exceptionhelper; + $this->customerUrl = $customerUrl; + $this->subscriptionOrder = $subscriptionOrder; + $this->subscriptionFactory = $subscriptionFactory; + } + + /** + * Check customer authentication + * + * @param RequestInterface $request + * @return \Magento\Framework\App\ResponseInterface + */ + public function dispatch(RequestInterface $request) + { + $loginUrl = $this->customerUrl->getLoginUrl(); + if (!$this->customerSession->authenticate($loginUrl)) { + $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); + } + return parent::dispatch($request); + } + + /** + * Execute + * + * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface + * @throws \Magento\Framework\Exception\NotFoundException + */ + public function execute() + { + $redirectResult = $this->resultRedirectFactory->create(); + $orderId = $this->getRequest()->getParam('id'); + $order = $this->subscriptionOrder->getOrderbyOriginalId($orderId); + $subscription = $this->subscriptionFactory + ->create() + ->load($order->getWorldpaySubscriptionId()); + if ($subscription->getCustomerId() != $this->customerSession->getCustomerId()) { + $redirectResult->setPath('noroute'); + $this->messageManager + ->addErrorMessage(__('Order not found.')); + return $redirectResult; + } + try { + $order->cancel()->save(); + $redirectResult->setPath( + 'sales/order/view/order_id/'.$orderId, + ['_secure' => true] + ); + $this->messageManager + ->addSuccessMessage(__($this->exceptionhelper->getConfigValue('MCAM14'))); + } catch (\Exception $e) { + $redirectResult->setPath( + 'worldpay/recurring_order/'.$subscription->getSubscriptionId(), + ['_secure' => true] + ); + $this->messageManager->addErrorMessage(__($this->exceptionhelper->getConfigValue('MCAM18'))); + } + return $redirectResult; + } +} diff --git a/Controller/Recurring/Order/Skiporders.php b/Controller/Recurring/Order/Skiporders.php new file mode 100644 index 0000000..57359fe --- /dev/null +++ b/Controller/Recurring/Order/Skiporders.php @@ -0,0 +1,68 @@ +resultPageFactory = $resultPageFactory; + $this->skipSubscriptionOrderFactory = $skipSubscriptionOrderFactory; + $this->customerSession = $customerSession; + $this->worldpayhelper = $worldpayhelper; + } + + /** + * Excute and redirect on result page + */ + public function execute() + { + $resultRedirect = $this->resultRedirectFactory->create(); + if (!$this->customerSession->isLoggedIn()) { + $resultRedirect->setPath('customer/account/login'); + return $resultRedirect; + } + return $this->resultPageFactory->create(); + } +} \ No newline at end of file diff --git a/Controller/Recurring/Order/View.php b/Controller/Recurring/Order/View.php new file mode 100644 index 0000000..5e51feb --- /dev/null +++ b/Controller/Recurring/Order/View.php @@ -0,0 +1,60 @@ +resultPageFactory = $resultPageFactory; + $this->SubscriptionOrderFactory = $SubscriptionOrderFactory; + $this->customerSession = $customerSession; + } + + /** + * Excute and redirect on result page + */ + public function execute() + { + $resultRedirect = $this->resultRedirectFactory->create(); + if (!$this->customerSession->isLoggedIn()) { + $resultRedirect->setPath('customer/account/login'); + return $resultRedirect; + } + return $this->resultPageFactory->create(); + } +} diff --git a/Controller/Redirectresult/Redirect.php b/Controller/Redirectresult/Redirect.php index f61d4ce..32608ca 100644 --- a/Controller/Redirectresult/Redirect.php +++ b/Controller/Redirectresult/Redirect.php @@ -29,6 +29,10 @@ class Redirect extends \Magento\Framework\App\Action\Action */ protected $mageOrder; + /** + * @var \Sapient\Worldpay\Helper\Data + */ + protected $worldpayHelper; /** * Constructor * @@ -36,16 +40,19 @@ class Redirect extends \Magento\Framework\App\Action\Action * @param PageFactory $pageFactory * @param \Magento\Checkout\Model\Session $checkoutsession * @param \Magento\Sales\Model\Order $mageOrder + * @param \Sapient\Worldpay\Helper\Data $worldpayHelper */ public function __construct( Context $context, PageFactory $pageFactory, \Magento\Checkout\Model\Session $checkoutsession, - \Magento\Sales\Model\Order $mageOrder + \Magento\Sales\Model\Order $mageOrder, + \Sapient\Worldpay\Helper\Data $worldpayHelper ) { $this->pageFactory = $pageFactory; $this->checkoutsession = $checkoutsession; $this->mageOrder = $mageOrder; + $this->worldpayHelper = $worldpayHelper; return parent::__construct($context); } /** @@ -55,10 +62,15 @@ public function __construct( */ public function execute() { + $resultRedirect = $this->resultRedirectFactory->create(); + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } $redirecturl = $this->checkoutsession->getWpRedirecturl(); $this->checkoutsession->unsWpRedirecturl(); $this->checkoutsession->unsIframePay(); $this->checkoutsession->unsHppOrderCode(); - return $this->resultRedirectFactory->create()->setUrl($redirecturl); + return $resultRedirect->setUrl($redirecturl); } } diff --git a/Controller/Redirectresult/Success.php b/Controller/Redirectresult/Success.php index b7c938a..0f330ba 100644 --- a/Controller/Redirectresult/Success.php +++ b/Controller/Redirectresult/Success.php @@ -26,6 +26,11 @@ class Success extends \Magento\Framework\App\Action\Action * @var \Sapient\Worldpay\Logger\WorldpayLogger */ protected $wplogger; + + /** + * @var \Sapient\Worldpay\Helper\Data + */ + protected $worldpayHelper; /** * Constructor * @@ -33,16 +38,19 @@ class Success extends \Magento\Framework\App\Action\Action * @param PageFactory $pageFactory * @param \Sapient\Worldpay\Model\Order\Service $orderservice * @param \Sapient\Worldpay\Logger\WorldpayLogger $wplogger + * @param \Sapient\Worldpay\Helper\Data $worldpayHelper */ public function __construct( Context $context, PageFactory $pageFactory, \Sapient\Worldpay\Model\Order\Service $orderservice, - \Sapient\Worldpay\Logger\WorldpayLogger $wplogger + \Sapient\Worldpay\Logger\WorldpayLogger $wplogger, + \Sapient\Worldpay\Helper\Data $worldpayHelper, ) { $this->pageFactory = $pageFactory; $this->orderservice = $orderservice; $this->wplogger = $wplogger; + $this->worldpayHelper = $worldpayHelper; return parent::__construct($context); } /** @@ -52,6 +60,11 @@ public function __construct( */ public function execute() { + $resultRedirect = $this->resultRedirectFactory->create(); + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } $this->wplogger->info('worldpay returned success url'); $this->orderservice->redirectOrderSuccess(); $order = $this->orderservice->getAuthorisedOrder(); @@ -59,8 +72,8 @@ public function execute() $this->orderservice->removeAuthorisedOrder(); if ($worldpaypayment->getIsMultishippingOrder()) { $url = 'multishipping/checkout/success'; - return $this->resultRedirectFactory->create()->setPath($url, ['_current' => true]); + return $resultRedirect->setPath($url, ['_current' => true]); } - return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success', ['_current' => true]); + return $resultRedirect->setPath('checkout/onepage/success', ['_current' => true]); } } diff --git a/Controller/Samsungpay/CallBack.php b/Controller/Samsungpay/CallBack.php index e4cc68b..9e63824 100644 --- a/Controller/Samsungpay/CallBack.php +++ b/Controller/Samsungpay/CallBack.php @@ -1,6 +1,5 @@ resultRedirectFactory->create(); + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } $order = $this->_checkoutSession->getLastRealOrder(); if (empty($order->getId())) { $order = $this->checkForMultishippingOrder(); @@ -175,6 +180,24 @@ public function execute() $environmentMode = $this->scopeConfig-> getValue('worldpay/general_config/environment_mode', $storeScope); + $quoteId = $order->getQuoteId(); + $quote = $this->quoteFactory->create()->load($quoteId); + /** Multishipping Samsung Pay Configuration */ + if ($quote->getIsMultiShipping()) { + + $msServiceId = $this->scopeConfig-> + getValue(self::SAMSUMG_CONFIG_PATH.'ms_service_id', $storeScope); + + $msOrderDescription = $this->scopeConfig-> + getValue(self::SAMSUMG_CONFIG_PATH.'ms_samsung_order_description', $storeScope); + + $msMerchantCode = $this->scopeConfig-> + getValue('worldpay/multishipping/ms_merchant_code', $storeScope); + + $serviceId = !empty($msServiceId) ? $msServiceId : $serviceId; + $orderDescription = !empty($msOrderDescription) ? $msOrderDescription : $orderDescription; + $merchantCode = !empty($msMerchantCode) ? $msMerchantCode : $merchantCode; + } if ($environmentMode == 'Test Mode') { $serviceUrl = "https://api-ops.stg.mpay.samsung.com/ops/v1/transactions/paymentCredentials/" . $refId . '?serviceId=' . $serviceId; @@ -224,8 +247,6 @@ public function execute() $exponent = $this->worldpayHelper->getCurrencyExponent($currencyCode); $grandTotal = $orderDetails['grand_total']; if ($isMultishipping) { - $quoteId = $order->getQuoteId(); - $quote = $this->quoteFactory->create()->load($quoteId); $grandTotal = $quote->getGrandTotal(); } $samsungPayOrderParams = []; @@ -245,7 +266,6 @@ public function execute() $lastEvent = $paymentService->xpath('//lastEvent'); if ($lastEvent[0] == 'AUTHORISED') { - $resultRedirect = $this->resultRedirectFactory->create(); if ($isMultishipping) { $this->_checkoutSession->unsMultishippingOrderCode(); $resultRedirect->setPath('worldpay/wallets/multishippingsuccess'); @@ -255,7 +275,6 @@ public function execute() $this->_checkoutSession->unsauthenticatedOrderId(); return $resultRedirect; } else { - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('worldpay/Redirectresult/cancel'); $this->orderManagement->cancel($orderId); $this->_checkoutSession->restoreQuote(); @@ -266,8 +285,6 @@ public function execute() $this->wplogger->error($e->getMessage()); } } else { - $quoteId = $order->getQuoteId(); - $quote = $this->quoteFactory->create()->load($quoteId); if ($quote->getIsMultiShipping()) { $this->multishipping->cancelMultishippingOrders($order); $this->_checkoutSession->unsMultishippingOrderCode(); @@ -279,7 +296,6 @@ public function execute() $this->orderManagement->cancel($orderId); $this->_checkoutSession->restoreQuote(); } - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('worldpay/Redirectresult/cancel'); return $resultRedirect; diff --git a/Controller/Samsungpay/Index.php b/Controller/Samsungpay/Index.php index 5c46618..e34536c 100644 --- a/Controller/Samsungpay/Index.php +++ b/Controller/Samsungpay/Index.php @@ -1,5 +1,5 @@ resultRedirectFactory->create(); + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $serviceId = $this->scopeConfig-> @@ -128,6 +134,8 @@ public function execute() $environmentMode = $this->scopeConfig-> getValue('worldpay/general_config/environment_mode', $storeScope); + $quoteId = $this->request->getParam('quoteId'); + if ($environmentMode == 'Test Mode') { $serviceUrl = "https://api-ops.stg.mpay.samsung.com/ops/v1/transactions"; } else { @@ -136,18 +144,34 @@ public function execute() $baseUrl = $this->_storeManager->getStore()->getBaseUrl(); - $quoteId = $this->request->getParam('quoteId'); if (!$this->customerSession->isLoggedIn()) { $quoteIdMask = $this->quoteIdMaskFactory->create(); $quoteIdMask->load($quoteId, 'masked_id'); $quoteId = $quoteIdMask->getQuoteId(); } + $quote = $this->quoteFactory->create()->load($quoteId); $quoteData = $quote->getData(); $currency = $quote->getQuoteCurrencyCode(); $grandTotal = $quote->getGrandTotal(); $postFields = []; + /** Multishipping Samsung Pay Configuration */ + if ($quote->getIsMultiShipping()) { + $msServiceId = $this->scopeConfig-> + getValue(self::SAMSUMG_CONFIG_PATH.'ms_service_id', $storeScope); + + $msShopName = $this->scopeConfig-> + getValue(self::SAMSUMG_CONFIG_PATH.'ms_samsung_merchant_shop_name', $storeScope); + + $msShopUrl = $this->scopeConfig-> + getValue(self::SAMSUMG_CONFIG_PATH.'ms_samsung_merchant_shop_url', $storeScope); + + $serviceId = !empty($msServiceId) ? $msServiceId : $serviceId; + $shopName = !empty($msShopName) ? $msShopName : $shopName; + $shopUrl = !empty($msShopUrl) ? $msShopUrl : $shopUrl; + } + $callBack = $baseUrl . 'worldpay/samsungpay/CallBack'; $exponent = $this->worldpayHelper->getCurrencyExponent($currency); $postFields['callback'] = $callBack; diff --git a/Controller/Savedcard/Addnewcard.php b/Controller/Savedcard/Addnewcard.php index 14125c0..4f663cf 100644 --- a/Controller/Savedcard/Addnewcard.php +++ b/Controller/Savedcard/Addnewcard.php @@ -53,11 +53,16 @@ public function __construct( */ public function execute() { + $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->customerSession->isLoggedIn()) { - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('customer/account/login'); return $resultRedirect; } + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } + $resultPage = $this->_resultPageFactory->create(); $resultPage->getConfig()->getTitle()->set( $this->worldpayHelper->getAccountLabelbyCode('IAVAC1') ? diff --git a/Controller/Savedcard/Delete.php b/Controller/Savedcard/Delete.php index 8767fc4..e0bad0b 100644 --- a/Controller/Savedcard/Delete.php +++ b/Controller/Savedcard/Delete.php @@ -27,22 +27,25 @@ class Delete extends \Magento\Framework\App\Action\Action * @var \Magento\Customer\Model\Session */ protected $customerSession; + /** * @var helper */ protected $helper; + /** * @var vaultPaymentToken */ protected $vaultPaymentToken; + /** * @var resultRedirect */ protected $resultRedirect; - /** - * @var StoreManagerInterface - */ + /** + * @var StoreManagerInterface + */ protected $_storeManager; /** @@ -75,6 +78,10 @@ class Delete extends \Magento\Framework\App\Action\Action */ protected $paymentTokenManagement; + /** + * @var \Sapient\Worldpay\Helper\Data + */ + protected $worldpayHelper; /** * Constructor * @@ -86,6 +93,7 @@ class Delete extends \Magento\Framework\App\Action\Action * @param \Sapient\Worldpay\Model\Token\Service $tokenService * @param \Sapient\Worldpay\Model\Token\WorldpayToken $worldpayToken * @param \Sapient\Worldpay\Logger\WorldpayLogger $wplogger + * @param \Sapient\Worldpay\Helper\Data $worldpayHelper * @param PaymentTokenRepositoryInterface $tokenRepository * @param PaymentTokenManagement $paymentTokenManagement * @param MyAccountException $helper @@ -101,6 +109,7 @@ public function __construct( \Sapient\Worldpay\Model\Token\Service $tokenService, \Sapient\Worldpay\Model\Token\WorldpayToken $worldpayToken, \Sapient\Worldpay\Logger\WorldpayLogger $wplogger, + \Sapient\Worldpay\Helper\Data $worldpayHelper, PaymentTokenRepositoryInterface $tokenRepository, PaymentTokenManagement $paymentTokenManagement, MyAccountException $helper, @@ -115,6 +124,7 @@ public function __construct( $this->_tokenService = $tokenService; $this->_worldpayToken = $worldpayToken; $this->wplogger = $wplogger; + $this->worldpayHelper = $worldpayHelper; $this->tokenRepository = $tokenRepository; $this->paymentTokenManagement = $paymentTokenManagement; $this->helper = $helper; @@ -137,6 +147,11 @@ public function getStoreId() */ public function execute() { + $resultRedirect = $this->resultRedirectFactory->create(); + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } $id = $this->getRequest()->getParam('id'); if ($id) { try { @@ -174,7 +189,7 @@ public function execute() } } } - $resultRedirect = $this->resultRedirectFactory->create(); + $resultRedirect->setPath('worldpay/savedcard/index'); return $resultRedirect; } diff --git a/Controller/Savedcard/Edit.php b/Controller/Savedcard/Edit.php index f3da1de..34414c9 100644 --- a/Controller/Savedcard/Edit.php +++ b/Controller/Savedcard/Edit.php @@ -63,25 +63,27 @@ public function __construct( */ public function execute() { + $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->customerSession->isLoggedIn()) { - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('customer/account/login'); return $resultRedirect; } + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } $resultPage = $this->_resultPageFactory->create(); $id = $this->getRequest()->getParam('id'); $customerId = $this->customerSession->getCustomer()->getId(); if ($id) { $cardDetails = $this->savecard->create()->load($id); if ($cardDetails->getCustomerId() != $customerId) { - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('404notfound'); return $resultRedirect; } $resultPage->getConfig()->getTitle()->set($this->worldpayHelper->getAccountLabelbyCode('AC7')); return $resultPage; } else { - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('404notfound'); return $resultRedirect; } diff --git a/Controller/Savedcard/Index.php b/Controller/Savedcard/Index.php index 10465ff..576cc7a 100644 --- a/Controller/Savedcard/Index.php +++ b/Controller/Savedcard/Index.php @@ -24,7 +24,7 @@ class Index extends \Magento\Framework\App\Action\Action * @var \Sapient\Worldpay\Helper\Data */ protected $worldpayHelper; - + /** * Constructor * @@ -53,11 +53,16 @@ public function __construct( */ public function execute() { + $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->customerSession->isLoggedIn()) { - $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('customer/account/login'); return $resultRedirect; } + if (!$this->worldpayHelper->isWorldPayEnable()) { + $resultRedirect->setPath('noroute'); + return $resultRedirect; + } + $resultPage = $this->_resultPageFactory->create(); $resultPage->getConfig()->getTitle()->set($this->worldpayHelper->getAccountLabelbyCode('AC29')); return $resultPage; diff --git a/Controller/Skiporder/Index.php b/Controller/Skiporder/Index.php new file mode 100644 index 0000000..ea51a53 --- /dev/null +++ b/Controller/Skiporder/Index.php @@ -0,0 +1,97 @@ +customerSession = $customerSession; + $this->worldpayhelper = $worldpayhelper; + $this->customerUrl = $customerUrl; + $this->skipOrderRepository = $skipOrderRepository; + parent::__construct($context); + } + + /** + * Check customer authentication + * + * @param RequestInterface $request + * @return \Magento\Framework\App\ResponseInterface + */ + public function dispatch(RequestInterface $request) + { + $loginUrl = $this->customerUrl->getLoginUrl(); + if (!$this->customerSession->authenticate($loginUrl)) { + $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); + } + return parent::dispatch($request); + } + + /** + * Display subscriptions bought by customer + * + * @return void + */ + public function execute() + { + if ($this->getRequest()->isAjax()) { + $params = $this->getRequest()->getParams('subscriptionId'); + $isSkipped = $this->skipOrderRepository->updateSkipHistory($params); + $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); + if ($isSkipped) { + $this->messageManager->addSuccess("Order skipped successfully"); + $resultJson->setData(["message" => ("Order skipped successfully"), "suceess" => true]); + } else { + $this->messageManager + ->addNoticeMessage("Someting went wrong. Please try again later."); + $resultJson->setData(["message" => ("Order skipped successfully"), "suceess" => false]); + } + return $resultJson; + } + $resultRedirect = $this->resultRedirectFactory->create(); + $resultRedirect->setPath('404notfound'); + return $resultRedirect; + } +} diff --git a/Cron/RecurringOrders.php b/Cron/RecurringOrders.php index d7add49..73065c1 100644 --- a/Cron/RecurringOrders.php +++ b/Cron/RecurringOrders.php @@ -242,7 +242,8 @@ public function updateRecurringTransOrderId($orderId, $recurringId) public function getRecurringOrderIds() { $curdate = date("Y-m-d"); - $fiveDays = strtotime(date("Y-m-d", strtotime($curdate)) . " +5 day"); + $orderBufferTime = "+".$this->recurringhelper->getRecurringOrderBufferTime()." day"; + $fiveDays = strtotime(date("Y-m-d", strtotime($curdate)) . " ".$orderBufferTime); $cronDate = date('Y-m-d', $fiveDays); $result = $this->transactionCollectionFactory->getCollection() ->addFieldToFilter('status', ['eq' => 'active']) diff --git a/Cron/RecurringOrdersEmail.php b/Cron/RecurringOrdersEmail.php new file mode 100644 index 0000000..ec1cce9 --- /dev/null +++ b/Cron/RecurringOrdersEmail.php @@ -0,0 +1,234 @@ +_logger = $wplogger; + $this->subscriptionCollectionFactory = $subscriptions; + $this->transactionCollectionFactory = $recurringTransactions; + $this->recurringOrdersEmail = $recurringOrdersEmail; + $this->_storeManager = $_storeManager; + $this->worldpaytoken = $worldpaytoken; + $this->recurringhelper = $recurringhelper; + $this->planFactory = $planFactory; + } + + /** + * Get the list of orders to be sync the status + */ + public function execute() + { + $this->_logger->info('Recurring Orders Email Notificaion executed on - '.date('Y-m-d H:i:s')); + $recurringOrderIds = $this->getRecurringOrders(); + if (!empty($recurringOrderIds)) { + foreach ($recurringOrderIds as $recurringOrder) { + $orderData = $paymentData = []; + $recurringOrderData = $recurringOrder; + $totalInfo = $this->getTotalDetails($recurringOrderData); + if ($totalInfo) { + try { + $subscriptionDetails = $totalInfo['subscriptionData']; + $orderId = $subscriptionDetails->getOriginalOrderId(); + $interval = $this->getPlanInterval($subscriptionDetails->getPlanId()); + if (($interval) && ($interval != 'WEEKLY')) { + $viewOrderUrl = $this->_storeManager->getStore() + ->getBaseUrl().'worldpay/recurring/edit/subscription_id/'.$subscriptionDetails + ->getSubscriptionId(); + $orderData = [ + 'email' => [$subscriptionDetails->getCustomerEmail()], + 'order_id' => $subscriptionDetails->getOriginalOrderIncrementId(), + 'billing_name' => $subscriptionDetails->getBillingName(), + 'recurring_date' => $recurringOrderData['recurring_date'], + 'product_name' => $subscriptionDetails->getProductName(), + 'view_order_url' => $viewOrderUrl, + 'mail_template' => $this->recurringhelper->getRecurringOrderReminderEmail(), + 'expired_msg' => $this->getCartExpiryMessage($totalInfo), + 'order_data' => $this->recurringhelper->getOrderDetails($orderId) + ]; + $this->recurringOrdersEmail->sendRecurringOrdersEmail($orderData); + } + } catch (Exception $e) { + $this->_logger->error($e->getMessage()); + } + } + } + } + return $this; + } + + /** + * Get the list of orders for send Email Notificaion + * + * @return array List of orders + */ + public function getRecurringOrders() + { + $curdate = date("Y-m-d"); + $days = $this->recurringhelper->getRecurringOrderBufferTime() + self::EMAIL_NOTIFICATION_DAYS; + $orderDate = strtotime(date("Y-m-d", strtotime($curdate)) . " +".$days." day"); + $recurringDate = date('Y-m-d', $orderDate); + $result = $this->transactionCollectionFactory->getCollection() + ->addFieldToFilter('status', ['eq' => 'active']) + ->addFieldToFilter('recurring_date', ['eq' => $recurringDate])->getData(); + return $result; + } + + /** + * Get Total Details + * + * @param array $recurringOrderData + */ + public function getTotalDetails($recurringOrderData) + { + $data = []; + if ($recurringOrderData) { + $tokenId = $recurringOrderData['worldpay_token_id']; + $data['tokenData'] = $this->getTokenInfo($tokenId, $recurringOrderData['customer_id']); + $data['subscriptionData'] = $this->getSubscriptionsInfo($recurringOrderData['subscription_id']); + } + return $data; + } + + /** + * Get Total Details + * + * @param Int $tokenId + * @param Int $customerId + */ + + public function getTokenInfo($tokenId, $customerId) + { + $curdate = date("Y-m-d"); + if ($tokenId) { + $result = $this->worldpaytoken->getCollection() + ->addFieldToFilter('id', ['eq' => trim($tokenId)]) + ->addFieldToFilter('customer_id', ['eq' => trim($customerId)]) + ->addFieldToFilter('token_expiry_date', ['gteq' => $curdate])->getData(); + return $result; + } + } + /** + * Get SubscriptionsInfo + * + * @param Int $subscriptionId + */ + public function getSubscriptionsInfo($subscriptionId) + { + if ($subscriptionId) { + $collection = $this->subscriptionCollectionFactory->getCollection() + ->addFieldToFilter('subscription_id', ['eq' => trim($subscriptionId)]); + if ($collection->getSize()) { + return $collection->getFirstItem(); + } + return false; + } + } + + /** + * Get Plan Interval + * + * @param Int $planId + */ + public function getPlanInterval($planId) + { + if ($planId) { + $plan = $this->planFactory->create()->loadById($planId); + return $plan->getInterval(); + } + return false; + } + + /** + * Get Cart Expiry Message Interval + * + * @param array $totalInfo + */ + public function getCartExpiryMessage($totalInfo) + { + $expiredMsg = ''; + if (isset($totalInfo['tokenData'][0])) { + $currentDate = date("Y-m-d"); + $currentMonth = date("m") + 1; + $currentYear = date("Y"); + + $expiryMonth = sprintf("%02d",$totalInfo['tokenData'][0]['card_expiry_month']); + $expiryYear = $totalInfo['tokenData'][0]['card_expiry_year']; + $expiry = date($expiryYear.'-'.$expiryMonth.'-01'); + + if ($expiry < $currentDate) { + $expiredMsg = 'Your card is expired. Plese add/update card details.'; + } else if ($expiryYear === $currentYear && $expiryMonth == $currentMonth) { + $expiredMsg = 'Your card is going to expire, please check the card or update the card details'; + } + } + return $expiredMsg; + } +} diff --git a/Helper/Data.php b/Helper/Data.php index 4555406..f6c484b 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -1194,6 +1194,30 @@ public function appleMerchantId() \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } + /** + * Check Multishipping ApplePay Enable + * + * @return string + */ + public function isMsApplePayEnable() + { + return (bool) $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/enabled', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Get Multishipping apple MerchantId + * + * @return string + */ + public function msAppleMerchantId() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_apple_pay_wallets_config/ms_merchant_name', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } /** * Get is Samsung Pay Enable * @@ -1206,6 +1230,20 @@ public function isSamsungPayEnable() \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } + + /** + * Get Samsung Pay Button Type + * + * @return string + */ + public function getSamsungPayButtonType() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/samsungpay_ssl/samsungpay_button_type', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** * Get is Dynamic 3DS2 Enabled * @@ -2489,9 +2527,9 @@ public function isApplePayEnableonPdp() } /** - * ApplePay button color + * ApplePay button color for PDP */ - public function getApplePayButtonColor() + public function getApplePayButtonColorPdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/apple_pay_wallets_pdp_config/applepay_button_color', @@ -2499,9 +2537,9 @@ public function getApplePayButtonColor() ); } /** - * ApplePay button type + * ApplePay button type for PDP */ - public function getApplePayButtonType() + public function getApplePayButtonTypePdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/apple_pay_wallets_pdp_config/applepay_button_type', @@ -2509,9 +2547,9 @@ public function getApplePayButtonType() ); } /** - * ApplePay button locale + * ApplePay button locale for PDP */ - public function getApplePayButtonLocale() + public function getApplePayButtonLocalePdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/apple_pay_wallets_pdp_config/applepay_button_locale', @@ -2519,9 +2557,9 @@ public function getApplePayButtonLocale() ); } /** - * Apple Pay on PopUp Order Place Button Text + * Apple Pay on PopUp Order Place Button Text for PDP */ - public function getApplePayPopupPlaceOrderText() + public function getApplePayPopupPlaceOrderTextPdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/apple_pay_wallets_pdp_config/applepay_place_order_button_configuration', @@ -2529,9 +2567,39 @@ public function getApplePayPopupPlaceOrderText() ); } /** - * Get googlepay button color + * ApplePay button color for Checkout */ - public function getGpayButtonColor() + public function getCheckoutApplePayBtnColor() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/applepay_ssl/applepay_button_color', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * ApplePay button type for Checkout + */ + public function getCheckoutApplePayBtnType() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/applepay_ssl/applepay_button_type', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * ApplePay button locale for Checkout + */ + public function getCheckoutApplePayBtnLocale() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/applepay_ssl/applepay_button_locale', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Get googlepay button color for PDP + */ + public function getGpayButtonColorPdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/google_pay_wallets_pdp_config/gpay_button_color', @@ -2539,9 +2607,9 @@ public function getGpayButtonColor() ); } /** - * Get googlepay button type + * Get googlepay button type for PDP */ - public function getGpayButtonType() + public function getGpayButtonTypePdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/google_pay_wallets_pdp_config/gpay_button_type', @@ -2549,15 +2617,45 @@ public function getGpayButtonType() ); } /** - * Get googlepay button locale + * Get googlepay button locale for PDP */ - public function getGpayButtonLocale() + public function getGpayButtonLocalePdp() { return $this->_scopeConfig->getValue( 'worldpay/wallets_config/google_pay_wallets_pdp_config/gpay_button_locale', \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } + /** + * Get googlepay button color for Checkout & Multishipping + */ + public function getGpayButtonColor() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/paywithgoogle_ssl/gpay_button_color', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Get googlepay button type for Checkout & Multishipping + */ + public function getGpayButtonType() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/paywithgoogle_ssl/gpay_button_type', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Get googlepay button locale for Checkout & Multishipping + */ + public function getGpayButtonLocale() + { + return $this->_scopeConfig->getValue( + 'worldpay/payment_method_logo_config/wallet/paywithgoogle_ssl/gpay_button_locale', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } /** * Get moto store id @@ -2699,9 +2797,15 @@ public function getPhpVersionUsed() */ public function getCurrentMagentoVersionDetails() { - $magento['Edition'] = $this->productMetaData->getEdition(); - $magento['Version'] = $this->productMetaData->getVersion(); - return $magento; + $mageDetails = []; + $mageDetails['platform'] = __('Magento'); + if ($this->productMetaData->getEdition()) { + $mageDetails['edition'] = __('Magento_').$this->productMetaData->getEdition(); + } + if ($this->productMetaData->getVersion()) { + $mageDetails['version'] = $this->productMetaData->getVersion(); + } + return $mageDetails; } /** * Get Plugin Tracker Details @@ -2712,21 +2816,21 @@ public function getCurrentMagentoVersionDetails() public function getPluginTrackerdetails() { $details=[]; - $magento = $this->getCurrentMagentoVersionDetails(); - $details['partner_edition'] = $magento['Edition']; - $details['partner_version'] = $magento['Version']; - $details['php_version'] = $this->getPhpVersionUsed(); - + $mageDetails = $this->getCurrentMagentoVersionDetails(); + $details['ecommerce_platform'] = $mageDetails['platform']; + $details['ecommerce_platform_edition'] = $mageDetails['edition']; + $details['ecommerce_platform_version'] = $mageDetails['version']; + if (($this->getCurrentWopayPluginVersion()!=null) && !empty($this->getCurrentWopayPluginVersion())) { - $details['plugin_version'] = $this->getCurrentWopayPluginVersion(); - } - if (($this->getWopayPluginVersionHistory()!=null) && !empty($this->getWopayPluginVersionHistory())) { - $details['worldpay_plugin_version_used_till_date'] = $this->getWopayPluginVersionHistory(); + $details['integration_version'] = $this->getCurrentWopayPluginVersion(); } - + if (($this->getUpgradeDates()!=null) && !empty($this->getUpgradeDates())) { - $details['upgrade_dates'] = $this->getUpgradeDates(); + $details['historic_integration_versions'] = $this->getUpgradeDates(); } + + $details['additional_details']['php_version'] = $this->getPhpVersionUsed(); + return $details; } @@ -3034,6 +3138,121 @@ public function getMultishippingInstallationId() ); return $multishippingIID; } + /** + * Get is Samsung Pay Enable for Multishipping + * + * @return string + */ + public function isMsSamsungPayEnable() + { + return (bool) $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_samsung_pay_wallets_config/enabled', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Get Multishipping Google Pay Enable + * + * @return string + */ + public function isMsGooglePayEnable() + { + return (bool) $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/enabled', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get Multishipping google Payment Methods + * + * @return string + */ + public function msGooglePaymentMethods() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/paymentmethods', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get MultiShipping google Auth Methods + * + * @return string + */ + public function msGoogleAuthMethods() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/authmethods', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get google Gateway Merchantname + * + * @return string + */ + public function msGoogleGatewayMerchantname() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/ms_gpay_gateway_merchantname', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get google Gateway Merchantid + * + * @return string + */ + public function msGoogleGatewayMerchantid() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/ms_gpay_gateway_merchantid', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get MultiShipping google Merchantid + * + * @return string + */ + public function msGoogleMerchantid() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/ms_gpay_merchantid', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get MultiShipping google Merchant name + * + * @return string + */ + public function msGoogleMerchantname() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/ms_gpay_merchantname', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get MultiShipping google test card holder name + * + * @return string + */ + public function msGoogleTestCardname() + { + return $this->_scopeConfig->getValue( + 'worldpay/multishipping/ms_wallets_config/ms_gpay_wallets_config/ms_gpay_test_cardholdername', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } /** * Get PaybyLink Installation Id @@ -3129,7 +3348,7 @@ public function getSEPADetails() array_key_exists("SEPA_DIRECT_DEBIT-SSL", $apmmethods)) { $data = $this->getSEPAMandateTypes(); if (!empty($data)) { - return explode(",", $data); + return $data; } } return []; @@ -3159,6 +3378,7 @@ public function getSEPAMandateTypes() \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } + /** * Get SEPA Merchant Number * diff --git a/Helper/Multishipping.php b/Helper/Multishipping.php index 9f6cae9..700d6d3 100644 --- a/Helper/Multishipping.php +++ b/Helper/Multishipping.php @@ -599,7 +599,7 @@ public function checkIsMultishippingIssue() */ public function getQuote($quoteId = null) { - $quote = $this->_checkoutSession->getQuote(); + $quote = $this->checkoutSession->getQuote(); return $quote; } /** diff --git a/Helper/Recurring.php b/Helper/Recurring.php index 060e3bb..665bcc8 100644 --- a/Helper/Recurring.php +++ b/Helper/Recurring.php @@ -7,6 +7,7 @@ use Sapient\Worldpay\Model\Config\Source\Interval; use Sapient\Worldpay\Model\Config\Source\TrialInterval; +use Sapient\Worldpay\Model\Recurring\Subscription\Transactions; use Magento\Catalog\Model\Product; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; @@ -15,7 +16,8 @@ class Recurring extends \Magento\Framework\App\Helper\AbstractHelper { public const PENDING_RECURRING_PAYMENT_ORDER_STATUS = 'pending_recurring_payment'; - + public const RECURRING_ORDER_SKIP_DAYS_UPTO = 9; + /** * Product type ids supported to act as subscriptions * @@ -142,6 +144,21 @@ class Recurring extends \Magento\Framework\App\Helper\AbstractHelper * @var \Magento\Integration\Model\Oauth\TokenFactory */ protected $_tokenModelFactory; + + /** + * @var $orderRepository + */ + protected $orderRepository; + /** + * @var \Magento\Customer\Model\Address\Config + */ + protected $_addressConfig; + + /** + * @var CollectionFactory + */ + private $transactionCollectionFactory; + /** * Recurring constructor * @param \Magento\Framework\App\Helper\Context $context @@ -166,6 +183,9 @@ class Recurring extends \Magento\Framework\App\Helper\AbstractHelper * @param \Magento\Integration\Model\Oauth\TokenFactory $tokenModelFactory * @param SerializerInterface $serializer * @param \Sapient\Worldpay\Helper\CurlHelper $curlHelper + * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository + * @param \Magento\Customer\Model\Address\Config $addressConfig + * @param Transactions $recurringTransactions */ public function __construct( \Magento\Framework\App\Helper\Context $context, @@ -189,7 +209,10 @@ public function __construct( \Magento\Customer\Model\Session $customerSession, \Magento\Integration\Model\Oauth\TokenFactory $tokenModelFactory, SerializerInterface $serializer, - \Sapient\Worldpay\Helper\CurlHelper $curlHelper + \Sapient\Worldpay\Helper\CurlHelper $curlHelper, + \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, + \Magento\Customer\Model\Address\Config $addressConfig, + Transactions $recurringTransactions ) { parent::__construct($context); $this->plansCollectionFactory = $plansCollectionFactory; @@ -210,6 +233,9 @@ public function __construct( $this->_tokenModelFactory = $tokenModelFactory; $this->serializer = $serializer; $this->curlHelper = $curlHelper; + $this->orderRepository = $orderRepository; + $this->_addressConfig = $addressConfig; + $this->transactionCollectionFactory = $recurringTransactions; } /** @@ -962,7 +988,6 @@ public function getEndDateLabel() return $label; } - /** * Get the list of admin labels * @@ -1099,4 +1124,112 @@ public function isWorldpayEnable() \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); } + /** + * Get Recurring Order Buffer Time + * + * @return string + */ + public function getRecurringOrderBufferTime() + { + return $this->scopeConfig->getValue( + 'worldpay/subscriptions/recurring_order_buffer_time', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Get Recurring Order Reminder Email Template + * + * @return string + */ + public function getRecurringOrderReminderEmail() + { + return $this->scopeConfig->getValue( + 'worldpay/subscriptions/recurring_order_reminder_email', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + + /** + * Get Order Details + * + * @param int $orderId + */ + public function getOrderDetails($orderId) + { + $order = $this->orderRepository->get($orderId); + $billingAddress = $order->getBillingAddress()->getData(); + $formattedShippingAddress = ''; + if ($order->getIsNotVirtual()) { + $shippingAddress = $order->getShippingAddress()->getData(); + $formattedShippingAddress = $this->getFormatAddressByCode($shippingAddress); + } + + $paymentMethod = $order->getPayment()->getAdditionalInformation('method_title'); + $orderDetails = [ + 'order' => $order, + 'order_id' => $order->getId(), + 'payment_html' => $paymentMethod, + 'formattedBillingAddress' => $this->getFormatAddressByCode($billingAddress), + 'formattedShippingAddress' => $formattedShippingAddress, + 'is_not_virtual' => $order->getIsNotVirtual() + ]; + return $orderDetails; + } + + /** + * Format Shipping Address + * + * @param array $address + * @return array + */ + public function getFormatAddressByCode($address) + { + $renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer(); + return $renderer->renderArray($address); + } + + /** + * Get next recurring order + * + * @param int $subscriptionId + * @param int $customerId + * @return array + */ + public function getNextRecurringOrder($subscriptionId,$customerId) + { + $nextOrder = $this->getNextRecurringOrderCollection($subscriptionId,$customerId); + if (!empty($nextOrder)) { + $curdate = date("Y-m-d"); + $skipDays = self::RECURRING_ORDER_SKIP_DAYS_UPTO; + $days = $this->getRecurringOrderBufferTime() + $skipDays; + $endDate = strtotime(date("Y-m-d", strtotime($curdate)) . " +".$days." day"); + $nextOrderDate = strtotime($nextOrder->getRecurringDate()); + $recurringEndDate = strtotime($nextOrder->getRecurringEndDate()); + if (($nextOrderDate <= $endDate) && ($nextOrderDate <= $recurringEndDate)) { + return $nextOrder; + } + } + return false; + } + + /** + * Get next recurring order collection + * + * @param int $subscriptionId + * @param int $customerId + * @return array + */ + public function getNextRecurringOrderCollection($subscriptionId,$customerId) + { + $curdate = date("Y-m-d"); + $collection = $this->transactionCollectionFactory->getCollection() + ->addFieldToFilter('status', ['eq' => 'active']) + ->addFieldToFilter('subscription_id', ['eq' => $subscriptionId]) + ->addFieldToFilter('customer_id', ['eq' => $customerId]) + ->addFieldToFilter('recurring_date', ['gteq' => $curdate]); + if ($collection->getSize()) { + return $collection->getFirstItem(); + } + return false; + } } diff --git a/Helper/SendRecurringOrdersEmail.php b/Helper/SendRecurringOrdersEmail.php new file mode 100644 index 0000000..93ca5e6 --- /dev/null +++ b/Helper/SendRecurringOrdersEmail.php @@ -0,0 +1,132 @@ +_scopeConfig = $scopeConfig; + $this->wplogger = $wplogger; + $this->storeManager = $storeManager; + $this->transportBuilder = $transportBuilder; + $this->inlineTranslation = $state; + } + + /** + * Send Email + * + * @param array $params + * @param string $toEmail + */ + public function sendEmail($params, $toEmail) + { + $senderDetails = $this->getAdminContactEmail(); + try { + // template variables pass here + $templateVars = $params; + $templateId = $params['mail_template']; + $subject = __("WORLDPAY: "). + "Reminder - Recurring order"; + + $templateVars['mail_subject'] = $subject; + $storeId = $this->storeManager->getStore()->getId(); + $from = ['email' => $senderDetails['email'], 'name' => $senderDetails['name']]; + $this->inlineTranslation->suspend(); + + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + $templateOptions = [ + 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'store' => $storeId + ]; + $transport = $this->transportBuilder->setTemplateIdentifier($templateId, $storeScope) + ->setTemplateOptions($templateOptions) + ->setTemplateVars($templateVars) + ->setFrom($from) + ->addTo($toEmail) + ->getTransport(); + $transport->sendMessage(); + $this->inlineTranslation->resume(); + } catch (\Exception $e) { + $this->wplogger->info(__('Unable to send email '). $e->getMessage()); + } + } + + /** + * Get store admin email and name + */ + public function getAdminContactEmail() + { + return [ + 'name' => $this->_scopeConfig->getValue( + 'trans_email/ident_support/name', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ), + 'email' => $this->_scopeConfig->getValue( + 'trans_email/ident_support/email', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ), + ]; + } + /** + * Send Pay By link Email + * + * @param array $params + */ + public function sendRecurringOrdersEmail($params) + { + try { + $customerEmail = $params['email']; + if (!empty($customerEmail)) { + foreach ($customerEmail as $recipientEmail) { + $this->wplogger->info("Recurring Order email to ".$recipientEmail); + $this->sendEmail($params, $recipientEmail); + } + } + + } catch (\Exception $e) { + $this->wplogger->info(__("Failed to send email:").$e->getMessage()); + } + } +} diff --git a/Helper/SkipOrderEmail.php b/Helper/SkipOrderEmail.php new file mode 100644 index 0000000..bb58f9a --- /dev/null +++ b/Helper/SkipOrderEmail.php @@ -0,0 +1,175 @@ +_scopeConfig = $scopeConfig; + $this->wplogger = $wplogger; + $this->_customerSession = $customerSession; + $this->storeManager = $storeManager; + $this->transportBuilder = $transportBuilder; + $this->checkoutSession = $checkoutSession; + $this->inlineTranslation = $state; + } + + /** + * Get Customer Emails + */ + public function getCustomerEmail() + { + if ($this->_customerSession->isLoggedIn()) { + $customerEmail = $this->_customerSession->getCustomer()->getEmail(); + } + if (!empty($customerEmail)) { + $allEmails = explode(',', $customerEmail); + if (!empty($allEmails)) { + return $allEmails; + } + } + return []; + } + /** + * Get store admin email and name + */ + public function getAdminContactEmail() + { + return [ + 'name' => $this->_scopeConfig->getValue( + 'trans_email/ident_support/name', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ), + 'email' => $this->_scopeConfig->getValue( + 'trans_email/ident_support/email', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ), + ]; + } + /** + * Get Skip Order Notification Email Template + * + * @return string + */ + public function getSkipOrderEmailTemplate() + { + return $this->_scopeConfig->getValue( + 'worldpay/subscriptions/skip_order_notification_email', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ); + } + /** + * Send Email + * + * @param array $params + * @param string $toEmail + */ + public function sendEmail($params, $toEmail) + { + $senderDetails = $this->getAdminContactEmail(); + $templateId = $this->getSkipOrderEmailTemplate(); + + try { + // template variables pass here + $templateVars = $params; + $subject = __("WORLDPAY: "). + "Skipped Order".' '.$params['orderId']; + + $templateVars['mail_subject'] = $subject; + $storeId = $this->storeManager->getStore()->getId(); + $from = ['email' => $senderDetails['email'], 'name' => $senderDetails['name']]; + $this->inlineTranslation->suspend(); + + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + $templateOptions = [ + 'area' => \Magento\Framework\App\Area::AREA_FRONTEND, + 'store' => $storeId + ]; + $transport = $this->transportBuilder->setTemplateIdentifier($templateId, $storeScope) + ->setTemplateOptions($templateOptions) + ->setTemplateVars($templateVars) + ->setFrom($from) + ->addTo($toEmail) + ->getTransport(); + $transport->sendMessage(); + $this->inlineTranslation->resume(); + } catch (\Exception $e) { + $this->wplogger->info(__('Unable to send email: '). $e->getMessage()); + } + } +/** + * Send Pay By link Email + * + * @param array $params + */ + public function sendSkipOrderEmail($params) + { + try { + $customerEmail = $this->getCustomerEmail(); + if (!empty($customerEmail)) { + foreach ($customerEmail as $recipientEmail) { + $this->sendEmail($params, $recipientEmail); + $this->wplogger->info("Skip Order email send to ".$recipientEmail); + } + } + } catch (\Exception $e) { + $this->wplogger->info(__("Failed to send email:").$e->getMessage()); + } + } +} diff --git a/Model/Authorisation/PayByLinkService.php b/Model/Authorisation/PayByLinkService.php index 17ed26f..7e26701 100644 --- a/Model/Authorisation/PayByLinkService.php +++ b/Model/Authorisation/PayByLinkService.php @@ -258,17 +258,14 @@ public function authorizePayment( } /** - * Get PBL expiry time + * Get PBL expiry time * */ public function getPayByLinkExpiryTime() { $currentDate = date('Y-m-d H:i:s'); $pblExpiryConfiguration = $this->worldpayhelper->getPayByLinkExpiryTime(); - $interval = date("Y-m-d H:i:s", $this->worldpayhelper - ->findPblOrderExpiryTime( - $currentDate, - $pblExpiryConfiguration - )); + $pblExpTime = $this->worldpayhelper->findPblOrderExpiryTime($currentDate, $pblExpiryConfiguration); + $interval = date("Y-m-d H:i:s", $pblExpTime); return $interval; } @@ -354,8 +351,7 @@ public function authorizeRegenaretPayment( $responseInquiry = $this->_sendRequest( dom_import_simplexml($inquirySimpleXml)->ownerDocument, $merchantUsername, - $merchantPassword, - \Sapient\Worldpay\Model\Request\PaymentServiceRequest::SEND_ADDITIONAL_HEADER + $merchantPassword ); $paymentService = new \SimpleXmlElement($responseInquiry); @@ -545,12 +541,11 @@ private function _setredirectpaybylinkhpp($redirectLink) * @param SimpleXmlElement $xml * @param string $username * @param string $password - * @param bool $additionalHeader * @return SimpleXmlElement $response */ - protected function _sendRequest($xml, $username, $password, $additionalHeader) + protected function _sendRequest($xml, $username, $password) { - $response = $this->_request->sendRequest($xml, $username, $password, $additionalHeader); + $response = $this->_request->sendRequest($xml, $username, $password); return $response; } /** diff --git a/Model/Authorisation/SepaTokenService.php b/Model/Authorisation/SepaTokenService.php new file mode 100644 index 0000000..d78fc46 --- /dev/null +++ b/Model/Authorisation/SepaTokenService.php @@ -0,0 +1,195 @@ +mappingservice = $mappingservice; + $this->paymentservicerequest = $paymentservicerequest; + $this->wplogger = $wplogger; + $this->directResponse = $directResponse; + $this->paymentservice = $paymentservice; + $this->checkoutSession = $checkoutSession; + $this->updateWorldPayPayment = $updateWorldPayPayment; + $this->worldpayHelper = $worldpayHelper; + $this->registryhelper = $registryhelper; + $this->urlBuilders = $urlBuilder; + $this->objectCopyService = $objectCopyService; + } + + /** + * Handles provides authorization data for direct + * + * It initiates a XML request to WorldPay and registers worldpayRedirectUrl + * + * @param MageOrder $mageOrder + * @param Quote $quote + * @param string $orderCode + * @param string $orderStoreId + * @param array $paymentDetails + * @param Payment $payment + */ + public function authorizePayment( + $mageOrder, + $quote, + $orderCode, + $orderStoreId, + $paymentDetails, + $payment + ) { + + $directOrderParams = $this->mappingservice->collectSEPATokenOrderParameters( + $orderCode, + $quote, + $orderStoreId, + $paymentDetails + ); + $response = $this->paymentservicerequest->sepaTokenOrder($directOrderParams); + $directResponse = $this->directResponse->setResponse($response); + $disclaimerFlag = ''; + + if (!empty($directOrderParams['primeRoutingData'])) { + $additionalInformation = $payment->getAdditionalInformation(); + $additionalInformation["worldpay_primerouting_enabled"]=true; + $payment->setAdditionalInformation( + $additionalInformation + ); + } + + if (isset($paymentDetails['additional_data']['disclaimerFlag'])) { + $disclaimerFlag = $paymentDetails['additional_data']['disclaimerFlag']; + } + + $this->updateWorldPayPayment->create()->updateWorldpayPayment($directResponse, $payment, $disclaimerFlag); + $this->_applyPaymentUpdate($directResponse, $payment); + } + + /** + * Apply payment update + * + * @param \Sapient\Worldpay\Model\Response\DirectResponse $directResponse + * @param Payment $payment + */ + private function _applyPaymentUpdate( + \Sapient\Worldpay\Model\Response\DirectResponse $directResponse, + $payment + ) { + $paymentUpdate = $this->paymentservice->createPaymentUpdateFromWorldPayXml($directResponse->getXml()); + $paymentUpdate->apply($payment); + $this->_abortIfPaymentError($paymentUpdate, $directResponse); + } + + /** + * Abort if payment error + * + * @param Object $paymentUpdate + * @param \SimpleXMLObject $directResponse + */ + private function _abortIfPaymentError($paymentUpdate, $directResponse) + { + $responseXml = $directResponse->getXml(); + $orderStatus = $responseXml->reply->orderStatus; + $payment = $orderStatus->payment; + $wpayCode = $payment->ISO8583ReturnCode['code'] ? $payment->ISO8583ReturnCode['code'] : 'Payment REFUSED'; + if ($paymentUpdate instanceof \Sapient\WorldPay\Model\Payment\Update\Refused) { + $msg = new Phrase($wpayCode); + throw new PaymentException($msg); + } + + if ($paymentUpdate instanceof \Sapient\WorldPay\Model\Payment\Update\Cancelled) { + $msg = new Phrase('Payment CANCELLED'); + throw new PaymentException($msg); + } + + if ($paymentUpdate instanceof \Sapient\WorldPay\Model\Payment\Update\Error) { + $msg = new Phrase('Payment ERROR'); + throw new PaymentException($msg); + } + } +} diff --git a/Model/Authorisation/WalletService.php b/Model/Authorisation/WalletService.php index 282698c..4886551 100644 --- a/Model/Authorisation/WalletService.php +++ b/Model/Authorisation/WalletService.php @@ -225,6 +225,7 @@ public function authorizePayment( $paymentxml=$orderStatus->payment; $paymentxml->paymentMethod[0] = 'APPLEPAY-SSL'; } + $this->updateWorldPayPayment->create()->updateWorldpayPayment($directResponse, $payment); $this->_applyPaymentUpdate($directResponse, $payment); } diff --git a/Model/Config/Source/DebitNetworks.php b/Model/Config/Source/DebitNetworks.php index 1149246..94a3bdc 100644 --- a/Model/Config/Source/DebitNetworks.php +++ b/Model/Config/Source/DebitNetworks.php @@ -1,7 +1,5 @@ 'pay-card', 'label' => __('Normal')], + ['value' => 'pay-card-dark', 'label' => __('Normal Dark')], + ['value' => 'pay-card-ver', 'label' => __('Vertical')], + ['value' => 'pay-card-ver-dark', 'label' => __('Vertical Dark ')], + + ]; + } +} diff --git a/Model/EditSubscriptionHistory.php b/Model/EditSubscriptionHistory.php new file mode 100644 index 0000000..b680a52 --- /dev/null +++ b/Model/EditSubscriptionHistory.php @@ -0,0 +1,137 @@ +_init(\Sapient\Worldpay\Model\ResourceModel\EditSubscriptionHistory::class); + } + + /** + * Get Id + */ + public function getId() + { + return parent::getData(self::ENTITY_ID); + } + + /** + * Set Id + * + * @param int $entityId + */ + public function setId($entityId) + { + return $this->setData(self::ENTITY_ID, $entityId); + } + + /** + * Get entityId + */ + public function getSubscriptionId() + { + return parent::getData(self::SUBSCRIPTION_ID); + } + + /** + * Set Subscription Id + * + * @param int $subscriptionId + */ + public function setSubscriptionId($subscriptionId) + { + return $this->setData(self::SUBSCRIPTION_ID, $subscriptionId); + } + + /** + * Get Customer Id + */ + public function getCustomerId() + { + return parent::getData(self::CUSTOMER_ID); + } + + /** + * Set Customer Id + * + * @param int $customerId + */ + public function setCustomerId($customerId) + { + return $this->setData(self::CUSTOMER_ID, $customerId); + } + + /** + * Get Old Data + */ + public function getOldData() + { + return parent::getData(self::OLD_DATA); + } + + /** + * Set shipping and payment method Data + * + * @param mixed $oldData + */ + public function setOldData($oldData) + { + return $this->setData(self::OLD_DATA, $oldData); + } + + /** + * Get Created At + */ + public function getCreatedAt() + { + return $this->setData(self::CREATED_AT); + } + + /** + * Set Created At + * + * @param string $createdAt + */ + public function setCreatedAt($createdAt) + { + return $this->setData(self::CREATED_AT, $createdAt); + } + + /** + * Get ModifiedAt + */ + public function getModifiedAt() + { + return $this->setData(self::MODIFIED_DATE); + } + + /** + * Set Modified At + * + * @param string $modifiedAt + */ + public function setModifiedAt($modifiedAt) + { + return $this->setData(self::MODIFIED_DATE, $modifiedAt); + } +} diff --git a/Model/EditSubscriptionHistoryRepository.php b/Model/EditSubscriptionHistoryRepository.php new file mode 100644 index 0000000..af832ed --- /dev/null +++ b/Model/EditSubscriptionHistoryRepository.php @@ -0,0 +1,178 @@ +editHistoryFactory = $editHistoryFactory; + $this->editHistoryResource = $editHistoryResource; + $this->editHistoryCollectionFactory = $editHistoryCollectionFactory; + $this->subscriptionFactory = $subscriptionFactory; + $this->customerSession = $customerSession; + $this->serializer = $serializer; + $this->orderRepository = $orderRepository; + $this->addressConfig = $addressConfig; + } + + /** + * Get ById + * + * @param int $id + * @return \Sapient\Worldpay\Api\Data\StudentInterface + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ + public function getById($id) + { + $editHistory = $this->editHistoryFactory->create(); + $this->editHistoryResource->load($editHistory, $id); + if (!$editHistory->getId()) { + throw new NoSuchEntityException(__('Unable to find History with ID "%1"', $id)); + } + return $editHistory; + } + + /** + * Save SubscriptionHistory data + * + * @param EditSubscriptionHistoryInterface $subscriptionHistory + * @return mixed + */ + public function save(EditSubscriptionHistoryInterface $subscriptionHistory): mixed + { + $this->editHistoryResource->save($subscriptionHistory); + return $subscriptionHistory; + } + + /** + * Update Edit History + * + * @param object $subscriptionOldInfo + * @param string $shippingOldAddress + * @param string $method + */ + public function updateEditHistory($subscriptionOldInfo, $shippingOldAddress, $method) + { + $customer = $this->customerSession->getCustomer(); + $customerId = $customer->getId(); + + $shippingAddress = $this->getShippingAddress($shippingOldAddress); + + $subscriptionHistory = $this->editHistoryFactory->create(); + $subscriptionOldData = [ + 'payment_method'=>$method, + 'shipping_address'=>$shippingAddress, + 'shipping_method' =>$subscriptionOldInfo->getShippingMethod() + ]; + $subscriptionOldData = $this->serializer->serialize($subscriptionOldData); + + $subscriptionHistory->setSubscriptionId($subscriptionOldInfo->getSubscriptionId()); + $subscriptionHistory->setCustomerId($customerId); + $subscriptionHistory->setOldData($subscriptionOldData); + $subscriptionHistory->setCreatedAt(date('Y-m-d')); + $subscriptionHistory->setModifiedAt(date('Y-m-d')); + $subscriptionHistory->save(); + } + + /** + * Get Subscription Data + * + * @param int $subscriptionId + * @return mixed + */ + public function getSubscriptionData($subscriptionId) + { + $subscription = $this->subscriptionFactory->create(); + $subscription->load($subscriptionId); + return $subscription; + } + + /** + * Get Shipping address data of specific order + * + * @param string $address + * @return string + */ + + public function getShippingAddress($address) + { + $renderer = $this->addressConfig->getFormatByCode('text')->getRenderer(); + return $renderer->renderArray($address); + } +} diff --git a/Model/Mapping/Service.php b/Model/Mapping/Service.php index b195d07..cf7c616 100644 --- a/Model/Mapping/Service.php +++ b/Model/Mapping/Service.php @@ -1096,10 +1096,9 @@ private function _getPaymentDetails($paymentDetails) } if ($paymentDetails['additional_data']['cc_type'] == "SEPA_DIRECT_DEBIT-SSL") { - $details = [ 'paymentType' => $paymentDetails['additional_data']['cc_type'], - 'sepaMandateType' => $paymentDetails['additional_data']['sepa_mandateType'], + 'sepaMandateType' => $this->worldpayHelper->getSEPADetails(), 'sepaIban' => $paymentDetails['additional_data']['sepa_iban'], 'sepaAccountHolderName' => $paymentDetails['additional_data']['sepa_accountHolderName'] ]; diff --git a/Model/Payment/StateResponse.php b/Model/Payment/StateResponse.php index 0de4d79..a23319e 100644 --- a/Model/Payment/StateResponse.php +++ b/Model/Payment/StateResponse.php @@ -25,6 +25,11 @@ class StateResponse implements \Sapient\Worldpay\Model\Payment\StateInterface * @var string */ public $merchantCode; + /** + * @var \SimpleXMLElement + */ + public $_xml; + /** * Constructor * diff --git a/Model/PaymentMethods/CcVault.php b/Model/PaymentMethods/CcVault.php index 0c58c85..b0a2f3d 100644 --- a/Model/PaymentMethods/CcVault.php +++ b/Model/PaymentMethods/CcVault.php @@ -144,6 +144,11 @@ class CcVault extends \Magento\Vault\Model\Method\Vault * @var \Magento\Framework\Registry */ protected $registry; + + /** + * @var object + */ + protected $_response; /** * CcVault constructor diff --git a/Model/PaymentMethods/Wallets.php b/Model/PaymentMethods/Wallets.php index 271543f..bbaa425 100644 --- a/Model/PaymentMethods/Wallets.php +++ b/Model/PaymentMethods/Wallets.php @@ -72,8 +72,8 @@ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null) if ($this->worlpayhelper->isMultiShipping()) { if ($this->worlpayhelper->isMultiShippingEnabledInWallets()) { if ($this->worlpayhelper->isGooglePayEnable() || - $this->worlpayhelper->isSamsungPayEnable() || - $this->worlpayhelper->isApplePayEnable() + $this->worlpayhelper->isMsSamsungPayEnable() || + $this->worlpayhelper->isMsApplePayEnable() ) { return true; } @@ -81,6 +81,7 @@ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null) return false; } /* End Multishipping code */ + if ($this->worlpayhelper->isWorldPayEnable() && $this->worlpayhelper->isWalletsEnabled() && !$this->worlpayhelper->getsubscriptionStatus()) { if ($this->worlpayhelper->isGooglePayEnable() || diff --git a/Model/Recurring/Order/Address/Renderer.php b/Model/Recurring/Order/Address/Renderer.php new file mode 100644 index 0000000..5d463d7 --- /dev/null +++ b/Model/Recurring/Order/Address/Renderer.php @@ -0,0 +1,70 @@ +addressConfig = $addressConfig; + $this->eventManager = $eventManager; + } + + /** + * Format address in a specific way + * + * @param Address $address + * @param string $type + * @return string|null + */ + public function format(Address $address, $type) + { + $formatType = $this->addressConfig->getFormatByCode($type); + if (!$formatType || !$formatType->getRenderer()) { + return null; + } + $this->eventManager->dispatch('customer_address_format', ['type' => $formatType, 'address' => $address]); + $addressData = $address->getData(); + + return $formatType->getRenderer()->renderArray($addressData); + } +} diff --git a/Model/Recurring/Order/CustomerPaymentTokens.php b/Model/Recurring/Order/CustomerPaymentTokens.php new file mode 100644 index 0000000..2b41ddd --- /dev/null +++ b/Model/Recurring/Order/CustomerPaymentTokens.php @@ -0,0 +1,111 @@ +scopeConfig = $scopeConfig; + $this->customerSession = $customerSession; + $this->savedToken = $savedTokenFactory; + $this->worldpayhelper = $worldpayhelper; + } + + /** + * Get All Tokens + * + * @param int $customerId + * @return mixed + */ + public function getAllTokens($customerId) + { + $merchantTokenEnabled = $this->worldpayhelper->getMerchantTokenization(); + $tokenType = $merchantTokenEnabled ? 'merchant' : 'shopper'; + return $this->savedToken->create()->getCollection() + ->addFieldToSelect([ + 'card_brand', + 'card_number', + 'cardholder_name', + 'card_expiry_month', + 'card_expiry_year', + 'transaction_identifier', + 'token_code']) + ->addFieldToFilter('customer_id', ['eq' => $customerId]) + ->addFieldToFilter('token_type', ['eq' => $tokenType]); + } + /** + * Get All Payment Tokens + * + * @return string + */ + + public function getAllPaymentTokens() + { + $jsonResponse = []; + if (!$this->customerSession->getCustomerId()) { + $jsonResponse['status'] = false; + $jsonResponse['msg'] = 'Log in to see saved tokens'; + } + + try { + $savedTokens = $this->getAllTokens($this->customerSession->getCustomerId()); + if ($savedTokens) { + $alltokens = []; + foreach ($savedTokens as $key => $token) { + $alltokens[$key]['token_id'] = $token->getId(); + $alltokens[$key]['token_code'] = $token->getData('token_code'); + $alltokens[$key]['cardholder_name'] = $token->getData('cardholder_name'); + $alltokens[$key]['card_number'] = $token->getData('card_number'); + $alltokens[$key]['card_expiry_month'] = $token->getData('card_expiry_month'); + $alltokens[$key]['card_expiry_year'] = $token->getData('card_expiry_year'); + } + + $jsonResponse['status'] = true; + $jsonResponse['tokens'] = $alltokens; + $jsonResponse['msg'] = 'Success'; + } + } catch (\Exception $e) { + $jsonResponse['status'] = false; + $jsonResponse['msg'] = $e->getMessage(); + } + return json_encode($jsonResponse); + } +} diff --git a/Model/Recurring/Order/Item/ToSubscription.php b/Model/Recurring/Order/Item/ToSubscription.php index 495ffe4..61ec090 100644 --- a/Model/Recurring/Order/Item/ToSubscription.php +++ b/Model/Recurring/Order/Item/ToSubscription.php @@ -130,147 +130,4 @@ public function convert(Order\Item $item, Order $order, $data = []) return $subscription; } - - /** - * Create subscription addons and discounts - * - * @param Subscription $subscription - * @param Order $order - */ - private function createAddonsAndDiscounts(Subscription $subscription, Order $order) - { - if ($subscription->getIntervalAmount() === null) { - return; - } - - $addonList = []; - $addonsAmount = 0; - $discountList = []; - $discountsAmount = 0; - - $amount = $order->getBaseTaxAmount(); - if ($amount >= 0.01) { - $addonList[] = $this->createAddon( - $subscription, - [ - 'code' => Subscription\Addon::TAX_CODE, - 'name' => __('Tax'), - 'amount' => $amount - ] - ); - $addonsAmount += $amount; - } - - $amount = $order->getBaseShippingAmount(); - if ($amount >= 0.01) { - $addonList[] = $this->createAddon( - $subscription, - [ - 'code' => Subscription\Addon::SHIPPING_CODE, - 'name' => __('Shipping'), - 'amount' => $amount - ] - ); - $addonsAmount += $amount; - } - - $amount = abs($order->getBaseDiscountAmount()); - if ($amount >= 0.01) { - $discountList[] = $this->createDiscount( - $subscription, - [ - 'code' => Subscription\Discount::DISCOUNT_CODE, - 'name' => $order->getDiscountDescription() - ? __('Discount (%1)', $order->getDiscountDescription()) : Subscription\Discount::DISCOUNT_NAME, - 'amount' => $amount - ] - ); - $discountsAmount += $amount; - } - - $reconciliationAmount = $subscription->getIntervalAmount() - $subscription->getPlan()->getIntervalAmount() - - $addonsAmount + $discountsAmount; - if (abs($reconciliationAmount) >= 0.01) { - if ($reconciliationAmount > 0) { - $addonList[] = $this->createAddon( - $subscription, - [ - 'code' => Subscription\Addon::RECONCILIATION_CODE, - 'name' => __('Reconciliation'), - 'amount' => $reconciliationAmount - ] - ); - } else { - $discountList[] = $this->createDiscount( - $subscription, - [ - 'code' => Subscription\Discount::RECONCILIATION_CODE, - 'name' => __('Reconciliation'), - 'amount' => abs($reconciliationAmount) - ] - ); - } - } - - $subscription->setAddonList($addonList); - $subscription->setDiscountList($discountList); - } - - /** - * Create subscription addon - * - * @param Subscription $subscription - * @param array $data - * @return Subscription\Addon - */ - private function createAddon(Subscription $subscription, $data = []) - { - /** @var Subscription\Addon $addon */ - $addon = $this->addonFactory->create(); - - $addon->addData($data); - $addon->setIsSystem(true); - - if ($subscription->getStartDate()) { - $startDate = $subscription->getStartDate(); - } else { - $startDate = date('Y-m-d'); - } - $addon->setStartDate($startDate); - - $endDate = $this->recurringHelper->calculateEndDate($subscription); - - //write log here - $addon->setEndDate($endDate); - - return $addon; - } - - /** - * Create subscription discount - * - * @param Subscription $subscription - * @param array $data - * @return Subscription\Discount - */ - private function createDiscount(Subscription $subscription, $data = []) - { - /** @var Subscription\Discount $discount */ - $discount = $this->discountFactory->create(); - - $discount->addData($data); - $discount->setIsSystem(true); - - if ($subscription->getStartDate()) { - $startDate = $subscription->getStartDate(); - } else { - $startDate = date('Y-m-d'); - } - $discount->setStartDate($startDate); - - $endDate = $this->recurringHelper->calculateEndDate($subscription); - $discount->setEndDate($endDate); - - return $discount; - } } diff --git a/Model/Recurring/Order/ShippingMethods.php b/Model/Recurring/Order/ShippingMethods.php new file mode 100644 index 0000000..bb3802c --- /dev/null +++ b/Model/Recurring/Order/ShippingMethods.php @@ -0,0 +1,210 @@ +scopeConfig = $scopeConfig; + $this->orderFactory = $orderFactory; + $this->rateRequestFactory = $rateRequestFactory; + $this->rateCollector = $rateCollector; + $this->storeManager = $storeManager; + $this->addressRepository = $addressRepository; + $this->cartRepository = $cartRepository; + $this->wplogger = $wplogger; + } + + /** + * Get Original IncrementId + * + * @param int $orderIncrementId + * + * @return object $order + */ + public function getOriginalOrder($orderIncrementId) + { + $order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId); + return $order; + } + + /** + * Get Address data + * + * @param int $addressId + * + * @return \Magento\Customer\Api\Data\AddressInterface + */ + public function getAddressData($addressId) + { + try { + $addressData = $this->addressRepository->getById($addressId); + } catch (\Exception $e) { + $this->wplogger->info(__('Address data not found:'). $e->getMessage()); + }; + return $addressData; + } + + /** + * Retrieve text of street lines, concatenated using LF symbol + * + * @param string $streetData + * @return string + */ + public function getStreetFull($streetData) + { + $street = $streetData; + return is_array($street) ? implode("\n", $street) : ($street ?? ''); + } + + /** + * Get Shipping Method + * + * @param string $orderIncrementId + * @param string $addressId + * @return string + */ + + public function getShippingMethod($orderIncrementId, $addressId) + { + $order = $this->getOriginalOrder($orderIncrementId); + $storeId = $order->getStoreId(); + $addressData = $this->getAddressData($addressId); + $quote = $this->cartRepository->get($order->getQuoteId()); + /** @var $request RateRequest */ + $request = $this->rateRequestFactory->create(); + $request->setAllItems($quote->getAllItems()); + $request->setDestCountryId($addressData->getCountryId()); + $request->setDestRegionId($addressData->getRegionId()); + if ($addressData->getRegionId()) { + $request->setDestRegionCode($addressData->getRegionId()); + } + $request->setDestStreet($this->getStreetFull($addressData->getStreet())); + $request->setDestCity($addressData->getCity()); + $request->setDestPostcode($addressData->getPostcode()); + $baseSubtotal = $order->getBaseSubtotal(); + $request->setPackageValue($baseSubtotal); + $baseSubtotalWithDiscount = $baseSubtotal + $order->getBaseDiscountAmount(); + $packageWithDiscount = $baseSubtotalWithDiscount; + $request->setPackageValueWithDiscount($packageWithDiscount); + $request->setPackageWeight($order->getWeight()); + $request->setPackageQty($order->getTotalQtyOrdered()); + + /** + * Need for shipping methods that use insurance based on price of physical products + */ + $packagePhysicalValue =$baseSubtotal; + $request->setPackagePhysicalValue($packagePhysicalValue); + + /** + * Store and website identifiers specified from StoreManager + */ + $request->setStoreId($storeId); + $request->setWebsiteId($this->storeManager->getWebsite()->getId()); + /** + * $request->setFreeShipping($this->getFreeShipping()); + */ + /** + * Currencies need to convert in free shipping + */ + $request->setBaseCurrency($order->getBaseCurrencyCode()); + $request->setPackageCurrency($order->getBaseCurrencyCode()); + /** + * $request->setLimitCarrier($this->getLimitCarrier()); + */ + $baseSubtotalInclTax = $order->getBaseSubtotalInclTax(); + $request->setBaseSubtotalInclTax($baseSubtotalInclTax); + $request->setBaseSubtotalWithDiscountInclTax( + $order->getBaseSubtotalWithDiscount() + + $order->getBaseTaxAmount() + ); + + $result = $this->rateCollector->create()->collectRates($request)->getResult(); + + $shippingRatesArr = []; + if ($result) { + $shippingRates = $result->getAllRates(); + + foreach ($shippingRates as $key => $shippingRate) { + $shippingRatesArr[$key]['carrier'] = $shippingRate->getData('carrier'); + $shippingRatesArr[$key]['carrier_title'] = $shippingRate->getData('carrier_title'); + $shippingRatesArr[$key]['method'] = $shippingRate->getData('method'); + $shippingRatesArr[$key]['method_title'] = $shippingRate->getData('method_title'); + $shippingRatesArr[$key]['price'] = $shippingRate->getData('price'); + $shippingRatesArr[$key]['cost'] = $shippingRate->getData('cost'); + } + } + + return json_encode($shippingRatesArr); + } +} diff --git a/Model/Recurring/Order/UpdateRecurringShipment.php b/Model/Recurring/Order/UpdateRecurringShipment.php new file mode 100644 index 0000000..184cf32 --- /dev/null +++ b/Model/Recurring/Order/UpdateRecurringShipment.php @@ -0,0 +1,300 @@ +scopeConfig = $scopeConfig; + $this->orderFactory = $orderFactory; + $this->rateRequestFactory = $rateRequestFactory; + $this->rateCollector = $rateCollector; + $this->storeManager = $storeManager; + $this->addressRepository = $addressRepository; + $this->cartRepository = $cartRepository; + $this->regionCollectionFactory = $regionCollectionFactory; + $this->subscriptionFactory = $subscriptionFactory; + $this->editSubscriptionRepository = $editSubscriptionRepository; + } + + /** + * Retrieve Original Order data + * + * @param int $orderIncrementId + * @return mixed + */ + public function getOriginalOrder($orderIncrementId) + { + $order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId); + return $order; + } + + /** + * Retrieve Address data + * + * @param int $addressId + * + * @return \Magento\Customer\Api\Data\AddressInterface + */ + public function getAddressData($addressId) + { + try { + $addressData = $this->addressRepository->getById($addressId); + } catch (\Exception $e) { + throw $e->getMessage(); + } + return $addressData; + } + + /** + * Retrieve text of street lines, concatenated using LF symbol + * + * @param string $streetData + * @return string + */ + public function getStreetFull($streetData) + { + $street = $streetData; + return is_array($street) ? implode("\n", $street) : ($street ?? ''); + } + + /** + * Update Shipment Data + * + * @param int $subscriptionId + * @return mixed + */ + public function getSubscription($subscriptionId) + { + return $this->subscriptionFactory + ->create() + ->load($subscriptionId); + } + + /** + * Update Shipment Data + * + * @param mixed $shipmentData + * @return string + */ + + public function updateRecurringShipment($shipmentData) : string + { + $shipmentUpdateMsg = [ + 'success'=> false, + 'msg'=> '' + ]; + try { + if (!empty($shipmentData)) { + + $orderIncrementId = $shipmentData['orderIncrementId']; + $addressId = $shipmentData['addressId']; + $shipmentMethodData = $shipmentData['shipping_method']; + $subscriptionId = $shipmentData['subscription_id']; + $currentSubscription = $this->getSubscription($subscriptionId); + + $addressData = $this->getAddressData($addressId); + + $subscriptionOldInfo = $this->editSubscriptionRepository->getSubscriptionData($subscriptionId); + $shippingOldAddress = $subscriptionOldInfo->getShippingAddress(); + $transactionData = $this->getTransactionData($currentSubscription); + $paymentMethod = $transactionData->getMethod(); + + $this->updateAddress($currentSubscription, $addressData); + $this->updateShipmentAmount($currentSubscription, $shipmentMethodData); + $this->editSubscriptionRepository + ->updateEditHistory( + $subscriptionOldInfo, + $shippingOldAddress, + $paymentMethod + ); + $shipmentUpdateMsg = [ + 'success'=> true, + 'msg'=> 'Shipping data updated' + ]; + } + } catch (\Exception $e) { + $shipmentUpdateMsg = [ + 'success'=> false, + 'msg'=> $e->getMessage() + ]; + } + return json_encode($shipmentUpdateMsg); + } + + /** + * Update Address + * + * @param object $subscriptionObj + * @param mixed $addressData + * + * @return mixed + */ + public function updateAddress($subscriptionObj, $addressData) + { + $subscription = $subscriptionObj->getShippingAddress(); + try { + + if ($addressData->getFirstname() != $subscription->getFirstname() || + $addressData->getLastname() != $subscription->getLastname() + ) { + $subscription->setFirstname($addressData->getFirstname()); + $subscription->setLastname($addressData->getLastname()); + $subscriptionObj->setBillingName($addressData->getFirstname() . ' ' . $addressData->getLastname()); + } + + if ($addressData->getStreet() != $subscription->getStreet()) { + $subscription->setStreet($addressData->getStreet()); + } + + if ($addressData->getCity() != $subscription->getCity()) { + $subscription->setCity($addressData->getCity()); + } + + /* 'region_id' may not be set for some countries */ + $regionId = $addressData->getRegionId(); + if (!empty($regionId) && $regionId != $subscription->getRegionId()) { + $region = $this->regionCollectionFactory + ->create() + ->getItemById((int) $regionId); + + $subscription->setRegionId($region->getRegionId()); + $subscription->setRegion($region->getName()); + } else { + $subscription->setRegionId($regionId); + $subscription->setRegion(''); + } + + if ($addressData->getPostcode() != $subscription->getPostcode()) { + $subscription->setPostcode($addressData->getPostcode()); + } + + if ($addressData->getCountryId() != $subscription->getCountryId()) { + $subscription->setCountryId($addressData->getCountryId()); + } + + if ($subscriptionObj->getShippingAddress()->hasDataChanges()) { + $subscriptionObj->setHasDataChanges(true); + } + if ($subscriptionObj->hasDataChanges()) { + $subscriptionObj->save(); + } + } catch (\Exception $e) { + throw $e->getMessage(); + } + } + + /** + * Transaction Data + * + * @param Subscription $subscriptionOrder + * + * @return mixed + */ + public function getTransactionData(\Sapient\Worldpay\Model\Recurring\Subscription $subscriptionOrder) + { + return $subscriptionOrder->getTransactionData(); + } + /** + * Update Shipping amount + * + * @param object $subscriptionObj + * @param object $shipmentMethodData + */ + public function updateShipmentAmount($subscriptionObj, $shipmentMethodData) + { + $shipmentPrice = $shipmentMethodData['price']; + $shippingMethod = $shipmentMethodData['carrier'].'_'.$shipmentMethodData['method']; + $shippingMethodTitle = $shipmentMethodData['carrier_title'].'-'.$shipmentMethodData['method_title']; + $subscriptionObj->setData('shipping_method', $shippingMethod); + $subscriptionObj->setData('shipping_description', $shippingMethodTitle); + $subscriptionObj->setData('shipping_amount', $shipmentPrice); + $subscriptionObj->save(); + } +} diff --git a/Model/Recurring/Order/UpdateRecurringToken.php b/Model/Recurring/Order/UpdateRecurringToken.php new file mode 100644 index 0000000..f769e8f --- /dev/null +++ b/Model/Recurring/Order/UpdateRecurringToken.php @@ -0,0 +1,233 @@ +scopeConfig = $scopeConfig; + $this->storeManager = $storeManager; + $this->coreRegistry = $registry; + $this->customerSession = $customerSession; + $this->transactionCollectionFactory = $recurringTransactions; + $this->subscriptionFactory = $subscriptionFactory; + $this->savedTokenService = $savedTokenService; + $this->savedToken = $savedToken; + $this->editSubscriptionRepository = $editSubscriptionRepository; + } + + /** + * Get store id + * + * @return int + */ + public function getStoreId() + { + return $this->storeManager->getStore()->getId(); + } + + /** + * Get token + * + * @param int $id + * @return string + */ + public function getToken($id) + { + return $this->savedToken->load($id); + } + + /** + * Get Current Subscription Order + * + * @return mixed + */ + public function getCurrentSubscriptionOrder() + { + return $this->coreRegistry->registry('current_subscription_order'); + } + + /** + * Get Active Recurring Transaction + * + * @param int $subscriptionId + * @return mixed + */ + public function getActiveRecurringTransaction($subscriptionId) + { + $customer = $this->customerSession->getCustomer(); + return $this->transactionCollectionFactory->getCollection() + ->addFieldToFilter('status', ['eq' => 'active']) + ->addFieldToFilter('customer_Id', ['eq' => $customer->getId()]) + ->addFieldToFilter('subscription_id', ['eq' => $subscriptionId]); + } + + /** + * Update Token Data + * + * @param string $tokenId + * @param string $subscriptionId + * @return string + */ + + public function updateRecurringPaymentToken($tokenId, $subscriptionId): string + { + $result = [ + 'success' => false, + 'msg' => '' + ]; + try { + $currenntActiveTransaction = $this->getActiveRecurringTransaction($subscriptionId); + + if ($currenntActiveTransaction->getSize()) { + + $transaction = $currenntActiveTransaction->getFirstItem(); + $this->verifyTokenFromWorldpay($tokenId); + + $subscriptionOldInfo = $this->editSubscriptionRepository->getSubscriptionData($subscriptionId); + $shippingOldAddress = $subscriptionOldInfo->getShippingAddress(); + $transactionData = $this->getTransactionData($subscriptionOldInfo); + $paymentMethod = $transactionData->getMethod(); + + $transaction->setData('worldpay_token_id', $tokenId); + $transaction->save(); + + $this->editSubscriptionRepository + ->updateEditHistory( + $subscriptionOldInfo, + $shippingOldAddress, + $paymentMethod + ); + $result = [ + 'success' => true, + 'msg' => 'Token Updated in Recurring order' + ]; + } + } catch (\Exception $e) { + $result = [ + 'success' => false, + 'msg' => $e->getMessage() + ]; + } + return json_encode($result); + } + + /** + * Verify Token From Worldpay + * + * @param int $savedTokenId + * @return mixed + */ + public function verifyTokenFromWorldpay($savedTokenId) + { + $customer = $this->customerSession->getCustomer(); + $savedToken = $this->getToken($savedTokenId); + return $this->savedTokenService->getTokenInquiry( + $savedToken, + $customer, + $this->getStoreId() + ); + } + + /** + * Get Transaction Data + * + * @param Subscription $subscriptionOrder + * @return mixed + */ + public function getTransactionData(\Sapient\Worldpay\Model\Recurring\Subscription $subscriptionOrder) + { + return $subscriptionOrder->getTransactionData(); + } +} diff --git a/Model/Recurring/Subscription.php b/Model/Recurring/Subscription.php index c482c8f..0d4ce98 100644 --- a/Model/Recurring/Subscription.php +++ b/Model/Recurring/Subscription.php @@ -171,6 +171,11 @@ class Subscription extends \Magento\Framework\Model\AbstractModel */ private $recurringHelper; + /** + * @var \Sapient\Worldpay\Model\ResourceModel\SavedToken + */ + private $savedToken; + /** * Subscription model constructor. * @@ -186,6 +191,7 @@ class Subscription extends \Magento\Framework\Model\AbstractModel * @param \Magento\Framework\Api\SortOrderBuilder $sortOrderBuilder * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency * @param \Sapient\Worldpay\Model\Recurring\Subscription\TransactionsFactory $transactionsFactory + * @param \Sapient\Worldpay\Model\SavedToken $savedToken * @param \Magento\Framework\Model\ResourceModel\AbstractResource||null $resource * @param \Magento\Framework\Data\Collection\AbstractDb||null $resourceCollection * @param array $data @@ -204,6 +210,7 @@ public function __construct( \Magento\Framework\Api\SortOrderBuilder $sortOrderBuilder, \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency, \Sapient\Worldpay\Model\Recurring\Subscription\TransactionsFactory $transactionsFactory, + \Sapient\Worldpay\Model\SavedToken $savedToken, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] @@ -220,6 +227,7 @@ public function __construct( $this->priceCurrency = $priceCurrency; $this->transactionsFactory = $transactionsFactory; $this->registryObj = $registry; + $this->savedToken = $savedToken; } /** @@ -232,7 +240,9 @@ protected function _construct() $this->_init(\Sapient\Worldpay\Model\ResourceModel\Recurring\Subscription::class); } /** - * @inheritdoc + * After save + * + * @return mixed */ public function afterSave() { @@ -431,7 +441,7 @@ public function getBillingAddress() /** * Retrieve order shipping address * - * @return \Magento\Sales\Model\Order\Address|null + * @return \Sapient\Worldpay\Model\Recurring\Subscription\Address|null */ public function getShippingAddress() { @@ -841,4 +851,23 @@ public function loadByOrderId($order_id) $id = $this->getResource()->loadByOriginalOrderIncrementId($order_id); return $this->load($id); } + /** + * Function to get is virtual column data + */ + public function getIsVirtual() + { + return $this->getData('is_virtual'); + } + + /** + * Function to get subscription transaction data + */ + public function getTransactionData() + { + $transactions = $this->transactionsFactory->create() + ->loadBySubscriptionIdActive($this->getSubscriptionId()); + $tokenDetails = $this->savedToken->load($transactions->getData('worldpay_token_id')); + + return $tokenDetails; + } } diff --git a/Model/Recurring/Subscription/Transactions.php b/Model/Recurring/Subscription/Transactions.php index 58b02ad..ddf57de 100644 --- a/Model/Recurring/Subscription/Transactions.php +++ b/Model/Recurring/Subscription/Transactions.php @@ -21,7 +21,7 @@ class Transactions extends AbstractModel private $subscription; /** - * Transactions constructor + * Initialize resource model * * @return void */ @@ -124,4 +124,19 @@ public function loadById($entityId) $id = $this->getResource()->loadById($entityId); return $this->load($id); } + + /** + * Load Subscription Active order Details + * + * @param int $subscriptionId + * @return array + */ + public function loadBySubscriptionIdActive($subscriptionId) + { + if (!$subscriptionId) { + return; + } + $id = $this->getResource()->loadBySubscriptionIdActive($subscriptionId); + return $this->load($id); + } } diff --git a/Model/Request/PaymentServiceRequest.php b/Model/Request/PaymentServiceRequest.php index 07f31d2..dc28d8f 100644 --- a/Model/Request/PaymentServiceRequest.php +++ b/Model/Request/PaymentServiceRequest.php @@ -229,6 +229,9 @@ public function order($directOrderParams) $this->customerSession, $requestConfiguration ); + if ($this->worldpayhelper->getsubscriptionStatus()) { + $directOrderParams['paymentDetails']['subscription_order'] = 1; + } if (empty($directOrderParams['thirdPartyData']) && empty($directOrderParams['shippingfee'])) { $directOrderParams['thirdPartyData']=''; @@ -288,7 +291,7 @@ public function order($directOrderParams) return $this->_sendRequest( dom_import_simplexml($orderSimpleXml)->ownerDocument, $xmlUsername, - $xmlPassword + $xmlPassword, ); } @@ -610,6 +613,10 @@ public function redirectOrder($redirectOrderParams) ); } + if ($this->worldpayhelper->getsubscriptionStatus()) { + $redirectOrderParams['paymentDetails']['subscription_order'] = 1; + } + if (empty($redirectOrderParams['thirdPartyData']) && empty($redirectOrderParams['shippingfee'])) { $redirectOrderParams['thirdPartyData']=''; $redirectOrderParams['shippingfee']=''; @@ -1803,7 +1810,7 @@ public function getItemDetails($capturedItems) public function collectPluginTrackerDetails($paymentType) { $pluginTrackerDetails = $this->worldpayhelper->getPluginTrackerdetails(); - $pluginTrackerDetails['additional_detail'] = $paymentType; + $pluginTrackerDetails['additional_details']['transaction_method'] = $paymentType; return json_encode($pluginTrackerDetails); } } diff --git a/Model/ResourceModel/EditSubscriptionHistory.php b/Model/ResourceModel/EditSubscriptionHistory.php new file mode 100644 index 0000000..8a1293d --- /dev/null +++ b/Model/ResourceModel/EditSubscriptionHistory.php @@ -0,0 +1,21 @@ +_init('worldpay_subscription_edit_history', 'entity_id'); + } +} diff --git a/Model/ResourceModel/EditSubscriptionHistory/Collection.php b/Model/ResourceModel/EditSubscriptionHistory/Collection.php new file mode 100644 index 0000000..ed63dfe --- /dev/null +++ b/Model/ResourceModel/EditSubscriptionHistory/Collection.php @@ -0,0 +1,25 @@ +_init( + \Sapient\Worldpay\Model\EditSubscriptionHistory::class, + \Sapient\Worldpay\Model\ResourceModel\EditSubscriptionHistory::class + ); + } +} diff --git a/Model/ResourceModel/Recurring/Subscription/Address/.LCKCollection.php~ b/Model/ResourceModel/Recurring/Subscription/Address/.LCKCollection.php~ deleted file mode 100644 index 1d2b74d..0000000 --- a/Model/ResourceModel/Recurring/Subscription/Address/.LCKCollection.php~ +++ /dev/null @@ -1 +0,0 @@ -C:\xampp\htdocs\worldpay\vendor\sapient\module-worldpay\Model\ResourceModel\Recurring\Subscription\Address\Collection.php \ No newline at end of file diff --git a/Model/ResourceModel/Recurring/Subscription/Transactions.php b/Model/ResourceModel/Recurring/Subscription/Transactions.php index 9eaf35b..8054f17 100644 --- a/Model/ResourceModel/Recurring/Subscription/Transactions.php +++ b/Model/ResourceModel/Recurring/Subscription/Transactions.php @@ -91,4 +91,21 @@ public function loadById($entityId) $id = $this->getConnection()->fetchOne($sql); return $id; } + + /** + * Load Active Transcation detail by $subscriptionId + * + * @param int $subscriptionId + * @return int $id + */ + public function loadBySubscriptionIdActive($subscriptionId) + { + $active = "active"; + $table = $this->getMainTable(); + $where = $this->getConnection()->quoteInto("subscription_id = ?", $subscriptionId); + $whereTwo = $this->getConnection()->quoteInto("status = ?", $active); + $sql = $this->getConnection()->select()->from($table, ['entity_id'])->where($where)->where($whereTwo); + $id = $this->getConnection()->fetchOne($sql); + return $id; + } } diff --git a/Model/ResourceModel/Recurring/Subscription/Transactions/Collection.php b/Model/ResourceModel/Recurring/Subscription/Transactions/Collection.php index d045810..b40413a 100644 --- a/Model/ResourceModel/Recurring/Subscription/Transactions/Collection.php +++ b/Model/ResourceModel/Recurring/Subscription/Transactions/Collection.php @@ -9,7 +9,7 @@ class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { /** - * @var string + * @var string $_idFieldName */ protected $_idFieldName = 'entity_id'; @@ -46,4 +46,18 @@ public function setSubscriptionFilter(\Sapient\Worldpay\Model\Recurring\Subscrip } return $this; } + + /** + * Set Status Filter + * + * @param Subscription $subscription + * @return $this + */ + public function setStatusFilter(\Sapient\Worldpay\Model\Recurring\Subscription $subscription) + { + if ($subscription->getId()) { + $this->addFieldToFilter('status', 'active'); + } + return $this; + } } diff --git a/Model/ResourceModel/SkipSubscriptionOrder.php b/Model/ResourceModel/SkipSubscriptionOrder.php new file mode 100644 index 0000000..2437361 --- /dev/null +++ b/Model/ResourceModel/SkipSubscriptionOrder.php @@ -0,0 +1,21 @@ +_init('worldpay_subscription_skip_orders', 'entity_id'); + } +} diff --git a/Model/ResourceModel/SkipSubscriptionOrder/Collection.php b/Model/ResourceModel/SkipSubscriptionOrder/Collection.php new file mode 100644 index 0000000..5fe5761 --- /dev/null +++ b/Model/ResourceModel/SkipSubscriptionOrder/Collection.php @@ -0,0 +1,94 @@ +_init( + \Sapient\Worldpay\Model\SkipSubscriptionOrder::class, + \Sapient\Worldpay\Model\ResourceModel\SkipSubscriptionOrder::class + ); + } + + /** + * Filter collection by customer id + * + * @param int $customerId + * @return $this + */ + public function addCustomerIdFilter($customerId) + { + if ($customerId) { + $this->addFieldToFilter('main_table.customer_id', $customerId); + } + + return $this; + } + + /** + * Join plans table + * + * @param array|string $cols + * @return $this + */ + public function joinPlans($cols = \Magento\Framework\DB\Select::SQL_WILDCARD) + { + if ($this->plansJoined) { + return $this; + } + + $this->getSelect()->joinLeft( + ['plans' => 'worldpay_recurring_plans'], + 'plans.plan_id = subscriptions.plan_id', + $cols ); + $this->plansJoined = true; + + return $this; + } + /** + * Join Subscriptions table + * + * @param array|string $cols + * @return $this + */ + public function joinSubscriptions($cols = \Magento\Framework\DB\Select::SQL_WILDCARD) + { + if ($this->subscriptionsJoined) { + return $this; + } + + $this->getSelect()->joinLeft( + ['subscriptions' => 'worldpay_subscriptions'], + 'subscriptions.subscription_id = main_table.subscription_id', + $cols ); + $this->subscriptionsJoined = true; + + return $this; + } +} diff --git a/Model/ResourceModel/SubscriptionOrder.php b/Model/ResourceModel/SubscriptionOrder.php new file mode 100644 index 0000000..8ccaf65 --- /dev/null +++ b/Model/ResourceModel/SubscriptionOrder.php @@ -0,0 +1,23 @@ +_init('worldpay_recurring_transactions', 'entity_id'); + } +} diff --git a/Model/ResourceModel/SubscriptionOrder/Collection.php b/Model/ResourceModel/SubscriptionOrder/Collection.php new file mode 100644 index 0000000..8536476 --- /dev/null +++ b/Model/ResourceModel/SubscriptionOrder/Collection.php @@ -0,0 +1,97 @@ +_init( + \Sapient\Worldpay\Model\SubscriptionOrder::class, + \Sapient\Worldpay\Model\ResourceModel\SubscriptionOrder::class + ); + } + + /** + * Filter collection by customer id + * + * @param int $customerId + * @return $this + */ + public function addCustomerIdFilter($customerId) + { + if ($customerId) { + $this->addFieldToFilter('main_table.customer_id', $customerId); + } + + return $this; + } + + /** + * Join plans table + * + * @param array|string $cols + * @return $this + */ + public function joinPlans($cols = \Magento\Framework\DB\Select::SQL_WILDCARD) + { + if ($this->plansJoined) { + return $this; + } + + $this->getSelect()->joinLeft( + ['plans' => 'worldpay_recurring_plans'], + 'plans.plan_id = main_table.plan_id', + $cols ); + $this->plansJoined = true; + + return $this; + } + /** + * Join Subscriptions table + * + * @param array|string $cols + * @return $this + */ + public function joinSubscriptions($cols = \Magento\Framework\DB\Select::SQL_WILDCARD) + { + if ($this->subscriptionsJoined) { + return $this; + } + + $this->getSelect()->joinLeft( + ['subscriptions' => 'worldpay_subscriptions'], + 'subscriptions.subscription_id = main_table.subscription_id', + $cols ); + $this->subscriptionsJoined = true; + + return $this; + } + +} diff --git a/Model/SkipSubscriptionOrder.php b/Model/SkipSubscriptionOrder.php new file mode 100644 index 0000000..453a1fb --- /dev/null +++ b/Model/SkipSubscriptionOrder.php @@ -0,0 +1,300 @@ +recurringhelper = $recurringhelper; + $this->skipSubcriptionCollectionFactory = $skipSubcriptionCollectionFactory; + $this->orderRepository = $orderRepository; + $this->customerSession = $customerSession; + } + + /** + * Initialize resource model + * + * @return void + */ + + protected function _construct() + { + /** + * Initialize resource model + * + * @return void + */ + $this->_init(\Sapient\Worldpay\Model\ResourceModel\SkipSubscriptionOrder::class); + } + /** + * Load Subscription order + * + * @param string $subscriptionId + * @param string $timeFilterby + * + * @return \Sapient\Worldpay\Model\skipSubscriptionOrderCollection + */ + public function getskipSubscriptionOrderCollection($subscriptionId, $timeFilterby) + { + if ($this->skipSubscriptionOrderCollection === null) { + $this->skipSubscriptionOrderCollection = $this->skipSubcriptionCollectionFactory->create(); + $this->skipSubscriptionOrderCollection + ->addFieldToFilter("main_table.subscription_id", ['eq' => $subscriptionId]) + ->joinSubscriptions(['product_name']) + ->joinPlans(['interval', 'interval_amount']) + ->addFieldToFilter('main_table.created_at', ['gteq'=> $timeFilterby]) + ->addCustomerIdFilter($this->customerSession->getCustomerId()) + ->addOrder('created_at', \Magento\Framework\Data\Collection::SORT_ORDER_DESC); + } + return $this->skipSubscriptionOrderCollection; + } + + /** + * Load Order by origin order id + * + * @param string $orderId + * @return orderRepository + */ + public function getOrderbyOriginalId($orderId) + { + $order = $this->orderRepository->get($orderId); + return $order; + } + + /** + * Return date for filter + * + * @param string $timeinterval + * @return string + */ + public function getFilterDate($timeinterval) + { + $period = 'm'; + if (!empty($timeinterval)) { + $timeInt = explode('-', $timeinterval); + $period = $timeInt[0]; + } + switch ($period) { + case 'm': + $time = strtotime(time());//$time = strtotime("-6 month", time()); + $date = date('Y-01-01'); + break; + case 'y': + $date = date('Y-01-01');//date("Y-m-d", $time); + break; + default: + $time = strtotime("-6 month", time()); + $date = date("Y-m-d", $time); + } + return $date; + } + + /** + * Get entityId + */ + public function getId() + { + return parent::getData(self::ENTITY_ID); + } + + /** + * Set entityId + * + * @param int $entityId + */ + public function setId($entityId) + { + return $this->setData(self::ENTITY_ID, $entityId); + } + + /** + * Get SubscriptionId + */ + public function getSubscriptionId() + { + return parent::getData(self::SUBSCRIPTION_ID); + } + + /** + * Set SubscriptionId + * + * @param int $subscriptionId + */ + public function setSubscriptionId($subscriptionId) + { + return $this->setData(self::SUBSCRIPTION_ID, $subscriptionId); + } + + /** + * Get CustomerId + */ + public function getCustomerId() + { + return parent::getData(self::CUSTOMER_ID); + } + + /** + * Set CustomerId + * + * @param int $customerId + */ + public function setCustomerId($customerId) + { + return $this->setData(self::CUSTOMER_ID, $customerId); + } + + /** + * Get IsSkipped + */ + public function getIsSkipped() + { + return parent::setIsSkipped(self::IS_SKIPPED); + } + + /** + * Set IsSkipped + * + * @param bool $isSkipped + */ + public function setIsSkipped($isSkipped) + { + return $this->setData(self::IS_SKIPPED, $isSkipped); + } + + /** + * Get NewRecurringDate + */ + public function getNewRecurringDate() + { + return $this->setData(self::NEW_RECURRING_DATE); + } + + /** + * Set NewRecurringDate + * + * @param string $newRecurringDate + * return mixed + */ + public function setNewRecurringDate($newRecurringDate) + { + return $this->setData(self::NEW_RECURRING_DATE, $newRecurringDate); + } + + /** + * Get OldRecurringDate + */ + public function getOldRecurringDate() + { + return $this->setData(self::OLD_RECURRING_DATE); + } + + /** + * Set OldRecurringDate + * + * @param string $oldRecurringDate + */ + public function setOldRecurringDate($oldRecurringDate) + { + return $this->setData(self::OLD_RECURRING_DATE, $oldRecurringDate); + } + + /** + * Get Created Date + */ + public function getCreatedAt() + { + return $this->setData(self::CREATED_AT); + } + + /** + * Set Created Date + * + * @param string $createdAt + */ + public function setCreatedAt($createdAt) + { + return $this->setData(self::CREATED_AT, $createdAt); + } + + /** + * Get updated date + * + * @param string $updatedAt + */ + public function getUpdatedAt() + { + return $this->setData(self::UPDATED_AT); + } + + /** + * Set updatedAt + * + * @param string $updatedAt + */ + public function setUpdatedAt($updatedAt) + { + return $this->setData(self::UPDATED_AT, $updatedAt); + } +} diff --git a/Model/SkipSubscriptionOrderRepository.php b/Model/SkipSubscriptionOrderRepository.php new file mode 100644 index 0000000..6a5a68e --- /dev/null +++ b/Model/SkipSubscriptionOrderRepository.php @@ -0,0 +1,264 @@ +skipOrderFactory = $skipOrderFactory; + $this->skipOrderResource = $skipOrderResource; + $this->skipOrderCollectionFactory = $skipOrderCollectionFactory; + $this->subscriptionCollectionFactory = $subscriptionCollectionFactory; + $this->customerSession = $customerSession; + $this->transactionFactory = $transactionsFactory; + $this->planFactory = $planFactory; + $this->skipOrderEmail = $skipOrderEmail; + $this->wplogger = $wplogger; + $this->recurringhelper = $recurringhelper; + } + + /** + * Get Skipked subscription Order By Id + * + * @param int $id + * @return \Sapient\Worldpay\Api\Data\StudentInterface + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ + public function getById($id) + { + $editHistory = $this->skipOrderFactory->create(); + $this->editHistoryResource->load($editHistory, $id); + if (!$editHistory->getId()) { + throw new NoSuchEntityException(__('Unable to find History with ID "%1"', $id)); + } + return $editHistory; + } + + /** + * Save Skipked subscription Order + * + * @param SkipSubscriptionOrderInterface $skipSubscriptionOrder + * @return mixed + */ + public function save(SkipSubscriptionOrderInterface $skipSubscriptionOrder): mixed + { + $this->skipOrderResource->save($skipSubscriptionOrder); + return $skipSubscriptionOrder; + } + + /** + * Update Skipked subscription Order + * + * @param mixed $params + * @return mixed + */ + public function updateSkipHistory($params) + { + + $subscriptionId = $params['subscriptionId']; + $recurringDate = date('Y-m-d', strtotime($params['nextOrder'])); + $customer = $this->customerSession->getCustomer(); + $customerId = $customer->getId(); + $customerName = $customer->getName(); + $subscriptionOrderData = $this->getsubscriptionOrderCollection( + $subscriptionId, + $customerId, + $recurringDate + ); + $recurringId = $subscriptionOrderData->getId(); + $newrecucceringDate = $this->updateSkipOrderDate($recurringId, $recurringDate); + $skipOrderHistory = $this->skipOrderFactory->create(); + try { + $orderId = $subscriptionOrderData->getOriginalOrderId(); + $skipOrderParams['orderId'] = $subscriptionOrderData->getOriginalOrderIncrementId(); + $skipOrderParams['customerName'] = $customerName; + $skipOrderParams['recurring_date'] = $recurringDate; + $skipOrderParams['order_data'] = $this->recurringhelper->getOrderDetails($orderId); + $skipOrderHistory->setSubscriptionId($subscriptionId); + $skipOrderHistory->setCustomerId($customerId); + $skipOrderHistory->setNewRecurringDate($newrecucceringDate); + $skipOrderHistory->setOldRecurringDate($recurringDate); + $skipOrderHistory->save(); + $this->skipOrderEmail->sendSkipOrderEmail($skipOrderParams); + + $this->wplogger->info(__('Skipped and next order date is: '). $newrecucceringDate); + return true; + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * Load Subscription order collection + * + * @param string $subscriptionId + * @param string $customerId + * @param string $recurringDate + * + * @return \Sapient\Worldpay\Model\subscriptionOrde + */ + public function getsubscriptionOrderCollection($subscriptionId, $customerId, $recurringDate) + { + if ($this->subscriptionOrderCollection === null) { + $this->subscriptionOrderCollection = $this->subscriptionCollectionFactory->create(); + $this->subscriptionOrderCollection + ->addFieldToFilter("subscription_id", ['eq' => $subscriptionId]) + ->addFieldToFilter("customer_id", ['eq' => $customerId]) + ->addFieldToFilter('status', ['eq' => 'active']); + } + return $this->subscriptionOrderCollection->getFirstItem(); + } + + /** + * Update Subscription order date in database + * + * @param int $id + * @param string $oldRecurringDate + * @return string + */ + public function updateSkipOrderDate($id, $oldRecurringDate) + { + $transactionDetails = $this->transactionFactory->create()->loadById($id); + + if ($transactionDetails) { + $date = $transactionDetails->getRecurringDate(); + $recurringEndDate = $transactionDetails->getRecurringEndDate(); + $week = strtotime(date("Y-m-d", strtotime($date)) . " +1 week"); + $monthdate = strtotime(date("Y-m-d", strtotime($date)) . " +1 month"); + $tmonthsdate = strtotime(date("Y-m-d", strtotime($date)) . " +3 month"); + $sixmonthsdate = strtotime(date("Y-m-d", strtotime($date)) . " +6 month"); + $yeardate = strtotime(date("Y-m-d", strtotime($date)) . " +12 month"); + + $plan = $this->planFactory->create()->loadById($transactionDetails->getPlanId()); + $planInterval = $plan->getInterval(); + + if ($planInterval == 'WEEKLY') { + $recurringDate = date('Y-m-d', $week); + } elseif ($planInterval == 'MONTHLY') { + $recurringDate = date('Y-m-d', $monthdate); + } elseif ($planInterval == 'QUARTERLY') { + $recurringDate = date('Y-m-d', $tmonthsdate); + } elseif ($planInterval == 'SEMIANNUAL') { + $recurringDate = date('Y-m-d', $sixmonthsdate); + } elseif ($planInterval == 'ANNUAL') { + $recurringDate = date('Y-m-d', $yeardate); + } + try { + if (strtotime($recurringDate) > strtotime($recurringEndDate)) { + $this->wplogger->info(__('Next order date is greater then End date: '). $recurringDate); + $transactionDetails->setRecurringDate($recurringEndDate); + $transactionDetails->setStatus('completed'); + $transactionDetails->save(); + return $oldRecurringDate; + } + $transactionDetails->setRecurringDate($recurringDate); + $transactionDetails->save(); + return $recurringDate; + + } catch (Exception $e) { + $this->wplogger + ->info(__('Skipped order date not updated: '). $e->getMessage()); + } + } + } +} diff --git a/Model/SubscriptionOrder.php b/Model/SubscriptionOrder.php new file mode 100644 index 0000000..cb0bcce --- /dev/null +++ b/Model/SubscriptionOrder.php @@ -0,0 +1,146 @@ +recurringhelper = $recurringhelper; + $this->subscriptionCollectionFactory = $subscriptionCollectionFactory; + $this->orderRepository = $orderRepository; + $this->customerSession = $customerSession; + } + + /** + * Initialize resource model + * + * @return void + */ + protected function _construct() + { + $this->_init(\Sapient\Worldpay\Model\ResourceModel\SubscriptionOrder::class); + } + + /** + * Load Subscription order + * + * @param string $subscriptionId + * @param string $timeFilterby + * @return \Sapient\Worldpay\Model\subscriptionOrde + */ + public function getsubscriptionOrderCollection($subscriptionId, $timeFilterby) + { + if ($this->subscriptionOrderCollection === null) { + $this->subscriptionOrderCollection = $this->subscriptionCollectionFactory->create(); + $this->subscriptionOrderCollection + ->addFieldToFilter("main_table.subscription_id", ['eq' => $subscriptionId]) + ->joinPlans(['interval', 'interval_amount']) + ->joinSubscriptions(['product_name']) + ->addFieldToFilter("main_table.status", ['eq' => 'completed']) + ->addFieldToFilter('main_table.created_at', ['gteq'=> $timeFilterby]) + ->addCustomerIdFilter($this->customerSession->getCustomerId()) + ->addOrder('created_at', \Magento\Framework\Data\Collection::SORT_ORDER_DESC); + } + return $this->subscriptionOrderCollection; + } + + /** + * Load Order by origin order id + * + * @param string $orderId + * @return orderRepository + */ + public function getOrderbyOriginalId($orderId) + { + $order = $this->orderRepository->get($orderId); + return $order; + } + + /** + * Return date for filter + * + * @param string $timeinterval + * @return string + */ + public function getFilterDate($timeinterval) + { + $period = 'm'; + if (!empty($timeinterval)) { + $timeInt = explode('-', $timeinterval); + $period = $timeInt[0]; + } + switch ($period) { + case 'm': + $time = strtotime(time());//$time = strtotime("-6 month", time()); + $date = date('Y-01-01'); + break; + case 'y': + $date = date('Y-01-01');//date("Y-m-d", $time); + break; + default: + $time = strtotime("-6 month", time()); + $date = date("Y-m-d", $time); + } + return $date; + } +} diff --git a/Model/System/Config/Backend/CurrentPluginVersion.php b/Model/System/Config/Backend/CurrentPluginVersion.php index 36f3ae7..5beccd4 100644 --- a/Model/System/Config/Backend/CurrentPluginVersion.php +++ b/Model/System/Config/Backend/CurrentPluginVersion.php @@ -74,7 +74,7 @@ protected function _afterLoad() $value = $this->getValue(); $moduleVersion = $this->getModuleVersion(self::MODULE_NAME); if (isset($moduleVersion)) { - $this->setValue($moduleVersion); + $this->setValue(trim($moduleVersion), ','); $this->configWriter->save( 'worldpay/general_config/plugin_tracker/current_wopay_plugin_version', $moduleVersion diff --git a/Model/System/Config/Backend/PluginUpgradeDates.php b/Model/System/Config/Backend/PluginUpgradeDates.php index 7711158..ff975d1 100644 --- a/Model/System/Config/Backend/PluginUpgradeDates.php +++ b/Model/System/Config/Backend/PluginUpgradeDates.php @@ -9,7 +9,8 @@ */ class PluginUpgradeDates extends \Magento\Framework\App\Config\Value { - + /* Module Name */ + public const MODULE_NAME = 'Sapient_Worldpay'; /** * * @var \Sapient\Worldpay\Logger\WorldpayLogger @@ -42,6 +43,11 @@ class PluginUpgradeDates extends \Magento\Framework\App\Config\Value * @var \Sapient\Worldpay\Model\System\Config\Backend\PluginVersionHistory */ private $versionhistory; + + /** + * @var \Sapient\Worldpay\Model\System\Config\Backend\CurrentPluginVersion + */ + private $currentversionconfig; /** * Constructor * @@ -51,6 +57,7 @@ class PluginUpgradeDates extends \Magento\Framework\App\Config\Value * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList * @param \Sapient\Worldpay\Logger\WorldpayLogger $wplogger * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig + * @param \Sapient\Worldpay\Model\System\Config\Backend\CurrentPluginVersion $currentversionconfig * @param \Magento\Framework\App\Cache\Manager $cacheManager * @param \Sapient\Worldpay\Model\System\Config\Backend\PluginVersionHistory $versionhistory * @param \Magento\Framework\App\Config\Storage\WriterInterface $configWriter @@ -65,6 +72,7 @@ public function __construct( \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Sapient\Worldpay\Logger\WorldpayLogger $wplogger, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, + \Sapient\Worldpay\Model\System\Config\Backend\CurrentPluginVersion $currentversionconfig, \Magento\Framework\App\Cache\Manager $cacheManager, \Sapient\Worldpay\Model\System\Config\Backend\PluginVersionHistory $versionhistory, \Magento\Framework\App\Config\Storage\WriterInterface $configWriter, @@ -75,6 +83,7 @@ public function __construct( $this->wplogger = $wplogger; $this->scopeConfig = $scopeConfig; $this->configWriter = $configWriter; + $this->currentversionconfig = $currentversionconfig; $this->cacheManager = $cacheManager; $this->versionhistory = $versionhistory; parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); @@ -91,8 +100,13 @@ protected function _afterLoad() $value = $this->getUpgradeDates(); if ((isset($value['oldData']) && !empty($value['oldData'])) && (isset($value['newData']) && !empty($value['newData']))) { - $data = $value['oldData'].",".$value['newData']; + if ($value['is_new_version']) { + $data = $value['oldData'].",".$value['newData']; + } else { + $data = $value['oldData']; + } $data =(array_unique(explode(",", $data))); + $data = array_slice($data, -3, 3, true); $data = implode(",", $data); $this->setValue($data); $this->configWriter->save( @@ -123,8 +137,13 @@ public function beforeSave() $value = $this->getUpgradeDates(); if ((isset($value['oldData']) && !empty($value['oldData'])) && (isset($value['newData']) && !empty($value['newData']))) { - $data = $value['oldData'].",".$value['newData']; + if ($value['is_new_version']) { + $data = $value['oldData'].",".$value['newData']; + } else { + $data = $value['oldData']; + } $data =(array_unique(explode(",", $data))); + $data = array_slice($data, -3, 3, true); $data = implode(",", $data); $this->setValue($data); $this->configWriter->save( @@ -152,7 +171,6 @@ public function getUpgradeDates() 'worldpay/general_config/plugin_tracker/current_wopay_plugin_version', \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); - //plugin upgrade dates $currentHistoryData = $this->scopeConfig->getValue( 'worldpay/general_config/plugin_tracker/upgrade_dates', @@ -163,10 +181,22 @@ public function getUpgradeDates() 'worldpay/general_config/plugin_tracker/wopay_plugin_version_history', \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); - if (isset($currentHistoryData) && !empty($currentHistoryData)) { $value['oldData'] = $currentHistoryData; } + //check new version + $currentVersion['newVersion'] = $this->currentversionconfig->getModuleVersion(self::MODULE_NAME); + if ($currentPluginData && + (isset($currentVersion['newVersion']) && $currentVersion['newVersion'] == $currentPluginData)) { + $value['newVersion'] = $currentPluginData; + } else { + $value['newVersion'] = isset($currentVersion['newVersion'])?$currentVersion['newVersion']:""; + } + $currentVersionHistoryDataAry = explode(',', (string) $currentVersionHistoryData); + $value['is_new_version'] = false; + if (!in_array($value['newVersion'], $currentVersionHistoryDataAry)) { + $value['is_new_version'] = true; + } $pastversions = $this->getVersionHistoryDetails()!=null? $this->getVersionHistoryDetails() :$currentVersionHistoryData; @@ -175,16 +205,24 @@ public function getUpgradeDates() } if (empty($currentHistoryData)) { - $value['newData'] = date("d-m-Y"); + $value['newData'] = date("d-m-Y").' - ('.$pastversions.')'; + ; return $value; } else { $datesHistoryData = explode(',', $currentHistoryData); } - if (empty($currentPluginData) || (!empty($currentPluginData) && empty($currentVersionHistoryData) - && (empty($value['oldData']))) || (count($versionHistoryData) != count($datesHistoryData))) { - $data = date("d-m-Y"); + && (empty($value['oldData']))) || (count($versionHistoryData) != count($datesHistoryData)) + ) { + + if (count($versionHistoryData) >= 2) { + $recentPluginVersion = array_slice($versionHistoryData, -2, 2, false); + $data = date("d-m-Y").' - ('.$recentPluginVersion[0].' to '.$recentPluginVersion[1].')'; + + } else { + $data = date("d-m-Y").' ('.$versionHistoryData[0].')'; + } $value['newData'] = $data; if (isset($value['oldData']) && ($value['oldData'] == $value['newData'])) { $value['oldData'] = ""; diff --git a/Model/System/Config/Backend/PluginVersionHistory.php b/Model/System/Config/Backend/PluginVersionHistory.php index c4f662b..cb04379 100644 --- a/Model/System/Config/Backend/PluginVersionHistory.php +++ b/Model/System/Config/Backend/PluginVersionHistory.php @@ -86,6 +86,7 @@ protected function _afterLoad() && (isset($value['newData']) && !empty($value['newData']))) { $data = $value['oldData'].",".$value['newData']; $data =(array_unique(explode(",", $data))); + $data = array_slice($data, -3, 3, true); $data = implode(",", $data); $this->setValue($data); $this->configWriter->save( @@ -118,14 +119,15 @@ public function beforeSave() && (isset($value['newData']) && !empty($value['newData']))) { $data = $value['oldData'].",".$value['newData']; $data =(array_unique(explode(",", $data))); + $data = array_slice($data, -3, 3, true); $data = implode(",", $data); - $this->setValue($data); + $this->setValue(trim($data, ',')); $this->configWriter->save( 'worldpay/general_config/plugin_tracker/wopay_plugin_version_history', $data ); } elseif (isset($value['newData'])) { - $this->setValue($value['newData']); + $this->setValue(trim($value['newData']), ','); $this->configWriter->save( 'worldpay/general_config/plugin_tracker/wopay_plugin_version_history', $value['newData'] diff --git a/Model/Token.php b/Model/Token.php index 5afaa93..9b83e6d 100644 --- a/Model/Token.php +++ b/Model/Token.php @@ -28,7 +28,14 @@ class Token * @var \Magento\Framework\Session\SessionManager */ protected $_session; - + /** + * @var \Sapient\Worldpay\Model\XmlBuilder\DirectOrderToken + */ + protected $xmlDirectOrderToken; + /** + * @var \Sapient\Worldpay\Logger\WorldpayLogger + */ + protected $_wplogger; /** * Constructor * diff --git a/Model/WorldpayConfigProvider.php b/Model/WorldpayConfigProvider.php index ed0cee3..c820b4f 100644 --- a/Model/WorldpayConfigProvider.php +++ b/Model/WorldpayConfigProvider.php @@ -246,9 +246,23 @@ public function getConfig() googleGatewayMerchantid(); $config['payment']['ccform']['googleMerchantname'] = $this->worldpayHelper->googleMerchantname(); $config['payment']['ccform']['googleMerchantid'] = $this->worldpayHelper->googleMerchantid(); + $config['payment']['ccform']['gpayButtonColor'] = $this->worldpayHelper->getGpayButtonColor(); + $config['payment']['ccform']['gpayButtonType'] = $this->worldpayHelper->getGpayButtonType(); + $config['payment']['ccform']['gpayButtonLocale'] = $this->worldpayHelper->getGpayButtonLocale(); $config['payment']['ccform']['appleMerchantid'] = $this->worldpayHelper->appleMerchantId(); $config['payment']['ccform']['isApplePayEnable'] = $this->worldpayHelper->isApplePayEnable(); + $config['payment']['ccform']['applePayButtonColor'] = $this->worldpayHelper + ->getCheckoutApplePayBtnColor(); + $config['payment']['ccform']['applePayButtonType'] = $this->worldpayHelper + ->getCheckoutApplePayBtnType(); + $config['payment']['ccform']['applePayButtonLocale'] = $this->worldpayHelper + ->getCheckoutApplePayBtnLocale(); + + // Multishipping Apple Pay configuration + $config['payment']['ccform']['msAppleMerchantid'] = $this->worldpayHelper->msAppleMerchantId(); + $config['payment']['ccform']['isMsApplePayEnable'] = $this->worldpayHelper->isMsApplePayEnable(); $config['payment']['ccform']['isSamsungPayEnable'] = $this->worldpayHelper->isSamsungPayEnable(); + $config['payment']['ccform']['samsungPayButton'] = $this->worldpayHelper->getSamsungPayButtonType(); if ($this->worldpayHelper->getEnvironmentMode()=='Live Mode') { $config['payment']['general']['environmentMode'] = "PRODUCTION"; @@ -306,7 +320,21 @@ public function getConfig() //Multishipping $config['payment']['ccform']['isMultishipping'] = $this->worldpayHelper->isMultiShipping(); - //Pay By Link + // Multishipping Googlpay start + $config['payment']['ccform']['isMsGooglePayEnable'] = $this->worldpayHelper->isMsGooglePayEnable(); + $config['payment']['ccform']['msGooglePaymentMethods'] = $this->worldpayHelper + ->msGooglePaymentMethods(); + $config['payment']['ccform']['msGoogleAuthMethods'] = $this->worldpayHelper->msGoogleAuthMethods(); + $config['payment']['ccform']['msGoogleGatewayMerchantname'] = $this->worldpayHelper-> + msGoogleGatewayMerchantname(); + $config['payment']['ccform']['msGoogleGatewayMerchantid'] = $this->worldpayHelper-> + msGoogleGatewayMerchantid(); + $config['payment']['ccform']['msGoogleMerchantname'] = $this->worldpayHelper->msGoogleMerchantname(); + $config['payment']['ccform']['msGoogleMerchantid'] = $this->worldpayHelper->msGoogleMerchantid(); + + //End multishipping Google pay + $config['payment']['ccform']['isMsSamsungPayEnable'] = $this->worldpayHelper->isMsSamsungPayEnable(); + //Pay By Link $config['payment']['ccform']['isPayByLinkEnable'] = $this->worldpayHelper->isPayByLinkEnable(); $config['payment']['ccform']['payByLinkButtonName'] = $this->worldpayHelper->getPayByLinkButtonName(); } @@ -325,7 +353,8 @@ public function getSaveCardList() if ($isSavedCardEnabled && ($this->customerSession->isLoggedIn() || $this->backendAuthSession->isLoggedIn())) { $savedCardsList = $this->savedTokenFactory->create()->getCollection() ->addFieldToFilter('customer_id', $this->customerSession->getCustomerId()) - ->addFieldToFilter('token_type', $tokenType)->getData(); + ->addFieldToFilter('token_type', $tokenType) + ->addFieldToFilter('method', ['neq' => 'SEPA_DIRECT_DEBIT-SSL'])->getData(); } return $savedCardsList; } diff --git a/Model/XmlBuilder/DirectIdealOrder.php b/Model/XmlBuilder/DirectIdealOrder.php index dbffbee..e4f3727 100644 --- a/Model/XmlBuilder/DirectIdealOrder.php +++ b/Model/XmlBuilder/DirectIdealOrder.php @@ -336,6 +336,7 @@ private function _addCreateTokenElement($order) ); } } + /** * Add paymentDetails and its child tag to xml * diff --git a/Model/XmlBuilder/RedirectKlarnaOrder.php b/Model/XmlBuilder/RedirectKlarnaOrder.php index 93447eb..edb15a3 100644 --- a/Model/XmlBuilder/RedirectKlarnaOrder.php +++ b/Model/XmlBuilder/RedirectKlarnaOrder.php @@ -310,7 +310,7 @@ private function _addPaymentMethodMaskElement($order) $locale = $this->orderlineitems['locale_code']; $include = $paymentMethodMask->addChild($this->paymentType); $include['shopperCountryCode'] = $this->billingAddress['countryCode']; - $include['locale'] = $locale; + $include['locale'] = str_replace('_', '-', $locale); $successUrl = $include->addChild('successURL', $urls['successURL']); $cancelURL = $include->addChild('cancelURL', $urls['cancelURL']); diff --git a/Model/XmlBuilder/RedirectOrder.php b/Model/XmlBuilder/RedirectOrder.php index b84bbc8..fa6ec86 100644 --- a/Model/XmlBuilder/RedirectOrder.php +++ b/Model/XmlBuilder/RedirectOrder.php @@ -310,6 +310,7 @@ private function _addOrderElement($submit) $this->_addStatementNarrativeElement($order); } $this->_addFraudSightData($order); + return $order; } @@ -592,6 +593,10 @@ protected function _addStoredCredentials($paymentDetailsElement) { $storedCredentials = $paymentDetailsElement->addChild('storedCredentials'); $storedCredentials['usage'] = "FIRST"; + $isSubscriptionOrder = isset($this->paymentDetails['subscription_order'])? true : false; + if ($isSubscriptionOrder) { + $storedCredentials['customerInitiatedReason'] = "RECURRING"; + } return $storedCredentials; } /** diff --git a/Model/XmlBuilder/Refund.php b/Model/XmlBuilder/Refund.php index e7599b3..946ecc3 100644 --- a/Model/XmlBuilder/Refund.php +++ b/Model/XmlBuilder/Refund.php @@ -161,7 +161,7 @@ private function _addRefundElement($orderModification, $order, $paymentType) */ private function _amountAsInt($amount) { - return round($amount, $this->exponent, PHP_ROUND_HALF_EVEN) * pow(10, $this->exponent); + return round((float)$amount, $this->exponent, PHP_ROUND_HALF_EVEN) * pow(10, $this->exponent); } /** diff --git a/Model/XmlBuilder/SEPAOrder.php b/Model/XmlBuilder/SEPAOrder.php index 7ab8680..5a60e4e 100644 --- a/Model/XmlBuilder/SEPAOrder.php +++ b/Model/XmlBuilder/SEPAOrder.php @@ -180,11 +180,10 @@ private function _addOrderElement($submit) return $order; } - /** * Add description tag to xml * - * @param \SimpleXMLElement $order + * @param SimpleXMLElement $order */ private function _addDescriptionElement($order) { diff --git a/Model/XmlBuilder/SEPATokenOrder.php b/Model/XmlBuilder/SEPATokenOrder.php new file mode 100644 index 0000000..934b6b7 --- /dev/null +++ b/Model/XmlBuilder/SEPATokenOrder.php @@ -0,0 +1,274 @@ + +EOD; + + /** + * @var string + */ + private $merchantCode; + /** + * @var string + */ + private $orderCode; + /** + * @var string + */ + private $orderDescription; + /** + * @var string + */ + private $currencyCode; + /** + * @var float + */ + private $amount; + /** + * @var string + */ + private $orderContent; + /** + * @var array + */ + private $paymentDetails; + /** + * @var string + */ + private $shopperEmail; + /** + * @var string + */ + private $acceptHeader; + /** + * @var string + */ + private $userAgentHeader; + /** + * @var array + */ + private $shippingAddress; + /** + * @var array + */ + private $billingAddress; + /** + * @var string + */ + private $shopperId; + /** + * @var array|string + */ + private $statementNarrative; + /** + * @var array|string + */ + private $exponent; + /** + * @var string $captureDelay + */ + private $captureDelay; + + /** + * Build xml for processing Request + * + * @param string $merchantCode + * @param string $orderCode + * @param string $orderDescription + * @param string $currencyCode + * @param float $amount + * @param string $orderContent + * @param array $paymentDetails + * @param string $shopperEmail + * @param string $acceptHeader + * @param string $userAgentHeader + * @param string $shippingAddress + * @param float $billingAddress + * @param string $shopperId + * @param string $statementNarrative + * @param string $exponent + * @param string $captureDelay + */ + public function build( + $merchantCode, + $orderCode, + $orderDescription, + $currencyCode, + $amount, + $orderContent, + $paymentDetails, + $shopperEmail, + $acceptHeader, + $userAgentHeader, + $shippingAddress, + $billingAddress, + $shopperId, + $statementNarrative, + $exponent, + $captureDelay + ) { + + $this->merchantCode = $merchantCode; + $this->orderCode = $orderCode; + $this->orderDescription = $orderDescription; + $this->currencyCode = $currencyCode; + $this->amount = $amount; + $this->orderContent = $orderContent; + $this->paymentDetails = $paymentDetails; + $this->shopperEmail = $shopperEmail; + $this->acceptHeader = $acceptHeader; + $this->userAgentHeader = $userAgentHeader; + $this->shippingAddress = $shippingAddress; + $this->billingAddress = $billingAddress; + $this->shopperId = $shopperId; + $this->statementNarrative = $statementNarrative; + $this->exponent = $exponent; + $this->captureDelay = $captureDelay; + + $xml = new \SimpleXMLElement(self::ROOT_ELEMENT); + $xml['merchantCode'] = $this->merchantCode; + $xml['version'] = '1.4'; + + $submit = $this->_addSubmitElement($xml); + $this->_addOrderElement($submit); + + return $xml; + } + + /** + * Add submit tag to xml + * + * @param SimpleXMLElement $xml + * @return SimpleXMLElement + */ + private function _addSubmitElement($xml) + { + return $xml->addChild('submit'); + } + + /** + * Add order and its child tag to xml + * + * @param SimpleXMLElement $submit + * @return SimpleXMLElement $order + */ + private function _addOrderElement($submit) + { + $order = $submit->addChild('order'); + $order['orderCode'] = $this->orderCode; + if ($this->captureDelay!="") { + $order['captureDelay'] = $this->captureDelay; + } + $this->_addDescriptionElement($order); + $this->_addAmountElement($order); + $this->_addOrderContentElement($order); + $this->_addPaymentDetailsElement($order); + $this->_addShopperElement($order); + return $order; + } + /** + * Add description tag to xml + * + * @param \SimpleXMLElement $order + */ + private function _addDescriptionElement($order) + { + $description = $order->addChild('description'); + $this->_addCDATA($description, $this->orderDescription); + } + /** + * Add OrderContent tag to xml + * + * @param SimpleXMLElement $order + */ + private function _addOrderContentElement($order) + { + $orderContent = $order->addChild('orderContent'); + $this->_addCDATA($orderContent, $this->orderContent); + } + /** + * Add amount and its child tag to xml + * + * @param SimpleXMLElement $order + */ + private function _addAmountElement($order) + { + $amountElement = $order->addChild('amount'); + $amountElement['currencyCode'] = $this->currencyCode; + $amountElement['exponent'] = $this->exponent; + $amountElement['value'] = $this->_amountAsInt($this->amount); + } + + /** + * Add paymentDetails and its child tag to xml + * + * @param SimpleXMLElement $order + */ + protected function _addPaymentDetailsElement($order) + { + $paymentDetailsElement = $order->addChild('paymentDetails'); + $sepaElement = $paymentDetailsElement->addChild('TOKEN-SSL'); + $sepaElement['tokenScope'] = self::TOKEN_SCOPE; + if ($this->paymentDetails['token_type']) { + $sepaElement['tokenScope'] = 'merchant'; + } + $sepaElement = $sepaElement->addChild('paymentTokenID', $this->paymentDetails['sepa_token']); + + return $paymentDetailsElement; + } + + /** + * Add shopper and its child tag to xml + * + * @param SimpleXMLElement $order + */ + protected function _addShopperElement($order) + { + $shopper = $order->addChild(self::TOKEN_SCOPE); + $shopper->addChild('shopperEmailAddress', $this->shopperEmail); + if (!$this->paymentDetails['token_type']) { + $shopper->addChild('authenticatedShopperID', $this->shopperId); + } + $browser = $shopper->addChild('browser'); + $acceptHeader = $browser->addChild('acceptHeader'); + $this->_addCDATA($acceptHeader, $this->acceptHeader); + $userAgentHeader = $browser->addChild('userAgentHeader'); + $this->_addCDATA($userAgentHeader, $this->userAgentHeader); + return $shopper; + } + /** + * Add cdata to xml + * + * @param SimpleXMLElement $element + * @param string $content + */ + protected function _addCDATA($element, $content) + { + $node = dom_import_simplexml($element); + $no = $node->ownerDocument; + $node->appendChild($no->createCDATASection($content)); + } + + /** + * Returns the rounded value of num to specified precision + * + * @param float $amount + * @return int + */ + private function _amountAsInt($amount) + { + return round($amount, $this->exponent, PHP_ROUND_HALF_EVEN) * pow(10, $this->exponent); + } +} diff --git a/Model/XmlBuilder/WalletOrder.php b/Model/XmlBuilder/WalletOrder.php index 1b4eea3..6920e38 100644 --- a/Model/XmlBuilder/WalletOrder.php +++ b/Model/XmlBuilder/WalletOrder.php @@ -117,6 +117,14 @@ class WalletOrder * @var array */ protected $billingAddress; + /** + * @var string + */ + protected $echoData; + /** + * @var string + */ + protected $shopperId; /** * Constructor * diff --git a/README.txt b/README.txt index 627a02e..a7b8de1 100644 --- a/README.txt +++ b/README.txt @@ -2,10 +2,12 @@ Latest releases for all supported version: For Magento 2.4.5 +Worldpay Plugin version: 2.4.5-p50124 +1. Magento 2.4.5-p5 compatible + Worldpay Plugin version: 2.4.5-p30923 1. Magento 2.4.5-p3 compatible - Worldpay Plugin version: 2.4.5-p20823 1. Magento 2.4.5-p2 compatible 2. SEPA Direct Debit diff --git a/composer.json b/composer.json index b90311c..4bf74a1 100644 --- a/composer.json +++ b/composer.json @@ -8,7 +8,7 @@ "magento/module-quote": ">=100.0.0", "magento/module-vault": ">=100.0.0" }, - "version": "2.4.5-p30923", + "version": "2.4.5-p50124", "license":"proprietary", "autoload":{ "files":[ diff --git a/docs/Worldpay Plugin For Magento 2 Installation Guide.pdf b/docs/Worldpay Plugin For Magento 2 Installation Guide.pdf index 81f2c35..e3c6798 100644 Binary files a/docs/Worldpay Plugin For Magento 2 Installation Guide.pdf and b/docs/Worldpay Plugin For Magento 2 Installation Guide.pdf differ diff --git a/docs/Worldpay plugin for Magento 2 user guide.pdf b/docs/Worldpay plugin for Magento 2 user guide.pdf index 37ad7e2..29fd795 100644 Binary files a/docs/Worldpay plugin for Magento 2 user guide.pdf and b/docs/Worldpay plugin for Magento 2 user guide.pdf differ diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index a6d73fe..020aa1c 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -104,13 +104,23 @@ Sapient\Worldpay\Model\Config\Source\PaymentMethodsCC + + Sapient\Worldpay\Block\Adminhtml\System\Config\CsePopup + Magento\Config\Model\Config\Source\Yesno + + + For this detail, You must connect with your Worldpay contact. + required-entry + + 1 + @@ -726,6 +736,19 @@ + + + validate-number validate-zero-or-greater validate-not-negative-number + + + + Magento\Config\Model\Config\Source\Email\Template + Will be send 10 days before buffer time + + + + Magento\Config\Model\Config\Source\Email\Template + @@ -1174,60 +1197,40 @@ - - - Magento\Config\Model\Config\Source\Yesno - - - - Sapient\Worldpay\Model\Config\Backend\Image - sapient_worldpay/images - sapient_worldpay/images - -
    -
  • Recommended size: Logo size should be (50*30)px and Max upto 50KB.
  • -
- ]]>
- 1 -
+ + + Sapient\Worldpay\Model\Config\Source\ApplePay\ButtonColor + + + + Sapient\Worldpay\Model\Config\Source\ApplePay\ButtonTypes + + + + Sapient\Worldpay\Model\Config\Source\ApplePay\ButtonLocale +
- - - Magento\Config\Model\Config\Source\Yesno - - - - Sapient\Worldpay\Model\Config\Backend\Image - sapient_worldpay/images - sapient_worldpay/images - -
    -
  • Recommended size: Logo size should be (50*30)px and Max upto 50KB.
  • -
- ]]>
- 1 -
+ + + Sapient\Worldpay\Model\Config\Source\GooglePay\ButtonColor + + + + Sapient\Worldpay\Model\Config\Source\GooglePay\ButtonTypes + + + + Sapient\Worldpay\Model\Config\Source\GooglePay\ButtonLocale +
- - - - Magento\Config\Model\Config\Source\Yesno - - - - Sapient\Worldpay\Model\Config\Backend\Image - sapient_worldpay/images - sapient_worldpay/images - -
    -
  • Recommended size: Logo size should be (50*30)px and Max upto 50KB.
  • -
- ]]>
- 1 -
+ + + + Sapient\Worldpay\Model\Config\Source\SamsungPayButtonTypes +
1 @@ -1286,6 +1289,100 @@ 1 Enter the merchant Installation Id for Multishipping orders. If it is blank, global merchant Installation Id entered under HPP configuration will be applicable.
+ + + + + + + + + + Magento\Config\Model\Config\Source\Yesno + + + + Location of the ApplePay.key.pem. eg. /var/www/html/cert/. Files should be have read access by the webserver + + + + Location of the ApplePay.crt.pem. eg. /var/www/html/cert/. Files should be have read access by the webserver + + + + Password set during the export of p12 file. + + + + For this detail, You must connect with your Worldpay contact. + + + + eg. mydomain.com + + + + + + + + + Magento\Config\Model\Config\Source\Yesno + + + + Sapient\Worldpay\Model\Config\Source\PaymentMethods + + + + Sapient\Worldpay\Model\Config\Source\AuthMethods + + + + For this detail, You must connect with your Worldpay contact. + + + + For this detail, You must connect with your Worldpay contact. + + + + This field only required for production mode. This can be generated from merchant's Google account + + + + + + + + + + + + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + + + + + + + + + + + + + + diff --git a/etc/config.xml b/etc/config.xml index c9e13b9..a388849 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -13,7 +13,7 @@ 1 Credit Cards AMEX-SSL,VISA-SSL,ECMC-SSL - 0 + 1 1 direct @@ -117,6 +117,23 @@ default 1 + + 5 + + + + + black + buy + en-GB + + + default + buy + en + + + @@ -182,5 +199,12 @@ 0 + + + + ../chromepay/sw.js + + + diff --git a/etc/crontab.xml b/etc/crontab.xml index a323964..0071b5e 100644 --- a/etc/crontab.xml +++ b/etc/crontab.xml @@ -6,6 +6,9 @@ + + * * * * * + * * * * * diff --git a/etc/db_schema.xml b/etc/db_schema.xml index fa0990b..510e238 100644 --- a/etc/db_schema.xml +++ b/etc/db_schema.xml @@ -296,4 +296,29 @@ + + + + + + + + + + +
+ + + + + + + + + + + + +
+ diff --git a/etc/di.xml b/etc/di.xml index d0b9e6d..5ed50e3 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -44,6 +44,18 @@ + + + + + + + + + + Sapient\Worldpay\Logger\WorldpayLogger diff --git a/etc/email_templates.xml b/etc/email_templates.xml index 394c847..365a1d3 100644 --- a/etc/email_templates.xml +++ b/etc/email_templates.xml @@ -15,4 +15,6 @@