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(); + } +} diff --git a/Block/Recurring/Customer/Subscriptions.php b/Block/Recurring/Customer/Subscriptions.php index e17cc09..db46a32 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); + } } diff --git a/Block/Recurring/Customer/Subscriptions/Edit.php b/Block/Recurring/Customer/Subscriptions/Edit.php index 9964c3e..e41af88 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/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/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/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..1d920aa --- /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(); + } +} 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 03724e0..32608ca 100644 --- a/Controller/Redirectresult/Redirect.php +++ b/Controller/Redirectresult/Redirect.php @@ -64,7 +64,7 @@ public function execute() { $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->worldpayHelper->isWorldPayEnable()) { - $resultRedirect->setPath('noroute'); + $resultRedirect->setPath('noroute'); return $resultRedirect; } $redirecturl = $this->checkoutsession->getWpRedirecturl(); diff --git a/Controller/Samsungpay/CallBack.php b/Controller/Samsungpay/CallBack.php index 5a39353..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'); + $resultRedirect->setPath('noroute'); return $resultRedirect; } $order = $this->_checkoutSession->getLastRealOrder(); diff --git a/Controller/Samsungpay/Index.php b/Controller/Samsungpay/Index.php index dc46a2e..e34536c 100644 --- a/Controller/Samsungpay/Index.php +++ b/Controller/Samsungpay/Index.php @@ -1,5 +1,5 @@ worldpayHelper->isWorldPayEnable()) { $resultRedirect->setPath('noroute'); return $resultRedirect; - } + } $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $serviceId = $this->scopeConfig-> 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/RecurringOrdersEmail.php b/Cron/RecurringOrdersEmail.php new file mode 100644 index 0000000..3d482f0 --- /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.'; + } elseif ($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 3082c2d..f6c484b 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -1230,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 * @@ -2785,11 +2799,11 @@ public function getCurrentMagentoVersionDetails() { $mageDetails = []; $mageDetails['platform'] = __('Magento'); - if($this->productMetaData->getEdition()){ - $mageDetails['edition'] = __('Magento_').$this->productMetaData->getEdition(); + if ($this->productMetaData->getEdition()) { + $mageDetails['edition'] = __('Magento_').$this->productMetaData->getEdition(); } - if($this->productMetaData->getVersion()){ - $mageDetails['version'] = $this->productMetaData->getVersion(); + if ($this->productMetaData->getVersion()) { + $mageDetails['version'] = $this->productMetaData->getVersion(); } return $mageDetails; } diff --git a/Helper/Recurring.php b/Helper/Recurring.php index 97220a4..4241a7d 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; } /** @@ -1110,4 +1136,100 @@ public function getRecurringOrderBufferTime() \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/Config/Source/SamsungPayButtonTypes.php b/Model/Config/Source/SamsungPayButtonTypes.php new file mode 100644 index 0000000..5f3226a --- /dev/null +++ b/Model/Config/Source/SamsungPayButtonTypes.php @@ -0,0 +1,24 @@ + '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/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/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/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..654710a --- /dev/null +++ b/Model/ResourceModel/SkipSubscriptionOrder/Collection.php @@ -0,0 +1,96 @@ +_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..e7215e0 --- /dev/null +++ b/Model/ResourceModel/SubscriptionOrder/Collection.php @@ -0,0 +1,98 @@ +_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/PluginUpgradeDates.php b/Model/System/Config/Backend/PluginUpgradeDates.php index a4bf1e1..ff975d1 100644 --- a/Model/System/Config/Backend/PluginUpgradeDates.php +++ b/Model/System/Config/Backend/PluginUpgradeDates.php @@ -192,7 +192,7 @@ public function getUpgradeDates() } else { $value['newVersion'] = isset($currentVersion['newVersion'])?$currentVersion['newVersion']:""; } - $currentVersionHistoryDataAry = explode(',', $currentVersionHistoryData); + $currentVersionHistoryDataAry = explode(',', (string) $currentVersionHistoryData); $value['is_new_version'] = false; if (!in_array($value['newVersion'], $currentVersionHistoryDataAry)) { $value['is_new_version'] = true; diff --git a/Model/WorldpayConfigProvider.php b/Model/WorldpayConfigProvider.php index 86e07b1..c820b4f 100644 --- a/Model/WorldpayConfigProvider.php +++ b/Model/WorldpayConfigProvider.php @@ -251,14 +251,18 @@ public function getConfig() $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(); + $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"; diff --git a/README.txt b/README.txt index c813b8b..7f65abf 100644 --- a/README.txt +++ b/README.txt @@ -2,6 +2,10 @@ Latest releases for all supported version: For Magento 2.4.6 +Worldpay Plugin version: 2.4.6-p30124 +1. Magento 2.4.6-p3 compatible +2. PHP 8.2 compatibility + Worldpay Plugin version: 2.4.6-p21023 1. Magento 2.4.6-p2 compatible 2. PHP 8.2 compatibility diff --git a/composer.json b/composer.json index d20f5cd..643e31e 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.6-p21023", + "version": "2.4.6-p30124", "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 9e1456d..98080f6 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 0b8cf54..1a83067 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 df6e370..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 + @@ -730,6 +740,15 @@ 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 + @@ -1207,23 +1226,11 @@ - - - - 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 diff --git a/etc/config.xml b/etc/config.xml index 1cf7aa6..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 @@ -199,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 @@