diff --git a/.gitignore b/.gitignore index babed18d..27d8fed6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,29 @@ -.idea/ +# General .DS_Store -**.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +build/ diff --git a/Bootstrap.php b/Bootstrap.php index 1fba31d9..08a88f3f 100755 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -34,6 +34,7 @@ public static function getPaymentMethods() 'rpayratepayrate', 'rpayratepaydebit', 'rpayratepayrate0', + 'rpayratepayprepayment', ]; } @@ -112,10 +113,19 @@ public function getCapabilities() */ public function install() { + parent::install(); + Logger::singleton()->info('INSTALL Plugin Bootstrap'); - $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onRegisterSubscriber'); - $this->str = 'Shopware_Console_Add_Command'; - $this->subscribeEvent('' . $this->str . '', 'onRegisterSubscriber'); + + Logger::singleton()->info('RatePAY: event subscription'); + $this->subscribeEvent( + 'Enlight_Controller_Front_StartDispatch', + 'onRegisterSubscriber' + ); + $this->subscribeEvent( + 'Shopware_Console_Add_Command', + 'onRegisterSubscriber' + ); $queue = [ new \RpayRatePay\Bootstrapping\PaymentsSetup($this), @@ -129,15 +139,21 @@ public function install() new \RpayRatePay\Bootstrapping\AdditionalOrderAttributeSetup($this), ]; + Logger::singleton()->info('RatePAY: bootstrap routines'); foreach ($queue as $bootstrapper) { $bootstrapper->install(); + Logger::singleton()->info('[OK] ' . get_class($bootstrapper)); } $this->Plugin()->setActive(true); + Logger::singleton()->info('RatePAY: Successful module installation'); return [ 'success' => true, - 'invalidateCache' => ['frontend', 'backend'] + 'invalidateCache' => [ + 'frontend', + 'backend' + ] ]; } @@ -151,7 +167,6 @@ public function install() */ public function update($version) { - Logger::singleton()->info('UPDATE Plugin Bootstrap ' . $version); $queue = [ new \RpayRatePay\Bootstrapping\FormsSetup($this), @@ -165,10 +180,13 @@ public function update($version) $this->_dropOrderAdditionalAttributes(); + Logger::singleton()->info('RatePAY: bootstrap routines'); foreach ($queue as $bootstrapper) { $bootstrapper->update(); + Logger::singleton()->info('[OK] ' . get_class($bootstrapper)); } + Logger::singleton()->info('RatePAY: Successful module update'); Logger::singleton()->addNotice('Successful module update'); return [ @@ -178,8 +196,8 @@ public function update($version) } /** - * drops additional attributes for ratepay orders in s_order_attributes - */ + * drops additional attributes for ratepay orders in s_order_attributes + */ public function _dropOrderAdditionalAttributes() { $metaDataCache = Shopware()->Models()->getConfiguration()->getMetadataCacheImpl(); @@ -247,6 +265,7 @@ public function onRegisterSubscriber() foreach ($subscribers as $subscriber) { Shopware()->Events()->addSubscriber($subscriber); +// Logger::singleton()->info('[OK] ' . get_class($subscriber)); } } } diff --git a/Bootstrapping/Database/CreateConfigTable.php b/Bootstrapping/Database/CreateConfigTable.php index ab0b6737..b9170bf5 100644 --- a/Bootstrapping/Database/CreateConfigTable.php +++ b/Bootstrapping/Database/CreateConfigTable.php @@ -19,6 +19,7 @@ protected function getQuery() '`installment` int(2) NOT NULL, ' . '`installment0` int(2) NOT NULL, ' . '`installmentDebit` int(2) NOT NULL, ' . + '`prepayment` int(2) NOT NULL, ' . '`device-fingerprint-status` varchar(3) NOT NULL, ' . '`device-fingerprint-snippet-id` varchar(55) NULL, ' . '`country-code-billing` varchar(30) NULL, ' . @@ -49,6 +50,12 @@ public function __invoke($database) $database->query($sql); } + $hasColumnPrepayment = ShopwareUtil::tableHasColumn('rpay_ratepay_config', 'prepayment'); + if (!$hasColumnPrepayment) { + $sql = 'ALTER TABLE rpay_ratepay_config ADD COLUMN prepayment int(2) NOT NULL'; + $database->query($sql); + } + $sql = 'ALTER TABLE rpay_ratepay_config DROP PRIMARY KEY, ADD PRIMARY KEY (shopId, country, backend);'; $database->query($sql); } diff --git a/Bootstrapping/Events/BackendOrderControllerSubscriber.php b/Bootstrapping/Events/BackendOrderControllerSubscriber.php index 4cf23aae..635bcd90 100644 --- a/Bootstrapping/Events/BackendOrderControllerSubscriber.php +++ b/Bootstrapping/Events/BackendOrderControllerSubscriber.php @@ -72,6 +72,7 @@ public function beforeCreateOrderAction(\Enlight_Hook_HookArgs $hookArgs) } $paymentRequestData = $this->orderStructToPaymentRequestData($orderStruct, $paymentType, $customer); + $method = \RpayRatePay\Component\Service\ShopwareUtil::getPaymentMethod($paymentType->getName()); $netItemPrices = \RpayRatePay\Component\Service\ShopwareUtil::customerCreatesNetOrders($customer); $paymentRequester = new \Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(null, true, $netItemPrices); @@ -84,7 +85,7 @@ public function beforeCreateOrderAction(\Enlight_Hook_HookArgs $hookArgs) $orderId = $view->getAssign('orderId'); - $this->doPostProcessing($orderId, $answer, $paymentRequestData); + $this->doPostProcessing($orderId, $answer, $paymentRequestData, $method); } else { $customerMessage = $answer->getCustomerMessage(); $this->fail($view, [$customerMessage]); @@ -99,8 +100,8 @@ public function beforeCreateOrderAction(\Enlight_Hook_HookArgs $hookArgs) private function orderStructToPaymentRequestData( \SwagBackendOrder\Components\Order\Struct\OrderStruct $orderStruct, - \Shopware\Models\Payment\Payment $paymentType, - \Shopware\Models\Customer\Customer $customer + \Shopware\Models\Payment\Payment $paymentType, + \Shopware\Models\Customer\Customer $customer ) { $method = \RpayRatePay\Component\Service\ShopwareUtil::getPaymentMethod( $paymentType->getName() @@ -174,7 +175,7 @@ private function runSwagValidations($orderStruct) return $violations; } - private function doPostProcessing($orderId, $answer, $paymentRequestData) + private function doPostProcessing($orderId, $answer, $paymentRequestData, $paymentMethod) { $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $orderId); @@ -199,8 +200,7 @@ private function doPostProcessing($orderId, $answer, $paymentRequestData) //insert ratepay positions $paymentProcessor->insertRatepayPositions($order); - //payment status closed - $paymentProcessor->setPaymentStatusPaid($order); + $paymentProcessor->setPaymentStatus($order); //insert positions if (\Shopware_Plugins_Frontend_RpayRatePay_Bootstrap::getPCConfig() == true) { diff --git a/Bootstrapping/Events/OrderOperationsSubscriber.php b/Bootstrapping/Events/OrderOperationsSubscriber.php index 9f2fa8f4..9792bef4 100644 --- a/Bootstrapping/Events/OrderOperationsSubscriber.php +++ b/Bootstrapping/Events/OrderOperationsSubscriber.php @@ -199,7 +199,7 @@ public function beforeDeleteOrder(\Enlight_Hook_HookArgs $arguments) $operationData['orderId'] = $order->getId(); $operationData['items'] = $items; $operationData['subtype'] = 'cancellation'; - $result = $modelFactory->callRequest('PaymentChange', $operationData); + $result = $modelFactory->callPaymentChange($operationData); if ($result !== true) { Logger::singleton()->warning('Bestellung könnte nicht gelöscht werden, da die Stornierung bei RatePAY fehlgeschlagen ist.'); diff --git a/Bootstrapping/Events/PaymentFilterSubscriber.php b/Bootstrapping/Events/PaymentFilterSubscriber.php index 7bddf3c3..79cc8db6 100644 --- a/Bootstrapping/Events/PaymentFilterSubscriber.php +++ b/Bootstrapping/Events/PaymentFilterSubscriber.php @@ -150,6 +150,11 @@ public function filterPayments(\Enlight_Event_EventArgs $arguments) $setToDefaultPayment = $paymentModel->getName() === 'rpayratepayrate0' ?: $setToDefaultPayment; continue; } + if ($payment['name'] === 'rpayratepayprepayment' && !$show['prepayment']) { + Logger::singleton()->info('RatePAY: Filter RatePAY-Prepayment'); + $setToDefaultPayment = $paymentModel->getName() === 'rpayratepayprepayment' ?: $setToDefaultPayment; + continue; + } $payments[] = $payment; } @@ -180,7 +185,7 @@ private function getRatePayPluginConfigByCountry($shopId, $country, $backend = f { $configLoader = new ConfigLoader(Shopware()->Db()); - $payments = ['installment', 'invoice', 'debit', 'installment0']; + $payments = ['installment', 'invoice', 'debit', 'installment0', 'prepayment']; $paymentConfig = []; foreach ($payments as $payment) { diff --git a/Bootstrapping/Events/UpdateTransactionsSubscriber.php b/Bootstrapping/Events/UpdateTransactionsSubscriber.php index 31368bc8..618de455 100644 --- a/Bootstrapping/Events/UpdateTransactionsSubscriber.php +++ b/Bootstrapping/Events/UpdateTransactionsSubscriber.php @@ -2,12 +2,15 @@ namespace RpayRatePay\Bootstrapping\Events; +use Doctrine\ORM\Query\Expr; use RpayRatePay\Component\Service\Logger; class UpdateTransactionsSubscriber implements \Enlight\Event\SubscriberInterface { const JOB_NAME = 'Shopware_Cronjob_UpdateRatepayTransactions'; + const MSG_NOTIFY_UPDATES_TO_RATEPAY = '[%d/%d] Processing order %d ...notify needed updates to RatePAY'; + /** * @var string */ @@ -49,12 +52,7 @@ public function updateRatepayTransactions(\Shopware_Components_Cron_CronJob $job /* @var \Shopware\Models\Order\Order $order */ $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $orderId); Logger::singleton()->info( - sprintf( - '[%d/%d] Processing order %d ...notify needed updated to RatePAY', - ($key + 1), - $totalOrders, - $orderId - ) + sprintf(self::MSG_NOTIFY_UPDATES_TO_RATEPAY, ($key + 1), $totalOrders, $orderId) ); $orderProcessor->informRatepayOfOrderStatusChange($order); } @@ -64,11 +62,13 @@ public function updateRatepayTransactions(\Shopware_Components_Cron_CronJob $job ); return $e->getMessage(); } + return 'Success'; } /** * @return mixed + * @throws \Exception */ private function getLastUpdateDate() { @@ -92,21 +92,22 @@ private function getLastUpdateDate() */ private function findCandidateOrdersForUpdate($config) { - $orderStatus = [ - $config['RatePayFullDelivery'], - $config['RatePayFullCancellation'], - $config['RatePayFullReturn'], + $allowedOrderStates = [ + $config->RatePayFullDelivery, + $config->RatePayFullCancellation, + $config->RatePayFullReturn, ]; $paymentMethods = $this->getAllowedPaymentMethods(); $changeDate = $this->getChangeDateLimit(); - $query = 'SELECT o.id FROM s_order o - INNER JOIN s_order_history oh ON oh.orderID = o.id - LEFT JOIN s_core_paymentmeans cp ON cp.id = o.paymentID - WHERE cp.name in (' . join(',', $paymentMethods) . ') - AND o.status in (' . join(',', $orderStatus) . ') - AND oh.change_date >= :changeDate - GROUP BY o.id'; + $query = Shopware()->Db()->select() + ->from(['history' => 's_order_history'], null) + ->joinLeft(['order' => 's_order'], 'history.orderID = order.id', ['id']) + ->joinLeft(['payment' => 's_core_paymentmeans'], 'order.paymentID = payment.id', null) + ->where('history.change_date >= :changeDate') + ->where('order.status IN (' . join(', ', $allowedOrderStates) . ')') + ->where('payment.name IN (' . join(', ', $paymentMethods) . ')') + ->distinct(true); $rows = Shopware()->Db()->fetchAll($query, [':changeDate' => $changeDate]); diff --git a/Bootstrapping/form_elements.json b/Bootstrapping/form_elements.json index a27412b3..8ada2ec8 100644 --- a/Bootstrapping/form_elements.json +++ b/Bootstrapping/form_elements.json @@ -286,5 +286,65 @@ "value": false, "scope":1 } + }, + { + "type":"select", + "name":"RatePayPrepaidPaymentStatus", + "config":{ + "label": "Status nach Zahlung mit Vorkasse:", + "value": 17, + "store":"base.PaymentStatus", + "displayField":"description", + "valueField":"id", + "scope":1 + } + }, + { + "type":"select", + "name":"RatePayInvoicePaymentStatus", + "config":{ + "label": "Status nach Zahlung mit Rechnung:", + "value": 12, + "store":"base.PaymentStatus", + "displayField":"description", + "valueField":"id", + "scope":1 + } + }, + { + "type":"select", + "name":"RatePayDebitPaymentStatus", + "config":{ + "label": "Status nach Zahlung mit Lastschrift:", + "value": 12, + "store":"base.PaymentStatus", + "displayField":"description", + "valueField":"id", + "scope":1 + } + }, + { + "type":"select", + "name":"RatePayInstallmentPaymentStatus", + "config":{ + "label": "Status nach Zahlung mit Rate:", + "value": 12, + "store":"base.PaymentStatus", + "displayField":"description", + "valueField":"id", + "scope":1 + } + }, + { + "type":"select", + "name":"RatePayInstallment0PaymentStatus", + "config":{ + "label": "Status nach Zahlung mit Nullprozent-Finanzierung:", + "value": 12, + "store":"base.PaymentStatus", + "displayField":"description", + "valueField":"id", + "scope":1 + } } -] \ No newline at end of file +] diff --git a/Bootstrapping/locale/backend/de_DE.json b/Bootstrapping/locale/backend/de_DE.json index 321999a1..42750a97 100644 --- a/Bootstrapping/locale/backend/de_DE.json +++ b/Bootstrapping/locale/backend/de_DE.json @@ -54,7 +54,7 @@ "label": "Zugangsdaten für die Schweiz" }, "button3": { - "label": "Bidirectionalität RatePAY-Bestellungen" + "label": "Bidirektionalität RatePAY-Bestellungen" }, "button4": { "label": "Zugangsdaten für Belgien" diff --git a/Bootstrapping/locale/frontend/en_EN.json b/Bootstrapping/locale/frontend/en_EN.json index 021b81b3..82f37b07 100644 --- a/Bootstrapping/locale/frontend/en_EN.json +++ b/Bootstrapping/locale/frontend/en_EN.json @@ -5,6 +5,7 @@ "dob_info": "Please enter a Date of Birth", "dobtooyoung": "For the chosen payment method you have to be at least 18 years old.", "invalidAge": "For the chosen payment method you have to be at least 18 years old.", + "dobnotvalid": "Please enter a valid date of birth", "invaliddata": "Please check your data", "phonenumbernotvalid": "Please enter a valid telephone number.", "ratepayAgbMouseover": "Um RatePAY nutzen zu können müssen sie den AGBs von RatePAY zustimmen", diff --git a/Bootstrapping/locale/frontend/fr_FR.json b/Bootstrapping/locale/frontend/fr_FR.json index a3effc75..55c913e3 100644 --- a/Bootstrapping/locale/frontend/fr_FR.json +++ b/Bootstrapping/locale/frontend/fr_FR.json @@ -5,6 +5,7 @@ "dob_info": "Date de naissance", "dobtooyoung": "Veuillez vérifier les informations fournies. Pour utiliser le moyen de paiement sélectionné, vous devez être âgé de plus de 18 ans et la date de naissance doit être renseignée selon le format TT.MM.JJJJ.')", "invalidAge": "Veuillez vérifier les informations fournies. Pour utiliser le moyen de paiement sélectionné, vous devez être âgé de plus de 18 ans et la date de naissance doit être renseignée selon le format TT.MM.JJJJ.", + "dobnotvalid": "Veuillez saisir votre date de naissance.", "invaliddata": "Afin de procéder à l'achat, veuillez indiquer le moyen de paiement et fournir les informations suivantes :", "ok": "ok", "phonenumbernotvalid": "Veuillez fournir un numéro de téléphone valide pour le moyen de paiement choisi.", diff --git a/Bootstrapping/payment_methods_install.json b/Bootstrapping/payment_methods_install.json index e137ef96..244bbaa6 100644 --- a/Bootstrapping/payment_methods_install.json +++ b/Bootstrapping/payment_methods_install.json @@ -34,5 +34,14 @@ "position": 4, "additionaldescription": "Kauf per 0% Finanzierung", "template": "RatePAYRate.tpl" + }, + { + "name": "rpayratepayprepayment", + "description": "Vorkasse", + "action": "rpay_ratepay", + "active": 1, + "position": 5, + "additionaldescription": "Kauf per Vorkasse", + "template": "RatePAYPrepayment.tpl" } ] \ No newline at end of file diff --git a/Bootstrapping/payment_methods_update.json b/Bootstrapping/payment_methods_update.json index 9af8d84b..98187ece 100644 --- a/Bootstrapping/payment_methods_update.json +++ b/Bootstrapping/payment_methods_update.json @@ -7,5 +7,14 @@ "position": 4, "additionaldescription": "Kauf per 0% Finanzierung", "template": "RatePAYRate.tpl" + }, + { + "name": "rpayratepaprepayment", + "description": "Vorkasse", + "action": "rpay_ratepay", + "active": 1, + "position": 5, + "additionaldescription": "Kauf per Vorkasse", + "template": "RatePAYPrepayment.tpl" } ] \ No newline at end of file diff --git a/Component/Logging.php b/Component/Logging.php index 1b222995..0aabfd77 100755 --- a/Component/Logging.php +++ b/Component/Logging.php @@ -59,7 +59,7 @@ public function logRequest($requestXml, $responseXml) try { Shopware()->Db()->insert('rpay_ratepay_logging', $bind); } catch (\Exception $exception) { - Logger::singleton()->error('Fehler beim Loggen: ' . $exception->getMessage()); + Logger::singleton()->error('RatePAY was unable to log order history: ' . $exception->getMessage()); } } } diff --git a/Component/Mapper/BasketArrayBuilder.php b/Component/Mapper/BasketArrayBuilder.php index 865e717b..52551794 100644 --- a/Component/Mapper/BasketArrayBuilder.php +++ b/Component/Mapper/BasketArrayBuilder.php @@ -309,7 +309,7 @@ private function getQuantityForRequest($item) $quantity = ($item->cancelledItems == 0) ? 0 : $item->cancelledItems; break; case 'shippingRate': - $quantity = ($item->maxQuantity == 0) ? 0 : $item->maxQuantity; + $quantity = ($item->maxQuantity == 0) ? 0 : $item->quantity; break; } diff --git a/Component/Mapper/ModelFactory.php b/Component/Mapper/ModelFactory.php index 44f3f2a1..e0fb9fa4 100755 --- a/Component/Mapper/ModelFactory.php +++ b/Component/Mapper/ModelFactory.php @@ -106,38 +106,6 @@ public function setTransactionId($transactionId) $this->_transactionId = $transactionId; } - /** - * call operation - * - * @param string $operationType - * @param array $operationData - * @deprecated - * @return bool|array|object - */ - public function callRequest($operationType, array $operationData = []) - { - switch ($operationType) { - case 'ProfileRequest': - return $this->callProfileRequest($operationData); - break; - case 'PaymentRequest': - return $this->callPaymentRequest(); - break; - case 'ConfirmationDeliver': - return $this->callConfirmationDeliver($operationData); - break; - case 'PaymentChange': - return $this->callPaymentChange($operationData); - break; - case 'PaymentConfirm': - return $this->callPaymentConfirm(); - break; - case 'CalculationRequest': - return $this->callCalculationRequest($operationData); - break; - } - } - public function callCalculationRequest($operationData) { $mbHead = $this->getHead(); @@ -266,7 +234,6 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) } $method = $paymentRequestData->getMethod(); - if ($method == 'INSTALLMENT0') { $this->setZPercent(); //side effect $method = 'INSTALLMENT'; //state @@ -375,17 +342,19 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) ] ]; + if (!empty($company)) { $contentArr['Customer']['CompanyName'] = $checkoutAddressBilling->getCompany(); $contentArr['Customer']['VatId'] = $checkoutAddressBilling->getVatId(); } + $elv = false; if (!empty($installmentDetails)) { $serviceUtil = new ShopwareUtil(); $contentArr['Payment']['DebitPayType'] = $serviceUtil->getDebitPayType( $this->getSession()->RatePAY['ratenrechner']['payment_firstday'] - ); + ); if ($contentArr['Payment']['DebitPayType'] == 'DIRECT-DEBIT') { $elv = true; @@ -453,7 +422,7 @@ private function getPaymentDetails() * @return bool|array * @throws \RatePAY\Exception\ModelException */ - private function callProfileRequest($operationData) + public function callProfileRequest($operationData) { $systemId = $this->getSystemId(); $sandbox = true; @@ -560,8 +529,12 @@ private function createBasketArray($items, $type = false, $orderId = null) * * @param $operationData * @return bool + * @throws \Doctrine\ORM\ORMException + * @throws \Doctrine\ORM\OptimisticLockException + * @throws \Doctrine\ORM\TransactionRequiredException + * @throws \RatePAY\Exception\ModelException */ - private function callConfirmationDeliver($operationData) + public function callConfirmationDeliver($operationData) { $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $operationData['orderId']); $countryCode = $order->getBilling()->getCountry()->getIso(); @@ -612,7 +585,7 @@ private function callConfirmationDeliver($operationData) return true; } elseif ($this->_retry == false && (int)$confirmationDeliver->getReasonCode() == 2300) { $this->_retry = true; - return $this->callRequest('ConfirmationDeliver', $operationData); + return $this->callConfirmationDeliver($operationData); } return false; @@ -623,8 +596,12 @@ private function callConfirmationDeliver($operationData) * * @param $operationData * @return bool + * @throws \Doctrine\ORM\ORMException + * @throws \Doctrine\ORM\OptimisticLockException + * @throws \Doctrine\ORM\TransactionRequiredException + * @throws \RatePAY\Exception\ModelException */ - private function callPaymentChange($operationData) + public function callPaymentChange($operationData) { $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $operationData['orderId']); $countryCode = $order->getBilling()->getCountry()->getIso(); @@ -671,7 +648,7 @@ private function callPaymentChange($operationData) return true; } elseif ($this->_retry == false && (int)$paymentChange->getReasonCode() == 2300) { $this->_retry = true; - return $this->callRequest('PaymentChange', $operationData); + return $this->callPaymentChange($operationData); } return false; } diff --git a/Component/Model/ShopwareCustomerWrapper.php b/Component/Model/ShopwareCustomerWrapper.php index df039722..aed53041 100644 --- a/Component/Model/ShopwareCustomerWrapper.php +++ b/Component/Model/ShopwareCustomerWrapper.php @@ -2,6 +2,7 @@ namespace RpayRatePay\Component\Model; +use RpayRatePay\Component\Service\Logger; use Shopware\Models\Customer\Customer; use RatePAY\Service\Util; @@ -130,6 +131,12 @@ private function getShippingChaotic() */ public function getBillingCountry() { + $shippingId = Shopware()->Session()->offsetGet('checkoutShippingAddressId'); + if (!empty($shippingId)) { + Logger::singleton()->info(__METHOD__ . ' --> ' . $shippingId); + return Shopware()->Models()->find('Shopware\Models\Customer\Address', $shippingId)->getCountry(); + } + $billingFresh = $this->getBillingFresh(); if (!is_null($billingFresh)) { @@ -147,6 +154,40 @@ public function getBillingCountry() return $country; } + public function getBillingFirstName() + { + $billingFresh = $this->getBillingFresh(); + + if (!is_null($billingFresh)) { + return $billingFresh->getFirstname(); + } + + $billingRotten = $this->getBillingRotten(); + + if (is_null($billingRotten)) { + return null; + } + + return $billingRotten->getFirstName(); + } + + public function getBillingLastName() + { + $billingFresh = $this->getBillingFresh(); + + if (!is_null($billingFresh)) { + return $billingFresh->getLastname(); + } + + $billingRotten = $this->getBillingRotten(); + + if (is_null($billingRotten)) { + return null; + } + + return $billingRotten->getLastName(); + } + /** * @return null|object|\Shopware\Models\Country\Country * @throws \Doctrine\ORM\ORMException diff --git a/Component/Service/ConfigLoader.php b/Component/Service/ConfigLoader.php index 57fe3d88..e61d26ed 100644 --- a/Component/Service/ConfigLoader.php +++ b/Component/Service/ConfigLoader.php @@ -26,7 +26,8 @@ private function getPaymentMeansMap() 'rpayratepayrate' => 'installment', 'rpayratepayinvoice' => 'invoice', 'rpayratepaydebit' => 'debit', - 'rpayratepayrate0' => 'installment0' + 'rpayratepayrate0' => 'installment0', + 'rpayratepayprepayment' => 'prepayment' ]; } diff --git a/Component/Service/OrderStatusChangeHandler.php b/Component/Service/OrderStatusChangeHandler.php index a2c418a4..7255f1b6 100644 --- a/Component/Service/OrderStatusChangeHandler.php +++ b/Component/Service/OrderStatusChangeHandler.php @@ -1,31 +1,47 @@ getOrderStatus()->getId() !== (int)($config['RatePayFullDelivery'])) { - return false; - } - $paymentMethods = \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap::getPaymentMethods(); - if (!in_array($order->getPayment()->getName(), $paymentMethods)) { + if ($order->getOrderStatus()->getId() !== (int)($config['RatePayFullDelivery']) + || !Helper::isRatePayPayment($order->getPayment()->getName())) { return false; } - $query = 'SELECT count(*) as ct FROM s_order o - LEFT JOIN s_order_details od ON od.orderID = o.id - LEFT JOIN rpay_ratepay_order_positions rop ON rop.s_order_details_id = od.id - WHERE o.id = ? - AND (rop.delivered != 0 OR rop.cancelled != 0 OR rop.returned != 0)'; + $query = Shopware()->Db()->select() + ->from(['position' => 'rpay_ratepay_order_positions'], ['total' => 'COUNT(*)']) + ->joinLeft(['detail' => 's_order_details'], 'position.s_order_details_id = detail.id', null) + ->where('detail.orderID = :orderId') + ->where('(position.delivered + position.cancelled + position.returned) > 0'); + + $count = (int)Shopware()->Db()->fetchOne($query, [':orderId' => $order->getId()]); + if ($count > 0) { + Logger::singleton()->warning( + sprintf('-> Order [%d] has %d "not deliverable" positions', $order->getId(), $count) + ); + } - $count = Shopware()->Db()->fetchOne($query, [$order->getId()]); - return (int)$count === 0; + return $count === 0; } /** @@ -33,25 +49,27 @@ private function mustSendFullShipped(Shopware\Models\Order\Order $order, $config * @param $config * @return bool */ - private function mustSendFullCancellation(Shopware\Models\Order\Order $order, $config) + private function canSendFullCancellation(\Shopware\Models\Order\Order $order, $config) { - if ($order->getOrderStatus()->getId() !== (int)($config['RatePayFullCancellation'])) { - return false; - } - $paymentMethods = \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap::getPaymentMethods(); - if (!in_array($order->getPayment()->getName(), $paymentMethods)) { + if ($order->getOrderStatus()->getId() !== (int)($config['RatePayFullCancellation']) + || !Helper::isRatePayPayment($order->getPayment()->getName())) { return false; } - $query = 'SELECT count(*) FROM s_order o - LEFT JOIN s_order_details od ON od.orderID = o.id - LEFT JOIN rpay_ratepay_order_positions rop ON rop.s_order_details_id = od.id - WHERE o.id = ? - AND (rop.delivered !=0 OR rop.cancelled != 0 OR rop.returned != 0)'; + $query = Shopware()->Db()->select() + ->from(['position' => 'rpay_ratepay_order_positions'], ['total' => 'COUNT(*)']) + ->joinLeft(['detail' => 's_order_details'], 'position.s_order_details_id = detail.id', null) + ->where('detail.orderID = :orderId') + ->where('(position.delivered + position.cancelled + position.returned) > 0'); - $count = Shopware()->Db()->fetchOne($query, [$order->getId()]); + $count = (int)Shopware()->Db()->fetchOne($query, [':orderId' => $order->getId()]); + if ($count > 0) { + Logger::singleton()->warning( + sprintf('-> Order [%d] has %d "not cancellable" positions', $order->getId(), $count) + ); + } - return (int)$count === 0; + return $count === 0; } /** @@ -59,25 +77,27 @@ private function mustSendFullCancellation(Shopware\Models\Order\Order $order, $c * @param $config * @return bool */ - private function mustSendFullReturn(Shopware\Models\Order\Order $order, $config) + private function canSendFullReturn(\Shopware\Models\Order\Order $order, $config) { - if ($order->getOrderStatus()->getId() !== (int)($config['RatePayFullReturn'])) { - return false; - } - $paymentMethods = \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap::getPaymentMethods(); - if (!in_array($order->getPayment()->getName(), $paymentMethods)) { + if ($order->getOrderStatus()->getId() !== (int)($config['RatePayFullReturn']) + || !Helper::isRatePayPayment($order->getPayment()->getName())) { return false; } - $query = 'SELECT count(*) FROM s_order o - LEFT JOIN s_order_details od ON od.orderID = o.id - LEFT JOIN rpay_ratepay_order_positions rop ON rop.s_order_details_id = od.id - WHERE o.id = ? - AND (rop.delivered = 0 OR rop.cancelled != 0 OR rop.returned != 0)'; + $query = Shopware()->Db()->select() + ->from(['position' => 'rpay_ratepay_order_positions'], ['total' => 'COUNT(*)']) + ->joinLeft(['detail' => 's_order_details'], 'position.s_order_details_id = detail.id', null) + ->where('detail.orderID = :orderId') + ->where('position.delivered != detail.quantity'); - $count = Shopware()->Db()->fetchOne($query, [$order->getId()]); + $count = (int)Shopware()->Db()->fetchOne($query, [':orderId' => $order->getId()]); + if ($count > 0) { + Logger::singleton()->warning( + sprintf('-> Order [%d] has %d "not returnable" positions', $order->getId(), $count) + ); + } - return (int)$count === 0; + return $count === 0; } /** @@ -86,7 +106,7 @@ private function mustSendFullReturn(Shopware\Models\Order\Order $order, $config) * @param \Shopware\Models\Order\Order $order * @throws \Zend_Db_Adapter_Exception */ - public function informRatepayOfOrderStatusChange(Shopware\Models\Order\Order $order) + public function informRatepayOfOrderStatusChange(\Shopware\Models\Order\Order $order) { $config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); @@ -95,93 +115,34 @@ public function informRatepayOfOrderStatusChange(Shopware\Models\Order\Order $or $netPrices = $order->getNet() === 1; $modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(null, $backend, $netPrices); - $history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); $shippingCosts = $order->getInvoiceShipping(); $items = []; - $i = 0; foreach ($order->getDetails() as $item) { - $items[$i]['articlename'] = $item->getArticlename(); - $items[$i]['ordernumber'] = $item->getArticlenumber(); - $items[$i]['quantity'] = $item->getQuantity(); - $items[$i]['priceNumeric'] = $item->getPrice(); - $items[$i]['tax_rate'] = $item->getTaxRate(); - $taxRate = $item->getTaxRate(); - $i++; + $items[] = $this->getItemForOrderDetails($item); } + if (!empty($shippingCosts)) { - $items['Shipping']['articlename'] = 'Shipping'; - $items['Shipping']['ordernumber'] = 'shipping'; - $items['Shipping']['quantity'] = 1; - $items['Shipping']['priceNumeric'] = $shippingCosts; - $items['Shipping']['tax_rate'] = $taxRate; + $items['Shipping'] = [ + 'articlename' => 'Shipping', + 'ordernumber' => 'shipping', + 'quantity' => 1, + 'priceNumeric' => $shippingCosts, + 'tax_rate' => $order->getDetails()->first()->getTaxRate(), + ]; } - if ($this->mustSendFullShipped($order, $config)) { - $modelFactory->setTransactionId($order->getTransactionID()); - $operationData['orderId'] = $order->getId(); - $operationData['items'] = $items; - $modelFactory->setOrderId($order->getNumber()); - $result = $modelFactory->callRequest('ConfirmationDeliver', $operationData); - - if ($result === true) { - foreach ($items as $item) { - $bind = [ - 'delivered' => $item['quantity'] - ]; - - $this->updateItem($order->getId(), $item['ordernumber'], $bind); - if ($item['quantity'] <= 0) { - continue; - } - $history->logHistory($order->getId(), 'Artikel wurde versand.', $item['articlename'], $item['ordernumber'], $item['quantity']); - } - } + if ($this->canSendFullDelivery($order, $config)) { + $this->performFullDeliveryRequest($order, $modelFactory, $items); } - if ($this->mustSendFullCancellation($order, $config)) { - $modelFactory->setTransactionId($order->getTransactionID()); - $operationData['orderId'] = $order->getId(); - $operationData['items'] = $items; - $operationData['subtype'] = 'cancellation'; - $modelFactory->setOrderId($order->getNumber()); - $result = $modelFactory->callRequest('PaymentChange', $operationData); - - if ($result === true) { - foreach ($items as $item) { - $bind = [ - 'cancelled' => $item['quantity'] - ]; - $this->updateItem($order->getId(), $item['ordernumber'], $bind); - if ($item['quantity'] <= 0) { - continue; - } - $history->logHistory($order->getId(), 'Artikel wurde storniert.', $item['articlename'], $item['ordernumber'], $item['quantity']); - } - } + if ($this->canSendFullCancellation($order, $config)) { + $this->performFullCancellationRequest($order, $modelFactory, $items); } - if ($this->mustSendFullReturn($order, $config)) { - $modelFactory->setTransactionId($order->getTransactionID()); - $operationData['orderId'] = $order->getId(); - $operationData['items'] = $items; - $operationData['subtype'] = 'return'; - $modelFactory->setOrderId($order->getNumber()); - $result = $modelFactory->callRequest('PaymentChange', $operationData); - - if ($result === true) { - foreach ($items as $item) { - $bind = [ - 'returned' => $item['quantity'] - ]; - $this->updateItem($order->getId(), $item['ordernumber'], $bind); - if ($item['quantity'] <= 0) { - continue; - } - $history->logHistory($order->getId(), 'Artikel wurde retourniert.', $item['articlename'], $item['ordernumber'], $item['quantity']); - } - } + if ($this->canSendFullReturn($order, $config)) { + $this->performFullReturnRequest($order, $modelFactory, $items); } } @@ -202,4 +163,144 @@ private function updateItem($orderID, $articleOrderNumber, $bind) Shopware()->Db()->update('rpay_ratepay_order_positions', $bind, '`s_order_details_id`=' . $positionId); } } + + /** + * @param $item + * @return array + */ + private function getItemForOrderDetails($item) + { + return [ + 'articlename' => $item->getArticlename(), + 'ordernumber' => $item->getArticlenumber(), + 'quantity' => $item->getQuantity(), + 'priceNumeric' => $item->getPrice(), + 'tax_rate' => $item->getTaxRate(), + ]; + } + + /** + * @param \Shopware\Models\Order\Order $order + * @param $state + * @param $items + * @param $history + * @param $historyMsg + * @throws Zend_Db_Adapter_Exception + */ + private function updateItemStates(\Shopware\Models\Order\Order $order, $state, $items, $history, $historyMsg) + { + if (!in_array($state, ['delivered', 'returned', 'cancelled'])) { + Logger::singleton()->error('Incorrect item state "' . $state . '" was given.'); + return; + } + + foreach ($items as $item) { + $bind = [ + $state => $item['quantity'] + ]; + + $this->updateItem($order->getId(), $item['ordernumber'], $bind); + if ($item['quantity'] <= 0) { + continue; + } + + $history->logHistory( + $order->getId(), + $historyMsg, + $item['articlename'], + $item['ordernumber'], + $item['quantity'] + ); + } + } + + /** + * @param \Shopware\Models\Order\Order $order + * @param $modelFactory + * @param $items + */ + private function performFullReturnRequest(\Shopware\Models\Order\Order $order, $modelFactory, $items) + { + Logger::singleton()->debug('--> canSendFullReturn'); + $history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + $operationData = [ + 'orderId' => $order->getId(), + 'items' => $items, + 'subtype' => 'return', + ]; + + try { + $modelFactory->setTransactionId($order->getTransactionID()); + $modelFactory->setOrderId($order->getNumber()); + $result = $modelFactory->callPaymentChange($operationData); + if ($result === true) { + $this->updateItemStates($order, 'returned', $items, $history, self::MSG_ARTICLE_WAS_RETURNED); + return; + } + + Logger::singleton()->warning(sprintf(self::MSG_FULL_RETURN_REJECTED, $order->getId())); + } catch (\Exception $e) { + Logger::singleton()->error( + sprintf(self::MSG_FAILED_SENDING_FULL_RETURN, $order->getId(), $e->getMessage()) + ); + } + } + + private function performFullCancellationRequest(\Shopware\Models\Order\Order $order, $modelFactory, $items) + { + Logger::singleton()->debug('--> canSendFullCancellation'); + $history = new \Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + $operationData = [ + 'orderId' => $order->getId(), + 'items' => $items, + 'subtype' => 'cancellation', + ]; + + try { + $modelFactory->setTransactionId($order->getTransactionID()); + $modelFactory->setOrderId($order->getNumber()); + $result = $modelFactory->callPaymentChange($operationData); + if ($result === true) { + $this->updateItemStates($order, 'cancelled', $items, $history, self::MSG_ARTICLE_WAS_CANCELLED); + return; + } + + Logger::singleton()->warning(sprintf(self::MSG_FULL_CANCELLATION_REJECTED, $order->getId())); + } catch (\Exception $e) { + Logger::singleton()->error( + sprintf(self::MSG_FAILED_SENDING_FULL_CANCELLATION, $order->getId(), $e->getMessage()) + ); + } + } + + /** + * @param \Shopware\Models\Order\Order $order + * @param $modelFactory + * @param $items + */ + private function performFullDeliveryRequest(\Shopware\Models\Order\Order $order, $modelFactory, $items) + { + Logger::singleton()->debug('--> canSendFullDelivery'); + $history = new \Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + $operationData = [ + 'orderId' => $order->getId(), + 'items' => $items, + ]; + + try { + $modelFactory->setTransactionId($order->getTransactionID()); + $modelFactory->setOrderId($order->getNumber()); + $result = $modelFactory->callConfirmationDeliver($operationData); + if ($result === true) { + $this->updateItemStates($order, 'delivered', $items, $history, self::MSG_ARTICLE_WAS_SENT); + return; + } + + Logger::singleton()->warning(sprintf(self::MSG_FULL_DELIVERY_REJECTED, $order->getId())); + } catch (\Exception $e) { + Logger::singleton()->error( + sprintf(self::MSG_FAILED_SENDING_FULL_DELIVERY, $order->getId(), $e->getMessage()) + ); + } + } } diff --git a/Component/Service/PaymentProcessor.php b/Component/Service/PaymentProcessor.php index a8bcd524..3efcc4c4 100644 --- a/Component/Service/PaymentProcessor.php +++ b/Component/Service/PaymentProcessor.php @@ -3,10 +3,10 @@ namespace RpayRatePay\Component\Service; use RpayRatePay\Component\Mapper\PaymentRequestData; +use RpayRatePay\Component\Service\ShopwareUtil; class PaymentProcessor { - const PAYMENT_STATUS_COMPLETELY_PAID = 12; private $db; public function __construct($db) @@ -79,19 +79,18 @@ public function setOrderTransactionId($order, $transactionId) /** * @param \Shopware\Models\Order\Order $order */ - public function setPaymentStatusPaid($order) + public function setPaymentStatus($order) { //set cleared date $dateTime = new \DateTime(); $order->setClearedDate($dateTime); - Shopware()->Models()->flush($order); Shopware()->Modules()->Order() ->setPaymentStatus( $order->getId(), - self::PAYMENT_STATUS_COMPLETELY_PAID, + ShopwareUtil::getStatusAfterRatePayPayment($order->getPayment()), false ); } diff --git a/Component/Service/RatepayConfigWriter.php b/Component/Service/RatepayConfigWriter.php index 217dfc2f..4a870c13 100644 --- a/Component/Service/RatepayConfigWriter.php +++ b/Component/Service/RatepayConfigWriter.php @@ -50,14 +50,14 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, 'securityCode' => $securityCode ]; - $response = $factory->callRequest('ProfileRequest', $data); + $response = $factory->callProfileRequest($data); if (!is_array($response) || $response === false) { Logger::singleton()->info('RatePAY: Profile_Request failed for profileId ' . $profileId); return false; } - $payments = ['invoice', 'elv', 'installment']; + $payments = ['invoice', 'elv', 'installment', 'prepayment']; $type = []; //INSERT INTO rpay_ratepay_config_payment AND sets $type[] @@ -124,6 +124,7 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, $type['elv'], 0, 0, + $type['prepayment'], $response['result']['merchantConfig']['eligibility-device-fingerprint'] ?: 'no', $response['result']['merchantConfig']['device-fingerprint-snippet-id'], strtoupper($response['result']['merchantConfig']['country-code-billing']), @@ -140,16 +141,17 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, $activePayments[] = '"rpayratepaydebit"'; $activePayments[] = '"rpayratepayrate"'; $activePayments[] = '"rpayratepayrate0"'; + $activePayments[] = '"rpayratepayprepayment"'; $updateSqlActivePaymentMethods = 'UPDATE `s_core_paymentmeans` SET `active` = 1 WHERE `name` in(' . implode(',', $activePayments) . ') AND `active` <> 0'; $configSql = 'INSERT INTO `rpay_ratepay_config`' - . '(`profileId`, `invoice`, `installment`, `debit`, `installment0`, `installmentDebit`,' + . '(`profileId`, `invoice`, `installment`, `debit`, `installment0`, `installmentDebit`, `prepayment`,' . '`device-fingerprint-status`, `device-fingerprint-snippet-id`,' . '`country-code-billing`, `country-code-delivery`,' . '`currency`,`country`, `sandbox`,' . '`backend`, `shopId`)' - . 'VALUES(' . substr(str_repeat('?,', 15), 0, -1) . ');'; // In case of altering cols change 14 by amount of affected cols + . 'VALUES(' . substr(str_repeat('?,', 16), 0, -1) . ');'; // In case of altering cols change 14 by amount of affected cols try { $this->db->query($configSql, $data); if (count($activePayments) > 0) { diff --git a/Component/Service/RatepayHelper.php b/Component/Service/RatepayHelper.php new file mode 100644 index 00000000..be1b4fbc --- /dev/null +++ b/Component/Service/RatepayHelper.php @@ -0,0 +1,33 @@ +getGroup()->getTax() === false; } + + /** + * @param \Shopware\Models\Payment\Payment $payment + * @return int + */ + public static function getStatusAfterRatePayPayment($payment) + { + $config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); + + switch ($payment->getName()) { + case 'rpayratepayinvoice': + return (int)$config->get('RatePayInvoicePaymentStatus'); + case 'rpayratepayrate': + return (int)$config->get('RatePayInstallmentPaymentStatus'); + case 'rpayratepaydebit': + return (int)$config->get('RatePayDebitPaymentStatus'); + case 'rpayratepayrate0': + return (int)$config->get('RatePayInstallment0PaymentStatus'); + case 'rpayratepayprepayment': + return (int)$config->get('RatePayPrepaidPaymentStatus'); + default: + Logger::singleton()->error( + 'Unable to define status for unknown method: ' . $payment->getName() + ); + return 17; + } + + } } diff --git a/Component/Validation.php b/Component/Validation.php index 54ef0098..c3b0539f 100755 --- a/Component/Validation.php +++ b/Component/Validation.php @@ -111,7 +111,7 @@ public function setAllowedCountriesDelivery($countriesStr) */ public function isRatePAYPayment() { - return in_array($this->_payment->getName(), ['rpayratepayinvoice', 'rpayratepayrate', 'rpayratepaydebit', 'rpayratepayrate0']); + return in_array($this->_payment->getName(), ['rpayratepayinvoice', 'rpayratepayrate', 'rpayratepaydebit', 'rpayratepayrate0', 'rpayratepayprepayment']); } /** diff --git a/Controller/backend/RpayRatepayLogging.php b/Controller/backend/RpayRatepayLogging.php index 8986a457..1c29f975 100755 --- a/Controller/backend/RpayRatepayLogging.php +++ b/Controller/backend/RpayRatepayLogging.php @@ -1,6 +1,8 @@ Request()->getParam('start')); $limit = intval($this->Request()->getParam('limit')); $orderId = $this->Request()->getParam('orderId'); + if (!is_null($orderId)) { $transactionId = Shopware()->Db()->fetchOne('SELECT `transactionId` FROM `s_order` WHERE `id`=?', [$orderId]); $sqlTotal = 'SELECT COUNT(*) FROM `rpay_ratepay_logging` WHERE `transactionId`=?'; - $sql = 'SELECT log.*, `s_user_billingaddress`.`firstname`,`s_user_billingaddress`.`lastname` FROM `rpay_ratepay_logging` AS `log` ' - . 'LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID`' - . 'LEFT JOIN `s_user_billingaddress` ON `s_order`.`userID`=`s_user_billingaddress`.`userID`' - . 'WHERE `log`.`transactionId`=?' + + $sql = 'SELECT log.*, s_user.id as user_id FROM `rpay_ratepay_logging` AS `log` ' + . 'LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID` ' + . 'LEFT JOIN s_user ON s_order.userID=s_user.id ' + . 'WHERE log.transactionId=?' . 'ORDER BY `id` DESC'; + $data = Shopware()->Db()->fetchAll($sql, [$transactionId]); $total = Shopware()->Db()->fetchOne($sqlTotal, [$transactionId]); } else { $sqlTotal = 'SELECT COUNT(*) FROM `rpay_ratepay_logging`'; - $sql = 'SELECT log.*, `s_user_billingaddress`.`firstname`,`s_user_billingaddress`.`lastname` FROM `rpay_ratepay_logging` AS `log` ' - . 'LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID`' - . 'LEFT JOIN `s_user_billingaddress` ON `s_order`.`userID`=`s_user_billingaddress`.`userID`' - . 'ORDER BY `id` DESC ' - . "LIMIT $start,$limit"; + + $sql = 'SELECT log.*, s_user.id as user_id FROM `rpay_ratepay_logging` AS `log` ' + . 'LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID` ' + . 'LEFT JOIN s_user ON s_order.userID=s_user.id ' + . 'ORDER BY `id` DESC'; + $data = Shopware()->Db()->fetchAll($sql); $total = Shopware()->Db()->fetchOne($sqlTotal); } $store = []; foreach ($data as $row) { + + if ($row['user_id']) { + $customer = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $row['user_id']); + $customerWrapped = new ShopwareCustomerWrapper($customer, Shopware()->Models()); + $row['firstname'] = $customerWrapped->getBillingFirstName(); + $row['lastname'] = $customerWrapped->getBillingLastName(); + } + $matchesRequest = []; preg_match("/(.*)(<\?.*)/s", $row['request'], $matchesRequest); $row['request'] = $matchesRequest[1] . "\n" . $this->formatXml(trim($matchesRequest[2])); diff --git a/Controller/backend/RpayRatepayOrderDetail.php b/Controller/backend/RpayRatepayOrderDetail.php index bd1e4dc8..0306cd9e 100755 --- a/Controller/backend/RpayRatepayOrderDetail.php +++ b/Controller/backend/RpayRatepayOrderDetail.php @@ -58,58 +58,39 @@ public function init() public function initPositionsAction() { $articleNumbers = json_decode($this->Request()->getParam('articleNumber')); - $orderID = $this->Request()->getParam('orderId'); + $orderId = $this->Request()->getParam('orderId'); $success = true; - $bindings = [$orderID]; - $bind = ''; - $values = ''; + $articleNumberToInsert = []; + + $sqlCountEntries = " + SELECT `id`, COUNT(*) AS 'count', SUM(`quantity`) AS 'quantity' FROM `s_order_details` + WHERE `orderID`=? + AND `articleordernumber`=? + GROUP BY `id` + "; + foreach (array_unique($articleNumbers) as $articleNumber) { - $sqlCountEntrys = "SELECT `id`, COUNT(*) AS 'count', SUM(`quantity`) AS 'quantity' FROM `s_order_details` " - . 'WHERE `orderID`=? ' - . 'AND `articleordernumber` = ? ' - . 'ORDER BY `id` ASC'; try { - $row = Shopware()->Db()->fetchRow($sqlCountEntrys, [$orderID, $articleNumber]); + $row = Shopware()->Db()->fetchRow($sqlCountEntries, [$orderId, $articleNumber]); if ($row['count'] > 1) { // article already in order, update its quantity $sqlUpdate = 'UPDATE `s_order_details` SET `quantity`=? WHERE `id`=?'; $sqlDelete = 'DELETE FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber` = ? AND `id`!=?'; Shopware()->Db()->query($sqlUpdate, [$row['quantity'], $row['id']]); - Shopware()->Db()->query($sqlDelete, [$orderID, $articleNumber, $row['id']]); + Shopware()->Db()->query($sqlDelete, [$orderId, $articleNumber, $row['id']]); } else { - $bindings[] = $articleNumber; - $bind .= '?,'; + $articleNumberToInsert[] = $articleNumber; } } catch (\Exception $exception) { + Logger::singleton()->warn('Unable to initialize order position ' . $articleNumber . '. ' . $exception->getMessage()); $success = false; - Logger::singleton()->error('Exception:' . $exception->getMessage()); } } - if (!is_null($bind)) { // add new items to order - $bind = substr($bind, 0, -1); - $sqlSelectIDs = 'SELECT `id` FROM `s_order_details` ' - . "WHERE `orderID`=? AND `articleordernumber` IN ($bind) "; - try { - $detailIDs = Shopware()->Db()->fetchAll($sqlSelectIDs, $bindings); - foreach ($detailIDs as $row) { - $values .= '(' . $row['id'] . '),'; - } - $values = substr($values, 0, -1); - $sqlInsert = 'INSERT INTO `rpay_ratepay_order_positions` ' - . '(`s_order_details_id`) ' - . 'VALUES ' . $values; - Shopware()->Db()->query($sqlInsert); - } catch (\Exception $exception) { - $success = false; - Logger::singleton()->error('Exception:' . $exception->getMessage(), ' SQL:' . $sqlInsert); - } + if (!empty($articleNumberToInsert)) { // add new items to order + $success = $this->insertNewPositionsToOrder($articleNumberToInsert, $orderId); } - $this->View()->assign( - [ - 'success' => $success - ] - ); + $this->View()->assign(compact('success')); } /** @@ -164,19 +145,20 @@ public function deliverItemsAction() { $orderId = $this->Request()->getParam('orderId'); $items = json_decode($this->Request()->getParam('items')); - $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); - $order = $orderModel->findOneBy(['id' => $orderId]); + $order = Shopware()->Models() + ->getRepository('Shopware\Models\Order\Order') + ->findOneBy(['id' => $orderId]); $payment = $order->getPayment()->getName(); $this->_modelFactory->setTransactionId($order->getTransactionID()); $this->_modelFactory->setOrderId($order->getNumber()); - $itemsToDeliver = null; + $itemsToDeliver = 0; $sendItem = true; foreach ($items as $item) { $itemsToDeliver += $item->deliveredItems; - if ($payment == 'rpayratepayrate0' || $payment == 'rpayratepayrate') { + if (in_array($payment, ['rpayratepayrate0', 'rpayratepayrate'])) { if (($item->maxQuantity - $item->deliveredItems - $item->cancelled - $item->retournedItems - $item->delivered) !== 0) { $itemsToDeliver += $item->delivered; $sendItem = false; @@ -191,7 +173,7 @@ public function deliverItemsAction() $result = false; if ($sendItem == true) { - $result = $this->_modelFactory->callRequest('ConfirmationDeliver', $operationData); + $result = $this->_modelFactory->callConfirmationDeliver($operationData); } if ($result === true || $sendItem == false) { @@ -257,7 +239,7 @@ public function cancelItemsAction() $operationData['items'] = $items; $operationData['subtype'] = 'cancellation'; $this->_modelFactory->setOrderId($order->getNumber()); - $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); + $result = $this->_modelFactory->callPaymentChange($operationData); if ($result === true) { foreach ($items as $item) { @@ -318,7 +300,7 @@ public function returnItemsAction() $operationData['items'] = $items; $operationData['subtype'] = 'return'; $this->_modelFactory->setOrderId($order->getNumber()); - $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); + $result = $this->_modelFactory->callPaymentChange($operationData); if ($result === true) { foreach ($items as $item) { @@ -369,6 +351,7 @@ public function addAction() . 'INNER JOIN `rpay_ratepay_order_positions` ON `s_order_details`.`id` = `rpay_ratepay_order_positions`.`s_order_details_id` ' . 'WHERE `orderID`=?', [$orderId]); + $items = null; foreach ($orderItems as $row) { if ($row['quantityDeliver'] == 0) { continue; @@ -388,7 +371,7 @@ public function addAction() $items = $shippingRow; } - if ($onlyDebit == false) { + if ($onlyDebit === false) { $this->_modelFactory->setTransactionId($order['transactionID']); $operationData['orderId'] = $orderId; $operationData['items'] = $items; @@ -404,7 +387,7 @@ public function addAction() ) { $result = false; } else { - $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); + $result = $this->_modelFactory->callPaymentChange($operationData); } if ($result === true) { @@ -636,4 +619,36 @@ private function setNewOrderState($orderId, $operation = null) Logger::singleton()->error($exception->getMessage()); } } + + /** + * @param $articleOrderNumbers + * @param $orderId + * @return bool + */ + private function insertNewPositionsToOrder($articleOrderNumbers, $orderId) + { + $articleBinds = array_map(function ($item) { + return '?'; + }, $articleOrderNumbers); + $orderDetailIdsQuery = 'SELECT `id` FROM `s_order_details` + WHERE `orderID`=? AND `articleordernumber` IN (' . join(', ', $articleBinds) . ')'; + + try { + $queryArguments = array_merge([$orderId], $articleOrderNumbers); + $orderDetailIds = array_map( + function ($item) { + return $item['id']; + }, + Shopware()->Db()->fetchAll($orderDetailIdsQuery, $queryArguments) + ); + $newValues = '(' . implode('), (', $orderDetailIds) . ')'; + $sqlInsert = 'INSERT INTO `rpay_ratepay_order_positions` (`s_order_details_id`) VALUES ' . $newValues; + Shopware()->Db()->query($sqlInsert); + } catch (\Exception $exception) { + Logger::singleton()->error($exception->getMessage() . '. SQL:' . $sqlInsert); + return false; + } + + return true; + } } diff --git a/Controller/frontend/RpayRatepay.php b/Controller/frontend/RpayRatepay.php index 9cb57020..84a19cd0 100755 --- a/Controller/frontend/RpayRatepay.php +++ b/Controller/frontend/RpayRatepay.php @@ -38,7 +38,10 @@ class Shopware_Controllers_Frontend_RpayRatepay extends Shopware_Controllers_Fro private $_customerMessage; /** - * Initiates the Object + * @return string + * @throws \Doctrine\ORM\ORMException + * @throws \Doctrine\ORM\OptimisticLockException + * @throws \Doctrine\ORM\TransactionRequiredException */ public function init() { @@ -70,36 +73,7 @@ public function init() */ public function indexAction() { - Shopware()->Session()->RatePAY['errorRatenrechner'] = 'false'; - if (preg_match('/^rpayratepay(invoice|rate|debit|rate0)$/', $this->getPaymentShortName())) { - if ($this->getPaymentShortName() === 'rpayratepayrate' && !isset(Shopware()->Session()->RatePAY['ratenrechner']) - ) { - Shopware()->Session()->RatePAY['errorRatenrechner'] = 'true'; - $this->redirect( - Shopware()->Front()->Router()->assemble( - [ - 'controller' => 'checkout', - 'action' => 'confirm', - 'forceSecure' => true - ] - ) - ); - } elseif ($this->getPaymentShortName() === 'rpayratepayrate0' && !isset(Shopware()->Session()->RatePAY['ratenrechner'])) { - Shopware()->Session()->RatePAY['errorRatenrechner'] = 'true'; - $this->redirect( - Shopware()->Front()->Router()->assemble( - [ - 'controller' => 'checkout', - 'action' => 'confirm', - 'forceSecure' => true - ] - ) - ); - } else { - Logger::singleton()->info('proceed'); - $this->_proceedPayment(); - } - } else { + if (!$this->isRatePayPayment()) { $this->redirect( Shopware()->Front()->Router()->assemble( [ @@ -109,7 +83,27 @@ public function indexAction() ] ) ); + return; } + + if (!$this->isInstallmentPaymentWithoutCalculation()) { + Logger::singleton()->info('Proceed with RatePAY payment'); + Shopware()->Session()->RatePAY['errorRatenrechner'] = 'false'; + $this->_proceedPayment(); + return; + } + + Logger::singleton()->info('RatePAY installment has incomplete calculation'); + Shopware()->Session()->RatePAY['errorRatenrechner'] = 'true'; + $this->redirect( + Shopware()->Front()->Router()->assemble( + [ + 'controller' => 'checkout', + 'action' => 'confirm', + 'forceSecure' => true + ] + ) + ); } /** @@ -144,6 +138,7 @@ public function saveUserDataAction() $updateAddressData = []; if (!is_null($customerAddressBilling)) { + //shopware before 5.2 ... we could try changing order of if and ifelse if (method_exists($customerAddressBilling, 'getBirthday')) { $updateAddressData['phone'] = $Parameter['ratepay_phone'] ?: $customerAddressBilling->getPhone(); if ($customerAddressBilling->getCompany() !== '') { @@ -153,10 +148,10 @@ public function saveUserDataAction() } try { - Shopware()->Db()->update('s_user_billingaddress', $updateAddressData, 'userID=' . $Parameter['userid']); // ToDo: Why parameter? - Logger::singleton()->info('Kundendaten aktualisiert.'); + Shopware()->Db()->update('s_user_billingaddress', $updateAddressData, 'userID=' . $Parameter['userid']); // TODO: Parameterize or make otherwise safe + Logger::singleton()->info('Customer data was updated'); } catch (\Exception $exception) { - Logger::singleton()->error('Fehler beim Updaten der Userdaten: ' . $exception->getMessage()); + Logger::singleton()->error('RatePAY was unable to update customer data: ' . $exception->getMessage()); $return = 'NOK'; } } elseif (method_exists($userModel, 'getBirthday')) { // From Shopware 5.2 birthday is moved to customer object @@ -174,9 +169,9 @@ public function saveUserDataAction() if (count($updateAddressData) > 0) { Shopware()->Db()->update('s_user_addresses', $updateAddressData, 'id=' . $Parameter['checkoutBillingAddressId']); } - Logger::singleton()->info('Kundendaten aktualisiert.'); + Logger::singleton()->info('Customer data was updated'); } catch (\Exception $exception) { - Logger::singleton()->error('Fehler beim Updaten der User oder Address daten: ' . $exception->getMessage()); + Logger::singleton()->error('RatePAY was unable to update customer data: ' . $exception->getMessage()); $return = 'NOK'; } } else { @@ -231,7 +226,7 @@ private function _proceedPayment() Logger::singleton()->error($exception->getMessage()); } - $paymentProcessor->setPaymentStatusPaid($order); + $paymentProcessor->setPaymentStatus($order); if (Shopware_Plugins_Frontend_RpayRatePay_Bootstrap::getPCConfig() == true) { $paymentProcessor->sendPaymentConfirm($resultRequest->getTransactionId(), $order); @@ -302,16 +297,11 @@ private function getRatePayPluginConfigByCountry($shopId, $country, $backend = f //get ratepay config based on shopId and profileId return Shopware()->Db()->fetchRow(' - SELECT - * - FROM - `rpay_ratepay_config` - WHERE - `shopId` =? - AND - `profileId`=? - AND - backend=? + SELECT * + FROM `rpay_ratepay_config` + WHERE `shopId` =? + AND `profileId`=? + AND backend=? ', [$shopId, $profileId, $backend]); } @@ -348,4 +338,21 @@ public function getWhitelistedCSRFActions() 'calcRequest' ]; } + + /** + * @return bool + */ + private function isRatePayPayment() + { + return 1 === preg_match('/^rpayratepay(invoice|rate|debit|rate0|prepayment)$/', $this->getPaymentShortName()); + } + + /** + * @return bool + */ + private function isInstallmentPaymentWithoutCalculation() + { + return in_array($this->getPaymentShortName(), ['rpayratepayrate', 'rpayratepayrate0']) + && !isset(Shopware()->Session()->RatePAY['ratenrechner']); + } } diff --git a/Jenkinsfile b/Jenkinsfile index 930c3b1a..7c243b85 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -55,15 +55,14 @@ pipeline { stage('Deploy') { steps { echo "[STAGE] Deploy" - sh '''tar --exclude=build -czf ./build/RpayRatePayBase.tar . - mkdir -p build/dist/Frontend/RpayRatePay - tar -xzf build/RpayRatePayBase.tar -C build/dist/Frontend/RpayRatePay/ - - cd build/dist - zip -r RpayRatePay.zip Frontend -x \\*.git\\* -x \\*.DS_Store\\* -x \\*.idea\\* - - cd ../../ - rm -rf build/dist/Frontend build/RpayRatePayBase.zip''' + sh ''' + tar -czf build/dist.tar.gz Bootstrapping Component Controller Views Bootstrap.php plugin.json plugin.png README.md + mkdir -p build/dist/Frontend/RpayRatePay + tar -xzf build/dist.tar.gz -C build/dist/Frontend/RpayRatePay + rm -rf build/dist.tar.gz + cd build/dist + zip -r RpayRatePay.zip Frontend + ''' archiveArtifacts 'build/dist/RpayRatePay.zip' } } diff --git a/README.md b/README.md index d6eb661d..15209110 100755 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ |Module | RatePAY Module for Shopware |------|---------- |Author | Annegret Seufert -|Shop Version | `5.0.x` `5.1.x` `5.2.x` `5.3.x` -|Version | `5.2.6` +|Shop Version | `5.1.x` - `5.5.x` +|Version | `5.3.0` |Link | http://www.ratepay.com |Mail | integration@ratepay.com |Full Documentation | https://ratepay.gitbook.io/shopware/ @@ -24,6 +24,13 @@ ## Changelog +### Version 5.3.0 - Released 2018-11-07 +* Improve client side dob validation +* Improve bidirectionality process +* Add prepayment +* Add Shopware 5.5 compatibility +* Add configurable payment states + ### Version 5.2.6 - Released 2018-10-01 * fix ignored updates in bidirectional process * fix usage of addresses for shipping/billing during checkout diff --git a/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepaydelivery.js b/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepaydelivery.js index 8e309c14..f704e517 100755 --- a/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepaydelivery.js +++ b/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepaydelivery.js @@ -169,14 +169,15 @@ Ext.define('Shopware.apps.Order.view.detail.ratepaydelivery', { id: 0, inStock: 0, mode: 0, - price: Ext.getCmp('creditAmount').getValue() * -1, + price: (-1 * Math.abs(Ext.getCmp('creditAmount').getValue())), quantity: 1, statusDescription: "", statusId: 0, taxDescription: "", taxId: 1, taxRate: 0, - total: 0 + total: 0, + changed: me.record.get('changed') }, success: function (payload) { var response = Ext.JSON.decode(payload.responseText); @@ -234,65 +235,66 @@ Ext.define('Shopware.apps.Order.view.detail.ratepaydelivery', { } ], buttons: [ - { - text: '{s namespace=RatePAY name=ok}Ok{/s}', - handler: function () { - var randomnumber = Math.floor(Math.random() * 10001); - var debitname = 'Debit' + id + '+' + randomnumber; - Ext.Ajax.request({ - url: '{url controller=Order action=savePosition}', - method: 'POST', - async: false, - params: { - orderId: id, - articleId: 0, - articleName: 'Nachbelastung', - articleNumber: debitname, - id: 0, - inStock: 0, - mode: 0, - price: Ext.getCmp('debitAmount').getValue(), - quantity: 1, - statusDescription: "", - statusId: 0, - taxDescription: "", - taxId: 1, - taxRate: 0, - total: 0 - }, - success: function (payload) { - var response = Ext.JSON.decode(payload.responseText); - var articleNumber = new Array(); - var insertedIds = new Array(); - var message; - articleNumber.push(response.data.articleNumber); - insertedIds.push(response.data.id); - if (me.initPositions(articleNumber)) { - if (me.paymentChange(id, 'debit', insertedIds)) { - message = '{s namespace=RatePAY name=messagedebituccess}Nachbelastung wurde erfolgreich zur Bestellung hinzugefügt.{/s}'; - } else { - me.deletePosition(insertedIds); - message = '{s namespace=RatePAY name=messagedebitfailrequest}Nachbelastung konnte nicht korrekt an RatePAY übermittelt werden.{/s}'; - } + { + text: '{s namespace=RatePAY name=ok}Ok{/s}', + handler: function () { + var randomnumber = Math.floor(Math.random() * 10001); + var debitname = 'Debit' + id + '+' + randomnumber; + Ext.Ajax.request({ + url: '{url controller=Order action=savePosition}', + method: 'POST', + async: false, + params: { + orderId: id, + articleId: 0, + articleName: 'Nachbelastung', + articleNumber: debitname, + id: 0, + inStock: 0, + mode: 0, + price: Math.abs(Ext.getCmp('debitAmount').getValue()), + quantity: 1, + statusDescription: "", + statusId: 0, + taxDescription: "", + taxId: 1, + taxRate: 0, + total: 0, + changed: me.record.get('changed') + }, + success: function (payload) { + var response = Ext.JSON.decode(payload.responseText); + var articleNumber = new Array(); + var insertedIds = new Array(); + var message; + articleNumber.push(response.data.articleNumber); + insertedIds.push(response.data.id); + if (me.initPositions(articleNumber)) { + if (me.paymentChange(id, 'debit', insertedIds)) { + message = '{s namespace=RatePAY name=messagedebituccess}Nachbelastung wurde erfolgreich zur Bestellung hinzugefügt.{/s}'; } else { - message = '{s namespace=RatePAY name=messagedebitfailposition}Nachbelastung konnte nicht der Bestellung hinzugefügt werden.{/s}'; + me.deletePosition(insertedIds); + message = '{s namespace=RatePAY name=messagedebitfailrequest}Nachbelastung konnte nicht korrekt an RatePAY übermittelt werden.{/s}'; } - Ext.getCmp('debitWindow').close(); - Ext.Msg.alert('{s namespace=RatePAY name=messagedebittitle}Nachbelastung hinzufügen{/s}', message); - me.reloadGrid(); + } else { + message = '{s namespace=RatePAY name=messagedebitfailposition}Nachbelastung konnte nicht der Bestellung hinzugefügt werden.{/s}'; } - }); - } - }, - { - text: '{s namespace=backend/application/main name=detail_window/cancel_button_text}Cancel{/s}', - handler: function () { Ext.getCmp('debitWindow').close(); + Ext.Msg.alert('{s namespace=RatePAY name=messagedebittitle}Nachbelastung hinzufügen{/s}', message); + me.reloadGrid(); } + }); } - ] - }).show(); - } + }, + { + text: '{s namespace=backend/application/main name=detail_window/cancel_button_text}Cancel{/s}', + handler: function () { + Ext.getCmp('debitWindow').close(); + } + } + ] + }).show(); + } }, { iconCls: 'sprite-truck', @@ -473,12 +475,20 @@ Ext.define('Shopware.apps.Order.view.detail.ratepaydelivery', { } }); + me.record.store.reload({ + callback: function(records, operation, success) { + me.record = records.find(function (r) { + return r.internalId === me.record.internalId; + }); + } + }); + me.reconfigure(me.store); }, initPositions: function (articleNumber) { - var returnValue = false; var me = this; + var returnValue = false; var id = me.record.get('id'); Ext.Ajax.request({ url: '{url controller=RpayRatepayOrderDetail action=initPositions}', @@ -496,15 +506,15 @@ Ext.define('Shopware.apps.Order.view.detail.ratepaydelivery', { return returnValue; }, - paymentChange: function (id, suboperation, insertedIds) { + paymentChange: function (orderId, subOperation, insertedIds) { var returnValue = false; Ext.Ajax.request({ url: '{url controller=RpayRatepayOrderDetail action=add}', method: 'POST', async: false, params: { - orderId: id, - suboperation: suboperation, + orderId: orderId, + suboperation: subOperation, insertedIds: Ext.JSON.encode(insertedIds) }, success: function (payload) { @@ -514,6 +524,7 @@ Ext.define('Shopware.apps.Order.view.detail.ratepaydelivery', { }); return returnValue; }, + deletePosition: function (id) { var me = this; var orderid = me.record.get('id'); diff --git a/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepayretoure.js b/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepayretoure.js index 76c6590a..1020d2a5 100755 --- a/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepayretoure.js +++ b/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/articlemanagement/ratepayretoure.js @@ -40,7 +40,8 @@ Ext.define('Shopware.apps.Order.view.detail.ratepayretoure', { defaults: { flex: 1 } - } + }; + me.dockedItems = [ { xtype: 'toolbar', diff --git a/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/ratepaydetailorder.js b/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/ratepaydetailorder.js index 398f1404..9ab4594d 100755 --- a/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/ratepaydetailorder.js +++ b/Views/backend/rpay_ratepay_orderdetail/backend/order/view/detail/ratepaydetailorder.js @@ -30,17 +30,15 @@ Ext.define('Shopware.apps.Order.view.detail.ratepaydetailorder', { isRatePAYOrder: function () { var me = this; var paymentName = ''; - for (i = 0; i < me.paymentsStore.data.items.length; i++) { - if (me.paymentsStore.data.items[i].data.id == this.record.get('paymentId')) { - paymentName = me.paymentsStore.data.items[i].data.name; + var counter = 0; + var payments = me.paymentsStore.data.items; + for (i = 0; i < payments.length; i++) { + if (payments[i].data.id == this.record.get('paymentId')) { + paymentName = payments[i].data.name; } } - if (paymentName.search(/^rpayratepay(invoice|rate|rate0|debit)$/) != -1) { - return true; - } else { - return false; - } + return (paymentName.search(/^rpayratepay(invoice|rate|rate0|debit|prepayment)$/) !== -1); }, /** diff --git a/Views/responsive/frontend/_public/src/javascripts/jquery.ratepay_checkout.js b/Views/responsive/frontend/_public/src/javascripts/jquery.ratepay_checkout.js index 2802b714..1b01d401 100644 --- a/Views/responsive/frontend/_public/src/javascripts/jquery.ratepay_checkout.js +++ b/Views/responsive/frontend/_public/src/javascripts/jquery.ratepay_checkout.js @@ -183,7 +183,15 @@ /* dob validation */ if ($('#ratepay_birthyear').length) { /* only do the check if dob form exists */ - if ($('#ratepay_birthyear').val() != '' && $('#ratepay_birthmonth').val() != '' && $('#ratepay_birthday').val() != '') { + var year = $('#ratepay_birthyear').val().trim(); + var month = $('#ratepay_birthmonth').val().trim(); + var day = $('#ratepay_birthday').val().trim(); + + if ( + year.match(/^(1|2)\d{3}$/) // year begins with 1 or 2 followed by three digits + && month.match(/^(0?[1-9]|1[0-2])$/) // month can start with 0 followed by a digit (1-9) or starts with 1 followed by 0, 1 or 2 + && day.match(/^(0?[1-9]|(1|2)[0-9]|3[0-1])$/) // comparable to month logic but capable to match numbers from 1-31 + ) { dob = new Date($('#ratepay_birthyear').val() + '-' + $('#ratepay_birthmonth').val() + '-' + $('#ratepay_birthday').val()); /* validate age */ @@ -197,6 +205,7 @@ } else { error = true; userUpdate = false; + errorMessage = errorMessageDobNotValid; } } diff --git a/Views/responsive/frontend/installment/php/PiRatepayRateCalc.php b/Views/responsive/frontend/installment/php/PiRatepayRateCalc.php index a1cb4c5b..e418a575 100755 --- a/Views/responsive/frontend/installment/php/PiRatepayRateCalc.php +++ b/Views/responsive/frontend/installment/php/PiRatepayRateCalc.php @@ -8,7 +8,10 @@ * @package pi_ratepay_rate_calculator * Code by Ratepay GmbH */ - require_once 'PiRatepayRateCalcBase.php'; + +use RpayRatePay\Component\Model\ShopwareCustomerWrapper; + +require_once 'PiRatepayRateCalcBase.php'; /** * This is for the communication with RatePAY @@ -44,9 +47,11 @@ public function getRatepayRateConfig($backend = false) $shopId = Shopware()->Shop()->getId(); $userId = Shopware()->Session()->sUserId; - $user = Shopware()->Models()->getRepository('Shopware\Models\Customer\Billing')->findOneBy(array('customerId' => $userId)); - $country = Shopware()->Models()->find('Shopware\Models\Country\Country', $user->getCountryId()); - $countryIso = $country->getIso(); + + $customer = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $userId); + $userWrapped = new ShopwareCustomerWrapper($customer, Shopware()->Models()); + $countryIso = $userWrapped->getBillingCountry()->getIso(); + $basketAmount = $this->getRequestAmount(); $sBackend = $backend ? 1 : 0; @@ -147,16 +152,7 @@ private function requestRateDetails($subtype) return "RatePAY frontend controller: No user set"; } - $config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); - - if (isset($Parameter['checkoutBillingAddressId']) && !is_null($Parameter['checkoutBillingAddressId'])) { // From Shopware 5.2 current billing address is sent by parameter - $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $customerAddressBilling = $addressModel->findOneBy(array('id' => $Parameter['checkoutBillingAddressId'])); - $country = $customerAddressBilling->getCountry(); - } else { - $user = Shopware()->Models()->getRepository('Shopware\Models\Customer\Billing')->findOneBy(array('customerId' => $userId)); - $country = Shopware()->Models()->find('Shopware\Models\Country\Country', $user->getCountryId()); - } + //$config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); $customer = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $userId); $netPrices = ! $customer->getGroup()->getTax(); diff --git a/Views/responsive/frontend/payment_rpay_part/RatePAYErrorpage.tpl b/Views/responsive/frontend/payment_rpay_part/RatePAYErrorpage.tpl index bc0e0ba4..35f54cb4 100755 --- a/Views/responsive/frontend/payment_rpay_part/RatePAYErrorpage.tpl +++ b/Views/responsive/frontend/payment_rpay_part/RatePAYErrorpage.tpl @@ -3,7 +3,7 @@
@@ -19,9 +19,6 @@ {s namespace=frontend/checkout/ajax_add_article name=AjaxAddLinkCart}Warenkorb anzeigen{/s} - - {s namespace=frontend/account/index name=AccountLinkChangePayment}Zahlungsart ändern{/s} -
{/block} diff --git a/Views/responsive/frontend/payment_rpay_part/RatePAYFormElements.tpl b/Views/responsive/frontend/payment_rpay_part/RatePAYFormElements.tpl index aa1503dd..da6e3c21 100755 --- a/Views/responsive/frontend/payment_rpay_part/RatePAYFormElements.tpl +++ b/Views/responsive/frontend/payment_rpay_part/RatePAYFormElements.tpl @@ -6,15 +6,20 @@ {block name='ratepay_frontend_birthday'}

