diff --git a/phpstan.neon b/phpstan.neon index 3b1859bd..81b71261 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -4,4 +4,7 @@ parameters: - ./src checkMissingIterableValueType: false treatPhpDocTypesAsCertain: false - checkGenericClassInNonGenericObjectType: false \ No newline at end of file + checkGenericClassInNonGenericObjectType: false + excludePaths: + - ./src/Subscribers/OrderReturnCreatedSubscriber.php + - ./custom/plugins/BuckarooPayments/src/Service/RefundService.php diff --git a/src/Buckaroo/Client.php b/src/Buckaroo/Client.php index 140485cb..1a8080ec 100644 --- a/src/Buckaroo/Client.php +++ b/src/Buckaroo/Client.php @@ -5,7 +5,6 @@ namespace Buckaroo\Shopware6\Buckaroo; use Buckaroo\BuckarooClient; -use Buckaroo\Shopware6\Buckaroo\PayloadFragmentInterface; class Client { diff --git a/src/Buckaroo/Refund/Order/PaymentRecord.php b/src/Buckaroo/Refund/Order/PaymentRecord.php new file mode 100644 index 00000000..ea5dc073 --- /dev/null +++ b/src/Buckaroo/Refund/Order/PaymentRecord.php @@ -0,0 +1,61 @@ +transactionData = $transactionData; + } + + public function getId(): string + { + if ( + !isset($this->transactionData['id']) || + !is_scalar($this->transactionData['id']) + ) { + throw new \InvalidArgumentException('Transaction id must be a string'); + } + return (string)$this->transactionData['id']; + } + + public function getAmount(): float + { + if ( + !isset($this->transactionData['amount']) || + !is_scalar($this->transactionData['amount']) + ) { + return 0; + } + return (float)$this->transactionData['amount']; + } + + public function getOriginalTransactionId(): ?string + { + if ( + !isset($this->transactionData['transactions']) || + !is_string($this->transactionData['transactions']) + ) { + return null; + } + return $this->transactionData['transactions']; + } + + public function getPaymentCode(): ?string + { + if ( + !isset($this->transactionData['transaction_method']) && + !is_string($this->transactionData['transaction_method']) + ) { + return null; + } + return $this->transactionData['transaction_method']; + } +} diff --git a/src/Buckaroo/Refund/Order/PaymentRecordInterface.php b/src/Buckaroo/Refund/Order/PaymentRecordInterface.php new file mode 100644 index 00000000..747a4058 --- /dev/null +++ b/src/Buckaroo/Refund/Order/PaymentRecordInterface.php @@ -0,0 +1,16 @@ +transactionData = $transactionData; + $this->amount = $amount; + } + + public function getId(): string + { + if (!is_scalar($this->transactionData->get('id'))) { + return ''; + } + return (string)$this->transactionData->get('id'); + } + + public function getAmount(): float + { + + if ( + !is_scalar($this->transactionData->get('amount')) || + !is_scalar($this->transactionData->get('amount_credit')) + ) { + return 0.0; + } + return (float)$this->transactionData->get('amount') - (float)$this->transactionData->get('amount_credit'); + } + + public function getOriginalTransactionId(): ?string + { + if ( + !is_string($this->transactionData->get('transactions')) + ) { + return null; + } + return $this->transactionData->get('transactions'); + } + + public function getPaymentCode(): ?string + { + if ( + !is_string($this->transactionData->get('transaction_method')) + ) { + return null; + } + return $this->transactionData->get('transaction_method'); + } + + public function addAmount(float $amount): self + { + $this->amount += $amount; + return $this; + } +} diff --git a/src/Buckaroo/Refund/OrderRefundData.php b/src/Buckaroo/Refund/OrderRefundData.php new file mode 100644 index 00000000..dbcdb0b1 --- /dev/null +++ b/src/Buckaroo/Refund/OrderRefundData.php @@ -0,0 +1,96 @@ +order = $order; + $this->amount = $amount; + $this->paymentRecord = $paymentRecord; + } + public function getInvoiceNumber(): string + { + if ($this->order->getOrderNumber() === null) { + return ''; + } + return $this->order->getOrderNumber(); + } + + public function getOrderNumber(): string + { + return $this->getInvoiceNumber(); + } + + public function getAmount(): float + { + return $this->amount; + } + + public function getCurrency(): string + { + $currency = $this->order->getCurrency(); + if ($currency === null) { + throw new \InvalidArgumentException('Cannot find currency on order'); + } + return $currency->getIsoCode(); + } + + public function getTransactionId(): string + { + return $this->getLastTransaction()->getId(); + } + + public function getOrderId(): string + { + return $this->order->getId(); + } + + public function getLastTransaction(): OrderTransactionEntity + { + $transactions = $this->order->getTransactions(); + + if ($transactions === null) { + throw new \InvalidArgumentException('Cannot find last transaction on order'); + } + + /** @var \Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity|null */ + $transaction = $transactions->last(); + + if ($transaction === null) { + throw new \InvalidArgumentException('Cannot find last transaction on order'); + } + + return $transaction; + } + + public function getOrder(): OrderEntity + { + return $this->order; + } + + public function getPaymentRecord(): PaymentRecordInterface + { + return $this->paymentRecord; + } +} diff --git a/src/Buckaroo/Refund/RefundDataInterface.php b/src/Buckaroo/Refund/RefundDataInterface.php new file mode 100644 index 00000000..9b81a9ab --- /dev/null +++ b/src/Buckaroo/Refund/RefundDataInterface.php @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + - + + + + + - @@ -482,7 +502,7 @@ - + @@ -492,6 +512,14 @@ + + + + + + + + diff --git a/src/Resources/public/administration/js/buckaroo-payments.js b/src/Resources/public/administration/js/buckaroo-payments.js index c5620d80..e9b7e1b3 100644 --- a/src/Resources/public/administration/js/buckaroo-payments.js +++ b/src/Resources/public/administration/js/buckaroo-payments.js @@ -1 +1 @@ -!function(e){var t={};function n(a){if(t[a])return t[a].exports;var o=t[a]={i:a,l:!1,exports:{}};return e[a].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(a,o,function(t){return e[t]}.bind(null,o));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=(window.__sw__.assetPath + '/bundles/buckaroopayments/'),n(n.s="unXS")}({"5leu":function(e,t,n){},"6Dsi":function(e,t,n){var a=n("jA+u");a.__esModule&&(a=a.default),"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);(0,n("P8hj").default)("21e3d453",a,!0,{})},"8kDq":function(e,t,n){},C41O:function(e){e.exports=JSON.parse('{"buckaroo-payment":{"fee":"Buckaroo Fee","order":{"refundDescription":"Refund for order #orderNumber"},"general":{"title":"Buckaroo","description":"Buckaroo Payment"},"settingsForm":{"save":"Save","titleSuccess":"Success","titleError":"Error"},"supportModal":{"menuButton":"Version & Support","title":"Version & Support","support":{"description":"Before contacting Buckaroo technical support, please retrieve your (Merchant) key, Secret key, certificate and certificate thumbprint.","label1":"Buckaroo Payment Plaza:","label2":"Phone:","label3":"E-mail:","label4":"Website:","your_version":"Your PHP version:","version":"Version compatibility","information":"Information"}},"tabs":{"title":"Buckaroo Payment","overview":"Overview"},"paymentDetail":{"yourLink":"Your Paylink","paylinkButton":"Create paylink","paylinkDescription":"Create paylink for order","paylinkTitle":"Paylink","refundTitle":"Refund","transactionsTitle":"Transactions","amountTitle":"Amount","amountTotalTitle":"Grand total","amountRefundTotalTitle":"Refund Grand total","amountCustomRefundTitle":"Refund custom amount","buttonTitle":"Refund","successTitle":"Success","successMessage":"Buckaroo success refunded ","errorTitle":"Error","payTitle":"Capture payment","payDescription":"Capture and create invoice for order","payButton":"Capture payment"},"orderItems":{"title":"Items to Refund","types":{"id":"id","name":"Title","quantity":"Qty to Refund","totalAmount":"Subtotal"}},"transactionsToRefund":{"title":"Refund Totals"},"transactionHistory":{"types":{"id":"id","created_at":"Date/time","total":"Total","shipping_costs":"Shipping costs","total_excluding_vat":"Total excluding VAT","total_including_vat":"Total including VAT","vat":"VAT","transaction_key":"Transaction key","transaction_method":"Payment method","statuscode":"Status"}},"messageNotValid":"This field not valid.","messageNotBlank":"This field must not be empty.","button":{"labelTestApi":"Test connection"},"afterpay":{"setup":"Setup tax association for Riverty | AfterPay old ","hightTaxes":"High VAT taxes","middleTaxes":"Middle VAT taxes","lowTaxes":"Low VAT taxes","zeroTaxes":"Zero VAT","noTaxes":"No VAT tax"},"paymentInTestMode":"The payment for this order was made in test mode","refund":{"not_supported":"Refund is not supported","already_refunded":"This order is already refunded","refunded_amount":"Buckaroo success refunded"},"capture":{"invalid_amount":"Amount is not valid","capture_not_supported":"Capture is not supported","already_captured":"This order is already captured","captured_amount":"Successfully captured amount","general_capture_error":"Unfortunately an error occurred while processing your capture. Please try again."},"test_api":{"connection_ready":"Connection ready","connection_failed":"Connection failed"},"paylink":{"invalid_amount":"Amount is not valid","pay_link":"Your Paylink:"},"missing_order_id":"Missing order orderId","missing_transaction":"Order transaction not found","general_request_error":"Unfortunately an error occurred while processing your request. Please try again.","in3LogoLabel":"Payment Logo:"}}')},GLub:function(e,t){Shopware.Component.override("sw-context-menu-item",{mounted:function(){"BuckarooPayments"==this.routerLink.params.namespace&&(this.routerLink={name:"buckaroo.payment.index"})}})},LgLT:function(e){e.exports=JSON.parse('{"buckaroo-payment":{"fee":"Buckaroo Vergoeding","order":{"refundDescription":"Terugbetaling voor bestelling #orderNumber"},"general":{"title":"Buckaroo","description":"Buckaroo Payment"},"settingsForm":{"save":"Opslaan","titleSuccess":"Succes","titleError":"Fout"},"supportModal":{"menuButton":"Ondersteuning van de versie","title":"Ondersteuning van de versie","support":{"description":"Voordat u contact opneemt met Buckaroo technische ondersteuning, kunt u uw (Merchant) sleutel, geheime sleutel, certificaat en certificaat duimafdruk ophalen.","label1":"Buckaroo Payment Plaza:","label2":"Telefoon:","label3":"E-mail:","label4":"Website:","your_version":"Uw PHP versie:","version":"Verenigbaarheid van versie","information":"Informatie"}},"tabs":{"title":"Buckaroo Payment","overview":"Overzicht"},"paymentDetail":{"refundTitle":"Refund","transactionsTitle":"Transacties","amountTitle":"Bedrag","amountTotalTitle":"Algemeen totaal","amountRefundTotalTitle":"Eindtotaal totaal","amountCustomRefundTitle":"Aangepast bedrag terugbetalen","buttonTitle":"Restitutie","successTitle":"Succes","successMessage":"Buckaroo-succes terugbetaald ","errorTitle":"Fout","payTitle":"Capture betaling","payDescription":"Capture en maak factuur voor order","payButton":"Capture betaling"},"orderItems":{"title":"Te restitueren items","types":{"id":"id","name":"Titel","quantity":"Aantal terugbetalen","totalAmount":"Subtotaal"}},"transactionsToRefund":{"title":"Totalen terugbetalen"},"transactionHistory":{"types":{"id":"id","created_at":"Datum / tijd","total":"Total","shipping_costs":"Verzendkosten","total_excluding_vat":"Totaal exclusief VAT","total_including_vat":"Totaal inclusief VAT","vat":"VAT","transaction_key":"Transactiesleutel","transaction_method":"Betaalmethode","statuscode":"Toestand"}},"messageNotValid":"Dit veld is niet geldig.","messageNotBlank":"Dit veld mag niet leeg zijn.","button":{"labelTestApi":"Test verbinding"},"paymentInTestMode":"The payment for this order was made in test mode","refund":{"not_supported":"Refund is not supported","already_refunded":"This order is already refunded","refunded_amount":"Buckaroo success refunded"},"capture":{"invalid_amount":"Amount is not valid","capture_not_supported":"Capture is not supported","already_captured":"This order is already captured","captured_amount":"Successfully captured amount","general_capture_error":"Unfortunately an error occurred while processing your capture. Please try again."},"test_api":{"connection_ready":"Connection ready","connection_failed":"Connection failed"},"paylink":{"invalid_amount":"Amount is not valid","pay_link":"Your Paylink:"},"missing_order_id":"Missing order orderId","missing_transaction":"Order transaction not found","general_request_error":"Unfortunately an error occurred while processing your request. Please try again.","in3LogoLabel":"Payment Logo:"}}')},P8hj:function(e,t,n){"use strict";function a(e,t){for(var n=[],a={},o=0;on.parts.length&&(a.parts.length=n.parts.length)}else{var i=[];for(o=0;o2&&void 0!==arguments[2]?arguments[2]:"buckaroo";return a(this,l),c.call(this,e,t,n)}return t=l,(n=[{key:"getSupportVersion",value:function(){var e="_action/".concat(this.getApiBasePath(),"/version");return this.httpClient.post(e,{},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"getTaxes",value:function(){var e="_action/".concat(this.getApiBasePath(),"/taxes");return this.httpClient.post(e,{},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"getIn3Icons",value:function(){var e="_action/".concat(this.getApiBasePath(),"/in3/logos");return this.httpClient.post(e,{},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"getApiTest",value:function(e,t,n){var a="_action/".concat(this.getApiBasePath(),"/getBuckarooApiTest");return this.httpClient.post(a,{websiteKeyId:e,secretKeyId:t,saleChannelId:n},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}}])&&o(t.prototype,n),s&&o(t,s),Object.defineProperty(t,"prototype",{writable:!1}),l}(u);l.addServiceProvider("BuckarooPaymentSettingsService",(function(e){var t=l.getContainer("init");return new d(t.httpClient,e.loginService)}))},as8o:function(e,t,n){},"jA+u":function(e,t,n){},rWDw:function(e,t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:"buckaroo";return a(this,l),c.call(this,e,t,n)}return t=l,(n=[{key:"getBuckarooTransaction",value:function(e){var t="_action/".concat(this.getApiBasePath(),"/getBuckarooTransaction");return this.httpClient.post(t,{transaction:e},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"refundPayment",value:function(e,t,n,a){var o="_action/".concat(this.getApiBasePath(),"/refund");return this.httpClient.post(o,{transaction:e,transactionsToRefund:t,orderItems:n,customRefundAmount:a},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"captureOrder",value:function(e){var t="_action/".concat(this.getApiBasePath(),"/capture");return this.httpClient.post(t,{transaction:e},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"createPaylink",value:function(e){var t="_action/".concat(this.getApiBasePath(),"/paylink");return this.httpClient.post(t,{transaction:e},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}}])&&o(t.prototype,n),s&&o(t,s),Object.defineProperty(t,"prototype",{writable:!1}),l}(u);l.addServiceProvider("BuckarooPaymentService",(function(e){var t=l.getContainer("init");return new d(t.httpClient,e.loginService)}))},tfhk:function(e,t,n){var a=n("as8o");a.__esModule&&(a=a.default),"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);(0,n("P8hj").default)("4859312a",a,!0,{})},unXS:function(e,t,n){"use strict";n.r(t);n("V1U6");var a=Shopware,o=a.Component,r=a.Mixin;o.register("buckaroo-settings",{template:'{% block buckaroo_payment %}\n\n {% block buckaroo_payment_header %}\n \n {% endblock %}\n\n {% block buckaroo_payment_actions %}\n \n {% endblock %}\n\n {% block buckaroo_payment_settings_content %}\n \n {% endblock %}\n\n{% endblock %}\n',mixins:[r.getByName("notification"),r.getByName("sw-inline-snippet")],inject:["BuckarooPaymentSettingsService"],data:function(){return{isLoading:!1,isSaveSuccessful:!1,config:{},websiteKeyIdFilled:!1,secretKeyIdFilled:!1,showValidationErrors:!1,phpversion:!1,supportMessage:!1,isSupportModalOpen:!1,isSupportMessageModalOpen:!1,isPhpVersionSupport:!1,collapsibleState:{websiteKey:!0,secretKey:!0,guid:!0,transactionLabel:!0,refundLabel:!0,creditcardEnabled:!0,creditcardsEnabled:!0,idealEnabled:!0,idealqrEnabled:!0,idealprocessingEnabled:!0,belfiusEnabled:!0,bancontactmrcashEnabled:!0,afterpayEnabled:!0,BillinkEnabled:!0,sofortueberweisungEnabled:!0,paypalEnabled:!0,transferEnabled:!0,giropayEnabled:!0,KBCPaymentButtonEnabled:!0,sepadirectdebitEnabled:!0,payconiqEnabled:!0,applepayEnabled:!0,giftcardsEnabled:!0,capayableEnabled:!0,epsEnabled:!0,Przelewy24Enabled:!0,AlipayEnabled:!0,WeChatPayEnabled:!0,TrustlyEnabled:!0,klarnaEnabled:!0,klarnainEnabled:!0,klarnakpEnabled:!0,advancedConfiguration:!0,BillinkCreateInvoiceAfterShipment:!0,payperemailEnabled:!0,paybybankEnabled:!0},collapsibleAdvancedState:{paylinkEnabled:!0,sendInvoiceEmail:!0,paymentSuccesStatus:!0,orderStatus:!0}}},created:function(){var e=this;this.createdComponent(),this.BuckarooPaymentSettingsService.getSupportVersion().then((function(t){e.phpversion=t.phpversion,e.isPhpVersionSupport=t.isPhpVersionSupport}))},computed:{credentialsMissing:function(){return!this.websiteKeyIdFilled||!this.secretKeyIdFilled}},metaInfo:function(){return{title:this.$createTitle()}},methods:{sendTestApi:function(){var e=this,t=this,n=this.getConfigValue("websiteKey"),a=this.getConfigValue("secretKey"),o=this.$refs.systemConfig.currentSalesChannelId;this.BuckarooPaymentSettingsService.getApiTest(n,a,o).then((function(n){"success"==n.status?e.createNotificationSuccess({title:t.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:t.$tc(n.message)}):e.createNotificationError({title:t.$tc("buckaroo-payment.settingsForm.titleError"),message:t.$tc(n.message)})}))},getCardConfig:function(e,t){return t.elements.forEach((function(t){if(t.name==e.name)return t.config})),!1},showLabel:function(e,t){return"single-select"==e.type||"multi-select"==e.type},showHelpText:function(e,t){return!(!this.showLabel(e,t)||!this.getCardInfo(e,t,"helpText"))},showButtonAfter:function(e,t){var n="advancedConfiguration";return null!=t["BuckarooPayments.config.advancedConfiguration"]&&t["BuckarooPayments.config.advancedConfiguration"]&&(n="orderStatus"),!!e.name.includes(n)},getLocale:function(e){var t=window.localStorage.getItem("sw-admin-locale");return null==t&&(t="en-GB"),null!=e[t]?e[t]:e["en-GB"]},getCardInfo:function(e,t,n){var a=this,o="";return t.elements.forEach((function(t){if(t.name==e.name&&null!=t.config)switch(n){case"label":o=null!=t.config.label?a.getLocale(t.config.label):"";break;case"helpText":o=null!=t.config.helpText?a.getLocale(t.config.helpText):""}})),o},createdComponent:function(){},saveFinish:function(){this.isSaveSuccessful=!1},onConfigChange:function(e){this.config=e,this.checkCredentialsFilled(),this.showValidationErrors=!1},checkCredentialsFilled:function(){this.websiteKeyIdFilled=!!this.getConfigValue("websiteKey"),this.secretKeyIdFilled=!!this.getConfigValue("secretKey")},validateWebsiteKey:function(){return!(this.getConfigValue("websiteKey").length<10||this.getConfigValue("websiteKey").length>10)},validateSecretKey:function(){return!(this.getConfigValue("secretKey").length<5||this.getConfigValue("secretKey").length>50)},getConfigValue:function(e){var t=this.$refs.systemConfig.actualConfigData.null;return null===this.$refs.systemConfig.currentSalesChannelId?this.config["BuckarooPayments.config.".concat(e)]:this.config["BuckarooPayments.config.".concat(e)]||t["BuckarooPayments.config.".concat(e)]},getPaymentConfigValue:function(e,t){var n=e.charAt(0).toUpperCase()+e.slice(1);return this.getConfigValue(t+n)||this.getConfigValue(e)},onSave:function(){var e=this;this.credentialsMissing?this.showValidationErrors=!0:this.validateWebsiteKey()&&this.validateSecretKey()?(this.isSaveSuccessful=!1,this.isLoading=!0,this.$refs.systemConfig.saveAll().then((function(){e.isLoading=!1,e.isSaveSuccessful=!0})).catch((function(){e.isLoading=!1}))):this.showValidationErrors=!0},displayField:function(e,t){var n=e.name.replace("BuckarooPayments.config.","");if(n in this.collapsibleState)return!0;if(n in this.collapsibleAdvancedState&&null!=t["BuckarooPayments.config.advancedConfiguration"]&&t["BuckarooPayments.config.advancedConfiguration"])return!0;var a=n;return(n=n.split(/([A-Z][a-z]+)/).filter((function(e){return e}))).pop(),n=n.join(""),"capayableLogo"===a?void 0===t["BuckarooPayments.config.capayableVersion"]||"v3"===t["BuckarooPayments.config.capayableVersion"]:!(null==t["BuckarooPayments.config."+n+"Enabled"]||!t["BuckarooPayments.config."+n+"Enabled"])||(!("allowedcreditcard"!=a||null==t["BuckarooPayments.config.creditcardEnabled"]||!t["BuckarooPayments.config.creditcardEnabled"])||(!("allowedcreditcards"!=a||null==t["BuckarooPayments.config.creditcardsEnabled"]||!t["BuckarooPayments.config.creditcardsEnabled"])||(!("allowedgiftcards"!=a||null==t["BuckarooPayments.config.giftcardsEnabled"]||!t["BuckarooPayments.config.giftcardsEnabled"])||(!("applepayShowProduct"!=a&&"applepayShowCart"!=a||null==t["BuckarooPayments.config.applepayEnabled"]||!t["BuckarooPayments.config.applepayEnabled"])||(!("idealRenderMode"!=a||null==t["BuckarooPayments.config.idealRenderMode"]||!t["BuckarooPayments.config.idealEnabled"])||(!("transferSendEmail"!=a&&"transferDateDue"!=a||null==t["BuckarooPayments.config.transferEnabled"]||!t["BuckarooPayments.config.transferEnabled"])||(!("afterpayCustomerType"!=a||null==t["BuckarooPayments.config.afterpayEnabled"]||!t["BuckarooPayments.config.afterpayEnabled"])||!("afterpayB2bMinAmount"!=a&&"afterpayB2bMaxAmount"!=a||!t["BuckarooPayments.config.afterpayEnabled"]||null==t["BuckarooPayments.config.afterpayCustomerType"]||"b2c"==t["BuckarooPayments.config.afterpayCustomerType"]))))))))},getBind:function(e,t){return t!==this.config&&this.onConfigChange(t),this.showValidationErrors&&("BuckarooPayments.config.websiteKey"!==e.name||this.websiteKeyIdFilled||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotBlank")}),"BuckarooPayments.config.secretKey"!==e.name||this.secretKeyIdFilled||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotBlank")}),"BuckarooPayments.config.websiteKey"!==e.name||this.validateWebsiteKey()||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotValid")}),"BuckarooPayments.config.secretKey"!==e.name||this.validateSecretKey()||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotValid")})),e}}});var i=Shopware,s=i.Component,c=i.Context,l=Shopware.Data.Criteria;s.override("sw-order-detail",{template:'{% block sw_order_detail_content_tabs %}\n \n
\n

{{ $tc(\'buckaroo-payment.paymentInTestMode\') }}

\n \n {% parent %}\n{% endblock %}\n\n\n{% block sw_order_detail_content_tabs_general %}\n {% parent %}\n\n \n {{ $tc(\'buckaroo-payment.tabs.title\') }}\n \n \n{% endblock %}\n\n{% block sw_order_detail_actions %}\n \n {% parent %}\n{% endblock %}',data:function(){return{isBuckarooPayment:!1,isPaymentInTestMode:!1}},computed:{isEditable:function(){return!this.isBuckarooPayment||"buckaroo.payment.detail"!==this.$route.name},showTabs:function(){return!0}},watch:{orderId:{deep:!0,handler:function(){var e=this;if(this.orderId){var t=this.repositoryFactory.create("order"),n=new l(1,1);n.addAssociation("transactions"),t.get(this.orderId,c.api,n).then((function(t){if(e.setPaymentInTestMode(t),t.transactions.length<=0||!t.transactions.last().paymentMethodId)e.setIsBuckarooPayment(null);else{var n=t.transactions.last().paymentMethodId;null!=n&&e.setIsBuckarooPayment(n)}}))}else this.setIsBuckarooPayment(null)},immediate:!0}},methods:{setPaymentInTestMode:function(e){e.customFields&&e.customFields.buckaroo_payment_in_test_mode&&(this.isPaymentInTestMode=!0===e.customFields.buckaroo_payment_in_test_mode)},setIsBuckarooPayment:function(e){var t=this;e&&this.repositoryFactory.create("payment_method").get(e,c.api).then((function(e){t.isBuckarooPayment=e.formattedHandlerIdentifier.indexOf("buckaroo")>=0}))}}});n("6Dsi");Shopware.Component.override("sw-settings-index",{template:'{% block sw_settings_content_card_slot_plugins %}\n {% parent %}\n\n \n \n \n{% endblock %}\n'});var u=Shopware,d=u.Component;u.Context,Shopware.Data.Criteria;d.override("sw-order-detail-base",{template:'{% block sw_order_detail_base_line_items_summary %}\n\n \n \n \n
{{ $tc(\'buckaroo-payment.fee\') }}
\n
{{ order.customFields.buckarooFee }}\n {% if order.currency.isoCode == "PLN" %}\n PLN\n {% else %}\n {{ order.currency.symbol }}\n {% endif %}\n
\n
\n
\n
\n\n {% parent %}\n \n{% endblock %}'});Shopware.Component.override("sw-order-user-card",{template:"{% block sw_order_detail_base_secondary_info_payment %}\n \n \n{% endblock %}\n\n",inject:["systemConfigApiService"],data:function(){return{config:{}}},created:function(){var e=this;this.systemConfigApiService.getValues("BuckarooPayments.config",null).then((function(t){e.config=t})).finally((function(){}))}});n("GLub"),n("tfhk");var p=Shopware,m=p.Component,f=p.Mixin,y=(p.Filter,p.Context),h=Shopware.Data.Criteria;m.register("buckaroo-payment-detail",{template:'{% block buckaroo_payment_detail %}\n
\n \n \n\n {{ $tc(\'buckaroo-payment.paymentDetail.paylinkDescription\') }}\n \n
\n {{ $tc(\'buckaroo-payment.paymentDetail.yourLink\') }}: {{ paylink }}\n
\n\n \n
\n \n \n {{ $tc(\'buckaroo-payment.paymentDetail.paylinkButton\') }}\n
\n
\n
\n\n
\n\n \n \n {{ $tc(\'buckaroo-payment.orderItems.title\') }}\n \n\n \n\n \n\n \n \n
{{ $tc(\'buckaroo-payment.paymentDetail.amountTotalTitle\') }}:
\n
{{ buckaroo_refund_amount }} {{ currency }}
\n
\n
\n \n \n \n \n
\n
{{ $tc(\'buckaroo-payment.transactionsToRefund.title\') }}
\n
\n
\n\n \n\n \n\n \n\n \n\n \n \n
{{ $tc(\'buckaroo-payment.paymentDetail.amountCustomRefundTitle\') }}:
\n
\n \n {{ currency }}\n
\n
\n \n
{{ $tc(\'buckaroo-payment.paymentDetail.amountRefundTotalTitle\') }}:
\n
{{ buckaroo_refund_total_amount }} {{ currency }}
\n
\n
\n \n
\n\n \n
\n \n {{ $tc(\'buckaroo-payment.paymentDetail.buttonTitle\') }}\n
\n
\n
\n\n
\n\n \n\n {{ $tc(\'buckaroo-payment.paymentDetail.payDescription\') }}\n\n \n
\n \n {{ $tc(\'buckaroo-payment.paymentDetail.payButton\') }}\n
\n
\n
\n\n
\n\n \n \n\n \n\n \n \n\n\n \n \n
\n{% endblock %}',inject:["repositoryFactory","BuckarooPaymentService","systemConfigApiService"],mixins:[f.getByName("notification")],data:function(){return{config:{},buckaroo_refund_amount:"0",buckaroo_refund_total_amount:"0",currency:"EUR",isRefundPossible:!0,isCapturePossible:!1,isPaylinkAvailable:!1,isPaylinkVisible:!1,paylinkMessage:"",paylink:"",isLoading:!1,order:!1,buckarooFee:!1,buckarooTransactions:null,orderItems:[],transactionsToRefund:[],relatedResources:[],isAllowedCustomRefund:!0}},computed:{orderItemsColumns:function(){return[{property:"name",label:this.$tc("buckaroo-payment.orderItems.types.name"),rawData:!0},{property:"quantity",label:this.$tc("buckaroo-payment.orderItems.types.quantity"),rawData:!0},{property:"totalAmount",label:this.$tc("buckaroo-payment.orderItems.types.totalAmount"),rawData:!0}]},transactionsToRefundColumns:function(){return[{property:"transaction_method",rawData:!0},{property:"amount",rawData:!0}]},relatedResourceColumns:function(){return[{property:"created_at",label:this.$tc("buckaroo-payment.transactionHistory.types.created_at"),rawData:!0},{property:"total",label:this.$tc("buckaroo-payment.transactionHistory.types.total"),rawData:!0},{property:"shipping_costs",label:this.$tc("buckaroo-payment.transactionHistory.types.shipping_costs"),rawData:!0},{property:"total_excluding_vat",label:this.$tc("buckaroo-payment.transactionHistory.types.total_excluding_vat"),rawData:!0},{property:"vat",label:this.$tc("buckaroo-payment.transactionHistory.types.vat"),rawData:!0},{property:"transaction_key",label:this.$tc("buckaroo-payment.transactionHistory.types.transaction_key"),rawData:!0},{property:"transaction_method",label:this.$tc("buckaroo-payment.transactionHistory.types.transaction_method"),rawData:!0},{property:"statuscode",label:this.$tc("buckaroo-payment.transactionHistory.types.statuscode"),rawData:!0}]}},created:function(){this.createdComponent()},methods:{recalculateOrderItems:function(){for(var e in this.buckaroo_refund_amount=0,this.orderItems)this.orderItems[e].totalAmount=parseFloat(parseFloat(this.orderItems[e].unitPrice)*parseFloat(this.orderItems[e].quantity||0)).toFixed(2),this.buckaroo_refund_amount=parseFloat(parseFloat(this.buckaroo_refund_amount)+parseFloat(this.orderItems[e].totalAmount)).toFixed(2)},recalculateRefundItems:function(){for(var e in this.buckaroo_refund_total_amount=0,this.transactionsToRefund)this.transactionsToRefund[e].amount&&(this.buckaroo_refund_total_amount=parseFloat(parseFloat(this.buckaroo_refund_total_amount)+parseFloat(this.transactionsToRefund[e].amount)).toFixed(2))},getCustomRefundEnabledEl:function(){return document.getElementById("buckaroo_custom_refund_enabled")},getCustomRefundAmountEl:function(){return document.getElementById("buckaroo_custom_refund_amount")},toggleCustomRefund:function(){this.getCustomRefundEnabledEl()&&this.getCustomRefundAmountEl()&&(this.getCustomRefundAmountEl().disabled=!this.getCustomRefundEnabledEl().checked)},getCustomRefundAmount:function(){return this.getCustomRefundEnabledEl()&&this.getCustomRefundAmountEl()&&this.getCustomRefundEnabledEl().checked?this.getCustomRefundAmountEl().value:0},createdComponent:function(){var e=this,t=this,n=this.$route.params.id;this.systemConfigApiService.getValues("BuckarooPayments.config",null).then((function(t){e.config=t}));var a=this.repositoryFactory.create("order"),o=new h(1,1);this.orderId=n,o.addAssociation("transactions.paymentMethod").addAssociation("transactions"),o.getAssociation("transactions").addSorting(h.sort("createdAt")),a.get(n,y.api,o).then((function(n){null!=n.customFields&&null!=n.customFields.buckarooFee&&(e.buckarooFee=n.customFields.buckarooFee),t.isCapturePossible=n.transactions&&n.transactions.last().paymentMethod&&n.transactions.last().paymentMethod.customFields&&n.transactions.last().paymentMethod.customFields.buckaroo_key&&["klarnakp","billink"].includes(n.transactions.last().paymentMethod.customFields.buckaroo_key.toLowerCase()),t.isPaylinkVisible=t.isPaylinkAvailable=e.getConfigValue("paylinkEnabled")&&n.stateMachineState&&n.stateMachineState.technicalName&&"open"==n.stateMachineState.technicalName&&n.transactions&&"open"==n.transactions.last().stateMachineState.technicalName})),this.BuckarooPaymentService.getBuckarooTransaction(n).then((function(n){e.$emit("loading-change",!1),n.orderItems.forEach((function(e){t.orderItems.push({id:e.id,name:e.name,quantity:e.quantity,quantityMax:e.quantity,unitPrice:e.unitPrice.value,totalAmount:e.totalAmount.value})})),t.recalculateOrderItems(),n.transactionsToRefund.forEach((function(e){["afterpay","Billink","klarnakp"].includes(e.transaction_method)&&(t.isAllowedCustomRefund=!1),t.transactionsToRefund.push({id:e.id,transactions:e.transactions,amount:e.total,amountMax:e.total,currency:e.currency,transaction_method:e.transaction_method,logo:e.transaction_method?e.logo:null}),t.currency=e.currency})),t.recalculateRefundItems(),n.transactions.forEach((function(e){t.relatedResources.push({id:e.id,transaction_key:e.transaction,total:e.total,total_excluding_vat:e.total_excluding_vat,shipping_costs:e.shipping_costs,vat:e.vat,transaction_method:e.transaction_method,logo:e.transaction_method?e.logo:null,created_at:e.created_at,statuscode:e.statuscode})}))})).catch((function(e){console.log("errorResponse",e)}))},refundOrder:function(e,t){var n=this,a=this;a.isRefundPossible=!1,this.BuckarooPaymentService.refundPayment(e,this.transactionsToRefund,this.orderItems,this.getCustomRefundAmount()).then((function(e){for(var t in e)e[t].status?n.createNotificationSuccess({title:a.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:a.$tc(e[t].message)+e[t].amount}):n.createNotificationError({title:a.$tc("buckaroo-payment.settingsForm.titleError"),message:a.$tc(e[t].message)});a.isRefundPossible=!0})).catch((function(e){n.createNotificationError({title:n.$tc("buckaroo-payment.settingsForm.titleError"),message:e.response.data.message}),a.isRefundPossible=!0}))},createPaylink:function(e){var t=this,n=this;n.isPaylinkAvailable=!1,this.BuckarooPaymentService.createPaylink(e,this.transactionsToRefund,this.orderItems).then((function(e){e.status?(n.paylinkMessage=n.$tc(e.message)+e.paylinkhref,n.paylink=e.paylink,t.createNotificationSuccess({title:n.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:n.paylinkMessage})):t.createNotificationError({title:n.$tc("buckaroo-payment.settingsForm.titleError"),message:n.$tc(e.message)}),n.isPaylinkAvailable=!0})).catch((function(e){t.createNotificationError({title:t.$tc("buckaroo-payment.settingsForm.titleError"),message:e.response.data.message}),n.isPaylinkAvailable=!0}))},getConfigValue:function(e){return this.config["BuckarooPayments.config.".concat(e)]},captureOrder:function(e){var t=this,n=this;n.isCapturePossible=!1,this.BuckarooPaymentService.captureOrder(e,this.transactionsToRefund,this.orderItems).then((function(e){e.status?t.createNotificationSuccess({title:n.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:n.$tc(e.message)+e.amount}):t.createNotificationError({title:n.$tc("buckaroo-payment.settingsForm.titleError"),message:n.$tc(e.message)}),n.isCapturePossible=!0})).catch((function(e){t.createNotificationError({title:t.$tc("buckaroo-payment.settingsForm.titleError"),message:n.$tc(e.response.data.message)}),n.isCapturePossible=!0}))}}});var g=n("LgLT"),b=n("VI1O"),v=n("C41O");Shopware.Module.register("buckaroo-payment",{type:"plugin",name:"BuckarooPayment",title:"buckaroo.general.title",description:"buckaroo.general.description",version:"1.0.0",targetVersion:"1.0.0",color:"#000000",icon:"default-action-settings",snippets:{"nl-NL":g,"de-DE":b,"en-GB":v},routeMiddleware:function(e,t){"sw.order.detail"===t.name&&t.children.push({component:"buckaroo-payment-detail",name:"buckaroo.payment.detail",isChildren:!0,path:"/sw/order/buckaroo/detail/:id"}),e(t)},routes:{index:{component:"buckaroo-settings",path:"index",meta:{parentPath:"sw.settings.index"}}}});n("rWDw"),n("WCCb");function k(e){return(k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function w(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function _(e){for(var t=1;t\n {{$tc(\'buckaroo-payment.afterpay.setup\')}}\n
\n
\n \n
\n
\n',inject:["BuckarooPaymentSettingsService"],data:function(){return{taxes:[],showTaxes:!1,afterpayTaxes:[{name:this.$tc("buckaroo-payment.afterpay.hightTaxes"),id:1},{name:this.$tc("buckaroo-payment.afterpay.middleTaxes"),id:5},{name:this.$tc("buckaroo-payment.afterpay.lowTaxes"),id:2},{name:this.$tc("buckaroo-payment.afterpay.zeroTaxes"),id:3},{name:this.$tc("buckaroo-payment.afterpay.noTaxes"),id:4}],taxAssociation:{}}},model:{prop:"value",event:"change"},computed:{},props:{name:{type:String,required:!0,default:""},value:{type:Object,required:!1,default:function(){return{}}}},created:function(){var e=this;this.BuckarooPaymentSettingsService.getTaxes().then((function(t){e.taxes=t.taxes.map((function(e){return{id:e.id,name:e.name}}))}))},methods:{setTaxAssociation:function(e,t){this.taxAssociation[e]=t,this.$emit("change",_(_({},this.value),this.taxAssociation))},getSelectValue:function(e){if(this.value[e])return this.value[e]}}});n("QdNZ");Shopware.Component.register("buckaroo-in3-logo",{template:'
\n {{$tc(\'buckaroo-payment.in3LogoLabel\')}}\n
\n \n
\n
',inject:["BuckarooPaymentSettingsService"],data:function(){return{logos:[],selectedLogo:null}},model:{prop:"value",event:"change"},props:{name:{type:String,required:!0,default:""},value:{type:String,required:!1,default:function(){return null}}},watch:{selectedLogo:function(e){this.$emit("change",e)}},created:function(){var e=this;this.BuckarooPaymentSettingsService.getIn3Icons().then((function(t){e.setInitialValue(),e.logos=t.logos}))},methods:{setInitialValue:function(){this.value?this.selectedLogo=this.value:(this.selectedLogo="default_payment_icon",this.$emit("change",this.selectedLogo))}}})}}); \ No newline at end of file +!function(e){var t={};function n(a){if(t[a])return t[a].exports;var o=t[a]={i:a,l:!1,exports:{}};return e[a].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(a,o,function(t){return e[t]}.bind(null,o));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=(window.__sw__.assetPath + '/bundles/buckaroopayments/'),n(n.s="unXS")}({"5leu":function(e,t,n){},"6Dsi":function(e,t,n){var a=n("jA+u");a.__esModule&&(a=a.default),"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);(0,n("P8hj").default)("21e3d453",a,!0,{})},"8kDq":function(e,t,n){},C41O:function(e){e.exports=JSON.parse('{"buckaroo-payment":{"fee":"Buckaroo Fee","order":{"refundDescription":"Refund for order #orderNumber"},"general":{"title":"Buckaroo","description":"Buckaroo Payment"},"settingsForm":{"save":"Save","titleSuccess":"Success","titleError":"Error"},"supportModal":{"menuButton":"Version & Support","title":"Version & Support","support":{"description":"Before contacting Buckaroo technical support, please retrieve your (Merchant) key, Secret key, certificate and certificate thumbprint.","label1":"Buckaroo Payment Plaza:","label2":"Phone:","label3":"E-mail:","label4":"Website:","your_version":"Your PHP version:","version":"Version compatibility","information":"Information"}},"tabs":{"title":"Buckaroo Payment","overview":"Overview"},"paymentDetail":{"yourLink":"Your Paylink","paylinkButton":"Create paylink","paylinkDescription":"Create paylink for order","paylinkTitle":"Paylink","refundTitle":"Refund","transactionsTitle":"Transactions","amountTitle":"Amount","amountTotalTitle":"Grand total","amountRefundTotalTitle":"Refund Grand total","amountCustomRefundTitle":"Refund custom amount","buttonTitle":"Refund","successTitle":"Success","successMessage":"Buckaroo success refunded ","errorTitle":"Error","payTitle":"Capture payment","payDescription":"Capture and create invoice for order","payButton":"Capture payment"},"orderItems":{"title":"Items to Refund","types":{"id":"id","name":"Title","quantity":"Qty to Refund","totalAmount":"Subtotal"}},"transactionsToRefund":{"title":"Refund Totals"},"transactionHistory":{"types":{"id":"id","created_at":"Date/time","total":"Total","shipping_costs":"Shipping costs","total_excluding_vat":"Total excluding VAT","total_including_vat":"Total including VAT","vat":"VAT","transaction_key":"Transaction key","transaction_method":"Payment method","statuscode":"Status"}},"messageNotValid":"This field not valid.","messageNotBlank":"This field must not be empty.","button":{"labelTestApi":"Test connection"},"afterpay":{"setup":"Setup tax association for Riverty | AfterPay old ","hightTaxes":"High VAT taxes","middleTaxes":"Middle VAT taxes","lowTaxes":"Low VAT taxes","zeroTaxes":"Zero VAT","noTaxes":"No VAT tax"},"paymentInTestMode":"The payment for this order was made in test mode","capture":{"invalid_amount":"Amount is not valid","capture_not_supported":"Capture is not supported","already_captured":"This order is already captured","captured_amount":"Successfully captured amount","general_capture_error":"Unfortunately an error occurred while processing your capture. Please try again."},"test_api":{"connection_ready":"Connection ready","connection_failed":"Connection failed"},"paylink":{"invalid_amount":"Amount is not valid","pay_link":"Your Paylink:"},"missing_order_id":"Missing order orderId","missing_transaction":"Order transaction not found","general_request_error":"Unfortunately an error occurred while processing your request. Please try again.","in3LogoLabel":"Payment Logo:"}}')},GLub:function(e,t){Shopware.Component.override("sw-context-menu-item",{mounted:function(){"BuckarooPayments"==this.routerLink.params.namespace&&(this.routerLink={name:"buckaroo.payment.index"})}})},LgLT:function(e){e.exports=JSON.parse('{"buckaroo-payment":{"fee":"Buckaroo Vergoeding","order":{"refundDescription":"Terugbetaling voor bestelling #orderNumber"},"general":{"title":"Buckaroo","description":"Buckaroo Payment"},"settingsForm":{"save":"Opslaan","titleSuccess":"Succes","titleError":"Fout"},"supportModal":{"menuButton":"Ondersteuning van de versie","title":"Ondersteuning van de versie","support":{"description":"Voordat u contact opneemt met Buckaroo technische ondersteuning, kunt u uw (Merchant) sleutel, geheime sleutel, certificaat en certificaat duimafdruk ophalen.","label1":"Buckaroo Payment Plaza:","label2":"Telefoon:","label3":"E-mail:","label4":"Website:","your_version":"Uw PHP versie:","version":"Verenigbaarheid van versie","information":"Informatie"}},"tabs":{"title":"Buckaroo Payment","overview":"Overzicht"},"paymentDetail":{"refundTitle":"Refund","transactionsTitle":"Transacties","amountTitle":"Bedrag","amountTotalTitle":"Algemeen totaal","amountRefundTotalTitle":"Eindtotaal totaal","amountCustomRefundTitle":"Aangepast bedrag terugbetalen","buttonTitle":"Restitutie","successTitle":"Succes","successMessage":"Buckaroo-succes terugbetaald ","errorTitle":"Fout","payTitle":"Capture betaling","payDescription":"Capture en maak factuur voor order","payButton":"Capture betaling"},"orderItems":{"title":"Te restitueren items","types":{"id":"id","name":"Titel","quantity":"Aantal terugbetalen","totalAmount":"Subtotaal"}},"transactionsToRefund":{"title":"Totalen terugbetalen"},"transactionHistory":{"types":{"id":"id","created_at":"Datum / tijd","total":"Total","shipping_costs":"Verzendkosten","total_excluding_vat":"Totaal exclusief VAT","total_including_vat":"Totaal inclusief VAT","vat":"VAT","transaction_key":"Transactiesleutel","transaction_method":"Betaalmethode","statuscode":"Toestand"}},"messageNotValid":"Dit veld is niet geldig.","messageNotBlank":"Dit veld mag niet leeg zijn.","button":{"labelTestApi":"Test verbinding"},"paymentInTestMode":"The payment for this order was made in test mode","capture":{"invalid_amount":"Amount is not valid","capture_not_supported":"Capture is not supported","already_captured":"This order is already captured","captured_amount":"Successfully captured amount","general_capture_error":"Unfortunately an error occurred while processing your capture. Please try again."},"test_api":{"connection_ready":"Connection ready","connection_failed":"Connection failed"},"paylink":{"invalid_amount":"Amount is not valid","pay_link":"Your Paylink:"},"missing_order_id":"Missing order orderId","missing_transaction":"Order transaction not found","general_request_error":"Unfortunately an error occurred while processing your request. Please try again.","in3LogoLabel":"Payment Logo:"}}')},P8hj:function(e,t,n){"use strict";function a(e,t){for(var n=[],a={},o=0;on.parts.length&&(a.parts.length=n.parts.length)}else{var i=[];for(o=0;o2&&void 0!==arguments[2]?arguments[2]:"buckaroo";return a(this,l),c.call(this,e,t,n)}return t=l,(n=[{key:"getSupportVersion",value:function(){var e="_action/".concat(this.getApiBasePath(),"/version");return this.httpClient.post(e,{},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"getTaxes",value:function(){var e="_action/".concat(this.getApiBasePath(),"/taxes");return this.httpClient.post(e,{},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"getIn3Icons",value:function(){var e="_action/".concat(this.getApiBasePath(),"/in3/logos");return this.httpClient.post(e,{},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"getApiTest",value:function(e,t,n){var a="_action/".concat(this.getApiBasePath(),"/getBuckarooApiTest");return this.httpClient.post(a,{websiteKeyId:e,secretKeyId:t,saleChannelId:n},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}}])&&o(t.prototype,n),s&&o(t,s),Object.defineProperty(t,"prototype",{writable:!1}),l}(u);l.addServiceProvider("BuckarooPaymentSettingsService",(function(e){var t=l.getContainer("init");return new d(t.httpClient,e.loginService)}))},as8o:function(e,t,n){},"jA+u":function(e,t,n){},rWDw:function(e,t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:"buckaroo";return a(this,l),c.call(this,e,t,n)}return t=l,(n=[{key:"getBuckarooTransaction",value:function(e){var t="_action/".concat(this.getApiBasePath(),"/getBuckarooTransaction");return this.httpClient.post(t,{transaction:e},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"refundPayment",value:function(e,t,n,a){var o="_action/".concat(this.getApiBasePath(),"/refund");return this.httpClient.post(o,{transaction:e,transactionsToRefund:t,orderItems:n,customRefundAmount:a},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"captureOrder",value:function(e){var t="_action/".concat(this.getApiBasePath(),"/capture");return this.httpClient.post(t,{transaction:e},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}},{key:"createPaylink",value:function(e){var t="_action/".concat(this.getApiBasePath(),"/paylink");return this.httpClient.post(t,{transaction:e},{headers:this.getBasicHeaders()}).then((function(e){return u.handleResponse(e)}))}}])&&o(t.prototype,n),s&&o(t,s),Object.defineProperty(t,"prototype",{writable:!1}),l}(u);l.addServiceProvider("BuckarooPaymentService",(function(e){var t=l.getContainer("init");return new d(t.httpClient,e.loginService)}))},tfhk:function(e,t,n){var a=n("as8o");a.__esModule&&(a=a.default),"string"==typeof a&&(a=[[e.i,a,""]]),a.locals&&(e.exports=a.locals);(0,n("P8hj").default)("4859312a",a,!0,{})},unXS:function(e,t,n){"use strict";n.r(t);n("V1U6");var a=Shopware,o=a.Component,r=a.Mixin;o.register("buckaroo-settings",{template:'{% block buckaroo_payment %}\n\n {% block buckaroo_payment_header %}\n \n {% endblock %}\n\n {% block buckaroo_payment_actions %}\n \n {% endblock %}\n\n {% block buckaroo_payment_settings_content %}\n \n {% endblock %}\n\n{% endblock %}\n',mixins:[r.getByName("notification"),r.getByName("sw-inline-snippet")],inject:["BuckarooPaymentSettingsService"],data:function(){return{isLoading:!1,isSaveSuccessful:!1,config:{},websiteKeyIdFilled:!1,secretKeyIdFilled:!1,showValidationErrors:!1,phpversion:!1,supportMessage:!1,isSupportModalOpen:!1,isSupportMessageModalOpen:!1,isPhpVersionSupport:!1,collapsibleState:{websiteKey:!0,secretKey:!0,guid:!0,transactionLabel:!0,refundLabel:!0,creditcardEnabled:!0,creditcardsEnabled:!0,idealEnabled:!0,idealqrEnabled:!0,idealprocessingEnabled:!0,belfiusEnabled:!0,bancontactmrcashEnabled:!0,afterpayEnabled:!0,BillinkEnabled:!0,sofortueberweisungEnabled:!0,paypalEnabled:!0,transferEnabled:!0,giropayEnabled:!0,KBCPaymentButtonEnabled:!0,sepadirectdebitEnabled:!0,payconiqEnabled:!0,applepayEnabled:!0,giftcardsEnabled:!0,capayableEnabled:!0,epsEnabled:!0,Przelewy24Enabled:!0,AlipayEnabled:!0,WeChatPayEnabled:!0,TrustlyEnabled:!0,klarnaEnabled:!0,klarnainEnabled:!0,klarnakpEnabled:!0,advancedConfiguration:!0,BillinkCreateInvoiceAfterShipment:!0,payperemailEnabled:!0,paybybankEnabled:!0},collapsibleAdvancedState:{paylinkEnabled:!0,sendInvoiceEmail:!0,paymentSuccesStatus:!0,orderStatus:!0}}},created:function(){var e=this;this.createdComponent(),this.BuckarooPaymentSettingsService.getSupportVersion().then((function(t){e.phpversion=t.phpversion,e.isPhpVersionSupport=t.isPhpVersionSupport}))},computed:{credentialsMissing:function(){return!this.websiteKeyIdFilled||!this.secretKeyIdFilled}},metaInfo:function(){return{title:this.$createTitle()}},methods:{sendTestApi:function(){var e=this,t=this,n=this.getConfigValue("websiteKey"),a=this.getConfigValue("secretKey"),o=this.$refs.systemConfig.currentSalesChannelId;this.BuckarooPaymentSettingsService.getApiTest(n,a,o).then((function(n){"success"==n.status?e.createNotificationSuccess({title:t.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:t.$tc(n.message)}):e.createNotificationError({title:t.$tc("buckaroo-payment.settingsForm.titleError"),message:t.$tc(n.message)})}))},getCardConfig:function(e,t){return t.elements.forEach((function(t){if(t.name==e.name)return t.config})),!1},showLabel:function(e,t){return"single-select"==e.type||"multi-select"==e.type},showHelpText:function(e,t){return!(!this.showLabel(e,t)||!this.getCardInfo(e,t,"helpText"))},showButtonAfter:function(e,t){var n="advancedConfiguration";return null!=t["BuckarooPayments.config.advancedConfiguration"]&&t["BuckarooPayments.config.advancedConfiguration"]&&(n="orderStatus"),!!e.name.includes(n)},getLocale:function(e){var t=window.localStorage.getItem("sw-admin-locale");return null==t&&(t="en-GB"),null!=e[t]?e[t]:e["en-GB"]},getCardInfo:function(e,t,n){var a=this,o="";return t.elements.forEach((function(t){if(t.name==e.name&&null!=t.config)switch(n){case"label":o=null!=t.config.label?a.getLocale(t.config.label):"";break;case"helpText":o=null!=t.config.helpText?a.getLocale(t.config.helpText):""}})),o},createdComponent:function(){},saveFinish:function(){this.isSaveSuccessful=!1},onConfigChange:function(e){this.config=e,this.checkCredentialsFilled(),this.showValidationErrors=!1},checkCredentialsFilled:function(){this.websiteKeyIdFilled=!!this.getConfigValue("websiteKey"),this.secretKeyIdFilled=!!this.getConfigValue("secretKey")},validateWebsiteKey:function(){return!(this.getConfigValue("websiteKey").length<10||this.getConfigValue("websiteKey").length>10)},validateSecretKey:function(){return!(this.getConfigValue("secretKey").length<5||this.getConfigValue("secretKey").length>50)},getConfigValue:function(e){var t=this.$refs.systemConfig.actualConfigData.null;return null===this.$refs.systemConfig.currentSalesChannelId?this.config["BuckarooPayments.config.".concat(e)]:this.config["BuckarooPayments.config.".concat(e)]||t["BuckarooPayments.config.".concat(e)]},getPaymentConfigValue:function(e,t){var n=e.charAt(0).toUpperCase()+e.slice(1);return this.getConfigValue(t+n)||this.getConfigValue(e)},onSave:function(){var e=this;this.credentialsMissing?this.showValidationErrors=!0:this.validateWebsiteKey()&&this.validateSecretKey()?(this.isSaveSuccessful=!1,this.isLoading=!0,this.$refs.systemConfig.saveAll().then((function(){e.isLoading=!1,e.isSaveSuccessful=!0})).catch((function(){e.isLoading=!1}))):this.showValidationErrors=!0},displayField:function(e,t){var n=e.name.replace("BuckarooPayments.config.","");if(n in this.collapsibleState)return!0;if(n in this.collapsibleAdvancedState&&null!=t["BuckarooPayments.config.advancedConfiguration"]&&t["BuckarooPayments.config.advancedConfiguration"])return!0;var a=n;return(n=n.split(/([A-Z][a-z]+)/).filter((function(e){return e}))).pop(),n=n.join(""),"capayableLogo"===a?void 0===t["BuckarooPayments.config.capayableVersion"]||"v3"===t["BuckarooPayments.config.capayableVersion"]:!(null==t["BuckarooPayments.config."+n+"Enabled"]||!t["BuckarooPayments.config."+n+"Enabled"])||(!("allowedcreditcard"!=a||null==t["BuckarooPayments.config.creditcardEnabled"]||!t["BuckarooPayments.config.creditcardEnabled"])||(!("allowedcreditcards"!=a||null==t["BuckarooPayments.config.creditcardsEnabled"]||!t["BuckarooPayments.config.creditcardsEnabled"])||(!("allowedgiftcards"!=a||null==t["BuckarooPayments.config.giftcardsEnabled"]||!t["BuckarooPayments.config.giftcardsEnabled"])||(!("applepayShowProduct"!=a&&"applepayShowCart"!=a||null==t["BuckarooPayments.config.applepayEnabled"]||!t["BuckarooPayments.config.applepayEnabled"])||(!("idealRenderMode"!=a||null==t["BuckarooPayments.config.idealRenderMode"]||!t["BuckarooPayments.config.idealEnabled"])||(!("transferSendEmail"!=a&&"transferDateDue"!=a||null==t["BuckarooPayments.config.transferEnabled"]||!t["BuckarooPayments.config.transferEnabled"])||(!("afterpayCustomerType"!=a||null==t["BuckarooPayments.config.afterpayEnabled"]||!t["BuckarooPayments.config.afterpayEnabled"])||!("afterpayB2bMinAmount"!=a&&"afterpayB2bMaxAmount"!=a||!t["BuckarooPayments.config.afterpayEnabled"]||null==t["BuckarooPayments.config.afterpayCustomerType"]||"b2c"==t["BuckarooPayments.config.afterpayCustomerType"]))))))))},getBind:function(e,t){return t!==this.config&&this.onConfigChange(t),this.showValidationErrors&&("BuckarooPayments.config.websiteKey"!==e.name||this.websiteKeyIdFilled||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotBlank")}),"BuckarooPayments.config.secretKey"!==e.name||this.secretKeyIdFilled||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotBlank")}),"BuckarooPayments.config.websiteKey"!==e.name||this.validateWebsiteKey()||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotValid")}),"BuckarooPayments.config.secretKey"!==e.name||this.validateSecretKey()||(e.config.error={code:1,detail:this.$tc("buckaroo-payment.messageNotValid")})),e}}});var i=Shopware,s=i.Component,c=i.Context,l=Shopware.Data.Criteria;s.override("sw-order-detail",{template:'{% block sw_order_detail_content_tabs %}\n \n
\n

{{ $tc(\'buckaroo-payment.paymentInTestMode\') }}

\n \n {% parent %}\n{% endblock %}\n\n\n{% block sw_order_detail_content_tabs_general %}\n {% parent %}\n\n \n {{ $tc(\'buckaroo-payment.tabs.title\') }}\n \n \n{% endblock %}\n\n{% block sw_order_detail_actions %}\n \n {% parent %}\n{% endblock %}',data:function(){return{isBuckarooPayment:!1,isPaymentInTestMode:!1}},computed:{isEditable:function(){return!this.isBuckarooPayment||"buckaroo.payment.detail"!==this.$route.name},showTabs:function(){return!0}},watch:{orderId:{deep:!0,handler:function(){var e=this;if(this.orderId){var t=this.repositoryFactory.create("order"),n=new l(1,1);n.addAssociation("transactions"),t.get(this.orderId,c.api,n).then((function(t){if(e.setPaymentInTestMode(t),t.transactions.length<=0||!t.transactions.last().paymentMethodId)e.setIsBuckarooPayment(null);else{var n=t.transactions.last().paymentMethodId;null!=n&&e.setIsBuckarooPayment(n)}}))}else this.setIsBuckarooPayment(null)},immediate:!0}},methods:{setPaymentInTestMode:function(e){e.customFields&&e.customFields.buckaroo_payment_in_test_mode&&(this.isPaymentInTestMode=!0===e.customFields.buckaroo_payment_in_test_mode)},setIsBuckarooPayment:function(e){var t=this;e&&this.repositoryFactory.create("payment_method").get(e,c.api).then((function(e){t.isBuckarooPayment=e.formattedHandlerIdentifier.indexOf("buckaroo")>=0}))}}});n("6Dsi");Shopware.Component.override("sw-settings-index",{template:'{% block sw_settings_content_card_slot_plugins %}\n {% parent %}\n\n \n \n \n{% endblock %}\n'});var u=Shopware,d=u.Component;u.Context,Shopware.Data.Criteria;d.override("sw-order-detail-base",{template:'{% block sw_order_detail_base_line_items_summary %}\n\n \n \n \n
{{ $tc(\'buckaroo-payment.fee\') }}
\n
{{ order.customFields.buckarooFee }}\n {% if order.currency.isoCode == "PLN" %}\n PLN\n {% else %}\n {{ order.currency.symbol }}\n {% endif %}\n
\n
\n
\n
\n\n {% parent %}\n \n{% endblock %}'});Shopware.Component.override("sw-order-user-card",{template:"{% block sw_order_detail_base_secondary_info_payment %}\n \n \n{% endblock %}\n\n",inject:["systemConfigApiService"],data:function(){return{config:{}}},created:function(){var e=this;this.systemConfigApiService.getValues("BuckarooPayments.config",null).then((function(t){e.config=t})).finally((function(){}))}});n("GLub"),n("tfhk");var p=Shopware,m=p.Component,f=p.Mixin,y=(p.Filter,p.Context),g=Shopware.Data.Criteria;m.register("buckaroo-payment-detail",{template:'{% block buckaroo_payment_detail %}\n
\n \n \n\n {{ $tc(\'buckaroo-payment.paymentDetail.paylinkDescription\') }}\n \n
\n {{ $tc(\'buckaroo-payment.paymentDetail.yourLink\') }}: {{ paylink }}\n
\n\n \n
\n \n \n {{ $tc(\'buckaroo-payment.paymentDetail.paylinkButton\') }}\n
\n
\n
\n\n
\n\n \n \n {{ $tc(\'buckaroo-payment.orderItems.title\') }}\n \n\n \n\n \n\n \n \n
{{ $tc(\'buckaroo-payment.paymentDetail.amountTotalTitle\') }}:
\n
{{ buckaroo_refund_amount }} {{ currency }}
\n
\n
\n \n \n \n \n
\n
{{ $tc(\'buckaroo-payment.transactionsToRefund.title\') }}
\n
\n
\n\n \n\n \n\n \n\n \n\n \n \n
{{ $tc(\'buckaroo-payment.paymentDetail.amountCustomRefundTitle\') }}:
\n
\n \n {{ currency }}\n
\n
\n \n
{{ $tc(\'buckaroo-payment.paymentDetail.amountRefundTotalTitle\') }}:
\n
{{ buckaroo_refund_total_amount }} {{ currency }}
\n
\n
\n \n
\n\n \n
\n \n {{ $tc(\'buckaroo-payment.paymentDetail.buttonTitle\') }}\n
\n
\n
\n\n
\n\n \n\n {{ $tc(\'buckaroo-payment.paymentDetail.payDescription\') }}\n\n \n
\n \n {{ $tc(\'buckaroo-payment.paymentDetail.payButton\') }}\n
\n
\n
\n\n
\n\n \n \n\n \n\n \n \n\n\n \n \n
\n{% endblock %}',inject:["repositoryFactory","BuckarooPaymentService","systemConfigApiService"],mixins:[f.getByName("notification")],data:function(){return{config:{},buckaroo_refund_amount:"0",buckaroo_refund_total_amount:"0",currency:"EUR",isRefundPossible:!0,isCapturePossible:!1,isPaylinkAvailable:!1,isPaylinkVisible:!1,paylinkMessage:"",paylink:"",isLoading:!1,order:!1,buckarooFee:!1,buckarooTransactions:null,orderItems:[],transactionsToRefund:[],relatedResources:[],isAllowedCustomRefund:!0}},computed:{orderItemsColumns:function(){return[{property:"name",label:this.$tc("buckaroo-payment.orderItems.types.name"),rawData:!0},{property:"quantity",label:this.$tc("buckaroo-payment.orderItems.types.quantity"),rawData:!0},{property:"totalAmount",label:this.$tc("buckaroo-payment.orderItems.types.totalAmount"),rawData:!0}]},transactionsToRefundColumns:function(){return[{property:"transaction_method",rawData:!0},{property:"amount",rawData:!0}]},relatedResourceColumns:function(){return[{property:"created_at",label:this.$tc("buckaroo-payment.transactionHistory.types.created_at"),rawData:!0},{property:"total",label:this.$tc("buckaroo-payment.transactionHistory.types.total"),rawData:!0},{property:"shipping_costs",label:this.$tc("buckaroo-payment.transactionHistory.types.shipping_costs"),rawData:!0},{property:"total_excluding_vat",label:this.$tc("buckaroo-payment.transactionHistory.types.total_excluding_vat"),rawData:!0},{property:"vat",label:this.$tc("buckaroo-payment.transactionHistory.types.vat"),rawData:!0},{property:"transaction_key",label:this.$tc("buckaroo-payment.transactionHistory.types.transaction_key"),rawData:!0},{property:"transaction_method",label:this.$tc("buckaroo-payment.transactionHistory.types.transaction_method"),rawData:!0},{property:"statuscode",label:this.$tc("buckaroo-payment.transactionHistory.types.statuscode"),rawData:!0}]}},created:function(){this.createdComponent()},methods:{recalculateOrderItems:function(){for(var e in this.buckaroo_refund_amount=0,this.orderItems)this.orderItems[e].totalAmount=parseFloat(parseFloat(this.orderItems[e].unitPrice)*parseFloat(this.orderItems[e].quantity||0)).toFixed(2),this.buckaroo_refund_amount=parseFloat(parseFloat(this.buckaroo_refund_amount)+parseFloat(this.orderItems[e].totalAmount)).toFixed(2)},recalculateRefundItems:function(){for(var e in this.buckaroo_refund_total_amount=0,this.transactionsToRefund)this.transactionsToRefund[e].amount&&(this.buckaroo_refund_total_amount=parseFloat(parseFloat(this.buckaroo_refund_total_amount)+parseFloat(this.transactionsToRefund[e].amount)).toFixed(2))},getCustomRefundEnabledEl:function(){return document.getElementById("buckaroo_custom_refund_enabled")},getCustomRefundAmountEl:function(){return document.getElementById("buckaroo_custom_refund_amount")},toggleCustomRefund:function(){this.getCustomRefundEnabledEl()&&this.getCustomRefundAmountEl()&&(this.getCustomRefundAmountEl().disabled=!this.getCustomRefundEnabledEl().checked)},getCustomRefundAmount:function(){return this.getCustomRefundEnabledEl()&&this.getCustomRefundAmountEl()&&this.getCustomRefundEnabledEl().checked?this.getCustomRefundAmountEl().value:0},createdComponent:function(){var e=this,t=this,n=this.$route.params.id;this.systemConfigApiService.getValues("BuckarooPayments.config",null).then((function(t){e.config=t}));var a=this.repositoryFactory.create("order"),o=new g(1,1);this.orderId=n,o.addAssociation("transactions.paymentMethod").addAssociation("transactions"),o.getAssociation("transactions").addSorting(g.sort("createdAt")),a.get(n,y.api,o).then((function(n){null!=n.customFields&&null!=n.customFields.buckarooFee&&(e.buckarooFee=n.customFields.buckarooFee),t.isCapturePossible=n.transactions&&n.transactions.last().paymentMethod&&n.transactions.last().paymentMethod.customFields&&n.transactions.last().paymentMethod.customFields.buckaroo_key&&["klarnakp","billink"].includes(n.transactions.last().paymentMethod.customFields.buckaroo_key.toLowerCase()),t.isPaylinkVisible=t.isPaylinkAvailable=e.getConfigValue("paylinkEnabled")&&n.stateMachineState&&n.stateMachineState.technicalName&&"open"==n.stateMachineState.technicalName&&n.transactions&&"open"==n.transactions.last().stateMachineState.technicalName})),this.BuckarooPaymentService.getBuckarooTransaction(n).then((function(n){e.$emit("loading-change",!1),n.orderItems.forEach((function(e){t.orderItems.push({id:e.id,name:e.name,quantity:e.quantity,quantityMax:e.quantity,unitPrice:e.unitPrice.value,totalAmount:e.totalAmount.value})})),t.recalculateOrderItems(),n.transactionsToRefund.forEach((function(e){["afterpay","Billink","klarnakp"].includes(e.transaction_method)&&(t.isAllowedCustomRefund=!1),t.transactionsToRefund.push({id:e.id,transactions:e.transactions,amount:e.total,amountMax:e.total,currency:e.currency,transaction_method:e.transaction_method,logo:e.transaction_method?e.logo:null}),t.currency=e.currency})),t.recalculateRefundItems(),n.transactions.forEach((function(e){t.relatedResources.push({id:e.id,transaction_key:e.transaction,total:e.total,total_excluding_vat:e.total_excluding_vat,shipping_costs:e.shipping_costs,vat:e.vat,transaction_method:e.transaction_method,logo:e.transaction_method?e.logo:null,created_at:e.created_at,statuscode:e.statuscode})}))})).catch((function(e){console.log("errorResponse",e)}))},refundOrder:function(e,t){var n=this,a=this;a.isRefundPossible=!1,this.BuckarooPaymentService.refundPayment(e,this.transactionsToRefund,this.orderItems,this.getCustomRefundAmount()).then((function(e){for(var t in e)e[t].status?n.createNotificationSuccess({title:a.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:e[t].message}):n.createNotificationError({title:a.$tc("buckaroo-payment.settingsForm.titleError"),message:e[t].message});a.isRefundPossible=!0})).catch((function(e){n.createNotificationError({title:n.$tc("buckaroo-payment.settingsForm.titleError"),message:e.response.data.message}),a.isRefundPossible=!0}))},createPaylink:function(e){var t=this,n=this;n.isPaylinkAvailable=!1,this.BuckarooPaymentService.createPaylink(e,this.transactionsToRefund,this.orderItems).then((function(e){e.status?(n.paylinkMessage=n.$tc(e.message)+e.paylinkhref,n.paylink=e.paylink,t.createNotificationSuccess({title:n.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:n.paylinkMessage})):t.createNotificationError({title:n.$tc("buckaroo-payment.settingsForm.titleError"),message:n.$tc(e.message)}),n.isPaylinkAvailable=!0})).catch((function(e){t.createNotificationError({title:t.$tc("buckaroo-payment.settingsForm.titleError"),message:e.response.data.message}),n.isPaylinkAvailable=!0}))},getConfigValue:function(e){return this.config["BuckarooPayments.config.".concat(e)]},captureOrder:function(e){var t=this,n=this;n.isCapturePossible=!1,this.BuckarooPaymentService.captureOrder(e,this.transactionsToRefund,this.orderItems).then((function(e){e.status?t.createNotificationSuccess({title:n.$tc("buckaroo-payment.settingsForm.titleSuccess"),message:n.$tc(e.message)+e.amount}):t.createNotificationError({title:n.$tc("buckaroo-payment.settingsForm.titleError"),message:n.$tc(e.message)}),n.isCapturePossible=!0})).catch((function(e){t.createNotificationError({title:t.$tc("buckaroo-payment.settingsForm.titleError"),message:n.$tc(e.response.data.message)}),n.isCapturePossible=!0}))}}});var h=n("LgLT"),b=n("VI1O"),v=n("C41O");Shopware.Module.register("buckaroo-payment",{type:"plugin",name:"BuckarooPayment",title:"buckaroo.general.title",description:"buckaroo.general.description",version:"1.0.0",targetVersion:"1.0.0",color:"#000000",icon:"default-action-settings",snippets:{"nl-NL":h,"de-DE":b,"en-GB":v},routeMiddleware:function(e,t){"sw.order.detail"===t.name&&t.children.push({component:"buckaroo-payment-detail",name:"buckaroo.payment.detail",isChildren:!0,path:"/sw/order/buckaroo/detail/:id"}),e(t)},routes:{index:{component:"buckaroo-settings",path:"index",meta:{parentPath:"sw.settings.index"}}}});n("rWDw"),n("WCCb");function k(e){return(k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function w(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function _(e){for(var t=1;t\n {{$tc(\'buckaroo-payment.afterpay.setup\')}}\n
\n
\n \n
\n
\n',inject:["BuckarooPaymentSettingsService"],data:function(){return{taxes:[],showTaxes:!1,afterpayTaxes:[{name:this.$tc("buckaroo-payment.afterpay.hightTaxes"),id:1},{name:this.$tc("buckaroo-payment.afterpay.middleTaxes"),id:5},{name:this.$tc("buckaroo-payment.afterpay.lowTaxes"),id:2},{name:this.$tc("buckaroo-payment.afterpay.zeroTaxes"),id:3},{name:this.$tc("buckaroo-payment.afterpay.noTaxes"),id:4}],taxAssociation:{}}},model:{prop:"value",event:"change"},computed:{},props:{name:{type:String,required:!0,default:""},value:{type:Object,required:!1,default:function(){return{}}}},created:function(){var e=this;this.BuckarooPaymentSettingsService.getTaxes().then((function(t){e.taxes=t.taxes.map((function(e){return{id:e.id,name:e.name}}))}))},methods:{setTaxAssociation:function(e,t){this.taxAssociation[e]=t,this.$emit("change",_(_({},this.value),this.taxAssociation))},getSelectValue:function(e){if(this.value[e])return this.value[e]}}});n("QdNZ");Shopware.Component.register("buckaroo-in3-logo",{template:'
\n {{$tc(\'buckaroo-payment.in3LogoLabel\')}}\n
\n \n
\n
',inject:["BuckarooPaymentSettingsService"],data:function(){return{logos:[],selectedLogo:null}},model:{prop:"value",event:"change"},props:{name:{type:String,required:!0,default:""},value:{type:String,required:!1,default:function(){return null}}},watch:{selectedLogo:function(e){this.$emit("change",e)}},created:function(){var e=this;this.BuckarooPaymentSettingsService.getIn3Icons().then((function(t){e.setInitialValue(),e.logos=t.logos}))},methods:{setInitialValue:function(){this.value?this.selectedLogo=this.value:(this.selectedLogo="default_payment_icon",this.$emit("change",this.selectedLogo))}}})}}); \ No newline at end of file diff --git a/src/Service/Refund/Builder.php b/src/Service/Refund/Builder.php new file mode 100644 index 00000000..b8d006b6 --- /dev/null +++ b/src/Service/Refund/Builder.php @@ -0,0 +1,217 @@ +clientService = $clientService; + $this->settingsService = $settingsService; + $this->urlService = $urlService; + } + + public function build( + RefundDataInterface $refundData, + Request $request, + string $configCode + ): Client { + $paymentRecord = $refundData->getPaymentRecord(); + $transactionMethod = $paymentRecord->getPaymentCode(); + + $client = $this->getClient( + $configCode, + $refundData->getOrder()->getSalesChannelId() + ) + ->setAction('refund') + ->setPayload( + array_merge_recursive( + $this->getCommonRequestPayload( + $request, + $refundData, + $paymentRecord->getOriginalTransactionId(), + ), + $this->getMethodPayload( + $refundData->getAmount(), + $configCode, + $transactionMethod + ) + ) + ); + + if ( + $configCode === 'giftcards' && $transactionMethod !== null + ) { + $client->setPaymentCode($transactionMethod); + } + + //Override payByBank if transaction was made with ideal + if ($configCode === 'paybybank' && $transactionMethod === 'ideal') { + $client->setPaymentCode($transactionMethod); + } + + return $client; + } + + /** + * Get parameters common to all payment methods + * + * @param Request $request + * @param RefundDataInterface $refundData + * @param mixed $transactionKey + * + * @return array + */ + private function getCommonRequestPayload( + Request $request, + RefundDataInterface $refundData, + $transactionKey, + ): array { + + if (!is_scalar($transactionKey)) { + $transactionKey = ''; + } + + return [ + 'order' => $refundData->getInvoiceNumber(), + 'invoice' => $refundData->getOrderNumber(), + 'amountCredit' => $refundData->getAmount(), + 'currency' => $refundData->getCurrency(), + 'pushURL' => $this->urlService->getReturnUrl('buckaroo.payment.push'), + 'pushURLFailure' => $this->urlService->getReturnUrl('buckaroo.payment.push'), + 'clientIP' => $this->getIp($request), + 'originalTransactionKey' => (string)$transactionKey, + 'additionalParameters' => [ + 'orderTransactionId' => $refundData->getTransactionId(), + 'orderId' => $refundData->getOrderId(), + ], + ]; + } + + /** + * Get method specific payloads + * + * @param float $amount + * @param string $configCode + * @param string|null $transactionMethod + * + * @return array + */ + private function getMethodPayload( + float $amount, + string $configCode, + string $transactionMethod = null + ): array { + if ( + $configCode === "afterpay" && + $this->settingsService->getSetting('afterpayEnabledold') === true + ) { + return $this->getRefundRequestArticlesForAfterpayOld($amount); + } + + if (in_array($configCode, ["afterpay", "Billink", "klarnakp"])) { + return $this->getRefundArticleData($amount); + } + + if ( + in_array($configCode, ['creditcard', 'creditcards', 'giftcards']) && + $transactionMethod !== null + ) { + return [ + "name" => $transactionMethod, + "version" => 2 + ]; + } + + return []; + } + + /** + * Get buckaroo client + * + * @param string $paymentCode + * @param string $salesChannelId + * + * @return Client + */ + private function getClient(string $paymentCode, string $salesChannelId): Client + { + return $this->clientService + ->get($paymentCode, $salesChannelId); + } + + /** + * @param float $amount + * + * @return array + */ + private function getRefundArticleData(float $amount): array + { + + return [ + 'articles' => [[ + 'refundType' => 'Return', + 'identifier' => 1, + 'description' => 'Refund', + 'quantity' => 1, + 'price' => round($amount, 2), + 'vatPercentage' => 0, + ]] + ]; + } + + /** + * @param float $amount + * + * @return array + */ + private function getRefundRequestArticlesForAfterpayOld(float $amount): array + { + + return [ + 'articles' => [[ + 'identifier' => 1, + 'description' => 'Refund', + 'quantity' => 1, + 'price' => round($amount, 2), + 'vatCategory' => 4, + ]] + ]; + } + + /** + * Get client ip + * + * @param Request $request + * + * @return array + */ + private function getIp(Request $request): array + { + $remoteIp = $request->getClientIp(); + + return [ + 'address' => $remoteIp, + 'type' => IPProtocolVersion::getVersion($remoteIp) + ]; + } +} diff --git a/src/Service/Refund/ResponseHandler.php b/src/Service/Refund/ResponseHandler.php new file mode 100644 index 00000000..45e579ed --- /dev/null +++ b/src/Service/Refund/ResponseHandler.php @@ -0,0 +1,145 @@ +buckarooTransactionEntityRepository = $buckarooTransactionEntityRepository; + $this->transactionService = $transactionService; + $this->stateTransitionService = $stateTransitionService; + $this->translator = $translator; + } + + + /** + * Handle response from payment engine + * + * @param ClientResponseInterface $response + * @param RefundDataInterface $refundData + * @param Context $context + * @param array $orderItems + * + * @return array + */ + public function handle( + ClientResponseInterface $response, + RefundDataInterface $refundData, + Context $context, + array $orderItems, + ): array { + + $transactionId = $refundData->getPaymentRecord()->getId(); + $transaction = $refundData->getLastTransaction(); + $amount = $refundData->getAmount(); + + if ($response->isSuccess()) { + $status = ($amount < $refundData->getOrder()->getAmountTotal()) ? 'partial_refunded' : 'refunded'; + $this->stateTransitionService->transitionPaymentState($status, $transaction->getId(), $context); + $this->transactionService->saveTransactionData($transaction->getId(), $context, [$status => 1]); + + // updating refunded items in transaction + if (count($orderItems)) { + $orderItemsRefunded = []; + foreach ($orderItems as $value) { + if ( + is_array($value) && + isset($value['id']) && + isset($value['quantity']) && + is_string($value['id']) && + is_scalar($value['quantity']) + ) { + $orderItemsRefunded[$value['id']] = $value['quantity']; + } + } + $orderItems = ''; + + $refunded_items = ''; + + $bkTransaction = $this->buckarooTransactionEntityRepository + ->getById($transactionId); + if ($bkTransaction !== null) { + $refunded_items = $bkTransaction->get("refunded_items"); + } + + if (!is_string($refunded_items)) { + $refunded_items = ''; + } + + if (!empty($refunded_items)) { + $refunded_items = json_decode($refunded_items, true); + if (is_array($refunded_items)) { + foreach ($refunded_items as $k => $qnt) { + if (!is_scalar($qnt)) { + $qnt = 0; + } + $qnt = (int)$qnt; + if (!isset($orderItemsRefunded[$k])) { + $orderItemsRefunded[$k] = 0; + } + $orderItemsRefunded[$k] = $orderItemsRefunded[$k] + $qnt; + } + } + } + + $amountCredit = 0; + $transaction = $this->buckarooTransactionEntityRepository->getById($transactionId); + if ($transaction !== null && is_scalar($transaction->get('amount_credit'))) { + $amountCredit = (float)$transaction->get('amount_credit'); + } + + + $this->buckarooTransactionEntityRepository + ->save( + $transactionId, + [ + 'refunded_items' => json_encode($orderItemsRefunded), + 'amount_credit' => (string)($amountCredit + $amount) + ], + ); + } + + return [ + 'status' => true, + 'message' => $this->translator->trans( + "buckaroo.refund.refunded_amount", + [ + '%amount%' => $amount, + '%currency%' => $refundData->getCurrency() + ] + ) + ]; + } + + return [ + 'status' => false, + 'message' => $response->getSomeError(), + 'code' => $response->getStatusCode(), + ]; + } +} diff --git a/src/Service/RefundService.php b/src/Service/RefundService.php index 637617e9..e9bda934 100644 --- a/src/Service/RefundService.php +++ b/src/Service/RefundService.php @@ -5,18 +5,15 @@ namespace Buckaroo\Shopware6\Service; use Shopware\Core\Framework\Context; -use Buckaroo\Shopware6\Buckaroo\Client; -use Buckaroo\Shopware6\Service\UrlService; use Shopware\Core\Checkout\Order\OrderEntity; use Symfony\Component\HttpFoundation\Request; +use Buckaroo\Shopware6\Service\Refund\Builder; use Buckaroo\Shopware6\Service\TransactionService; -use Buckaroo\Shopware6\Service\Buckaroo\ClientService; -use Buckaroo\Shopware6\Service\StateTransitionService; use Symfony\Contracts\Translation\TranslatorInterface; -use Buckaroo\Shopware6\Buckaroo\ClientResponseInterface; -use Buckaroo\Shopware6\Helpers\Constants\IPProtocolVersion; -use Buckaroo\Shopware6\Entity\Transaction\BuckarooTransactionEntityRepository; -use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; +use Buckaroo\Shopware6\Buckaroo\Refund\OrderRefundData; +use Buckaroo\Shopware6\Buckaroo\Refund\Order\PaymentRecord; +use Buckaroo\Shopware6\Buckaroo\Refund\RefundDataInterface; +use Buckaroo\Shopware6\Service\Refund\ResponseHandler; class RefundService { @@ -24,32 +21,20 @@ class RefundService protected TranslatorInterface $translator; - protected BuckarooTransactionEntityRepository $buckarooTransactionEntityRepository; + protected Builder $refundBuilder; - protected SettingsService $settingsService; - - protected UrlService $urlService; - - protected StateTransitionService $stateTransitionService; - - protected ClientService $clientService; + protected ResponseHandler $refundResponseHandler; public function __construct( - BuckarooTransactionEntityRepository $buckarooTransactionEntityRepository, - SettingsService $settingsService, TransactionService $transactionService, - UrlService $urlService, - StateTransitionService $stateTransitionService, TranslatorInterface $translator, - ClientService $clientService + Builder $refundBuilder, + ResponseHandler $refundResponseHandler ) { - $this->buckarooTransactionEntityRepository = $buckarooTransactionEntityRepository; $this->transactionService = $transactionService; - $this->settingsService = $settingsService; - $this->urlService = $urlService; - $this->stateTransitionService = $stateTransitionService; $this->translator = $translator; - $this->clientService = $clientService; + $this->refundBuilder = $refundBuilder; + $this->refundResponseHandler = $refundResponseHandler; } /** @@ -97,264 +82,40 @@ public function refund( if ($amount <= 0) { return []; } - - $client = $this->getClient( - $configCode, - $order->getSalesChannelId() - ) - ->setAction('refund') - ->setPayload( - array_merge_recursive( - $this->getCommonRequestPayload( - $request, - $order, - $transaction['transactions'], - $amount - ), - $this->getMethodPayload( - $amount, - $configCode, - $transaction - ) - ) - ); - - if ( - $configCode === 'giftcards' && - isset($transaction['transaction_method']) && - is_string($transaction['transaction_method']) - ) { - $client->setPaymentCode($transaction['transaction_method']); - } - - //Override payByBank if transaction was made with ideal - if ($configCode === 'paybybank' && $transaction['transaction_method'] === 'ideal') { - $client->setPaymentCode($transaction['transaction_method']); - } - - - return $this->handleResponse( - $client->execute(), - $order, + return $this->handleRefund( + new OrderRefundData( + $order, + new PaymentRecord($transaction), + $amount + ), + $request, $context, $orderItems, - $transaction['id'], - $amount + $configCode ); } - - /** - * Handle response from payment engine - * - * @param ClientResponseInterface $response - * @param OrderEntity $order - * @param Context $context - * @param array $orderItems - * @param mixed $transactionId - * @param float $amount - * - * @return array - */ - private function handleResponse( - ClientResponseInterface $response, - OrderEntity $order, + protected function handleRefund( + RefundDataInterface $refundData, + Request $request, Context $context, array $orderItems, - $transactionId, - float $amount + string $configCode ): array { - if (!is_scalar($transactionId)) { - throw new \InvalidArgumentException('Transaction id must be a string'); - } - $transactionId = (string)$transactionId; - - $transaction = $this->getLastTransaction($order); - - if ($response->isSuccess()) { - $status = ($amount < $order->getAmountTotal()) ? 'partial_refunded' : 'refunded'; - $this->stateTransitionService->transitionPaymentState($status, $transaction->getId(), $context); - $this->transactionService->saveTransactionData($transaction->getId(), $context, [$status => 1]); - - // updating refunded items in transaction - if (count($orderItems)) { - $orderItemsRefunded = []; - foreach ($orderItems as $value) { - if ( - is_array($value) && - isset($value['id']) && - isset($value['quantity']) && - is_string($value['id']) && - is_scalar($value['quantity']) - ) { - $orderItemsRefunded[$value['id']] = $value['quantity']; - } - } - $orderItems = ''; - - $refunded_items = ''; - - $bkTransaction = $this->buckarooTransactionEntityRepository - ->getById($transactionId); - if ($bkTransaction !== null) { - $refunded_items = $bkTransaction->get("refunded_items"); - } - - if (!is_string($refunded_items)) { - $refunded_items = ''; - } - - if (!empty($refunded_items)) { - $refunded_items = json_decode($refunded_items, true); - if (is_array($refunded_items)) { - foreach ($refunded_items as $k => $qnt) { - if (!is_scalar($qnt)) { - $qnt = 0; - } - $qnt = (int)$qnt; - if (!isset($orderItemsRefunded[$k])) { - $orderItemsRefunded[$k] = 0; - } - $orderItemsRefunded[$k] = $orderItemsRefunded[$k] + $qnt; - } - } - } - - $amountCredit = 0; - $transaction = $this->buckarooTransactionEntityRepository->getById($transactionId); - if ($transaction !== null && is_scalar($transaction->get('amount_credit'))) { - $amountCredit = (float)$transaction->get('amount_credit'); - } - - - $this->buckarooTransactionEntityRepository - ->save( - $transactionId, - [ - 'refunded_items' => json_encode($orderItemsRefunded), - 'amount_credit' => (string)($amountCredit + $amount) - ], - ); - } - - return [ - 'status' => true, - 'message' => $this->translator->trans("buckaroo-payment.refund.refunded_amount"), - 'amount' => sprintf(" %s %s", $amount, $this->getCurrencyIso($order)) - ]; - } - - return [ - 'status' => false, - 'message' => $response->getSomeError(), - 'code' => $response->getStatusCode(), - ]; - } - - protected function getLastTransaction(OrderEntity $order): OrderTransactionEntity - { - $transactions = $order->getTransactions(); - - if ($transactions === null) { - throw new \InvalidArgumentException('Cannot find last transaction on order'); - } - - /** @var \Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity|null */ - $transaction = $transactions->last(); - - if ($transaction === null) { - throw new \InvalidArgumentException('Cannot find last transaction on order'); - } - - return $transaction; - } - protected function getCurrencyIso(OrderEntity $order): string - { - $currency = $order->getCurrency(); - if ($currency === null) { - throw new \InvalidArgumentException('Cannot find currency on order'); - } - return $currency->getIsoCode(); - } - - /** - * Get parameters common to all payment methods - * - * @param Request $request - * @param OrderEntity $order - * @param mixed $transactionKey - * @param float $amount - * - * @return array - */ - private function getCommonRequestPayload( - Request $request, - OrderEntity $order, - $transactionKey, - float $amount - ): array { - - if (!is_scalar($transactionKey)) { - $transactionKey = ''; - } - - $transaction = $this->getLastTransaction($order); - return [ - 'order' => $order->getOrderNumber(), - 'invoice' => $order->getOrderNumber(), - 'amountCredit' => $amount, - 'currency' => $this->getCurrencyIso($order), - 'pushURL' => $this->urlService->getReturnUrl('buckaroo.payment.push'), - 'pushURLFailure' => $this->urlService->getReturnUrl('buckaroo.payment.push'), - 'clientIP' => $this->getIp($request), - 'originalTransactionKey' => (string)$transactionKey, - 'additionalParameters' => [ - 'orderTransactionId' => $transaction->getId(), - 'orderId' => $order->getId(), - ], - ]; - } - - /** - * Get method specific payloads - * - * @param float $amount - * @param string $configCode - * @param array $transaction - * - * @return array - */ - private function getMethodPayload( - float $amount, - string $configCode, - array $transaction - ): array { - if ( - $configCode === "afterpay" && - $this->settingsService->getSetting('afterpayEnabledold') === true - ) { - return $this->getRefundRequestArticlesForAfterpayOld($amount); - } - - if (in_array($configCode, ["afterpay", "Billink", "klarnakp"])) { - return $this->getRefundArticleData($amount); - } - - if ( - in_array($configCode, ['creditcard', 'creditcards', 'giftcards']) && - isset($transaction['transaction_method']) && - is_string($transaction['transaction_method']) - ) { - return [ - "name" => $transaction['transaction_method'], - "version" => 2 - ]; - } + $client = $this->refundBuilder->build( + $refundData, + $request, + $configCode + ); - return []; + return $this->refundResponseHandler->handle( + $client->execute(), + $refundData, + $context, + $orderItems, + ); } - /** * Validate request and return any errors * @@ -369,65 +130,33 @@ private function validate(OrderEntity $order, array $customFields): ?array if ($order->getAmountTotal() <= 0) { return [ 'status' => false, - 'message' => $this->translator->trans("buckaroo-payment.capture.invalid_amount") + 'message' => $this->translator->trans("buckaroo.refund.invalid_amount") ]; } if ($customFields['canRefund'] == 0) { return [ 'status' => false, - 'message' => $this->translator->trans("buckaroo-payment.refund.not_supported") + 'message' => $this->translator->trans("buckaroo.refund.not_supported") ]; } if (!empty($customFields['refunded']) && ($customFields['refunded'] == 1)) { return [ 'status' => false, - 'message' => $this->translator->trans("buckaroo-payment.refund.already_refunded") + 'message' => $this->translator->trans("buckaroo.refund.already_refunded") ]; } if (!isset($customFields['originalTransactionKey'])) { return [ 'status' => false, - 'message' => $this->translator->trans("buckaroo-payment.general_error") + 'message' => $this->translator->trans("buckaroo.refund.general_error") ]; } return null; } - - /** - * Get buckaroo client - * - * @param string $paymentCode - * @param string $salesChannelId - * - * @return Client - */ - private function getClient(string $paymentCode, string $salesChannelId): Client - { - return $this->clientService - ->get($paymentCode, $salesChannelId); - } - - - /** - * Get client ip - * - * @param Request $request - * - * @return array - */ - private function getIp(Request $request): array - { - $remoteIp = $request->getClientIp(); - - return [ - 'address' => $remoteIp, - 'type' => IPProtocolVersion::getVersion($remoteIp) - ]; - } - + /** * * @param array $orderItems @@ -483,43 +212,4 @@ public function getConfigCode( } return $customFields['serviceName']; } - - /** - * @param float $amount - * - * @return array - */ - private function getRefundArticleData(float $amount): array - { - - return [ - 'articles' => [[ - 'refundType' => 'Return', - 'identifier' => 1, - 'description' => 'Refund', - 'quantity' => 1, - 'price' => round($amount, 2), - 'vatPercentage' => 0, - ]] - ]; - } - - /** - * @param float $amount - * - * @return array - */ - private function getRefundRequestArticlesForAfterpayOld(float $amount): array - { - - return [ - 'articles' => [[ - 'identifier' => 1, - 'description' => 'Refund', - 'quantity' => 1, - 'price' => round($amount, 2), - 'vatCategory' => 4, - ]] - ]; - } } diff --git a/src/Service/ReturnService.php b/src/Service/ReturnService.php new file mode 100644 index 00000000..d5dee4e3 --- /dev/null +++ b/src/Service/ReturnService.php @@ -0,0 +1,249 @@ +transactionService = $transactionService; + $this->translator = $translator; + $this->refundBuilder = $refundBuilder; + $this->refundResponseHandler = $refundResponseHandler; + $this->buckarooTransactionEntityRepository = $buckarooTransactionEntityRepository; + $this->stateMachineRegistry = $stateMachineRegistry; + } + + public function refundAll( + OrderReturnEntity $orderReturn, + Context $context + ): array { + + $order = $orderReturn->getOrder(); + $amount = $orderReturn->getAmountTotal(); + + if ($amount === null) { + return []; + } + $paymentRecords = $this->getPaymentRecords($order->getId()); + + $response = []; + foreach ($paymentRecords as $paymentRecord) { + $response[] = $this->refund($order, $context, $paymentRecord, $amount); + } + + if ($this->refundsAreSuccessful($response)) { + $this->setOrderReturnState( + $orderReturn->getId(), + OrderReturnStates::STATE_DONE, + $context + ); + } + return $response; + } + + /** + * Do a buckaroo refund request + * + * @param OrderEntity $order + * @param Context $context + * + * @return array|null + */ + protected function refund( + OrderEntity $order, + Context $context, + ReturnPaymentRecord $paymentRecord, + float $amount + ): ?array { + if (!$this->transactionService->isBuckarooPaymentMethod($order)) { + return null; + } + + $customFields = $this->transactionService->getCustomFields($order, $context); + $configCode = $this->getConfigCode($customFields); + if ($amount <= 0) { + return []; + } + + return $this->handleRefund( + new OrderRefundData( + $order, + $paymentRecord, + $amount + ), + Request::createFromGlobals(), + $context, + [], + $configCode + ); + } + + /** + * Handle the build and execution of the refund request + * + * @param RefundDataInterface $refundData + * @param Request $request + * @param Context $context + * @param array $orderItems + * @param string $configCode + * + * @return array + */ + protected function handleRefund( + RefundDataInterface $refundData, + Request $request, + Context $context, + array $orderItems, + string $configCode + ): array { + $client = $this->refundBuilder->build( + $refundData, + $request, + $configCode + ); + + return $this->refundResponseHandler->handle( + $client->execute(), + $refundData, + $context, + $orderItems, + ); + } + + /** + * @param array $customFields + * + * @return string + */ + public function getConfigCode( + array $customFields + ): string { + if (!is_string($customFields['serviceName'])) { + throw new \InvalidArgumentException('Service name is not a string'); + } + return $customFields['serviceName']; + } + + /** + * Get payment records from the database + * + * @param string $orderId + * + * @return array + */ + private function getPaymentRecords(string $orderId): array + { + $transactions = $this->buckarooTransactionEntityRepository->findByOrderId($orderId); + + $paymentRecords = []; + + + foreach ($transactions as $transaction) { + $transactionKey = $transaction->get("transactions"); + + if (!in_array($transactionKey, array_keys($paymentRecords))) { + $paymentRecords[$transactionKey] = new ReturnPaymentRecord( + $transaction, + $this->getTransactionAmount($transaction) + ); + } else { + $paymentRecords[$transactionKey]->addAmount( + $this->getTransactionAmount($transaction) + ); + } + } + return array_values($paymentRecords); + } + + /** + * Get transaction amount + * + * @param BuckarooTransactionEntity $transaction + * + * @return float + */ + private function getTransactionAmount(BuckarooTransactionEntity $transaction): float + { + $amount = 0; + + if ( + is_scalar($transaction->get("amount")) + ) { + $amount = (float)$transaction->get("amount"); + } + + if ( + is_scalar($transaction->get("amount_credit")) + ) { + $amount -= (float)$transaction->get("amount_credit"); + } + return $amount; + } + + private function setOrderReturnState(string $orderReturnId, string $state, Context $context) + { + try { + $this->stateMachineRegistry->transition( + new Transition( + OrderReturnDefinition::ENTITY_NAME, + $orderReturnId, + $state, + 'stateId' + ), + $context + ); + } catch (\Throwable $th) { + throw new \Exception("Invalid order return status transition", 0, $th); + } + + } + + private function refundsAreSuccessful(array $responses): bool + { + foreach ($responses as $response) { + if (!$response['status']) { + return false; + } + } + return true; + } +} diff --git a/src/Subscribers/CheckoutConfirmTemplateSubscriber.php b/src/Subscribers/CheckoutConfirmTemplateSubscriber.php index 58d9e8f6..eb6fb137 100644 --- a/src/Subscribers/CheckoutConfirmTemplateSubscriber.php +++ b/src/Subscribers/CheckoutConfirmTemplateSubscriber.php @@ -210,7 +210,6 @@ public function hideNotEnabledPaymentMethods($event): void if ($buckarooKey === 'afterpay' && !$this->canShowAfterpay($event)) { $paymentMethods = $this->removePaymentMethod($paymentMethods, $paymentMethod->getId()); } - } $event->getPage()->setPaymentMethods($paymentMethods); } diff --git a/src/Subscribers/OrderReturnInProgressSubscriber.php b/src/Subscribers/OrderReturnInProgressSubscriber.php new file mode 100644 index 00000000..77961eb6 --- /dev/null +++ b/src/Subscribers/OrderReturnInProgressSubscriber.php @@ -0,0 +1,123 @@ +orderReturnRepository = $orderReturnRepository; + $this->returnService = $returnService; + $this->logger = $logger; + $this->notificationService = $notificationService; + } + + /** + * @inheritDoc + */ + public static function getSubscribedEvents() + { + return [ + 'state_machine.order_return.state_changed' => 'onReturnInProgress', + ]; + } + + public function onReturnInProgress(StateMachineStateChangeEvent $event) + { + if ( + $event->getNextState()->getTechnicalName() !== OrderReturnStates::STATE_IN_PROGRESS || + $event->getPreviousState()->getTechnicalName() !== OrderReturnStates::STATE_OPEN + ) { + return; + } + + if ($this->orderReturnRepository === null) { + return; + } + + $criteria = new Criteria([$event->getTransition()->getEntityId()]); + $criteria->addAssociation('order'); + $criteria->addAssociation('order.currency'); + $criteria->addAssociation('order.transactions'); + $criteria->addAssociation('order.transactions.paymentMethod'); + $criteria->addAssociation('order.transactions.paymentMethod.plugin'); + /** @var OrderReturnEntity */ + $orderReturn = $this->orderReturnRepository->search( + $criteria, + $event->getContext() + )->first(); + + if ($orderReturn !== null) { + $this->createRefund($orderReturn, $event->getContext()); + } + } + + private function createRefund(OrderReturnEntity $orderReturn, $context) + { + try { + $response = $this->returnService->refundAll( + $orderReturn, + $context, + ); + + $this->createNotifications($response, $context); + } catch (\Throwable $th) { + $this->logger->debug((string)$th); + } + } + + private function createNotifications(array $response, Context $context) + { + foreach ($response as $result) { + $status = 'danger'; + if (isset($result['status']) && $result['status'] === true) { + $status = 'success'; + } + + $message = "A error has occurred while processing the buckaroo refund"; + if (isset($result['message'])) { + $message = $result['message']; + } + + $this->notificationService->createNotification( + [ + 'id' => Uuid::randomHex(), + 'status' => $status, + 'message' => $message, + 'adminOnly' => true, + 'requiredPrivileges' => [], + 'createdByIntegrationId' => null, + 'createdByUserId' => null, + ], + $context + ); + } + } +} diff --git a/src/translations/messages.en-GB.json b/src/translations/messages.en-GB.json index 5bee03cc..4273d0d8 100644 --- a/src/translations/messages.en-GB.json +++ b/src/translations/messages.en-GB.json @@ -2,6 +2,12 @@ "buckaroo": { "statuscode_failed": "Unfortunately an error occurred while processing your payment. Please try again. If this error persists, please choose a different payment method.", "userCanceled": "According to our system, you have canceled the payment. If this is not the case, please contact us.", - "billinkRejectedMessage": "Unfortunately, it is currently not possible for you to use Billink, Please select another payment method or contact Billink." + "billinkRejectedMessage": "Unfortunately, it is currently not possible for you to use Billink, Please select another payment method or contact Billink.", + "refund": { + "invalid_amount": "Amount is not valid", + "not_supported": "Refund is not supported", + "already_refunded": "This order is already refunded", + "refunded_amount": "Buckaroo successfully refunded %amount% %currency%" + } } } \ No newline at end of file diff --git a/src/translations/messages.nl-NL.json b/src/translations/messages.nl-NL.json index 85a6da0c..6331289e 100644 --- a/src/translations/messages.nl-NL.json +++ b/src/translations/messages.nl-NL.json @@ -2,6 +2,13 @@ "buckaroo": { "statuscode_failed": "Helaas is er een fout opgetreden tijdens het verwerken van uw betaling. Probeer het opnieuw. Als deze fout zich blijft voordoen, kies dan een andere betaalmethode.", "userCanceled": "Volgens ons systeem heb je de betaling geannuleerd. Mocht dit niet het geval zijn, neem dan contact met ons op.", - "billinkRejectedMessage": "Helaas is het op dit moment voor jou niet mogelijk om gebruik te maken van Billink, selecteer een andere betaalmethode of neem contact op met Billink." + "billinkRejectedMessage": "Helaas is het op dit moment voor jou niet mogelijk om gebruik te maken van Billink, selecteer een andere betaalmethode of neem contact op met Billink.", + "refund": { + "general_error": "Unfortunately an error occurred while processing your return. Please try again.", + "invalid_amount": "Amount is not valid", + "not_supported": "Refund is not supported", + "already_refunded": "This order is already refunded", + "refunded_amount": "Buckaroo successfully refunded %amount% %currency%" + } } } \ No newline at end of file