+
- + {s namespace=frontend/register/personal_fieldset name=RegisterPlaceholderBirthdayTag}Tag{/s}* + +
+
- + {s namespace=frontend/register/personal_fieldset name=RegisterPlaceholderBirthdayMonth}Monat{/s}* + +
+
- + {s namespace=frontend/register/personal_fieldset name=RegisterPlaceholderBirthdayYear}Jahr{/s}* + +
+ @@ -38,6 +40,11 @@ {include file='frontend/payment_rpay_part/RatePAYFormElements.tpl'} {/if} + {if $sPayment.name == 'rpayratepayprepayment'} + {include file='frontend/payment_rpay_part/RatePAYErrorMessage.tpl'} + {include file='frontend/payment_rpay_part/RatePAYFormElements.tpl'} + {/if} + {if $sPayment.name == 'rpayratepaydebit'} {include file='frontend/payment_rpay_part/RatePAYSEPAInformationHeader.tpl'} {include file='frontend/payment_rpay_part/RatePAYErrorMessage.tpl'} diff --git a/Views/responsive/frontend/payment_rpay_part/index/index.tpl b/Views/responsive/frontend/payment_rpay_part/index/index.tpl index 22385539..a9ade470 100644 --- a/Views/responsive/frontend/payment_rpay_part/index/index.tpl +++ b/Views/responsive/frontend/payment_rpay_part/index/index.tpl @@ -13,6 +13,7 @@ var errorMessageDataComplete = '{s namespace=RatePAY name=invaliddata}Bitte vervollständigen Sie die Daten.{/s}'; var errorMessageValidAge = '{s namespace=RatePAY name=dobtooyoung}Für eine Bezahlung mit RatePAY müssen Sie mindestens 18 Jahre alt sein.{/s}'; + var errorMessageDobNotValid = '{s namespace=RatePAY name=dobNotValid}Bitte geben Sie ein gültiges Geburtsdatum ein.{/s}'; var errorMessageValidPhone = '{s namespace=RatePAY name=phonenumbernotvalid}Bitte geben Sie eine gültige Telefonnummer an. Die Nummer muss mindestens 6 Zeichen lang sein und darf Sonderzeichen wie - und + enthalten.{/s}'; var errorMessageValidBankData = '{s namespace=RatePAY name=bankdatanotvalid}Für eine Bezahlung mit RatePay müssen Sie gültige Bankverbindung angeben.{/s}'; var errorMessageAcceptSepaAGB = '{s namespace=RatePAY name=ratepayAgbMouseover}Um RatePAY nutzen zu können müssen sie den AGBs von RatePAY zustimmen{/s}'; diff --git a/plugin.json b/plugin.json index edc2198a..7185f627 100644 --- a/plugin.json +++ b/plugin.json @@ -10,7 +10,7 @@ "author": "RatePAY GmbH", "supplier": "RatePAY GmbH", "description": "

RatePAY Payment plugin for Shopware Community Edition Version 5

  • RatePAY Payment Module
  • Payment means: Invoice, Direct Debit (ELV), Rate
  • Cancellations, Returns, etc. can be created from an additional tab in the order detail view
  • Integrated support for multishops
  • Improved payment form with visual feedback for your customers
  • Supported Languages: German, English
  • Backend Log with custom View accessible from your shop backend
", - "currentVersion": "5.2.6", + "currentVersion": "5.3.0", "payment_confirm": true, "compatibility": { "minimumVersion": "5.0.0",