Date: Wed, 15 Feb 2023 22:58:30 -0300
Subject: [PATCH 044/156] :sparkles: updates
---
.../checkout/model/payment/order-value.js | 78 +++++++++++++++++
.../front/checkout/model/payment/two-cards.js | 85 -------------------
src/Block/Checkout/Form/Billet.php | 2 +-
src/Block/Checkout/Form/Pix.php | 2 +-
src/Block/Checkout/Gateway.php | 3 +-
src/Model/Payment/Data/Billet.php | 60 +++++++++++++
src/Model/Payment/Data/Card.php | 22 ++++-
src/Model/Payment/Data/Multicustomers.php | 24 ++++++
src/Model/Payment/Data/PaymentRequest.php | 34 ++++++++
.../Payment/Data/PaymentRequestInterface.php | 6 ++
src/Model/Payment/Data/Pix.php | 60 +++++++++++++
templates/checkout/form/billet.phtml | 2 +-
templates/checkout/form/card.phtml | 4 +-
.../form/field/enable-multicustomers.phtml | 2 +-
templates/checkout/payment/2-cards.phtml | 2 +-
.../checkout/payment/billet-and-card.phtml | 4 +-
templates/checkout/payment/credit-card.phtml | 7 +-
17 files changed, 294 insertions(+), 103 deletions(-)
create mode 100644 assets/javascripts/front/checkout/model/payment/order-value.js
create mode 100644 src/Model/Payment/Data/Billet.php
create mode 100644 src/Model/Payment/Data/Multicustomers.php
create mode 100644 src/Model/Payment/Data/Pix.php
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
new file mode 100644
index 00000000..e7835d4d
--- /dev/null
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -0,0 +1,78 @@
+(function ($) {
+ const cardValueTarget = 'input[data-pagarmecheckout-element=order-value]';
+ let pagarme = {
+ keyEventHandler: function (e) {
+ fillAnotherInput(e);
+ },
+ getCartTotals: function () {
+ return cartTotal;
+ }
+ }
+ async function fillAnotherInput(e) {
+ let input = $(e.currentTarget);
+ const empty = '';
+ let nextInput = input.closest('fieldset').siblings('fieldset').find('input').filter(':visible:first');
+ if (nextInput.length === 0) {
+ nextInput = input.closest('div').siblings('div').find('input').first();
+ }
+ let value = await formatValue(e.currentTarget.value);
+ if (!value) {
+ return;
+ }
+ let total = await formatValue(pagarme.getCartTotals());
+ if (value > total) {
+ showError('O valor não pode ser maior que total do pedido!');
+ input.val(empty);
+ nextInput.val(empty);
+ return;
+ }
+ nextInput.val(await formatValue((total - value), false));
+ input.val(await formatValue(value, false));
+ }
+
+ function formatValue(value, raw = true) {
+ return new Promise((resolve) => {
+ if (raw) {
+ if (typeof value !== 'string') {
+ value = value.toString();
+ }
+ value = value.replace('.', '');
+ resolve(parseFloat(value.replace(',', '.')));
+ } else {
+ if (typeof value === 'string') {
+ value = parseFloat(value);
+ }
+ resolve(value.toFixed(2).replace('.', ','));
+ }
+ });
+ }
+
+ function addsMask() {
+ $(cardValueTarget).mask('#.##0,00', {
+ reverse: true
+ });
+ }
+
+ function showError(text)
+ {
+ const message = {
+ type: 'error',
+ html: text,
+ allowOutsideClick: false
+ };
+ try {
+ swal(message);
+ } catch (e) {
+ new swal(message);
+ }
+ }
+
+ $( document ).ready(function() {
+ addsMask();
+ });
+
+ $(cardValueTarget).on('blur', function (e) {
+ pagarme.keyEventHandler(e);
+ });
+ } (jQuery)
+);
diff --git a/assets/javascripts/front/checkout/model/payment/two-cards.js b/assets/javascripts/front/checkout/model/payment/two-cards.js
index 92822018..b3b2278e 100644
--- a/assets/javascripts/front/checkout/model/payment/two-cards.js
+++ b/assets/javascripts/front/checkout/model/payment/two-cards.js
@@ -1,90 +1,5 @@
/* globals wc_pagarme_checkout */
(function ($) {
- const cardValueTarget = 'input[data-element=card-order-value]';
-
- let pagarme = {
- getCheckoutPaymentElement: function () {
- let value = $('form.checkout input[name="payment_method"]:checked').val();
- return $('.wc_payment_method.payment_method_' + value);
- },
- isPagarmePayment: function () {
- return $('form.checkout input[name="payment_method"]:checked').val().indexOf('pagarme');
- },
- keyEventHandler: function (e) {
- fillAnotherInput(e);
- },
- getCartTotals: function () {
- return cartTotal;
- }
- }
-
- async function fillAnotherInput(e) {
- let input = $(e.currentTarget);
- const empty = '';
- let nextInput = input.closest('fieldset').siblings('fieldset').find('input').filter(':visible:first');
- if (nextInput.length === 0) {
- nextInput = input.closest('div').siblings('div').find('input').first();
- }
- let value = await formatValue(e.currentTarget.value);
- if (!value) {
- return;
- }
- let total = await formatValue(pagarme.getCartTotals());
- if (value > total) {
- showError('O valor não pode ser maior que total do pedido!');
- input.val(empty);
- nextInput.val(empty);
- return;
- }
- nextInput.val(await formatValue((total - value), false));
- input.val(await formatValue(value, false));
- }
-
- function formatValue(value, raw = true) {
- return new Promise((resolve) => {
- if (raw) {
- if (typeof value !== 'string') {
- value = value.toString();
- }
- value = value.replace('.', '');
- resolve(parseFloat(value.replace(',', '.')));
- } else {
- if (typeof value === 'string') {
- value = parseFloat(value);
- }
- resolve(value.toFixed(2).replace('.', ','));
- }
- });
- }
-
- function addsMask() {
- $(cardValueTarget).mask('#.##0,00', {
- reverse: true
- });
- }
-
- function showError(text)
- {
- const message = {
- type: 'error',
- html: text,
- allowOutsideClick: false
- };
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
- }
-
- $( document ).ready(function() {
- addsMask();
- });
-
- $(cardValueTarget).on('blur', function (e) {
- pagarme.keyEventHandler(e);
- });
-
} (jQuery)
);
diff --git a/src/Block/Checkout/Form/Billet.php b/src/Block/Checkout/Form/Billet.php
index 5e58574d..664e533e 100644
--- a/src/Block/Checkout/Form/Billet.php
+++ b/src/Block/Checkout/Form/Billet.php
@@ -32,7 +32,7 @@ class Billet extends Gateway
*/
public function getElementId(string $id)
{
- $id = '[' . $id . ']';
+ $id = '[billet][' . $id . ']';
return parent::getElementId($id);
}
}
diff --git a/src/Block/Checkout/Form/Pix.php b/src/Block/Checkout/Form/Pix.php
index 623e70da..1b7a434c 100644
--- a/src/Block/Checkout/Form/Pix.php
+++ b/src/Block/Checkout/Form/Pix.php
@@ -32,7 +32,7 @@ class Pix extends Gateway
*/
public function getElementId(string $id)
{
- $id = '[' . $id . ']';
+ $id = '[pix][' . $id . ']';
return parent::getElementId($id);
}
}
diff --git a/src/Block/Checkout/Gateway.php b/src/Block/Checkout/Gateway.php
index 558237cc..1d9e892b 100644
--- a/src/Block/Checkout/Gateway.php
+++ b/src/Block/Checkout/Gateway.php
@@ -143,11 +143,12 @@ public function getConfig()
/**
* @param bool $include
- * @return void
+ * @return $this
*/
public function setIncludeContainer(bool $include = true)
{
$this->container = $include;
+ return $this;
}
/**
diff --git a/src/Model/Payment/Data/Billet.php b/src/Model/Payment/Data/Billet.php
new file mode 100644
index 00000000..2884d5cc
--- /dev/null
+++ b/src/Model/Payment/Data/Billet.php
@@ -0,0 +1,60 @@
+multicustomers = $multicustomers;
+ $this->init();
+ }
+
+ /**
+ * @return void
+ */
+ private function init()
+ {
+ if ($this->getPostPaymentContent() && is_array($this->getPostPaymentContent()) && array_key_exists('billet', $this->getPostPaymentContent())) {
+ foreach ($this->getPostPaymentContent()['billet'] as $field => $value) {
+ $this->{$this->getMethod($field)}($value);
+ }
+ }
+ }
+
+ /**
+ * @param $data
+ * @return Billet
+ */
+ public function setMulticustomers($data)
+ {
+ return $this->setData('multicustomers', $this->multicustomers->setData($data));
+ }
+}
diff --git a/src/Model/Payment/Data/Card.php b/src/Model/Payment/Data/Card.php
index b18b24dd..5d5a0f56 100644
--- a/src/Model/Payment/Data/Card.php
+++ b/src/Model/Payment/Data/Card.php
@@ -17,7 +17,7 @@
defined( 'ABSPATH' ) || exit;
/**
- * Class ShippingMethod
+ * Class Card
* @package Woocommerce\Pagarme\Model\Payment\Data
*/
class Card extends AbstractPayment
@@ -25,18 +25,27 @@ class Card extends AbstractPayment
/** @var int */
private $num;
+ /** @var Multicustomers|null */
+ private $multicustomers;
+
/**
* @param int $num
* @param Json|null $jsonSerialize
* @param array $data
+ * @param Multicustomers|null $multicustomers
*/
public function __construct(
$num = 1,
Json $jsonSerialize = null,
- array $data = []
+ array $data = [],
+ Multicustomers $multicustomers = null
) {
parent::__construct($jsonSerialize, $data);
$this->num = $num;
+ if (!$multicustomers) {
+ $multicustomers = new Multicustomers;
+ }
+ $this->multicustomers = $multicustomers;
$this->init();
}
@@ -50,5 +59,12 @@ private function init()
}
}
-
+ /**
+ * @param $data
+ * @return $this
+ */
+ public function setMulticustomers($data)
+ {
+ return $this->setData('multicustomers', $this->multicustomers->setData($data));
+ }
}
diff --git a/src/Model/Payment/Data/Multicustomers.php b/src/Model/Payment/Data/Multicustomers.php
new file mode 100644
index 00000000..18459bc3
--- /dev/null
+++ b/src/Model/Payment/Data/Multicustomers.php
@@ -0,0 +1,24 @@
+cards = $cards;
$this->shippingMethod = $shippingMethod;
$this->shippingAddress = $shippingAddress;
$this->billingAddress = $billingAddress;
+ $this->billet = $billet;
+ $this->pix = $pix;
$this->init();
}
@@ -149,4 +167,20 @@ public function setBillingAddress()
{
return $this->setData(self::BILLING_ADDRESS, $this->billingAddress);
}
+
+ /**
+ * @return PaymentRequest
+ */
+ public function setBillet()
+ {
+ return $this->setData(self::BILLET, $this->billet);
+ }
+
+ /**
+ * @return PaymentRequest
+ */
+ public function setPix()
+ {
+ return $this->setData(self::PIX, $this->pix);
+ }
}
diff --git a/src/Model/Payment/Data/PaymentRequestInterface.php b/src/Model/Payment/Data/PaymentRequestInterface.php
index 8cf3267f..020e7d01 100644
--- a/src/Model/Payment/Data/PaymentRequestInterface.php
+++ b/src/Model/Payment/Data/PaymentRequestInterface.php
@@ -37,6 +37,12 @@ interface PaymentRequestInterface
/** @var string */
const PAGARME_PAYMENT_REQUEST_KEY = 'pagarme_payment_request';
+ /** @var string */
+ const BILLET = 'billet';
+
+ /** @var string */
+ const PIX = 'pix';
+
/**
* @param string $value
* @return PaymentRequest
diff --git a/src/Model/Payment/Data/Pix.php b/src/Model/Payment/Data/Pix.php
new file mode 100644
index 00000000..f1e8c7ff
--- /dev/null
+++ b/src/Model/Payment/Data/Pix.php
@@ -0,0 +1,60 @@
+multicustomers = $multicustomers;
+ $this->init();
+ }
+
+ /**
+ * @return void
+ */
+ private function init()
+ {
+ if ($this->getPostPaymentContent() && is_array($this->getPostPaymentContent()) && array_key_exists('pix', $this->getPostPaymentContent())) {
+ foreach ($this->getPostPaymentContent()['pix'] as $field => $value) {
+ $this->{$this->getMethod($field)}($value);
+ }
+ }
+ }
+
+ /**
+ * @param $data
+ * @return $this
+ */
+ public function setMulticustomers($data)
+ {
+ return $this->setData('multicustomers', $this->multicustomers->setData($data));
+ }
+}
diff --git a/templates/checkout/form/billet.phtml b/templates/checkout/form/billet.phtml
index b767fb8a..192c8b69 100644
--- a/templates/checkout/form/billet.phtml
+++ b/templates/checkout/form/billet.phtml
@@ -21,7 +21,7 @@ if (!function_exists('add_action')) {
*
-
+
= $this->getMessage(true) ?>
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index a571d9fd..f5e7a93d 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -30,8 +30,8 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
- *
-
+ *
+
= $this->createBlock(
diff --git a/templates/checkout/form/field/enable-multicustomers.phtml b/templates/checkout/form/field/enable-multicustomers.phtml
index b0f97d3a..7372707b 100644
--- a/templates/checkout/form/field/enable-multicustomers.phtml
+++ b/templates/checkout/form/field/enable-multicustomers.phtml
@@ -12,7 +12,7 @@
declare( strict_types=1 );
?>
getConfig()->getMulticustomers()) : ?>
- = $this->formatElement(
+ = $this->setIncludeContainer()->formatElement(
'',
['p' => ['class' => true, 'data-element' => true]]
) ?>
diff --git a/templates/checkout/payment/2-cards.phtml b/templates/checkout/payment/2-cards.phtml
index fee1de2d..33b94464 100644
--- a/templates/checkout/payment/2-cards.phtml
+++ b/templates/checkout/payment/2-cards.phtml
@@ -23,4 +23,4 @@ if (!function_exists('add_action')) {
'qty_cards' => $this->getQtyCards()
]
)->toHtml() ?>
-
+
diff --git a/templates/checkout/payment/billet-and-card.phtml b/templates/checkout/payment/billet-and-card.phtml
index bf41fb9d..a85e03da 100644
--- a/templates/checkout/payment/billet-and-card.phtml
+++ b/templates/checkout/payment/billet-and-card.phtml
@@ -33,7 +33,7 @@ if (!function_exists('add_action')) {
'qty_cards' => $this->getQtyCards(),
'show_order_value' => true,
'show_multicustomers_form' => true,
- 'multicustomers_sequence' => 2,
- 'show_order_value' => true,
+ 'multicustomers_sequence' => 2
]
)->toHtml() ?>
+
diff --git a/templates/checkout/payment/credit-card.phtml b/templates/checkout/payment/credit-card.phtml
index 092193a4..46f3a557 100644
--- a/templates/checkout/payment/credit-card.phtml
+++ b/templates/checkout/payment/credit-card.phtml
@@ -14,14 +14,11 @@ declare( strict_types=1 );
if (!function_exists('add_action')) {
exit(0);
}
-$y = $this->getQtyCards();
-$x = $this->getPaymentInstance();
-
$this->createBlock(
'\Woocommerce\Pagarme\Block\Checkout\Form\Card',
'pagarme.checkout.form.card',
[
- 'payment_instance' => $x,
- 'qty_cards' => $y
+ 'payment_instance' => $this->getPaymentInstance(),
+ 'qty_cards' => $this->getQtyCards()
]
)->toHtml();
From 1174bb37b56d5f3f3c8d593e39014349b6168648 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Thu, 16 Feb 2023 23:06:40 -0300
Subject: [PATCH 045/156] :sparkles: improve customers, payment and field to
sdk
---
assets/stylesheets/front/_checkout.scss | 4 --
src/Model/Checkout.php | 56 ++++++++++++++++++++--
src/Model/Payment/Data/AbstractPayment.php | 32 +++++++++++++
src/Model/Payment/Data/Billet.php | 22 ++++-----
src/Model/Payment/Data/Card.php | 20 +++++++-
src/Model/Payment/Data/Cards.php | 2 +-
src/Model/Payment/Data/Multicustomers.php | 10 ++++
src/Model/Payment/Data/PaymentRequest.php | 22 ++++++---
src/Model/Payment/Data/Pix.php | 20 +++-----
9 files changed, 145 insertions(+), 43 deletions(-)
diff --git a/assets/stylesheets/front/_checkout.scss b/assets/stylesheets/front/_checkout.scss
index b1bbea47..531ff5d6 100644
--- a/assets/stylesheets/front/_checkout.scss
+++ b/assets/stylesheets/front/_checkout.scss
@@ -6,10 +6,6 @@
box-shadow: 1px 1px 3px #da3c39;
}
- input[type="text"] {
- width: 200px;
- }
-
input, select {
margin: 0;
}
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index a2c12372..afe88ff3 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -19,6 +19,10 @@
}
use WC_Order;
+use Woocommerce\Pagarme\Model\Payment\Data\AbstractPayment;
+use Woocommerce\Pagarme\Model\Payment\Data\Card;
+use Woocommerce\Pagarme\Model\Payment\Data\Cards;
+use Woocommerce\Pagarme\Model\Payment\Data\Multicustomers;
use Woocommerce\Pagarme\Model\Payment\Data\PaymentRequest;
use Woocommerce\Pagarme\Model\Payment\Data\PaymentRequestInterface;
@@ -124,19 +128,19 @@ public function process(WC_Order $wc_order = null, string $type = CheckoutTypes:
private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
{
$fields = [
- 'payment_method' => $paymentRequest->getPaymentMethod()
+ 'payment_method' => str_replace('-', '_', $paymentRequest->getPaymentMethod())
];
if ($cards = $paymentRequest->getCards()) {
foreach ($cards as $key => $card) {
$key++;
if ($key === 1) {
- if ($orderValue = $card->getCardOrderValue()) {
+ if ($orderValue = $card->getOrderValue()) {
$fields['card_order_value'] = $orderValue;
}
$fields['brand'] = $card->getBrand();
$fields['installments'] = $card->getInstallment();
} else {
- if ($orderValue = $card->getCardOrderValue()) {
+ if ($orderValue = $card->getOrderValue()) {
$fields['card_order_value' . $key] = $orderValue;
}
$fields['brand' . $key] = $card->getBrand();
@@ -145,6 +149,52 @@ private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
$fields['pagarmetoken' . $key] = $card->getToken();
}
}
+ $this->extractMulticustomers($fields, $paymentRequest);
+ $this->extractOrderValue($fields, $paymentRequest);
return $fields;
}
+
+ private function extractMulticustomers(array &$fields, PaymentRequestInterface $paymentRequest)
+ {
+ foreach ($paymentRequest->getData() as $method => $data) {
+ if ($data instanceof AbstractPayment) {
+ if ($data->getMulticustomers() instanceof Multicustomers) {
+ foreach ($data->getMulticustomers()->getData() as $key => $value) {
+ $fields['multicustomer_' . $method][$key] = $value;
+ $fields['multicustomer_' . $method . '[' . $key . ']'] = $value;
+ $fields['enable_multicustomers_' . $method] = 1;
+ }
+ }
+ }
+ if (is_array($data)) {
+ foreach ($data as $sequece => $datum) {
+ if ($datum instanceof Card) {
+ $method = 'card';
+ $sequece++;
+ if (count($data) > 1) {
+ $method .= $sequece;
+ }
+ if ($datum->getMulticustomers() instanceof Multicustomers) {
+ foreach ($datum->getMulticustomers()->getData() as $key => $value) {
+ $fields['multicustomer_' . $method][$key] = $value;
+ $fields['multicustomer_' . $method . '[' . $key . ']'] = $value;
+ $fields['enable_multicustomers_' . $method] = $value;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private function extractOrderValue(array &$fields, PaymentRequestInterface $paymentRequest)
+ {
+ foreach ($paymentRequest->getData() as $method => $data) {
+ if ($data instanceof AbstractPayment) {
+ if ($orderValue = $data->getOrderValue()) {
+ $fields[$method . '_value'] = $orderValue;
+ }
+ }
+ }
+ }
}
diff --git a/src/Model/Payment/Data/AbstractPayment.php b/src/Model/Payment/Data/AbstractPayment.php
index 5d496838..f7736218 100644
--- a/src/Model/Payment/Data/AbstractPayment.php
+++ b/src/Model/Payment/Data/AbstractPayment.php
@@ -21,6 +21,21 @@
*/
class AbstractPayment extends DataObject
{
+ /** @var string */
+ protected $identifier = 'pix';
+
+ /**
+ * @return void
+ */
+ protected function init()
+ {
+ if ($this->getPostPaymentContent() && is_array($this->getPostPaymentContent()) && array_key_exists($this->identifier, $this->getPostPaymentContent())) {
+ foreach ($this->getPostPaymentContent()[$this->identifier] as $field => $value) {
+ $this->{$this->getMethod($field)}($value);
+ }
+ }
+ }
+
/**
* @return array|null
*/
@@ -60,4 +75,21 @@ public function convertField(string $field)
{
return str_replace('-', '_', ucwords(str_replace('_', ' ', $field)));
}
+
+ /**
+ * @param string $method
+ * @param bool $identifier
+ * @return bool
+ */
+ protected function havePaymentForm(string $method, bool $identifier = true)
+ {
+ $content = $this->getPostPaymentContent();
+ if ($identifier && isset($this->getPostPaymentContent()[$this->identifier])) {
+ $content = $this->getPostPaymentContent()[$this->identifier];
+ }
+ if (is_array($content) && array_key_exists($method, $content)) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/src/Model/Payment/Data/Billet.php b/src/Model/Payment/Data/Billet.php
index 2884d5cc..91c2ca7c 100644
--- a/src/Model/Payment/Data/Billet.php
+++ b/src/Model/Payment/Data/Billet.php
@@ -24,6 +24,9 @@ class Billet extends AbstractPayment
/** @var Multicustomers|null */
private $multicustomers;
+ /** @var string */
+ protected $identifier = 'billet';
+
public function __construct(
Json $jsonSerialize = null,
array $data = [],
@@ -37,24 +40,15 @@ public function __construct(
$this->init();
}
- /**
- * @return void
- */
- private function init()
- {
- if ($this->getPostPaymentContent() && is_array($this->getPostPaymentContent()) && array_key_exists('billet', $this->getPostPaymentContent())) {
- foreach ($this->getPostPaymentContent()['billet'] as $field => $value) {
- $this->{$this->getMethod($field)}($value);
- }
- }
- }
-
/**
* @param $data
- * @return Billet
+ * @return $this
*/
public function setMulticustomers($data)
{
- return $this->setData('multicustomers', $this->multicustomers->setData($data));
+ if ($this->havePaymentForm(Multicustomers::FIELD) && $this->multicustomers->isEnable($data)) {
+ return $this->setData(Multicustomers::FIELD, $this->multicustomers->setData($data));
+ }
+ return $this;
}
}
diff --git a/src/Model/Payment/Data/Card.php b/src/Model/Payment/Data/Card.php
index 5d5a0f56..f5f988df 100644
--- a/src/Model/Payment/Data/Card.php
+++ b/src/Model/Payment/Data/Card.php
@@ -52,19 +52,35 @@ public function __construct(
/**
* @return void
*/
- private function init()
+ protected function init()
{
foreach ($this->getPostPaymentContent()['cards'][$this->num] as $field => $value) {
$this->{$this->getMethod($field)}($value);
}
}
+ /**
+ * @param string $method
+ * @param bool $identifier
+ * @return bool
+ */
+ protected function havePaymentForm(string $method, bool $identifier = true)
+ {
+ if ($this->getPostPaymentContent()['cards'][$this->num] && is_array($this->getPostPaymentContent()['cards'][$this->num]) && array_key_exists($method, $this->getPostPaymentContent()['cards'][$this->num])) {
+ return true;
+ }
+ return false;
+ }
+
/**
* @param $data
* @return $this
*/
public function setMulticustomers($data)
{
- return $this->setData('multicustomers', $this->multicustomers->setData($data));
+ if ($this->havePaymentForm(Multicustomers::FIELD) && $this->multicustomers->isEnable($data)) {
+ return $this->setData(Multicustomers::FIELD, $this->multicustomers->setData($data));
+ }
+ return $this;
}
}
diff --git a/src/Model/Payment/Data/Cards.php b/src/Model/Payment/Data/Cards.php
index 95a683d4..eab69251 100644
--- a/src/Model/Payment/Data/Cards.php
+++ b/src/Model/Payment/Data/Cards.php
@@ -40,7 +40,7 @@ public function __construct(
/**
* @return Cards
*/
- private function init()
+ protected function init()
{
$cards = [];
for ($count = 1; $count <= $this->getCountTokens(); $count++) {
diff --git a/src/Model/Payment/Data/Multicustomers.php b/src/Model/Payment/Data/Multicustomers.php
index 18459bc3..c5413cf6 100644
--- a/src/Model/Payment/Data/Multicustomers.php
+++ b/src/Model/Payment/Data/Multicustomers.php
@@ -21,4 +21,14 @@
*/
class Multicustomers extends AbstractPayment
{
+ const FIELD = 'multicustomers';
+
+ /**
+ * @param array $data
+ * @return bool
+ */
+ public function isEnable(array $data)
+ {
+ return array_key_exists('enable', $data) ? $data['enable'] : false;
+ }
}
diff --git a/src/Model/Payment/Data/PaymentRequest.php b/src/Model/Payment/Data/PaymentRequest.php
index bcdf4728..4fd04645 100644
--- a/src/Model/Payment/Data/PaymentRequest.php
+++ b/src/Model/Payment/Data/PaymentRequest.php
@@ -90,11 +90,12 @@ public function __construct(
/**
* @return void
*/
- private function init()
+ protected function init()
{
foreach ($this->getConstants() as $const) {
- if (isset($_POST[$const])) {
- $this->{$this->getMethod($const)}($_POST[$const]);
+ if (isset($_POST[$const]) || isset($this->getPostPaymentContent()[$const])) {
+ $value = $_POST[$const] ?? $this->getPostPaymentContent()[$const];
+ $this->{$this->getMethod($const)}($value);
}
}
$this->setCards();
@@ -149,7 +150,10 @@ public function getShippingMethod()
*/
public function setCards()
{
- return $this->setData(self::CARDS, $this->cards->getCards());
+ if ($this->havePaymentForm(self::CARDS, false)) {
+ return $this->setData(self::CARDS, $this->cards->getCards());
+ }
+ return $this;
}
/**
@@ -173,7 +177,10 @@ public function setBillingAddress()
*/
public function setBillet()
{
- return $this->setData(self::BILLET, $this->billet);
+ if ($this->havePaymentForm(self::BILLET, false)) {
+ return $this->setData(self::BILLET, $this->billet);
+ }
+ return $this;
}
/**
@@ -181,6 +188,9 @@ public function setBillet()
*/
public function setPix()
{
- return $this->setData(self::PIX, $this->pix);
+ if ($this->havePaymentForm(self::PIX, false)) {
+ return $this->setData(self::PIX, $this->pix);
+ }
+ return $this;
}
}
diff --git a/src/Model/Payment/Data/Pix.php b/src/Model/Payment/Data/Pix.php
index f1e8c7ff..aec35b1e 100644
--- a/src/Model/Payment/Data/Pix.php
+++ b/src/Model/Payment/Data/Pix.php
@@ -24,6 +24,9 @@ class Pix extends AbstractPayment
/** @var Multicustomers|null */
private $multicustomers;
+ /** @var string */
+ protected $identifier = 'pix';
+
public function __construct(
Json $jsonSerialize = null,
array $data = [],
@@ -37,24 +40,15 @@ public function __construct(
$this->init();
}
- /**
- * @return void
- */
- private function init()
- {
- if ($this->getPostPaymentContent() && is_array($this->getPostPaymentContent()) && array_key_exists('pix', $this->getPostPaymentContent())) {
- foreach ($this->getPostPaymentContent()['pix'] as $field => $value) {
- $this->{$this->getMethod($field)}($value);
- }
- }
- }
-
/**
* @param $data
* @return $this
*/
public function setMulticustomers($data)
{
- return $this->setData('multicustomers', $this->multicustomers->setData($data));
+ if ($this->havePaymentForm(Multicustomers::FIELD) && $this->multicustomers->isEnable($data)) {
+ return $this->setData(Multicustomers::FIELD, $this->multicustomers->setData($data));
+ }
+ return $this;
}
}
From f07949b68f6c0f88cc1d8374948f0a7ce6bf587e Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Sat, 25 Feb 2023 17:22:17 -0300
Subject: [PATCH 046/156] :sparkles: updates
---
src/Block/Checkout/Gateway.php | 1 -
src/Block/Checkout/ThankYou.php | 120 +++++
src/Block/Checkout/ThankYou/Billet.php | 42 ++
src/Block/Checkout/ThankYou/BilletAndCard.php | 51 +++
src/Block/Checkout/ThankYou/Pix.php | 69 +++
src/Block/Checkout/ThankYou/Voucher.php | 43 ++
.../WoocommercePlatformOrderDecorator.php | 6 +-
src/Controller/Gateways/AbstractGateway.php | 29 +-
src/Model/Payment/AbstractPayment.php | 90 ++++
src/Model/Payment/Billet.php | 20 +
src/Model/Payment/BilletCard.php | 37 ++
src/Model/Payment/Card.php | 89 ++++
src/Model/Payment/Pix.php | 2 +
src/Model/Payment/TwoCards.php | 29 ++
src/Model/Payment/Voucher.php | 21 +
src/Model/PaymentTemp.php | 429 ++++++++++++++++++
templates/checkout/thank-you.phtml | 43 ++
.../checkout/thankyou/billet-and-card.phtml | 44 ++
templates/checkout/thankyou/billet.phtml | 39 ++
templates/checkout/thankyou/pix.phtml | 42 ++
templates/checkout/thankyou/voucher.phtml | 32 ++
21 files changed, 1271 insertions(+), 7 deletions(-)
create mode 100644 src/Block/Checkout/ThankYou.php
create mode 100644 src/Block/Checkout/ThankYou/Billet.php
create mode 100644 src/Block/Checkout/ThankYou/BilletAndCard.php
create mode 100644 src/Block/Checkout/ThankYou/Pix.php
create mode 100644 src/Block/Checkout/ThankYou/Voucher.php
create mode 100644 src/Model/PaymentTemp.php
create mode 100644 templates/checkout/thank-you.phtml
create mode 100644 templates/checkout/thankyou/billet-and-card.phtml
create mode 100644 templates/checkout/thankyou/billet.phtml
create mode 100644 templates/checkout/thankyou/pix.phtml
create mode 100644 templates/checkout/thankyou/voucher.phtml
diff --git a/src/Block/Checkout/Gateway.php b/src/Block/Checkout/Gateway.php
index 1d9e892b..e89c3493 100644
--- a/src/Block/Checkout/Gateway.php
+++ b/src/Block/Checkout/Gateway.php
@@ -99,7 +99,6 @@ public function getElementId(string $id)
public function getPaymentClass()
{
-
return '\Woocommerce\Pagarme\Block\Checkout\Payment\\' . str_replace(' ', '', ucwords($this->numeralReplace(str_replace(['_', '-'], ' ', $this->getPaymentInstance()->getMethodCode()))));
}
diff --git a/src/Block/Checkout/ThankYou.php b/src/Block/Checkout/ThankYou.php
new file mode 100644
index 00000000..fe07b4f1
--- /dev/null
+++ b/src/Block/Checkout/ThankYou.php
@@ -0,0 +1,120 @@
+numeralReplace(str_replace(['_', '-'], ' ', $this->getPaymentMethod()))));
+ }
+
+ /**
+ * @param string $class
+ * @return array|string|string[]
+ */
+ public function numeralReplace(string $class)
+ {
+ return str_replace(
+ ['1', '2', '3'],
+ ['one', 'two', 'tree'],
+ $class
+ );
+ }
+
+ /**
+ * @param string $content
+ * @param array $element
+ * @return string
+ */
+ public function formatElement(string $content, array $element)
+ {
+ if (!$this->container) {
+ $content = '';
+ }
+ return wp_kses($content, $element);
+ }
+
+ /**
+ * @param bool $include
+ * @return $this
+ */
+ public function setIncludeContainer(bool $include = true)
+ {
+ $this->container = $include;
+ return $this;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getContainer()
+ {
+ return $this->container;
+ }
+
+ /**
+ * @return mixed|null
+ */
+ public function getResponseData()
+ {
+ if ($order = $this->getPagarmeOrder()) {
+ if (property_exists($order, 'response_data')) {
+ $response = $order->response_data;
+ if (is_string($response)) {
+ $response = json_decode($response);
+ }
+ return $response;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @return bool
+ */
+ public function isSuccessOrder()
+ {
+ if (!in_array($this->getPagarmeOrder()->pagarme_status, ['failed', 'canceled'])) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @param string $path
+ * @return string
+ */
+ public function getFilePath(string $path)
+ {
+ return esc_url(plugins_url($path, WCMP_ROOT_FILE));
+ }
+}
diff --git a/src/Block/Checkout/ThankYou/Billet.php b/src/Block/Checkout/ThankYou/Billet.php
new file mode 100644
index 00000000..75f1ef10
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/Billet.php
@@ -0,0 +1,42 @@
+getResponseData()) {
+ $charges = $response->charges;
+ $charge = array_shift($charges);
+ $transaction = array_shift($charge->transactions);
+ return $transaction->boletoUrl;
+ }
+ return null;
+ }
+}
diff --git a/src/Block/Checkout/ThankYou/BilletAndCard.php b/src/Block/Checkout/ThankYou/BilletAndCard.php
new file mode 100644
index 00000000..cee12dd5
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/BilletAndCard.php
@@ -0,0 +1,51 @@
+getResponseData()) {
+ return $response->charges;
+ }
+ } catch (\Exception $e) {}
+ return null;
+ }
+
+ public function getTransactionType($charge)
+ {
+ return $this->getTransacion($charge)->type;
+ }
+
+ public function getTransacion($charge)
+ {
+ return array_shift($charge->transactions);
+ }
+}
diff --git a/src/Block/Checkout/ThankYou/Pix.php b/src/Block/Checkout/ThankYou/Pix.php
new file mode 100644
index 00000000..05a741aa
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/Pix.php
@@ -0,0 +1,69 @@
+getResponseData()) {
+ $charges = $response->charges;
+ $charge = array_shift($charges);
+ $transaction = array_shift($charge->transactions);
+ return $transaction->postData->qr_code_url;
+ }
+ return null;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getRawQrCode()
+ {
+ if ($response = $this->getResponseData()) {
+ $charges = $response->charges;
+ $charge = array_shift($charges);
+ $transaction = array_shift($charge->transactions);
+ return $transaction->postData->qr_code;
+ }
+ return null;
+ }
+
+ /**
+ * @return array
+ */
+ public function getInstructions()
+ {
+ return [
+ '1. Point your phone at this screen to capture the code.',
+ '2. Open your payments app.',
+ '3. Confirm the information and complete the payment on the app.',
+ '4. We will send you a purchase confirmation.'
+ ];
+ }
+}
diff --git a/src/Block/Checkout/ThankYou/Voucher.php b/src/Block/Checkout/ThankYou/Voucher.php
new file mode 100644
index 00000000..5075d846
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/Voucher.php
@@ -0,0 +1,43 @@
+getResponseData()) {
+ $charges = $response->charges;
+ $charge = array_shift($charges);
+ return $charge->status;
+ }
+ } catch (\Exception $e) {}
+ return null;
+ }
+}
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index 1a00c0ed..407c72bd 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -952,7 +952,7 @@ private function extractPaymentDataFromBilletCreditcard(&$paymentData)
$paymentData[$boletoDataIndex] = [];
}
- if ($this->formData["enable_multicustomers_billet"]) {
+ if (isset($this->formData["enable_multicustomers_billet"]) && $this->formData["enable_multicustomers_billet"]) {
$newPaymentData->customer = $this->extractMultibuyerData(
'billet'
);
@@ -977,7 +977,7 @@ private function extractPaymentDataFromBillet(&$paymentData)
$paymentData[$boletoDataIndex] = [];
}
- if ($this->formData["enable_multicustomers_billet"]) {
+ if (isset($this->formData["enable_multicustomers_billet"]) && $this->formData["enable_multicustomers_billet"]) {
$newPaymentData->customer = $this->extractMultibuyerData(
'billet'
);
@@ -1012,7 +1012,7 @@ private function extractPaymentDataFromPix(&$paymentData)
private function extractPaymentDataFromVoucher(&$paymentData)
{
- $identifier = $this->formData["pagarmetoken"];
+ $identifier = $this->formData["pagarmetoken1"];
if (!$identifier) {
$identifier = $this->formData["card_id"];
}
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index c4a58beb..d240515f 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -13,11 +13,13 @@
use WC_Payment_Gateway;
use WC_Order;
+use Woocommerce\Pagarme\Block\Template;
use Woocommerce\Pagarme\Model\Checkout;
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Gateway;
+use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Payment\PostFormatter;
use Woocommerce\Pagarme\Model\WooOrderRepository;
use Woocommerce\Pagarme\Block\Checkout\Gateway as GatewayBlock;
@@ -64,6 +66,9 @@ abstract class AbstractGateway extends WC_Payment_Gateway
/** @var GatewayBlock */
private $gatewayBlock;
+ /** @var Template*/
+ private Template $template;
+
/**
* @param Gateway|null $gateway
* @param WooOrderRepository|null $wooOrderRepository
@@ -76,7 +81,8 @@ public function __construct(
WooOrderRepository $wooOrderRepository = null,
PostFormatter $postFormatter = null,
Config $config = null,
- GatewayBlock $gatewayBlock = null
+ GatewayBlock $gatewayBlock = null,
+ Template $template = null
) {
if (!$gateway) {
$gateway = new Gateway();
@@ -96,12 +102,16 @@ public function __construct(
if (!$gatewayBlock) {
$gatewayBlock = new GatewayBlock;
}
+ if (!$template) {
+ $template = new Template;
+ }
$this->gatewayBlock = $gatewayBlock;
$this->config = $config;
$this->postFormatter = $postFormatter;
$this->model = $gateway;
$this->checkout = $checkout;
$this->wooOrderRepository = $wooOrderRepository;
+ $this->template = $template;
$this->id = 'woo-pagarme-payments-' . $this->method;
$this->method_title = $this->getPaymentMethodTitle();
$this->method_description = __('Payment Gateway Pagar.me', 'woo-pagarme-payments') . ' ' . $this->method_title;
@@ -117,7 +127,7 @@ public function __construct(
add_action(self::PAYMENT_OPTION_UPDATE_SLUG . $this->id, [$this, 'process_admin_options']);
}
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
- add_action('woocommerce_thankyou_' . $this->vendor . ' ' . $this->method_title, [$this, 'thank_you_page']);
+ add_action('woocommerce_thankyou_' . $this->vendor, [$this, 'thank_you_page']);
add_action('admin_enqueue_scripts', array($this, 'payments_scripts'));
}
@@ -181,11 +191,24 @@ public function checkout_transparent($order_id)
/**
* @param $order_id
* @return void
+ * @throws \Exception
*/
public function thank_you_page($order_id)
{
$order = $this->wooOrderRepository->getById($order_id);
- require_once Core::get_file_path('thank-you-page.php', 'templates/');
+ $pagarmeOrder = new Order($order_id);
+ if ($this->method === $pagarmeOrder->payment_method) {
+ $this->template->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou',
+ 'pagarme.checkout.thank-you',
+ [
+ 'woo_order' => $order,
+ 'pagarme_order' => $pagarmeOrder,
+ 'payment_method' => $this->method,
+ 'container' => true
+ ]
+ )->toHtml();
+ }
}
/**
diff --git a/src/Model/Payment/AbstractPayment.php b/src/Model/Payment/AbstractPayment.php
index f7e2f435..558cb02e 100644
--- a/src/Model/Payment/AbstractPayment.php
+++ b/src/Model/Payment/AbstractPayment.php
@@ -13,8 +13,12 @@
defined( 'ABSPATH' ) || exit;
+use WC_Order;
+use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Customer;
+use Woocommerce\Pagarme\Model\Order;
+use Woocommerce\Pagarme\Resource\Customers;
/**
* Abstract AbstractPayment
@@ -148,4 +152,90 @@ public function getConfigDataProvider()
}
return $jsConfigProvider;
}
+
+ /**
+ * @return string[]
+ * @throws \Exception
+ */
+ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ return ['payment_method' => $this->getMethodCode()];
+ }
+
+ /**
+ * @param WC_Order $wc_order
+ * @param array $form_fields
+ * @param Customers|null $customer
+ * @return null[]|string[]
+ * @throws \Exception
+ */
+ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $request = [];
+ $content = $this->getPayRequestBase($wc_order, $form_fields, $customer);
+ $content['amount'] = Utils::format_order_price($wc_order->get_total());
+ if ($multicustomers = $this->getMulticustomerData($this->code, $form_fields)) {
+ $content['customer'] = $multicustomers;
+ }
+ $request[] = $content;
+ return $request;
+ }
+
+ protected function getMulticustomerData($type, $form_fields)
+ {
+ $prefix = "multicustomer_{$type}";
+ $is_enabled = Utils::get_value_by($form_fields, "enable_multicustomers_{$type}");
+
+ if (!$is_enabled) {
+ return false;
+ }
+
+ $cpf = Utils::get_value_by($form_fields, $prefix . '[cpf]');
+ $zip_code = Utils::get_value_by($form_fields, $prefix . '[zip_code]');
+
+ return array(
+ 'name' => Utils::get_value_by($form_fields, $prefix . '[name]'),
+ 'email' => Utils::get_value_by($form_fields, $prefix . '[email]'),
+ 'document' => Utils::format_document($cpf),
+ 'type' => 'individual',
+ 'address' => array(
+ 'street' => Utils::get_value_by($form_fields, $prefix . '[street]'),
+ 'number' => Utils::get_value_by($form_fields, $prefix . '[number]'),
+ 'complement' => Utils::get_value_by($form_fields, $prefix . '[complement]'),
+ 'neighborhood' => Utils::get_value_by($form_fields, $prefix . '[neighborhood]'),
+ 'zip_code' => preg_replace('/[^\d]+/', '', $zip_code),
+ 'city' => Utils::get_value_by($form_fields, $prefix . '[city]'),
+ 'state' => Utils::get_value_by($form_fields, $prefix . '[state]'),
+ 'country' => 'BR',
+ ),
+ );
+ }
+
+ protected function getBillingAddressFromCustomer(Customers $customer, WC_Order $wc_order)
+ {
+ $addressArray = isset($customer->address) ? (array) $customer->address : [];
+ if (empty($addressArray)) {
+ $addressArray = $this->getCustomerAddressFromWcOrder($wc_order);
+ }
+ return [
+ 'street' => $addressArray["street"],
+ 'complement' => $addressArray["complement"],
+ 'number' => $addressArray["number"],
+ 'zip_code' => $addressArray["zip_code"],
+ 'neighborhood' => $addressArray["neighborhood"],
+ 'city' => $addressArray["city"],
+ 'state' => $addressArray["state"],
+ 'country' => $addressArray["country"]
+ ];
+ }
+
+ /**
+ * @param WC_Order $wc_order
+ * @return array
+ */
+ private function getCustomerAddressFromWcOrder(WC_Order $wc_order)
+ {
+ $order = new Order($wc_order->get_order_number());
+ return Utils::build_customer_address_from_order($order);
+ }
}
diff --git a/src/Model/Payment/Billet.php b/src/Model/Payment/Billet.php
index 12fe5d4b..35625ae4 100644
--- a/src/Model/Payment/Billet.php
+++ b/src/Model/Payment/Billet.php
@@ -12,7 +12,10 @@
namespace Woocommerce\Pagarme\Model\Payment;
use ReflectionClass;
+use WC_Order;
use Woocommerce\Pagarme\Core;
+use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
@@ -59,4 +62,21 @@ public function getMessage()
{
return __('O Boleto bancário será exibido após a confirmação da compra e poderá ser pago em qualquer agência bancária, pelo seu smartphone ou computador através de serviços digitais de bancos.', 'woo-pagarme-payments');
}
+
+ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $expirationDate = new \DateTime();
+ $days = (int) $this->getConfig()->getBilletDeadlineDays();
+ if ($days) {
+ $expirationDate->modify("+{$days} day");
+ }
+ return [
+ 'payment_method' => 'boleto',
+ 'boleto' => [
+ 'bank' => $this->getConfig()->getBilletBank(),
+ 'instructions' => $this->getConfig()->getBilletInstructions(),
+ 'due_at' => $expirationDate->format('c')
+ ]
+ ];
+ }
}
diff --git a/src/Model/Payment/BilletCard.php b/src/Model/Payment/BilletCard.php
index 781d0116..8fec6eef 100644
--- a/src/Model/Payment/BilletCard.php
+++ b/src/Model/Payment/BilletCard.php
@@ -12,6 +12,9 @@
namespace Woocommerce\Pagarme\Model\Payment;
use ReflectionClass;
+use WC_Order;
+use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
@@ -61,6 +64,25 @@ class BilletCard extends AbstractPayment implements PaymentInterface
'save_credit_card4' => 'save_credit_card'
];
+
+ /** @var CreditCard */
+ private $creditCard;
+
+ /** @var Billet */
+ private $billet;
+
+ /**
+ * @param CreditCard $creditCard
+ * @param Billet $billet
+ */
+ public function __construct(
+ CreditCard $creditCard,
+ Billet $billet
+ ) {
+ $this->creditCard = $creditCard;
+ $this->billet = $billet;
+ }
+
/**
* @return array
*/
@@ -77,4 +99,19 @@ public function renameFieldsPost(
}
return $formattedPost;
}
+
+ /**
+ * @param WC_Order $wc_order
+ * @param array $form_fields
+ * @param Customers|null $customer
+ * @return null[]|string[]
+ * @throws \Exception
+ */
+ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $content = [];
+ $content[] = $this->billet->getPayRequest($wc_order, $form_fields, $customer);
+ $content[] = $this->creditCard->getPayRequest($wc_order, $form_fields, $customer);
+ return $content;
+ }
}
diff --git a/src/Model/Payment/Card.php b/src/Model/Payment/Card.php
index 4b85f84c..1da5f142 100644
--- a/src/Model/Payment/Card.php
+++ b/src/Model/Payment/Card.php
@@ -12,6 +12,10 @@
namespace Woocommerce\Pagarme\Model\Payment;
use Pagarme\Core\Payment\Aggregates\SavedCard;
+use WC_Order;
+use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Model\Gateway;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
@@ -21,6 +25,9 @@
*/
class Card extends AbstractPayment
{
+ /** @var int */
+ protected $payRequestCardNum = 1;
+
/**
* @return SavedCard[]|null
*/
@@ -36,4 +43,86 @@ public function getIsEnableWallet()
{
return (bool) $this->getConfig()->{'get' . str_replace(' ', '', ucwords(str_replace('_', ' ', $this->code))) . 'Wallet'}();
}
+
+ /**
+ * Return which credit card type will be send. (card ou card_token)
+ * @param array $form_fields
+ * @param array $card_data
+ * @param string $suffix Suffix for each attribute
+ * @return array
+ */
+ protected function handleCardType($form_fields, $card_data, $suffix = '')
+ {
+ $card_id = Utils::get_value_by($form_fields, "card_id{$suffix}", false);
+ $pagarmetoken = !$suffix ? 'pagarmetoken1' : "pagarmetoken{$suffix}";
+ if ($card_id) {
+ $card_data['credit_card']['card_id'] = $card_id;
+ } else {
+ $card_data['credit_card']['card_token'] = Utils::get_value_by($form_fields, $pagarmetoken);
+ }
+ return $card_data;
+ }
+
+ /**
+ * @param int $num
+ * @return $this
+ */
+ public function setPayRequestCardNum(int $num)
+ {
+ $this->payRequestCardNum = $num;
+ return $this;
+ }
+
+ /**
+ * @param WC_Order $wc_order
+ * @param array $form_fields
+ * @param Customers|null $customer
+ * @return array|string[]
+ * @throws \Exception
+ */
+ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $suffix = $this->payRequestCardNum === 1 ? '' : '2';
+ $content = parent::getPayRequestBase($wc_order, $form_fields, $customer);
+ $content['voucher'] = [
+ 'statement_descriptor' => $this->getConfig()->getVoucherSoftDescriptor(),
+ 'credit_card' => [
+ 'installments' => Utils::get_value_by($form_fields, "installments{$suffix}"),
+ 'statement_descriptor' => $this->getConfig()->getCcSoftDescriptor(),
+ 'capture' => $this->getConfig()->getIsActiveCapture(),
+ 'card' => [
+ 'billing_address' => $this->getBillingAddressFromCustomer($customer, $wc_order)
+ ]
+ ]
+ ];
+ return $this->handleCardType($form_fields, $content, $suffix);
+ }
+
+ protected function getPriceWithInterest($price, $installments, $flag = '')
+ {
+ $type = intval($this->getConfig()->getCcInstallmentType());
+ $amount = $price;
+ if ($type === Gateway::CC_TYPE_SINGLE) { // Parcelamento único
+ $no_interest = intval($this->getConfig()->getCcInstallmentsWithoutInterest());
+ $interest = Utils::str_to_float($this->getConfig()->getCcInstallmentsInterest());
+ $interest_increase = Utils::str_to_float($this->getConfig()->getCcInstallmentsInterestIncrease());
+ $max_installments = intval($this->getConfig()->getCcInstallmentsMaximum());
+ } else { // Parcelamento por bandeira
+ $settings_by_flag = $this->getConfig()->getCcInstallmentsByFlag();
+ $no_interest = intval($settings_by_flag['no_interest'][$flag]);
+ $interest = Utils::str_to_float($settings_by_flag['interest'][$flag]);
+ $interest_increase = Utils::str_to_float($settings_by_flag['interest_increase'][$flag]);
+ $max_installments = intval($settings_by_flag['max_installment'][$flag]);
+ }
+ if ($installments <= $no_interest) {
+ return $amount;
+ }
+ if ($interest) {
+ if ($interest_increase && $installments > $no_interest + 1) {
+ $interest += ($interest_increase * ($installments - ($no_interest + 1)));
+ }
+ $amount += Utils::calc_percentage($interest, $price);
+ }
+ return $amount;
+ }
}
diff --git a/src/Model/Payment/Pix.php b/src/Model/Payment/Pix.php
index 6278a94a..9e6ff563 100644
--- a/src/Model/Payment/Pix.php
+++ b/src/Model/Payment/Pix.php
@@ -12,7 +12,9 @@
namespace Woocommerce\Pagarme\Model\Payment;
use ReflectionClass;
+use WC_Order;
use Woocommerce\Pagarme\Core;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
diff --git a/src/Model/Payment/TwoCards.php b/src/Model/Payment/TwoCards.php
index 7ed041da..40e94ed3 100644
--- a/src/Model/Payment/TwoCards.php
+++ b/src/Model/Payment/TwoCards.php
@@ -12,6 +12,8 @@
namespace Woocommerce\Pagarme\Model\Payment;
use Pagarme\Core\Payment\Aggregates\SavedCard;
+use WC_Order;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
@@ -66,6 +68,18 @@ class TwoCards extends AbstractPayment implements PaymentInterface
'save_credit_card3' => 'save_credit_card2'
];
+ /** @var CreditCard */
+ private $creditCard;
+
+ /**
+ * @param CreditCard $creditCard
+ */
+ public function __construct(
+ CreditCard $creditCard
+ ) {
+ $this->creditCard = $creditCard;
+ }
+
/**
* @return SavedCard[]|null
*/
@@ -81,4 +95,19 @@ public function getIsEnableWallet()
{
return (bool) $this->getConfig()->{'get' . str_replace(' ', '', ucwords(str_replace('_', ' ', $this->code))) . 'Wallet'}();
}
+
+ /**
+ * @param WC_Order $wc_order
+ * @param array $form_fields
+ * @param Customers|null $customer
+ * @return null[]|string[]
+ * @throws \Exception
+ */
+ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $content = [];
+ $content[] = $this->creditCard->getPayRequest($wc_order, $form_fields, $customer);
+ $content[] = $this->creditCard->setPayRequestCardNum(2)->getPayRequest($wc_order, $form_fields, $customer);
+ return $content;
+ }
}
diff --git a/src/Model/Payment/Voucher.php b/src/Model/Payment/Voucher.php
index 34d2cb04..287ab073 100644
--- a/src/Model/Payment/Voucher.php
+++ b/src/Model/Payment/Voucher.php
@@ -11,8 +11,10 @@
namespace Woocommerce\Pagarme\Model\Payment;
+use WC_Order;
use Woocommerce\Pagarme\Model\Payment\Voucher\Brands;
use Woocommerce\Pagarme\Model\Payment\Voucher\BrandsInterface;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
@@ -64,4 +66,23 @@ public function getConfigDataProvider()
}
return $jsConfigProvider;
}
+
+ /**
+ * @param WC_Order $wc_order
+ * @param array $form_fields
+ * @param Customers|null $customer
+ * @return array|string[]
+ * @throws \Exception
+ */
+ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $content = parent::getPayRequestBase($wc_order, $form_fields, $customer);
+ $content['voucher'] = [
+ 'statement_descriptor' => $this->getConfig()->getVoucherSoftDescriptor(),
+ 'card' => [
+ 'billing_address' => $this->getBillingAddressFromCustomer($customer, $wc_order)
+ ]
+ ];
+ return $this->handleCardType($form_fields, $content);
+ }
}
diff --git a/src/Model/PaymentTemp.php b/src/Model/PaymentTemp.php
new file mode 100644
index 00000000..6ad2a5cd
--- /dev/null
+++ b/src/Model/PaymentTemp.php
@@ -0,0 +1,429 @@
+payment_method = $payment_method;
+ $this->settings = Setting::get_instance();
+ }
+
+ /**
+ * Return the payment array for API request
+ *
+ * @param $wc_order object order from woocommerce
+ * @param $form_fields array Sent form fields
+ * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
+ *
+ * @return array
+ */
+ public function get_payment_data($wc_order, $form_fields, $customer)
+ {
+ $method_name = $this->get_method_name();
+
+ if (!method_exists($this, $method_name)) {
+ throw new \Exception('Payment method name not exists');
+ }
+
+ $data = $this->{$method_name}($wc_order, $form_fields, $customer);
+
+ if ($method_name == 'pay_billet_and_card' || $method_name == 'pay_2_cards') {
+ return $data;
+ }
+
+ return array($data);
+ }
+
+ /**
+ * Return method name according to the selected payment method
+ *
+ * @return string
+ */
+ public function get_method_name()
+ {
+ return "pay_{$this->payment_method}";
+ }
+
+ /**
+ * Return payment data for "boleto"
+ *
+ * @return array
+ */
+ public function pay_billet($wc_order, $form_fields)
+ {
+ $billet = $this->pay_billet_base();
+ $billet['amount'] = Utils::format_order_price($wc_order->get_total());
+ $multicustomer = $this->get_multicustomer_data('billet', $form_fields);
+
+ if ($multicustomer) {
+ $billet['customer'] = $multicustomer;
+ }
+
+ return $billet;
+ }
+
+ /**
+ * Return payment data for "pix"
+ *
+ * @return array
+ */
+ public function pay_pix($wc_order, $form_fields)
+ {
+ $pix = $this->pay_pix_base();
+ $pix['amount'] = Utils::format_order_price($wc_order->get_total());
+ $multicustomer = $this->get_multicustomer_data('pix', $form_fields);
+
+ if ($multicustomer) {
+ $pix['customer'] = $multicustomer;
+ }
+
+ return $pix;
+ }
+
+ /**
+ * Return payment data for "voucher"
+ *
+ * @return array
+ */
+ public function pay_voucher($wc_order, $form_fields, $customer)
+ {
+ $card = $this->pay_voucher_base($wc_order, $form_fields, $customer);
+ $card_amount = $wc_order->get_total();
+ $card['amount'] = Utils::format_order_price($card_amount);
+ return $card;
+ }
+
+ /**
+ * Return payment data for "voucher" base
+ *
+ * @param $wc_order object order from woocommerce
+ * @param $form_fields array Sent form fields
+ * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
+ *
+ * @return array
+ */
+ private function pay_voucher_base($wc_order, $form_fields, $customer)
+ {
+ $card_data = array(
+ 'payment_method' => 'voucher',
+ 'voucher' => array(
+ 'statement_descriptor' => $this->settings->voucher_soft_descriptor,
+ 'card' => array(
+ 'billing_address' => $this->get_billing_address_from_customer($customer, $wc_order)
+ )
+ ),
+ );
+
+ return $this->handle_credit_card_type($form_fields, $card_data, '');
+ }
+
+ /**
+ * Return payment data for "credit_card"
+ *
+ * @param $wc_order object order from woocommerce
+ * @param $form_fields array Sent form fields
+ * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
+ *
+ * @return array
+ */
+ public function pay_credit_card($wc_order, $form_fields, $customer)
+ {
+ $card = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
+ $card_installments = Utils::get_value_by($form_fields, 'installments');
+ $card_brand = Utils::get_value_by($form_fields, 'brand');
+ $card_amount = $this->get_price_with_interest($wc_order->get_total(), $card_installments, $card_brand);
+ $card['amount'] = Utils::format_order_price($card_amount);
+ $multicustomer = $this->get_multicustomer_data('card', $form_fields);
+
+ if ($multicustomer) {
+ $card['customer'] = $multicustomer;
+ }
+
+ if (!$multicustomer && !empty($customer->email)) {
+ $card['customer'] = $customer;
+ }
+
+ return $card;
+ }
+
+ /**
+ * Return payment data for "billet_and_card"
+ *
+ * @param $wc_order object order from woocommerce
+ * @param $form_fields array Sent form fields
+ * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
+ *
+ * @return array
+ */
+ public function pay_billet_and_card($wc_order, $form_fields, $customer)
+ {
+ $billet_amount = Utils::get_value_by($form_fields, 'billet_value');
+ $billet = $this->pay_billet_base();
+ $billet['amount'] = Utils::format_desnormalized_order_price($billet_amount);
+ $billet_multicustomer = $this->get_multicustomer_data('billet', $form_fields);
+
+ if ($billet_multicustomer) {
+ $billet['customer'] = $billet_multicustomer;
+ }
+
+ $card = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
+
+ if (!is_array($card) && $card->code != 200) {
+ return $card;
+ }
+
+ $card_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value'));
+ $card_installments = Utils::get_value_by($form_fields, 'installments');
+ $card_brand = Utils::get_value_by($form_fields, 'brand');
+
+ $card_amount = $this->get_price_with_interest($card_amount, $card_installments, $card_brand);
+ $card['amount'] = Utils::format_order_price($card_amount);
+ $multicustomer = $this->get_multicustomer_data('card', $form_fields);
+
+ if ($multicustomer) {
+ $card['customer'] = $multicustomer;
+ }
+
+ return array($billet, $card);
+ }
+
+ /**
+ * Return payment data for "2_cards"
+ *
+ * @param $wc_order object order from woocommerce
+ * @param $form_fields array Sent form fields
+ * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
+ *
+ * @return array
+ */
+ public function pay_2_cards($wc_order, $form_fields, $customer)
+ {
+ $card1_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value'));
+ $card2_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value2'));
+
+ $card1 = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
+ $card2 = $this->pay_credit_card_base($wc_order, $form_fields, $customer, true);
+
+ $card1_installments = Utils::get_value_by($form_fields, 'installments');
+ $card2_installments = Utils::get_value_by($form_fields, 'installments2');
+
+ $card1_brand = Utils::get_value_by($form_fields, 'brand');
+ $card2_brand = Utils::get_value_by($form_fields, 'brand2');
+
+ $card1_amount = $this->get_price_with_interest($card1_amount, $card1_installments, $card1_brand);
+ $card2_amount = $this->get_price_with_interest($card2_amount, $card2_installments, $card2_brand);
+
+ $card1['amount'] = Utils::format_order_price($card1_amount);
+ $card2['amount'] = Utils::format_order_price($card2_amount);
+
+ $multicustomer_card1 = $this->get_multicustomer_data('card1', $form_fields);
+ $multicustomer_card2 = $this->get_multicustomer_data('card2', $form_fields);
+
+ if ($multicustomer_card1) {
+ $card1['customer'] = $multicustomer_card1;
+ }
+
+ if ($multicustomer_card2) {
+ $card2['customer'] = $multicustomer_card2;
+ }
+
+ return array($card1, $card2);
+ }
+
+ /**
+ * Return payment data for "credit_card" base (without amount)
+ *
+ * @param $wc_order object order from woocommerce
+ * @param $form_fields array Sent form fields
+ * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
+ *
+ * @return array
+ */
+ private function pay_credit_card_base($wc_order, $form_fields, $customer, $is_second_card = false)
+ {
+ $suffix = $is_second_card ? '2' : '';
+ $card_data = array(
+ 'payment_method' => 'credit_card',
+ 'credit_card' => array(
+ 'installments' => Utils::get_value_by($form_fields, "installments{$suffix}"),
+ 'statement_descriptor' => $this->settings->cc_soft_descriptor,
+ 'capture' => $this->settings->is_active_capture(),
+ 'card' => array(
+ 'billing_address' => $this->get_billing_address_from_customer($customer, $wc_order)
+ )
+ ),
+ );
+
+ return $this->handle_credit_card_type($form_fields, $card_data, $suffix);
+ }
+
+ private function get_billing_address_from_customer($customer, $wc_order)
+ {
+ $addressArray = isset($customer->address) ? (array) $customer->address : [];
+
+ if (empty($addressArray)) {
+ $addressArray = $this->get_customer_address_from_wc_order($wc_order);
+ }
+
+ return array(
+ 'street' => $addressArray["street"],
+ 'complement' => $addressArray["complement"],
+ 'number' => $addressArray["number"],
+ 'zip_code' => $addressArray["zip_code"],
+ 'neighborhood' => $addressArray["neighborhood"],
+ 'city' => $addressArray["city"],
+ 'state' => $addressArray["state"],
+ 'country' => $addressArray["country"]
+ );
+ }
+
+ private function get_customer_address_from_wc_order($wc_order)
+ {
+ $order = new Order($wc_order->get_order_number());
+
+ return Utils::build_customer_address_from_order($order);
+ }
+
+ /**
+ * Return payment data for "boleto"
+ *
+ * @return array
+ */
+ private function pay_billet_base()
+ {
+ $expiration_date = new \DateTime();
+ $days = (int) $this->settings->billet_deadline_days;
+
+ if ($days) {
+ $expiration_date->modify("+{$days} day");
+ }
+
+ return array(
+ 'payment_method' => 'boleto',
+ 'boleto' => array(
+ 'bank' => $this->settings->billet_bank,
+ 'instructions' => $this->settings->billet_instructions,
+ 'due_at' => $expiration_date->format('c'),
+ ),
+ );
+ }
+
+ /**
+ * Return payment data for "pix"
+ *
+ * @return array
+ */
+ private function pay_pix_base()
+ {
+ return array(
+ 'payment_method' => 'pix'
+ );
+ }
+
+ /**
+ * Return which credit card type will be send. (card ou card_token)
+ *
+ * @param array $form_fields
+ * @param array $card_data
+ * @param string $suffix Suffix for each attribute
+ *
+ * @return array
+ */
+ private function handle_credit_card_type($form_fields, $card_data, $suffix = '')
+ {
+ $card_id = Utils::get_value_by($form_fields, "card_id{$suffix}", false);
+ $pagarmetoken = !$suffix ? 'pagarmetoken1' : "pagarmetoken{$suffix}";
+
+ if ($card_id) {
+ $card_data['credit_card']['card_id'] = $card_id;
+ } else {
+ $card_data['credit_card']['card_token'] = Utils::get_value_by($form_fields, $pagarmetoken);
+ }
+
+ return $card_data;
+ }
+
+ private function get_price_with_interest($price, $installments, $flag = '')
+ {
+ $type = intval($this->settings->cc_installment_type);
+ $amount = $price;
+
+ if ($type === Gateway::CC_TYPE_SINGLE) { // Parcelamento único
+ $no_interest = intval($this->settings->cc_installments_without_interest);
+ $interest = Utils::str_to_float($this->settings->cc_installments_interest);
+ $interest_increase = Utils::str_to_float($this->settings->cc_installments_interest_increase);
+ $max_installments = intval($this->settings->cc_installments_maximum);
+ } else { // Parcelamento por bandeira
+ $settings_by_flag = $this->settings->cc_installments_by_flag;
+ $no_interest = intval($settings_by_flag['no_interest'][$flag]);
+ $interest = Utils::str_to_float($settings_by_flag['interest'][$flag]);
+ $interest_increase = Utils::str_to_float($settings_by_flag['interest_increase'][$flag]);
+ $max_installments = intval($settings_by_flag['max_installment'][$flag]);
+ }
+
+ if ($installments <= $no_interest) {
+ return $amount;
+ }
+
+ if ($interest) {
+
+ if ($interest_increase && $installments > $no_interest + 1) {
+ $interest += ($interest_increase * ($installments - ($no_interest + 1)));
+ }
+
+ $amount += Utils::calc_percentage($interest, $price);
+ }
+
+ return $amount;
+ }
+
+ private function get_multicustomer_data($type, $form_fields)
+ {
+ $prefix = "multicustomer_{$type}";
+ $is_enabled = Utils::get_value_by($form_fields, "enable_multicustomers_{$type}");
+
+ if (!$is_enabled) {
+ return false;
+ }
+
+ $cpf = Utils::get_value_by($form_fields, $prefix . '[cpf]');
+ $zip_code = Utils::get_value_by($form_fields, $prefix . '[zip_code]');
+
+ return array(
+ 'name' => Utils::get_value_by($form_fields, $prefix . '[name]'),
+ 'email' => Utils::get_value_by($form_fields, $prefix . '[email]'),
+ 'document' => Utils::format_document($cpf),
+ 'type' => 'individual',
+ 'address' => array(
+ 'street' => Utils::get_value_by($form_fields, $prefix . '[street]'),
+ 'number' => Utils::get_value_by($form_fields, $prefix . '[number]'),
+ 'complement' => Utils::get_value_by($form_fields, $prefix . '[complement]'),
+ 'neighborhood' => Utils::get_value_by($form_fields, $prefix . '[neighborhood]'),
+ 'zip_code' => preg_replace('/[^\d]+/', '', $zip_code),
+ 'city' => Utils::get_value_by($form_fields, $prefix . '[city]'),
+ 'state' => Utils::get_value_by($form_fields, $prefix . '[state]'),
+ 'country' => 'BR',
+ ),
+ );
+ }
+}
diff --git a/templates/checkout/thank-you.phtml b/templates/checkout/thank-you.phtml
new file mode 100644
index 00000000..3bb4a13a
--- /dev/null
+++ b/templates/checkout/thank-you.phtml
@@ -0,0 +1,43 @@
+
+
+
+ =
+ $this->setIncludeContainer()->formatElement(
+ '
' . __('Your transaction has been processed.', 'woo-pagarme-payments') . '
',
+ ['p' => []]
+ )
+ ?>
+ = $this->createBlock(
+ $this->getThankYouClass(),
+ 'pagarme.checkout.than-you',
+ [
+ 'woo_order' => $this->getWooOrder(),
+ 'pagarme_order' => $this->getPagarmeOrder(),
+ 'payment_method' => $this->getPaymentMethod()
+ ]
+ )->toHtml() ?>
+ =
+ $this->setIncludeContainer()->formatElement(
+ '
' . __('If you have any questions regarding the transaction, please contact us.', 'woo-pagarme-payments') . '
',
+ ['p' => []]
+ )
+ ?>
+
+
+
diff --git a/templates/checkout/thankyou/billet-and-card.phtml b/templates/checkout/thankyou/billet-and-card.phtml
new file mode 100644
index 00000000..05d568a8
--- /dev/null
+++ b/templates/checkout/thankyou/billet-and-card.phtml
@@ -0,0 +1,44 @@
+
+getCharges()) : ?>
+ getCharges() as $charge) : ?>
+ getTransactionType($charge) === 'credit_card') : ?>
+ = $this->setIncludeContainer()->formatElement('', ['p' => []]) ?>
+ ' . strtoupper(
+ __(
+ ucfirst($charge->status),
+ 'woo-pagarme-payments'
+ )
+ ) . ''
+ );
+ ?>
+ = $this->setIncludeContainer()->formatElement('
', ['p' => []]) ?>
+
+ getTransactionType($charge) === 'boleto') : ?>
+
+ = __('BOLETO: If you have not yet received the boleto, please click the button below to print.', 'woo-pagarme-payments'); ?>
+
+
+ = __('Print', 'woo-pagarme-payments'); ?>
+
+
+
+
diff --git a/templates/checkout/thankyou/billet.phtml b/templates/checkout/thankyou/billet.phtml
new file mode 100644
index 00000000..eb4188cc
--- /dev/null
+++ b/templates/checkout/thankyou/billet.phtml
@@ -0,0 +1,39 @@
+
+getBilletUrl()) : ?>
+
+
+
+
+
+
+
+
+ ' . strtoupper(
+ __(
+ 'Failed',
+ 'woo-pagarme-payments'
+ )
+ ) . ''
+ );
+ ?>
+
+
diff --git a/templates/checkout/thankyou/pix.phtml b/templates/checkout/thankyou/pix.phtml
new file mode 100644
index 00000000..77f6b18b
--- /dev/null
+++ b/templates/checkout/thankyou/pix.phtml
@@ -0,0 +1,42 @@
+
+getQrCodeUrl()) : ?>
+
+
+
+
+ = __('Copy Code', 'woo-pagarme-payments'); ?>
+
+ getInstructions() as $instruction) : ?>
+
+ = __($instruction, 'woo-pagarme-payments'); ?>
+
+
+
+ ',
+ esc_url($this->getFilePath('assets/images/pix-checkout-attention.svg')),
+ esc_html__('pix attention icon', 'woo-pagarme-payments')
+ );
+ ?>
+
+
+
+
+
diff --git a/templates/checkout/thankyou/voucher.phtml b/templates/checkout/thankyou/voucher.phtml
new file mode 100644
index 00000000..df88cbd4
--- /dev/null
+++ b/templates/checkout/thankyou/voucher.phtml
@@ -0,0 +1,32 @@
+
+
+ ' . strtoupper(
+ __(
+ $this->getChargeStatus() ? ucfirst($this->getChargeStatus()) : 'Failed',
+ 'woo-pagarme-payments'
+ )
+ ) . ''
+ );
+ /** phpcs:enable */
+ ?>
+
From 0a3994626f8b693fc025b5dd157cb1c5f177833e Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 16 Feb 2023 09:10:12 -0300
Subject: [PATCH 047/156] Installments
---
src/Controller/Checkout.php | 13 ++++++++-----
src/Model/CardInstallments.php | 5 ++++-
templates/checkout/form/billet.phtml | 2 +-
templates/checkout/form/card.phtml | 2 +-
templates/checkout/form/card/installments.phtml | 2 +-
templates/checkout/form/card/wallet.phtml | 2 +-
templates/checkout/form/pix.phtml | 2 +-
7 files changed, 17 insertions(+), 11 deletions(-)
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index c78cdd0c..e5d3fa4e 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -103,12 +103,15 @@ public function build_installments()
if (!Utils::is_request_ajax() || Utils::server('REQUEST_METHOD') !== 'GET') {
exit(0);
}
- $html = $this->cardInstallments->renderOptions(
- $this->cardInstallments->getInstallmentsByType(
- Utils::get('total', false),
- Utils::get('flag', false, 'esc_html')
- ));
+ $x = $this->cardInstallments->getInstallmentsByType(
+ Utils::get('total', false),
+ Utils::get('flag', false, 'esc_html')
+
+ );
+
+
+ $html = $this->cardInstallments->renderOptions($x);
echo wp_kses_no_null($html);
exit();
}
diff --git a/src/Model/CardInstallments.php b/src/Model/CardInstallments.php
index 03241d13..d38b1e04 100644
--- a/src/Model/CardInstallments.php
+++ b/src/Model/CardInstallments.php
@@ -146,7 +146,10 @@ private function calcInstallments2(array $params)
$configByFlags = $this->config->getCcInstallmentsByFlag();
extract($params, EXTR_SKIP);
if (!$flag || !isset($configByFlags['max_installment'][$flag])) {
- return sprintf('%s ', __('This card brand not is allowed on checkout.', Core::SLUG));
+ return [[
+ 'value' => 0,
+ 'content' => __('This card brand not is allowed on checkout.', Core::SLUG)
+ ]];
}
$maxInstallments = intval($configByFlags['max_installment'][$flag]);
$minAmount = Utils::str_to_float($configByFlags['installment_min_amount'][$flag]);
diff --git a/templates/checkout/form/billet.phtml b/templates/checkout/form/billet.phtml
index 192c8b69..0b3a9687 100644
--- a/templates/checkout/form/billet.phtml
+++ b/templates/checkout/form/billet.phtml
@@ -21,7 +21,7 @@ if (!function_exists('add_action')) {
*
-
+
= $this->getMessage(true) ?>
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index f5e7a93d..8ab42268 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -55,7 +55,7 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
*
-
+
diff --git a/templates/checkout/form/card/installments.phtml b/templates/checkout/form/card/installments.phtml
index b05a6b5b..bf113f7b 100644
--- a/templates/checkout/form/card/installments.phtml
+++ b/templates/checkout/form/card/installments.phtml
@@ -18,7 +18,7 @@ if (!function_exists('add_action')) {
*
-getInstallmentsComponent() ?> data-total="= esc_html($this->getCartTotals()); ?>" data-type="= $this->getInstallmentsType(); ?>" data-action="select2" data-required="true" data-element="installments" name="= $this->getElementId('installment') ?>" style="font-size: 1.41575em">
+getInstallmentsComponent() ?> data-total="= esc_html($this->getCartTotals()); ?>" data-type="= $this->getInstallmentsType(); ?>" data-action="select2" data-required="true" data-element="installments" name="= $this->getElementId('installment') ?>">
getInstallmentsType() !== 2) : ?>
render() as $options) : ?>
= $options['content'] ?>
diff --git a/templates/checkout/form/card/wallet.phtml b/templates/checkout/form/card/wallet.phtml
index 7ea04a5b..be3e382b 100644
--- a/templates/checkout/form/card/wallet.phtml
+++ b/templates/checkout/form/card/wallet.phtml
@@ -17,7 +17,7 @@ if (!function_exists('add_action')) {
?>
getConfig()->getIsEnableWallet() && $this->getPaymentInstance()->getCards()) : ?>
-
+
getPaymentInstance()->getCards() as $card) : ?>
*
-
+
showMessage() && $this->getMessage()) : ?>
From 9527add015acd94f2ecd9ee3d08ad8227d5220d8 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 17 Feb 2023 10:58:28 -0300
Subject: [PATCH 048/156] installments in muilti means
---
.../front/checkout/model/payment/card.js | 5 ++++-
src/Controller/Checkout.php | 14 ++++++--------
2 files changed, 10 insertions(+), 9 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index 5c486ffc..c93c2e81 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -5,6 +5,7 @@
const cardNumberTarget = 'input[data-element="pagarme-card-number"]';
const brandTarget = '[data-pagarmecheckout-element="brand-input"]';
const brandImgTarget = 'span[name="brand-image"]';
+ const valueTarget = '[data-pagarmecheckout-element="order-value"]';
const installmentsTarget = '[data-pagarme-component="installments"]';
const mundiCdn = 'https://cdn.mundipagg.com/assets/images/logos/brands/png/';
const limit = 10;
@@ -210,7 +211,9 @@
function updateInstallmentsElement(e) {
let elem = e.currentTarget;
- let brand = $(elem).parent().find(brandTarget).val(),
+ let brand = $(elem).parent().find(brandTarget).val();
+ let total = $(elem).closest('fieldset').find(valueTarget).val();
+ if (!total)
total = cartTotal;
if (!brand || !total)
throw "Cant update installments: invalid total and/or brand";
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index e5d3fa4e..a2f72159 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -103,15 +103,13 @@ public function build_installments()
if (!Utils::is_request_ajax() || Utils::server('REQUEST_METHOD') !== 'GET') {
exit(0);
}
+
+ $html = $this->cardInstallments->renderOptions(
+ $this->cardInstallments->getInstallmentsByType(
+ Utils::get('total', false),
+ Utils::get('flag', false, 'esc_html')
- $x = $this->cardInstallments->getInstallmentsByType(
- Utils::get('total', false),
- Utils::get('flag', false, 'esc_html')
-
- );
-
-
- $html = $this->cardInstallments->renderOptions($x);
+ ));
echo wp_kses_no_null($html);
exit();
}
From 60d747b59247d20fb99a77da67c73419603110d6 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Sun, 26 Feb 2023 12:02:36 -0300
Subject: [PATCH 049/156] :sparkles: updates
---
src/Block/AbstractBlock.php | 5 +--
.../System/Config/Page/PageSettings.php | 3 +-
src/Block/Checkout/Environment.php | 5 +--
src/Block/Checkout/Gateway.php | 10 ++----
src/Controller/Gateways/AbstractGateway.php | 35 ++++---------------
src/Model/Payment/AbstractPayment.php | 15 ++------
src/Model/Payment/BilletCard.php | 13 ++++---
7 files changed, 21 insertions(+), 65 deletions(-)
diff --git a/src/Block/AbstractBlock.php b/src/Block/AbstractBlock.php
index 8c3121ce..20eb68b4 100644
--- a/src/Block/AbstractBlock.php
+++ b/src/Block/AbstractBlock.php
@@ -32,10 +32,7 @@ public function __construct(
Json $jsonSerialize = null,
array $data = []
) {
- if (!$jsonSerialize) {
- $jsonSerialize = new Json;
- }
- $this->jsonSerialize = $jsonSerialize;
+ $this->jsonSerialize = $jsonSerialize ?? new Json;
parent::__construct($jsonSerialize, $data);
}
diff --git a/src/Block/Adminhtml/System/Config/Page/PageSettings.php b/src/Block/Adminhtml/System/Config/Page/PageSettings.php
index 76977930..292bcf53 100644
--- a/src/Block/Adminhtml/System/Config/Page/PageSettings.php
+++ b/src/Block/Adminhtml/System/Config/Page/PageSettings.php
@@ -40,8 +40,7 @@ class PageSettings
public function __construct(
string $options,
array $paymentMethods
- )
- {
+ ) {
$this->options = $options;
$this->paymentMethods = $paymentMethods;
$this->paymentGateways = $this->getPaymentGateways();
diff --git a/src/Block/Checkout/Environment.php b/src/Block/Checkout/Environment.php
index 7476dc78..b3610b73 100644
--- a/src/Block/Checkout/Environment.php
+++ b/src/Block/Checkout/Environment.php
@@ -39,11 +39,8 @@ public function __construct(
Config $config = null
) {
parent::__construct($jsonSerialize, $data);
- if (!$config) {
- $config = new Config;
- }
if (!$this->getData('config')) {
- $this->setData('config', $config);
+ $this->setData('config', $config ?? new Config);
}
}
diff --git a/src/Block/Checkout/Gateway.php b/src/Block/Checkout/Gateway.php
index e89c3493..1596f118 100644
--- a/src/Block/Checkout/Gateway.php
+++ b/src/Block/Checkout/Gateway.php
@@ -49,17 +49,11 @@ public function __construct(
)
{
parent::__construct($jsonSerialize, $data);
- if (!$config) {
- $config = new Config;
- }
- if (!$gateway) {
- $gateway = new GatewayModel;
- }
if (!$this->getData('config')) {
- $this->setData('config', $config);
+ $this->setData('config', $config ?? new Config);
}
if (!$this->getData('gateway')) {
- $this->setData('gateway', $gateway);
+ $this->setData('gateway', $gateway ?? new GatewayModel);
}
}
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index d240515f..77cd07e5 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -84,34 +84,13 @@ public function __construct(
GatewayBlock $gatewayBlock = null,
Template $template = null
) {
- if (!$gateway) {
- $gateway = new Gateway();
- }
- if (!$wooOrderRepository) {
- $wooOrderRepository = new WooOrderRepository();
- }
- if (!$postFormatter) {
- $postFormatter = new PostFormatter();
- }
- if (!$config) {
- $config = new Config();
- }
- if (!$checkout) {
- $checkout = new Checkout;
- }
- if (!$gatewayBlock) {
- $gatewayBlock = new GatewayBlock;
- }
- if (!$template) {
- $template = new Template;
- }
- $this->gatewayBlock = $gatewayBlock;
- $this->config = $config;
- $this->postFormatter = $postFormatter;
- $this->model = $gateway;
- $this->checkout = $checkout;
- $this->wooOrderRepository = $wooOrderRepository;
- $this->template = $template;
+ $this->gatewayBlock = $gatewayBlock ?? new GatewayBlock;
+ $this->config = $config ?? new Config;
+ $this->postFormatter = $postFormatter ?? new PostFormatter;
+ $this->model = $gateway ?? new Gateway;
+ $this->checkout = $checkout ?? new Checkout;
+ $this->wooOrderRepository = $wooOrderRepository ?? new WooOrderRepository;
+ $this->template = $template ?? new Template;
$this->id = 'woo-pagarme-payments-' . $this->method;
$this->method_title = $this->getPaymentMethodTitle();
$this->method_description = __('Payment Gateway Pagar.me', 'woo-pagarme-payments') . ' ' . $this->method_title;
diff --git a/src/Model/Payment/AbstractPayment.php b/src/Model/Payment/AbstractPayment.php
index 558cb02e..1bdc88dc 100644
--- a/src/Model/Payment/AbstractPayment.php
+++ b/src/Model/Payment/AbstractPayment.php
@@ -47,10 +47,7 @@ abstract class AbstractPayment
*/
public function getSuffix()
{
- if ($this->suffix) {
- return $this->suffix;
- }
- return $this->error($this->suffix);
+ return $this->suffix ?? $this->error($this->suffix);
}
/**
@@ -59,10 +56,7 @@ public function getSuffix()
*/
public function getName()
{
- if ($this->name) {
- return $this->name;
- }
- return $this->error($this->name);
+ return $this->name ?? $this->error($this->name);
}
/**
@@ -71,10 +65,7 @@ public function getName()
*/
public function getMethodCode()
{
- if ($this->code) {
- return $this->code;
- }
- return $this->error($this->code);
+ return $this->code ?? $this->error($this->code);
}
/**
diff --git a/src/Model/Payment/BilletCard.php b/src/Model/Payment/BilletCard.php
index 8fec6eef..c45d60af 100644
--- a/src/Model/Payment/BilletCard.php
+++ b/src/Model/Payment/BilletCard.php
@@ -64,7 +64,6 @@ class BilletCard extends AbstractPayment implements PaymentInterface
'save_credit_card4' => 'save_credit_card'
];
-
/** @var CreditCard */
private $creditCard;
@@ -72,15 +71,15 @@ class BilletCard extends AbstractPayment implements PaymentInterface
private $billet;
/**
- * @param CreditCard $creditCard
- * @param Billet $billet
+ * @param CreditCard|null $creditCard
+ * @param Billet|null $billet
*/
public function __construct(
- CreditCard $creditCard,
- Billet $billet
+ CreditCard $creditCard = null,
+ Billet $billet = null
) {
- $this->creditCard = $creditCard;
- $this->billet = $billet;
+ $this->creditCard = $creditCard ?? new CreditCard;
+ $this->billet = $billet ?? new Billet;
}
/**
From 78bab962b467fc620951cb538f4c25d7e5026828 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Sun, 26 Feb 2023 12:05:51 -0300
Subject: [PATCH 050/156] :bug: fix model construct
---
src/Model/Payment/TwoCards.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/Model/Payment/TwoCards.php b/src/Model/Payment/TwoCards.php
index 40e94ed3..78f2f29c 100644
--- a/src/Model/Payment/TwoCards.php
+++ b/src/Model/Payment/TwoCards.php
@@ -72,12 +72,12 @@ class TwoCards extends AbstractPayment implements PaymentInterface
private $creditCard;
/**
- * @param CreditCard $creditCard
+ * @param CreditCard|null $creditCard
*/
public function __construct(
- CreditCard $creditCard
+ CreditCard $creditCard = null
) {
- $this->creditCard = $creditCard;
+ $this->creditCard = $creditCard ?? new CreditCard;
}
/**
From b43d1ca7a2e1b524aff902208d19a9c506faa30b Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Sun, 26 Feb 2023 21:01:39 -0300
Subject: [PATCH 051/156] :sparkles: updates
---
src/Block/Checkout/ThankYou/CreditCard.php | 38 +++++++++++++++++++
src/Model/Payment/AbstractPayment.php | 2 +-
src/Model/Payment/Card.php | 15 +++-----
src/Model/Payment/Data/Billet.php | 5 +--
src/Model/Payment/Data/Card.php | 5 +--
src/Model/Payment/Data/PaymentRequest.php | 30 +++------------
src/Model/Payment/Data/Pix.php | 5 +--
templates/checkout/thankyou/credit-card.phtml | 30 +++++++++++++++
8 files changed, 84 insertions(+), 46 deletions(-)
create mode 100644 src/Block/Checkout/ThankYou/CreditCard.php
create mode 100644 templates/checkout/thankyou/credit-card.phtml
diff --git a/src/Block/Checkout/ThankYou/CreditCard.php b/src/Block/Checkout/ThankYou/CreditCard.php
new file mode 100644
index 00000000..49ca0d18
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/CreditCard.php
@@ -0,0 +1,38 @@
+getResponseData()) {
+ if (property_exists($response, 'charges')) {
+ return array_shift($response->charges);
+ }
+ }
+ return null;
+ }
+}
diff --git a/src/Model/Payment/AbstractPayment.php b/src/Model/Payment/AbstractPayment.php
index 1bdc88dc..10a5d4f1 100644
--- a/src/Model/Payment/AbstractPayment.php
+++ b/src/Model/Payment/AbstractPayment.php
@@ -202,7 +202,7 @@ protected function getMulticustomerData($type, $form_fields)
);
}
- protected function getBillingAddressFromCustomer(Customers $customer, WC_Order $wc_order)
+ protected function getBillingAddressFromCustomer($customer, WC_Order $wc_order)
{
$addressArray = isset($customer->address) ? (array) $customer->address : [];
if (empty($addressArray)) {
diff --git a/src/Model/Payment/Card.php b/src/Model/Payment/Card.php
index 1da5f142..6acd86bc 100644
--- a/src/Model/Payment/Card.php
+++ b/src/Model/Payment/Card.php
@@ -84,15 +84,12 @@ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $custo
{
$suffix = $this->payRequestCardNum === 1 ? '' : '2';
$content = parent::getPayRequestBase($wc_order, $form_fields, $customer);
- $content['voucher'] = [
- 'statement_descriptor' => $this->getConfig()->getVoucherSoftDescriptor(),
- 'credit_card' => [
- 'installments' => Utils::get_value_by($form_fields, "installments{$suffix}"),
- 'statement_descriptor' => $this->getConfig()->getCcSoftDescriptor(),
- 'capture' => $this->getConfig()->getIsActiveCapture(),
- 'card' => [
- 'billing_address' => $this->getBillingAddressFromCustomer($customer, $wc_order)
- ]
+ $content[$this->getMethodCode()] = [
+ 'installments' => Utils::get_value_by($form_fields, "installments{$suffix}"),
+ 'statement_descriptor' => $this->getConfig()->getCcSoftDescriptor(),
+ 'capture' => $this->getConfig()->getIsActiveCapture(),
+ 'card' => [
+ 'billing_address' => $this->getBillingAddressFromCustomer($customer, $wc_order)
]
];
return $this->handleCardType($form_fields, $content, $suffix);
diff --git a/src/Model/Payment/Data/Billet.php b/src/Model/Payment/Data/Billet.php
index 91c2ca7c..59d89b3d 100644
--- a/src/Model/Payment/Data/Billet.php
+++ b/src/Model/Payment/Data/Billet.php
@@ -33,10 +33,7 @@ public function __construct(
Multicustomers $multicustomers = null
) {
parent::__construct($jsonSerialize, $data);
- if (!$multicustomers) {
- $multicustomers = new Multicustomers;
- }
- $this->multicustomers = $multicustomers;
+ $this->multicustomers = $multicustomers ?? new Multicustomers;
$this->init();
}
diff --git a/src/Model/Payment/Data/Card.php b/src/Model/Payment/Data/Card.php
index f5f988df..53d8f5ba 100644
--- a/src/Model/Payment/Data/Card.php
+++ b/src/Model/Payment/Data/Card.php
@@ -42,10 +42,7 @@ public function __construct(
) {
parent::__construct($jsonSerialize, $data);
$this->num = $num;
- if (!$multicustomers) {
- $multicustomers = new Multicustomers;
- }
- $this->multicustomers = $multicustomers;
+ $this->multicustomers = $multicustomers ?? new Multicustomers;
$this->init();
}
diff --git a/src/Model/Payment/Data/PaymentRequest.php b/src/Model/Payment/Data/PaymentRequest.php
index 4fd04645..dc968bfd 100644
--- a/src/Model/Payment/Data/PaymentRequest.php
+++ b/src/Model/Payment/Data/PaymentRequest.php
@@ -60,30 +60,12 @@ public function __construct(
array $data = []
) {
parent::__construct($jsonSerialize, $data);
- if (!$shippingMethod) {
- $shippingMethod = new ShippingMethod;
- }
- if (!$cards) {
- $cards = new Cards;
- }
- if (!$shippingAddress) {
- $shippingAddress = new ShippingAddress;
- }
- if (!$billingAddress) {
- $billingAddress = new BillingAddress;
- }
- if (!$billet) {
- $billet = new Billet;
- }
- if (!$pix) {
- $pix = new Pix;
- }
- $this->cards = $cards;
- $this->shippingMethod = $shippingMethod;
- $this->shippingAddress = $shippingAddress;
- $this->billingAddress = $billingAddress;
- $this->billet = $billet;
- $this->pix = $pix;
+ $this->cards = $cards ?? new Cards;
+ $this->shippingMethod = $shippingMethod ?? new ShippingMethod;
+ $this->shippingAddress = $shippingAddress ?? new ShippingAddress;
+ $this->billingAddress = $billingAddress ?? new BillingAddress;
+ $this->billet = $billet ?? new Billet;
+ $this->pix = $pix ?? new Pix;
$this->init();
}
diff --git a/src/Model/Payment/Data/Pix.php b/src/Model/Payment/Data/Pix.php
index aec35b1e..d1fb27f1 100644
--- a/src/Model/Payment/Data/Pix.php
+++ b/src/Model/Payment/Data/Pix.php
@@ -33,10 +33,7 @@ public function __construct(
Multicustomers $multicustomers = null
) {
parent::__construct($jsonSerialize, $data);
- if (!$multicustomers) {
- $multicustomers = new Multicustomers;
- }
- $this->multicustomers = $multicustomers;
+ $this->multicustomers = $multicustomers ?? new Multicustomers;
$this->init();
}
diff --git a/templates/checkout/thankyou/credit-card.phtml b/templates/checkout/thankyou/credit-card.phtml
new file mode 100644
index 00000000..07f71b98
--- /dev/null
+++ b/templates/checkout/thankyou/credit-card.phtml
@@ -0,0 +1,30 @@
+
+
+ ' . strtoupper(
+ __(
+ $this->getCharge() ? ucfirst($this->getCharge()->status) : 'Failed',
+ 'woo-pagarme-payments'
+ )
+ ) . ''
+ );
+ ?>
+
From dd0fafae079491c7890c1b792cde09616eb2404c Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 27 Feb 2023 09:30:52 -0300
Subject: [PATCH 052/156] :sparkles: updates
---
src/Block/Checkout/ThankYou.php | 1 +
src/Block/Checkout/ThankYou/BilletAndCard.php | 2 +-
.../Checkout/ThankYou/StatusTransaction.php | 36 +++++++++++++++++++
src/Model/Payment/AbstractPayment.php | 15 +++++++-
src/Model/Payment/BilletCard.php | 6 ++--
src/Model/Payment/Card.php | 1 +
.../checkout/thankyou/billet-and-card.phtml | 5 +++
templates/checkout/thankyou/billet.phtml | 17 +++------
templates/checkout/thankyou/credit-card.phtml | 20 ++++-------
.../thankyou/status-transaction.phtml | 25 +++++++++++++
templates/checkout/thankyou/voucher.phtml | 22 ++++--------
11 files changed, 104 insertions(+), 46 deletions(-)
create mode 100644 src/Block/Checkout/ThankYou/StatusTransaction.php
create mode 100644 templates/checkout/thankyou/status-transaction.phtml
diff --git a/src/Block/Checkout/ThankYou.php b/src/Block/Checkout/ThankYou.php
index fe07b4f1..1ffdd9ee 100644
--- a/src/Block/Checkout/ThankYou.php
+++ b/src/Block/Checkout/ThankYou.php
@@ -29,6 +29,7 @@ class ThankYou extends Template
/** @var bool */
protected $container;
+
/**
* @return string
*/
diff --git a/src/Block/Checkout/ThankYou/BilletAndCard.php b/src/Block/Checkout/ThankYou/BilletAndCard.php
index cee12dd5..fbc03006 100644
--- a/src/Block/Checkout/ThankYou/BilletAndCard.php
+++ b/src/Block/Checkout/ThankYou/BilletAndCard.php
@@ -46,6 +46,6 @@ public function getTransactionType($charge)
public function getTransacion($charge)
{
- return array_shift($charge->transactions);
+ return current($charge->transactions);
}
}
diff --git a/src/Block/Checkout/ThankYou/StatusTransaction.php b/src/Block/Checkout/ThankYou/StatusTransaction.php
new file mode 100644
index 00000000..d715eb40
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/StatusTransaction.php
@@ -0,0 +1,36 @@
+getData('message') ? $this->getData('message') : __('Failed', 'woo-pagarme-payments');
+ }
+}
diff --git a/src/Model/Payment/AbstractPayment.php b/src/Model/Payment/AbstractPayment.php
index 10a5d4f1..dadba3ec 100644
--- a/src/Model/Payment/AbstractPayment.php
+++ b/src/Model/Payment/AbstractPayment.php
@@ -41,6 +41,9 @@ abstract class AbstractPayment
/** @var array */
protected $dictionary = [];
+ /** @var null */
+ protected $charOrderValue = null;
+
/**
* @return int
* @throws \Exception
@@ -164,7 +167,7 @@ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer
{
$request = [];
$content = $this->getPayRequestBase($wc_order, $form_fields, $customer);
- $content['amount'] = Utils::format_order_price($wc_order->get_total());
+ $content['amount'] = Utils::format_desnormalized_order_price($this->getAmount($wc_order, $form_fields));
if ($multicustomers = $this->getMulticustomerData($this->code, $form_fields)) {
$content['customer'] = $multicustomers;
}
@@ -172,6 +175,16 @@ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer
return $request;
}
+ protected function getAmount(WC_Order $wc_order, $form_fields)
+ {
+ $amount = $wc_order->get_total();
+ $charOrderValue = $this->charOrderValue ?? $this->code . '_value';
+ if ($value = Utils::get_value_by($form_fields, $charOrderValue)) {
+ $amount = $value;
+ }
+ return $amount;
+ }
+
protected function getMulticustomerData($type, $form_fields)
{
$prefix = "multicustomer_{$type}";
diff --git a/src/Model/Payment/BilletCard.php b/src/Model/Payment/BilletCard.php
index c45d60af..f7d55208 100644
--- a/src/Model/Payment/BilletCard.php
+++ b/src/Model/Payment/BilletCard.php
@@ -25,7 +25,7 @@
class BilletCard extends AbstractPayment implements PaymentInterface
{
/** @var string */
- const PAYMENT_CODE = 'billet-and-card';
+ const PAYMENT_CODE = 'billet_and_card';
/** @var int */
protected $suffix = 4;
@@ -109,8 +109,8 @@ public function renameFieldsPost(
public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer = null)
{
$content = [];
- $content[] = $this->billet->getPayRequest($wc_order, $form_fields, $customer);
- $content[] = $this->creditCard->getPayRequest($wc_order, $form_fields, $customer);
+ $content[] = current($this->billet->getPayRequest($wc_order, $form_fields, $customer));
+ $content[] = current($this->creditCard->getPayRequest($wc_order, $form_fields, $customer));
return $content;
}
}
diff --git a/src/Model/Payment/Card.php b/src/Model/Payment/Card.php
index 6acd86bc..76ac0f30 100644
--- a/src/Model/Payment/Card.php
+++ b/src/Model/Payment/Card.php
@@ -92,6 +92,7 @@ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $custo
'billing_address' => $this->getBillingAddressFromCustomer($customer, $wc_order)
]
];
+ $this->charOrderValue = 'card_order_value' . $suffix;
return $this->handleCardType($form_fields, $content, $suffix);
}
diff --git a/templates/checkout/thankyou/billet-and-card.phtml b/templates/checkout/thankyou/billet-and-card.phtml
index 05d568a8..d955c735 100644
--- a/templates/checkout/thankyou/billet-and-card.phtml
+++ b/templates/checkout/thankyou/billet-and-card.phtml
@@ -41,4 +41,9 @@ if (!function_exists('add_action')) {
+
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\StatusTransaction',
+ 'pagarme.checkout.thankyou.statustransaction'
+ )->toHtml() ?>
diff --git a/templates/checkout/thankyou/billet.phtml b/templates/checkout/thankyou/billet.phtml
index eb4188cc..835265c5 100644
--- a/templates/checkout/thankyou/billet.phtml
+++ b/templates/checkout/thankyou/billet.phtml
@@ -23,17 +23,8 @@ if (!function_exists('add_action')) {
-
- ' . strtoupper(
- __(
- 'Failed',
- 'woo-pagarme-payments'
- )
- ) . ''
- );
- ?>
-
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\StatusTransaction',
+ 'pagarme.checkout.thankyou.statustransaction'
+ )->toHtml() ?>
diff --git a/templates/checkout/thankyou/credit-card.phtml b/templates/checkout/thankyou/credit-card.phtml
index 07f71b98..c39dc9ab 100644
--- a/templates/checkout/thankyou/credit-card.phtml
+++ b/templates/checkout/thankyou/credit-card.phtml
@@ -15,16 +15,10 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-
- ' . strtoupper(
- __(
- $this->getCharge() ? ucfirst($this->getCharge()->status) : 'Failed',
- 'woo-pagarme-payments'
- )
- ) . ''
- );
- ?>
-
+= $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\StatusTransaction',
+ 'pagarme.checkout.thankyou.statustransaction',
+ [
+ 'message' => $this->getCharge() ? ucfirst($this->getCharge()->status) : null
+ ]
+)->toHtml() ?>
diff --git a/templates/checkout/thankyou/status-transaction.phtml b/templates/checkout/thankyou/status-transaction.phtml
new file mode 100644
index 00000000..41ddd0f5
--- /dev/null
+++ b/templates/checkout/thankyou/status-transaction.phtml
@@ -0,0 +1,25 @@
+
+
+ ' . strtoupper($this->getMessage()) . ''
+ );
+ ?>
+
diff --git a/templates/checkout/thankyou/voucher.phtml b/templates/checkout/thankyou/voucher.phtml
index df88cbd4..d8cfb21c 100644
--- a/templates/checkout/thankyou/voucher.phtml
+++ b/templates/checkout/thankyou/voucher.phtml
@@ -15,18 +15,10 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-
- ' . strtoupper(
- __(
- $this->getChargeStatus() ? ucfirst($this->getChargeStatus()) : 'Failed',
- 'woo-pagarme-payments'
- )
- ) . ''
- );
- /** phpcs:enable */
- ?>
-
+= $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\StatusTransaction',
+ 'pagarme.checkout.thankyou.statustransaction',
+ [
+ 'message' => $this->getChargeStatus() ? ucfirst($this->getChargeStatus()) : null
+ ]
+)->toHtml() ?>
From 44e305b3b78a536efdb543c2f536989532e22ce8 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 27 Feb 2023 11:33:13 -0300
Subject: [PATCH 053/156] :sparkles: updates
---
src/Block/Checkout/ThankYou/Billet.php | 23 +++++++---
src/Block/Checkout/ThankYou/BilletAndCard.php | 10 ++++-
src/Block/Checkout/ThankYou/CreditCard.php | 3 ++
src/Block/Checkout/ThankYou/Pix.php | 28 +++++++-----
.../Checkout/ThankYou/StatusTransaction.php | 2 +-
src/Block/Checkout/ThankYou/TwoCards.php | 44 +++++++++++++++++++
src/Model/Payment/TwoCards.php | 4 +-
templates/checkout/thankyou/2-cards.phtml | 27 ++++++++++++
.../checkout/thankyou/billet-and-card.phtml | 33 +++++++-------
templates/checkout/thankyou/pix.phtml | 5 +++
10 files changed, 140 insertions(+), 39 deletions(-)
create mode 100644 src/Block/Checkout/ThankYou/TwoCards.php
create mode 100644 templates/checkout/thankyou/2-cards.phtml
diff --git a/src/Block/Checkout/ThankYou/Billet.php b/src/Block/Checkout/ThankYou/Billet.php
index 75f1ef10..c037212c 100644
--- a/src/Block/Checkout/ThankYou/Billet.php
+++ b/src/Block/Checkout/ThankYou/Billet.php
@@ -26,17 +26,30 @@ class Billet extends ThankYou
*/
protected $_template = 'templates/checkout/thankyou/billet';
+
+ public function getCharge()
+ {
+ if ($charge = $this->getData('charge')) {
+ return $charge;
+ }
+ if ($response = $this->getResponseData()) {
+ if (property_exists($response, 'charges')) {
+ return current($response->charges);
+ }
+ }
+ return null;
+ }
+
/**
* @return string|null
*/
public function getBilletUrl()
{
- if ($response = $this->getResponseData()) {
- $charges = $response->charges;
- $charge = array_shift($charges);
- $transaction = array_shift($charge->transactions);
+ try {
+ $charge = $this->getCharge();
+ $transaction = current($charge->transactions);
return $transaction->boletoUrl;
- }
+ } catch (\Exception $e) {}
return null;
}
}
diff --git a/src/Block/Checkout/ThankYou/BilletAndCard.php b/src/Block/Checkout/ThankYou/BilletAndCard.php
index fbc03006..7c6ec50a 100644
--- a/src/Block/Checkout/ThankYou/BilletAndCard.php
+++ b/src/Block/Checkout/ThankYou/BilletAndCard.php
@@ -41,11 +41,17 @@ public function getCharges()
public function getTransactionType($charge)
{
- return $this->getTransacion($charge)->type;
+ try {
+ return $this->getTransacion($charge)->type;
+ } catch (\Exception $e) {}
+ return null;
}
public function getTransacion($charge)
{
- return current($charge->transactions);
+ try {
+ return current($charge->transactions);
+ } catch (\Exception $e) {}
+ return null;
}
}
diff --git a/src/Block/Checkout/ThankYou/CreditCard.php b/src/Block/Checkout/ThankYou/CreditCard.php
index 49ca0d18..51901135 100644
--- a/src/Block/Checkout/ThankYou/CreditCard.php
+++ b/src/Block/Checkout/ThankYou/CreditCard.php
@@ -28,6 +28,9 @@ class CreditCard extends ThankYou
public function getCharge()
{
+ if ($charge = $this->getData('charge')) {
+ return $charge;
+ }
if ($response = $this->getResponseData()) {
if (property_exists($response, 'charges')) {
return array_shift($response->charges);
diff --git a/src/Block/Checkout/ThankYou/Pix.php b/src/Block/Checkout/ThankYou/Pix.php
index 05a741aa..edee1b4a 100644
--- a/src/Block/Checkout/ThankYou/Pix.php
+++ b/src/Block/Checkout/ThankYou/Pix.php
@@ -31,12 +31,14 @@ class Pix extends ThankYou
*/
public function getQrCodeUrl()
{
- if ($response = $this->getResponseData()) {
- $charges = $response->charges;
- $charge = array_shift($charges);
- $transaction = array_shift($charge->transactions);
- return $transaction->postData->qr_code_url;
- }
+ try {
+ if ($response = $this->getResponseData()) {
+ $charges = $response->charges;
+ $charge = array_shift($charges);
+ $transaction = array_shift($charge->transactions);
+ return $transaction->postData->qr_code_url;
+ }
+ } catch (\Exception $e) {}
return null;
}
@@ -45,12 +47,14 @@ public function getQrCodeUrl()
*/
public function getRawQrCode()
{
- if ($response = $this->getResponseData()) {
- $charges = $response->charges;
- $charge = array_shift($charges);
- $transaction = array_shift($charge->transactions);
- return $transaction->postData->qr_code;
- }
+ try {
+ if ($response = $this->getResponseData()) {
+ $charges = $response->charges;
+ $charge = array_shift($charges);
+ $transaction = array_shift($charge->transactions);
+ return $transaction->postData->qr_code;
+ }
+ } catch (\Exception $e) {}
return null;
}
diff --git a/src/Block/Checkout/ThankYou/StatusTransaction.php b/src/Block/Checkout/ThankYou/StatusTransaction.php
index d715eb40..80065623 100644
--- a/src/Block/Checkout/ThankYou/StatusTransaction.php
+++ b/src/Block/Checkout/ThankYou/StatusTransaction.php
@@ -31,6 +31,6 @@ class StatusTransaction extends ThankYou
*/
public function getMessage()
{
- return $this->getData('message') ? $this->getData('message') : __('Failed', 'woo-pagarme-payments');
+ return $this->getData('message') ? __($this->getData('message'), 'woo-pagarme-payments') : __('Failed', 'woo-pagarme-payments');
}
}
diff --git a/src/Block/Checkout/ThankYou/TwoCards.php b/src/Block/Checkout/ThankYou/TwoCards.php
new file mode 100644
index 00000000..74c5b1a2
--- /dev/null
+++ b/src/Block/Checkout/ThankYou/TwoCards.php
@@ -0,0 +1,44 @@
+getData('charges')) {
+ return $charges;
+ }
+ if ($response = $this->getResponseData()) {
+ if (property_exists($response, 'charges')) {
+ return $response->charges;
+ }
+ }
+ return null;
+ }
+}
diff --git a/src/Model/Payment/TwoCards.php b/src/Model/Payment/TwoCards.php
index 78f2f29c..a1248237 100644
--- a/src/Model/Payment/TwoCards.php
+++ b/src/Model/Payment/TwoCards.php
@@ -106,8 +106,8 @@ public function getIsEnableWallet()
public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer = null)
{
$content = [];
- $content[] = $this->creditCard->getPayRequest($wc_order, $form_fields, $customer);
- $content[] = $this->creditCard->setPayRequestCardNum(2)->getPayRequest($wc_order, $form_fields, $customer);
+ $content[] = current($this->creditCard->getPayRequest($wc_order, $form_fields, $customer));
+ $content[] = current($this->creditCard->setPayRequestCardNum(2)->getPayRequest($wc_order, $form_fields, $customer));
return $content;
}
}
diff --git a/templates/checkout/thankyou/2-cards.phtml b/templates/checkout/thankyou/2-cards.phtml
new file mode 100644
index 00000000..53246c80
--- /dev/null
+++ b/templates/checkout/thankyou/2-cards.phtml
@@ -0,0 +1,27 @@
+
+getCharges() as $key => $charge) : ?>
+ = __('CREDIT CARD', 'woo-pagarme-payments') . ' ' . ++$key; ?>
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\CreditCard',
+ 'pagarme.checkout.thankyou.credit_card',
+ [
+ 'charge' => $charge
+ ]
+ )->toHtml() ?>
+
diff --git a/templates/checkout/thankyou/billet-and-card.phtml b/templates/checkout/thankyou/billet-and-card.phtml
index d955c735..d24d7138 100644
--- a/templates/checkout/thankyou/billet-and-card.phtml
+++ b/templates/checkout/thankyou/billet-and-card.phtml
@@ -19,26 +19,25 @@ if (!function_exists('add_action')) {
getCharges() as $charge) : ?>
getTransactionType($charge) === 'credit_card') : ?>
= $this->setIncludeContainer()->formatElement('', ['p' => []]) ?>
- ' . strtoupper(
- __(
- ucfirst($charge->status),
- 'woo-pagarme-payments'
- )
- ) . ''
- );
- ?>
+ = __('CREDIT CARD', 'woo-pagarme-payments'); ?>
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\CreditCard',
+ 'pagarme.checkout.thankyou.credit_card',
+ [
+ 'charge' => $charge
+ ]
+ )->toHtml() ?>
= $this->setIncludeContainer()->formatElement('
', ['p' => []]) ?>
getTransactionType($charge) === 'boleto') : ?>
-
- = __('BOLETO: If you have not yet received the boleto, please click the button below to print.', 'woo-pagarme-payments'); ?>
-
-
- = __('Print', 'woo-pagarme-payments'); ?>
-
+ = __('BOLETO', 'woo-pagarme-payments'); ?>
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\Billet',
+ 'pagarme.checkout.thankyou.billet',
+ [
+ 'charge' => $charge
+ ]
+ )->toHtml() ?>
diff --git a/templates/checkout/thankyou/pix.phtml b/templates/checkout/thankyou/pix.phtml
index 77f6b18b..572c7f99 100644
--- a/templates/checkout/thankyou/pix.phtml
+++ b/templates/checkout/thankyou/pix.phtml
@@ -39,4 +39,9 @@ if (!function_exists('add_action')) {
+
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Checkout\ThankYou\StatusTransaction',
+ 'pagarme.checkout.thankyou.statustransaction'
+ )->toHtml() ?>
From 4709a5a05c8bc93c1058de23dec08d9384728545 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 27 Feb 2023 22:25:48 -0300
Subject: [PATCH 054/156] :sparkles: updates
---
src/Block/Adminhtml/Sales/Order.php | 57 +++++++
.../Adminhtml/Sales/Order/AbstractMetaBox.php | 88 +++++++++++
.../Sales/Order/MetaBox/ChargeActions.php | 144 ++++++++++++++++++
.../Adminhtml/Sales/Order/MetaBox/Modal.php | 111 ++++++++++++++
.../Sales/Order/MetaBoxInterface.php | 32 ++++
src/Block/Adminhtml/Sales/Order/MetaBoxes.php | 92 +++++++++++
src/Block/Checkout/ThankYou.php | 1 -
src/Controller/Orders.php | 33 ++--
src/Model/Charge.php | 2 +-
src/Model/Gateway.php | 1 -
src/View/Orders.php | 6 +-
templates/adminhtml/sales/order.phtml | 17 +++
.../sales/order/meta-box/charge-actions.phtml | 88 +++++++++++
.../sales/order/meta-box/modal.phtml | 43 ++++++
14 files changed, 698 insertions(+), 17 deletions(-)
create mode 100644 src/Block/Adminhtml/Sales/Order.php
create mode 100644 src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php
create mode 100644 src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
create mode 100644 src/Block/Adminhtml/Sales/Order/MetaBox/Modal.php
create mode 100644 src/Block/Adminhtml/Sales/Order/MetaBoxInterface.php
create mode 100644 src/Block/Adminhtml/Sales/Order/MetaBoxes.php
create mode 100644 templates/adminhtml/sales/order.phtml
create mode 100644 templates/adminhtml/sales/order/meta-box/charge-actions.phtml
create mode 100644 templates/adminhtml/sales/order/meta-box/modal.phtml
diff --git a/src/Block/Adminhtml/Sales/Order.php b/src/Block/Adminhtml/Sales/Order.php
new file mode 100644
index 00000000..811c84de
--- /dev/null
+++ b/src/Block/Adminhtml/Sales/Order.php
@@ -0,0 +1,57 @@
+metaBoxes = $metaBoxes ?? new MetaBoxes;
+ }
+
+ /**
+ * @return array
+ */
+ public function getMetaBoxes(): array
+ {
+ return $this->metaBoxes->getMetaBoxes();
+ }
+}
diff --git a/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php b/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php
new file mode 100644
index 00000000..f43c0055
--- /dev/null
+++ b/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php
@@ -0,0 +1,88 @@
+title, 'woo-pagarme-payments');
+ }
+
+ /**
+ * @return string
+ */
+ public function getCode()
+ {
+ return $this->code;
+ }
+
+ /** return int */
+ public function getSortOrder()
+ {
+ return $this->sortOrder;
+ }
+
+ /**
+ * @param bool $include
+ * @return $this
+ */
+ public function setIncludeContainer(bool $include = true)
+ {
+ $this->container = $include;
+ return $this;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getContainer()
+ {
+ return $this->container;
+ }
+
+ /**
+ * @param string $content
+ * @param array $element
+ * @return string
+ */
+ public function formatElement(string $content, array $element)
+ {
+ if (!$this->container) {
+ $content = '';
+ }
+ return wp_kses($content, $element);
+ }
+}
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php b/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
new file mode 100644
index 00000000..acf13b1e
--- /dev/null
+++ b/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
@@ -0,0 +1,144 @@
+order = $order ?? new Order($this->getOrderId());
+ $this->charge = $charge ?? new \Woocommerce\Pagarme\Model\Charge;
+ }
+
+ /**
+ * @return Order
+ */
+ public function getOrder()
+ {
+ return $this->order;
+ }
+
+ private function getOrderId()
+ {
+ if (isset($this->getRequest()['post'])) {
+ return $this->getRequest()['post'];
+ }
+ return null;
+ }
+
+ /**
+ * @return false|Charge
+ */
+ public function getCharges()
+ {
+ return $this->getOrder()->get_charges();
+ }
+
+ /**
+ * @return array
+ */
+ private function getRequest()
+ {
+ return $_REQUEST;
+ }
+
+ public function getHeaderGrid()
+ {
+ return [
+ 'Charge ID',
+ 'Type',
+ "Total Amount",
+ 'Partially Captured',
+ 'Partially Canceled',
+ 'Partially Reversed',
+ 'Status',
+ 'Action'
+ ];
+ }
+
+ public function getTransaction($charge)
+ {
+ return current($charge->getTransactions());
+ }
+
+ /**
+ * @param $charge
+ * @param string $type
+ * @return String
+ */
+ public function getAmount($charge, string $type = '')
+ {
+ $method = 'get' . ucfirst($type) . 'Amount';
+ return $charge->{$method}() ? Utils::format_order_price_to_view($charge->{$method}()) : '-';
+ }
+
+ /**
+ * @return string[]
+ */
+ public function getTotals()
+ {
+ return [
+ '',
+ 'paid',
+ 'canceled',
+ 'refunded'
+ ];
+ }
+
+ /**
+ * @return \Woocommerce\Pagarme\Model\Charge
+ */
+ public function getChargeInstance()
+ {
+ return $this->charge;
+ }
+}
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBox/Modal.php b/src/Block/Adminhtml/Sales/Order/MetaBox/Modal.php
new file mode 100644
index 00000000..1400d717
--- /dev/null
+++ b/src/Block/Adminhtml/Sales/Order/MetaBox/Modal.php
@@ -0,0 +1,111 @@
+getTransactions());
+ }
+
+ /**
+ * @return string|void
+ */
+ public function getPartiallyType()
+ {
+ if ($this->getModalType() === self::MODAL_TYPE_CAPTURE) {
+ return 'partially captured';
+ }
+ if ($this->getModalType() === self::MODAL_TYPE_CANCEL) {
+ return 'partially canceled';
+ }
+ return '';
+ }
+
+ public function getLabelByType()
+ {
+ if ($this->getModalType() === self::MODAL_TYPE_CAPTURE) {
+ return 'Value to be captured: ';
+ }
+ if ($this->getModalType() === self::MODAL_TYPE_CANCEL) {
+ return 'Value to be canceled: ';
+ }
+ return '';
+ }
+
+ /**
+ * @return int|String|void
+ */
+ public function getActionAmount()
+ {
+ if ($this->getModalType() === self::MODAL_TYPE_CANCEL) {
+ $canceled = $this->getCharge()->getCanceledAmount() ? $this->getCharge()->getCanceledAmount() : 0;
+ $refunded = $this->getCharge()->getRefundedAmount() ? $this->getRefundedAmount()->getCanceledAmount() : 0;
+ $paid = $this->getCharge()->getPaidAmount() ? $this->getCharge()->getPaidAmount() : 0;
+ $toCancel = $this->getCharge()->getAmount();
+ if ($paid) {
+ $toCancel = $paid;
+ }
+ if ($paid && $canceled) {
+ $toCancel = $paid - $canceled;
+ }
+ if ($paid && $refunded) {
+ $toCancel = max(0, $paid - $refunded);
+ }
+ return $toCancel;
+ }
+ return 0;
+ }
+
+ /**
+ * @return String
+ */
+ public function getAmount()
+ {
+ return Utils::format_order_price_to_view($this->getCharge()->getAmount());
+ }
+
+ public function getPartiallyAmount()
+ {
+ if ($this->getModalType() === self::MODAL_TYPE_CAPTURE) {
+ return $this->getCharge()->getPaidAmount() ? Utils::format_order_price_to_view($this->getCharge()->getPaidAmount()) : ' - ';
+ }
+ if ($this->getModalType() === self::MODAL_TYPE_CANCEL) {
+ return $this->getCharge()->getCanceledAmount() ? Utils::format_order_price_to_view($this->getCharge()->getCanceledAmount()) : ' - ';
+ }
+ }
+}
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBoxInterface.php b/src/Block/Adminhtml/Sales/Order/MetaBoxInterface.php
new file mode 100644
index 00000000..edc7d8e6
--- /dev/null
+++ b/src/Block/Adminhtml/Sales/Order/MetaBoxInterface.php
@@ -0,0 +1,32 @@
+getMetaBoxesDeclared() as $class) {
+ /** @var MetaBoxInterface $metaBox */
+ $metaBox = new $class;
+ if ($metaBox->getCode() === $code) {
+ return $metaBox;
+ }
+ }
+ throw new \Exception(__('Invalid MetaBox: ', 'woo-pagarme-payments') . $code);
+ }
+
+ /**
+ * @return array
+ */
+ public function getMetaBoxesDeclared()
+ {
+ $this->autoLoad();
+ $object = [];
+ foreach (get_declared_classes() as $class) {
+ try {
+ $reflect = new ReflectionClass($class);
+ if($reflect->implementsInterface(MetaBoxInterface::class)) {
+ $explodedFileName = explode(DIRECTORY_SEPARATOR, $reflect->getFileName());
+ $object[end($explodedFileName)] = $class;
+ }
+ } catch (\ReflectionException $e) {}
+ }
+ return $object;
+ }
+
+ /**
+ * @param bool $sort
+ * @return array
+ */
+ public function getMetaBoxes(bool $sort = true)
+ {
+ $object = [];
+ foreach ($this->getMetaBoxesDeclared() as $class) {
+ /** @var MetaBoxInterface $metaBox */
+ $metaBox = new $class;
+ if ($sort) {
+ $sortOrder = $metaBox->getSortOrder();
+ do {
+ $sortOrder++;
+ } while(isset($object[$sortOrder]));
+ $object[$sortOrder] = $metaBox;
+ } else {
+ $object[] = $metaBox;
+ }
+ }
+ return $object;
+ }
+
+ /**
+ * @return void
+ */
+ private function autoLoad()
+ {
+ foreach(glob( __DIR__ . '/MetaBox/*.php') as $file) {
+ include_once($file);
+ }
+ }
+}
diff --git a/src/Block/Checkout/ThankYou.php b/src/Block/Checkout/ThankYou.php
index 1ffdd9ee..fe07b4f1 100644
--- a/src/Block/Checkout/ThankYou.php
+++ b/src/Block/Checkout/ThankYou.php
@@ -29,7 +29,6 @@ class ThankYou extends Template
/** @var bool */
protected $container;
-
/**
* @return string
*/
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index 7b93f5d1..5f3e8aa7 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -6,6 +6,7 @@
exit(0);
}
+use Woocommerce\Pagarme\Block\Adminhtml\Sales\Order as BlockOrder;
use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Setting;
use Woocommerce\Pagarme\Concrete\WoocommerceCoreSetup;
@@ -18,15 +19,19 @@ class Orders
{
private $settings;
- public function __construct()
- {
+ /** @var BlockOrder */
+ private $blockOrder;
+
+ public function __construct(
+ BlockOrder $blockOrder = null
+ ) {
$this->settings = Setting::get_instance();
$this->debug = $this->settings->is_enabled_logs();
-
+ $this->blockOrder = $blockOrder ?? new BlockOrder;
add_action('on_pagarme_order_paid', array($this, 'set_order_paid'), 20, 2);
add_action('on_pagarme_order_created', array($this, 'set_order_created'), 20, 2);
add_action('on_pagarme_order_canceled', array($this, 'set_order_canceled'), 20, 2);
- add_action('add_meta_boxes', array($this, 'add_capture_metabox'));
+ add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
}
public function create_order(WC_Order $wc_order, $payment_method, $form_fields)
@@ -79,15 +84,17 @@ public function set_order_canceled(Order $order, $body)
$order->payment_canceled();
}
- public function add_capture_metabox()
+ public function add_meta_boxes()
{
- add_meta_box(
- 'woo-pagarme-capture',
- 'Pagar.me - Captura/Cancelamento',
- array('Woocommerce\Pagarme\View\Orders', 'render_capture_metabox'),
- 'shop_order',
- 'advanced',
- 'high'
- );
+ foreach ($this->blockOrder->getMetaBoxes() as $metaBox) {
+ add_meta_box(
+ 'woo-pagarme-capture',
+ $metaBox->getTitle(),
+ [$metaBox, 'toHtml'],
+ 'shop_order',
+ 'advanced',
+ 'high'
+ );
+ }
}
}
diff --git a/src/Model/Charge.php b/src/Model/Charge.php
index dd4c6f74..d11bd518 100644
--- a/src/Model/Charge.php
+++ b/src/Model/Charge.php
@@ -220,7 +220,7 @@ public function get_i18n_status($status)
public function is_allowed_capture($charge)
{
- $transaction = array_shift($charge->getTransactions());
+ $transaction = current($charge->getTransactions());
$method = $transaction->getTransactionType()->getType();
$chargeStatus = $charge->getStatus()->getStatus();
diff --git a/src/Model/Gateway.php b/src/Model/Gateway.php
index 59fd1288..e223438f 100644
--- a/src/Model/Gateway.php
+++ b/src/Model/Gateway.php
@@ -261,7 +261,6 @@ public function getPaymentInstace($paymentCode)
foreach ($this->getPayments() as $class) {
/** @var PaymentInterface $payment */
$payment = new $class;
- $x = $payment->getMethodCode();
if ($payment->getMethodCode() === $paymentCode) {
return $payment;
}
diff --git a/src/View/Orders.php b/src/View/Orders.php
index 44423a3b..d19213c6 100644
--- a/src/View/Orders.php
+++ b/src/View/Orders.php
@@ -12,6 +12,10 @@
use Woocommerce\Pagarme\Model\Charge;
use Woocommerce\Pagarme\Model\Setting;
+/**
+ * @deprecated Class for backward compatibility. Will be removed someday.
+ * @see \Woocommerce\Pagarme\Block\Adminhtml\Sales\Order
+ */
class Orders
{
public static function render_capture_metabox($post)
@@ -72,7 +76,7 @@ public static function render_capture_metabox($post)
?>
array('class' => true)]);
?>
-
+
is_allowed_cancel($charge) ? 'disabled=disabled' : ''); ?> class="button-primary">Cancelar
diff --git a/templates/adminhtml/sales/order.phtml b/templates/adminhtml/sales/order.phtml
new file mode 100644
index 00000000..c5eae146
--- /dev/null
+++ b/templates/adminhtml/sales/order.phtml
@@ -0,0 +1,17 @@
+
diff --git a/templates/adminhtml/sales/order/meta-box/charge-actions.phtml b/templates/adminhtml/sales/order/meta-box/charge-actions.phtml
new file mode 100644
index 00000000..f3fea46c
--- /dev/null
+++ b/templates/adminhtml/sales/order/meta-box/charge-actions.phtml
@@ -0,0 +1,88 @@
+
+getCharges()) : ?>
+
+
+
+
+
+ getHeaderGrid() as $head) : ?>
+ = __($head, 'woo-pagarme-payments') ?>
+
+
+
+ getCharges() as $charge) : ?>
+
+ = $charge->getPagarmeId()->getValue() ?>
+ = strtoupper($this->getTransaction($charge)->getTransactionType()->getType()) ?>
+ getTotals() as $total) : ?>
+
+ =
+ $this->setIncludeContainer()->formatElement(
+ $this->getAmount($charge, $total),
+ ['span' => ['class' => true]]
+ )
+ ?>
+
+
+ = strtoupper(__(ucfirst($charge->getStatus()->getStatus()), 'woo-pagarme-payments')) ?>
+
+ getChargeInstance()->is_allowed_cancel($charge) ? '' : 'disabled=disabled' ?> class="button-primary">= __('Cancel', 'woo-pagarme-payments') ?>
+ getTransaction($charge)->getTransactionType()->getType() == 'credit_card') : ?>
+ getChargeInstance()->is_allowed_capture($charge) ? '' : 'disabled=disabled' ?> class="button-primary">= __('Capture', 'woo-pagarme-payments') ?>
+
+
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Adminhtml\Sales\Order\MetaBox\Modal',
+ 'pagarme.sales.order.metabox.modal.cancel',
+ [
+ 'charge' => $charge,
+ 'modal_type' => Modal::MODAL_TYPE_CANCEL
+ ]
+ )->toHtml() ?>
+ = $this->createBlock(
+ '\Woocommerce\Pagarme\Block\Adminhtml\Sales\Order\MetaBox\Modal',
+ 'pagarme.sales.order.metabox.modal.capture',
+ [
+ 'charge' => $charge,
+ 'modal_type' => Modal::MODAL_TYPE_CAPTURE
+ ]
+ )->toHtml() ?>
+
+
+
+
+
+ =
+ $this->setIncludeContainer()->formatElement(
+ '' . __('No records found.', 'woo-pagarme-payments') . '
',
+ ['p' => []]
+ )
+ ?>
+
diff --git a/templates/adminhtml/sales/order/meta-box/modal.phtml b/templates/adminhtml/sales/order/meta-box/modal.phtml
new file mode 100644
index 00000000..3661cc6a
--- /dev/null
+++ b/templates/adminhtml/sales/order/meta-box/modal.phtml
@@ -0,0 +1,43 @@
+
+getModalType()) : ?>
+
+
= AbstractGateway::PAGARME ?> - = ucfirst(__($modalType, 'woo-pagarme-payments')); ?>
+
= ucwords(__('charge id', 'woo-pagarme-payments')) ?>: = $this->getCharge()->getPagarmeId()->getValue() ?>
+
= ucwords(__('type', 'woo-pagarme-payments')) ?>: = $this->getTransaction($this->getCharge())->getTransactionType()->getType() ?>
+
= ucwords(__('total amount', 'woo-pagarme-payments')) ?>: = $this->getAmount() ?>
+
= ucwords(__($this->getPartiallyType(), 'woo-pagarme-payments')) ?>: = $this->getPartiallyAmount()?>
+
= ucwords(__('status', 'woo-pagarme-payments')) ?>: = strtoupper(__(ucfirst($this->getCharge()->getStatus()->getStatus()), 'woo-pagarme-payments')) ?>
+
+ = $this->getLabelByType() ?>
+ getCharge()->getStatus()->getStatus() === 'pending') ? 'disabled=disabled' : '' ?> />
+
+
+
+ = ucwords(__('Confirm', 'woo-pagarme-payments')) ?>
+ = ucwords(__('Cancel', 'woo-pagarme-payments')) ?>
+
+
+
From 37ecc07acc2dec866f1b16f9bd91776c35ad0bac Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 1 Mar 2023 20:57:49 -0300
Subject: [PATCH 055/156] :sparkles: updates
---
src/Block/Checkout/Field/Wallet.php | 20 +++++++++++++++++++
src/Block/Checkout/Form/Card.php | 11 ++++++----
src/Model/Checkout.php | 6 ++++++
src/Model/Payment/PostFormatter.php | 14 +++----------
templates/checkout/form/card.phtml | 9 +--------
templates/checkout/form/field/card-save.phtml | 2 +-
6 files changed, 38 insertions(+), 24 deletions(-)
diff --git a/src/Block/Checkout/Field/Wallet.php b/src/Block/Checkout/Field/Wallet.php
index 50a5f738..7e704590 100644
--- a/src/Block/Checkout/Field/Wallet.php
+++ b/src/Block/Checkout/Field/Wallet.php
@@ -12,6 +12,8 @@
namespace Woocommerce\Pagarme\Block\Checkout\Field;
use Woocommerce\Pagarme\Block\Checkout\Gateway;
+use Woocommerce\Pagarme\Model\Payment\CreditCard;
+use Woocommerce\Pagarme\Model\Payment\Voucher;
defined( 'ABSPATH' ) || exit;
@@ -55,7 +57,25 @@ public function getSequence()
*/
public function getElementId(string $id)
{
+ if ($this->getParentElementId()) {
+ return $this->getParentElementId() . '[' . $id . ']';
+ }
$id = '[wallet][' . $this->getSequence() . '][' . $id . ']';
return parent::getElementId($id);
}
+
+ /**
+ * @return bool
+ */
+ public function getIsEnableWallet()
+ {
+ $configField = [
+ CreditCard::PAYMENT_CODE => 'cc-allow-save',
+ Voucher::PAYMENT_CODE => 'voucher-card-wallet'
+ ];
+ $method = 'get' . str_replace(' ', '', ucwords(str_replace('-', ' ' ,
+ $configField[$this->getPaymentInstance()->getMethodCode()]
+ )));
+ return (bool)$this->getConfig()->{$method}();
+ }
}
diff --git a/src/Block/Checkout/Form/Card.php b/src/Block/Checkout/Form/Card.php
index f86aff6f..6e651421 100644
--- a/src/Block/Checkout/Form/Card.php
+++ b/src/Block/Checkout/Form/Card.php
@@ -100,13 +100,16 @@ public function showHolderName()
}
/**
- * @param string $id
+ * @param string|null $id
* @return string
*/
- public function getElementId(string $id)
+ public function getElementId(string $id = null)
{
- $id = '[cards][' . $this->getSequence() . '][' . $id . ']';
- return parent::getElementId($id);
+ $elementId = '[cards][' . $this->getSequence() . ']';
+ if ($id) {
+ $elementId .= '[' . $id . ']';
+ }
+ return parent::getElementId($elementId);
}
/**
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index afe88ff3..02e14ef0 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -139,12 +139,18 @@ private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
}
$fields['brand'] = $card->getBrand();
$fields['installments'] = $card->getInstallment();
+ if ($card->getSaveCard()) {
+ $fields['save_credit_card'] = 1;
+ }
} else {
if ($orderValue = $card->getOrderValue()) {
$fields['card_order_value' . $key] = $orderValue;
}
$fields['brand' . $key] = $card->getBrand();
$fields['installments' . $key] = $card->getInstallment();
+ if ($card->getSaveCard()) {
+ $fields['save_credit_card' . $key] = 1;
+ }
}
$fields['pagarmetoken' . $key] = $card->getToken();
}
diff --git a/src/Model/Payment/PostFormatter.php b/src/Model/Payment/PostFormatter.php
index 49a539b2..c9d5dfa0 100644
--- a/src/Model/Payment/PostFormatter.php
+++ b/src/Model/Payment/PostFormatter.php
@@ -46,18 +46,10 @@ public function __construct(
$paymentMethod = null,
$orderId = null
) {
- if ($paymentMethod) {
- $this->paymentMethod = $paymentMethod;
- }
- if (!$gateway) {
- $gateway = new Gateway();
- }
- if (!$paymentRequest) {
- $paymentRequest = new PaymentRequest;
- }
+ $this->paymentMethod = $paymentMethod;
+ $this->gateway = $gateway ?? new Gateway;
+ $this->paymentRequest = $paymentRequest ?? new PaymentRequest;
$this->orderId = $orderId;
- $this->gateway = $gateway;
- $this->paymentRequest = $paymentRequest;
}
/**
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index 8ab42268..65081d0d 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -34,14 +34,6 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
- = $this->createBlock(
- '\Woocommerce\Pagarme\Block\Checkout\Field\Wallet',
- 'pagarme.checkout.field.wallet',
- [
- 'payment_instance' => $this->getPaymentInstance(),
- 'sequence' => $qty
- ]
- )->toHtml() ?>
= $this->createBlock(
'\Woocommerce\Pagarme\Block\Checkout\Form\Wallet',
'pagarme.checkout.form.wallet',
@@ -100,6 +92,7 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
'pagarme.checkout.field.wallet',
[
'payment_instance' => $this->getPaymentInstance(),
+ 'parent_element_id' => $this->getElementId(),
'sequence' => $qty
]
)->toHtml() ?>
diff --git a/templates/checkout/form/field/card-save.phtml b/templates/checkout/form/field/card-save.phtml
index 62800ee9..9fde5d14 100644
--- a/templates/checkout/form/field/card-save.phtml
+++ b/templates/checkout/form/field/card-save.phtml
@@ -15,7 +15,7 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-getConfig()->getIsEnableWallet()) : ?>
+getIsEnableWallet()) : ?>
getPaymentInstance()->getCustomer()->save_credit_card, true); ?>>
From b6a53cce5ee286af3ffb6e6f2b930da1285edb21 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Fri, 3 Mar 2023 08:28:39 -0300
Subject: [PATCH 056/156] :sparkles: change checkbox to select in admin
payments gateway
---
src/Controller/Gateways/AbstractGateway.php | 11 +-
src/Controller/Gateways/BilletCreditCard.php | 6 +-
src/Controller/Gateways/CreditCard.php | 16 ++-
src/Controller/Gateways/Voucher.php | 6 +-
src/Model/Config.php | 8 ++
.../Config/PagarmeCoreConfigManagement.php | 117 ++++++++++++++++++
6 files changed, 152 insertions(+), 12 deletions(-)
create mode 100644 src/Model/Config/PagarmeCoreConfigManagement.php
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 77cd07e5..c691e492 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -18,6 +18,7 @@
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Config;
+use Woocommerce\Pagarme\Model\Config\Source\Yesno;
use Woocommerce\Pagarme\Model\Gateway;
use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Payment\PostFormatter;
@@ -69,6 +70,9 @@ abstract class AbstractGateway extends WC_Payment_Gateway
/** @var Template*/
private Template $template;
+ /** @var Yesno */
+ protected $yesnoOptions;
+
/**
* @param Gateway|null $gateway
* @param WooOrderRepository|null $wooOrderRepository
@@ -76,6 +80,7 @@ abstract class AbstractGateway extends WC_Payment_Gateway
* @param Config|null $config
*/
public function __construct(
+ Yesno $yesnoOptions = null,
Checkout $checkout = null,
Gateway $gateway = null,
WooOrderRepository $wooOrderRepository = null,
@@ -92,6 +97,7 @@ public function __construct(
$this->wooOrderRepository = $wooOrderRepository ?? new WooOrderRepository;
$this->template = $template ?? new Template;
$this->id = 'woo-pagarme-payments-' . $this->method;
+ $this->yesnoOptions = $yesnoOptions ?? new Yesno;
$this->method_title = $this->getPaymentMethodTitle();
$this->method_description = __('Payment Gateway Pagar.me', 'woo-pagarme-payments') . ' ' . $this->method_title;
$this->has_fields = false;
@@ -260,10 +266,11 @@ public function field_enabled()
{
return [
'title' => __('Enable/Disable', 'woocommerce'),
- 'type' => 'checkbox',
+ 'type' => 'select',
+ 'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable', 'woo-pagarme-payments') . ' ' .
__($this->getPaymentMethodTitle(), 'woo-pagarme-payments'),
- 'default' => $this->config->getData('enable_' . $this->method) ?? 'no',
+ 'default' => $this->config->getData('enable_' . $this->method) ?? Yesno::NO_VALUE,
];
}
diff --git a/src/Controller/Gateways/BilletCreditCard.php b/src/Controller/Gateways/BilletCreditCard.php
index e80b71fd..77592b68 100644
--- a/src/Controller/Gateways/BilletCreditCard.php
+++ b/src/Controller/Gateways/BilletCreditCard.php
@@ -11,6 +11,7 @@
namespace Woocommerce\Pagarme\Controller\Gateways;
+use Woocommerce\Pagarme\Model\Config\Source\Yesno;
use Woocommerce\Pagarme\Model\Payment\BilletCard;
defined('ABSPATH') || exit;
@@ -35,10 +36,11 @@ public function field_enabled()
{
return array(
'title' => __('Enable/Disable', 'woocommerce'),
- 'type' => 'checkbox',
+ 'type' => 'select',
+ 'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable multi-means (Boleto + Credit card)', 'woo-pagarme-payments'),
'old_name' => 'multimethods_billet_card',
- 'default' => $this->config->getData('multimethods_billet_card') ?? 'no',
+ 'default' => $this->config->getData('multimethods_billet_card') ?? Yesno::NO_VALUE,
'custom_attributes' => array(
'data-action' => 'enable-multimethods-billet-card',
'data-requires-field' => 'billet-bank',
diff --git a/src/Controller/Gateways/CreditCard.php b/src/Controller/Gateways/CreditCard.php
index 288ac42f..9e6465e3 100644
--- a/src/Controller/Gateways/CreditCard.php
+++ b/src/Controller/Gateways/CreditCard.php
@@ -11,6 +11,7 @@
namespace Woocommerce\Pagarme\Controller\Gateways;
+use Woocommerce\Pagarme\Model\Config\Source\Yesno;
use Woocommerce\Pagarme\Model\Gateway;
defined('ABSPATH') || exit;
@@ -67,10 +68,11 @@ public function field_enabled()
{
return [
'title' => __('Enable/Disable', 'woocommerce'),
- 'type' => 'checkbox',
+ 'type' => 'select',
+ 'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable credit card', 'woo-pagarme-payments'),
'old_name' => 'enable_credit_card',
- 'default' => $this->config->getData('enable_credit_card') ?? 'no',
+ 'default' => $this->config->getData('enable_credit_card') ?? Yesno::NO_VALUE,
];
}
@@ -120,9 +122,10 @@ public function field_cc_allow_save()
{
return array(
'title' => __('Card wallet', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
+ 'type' => 'select',
+ 'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable card wallet', 'woo-pagarme-payments'),
- 'default' => 'no',
+ 'default' => Yesno::NO_VALUE,
'description' => __('Allows for cards to be saved for future purchases.', 'woo-pagarme-payments'),
'desc_tip' => true,
'custom_attributes' => array(
@@ -267,9 +270,10 @@ public function antifraud_enabled()
{
return array(
'title' => __('Enable', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
+ 'type' => 'select',
+ 'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable anti fraud', 'woo-pagarme-payments'),
- 'default' => 'no',
+ 'default' => Yesno::NO_VALUE,
'custom_attributes' => array(
'data-field' => 'antifraud-enabled',
)
diff --git a/src/Controller/Gateways/Voucher.php b/src/Controller/Gateways/Voucher.php
index cabe9ed8..5e254221 100644
--- a/src/Controller/Gateways/Voucher.php
+++ b/src/Controller/Gateways/Voucher.php
@@ -11,6 +11,7 @@
namespace Woocommerce\Pagarme\Controller\Gateways;
+use Woocommerce\Pagarme\Model\Config\Source\Yesno;
use Woocommerce\Pagarme\Model\Payment\Voucher\Brands;
use Woocommerce\Pagarme\Model\Payment\Voucher\BrandsInterface;
@@ -105,9 +106,10 @@ public function field_voucher_card_wallet()
return [
'title' => __('Card Wallet', 'woo-pagarme-payments'),
'desc_tip' => __('Enable Card Wallet', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
+ 'type' => 'select',
'label' => __('Card Wallet', 'woo-pagarme-payments'),
- 'default' => 'no',
+ 'options' => $this->yesnoOptions->toArray(),
+ 'default' => Yesno::NO_VALUE,
'custom_attributes' => [
'data-field' => 'voucher-card-wallet',
]
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 5710f254..876d43fb 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -13,6 +13,7 @@
use Pagarme\Core\Hub\Services\HubIntegrationService;
use Woocommerce\Pagarme\Core;
+use Woocommerce\Pagarme\Model\Config\PagarmeCoreConfigManagement;
use Woocommerce\Pagarme\Model\Config\Source\EnvironmentsTypes;
use Woocommerce\Pagarme\Model\Data\DataObject;
use Woocommerce\Pagarme\Model\Serialize\Serializer\Json;
@@ -29,14 +30,20 @@ class Config extends DataObject
/** @var string */
const HUB_SANDBOX_ENVIRONMENT = 'Sandbox';
+ /** @var PagarmeCoreConfigManagement */
+ private $pagarmeCoreConfigManagement;
+
/**
+ * @param PagarmeCoreConfigManagement|null $pagarmeCoreConfigManagement
* @param Json|null $jsonSerialize
* @param array $data
*/
public function __construct(
+ PagarmeCoreConfigManagement $pagarmeCoreConfigManagement = null,
Json $jsonSerialize = null,
array $data = []
) {
+ $this->pagarmeCoreConfigManagement = $pagarmeCoreConfigManagement ?? new PagarmeCoreConfigManagement;
parent::__construct($jsonSerialize, $data);
$this->init();
}
@@ -82,6 +89,7 @@ public function save(Config $config = null)
$config = $this;
}
update_option($this->getOptionKey(), $config->getData());
+ $this->pagarmeCoreConfigManagement->update($config);
}
/**
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
new file mode 100644
index 00000000..b8d038bf
--- /dev/null
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -0,0 +1,117 @@
+pagarmeCoreConfigFactory = $pagarmeCoreConfigFactory ?? new ConfigurationFactory;
+ $this->jsonSerialize = $jsonSerialize ?? new Json;
+ $this->dataObject = $dataObject ?? new DataObject;
+ }
+
+ public function update(Config $config)
+ {
+ $data = $config->getData();
+ foreach ($data as $key => $datum) {
+ unset($data[$key]);
+ $key = $method = $this->getMethod($key, '');
+ if (method_exists($this, 'convertKey' . $method)) {
+ $key = $this->{'convertKey' . $method}();
+ }
+ $data[lcfirst($key)] = $datum;
+ }
+ $this->setCardConfigs($data);
+ $data = $this->pagarmeCoreConfigFactory->createFromJsonData(
+ $this->jsonSerialize->serialize($data)
+ );
+ $this->pagarmeCoreConfigRepository = $this->pagarmeCoreConfigRepository ?? new ConfigurationRepository;
+ $this->pagarmeCoreConfigRepository->save($data);
+ }
+
+ public function setCardConfigs(&$data)
+ {
+ $data['cardConfigs'] = [];
+ }
+
+ /**
+ * @param string $value
+ * @param string $type
+ * @return string
+ */
+ private function getMethod(string $value, string $type = 'set')
+ {
+ return $type . str_replace(' ', '', ucwords(str_replace('_', ' ', $value)));
+ }
+
+ /**
+ * @return string
+ */
+ public function convertKeyCcAllowSave()
+ {
+ return 'saveCards';
+ }
+
+ /**
+ * @return string
+ */
+ public function convertKeyVoucherCardWallet()
+ {
+ return 'saveVoucherCards';
+ }
+
+ /**
+ * @return string
+ */
+ public function convertKeyEnableCreditCard()
+ {
+ return 'saveVoucherCards';
+ }
+}
From 5f2a1141f6c5a167b66154226d93a95a3f1a1df1 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 2 Mar 2023 09:15:58 -0300
Subject: [PATCH 057/156] Refactor JS
---
.../checkout/model/payment/order-value.js | 142 +++++++++---------
assets/javascripts/vendor/jquery.mask.js | 124 +++++++++++----
src/Block/AbstractBlock.php | 47 +++++-
src/Block/Checkout/Form/Card.php | 5 +
src/Block/Checkout/Form/Multicustomers.php | 5 +
src/Block/Checkout/Payment/BilletAndCard.php | 5 +
src/Block/Checkout/Payment/TwoCards.php | 5 +
.../WoocommercePlatformOrderDecorator.php | 2 +-
src/Controller/Checkout.php | 2 +-
src/Controller/Gateways/AbstractGateway.php | 2 +-
src/Core.php | 23 ++-
templates/checkout/form/card.phtml | 7 +-
templates/checkout/form/multicustomers.php | 1 -
templates/checkout/payment/2-cards.phtml | 9 +-
.../checkout/payment/billet-and-card.phtml | 6 +-
templates/checkout/payment/voucher.phtml | 1 -
16 files changed, 263 insertions(+), 123 deletions(-)
mode change 100644 => 100755 assets/javascripts/vendor/jquery.mask.js
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index e7835d4d..4183fe08 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -1,78 +1,76 @@
-(function ($) {
- const cardValueTarget = 'input[data-pagarmecheckout-element=order-value]';
- let pagarme = {
- keyEventHandler: function (e) {
- fillAnotherInput(e);
- },
- getCartTotals: function () {
- return cartTotal;
- }
- }
- async function fillAnotherInput(e) {
- let input = $(e.currentTarget);
- const empty = '';
- let nextInput = input.closest('fieldset').siblings('fieldset').find('input').filter(':visible:first');
- if (nextInput.length === 0) {
- nextInput = input.closest('div').siblings('div').find('input').first();
- }
- let value = await formatValue(e.currentTarget.value);
- if (!value) {
- return;
- }
- let total = await formatValue(pagarme.getCartTotals());
- if (value > total) {
- showError('O valor não pode ser maior que total do pedido!');
- input.val(empty);
- nextInput.val(empty);
- return;
- }
- nextInput.val(await formatValue((total - value), false));
- input.val(await formatValue(value, false));
+const cardValueTarget = 'input[data-pagarmecheckout-element="order-value"]';
+const firstCardValue = '[data-pagarmecheckout-card-num="1"]';
+let pagarmeOrderValue = {
+ cardValueTarget: 'input[data-pagarmecheckout-element="order-value"]',
+ firstCardValue: '[data-pagarmecheckout-card-num="1"]',
+ start: function () {
+ this.addsMask();
+ this.addEventListener();
+ // let e = jQuery(cardValueTarget + firstCardValue).val(10);
+ },
+ fillAnotherInput: async function (e) {
+ let input = jQuery(e.currentTarget);
+ const empty = '';
+ let nextInput = input.closest('fieldset').siblings('fieldset').find('input').filter(':visible:first');
+ if (nextInput.length === 0) {
+ nextInput = input.closest('div').siblings('div').find('input').first();
}
-
- function formatValue(value, raw = true) {
- return new Promise((resolve) => {
- if (raw) {
- if (typeof value !== 'string') {
- value = value.toString();
- }
- value = value.replace('.', '');
- resolve(parseFloat(value.replace(',', '.')));
- } else {
- if (typeof value === 'string') {
- value = parseFloat(value);
- }
- resolve(value.toFixed(2).replace('.', ','));
- }
- });
+ let total = await this.formatValue(this.getCartTotals());
+ let value = await this.formatValue(e.currentTarget.value);
+ if (!value) {
+ value = await this.formatValue(this.getCartTotals() / 2);
}
-
- function addsMask() {
- $(cardValueTarget).mask('#.##0,00', {
- reverse: true
- });
+ if (value > total) {
+ this.showError('O valor não pode ser maior que total do pedido!');
+ input.val(empty);
+ nextInput.val(empty);
+ return;
}
-
- function showError(text)
- {
- const message = {
- type: 'error',
- html: text,
- allowOutsideClick: false
- };
- try {
- swal(message);
- } catch (e) {
- new swal(message);
+ nextInput.val(await this.formatValue((total - value), false));
+ input.val(await this.formatValue(value, false));
+ pagarmeCard.updateInstallmentsElement(e);
+ },
+ formatValue: function (value, raw = true) {
+ return new Promise((resolve) => {
+ if (raw) {
+ if (typeof value !== 'string') {
+ value = value.toString();
+ }
+ resolve(parseFloat(value.replace(',', '.')));
+ } else {
+ if (typeof value === 'string') {
+ value = parseFloat(value);
+ }
+ resolve(value.toFixed(2).replace('.', ','));
}
- }
-
- $( document ).ready(function() {
- addsMask();
});
-
- $(cardValueTarget).on('blur', function (e) {
- pagarme.keyEventHandler(e);
+ },
+ addsMask: function () {
+ jQuery(this.cardValueTarget).mask('#.##0,00', {
+ reverse: true
+ });
+ },
+ showError: function (text) {
+ const message = {
+ type: 'error',
+ html: text,
+ allowOutsideClick: false
+ };
+ try {
+ swal(message);
+ } catch (e) {
+ new swal(message);
+ }
+ },
+ addEventListener: function () {
+ jQuery(this.cardValueTarget).on('change', function (e) {
+ pagarmeOrderValue.keyEventHandler(e);
});
- } (jQuery)
-);
+ },
+ keyEventHandler: function (e) {
+ this.fillAnotherInput(e);
+ },
+ getCartTotals: function () {
+ return cartTotal;
+ }
+}
diff --git a/assets/javascripts/vendor/jquery.mask.js b/assets/javascripts/vendor/jquery.mask.js
old mode 100644
new mode 100755
index e8d1ed58..7e0216cb
--- a/assets/javascripts/vendor/jquery.mask.js
+++ b/assets/javascripts/vendor/jquery.mask.js
@@ -1,11 +1,11 @@
/**
* jquery.mask.js
- * @version: v1.14.10
+ * @version: v1.14.16
* @author: Igor Escobar
*
- * Created by Igor Escobar on 2012-03-10. Please report any bug at http://blog.igorescobar.com
+ * Created by Igor Escobar on 2012-03-10. Please report any bug at github.com/igorescobar/jQuery-Mask-Plugin
*
- * Copyright (c) 2012 Igor Escobar http://blog.igorescobar.com
+ * Copyright (c) 2012 Igor Escobar http://igorescobar.com
*
* The MIT License (http://www.opensource.org/licenses/mit-license.php)
*
@@ -35,21 +35,20 @@
/* jshint maxcomplexity:17 */
/* global define */
-'use strict';
-
// UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.
-// https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js
+// https://github.com/umdjs/umd/blob/master/templates/jqueryPlugin.js
(function (factory, jQuery, Zepto) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
- } else if (typeof exports === 'object') {
+ } else if (typeof exports === 'object' && typeof Meteor === 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery || Zepto);
}
}(function ($) {
+ 'use strict';
var Mask = function (el, mask, options) {
@@ -100,6 +99,8 @@
.on('keydown.mask', function(e) {
el.data('mask-keycode', e.keyCode || e.which);
el.data('mask-previus-value', el.val());
+ el.data('mask-previus-caret-pos', p.getCaret());
+ p.maskDigitPosMapOld = p.maskDigitPosMap;
})
.on($.jMaskGlobals.useInput ? 'input.mask' : 'keyup.mask', p.behaviour)
.on('paste.mask drop.mask', function() {
@@ -186,26 +187,64 @@
return r;
},
- calculateCaretPosition: function(caretPos, newVal) {
- var newValL = newVal.length,
- oValue = el.data('mask-previus-value') || '',
- oValueL = oValue.length;
+ calculateCaretPosition: function(oldVal) {
+ var newVal = p.getMasked(),
+ caretPosNew = p.getCaret();
+ if (oldVal !== newVal) {
+ var caretPosOld = el.data('mask-previus-caret-pos') || 0,
+ newValL = newVal.length,
+ oldValL = oldVal.length,
+ maskDigitsBeforeCaret = 0,
+ maskDigitsAfterCaret = 0,
+ maskDigitsBeforeCaretAll = 0,
+ maskDigitsBeforeCaretAllOld = 0,
+ i = 0;
+
+ for (i = caretPosNew; i < newValL; i++) {
+ if (!p.maskDigitPosMap[i]) {
+ break;
+ }
+ maskDigitsAfterCaret++;
+ }
+
+ for (i = caretPosNew - 1; i >= 0; i--) {
+ if (!p.maskDigitPosMap[i]) {
+ break;
+ }
+ maskDigitsBeforeCaret++;
+ }
- // edge cases when erasing digits
- if (el.data('mask-keycode') === 8 && oValue !== newVal) {
- caretPos = caretPos - (newVal.slice(0, caretPos).length - oValue.slice(0, caretPos).length);
+ for (i = caretPosNew - 1; i >= 0; i--) {
+ if (p.maskDigitPosMap[i]) {
+ maskDigitsBeforeCaretAll++;
+ }
+ }
+
+ for (i = caretPosOld - 1; i >= 0; i--) {
+ if (p.maskDigitPosMapOld[i]) {
+ maskDigitsBeforeCaretAllOld++;
+ }
+ }
- // edge cases when typing new digits
- } else if (oValue !== newVal) {
// if the cursor is at the end keep it there
- if (caretPos >= oValueL) {
- caretPos = newValL;
- } else {
- caretPos = caretPos + (newVal.slice(0, caretPos).length - oValue.slice(0, caretPos).length);
+ if (caretPosNew > oldValL) {
+ caretPosNew = newValL * 10;
+ } else if (caretPosOld >= caretPosNew && caretPosOld !== oldValL) {
+ if (!p.maskDigitPosMapOld[caretPosNew]) {
+ var caretPos = caretPosNew;
+ caretPosNew -= maskDigitsBeforeCaretAllOld - maskDigitsBeforeCaretAll;
+ caretPosNew -= maskDigitsBeforeCaret;
+ if (p.maskDigitPosMap[caretPosNew]) {
+ caretPosNew = caretPos;
+ }
+ }
+ }
+ else if (caretPosNew > caretPosOld) {
+ caretPosNew += maskDigitsBeforeCaretAll - maskDigitsBeforeCaretAllOld;
+ caretPosNew += maskDigitsAfterCaret;
}
}
-
- return caretPos;
+ return caretPosNew;
},
behaviour: function(e) {
e = e || window.event;
@@ -214,12 +253,15 @@
var keyCode = el.data('mask-keycode');
if ($.inArray(keyCode, jMask.byPassKeys) === -1) {
- var newVal = p.getMasked(),
- caretPos = p.getCaret();
+ var newVal = p.getMasked(),
+ caretPos = p.getCaret(),
+ oldVal = el.data('mask-previus-value') || '';
- setTimeout(function(caretPos, newVal) {
- p.setCaret(p.calculateCaretPosition(caretPos, newVal));
- }, 10, caretPos, newVal);
+ // this is a compensation to devices/browsers that don't compensate
+ // caret positioning the right way
+ setTimeout(function() {
+ p.setCaret(p.calculateCaretPosition(oldVal));
+ }, $.jMaskGlobals.keyStrokeCompensation);
p.val(newVal);
p.setCaret(caretPos);
@@ -233,6 +275,8 @@
v = 0, valLen = value.length,
offset = 1, addMethod = 'push',
resetPos = -1,
+ maskDigitCount = 0,
+ maskDigitPosArr = [],
lastMaskChar,
check;
@@ -264,7 +308,7 @@
if (translation.recursive) {
if (resetPos === -1) {
resetPos = m;
- } else if (m === lastMaskChar) {
+ } else if (m === lastMaskChar && m !== resetPos) {
m = resetPos - offset;
}
@@ -277,6 +321,7 @@
// matched the last untranslated (raw) mask character that we encountered
// likely an insert offset the mask character from the last entry; fall
// through and only increment v
+ maskDigitCount--;
lastUntranslatedMaskChar = undefined;
} else if (translation.optional) {
m += offset;
@@ -295,9 +340,12 @@
}
if (valDigit === maskDigit) {
+ maskDigitPosArr.push(v);
v += offset;
} else {
lastUntranslatedMaskChar = maskDigit;
+ maskDigitPosArr.push(v + maskDigitCount);
+ maskDigitCount++;
}
m += offset;
@@ -309,7 +357,16 @@
buf.push(lastMaskCharDigit);
}
- return buf.join('');
+ var newVal = buf.join('');
+ p.mapMaskdigitPositions(newVal, maskDigitPosArr, valLen);
+ return newVal;
+ },
+ mapMaskdigitPositions: function(newVal, maskDigitPosArr, valLen) {
+ var maskDiff = options.reverse ? newVal.length - valLen : 0;
+ p.maskDigitPosMap = {};
+ for (var i = 0; i < maskDigitPosArr.length; i++) {
+ p.maskDigitPosMap[maskDigitPosArr[i] + maskDiff] = 1;
+ }
},
callbacks: function (e) {
var val = p.val(),
@@ -338,6 +395,12 @@
jMask.options = options;
jMask.remove = function() {
var caret = p.getCaret();
+ if (jMask.options.placeholder) {
+ el.removeAttr('placeholder');
+ }
+ if (el.data('mask-maxlength')) {
+ el.removeAttr('maxlength');
+ }
p.destroyEvents();
p.val(jMask.getCleanVal());
p.setCaret(caret);
@@ -392,7 +455,7 @@
}
if (maxlength) {
- el.attr('maxlength', mask.length);
+ el.attr('maxlength', mask.length).data('mask-maxlength', true);
}
p.destroyEvents();
@@ -511,6 +574,7 @@
dataMask: true,
watchInterval: 300,
watchInputs: true,
+ keyStrokeCompensation: 10,
// old versions of chrome dont work great with input event
useInput: !/Chrome\/[2-4][0-9]|SamsungBrowser/.test(window.navigator.userAgent) && eventSupported('input'),
watchDataMask: false,
diff --git a/src/Block/AbstractBlock.php b/src/Block/AbstractBlock.php
index 20eb68b4..ed32856c 100644
--- a/src/Block/AbstractBlock.php
+++ b/src/Block/AbstractBlock.php
@@ -7,14 +7,15 @@
* @link https://pagar.me
*/
-declare( strict_types=1 );
+declare(strict_types=1);
namespace Woocommerce\Pagarme\Block;
+use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Model\Data\DataObject;
use Woocommerce\Pagarme\Model\Serialize\Serializer\Json;
-defined( 'ABSPATH' ) || exit;
+defined('ABSPATH') || exit;
/**
* Class AbstractBlock
@@ -28,12 +29,17 @@ abstract class AbstractBlock extends DataObject
/** @var Json */
protected $jsonSerialize;
+ /** @var Json */
+ protected $scripts;
+
public function __construct(
- Json $jsonSerialize = null,
+ Json $jsonSerialize = null,
array $data = []
- ) {
+ )
+ {
$this->jsonSerialize = $jsonSerialize ?? new Json;
parent::__construct($jsonSerialize, $data);
+ $this->enqueue_scripts();
}
/**
@@ -71,4 +77,37 @@ protected function _toHtml()
{
return '';
}
+
+ public function enqueue_scripts($scripts = null)
+ {
+ if (!$scripts) {
+ $scripts = $this->scripts;
+ }
+ if (is_null($scripts)) {
+ return;
+ }
+ if (!is_array($scripts)) {
+ $scripts = [$scripts];
+ }
+ foreach ($scripts as $script) {
+ $fileName = explode('/', $script);
+ $id = "pagarme_scripts_" . end($fileName);
+ wp_enqueue_script(
+ $id,
+ $this->getScriptUrl($script),
+ array('jquery', 'jquery.mask'),
+ $this->getScriptVer($script), true
+ );
+ }
+ }
+
+ public function getScriptUrl($jsFileName)
+ {
+ return Core::plugins_url('assets/javascripts/front/' . $jsFileName . '.js');
+ }
+
+ public function getScriptVer($jsFileName)
+ {
+ return Core::filemtime('assets/javascripts/front/' . $jsFileName . '.js');
+ }
}
diff --git a/src/Block/Checkout/Form/Card.php b/src/Block/Checkout/Form/Card.php
index 6e651421..f3bda9b5 100644
--- a/src/Block/Checkout/Form/Card.php
+++ b/src/Block/Checkout/Form/Card.php
@@ -28,6 +28,11 @@ class Card extends Gateway
*/
protected $_template = 'templates/checkout/form/card';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/payment/card', 'checkout/model/payment/card/tokenize'];
+
/** @var int */
protected $sequence = 1;
diff --git a/src/Block/Checkout/Form/Multicustomers.php b/src/Block/Checkout/Form/Multicustomers.php
index c453c7ed..fb0287eb 100644
--- a/src/Block/Checkout/Form/Multicustomers.php
+++ b/src/Block/Checkout/Form/Multicustomers.php
@@ -30,6 +30,11 @@ class Multicustomers extends Gateway
*/
protected $_template = 'templates/checkout/form/multicustomers';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/multicustomers'];
+
/** @var int */
protected $sequence = 1;
diff --git a/src/Block/Checkout/Payment/BilletAndCard.php b/src/Block/Checkout/Payment/BilletAndCard.php
index ab908578..22bb30b2 100644
--- a/src/Block/Checkout/Payment/BilletAndCard.php
+++ b/src/Block/Checkout/Payment/BilletAndCard.php
@@ -26,6 +26,11 @@ class BilletAndCard extends Gateway
*/
protected $_template = 'templates/checkout/payment/billet-and-card';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/payment/order-value'];
+
/**
* @return int
*/
diff --git a/src/Block/Checkout/Payment/TwoCards.php b/src/Block/Checkout/Payment/TwoCards.php
index 88cb885d..04ed2e5a 100644
--- a/src/Block/Checkout/Payment/TwoCards.php
+++ b/src/Block/Checkout/Payment/TwoCards.php
@@ -26,6 +26,11 @@ class TwoCards extends Gateway
*/
protected $_template = 'templates/checkout/payment/2-cards';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/payment/order-value'];
+
/**
* @return int
*/
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index 407c72bd..956d3446 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -1001,7 +1001,7 @@ private function extractPaymentDataFromPix(&$paymentData)
$paymentData[$pixDataIndex] = [];
}
- if ($this->formData["enable_multicustomers_pix"]) {
+ if (isset($this->formData["enable_multicustomers_pix"]) && $this->formData["enable_multicustomers_pix"]) {
$newPaymentData->customer = $this->extractMultibuyerData(
'pix'
);
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index a2f72159..18a95687 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -103,7 +103,7 @@ public function build_installments()
if (!Utils::is_request_ajax() || Utils::server('REQUEST_METHOD') !== 'GET') {
exit(0);
}
-
+
$html = $this->cardInstallments->renderOptions(
$this->cardInstallments->getInstallmentsByType(
Utils::get('total', false),
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index c691e492..1b214a7c 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -68,7 +68,7 @@ abstract class AbstractGateway extends WC_Payment_Gateway
private $gatewayBlock;
/** @var Template*/
- private Template $template;
+ private $template;
/** @var Yesno */
protected $yesnoOptions;
diff --git a/src/Core.php b/src/Core.php
index 4b7939fd..87b5fe09 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -119,13 +119,13 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
{
$id = "{$type}-script-" . self::SLUG;
- wp_enqueue_script(
- $id,
- self::plugins_url("assets/javascripts/{$type}/built.js"),
- array_merge(array('jquery'), $deps),
- self::filemtime("assets/javascripts/{$type}/built.js"),
- true
- );
+// wp_enqueue_script(
+// $id,
+// self::plugins_url("assets/javascripts/{$type}/built.js"),
+// array_merge(array('jquery'), $deps),
+// self::filemtime("assets/javascripts/{$type}/built.js"),
+// true
+// );
if ($type == 'front') {
wp_enqueue_script(
@@ -133,7 +133,14 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
self::plugins_url("assets/javascripts/vendor/sweetalert2.js"),
array_merge(array('jquery'), $deps),
self::filemtime("assets/javascripts/vendor/sweetalert2.js"),
- true
+ false
+ );
+ wp_enqueue_script(
+ 'jquery.mask',
+ self::plugins_url("assets/javascripts/vendor/jquery.mask.js"),
+ array('jquery'),
+ '1.14.16',
+ false
);
}
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index 65081d0d..02c3bd54 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -119,5 +119,8 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
-
-
+
diff --git a/templates/checkout/form/multicustomers.php b/templates/checkout/form/multicustomers.php
index 23ed1651..50e6c51a 100644
--- a/templates/checkout/form/multicustomers.php
+++ b/templates/checkout/form/multicustomers.php
@@ -82,4 +82,3 @@
-
diff --git a/templates/checkout/payment/2-cards.phtml b/templates/checkout/payment/2-cards.phtml
index 33b94464..f2a6bc5b 100644
--- a/templates/checkout/payment/2-cards.phtml
+++ b/templates/checkout/payment/2-cards.phtml
@@ -23,4 +23,11 @@ if (!function_exists('add_action')) {
'qty_cards' => $this->getQtyCards()
]
)->toHtml() ?>
-
+
+
+
diff --git a/templates/checkout/payment/billet-and-card.phtml b/templates/checkout/payment/billet-and-card.phtml
index a85e03da..9cc8f683 100644
--- a/templates/checkout/payment/billet-and-card.phtml
+++ b/templates/checkout/payment/billet-and-card.phtml
@@ -36,4 +36,8 @@ if (!function_exists('add_action')) {
'multicustomers_sequence' => 2
]
)->toHtml() ?>
-
+
diff --git a/templates/checkout/payment/voucher.phtml b/templates/checkout/payment/voucher.phtml
index 303d4c69..d0b3b6aa 100644
--- a/templates/checkout/payment/voucher.phtml
+++ b/templates/checkout/payment/voucher.phtml
@@ -23,4 +23,3 @@ if (!function_exists('add_action')) {
'qty_cards' => $this->getQtyCards()
]
)->toHtml() ?>
-
From 075ca72682275aec6fd927dc9f664bce9bd20115 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 2 Mar 2023 09:48:36 -0300
Subject: [PATCH 058/156] Bug
---
templates/checkout/form/card.phtml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index 02c3bd54..14a5d6e2 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -120,7 +120,7 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
From 1ad75b5ca25156409cad2379dcd38c2aae99de16 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 2 Mar 2023 12:35:18 -0300
Subject: [PATCH 059/156] Bug
---
src/Concrete/WoocommercePlatformOrderDecorator.php | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index 956d3446..2dbc5727 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -768,7 +768,7 @@ private function extractBasePaymentData()
$newPaymentData->amount = $amount;
- if ($this->formData["enable_multicustomers_card"]) {
+ if (isset($this->formData["enable_multicustomers_card"]) && $this->formData["enable_multicustomers_card"]) {
$newPaymentData->customer = $this->extractMultibuyerData(
'card'
);
@@ -823,9 +823,8 @@ private function extractPaymentDataFromTwoCreditCards(&$paymentData)
$multiCustomerFlag = empty($index) ? "enable_multicustomers_card1"
: "enable_multicustomers_card2";
if ($this->formData[$multiCustomerFlag]) {
- $card = array_pop(
- explode("_", $multiCustomerFlag)
- );
+ $flag = explode("_", $multiCustomerFlag)
+ $card = array_pop($flag);
$newPaymentData->customer = $this->extractMultibuyerData(
$card
From 85c5703ce9cf0da3de0d193f859a0844867d2b0a Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Fri, 3 Mar 2023 09:28:26 -0300
Subject: [PATCH 060/156] :sparkles: updates
---
.../Config/PagarmeCoreConfigManagement.php | 34 ++++++++++++++++++-
1 file changed, 33 insertions(+), 1 deletion(-)
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index b8d038bf..48456865 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -107,11 +107,43 @@ public function convertKeyVoucherCardWallet()
return 'saveVoucherCards';
}
+ /**
+ * @return string
+ */
+ public function convertKeyAntifraudMinValue()
+ {
+ return 'antifraudMinAmount';
+ }
+
+ /**
+ * @return string
+ */
+ public function convertKeyEnableBillet()
+ {
+ return 'boletoEnabled';
+ }
+
/**
* @return string
*/
public function convertKeyEnableCreditCard()
{
- return 'saveVoucherCards';
+ return 'creditCardEnabled';
+ }
+
+ /**
+ * @return string
+ */
+ public function convertKeyMultimethods2Cards()
+ {
+ return 'twoCreditCardsEnabled';
+ }
+
+ /**
+ * @return string
+ */
+ public function convertKeyMultimethodsBilletCard()
+ {
+ return 'boletoCreditCardEnabled';
}
}
From 72762fadc301b3fc9d29435c7199697c77b99e08 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Fri, 3 Mar 2023 13:27:41 -0300
Subject: [PATCH 061/156] :sparkles: updates
---
src/Controller/Gateways/AbstractGateway.php | 4 ++--
src/Controller/Gateways/BilletCreditCard.php | 4 ++--
src/Controller/Gateways/CreditCard.php | 4 ++--
src/Controller/Gateways/Voucher.php | 4 ++--
src/Model/Config/Source/AbstractOptions.php | 18 ++++++++++++++++++
5 files changed, 26 insertions(+), 8 deletions(-)
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 1b214a7c..fd9e3132 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -267,10 +267,10 @@ public function field_enabled()
return [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(),
'label' => __('Enable', 'woo-pagarme-payments') . ' ' .
__($this->getPaymentMethodTitle(), 'woo-pagarme-payments'),
- 'default' => $this->config->getData('enable_' . $this->method) ?? Yesno::NO_VALUE,
+ 'default' => $this->config->getData('enable_' . $this->method) ?? strtolower(Yesno::NO),
];
}
diff --git a/src/Controller/Gateways/BilletCreditCard.php b/src/Controller/Gateways/BilletCreditCard.php
index 77592b68..907f170c 100644
--- a/src/Controller/Gateways/BilletCreditCard.php
+++ b/src/Controller/Gateways/BilletCreditCard.php
@@ -37,10 +37,10 @@ public function field_enabled()
return array(
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(),
'label' => __('Enable multi-means (Boleto + Credit card)', 'woo-pagarme-payments'),
'old_name' => 'multimethods_billet_card',
- 'default' => $this->config->getData('multimethods_billet_card') ?? Yesno::NO_VALUE,
+ 'default' => $this->config->getData('multimethods_billet_card') ?? strtolower(Yesno::NO),
'custom_attributes' => array(
'data-action' => 'enable-multimethods-billet-card',
'data-requires-field' => 'billet-bank',
diff --git a/src/Controller/Gateways/CreditCard.php b/src/Controller/Gateways/CreditCard.php
index 9e6465e3..ed56c1a3 100644
--- a/src/Controller/Gateways/CreditCard.php
+++ b/src/Controller/Gateways/CreditCard.php
@@ -69,10 +69,10 @@ public function field_enabled()
return [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(),
'label' => __('Enable credit card', 'woo-pagarme-payments'),
'old_name' => 'enable_credit_card',
- 'default' => $this->config->getData('enable_credit_card') ?? Yesno::NO_VALUE,
+ 'default' => $this->config->getData('enable_credit_card') ?? strtolower(Yesno::NO),
];
}
diff --git a/src/Controller/Gateways/Voucher.php b/src/Controller/Gateways/Voucher.php
index 5e254221..e0503307 100644
--- a/src/Controller/Gateways/Voucher.php
+++ b/src/Controller/Gateways/Voucher.php
@@ -108,8 +108,8 @@ public function field_voucher_card_wallet()
'desc_tip' => __('Enable Card Wallet', 'woo-pagarme-payments'),
'type' => 'select',
'label' => __('Card Wallet', 'woo-pagarme-payments'),
- 'options' => $this->yesnoOptions->toArray(),
- 'default' => Yesno::NO_VALUE,
+ 'options' => $this->yesnoOptions->toLabelsArray(),
+ 'default' => strtolower(Yesno::NO),
'custom_attributes' => [
'data-field' => 'voucher-card-wallet',
]
diff --git a/src/Model/Config/Source/AbstractOptions.php b/src/Model/Config/Source/AbstractOptions.php
index f2a25d25..c4c968bb 100644
--- a/src/Model/Config/Source/AbstractOptions.php
+++ b/src/Model/Config/Source/AbstractOptions.php
@@ -53,4 +53,22 @@ public function toArray()
}
return $options;
}
+
+ /**
+ * "key-value" format
+ * @return array
+ */
+ public function toLabelsArray($translate = false)
+ {
+ $options = [];
+ $reflectionClass = new \ReflectionClass($this);
+ $const = $reflectionClass->getConstants();
+ foreach ($const as $code => $value) {
+ if (strpos($code, '_VALUE') === false) {
+ $value = $translate ? __($value) : $value;
+ $options[strtolower($value)] = $value;
+ }
+ }
+ return $options;
+ }
}
From ee42e173f1ed760e6835a1132dead3fdc46a6e21 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 6 Mar 2023 16:40:26 -0300
Subject: [PATCH 062/156] :sparkles: save custom table decorator with new
config
---
src/Concrete/WoocommerceCoreSetup.php | 77 ++++++++-----------
.../WoocommercePlatformOrderDecorator.php | 2 +-
src/Controller/Gateways/Voucher.php | 4 +-
src/Model/Config.php | 12 +++
.../Config/PagarmeCoreConfigManagement.php | 54 +++++++++----
5 files changed, 90 insertions(+), 59 deletions(-)
diff --git a/src/Concrete/WoocommerceCoreSetup.php b/src/Concrete/WoocommerceCoreSetup.php
index 998c3abb..3e372729 100644
--- a/src/Concrete/WoocommerceCoreSetup.php
+++ b/src/Concrete/WoocommerceCoreSetup.php
@@ -16,6 +16,7 @@
use Woocommerce\Pagarme\Concrete\WoocommercePlatformPaymentMethodDecorator;
use Woocommerce\Pagarme\Concrete\WoocommercePlatformProductDecorator;
use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Setting;
final class WoocommerceCoreSetup extends AbstractModuleCoreSetup
@@ -92,9 +93,8 @@ public function _getStoreLanguage()
public function loadModuleConfigurationFromPlatform()
{
- $storeConfig = Setting::get_instance();
+ $storeConfig = new Config;
$configData = new \stdClass();
-
$configData = self::fillWithGeneralConfig($configData, $storeConfig);
$configData = self::fillWithPagarmeKeys($configData, $storeConfig);
$configData = self::fillWithCardConfig($configData, $storeConfig);
@@ -127,13 +127,13 @@ private static function checkWebSiteExists()
static private function fillWithVoucherConfig($dataObj, $storeConfig)
{
$voucherConfig = new \stdClass();
- $voucherConfig->enabled = $storeConfig->is_active_voucher();
+ $voucherConfig->enabled = $storeConfig->getEnableVoucher();
$voucherConfig->title = null;
$voucherConfig->cardOperation = null;
- $dataObj->voucherCardStatementDescriptor = $storeConfig->isVoucherStatementDescriptor();
+ $dataObj->voucherCardStatementDescriptor = $storeConfig->getVoucherSoftDescriptor();
$dataObj->cardConfigs = self::getBrandConfig($storeConfig);
$dataObj->voucherConfig = $voucherConfig;
- $dataObj->saveVoucherCards = $storeConfig->is_allowed_save_voucher_card();
+ $dataObj->saveVoucherCards = $storeConfig->getVoucherCardWallet();
return $dataObj;
}
@@ -146,15 +146,15 @@ static private function fillWithCardConfig($dataObj, $storeConfig)
{
$moneyService = new MoneyService();
- $dataObj->creditCardEnabled = $storeConfig->is_active_credit_card();
+ $dataObj->creditCardEnabled = $storeConfig->getEnableCreditCard();
$dataObj->installmentsEnabled = true;
$dataObj->cardOperation = $storeConfig->getCardOperationForCore();
- $dataObj->cardStatementDescriptor = $storeConfig->isCardStatementDescriptor();
- $dataObj->antifraudEnabled = $storeConfig->isAntifraudEnabled();
- $dataObj->antifraudMinAmount = intval($storeConfig->antifraud_min_value);
- $dataObj->saveCards = $storeConfig->is_allowed_save_credit_card();
- $dataObj->saveVoucherCards = $storeConfig->is_allowed_save_voucher_card();
- $dataObj->installmentsDefaultConfig = $storeConfig->isInstallmentsDefaultConfig();
+ $dataObj->cardStatementDescriptor = $storeConfig->getIsCardStatementDescriptor();
+ $dataObj->antifraudEnabled = $storeConfig->getAntifraudEnabled();
+ $dataObj->antifraudMinAmount = intval($storeConfig->getAntifraudMinValue());
+ $dataObj->saveCards = $storeConfig->getCcAllowSave();
+ $dataObj->saveVoucherCards = $storeConfig->getVoucherCardWallet();
+ $dataObj->installmentsDefaultConfig = $storeConfig->getIsInstallmentsDefaultConfig();
$dataObj->antifraudMinAmount =
$moneyService->floatToCents(
@@ -169,10 +169,10 @@ static private function fillWithCardConfig($dataObj, $storeConfig)
private static function fillWithPixConfig($dataObj, $storeConfig)
{
$pixConfig = new \stdClass();
- $pixConfig->enabled = $storeConfig->is_active_pix();
- $pixConfig->expirationQrCode = $storeConfig->pix_qrcode_expiration_time;
+ $pixConfig->enabled = $storeConfig->getEnablePix();
+ $pixConfig->expirationQrCode = $storeConfig->getPixQrcodeExpirationTime();
$pixConfig->bankType = 'Pagar.me';
- $pixAdditionalData = $storeConfig->pix_additional_data;
+ $pixAdditionalData = $storeConfig->getPixAdditionalData();
if (
!empty($pixAdditionalData)
@@ -191,31 +191,31 @@ private static function fillWithPixConfig($dataObj, $storeConfig)
static private function fillWithBoletoConfig($dataObj, $storeConfig)
{
- $dataObj->boletoEnabled = $storeConfig->is_active_billet();
- $dataObj->boletoInstructions = $storeConfig->billet_instructions;
- $dataObj->boletoDueDays = $storeConfig->billet_deadline_days;
- $dataObj->boletoBankCode = $storeConfig->billet_bank;
+ $dataObj->boletoEnabled = $storeConfig->getEnableBillet();
+ $dataObj->boletoInstructions = $storeConfig->getBilletInstructions();
+ $dataObj->boletoDueDays = $storeConfig->getBilletDeadlineDays();
+ $dataObj->boletoBankCode = $storeConfig->getBilletBank();
return $dataObj;
}
static private function fillWithBoletoCreditCardConfig($dataObj, $storeConfig)
{
- $dataObj->boletoCreditCardEnabled = $storeConfig->is_active_billet_and_card();
+ $dataObj->boletoCreditCardEnabled = $storeConfig->getMultimethodsBilletCard();
return $dataObj;
}
static private function fillWithTwoCreditCardsConfig($dataObj, $storeConfig)
{
- $dataObj->twoCreditCardsEnabled = $storeConfig->is_active_2_cards();
+ $dataObj->twoCreditCardsEnabled = $storeConfig->getMultimethods2Card();
return $dataObj;
}
static private function fillWithMultiBuyerConfig($dataObj, $storeConfig)
{
- $dataObj->multibuyer = $storeConfig->is_active_multicustomers();
+ $dataObj->multibuyer = $storeConfig->getMulticustomers();
return $dataObj;
}
@@ -223,15 +223,10 @@ static private function fillWithMultiBuyerConfig($dataObj, $storeConfig)
static private function fillWithPagarmeKeys($dataObj, $storeConfig)
{
$options = [
- Configuration::KEY_SECRET => $storeConfig->production_secret_key,
- Configuration::KEY_PUBLIC => $storeConfig->production_public_key
+ Configuration::KEY_SECRET => $storeConfig->getSecretKey(),
+ Configuration::KEY_PUBLIC => $storeConfig->getPublicKey()
];
- if ($dataObj->testMode) {
- $options[Configuration::KEY_SECRET] .= $storeConfig->sandbox_secret_key;
- $options[Configuration::KEY_PUBLIC] .= $storeConfig->sandbox_public_key;
- }
-
$options = (object) $options;
$dataObj->keys = $options;
@@ -240,8 +235,8 @@ static private function fillWithPagarmeKeys($dataObj, $storeConfig)
static private function fillWithGeneralConfig($dataObj, $storeConfig)
{
- $dataObj->enabled = $storeConfig->is_enabled();
- $dataObj->testMode = $storeConfig->is_sandbox();
+ $dataObj->enabled = $storeConfig->getEnabled();
+ $dataObj->testMode = $storeConfig->getIsSandboxMode();
$dataObj->sendMail = false;
$dataObj->createOrder = false;
@@ -257,7 +252,7 @@ static private function getBrandConfig($storeConfig)
{
$brands = array_merge(
[''],
- $storeConfig->get_flags_list()
+ $storeConfig->getCcFlags()
);
$cardConfigs = [];
@@ -270,7 +265,7 @@ static private function getBrandConfig($storeConfig)
$brandMethod = 'nobrand';
}
- $settingsByBrand = $storeConfig->cc_installments_by_flag;
+ $settingsByBrand = $storeConfig->getCcInstallmentsByFlag();
$max = !empty($settingsByBrand) && array_key_exists($brand, $settingsByBrand['max_installment']) ?
$settingsByBrand['max_installment'][$brand] : 0;
@@ -281,10 +276,10 @@ static private function getBrandConfig($storeConfig)
}
if (empty($max)) {
- $max = $storeConfig->cc_installments_maximum;
- $initial = $storeConfig->cc_installments_interest;
- $incremental = $storeConfig->cc_installments_interest_increase;
- $maxWithout = $storeConfig->cc_installments_without_interest;
+ $max = $storeConfig->getCcInstallmentsMaximum();
+ $initial = $storeConfig->getCcInstallmentsInterest();
+ $incremental = $storeConfig->getCcInstallmentsInterestIncrease();
+ $maxWithout = $storeConfig->getCcInstallmentsWithoutInterest();
}
$minValue = null;
@@ -329,12 +324,8 @@ static private function fillWithRecurrenceConfig(&$dataObj, $storeConfig)
static private function fillWithHubConfig($dataObj, $storeConfig)
{
- $dataObj->hubInstallId = null;
- $dataObj->hubEnvironment = null;
- if ($storeConfig->isHubEnabled()) {
- $dataObj->hubInstallId = $storeConfig->hub_install_id;
- $dataObj->hubEnvironment = $storeConfig->hub_environment;
- }
+ $dataObj->hubInstallId = $storeConfig->getHubInstallId();
+ $dataObj->hubEnvironment = $storeConfig->getHubEnvironment();
return $dataObj;
}
}
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index 2dbc5727..f388561c 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -823,7 +823,7 @@ private function extractPaymentDataFromTwoCreditCards(&$paymentData)
$multiCustomerFlag = empty($index) ? "enable_multicustomers_card1"
: "enable_multicustomers_card2";
if ($this->formData[$multiCustomerFlag]) {
- $flag = explode("_", $multiCustomerFlag)
+ $flag = explode("_", $multiCustomerFlag);
$card = array_pop($flag);
$newPaymentData->customer = $this->extractMultibuyerData(
diff --git a/src/Controller/Gateways/Voucher.php b/src/Controller/Gateways/Voucher.php
index e0503307..5e254221 100644
--- a/src/Controller/Gateways/Voucher.php
+++ b/src/Controller/Gateways/Voucher.php
@@ -108,8 +108,8 @@ public function field_voucher_card_wallet()
'desc_tip' => __('Enable Card Wallet', 'woo-pagarme-payments'),
'type' => 'select',
'label' => __('Card Wallet', 'woo-pagarme-payments'),
- 'options' => $this->yesnoOptions->toLabelsArray(),
- 'default' => strtolower(Yesno::NO),
+ 'options' => $this->yesnoOptions->toArray(),
+ 'default' => Yesno::NO_VALUE,
'custom_attributes' => [
'data-field' => 'voucher-card-wallet',
]
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 876d43fb..01c54caf 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -201,4 +201,16 @@ public function getPublicKey()
}
return $publicKey;
}
+
+ /**
+ * @return string
+ */
+ public function getSecretKey()
+ {
+ $publicKey = $this->getData('production_secret_key');
+ if ($this->getHubEnvironment() === EnvironmentsTypes::SANDBOX_VALUE && $this->getData('sandbox_secret_key')) {
+ $publicKey = $this->getData('sandbox_secret_key');
+ }
+ return $publicKey;
+ }
}
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index 48456865..4f38f7ef 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -12,8 +12,10 @@
namespace Woocommerce\Pagarme\Model\Config;
use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup as MPSetup;
+use Pagarme\Core\Kernel\Exceptions\InvalidParamException;
use Pagarme\Core\Kernel\Factories\ConfigurationFactory;
use Pagarme\Core\Kernel\Repositories\ConfigurationRepository;
+use Pagarme\Core\Kernel\ValueObjects\Id\GUID;
use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Data\DataObject;
use Woocommerce\Pagarme\Model\Serialize\Serializer\Json;
@@ -38,17 +40,12 @@ class PagarmeCoreConfigManagement
/** @var DataObject */
private $dataObject;
- /** @var \Pagarme\Core\Kernel\Aggregates\Configuration */
- private $moduleConfig;
-
/**
* @param ConfigurationFactory|null $pagarmeCoreConfigFactory
- * @param ConfigurationRepository|null $pagarmeCoreConfigRepository
* @param Json|null $jsonSerialize
*/
public function __construct(
ConfigurationFactory $pagarmeCoreConfigFactory = null,
- ConfigurationRepository $pagarmeCoreConfigRepository = null,
Json $jsonSerialize = null,
DataObject $dataObject = null
) {
@@ -60,20 +57,23 @@ public function __construct(
public function update(Config $config)
{
$data = $config->getData();
+ /** @var \Pagarme\Core\Kernel\Aggregates\Configuration */
+ $moduleConfig = MPSetup::getModuleConfiguration();
foreach ($data as $key => $datum) {
unset($data[$key]);
- $key = $method = $this->getMethod($key, '');
+ $method = $this->getMethod($key, '');
if (method_exists($this, 'convertKey' . $method)) {
- $key = $this->{'convertKey' . $method}();
+ $method = $this->{'convertKey' . $method}();
+ }
+ if (method_exists($this, 'convertData' . $method)) {
+ $datum = $this->{'convertData' . $method}($datum);
+ }
+ if (method_exists($moduleConfig, $this->getMethod($method))) {
+ $moduleConfig->{$this->getMethod($method)}($datum);
}
- $data[lcfirst($key)] = $datum;
}
- $this->setCardConfigs($data);
- $data = $this->pagarmeCoreConfigFactory->createFromJsonData(
- $this->jsonSerialize->serialize($data)
- );
$this->pagarmeCoreConfigRepository = $this->pagarmeCoreConfigRepository ?? new ConfigurationRepository;
- $this->pagarmeCoreConfigRepository->save($data);
+ $this->pagarmeCoreConfigRepository->save($moduleConfig);
}
public function setCardConfigs(&$data)
@@ -146,4 +146,32 @@ public function convertKeyMultimethodsBilletCard()
{
return 'boletoCreditCardEnabled';
}
+
+ /**
+ * @param $datum
+ * @return bool
+ */
+ public function convertDataSaveCards($datum)
+ {
+ return (bool) $datum;
+ }
+
+ /**
+ * @param $datum
+ * @return bool
+ */
+ public function convertDataSaveVoucherCards($datum)
+ {
+ return (bool) $datum;
+ }
+
+ /**
+ * @param $datum
+ * @return GUID
+ * @throws InvalidParamException
+ */
+ public function convertDataHubInstallId($datum)
+ {
+ return new GUID($datum);
+ }
}
From 47a86956644ea463d75c1c8698f607f541beb606 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Mon, 6 Mar 2023 10:36:20 -0300
Subject: [PATCH 063/156] Call tokenize card once
---
.../checkout/model/payment/card/tokenize.js | 54 ++++++-------------
.../checkout/model/payment/order-value.js | 14 +++--
src/Block/Checkout/Field/Wallet.php | 4 ++
3 files changed, 31 insertions(+), 41 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card/tokenize.js b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
index 504c1af7..0d076d17 100644
--- a/assets/javascripts/front/checkout/model/payment/card/tokenize.js
+++ b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
@@ -12,19 +12,12 @@
const form = $('form.checkout');
var pagarme = {
- isPagarmePayment: function () {
- return $('form.checkout input[name="payment_method"]:checked').val().indexOf('pagarme');
- },
getEndpoint: function () {
let url = new URL(apiUrl);
url.searchParams.append('appId', appId);
- return url.toString();
- },
- getCheckoutPaymentElement: function () {
- let value = $('form.checkout input[name="payment_method"]:checked').val();
- return $('.wc_payment_method.payment_method_' + value);
+ return url.toString();
},
- getCardsForm: function(el) {
+ getCardsForm: function (el) {
return el.find('fieldset[data-pagarmecheckout="card"]');
},
haveCardForm: function (el) {
@@ -33,24 +26,17 @@
}
return false;
},
- hasSelectedWallet: function (el) {
- let elWallet = $(el).find('select[data-element="choose-credit-card"]');
- if (elWallet.length) {
- return elWallet.val().trim() !== '';
- }
- return false;
- },
};
async function execute() {
- let el = pagarme.getCheckoutPaymentElement();
- if (pagarme.isPagarmePayment() && pagarme.haveCardForm(el) !== false) {
+ let el = pagarmeCard.getCheckoutPaymentElement();
+ if (pagarmeCard.isPagarmePayment() && pagarme.haveCardForm(el) !== false) {
pagarme.getCardsForm(el).each(await tokenize);
}
}
async function tokenize() {
- if (pagarme.hasSelectedWallet(this) === false) {
+ if (pagarmeCard.hasSelectedWallet(this) === false) {
let endpoint = pagarme.getEndpoint(),
card = createCardObject(this),
field = $(this);
@@ -121,8 +107,7 @@
});
}
- function showError(text)
- {
+ function showError(text) {
const message = {
type: 'error',
html: text,
@@ -135,10 +120,9 @@
}
}
- async function createTokenInput(response, field)
- {
+ async function createTokenInput(response, field) {
try {
- let clear = await clearInputTokens(field);
+ let clear = await clearInputTokens(field);
} catch (e) {
showError(e.message);
}
@@ -147,22 +131,16 @@
if (!(field instanceof jQuery)) {
field = $(field);
}
- input.attr(
- 'type', 'hidden'
- ).attr(
- 'name', vendor + '[' + field.attr(paymentMethodTarget) + '][cards][' + field.attr(sequenceTarget) + '][' + token + ']'
- ).attr(
- 'id', vendor + '[' + field.attr(paymentMethodTarget) + '][cards][' + field.attr(sequenceTarget) + '][' + token + ']'
- ).attr(
- 'value', objJSON.id
- ).attr(
- tokenElementTarget, token
- );
+ let inputName = vendor + '[' + field.attr(paymentMethodTarget) + '][cards][' + field.attr(sequenceTarget) + '][' + token + ']'
+ input.attr('type', 'hidden')
+ .attr('name', inputName)
+ .attr('id', inputName)
+ .attr('value', objJSON.id)
+ .attr(tokenElementTarget, token);
field.append(input);
}
- function clearInputTokens(field)
- {
+ function clearInputTokens(field) {
return new Promise((resolve) => {
if (!(field instanceof jQuery)) {
field = $(field);
@@ -187,5 +165,5 @@
}
}
);
- } (jQuery)
+ }(jQuery)
);
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index 4183fe08..9c6ac51d 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -1,12 +1,20 @@
const cardValueTarget = 'input[data-pagarmecheckout-element="order-value"]';
const firstCardValue = '[data-pagarmecheckout-card-num="1"]';
let pagarmeOrderValue = {
- cardValueTarget: 'input[data-pagarmecheckout-element="order-value"]',
- firstCardValue: '[data-pagarmecheckout-card-num="1"]',
+ started: false,
+ isStarted: function (){
+ if (!this.started){
+ this.started = true;
+ return false;
+ }
+ return true;
+ },
start: function () {
+ if (this.isStarted()) {
+ return;
+ }
this.addsMask();
this.addEventListener();
- // let e = jQuery(cardValueTarget + firstCardValue).val(10);
},
fillAnotherInput: async function (e) {
let input = jQuery(e.currentTarget);
diff --git a/src/Block/Checkout/Field/Wallet.php b/src/Block/Checkout/Field/Wallet.php
index 7e704590..40bcf64e 100644
--- a/src/Block/Checkout/Field/Wallet.php
+++ b/src/Block/Checkout/Field/Wallet.php
@@ -12,7 +12,9 @@
namespace Woocommerce\Pagarme\Block\Checkout\Field;
use Woocommerce\Pagarme\Block\Checkout\Gateway;
+use Woocommerce\Pagarme\Model\Payment\BilletCard;
use Woocommerce\Pagarme\Model\Payment\CreditCard;
+use Woocommerce\Pagarme\Model\Payment\TwoCards;
use Woocommerce\Pagarme\Model\Payment\Voucher;
defined( 'ABSPATH' ) || exit;
@@ -71,6 +73,8 @@ public function getIsEnableWallet()
{
$configField = [
CreditCard::PAYMENT_CODE => 'cc-allow-save',
+ TwoCards::PAYMENT_CODE => 'cc-allow-save',
+ BilletCard::PAYMENT_CODE => 'cc-allow-save',
Voucher::PAYMENT_CODE => 'voucher-card-wallet'
];
$method = 'get' . str_replace(' ', '', ucwords(str_replace('-', ' ' ,
From 3cdb7de218396f9b4617133658072c473c624c4d Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Mon, 6 Mar 2023 11:44:55 -0300
Subject: [PATCH 064/156] Migrate bug
---
src/DB/Migration/AbstractMigration.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/DB/Migration/AbstractMigration.php b/src/DB/Migration/AbstractMigration.php
index db07696b..41d85b28 100644
--- a/src/DB/Migration/AbstractMigration.php
+++ b/src/DB/Migration/AbstractMigration.php
@@ -66,7 +66,7 @@ public function canApply(MigrationInterface $migration): bool
public function registerMigration(MigrationInterface $migration)
{
$migrationSetting = $this->settings->__get(self::MIGRATION_SETTINGS);
- if (empty($migrationSetting)) {
+ if (!is_array($migrationSetting)) {
$migrationSetting = [];
}
$migrationSetting[] = get_class($migration);
From ea9705b8166da8868c7abdd0d3d5d30e895b7141 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 6 Mar 2023 18:52:06 -0300
Subject: [PATCH 065/156] :sparkles: updates
---
src/Model/Config.php | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 01c54caf..80de2a5b 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -213,4 +213,9 @@ public function getSecretKey()
}
return $publicKey;
}
+
+ public function getCardOperationForCore()
+ {
+ return ((int)$this->getCcOperationType() === 2 ? 'auth_and_capture' : 'auth_only');
+ }
}
From a698450af3f29592801f9f8df4f16e5804001a5c Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 6 Mar 2023 20:20:36 -0300
Subject: [PATCH 066/156] :sparkles: field wallet
---
src/Block/Checkout/Form/Wallet.php | 19 +++++++++++++++++++
templates/checkout/form/card/wallet.phtml | 21 +++++++++++++--------
2 files changed, 32 insertions(+), 8 deletions(-)
diff --git a/src/Block/Checkout/Form/Wallet.php b/src/Block/Checkout/Form/Wallet.php
index 182b9c77..bab2f225 100644
--- a/src/Block/Checkout/Form/Wallet.php
+++ b/src/Block/Checkout/Form/Wallet.php
@@ -13,6 +13,8 @@
use Woocommerce\Pagarme\Block\Checkout\Gateway;
use Woocommerce\Pagarme\Model\Config;
+use Woocommerce\Pagarme\Model\Payment\CreditCard;
+use Woocommerce\Pagarme\Model\Payment\Voucher;
defined( 'ABSPATH' ) || exit;
@@ -68,6 +70,23 @@ public function getSequence()
return $this->getData('sequence');
}
+ /**
+ * @return bool
+ */
+ public function isWalletEnable()
+ {
+ $result = false;
+ switch ($this->getPaymentInstance()->getMethodCode()) {
+ case CreditCard::PAYMENT_CODE:
+ $result = (bool) $this->getConfig()->getCcAllowSave();
+ break;
+ case Voucher::PAYMENT_CODE:
+ $result = (bool) $this->getConfig()->getVoucherCardWallet();
+ break;
+ }
+ return $result;
+ }
+
/**
* @param string $id
* @return string
diff --git a/templates/checkout/form/card/wallet.phtml b/templates/checkout/form/card/wallet.phtml
index be3e382b..333fce32 100644
--- a/templates/checkout/form/card/wallet.phtml
+++ b/templates/checkout/form/card/wallet.phtml
@@ -15,11 +15,15 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-getConfig()->getIsEnableWallet() && $this->getPaymentInstance()->getCards()) : ?>
-
-
- getPaymentInstance()->getCards() as $card) : ?>
- isWalletEnable() && $this->getPaymentInstance()->getCards()) : ?>
+
+
+ = __('Cards save', 'woo-pagarme-payments'); ?>
+
+
+ = __('Select', 'woo-pagarme-payments'); ?>
+ getPaymentInstance()->getCards() as $card) : ?>
+ (%1$s) •••• •••• •••• %4$s',
esc_html(strtoupper($card->getBrand()->getName())),
@@ -27,7 +31,8 @@ if (!function_exists('add_action')) {
esc_html(strtolower($card->getBrand()->getName())),
esc_html($card->getLastFourDigits()->getValue())
);
- ?>
-
-
+ ?>
+
+
+
From d84c74e2742e87ec1c0d8df49f6b97e733028a4c Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 7 Mar 2023 11:38:31 -0300
Subject: [PATCH 067/156] :bug: WoocommerceCoreSetup ccFlags
---
src/Model/Config.php | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 80de2a5b..ae5b6d84 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -218,4 +218,12 @@ public function getCardOperationForCore()
{
return ((int)$this->getCcOperationType() === 2 ? 'auth_and_capture' : 'auth_only');
}
+
+ /**
+ * @return array|mixed
+ */
+ public function getCcFlags()
+ {
+ return $this->getData('cc_flags') ?? [];
+ }
}
From 2812864ec437be74fc37c19c8c43665a19476cca Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 7 Mar 2023 14:28:06 -0300
Subject: [PATCH 068/156] :bug: WoocommerceCoreSetup wallets
---
.../checkout/model/payment/card/wallet.js | 37 +++++++++++
src/Model/Config.php | 6 +-
.../config/form/field/hub/integration.phtml | 66 +++++--------------
templates/checkout/form/card.phtml | 53 +++++++--------
templates/checkout/form/card/wallet.phtml | 8 ++-
templates/checkout/form/field/card-save.phtml | 2 +-
6 files changed, 92 insertions(+), 80 deletions(-)
create mode 100644 assets/javascripts/front/checkout/model/payment/card/wallet.js
diff --git a/assets/javascripts/front/checkout/model/payment/card/wallet.js b/assets/javascripts/front/checkout/model/payment/card/wallet.js
new file mode 100644
index 00000000..b573b863
--- /dev/null
+++ b/assets/javascripts/front/checkout/model/payment/card/wallet.js
@@ -0,0 +1,37 @@
+/* globals wc_pagarme_checkout */
+$ = jQuery;
+const cardSaveTarget = 'select[data-element="choose-credit-card"]';
+const cardFields = [
+ '[data-pagarmecheckout-element="fields-cc-data"]',
+ '[data-element="save-cc-check"]',
+ '[data-element="enable-multicustomers-check"]'
+];
+let pagarmeWallet = {
+ started: false,
+ isStarted: function (){
+ if (!this.started){
+ this.started = true;
+ return false;
+ }
+ return true;
+ },
+ onChangeCard: function (e) {
+ let select = $( e.currentTarget );
+ let wrapper = select.closest( 'fieldset' );
+ let method = e.currentTarget.value.trim() ? 'slideUp': 'slideDown';
+ cardFields.forEach( function (field) {
+ wrapper.find(field)[method]();
+ });
+ },
+ addEventListener: function () {
+ $(cardSaveTarget).on('change', function (e) {
+ pagarmeWallet.onChangeCard(e);
+ });
+ },
+ start: function () {
+ if (this.isStarted()) {
+ return;
+ }
+ this.addEventListener();
+ },
+}
diff --git a/src/Model/Config.php b/src/Model/Config.php
index ae5b6d84..f40bacf6 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -224,6 +224,10 @@ public function getCardOperationForCore()
*/
public function getCcFlags()
{
- return $this->getData('cc_flags') ?? [];
+ $ccFlags = [];
+ if ($value = $this->getData('cc_flags')) {
+ $ccFlags = $value;
+ }
+ return $ccFlags;
}
}
diff --git a/src/View/Admin/templates/system/config/form/field/hub/integration.phtml b/src/View/Admin/templates/system/config/form/field/hub/integration.phtml
index d6493306..2686f297 100644
--- a/src/View/Admin/templates/system/config/form/field/hub/integration.phtml
+++ b/src/View/Admin/templates/system/config/form/field/hub/integration.phtml
@@ -26,58 +26,22 @@ if ( ! defined( 'ABSPATH' ) ) {
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index 14a5d6e2..c3c71fc3 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -44,33 +44,34 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
)->toHtml() ?>
-
= $this->createBlock(
'\Woocommerce\Pagarme\Block\Checkout\Form\Installments',
diff --git a/templates/checkout/form/card/wallet.phtml b/templates/checkout/form/card/wallet.phtml
index 333fce32..fa5e9ea8 100644
--- a/templates/checkout/form/card/wallet.phtml
+++ b/templates/checkout/form/card/wallet.phtml
@@ -14,6 +14,7 @@ declare( strict_types=1 );
if (!function_exists('add_action')) {
exit(0);
}
+wp_enqueue_script('pagarme-checkout-wallet', $this->getFileUrl('assets/javascripts/front/checkout/model/payment/card/wallet.js'));
?>
isWalletEnable() && $this->getPaymentInstance()->getCards()) : ?>
@@ -21,7 +22,7 @@ if (!function_exists('add_action')) {
= __('Cards save', 'woo-pagarme-payments'); ?>
- = __('Select', 'woo-pagarme-payments'); ?>
+ = __('Saved credit card', 'woo-pagarme-payments'); ?>
getPaymentInstance()->getCards() as $card) : ?>
+
diff --git a/templates/checkout/form/field/card-save.phtml b/templates/checkout/form/field/card-save.phtml
index 9fde5d14..c34d79e3 100644
--- a/templates/checkout/form/field/card-save.phtml
+++ b/templates/checkout/form/field/card-save.phtml
@@ -18,7 +18,7 @@ if (!function_exists('add_action')) {
getIsEnableWallet()) : ?>
- getPaymentInstance()->getCustomer()->save_credit_card, true); ?>>
+ getPaymentInstance()->getCustomer()->save_credit_card, true); ?>>
From 2b5e40843b87a9e5cd8d439cd119b1566b5ed71e Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 7 Mar 2023 15:12:08 -0300
Subject: [PATCH 069/156] :sparkles: create request with wallet-id
---
src/Model/Payment/Data/Cards.php | 11 +++++++----
1 file changed, 7 insertions(+), 4 deletions(-)
diff --git a/src/Model/Payment/Data/Cards.php b/src/Model/Payment/Data/Cards.php
index eab69251..b16c635d 100644
--- a/src/Model/Payment/Data/Cards.php
+++ b/src/Model/Payment/Data/Cards.php
@@ -43,7 +43,7 @@ public function __construct(
protected function init()
{
$cards = [];
- for ($count = 1; $count <= $this->getCountTokens(); $count++) {
+ for ($count = 1; $count <= $this->getCountCards(); $count++) {
$card = new Card($count);
$cards[] = $card;
}
@@ -53,14 +53,17 @@ protected function init()
/**
* @return int
*/
- private function getCountTokens()
+ private function getCountCards()
{
$count = 0;
if ($this->getPostPaymentContent() && isset($this->getPostPaymentContent()['cards'])) {
foreach ($this->getPostPaymentContent()['cards'] as $card) {
foreach ($card as $key => $value) {
- if (strpos($key, 'token') !== false) {
- $count++;
+ if (strpos($key, 'token') !== false || $key === 'wallet-id') {
+ if ($value) {
+ $count++;
+ break;
+ }
}
}
}
From 759bfb8cfebca6ba0440ea1ce9548936e5c16b11 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 7 Mar 2023 16:19:32 -0300
Subject: [PATCH 070/156] :sparkles: request wallet-id to card_id
---
.../javascripts/front/checkout/model/payment/card/wallet.js | 3 +++
src/Model/Checkout.php | 6 ++++++
2 files changed, 9 insertions(+)
diff --git a/assets/javascripts/front/checkout/model/payment/card/wallet.js b/assets/javascripts/front/checkout/model/payment/card/wallet.js
index b573b863..1cf19d8b 100644
--- a/assets/javascripts/front/checkout/model/payment/card/wallet.js
+++ b/assets/javascripts/front/checkout/model/payment/card/wallet.js
@@ -19,6 +19,9 @@ let pagarmeWallet = {
let select = $( e.currentTarget );
let wrapper = select.closest( 'fieldset' );
let method = e.currentTarget.value.trim() ? 'slideUp': 'slideDown';
+ let brand = select.find('option:selected').data('brand');
+ let brandInput = wrapper.find(pagarmeCard.getBrandTarget());
+ brandInput.val(brand);
cardFields.forEach( function (field) {
wrapper.find(field)[method]();
});
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 02e14ef0..5fe59588 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -142,6 +142,9 @@ private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
if ($card->getSaveCard()) {
$fields['save_credit_card'] = 1;
}
+ if ($value = $card->getWalletId()) {
+ $fields['card_id'] = $value;
+ }
} else {
if ($orderValue = $card->getOrderValue()) {
$fields['card_order_value' . $key] = $orderValue;
@@ -151,6 +154,9 @@ private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
if ($card->getSaveCard()) {
$fields['save_credit_card' . $key] = 1;
}
+ if ($value = $card->getWalletId()) {
+ $fields['card_id' . $key] = $value;
+ }
}
$fields['pagarmetoken' . $key] = $card->getToken();
}
From 1620913e2f986b467cb6425c8ebf9590363c8844 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 7 Mar 2023 16:30:35 -0300
Subject: [PATCH 071/156] :bug: getCards in billetCard method
---
src/Block/Checkout/Form/Wallet.php | 6 +++---
src/Model/Payment/BilletCard.php | 11 ++++++++++-
2 files changed, 13 insertions(+), 4 deletions(-)
diff --git a/src/Block/Checkout/Form/Wallet.php b/src/Block/Checkout/Form/Wallet.php
index bab2f225..40c685c0 100644
--- a/src/Block/Checkout/Form/Wallet.php
+++ b/src/Block/Checkout/Form/Wallet.php
@@ -77,12 +77,12 @@ public function isWalletEnable()
{
$result = false;
switch ($this->getPaymentInstance()->getMethodCode()) {
- case CreditCard::PAYMENT_CODE:
- $result = (bool) $this->getConfig()->getCcAllowSave();
- break;
case Voucher::PAYMENT_CODE:
$result = (bool) $this->getConfig()->getVoucherCardWallet();
break;
+ default:
+ $result = (bool) $this->getConfig()->getCcAllowSave();
+ break;
}
return $result;
}
diff --git a/src/Model/Payment/BilletCard.php b/src/Model/Payment/BilletCard.php
index f7d55208..cc90c0db 100644
--- a/src/Model/Payment/BilletCard.php
+++ b/src/Model/Payment/BilletCard.php
@@ -11,6 +11,7 @@
namespace Woocommerce\Pagarme\Model\Payment;
+use Pagarme\Core\Payment\Aggregates\SavedCard;
use ReflectionClass;
use WC_Order;
use Woocommerce\Pagarme\Helper\Utils;
@@ -22,7 +23,7 @@
* Class BilletCard
* @package Woocommerce\Pagarme\Model\Payment
*/
-class BilletCard extends AbstractPayment implements PaymentInterface
+class BilletCard extends Card implements PaymentInterface
{
/** @var string */
const PAYMENT_CODE = 'billet_and_card';
@@ -113,4 +114,12 @@ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer
$content[] = current($this->creditCard->getPayRequest($wc_order, $form_fields, $customer));
return $content;
}
+
+ /**
+ * @return SavedCard[]|null
+ */
+ public function getCards()
+ {
+ return $this->getCustomer()->get_cards(CreditCard::PAYMENT_CODE);
+ }
}
From 93a69edafd26eedeb14fa1344a2f648bcc586057 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Wed, 8 Mar 2023 11:54:38 -0300
Subject: [PATCH 072/156] multicustomer bugs
---
.../front/checkout/model/multicustomers.js | 52 +++++++++++++++----
.../front/checkout/model/payment.js | 18 +++++++
.../checkout/model/payment/order-value.js | 5 +-
templates/checkout/form/multicustomers.php | 5 ++
4 files changed, 68 insertions(+), 12 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/multicustomers.js b/assets/javascripts/front/checkout/model/multicustomers.js
index 52eb9d42..89506e8d 100644
--- a/assets/javascripts/front/checkout/model/multicustomers.js
+++ b/assets/javascripts/front/checkout/model/multicustomers.js
@@ -1,13 +1,45 @@
jQuery(function ($) {
- const inputTarget = 'input[data-element=enable-multicustomers]';
+ const multiCustomerTarget = 'input[data-element=enable-multicustomers]';
const form = 'fieldset[data-pagarme-payment-element=multicustomers]'
- $(inputTarget).click(function (e) {
- let input = $(e.currentTarget);
- let method = input.is(':checked') ? 'slideDown' : 'slideUp';
- if (input.parent().closest('fieldset').find(form).length) {
- input.parent().closest('fieldset').find(form)[method]();
- } else {
- input.parent().closest('div').find(form)[method]();
- }
- });
+ window.pagarmeMultiCustomer = {
+ started: false,
+ isStarted: function (){
+ if (!this.started){
+ this.started = true;
+ return false;
+ }
+ return true;
+ },
+ start: function () {
+ if (this.isStarted()) {
+ return;
+ }
+ this.addsMask();
+ this.addEventListener();
+ },
+ addsMask: function () {
+ // $('.pagarme-card-form-card-number').mask('0000 0000 0000 0000');
+ // $('.pagarme-card-form-card-expiry').mask('00 / 00');
+ // $('.pagarme-card-form-card-cvc').mask('0000');
+ // $('input[name*=\\[cpf\\]]').mask('000.000.000-00');
+ // $('input[name*=\\[zip_code\\]]').mask('00000-000');
+ // $('#billing_cpf').change(function () {
+ // $('input[name="pagarme[voucher][cards][1][document-holder]"]').empty();
+ // $('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).mask("999.999.999-99").trigger('input');
+ // });
+ // $('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).mask("999.999.999-99").trigger('input');
+ },
+ addEventListener: function () {
+ $(multiCustomerTarget).click(function (e) {
+ let input = $(e.currentTarget);
+ let method = input.is(':checked') ? 'slideDown' : 'slideUp';
+ if (input.parent().closest('fieldset').find(form).length) {
+ input.parent().closest('fieldset').find(form)[method]();
+ } else {
+ input.parent().closest('div').find(form)[method]();
+ }
+ });
+
+ },
+ }
});
diff --git a/assets/javascripts/front/checkout/model/payment.js b/assets/javascripts/front/checkout/model/payment.js
index 7ee0ad9f..046f772f 100644
--- a/assets/javascripts/front/checkout/model/payment.js
+++ b/assets/javascripts/front/checkout/model/payment.js
@@ -2,4 +2,22 @@
jQuery(function ($) {
globalThis.wc_pagarme_checkout = wc_pagarme_checkout;
+ wc_pagarme_checkout.validate = function () {
+ var requiredFields = $('[data-required=true]:visible'),
+ isValid = true;
+
+ requiredFields.each(function (index, item) {
+ var field = $(item);
+ if (!$.trim(field.val())) {
+ if (field.attr('id') == 'installments') {
+ field = field.next(); //Select2 span
+ }
+ field.addClass('invalid');
+ isValid = false;
+ }
+ });
+
+ return isValid;
+ };
+
});
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index 9c6ac51d..bd110631 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -1,5 +1,6 @@
const cardValueTarget = 'input[data-pagarmecheckout-element="order-value"]';
const firstCardValue = '[data-pagarmecheckout-card-num="1"]';
+
let pagarmeOrderValue = {
started: false,
isStarted: function (){
@@ -54,7 +55,7 @@ let pagarmeOrderValue = {
});
},
addsMask: function () {
- jQuery(this.cardValueTarget).mask('#.##0,00', {
+ jQuery(cardValueTarget).mask('#.##0,00', {
reverse: true
});
},
@@ -71,7 +72,7 @@ let pagarmeOrderValue = {
}
},
addEventListener: function () {
- jQuery(this.cardValueTarget).on('change', function (e) {
+ jQuery(cardValueTarget).on('change', function (e) {
pagarmeOrderValue.keyEventHandler(e);
});
},
diff --git a/templates/checkout/form/multicustomers.php b/templates/checkout/form/multicustomers.php
index 50e6c51a..4736420c 100644
--- a/templates/checkout/form/multicustomers.php
+++ b/templates/checkout/form/multicustomers.php
@@ -82,3 +82,8 @@
+
From e562a3a4218cba7046f4c56ef176c5b195762bb1 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 8 Mar 2023 18:31:13 -0300
Subject: [PATCH 073/156] :sparkles: fix empty installments to 1
---
src/Block/Checkout/ThankYou/TwoCards.php | 2 +-
src/Concrete/WoocommerceCoreSetup.php | 2 +-
src/Model/Checkout.php | 4 ++--
src/Model/Config/PagarmeCoreConfigManagement.php | 5 -----
src/Model/Payment/Card.php | 2 +-
src/Model/Payment/Data/Card.php | 9 +++++++++
6 files changed, 14 insertions(+), 10 deletions(-)
diff --git a/src/Block/Checkout/ThankYou/TwoCards.php b/src/Block/Checkout/ThankYou/TwoCards.php
index 74c5b1a2..97424df5 100644
--- a/src/Block/Checkout/ThankYou/TwoCards.php
+++ b/src/Block/Checkout/ThankYou/TwoCards.php
@@ -39,6 +39,6 @@ public function getCharges()
return $response->charges;
}
}
- return null;
+ return [null, null];
}
}
diff --git a/src/Concrete/WoocommerceCoreSetup.php b/src/Concrete/WoocommerceCoreSetup.php
index 3e372729..f2c2ca75 100644
--- a/src/Concrete/WoocommerceCoreSetup.php
+++ b/src/Concrete/WoocommerceCoreSetup.php
@@ -235,7 +235,7 @@ static private function fillWithPagarmeKeys($dataObj, $storeConfig)
static private function fillWithGeneralConfig($dataObj, $storeConfig)
{
- $dataObj->enabled = $storeConfig->getEnabled();
+ $dataObj->enabled = (bool)$storeConfig->getEnabled();
$dataObj->testMode = $storeConfig->getIsSandboxMode();
$dataObj->sendMail = false;
$dataObj->createOrder = false;
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 5fe59588..73a5d074 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -138,7 +138,7 @@ private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
$fields['card_order_value'] = $orderValue;
}
$fields['brand'] = $card->getBrand();
- $fields['installments'] = $card->getInstallment();
+ $fields['installments'] = $card->getInstallment() ?? 1;
if ($card->getSaveCard()) {
$fields['save_credit_card'] = 1;
}
@@ -150,7 +150,7 @@ private function convertCheckoutObject(PaymentRequestInterface $paymentRequest)
$fields['card_order_value' . $key] = $orderValue;
}
$fields['brand' . $key] = $card->getBrand();
- $fields['installments' . $key] = $card->getInstallment();
+ $fields['installments' . $key] = $card->getInstallment() ?? 1;
if ($card->getSaveCard()) {
$fields['save_credit_card' . $key] = 1;
}
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index 4f38f7ef..d46717e2 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -76,11 +76,6 @@ public function update(Config $config)
$this->pagarmeCoreConfigRepository->save($moduleConfig);
}
- public function setCardConfigs(&$data)
- {
- $data['cardConfigs'] = [];
- }
-
/**
* @param string $value
* @param string $type
diff --git a/src/Model/Payment/Card.php b/src/Model/Payment/Card.php
index 76ac0f30..eace2542 100644
--- a/src/Model/Payment/Card.php
+++ b/src/Model/Payment/Card.php
@@ -33,7 +33,7 @@ class Card extends AbstractPayment
*/
public function getCards()
{
- return $this->getCustomer()->get_cards($this->code);
+ return $this->getCustomer()->get_cards([$this->code]);
}
/**
diff --git a/src/Model/Payment/Data/Card.php b/src/Model/Payment/Data/Card.php
index 53d8f5ba..0656194b 100644
--- a/src/Model/Payment/Data/Card.php
+++ b/src/Model/Payment/Data/Card.php
@@ -56,6 +56,15 @@ protected function init()
}
}
+ protected function setInstallment($data)
+ {
+ $value = 1;
+ if ($data) {
+ $value = $data;
+ }
+ return $this->setData('installment', $value);
+ }
+
/**
* @param string $method
* @param bool $identifier
From d885bee44c39f0f6890c2c34c41eeeb4eba155b6 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Thu, 9 Mar 2023 10:04:24 -0300
Subject: [PATCH 074/156] :sparkles: fix installments order value
---
assets/javascripts/front/checkout/model/payment/order-value.js | 1 +
src/Model/Config/Source/AbstractOptions.php | 2 +-
2 files changed, 2 insertions(+), 1 deletion(-)
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index bd110631..226e8550 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -78,6 +78,7 @@ let pagarmeOrderValue = {
},
keyEventHandler: function (e) {
this.fillAnotherInput(e);
+ pagarmeCard.updateInstallmentsElement(e);
},
getCartTotals: function () {
return cartTotal;
diff --git a/src/Model/Config/Source/AbstractOptions.php b/src/Model/Config/Source/AbstractOptions.php
index c4c968bb..cb3326d0 100644
--- a/src/Model/Config/Source/AbstractOptions.php
+++ b/src/Model/Config/Source/AbstractOptions.php
@@ -16,7 +16,7 @@
defined( 'ABSPATH' ) || exit;
/**
- * Class Yesno
+ * Class AbstractOptions
* @package Woocommerce\Pagarme\Model\Config\Source
*/
abstract class AbstractOptions implements OptionSourceInterface
From cb4da8e878e5bc9411c5904dcfdd9d42b19ef5e9 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 9 Mar 2023 10:22:13 -0300
Subject: [PATCH 075/156] sweetalert2 on admin
---
src/Core.php | 28 ++++++++++++++--------------
1 file changed, 14 insertions(+), 14 deletions(-)
diff --git a/src/Core.php b/src/Core.php
index 87b5fe09..85c39310 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -126,22 +126,22 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
// self::filemtime("assets/javascripts/{$type}/built.js"),
// true
// );
+ wp_enqueue_script(
+ 'sweetalert2',
+ self::plugins_url("assets/javascripts/vendor/sweetalert2.js"),
+ array_merge(array('jquery'), $deps),
+ self::filemtime("assets/javascripts/vendor/sweetalert2.js"),
+ false
+ );
+ wp_enqueue_script(
+ 'jquery.mask',
+ self::plugins_url("assets/javascripts/vendor/jquery.mask.js"),
+ array('jquery'),
+ '1.14.16',
+ false
+ );
if ($type == 'front') {
- wp_enqueue_script(
- 'sweetalert2',
- self::plugins_url("assets/javascripts/vendor/sweetalert2.js"),
- array_merge(array('jquery'), $deps),
- self::filemtime("assets/javascripts/vendor/sweetalert2.js"),
- false
- );
- wp_enqueue_script(
- 'jquery.mask',
- self::plugins_url("assets/javascripts/vendor/jquery.mask.js"),
- array('jquery'),
- '1.14.16',
- false
- );
}
wp_localize_script(
From 79e9c289e2c6abdf3745eb78b5513f9f14b2f212 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Fri, 10 Mar 2023 14:28:03 -0300
Subject: [PATCH 076/156] :sparkles: installments update order value billet and
card
---
.../front/checkout/model/payment/card/tokenize.js | 10 ++--------
.../front/checkout/model/payment/order-value.js | 13 ++++++++++++-
2 files changed, 14 insertions(+), 9 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card/tokenize.js b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
index 0d076d17..0506cce6 100644
--- a/assets/javascripts/front/checkout/model/payment/card/tokenize.js
+++ b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
@@ -19,18 +19,12 @@
},
getCardsForm: function (el) {
return el.find('fieldset[data-pagarmecheckout="card"]');
- },
- haveCardForm: function (el) {
- if (el.has('fieldset[data-pagarmecheckout="card"]').length) {
- return true;
- }
- return false;
- },
+ }
};
async function execute() {
let el = pagarmeCard.getCheckoutPaymentElement();
- if (pagarmeCard.isPagarmePayment() && pagarme.haveCardForm(el) !== false) {
+ if (pagarmeCard.isPagarmePayment() && pagarmeCard.haveCardForm(el) !== false) {
pagarme.getCardsForm(el).each(await tokenize);
}
}
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index 226e8550..9f84ddeb 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -37,7 +37,18 @@ let pagarmeOrderValue = {
}
nextInput.val(await this.formatValue((total - value), false));
input.val(await this.formatValue(value, false));
- pagarmeCard.updateInstallmentsElement(e);
+ [e, nextInput].forEach( function (input) {
+ if (!input instanceof $) {
+ input = $(input);
+ }
+ if (input instanceof $.Event) {
+ input = $(input.currentTarget);
+ }
+ let fieldset = input.closest('fieldset').first();
+ if (pagarmeCard.haveCardForm(fieldset)) {
+ pagarmeCard.updateInstallmentsElement(fieldset);
+ }
+ });
},
formatValue: function (value, raw = true) {
return new Promise((resolve) => {
From 1a494d57666ab227ed616b972195304ac796744e Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 15 Mar 2023 09:09:14 -0300
Subject: [PATCH 077/156] :sparkles: add admin action capture/cancel event
---
.../admin/sales/order/view/cancel-capture.js | 153 ++++++++++++++++++
src/Controller/Orders.php | 8 +
src/Core.php | 7 +
.../sales/order/meta-box/charge-actions.phtml | 5 +
4 files changed, 173 insertions(+)
create mode 100644 assets/javascripts/admin/sales/order/view/cancel-capture.js
diff --git a/assets/javascripts/admin/sales/order/view/cancel-capture.js b/assets/javascripts/admin/sales/order/view/cancel-capture.js
new file mode 100644
index 00000000..efbf1de0
--- /dev/null
+++ b/assets/javascripts/admin/sales/order/view/cancel-capture.js
@@ -0,0 +1,153 @@
+$ = jQuery;
+const actionsTarget = '[data-ref]:enabled';
+const modalTarget = '.modal';
+const amountTarget = '[data-element=amount]';
+
+let pagarmeCancelCapture = {
+ started: false,
+ lock:false,
+
+ isStarted: function (){
+ if (!this.started){
+ this.started = true;
+ return false;
+ }
+ return true;
+ },
+
+ start: function () {
+ console.log('teste');
+ if (this.isStarted()) {
+ return;
+ }
+ this.startModal();
+ this.addEventListener();
+ },
+
+ startModal: function () {
+ let self = this;
+ $(modalTarget).iziModal({
+ padding: 20,
+ onOpening: function (modal) {
+ let amount = modal.$element.find( amountTarget );
+ const options = {
+ reverse:true,
+ onKeyPress: function(amountValue, event, field){
+ if (!event.originalEvent){
+ return;
+ }
+ amountValue = amountValue.replace(/^0+/, '')
+ if (amountValue[0] === ','){
+ amountValue = '0' + amountValue;
+ }
+ if (amountValue && amountValue.length <= 2){
+ amountValue = ('000'+amountValue).slice(-3);
+ field.val(amountValue);
+ field.trigger('input');
+ return;
+ }
+ field.val(amountValue);
+ }
+ };
+ amount.mask( "#.##0,00", options );
+ modal.$element.on( 'click', '[data-action=capture]', self.onClickCapture.bind(self) );
+ modal.$element.on( 'click', '[data-action=cancel]', self.onClickCancel.bind(self) );
+ }
+ });
+ },
+
+ onClickCapture: function (e) {
+ e.preventDefault();
+ this.handleEvents( e, 'capture' );
+ },
+
+ onClickCancel: function (e) {
+ e.preventDefault();
+ this.handleEvents( e, 'cancel' );
+ },
+
+ handleEvents: function (DOMEvent, type) {
+ let target = $( DOMEvent.currentTarget );
+ let wrapper = target.closest( '[data-charge]' );
+ let chargeId = wrapper.data( 'charge' );
+ let amount = wrapper.find( '[data-element=amount]' ).val();
+ this.request( type, chargeId, amount);
+ },
+
+ request: function (mode, chargeId, amount) {
+ if ( this.lock ) {
+ return;
+ }
+ this.lock = true;
+ this.requestInProgress();
+ let ajax = $.ajax({
+ 'url': this.getAjaxUrl(),
+ 'method': 'POST',
+ 'data': {
+ 'action': 'STW3dqRT6E',
+ 'mode': mode,
+ 'charge_id': chargeId,
+ 'amount': amount
+ }
+ });
+ ajax.done( this._onDone.bind(this) );
+ ajax.fail( this._onFail.bind(this) );
+ },
+
+ openModal: function (e) {
+ e.preventDefault();
+ let target = e.currentTarget;
+ let selector = '[data-charge-action=' + target.dataset.ref + '-' + target.dataset.type + ']';
+ $(selector).iziModal('open');
+ },
+
+ requestInProgress: function () {
+ swal({
+ title: ' ',
+ text: 'Processando...',
+ allowOutsideClick: false
+ });
+ swal.showLoading();
+ },
+
+ _onDone: function(response) {
+ this.lock = false;
+ $( modalTarget ).iziModal('close');
+ swal.close();
+ swal({
+ type: 'success',
+ title: ' ',
+ html: response.data.message,
+ showConfirmButton: false,
+ timer: 2000
+ }).then(
+ function () { },
+ function (dismiss) {
+ window.location.reload();
+ }
+ );
+ },
+
+ getAjaxUrl: function() {
+ return window.pagarme_settings.ajax_url;
+ },
+
+ _onFail: function(xhr) {
+ this.lock = false;
+ swal.close();
+ let data = JSON.parse(xhr.responseText);
+ swal({
+ type: 'error',
+ title: ' ',
+ html: data.message,
+ showConfirmButton: false,
+ timer: 2000
+ });
+ },
+
+ addEventListener: function () {
+ $(actionsTarget).on('click', function (e) {
+ pagarmeCancelCapture.openModal(e);
+ });
+ },
+}
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index 5f3e8aa7..bb420772 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -7,6 +7,7 @@
}
use Woocommerce\Pagarme\Block\Adminhtml\Sales\Order as BlockOrder;
+use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Setting;
use Woocommerce\Pagarme\Concrete\WoocommerceCoreSetup;
@@ -86,6 +87,8 @@ public function set_order_canceled(Order $order, $body)
public function add_meta_boxes()
{
+ wp_register_script('pagarme-adminhmlt-order-view-cancel-capture', $this->jsUrl('sales/order/view/cancel-capture'), ['jquery'], false);
+ wp_enqueue_script('pagarme-adminhmlt-order-view-cancel-capture');
foreach ($this->blockOrder->getMetaBoxes() as $metaBox) {
add_meta_box(
'woo-pagarme-capture',
@@ -97,4 +100,9 @@ public function add_meta_boxes()
);
}
}
+
+ public function jsUrl($jsFileName)
+ {
+ return Core::plugins_url('assets/javascripts/admin/' . $jsFileName . '.js');
+ }
}
diff --git a/src/Core.php b/src/Core.php
index 85c39310..f47d15e9 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -133,6 +133,13 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
self::filemtime("assets/javascripts/vendor/sweetalert2.js"),
false
);
+ wp_enqueue_script(
+ 'izimodal',
+ self::plugins_url("assets/javascripts/admin/vendor/izimodal.js"),
+ array_merge(['jquery'], $deps),
+ self::filemtime("assets/javascripts/admin/vendor/izimodal.js"),
+ false
+ );
wp_enqueue_script(
'jquery.mask',
self::plugins_url("assets/javascripts/vendor/jquery.mask.js"),
diff --git a/templates/adminhtml/sales/order/meta-box/charge-actions.phtml b/templates/adminhtml/sales/order/meta-box/charge-actions.phtml
index f3fea46c..a6f6d712 100644
--- a/templates/adminhtml/sales/order/meta-box/charge-actions.phtml
+++ b/templates/adminhtml/sales/order/meta-box/charge-actions.phtml
@@ -86,3 +86,8 @@ if (!function_exists('add_action')) {
)
?>
+
From 35d41b6c71817322dcb1d792c688d8cdb926491b Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 20 Mar 2023 09:26:02 -0300
Subject: [PATCH 078/156] :bug: fix metabox in order load
---
.../Adminhtml/Sales/Order/MetaBox/ChargeActions.php | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php b/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
index acf13b1e..d8f66b87 100644
--- a/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
+++ b/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
@@ -55,7 +55,9 @@ public function __construct(
\Woocommerce\Pagarme\Model\Charge $charge = null
) {
parent::__construct($jsonSerialize, $data);
- $this->order = $order ?? new Order($this->getOrderId());
+ try {
+ $this->order = $order ?? new Order($this->getOrderId());
+ } catch (\Exception $e) {}
$this->charge = $charge ?? new \Woocommerce\Pagarme\Model\Charge;
}
@@ -80,7 +82,10 @@ private function getOrderId()
*/
public function getCharges()
{
- return $this->getOrder()->get_charges();
+ if ($this->getOrder()) {
+ return $this->getOrder()->get_charges();
+ }
+ return null;
}
/**
From d209a9bcc41da4eb350b0c7d200cfe6f2391785c Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 16 Mar 2023 16:11:19 -0300
Subject: [PATCH 079/156] validations checkout
---
.../front/checkout/model/multicustomers.js | 14 -----
.../front/checkout/model/payment.js | 13 ++++-
.../checkout/model/payment/card/tokenize.js | 52 ++++++++++++++++++-
.../checkout/model/payment/order-value.js | 43 ++++++---------
src/Core.php | 18 -------
templates/checkout/billet-and-card-item.php | 2 +-
templates/checkout/form/billet.phtml | 2 +-
templates/checkout/form/card.phtml | 6 +--
8 files changed, 84 insertions(+), 66 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/multicustomers.js b/assets/javascripts/front/checkout/model/multicustomers.js
index 89506e8d..5a239ba5 100644
--- a/assets/javascripts/front/checkout/model/multicustomers.js
+++ b/assets/javascripts/front/checkout/model/multicustomers.js
@@ -14,21 +14,8 @@ jQuery(function ($) {
if (this.isStarted()) {
return;
}
- this.addsMask();
this.addEventListener();
},
- addsMask: function () {
- // $('.pagarme-card-form-card-number').mask('0000 0000 0000 0000');
- // $('.pagarme-card-form-card-expiry').mask('00 / 00');
- // $('.pagarme-card-form-card-cvc').mask('0000');
- // $('input[name*=\\[cpf\\]]').mask('000.000.000-00');
- // $('input[name*=\\[zip_code\\]]').mask('00000-000');
- // $('#billing_cpf').change(function () {
- // $('input[name="pagarme[voucher][cards][1][document-holder]"]').empty();
- // $('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).mask("999.999.999-99").trigger('input');
- // });
- // $('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).mask("999.999.999-99").trigger('input');
- },
addEventListener: function () {
$(multiCustomerTarget).click(function (e) {
let input = $(e.currentTarget);
@@ -39,7 +26,6 @@ jQuery(function ($) {
input.parent().closest('div').find(form)[method]();
}
});
-
},
}
});
diff --git a/assets/javascripts/front/checkout/model/payment.js b/assets/javascripts/front/checkout/model/payment.js
index 046f772f..06f26cea 100644
--- a/assets/javascripts/front/checkout/model/payment.js
+++ b/assets/javascripts/front/checkout/model/payment.js
@@ -2,22 +2,31 @@
jQuery(function ($) {
globalThis.wc_pagarme_checkout = wc_pagarme_checkout;
+ $.jMaskGlobals.watchDataMask = true;
wc_pagarme_checkout.validate = function () {
var requiredFields = $('[data-required=true]:visible'),
isValid = true;
requiredFields.each(function (index, item) {
var field = $(item);
+ const wrapper = field.closest( '.form-row' )
if (!$.trim(field.val())) {
if (field.attr('id') == 'installments') {
field = field.next(); //Select2 span
}
- field.addClass('invalid');
+ field.addClass('invalid')
+ if (isValid) {
+ field.focus();
+ }
+ wrapper.addClass('woocommerce-invalid' ); // error
isValid = false;
}
});
+ if (!isValid) {
+ swal('Prencha os campos obrigatórios');
+ $('[data-required=true]:visible.invalid')[0].append('Campo Obrigatório
');
+ }
return isValid;
};
-
});
diff --git a/assets/javascripts/front/checkout/model/payment/card/tokenize.js b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
index 0506cce6..9d59b8ed 100644
--- a/assets/javascripts/front/checkout/model/payment/card/tokenize.js
+++ b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
@@ -23,6 +23,9 @@
};
async function execute() {
+ if (wc_pagarme_checkout.validate() === false) {
+ return;
+ }
let el = pagarmeCard.getCheckoutPaymentElement();
if (pagarmeCard.isPagarmePayment() && pagarmeCard.haveCardForm(el) !== false) {
pagarme.getCardsForm(el).each(await tokenize);
@@ -42,7 +45,11 @@
createTokenInput(data, field);
},
function (error) {
- showError('Não foi possÃvel gerar a transação segura. Serviço indisponÃvel.')
+ if (error.statusCode == 503) {
+ showError('Não foi possÃvel gerar a transação segura. Serviço indisponÃvel.')
+ } else {
+ listError(error.errors);
+ }
}
);
}
@@ -102,6 +109,7 @@
}
function showError(text) {
+ swal.close();
const message = {
type: 'error',
html: text,
@@ -114,6 +122,48 @@
}
}
+ function listError(errors) {
+ var error, rect;
+ var element = $('input[name$="payment_method"]:checked').closest('li').find('#wcmp-checkout-errors');
+
+ swal.close();
+
+ wc_pagarme_checkout.errorList = '';
+
+ for (error in errors) {
+ (errors[error] || []).forEach(parseErrorsList.bind(this, error));
+ }
+
+ element.find('.woocommerce-error').html(wc_pagarme_checkout.errorList);
+ element.slideDown();
+
+ rect = element.get(0).getBoundingClientRect();
+
+ jQuery('#wcmp-submit').removeAttr('disabled', 'disabled');
+
+ window.scrollTo(0, (rect.top + window.scrollY) - 40);
+ };
+
+ function parseErrorsList (error, message) {
+ wc_pagarme_checkout.errorList += '' + translateErrors(error, message) + ' ';
+ };
+
+ function translateErrors(error, message) {
+ error = error.replace('request.', '');
+ var output = error + ': ' + message;
+ // var ptBrMessages = PagarmeGlobalVars.checkoutErrors.pt_BR;
+
+ // if (PagarmeGlobalVars.WPLANG != 'pt_BR') {
+ // return output;
+ // }
+ //
+ // if (ptBrMessages.hasOwnProperty(output)) {
+ // return ptBrMessages[output];
+ // }
+
+ return output;
+ };
+
async function createTokenInput(response, field) {
try {
let clear = await clearInputTokens(field);
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index 9f84ddeb..602b4959 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -3,8 +3,8 @@ const firstCardValue = '[data-pagarmecheckout-card-num="1"]';
let pagarmeOrderValue = {
started: false,
- isStarted: function (){
- if (!this.started){
+ isStarted: function () {
+ if (!this.started) {
this.started = true;
return false;
}
@@ -14,7 +14,6 @@ let pagarmeOrderValue = {
if (this.isStarted()) {
return;
}
- this.addsMask();
this.addEventListener();
},
fillAnotherInput: async function (e) {
@@ -24,10 +23,10 @@ let pagarmeOrderValue = {
if (nextInput.length === 0) {
nextInput = input.closest('div').siblings('div').find('input').first();
}
- let total = await this.formatValue(this.getCartTotals());
- let value = await this.formatValue(e.currentTarget.value);
+ let total = this.formatValue(this.getCartTotals());
+ let value = this.formatValue(e.currentTarget.value);
if (!value) {
- value = await this.formatValue(this.getCartTotals() / 2);
+ value = this.formatValue(this.getCartTotals() / 2);
}
if (value > total) {
this.showError('O valor não pode ser maior que total do pedido!');
@@ -35,9 +34,9 @@ let pagarmeOrderValue = {
nextInput.val(empty);
return;
}
- nextInput.val(await this.formatValue((total - value), false));
- input.val(await this.formatValue(value, false));
- [e, nextInput].forEach( function (input) {
+ nextInput.val(this.formatValue((total - value), false));
+ input.val(this.formatValue(value, false));
+ [e, nextInput].forEach(function (input) {
if (!input instanceof $) {
input = $(input);
}
@@ -51,24 +50,16 @@ let pagarmeOrderValue = {
});
},
formatValue: function (value, raw = true) {
- return new Promise((resolve) => {
- if (raw) {
- if (typeof value !== 'string') {
- value = value.toString();
- }
- resolve(parseFloat(value.replace(',', '.')));
- } else {
- if (typeof value === 'string') {
- value = parseFloat(value);
- }
- resolve(value.toFixed(2).replace('.', ','));
+ if (raw) {
+ if (typeof value !== 'string') {
+ value = value.toString();
}
- });
- },
- addsMask: function () {
- jQuery(cardValueTarget).mask('#.##0,00', {
- reverse: true
- });
+ return parseFloat(value.replace(',', '.'));
+ }
+ if (typeof value === 'string') {
+ value = parseFloat(value);
+ }
+ return value.toFixed(2).replace('.', ',');
},
showError: function (text) {
const message = {
diff --git a/src/Core.php b/src/Core.php
index f47d15e9..6db0c307 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -117,15 +117,6 @@ public static function scripts_front()
public static function enqueue_scripts($type, $deps = array(), $localize_args = array())
{
- $id = "{$type}-script-" . self::SLUG;
-
-// wp_enqueue_script(
-// $id,
-// self::plugins_url("assets/javascripts/{$type}/built.js"),
-// array_merge(array('jquery'), $deps),
-// self::filemtime("assets/javascripts/{$type}/built.js"),
-// true
-// );
wp_enqueue_script(
'sweetalert2',
self::plugins_url("assets/javascripts/vendor/sweetalert2.js"),
@@ -147,15 +138,6 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
'1.14.16',
false
);
-
- if ($type == 'front') {
- }
-
- wp_localize_script(
- $id,
- self::LOCALIZE_SCRIPT_ID,
- self::get_localize_script_args($localize_args)
- );
}
public static function enqueue_styles($type)
diff --git a/templates/checkout/billet-and-card-item.php b/templates/checkout/billet-and-card-item.php
index 811df2fd..c8025acb 100644
--- a/templates/checkout/billet-and-card-item.php
+++ b/templates/checkout/billet-and-card-item.php
@@ -38,7 +38,7 @@
*
-
+
*
-
+
= $this->getMessage(true) ?>
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index c3c71fc3..e2f71891 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -31,7 +31,7 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
*
-
+
= $this->createBlock(
@@ -62,13 +62,13 @@ wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts
*
-
+
*
-
+
From 8cb48f2910bf51ada7cd80fd8a9d1ed0848c1c4c Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 20 Mar 2023 09:27:43 -0300
Subject: [PATCH 080/156] :bug: fix in config empty data
---
src/Model/Config.php | 16 +++++++++-------
1 file changed, 9 insertions(+), 7 deletions(-)
diff --git a/src/Model/Config.php b/src/Model/Config.php
index f40bacf6..153c8d17 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -53,14 +53,16 @@ public function __construct(
*/
private function init()
{
- foreach ($this->getOptions() as $key => $value) {
- $this->setData($key, $value);
+ if (is_array($this->getOptions()) || is_object($this->getOptions())) {
+ foreach ($this->getOptions() as $key => $value) {
+ $this->setData($key, $value);
+ }
+ add_action(
+ 'update_option_' . $this->getOptionKey(),
+ [ $this, 'updateOption' ],
+ 10, 3
+ );
}
- add_action(
- 'update_option_' . $this->getOptionKey(),
- [ $this, 'updateOption' ],
- 10, 3
- );
}
/**
From 05c052a9c9c23c889ba55b5d45e1452ca03fc831 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 21 Mar 2023 11:14:48 -0300
Subject: [PATCH 081/156] validacao no checkout
---
.../front/checkout/model/payment.js | 1 +
.../checkout/model/payment/card/tokenize.js | 20 ++++++++++---------
src/Block/Checkout/Field/Wallet.php | 2 ++
templates/checkout/default.php | 1 -
templates/checkout/form/card.phtml | 2 +-
templates/checkout/form/card/wallet.phtml | 2 +-
6 files changed, 16 insertions(+), 12 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment.js b/assets/javascripts/front/checkout/model/payment.js
index 06f26cea..09f7d6c0 100644
--- a/assets/javascripts/front/checkout/model/payment.js
+++ b/assets/javascripts/front/checkout/model/payment.js
@@ -3,6 +3,7 @@
jQuery(function ($) {
globalThis.wc_pagarme_checkout = wc_pagarme_checkout;
$.jMaskGlobals.watchDataMask = true;
+
wc_pagarme_checkout.validate = function () {
var requiredFields = $('[data-required=true]:visible'),
isValid = true;
diff --git a/assets/javascripts/front/checkout/model/payment/card/tokenize.js b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
index 9d59b8ed..c524fee5 100644
--- a/assets/javascripts/front/checkout/model/payment/card/tokenize.js
+++ b/assets/javascripts/front/checkout/model/payment/card/tokenize.js
@@ -34,6 +34,7 @@
async function tokenize() {
if (pagarmeCard.hasSelectedWallet(this) === false) {
+ wc_pagarme_checkout.errorTokenize = false;
let endpoint = pagarme.getEndpoint(),
card = createCardObject(this),
field = $(this);
@@ -45,6 +46,7 @@
createTokenInput(data, field);
},
function (error) {
+ wc_pagarme_checkout.errorTokenize = true;
if (error.statusCode == 503) {
showError('Não foi possÃvel gerar a transação segura. Serviço indisponÃvel.')
} else {
@@ -151,15 +153,15 @@
function translateErrors(error, message) {
error = error.replace('request.', '');
var output = error + ': ' + message;
- // var ptBrMessages = PagarmeGlobalVars.checkoutErrors.pt_BR;
-
- // if (PagarmeGlobalVars.WPLANG != 'pt_BR') {
- // return output;
- // }
- //
- // if (ptBrMessages.hasOwnProperty(output)) {
- // return ptBrMessages[output];
- // }
+ var ptBrMessages = PagarmeGlobalVars.checkoutErrors.pt_BR;
+
+ if (PagarmeGlobalVars.WPLANG != 'pt_BR') {
+ return output;
+ }
+
+ if (ptBrMessages.hasOwnProperty(output)) {
+ return ptBrMessages[output];
+ }
return output;
};
diff --git a/src/Block/Checkout/Field/Wallet.php b/src/Block/Checkout/Field/Wallet.php
index 40bcf64e..cf050aa9 100644
--- a/src/Block/Checkout/Field/Wallet.php
+++ b/src/Block/Checkout/Field/Wallet.php
@@ -30,6 +30,8 @@ class Wallet extends Gateway
*/
protected $_template = 'templates/checkout/form/field/card-save';
+ protected $scripts = ['checkout/model/payment/card/wallet'];
+
/** @var int */
protected $sequence = 1;
diff --git a/templates/checkout/default.php b/templates/checkout/default.php
index 34db8f1b..4bbbd937 100644
--- a/templates/checkout/default.php
+++ b/templates/checkout/default.php
@@ -17,7 +17,6 @@
global $woocommerce;
-wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts/front/checkout/model/payment.js'));
wp_localize_script(
'pagarme-checkout-card',
'wc_pagarme_checkout',
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index e2f71891..8a4cf70e 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -14,7 +14,7 @@ declare( strict_types=1 );
if (!function_exists('add_action')) {
exit(0);
}
-wp_enqueue_script('pagarme-checkout-card', $this->getFileUrl('assets/javascripts/front/checkout/model/payment/card.js'));
+
?>
getQuantityCards(); $qty++) : ?>
setData('sequence', $qty); ?>
diff --git a/templates/checkout/form/card/wallet.phtml b/templates/checkout/form/card/wallet.phtml
index fa5e9ea8..ff0c3353 100644
--- a/templates/checkout/form/card/wallet.phtml
+++ b/templates/checkout/form/card/wallet.phtml
@@ -14,7 +14,7 @@ declare( strict_types=1 );
if (!function_exists('add_action')) {
exit(0);
}
-wp_enqueue_script('pagarme-checkout-wallet', $this->getFileUrl('assets/javascripts/front/checkout/model/payment/card/wallet.js'));
+
?>
isWalletEnable() && $this->getPaymentInstance()->getCards()) : ?>
From 7e2a5fce0aa0712d2750297bbeae49da5f0f4958 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 22 Mar 2023 21:22:52 -0300
Subject: [PATCH 082/156] :bug: validate collumn without schema declaration and
unregister in fail apply migration
---
src/DB/Migration/AbstractMigration.php | 41 ++++++++++++++-----
src/DB/Migration/MigrationInterface.php | 12 ++++++
.../2021-10-28-0000-TypeInSavedCardTable.php | 27 +++++++++---
src/DB/Migration/Migrator.php | 3 ++
4 files changed, 67 insertions(+), 16 deletions(-)
diff --git a/src/DB/Migration/AbstractMigration.php b/src/DB/Migration/AbstractMigration.php
index 41d85b28..04cb36e0 100644
--- a/src/DB/Migration/AbstractMigration.php
+++ b/src/DB/Migration/AbstractMigration.php
@@ -11,7 +11,7 @@
namespace Woocommerce\Pagarme\DB\Migration;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use wpdb;
defined( 'ABSPATH' ) || exit;
@@ -30,19 +30,19 @@ abstract class AbstractMigration
protected $wpdb;
/**
- * @var Setting
+ * @var Config
*/
protected $settings;
/**
- * @param Setting|null $settings
+ * @param Config|null $settings
*/
public function __construct(
- ?Setting $settings = null
+ ?Config $settings = null
) {
global $wpdb;
$this->wpdb = $wpdb;
- $this->settings = $settings ?? Setting::get_instance();
+ $this->settings = $settings ?? new Config;
}
/**
@@ -51,9 +51,9 @@ public function __construct(
*/
public function canApply(MigrationInterface $migration): bool
{
- if ( $this->settings->__get(self::MIGRATION_SETTINGS) &&
- is_array($this->settings->__get(self::MIGRATION_SETTINGS)) &&
- in_array(get_class($migration), $this->settings->__get(self::MIGRATION_SETTINGS)) ) {
+ if ( $this->settings->getData(self::MIGRATION_SETTINGS) &&
+ is_array($this->settings->getData(self::MIGRATION_SETTINGS)) &&
+ in_array(get_class($migration), $this->settings->getData(self::MIGRATION_SETTINGS)) ) {
return false;
}
return true;
@@ -65,12 +65,33 @@ public function canApply(MigrationInterface $migration): bool
*/
public function registerMigration(MigrationInterface $migration)
{
- $migrationSetting = $this->settings->__get(self::MIGRATION_SETTINGS);
+ $migrationSetting = $this->settings->getData(self::MIGRATION_SETTINGS);
if (!is_array($migrationSetting)) {
$migrationSetting = [];
}
$migrationSetting[] = get_class($migration);
- $this->settings->set(self::MIGRATION_SETTINGS, $migrationSetting);
+ $this->settings->setData(self::MIGRATION_SETTINGS, $migrationSetting);
+ $this->settings->save();
+ }
+
+ /**
+ * @param MigrationInterface $migration
+ * @return void
+ */
+ public function unregisterMigration(MigrationInterface $migration): void
+ {
+ $migrationSetting = $this->settings->getData(self::MIGRATION_SETTINGS);
+ if (!is_array($migrationSetting)) {
+ return;
+ }
+ $class = get_class($migration);
+ $key = array_search($class, $migrationSetting);
+ if (is_int($key) && array_key_exists($key,$migrationSetting)) {
+ unset($migrationSetting[$key]);
+ $migrationSetting = array_values($migrationSetting);
+ $this->settings->setData(self::MIGRATION_SETTINGS, $migrationSetting);
+ }
+ $this->settings->save();
}
/**
diff --git a/src/DB/Migration/MigrationInterface.php b/src/DB/Migration/MigrationInterface.php
index 7f0bdff5..f3a179b2 100644
--- a/src/DB/Migration/MigrationInterface.php
+++ b/src/DB/Migration/MigrationInterface.php
@@ -44,4 +44,16 @@ public function registerMigration(MigrationInterface $migration);
* @return array
*/
public function getDependencies(): array;
+
+ /**
+ * @param MigrationInterface $migration
+ * @return void
+ */
+ public function unregisterMigration(MigrationInterface $migration): void;
+
+ /**
+ * Checks if the migration has already been run. Returns true if not.
+ * @return bool
+ */
+ public function validate(): bool;
}
diff --git a/src/DB/Migration/Migrations/2021-10-28-0000-TypeInSavedCardTable.php b/src/DB/Migration/Migrations/2021-10-28-0000-TypeInSavedCardTable.php
index 80abd84d..ac64b8a4 100644
--- a/src/DB/Migration/Migrations/2021-10-28-0000-TypeInSavedCardTable.php
+++ b/src/DB/Migration/Migrations/2021-10-28-0000-TypeInSavedCardTable.php
@@ -31,19 +31,34 @@ class TypeInSavedCardTable extends AbstractMigration implements MigrationInterfa
/**
* Apply the migrations.
- *
* @return void
*/
public function apply(): void
{
$table_name = $this->wpdb->prefix . self::TABLE;
$column_name = self::COLUMN_TYPE;
- $row = $this->wpdb->get_results( "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '$table_name' AND column_name = '$column_name'");
+ if ($this->validate()) {
+ try {
+ $query = "ALTER TABLE {$table_name} ADD {$column_name} varchar(30) not null comment 'card type' AFTER brand";
+ $this->wpdb->query($query);
+ $query = "UPDATE {$table_name} SET type = 'credit_card'";
+ $this->wpdb->query($query);
+ } catch (\Exception $e) {}
+ }
+ }
+
+ /**
+ * Checks if the migration has already been run. Returns true if not.
+ * @return bool
+ */
+ public function validate(): bool
+ {
+ $table_name = $this->wpdb->prefix . self::TABLE;
+ $column_name = self::COLUMN_TYPE;
+ $row = $this->wpdb->get_results( "SHOW COLUMNS FROM $table_name LIKE '$column_name'");
if (empty($row)) {
- $query = "ALTER TABLE {$table_name} ADD {$column_name} varchar(30) not null comment 'card type' AFTER brand";
- $this->wpdb->query($query);
+ return true;
}
- $query = "UPDATE {$table_name} SET type = 'credit_card'";
- $this->wpdb->query($query);
+ return false;
}
}
diff --git a/src/DB/Migration/Migrator.php b/src/DB/Migration/Migrator.php
index 22447ba2..e4187799 100644
--- a/src/DB/Migration/Migrator.php
+++ b/src/DB/Migration/Migrator.php
@@ -34,6 +34,9 @@ public function execute()
foreach ($migrationsClasses as $class) {
/** @var MigrationInterface $migration */
$migration = new $class;
+ if ($migration->validate()) {
+ $migration->unregisterMigration($migration);
+ }
if ($migration->canApply($migration)) {
$migration->apply();
$migration->registerMigration($migration);
From 2b98c36bcf867f53d03a22f27fdc94846cb19650 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 22 Mar 2023 22:54:24 -0300
Subject: [PATCH 083/156] :bug: fix error in empty charge for billet
---
src/Block/Checkout/ThankYou/Billet.php | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/src/Block/Checkout/ThankYou/Billet.php b/src/Block/Checkout/ThankYou/Billet.php
index c037212c..3d19915b 100644
--- a/src/Block/Checkout/ThankYou/Billet.php
+++ b/src/Block/Checkout/ThankYou/Billet.php
@@ -47,8 +47,10 @@ public function getBilletUrl()
{
try {
$charge = $this->getCharge();
- $transaction = current($charge->transactions);
- return $transaction->boletoUrl;
+ if ($charge) {
+ $transaction = current($charge->transactions);
+ return $transaction->boletoUrl;
+ }
} catch (\Exception $e) {}
return null;
}
From 7dca96a29d6a83e6c1b11009d0b22e82b192a6da Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Wed, 15 Mar 2023 13:24:48 -0300
Subject: [PATCH 084/156] :sparkles: fix logo and css
---
assets/images/logo.svg | 11 +++++++++++
assets/stylesheets/front/style.css | 15 +++++++++++++++
src/Controller/Gateways/AbstractGateway.php | 2 +-
3 files changed, 27 insertions(+), 1 deletion(-)
create mode 100644 assets/images/logo.svg
diff --git a/assets/images/logo.svg b/assets/images/logo.svg
new file mode 100644
index 00000000..1e318156
--- /dev/null
+++ b/assets/images/logo.svg
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
diff --git a/assets/stylesheets/front/style.css b/assets/stylesheets/front/style.css
index 71c99ee5..fd7a1538 100644
--- a/assets/stylesheets/front/style.css
+++ b/assets/stylesheets/front/style.css
@@ -1045,4 +1045,19 @@ body .swal2-animate-x-mark {
color: #6f4400;
position: relative;
}
+
+@media only screen and (max-width: 1023px) {
+ .select2-container--open .select2-dropdown--below{
+ margin-top: 50px;
+ }
+}
+
+li.wc_payment_method[class*="pagarme-payments"] label {
+ display: inline;
+}
+
+li.wc_payment_method[class*="pagarme-payments"] img {
+ max-width: 30px;
+ float: right;
+}
/*# sourceMappingURL=assets/stylesheets/front/style.css.map */
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index fd9e3132..62c4f06e 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -101,7 +101,7 @@ public function __construct(
$this->method_title = $this->getPaymentMethodTitle();
$this->method_description = __('Payment Gateway Pagar.me', 'woo-pagarme-payments') . ' ' . $this->method_title;
$this->has_fields = false;
- $this->icon = Core::plugins_url('assets/images/logo.png');
+ $this->icon = Core::plugins_url('assets/images/logo.svg');
$this->init_form_fields();
$this->init_settings();
$this->enabled = $this->get_option('enabled', 'no');
From 3183dfec26d906c4698de9d9ce1f44ea63d8594c Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 27 Mar 2023 23:13:02 -0300
Subject: [PATCH 085/156] :sparkles: fix payment data and add in admin order
view
---
assets/stylesheets/admin/style.css | 4 +
.../Adminhtml/Sales/Order/AbstractMetaBox.php | 2 +-
.../Order/MetaBox/AdditionalInformation.php | 95 +++++++++++++++++++
.../Sales/Order/MetaBox/ChargeActions.php | 18 +++-
src/Block/Order/Charge.php | 66 +++++++++++++
src/Block/Order/PaymentDetails.php | 47 +++++++++
.../Order/Transaction/AbstractTransaction.php | 42 ++++++++
src/Block/Order/Transaction/Boleto.php | 37 ++++++++
src/Block/Order/Transaction/CreditCard.php | 88 +++++++++++++++++
.../Order/Transaction/DefaultTransaction.php | 27 ++++++
src/Block/Order/Transaction/Pix.php | 73 ++++++++++++++
src/Controller/Checkout.php | 3 +-
src/Controller/Orders.php | 2 +-
src/Model/Payment/Card.php | 13 +--
.../meta-box/additional-information.phtml | 22 +++++
templates/order/charge.phtml | 34 +++++++
templates/order/payment-details.phtml | 41 ++++++++
templates/order/transaction/billet.phtml | 34 +++++++
templates/order/transaction/credit-card.phtml | 29 ++++++
templates/order/transaction/default.phtml | 21 ++++
templates/order/transaction/pix.phtml | 51 ++++++++++
21 files changed, 737 insertions(+), 12 deletions(-)
create mode 100644 src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php
create mode 100644 src/Block/Order/Charge.php
create mode 100644 src/Block/Order/PaymentDetails.php
create mode 100644 src/Block/Order/Transaction/AbstractTransaction.php
create mode 100644 src/Block/Order/Transaction/Boleto.php
create mode 100644 src/Block/Order/Transaction/CreditCard.php
create mode 100644 src/Block/Order/Transaction/DefaultTransaction.php
create mode 100644 src/Block/Order/Transaction/Pix.php
create mode 100644 templates/adminhtml/sales/order/meta-box/additional-information.phtml
create mode 100644 templates/order/charge.phtml
create mode 100644 templates/order/payment-details.phtml
create mode 100644 templates/order/transaction/billet.phtml
create mode 100644 templates/order/transaction/credit-card.phtml
create mode 100644 templates/order/transaction/default.phtml
create mode 100644 templates/order/transaction/pix.phtml
diff --git a/assets/stylesheets/admin/style.css b/assets/stylesheets/admin/style.css
index 7c010647..5fb0fd7e 100644
--- a/assets/stylesheets/admin/style.css
+++ b/assets/stylesheets/admin/style.css
@@ -2263,4 +2263,8 @@ body .swal2-animate-x-mark {
color: #e02b27;
position: relative;
}
+
+#woo-pagarme-additional-information section h2{
+ display: none;
+}
/*# sourceMappingURL=assets/stylesheets/admin/style.css.map */
diff --git a/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php b/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php
index f43c0055..6d2eda1c 100644
--- a/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php
+++ b/src/Block/Adminhtml/Sales/Order/AbstractMetaBox.php
@@ -46,7 +46,7 @@ public function getTitle()
*/
public function getCode()
{
- return $this->code;
+ return 'woo-pagarme-' . $this->code;
}
/** return int */
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php b/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php
new file mode 100644
index 00000000..57db051a
--- /dev/null
+++ b/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php
@@ -0,0 +1,95 @@
+order = $order ?? new Order($this->getOrderId());
+ } catch (\Exception $e) {}
+ $this->charge = $charge ?? new \Woocommerce\Pagarme\Model\Charge;
+ }
+
+ /**
+ * @return Order
+ */
+ public function getOrder()
+ {
+ return $this->order;
+ }
+
+ /**
+ * @return mixed|null
+ */
+ private function getOrderId()
+ {
+ if (!$this->getData('order_id')) {
+ if (isset($this->getRequest()['post'])) {
+ $this->setData('order_id', (int)$this->getRequest()['post']);
+ }
+ }
+ return $this->getData('order_id');
+ }
+
+ /**
+ * @return array
+ */
+ private function getRequest()
+ {
+ return $_REQUEST;
+ }
+}
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php b/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
index d8f66b87..d358ce12 100644
--- a/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
+++ b/src/Block/Adminhtml/Sales/Order/MetaBox/ChargeActions.php
@@ -27,7 +27,7 @@
class ChargeActions extends AbstractMetaBox implements MetaBoxInterface
{
/** @var string */
- protected $code = 'charge-actions';
+ protected $code = 'capture';
/** @var int */
protected $sortOrder = 1;
@@ -48,6 +48,12 @@ class ChargeActions extends AbstractMetaBox implements MetaBoxInterface
*/
protected $_template = 'templates/adminhtml/sales/order/meta-box/charge-actions';
+ /**
+ * @param Json|null $jsonSerialize
+ * @param array $data
+ * @param Order|null $order
+ * @param \Woocommerce\Pagarme\Model\Charge|null $charge
+ */
public function __construct(
Json $jsonSerialize = null,
array $data = [],
@@ -69,6 +75,9 @@ public function getOrder()
return $this->order;
}
+ /**
+ * @return mixed|null
+ */
private function getOrderId()
{
if (isset($this->getRequest()['post'])) {
@@ -96,6 +105,9 @@ private function getRequest()
return $_REQUEST;
}
+ /**
+ * @return string[]
+ */
public function getHeaderGrid()
{
return [
@@ -110,6 +122,10 @@ public function getHeaderGrid()
];
}
+ /**
+ * @param $charge
+ * @return false|mixed
+ */
public function getTransaction($charge)
{
return current($charge->getTransactions());
diff --git a/src/Block/Order/Charge.php b/src/Block/Order/Charge.php
new file mode 100644
index 00000000..d030a5ae
--- /dev/null
+++ b/src/Block/Order/Charge.php
@@ -0,0 +1,66 @@
+modelCharge = $modelCharge ?? new \Woocommerce\Pagarme\Model\Charge;
+ }
+
+ public function getTransactionClass($transaction)
+ {
+ $class = $this->getPaymentMethod($transaction->getTransactionType()->getType());
+ if (!class_exists($this->basePath . $class)) {
+ $class = 'DefaultTransaction';
+ }
+ return $this->basePath . $class;
+ }
+
+ public function getChargeStatus()
+ {
+ return $this->modelCharge->get_i18n_status($this->getCharge()->getStatus()->getStatus());
+ }
+
+ /**
+ * @param string $method
+ * @return array|string|string[]
+ */
+ protected function getPaymentMethod(string $method)
+ {
+ return str_replace(' ', '', ucwords(str_replace('_', ' ', $method)));
+ }
+}
diff --git a/src/Block/Order/PaymentDetails.php b/src/Block/Order/PaymentDetails.php
new file mode 100644
index 00000000..ac5a6506
--- /dev/null
+++ b/src/Block/Order/PaymentDetails.php
@@ -0,0 +1,47 @@
+setOrderId($orderId)
+ ->setOrder(new Order($orderId))->toHtml();
+ }
+
+ public function getCharges()
+ {
+ if ($this->getOrder() && $this->getOrder() instanceof Order) {
+ return $this->getOrder()->get_charges();
+ }
+ return null;
+ }
+}
diff --git a/src/Block/Order/Transaction/AbstractTransaction.php b/src/Block/Order/Transaction/AbstractTransaction.php
new file mode 100644
index 00000000..6d485add
--- /dev/null
+++ b/src/Block/Order/Transaction/AbstractTransaction.php
@@ -0,0 +1,42 @@
+getTransaction() && $this->getTransaction()->getTransactionType()->getType()) {
+ return str_replace(' ', '', ucwords(str_replace('_', ' ', $this->getTransaction()->getTransactionType()->getType())));
+ }
+ }
+}
diff --git a/src/Block/Order/Transaction/Boleto.php b/src/Block/Order/Transaction/Boleto.php
new file mode 100644
index 00000000..eb384a1d
--- /dev/null
+++ b/src/Block/Order/Transaction/Boleto.php
@@ -0,0 +1,37 @@
+getTransaction()->getBoletoUrl();
+ } catch (\Exception $e) {}
+ return null;
+ }
+}
diff --git a/src/Block/Order/Transaction/CreditCard.php b/src/Block/Order/Transaction/CreditCard.php
new file mode 100644
index 00000000..deb1ac3b
--- /dev/null
+++ b/src/Block/Order/Transaction/CreditCard.php
@@ -0,0 +1,88 @@
+getTransaction() && $this->getTransaction()->getPostData()) {
+ $postData = $this->getTransaction()->getPostData();
+ if (property_exists($postData, 'tran_data')) {
+ $data = $this->jsonSerialize->unserialize($postData->tran_data);
+ foreach ($data as $key => $datum) {
+ if ($key === 'card' && is_array($datum)) {
+ foreach ($datum as $key2 => $datum2) {
+ if (in_array($key2, $this->cardData)) {
+ $value[$this->getLabel($key2)] = $this->convertData($key2, $datum2);
+ }
+ }
+ continue;
+ }
+ if (in_array($key, $this->cardData)) {
+ $value[$this->getLabel($key)] = $this->convertData($key, $datum);
+ }
+ }
+ }
+ }
+ } catch (\Exception $e) {}
+ return $value;
+ }
+
+ /**
+ * @param string $key
+ * @return string|null
+ */
+ private function getLabel(string $key)
+ {
+ return __(ucwords(str_replace('_', ' ', $key)), 'woo-pagarme-payments');
+ }
+
+ /**
+ * @param $key
+ * @param $value
+ * @return String
+ */
+ public function convertData($key, $value)
+ {
+ if ($key === 'amount') {
+ return Utils::format_order_price_to_view($value);
+ }
+ return $value;
+ }
+}
diff --git a/src/Block/Order/Transaction/DefaultTransaction.php b/src/Block/Order/Transaction/DefaultTransaction.php
new file mode 100644
index 00000000..2e222870
--- /dev/null
+++ b/src/Block/Order/Transaction/DefaultTransaction.php
@@ -0,0 +1,27 @@
+getTransaction() && $this->getTransaction()->getPostData()) {
+ $postData = $this->getTransaction()->getPostData();
+ if (property_exists($postData, 'tran_data')) {
+ $data = $this->jsonSerialize->unserialize($postData->tran_data);
+ return $data['qr_code_url'];
+ }
+ }
+ } catch (\Exception $e) {}
+ return null;
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getRawQrCode()
+ {
+ try {
+ if ($this->getTransaction() && $this->getTransaction()->getPostData()) {
+ $postData = $this->getTransaction()->getPostData();
+ if (property_exists($postData, 'tran_data')) {
+ $data = $this->jsonSerialize->unserialize($postData->tran_data);
+ return $data['qr_code'];
+ }
+ }
+ } catch (\Exception $e) {}
+ return null;
+ }
+
+ /**
+ * @return array
+ */
+ public function getInstructions()
+ {
+ return [
+ '1. Point your phone at this screen to capture the code.',
+ '2. Open your payments app.',
+ '3. Confirm the information and complete the payment on the app.',
+ '4. We will send you a purchase confirmation.'
+ ];
+ }
+}
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index 18a95687..9f00c178 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -32,7 +32,8 @@ public function __construct(
) {
$this->ordersController = new Orders();
add_action('woocommerce_api_' . Model\Checkout::API_REQUEST, array($this, 'process_checkout_transparent'));
- add_action('woocommerce_view_order', array('Woocommerce\Pagarme\View\Checkouts', 'render_payment_details'));
+ $oaymentDetails = new \Woocommerce\Pagarme\Block\Order\PaymentDetails();
+ add_action('woocommerce_view_order', [$oaymentDetails, 'render']);
add_action('wp_ajax_xqRhBHJ5sW', array($this, 'build_installments'));
add_action('wp_ajax_nopriv_xqRhBHJ5sW', array($this, 'build_installments'));
add_filter('wcbcf_billing_fields', array($this, 'set_required_fields'));
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index bb420772..43411463 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -91,7 +91,7 @@ public function add_meta_boxes()
wp_enqueue_script('pagarme-adminhmlt-order-view-cancel-capture');
foreach ($this->blockOrder->getMetaBoxes() as $metaBox) {
add_meta_box(
- 'woo-pagarme-capture',
+ $metaBox->getCode(),
$metaBox->getTitle(),
[$metaBox, 'toHtml'],
'shop_order',
diff --git a/src/Model/Payment/Card.php b/src/Model/Payment/Card.php
index eace2542..99112f8c 100644
--- a/src/Model/Payment/Card.php
+++ b/src/Model/Payment/Card.php
@@ -98,15 +98,12 @@ public function getPayRequestBase(WC_Order $wc_order, array $form_fields, $custo
protected function getPriceWithInterest($price, $installments, $flag = '')
{
- $type = intval($this->getConfig()->getCcInstallmentType());
$amount = $price;
- if ($type === Gateway::CC_TYPE_SINGLE) { // Parcelamento único
- $no_interest = intval($this->getConfig()->getCcInstallmentsWithoutInterest());
- $interest = Utils::str_to_float($this->getConfig()->getCcInstallmentsInterest());
- $interest_increase = Utils::str_to_float($this->getConfig()->getCcInstallmentsInterestIncrease());
- $max_installments = intval($this->getConfig()->getCcInstallmentsMaximum());
- } else { // Parcelamento por bandeira
- $settings_by_flag = $this->getConfig()->getCcInstallmentsByFlag();
+ $no_interest = intval($this->getConfig()->getCcInstallmentsWithoutInterest());
+ $interest = Utils::str_to_float($this->getConfig()->getCcInstallmentsInterest());
+ $interest_increase = Utils::str_to_float($this->getConfig()->getCcInstallmentsInterestIncrease());
+ $max_installments = intval($this->getConfig()->getCcInstallmentsMaximum());
+ if ($settings_by_flag = $this->getConfig()->getCcInstallmentsByFlag()) {
$no_interest = intval($settings_by_flag['no_interest'][$flag]);
$interest = Utils::str_to_float($settings_by_flag['interest'][$flag]);
$interest_increase = Utils::str_to_float($settings_by_flag['interest_increase'][$flag]);
diff --git a/templates/adminhtml/sales/order/meta-box/additional-information.phtml b/templates/adminhtml/sales/order/meta-box/additional-information.phtml
new file mode 100644
index 00000000..a6a8717e
--- /dev/null
+++ b/templates/adminhtml/sales/order/meta-box/additional-information.phtml
@@ -0,0 +1,22 @@
+
+= $this->createBlock(
+ \Woocommerce\Pagarme\Block\Order\PaymentDetails::class,
+ 'adminhtml.sales.order.additional-information',
+ []
+)->render($this->getOrderId()); ?>
diff --git a/templates/order/charge.phtml b/templates/order/charge.phtml
new file mode 100644
index 00000000..e9aca56b
--- /dev/null
+++ b/templates/order/charge.phtml
@@ -0,0 +1,34 @@
+
+getCharge() && $this->getCharge()->getTransactions()) : ?>
+ getCharge()->getTransactions() as $transaction) : ?>
+ =
+ $this->createBlock(
+ $this->getTransactionClass($transaction),
+ 'pagarme.order.charge.transaction',
+ [
+ 'transaction' => $transaction
+ ]
+ )->toHtml();
+ ?>
+
+
+ = __('Status', 'woo-pagarme-payments'); ?>:
+ = $this->getChargeStatus(); ?>
+
+
diff --git a/templates/order/payment-details.phtml b/templates/order/payment-details.phtml
new file mode 100644
index 00000000..6b761a94
--- /dev/null
+++ b/templates/order/payment-details.phtml
@@ -0,0 +1,41 @@
+
+getCharges()) : ?>
+
+ = __('Payment Data', 'woo-pagarme-payments'); ?>
+
+ getCharges() as $charge) : ?>
+ =
+ $this->createBlock(Charge::class,
+ 'pagarme.order.charge',
+ [
+ 'charge' => $charge
+ ]
+ )->toHtml()
+ ?>
+
+
+
+
+
+ = __('No records found.', 'woo-pagarme-payments'); ?>
+
+
+
diff --git a/templates/order/transaction/billet.phtml b/templates/order/transaction/billet.phtml
new file mode 100644
index 00000000..c9d17725
--- /dev/null
+++ b/templates/order/transaction/billet.phtml
@@ -0,0 +1,34 @@
+
+
+ = __('Payment Type', 'woo-pagarme-payments'); ?>:
+ = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
+
+getBilletUrl()) : ?>
+
+ = __('Billet', 'woo-pagarme-payments'); ?>:
+
+
+ = __('If you have not yet received the boleto, please click the button below to print.', 'woo-pagarme-payments'); ?>
+
+
+ = __('Print', 'woo-pagarme-payments'); ?>
+
+
+
+
diff --git a/templates/order/transaction/credit-card.phtml b/templates/order/transaction/credit-card.phtml
new file mode 100644
index 00000000..f92d7292
--- /dev/null
+++ b/templates/order/transaction/credit-card.phtml
@@ -0,0 +1,29 @@
+
+
+ = __('Payment Type', 'woo-pagarme-payments'); ?>:
+ = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
+
+getCardDetails()) : ?>
+ getCardDetails() as $label => $value) : ?>
+
+ = $label ?>:
+ = $value ?>
+
+
+
diff --git a/templates/order/transaction/default.phtml b/templates/order/transaction/default.phtml
new file mode 100644
index 00000000..55d54b30
--- /dev/null
+++ b/templates/order/transaction/default.phtml
@@ -0,0 +1,21 @@
+
+
+ = __('Payment Type', 'woo-pagarme-payments'); ?>:
+ = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
+
diff --git a/templates/order/transaction/pix.phtml b/templates/order/transaction/pix.phtml
new file mode 100644
index 00000000..392917ea
--- /dev/null
+++ b/templates/order/transaction/pix.phtml
@@ -0,0 +1,51 @@
+
+
+ = __('Payment Type', 'woo-pagarme-payments'); ?>:
+ = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
+
+getQrCodeUrl()) : ?>
+
+ = __('QR Code', 'woo-pagarme-payments'); ?>:
+
+
+
+
+
+ = __('Copy Code', 'woo-pagarme-payments'); ?>
+
+ getInstructions() as $instruction) : ?>
+
+ = __($instruction, 'woo-pagarme-payments'); ?>
+
+
+
+ ',
+ esc_url($this->getFilePath('assets/images/pix-checkout-attention.svg')),
+ esc_html__('pix attention icon', 'woo-pagarme-payments')
+ );
+ ?>
+
+
+
+
+
+
+
From 2c560d1f89afef862711970e1c0af764fe4e5d24 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 28 Mar 2023 22:54:06 -0300
Subject: [PATCH 086/156] :sparkles: update table by charge, add css for admin
---
assets/stylesheets/admin/style.css | 51 +++++++++++++++++++
src/Block/Adminhtml/Sales/Order.php | 2 +
src/Block/Order/Charge.php | 10 ++++
src/Block/Order/PaymentDetails.php | 9 ++++
.../Order/Transaction/AbstractTransaction.php | 10 ----
templates/order/charge.phtml | 35 ++++++++-----
templates/order/payment-details.phtml | 25 ++++-----
templates/order/transaction/billet.phtml | 4 --
templates/order/transaction/credit-card.phtml | 4 --
templates/order/transaction/default.phtml | 4 --
templates/order/transaction/pix.phtml | 5 +-
11 files changed, 106 insertions(+), 53 deletions(-)
diff --git a/assets/stylesheets/admin/style.css b/assets/stylesheets/admin/style.css
index 5fb0fd7e..409ca298 100644
--- a/assets/stylesheets/admin/style.css
+++ b/assets/stylesheets/admin/style.css
@@ -2267,4 +2267,55 @@ body .swal2-animate-x-mark {
#woo-pagarme-additional-information section h2{
display: none;
}
+
+#woo-pagarme-additional-information table.woocommerce-table{
+ border-spacing: 0;
+ width: 100%;
+ margin: 0 0 1.41575em;
+ border-collapse: separate;
+}
+
+#woo-pagarme-additional-information table.woocommerce-table thead{
+ display: table-header-group;
+ vertical-align: middle;
+ border-color: inherit;
+}
+
+#woo-pagarme-additional-information table.woocommerce-table thead th{
+ padding: 1.41575em;
+ vertical-align: middle;
+ text-align: center;
+}
+
+#woo-pagarme-additional-information table.woocommerce-table tr{
+ display: table-row;
+ vertical-align: inherit;
+ border-color: inherit;
+ box-sizing: border-box;
+}
+
+#woo-pagarme-additional-information table.woocommerce-table td{
+ box-sizing: border-box;
+ padding: 1em 1.41575em;
+ text-align: left;
+ vertical-align: top;
+ background-color: #fdfdfd;
+}
+
+#woo-pagarme-additional-information table.woocommerce-table th{
+ display: table-cell;
+ box-sizing: border-box;
+ padding: 1em 1.41575em;
+ text-align: left;
+ vertical-align: top;
+ font-weight: 600;
+ background-color: #f8f8f8;
+}
+
+#woo-pagarme-additional-information table.woocommerce-table tbody{
+ display: table-row-group;
+ vertical-align: middle;
+ border-color: inherit;
+ box-sizing: border-box;
+}
/*# sourceMappingURL=assets/stylesheets/admin/style.css.map */
diff --git a/src/Block/Adminhtml/Sales/Order.php b/src/Block/Adminhtml/Sales/Order.php
index 811c84de..7a11504a 100644
--- a/src/Block/Adminhtml/Sales/Order.php
+++ b/src/Block/Adminhtml/Sales/Order.php
@@ -54,4 +54,6 @@ public function getMetaBoxes(): array
{
return $this->metaBoxes->getMetaBoxes();
}
+
+
}
diff --git a/src/Block/Order/Charge.php b/src/Block/Order/Charge.php
index d030a5ae..c8258aeb 100644
--- a/src/Block/Order/Charge.php
+++ b/src/Block/Order/Charge.php
@@ -63,4 +63,14 @@ protected function getPaymentMethod(string $method)
{
return str_replace(' ', '', ucwords(str_replace('_', ' ', $method)));
}
+
+ /**
+ * @return array|string|string[]|void
+ */
+ public function getTransactionType($transaction)
+ {
+ if ($transaction && $transaction->getTransactionType()->getType()) {
+ return str_replace(' ', '', ucwords(str_replace('_', ' ', $transaction->getTransactionType()->getType())));
+ }
+ }
}
diff --git a/src/Block/Order/PaymentDetails.php b/src/Block/Order/PaymentDetails.php
index ac5a6506..8a2b0e97 100644
--- a/src/Block/Order/PaymentDetails.php
+++ b/src/Block/Order/PaymentDetails.php
@@ -12,6 +12,7 @@
namespace Woocommerce\Pagarme\Block\Order;
use Woocommerce\Pagarme\Block\Template;
+use Woocommerce\Pagarme\Controller\Gateways\AbstractGateway;
use Woocommerce\Pagarme\Model\Order;
defined( 'ABSPATH' ) || exit;
@@ -44,4 +45,12 @@ public function getCharges()
}
return null;
}
+
+ public function isPagarmePaymentMethod(Order $order)
+ {
+ if (property_exists($order, 'wc_order')) {
+ return $order->wc_order->get_payment_method() === AbstractGateway::PAGARME;
+ }
+ return false;
+ }
}
diff --git a/src/Block/Order/Transaction/AbstractTransaction.php b/src/Block/Order/Transaction/AbstractTransaction.php
index 6d485add..e25115f7 100644
--- a/src/Block/Order/Transaction/AbstractTransaction.php
+++ b/src/Block/Order/Transaction/AbstractTransaction.php
@@ -29,14 +29,4 @@ public function getFilePath(string $path)
{
return esc_url(plugins_url($path, WCMP_ROOT_FILE));
}
-
- /**
- * @return array|string|string[]|void
- */
- public function getTransactionType()
- {
- if ($this->getTransaction() && $this->getTransaction()->getTransactionType()->getType()) {
- return str_replace(' ', '', ucwords(str_replace('_', ' ', $this->getTransaction()->getTransactionType()->getType())));
- }
- }
}
diff --git a/templates/order/charge.phtml b/templates/order/charge.phtml
index e9aca56b..72e3dd7d 100644
--- a/templates/order/charge.phtml
+++ b/templates/order/charge.phtml
@@ -17,18 +17,27 @@ if (!function_exists('add_action')) {
?>
getCharge() && $this->getCharge()->getTransactions()) : ?>
getCharge()->getTransactions() as $transaction) : ?>
- =
- $this->createBlock(
- $this->getTransactionClass($transaction),
- 'pagarme.order.charge.transaction',
- [
- 'transaction' => $transaction
- ]
- )->toHtml();
- ?>
+
+
+
+ = __($this->getTransactionType($transaction), 'woo-pagarme-payments'); ?>
+
+
+
+ =
+ $this->createBlock(
+ $this->getTransactionClass($transaction),
+ 'pagarme.order.charge.transaction',
+ [
+ 'transaction' => $transaction
+ ]
+ )->toHtml();
+ ?>
+
+ = __('Status', 'woo-pagarme-payments'); ?>:
+ = $this->getChargeStatus(); ?>
+
+
+
-
- = __('Status', 'woo-pagarme-payments'); ?>:
- = $this->getChargeStatus(); ?>
-
diff --git a/templates/order/payment-details.phtml b/templates/order/payment-details.phtml
index 6b761a94..7906c2f4 100644
--- a/templates/order/payment-details.phtml
+++ b/templates/order/payment-details.phtml
@@ -17,25 +17,22 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-getCharges()) : ?>
+isPagarmePaymentMethod($this->getOrder())) : ?>
= __('Payment Data', 'woo-pagarme-payments'); ?>
-
+ getCharges()) : ?>
getCharges() as $charge) : ?>
=
- $this->createBlock(Charge::class,
- 'pagarme.order.charge',
- [
- 'charge' => $charge
- ]
- )->toHtml()
+ $this->createBlock(Charge::class,
+ 'pagarme.order.charge',
+ [
+ 'charge' => $charge
+ ]
+ )->toHtml()
?>
-
-
-
-
- = __('No records found.', 'woo-pagarme-payments'); ?>
+
+ = __('No records found.', 'woo-pagarme-payments'); ?>
+
-
diff --git a/templates/order/transaction/billet.phtml b/templates/order/transaction/billet.phtml
index c9d17725..73cd485f 100644
--- a/templates/order/transaction/billet.phtml
+++ b/templates/order/transaction/billet.phtml
@@ -15,10 +15,6 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-
- = __('Payment Type', 'woo-pagarme-payments'); ?>:
- = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
-
getBilletUrl()) : ?>
= __('Billet', 'woo-pagarme-payments'); ?>:
diff --git a/templates/order/transaction/credit-card.phtml b/templates/order/transaction/credit-card.phtml
index f92d7292..21d9684c 100644
--- a/templates/order/transaction/credit-card.phtml
+++ b/templates/order/transaction/credit-card.phtml
@@ -15,10 +15,6 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-
- = __('Payment Type', 'woo-pagarme-payments'); ?>:
- = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
-
getCardDetails()) : ?>
getCardDetails() as $label => $value) : ?>
diff --git a/templates/order/transaction/default.phtml b/templates/order/transaction/default.phtml
index 55d54b30..2c1255e6 100644
--- a/templates/order/transaction/default.phtml
+++ b/templates/order/transaction/default.phtml
@@ -15,7 +15,3 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-
- = __('Payment Type', 'woo-pagarme-payments'); ?>:
- = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
-
diff --git a/templates/order/transaction/pix.phtml b/templates/order/transaction/pix.phtml
index 392917ea..d0490da0 100644
--- a/templates/order/transaction/pix.phtml
+++ b/templates/order/transaction/pix.phtml
@@ -15,10 +15,7 @@ if (!function_exists('add_action')) {
exit(0);
}
?>
-
- = __('Payment Type', 'woo-pagarme-payments'); ?>:
- = __($this->getTransactionType(), 'woo-pagarme-payments'); ?>
-
+
getQrCodeUrl()) : ?>
= __('QR Code', 'woo-pagarme-payments'); ?>:
From 5abfd982700511ffdf44013c6144d4fff5e8a388 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Thu, 30 Mar 2023 15:04:52 -0300
Subject: [PATCH 087/156] :sparkles: pix copy/past
---
.../front/checkout/model/payment.js | 50 +++++++++----------
.../front/checkout/model/payment/pix.js | 36 +++++++++++++
src/Block/AbstractBlock.php | 7 ++-
.../Order/MetaBox/AdditionalInformation.php | 5 ++
src/Block/Checkout/ThankYou/Pix.php | 5 ++
templates/checkout/form/pix.phtml | 2 -
templates/checkout/thankyou/pix.phtml | 2 +-
templates/order/charge.phtml | 1 +
templates/order/transaction/pix.phtml | 2 +-
9 files changed, 79 insertions(+), 31 deletions(-)
create mode 100644 assets/javascripts/front/checkout/model/payment/pix.js
diff --git a/assets/javascripts/front/checkout/model/payment.js b/assets/javascripts/front/checkout/model/payment.js
index 09f7d6c0..6b762d6c 100644
--- a/assets/javascripts/front/checkout/model/payment.js
+++ b/assets/javascripts/front/checkout/model/payment.js
@@ -1,33 +1,33 @@
/* globals wc_pagarme_checkout */
jQuery(function ($) {
- globalThis.wc_pagarme_checkout = wc_pagarme_checkout;
- $.jMaskGlobals.watchDataMask = true;
+ if (typeof wc_pagarme_checkout !== 'undefined') {
+ globalThis.wc_pagarme_checkout = wc_pagarme_checkout;
+ $.jMaskGlobals.watchDataMask = true;
+ wc_pagarme_checkout.validate = function () {
+ var requiredFields = $('[data-required=true]:visible'),
+ isValid = true;
- wc_pagarme_checkout.validate = function () {
- var requiredFields = $('[data-required=true]:visible'),
- isValid = true;
-
- requiredFields.each(function (index, item) {
- var field = $(item);
- const wrapper = field.closest( '.form-row' )
- if (!$.trim(field.val())) {
- if (field.attr('id') == 'installments') {
- field = field.next(); //Select2 span
- }
- field.addClass('invalid')
- if (isValid) {
- field.focus();
+ requiredFields.each(function (index, item) {
+ var field = $(item);
+ const wrapper = field.closest( '.form-row' )
+ if (!$.trim(field.val())) {
+ if (field.attr('id') == 'installments') {
+ field = field.next(); //Select2 span
+ }
+ field.addClass('invalid')
+ if (isValid) {
+ field.focus();
+ }
+ wrapper.addClass('woocommerce-invalid' ); // error
+ isValid = false;
}
- wrapper.addClass('woocommerce-invalid' ); // error
- isValid = false;
+ });
+ if (!isValid) {
+ swal('Prencha os campos obrigatórios');
+ $('[data-required=true]:visible.invalid')[0].append('Campo Obrigatório
');
}
- });
- if (!isValid) {
- swal('Prencha os campos obrigatórios');
- $('[data-required=true]:visible.invalid')[0].append('Campo Obrigatório
');
-
+ return isValid;
}
- return isValid;
- };
+ }
});
diff --git a/assets/javascripts/front/checkout/model/payment/pix.js b/assets/javascripts/front/checkout/model/payment/pix.js
new file mode 100644
index 00000000..35ba6f82
--- /dev/null
+++ b/assets/javascripts/front/checkout/model/payment/pix.js
@@ -0,0 +1,36 @@
+const qrRawCodeTarget = '#pagarme-qr-code';
+$ = jQuery;
+let pagarmePix = {
+ started: false,
+ isStarted: function () {
+ if (!this.started) {
+ this.started = true;
+ return false;
+ }
+ return true;
+ },
+ start: function () {
+ if (this.isStarted()) {
+ return;
+ }
+ this.addEventListener();
+ },
+ addEventListener: function () {
+ $(qrRawCodeTarget).on('click', function (e) {
+ pagarmePix.copyRawCode();
+ });
+ },
+ copyRawCode: function () {
+ let elem = $(qrRawCodeTarget)
+ if (!elem.length) {
+ return;
+ }
+ let input = $(' ').attr({
+ value: elem.attr('rawCode')
+ }).appendTo(elem.parent()).select();
+ document.execCommand('copy', false);
+ input.remove();
+ alert("Código copiado.");
+ }
+}
+pagarmePix.start();
diff --git a/src/Block/AbstractBlock.php b/src/Block/AbstractBlock.php
index ed32856c..7f565980 100644
--- a/src/Block/AbstractBlock.php
+++ b/src/Block/AbstractBlock.php
@@ -32,6 +32,9 @@ abstract class AbstractBlock extends DataObject
/** @var Json */
protected $scripts;
+ /** @var string */
+ protected $areaCode = 'front';
+
public function __construct(
Json $jsonSerialize = null,
array $data = []
@@ -103,11 +106,11 @@ public function enqueue_scripts($scripts = null)
public function getScriptUrl($jsFileName)
{
- return Core::plugins_url('assets/javascripts/front/' . $jsFileName . '.js');
+ return Core::plugins_url('assets/javascripts/' . $this->areaCode . '/' . $jsFileName . '.js');
}
public function getScriptVer($jsFileName)
{
- return Core::filemtime('assets/javascripts/front/' . $jsFileName . '.js');
+ return Core::filemtime('assets/javascripts/' . $this->areaCode . '/' . $jsFileName . '.js');
}
}
diff --git a/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php b/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php
index 57db051a..03a27ae0 100644
--- a/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php
+++ b/src/Block/Adminhtml/Sales/Order/MetaBox/AdditionalInformation.php
@@ -45,6 +45,11 @@ class AdditionalInformation extends AbstractMetaBox implements MetaBoxInterface
*/
protected $_template = 'templates/adminhtml/sales/order/meta-box/additional-information';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/payment/pix'];
+
/**
* @param Json|null $jsonSerialize
* @param array $data
diff --git a/src/Block/Checkout/ThankYou/Pix.php b/src/Block/Checkout/ThankYou/Pix.php
index edee1b4a..275d34f5 100644
--- a/src/Block/Checkout/ThankYou/Pix.php
+++ b/src/Block/Checkout/ThankYou/Pix.php
@@ -26,6 +26,11 @@ class Pix extends ThankYou
*/
protected $_template = 'templates/checkout/thankyou/pix';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/payment/pix'];
+
/**
* @return string|null
*/
diff --git a/templates/checkout/form/pix.phtml b/templates/checkout/form/pix.phtml
index 9423d3d0..fd38e366 100644
--- a/templates/checkout/form/pix.phtml
+++ b/templates/checkout/form/pix.phtml
@@ -51,5 +51,3 @@ if (!function_exists('add_action')) {
)->toHtml() ?>
-
-
diff --git a/templates/checkout/thankyou/pix.phtml b/templates/checkout/thankyou/pix.phtml
index 572c7f99..330cbe5d 100644
--- a/templates/checkout/thankyou/pix.phtml
+++ b/templates/checkout/thankyou/pix.phtml
@@ -19,7 +19,7 @@ if (!function_exists('add_action')) {
-
+
= __('Copy Code', 'woo-pagarme-payments'); ?>
getInstructions() as $instruction) : ?>
diff --git a/templates/order/charge.phtml b/templates/order/charge.phtml
index 72e3dd7d..c0da8dae 100644
--- a/templates/order/charge.phtml
+++ b/templates/order/charge.phtml
@@ -39,5 +39,6 @@ if (!function_exists('add_action')) {
+
diff --git a/templates/order/transaction/pix.phtml b/templates/order/transaction/pix.phtml
index d0490da0..5063e09d 100644
--- a/templates/order/transaction/pix.phtml
+++ b/templates/order/transaction/pix.phtml
@@ -23,7 +23,7 @@ if (!function_exists('add_action')) {
-
+
= __('Copy Code', 'woo-pagarme-payments'); ?>
getInstructions() as $instruction) : ?>
From 609367fed487b48ae92bb8f6b2784f70fe1ccd83 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 31 Mar 2023 18:59:43 -0300
Subject: [PATCH 088/156] Validate address number
---
.../front/checkout/model/payment.js | 15 ++++++++++++++-
src/Model/Checkout.php | 18 ++++++++++++++++++
2 files changed, 32 insertions(+), 1 deletion(-)
diff --git a/assets/javascripts/front/checkout/model/payment.js b/assets/javascripts/front/checkout/model/payment.js
index 6b762d6c..d3267182 100644
--- a/assets/javascripts/front/checkout/model/payment.js
+++ b/assets/javascripts/front/checkout/model/payment.js
@@ -6,7 +6,7 @@ jQuery(function ($) {
$.jMaskGlobals.watchDataMask = true;
wc_pagarme_checkout.validate = function () {
var requiredFields = $('[data-required=true]:visible'),
- isValid = true;
+ isValid = wc_pagarme_checkout.validateNumberAdrress();
requiredFields.each(function (index, item) {
var field = $(item);
@@ -29,5 +29,18 @@ jQuery(function ($) {
}
return isValid;
}
+
+ wc_pagarme_checkout.validateNumberAdrress = function () {
+ var requiredFields = $("#billing_number, #shipping_number:visible, input[name*='[multicustomers][number]']:visible");
+ requiredFields.each(function (index, item) {
+ var field = $(item);
+ if (field.val() == 0) {
+ field.val('');
+ field.data('required', true).addClass('invalid');
+ return false;
+ }
+ return true;
+ });
+ }
}
});
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 73a5d074..66032065 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -69,6 +69,24 @@ public function __construct(
$this->orders = $orders;
$this->gateway = $gateway;
$this->wooOrderRepository = $wooOrderRepository;
+ add_action('woocommerce_after_checkout_validation', array($this, 'validateCheckout'), 10, 2);
+ }
+
+ public function validateCheckout($fields, $errors)
+ {
+ if (
+ $fields['billing_number'] == 0 &&
+ !key_exists('billing_number_required', $errors->errors)
+ ) {
+ $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigatório.');
+ }
+ if (
+ $fields['ship_to_different_address'] &&
+ $fields['shipping_number'] == 0 &&
+ !key_exists('shipping_number_required', $errors->errors)
+ ) {
+ $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigatório.');
+ }
}
/**
From 4cc370190e3798e844f87646b4ad182853ebb0dc Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Mon, 3 Apr 2023 11:48:53 -0300
Subject: [PATCH 089/156] Validate address number
---
.../front/checkout/model/payment.js | 23 ++++---------------
1 file changed, 4 insertions(+), 19 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment.js b/assets/javascripts/front/checkout/model/payment.js
index d3267182..7e7c7893 100644
--- a/assets/javascripts/front/checkout/model/payment.js
+++ b/assets/javascripts/front/checkout/model/payment.js
@@ -5,17 +5,16 @@ jQuery(function ($) {
globalThis.wc_pagarme_checkout = wc_pagarme_checkout;
$.jMaskGlobals.watchDataMask = true;
wc_pagarme_checkout.validate = function () {
- var requiredFields = $('[data-required=true]:visible'),
- isValid = wc_pagarme_checkout.validateNumberAdrress();
-
+ var requiredFields = $('#billing_number, #shipping_number:visible, input[data-required=true]:visible'),
+ isValid = true;
requiredFields.each(function (index, item) {
var field = $(item);
const wrapper = field.closest( '.form-row' )
- if (!$.trim(field.val())) {
+ if (field.val() == 0 || !$.trim(field.val())) {
if (field.attr('id') == 'installments') {
field = field.next(); //Select2 span
}
- field.addClass('invalid')
+ field.addClass('invalid').val('');
if (isValid) {
field.focus();
}
@@ -25,22 +24,8 @@ jQuery(function ($) {
});
if (!isValid) {
swal('Prencha os campos obrigatórios');
- $('[data-required=true]:visible.invalid')[0].append('Campo Obrigatório
');
}
return isValid;
}
-
- wc_pagarme_checkout.validateNumberAdrress = function () {
- var requiredFields = $("#billing_number, #shipping_number:visible, input[name*='[multicustomers][number]']:visible");
- requiredFields.each(function (index, item) {
- var field = $(item);
- if (field.val() == 0) {
- field.val('');
- field.data('required', true).addClass('invalid');
- return false;
- }
- return true;
- });
- }
}
});
From 4540ab1f1974b940173e33de78750f187536f513 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Mon, 3 Apr 2023 14:50:30 -0300
Subject: [PATCH 090/156] :sparkles: warning in update
---
assets/stylesheets/admin/style.css | 28 ++++++++++++++++++++++++
constants.php | 2 ++
src/Block/Order/Transaction/Pix.php | 5 +++++
woo-pagarme-payments.php | 33 +++++++++++++++++++++++++++++
4 files changed, 68 insertions(+)
diff --git a/assets/stylesheets/admin/style.css b/assets/stylesheets/admin/style.css
index 409ca298..89a9a921 100644
--- a/assets/stylesheets/admin/style.css
+++ b/assets/stylesheets/admin/style.css
@@ -2318,4 +2318,32 @@ body .swal2-animate-x-mark {
border-color: inherit;
box-sizing: border-box;
}
+
+.pagarme-major-update-warning-separator {
+ margin: 15px -12px;
+ border: 2px solid #dba617;
+}
+
+.pagarme-major-update-warning {
+ margin-bottom: 5px;
+ max-width: 1000px;
+ display: -webkit-box;
+ display: -ms-flexbox;
+ display: flex;
+}
+
+.pagarme-major-update-warning + p {
+ display: none;
+}
+
+.pagarme-major-update-warning p:before {
+ color: #ff0004;
+ content: "\f534";
+}
+
+.pagarme-major-update-title {
+ font-weight: 600;
+ margin-bottom: 10px;
+ margin-top: 5px;
+}
/*# sourceMappingURL=assets/stylesheets/admin/style.css.map */
diff --git a/constants.php b/constants.php
index 75695f52..0854c3d8 100644
--- a/constants.php
+++ b/constants.php
@@ -17,3 +17,5 @@ function wc_pagarme_define($name, $value)
wc_pagarme_define('WCMP_ROOT_SRC', WCMP_ROOT_PATH . 'src/');
wc_pagarme_define('WCMP_ROOT_FILE', WCMP_ROOT_PATH . WCMP_SLUG . '.php');
wc_pagarme_define('WCMP_OPTION_ACTIVATE', 'wcmp_official_activate');
+wc_pagarme_define('WCMP__FILE__', __FILE__ );
+wc_pagarme_define('WCMP_PLUGIN_BASE', plugin_basename( WCMP_ROOT_FILE ) );
diff --git a/src/Block/Order/Transaction/Pix.php b/src/Block/Order/Transaction/Pix.php
index a702f3a3..398459ed 100644
--- a/src/Block/Order/Transaction/Pix.php
+++ b/src/Block/Order/Transaction/Pix.php
@@ -24,6 +24,11 @@ class Pix extends AbstractTransaction
*/
protected $_template = 'templates/order/transaction/pix';
+ /**
+ * @var string[]
+ */
+ protected $scripts = ['checkout/model/payment/pix'];
+
/**
* @return string|null
*/
diff --git a/woo-pagarme-payments.php b/woo-pagarme-payments.php
index bafd5f2e..c2918328 100644
--- a/woo-pagarme-payments.php
+++ b/woo-pagarme-payments.php
@@ -80,6 +80,10 @@ function wcmp_plugins_loaded_check()
$woocommerce = class_exists('WooCommerce');
$checkout_fields = class_exists('Extra_Checkout_Fields_For_Brazil');
+ add_action( 'in_plugin_update_message-' . WCMP_PLUGIN_BASE, function( $plugin_data ) {
+ versionUpdateWarning( WCMP_VERSION, $plugin_data['new_version'] );
+ } );
+
if ($woocommerce && $checkout_fields) {
_wcmp_load_instances();
return;
@@ -92,7 +96,36 @@ function wcmp_plugins_loaded_check()
if (!$checkout_fields) {
_wcmp_load_notice('admin_notice_error_wecffb');
}
+}
+
+function versionUpdateWarning($currentVersion, $newVersion)
+{
+ $current_version_major_part = explode( '.', $currentVersion )[0];
+ $new_version_major_part = explode( '.', $newVersion )[0];
+ if ( $current_version_major_part >= $new_version_major_part ) {
+ return;
+ }
+ ?>
+
+
+
+
+
+ = __( 'We recommend backup before upgrading!', 'woo-pagarme-payments' ); ?>
+
+
+ ',
+ ''
+ );
+ ?>
+
+
+
+
Date: Mon, 3 Apr 2023 14:43:06 -0300
Subject: [PATCH 091/156] Change Order number by order id
---
src/Concrete/WoocommercePlatformOrderDecorator.php | 10 +++++-----
src/Controller/Checkout.php | 2 +-
src/Helper/Utils.php | 2 +-
src/Model/Checkout.php | 2 +-
src/Model/Order.php | 2 +-
src/Model/Payment/AbstractPayment.php | 2 +-
src/Model/PaymentTemp.php | 2 +-
7 files changed, 11 insertions(+), 11 deletions(-)
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index f388561c..e8cadd31 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -241,7 +241,7 @@ public function canInvoice()
public function getIncrementId()
{
- return $this->getPlatformOrder()->get_order_number();
+ return $this->getPlatformOrder()->get_id();
}
public function getGrandTotal()
@@ -364,7 +364,7 @@ public function getInvoiceCollection()
*/
public function getPagarmeId()
{
- $orderId = $this->platformOrder->get_order_number();
+ $orderId = $this->platformOrder->get_id();
if (empty($orderId)) {
return null;
}
@@ -420,7 +420,7 @@ public function getCustomer()
*/
private function getRegisteredCustomer($woocommerceCustomerId)
{
- $order = new Order($this->getPlatformOrder()->get_order_number());
+ $order = new Order($this->getPlatformOrder()->get_id());
$address = Utils::build_customer_address_from_order($order);
$document = Utils::build_document_from_order($order);
@@ -475,7 +475,7 @@ private function getRegisteredCustomer($woocommerceCustomerId)
*/
private function getGuestCustomer()
{
- $order = new Order($this->getPlatformOrder()->get_order_number());
+ $order = new Order($this->getPlatformOrder()->get_id());
$address = Utils::build_customer_address_from_order($order);
$document = Utils::build_document_from_order($order);
@@ -843,7 +843,7 @@ private function extractMultibuyerData(
return null;
}
- $order = new Order($this->getPlatformOrder()->get_order_number());
+ $order = new Order($this->getPlatformOrder()->get_id());
$fields = [
"multicustomer_{$paymentMethod}[name]" => "name",
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index 9f00c178..f56bd0ef 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -77,7 +77,7 @@ public function process_checkout_transparent(WC_Order $wc_order = null): bool
$fields
);
- $order = new Order($wc_order->get_order_number());
+ $order = new Order($wc_order->get_id());
$order->payment_method = $fields['payment_method'];
$order->update_meta('_payment_method_title', $this->payment_methods[$fields['payment_method']]);
$order->update_meta('_payment_method', AbstractGateway::PAGARME . ' ' . $this->payment_methods[$fields['payment_method']]);
diff --git a/src/Helper/Utils.php b/src/Helper/Utils.php
index d2cbc127..b46432bd 100644
--- a/src/Helper/Utils.php
+++ b/src/Helper/Utils.php
@@ -740,7 +740,7 @@ public static function build_customer_shipping_from_wc_order(WC_Order $wc_order)
{
$method = $wc_order->get_shipping_method();
- $order = new Order($wc_order->get_order_number());
+ $order = new Order($wc_order->get_id());
if (!$method) {
$method = 'Não informado';
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 66032065..39435250 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -124,7 +124,7 @@ public function process(WC_Order $wc_order = null, string $type = CheckoutTypes:
$paymentInstance = $this->gateway->getPaymentInstace($fields['payment_method']);
- $order = new Order($wc_order->get_order_number());
+ $order = new Order($wc_order->get_id());
$order->payment_method = $fields['payment_method'];
$order->update_meta('_payment_method_title', $paymentInstance->getName());
$order->update_meta('_payment_method', AbstractGateway::PAGARME);
diff --git a/src/Model/Order.php b/src/Model/Order.php
index d54a92d6..269d2f6d 100644
--- a/src/Model/Order.php
+++ b/src/Model/Order.php
@@ -73,7 +73,7 @@ public function payment_on_hold()
if (!in_array($current_status, ['on-hold', 'completed', 'canceled', 'cancelled', 'processing'])) {
$this->wc_order->update_status('on-hold', __('Pagar.me: Awaiting payment confirmation.', 'woo-pagarme-payments'));
- wc_reduce_stock_levels($this->wc_order->get_order_number());
+ wc_reduce_stock_levels($this->wc_order->get_id());
}
$statusArray = [
diff --git a/src/Model/Payment/AbstractPayment.php b/src/Model/Payment/AbstractPayment.php
index dadba3ec..583efe42 100644
--- a/src/Model/Payment/AbstractPayment.php
+++ b/src/Model/Payment/AbstractPayment.php
@@ -239,7 +239,7 @@ protected function getBillingAddressFromCustomer($customer, WC_Order $wc_order)
*/
private function getCustomerAddressFromWcOrder(WC_Order $wc_order)
{
- $order = new Order($wc_order->get_order_number());
+ $order = new Order($wc_order->get_id());
return Utils::build_customer_address_from_order($order);
}
}
diff --git a/src/Model/PaymentTemp.php b/src/Model/PaymentTemp.php
index 6ad2a5cd..c89169a3 100644
--- a/src/Model/PaymentTemp.php
+++ b/src/Model/PaymentTemp.php
@@ -299,7 +299,7 @@ private function get_billing_address_from_customer($customer, $wc_order)
private function get_customer_address_from_wc_order($wc_order)
{
- $order = new Order($wc_order->get_order_number());
+ $order = new Order($wc_order->get_id());
return Utils::build_customer_address_from_order($order);
}
From a85c82c6199b297f08af54fe45358829f8acde4c Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 4 Apr 2023 08:41:03 -0300
Subject: [PATCH 092/156] :sparkles: cursor:pointer in QrCode link
---
assets/stylesheets/admin/style.css | 4 ++++
assets/stylesheets/front/style.css | 4 ++++
2 files changed, 8 insertions(+)
diff --git a/assets/stylesheets/admin/style.css b/assets/stylesheets/admin/style.css
index 89a9a921..64b7e80c 100644
--- a/assets/stylesheets/admin/style.css
+++ b/assets/stylesheets/admin/style.css
@@ -2346,4 +2346,8 @@ body .swal2-animate-x-mark {
margin-bottom: 10px;
margin-top: 5px;
}
+
+#pagarme-qr-code {
+ cursor:pointer;
+}
/*# sourceMappingURL=assets/stylesheets/admin/style.css.map */
diff --git a/assets/stylesheets/front/style.css b/assets/stylesheets/front/style.css
index fd7a1538..93be2945 100644
--- a/assets/stylesheets/front/style.css
+++ b/assets/stylesheets/front/style.css
@@ -1060,4 +1060,8 @@ li.wc_payment_method[class*="pagarme-payments"] img {
max-width: 30px;
float: right;
}
+
+#pagarme-qr-code {
+ cursor:pointer;
+}
/*# sourceMappingURL=assets/stylesheets/front/style.css.map */
From f0334c82aad40b04ef4e62c9f21c150a390d1fe7 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 4 Apr 2023 09:56:01 -0300
Subject: [PATCH 093/156] :sparkles: initial config
---
.../2023-04-04-0000-InitialModuleConfig.php | 71 +++++++++++++++++++
1 file changed, 71 insertions(+)
create mode 100644 src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
diff --git a/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php b/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
new file mode 100644
index 00000000..41d5d2a0
--- /dev/null
+++ b/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
@@ -0,0 +1,71 @@
+ '0',
+ 'enable_logs' => '0',
+ 'enable_pix' => 'no',
+ 'pix_title' => 'Pix',
+ 'pix_qrcode_expiration_time' => 3500,
+ 'pix_additional_data' => 'Custom Store PIX',
+ 'enable_credit_card' => 'no',
+ 'credit_card_title' => 'Credit Card',
+ 'cc_operation_type' => '2',
+ 'cc_soft_descriptor' => 'Credit Card',
+ 'cc_installment_type' => '1',
+ 'cc_installments_maximum' => '1',
+ 'cc_installments_min_amount' => '',
+ 'cc_installments_interest' => '',
+ 'cc_installments_interest_increase' => '',
+ 'cc_installments_without_interest' => '',
+ 'cc_allow_save' => '0',
+ 'antifraud_enabled' => '0',
+ 'antifraud_min_value' => '',
+ self::PARAM => true
+ ];
+ $this->settings->addData($data)->save();
+ }
+
+ /**
+ * Checks if the migration has already been run. Returns true if not.
+ * @return bool
+ */
+ public function validate(): bool
+ {
+ if (!$this->settings->getData(self::PARAM)) {
+ return true;
+ }
+ return false;
+ }
+}
From 92ee2d971f9f5145ff79e58e782f99b49edef99b Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 4 Apr 2023 11:42:42 -0300
Subject: [PATCH 094/156] :sparkles: fix validation in migration
---
.../2023-04-04-0000-InitialModuleConfig.php | 48 ++++++++++---------
1 file changed, 25 insertions(+), 23 deletions(-)
diff --git a/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php b/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
index 41d5d2a0..94ae74c7 100644
--- a/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
+++ b/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
@@ -32,29 +32,31 @@ class InitialModuleConfig extends AbstractMigration implements MigrationInterfac
*/
public function apply(): void
{
- $data = [
- 'multicustomers' => '0',
- 'enable_logs' => '0',
- 'enable_pix' => 'no',
- 'pix_title' => 'Pix',
- 'pix_qrcode_expiration_time' => 3500,
- 'pix_additional_data' => 'Custom Store PIX',
- 'enable_credit_card' => 'no',
- 'credit_card_title' => 'Credit Card',
- 'cc_operation_type' => '2',
- 'cc_soft_descriptor' => 'Credit Card',
- 'cc_installment_type' => '1',
- 'cc_installments_maximum' => '1',
- 'cc_installments_min_amount' => '',
- 'cc_installments_interest' => '',
- 'cc_installments_interest_increase' => '',
- 'cc_installments_without_interest' => '',
- 'cc_allow_save' => '0',
- 'antifraud_enabled' => '0',
- 'antifraud_min_value' => '',
- self::PARAM => true
- ];
- $this->settings->addData($data)->save();
+ if ($this->validate()) {
+ $data = [
+ 'multicustomers' => '0',
+ 'enable_logs' => '0',
+ 'enable_pix' => 'no',
+ 'pix_title' => 'Pix',
+ 'pix_qrcode_expiration_time' => 3500,
+ 'pix_additional_data' => 'Custom Store PIX',
+ 'enable_credit_card' => 'no',
+ 'credit_card_title' => 'Credit Card',
+ 'cc_operation_type' => '2',
+ 'cc_soft_descriptor' => 'Credit Card',
+ 'cc_installment_type' => '1',
+ 'cc_installments_maximum' => '1',
+ 'cc_installments_min_amount' => '',
+ 'cc_installments_interest' => '',
+ 'cc_installments_interest_increase' => '',
+ 'cc_installments_without_interest' => '',
+ 'cc_allow_save' => '0',
+ 'antifraud_enabled' => '0',
+ 'antifraud_min_value' => '',
+ self::PARAM => true
+ ];
+ $this->settings->addData($data)->save();
+ }
}
/**
From 94389db1e821774e27553c974d4c27cce668c179 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 5 Apr 2023 09:58:29 -0300
Subject: [PATCH 095/156] :sparkles: payment data voucher
---
src/Block/Order/Transaction/AbstractCard.php | 88 +++++++++++++++++++
src/Block/Order/Transaction/CreditCard.php | 67 +-------------
src/Block/Order/Transaction/Voucher.php | 23 +++++
.../{credit-card.phtml => card.phtml} | 0
4 files changed, 112 insertions(+), 66 deletions(-)
create mode 100644 src/Block/Order/Transaction/AbstractCard.php
create mode 100644 src/Block/Order/Transaction/Voucher.php
rename templates/order/transaction/{credit-card.phtml => card.phtml} (100%)
diff --git a/src/Block/Order/Transaction/AbstractCard.php b/src/Block/Order/Transaction/AbstractCard.php
new file mode 100644
index 00000000..7f81e375
--- /dev/null
+++ b/src/Block/Order/Transaction/AbstractCard.php
@@ -0,0 +1,88 @@
+getTransaction() && $this->getTransaction()->getPostData()) {
+ $postData = $this->getTransaction()->getPostData();
+ if (property_exists($postData, 'tran_data')) {
+ $data = $this->jsonSerialize->unserialize($postData->tran_data);
+ foreach ($data as $key => $datum) {
+ if ($key === 'card' && is_array($datum)) {
+ foreach ($datum as $key2 => $datum2) {
+ if (in_array($key2, $this->cardData)) {
+ $value[$this->getLabel($key2)] = $this->convertData($key2, $datum2);
+ }
+ }
+ continue;
+ }
+ if (in_array($key, $this->cardData)) {
+ $value[$this->getLabel($key)] = $this->convertData($key, $datum);
+ }
+ }
+ }
+ }
+ } catch (\Exception $e) {}
+ return $value;
+ }
+
+ /**
+ * @param string $key
+ * @return string|null
+ */
+ private function getLabel(string $key)
+ {
+ return __(ucwords(str_replace('_', ' ', $key)), 'woo-pagarme-payments');
+ }
+
+ /**
+ * @param $key
+ * @param $value
+ * @return String
+ */
+ public function convertData($key, $value)
+ {
+ if ($key === 'amount') {
+ return Utils::format_order_price_to_view($value);
+ }
+ return $value;
+ }
+}
diff --git a/src/Block/Order/Transaction/CreditCard.php b/src/Block/Order/Transaction/CreditCard.php
index deb1ac3b..0035ff6b 100644
--- a/src/Block/Order/Transaction/CreditCard.php
+++ b/src/Block/Order/Transaction/CreditCard.php
@@ -11,78 +11,13 @@
namespace Woocommerce\Pagarme\Block\Order\Transaction;
-use Woocommerce\Pagarme\Helper\Utils;
-
defined( 'ABSPATH' ) || exit;
/**
* Class CreditCard
* @package Woocommerce\Pagarme\Block\Order
*/
-class CreditCard extends AbstractTransaction
+class CreditCard extends AbstractCard
{
- /**
- * @var string
- */
- protected $_template = 'templates/order/transaction/credit-card';
-
- protected $cardData = [
- 'holder_name',
- 'brand',
- 'last_four_digits',
- 'installments',
- 'amount'
- ];
-
- /**
- * @return array
- */
- public function getCardDetails()
- {
- $value = [];
- try {
- if ($this->getTransaction() && $this->getTransaction()->getPostData()) {
- $postData = $this->getTransaction()->getPostData();
- if (property_exists($postData, 'tran_data')) {
- $data = $this->jsonSerialize->unserialize($postData->tran_data);
- foreach ($data as $key => $datum) {
- if ($key === 'card' && is_array($datum)) {
- foreach ($datum as $key2 => $datum2) {
- if (in_array($key2, $this->cardData)) {
- $value[$this->getLabel($key2)] = $this->convertData($key2, $datum2);
- }
- }
- continue;
- }
- if (in_array($key, $this->cardData)) {
- $value[$this->getLabel($key)] = $this->convertData($key, $datum);
- }
- }
- }
- }
- } catch (\Exception $e) {}
- return $value;
- }
-
- /**
- * @param string $key
- * @return string|null
- */
- private function getLabel(string $key)
- {
- return __(ucwords(str_replace('_', ' ', $key)), 'woo-pagarme-payments');
- }
- /**
- * @param $key
- * @param $value
- * @return String
- */
- public function convertData($key, $value)
- {
- if ($key === 'amount') {
- return Utils::format_order_price_to_view($value);
- }
- return $value;
- }
}
diff --git a/src/Block/Order/Transaction/Voucher.php b/src/Block/Order/Transaction/Voucher.php
new file mode 100644
index 00000000..cd3b4bc6
--- /dev/null
+++ b/src/Block/Order/Transaction/Voucher.php
@@ -0,0 +1,23 @@
+
Date: Wed, 5 Apr 2023 08:20:44 -0300
Subject: [PATCH 096/156] Retirada de chamadas para o Model/Setting.php
(depreciado)
---
.../System/Config/Form/AbstractField.php | 4 ++--
.../System/Config/Page/PageSettings.php | 2 +-
src/Controller/Hub.php | 19 ++++++++++---------
src/Controller/HubCommand.php | 6 +++---
.../system/config/form/field/checkbox.phtml | 0
.../config/form/field/hub/environment.phtml | 0
.../config/form/field/hub/integration.phtml | 0
.../system/config/form/field/main.phtml | 0
.../system/config/form/field/select.phtml | 0
.../system/config/form/field/text.phtml | 0
.../system/config/page/settings.phtml | 0
11 files changed, 16 insertions(+), 15 deletions(-)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/form/field/checkbox.phtml (100%)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/form/field/hub/environment.phtml (100%)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/form/field/hub/integration.phtml (100%)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/form/field/main.phtml (100%)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/form/field/select.phtml (100%)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/form/field/text.phtml (100%)
rename {src/View/Admin/templates => templates/adminhtml}/system/config/page/settings.phtml (100%)
diff --git a/src/Block/Adminhtml/System/Config/Form/AbstractField.php b/src/Block/Adminhtml/System/Config/Form/AbstractField.php
index 2d46301c..d5569dc8 100644
--- a/src/Block/Adminhtml/System/Config/Form/AbstractField.php
+++ b/src/Block/Adminhtml/System/Config/Form/AbstractField.php
@@ -26,7 +26,7 @@ abstract class AbstractField
protected $template = 'main.phtml';
/** @var string */
- protected $templatePath = 'View/Admin/templates/system/config/form/field/';
+ protected $templatePath = 'templates/adminhtml/system/config/form/field/';
/** @var mixed|null */
protected $default = null;
@@ -136,7 +136,7 @@ public function getElementCallBack($values)
*/
public function includeTemplate(string $file = 'main.phtml')
{
- include plugin_dir_path(WCMP_ROOT_SRC ) . 'src' . DIRECTORY_SEPARATOR . $this->templatePath . $file;
+ include plugin_dir_path(WCMP_ROOT_SRC ) . DIRECTORY_SEPARATOR . $this->templatePath . $file;
}
/**
diff --git a/src/Block/Adminhtml/System/Config/Page/PageSettings.php b/src/Block/Adminhtml/System/Config/Page/PageSettings.php
index 292bcf53..8be9519b 100644
--- a/src/Block/Adminhtml/System/Config/Page/PageSettings.php
+++ b/src/Block/Adminhtml/System/Config/Page/PageSettings.php
@@ -20,7 +20,7 @@ class PageSettings
{
protected $template = 'settings.phtml';
- protected $templatePath = 'src/View/Admin/templates/system/config/page/';
+ protected $templatePath = 'templates/adminhtml/system/config/page/';
/**
* @var array
diff --git a/src/Controller/Hub.php b/src/Controller/Hub.php
index 2261e5d8..19535e7f 100644
--- a/src/Controller/Hub.php
+++ b/src/Controller/Hub.php
@@ -9,7 +9,7 @@
use Pagarme\Core\Hub\Services\HubIntegrationService;
use Woocommerce\Pagarme\Concrete\WoocommerceCoreSetup as CoreSetup;
use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use Exception;
class Hub
@@ -18,7 +18,7 @@ class Hub
public function __construct()
{
- $this->settings = Setting::get_instance();
+ $this->settings = new Config();
add_action('woocommerce_api_' . Core::get_hub_name(), array($this, 'handle_requests'));
}
@@ -46,28 +46,29 @@ public function updateConfig()
{
$moduleConfig = CoreSetup::getModuleConfiguration();
- $this->settings->set(
+ $this->settings->setData(
'hub_install_id',
$moduleConfig->getHubInstallId()->getValue()
);
- $this->settings->set(
+ $this->settings->setData(
'hub_environment',
$moduleConfig->getHubEnvironment()->getValue()
);
- $this->settings->set(
+ $this->settings->setData(
'production_secret_key',
$moduleConfig->getSecretKey()->getValue()
);
- $this->settings->set(
+ $this->settings->setData(
'production_public_key',
$moduleConfig->getPublicKey()->getValue()
);
- $this->settings->set('sandbox_secret_key', null);
- $this->settings->set('sandbox_public_key', null);
- $this->settings->set('environment', null);
+ $this->settings->setData('sandbox_secret_key', null);
+ $this->settings->setData('sandbox_public_key', null);
+ $this->settings->setData('environment', null);
+ $this->settings->save();
}
}
diff --git a/src/Controller/HubCommand.php b/src/Controller/HubCommand.php
index c3748650..e4c0894f 100644
--- a/src/Controller/HubCommand.php
+++ b/src/Controller/HubCommand.php
@@ -9,7 +9,7 @@
use Pagarme\Core\Hub\Services\HubIntegrationService;
use Woocommerce\Pagarme\Concrete\WoocommerceCoreSetup as CoreSetup;
use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Helper\Utils;
class HubCommand
@@ -21,7 +21,7 @@ class HubCommand
public function __construct()
{
- $this->settings = Setting::get_instance();
+ $this->settings = new Config;
add_action('woocommerce_api_' . Core::get_hub_command_name(), array($this, 'handle_requests'));
}
@@ -87,7 +87,7 @@ private function uninstallCommand()
];
foreach ($keysToClear as $key) {
- $this->settings->set(
+ $this->settings->setData(
$key,
null
);
diff --git a/src/View/Admin/templates/system/config/form/field/checkbox.phtml b/templates/adminhtml/system/config/form/field/checkbox.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/form/field/checkbox.phtml
rename to templates/adminhtml/system/config/form/field/checkbox.phtml
diff --git a/src/View/Admin/templates/system/config/form/field/hub/environment.phtml b/templates/adminhtml/system/config/form/field/hub/environment.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/form/field/hub/environment.phtml
rename to templates/adminhtml/system/config/form/field/hub/environment.phtml
diff --git a/src/View/Admin/templates/system/config/form/field/hub/integration.phtml b/templates/adminhtml/system/config/form/field/hub/integration.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/form/field/hub/integration.phtml
rename to templates/adminhtml/system/config/form/field/hub/integration.phtml
diff --git a/src/View/Admin/templates/system/config/form/field/main.phtml b/templates/adminhtml/system/config/form/field/main.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/form/field/main.phtml
rename to templates/adminhtml/system/config/form/field/main.phtml
diff --git a/src/View/Admin/templates/system/config/form/field/select.phtml b/templates/adminhtml/system/config/form/field/select.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/form/field/select.phtml
rename to templates/adminhtml/system/config/form/field/select.phtml
diff --git a/src/View/Admin/templates/system/config/form/field/text.phtml b/templates/adminhtml/system/config/form/field/text.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/form/field/text.phtml
rename to templates/adminhtml/system/config/form/field/text.phtml
diff --git a/src/View/Admin/templates/system/config/page/settings.phtml b/templates/adminhtml/system/config/page/settings.phtml
similarity index 100%
rename from src/View/Admin/templates/system/config/page/settings.phtml
rename to templates/adminhtml/system/config/page/settings.phtml
From 67cead3ee677fdba654cc4612a20d98e39433d80 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Wed, 5 Apr 2023 08:23:01 -0300
Subject: [PATCH 097/156] =?UTF-8?q?Inserir=20uma=20valida=C3=A7=C3=A3o=20p?=
=?UTF-8?q?ara=20quando=20o=20token=20de=20instala=C3=A7=C3=A3o=20for=20nu?=
=?UTF-8?q?lo.?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../src/Hub/Aggregates/InstallToken.php | 2 +-
.../src/Hub/Services/HubIntegrationService.php | 8 ++++++--
2 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/vendor/pagarme/ecommerce-module-core/src/Hub/Aggregates/InstallToken.php b/vendor/pagarme/ecommerce-module-core/src/Hub/Aggregates/InstallToken.php
index 764fc3d4..2cb1f64a 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Hub/Aggregates/InstallToken.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Hub/Aggregates/InstallToken.php
@@ -7,7 +7,7 @@
final class InstallToken extends AbstractEntity
{
- const LIFE_SPAN = 1800; //time in seconds
+ const LIFE_SPAN = 43200; //time in seconds
/**
*
diff --git a/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php b/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php
index 5b9cb3f6..cfe1c9e9 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php
@@ -59,11 +59,15 @@ public function endHubIntegration(
$installToken = $tokenRepo->findByPagarmeId(new HubInstallToken($installToken));
+ if (is_null($installToken)) {
+ $message = "Received an invalid installToken. NULL: $rawToken";
+ $exception = new \Exception($message);
+ $this->logService->exception($exception);
+ throw $exception;
+ }
if (empty($installToken)) {
$message = "installToken not found in database. Raw Token: $rawToken";
-
$exception = new \Exception($message);
-
$this->logService->exception($exception);
throw $exception;
}
From e145f57b82eba336e75dfae347d1dfa6da2ec139 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 5 Apr 2023 13:54:19 -0300
Subject: [PATCH 098/156] :sparkles: update disintegrate function and
translations
---
src/Controller/Gateways/AbstractGateway.php | 4 +-
src/Controller/Gateways/BilletCreditCard.php | 2 +-
src/Controller/Gateways/CreditCard.php | 2 +-
src/Controller/HubCommand.php | 23 ++----
.../Config/PagarmeCoreConfigManagement.php | 3 +
src/Model/Config/Source/AbstractOptions.php | 3 +-
.../config/form/field/hub/integration.phtml | 75 ++++++++++++++-----
.../system/config/form/field/select.phtml | 2 +-
8 files changed, 73 insertions(+), 41 deletions(-)
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 62c4f06e..affca12e 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -267,10 +267,10 @@ public function field_enabled()
return [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toLabelsArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
'label' => __('Enable', 'woo-pagarme-payments') . ' ' .
__($this->getPaymentMethodTitle(), 'woo-pagarme-payments'),
- 'default' => $this->config->getData('enable_' . $this->method) ?? strtolower(Yesno::NO),
+ 'default' => __($this->config->getData('enable_' . $this->method), 'woo-pagarme-payments') ?? strtolower(Yesno::NO),
];
}
diff --git a/src/Controller/Gateways/BilletCreditCard.php b/src/Controller/Gateways/BilletCreditCard.php
index 907f170c..90411f49 100644
--- a/src/Controller/Gateways/BilletCreditCard.php
+++ b/src/Controller/Gateways/BilletCreditCard.php
@@ -37,7 +37,7 @@ public function field_enabled()
return array(
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toLabelsArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
'label' => __('Enable multi-means (Boleto + Credit card)', 'woo-pagarme-payments'),
'old_name' => 'multimethods_billet_card',
'default' => $this->config->getData('multimethods_billet_card') ?? strtolower(Yesno::NO),
diff --git a/src/Controller/Gateways/CreditCard.php b/src/Controller/Gateways/CreditCard.php
index ed56c1a3..c3b9e9f4 100644
--- a/src/Controller/Gateways/CreditCard.php
+++ b/src/Controller/Gateways/CreditCard.php
@@ -69,7 +69,7 @@ public function field_enabled()
return [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toLabelsArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
'label' => __('Enable credit card', 'woo-pagarme-payments'),
'old_name' => 'enable_credit_card',
'default' => $this->config->getData('enable_credit_card') ?? strtolower(Yesno::NO),
diff --git a/src/Controller/HubCommand.php b/src/Controller/HubCommand.php
index e4c0894f..67565e0c 100644
--- a/src/Controller/HubCommand.php
+++ b/src/Controller/HubCommand.php
@@ -77,22 +77,15 @@ private function sendResponse($message, $code)
private function uninstallCommand()
{
$keysToClear = [
- 'hub_install_id',
- 'hub_environment',
- 'production_secret_key',
- 'production_public_key',
- 'sandbox_secret_key',
- 'sandbox_public_key',
- 'environment'
+ 'hub_install_id' => null,
+ 'hub_environment' => null,
+ 'production_secret_key' => null,
+ 'production_public_key' => null,
+ 'sandbox_secret_key' => null,
+ 'sandbox_public_key' => null,
+ 'environment' => null
];
-
- foreach ($keysToClear as $key) {
- $this->settings->setData(
- $key,
- null
- );
- }
-
+ $this->settings->addData($keysToClear)->save();
return 'Hub uninstalled successfully';
}
}
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index d46717e2..d490fe12 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -167,6 +167,9 @@ public function convertDataSaveVoucherCards($datum)
*/
public function convertDataHubInstallId($datum)
{
+ if (!$datum) {
+ $datum = '00000000-0000-0000-0000-000000000000';
+ }
return new GUID($datum);
}
}
diff --git a/src/Model/Config/Source/AbstractOptions.php b/src/Model/Config/Source/AbstractOptions.php
index cb3326d0..b4c32439 100644
--- a/src/Model/Config/Source/AbstractOptions.php
+++ b/src/Model/Config/Source/AbstractOptions.php
@@ -65,8 +65,7 @@ public function toLabelsArray($translate = false)
$const = $reflectionClass->getConstants();
foreach ($const as $code => $value) {
if (strpos($code, '_VALUE') === false) {
- $value = $translate ? __($value) : $value;
- $options[strtolower($value)] = $value;
+ $options[strtolower($value)] = $translate ? __($value) : $value;
}
}
return $options;
diff --git a/templates/adminhtml/system/config/form/field/hub/integration.phtml b/templates/adminhtml/system/config/form/field/hub/integration.phtml
index 2686f297..8ac5091f 100644
--- a/templates/adminhtml/system/config/form/field/hub/integration.phtml
+++ b/templates/adminhtml/system/config/form/field/hub/integration.phtml
@@ -13,35 +13,72 @@ if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
-
-
getButtonLabel()); ?>
+
+
= esc_attr($this->getButtonLabel()); ?>
config->getHubInstallId()) : ?>
-
-
+
+
= esc_attr(__('Disintegrate', 'woo-pagarme-payments')); ?>
diff --git a/templates/adminhtml/system/config/form/field/select.phtml b/templates/adminhtml/system/config/form/field/select.phtml
index 71eea425..4e1139d9 100644
--- a/templates/adminhtml/system/config/form/field/select.phtml
+++ b/templates/adminhtml/system/config/form/field/select.phtml
@@ -15,6 +15,6 @@ if ( ! defined( 'ABSPATH' ) ) {
?>
getReadonly() ? '' : 'readonly' ; ?>>
getOptions() as $option) : ?>
- getCurrent(), $option['value'], true) ?>>= esc_html($option['label']) ?>
+ getCurrent(), $option['value'], true) ?>>= esc_html(__($option['label'], 'woo-pagarme-payments')) ?>
From 4a0840a1da83298b17e1d5694b989685ad9486b6 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 6 Apr 2023 18:27:20 -0300
Subject: [PATCH 099/156] Bugs no Checkout
---
.../front/checkout/model/multicustomers.js | 6 +++---
.../checkout/model/payment/card/wallet.js | 6 +++---
.../checkout/model/payment/order-value.js | 6 +++---
.../front/checkout/model/payment/pix.js | 6 +++---
.../config/form/field/hub/integration.phtml | 1 +
.../ValueObjects/Configuration/CardConfig.php | 19 ++++++++-----------
6 files changed, 21 insertions(+), 23 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/multicustomers.js b/assets/javascripts/front/checkout/model/multicustomers.js
index 5a239ba5..050fd6db 100644
--- a/assets/javascripts/front/checkout/model/multicustomers.js
+++ b/assets/javascripts/front/checkout/model/multicustomers.js
@@ -11,9 +11,9 @@ jQuery(function ($) {
return true;
},
start: function () {
- if (this.isStarted()) {
- return;
- }
+ // if (this.isStarted()) {
+ // return;
+ // }
this.addEventListener();
},
addEventListener: function () {
diff --git a/assets/javascripts/front/checkout/model/payment/card/wallet.js b/assets/javascripts/front/checkout/model/payment/card/wallet.js
index 1cf19d8b..efe95474 100644
--- a/assets/javascripts/front/checkout/model/payment/card/wallet.js
+++ b/assets/javascripts/front/checkout/model/payment/card/wallet.js
@@ -32,9 +32,9 @@ let pagarmeWallet = {
});
},
start: function () {
- if (this.isStarted()) {
- return;
- }
+ // if (this.isStarted()) {
+ // return;
+ // }
this.addEventListener();
},
}
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index 602b4959..985c89b7 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -11,9 +11,9 @@ let pagarmeOrderValue = {
return true;
},
start: function () {
- if (this.isStarted()) {
- return;
- }
+ // if (this.isStarted()) {
+ // return;
+ // }
this.addEventListener();
},
fillAnotherInput: async function (e) {
diff --git a/assets/javascripts/front/checkout/model/payment/pix.js b/assets/javascripts/front/checkout/model/payment/pix.js
index 35ba6f82..6382e9c4 100644
--- a/assets/javascripts/front/checkout/model/payment/pix.js
+++ b/assets/javascripts/front/checkout/model/payment/pix.js
@@ -10,9 +10,9 @@ let pagarmePix = {
return true;
},
start: function () {
- if (this.isStarted()) {
- return;
- }
+ // if (this.isStarted()) {
+ // return;
+ // }
this.addEventListener();
},
addEventListener: function () {
diff --git a/templates/adminhtml/system/config/form/field/hub/integration.phtml b/templates/adminhtml/system/config/form/field/hub/integration.phtml
index 8ac5091f..08bff326 100644
--- a/templates/adminhtml/system/config/form/field/hub/integration.phtml
+++ b/templates/adminhtml/system/config/form/field/hub/integration.phtml
@@ -61,6 +61,7 @@ if ( ! defined( 'ABSPATH' ) ) {
'= esc_attr(__('Integration keys successfully removed. Reload the page.', 'woo-pagarme-payments')); ?>',
'success'
)
+ document.location.reload(true);
},
fail: function (response) {
swal(
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/CardConfig.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/CardConfig.php
index 3e6903cf..ab6a6c29 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/CardConfig.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/CardConfig.php
@@ -11,7 +11,7 @@ final class CardConfig extends AbstractValueObject
{
/**
*
- * @var bool
+ * @var bool
*/
private $enabled;
/**
@@ -21,28 +21,28 @@ final class CardConfig extends AbstractValueObject
private $brand;
/**
*
- * @var int
+ * @var int
*/
private $maxInstallment;
/**
*
- * @var int
+ * @var int
*/
private $maxInstallmentWithoutInterest;
/**
*
- * @var float
+ * @var float
*/
private $initialInterest;
/**
*
- * @var float
+ * @var float
*/
private $incrementalInterest;
/**
*
- * @var int
+ * @var int
*/
private $minValue;
@@ -139,10 +139,7 @@ private function setMaxInstallmentWithoutInterest($maxInstallmentWithoutInterest
new Installment($newMaxInstallmentWithoutInterest, 1, 0);
if ($newMaxInstallmentWithoutInterest > $this->maxInstallment) {
- throw new InvalidParamException(
- "'Max installment without interest' must be equal or smaller than 'Max Installments'! ",
- $maxInstallmentWithoutInterest
- );
+ $newMaxInstallmentWithoutInterest = $this->maxInstallment;
}
$this->maxInstallmentWithoutInterest = $newMaxInstallmentWithoutInterest;
@@ -302,4 +299,4 @@ protected function isEqual($object)
$this->incrementalInterest === $object->getIncrementalInterest() &&
$this->minValue === $object->getMinValue();
}
-}
\ No newline at end of file
+}
From 58bac8c16a32808fdd11aebf9994593a66b78b2f Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 6 Apr 2023 18:35:17 -0300
Subject: [PATCH 100/156] Wallet - Autocomplete
---
templates/checkout/form/card/wallet.phtml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/templates/checkout/form/card/wallet.phtml b/templates/checkout/form/card/wallet.phtml
index ff0c3353..81726ede 100644
--- a/templates/checkout/form/card/wallet.phtml
+++ b/templates/checkout/form/card/wallet.phtml
@@ -21,7 +21,7 @@ if (!function_exists('add_action')) {
= __('Cards save', 'woo-pagarme-payments'); ?>
-
+
= __('Saved credit card', 'woo-pagarme-payments'); ?>
getPaymentInstance()->getCards() as $card) : ?>
Date: Mon, 10 Apr 2023 09:55:57 -0300
Subject: [PATCH 101/156] :sparkles: translate and new features
---
.../javascripts/front/checkout/model/payment/pix.js | 11 ++++++++++-
assets/stylesheets/front/style.css | 2 +-
woo-pagarme-payments.php | 1 -
3 files changed, 11 insertions(+), 3 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/pix.js b/assets/javascripts/front/checkout/model/payment/pix.js
index 6382e9c4..24038057 100644
--- a/assets/javascripts/front/checkout/model/payment/pix.js
+++ b/assets/javascripts/front/checkout/model/payment/pix.js
@@ -30,7 +30,16 @@ let pagarmePix = {
}).appendTo(elem.parent()).select();
document.execCommand('copy', false);
input.remove();
- alert("Código copiado.");
+ const message = {
+ type: 'success',
+ html: 'Código copiado.',
+ allowOutsideClick: false
+ };
+ try {
+ swal(message);
+ } catch (e) {
+ new swal(message);
+ }
}
}
pagarmePix.start();
diff --git a/assets/stylesheets/front/style.css b/assets/stylesheets/front/style.css
index 93be2945..70c45274 100644
--- a/assets/stylesheets/front/style.css
+++ b/assets/stylesheets/front/style.css
@@ -961,7 +961,7 @@ body .swal2-animate-x-mark {
margin: 20px auto 20px auto;
padding: 6px;
text-align: center;
- width: 200px;
+ max-width: 200px;
}
#wcmp-checkout-errors {
diff --git a/woo-pagarme-payments.php b/woo-pagarme-payments.php
index c2918328..e7b8780c 100644
--- a/woo-pagarme-payments.php
+++ b/woo-pagarme-payments.php
@@ -79,7 +79,6 @@ function wcmp_plugins_loaded_check()
{
$woocommerce = class_exists('WooCommerce');
$checkout_fields = class_exists('Extra_Checkout_Fields_For_Brazil');
-
add_action( 'in_plugin_update_message-' . WCMP_PLUGIN_BASE, function( $plugin_data ) {
versionUpdateWarning( WCMP_VERSION, $plugin_data['new_version'] );
} );
From c61e54534a74ad42be30bb2fbc613eee50a72406 Mon Sep 17 00:00:00 2001
From: Claudio Hessel
Date: Fri, 18 Nov 2022 19:35:06 -0300
Subject: [PATCH 102/156] PAOPN-94: add multi-buyer on voucher payments
---
.../ecommerce-module-core/src/Kernel/Services/OrderService.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php
index 0da41cd3..99734e32 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php
@@ -257,6 +257,7 @@ public function createOrderAtPagarme(PlatformOrderInterface $platformOrder)
//build PaymentOrder based on platformOrder
$paymentOrder = $this->extractPaymentOrderFromPlatformOrder($platformOrder);
+ $orderInfo = $this->getOrderInfo($platformOrder);
$i18n = new LocalizationService();
From a05a9724fb14f3fd4c5801ea3faba5325bb99a69 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Thiago=20Sim=C3=B5es=20Gon=C3=A7alves?=
Date: Tue, 17 Jan 2023 17:52:12 -0300
Subject: [PATCH 103/156] Convert CircleCI
---
.github/workflows/pr.yml | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 2ebf0f88..de869482 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -51,11 +51,10 @@ jobs:
steps:
- name: Checkout project
uses: actions/checkout@v3
- with:
- fetch-depth: 0
- name: Run Sonar
uses: sonarsource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
+
From fdcb3542c12cff311a527d82b748bf185731c8df Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 13 Apr 2023 16:56:31 -0300
Subject: [PATCH 104/156] delete deprecated files
---
assets/javascripts/boot.js | 9 -
assets/javascripts/front/built.js | 3429 -----------------
assets/javascripts/front/libs/index.php | 2 -
assets/javascripts/front/main.js | 873 -----
assets/javascripts/front/templates/index.php | 2 -
assets/javascripts/front/vendor/index.php | 2 -
src/Block/Checkout/Form/Installments.php | 9 +-
src/Controller/Gateways.php | 1269 ------
src/Model/PaymentTemp.php | 429 ---
src/View/Admin/html-checkbox-field.php | 18 -
src/View/Admin/html-hub-enviroment.php | 19 -
.../Admin/html-hub-integration-button.php | 80 -
src/View/Admin/html-select-field.php | 19 -
src/View/Admin/html-text-field.php | 18 -
src/View/Checkouts.php | 488 ---
src/View/Orders.php | 167 -
src/View/index.php | 2 -
17 files changed, 8 insertions(+), 6827 deletions(-)
delete mode 100644 assets/javascripts/boot.js
delete mode 100755 assets/javascripts/front/built.js
delete mode 100644 assets/javascripts/front/libs/index.php
delete mode 100644 assets/javascripts/front/main.js
delete mode 100644 assets/javascripts/front/templates/index.php
delete mode 100644 assets/javascripts/front/vendor/index.php
delete mode 100644 src/Controller/Gateways.php
delete mode 100644 src/Model/PaymentTemp.php
delete mode 100644 src/View/Admin/html-checkbox-field.php
delete mode 100644 src/View/Admin/html-hub-enviroment.php
delete mode 100644 src/View/Admin/html-hub-integration-button.php
delete mode 100644 src/View/Admin/html-select-field.php
delete mode 100644 src/View/Admin/html-text-field.php
delete mode 100644 src/View/Checkouts.php
delete mode 100644 src/View/Orders.php
delete mode 100644 src/View/index.php
diff --git a/assets/javascripts/boot.js b/assets/javascripts/boot.js
deleted file mode 100644
index ef7689c3..00000000
--- a/assets/javascripts/boot.js
+++ /dev/null
@@ -1,9 +0,0 @@
-jQuery(function($) {
- var context = $( 'body' );
-
- Pagarme.vars = {
- body : context
- };
-
- Pagarme.Application.init.apply( null, [context] );
-});
diff --git a/assets/javascripts/front/built.js b/assets/javascripts/front/built.js
deleted file mode 100755
index b5566fa6..00000000
--- a/assets/javascripts/front/built.js
+++ /dev/null
@@ -1,3429 +0,0 @@
-;
-(function(context, $) {
-
- 'use strict';
-
- var MONSTER = function(namespace, callback) {
- var parts = namespace.split('\.'),
- parent = context,
- count = parts.length,
- i = 0;
-
- for (i; i < count; i++) {
- parent[parts[i]] = (count - 1 === i) ? MONSTER.Builder() : parent[parts[i]] || {};
- parent = parent[parts[i]];
- }
-
- if ('function' === typeof callback) {
-
- if (!~namespace.indexOf('Components')) {
- parent.click = MONSTER.click.bind(parent);
- parent.ajax = MONSTER.ajax.bind(parent);
- }
-
- callback.call(null, parent, $, MONSTER.utils);
- }
-
- return parent;
- };
-
- MONSTER.getElements = function(context) {
- var elements = {},
- byElement = this.byElement.bind(context);
-
- context.find('[data-element]').each(function(index, element) {
- var name = this.utils.toDataSetName(element.dataset.element);
-
- if (!elements[name]) {
- elements[name] = byElement(element.dataset.element);
- }
- }.bind(this));
-
- return elements;
- };
-
- MONSTER.byAction = function(name, el) {
- var container = (el || this);
- return container.find('[data-action="' + name + '"]');
- };
-
- MONSTER.byElement = function(name) {
- return this.find('[data-element="' + name + '"]');
- };
-
- MONSTER.event = function(instance, event, action) {
- var handle = MONSTER.utils.getEventCallbackName(action, event);
- this.byAction(action).on(event, $.proxy(instance, handle));
- };
-
- MONSTER.getInstance = function(instance, context) {
- context.byAction = this.byAction.bind(context);
- instance.$el = context;
- instance.data = context.data();
- instance.on = this.event.bind(context, instance);
- instance.elements = this.getElements(context);
- instance.addPrefix = this.utils.addPrefix;
- instance.prefix = this.utils.prefix();
- instance.ajax = this.ajax.bind(instance);
- instance.click = this.click.bind(instance);
-
- return instance;
- };
-
- MONSTER.Builder = function() {
- var Kernel, Builder;
- var self = this;
-
- Kernel = function() {};
- Builder = function(context) {
- var instance = new Kernel();
- instance = self.getInstance(instance, context);
-
- instance.start.apply(instance, arguments);
-
- return instance;
- };
-
- Builder.fn = Builder.prototype;
- Kernel.prototype = Builder.fn;
- Builder.fn.start = function() {};
-
- return Builder;
- };
-
- MONSTER.ajax = function(options, done, fail) {
- var ajax, defaults = {
- method: 'POST',
- url: MONSTER.utils.getAjaxUrl(),
- data: {}
- };
-
- ajax = $.ajax($.extend(defaults, (options || {})));
-
- ajax.done($.proxy(this, (done || '_done')));
- ajax.fail($.proxy(this, (fail || '_fail')));
- };
-
- MONSTER.click = function(action, context) {
- var instance = (context || this);
- MONSTER.byAction(action, instance.$el).on('click', $.proxy(instance, MONSTER.utils.getEventCallbackName(action)));
- };
-
- MONSTER.utils = {
-
- getGlobalVars: function(name) {
- return (window.PagarmeGlobalVars || {})[name];
- },
-
- prefix: function() {
- return (this.getGlobalVars('prefix') || 'monster')
- },
-
- getAjaxUrl: function() {
- return this.getGlobalVars('ajaxUrl');
- },
-
- getLocale: function() {
- return this.getGlobalVars('WPLANG');
- },
-
- getSpinnerUrl: function() {
- return this.getGlobalVars('spinnerUrl');
- },
-
- getPathUrl: function(url) {
- return decodeURIComponent(url).split(/[?#]/)[0];
- },
-
- getTime: function() {
- return (new Date()).getTime();
- },
-
- encodeUrl: function(url) {
- return encodeURIComponent(url);
- },
-
- decodeUrl: function(url) {
- return decodeURIComponent(url);
- },
-
- ucfirst: function(text) {
- return this.parseName(text, /(\b[a-z])/g);
- },
-
- toDataSetName: function(text) {
- return this.parseName(text, /(-)\w/g);
- },
-
- hasParam: function() {
- return ~window.location.href.indexOf('?');
- },
-
- getPathName: function() {
- return window.location.pathname;
- },
-
- getEventCallbackName: function(action, event) {
- return this.ucfirst(['_on', (event || 'click'), action].join('-'));
- },
-
- addPrefix: function(tag, separator) {
- var sep = (separator || '-');
- return this.prefix() + sep + tag;
- },
-
- getSpinner: function() {
- var img = document.createElement('img');
- img.src = this.getSpinnerUrl();
- img.className = this.prefix() + '-spinner';
-
- return img;
- },
-
- isMobile: function() {
- return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|Tablet OS|IEMobile|Opera Mini/i.test(
- navigator.userAgent
- ));
- },
-
- parseName: function(text, regex) {
- return text.replace(regex, function(match) {
- return match.toUpperCase();
- }).replace(/-/g, '');
- },
-
- remove: function(element) {
- element.fadeOut('fast', function() {
- element.remove();
- });
- },
-
- getId: function(id) {
- if (!id) {
- return false;
- }
-
- return document.getElementById(id);
- },
-
- findComponent: function(selector, callback) {
- var components = $(this).find(selector);
-
- if (components.length && typeof callback === 'function') {
- callback.call(null, components, $(this));
- }
-
- return components.length;
- },
-
- get: function(key, defaultVal) {
- var query, vars, varsLength, pair, i;
-
- if (!this.hasParam()) {
- return (defaultVal || '');
- }
-
- query = window.location.search.substring(1);
- vars = query.split('&');
- varsLength = vars.length;
-
- for (i = 0; i < varsLength; i++) {
- pair = vars[i].split('=');
-
- if (pair[0] === key) {
- return pair[1];
- }
- }
-
- return (defaultVal || '');
- },
-
- strToCode: function(str) {
- var hash = 0,
- strLen = str.length,
- i, chr;
-
- if (!strLen) {
- return hash;
- }
-
- for (i = 0; i < strLen; i++) {
- chr = str.charCodeAt(i);
- hash = ((hash << 5) - hash) + chr;
- hash |= 0;
- }
-
- return Math.abs(hash);
- }
- };
-
- context.MONSTER = MONSTER;
-
-})(window, jQuery);;
-MONSTER('Pagarme.BuildComponents', function(Model, $, utils) {
-
- Model.create = function(container) {
- var components = '[data-' + utils.addPrefix('component') + ']',
- findComponent = utils.findComponent.bind(container);
-
- findComponent(components, $.proxy(this, '_start'));
- };
-
- Model._start = function(components) {
- if (typeof Pagarme.Components === 'undefined') {
- return;
- }
-
- this._iterator(components);
- };
-
- Model._iterator = function(components) {
- var name;
-
- components.each(function(index, component) {
- component = $(component);
- name = utils.ucfirst(this.getComponent(component));
- this._callback(name, component);
- }.bind(this));
- };
-
- Model.getComponent = function(component) {
- var component = component.data(utils.addPrefix('component'));
-
- if (!component) {
- return '';
- }
-
- return component;
- };
-
- Model._callback = function(name, component) {
- var callback = Pagarme.Components[name];
-
- if (typeof callback == 'function') {
- callback.call(null, component);
- return;
- }
-
- console.log('Component "' + name + '" is not a function.');
- };
-
-}, {});;
-MONSTER('Pagarme.BuildCreate', function(Model, $, utils) {
-
- Model.init = function(container, names) {
- if (!names.length) {
- return;
- }
-
- this.$el = container;
- names.forEach(this.findNames.bind(this));
- };
-
- Model.findNames = function(name, index) {
- this.callback(Pagarme[utils.ucfirst(name)]);
- };
-
- Model.callback = function(callback) {
- if (typeof callback !== 'function') {
- return;
- }
-
- callback.create(this.$el);
- };
-
-}, {});;
-/**
- * jquery.mask.js
- * @version: v1.14.10
- * @author: Igor Escobar
- *
- * Created by Igor Escobar on 2012-03-10. Please report any bug at http://blog.igorescobar.com
- *
- * Copyright (c) 2012 Igor Escobar http://blog.igorescobar.com
- *
- * The MIT License (http://www.opensource.org/licenses/mit-license.php)
- *
- * Permission is hereby granted, free of charge, to any person
- * obtaining a copy of this software and associated documentation
- * files (the "Software"), to deal in the Software without
- * restriction, including without limitation the rights to use,
- * copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following
- * conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- * OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/* jshint laxbreak: true */
-/* jshint maxcomplexity:17 */
-/* global define */
-
-'use strict';
-
-// UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.
-// https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js
-(function(factory, jQuery, Zepto) {
-
- if (typeof define === 'function' && define.amd) {
- define(['jquery'], factory);
- } else if (typeof exports === 'object') {
- module.exports = factory(require('jquery'));
- } else {
- factory(jQuery || Zepto);
- }
-
-}(function($) {
-
- var Mask = function(el, mask, options) {
-
- var p = {
- invalid: [],
- getCaret: function() {
- try {
- var sel,
- pos = 0,
- ctrl = el.get(0),
- dSel = document.selection,
- cSelStart = ctrl.selectionStart;
-
- // IE Support
- if (dSel && navigator.appVersion.indexOf('MSIE 10') === -1) {
- sel = dSel.createRange();
- sel.moveStart('character', -p.val().length);
- pos = sel.text.length;
- }
- // Firefox support
- else if (cSelStart || cSelStart === '0') {
- pos = cSelStart;
- }
-
- return pos;
- } catch (e) {}
- },
- setCaret: function(pos) {
- try {
- if (el.is(':focus')) {
- var range, ctrl = el.get(0);
-
- // Firefox, WebKit, etc..
- if (ctrl.setSelectionRange) {
- ctrl.setSelectionRange(pos, pos);
- } else { // IE
- range = ctrl.createTextRange();
- range.collapse(true);
- range.moveEnd('character', pos);
- range.moveStart('character', pos);
- range.select();
- }
- }
- } catch (e) {}
- },
- events: function() {
- el
- .on('keydown.mask', function(e) {
- el.data('mask-keycode', e.keyCode || e.which);
- el.data('mask-previus-value', el.val());
- })
- .on($.jMaskGlobals.useInput ? 'input.mask' : 'keyup.mask', p.behaviour)
- .on('paste.mask drop.mask', function() {
- setTimeout(function() {
- el.keydown().keyup();
- }, 100);
- })
- .on('change.mask', function() {
- el.data('changed', true);
- })
- .on('blur.mask', function() {
- if (oldValue !== p.val() && !el.data('changed')) {
- el.trigger('change');
- }
- el.data('changed', false);
- })
- // it's very important that this callback remains in this position
- // otherwhise oldValue it's going to work buggy
- .on('blur.mask', function() {
- oldValue = p.val();
- })
- // select all text on focus
- .on('focus.mask', function(e) {
- if (options.selectOnFocus === true) {
- $(e.target).select();
- }
- })
- // clear the value if it not complete the mask
- .on('focusout.mask', function() {
- if (options.clearIfNotMatch && !regexMask.test(p.val())) {
- p.val('');
- }
- });
- },
- getRegexMask: function() {
- var maskChunks = [],
- translation, pattern, optional, recursive, oRecursive, r;
-
- for (var i = 0; i < mask.length; i++) {
- translation = jMask.translation[mask.charAt(i)];
-
- if (translation) {
-
- pattern = translation.pattern.toString().replace(/.{1}$|^.{1}/g, '');
- optional = translation.optional;
- recursive = translation.recursive;
-
- if (recursive) {
- maskChunks.push(mask.charAt(i));
- oRecursive = { digit: mask.charAt(i), pattern: pattern };
- } else {
- maskChunks.push(!optional && !recursive ? pattern : (pattern + '?'));
- }
-
- } else {
- maskChunks.push(mask.charAt(i).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
- }
- }
-
- r = maskChunks.join('');
-
- if (oRecursive) {
- r = r.replace(new RegExp('(' + oRecursive.digit + '(.*' + oRecursive.digit + ')?)'), '($1)?')
- .replace(new RegExp(oRecursive.digit, 'g'), oRecursive.pattern);
- }
-
- return new RegExp(r);
- },
- destroyEvents: function() {
- el.off(['input', 'keydown', 'keyup', 'paste', 'drop', 'blur', 'focusout', ''].join('.mask '));
- },
- val: function(v) {
- var isInput = el.is('input'),
- method = isInput ? 'val' : 'text',
- r;
-
- if (arguments.length > 0) {
- if (el[method]() !== v) {
- el[method](v);
- }
- r = el;
- } else {
- r = el[method]();
- }
-
- return r;
- },
- calculateCaretPosition: function(caretPos, newVal) {
- var newValL = newVal.length,
- oValue = el.data('mask-previus-value') || '',
- oValueL = oValue.length;
-
- // edge cases when erasing digits
- if (el.data('mask-keycode') === 8 && oValue !== newVal) {
- caretPos = caretPos - (newVal.slice(0, caretPos).length - oValue.slice(0, caretPos).length);
-
- // edge cases when typing new digits
- } else if (oValue !== newVal) {
- // if the cursor is at the end keep it there
- if (caretPos >= oValueL) {
- caretPos = newValL;
- } else {
- caretPos = caretPos + (newVal.slice(0, caretPos).length - oValue.slice(0, caretPos).length);
- }
- }
-
- return caretPos;
- },
- behaviour: function(e) {
- e = e || window.event;
- p.invalid = [];
-
- var keyCode = el.data('mask-keycode');
-
- if ($.inArray(keyCode, jMask.byPassKeys) === -1) {
- var newVal = p.getMasked(),
- caretPos = p.getCaret();
-
- setTimeout(function(caretPos, newVal) {
- p.setCaret(p.calculateCaretPosition(caretPos, newVal));
- }, 10, caretPos, newVal);
-
- p.val(newVal);
- p.setCaret(caretPos);
- return p.callbacks(e);
- }
- },
- getMasked: function(skipMaskChars, val) {
- var buf = [],
- value = val === undefined ? p.val() : val + '',
- m = 0,
- maskLen = mask.length,
- v = 0,
- valLen = value.length,
- offset = 1,
- addMethod = 'push',
- resetPos = -1,
- lastMaskChar,
- check;
-
- if (options.reverse) {
- addMethod = 'unshift';
- offset = -1;
- lastMaskChar = 0;
- m = maskLen - 1;
- v = valLen - 1;
- check = function() {
- return m > -1 && v > -1;
- };
- } else {
- lastMaskChar = maskLen - 1;
- check = function() {
- return m < maskLen && v < valLen;
- };
- }
-
- var lastUntranslatedMaskChar;
- while (check()) {
- var maskDigit = mask.charAt(m),
- valDigit = value.charAt(v),
- translation = jMask.translation[maskDigit];
-
- if (translation) {
- if (valDigit.match(translation.pattern)) {
- buf[addMethod](valDigit);
- if (translation.recursive) {
- if (resetPos === -1) {
- resetPos = m;
- } else if (m === lastMaskChar) {
- m = resetPos - offset;
- }
-
- if (lastMaskChar === resetPos) {
- m -= offset;
- }
- }
- m += offset;
- } else if (valDigit === lastUntranslatedMaskChar) {
- // matched the last untranslated (raw) mask character that we encountered
- // likely an insert offset the mask character from the last entry; fall
- // through and only increment v
- lastUntranslatedMaskChar = undefined;
- } else if (translation.optional) {
- m += offset;
- v -= offset;
- } else if (translation.fallback) {
- buf[addMethod](translation.fallback);
- m += offset;
- v -= offset;
- } else {
- p.invalid.push({ p: v, v: valDigit, e: translation.pattern });
- }
- v += offset;
- } else {
- if (!skipMaskChars) {
- buf[addMethod](maskDigit);
- }
-
- if (valDigit === maskDigit) {
- v += offset;
- } else {
- lastUntranslatedMaskChar = maskDigit;
- }
-
- m += offset;
- }
- }
-
- var lastMaskCharDigit = mask.charAt(lastMaskChar);
- if (maskLen === valLen + 1 && !jMask.translation[lastMaskCharDigit]) {
- buf.push(lastMaskCharDigit);
- }
-
- return buf.join('');
- },
- callbacks: function(e) {
- var val = p.val(),
- changed = val !== oldValue,
- defaultArgs = [val, e, el, options],
- callback = function(name, criteria, args) {
- if (typeof options[name] === 'function' && criteria) {
- options[name].apply(this, args);
- }
- };
-
- callback('onChange', changed === true, defaultArgs);
- callback('onKeyPress', changed === true, defaultArgs);
- callback('onComplete', val.length === mask.length, defaultArgs);
- callback('onInvalid', p.invalid.length > 0, [val, e, el, p.invalid, options]);
- }
- };
-
- el = $(el);
- var jMask = this,
- oldValue = p.val(),
- regexMask;
-
- mask = typeof mask === 'function' ? mask(p.val(), undefined, el, options) : mask;
-
- // public methods
- jMask.mask = mask;
- jMask.options = options;
- jMask.remove = function() {
- var caret = p.getCaret();
- p.destroyEvents();
- p.val(jMask.getCleanVal());
- p.setCaret(caret);
- return el;
- };
-
- // get value without mask
- jMask.getCleanVal = function() {
- return p.getMasked(true);
- };
-
- // get masked value without the value being in the input or element
- jMask.getMaskedVal = function(val) {
- return p.getMasked(false, val);
- };
-
- jMask.init = function(onlyMask) {
- onlyMask = onlyMask || false;
- options = options || {};
-
- jMask.clearIfNotMatch = $.jMaskGlobals.clearIfNotMatch;
- jMask.byPassKeys = $.jMaskGlobals.byPassKeys;
- jMask.translation = $.extend({}, $.jMaskGlobals.translation, options.translation);
-
- jMask = $.extend(true, {}, jMask, options);
-
- regexMask = p.getRegexMask();
-
- if (onlyMask) {
- p.events();
- p.val(p.getMasked());
- } else {
- if (options.placeholder) {
- el.attr('placeholder', options.placeholder);
- }
-
- // this is necessary, otherwise if the user submit the form
- // and then press the "back" button, the autocomplete will erase
- // the data. Works fine on IE9+, FF, Opera, Safari.
- if (el.data('mask')) {
- el.attr('autocomplete', 'off');
- }
-
- // detect if is necessary let the user type freely.
- // for is a lot faster than forEach.
- for (var i = 0, maxlength = true; i < mask.length; i++) {
- var translation = jMask.translation[mask.charAt(i)];
- if (translation && translation.recursive) {
- maxlength = false;
- break;
- }
- }
-
- if (maxlength) {
- el.attr('maxlength', mask.length);
- }
-
- p.destroyEvents();
- p.events();
-
- var caret = p.getCaret();
- p.val(p.getMasked());
- p.setCaret(caret);
- }
- };
-
- jMask.init(!el.is('input'));
- };
-
- $.maskWatchers = {};
- var HTMLAttributes = function() {
- var input = $(this),
- options = {},
- prefix = 'data-mask-',
- mask = input.attr('data-mask');
-
- if (input.attr(prefix + 'reverse')) {
- options.reverse = true;
- }
-
- if (input.attr(prefix + 'clearifnotmatch')) {
- options.clearIfNotMatch = true;
- }
-
- if (input.attr(prefix + 'selectonfocus') === 'true') {
- options.selectOnFocus = true;
- }
-
- if (notSameMaskObject(input, mask, options)) {
- return input.data('mask', new Mask(this, mask, options));
- }
- },
- notSameMaskObject = function(field, mask, options) {
- options = options || {};
- var maskObject = $(field).data('mask'),
- stringify = JSON.stringify,
- value = $(field).val() || $(field).text();
- try {
- if (typeof mask === 'function') {
- mask = mask(value);
- }
- return typeof maskObject !== 'object' || stringify(maskObject.options) !== stringify(options) || maskObject.mask !== mask;
- } catch (e) {}
- },
- eventSupported = function(eventName) {
- var el = document.createElement('div'),
- isSupported;
-
- eventName = 'on' + eventName;
- isSupported = (eventName in el);
-
- if (!isSupported) {
- el.setAttribute(eventName, 'return;');
- isSupported = typeof el[eventName] === 'function';
- }
- el = null;
-
- return isSupported;
- };
-
- $.fn.mask = function(mask, options) {
- options = options || {};
- var selector = this.selector,
- globals = $.jMaskGlobals,
- interval = globals.watchInterval,
- watchInputs = options.watchInputs || globals.watchInputs,
- maskFunction = function() {
- if (notSameMaskObject(this, mask, options)) {
- return $(this).data('mask', new Mask(this, mask, options));
- }
- };
-
- $(this).each(maskFunction);
-
- if (selector && selector !== '' && watchInputs) {
- clearInterval($.maskWatchers[selector]);
- $.maskWatchers[selector] = setInterval(function() {
- $(document).find(selector).each(maskFunction);
- }, interval);
- }
- return this;
- };
-
- $.fn.masked = function(val) {
- return this.data('mask').getMaskedVal(val);
- };
-
- $.fn.unmask = function() {
- clearInterval($.maskWatchers[this.selector]);
- delete $.maskWatchers[this.selector];
- return this.each(function() {
- var dataMask = $(this).data('mask');
- if (dataMask) {
- dataMask.remove().removeData('mask');
- }
- });
- };
-
- $.fn.cleanVal = function() {
- return this.data('mask').getCleanVal();
- };
-
- $.applyDataMask = function(selector) {
- selector = selector || $.jMaskGlobals.maskElements;
- var $selector = (selector instanceof $) ? selector : $(selector);
- $selector.filter($.jMaskGlobals.dataMaskAttr).each(HTMLAttributes);
- };
-
- var globals = {
- maskElements: 'input,td,span,div',
- dataMaskAttr: '*[data-mask]',
- dataMask: true,
- watchInterval: 300,
- watchInputs: true,
- // old versions of chrome dont work great with input event
- useInput: !/Chrome\/[2-4][0-9]|SamsungBrowser/.test(window.navigator.userAgent) && eventSupported('input'),
- watchDataMask: false,
- byPassKeys: [9, 16, 17, 18, 36, 37, 38, 39, 40, 91],
- translation: {
- '0': { pattern: /\d/ },
- '9': { pattern: /\d/, optional: true },
- '#': { pattern: /\d/, recursive: true },
- 'A': { pattern: /[a-zA-Z0-9]/ },
- 'S': { pattern: /[a-zA-Z]/ }
- }
- };
-
- $.jMaskGlobals = $.jMaskGlobals || {};
- globals = $.jMaskGlobals = $.extend(true, {}, globals, $.jMaskGlobals);
-
- // looking for inputs with data-mask attribute
- if (globals.dataMask) {
- $.applyDataMask();
- }
-
- setInterval(function() {
- if ($.jMaskGlobals.watchDataMask) {
- $.applyDataMask();
- }
- }, globals.watchInterval);
-}, window.jQuery, window.Zepto));;;
-(function($) {
-
- $.fn.isEmptyValue = function() {
- return !($.trim(this.val()));
- };
-
-})(jQuery);;
-/*!
- * sweetalert2 v6.6.2
- * Released under the MIT License.
- */
-(function(global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global.Sweetalert2 = factory());
-}(this, (function() {
- 'use strict';
-
- var defaultParams = {
- title: '',
- titleText: '',
- text: '',
- html: '',
- type: null,
- customClass: '',
- target: 'body',
- animation: true,
- allowOutsideClick: true,
- allowEscapeKey: true,
- allowEnterKey: true,
- showConfirmButton: true,
- showCancelButton: false,
- preConfirm: null,
- confirmButtonText: 'OK',
- confirmButtonColor: '#3085d6',
- confirmButtonClass: null,
- cancelButtonText: 'Cancel',
- cancelButtonColor: '#aaa',
- cancelButtonClass: null,
- buttonsStyling: true,
- reverseButtons: false,
- focusCancel: false,
- showCloseButton: false,
- showLoaderOnConfirm: false,
- imageUrl: null,
- imageWidth: null,
- imageHeight: null,
- imageClass: null,
- timer: null,
- width: 500,
- padding: 20,
- background: '#fff',
- input: null,
- inputPlaceholder: '',
- inputValue: '',
- inputOptions: {},
- inputAutoTrim: true,
- inputClass: null,
- inputAttributes: {},
- inputValidator: null,
- progressSteps: [],
- currentProgressStep: null,
- progressStepsDistance: '40px',
- onOpen: null,
- onClose: null
- };
-
- var swalPrefix = 'swal2-';
-
- var prefix = function prefix(items) {
- var result = {};
- for (var i in items) {
- result[items[i]] = swalPrefix + items[i];
- }
- return result;
- };
-
- var swalClasses = prefix(['container', 'shown', 'iosfix', 'modal', 'overlay', 'fade', 'show', 'hide', 'noanimation', 'close', 'title', 'content', 'buttonswrapper', 'confirm', 'cancel', 'icon', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea', 'inputerror', 'validationerror', 'progresssteps', 'activeprogressstep', 'progresscircle', 'progressline', 'loading', 'styled']);
-
- var iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
-
- /*
- * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color)
- */
- var colorLuminance = function colorLuminance(hex, lum) {
- // Validate hex string
- hex = String(hex).replace(/[^0-9a-f]/gi, '');
- if (hex.length < 6) {
- hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
- }
- lum = lum || 0;
-
- // Convert to decimal and change luminosity
- var rgb = '#';
- for (var i = 0; i < 3; i++) {
- var c = parseInt(hex.substr(i * 2, 2), 16);
- c = Math.round(Math.min(Math.max(0, c + c * lum), 255)).toString(16);
- rgb += ('00' + c).substr(c.length);
- }
-
- return rgb;
- };
-
- var uniqueArray = function uniqueArray(arr) {
- var result = [];
- for (var i in arr) {
- if (result.indexOf(arr[i]) === -1) {
- result.push(arr[i]);
- }
- }
- return result;
- };
-
- /* global MouseEvent */
-
- // Remember state in cases where opening and handling a modal will fiddle with it.
- var states = {
- previousWindowKeyDown: null,
- previousActiveElement: null,
- previousBodyPadding: null
- };
-
- /*
- * Add modal + overlay to DOM
- */
- var init = function init(params) {
- if (typeof document === 'undefined') {
- console.error('SweetAlert2 requires document to initialize');
- return;
- }
-
- var container = document.createElement('div');
- container.className = swalClasses.container;
- container.innerHTML = sweetHTML;
-
- var targetElement = document.querySelector(params.target);
- if (!targetElement) {
- console.warn('SweetAlert2: Can\'t find the target "' + params.target + '"');
- targetElement = document.body;
- }
- targetElement.appendChild(container);
-
- var modal = getModal();
- var input = getChildByClass(modal, swalClasses.input);
- var file = getChildByClass(modal, swalClasses.file);
- var range = modal.querySelector('.' + swalClasses.range + ' input');
- var rangeOutput = modal.querySelector('.' + swalClasses.range + ' output');
- var select = getChildByClass(modal, swalClasses.select);
- var checkbox = modal.querySelector('.' + swalClasses.checkbox + ' input');
- var textarea = getChildByClass(modal, swalClasses.textarea);
-
- input.oninput = function() {
- sweetAlert.resetValidationError();
- };
-
- input.onkeydown = function(event) {
- setTimeout(function() {
- if (event.keyCode === 13 && params.allowEnterKey) {
- event.stopPropagation();
- sweetAlert.clickConfirm();
- }
- }, 0);
- };
-
- file.onchange = function() {
- sweetAlert.resetValidationError();
- };
-
- range.oninput = function() {
- sweetAlert.resetValidationError();
- rangeOutput.value = range.value;
- };
-
- range.onchange = function() {
- sweetAlert.resetValidationError();
- range.previousSibling.value = range.value;
- };
-
- select.onchange = function() {
- sweetAlert.resetValidationError();
- };
-
- checkbox.onchange = function() {
- sweetAlert.resetValidationError();
- };
-
- textarea.oninput = function() {
- sweetAlert.resetValidationError();
- };
-
- return modal;
- };
-
- /*
- * Manipulate DOM
- */
-
- var sweetHTML = ('\n \n
\n
\n \n
\n
?
\n
!
\n
i
\n
\n
\n
\n
\n
\n
\n
\n \n \n
\n
\n
\n
\n \n \n
\n
\n
\n OK \n Cancel \n
\n
× \n
\n').replace(/(^|\n)\s*/g, '');
-
- var getContainer = function getContainer() {
- return document.body.querySelector('.' + swalClasses.container);
- };
-
- var getModal = function getModal() {
- return getContainer() ? getContainer().querySelector('.' + swalClasses.modal) : null;
- };
-
- var getIcons = function getIcons() {
- var modal = getModal();
- return modal.querySelectorAll('.' + swalClasses.icon);
- };
-
- var elementByClass = function elementByClass(className) {
- return getContainer() ? getContainer().querySelector('.' + className) : null;
- };
-
- var getTitle = function getTitle() {
- return elementByClass(swalClasses.title);
- };
-
- var getContent = function getContent() {
- return elementByClass(swalClasses.content);
- };
-
- var getImage = function getImage() {
- return elementByClass(swalClasses.image);
- };
-
- var getButtonsWrapper = function getButtonsWrapper() {
- return elementByClass(swalClasses.buttonswrapper);
- };
-
- var getProgressSteps = function getProgressSteps() {
- return elementByClass(swalClasses.progresssteps);
- };
-
- var getValidationError = function getValidationError() {
- return elementByClass(swalClasses.validationerror);
- };
-
- var getConfirmButton = function getConfirmButton() {
- return elementByClass(swalClasses.confirm);
- };
-
- var getCancelButton = function getCancelButton() {
- return elementByClass(swalClasses.cancel);
- };
-
- var getCloseButton = function getCloseButton() {
- return elementByClass(swalClasses.close);
- };
-
- var getFocusableElements = function getFocusableElements(focusCancel) {
- var buttons = [getConfirmButton(), getCancelButton()];
- if (focusCancel) {
- buttons.reverse();
- }
- var focusableElements = buttons.concat(Array.prototype.slice.call(getModal().querySelectorAll('button, input:not([type=hidden]), textarea, select, a, *[tabindex]:not([tabindex="-1"])')));
- return uniqueArray(focusableElements);
- };
-
- var hasClass = function hasClass(elem, className) {
- if (elem.classList) {
- return elem.classList.contains(className);
- }
- return false;
- };
-
- var focusInput = function focusInput(input) {
- input.focus();
-
- // place cursor at end of text in text input
- if (input.type !== 'file') {
- // http://stackoverflow.com/a/2345915/1331425
- var val = input.value;
- input.value = '';
- input.value = val;
- }
- };
-
- var addClass = function addClass(elem, className) {
- if (!elem || !className) {
- return;
- }
- var classes = className.split(/\s+/).filter(Boolean);
- classes.forEach(function(className) {
- elem.classList.add(className);
- });
- };
-
- var removeClass = function removeClass(elem, className) {
- if (!elem || !className) {
- return;
- }
- var classes = className.split(/\s+/).filter(Boolean);
- classes.forEach(function(className) {
- elem.classList.remove(className);
- });
- };
-
- var getChildByClass = function getChildByClass(elem, className) {
- for (var i = 0; i < elem.childNodes.length; i++) {
- if (hasClass(elem.childNodes[i], className)) {
- return elem.childNodes[i];
- }
- }
- };
-
- var show = function show(elem, display) {
- if (!display) {
- display = 'block';
- }
- elem.style.opacity = '';
- elem.style.display = display;
- };
-
- var hide = function hide(elem) {
- elem.style.opacity = '';
- elem.style.display = 'none';
- };
-
- var empty = function empty(elem) {
- while (elem.firstChild) {
- elem.removeChild(elem.firstChild);
- }
- };
-
- // borrowed from jqeury $(elem).is(':visible') implementation
- var isVisible = function isVisible(elem) {
- return elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length;
- };
-
- var removeStyleProperty = function removeStyleProperty(elem, property) {
- if (elem.style.removeProperty) {
- elem.style.removeProperty(property);
- } else {
- elem.style.removeAttribute(property);
- }
- };
-
- var fireClick = function fireClick(node) {
- if (!isVisible(node)) {
- return false;
- }
-
- // Taken from http://www.nonobtrusive.com/2011/11/29/programatically-fire-crossbrowser-click-event-with-javascript/
- // Then fixed for today's Chrome browser.
- if (typeof MouseEvent === 'function') {
- // Up-to-date approach
- var mevt = new MouseEvent('click', {
- view: window,
- bubbles: false,
- cancelable: true
- });
- node.dispatchEvent(mevt);
- } else if (document.createEvent) {
- // Fallback
- var evt = document.createEvent('MouseEvents');
- evt.initEvent('click', false, false);
- node.dispatchEvent(evt);
- } else if (document.createEventObject) {
- node.fireEvent('onclick');
- } else if (typeof node.onclick === 'function') {
- node.onclick();
- }
- };
-
- var animationEndEvent = function() {
- var testEl = document.createElement('div');
- var transEndEventNames = {
- 'WebkitAnimation': 'webkitAnimationEnd',
- 'OAnimation': 'oAnimationEnd oanimationend',
- 'msAnimation': 'MSAnimationEnd',
- 'animation': 'animationend'
- };
- for (var i in transEndEventNames) {
- if (transEndEventNames.hasOwnProperty(i) && testEl.style[i] !== undefined) {
- return transEndEventNames[i];
- }
- }
-
- return false;
- }();
-
- // Reset previous window keydown handler and focued element
- var resetPrevState = function resetPrevState() {
- window.onkeydown = states.previousWindowKeyDown;
- if (states.previousActiveElement && states.previousActiveElement.focus) {
- var x = window.scrollX;
- var y = window.scrollY;
- states.previousActiveElement.focus();
- if (x && y) {
- // IE has no scrollX/scrollY support
- window.scrollTo(x, y);
- }
- }
- };
-
- // Measure width of scrollbar
- // https://github.com/twbs/bootstrap/blob/master/js/modal.js#L279-L286
- var measureScrollbar = function measureScrollbar() {
- var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
- if (supportsTouch) {
- return 0;
- }
- var scrollDiv = document.createElement('div');
- scrollDiv.style.width = '50px';
- scrollDiv.style.height = '50px';
- scrollDiv.style.overflow = 'scroll';
- document.body.appendChild(scrollDiv);
- var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
- document.body.removeChild(scrollDiv);
- return scrollbarWidth;
- };
-
- // JavaScript Debounce Function
- // Simplivied version of https://davidwalsh.name/javascript-debounce-function
- var debounce = function debounce(func, wait) {
- var timeout = void 0;
- return function() {
- var later = function later() {
- timeout = null;
- func();
- };
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
- };
- };
-
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
- return typeof obj;
- } : function(obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var _extends = Object.assign || function(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
-
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
-
- return target;
- };
-
- var modalParams = _extends({}, defaultParams);
- var queue = [];
- var swal2Observer = void 0;
-
- /*
- * Set type, text and actions on modal
- */
- var setParameters = function setParameters(params) {
- var modal = getModal() || init(params);
-
- for (var param in params) {
- if (!defaultParams.hasOwnProperty(param) && param !== 'extraParams') {
- console.warn('SweetAlert2: Unknown parameter "' + param + '"');
- }
- }
-
- // Set modal width
- modal.style.width = typeof params.width === 'number' ? params.width + 'px' : params.width;
-
- modal.style.padding = params.padding + 'px';
- modal.style.background = params.background;
- var successIconParts = modal.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
- for (var i = 0; i < successIconParts.length; i++) {
- successIconParts[i].style.background = params.background;
- }
-
- var title = getTitle();
- var content = getContent();
- var buttonsWrapper = getButtonsWrapper();
- var confirmButton = getConfirmButton();
- var cancelButton = getCancelButton();
- var closeButton = getCloseButton();
-
- // Title
- if (params.titleText) {
- title.innerText = params.titleText;
- } else {
- title.innerHTML = params.title.split('\n').join(' ');
- }
-
- // Content
- if (params.text || params.html) {
- if (_typeof(params.html) === 'object') {
- content.innerHTML = '';
- if (0 in params.html) {
- for (var _i = 0; _i in params.html; _i++) {
- content.appendChild(params.html[_i].cloneNode(true));
- }
- } else {
- content.appendChild(params.html.cloneNode(true));
- }
- } else if (params.html) {
- content.innerHTML = params.html;
- } else if (params.text) {
- content.textContent = params.text;
- }
- show(content);
- } else {
- hide(content);
- }
-
- // Close button
- if (params.showCloseButton) {
- show(closeButton);
- } else {
- hide(closeButton);
- }
-
- // Custom Class
- modal.className = swalClasses.modal;
- if (params.customClass) {
- addClass(modal, params.customClass);
- }
-
- // Progress steps
- var progressStepsContainer = getProgressSteps();
- var currentProgressStep = parseInt(params.currentProgressStep === null ? sweetAlert.getQueueStep() : params.currentProgressStep, 10);
- if (params.progressSteps.length) {
- show(progressStepsContainer);
- empty(progressStepsContainer);
- if (currentProgressStep >= params.progressSteps.length) {
- console.warn('SweetAlert2: Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
- }
- params.progressSteps.forEach(function(step, index) {
- var circle = document.createElement('li');
- addClass(circle, swalClasses.progresscircle);
- circle.innerHTML = step;
- if (index === currentProgressStep) {
- addClass(circle, swalClasses.activeprogressstep);
- }
- progressStepsContainer.appendChild(circle);
- if (index !== params.progressSteps.length - 1) {
- var line = document.createElement('li');
- addClass(line, swalClasses.progressline);
- line.style.width = params.progressStepsDistance;
- progressStepsContainer.appendChild(line);
- }
- });
- } else {
- hide(progressStepsContainer);
- }
-
- // Icon
- var icons = getIcons();
- for (var _i2 = 0; _i2 < icons.length; _i2++) {
- hide(icons[_i2]);
- }
- if (params.type) {
- var validType = false;
- for (var iconType in iconTypes) {
- if (params.type === iconType) {
- validType = true;
- break;
- }
- }
- if (!validType) {
- console.error('SweetAlert2: Unknown alert type: ' + params.type);
- return false;
- }
- var icon = modal.querySelector('.' + swalClasses.icon + '.' + iconTypes[params.type]);
- show(icon);
-
- // Animate icon
- if (params.animation) {
- switch (params.type) {
- case 'success':
- addClass(icon, 'swal2-animate-success-icon');
- addClass(icon.querySelector('.swal2-success-line-tip'), 'swal2-animate-success-line-tip');
- addClass(icon.querySelector('.swal2-success-line-long'), 'swal2-animate-success-line-long');
- break;
- case 'error':
- addClass(icon, 'swal2-animate-error-icon');
- addClass(icon.querySelector('.swal2-x-mark'), 'swal2-animate-x-mark');
- break;
- default:
- break;
- }
- }
- }
-
- // Custom image
- var image = getImage();
- if (params.imageUrl) {
- image.setAttribute('src', params.imageUrl);
- show(image);
-
- if (params.imageWidth) {
- image.setAttribute('width', params.imageWidth);
- } else {
- image.removeAttribute('width');
- }
-
- if (params.imageHeight) {
- image.setAttribute('height', params.imageHeight);
- } else {
- image.removeAttribute('height');
- }
-
- image.className = swalClasses.image;
- if (params.imageClass) {
- addClass(image, params.imageClass);
- }
- } else {
- hide(image);
- }
-
- // Cancel button
- if (params.showCancelButton) {
- cancelButton.style.display = 'inline-block';
- } else {
- hide(cancelButton);
- }
-
- // Confirm button
- if (params.showConfirmButton) {
- removeStyleProperty(confirmButton, 'display');
- } else {
- hide(confirmButton);
- }
-
- // Buttons wrapper
- if (!params.showConfirmButton && !params.showCancelButton) {
- hide(buttonsWrapper);
- } else {
- show(buttonsWrapper);
- }
-
- // Edit text on cancel and confirm buttons
- confirmButton.innerHTML = params.confirmButtonText;
- cancelButton.innerHTML = params.cancelButtonText;
-
- // Set buttons to selected background colors
- if (params.buttonsStyling) {
- confirmButton.style.backgroundColor = params.confirmButtonColor;
- cancelButton.style.backgroundColor = params.cancelButtonColor;
- }
-
- // Add buttons custom classes
- confirmButton.className = swalClasses.confirm;
- addClass(confirmButton, params.confirmButtonClass);
- cancelButton.className = swalClasses.cancel;
- addClass(cancelButton, params.cancelButtonClass);
-
- // Buttons styling
- if (params.buttonsStyling) {
- addClass(confirmButton, swalClasses.styled);
- addClass(cancelButton, swalClasses.styled);
- } else {
- removeClass(confirmButton, swalClasses.styled);
- removeClass(cancelButton, swalClasses.styled);
-
- confirmButton.style.backgroundColor = confirmButton.style.borderLeftColor = confirmButton.style.borderRightColor = '';
- cancelButton.style.backgroundColor = cancelButton.style.borderLeftColor = cancelButton.style.borderRightColor = '';
- }
-
- // CSS animation
- if (params.animation === true) {
- removeClass(modal, swalClasses.noanimation);
- } else {
- addClass(modal, swalClasses.noanimation);
- }
- };
-
- /*
- * Animations
- */
- var openModal = function openModal(animation, onComplete) {
- var container = getContainer();
- var modal = getModal();
-
- if (animation) {
- addClass(modal, swalClasses.show);
- addClass(container, swalClasses.fade);
- removeClass(modal, swalClasses.hide);
- } else {
- removeClass(modal, swalClasses.fade);
- }
- show(modal);
-
- // scrolling is 'hidden' until animation is done, after that 'auto'
- container.style.overflowY = 'hidden';
- if (animationEndEvent && !hasClass(modal, swalClasses.noanimation)) {
- modal.addEventListener(animationEndEvent, function swalCloseEventFinished() {
- modal.removeEventListener(animationEndEvent, swalCloseEventFinished);
- container.style.overflowY = 'auto';
- });
- } else {
- container.style.overflowY = 'auto';
- }
-
- addClass(document.documentElement, swalClasses.shown);
- addClass(document.body, swalClasses.shown);
- addClass(container, swalClasses.shown);
- fixScrollbar();
- iOSfix();
- states.previousActiveElement = document.activeElement;
- if (onComplete !== null && typeof onComplete === 'function') {
- setTimeout(function() {
- onComplete(modal);
- });
- }
- };
-
- var fixScrollbar = function fixScrollbar() {
- // for queues, do not do this more than once
- if (states.previousBodyPadding !== null) {
- return;
- }
- // if the body has overflow
- if (document.body.scrollHeight > window.innerHeight) {
- // add padding so the content doesn't shift after removal of scrollbar
- states.previousBodyPadding = document.body.style.paddingRight;
- document.body.style.paddingRight = measureScrollbar() + 'px';
- }
- };
-
- var undoScrollbar = function undoScrollbar() {
- if (states.previousBodyPadding !== null) {
- document.body.style.paddingRight = states.previousBodyPadding;
- states.previousBodyPadding = null;
- }
- };
-
- // Fix iOS scrolling http://stackoverflow.com/q/39626302/1331425
- var iOSfix = function iOSfix() {
- var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
- if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
- var offset = document.body.scrollTop;
- document.body.style.top = offset * -1 + 'px';
- addClass(document.body, swalClasses.iosfix);
- }
- };
-
- var undoIOSfix = function undoIOSfix() {
- if (hasClass(document.body, swalClasses.iosfix)) {
- var offset = parseInt(document.body.style.top, 10);
- removeClass(document.body, swalClasses.iosfix);
- document.body.style.top = '';
- document.body.scrollTop = offset * -1;
- }
- };
-
- // SweetAlert entry point
- var sweetAlert = function sweetAlert() {
- for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- if (args[0] === undefined) {
- console.error('SweetAlert2 expects at least 1 attribute!');
- return false;
- }
-
- var params = _extends({}, modalParams);
-
- switch (_typeof(args[0])) {
- case 'string':
- params.title = args[0];
- params.html = args[1];
- params.type = args[2];
-
- break;
-
- case 'object':
- _extends(params, args[0]);
- params.extraParams = args[0].extraParams;
-
- if (params.input === 'email' && params.inputValidator === null) {
- params.inputValidator = function(email) {
- return new Promise(function(resolve, reject) {
- var emailRegex = /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
- if (emailRegex.test(email)) {
- resolve();
- } else {
- reject('Invalid email address');
- }
- });
- };
- }
-
- if (params.input === 'url' && params.inputValidator === null) {
- params.inputValidator = function(url) {
- return new Promise(function(resolve, reject) {
- var urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;
- if (urlRegex.test(url)) {
- resolve();
- } else {
- reject('Invalid URL');
- }
- });
- };
- }
- break;
-
- default:
- console.error('SweetAlert2: Unexpected type of argument! Expected "string" or "object", got ' + _typeof(args[0]));
- return false;
- }
-
- setParameters(params);
-
- var container = getContainer();
- var modal = getModal();
-
- return new Promise(function(resolve, reject) {
- // Close on timer
- if (params.timer) {
- modal.timeout = setTimeout(function() {
- sweetAlert.closeModal(params.onClose);
- reject('timer');
- }, params.timer);
- }
-
- // Get input element by specified type or, if type isn't specified, by params.input
- var getInput = function getInput(inputType) {
- inputType = inputType || params.input;
- if (!inputType) {
- return null;
- }
- switch (inputType) {
- case 'select':
- case 'textarea':
- case 'file':
- return getChildByClass(modal, swalClasses[inputType]);
- case 'checkbox':
- return modal.querySelector('.' + swalClasses.checkbox + ' input');
- case 'radio':
- return modal.querySelector('.' + swalClasses.radio + ' input:checked') || modal.querySelector('.' + swalClasses.radio + ' input:first-child');
- case 'range':
- return modal.querySelector('.' + swalClasses.range + ' input');
- default:
- return getChildByClass(modal, swalClasses.input);
- }
- };
-
- // Get the value of the modal input
- var getInputValue = function getInputValue() {
- var input = getInput();
- if (!input) {
- return null;
- }
- switch (params.input) {
- case 'checkbox':
- return input.checked ? 1 : 0;
- case 'radio':
- return input.checked ? input.value : null;
- case 'file':
- return input.files.length ? input.files[0] : null;
- default:
- return params.inputAutoTrim ? input.value.trim() : input.value;
- }
- };
-
- // input autofocus
- if (params.input) {
- setTimeout(function() {
- var input = getInput();
- if (input) {
- focusInput(input);
- }
- }, 0);
- }
-
- var confirm = function confirm(value) {
- if (params.showLoaderOnConfirm) {
- sweetAlert.showLoading();
- }
-
- if (params.preConfirm) {
- params.preConfirm(value, params.extraParams).then(function(preConfirmValue) {
- sweetAlert.closeModal(params.onClose);
- resolve(preConfirmValue || value);
- }, function(error) {
- sweetAlert.hideLoading();
- if (error) {
- sweetAlert.showValidationError(error);
- }
- });
- } else {
- sweetAlert.closeModal(params.onClose);
- resolve(value);
- }
- };
-
- // Mouse interactions
- var onButtonEvent = function onButtonEvent(event) {
- var e = event || window.event;
- var target = e.target || e.srcElement;
- var confirmButton = getConfirmButton();
- var cancelButton = getCancelButton();
- var targetedConfirm = confirmButton && (confirmButton === target || confirmButton.contains(target));
- var targetedCancel = cancelButton && (cancelButton === target || cancelButton.contains(target));
-
- switch (e.type) {
- case 'mouseover':
- case 'mouseup':
- if (params.buttonsStyling) {
- if (targetedConfirm) {
- confirmButton.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.1);
- } else if (targetedCancel) {
- cancelButton.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.1);
- }
- }
- break;
- case 'mouseout':
- if (params.buttonsStyling) {
- if (targetedConfirm) {
- confirmButton.style.backgroundColor = params.confirmButtonColor;
- } else if (targetedCancel) {
- cancelButton.style.backgroundColor = params.cancelButtonColor;
- }
- }
- break;
- case 'mousedown':
- if (params.buttonsStyling) {
- if (targetedConfirm) {
- confirmButton.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.2);
- } else if (targetedCancel) {
- cancelButton.style.backgroundColor = colorLuminance(params.cancelButtonColor, -0.2);
- }
- }
- break;
- case 'click':
- // Clicked 'confirm'
- if (targetedConfirm && sweetAlert.isVisible()) {
- sweetAlert.disableButtons();
- if (params.input) {
- var inputValue = getInputValue();
-
- if (params.inputValidator) {
- sweetAlert.disableInput();
- params.inputValidator(inputValue, params.extraParams).then(function() {
- sweetAlert.enableButtons();
- sweetAlert.enableInput();
- confirm(inputValue);
- }, function(error) {
- sweetAlert.enableButtons();
- sweetAlert.enableInput();
- if (error) {
- sweetAlert.showValidationError(error);
- }
- });
- } else {
- confirm(inputValue);
- }
- } else {
- confirm(true);
- }
-
- // Clicked 'cancel'
- } else if (targetedCancel && sweetAlert.isVisible()) {
- sweetAlert.disableButtons();
- sweetAlert.closeModal(params.onClose);
- reject('cancel');
- }
- break;
- default:
- }
- };
-
- var buttons = modal.querySelectorAll('button');
- for (var i = 0; i < buttons.length; i++) {
- buttons[i].onclick = onButtonEvent;
- buttons[i].onmouseover = onButtonEvent;
- buttons[i].onmouseout = onButtonEvent;
- buttons[i].onmousedown = onButtonEvent;
- }
-
- // Closing modal by close button
- getCloseButton().onclick = function() {
- sweetAlert.closeModal(params.onClose);
- reject('close');
- };
-
- // Closing modal by overlay click
- container.onclick = function(e) {
- if (e.target !== container) {
- return;
- }
- if (params.allowOutsideClick) {
- sweetAlert.closeModal(params.onClose);
- reject('overlay');
- }
- };
-
- var buttonsWrapper = getButtonsWrapper();
- var confirmButton = getConfirmButton();
- var cancelButton = getCancelButton();
-
- // Reverse buttons (Confirm on the right side)
- if (params.reverseButtons) {
- confirmButton.parentNode.insertBefore(cancelButton, confirmButton);
- } else {
- confirmButton.parentNode.insertBefore(confirmButton, cancelButton);
- }
-
- // Focus handling
- var setFocus = function setFocus(index, increment) {
- var focusableElements = getFocusableElements(params.focusCancel);
- // search for visible elements and select the next possible match
- for (var _i3 = 0; _i3 < focusableElements.length; _i3++) {
- index = index + increment;
-
- // rollover to first item
- if (index === focusableElements.length) {
- index = 0;
-
- // go to last item
- } else if (index === -1) {
- index = focusableElements.length - 1;
- }
-
- // determine if element is visible
- var el = focusableElements[index];
- if (isVisible(el)) {
- return el.focus();
- }
- }
- };
-
- var handleKeyDown = function handleKeyDown(event) {
- var e = event || window.event;
- var keyCode = e.keyCode || e.which;
-
- if ([9, 13, 32, 27, 37, 38, 39, 40].indexOf(keyCode) === -1) {
- // Don't do work on keys we don't care about.
- return;
- }
-
- var targetElement = e.target || e.srcElement;
-
- var focusableElements = getFocusableElements(params.focusCancel);
- var btnIndex = -1; // Find the button - note, this is a nodelist, not an array.
- for (var _i4 = 0; _i4 < focusableElements.length; _i4++) {
- if (targetElement === focusableElements[_i4]) {
- btnIndex = _i4;
- break;
- }
- }
-
- // TAB
- if (keyCode === 9) {
- if (!e.shiftKey) {
- // Cycle to the next button
- setFocus(btnIndex, 1);
- } else {
- // Cycle to the prev button
- setFocus(btnIndex, -1);
- }
- e.stopPropagation();
- e.preventDefault();
-
- // ARROWS - switch focus between buttons
- } else if (keyCode === 37 || keyCode === 38 || keyCode === 39 || keyCode === 40) {
- // focus Cancel button if Confirm button is currently focused
- if (document.activeElement === confirmButton && isVisible(cancelButton)) {
- cancelButton.focus();
- // and vice versa
- } else if (document.activeElement === cancelButton && isVisible(confirmButton)) {
- confirmButton.focus();
- }
-
- // ENTER/SPACE
- } else if (keyCode === 13 || keyCode === 32) {
- if (btnIndex === -1 && params.allowEnterKey) {
- // ENTER/SPACE clicked outside of a button.
- if (params.focusCancel) {
- fireClick(cancelButton, e);
- } else {
- fireClick(confirmButton, e);
- }
- e.stopPropagation();
- e.preventDefault();
- }
-
- // ESC
- } else if (keyCode === 27 && params.allowEscapeKey === true) {
- sweetAlert.closeModal(params.onClose);
- reject('esc');
- }
- };
-
- states.previousWindowKeyDown = window.onkeydown;
- window.onkeydown = handleKeyDown;
-
- // Loading state
- if (params.buttonsStyling) {
- confirmButton.style.borderLeftColor = params.confirmButtonColor;
- confirmButton.style.borderRightColor = params.confirmButtonColor;
- }
-
- /**
- * Show spinner instead of Confirm button and disable Cancel button
- */
- sweetAlert.showLoading = sweetAlert.enableLoading = function() {
- show(buttonsWrapper);
- show(confirmButton, 'inline-block');
- addClass(buttonsWrapper, swalClasses.loading);
- addClass(modal, swalClasses.loading);
- confirmButton.disabled = true;
- cancelButton.disabled = true;
- };
-
- /**
- * Show spinner instead of Confirm button and disable Cancel button
- */
- sweetAlert.hideLoading = sweetAlert.disableLoading = function() {
- if (!params.showConfirmButton) {
- hide(confirmButton);
- if (!params.showCancelButton) {
- hide(getButtonsWrapper());
- }
- }
- removeClass(buttonsWrapper, swalClasses.loading);
- removeClass(modal, swalClasses.loading);
- confirmButton.disabled = false;
- cancelButton.disabled = false;
- };
-
- sweetAlert.getTitle = function() {
- return getTitle();
- };
- sweetAlert.getContent = function() {
- return getContent();
- };
- sweetAlert.getInput = function() {
- return getInput();
- };
- sweetAlert.getImage = function() {
- return getImage();
- };
- sweetAlert.getButtonsWrapper = function() {
- return getButtonsWrapper();
- };
- sweetAlert.getConfirmButton = function() {
- return getConfirmButton();
- };
- sweetAlert.getCancelButton = function() {
- return getCancelButton();
- };
-
- sweetAlert.enableButtons = function() {
- confirmButton.disabled = false;
- cancelButton.disabled = false;
- };
-
- sweetAlert.disableButtons = function() {
- confirmButton.disabled = true;
- cancelButton.disabled = true;
- };
-
- sweetAlert.enableConfirmButton = function() {
- confirmButton.disabled = false;
- };
-
- sweetAlert.disableConfirmButton = function() {
- confirmButton.disabled = true;
- };
-
- sweetAlert.enableInput = function() {
- var input = getInput();
- if (!input) {
- return false;
- }
- if (input.type === 'radio') {
- var radiosContainer = input.parentNode.parentNode;
- var radios = radiosContainer.querySelectorAll('input');
- for (var _i5 = 0; _i5 < radios.length; _i5++) {
- radios[_i5].disabled = false;
- }
- } else {
- input.disabled = false;
- }
- };
-
- sweetAlert.disableInput = function() {
- var input = getInput();
- if (!input) {
- return false;
- }
- if (input && input.type === 'radio') {
- var radiosContainer = input.parentNode.parentNode;
- var radios = radiosContainer.querySelectorAll('input');
- for (var _i6 = 0; _i6 < radios.length; _i6++) {
- radios[_i6].disabled = true;
- }
- } else {
- input.disabled = true;
- }
- };
-
- // Set modal min-height to disable scrolling inside the modal
- sweetAlert.recalculateHeight = debounce(function() {
- var modal = getModal();
- if (!modal) {
- return;
- }
- var prevState = modal.style.display;
- modal.style.minHeight = '';
- show(modal);
- modal.style.minHeight = modal.scrollHeight + 1 + 'px';
- modal.style.display = prevState;
- }, 50);
-
- // Show block with validation error
- sweetAlert.showValidationError = function(error) {
- var validationError = getValidationError();
- validationError.innerHTML = error;
- show(validationError);
-
- var input = getInput();
- if (input) {
- focusInput(input);
- addClass(input, swalClasses.inputerror);
- }
- };
-
- // Hide block with validation error
- sweetAlert.resetValidationError = function() {
- var validationError = getValidationError();
- hide(validationError);
- sweetAlert.recalculateHeight();
-
- var input = getInput();
- if (input) {
- removeClass(input, swalClasses.inputerror);
- }
- };
-
- sweetAlert.getProgressSteps = function() {
- return params.progressSteps;
- };
-
- sweetAlert.setProgressSteps = function(progressSteps) {
- params.progressSteps = progressSteps;
- setParameters(params);
- };
-
- sweetAlert.showProgressSteps = function() {
- show(getProgressSteps());
- };
-
- sweetAlert.hideProgressSteps = function() {
- hide(getProgressSteps());
- };
-
- sweetAlert.enableButtons();
- sweetAlert.hideLoading();
- sweetAlert.resetValidationError();
-
- // inputs
- var inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
- var input = void 0;
- for (var _i7 = 0; _i7 < inputTypes.length; _i7++) {
- var inputClass = swalClasses[inputTypes[_i7]];
- var inputContainer = getChildByClass(modal, inputClass);
- input = getInput(inputTypes[_i7]);
-
- // set attributes
- if (input) {
- for (var j in input.attributes) {
- if (input.attributes.hasOwnProperty(j)) {
- var attrName = input.attributes[j].name;
- if (attrName !== 'type' && attrName !== 'value') {
- input.removeAttribute(attrName);
- }
- }
- }
- for (var attr in params.inputAttributes) {
- input.setAttribute(attr, params.inputAttributes[attr]);
- }
- }
-
- // set class
- inputContainer.className = inputClass;
- if (params.inputClass) {
- addClass(inputContainer, params.inputClass);
- }
-
- hide(inputContainer);
- }
-
- var populateInputOptions = void 0;
- switch (params.input) {
- case 'text':
- case 'email':
- case 'password':
- case 'number':
- case 'tel':
- case 'url':
- input = getChildByClass(modal, swalClasses.input);
- input.value = params.inputValue;
- input.placeholder = params.inputPlaceholder;
- input.type = params.input;
- show(input);
- break;
- case 'file':
- input = getChildByClass(modal, swalClasses.file);
- input.placeholder = params.inputPlaceholder;
- input.type = params.input;
- show(input);
- break;
- case 'range':
- var range = getChildByClass(modal, swalClasses.range);
- var rangeInput = range.querySelector('input');
- var rangeOutput = range.querySelector('output');
- rangeInput.value = params.inputValue;
- rangeInput.type = params.input;
- rangeOutput.value = params.inputValue;
- show(range);
- break;
- case 'select':
- var select = getChildByClass(modal, swalClasses.select);
- select.innerHTML = '';
- if (params.inputPlaceholder) {
- var placeholder = document.createElement('option');
- placeholder.innerHTML = params.inputPlaceholder;
- placeholder.value = '';
- placeholder.disabled = true;
- placeholder.selected = true;
- select.appendChild(placeholder);
- }
- populateInputOptions = function populateInputOptions(inputOptions) {
- for (var optionValue in inputOptions) {
- var option = document.createElement('option');
- option.value = optionValue;
- option.innerHTML = inputOptions[optionValue];
- if (params.inputValue === optionValue) {
- option.selected = true;
- }
- select.appendChild(option);
- }
- show(select);
- select.focus();
- };
- break;
- case 'radio':
- var radio = getChildByClass(modal, swalClasses.radio);
- radio.innerHTML = '';
- populateInputOptions = function populateInputOptions(inputOptions) {
- for (var radioValue in inputOptions) {
- var radioInput = document.createElement('input');
- var radioLabel = document.createElement('label');
- var radioLabelSpan = document.createElement('span');
- radioInput.type = 'radio';
- radioInput.name = swalClasses.radio;
- radioInput.value = radioValue;
- if (params.inputValue === radioValue) {
- radioInput.checked = true;
- }
- radioLabelSpan.innerHTML = inputOptions[radioValue];
- radioLabel.appendChild(radioInput);
- radioLabel.appendChild(radioLabelSpan);
- radioLabel.for = radioInput.id;
- radio.appendChild(radioLabel);
- }
- show(radio);
- var radios = radio.querySelectorAll('input');
- if (radios.length) {
- radios[0].focus();
- }
- };
- break;
- case 'checkbox':
- var checkbox = getChildByClass(modal, swalClasses.checkbox);
- var checkboxInput = getInput('checkbox');
- checkboxInput.type = 'checkbox';
- checkboxInput.value = 1;
- checkboxInput.id = swalClasses.checkbox;
- checkboxInput.checked = Boolean(params.inputValue);
- var label = checkbox.getElementsByTagName('span');
- if (label.length) {
- checkbox.removeChild(label[0]);
- }
- label = document.createElement('span');
- label.innerHTML = params.inputPlaceholder;
- checkbox.appendChild(label);
- show(checkbox);
- break;
- case 'textarea':
- var textarea = getChildByClass(modal, swalClasses.textarea);
- textarea.value = params.inputValue;
- textarea.placeholder = params.inputPlaceholder;
- show(textarea);
- break;
- case null:
- break;
- default:
- console.error('SweetAlert2: Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "' + params.input + '"');
- break;
- }
-
- if (params.input === 'select' || params.input === 'radio') {
- if (params.inputOptions instanceof Promise) {
- sweetAlert.showLoading();
- params.inputOptions.then(function(inputOptions) {
- sweetAlert.hideLoading();
- populateInputOptions(inputOptions);
- });
- } else if (_typeof(params.inputOptions) === 'object') {
- populateInputOptions(params.inputOptions);
- } else {
- console.error('SweetAlert2: Unexpected type of inputOptions! Expected object or Promise, got ' + _typeof(params.inputOptions));
- }
- }
-
- openModal(params.animation, params.onOpen);
-
- // Focus the first element (input or button)
- if (params.allowEnterKey) {
- setFocus(-1, 1);
- } else {
- if (document.activeElement) {
- document.activeElement.blur();
- }
- }
-
- // fix scroll
- getContainer().scrollTop = 0;
-
- // Observe changes inside the modal and adjust height
- if (typeof MutationObserver !== 'undefined' && !swal2Observer) {
- swal2Observer = new MutationObserver(sweetAlert.recalculateHeight);
- swal2Observer.observe(modal, { childList: true, characterData: true, subtree: true });
- }
- });
- };
-
- /*
- * Global function to determine if swal2 modal is shown
- */
- sweetAlert.isVisible = function() {
- return !!getModal();
- };
-
- /*
- * Global function for chaining sweetAlert modals
- */
- sweetAlert.queue = function(steps) {
- queue = steps;
- var resetQueue = function resetQueue() {
- queue = [];
- document.body.removeAttribute('data-swal2-queue-step');
- };
- var queueResult = [];
- return new Promise(function(resolve, reject) {
- (function step(i, callback) {
- if (i < queue.length) {
- document.body.setAttribute('data-swal2-queue-step', i);
-
- sweetAlert(queue[i]).then(function(result) {
- queueResult.push(result);
- step(i + 1, callback);
- }, function(dismiss) {
- resetQueue();
- reject(dismiss);
- });
- } else {
- resetQueue();
- resolve(queueResult);
- }
- })(0);
- });
- };
-
- /*
- * Global function for getting the index of current modal in queue
- */
- sweetAlert.getQueueStep = function() {
- return document.body.getAttribute('data-swal2-queue-step');
- };
-
- /*
- * Global function for inserting a modal to the queue
- */
- sweetAlert.insertQueueStep = function(step, index) {
- if (index && index < queue.length) {
- return queue.splice(index, 0, step);
- }
- return queue.push(step);
- };
-
- /*
- * Global function for deleting a modal from the queue
- */
- sweetAlert.deleteQueueStep = function(index) {
- if (typeof queue[index] !== 'undefined') {
- queue.splice(index, 1);
- }
- };
-
- /*
- * Global function to close sweetAlert
- */
- sweetAlert.close = sweetAlert.closeModal = function(onComplete) {
- var container = getContainer();
- var modal = getModal();
- if (!modal) {
- return;
- }
- removeClass(modal, swalClasses.show);
- addClass(modal, swalClasses.hide);
- clearTimeout(modal.timeout);
-
- resetPrevState();
-
- var removeModalAndResetState = function removeModalAndResetState() {
- if (container.parentNode) {
- container.parentNode.removeChild(container);
- }
- removeClass(document.documentElement, swalClasses.shown);
- removeClass(document.body, swalClasses.shown);
- undoScrollbar();
- undoIOSfix();
- };
-
- // If animation is supported, animate
- if (animationEndEvent && !hasClass(modal, swalClasses.noanimation)) {
- modal.addEventListener(animationEndEvent, function swalCloseEventFinished() {
- modal.removeEventListener(animationEndEvent, swalCloseEventFinished);
- if (hasClass(modal, swalClasses.hide)) {
- removeModalAndResetState();
- }
- });
- } else {
- // Otherwise, remove immediately
- removeModalAndResetState();
- }
- if (onComplete !== null && typeof onComplete === 'function') {
- setTimeout(function() {
- onComplete(modal);
- });
- }
- };
-
- /*
- * Global function to click 'Confirm' button
- */
- sweetAlert.clickConfirm = function() {
- return getConfirmButton().click();
- };
-
- /*
- * Global function to click 'Cancel' button
- */
- sweetAlert.clickCancel = function() {
- return getCancelButton().click();
- };
-
- /**
- * Set default params for each popup
- * @param {Object} userParams
- */
- sweetAlert.setDefaults = function(userParams) {
- if (!userParams || (typeof userParams === 'undefined' ? 'undefined' : _typeof(userParams)) !== 'object') {
- return console.error('SweetAlert2: the argument for setDefaults() is required and has to be a object');
- }
-
- for (var param in userParams) {
- if (!defaultParams.hasOwnProperty(param) && param !== 'extraParams') {
- console.warn('SweetAlert2: Unknown parameter "' + param + '"');
- delete userParams[param];
- }
- }
-
- _extends(modalParams, userParams);
- };
-
- /**
- * Reset default params for each popup
- */
- sweetAlert.resetDefaults = function() {
- modalParams = _extends({}, defaultParams);
- };
-
- sweetAlert.noop = function() {};
-
- sweetAlert.version = '6.6.2';
-
- sweetAlert.default = sweetAlert;
-
- return sweetAlert;
-
-})));
-if (window.Sweetalert2) window.sweetAlert = window.swal = window.Sweetalert2;;
-MONSTER('Pagarme.Application', function(Model, $, utils) {
-
- var createNames = [];
-
- Model.init = function(container) {
- Pagarme.BuildComponents.create(container);
- Pagarme.BuildCreate.init(container, createNames);
- };
-
-});;
-MONSTER('Pagarme.CheckoutErrors', function(Model, $, utils) {
-
- Model.create = function(context) {
- this.context = context;
- this.init();
- };
-
- Model.init = function() {
- $('body').on('onPagarmeCheckoutFail', this.error.bind(this));
- };
-
- Model.error = function(event, errorThrown) {
- var error, rect;
- var element = $('#wcmp-checkout-errors');
-
- swal.close();
-
- this.errorList = '';
-
- for (error in errorThrown.errors) {
- (errorThrown.errors[error] || []).forEach(this.parseErrorsList.bind(this, error));
- }
-
- element.find('.woocommerce-error').html(this.errorList);
- element.slideDown();
-
- rect = element.get(0).getBoundingClientRect();
-
- jQuery('#wcmp-submit').removeAttr('disabled', 'disabled');
-
- window.scrollTo(0, (rect.top + window.scrollY) - 40);
- };
-
- Model.parseErrorsList = function(error, message, index) {
- this.errorList += '' + this.translateErrors(error, message) + ' ';
- };
-
- Model.translateErrors = function(error, message) {
- error = error.replace('request.', '');
- var output = error + ': ' + message;
- var ptBrMessages = PagarmeGlobalVars.checkoutErrors.pt_BR;
-
- if (PagarmeGlobalVars.WPLANG != 'pt_BR') {
- return output;
- }
-
- if (ptBrMessages.hasOwnProperty(output)) {
- return ptBrMessages[output];
- }
-
- return output;
- };
-
-});;
-MONSTER('Pagarme.Components.CheckoutTransparent', function(Model, $, utils) {
-
- Model.fn.start = function() {
- this.lock = false;
-
- this.addEventListener();
-
- Pagarme.CheckoutErrors.create(this);
-
- if (typeof $().select2 === 'function') {
- this.applySelect2();
- }
-
- $('div#woo-pagarme-payment-methods > ul li input:first').attr('checked', 'checked');
- $('div#woo-pagarme-payment-methods > ul li:first').find('.payment_box').show();
-
- $('input#payment_method_woo-pagarme-payments').click(function() {
- $('div#woo-pagarme-payment-methods').removeAttr('style');
-
- $('div#woo-pagarme-payment-methods > ul li').find(function() {
- $('input:checked:last').nextAll().show();
- });
- });
-
- };
-
- Model.fn.addEventListener = function() {
-
- $('#place_order').on('click', this._onSubmit.bind(this));
-
- this.click('tab');
- this.click('choose-payment');
-
- if (this.elements.cardHolderName) {
- this.elements.cardHolderName.on('keypress', this.removeSpecialChars);
- this.elements.cardHolderName.on('blur', this.removeSpecialChars);
- }
-
- $('[data-required=true]').on('keypress', this.setAsValid);
- $('[data-required=true]').on('blur', this.setAsValid);
-
-
- if (this.elements.cardNumber) {
- this.elements.cardNumber.on('keyup', this.updateInstallments);
- this.elements.cardNumber.on('keydown', this.updateInstallments);
- }
- };
-
- Model.fn._onSubmit = function(e) {
- e.preventDefault();
-
- if (!this.validate()) {
- jQuery('#wcmp-submit').removeAttr('disabled', 'disabled');
- return false;
- }
-
- $('body').on('onPagarmeCheckoutDone', function() {
- if ($('input[name=payment_method]').val() == '2_cards') {
- return;
- }
- }.bind(this));
-
- $('body').on('onPagarme2CardsDone', function() {
- if (window.Pagarme2Cards === 2) {
- this.loadSwal();
- }
- window.Pagarme2Cards = 0;
- }.bind(this));
-
- jQuery('#wcmp-submit').attr('disabled', 'disabled');
-
- $('body').trigger('onPagarmeSubmit', [e])
-
- if (
- $('input[name=payment_method]').val() === 'billet' ||
- $('input[name=payment_method]').val() === 'pix') {
- this.loadSwal();
- }
-
-
- };
-
- Model.fn._onClickTab = function(event) {
- window.location = this.data.paymentUrl + '&tab=' + event.currentTarget.dataset.ref + $(event.currentTarget).attr('href');
- };
-
- Model.fn._onClickChoosePayment = function(e) {
- var target = $(e.currentTarget);
- var forms = $('.wc-credit-card-form');
-
- forms.attr('disabled', true);
- target.prev().removeAttr('disabled');
- };
-
- Model.fn._done = function(response) {
- this.lock = false;
- if (!response.success) {
- this.failMessage(
- this.getFailMessage(response.data)
- );
- } else {
- this.successMessage();
- }
-
- var self = this;
-
- if (response.data.status == "failed") {
- swal({
- type: 'error',
- html: this.getFailMessage()
- }).then(function() {
- window.location.href = self.data.returnUrl;
- });
- }
- };
-
- Model.fn._fail = function(jqXHR, textStatus, errorThrown) {
- this.lock = false;
- this.failMessage();
- };
-
- Model.fn.getFailMessage = function(message = "") {
- if (!message) {
- return "Transação não autorizada."
- }
-
- return message;
- };
-
- Model.fn.failMessage = function(message) {
- swal({
- type: 'error',
- html: message || this.data.swal.text_default
- });
- };
-
- Model.fn.successMessage = function() {
- var self = this;
-
- swal({
- type: 'success',
- html: this.data.swal.text_success,
- allowOutsideClick: false
- }).then(function() {
- window.location.href = self.data.returnUrl;
- });
- };
-
- Model.fn.applySelect2 = function() {
- this.$el.byAction('select2').select2({
- width: '100%',
- minimumResultsForSearch: 20
- });
-
- this.$el.find('[data-element=state]').select2({
- width: '100%',
- minimumResultsForSearch: 20
- });
- };
-
- Model.fn.removeSpecialChars = function() {
- this.value = this.value.replace(/[^a-zA-Z ]/g, "");
- };
-
- Model.fn.setAsValid = function() {
- if (this.value) {
- $(this).removeClass('invalid');
- }
- };
-
- Model.fn.updateInstallments = function(e) {
- if (!this.value) {
- var option = '... ';
- var select = $(e.currentTarget)
- .closest('fieldset')
- .find('[data-element=installments]');
-
- if (select.data('type') == 2) {
- select.html(option);
- }
- }
- };
-
- Model.fn.validate = function() {
- var requiredFields = $('[data-required=true]:visible'),
- isValid = true;
-
- requiredFields.each(function(index, item) {
- var field = $(item);
- if (!$.trim(field.val())) {
- if (field.attr('id') == 'installments') {
- field = field.next(); //Select2 span
- }
- field.addClass('invalid');
- isValid = false;
- }
- });
-
- return isValid;
- };
-
- Model.fn._onOpenSwal = function() {
- if (this.lock) {
- return;
- }
-
- this.lock = true;
-
- swal.showLoading();
-
- var inputsSubmit = this.$el.serializeArray();
-
- this.ajax({
- url: this.data.apiRequest,
- data: {
- order: this.data.order,
- fields: inputsSubmit
- },
- success: function(data) {
- if (data.success == false) {
- jQuery('#wcmp-submit').removeAttr('disabled', 'disabled');
- }
- },
- fail: function(data) {
- jQuery('#wcmp-submit').removeAttr('disabled', 'disabled');
- }
- });
- };
-
- Model.fn.hasCardId = function(wrapper) {
- var element = wrapper.find('[data-element="choose-credit-card"]');
-
- if (element === undefined || element.length === 0) {
- return false;
- }
-
- return element.val().trim() !== '';
- };
-
- Model.fn.requestInProgress = function() {
- swal({
- title: this.data.swal.title,
- text: this.data.swal.text,
- allowOutsideClick: false
- });
- swal.showLoading();
- };
-
- Model.fn.isTwoCardsPayment = function(firstInput, secondInput) {
- return firstInput.id.includes("card") && secondInput.id.includes("card");
- };
-
- Model.fn.isBilletAndCardPayment = function(firstInput, secondInput) {
- return (firstInput.id.includes("card") && secondInput.id.includes("billet")) ||
- (firstInput.id.includes("billet") && secondInput.id.includes("card"));
- };
-
- Model.fn.refreshBothInstallmentsSelects = function(event, secondInput) {
- event.currentTarget = secondInput;
- event.target = secondInput;
- };
-
- Model.fn.refreshCardInstallmentSelect = function(event, secondInput) {
- const targetInput = event.target.id.includes("card") ? event.target : secondInput;
-
- event.currentTarget = targetInput;
- event.target = targetInput;
- }
-
-});;
-MONSTER('Pagarme.Components.Installments', function(Model, $, utils) {
- Model.fn.start = function() {
- this.lock = false;
- this.total = this.$el.data('total');
- this.addEventListener();
- };
-
- Model.fn.addEventListener = function() {
- if (this.$el.data('type') == 2) {
- $('body').on('pagarmeChangeBrand', this.onChangeBrand.bind(this));
- }
-
- $('body').on('pagarmeBlurCardOrderValue', this.onBlurCardOrderValue.bind(this));
- };
-
- Model.fn.onChangeBrand = function(event, brand, cardNumberLength, wrapper) {
- var cardOrderValue = wrapper.find('[data-element=card-order-value]');
-
- if (cardOrderValue.length) {
- this.total = cardOrderValue.val();
- this.total = this.total.replace('.', '');
- this.total = this.total.replace(',', '.');
- }
-
- if (cardNumberLength >= 13 && cardNumberLength <= 19) {
- this.request(brand, this.total, wrapper);
- }
- };
-
- Model.fn.onBlurCardOrderValue = function(event, brand, total, wrapper) {
- this.request(brand, total, wrapper);
- };
-
- Model.fn.request = function(brand, total, wrapper) {
- return;
- var storageName = btoa(brand + total);
- var storage = sessionStorage.getItem(storageName);
- var select = wrapper.find('[data-element=installments]');
-
- if (storage) {
- select.html(storage);
- return false;
- }
-
- var ajax = $.ajax({
- 'url': MONSTER.utils.getAjaxUrl(),
- 'data': {
- 'action': 'xqRhBHJ5sW',
- 'flag': brand,
- 'total': total
- }
- });
-
- ajax.done($.proxy(this._done, this, select, storageName));
- ajax.fail(this._fail.bind(this));
-
- if (this.lock) {
- return;
- }
-
- this.lock = true;
-
- this.showLoader();
-
- };
-
- Model.fn._done = function(select, storageName, response) {
- this.lock = false;
- select.html(response);
- sessionStorage.setItem(storageName, response);
- this.removeLoader();
- };
-
- Model.fn._fail = function() {
- this.lock = false;
- this.removeLoader();
- };
-
- Model.fn.showLoader = function() {
- $('#wcmp-checkout-form').block({
- message: null,
- overlayCSS: {
- background: '#fff',
- opacity: 0.6
- }
- });
- };
-
- Model.fn.removeLoader = function() {
- $('#wcmp-checkout-form').unblock();
- };
-});;
-MONSTER('Pagarme.Components.PagarmeCheckout', function(Model, $, utils) {
-
- window.Pagarme2Cards = 0;
-
- window.pagarmeQrCodeCopy = async function() {
- const qrCodeElement = document.getElementById("pagarme-qr-code");
-
- if (!qrCodeElement) {
- return;
- }
-
- const rawCode = qrCodeElement.getAttribute("rawCode");
- const alternativePagarmeQrCodeCopy = (rawCode) => {
- const responseDiv = document.getElementById("pagarme-qr-code-response");
- const input = document.createElement("input");
- responseDiv.innerHTML = "";
- input.value=rawCode;
- responseDiv.appendChild(input);
- input.focus();
- input.select();
- alert("Falha ao copiar! Por favor, copie o código manualmente utilizando o campo abaixo do botão.");
- };
-
- if (window.isSecureContext && navigator.clipboard) {
- try {
- await navigator.clipboard.writeText(rawCode);
- alert("Código copiado!");
- } catch (err) {
- alternativePagarmeQrCodeCopy(rawCode);
- }
- return;
- }
-
- const input = document.createElement('input');
- document.body.appendChild(input)
- input.value = rawCode;
- input.select();
- try {
- document.execCommand('copy', false);
- alert("Código copiado!");
- } catch (err) {
- alternativePagarmeQrCodeCopy(rawCode);
- }
- input.remove();
- }
-
- Model.fn.start = function() {
- this.script = $('[data-pagarmecheckout-app-id]');
- this.form = $('[data-pagarmecheckout-form]');
- this.suffix = this.$el.data('pagarmecheckoutSuffix') || 1;
- this.creditCardNumber = this.$el.find('[data-pagarmecheckout-element="number"]');
- this.creditCardBrand = this.$el.find('[data-pagarmecheckout-element="brand"]');
- this.brandInput = this.$el.find('[data-pagarmecheckout-element="brand-input"]');
- this.chooseCreditCard = this.$el.closest('fieldset').find('[data-element="choose-credit-card"]');
- this.cvv = this.$el.find('[data-pagarmecheckout-element="cvv"]');
- this.appId = this.script.data('pagarmecheckoutAppId');
- this.apiURL = 'https://api.mundipagg.com/core/v1/tokens?appId=' + this.appId;
-
- this.addEventListener();
- };
-
- Model.fn.addEventListener = function() {
- this.creditCardNumber.on('keyup', this.keyEventHandlerCard.bind(this));
- $('body').on('onPagarmeSubmit', this.onSubmit.bind(this));
- };
-
- Model.fn.hasCardId = function() {
- if (this.chooseCreditCard === undefined || this.chooseCreditCard.length === 0) {
- return false;
- }
- return this.chooseCreditCard.val().trim() !== '';
- };
-
- Model.fn.createCheckoutObj = function(fields) {
- var obj = {},
- i = 0,
- length = fields.length,
- prop, key;
- obj['type'] = 'credit_card';
- for (i = 0; i < length; i += 1) {
- if (fields[i].getAttribute('data-pagarmecheckout-element') === 'exp_date') {
- var sep = fields[i].getAttribute('data-pagarmecheckout-separator') ? fields[i].getAttribute('data-pagarmecheckout-separator') : '/';
- var values = fields[i].value.split(sep);
- obj['exp_month'] = values[0];
- obj['exp_year'] = values[1];
- } else {
- prop = fields[i].getAttribute('data-pagarmecheckout-element');
- key = fields[i].value;
-
- if (prop == 'brand') {
- key = fields[i].getAttribute('data-pagarmecheckout-brand');
- }
- }
- obj[prop] = key;
- }
- return obj;
- };
-
- Model.fn.disableFields = function(fields) {
- for (var i = 0; i < fields.length; i += 1) {
- fields[i].setAttribute('disabled', 'disabled');
- }
- };
-
- Model.fn.enableFields = function(fields) {
- for (var i = 0; i < fields.length; i += 1) {
- fields[i].removeAttribute('disabled');
- }
- };
-
- Model.fn.getAPIData = function(url, data, success, fail) {
- var xhr = new XMLHttpRequest();
- var suffix = this.suffix;
-
- xhr.open('POST', url);
- xhr.onreadystatechange = function() {
- if (xhr.readyState < 4) {
- return;
- }
- if (xhr.status == 200) {
- success.call(null, xhr.responseText, suffix);
- } else {
- var errorObj = {};
- if (xhr.response) {
- errorObj = JSON.parse(xhr.response);
- errorObj.statusCode = xhr.status;
- } else {
- errorObj.statusCode = 503;
- }
-
- fail.call(null, errorObj, suffix);
- }
- };
-
- xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
- xhr.send(JSON.stringify({
- card: data
- }));
-
- return xhr;
- };
-
- Model.fn.getBrand = function(types, bin) {
- var oldPrefix = '';
- var currentBrand;
- for (var i = 0; i < types.length; i += 1) {
- var current_type = types[i];
- for (var j = 0; j < current_type.prefixes.length; j += 1) {
- var prefix = current_type.prefixes[j].toString();
- if (bin.indexOf(prefix) === 0 && oldPrefix.length < prefix.length) {
- oldPrefix = prefix;
- currentBrand = current_type.brand;
- }
- }
- }
- return currentBrand;
- };
-
- Model.fn.changeBrand = function(brand, cardNumberLength) {
- var $brand = this.creditCardBrand.get(0);
- var wrapper = this.creditCardBrand.closest('fieldset');
- var imageSrc = 'https://cdn.mundipagg.com/assets/images/logos/brands/png/';
- var $img = $('img', $brand)[0];
- var src;
-
- $brand.setAttribute('data-pagarmecheckout-brand', brand);
- this.brandInput.val(brand);
-
- jQuery('body').trigger('pagarmeChangeBrand', [brand, cardNumberLength, wrapper]);
-
- if (brand === '') {
- $brand.innerHTML = '';
- } else {
- if ($brand.getAttribute('data-pagarmecheckout-brand-image') !== null) {
- src = imageSrc + brand + '.png';
- if (!$img) {
- var $newImg = document.createElement('img');
- $newImg.setAttribute('src', src);
- $newImg.setAttribute('style', 'float: right;\n' +
- 'border: 0;\n' +
- 'padding: 0;\n' +
- 'max-height: 1.618em;');
- $brand.appendChild($newImg);
- } else {
- $img.setAttribute('src', src);
- }
- }
- }
- };
-
- Model.fn.keyEventHandlerCard = function(event) {
- var elem = event.currentTarget;
- var cardNumber = elem.value.replace(/\s/g, '');
- var bin = cardNumber.substr(0, 6);
- var types = this.getCardTypes();
- var brand;
- if (cardNumber.length >= 6) {
- brand = this.getBrand(types, bin);
- if (brand) {
- this.changeBrand(brand, cardNumber.length);
- } else {
- this.changeBrand('', cardNumber.length);
- }
- } else {
- this.changeBrand('', cardNumber.length);
- }
- };
-
- Model.fn.serialize = function(obj) {
- var str = [];
- for (var p in obj) {
- if (obj.hasOwnProperty(p)) {
- str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
- }
- }
- return str.join("&");
- };
-
- Model.fn.getCardTypes = function() {
- return [{
- brand: 'vr',
- brandName: 'VR',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [637036, 627416, 636350, 637037]
- }, {
- brand: 'mais',
- brandName: 'Mais',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [628028]
- }, {
- brand: 'paqueta',
- brandName: 'Paqueta',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [960371]
- }, {
- brand: 'sodexo',
- brandName: 'Sodexo',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [603389, 606071, 606069, 600818, 606070, 606068]
- }, {
- brand: 'hipercard',
- brandName: 'Hipercard',
- gaps: [4, 8, 12],
- lenghts: [13, 16, 19],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [384100, 384140, 384160, 60, 606282, 637095, 637568, 637599, 637609, 637612, 637600]
- }, {
- brand: 'discover',
- brandName: 'Discover',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 4,
- prefixes: [6011, 622, 64, 65]
- }, {
- brand: 'diners',
- brandName: 'Diners',
- gaps: [4, 8, 12],
- lenghts: [14, 16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [300, 301, 302, 303, 304, 305, 36, 38]
- }, {
- brand: 'amex',
- brandName: 'Amex',
- gaps: [4, 10],
- lenghts: [15],
- mask: '/(\\d{1,4})(\\d{1,6})?(\\d{1,5})?/g',
- cvv: 4,
- prefixes: [34, 37]
- }, {
- brand: 'aura',
- brandName: 'Aura',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [50]
- }, {
- brand: 'jcb',
- brandName: 'JCB',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [35, 2131, 1800]
- }, {
- brand: 'visa',
- brandName: 'Visa',
- gaps: [4, 8, 12],
- lenghts: [13, 16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [4]
- }, {
- brand: 'mastercard',
- brandName: 'Mastercard',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [5, 2]
- }, {
- brand: 'elo',
- brandName: 'Elo',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [401178, 401179, 431274, 438935, 451416, 457393, 457631, 457632, 498405, 498410, 498411, 498412, 498418, 498419, 498420, 498421, 498422, 498427, 498428, 498429, 498432, 498433, 498472, 498473, 498487, 498493, 498494, 498497, 498498, 504175, 506699, 506700, 506701, 506702, 506703, 506704, 506705, 506706, 506707, 506708, 506709, 506710, 506711, 506712, 506713, 506714, 506715, 506716, 506717, 506718, 506719, 506720, 506721, 506722, 506723, 506724, 506725, 506726, 506727, 506728, 506729, 506730, 506731, 506732, 506733, 506734, 506735, 506736, 506737, 506738, 506739, 506740, 506741, 506742, 506743, 506744, 506745, 506746, 506747, 506748, 506749, 506750, 506751, 506752, 506753, 506754, 506755, 506756, 506757, 506758, 506759, 506760, 506761, 506762, 506763, 506764, 506765, 506766, 506767, 506768, 506769, 506770, 506771, 506772, 506773, 506774, 506775, 506776, 506777, 506778, 509000, 509001, 509002, 509003, 509004, 509005, 509006, 509007, 509008, 509009, 509010, 509011, 509012, 509013, 509014, 509015, 509016, 509017, 509018, 509019, 509020, 509021, 509022, 509023, 509024, 509025, 509026, 509027, 509028, 509029, 509030, 509031, 509032, 509033, 509034, 509035, 509036, 509037, 509038, 509039, 509040, 509041, 509042, 509043, 509044, 509045, 509046, 509047, 509048, 509049, 509050, 509051, 509052, 509053, 509054, 509055, 509056, 509057, 509058, 509059, 509060, 509061, 509062, 509063, 509064, 509065, 509066, 509067, 509068, 509069, 509070, 509071, 509072, 509073, 509074, 509075, 509076, 509077, 509078, 509079, 509080, 509081, 509082, 509083, 509084, 509085, 509086, 509087, 509088, 509089, 509090, 509091, 509092, 509093, 509094, 509095, 509096, 509097, 509098, 509099, 509100, 509101, 509102, 509103, 509104, 509105, 509106, 509107, 509108, 509109, 509110, 509111, 509112, 509113, 509114, 509115, 509116, 509117, 509118, 509119, 509120, 509121, 509122, 509123, 509124, 509125, 509126, 509127, 509128, 509129, 509130, 509131, 509132, 509133, 509134, 509135, 509136, 509137, 509138, 509139, 509140, 509141, 509142, 509143, 509144, 509145, 509146, 509147, 509148, 509149, 509150, 509151, 509152, 509153, 509154, 509155, 509156, 509157, 509158, 509159, 509160, 509161, 509162, 509163, 509164, 509165, 509166, 509167, 509168, 509169, 509170, 509171, 509172, 509173, 509174, 509175, 509176, 509177, 509178, 509179, 509180, 509181, 509182, 509183, 509184, 509185, 509186, 509187, 509188, 509189, 509190, 509191, 509192, 509193, 509194, 509195, 509196, 509197, 509198, 509199, 509200, 509201, 509202, 509203, 509204, 509205, 509206, 509207, 509208, 509209, 509210, 509211, 509212, 509213, 509214, 509215, 509216, 509217, 509218, 509219, 509220, 509221, 509222, 509223, 509224, 509225, 509226, 509227, 509228, 509229, 509230, 509231, 509232, 509233, 509234, 509235, 509236, 509237, 509238, 509239, 509240, 509241, 509242, 509243, 509244, 509245, 509246, 509247, 509248, 509249, 509250, 509251, 509252, 509253, 509254, 509255, 509256, 509257, 509258, 509259, 509260, 509261, 509262, 509263, 509264, 509265, 509266, 509267, 509268, 509269, 509270, 509271, 509272, 509273, 509274, 509275, 509276, 509277, 509278, 509279, 509280, 509281, 509282, 509283, 509284, 509285, 509286, 509287, 509288, 509289, 509290, 509291, 509292, 509293, 509294, 509295, 509296, 509297, 509298, 509299, 509300, 509301, 509302, 509303, 509304, 509305, 509306, 509307, 509308, 509309, 509310, 509311, 509312, 509313, 509314, 509315, 509316, 509317, 509318, 509319, 509320, 509321, 509322, 509323, 509324, 509325, 509326, 509327, 509328, 509329, 509330, 509331, 509332, 509333, 509334, 509335, 509336, 509337, 509338, 509339, 509340, 509341, 509342, 509343, 509344, 509345, 509346, 509347, 509348, 509349, 509350, 509351, 509352, 509353, 509354, 509355, 509356, 509357, 509358, 509359, 509360, 509361, 509362, 509363, 509364, 509365, 509366, 509367, 509368, 509369, 509370, 509371, 509372, 509373, 509374, 509375, 509376, 509377, 509378, 509379, 509380, 509381, 509382, 509383, 509384, 509385, 509386, 509387, 509388, 509389, 509390, 509391, 509392, 509393, 509394, 509395, 509396, 509397, 509398, 509399, 509400, 509401, 509402, 509403, 509404, 509405, 509406, 509407, 509408, 509409, 509410, 509411, 509412, 509413, 509414, 509415, 509416, 509417, 509418, 509419, 509420, 509421, 509422, 509423, 509424, 509425, 509426, 509427, 509428, 509429, 509430, 509431, 509432, 509433, 509434, 509435, 509436, 509437, 509438, 509439, 509440, 509441, 509442, 509443, 509444, 509445, 509446, 509447, 509448, 509449, 509450, 509451, 509452, 509453, 509454, 509455, 509456, 509457, 509458, 509459, 509460, 509461, 509462, 509463, 509464, 509465, 509466, 509467, 509468, 509469, 509470, 509471, 509472, 509473, 509474, 509475, 509476, 509477, 509478, 509479, 509480, 509481, 509482, 509483, 509484, 509485, 509486, 509487, 509488, 509489, 509490, 509491, 509492, 509493, 509494, 509495, 509496, 509497, 509498, 509499, 509500, 509501, 509502, 509503, 509504, 509505, 509506, 509507, 509508, 509509, 509510, 509511, 509512, 509513, 509514, 509515, 509516, 509517, 509518, 509519, 509520, 509521, 509522, 509523, 509524, 509525, 509526, 509527, 509528, 509529, 509530, 509531, 509532, 509533, 509534, 509535, 509536, 509537, 509538, 509539, 509540, 509541, 509542, 509543, 509544, 509545, 509546, 509547, 509548, 509549, 509550, 509551, 509552, 509553, 509554, 509555, 509556, 509557, 509558, 509559, 509560, 509561, 509562, 509563, 509564, 509565, 509566, 509567, 509568, 509569, 509570, 509571, 509572, 509573, 509574, 509575, 509576, 509577, 509578, 509579, 509580, 509581, 509582, 509583, 509584, 509585, 509586, 509587, 509588, 509589, 509590, 509591, 509592, 509593, 509594, 509595, 509596, 509597, 509598, 509599, 509600, 509601, 509602, 509603, 509604, 509605, 509606, 509607, 509608, 509609, 509610, 509611, 509612, 509613, 509614, 509615, 509616, 509617, 509618, 509619, 509620, 509621, 509622, 509623, 509624, 509625, 509626, 509627, 509628, 509629, 509630, 509631, 509632, 509633, 509634, 509635, 509636, 509637, 509638, 509639, 509640, 509641, 509642, 509643, 509644, 509645, 509646, 509647, 509648, 509649, 509650, 509651, 509652, 509653, 509654, 509655, 509656, 509657, 509658, 509659, 509660, 509661, 509662, 509663, 509664, 509665, 509666, 509667, 509668, 509669, 509670, 509671, 509672, 509673, 509674, 509675, 509676, 509677, 509678, 509679, 509680, 509681, 509682, 509683, 509684, 509685, 509686, 509687, 509688, 509689, 509690, 509691, 509692, 509693, 509694, 509695, 509696, 509697, 509698, 509699, 509700, 509701, 509702, 509703, 509704, 509705, 509706, 509707, 509708, 509709, 509710, 509711, 509712, 509713, 509714, 509715, 509716, 509717, 509718, 509719, 509720, 509721, 509722, 509723, 509724, 509725, 509726, 509727, 509728, 509729, 509730, 509731, 509732, 509733, 509734, 509735, 509736, 509737, 509738, 509739, 509740, 509741, 509742, 509743, 509744, 509745, 509746, 509747, 509748, 509749, 509750, 509751, 509752, 509753, 509754, 509755, 509756, 509757, 509758, 509759, 509760, 509761, 509762, 509763, 509764, 509765, 509766, 509767, 509768, 509769, 509770, 509771, 509772, 509773, 509774, 509775, 509776, 509777, 509778, 509779, 509780, 509781, 509782, 509783, 509784, 509785, 509786, 509787, 509788, 509789, 509790, 509791, 509792, 509793, 509794, 509795, 509796, 509797, 509798, 509799, 509800, 509801, 509802, 509803, 509804, 509805, 509806, 509807, 509808, 509809, 509810, 509811, 509812, 509813, 509814, 509815, 509816, 509817, 509818, 509819, 509820, 509821, 509822, 509823, 509824, 509825, 509826, 509827, 509828, 509829, 509830, 509831, 509832, 509833, 509834, 509835, 509836, 509837, 509838, 509839, 509840, 509841, 509842, 509843, 509844, 509845, 509846, 509847, 509848, 509849, 509850, 509851, 509852, 509853, 509854, 509855, 509856, 509857, 509858, 509859, 509860, 509861, 509862, 509863, 509864, 509865, 509866, 509867, 509868, 509869, 509870, 509871, 509872, 509873, 509874, 509875, 509876, 509877, 509878, 509879, 509880, 509881, 509882, 509883, 509884, 509885, 509886, 509887, 509888, 509889, 509890, 509891, 509892, 509893, 509894, 509895, 509896, 509897, 509898, 509899, 509900, 509901, 509902, 509903, 509904, 509905, 509906, 509907, 509908, 509909, 509910, 509911, 509912, 509913, 509914, 509915, 509916, 509917, 509918, 509919, 509920, 509921, 509922, 509923, 509924, 509925, 509926, 509927, 509928, 509929, 509930, 509931, 509932, 509933, 509934, 509935, 509936, 509937, 509938, 509939, 509940, 509941, 509942, 509943, 509944, 509945, 509946, 509947, 509948, 509949, 509950, 509951, 509952, 509953, 509954, 509955, 509956, 509957, 509958, 509959, 509960, 509961, 509962, 509963, 509964, 509965, 509966, 509967, 509968, 509969, 509970, 509971, 509972, 509973, 509974, 509975, 509976, 509977, 509978, 509979, 509980, 509981, 509982, 509983, 509984, 509985, 509986, 509987, 509988, 509989, 509990, 509991, 509992, 509993, 509994, 509995, 509996, 509997, 509998, 509999, 627780, 636297, 636368, 650031, 650032, 650033, 650035, 650036, 650037, 650038, 650039, 650040, 650041, 650042, 650043, 650044, 650045, 650046, 650047, 650048, 650049, 650050, 650051, 650405, 650406, 650407, 650408, 650409, 650410, 650411, 650412, 650413, 650414, 650415, 650416, 650417, 650418, 650419, 650420, 650421, 650422, 650423, 650424, 650425, 650426, 650427, 650428, 650429, 650430, 650431, 650432, 650433, 650434, 650435, 650436, 650437, 650438, 650439, 650485, 650486, 650487, 650488, 650489, 650490, 650491, 650492, 650493, 650494, 650495, 650496, 650497, 650498, 650499, 650500, 650501, 650502, 650503, 650504, 650505, 650506, 650507, 650508, 650509, 650510, 650511, 650512, 650513, 650514, 650515, 650516, 650517, 650518, 650519, 650520, 650521, 650522, 650523, 650524, 650525, 650526, 650527, 650528, 650529, 650530, 650531, 650532, 650533, 650534, 650535, 650536, 650537, 650538, 650541, 650542, 650543, 650544, 650545, 650546, 650547, 650548, 650549, 650550, 650551, 650552, 650553, 650554, 650555, 650556, 650557, 650558, 650559, 650560, 650561, 650562, 650563, 650564, 650565, 650566, 650567, 650568, 650569, 650570, 650571, 650572, 650573, 650574, 650575, 650576, 650577, 650578, 650579, 650580, 650581, 650582, 650583, 650584, 650585, 650586, 650587, 650588, 650589, 650590, 650591, 650592, 650593, 650594, 650595, 650596, 650597, 650598, 650700, 650701, 650702, 650703, 650704, 650705, 650706, 650707, 650708, 650709, 650710, 650711, 650712, 650713, 650714, 650715, 650716, 650717, 650718, 650720, 650721, 650722, 650723, 650724, 650725, 650726, 650727, 650901, 650902, 650903, 650904, 650905, 650906, 650907, 650908, 650909, 650910, 650911, 650912, 650913, 650914, 650915, 650916, 650917, 650918, 650919, 650920, 651652, 651653, 651654, 651655, 651656, 651657, 651658, 651659, 651660, 651661, 651662, 651663, 651664, 651665, 651666, 651667, 651668, 651669, 651670, 651671, 651672, 651673, 651674, 651675, 651676, 651677, 651678, 651679, 655000, 655001, 655002, 655003, 655004, 655005, 655006, 655007, 655008, 655009, 655010, 655011, 655012, 655013, 655014, 655015, 655016, 655017, 655018, 655019, 655021, 655022, 655023, 655024, 655025, 655026, 655027, 655028, 655029, 655030, 655031, 655032, 655033, 655034, 655035, 655036, 655037, 655038, 655039, 655040, 655041, 655042, 655043, 655044, 655045, 655046, 655047, 655048, 655049, 655050, 655051, 655052, 655053, 655054, 655055, 655056, 655057, 655058, 637095, 650921, 650978]
- }];
- };
-
- Model.fn.onSubmit = function(e) {
- if (this.hasCardId()) {
- $('body').trigger('onPagarmeCheckoutDone');
-
- if ($('input[name=payment_method]').val() == '2_cards') {
- window.Pagarme2Cards = window.Pagarme2Cards + 1;
- if (window.Pagarme2Cards === 2) {
- $('body').trigger('onPagarme2CardsDone');
- }
- }
- return;
- }
-
- var $this = this;
- var markedInputs = this.$el.find('[data-pagarmecheckout-element]');
- var notMarkedInputs = this.$el.find('input:not([data-pagarmecheckout-element])');
- var checkoutObj = this.createCheckoutObj(markedInputs);
- var callbackObj = {};
- var $hidden = this.$el.find('[name="pagarmetoken' + this.suffix + '"]');
- var cb;
-
- if ($hidden) {
- $hidden.remove();
- }
-
- e.preventDefault();
-
- swal.close();
-
- swal({
- title: '',
- text: 'Gerando transação segura...',
- allowOutsideClick: false
- });
-
- swal.showLoading();
-
- this.getAPIData(
- this.apiURL,
- checkoutObj,
- function(data, suffix) {
- var objJSON = JSON.parse(data);
-
- $hidden = document.createElement('input');
- $hidden.setAttribute('type', 'hidden');
- $hidden.setAttribute('name', 'pagarmetoken' + $this.suffix);
- $hidden.setAttribute('value', objJSON.id);
- $hidden.setAttribute('data-pagarmetoken', $this.suffix);
-
- $this.$el.append($hidden);
-
- for (var i = 0; i < notMarkedInputs.length; i += 1) {
- callbackObj[notMarkedInputs[i]['name']] = notMarkedInputs[i]['value'];
- }
-
- callbackObj['pagarmetoken'] = objJSON.id;
- cb = $this._onDone.call(null, callbackObj, suffix);
-
- if (typeof cb === 'boolean' && !cb) {
- $this.enableFields(markedInputs);
- return;
- }
-
- var form = $('form.checkout');
- form.submit();
- },
- function(error, suffix) {
- swal.close();
- if (error.statusCode == 503) {
- swal({
- type: 'error',
- html: 'Não foi possÃvel gerar a transação segura. Serviço indisponÃvel.'
- });
- } else {
- $this._onFail(error, suffix);
- }
-
- }
- );
- };
-
- Model.fn._onFail = function(error, suffix) {
- $('body').trigger('onPagarmeCheckoutFail', [error]);
- };
-
- Model.fn._onDone = function(data, suffix) {
- $('body').trigger('onPagarmeCheckoutDone', [data]);
-
- if ($('input[name=payment_method]').val() == '2_cards') {
- window.Pagarme2Cards = window.Pagarme2Cards + 1;
- if (window.Pagarme2Cards === 2) {
- $('body').trigger('onPagarme2CardsDone');
- }
- }
- };
-
-});;
-MONSTER('Pagarme.Components.Wallet', function(Model, $, utils) {
-
- Model.fn.start = function() {
- this.addEventListener();
- };
-
- Model.fn.addEventListener = function() {
- this.click('remove-card');
- };
-
- Model.fn._onClickRemoveCard = function(event) {
- event.preventDefault();
-
- swal({
- title: this.data.swal.confirm_title,
- text: this.data.swal.confirm_text,
- type: 'warning',
- showCancelButton: true,
- confirmButtonColor: this.data.swal.confirm_color,
- cancelButtonColor: this.data.swal.cancel_color,
- confirmButtonText: this.data.swal.confirm_button,
- cancelButtonText: this.data.swal.cancel_button,
- allowOutsideClick: false,
- }).then(this._request.bind(this, event.currentTarget.dataset.value), function() {});
- };
-
- Model.fn._request = function(cardId) {
- swal.showLoading();
-
- this.ajax({
- url: this.data.apiRequest,
- data: {
- card_id: cardId
- }
- });
- };
-
- Model.fn._done = function(response) {
- if (response.success) {
- this.successMessage(response.data);
- } else {
- this.failMessage(response.data);
- }
- };
-
- Model.fn._fail = function(jqXHR, textStatus, errorThrown) {
-
- };
-
- Model.fn.failMessage = function(message) {
- swal({
- type: 'error',
- html: message
- }).then(function() {});
- };
-
- Model.fn.successMessage = function(message) {
- swal({
- type: 'success',
- html: message,
- allowOutsideClick: false
- }).then(function() {
- window.location.reload(true);
- });
- };
-
-});;
-jQuery(function($) {
- var context = $('body');
-
- Pagarme.vars = {
- body: context
- };
-
- Pagarme.Application.init.apply(null, [context]);
-});
-
-jQuery(function($) {
- $('#billing_cpf').change(function() {
- $('input[name="voucher-document-holder"]').empty();
- $('input[name="voucher-document-holder"]').val($('#billing_cpf').val()).mask("999.999.999-99").trigger('input');
- });
- $('input[name="voucher-document-holder"]').val($('#billing_cpf').val()).mask("999.999.999-99").trigger('input');
-});
\ No newline at end of file
diff --git a/assets/javascripts/front/libs/index.php b/assets/javascripts/front/libs/index.php
deleted file mode 100644
index 7e914158..00000000
--- a/assets/javascripts/front/libs/index.php
+++ /dev/null
@@ -1,2 +0,0 @@
- total) {
- const message = {
- type: 'error',
- text: 'O valor não pode ser maior que total do pedido!'
- };
-
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
-
- input.val('');
- nextInput.val('');
- return;
- }
-
- nextValue = nextValue.toFixed(2);
- nextValue = nextValue.replace('.', ',');
-
- value = value.toFixed(2);
- value = value.replace('.', ',');
-
- nextInput.val(nextValue);
- input.val(value);
-
- if (isTwoCardsPayment(event.target, nextInput[0])) {
- refreshBothInstallmentsSelects(event, nextInput[0]);
- }
-
- if (isBilletAndCardPayment(event.target, nextInput[0])) {
- refreshCardInstallmentSelect(event, nextInput[0]);
- }
- };
-
- const isTwoCardsPayment = function (firstInput, secondInput) {
- return firstInput.id.includes("card") && secondInput.id.includes("card");
- };
-
- const refreshBothInstallmentsSelects = function (event, secondInput) {
- _onBlurCardOrderValue(event);
- event.currentTarget = secondInput;
- event.target = secondInput;
-
- _onBlurCardOrderValue(event);
- };
-
- const _onBlurCardOrderValue = function (e, useTotal) {
- var option = '... ';
- var wrapper = $(e.currentTarget).closest('fieldset');
- var total = e.target.value;
-
- if (useTotal) {
- total = '' + cartTotal;
- }
-
- if (total) {
- total = total.replace('.', '');
- total = total.replace(',', '.');
- let brand = creditCardBrand && creditCardBrand.get(0).getAttribute('brand');
- if (!creditCardBrand) {
- const cardId = wrapper.find('[data-element=choose-credit-card]') &&
- wrapper.find('[data-element=choose-credit-card]').get(0).value;
-
- if (!cardId) return;
-
- brand = wrapper.find('[data-element=choose-credit-card]').find("option:selected").attr('data-brand');
- };
-
- $('body').trigger("pagarmeBlurCardOrderValue", [brand, total, wrapper]);
- } else {
- wrapper.find('[data-element=installments]').html(option);
- }
- };
-
- const onSelectOneClickBuy = function (event, brand, wrapper) {
- const valueInput = wrapper.find('input[data-element=card-order-value]').val();
- let value = cartTotal;
- if (typeof (valueInput) === 'string') {
- value = parseFloat(valueInput.replace(',', '.'));
- }
- updateInstallmentsElement(brand, value, wrapper);
- };
-
- const onBlurCardOrderValue = function (event, brand, total, wrapper) {
- updateInstallmentsElement(brand, total, wrapper);
- };
-
- const updateInstallmentsElement = function (brand, total, wrapper) {
- if (!brand || !total) return;
- var storageName = btoa(brand + total);
- var storage = sessionStorage.getItem(storageName);
- var select = wrapper.find('[data-element=installments]');
-
- if (storage) {
- select.html(storage);
- return false;
- }
-
- var ajax = $.ajax({
- 'url': ajaxUrl,
- 'data': {
- 'action': 'xqRhBHJ5sW',
- 'flag': brand,
- 'total': total
- }
- });
-
- ajax.done($.proxy(_done, this, select, storageName));
- ajax.fail(_fail);
-
- showLoader();
- };
-
- const _done = function (select, storageName, response) {
- select.html(response);
- sessionStorage.setItem(storageName, response);
- removeLoader();
- };
-
- const _fail = function () {
- removeLoader();
- };
-
- const removeLoader = function () {
- $('#wcmp-checkout-form').unblock();
- };
-
- const showLoader = function () {
- $('#wcmp-checkout-form').block({
- message: null,
- overlayCSS: {
- background: '#fff',
- opacity: 0.6
- }
- });
- };
-
- const isBilletAndCardPayment = function (firstInput, secondInput) {
- return (firstInput.id.includes("card") && secondInput.id.includes("billet")) ||
- (firstInput.id.includes("billet") && secondInput.id.includes("card"));
- };
-
- const refreshCardInstallmentSelect = function (event, secondInput) {
- const targetInput = event.target.id.includes("card") ? event.target : secondInput;
-
- event.currentTarget = targetInput;
- event.target = targetInput;
-
- _onBlurCardOrderValue(event);
- };
-
- $('input[name=pagarme_payment_method]').change(openPaymentMethodDetails);
-
- $('input[data-element=pagarme-voucher-card-number]').on('blur', function (e) {
- var cardNumberInput = $(e.currentTarget);
-
-
- creditCardBrand = cardNumberInput.siblings("span[name^='voucher-brand-image']");
- suffix = creditCardBrand.get(0).getAttribute('pagarme-suffix');
-
-
- brandInput = cardNumberInput.siblings("input[type='hidden']");
-
- keyEventHandlerCard(e);
- });
-
- $('input[data-element=enable-multicustomers]').click(function (e) {
- var input = $(e.currentTarget);
- var method = input.is(':checked') ? 'slideDown' : 'slideUp';
- var target = '[data-ref="' + input.data('target') + '"]';
- $(target)[method]();
- });
-
- $('#place_order').on('click', function (e) {
- if (!$('input#payment_method_woo-pagarme-payments').is(":checked")) {
- return submitForm();
- }
-
- e.preventDefault();
- e.stopPropagation();
-
- jQuery('#wcmp-submit').attr('disabled', 'disabled');
-
- if (isBilletOrPix()) {
- const message = {
- title: 'Aguarde...',
- text: 'Nós estamos processando sua requisição.',
- allowOutsideClick: false
- };
-
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
- swal.showLoading();
- return submitForm();
- }
-
- clearTokens();
- onSubmit(e);
- });
-
- const isBilletOrPix = function () {
- return $('input[name=pagarme_payment_method]:checked').get(0).value === 'billet' ||
- $('input[name=pagarme_payment_method]:checked').get(0).value === 'pix' ? true : false;
- }
-
- const clearTokens = function () {
- const possibleSuffixes = 5;
-
- for (let i = 1; i <= possibleSuffixes; i++) {
- const pagarmeTokenInputId = '#pagarmetoken' + i;
- const htmlElement = $(pagarmeTokenInputId).get(0);
- if (htmlElement) {
- htmlElement.remove();
- }
- }
- }
-
- const getAPIData = function (url, data, suffix, success, fail) {
- var xhr = new XMLHttpRequest();
-
- xhr.open('POST', url);
- xhr.onreadystatechange = function () {
- if (xhr.readyState < 4) {
- return;
- }
- if (xhr.status == 200) {
- success.call(null, xhr.responseText, suffix);
- } else {
- var errorObj = {};
- if (xhr.response) {
- errorObj = JSON.parse(xhr.response);
- errorObj.statusCode = xhr.status;
- } else {
- errorObj.statusCode = 503;
- }
-
- fail.call(null, errorObj, suffix);
- }
- };
- xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
- xhr.send(JSON.stringify({
- card: data
- }));
-
- return xhr;
- };
-
- const getBrand = function (types, bin) {
- var oldPrefix = '';
- var currentBrand;
- for (var i = 0; i < types.length; i += 1) {
- var current_type = types[i];
- for (var j = 0; j < current_type.prefixes.length; j += 1) {
- var prefix = current_type.prefixes[j].toString();
- if (bin.indexOf(prefix) === 0 && oldPrefix.length < prefix.length) {
- oldPrefix = prefix;
- currentBrand = current_type.brand;
- }
- }
- }
- return currentBrand;
- };
-
- const changeBrand = function (brand, cardNumberLength) {
- var $brand = creditCardBrand.get(0);
- var wrapper = creditCardBrand.closest('fieldset');
- const selectedPaymentMethod = $('input[name=pagarme_payment_method]:checked').get(0).value;
-
- var imageSrc = 'https://cdn.mundipagg.com/assets/images/logos/brands/png/';
- var $img = $('img', $brand)[0];
- var src;
-
- $brand.setAttribute('data-pagarmecheckout-brand-' + suffix, brand);
- $brand.setAttribute('brand', brand);
- brandInput.val(brand);
-
- if (brand === '') {
- $brand.innerHTML = '';
- } else {
- if ($brand.getAttribute("name").includes('brand-image')) {
- src = imageSrc + brand + '.png';
- if (!$img) {
- var $newImg = document.createElement('img');
- $newImg.setAttribute('src', src);
- $newImg.setAttribute('style', 'float: right;\n' +
- 'border: 0;\n' +
- 'padding: 0;\n' +
- 'max-height: 1.618em;');
- $brand.appendChild($newImg);
- } else {
- $img.setAttribute('src', src);
- }
- let orderValue = cartTotal;
- if (selectedPaymentMethod === 'billet-and-card' || selectedPaymentMethod === '2_cards') {
- const rawValue = creditCardBrand
- .closest('.wc-credit-card-form')
- .find('input[data-element=card-order-value]')
- .get(0).value;
- orderValue = parseFloat(rawValue.replace(',', '.'));
- }
-
- updateInstallmentsElement(brand, orderValue, wrapper);
- }
- }
- };
-
- const createCheckoutObj = function (fields, suffix) {
- var obj = {},
- i = 0,
- length = fields.length,
- prop, key;
- obj['type'] = 'credit_card';
- for (i = 0; i < length; i++) {
- prop = fields[i].getAttribute('data-pagarmecheckout-element-' + suffix);
- if (prop === 'exp_date') {
- var sep = fields[i].getAttribute('data-pagarmecheckout-separator') ? fields[i].getAttribute('data-pagarmecheckout-separator') : '/';
- var values = fields[i].value.replace(/\s/g, '').split(sep);
- obj['exp_month'] = values[0];
- obj['exp_year'] = values[1];
- } else {
- key = fields[i].value;
-
- if (prop == 'number') {
- key = key.replace(/\s/g, '');
- }
- if (prop == 'brand') {
- key = fields[i].getAttribute('data-pagarmecheckout-brand' + suffix);
- }
- }
- obj[prop] = key;
- }
- return obj;
- };
-
- const prepareCheckoutObject = function (checkoutObj) {
-
- let preparedCheckoutObject = {
- number: checkoutObj.number,
- holder_name: checkoutObj.holder_name,
- exp_month: checkoutObj.exp_month,
- exp_year: checkoutObj.exp_year,
- cvv: checkoutObj.cvv,
- }
-
- if ($('#voucher').is(':checked')) {
- preparedCheckoutObject.holder_name = $('#voucher-card-holder-name').val();
- preparedCheckoutObject.holder_document = $('#voucher-document-holder').val().replace('-', '').replace('.', '').replace('.', '').replace(' ', '');
- }
-
- return preparedCheckoutObject;
- };
-
- const submitForm = function () {
- const form = $('form.checkout');
- form.submit();
- }
-
- const onSubmit = function (e) {
-
- // Bail if payment method isn't Pagar.me
- if ($('input[name=payment_method]:checked').val() !== 'woo-pagarme-payments') {
- // Submit form normally
- return submitForm();
- }
-
- const paymentMethod = $('input[name=pagarme_payment_method]:checked').get(0).value;
- if (hasCardId() && paymentMethod !== '2_cards') {
- return submitForm();
- }
-
- const suffixes = [];
- let cardTokensGenerated = 0;
- if (paymentMethod === '2_cards') {
- suffixes.push(2, 3);
- } else {
- suffixes.push(+$('input[name=pagarme_payment_method]:checked')
- .closest('li')
- .find('[data-pagarmecheckout-suffix]')
- .data('pagarmecheckout-suffix'));
- }
-
- e.preventDefault();
-
- swal.close();
-
- const message = {
- title: '',
- text: 'Gerando transação segura...',
- allowOutsideClick: false
- };
-
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
-
- swal.showLoading();
-
- for (let i = 0; i < suffixes.length; i++) {
- const suffix = suffixes[i];
- const savedCardSelectName = 'card_id' + suffix;
- const savedCardSelect = $(`[name=${savedCardSelectName}]`);
- if (savedCardSelect.val()) {
- cardTokensGenerated++;
- if (cardTokensGenerated === suffixes.length) {
- return submitForm();
- }
- continue;
- }
-
- var markedInputs = $el.find('[data-pagarmecheckout-element-' + suffix + ']');
- var notMarkedInputs = $el.find('input:not([data-pagarmecheckout-element])');
- var checkoutObj = createCheckoutObj(markedInputs, suffix);
- checkoutObj = prepareCheckoutObject(checkoutObj);
- var callbackObj = {};
- var $hidden = $el.find('[name="pagarmetoken' + suffix + '"]');
- var cb;
-
- if ($hidden) {
- $hidden.remove();
- }
-
- getAPIData(
- apiURL,
- checkoutObj,
- suffix,
- function (data, suffix) {
- const objJSON = JSON.parse(data);
- const form = $('form.checkout');
-
- $hidden = document.createElement('input');
- $hidden.setAttribute('type', 'hidden');
- $hidden.setAttribute('name', 'pagarmetoken' + suffix);
- $hidden.setAttribute('id', 'pagarmetoken' + suffix);
- $hidden.setAttribute('value', objJSON.id);
- $hidden.setAttribute('data-pagarmetoken', suffix);
-
- form.append($hidden);
-
- for (var i = 0; i < notMarkedInputs.length; i += 1) {
- callbackObj[notMarkedInputs[i]['name']] = notMarkedInputs[i]['value'];
- }
-
- callbackObj['pagarmetoken'] = objJSON.id;
- cardTokensGenerated++;
-
- if (cardTokensGenerated === suffixes.length) {
- cb = _onDone.call(null, callbackObj, suffix);
- if (typeof cb === 'boolean' && !cb) {
- enableFields(markedInputs);
- return;
- }
-
- swal.close();
-
- const message = {
- title: 'Aguarde...',
- text: 'Nós estamos processando sua requisição.',
- allowOutsideClick: false
- };
-
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
-
- swal.showLoading();
-
- form.submit();
- }
-
- },
- function (error, suffix) {
- swal.close();
- if (error.statusCode == 503) {
- const message = {
- type: 'error',
- html: 'Não foi possÃvel gerar a transação segura. Serviço indisponÃvel.'
- };
-
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
- } else {
- _onFail(error, suffix);
- }
-
- }
- );
- }
- };
-
- const _onFail = function (error, suffix) {
- $('body').trigger('onPagarmeCheckoutFail', [error]);
- };
-
- const _onDone = function (data, suffix) { };
-
- const getCardTypes = function () {
- return [{
- brand: 'vr',
- brandName: 'VR',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [637036, 627416, 636350, 637037]
- }, {
- brand: 'mais',
- brandName: 'Mais',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [628028]
- }, {
- brand: 'paqueta',
- brandName: 'Paqueta',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [960371]
- }, {
- brand: 'sodexo',
- brandName: 'Sodexo',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [603389, 606071, 606069, 600818, 606070, 606068]
- }, {
- brand: 'hipercard',
- brandName: 'Hipercard',
- gaps: [4, 8, 12],
- lenghts: [13, 16, 19],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [384100, 384140, 384160, 60, 606282, 637095, 637568, 637599, 637609, 637612, 637600]
- }, {
- brand: 'discover',
- brandName: 'Discover',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 4,
- prefixes: [6011, 622, 64, 65]
- }, {
- brand: 'diners',
- brandName: 'Diners',
- gaps: [4, 8, 12],
- lenghts: [14, 16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [300, 301, 302, 303, 304, 305, 36, 38]
- }, {
- brand: 'amex',
- brandName: 'Amex',
- gaps: [4, 10],
- lenghts: [15],
- mask: '/(\\d{1,4})(\\d{1,6})?(\\d{1,5})?/g',
- cvv: 4,
- prefixes: [34, 37]
- }, {
- brand: 'aura',
- brandName: 'Aura',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [50]
- }, {
- brand: 'jcb',
- brandName: 'JCB',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [35, 2131, 1800]
- }, {
- brand: 'visa',
- brandName: 'Visa',
- gaps: [4, 8, 12],
- lenghts: [13, 16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [4]
- }, {
- brand: 'mastercard',
- brandName: 'Mastercard',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [5, 2]
- }, {
- brand: 'elo',
- brandName: 'Elo',
- gaps: [4, 8, 12],
- lenghts: [16],
- mask: '/(\\d{1,4})/g',
- cvv: 3,
- prefixes: [401178, 401179, 431274, 438935, 451416, 457393, 457631, 457632, 498405, 498410, 498411, 498412, 498418, 498419, 498420, 498421, 498422, 498427, 498428, 498429, 498432, 498433, 498472, 498473, 498487, 498493, 498494, 498497, 498498, 504175, 506699, 506700, 506701, 506702, 506703, 506704, 506705, 506706, 506707, 506708, 506709, 506710, 506711, 506712, 506713, 506714, 506715, 506716, 506717, 506718, 506719, 506720, 506721, 506722, 506723, 506724, 506725, 506726, 506727, 506728, 506729, 506730, 506731, 506732, 506733, 506734, 506735, 506736, 506737, 506738, 506739, 506740, 506741, 506742, 506743, 506744, 506745, 506746, 506747, 506748, 506749, 506750, 506751, 506752, 506753, 506754, 506755, 506756, 506757, 506758, 506759, 506760, 506761, 506762, 506763, 506764, 506765, 506766, 506767, 506768, 506769, 506770, 506771, 506772, 506773, 506774, 506775, 506776, 506777, 506778, 509000, 509001, 509002, 509003, 509004, 509005, 509006, 509007, 509008, 509009, 509010, 509011, 509012, 509013, 509014, 509015, 509016, 509017, 509018, 509019, 509020, 509021, 509022, 509023, 509024, 509025, 509026, 509027, 509028, 509029, 509030, 509031, 509032, 509033, 509034, 509035, 509036, 509037, 509038, 509039, 509040, 509041, 509042, 509043, 509044, 509045, 509046, 509047, 509048, 509049, 509050, 509051, 509052, 509053, 509054, 509055, 509056, 509057, 509058, 509059, 509060, 509061, 509062, 509063, 509064, 509065, 509066, 509067, 509068, 509069, 509070, 509071, 509072, 509073, 509074, 509075, 509076, 509077, 509078, 509079, 509080, 509081, 509082, 509083, 509084, 509085, 509086, 509087, 509088, 509089, 509090, 509091, 509092, 509093, 509094, 509095, 509096, 509097, 509098, 509099, 509100, 509101, 509102, 509103, 509104, 509105, 509106, 509107, 509108, 509109, 509110, 509111, 509112, 509113, 509114, 509115, 509116, 509117, 509118, 509119, 509120, 509121, 509122, 509123, 509124, 509125, 509126, 509127, 509128, 509129, 509130, 509131, 509132, 509133, 509134, 509135, 509136, 509137, 509138, 509139, 509140, 509141, 509142, 509143, 509144, 509145, 509146, 509147, 509148, 509149, 509150, 509151, 509152, 509153, 509154, 509155, 509156, 509157, 509158, 509159, 509160, 509161, 509162, 509163, 509164, 509165, 509166, 509167, 509168, 509169, 509170, 509171, 509172, 509173, 509174, 509175, 509176, 509177, 509178, 509179, 509180, 509181, 509182, 509183, 509184, 509185, 509186, 509187, 509188, 509189, 509190, 509191, 509192, 509193, 509194, 509195, 509196, 509197, 509198, 509199, 509200, 509201, 509202, 509203, 509204, 509205, 509206, 509207, 509208, 509209, 509210, 509211, 509212, 509213, 509214, 509215, 509216, 509217, 509218, 509219, 509220, 509221, 509222, 509223, 509224, 509225, 509226, 509227, 509228, 509229, 509230, 509231, 509232, 509233, 509234, 509235, 509236, 509237, 509238, 509239, 509240, 509241, 509242, 509243, 509244, 509245, 509246, 509247, 509248, 509249, 509250, 509251, 509252, 509253, 509254, 509255, 509256, 509257, 509258, 509259, 509260, 509261, 509262, 509263, 509264, 509265, 509266, 509267, 509268, 509269, 509270, 509271, 509272, 509273, 509274, 509275, 509276, 509277, 509278, 509279, 509280, 509281, 509282, 509283, 509284, 509285, 509286, 509287, 509288, 509289, 509290, 509291, 509292, 509293, 509294, 509295, 509296, 509297, 509298, 509299, 509300, 509301, 509302, 509303, 509304, 509305, 509306, 509307, 509308, 509309, 509310, 509311, 509312, 509313, 509314, 509315, 509316, 509317, 509318, 509319, 509320, 509321, 509322, 509323, 509324, 509325, 509326, 509327, 509328, 509329, 509330, 509331, 509332, 509333, 509334, 509335, 509336, 509337, 509338, 509339, 509340, 509341, 509342, 509343, 509344, 509345, 509346, 509347, 509348, 509349, 509350, 509351, 509352, 509353, 509354, 509355, 509356, 509357, 509358, 509359, 509360, 509361, 509362, 509363, 509364, 509365, 509366, 509367, 509368, 509369, 509370, 509371, 509372, 509373, 509374, 509375, 509376, 509377, 509378, 509379, 509380, 509381, 509382, 509383, 509384, 509385, 509386, 509387, 509388, 509389, 509390, 509391, 509392, 509393, 509394, 509395, 509396, 509397, 509398, 509399, 509400, 509401, 509402, 509403, 509404, 509405, 509406, 509407, 509408, 509409, 509410, 509411, 509412, 509413, 509414, 509415, 509416, 509417, 509418, 509419, 509420, 509421, 509422, 509423, 509424, 509425, 509426, 509427, 509428, 509429, 509430, 509431, 509432, 509433, 509434, 509435, 509436, 509437, 509438, 509439, 509440, 509441, 509442, 509443, 509444, 509445, 509446, 509447, 509448, 509449, 509450, 509451, 509452, 509453, 509454, 509455, 509456, 509457, 509458, 509459, 509460, 509461, 509462, 509463, 509464, 509465, 509466, 509467, 509468, 509469, 509470, 509471, 509472, 509473, 509474, 509475, 509476, 509477, 509478, 509479, 509480, 509481, 509482, 509483, 509484, 509485, 509486, 509487, 509488, 509489, 509490, 509491, 509492, 509493, 509494, 509495, 509496, 509497, 509498, 509499, 509500, 509501, 509502, 509503, 509504, 509505, 509506, 509507, 509508, 509509, 509510, 509511, 509512, 509513, 509514, 509515, 509516, 509517, 509518, 509519, 509520, 509521, 509522, 509523, 509524, 509525, 509526, 509527, 509528, 509529, 509530, 509531, 509532, 509533, 509534, 509535, 509536, 509537, 509538, 509539, 509540, 509541, 509542, 509543, 509544, 509545, 509546, 509547, 509548, 509549, 509550, 509551, 509552, 509553, 509554, 509555, 509556, 509557, 509558, 509559, 509560, 509561, 509562, 509563, 509564, 509565, 509566, 509567, 509568, 509569, 509570, 509571, 509572, 509573, 509574, 509575, 509576, 509577, 509578, 509579, 509580, 509581, 509582, 509583, 509584, 509585, 509586, 509587, 509588, 509589, 509590, 509591, 509592, 509593, 509594, 509595, 509596, 509597, 509598, 509599, 509600, 509601, 509602, 509603, 509604, 509605, 509606, 509607, 509608, 509609, 509610, 509611, 509612, 509613, 509614, 509615, 509616, 509617, 509618, 509619, 509620, 509621, 509622, 509623, 509624, 509625, 509626, 509627, 509628, 509629, 509630, 509631, 509632, 509633, 509634, 509635, 509636, 509637, 509638, 509639, 509640, 509641, 509642, 509643, 509644, 509645, 509646, 509647, 509648, 509649, 509650, 509651, 509652, 509653, 509654, 509655, 509656, 509657, 509658, 509659, 509660, 509661, 509662, 509663, 509664, 509665, 509666, 509667, 509668, 509669, 509670, 509671, 509672, 509673, 509674, 509675, 509676, 509677, 509678, 509679, 509680, 509681, 509682, 509683, 509684, 509685, 509686, 509687, 509688, 509689, 509690, 509691, 509692, 509693, 509694, 509695, 509696, 509697, 509698, 509699, 509700, 509701, 509702, 509703, 509704, 509705, 509706, 509707, 509708, 509709, 509710, 509711, 509712, 509713, 509714, 509715, 509716, 509717, 509718, 509719, 509720, 509721, 509722, 509723, 509724, 509725, 509726, 509727, 509728, 509729, 509730, 509731, 509732, 509733, 509734, 509735, 509736, 509737, 509738, 509739, 509740, 509741, 509742, 509743, 509744, 509745, 509746, 509747, 509748, 509749, 509750, 509751, 509752, 509753, 509754, 509755, 509756, 509757, 509758, 509759, 509760, 509761, 509762, 509763, 509764, 509765, 509766, 509767, 509768, 509769, 509770, 509771, 509772, 509773, 509774, 509775, 509776, 509777, 509778, 509779, 509780, 509781, 509782, 509783, 509784, 509785, 509786, 509787, 509788, 509789, 509790, 509791, 509792, 509793, 509794, 509795, 509796, 509797, 509798, 509799, 509800, 509801, 509802, 509803, 509804, 509805, 509806, 509807, 509808, 509809, 509810, 509811, 509812, 509813, 509814, 509815, 509816, 509817, 509818, 509819, 509820, 509821, 509822, 509823, 509824, 509825, 509826, 509827, 509828, 509829, 509830, 509831, 509832, 509833, 509834, 509835, 509836, 509837, 509838, 509839, 509840, 509841, 509842, 509843, 509844, 509845, 509846, 509847, 509848, 509849, 509850, 509851, 509852, 509853, 509854, 509855, 509856, 509857, 509858, 509859, 509860, 509861, 509862, 509863, 509864, 509865, 509866, 509867, 509868, 509869, 509870, 509871, 509872, 509873, 509874, 509875, 509876, 509877, 509878, 509879, 509880, 509881, 509882, 509883, 509884, 509885, 509886, 509887, 509888, 509889, 509890, 509891, 509892, 509893, 509894, 509895, 509896, 509897, 509898, 509899, 509900, 509901, 509902, 509903, 509904, 509905, 509906, 509907, 509908, 509909, 509910, 509911, 509912, 509913, 509914, 509915, 509916, 509917, 509918, 509919, 509920, 509921, 509922, 509923, 509924, 509925, 509926, 509927, 509928, 509929, 509930, 509931, 509932, 509933, 509934, 509935, 509936, 509937, 509938, 509939, 509940, 509941, 509942, 509943, 509944, 509945, 509946, 509947, 509948, 509949, 509950, 509951, 509952, 509953, 509954, 509955, 509956, 509957, 509958, 509959, 509960, 509961, 509962, 509963, 509964, 509965, 509966, 509967, 509968, 509969, 509970, 509971, 509972, 509973, 509974, 509975, 509976, 509977, 509978, 509979, 509980, 509981, 509982, 509983, 509984, 509985, 509986, 509987, 509988, 509989, 509990, 509991, 509992, 509993, 509994, 509995, 509996, 509997, 509998, 509999, 627780, 636297, 636368, 650031, 650032, 650033, 650035, 650036, 650037, 650038, 650039, 650040, 650041, 650042, 650043, 650044, 650045, 650046, 650047, 650048, 650049, 650050, 650051, 650405, 650406, 650407, 650408, 650409, 650410, 650411, 650412, 650413, 650414, 650415, 650416, 650417, 650418, 650419, 650420, 650421, 650422, 650423, 650424, 650425, 650426, 650427, 650428, 650429, 650430, 650431, 650432, 650433, 650434, 650435, 650436, 650437, 650438, 650439, 650485, 650486, 650487, 650488, 650489, 650490, 650491, 650492, 650493, 650494, 650495, 650496, 650497, 650498, 650499, 650500, 650501, 650502, 650503, 650504, 650505, 650506, 650507, 650508, 650509, 650510, 650511, 650512, 650513, 650514, 650515, 650516, 650517, 650518, 650519, 650520, 650521, 650522, 650523, 650524, 650525, 650526, 650527, 650528, 650529, 650530, 650531, 650532, 650533, 650534, 650535, 650536, 650537, 650538, 650541, 650542, 650543, 650544, 650545, 650546, 650547, 650548, 650549, 650550, 650551, 650552, 650553, 650554, 650555, 650556, 650557, 650558, 650559, 650560, 650561, 650562, 650563, 650564, 650565, 650566, 650567, 650568, 650569, 650570, 650571, 650572, 650573, 650574, 650575, 650576, 650577, 650578, 650579, 650580, 650581, 650582, 650583, 650584, 650585, 650586, 650587, 650588, 650589, 650590, 650591, 650592, 650593, 650594, 650595, 650596, 650597, 650598, 650700, 650701, 650702, 650703, 650704, 650705, 650706, 650707, 650708, 650709, 650710, 650711, 650712, 650713, 650714, 650715, 650716, 650717, 650718, 650720, 650721, 650722, 650723, 650724, 650725, 650726, 650727, 650901, 650902, 650903, 650904, 650905, 650906, 650907, 650908, 650909, 650910, 650911, 650912, 650913, 650914, 650915, 650916, 650917, 650918, 650919, 650920, 651652, 651653, 651654, 651655, 651656, 651657, 651658, 651659, 651660, 651661, 651662, 651663, 651664, 651665, 651666, 651667, 651668, 651669, 651670, 651671, 651672, 651673, 651674, 651675, 651676, 651677, 651678, 651679, 655000, 655001, 655002, 655003, 655004, 655005, 655006, 655007, 655008, 655009, 655010, 655011, 655012, 655013, 655014, 655015, 655016, 655017, 655018, 655019, 655021, 655022, 655023, 655024, 655025, 655026, 655027, 655028, 655029, 655030, 655031, 655032, 655033, 655034, 655035, 655036, 655037, 655038, 655039, 655040, 655041, 655042, 655043, 655044, 655045, 655046, 655047, 655048, 655049, 655050, 655051, 655052, 655053, 655054, 655055, 655056, 655057, 655058, 637095, 650921, 650978]
- }];
- };
-
- const serialize = function (obj) {
- var str = [];
- for (var p in obj) {
- if (obj.hasOwnProperty(p)) {
- str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
- }
- }
- return str.join("&");
- };
-
- const keyEventHandlerCard = function (event) {
- var elem = event.currentTarget;
- var cardNumber = elem.value.replace(/\s/g, '');
- var bin = cardNumber.substr(0, 6);
- var types = getCardTypes();
- var brand;
- if (cardNumber.length >= 6) {
- brand = getBrand(types, bin);
- if (brand) {
- changeBrand(brand, cardNumber.length);
- } else {
- changeBrand('', cardNumber.length);
- }
- } else {
- changeBrand('', cardNumber.length);
- }
- };
-
- const disableFields = function (fields) {
- for (let i = 0; i < fields.length; i += 1) {
- fields[i].setAttribute('disabled', 'disabled');
- }
- };
-
- const enableFields = function (fields) {
- for (let i = 0; i < fields.length; i += 1) {
- fields[i].removeAttribute('disabled');
- }
- };
-
- const hasCardId = function () {
- if (chooseCreditCard === undefined || chooseCreditCard.length === 0) {
- return false;
- }
- return chooseCreditCard.val().trim() !== '';
- };
-
- window.pagarmeQrCodeCopy = function () {
- const qrCodeElement = document.getElementById("pagarme-qr-code");
-
- if (!qrCodeElement) {
- return;
- }
-
- const rawCode = qrCodeElement.getAttribute("rawCode");
-
- const input = document.createElement('input');
- document.body.appendChild(input)
- input.value = rawCode;
- input.select();
- document.execCommand('copy', false);
- input.remove();
-
- alert("Código copiado.");
-
- }
-
- const validate = function () {
- var requiredFields = $('[data-required=true]:visible'),
- isValid = true;
-
- requiredFields.each(function (index, item) {
- var field = $(item);
- if (!$.trim(field.val())) {
- if (field.attr('id') == 'installments') {
- field = field.next(); //Select2 span
- }
- field.addClass('invalid');
- isValid = false;
- }
- });
-
- return isValid;
- };
-
- const error = function (event, errorThrown) {
- var error, rect;
- var element = $('#wcmp-checkout-errors');
-
- swal.close();
-
- errorList = '';
-
- for (error in errorThrown.errors) {
- (errorThrown.errors[error] || []).forEach(parseErrorsList.bind(error));
- }
-
- element.find('.woocommerce-error').html(errorList);
- element.slideDown();
-
- rect = element.get(0).getBoundingClientRect();
-
- jQuery('#wcmp-submit').removeAttr('disabled', 'disabled');
-
- window.scrollTo(0, (rect.top + window.scrollY) - 40);
- };
-
- const parseErrorsList = function (error, message, index) {
- errorList += ' ' + translateErrors(error, message) + ' ';
- };
-
- let translateErrors = function (error, message) {
- error = error.replace('request.', '');
- var ptBrMessages = PagarmeGlobalVars.checkoutErrors.pt_BR;
-
- if (PagarmeGlobalVars.WPLANG != 'pt_BR') {
- return error;
- }
-
- if (ptBrMessages.hasOwnProperty(error)) {
- return ptBrMessages[error];
- }
-
- return error;
- };
-
- const _onChangeCreditCard = function (event) {
- var select = $(event.currentTarget);
- var wrapper = select.closest('fieldset');
- var method = event.currentTarget.value.trim() ? 'slideUp' : 'slideDown';
- var type = method == 'slideUp' ? 'OneClickBuy' : 'DefaultBuy';
- var brandInput = wrapper.find('[type="hidden"]');
-
- $('#wcmp-checkout-errors').hide();
-
- $('body').trigger("onPagarmeCardTypeChange", [type, wrapper]);
-
- var brand = select.find('option:selected').data('brand');
- brandInput.val(brand);
-
- if (select.data('installments-type') == 2) {
-
- if (type == 'OneClickBuy') {
- $('body').trigger('pagarmeSelectOneClickBuy', [brand, wrapper]);
- } else {
- brandInput.val('');
- var option = '... ';
- $('[data-element=installments]').html(option);
- }
- } else if (type == 'OneClickBuy') {
- $('body').trigger('pagarmeSelectOneClickBuy', [brand, wrapper]);
- }
-
- wrapper.find('[data-element="fields-cc-data"]')[method]();
- wrapper.find('[data-element="fields-voucher-data"]')[method]();
- wrapper.find('[data-element="save-cc-check"]')[method]();
- wrapper.find('[data-element="enable-multicustomers-check"]')[method]();
- wrapper.find('[data-element="enable-multicustomers-label-card"]')[method]();
- };
-
- function addsMask() {
- $('.pagarme-card-form-card-number').mask('0000 0000 0000 0000');
- $('.pagarme-card-form-card-expiry').mask('00 / 00');
- $('.pagarme-card-form-card-cvc').mask('0000');
-
- $('#card-order-value').mask('#.##0,00', {
- reverse: true
- });
- $('#card-order-value2').mask('#.##0,00', {
- reverse: true
- });
- $('#billet-value').mask('#.##0,00', {
- reverse: true
- });
-
- $('input[name*=\\[cpf\\]]').mask('000.000.000-00');
- $('input[name*=\\[zip_code\\]]').mask('00000-000');
- }
-
- $('body').on('onPagarmeCheckoutFail', error);
- $('body').on('pagarmeBlurCardOrderValue', onBlurCardOrderValue);
- $('body').on('pagarmeSelectOneClickBuy', onSelectOneClickBuy);
-
- $('body').on('checkout_error', function () {
- swal.close();
- });
-
- $('body').on('updated_checkout', function () {
- if (isFirstLoad) {
- isFirstLoad = false;
- const firstPaymentMethod = jQuery("[data-pagarme-component=checkout-transparent]").children().first();
- const firstPaymentMethodInput = firstPaymentMethod.children('input');
- firstPaymentMethodInput.click();
- }
- const changeEvent = new Event('click');
- Object.defineProperty(changeEvent, 'target', {
- writable: false,
- value: $('input[name=pagarme_payment_method]:checked')
- });
- openPaymentMethodDetails(changeEvent);
- });
-});
diff --git a/assets/javascripts/front/templates/index.php b/assets/javascripts/front/templates/index.php
deleted file mode 100644
index 7e914158..00000000
--- a/assets/javascripts/front/templates/index.php
+++ /dev/null
@@ -1,2 +0,0 @@
-getInstallmentsByType($total);
+ }
+
/**
* @return array
*/
public function render()
{
- return Checkouts::render_installments($this->getCartTotals());
+ return $this->render_installments($this->getCartTotals());
}
}
diff --git a/src/Controller/Gateways.php b/src/Controller/Gateways.php
deleted file mode 100644
index 4f512d97..00000000
--- a/src/Controller/Gateways.php
+++ /dev/null
@@ -1,1269 +0,0 @@
-model = new Gateway();
-
- $this->id = 'woo-pagarme-payments';
- $this->method_title = __('Pagar.me Payments', 'woo-pagarme-payments');
- $this->method_description = __('Payment Gateway Pagar.me', 'woo-pagarme-payments');
- $this->has_fields = false;
- $this->icon = Core::plugins_url('assets/images/logo.png');
-
- $this->init_form_fields();
- $this->init_settings();
-
- $this->enabled = $this->get_option('enabled', 'no');
- $this->title = $this->get_option('title');
- $this->has_fields = true;
-
- if (is_admin()) {
- add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
- }
-
- add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
- add_action('woocommerce_thankyou_' . self::PAYMENT_METHOD, array($this, 'thank_you_page'));
- }
-
- public function payment_fields()
- {
- echo (Utils::get_template_as_string(
- 'templates/checkout/main',
- array(
- 'model' => $this->model,
- )
- ));
- }
-
- /**
- * Output the admin options table.
- *
- * @since 1.0
- * @param null
- * @return Void
- */
- public function admin_options()
- {
- printf(
- '%s
- ',
- __('General', 'woo-pagarme-payments'),
- Utils::get_component('settings'),
- $this->generate_settings_html($this->get_form_fields(), false)
- );
- }
-
- /**
- * Return the name of the option in the WP DB.
- * @since 1.0
- * @return string
- */
- public function get_option_key()
- {
- return $this->model->settings->get_option_key();
- }
-
- public function is_available()
- {
- return ($this->model->settings->is_enabled() && !$this->get_errors() && $this->model->supported_currency());
- }
-
- public function init_form_fields()
- {
- $this->form_fields = array(
- 'enabled' => $this->field_enabled(),
- 'hub_button_integration' => $this->field_hub_button_integration(),
- 'hub_environment' => $this->field_hub_environment(),
- 'title' => $this->field_title(),
- 'is_gateway_integration_type' => $this->field_is_gateway_integration_type(),
- 'section_payment_settings' => $this->section_payment_settings(),
- 'enable_credit_card' => $this->field_enable_credit_card(),
- 'enable_pix' => $this->field_enable_pix(),
- 'enable_billet' => $this->field_enable_billet(),
- 'enable_voucher' => $this->field_enable_voucher(),
- 'multimethods_2_cards' => $this->field_multimethods_2_cards(),
- 'multimethods_billet_card' => $this->field_multimethods_billet_card(),
- 'multicustomers' => $this->field_multicustomers(),
- 'section_credit_card' => $this->section_credit_card(),
- 'cc_operation_type' => $this->field_cc_operation_type(),
- 'cc_soft_descriptor' => $this->field_cc_soft_descriptor(),
- 'cc_flags' => $this->field_cc_flags(),
- 'cc_allow_save' => $this->field_cc_allow_save(),
- 'cc_installment_type' => $this->field_cc_installment_type(),
- 'cc_installments_maximum' => $this->field_cc_installment_fields('maximum'),
- 'cc_installments_min_amount' => $this->field_cc_installment_fields('installment_min_amount'),
- 'cc_installments_interest' => $this->field_cc_installment_fields('interest'),
- 'cc_installments_interest_increase' => $this->field_cc_installment_fields('interest_increase'),
- 'cc_installments_without_interest' => $this->field_cc_installment_fields('without_interest'),
- 'cc_installments_by_flag' => $this->field_cc_installment_fields('flags'),
- 'section_pix' => $this->section_pix(),
- 'pix_qrcode_expiration_time' => $this->field_pix_qrcode_expiration_time(),
- 'pix_additional_data' => $this->field_pix_additional_data(),
- 'section_billet' => $this->section_billet(),
- 'billet_bank' => $this->field_billet_bank(),
- 'billet_deadline_days' => $this->field_billet_deadline_days(),
- 'billet_instructions' => $this->field_billet_instructions(),
- 'section_voucher' => $this->section_voucher(),
- 'voucher_soft_descriptor' => $this->field_voucher_soft_descriptor(),
- 'field_voucher_flags' => $this->field_voucher_flags(),
- 'voucher_card_wallet' => $this->field_voucher_card_wallet(),
- 'section_antifraud' => $this->section_antifraud(),
- 'antifraud_enabled' => $this->antifraud_enabled(),
- 'antifraud_min_value' => $this->antifraud_min_value(),
- 'section_tools' => $this->section_tools(),
- 'enable_logs' => $this->field_enabled_logs(),
- );
- }
-
- public function process_payment($order_id): array
- {
- $wc_order = new WC_Order($order_id);
- $formattedPost['order'] = $order_id;
- $formattedPost['fields'] = array();
- $paymentMethod = sanitize_text_field($_POST['pagarme_payment_method']);
-
- $formattedPost = $this->formatPOST($formattedPost, $paymentMethod);
- $_POST = $formattedPost;
-
- $checkout = new Checkout();
- $checkout->process_checkout_transparent($wc_order);
-
- return array(
- 'result' => 'success',
- 'redirect' => $this->get_return_url($wc_order)
- );
- }
-
- private function formatPOST($formattedPost, $paymentMethod)
- {
- $filteredPost = array_intersect_key($_POST, array_flip(
- $this->dataToFilterFromPost($paymentMethod)
- ));
-
- $formattedPost = $this->addsFilteredDataInFormattedPostArray($filteredPost, $formattedPost);
-
- $formattedPost = $this->renameFieldsFromFormattedPost($formattedPost, $paymentMethod);
-
- $formattedPost = $this->formatMulticustomerCardArray($formattedPost);
-
- return $formattedPost;
- }
-
- private function addsFilteredDataInFormattedPostArray($filteredPost, $formattedPost)
- {
- foreach ($filteredPost as $key => $value) {
- array_push($formattedPost['fields'], [
- "name" => sanitize_text_field($key),
- "value" => $this->sanitize_field($value)
- ]);
- }
-
- return $formattedPost;
- }
-
- private function sanitize_field($field)
- {
- if (is_array($field)) {
- $sanitizedData = [];
- foreach ($field as $key => $value) {
- $sanitizedData[$key] = sanitize_text_field($value);
- }
- return $sanitizedData;
- }
-
- return sanitize_text_field($field);
- }
-
- private function formatMulticustomerCardArray($formattedPost)
- {
- foreach ($formattedPost['fields'] as $fieldsValue) {
- if (strstr($fieldsValue['name'], 'multicustomer_')) {
- $formattedPost = $this->addsDataInFormattedPost(
- $fieldsValue['value'],
- $fieldsValue['name'],
- $formattedPost
- );
- }
- }
-
- return $formattedPost;
- }
-
- private function dataToFilterFromPost($paymentMethod)
- {
- switch ($paymentMethod) {
- case 'credit_card':
- return [
- 'brand1',
- 'pagarmetoken1',
- 'installments_card',
- 'multicustomer_card',
- 'pagarme_payment_method',
- 'enable_multicustomers_card',
- 'save_credit_card1',
- 'card_id'
- ];
- case '2_cards':
- return [
- 'card_order_value',
- 'brand2',
- 'pagarmetoken2',
- 'installments',
- 'multicustomer_card1',
- 'card_order_value2',
- 'brand3',
- 'pagarmetoken3',
- 'installments2',
- 'multicustomer_card2',
- 'pagarme_payment_method',
- 'enable_multicustomers_card1',
- 'enable_multicustomers_card2',
- 'save_credit_card2',
- 'save_credit_card3',
- 'card_id2',
- 'card_id3'
- ];
- case 'billet-and-card':
- return [
- 'card_billet_order_value',
- 'installments3',
- 'multicustomer_card_billet',
- 'billet_value',
- 'brand4',
- 'pagarmetoken4',
- 'multicustomer_billet_card',
- 'pagarme_payment_method',
- 'enable_multicustomers_billet',
- 'enable_multicustomers_card',
- 'save_credit_card4',
- 'card_id4'
- ];
- case 'billet':
- return [
- 'multicustomer_billet',
- 'pagarme_payment_method',
- 'enable_multicustomers_billet',
- ];
- case 'pix':
- return [
- 'multicustomer_pix',
- 'pagarme_payment_method',
- 'enable_multicustomers_pix',
- ];
- case 'voucher':
- return [
- 'multicustomer_voucher',
- 'brand6',
- 'pagarme_payment_method',
- 'pagarmetoken6',
- 'enable_multicustomers_voucher',
- 'save_credit_card6',
- 'card_id6'
- ];
- default:
- return $_POST;
- }
- }
-
-
- private function addsDataInFormattedPost(
- $fieldValue,
- $fieldValueName,
- $formattedPost
- ) {
- foreach ($fieldValue as $key => $value) {
- array_push($formattedPost['fields'], [
- "name" => $fieldValueName . '[' . $key . ']',
- "value" => $value
- ]);
- }
-
- return $formattedPost;
- }
-
- private function renameFieldsFromFormattedPost($formattedPost, $paymentMethod)
- {
- foreach ($formattedPost['fields'] as $arrayFieldKey => $field) {
-
- $formattedPost = $this->applyForAllFields(
- $field,
- $formattedPost,
- $arrayFieldKey
- );
-
- if ($paymentMethod == 'credit_card') {
- $formattedPost = $this->applyForCardCreditField(
- $field,
- $formattedPost,
- $arrayFieldKey
- );
- }
-
- if ($paymentMethod == 'billet-and-card') {
- $formattedPost = $this->applyForBilletAndCardField(
- $field,
- $formattedPost,
- $arrayFieldKey
- );
- }
-
- if ($paymentMethod == '2_cards') {
- $formattedPost = $this->applyFor2CardField(
- $field,
- $formattedPost,
- $arrayFieldKey
- );
- }
-
- if ($paymentMethod == 'voucher') {
- $formattedPost = $this->applyForCardCVoucherField(
- $field,
- $formattedPost,
- $arrayFieldKey
- );
- }
- }
-
- return $formattedPost;
- }
-
- private function applyForAllFields(
- $field,
- $formattedPost,
- $arrayFieldKey
- ) {
- if (in_array('pagarme_payment_method', $field)) {
- $field['name'] = 'payment_method';
- $formattedPost['fields'][$arrayFieldKey] = $field;
- }
-
- return $formattedPost;
- }
-
- private function applyForCardCreditField(
- $field,
- $formattedPost,
- $arrayFieldKey
- ) {
-
- $dictionary = [
- 'installments_card' => 'installments',
- 'brand1' => 'brand',
- 'save_credit_card1' => 'save_credit_card'
- ];
-
- foreach ($dictionary as $fieldKey => $formatedPostKey) {
- if (in_array($fieldKey, $field)) {
- $field['name'] = $formatedPostKey;
- $formattedPost['fields'][$arrayFieldKey] = $field;
- }
- }
-
- return $formattedPost;
- }
-
- private function applyForCardCVoucherField(
- $field,
- $formattedPost,
- $arrayFieldKey
- ) {
- $dictionary = [
- 'card_id6' => 'card_id',
- 'brand6' => 'brand',
- 'save_credit_card6' => 'save_credit_card'
- ];
- foreach ($dictionary as $fieldKey => $formatedPostKey) {
- if (in_array($fieldKey, $field)) {
- $field['name'] = $formatedPostKey;
- $formattedPost['fields'][$arrayFieldKey] = $field;
- }
- }
- return $formattedPost;
- }
-
- private function applyForBilletAndCardField(
- $field,
- $formattedPost,
- $arrayFieldKey
- ) {
-
- $dictionary = [
- 'card_billet_order_value' => 'card_order_value',
- 'multicustomer_card_billet' => 'multicustomer_card',
- 'multicustomer_billet_card' => 'multicustomer_billet',
- 'brand4' => 'brand',
- 'installments3' => 'installments',
- 'pagarmetoken4' => 'pagarmetoken1',
- 'card_id4' => 'card_id',
- 'save_credit_card4' => 'save_credit_card'
- ];
-
- foreach ($dictionary as $fieldKey => $formatedPostKey) {
- if (in_array($fieldKey, $field)) {
- $field['name'] = $formatedPostKey;
- $formattedPost['fields'][$arrayFieldKey] = $field;
- }
- }
-
- if (in_array('pagarme_payment_method', $field)) {
- $field['name'] = 'payment_method';
- $field['value'] = 'billet_and_card';
- $formattedPost['fields'][$arrayFieldKey] = $field;
- }
-
- return $formattedPost;
- }
-
- private function applyFor2CardField(
- $field,
- $formattedPost,
- $arrayFieldKey
- ) {
-
- $dictionary = [
- 'brand2' => 'brand',
- 'brand3' => 'brand2',
- 'pagarmetoken2' => 'pagarmetoken1',
- 'pagarmetoken3' => 'pagarmetoken2',
- 'card_id2' => 'card_id',
- 'card_id3' => 'card_id2',
- 'save_credit_card2' => 'save_credit_card',
- 'save_credit_card3' => 'save_credit_card2'
-
- ];
-
- foreach ($dictionary as $fieldKey => $formatedPostKey) {
- if (in_array($fieldKey, $field)) {
- $field['name'] = $formatedPostKey;
- $formattedPost['fields'][$arrayFieldKey] = $field;
- }
- }
-
- return $formattedPost;
- }
-
- public function receipt_page($order_id)
- {
- $this->checkout_transparent($order_id);
- }
-
- public function thank_you_page($order_id)
- {
- $order = new WC_Order($order_id);
-
- require_once Core::get_file_path('thank-you-page.php', 'templates/');
- }
-
- public function checkout_transparent($order_id)
- {
- $wc_order = new WC_Order($order_id);
-
- require_once Core::get_file_path('main.php', 'templates/checkout/');
- }
-
- public function section_payment_settings()
- {
- return array(
- 'title' => __('Payment methods', 'woo-pagarme-payments'),
- 'type' => 'title',
- );
- }
-
- public function field_enabled()
- {
- return array(
- 'title' => __('Enable', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable Pagar.me', 'woo-pagarme-payments'),
- 'default' => 'no',
- );
- }
-
- public function field_title()
- {
- return array(
- 'title' => __('Checkout title', 'woo-pagarme-payments'),
- 'description' => __('Name shown to the customer in the checkout page.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'default' => __('Pagar.me', 'woo-pagarme-payments'),
- );
- }
-
- public function field_is_gateway_integration_type()
- {
- return array(
- 'title' => __('Advanced settings', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable advanced settings', 'woo-pagarme-payments'),
- 'default' => 'no',
- 'description' => __('Configurations that only works for Gateway customers, who have a direct contract with an acquirer.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'custom_attributes' => array(
- 'data-action' => 'is-gateway-integration-type',
- ),
- );
- }
-
- public function field_enable_credit_card()
- {
- return array(
- 'title' => __('Credit card', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable credit card', 'woo-pagarme-payments'),
- 'default' => 'yes',
- );
- }
-
- public function field_enable_pix()
- {
- return array(
- 'title' => __('Pix', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable pix', 'woo-pagarme-payments'),
- 'default' => 'no'
- );
- }
-
- public function field_enable_voucher()
- {
- return array(
- 'title' => __('Voucher', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable voucher', 'woo-pagarme-payments'),
- 'default' => 'no'
- );
- }
-
- public function field_voucher_card_wallet()
- {
- return array(
- 'title' => __('Card Wallet', 'woo-pagarme-payments'),
- 'desc_tip' => __('Enable Card Wallet', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Card Wallet', 'woo-pagarme-payments'),
- 'default' => 'no',
- 'custom_attributes' => array(
- 'data-field' => 'voucher-card-wallet',
- ),
- );
- }
-
- public function field_enable_billet()
- {
- return array(
- 'title' => __('Boleto', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable boleto', 'woo-pagarme-payments'),
- 'default' => 'yes',
- 'custom_attributes' => array(
- 'data-action' => 'enable-billet',
- 'data-requires-field' => 'billet-bank',
- ),
- );
- }
-
- public function field_multimethods_2_cards()
- {
- return array(
- 'title' => __('Multi-means (2 Credit cards)', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable multi-means (2 Credit cards)', 'woo-pagarme-payments'),
- 'default' => 'no',
- );
- }
-
- public function field_multimethods_billet_card()
- {
- return array(
- 'title' => __('Multi-means (Boleto + Credit card)', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable multi-means (Boleto + Credit card)', 'woo-pagarme-payments'),
- 'default' => 'no',
- 'custom_attributes' => array(
- 'data-action' => 'enable-multimethods-billet-card',
- 'data-requires-field' => 'billet-bank',
- ),
- );
- }
-
- public function field_multicustomers()
- {
- return array(
- 'title' => __('Multi-buyers', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable multi-buyers', 'woo-pagarme-payments'),
- 'default' => 'no',
- );
- }
-
- public function section_voucher()
- {
- return array(
- 'title' => __('Voucher settings', 'woo-pagarme-payments'),
- 'type' => 'title',
- 'custom_attributes' => array(
- 'data-field' => 'voucher-section',
- )
- );
- }
-
- public function field_voucher_soft_descriptor()
- {
- return array(
- 'title' => __('Soft descriptor', 'woo-pagarme-payments'),
- 'desc_tip' => __('Description that appears on the voucher bill.', 'woo-pagarme-payments'),
- 'description' => sprintf(__("Max length of %s characters.", 'woo-pagarme-payments'), 13),
- 'custom_attributes' => array(
- 'data-field' => 'voucher-soft-descriptor',
- 'data-action' => 'voucher-soft-descriptor',
- 'data-element' => 'validate',
- 'maxlength' => 22,
- 'data-error-msg' => __('This field is required.', 'woo-pagarme-payments'),
- ),
- );
- }
-
- public function field_voucher_flags()
- {
- return array(
- 'type' => 'multiselect',
- 'title' => __('Voucher Card Brands', 'woo-pagarme-payments'),
- 'select_buttons' => false,
- 'class' => 'wc-enhanced-select',
- 'options' => array(
- 'alelo' => 'Alelo',
- 'sodexo' => 'Sodexo',
- 'vr' => 'VR',
- ),
- 'custom_attributes' => array(
- 'data-field' => 'voucher-flags-select',
- 'data-element' => 'voucher-flags-select',
- 'data-action' => 'flags',
- ),
- );
- }
-
- public function section_credit_card()
- {
- return array(
- 'title' => __('Credit card settings', 'woo-pagarme-payments'),
- 'type' => 'title',
- );
- }
-
- public function field_cc_operation_type()
- {
- return array(
- 'type' => 'select',
- 'title' => __('Operation Type', 'woo-pagarme-payments'),
- 'class' => 'wc-enhanced-select',
- 'default' => 1,
- 'options' => array(
- 1 => __('Authorize', 'woo-pagarme-payments'),
- 2 => __('Authorize and Capture', 'woo-pagarme-payments'),
- ),
- );
- }
-
- public function field_cc_soft_descriptor()
- {
- return array(
- 'title' => __('Soft descriptor', 'woo-pagarme-payments'),
- 'desc_tip' => __('Description that appears on the credit card bill.', 'woo-pagarme-payments'),
- 'description' => sprintf(__("Max length of %s characters.", 'woo-pagarme-payments'), 13),
- 'custom_attributes' => array(
- 'data-field' => 'soft-descriptor',
- 'data-action' => 'soft-descriptor',
- 'data-element' => 'validate',
- 'maxlength' => 13,
- 'data-error-msg' => __('This field is required.', 'woo-pagarme-payments'),
- ),
- );
- }
-
- public function field_cc_allow_save()
- {
- return array(
- 'title' => __('Card wallet', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable card wallet', 'woo-pagarme-payments'),
- 'default' => 'no',
- 'description' => __('Allows for cards to be saved for future purchases.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'custom_attributes' => array(
- 'data-field' => 'cc-allow-save',
- ),
- );
- }
-
- public function field_cc_flags()
- {
- return array(
- 'type' => 'multiselect',
- 'title' => __('Card Brands', 'woo-pagarme-payments'),
- 'select_buttons' => false,
- 'class' => 'wc-enhanced-select',
- 'options' => $this->model->settings->get_flags_list(),
- 'custom_attributes' => array(
- 'data-field' => 'flags-select',
- 'data-element' => 'flags-select',
- 'data-action' => 'flags',
- ),
- );
- }
-
- public function field_cc_manual_capture()
- {
- return array(
- 'title' => __('Manual Capture', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable Manual Capture', 'woo-pagarme-payments'),
- 'default' => 'yes',
- );
- }
-
- public function field_cc_installment_type()
- {
- return array(
- 'title' => __('Installment configuration', 'woo-pagarme-payments'),
- 'type' => 'select',
- 'class' => 'wc-enhanced-select',
- 'label' => __('Choose the installment configuration', 'woo-pagarme-payments'),
- 'default' => 1,
- 'options' => array(
- Gateway::CC_TYPE_SINGLE => __('For all card brands', 'woo-pagarme-payments'),
- Gateway::CC_TYPE_BY_FLAG => __('By card brand', 'woo-pagarme-payments'),
- ),
- 'custom_attributes' => array(
- 'data-element' => 'installments-type-select',
- 'data-action' => 'installments-type',
- ),
- );
- }
-
- public function field_cc_installment_fields($field)
- {
- $installments = array();
-
- $installments['maximum'] = array(
- 'title' => __('Max number of installments', 'woo-pagarme-payments'),
- 'type' => 'select',
- 'default' => 12,
- 'options' => $this->model->get_installment_options(),
- 'custom_attributes' => array(
- 'data-field' => 'installments-maximum',
- ),
- );
-
- $installments['installment_min_amount'] = array(
- 'title' => __('Minimum installment amount', 'woo-pagarme-payments'),
- 'type' => 'text',
- 'description' => __('Defines the minimum value that an installment can assume', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'placeholder' => '0.00',
- 'custom_attributes' => array(
- 'data-field' => 'installments-min-amount',
- 'data-mask' => '##0.00',
- 'data-mask-reverse' => 'true',
- ),
- );
-
- $installments['interest'] = array(
- 'title' => __('Initial interest rate (%)', 'woo-pagarme-payments'),
- 'type' => 'text',
- 'description' => __('Interest rate applied starting with the first installment with interest.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'placeholder' => '0.00',
- 'custom_attributes' => array(
- 'data-field' => 'installments-interest',
- 'data-mask' => '##0.00',
- 'data-mask-reverse' => 'true',
- ),
- );
-
- $installments['interest_increase'] = array(
- 'title' => __('Incremental interest rate (%)', 'woo-pagarme-payments'),
- 'type' => 'text',
- 'description' => __('Interest rate added for each installment with interest.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'placeholder' => '0.00',
- 'custom_attributes' => array(
- 'data-field' => 'installments-interest-increase',
- 'data-mask' => '##0.00',
- 'data-mask-reverse' => 'true',
- ),
- );
-
- $installments['without_interest'] = array(
- 'title' => __('Number of installments without interest', 'woo-pagarme-payments'),
- 'type' => 'select',
- 'default' => 3,
- 'options' => $this->model->get_installment_options(),
- 'custom_attributes' => array(
- 'data-field' => 'installments-without-interest',
- ),
- );
-
- $installments['flags'] = array(
- 'title' => __('Settings by card brand', 'woo-pagarme-payments'),
- 'type' => 'installments_by_flag',
- );
-
- return $installments[$field];
- }
-
- public function section_pix()
- {
- return array(
- 'title' => __('Pix settings', 'woo-pagarme-payments'),
- 'type' => 'title',
- );
- }
-
- public function field_pix_qrcode_expiration_time()
- {
- return array(
- 'title' => __('QR code expiration time', 'woo-pagarme-payments'),
- 'description' => __('Expiration time in seconds of the generated pix QR code.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'placeholder' => 3500,
- 'default' => 3500,
- 'custom_attributes' => array(
- 'data-mask' => '##0',
- 'data-mask-reverse' => 'true',
- ),
- );
- }
-
- public function field_pix_additional_data()
- {
- return array(
- 'title' => __('Additional information', 'woo-pagarme-payments'),
- 'description' => __('Set of key and value used to add information to the generated pix. This will be visible to the buyer during the payment process.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'type' => 'pix_additional_data',
- );
- }
-
- public function field_hub_button_integration()
- {
- return array(
- 'title' => __('Hub integration', 'woo-pagarme-payments'),
- 'type' => 'hub_button_integration',
- );
- }
-
- public function field_hub_environment()
- {
- return array(
- 'title' => __('Integration environment', 'woo-pagarme-payments'),
- 'type' => 'hub_environment',
- );
- }
-
- public function section_billet()
- {
- return array(
- 'title' => __('Boleto settings', 'woo-pagarme-payments'),
- 'type' => 'title',
- );
- }
-
- public function field_billet_bank()
- {
- return array(
- 'type' => 'select',
- 'title' => __('Bank', 'woo-pagarme-payments'),
- 'class' => 'wc-enhanced-select',
- 'default' => 0,
- 'options' => array(
- '237' => 'Banco Bradesco S.A.',
- '341' => 'Banco Itaú S.A.',
- '033' => 'Banco Santander S.A.',
- '745' => 'Banco Citibank S.A.',
- '001' => 'Banco do Brasil S.A.',
- '104' => 'Caixa Econômica Federal',
- ),
- 'custom_attributes' => array(
- 'data-field' => 'billet-bank',
- )
- );
- }
-
- public function field_billet_deadline_days()
- {
- return array(
- 'title' => __('Default expiration days', 'woo-pagarme-payments'),
- 'description' => __('Number of days until the expiration date of the generated boleto.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'placeholder' => 5,
- 'default' => 5,
- 'custom_attributes' => array(
- 'data-mask' => '##0',
- 'data-mask-reverse' => 'true',
- ),
- );
- }
-
- public function field_billet_instructions()
- {
- return array(
- 'title' => __('Payment instructions', 'woo-pagarme-payments'),
- 'type' => 'text',
- 'description' => __('Instructions printed on the boleto.', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- );
- }
-
- public function section_antifraud()
- {
- return array(
- 'title' => __('Anti fraud settings', 'woo-pagarme-payments'),
- 'type' => 'title',
- 'custom_attributes' => array(
- 'data-field' => 'antifraud-section',
- )
- );
- }
-
- public function antifraud_enabled()
- {
- return array(
- 'title' => __('Enable', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable anti fraud', 'woo-pagarme-payments'),
- 'default' => 'no',
- 'custom_attributes' => array(
- 'data-field' => 'antifraud-enabled',
- )
- );
- }
-
- public function antifraud_min_value()
- {
- return array(
- 'title' => __('Minimum amount', 'woo-pagarme-payments'),
- 'type' => 'text',
- 'description' => __('Minimum order amount to send it to the anti fraud', 'woo-pagarme-payments'),
- 'desc_tip' => true,
- 'placeholder' => '100,00',
- 'custom_attributes' => array(
- 'data-mask' => '#.##0,00',
- 'data-mask-reverse' => 'true',
- 'data-field' => 'antifraud-min-value',
- ),
- );
- }
-
- public function section_tools()
- {
- return array(
- 'title' => __('Tools', 'woo-pagarme-payments'),
- 'type' => 'title',
- );
- }
-
- public function field_enabled_logs()
- {
- return array(
- 'title' => __('Logs', 'woo-pagarme-payments'),
- 'type' => 'checkbox',
- 'label' => __('Enable', 'woo-pagarme-payments'),
- 'default' => 'no',
- 'description' => __('Log Pagar.me events, you can check this log in WooCommerce>Status>Logs.', 'woo-pagarme-payments'),
- );
- }
-
- /**
- * Get HTML for descriptions.
- *
- * @param array $data
- * @return string
- */
- public function get_description_html($data)
- {
- if ($data['desc_tip'] === true) {
- return;
- } elseif (!empty($data['desc_tip'])) {
- $description = $data['description'];
- } elseif (!empty($data['description'])) {
- $description = $data['description'];
- } else {
- return;
- }
-
- return sprintf(
- '%s
',
- sanitize_html_class(Utils::get_value_by($data, 'class_p')),
- strip_tags($description, '')
- );
- }
-
- public function generate_pix_additional_data_html($key, $data)
- {
- $field_key = $this->get_field_key($key);
-
- $value = (array) $this->get_option($key, array());
- ob_start();
-
-?>
-
-
-
-
-
- get_tooltip_html($data), ['span' => array('class' => true, 'data-tip' => true)]); ?>
-
-
-
-
-
- " placeholder="" />
- " placeholder="" />
-
-
-
- model->settings->hub_install_id;
- $button_label = $this->model->get_hub_button_text($hub_install_id);
- $url_hub = $this->model->get_hub_url($hub_install_id);
-
- ob_start();
- ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- model->settings->hub_environment); ?>
-
-
- model->is_sandbox_mode()) : ?>
-
-
-
-
-
- = __('Important! This store is linked to the Pagar.me test environment. This environment is intended for integration validation and does not generate real financial transactions.', 'woo-pagarme-payments'); ?>
-
-
-
-
-
-
- get_field_key($key);
- $defaults = array(
- 'title' => '',
- 'disabled' => false,
- 'class' => '',
- 'css' => '',
- 'placeholder' => '',
- 'type' => 'text',
- 'desc_tip' => false,
- 'description' => '',
- 'custom_attributes' => array(),
- );
-
- $data = wp_parse_args($data, $defaults);
- $value = (array) $this->get_option($key, array());
- $flags = $this->model->settings->get_flags_list();
-
- ob_start();
-
- ?>
-
-
-
- get_tooltip_html($data)); ?>
-
-
-
-
-
-
-
-
-payment_method = $payment_method;
- $this->settings = Setting::get_instance();
- }
-
- /**
- * Return the payment array for API request
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function get_payment_data($wc_order, $form_fields, $customer)
- {
- $method_name = $this->get_method_name();
-
- if (!method_exists($this, $method_name)) {
- throw new \Exception('Payment method name not exists');
- }
-
- $data = $this->{$method_name}($wc_order, $form_fields, $customer);
-
- if ($method_name == 'pay_billet_and_card' || $method_name == 'pay_2_cards') {
- return $data;
- }
-
- return array($data);
- }
-
- /**
- * Return method name according to the selected payment method
- *
- * @return string
- */
- public function get_method_name()
- {
- return "pay_{$this->payment_method}";
- }
-
- /**
- * Return payment data for "boleto"
- *
- * @return array
- */
- public function pay_billet($wc_order, $form_fields)
- {
- $billet = $this->pay_billet_base();
- $billet['amount'] = Utils::format_order_price($wc_order->get_total());
- $multicustomer = $this->get_multicustomer_data('billet', $form_fields);
-
- if ($multicustomer) {
- $billet['customer'] = $multicustomer;
- }
-
- return $billet;
- }
-
- /**
- * Return payment data for "pix"
- *
- * @return array
- */
- public function pay_pix($wc_order, $form_fields)
- {
- $pix = $this->pay_pix_base();
- $pix['amount'] = Utils::format_order_price($wc_order->get_total());
- $multicustomer = $this->get_multicustomer_data('pix', $form_fields);
-
- if ($multicustomer) {
- $pix['customer'] = $multicustomer;
- }
-
- return $pix;
- }
-
- /**
- * Return payment data for "voucher"
- *
- * @return array
- */
- public function pay_voucher($wc_order, $form_fields, $customer)
- {
- $card = $this->pay_voucher_base($wc_order, $form_fields, $customer);
- $card_amount = $wc_order->get_total();
- $card['amount'] = Utils::format_order_price($card_amount);
- return $card;
- }
-
- /**
- * Return payment data for "voucher" base
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- private function pay_voucher_base($wc_order, $form_fields, $customer)
- {
- $card_data = array(
- 'payment_method' => 'voucher',
- 'voucher' => array(
- 'statement_descriptor' => $this->settings->voucher_soft_descriptor,
- 'card' => array(
- 'billing_address' => $this->get_billing_address_from_customer($customer, $wc_order)
- )
- ),
- );
-
- return $this->handle_credit_card_type($form_fields, $card_data, '');
- }
-
- /**
- * Return payment data for "credit_card"
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function pay_credit_card($wc_order, $form_fields, $customer)
- {
- $card = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
- $card_installments = Utils::get_value_by($form_fields, 'installments');
- $card_brand = Utils::get_value_by($form_fields, 'brand');
- $card_amount = $this->get_price_with_interest($wc_order->get_total(), $card_installments, $card_brand);
- $card['amount'] = Utils::format_order_price($card_amount);
- $multicustomer = $this->get_multicustomer_data('card', $form_fields);
-
- if ($multicustomer) {
- $card['customer'] = $multicustomer;
- }
-
- if (!$multicustomer && !empty($customer->email)) {
- $card['customer'] = $customer;
- }
-
- return $card;
- }
-
- /**
- * Return payment data for "billet_and_card"
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function pay_billet_and_card($wc_order, $form_fields, $customer)
- {
- $billet_amount = Utils::get_value_by($form_fields, 'billet_value');
- $billet = $this->pay_billet_base();
- $billet['amount'] = Utils::format_desnormalized_order_price($billet_amount);
- $billet_multicustomer = $this->get_multicustomer_data('billet', $form_fields);
-
- if ($billet_multicustomer) {
- $billet['customer'] = $billet_multicustomer;
- }
-
- $card = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
-
- if (!is_array($card) && $card->code != 200) {
- return $card;
- }
-
- $card_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value'));
- $card_installments = Utils::get_value_by($form_fields, 'installments');
- $card_brand = Utils::get_value_by($form_fields, 'brand');
-
- $card_amount = $this->get_price_with_interest($card_amount, $card_installments, $card_brand);
- $card['amount'] = Utils::format_order_price($card_amount);
- $multicustomer = $this->get_multicustomer_data('card', $form_fields);
-
- if ($multicustomer) {
- $card['customer'] = $multicustomer;
- }
-
- return array($billet, $card);
- }
-
- /**
- * Return payment data for "2_cards"
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function pay_2_cards($wc_order, $form_fields, $customer)
- {
- $card1_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value'));
- $card2_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value2'));
-
- $card1 = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
- $card2 = $this->pay_credit_card_base($wc_order, $form_fields, $customer, true);
-
- $card1_installments = Utils::get_value_by($form_fields, 'installments');
- $card2_installments = Utils::get_value_by($form_fields, 'installments2');
-
- $card1_brand = Utils::get_value_by($form_fields, 'brand');
- $card2_brand = Utils::get_value_by($form_fields, 'brand2');
-
- $card1_amount = $this->get_price_with_interest($card1_amount, $card1_installments, $card1_brand);
- $card2_amount = $this->get_price_with_interest($card2_amount, $card2_installments, $card2_brand);
-
- $card1['amount'] = Utils::format_order_price($card1_amount);
- $card2['amount'] = Utils::format_order_price($card2_amount);
-
- $multicustomer_card1 = $this->get_multicustomer_data('card1', $form_fields);
- $multicustomer_card2 = $this->get_multicustomer_data('card2', $form_fields);
-
- if ($multicustomer_card1) {
- $card1['customer'] = $multicustomer_card1;
- }
-
- if ($multicustomer_card2) {
- $card2['customer'] = $multicustomer_card2;
- }
-
- return array($card1, $card2);
- }
-
- /**
- * Return payment data for "credit_card" base (without amount)
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- private function pay_credit_card_base($wc_order, $form_fields, $customer, $is_second_card = false)
- {
- $suffix = $is_second_card ? '2' : '';
- $card_data = array(
- 'payment_method' => 'credit_card',
- 'credit_card' => array(
- 'installments' => Utils::get_value_by($form_fields, "installments{$suffix}"),
- 'statement_descriptor' => $this->settings->cc_soft_descriptor,
- 'capture' => $this->settings->is_active_capture(),
- 'card' => array(
- 'billing_address' => $this->get_billing_address_from_customer($customer, $wc_order)
- )
- ),
- );
-
- return $this->handle_credit_card_type($form_fields, $card_data, $suffix);
- }
-
- private function get_billing_address_from_customer($customer, $wc_order)
- {
- $addressArray = isset($customer->address) ? (array) $customer->address : [];
-
- if (empty($addressArray)) {
- $addressArray = $this->get_customer_address_from_wc_order($wc_order);
- }
-
- return array(
- 'street' => $addressArray["street"],
- 'complement' => $addressArray["complement"],
- 'number' => $addressArray["number"],
- 'zip_code' => $addressArray["zip_code"],
- 'neighborhood' => $addressArray["neighborhood"],
- 'city' => $addressArray["city"],
- 'state' => $addressArray["state"],
- 'country' => $addressArray["country"]
- );
- }
-
- private function get_customer_address_from_wc_order($wc_order)
- {
- $order = new Order($wc_order->get_id());
-
- return Utils::build_customer_address_from_order($order);
- }
-
- /**
- * Return payment data for "boleto"
- *
- * @return array
- */
- private function pay_billet_base()
- {
- $expiration_date = new \DateTime();
- $days = (int) $this->settings->billet_deadline_days;
-
- if ($days) {
- $expiration_date->modify("+{$days} day");
- }
-
- return array(
- 'payment_method' => 'boleto',
- 'boleto' => array(
- 'bank' => $this->settings->billet_bank,
- 'instructions' => $this->settings->billet_instructions,
- 'due_at' => $expiration_date->format('c'),
- ),
- );
- }
-
- /**
- * Return payment data for "pix"
- *
- * @return array
- */
- private function pay_pix_base()
- {
- return array(
- 'payment_method' => 'pix'
- );
- }
-
- /**
- * Return which credit card type will be send. (card ou card_token)
- *
- * @param array $form_fields
- * @param array $card_data
- * @param string $suffix Suffix for each attribute
- *
- * @return array
- */
- private function handle_credit_card_type($form_fields, $card_data, $suffix = '')
- {
- $card_id = Utils::get_value_by($form_fields, "card_id{$suffix}", false);
- $pagarmetoken = !$suffix ? 'pagarmetoken1' : "pagarmetoken{$suffix}";
-
- if ($card_id) {
- $card_data['credit_card']['card_id'] = $card_id;
- } else {
- $card_data['credit_card']['card_token'] = Utils::get_value_by($form_fields, $pagarmetoken);
- }
-
- return $card_data;
- }
-
- private function get_price_with_interest($price, $installments, $flag = '')
- {
- $type = intval($this->settings->cc_installment_type);
- $amount = $price;
-
- if ($type === Gateway::CC_TYPE_SINGLE) { // Parcelamento único
- $no_interest = intval($this->settings->cc_installments_without_interest);
- $interest = Utils::str_to_float($this->settings->cc_installments_interest);
- $interest_increase = Utils::str_to_float($this->settings->cc_installments_interest_increase);
- $max_installments = intval($this->settings->cc_installments_maximum);
- } else { // Parcelamento por bandeira
- $settings_by_flag = $this->settings->cc_installments_by_flag;
- $no_interest = intval($settings_by_flag['no_interest'][$flag]);
- $interest = Utils::str_to_float($settings_by_flag['interest'][$flag]);
- $interest_increase = Utils::str_to_float($settings_by_flag['interest_increase'][$flag]);
- $max_installments = intval($settings_by_flag['max_installment'][$flag]);
- }
-
- if ($installments <= $no_interest) {
- return $amount;
- }
-
- if ($interest) {
-
- if ($interest_increase && $installments > $no_interest + 1) {
- $interest += ($interest_increase * ($installments - ($no_interest + 1)));
- }
-
- $amount += Utils::calc_percentage($interest, $price);
- }
-
- return $amount;
- }
-
- private function get_multicustomer_data($type, $form_fields)
- {
- $prefix = "multicustomer_{$type}";
- $is_enabled = Utils::get_value_by($form_fields, "enable_multicustomers_{$type}");
-
- if (!$is_enabled) {
- return false;
- }
-
- $cpf = Utils::get_value_by($form_fields, $prefix . '[cpf]');
- $zip_code = Utils::get_value_by($form_fields, $prefix . '[zip_code]');
-
- return array(
- 'name' => Utils::get_value_by($form_fields, $prefix . '[name]'),
- 'email' => Utils::get_value_by($form_fields, $prefix . '[email]'),
- 'document' => Utils::format_document($cpf),
- 'type' => 'individual',
- 'address' => array(
- 'street' => Utils::get_value_by($form_fields, $prefix . '[street]'),
- 'number' => Utils::get_value_by($form_fields, $prefix . '[number]'),
- 'complement' => Utils::get_value_by($form_fields, $prefix . '[complement]'),
- 'neighborhood' => Utils::get_value_by($form_fields, $prefix . '[neighborhood]'),
- 'zip_code' => preg_replace('/[^\d]+/', '', $zip_code),
- 'city' => Utils::get_value_by($form_fields, $prefix . '[city]'),
- 'state' => Utils::get_value_by($form_fields, $prefix . '[state]'),
- 'country' => 'BR',
- ),
- );
- }
-}
diff --git a/src/View/Admin/html-checkbox-field.php b/src/View/Admin/html-checkbox-field.php
deleted file mode 100644
index 56bf817c..00000000
--- a/src/View/Admin/html-checkbox-field.php
+++ /dev/null
@@ -1,18 +0,0 @@
-
- />
-
-
-
-
-
-
-
-
-
-
- = __('Important! This store is linked to the Pagar.me test environment. This environment is intended for integration validation and does not generate real financial transactions.', 'woo-pagarme-payments'); ?>
-
-
-
diff --git a/src/View/Admin/html-hub-integration-button.php b/src/View/Admin/html-hub-integration-button.php
deleted file mode 100644
index 590f9473..00000000
--- a/src/View/Admin/html-hub-integration-button.php
+++ /dev/null
@@ -1,80 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/View/Admin/html-select-field.php b/src/View/Admin/html-select-field.php
deleted file mode 100644
index c2eb7d5a..00000000
--- a/src/View/Admin/html-select-field.php
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
- $value ) : ?>
- >
-
-
-
-
-
-
-
-
-
-
-
-' . __('Your transaction has been processed.', 'woo-pagarme-payments') . '',
- array('p' => array('class' => true))
- );
- }
-
- protected static function message_after()
- {
- echo wp_kses(
- '' . __('If you have any questions regarding the transaction, please contact us.', 'woo-pagarme-payments') . '
',
- array('p' => array())
- );
- }
-
- public static function handle_messages(Order $order)
- {
- switch ($order->payment_method) {
- case 'billet':
- return self::billet_message($order);
-
- case 'credit_card':
- return self::credit_card_message($order);
-
- case 'pix':
- return self::pix_message($order);
-
- case 'billet_and_card':
- return self::billet_and_card_message($order);
-
- case '2_cards':
- return self::two_credit_card_message($order);
- case 'voucher':
- return self::credit_card_message($order);
- }
- }
-
- public static function billet_message($order)
- {
- $response_data = $order->response_data;
-
- if (!$response_data) :
- return self::render_failed_message();
- endif;
-
- if (is_string($response_data)) {
- $response_data = json_decode($response_data);
- }
-
- $charges = $response_data->charges;
- $charge = array_shift($charges);
- $transaction = array_shift($charge->transactions);
-
- ob_start();
-
- self::message_before();
-
-?>
-
-
-
-
-
-
-
-
- response_data;
-
- if (is_string($response_data)) {
- $response_data = json_decode($response_data);
- }
-
- $charge = null;
- if (!empty($response_data)) {
- $charges = $response_data->charges;
- $charge = array_shift($charges);
- }
-
- ob_start();
-
- self::message_before();
-
- ?>
-
- ' . strtoupper(
- __(
- $charge ? ucfirst($charge->status) : 'Failed',
- 'woo-pagarme-payments'
- )
- ) . ''
- );
- /** phpcs:enable */
- ?>
-
- response_data;
-
- if (is_string($response_data)) {
- $response_data = json_decode($response_data);
- }
-
- $first_charge = null;
- $second_charge = null;
- if (!empty($response_data)) {
- $charges = $response_data->charges;
- $first_charge = array_shift($charges);
- $second_charge = array_shift($charges);
- }
-
- ob_start();
-
- self::message_before();
-
- ?>
-
- ' . strtoupper(
- __(
- $first_charge ? ucfirst($first_charge->status) : 'Failed',
- 'woo-pagarme-payments'
- )
- ) . '',
- '' . strtoupper(
- __(
- $second_charge ? ucfirst($second_charge->status) : 'Failed',
- 'woo-pagarme-payments'
- )
- ) . ' '
- );
- /** phpcs:enable */
- ?>
-
- response_data;
-
- if (!$response_data) :
- return self::render_failed_message();
- endif;
-
- if (is_string($response_data)) {
- $response_data = json_decode($response_data);
- }
-
- $charges = $response_data->charges;
- $charge = array_shift($charges);
- $transaction = array_shift($charge->transactions);
- $qrCodeUrl = $transaction->postData->qr_code_url;
- $rawQrCode = $transaction->postData->qr_code;
- ob_start();
-
- self::message_before();
-
- ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ',
- esc_url(Core::plugins_url('assets/images/pix-checkout-attention.svg')),
- esc_html__('pix attention icon', 'woo-pagarme-payments')
- );
- ?>
-
-
-
-
-
-
-
-
- response_data);
-
- if (!$response) :
- return self::render_failed_message();
- endif;
-
- $charges = $response->charges;
-
- ob_start();
-
- self::message_before();
-
- foreach ($charges as $charge) :
-
- $transaction = array_shift($charge->transactions);
- $transactionType = $transaction->type;
- if ($transactionType == 'credit_card') :
- echo wp_kses('', array('p' => array()));
- /** phpcs:disable */
- printf(
- __('CREDIT CARD: The status of your transaction is %s.', 'woo-pagarme-payments'),
- '' . strtoupper(
- __(
- ucfirst($charge->status),
- 'woo-pagarme-payments'
- )
- ) . ' '
- );
- /** phpcs:enable */
- echo wp_kses('
', array('p' => array()));;
- endif;
-
- if ($transactionType == 'boleto') :
- ?>
-
-
-
-
-
-
-
-
-
- ' . strtoupper(
- __(
- 'Failed',
- 'woo-pagarme-payments'
- )
- ) . ''
- );
- ?>
-
-
- get_charges();
-
- if (!$charges) {
- $charges = isset($order->response_data->charges) ? $order->response_data->charges : false;
- }
-
- if (empty($charges)) {
- return;
- }
-
- $model_charge = new Charge();
-
- ?>
-
- getInstallmentsByType($total);
- }
-
- private static function get_payment_detail($charge, Charge $model_charge)
- {
- $html = '';
- if (property_exists($charge, 'payment_method') && $charge->payment_method === 'boleto') {
-
- $due_at = new \DateTime($charge->last_transaction->due_at);
-
- ob_start()
-
- ?>
-
- :
-
-
-
- Link:
-
-
- last_transaction->pdf); ?>
-
-
-
-
- :
- last_transaction->line); ?>
-
-
- :
- format('d/m/Y')); ?>
-
-
- :
- amount)); ?>
-
-
- :
- get_i18n_status($charge->status)); ?>
-
-
-
-
- payment_method === 'credit_card') {
-
- ob_start()
-
- ?>
-
- :
-
-
-
- :
- last_transaction->card->holder_name); ?>
-
-
- :
- last_transaction->card->brand); ?>
-
-
- :
-
- **** **** **** last_transaction->card->last_four_digits); ?>
-
-
-
- :
- last_transaction->installments); ?>
-
-
- :
- amount)); ?>
-
-
- :
- get_i18n_status($charge->status)); ?>
-
-
-
-
-ID);
- $charges = $model->get_charges(true);
- $charge_model = new Charge();
-
- if (empty($charges)) {
- echo wp_kses('Nenhum registro encontrado.
', array('p' => array()));
- return;
- }
-
-?>
-
-
-
-
-
- Charge ID
- Tipo
- Valor Total
- Parcialmente Capturado
- Parcialmente Cancelado
- Parcialmente Estornado
- Status
- Ação
-
-
-
-
- >
- getTransactions();
- $transaction = array_shift($transactions);
- $chargeId = $charge->getPagarmeId()->getValue();
- $chargeStatus = $charge->getStatus()->getStatus();
-
- $paid_amount = !empty($charge->getPaidAmount()) ? Utils::format_order_price_to_view($charge->getPaidAmount()) : ' - ';
- $canceled_amount = !empty($charge->getCanceledAmount()) ? Utils::format_order_price_to_view($charge->getCanceledAmount()) : ' - ';
- $refunded_amount = !empty($charge->getRefundedAmount()) ? Utils::format_order_price_to_view($charge->getRefundedAmount()) : ' - ';
-
- ?>
-
- getTransactionType()->getType())); ?>
- getAmount()), ['span' => array('class' => true)]); ?>
- array('class' => true)]);
- ?>
- array('class' => true)]);
- ?>
- array('class' => true)]);
- ?>
-
-
- is_allowed_cancel($charge) ? 'disabled=disabled' : ''); ?> class="button-primary">Cancelar
-
- getTransactionType()->getType() == 'credit_card') : ?>
- is_allowed_capture($charge) ? 'disabled=disabled' : ''); ?> class="button-primary">Capturar
-
-
-
-
-
-
-
-
-
- getPaidAmount()) ? Utils::format_order_price_to_view($charge->getPaidAmount()) : ' - ';
- $chargeId = $charge->getPagarmeId()->getValue();
- $chargeStatus = $charge->getStatus()->getStatus();
-
- ?>
-
-
Pagar.me - Captura
-
CHARGE ID:
-
TIPO: getTransactionType()->getType())); ?>
-
VALOR TOTAL: getAmount()); ?>
-
PARCIALMENTE CAPTURADO: array('class' => true)]); ?>
-
STATUS:
-
- Valor a ser capturado: R$
-
-
-
-
- Confirmar
- Cancelar
-
-
- getCanceledAmount()) ? $charge->getCanceledAmount() : 0;
- $refunded_amount = !empty($charge->getRefundedAmount()) ? $charge->getRefundedAmount() : 0;
- $paid_amount = !empty($charge->getPaidAmount()) ? $charge->getPaidAmount() : 0;
-
- $value_to_cancel = $charge->getAmount();
- $chargeId = $charge->getPagarmeId()->getValue();
- $chargeStatus = $charge->getStatus()->getStatus();
-
- if ($paid_amount) {
- $value_to_cancel = $paid_amount;
- }
-
- if ($paid_amount && $canceled_amount) {
- $value_to_cancel = $paid_amount - $canceled_amount;
- }
-
- if ($paid_amount && $refunded_amount) {
- $value_to_cancel = max(0, $paid_amount - $refunded_amount);
- }
-
- $canceled_amount = !empty($canceled_amount) ? Utils::format_order_price_to_view($canceled_amount) : '-';
- ?>
-
-
Pagar.me - Cancelamento
-
CHARGE ID:
-
TIPO: getTransactionType()->getType())); ?>
-
VALOR TOTAL: getAmount()); ?>
-
PARCIALMENTE CANCELADO: array('class' => true)]); ?>
-
STATUS:
-
- Valor a ser cancelado: R$
- />
-
-
-
- Confirmar
- Cancelar
-
-
-
Date: Thu, 13 Apr 2023 17:13:25 -0300
Subject: [PATCH 105/156] delete deprecated files
---
.circleci/config.yml | 142 ---------------------------------------
.github/workflows/pr.yml | 4 +-
2 files changed, 3 insertions(+), 143 deletions(-)
delete mode 100644 .circleci/config.yml
diff --git a/.circleci/config.yml b/.circleci/config.yml
deleted file mode 100644
index bc7acda4..00000000
--- a/.circleci/config.yml
+++ /dev/null
@@ -1,142 +0,0 @@
-version: 2.1
-
-parameters:
- machine_image:
- type: string
- default: ubuntu-2004:202010-01
- working_dir:
- type: string
- default: '~/woocommerce'
-
-jobs:
- build:
- working_directory: /app
- docker:
- - image: php:7.2-apache
- environment:
- APP_ENV: test
- steps:
- - checkout
- - run:
- name: Install system packages
- command: apt-get update && apt-get -y install zip git zlib1g-dev wget
- - run:
- name: Install PHP extensions
- command: |
- docker-php-ext-install pdo
- docker-php-ext-install zip
- - run:
- name: Install Composer
- command: |
- php -r "copy('http://getcomposer.org/installer', 'composer-setup.php');"
- php composer-setup.php --version=1.10.13
- - run:
- name: Display PHP information
- command: |
- php -v
- php composer.phar --version
- - run:
- name: Check PHP sintax
- command: find . -name \*.php -exec php -l "{}" \;
- - run:
- name: Install project dependencies
- command: |
- cd /app
- php composer.phar install
- - store_artifacts:
- path: /app
- destination: app-artifact
- - persist_to_workspace:
- root: /
- paths:
- - app
-
- publish:
- working_directory: /
- docker:
- - image: docker:17.05.0-ce-git
- steps:
- - setup_remote_docker
- - attach_workspace:
- at: /
- - run:
- name: Copy CI files to root
- command: |
- cd /app
- cp .circleci/data/.htaccess .
- cp .circleci/data/Dockerfile .
- cp .circleci/data/update-wp-config.php .
- cp .circleci/data/wait-for-mysql.sh .
- - run:
- name: Build image base for modifications
- command: |
- cd /app && ls
- docker build -t ${DOCKER_ACCOUNT}/${PROJECT_NAME}:latest .
- docker run --name newimage -d -p3306:3306 -p80:80 ${DOCKER_ACCOUNT}/${PROJECT_NAME}:latest
- - run:
- name: Wait for MySQL Service
- command: |
- docker exec -it newimage sh /app/wp-content/plugins/${PLUGIN_NAME}/wait-for-mysql.sh
- docker exec -it newimage rm /app/wp-content/plugins/${PLUGIN_NAME}/wait-for-mysql.sh
- - run:
- name: Activate and setup Plugin
- command: |
- docker exec -it newimage wp plugin activate ${PLUGIN_NAME} --allow-root
- docker exec -it newimage chmod -R 777 /app/wp-content/plugins/${PLUGIN_NAME}
- docker exec -it newimage mysql -u root -D wordpress -e "REPLACE INTO wp_options (option_name,option_value) VALUES ('${PLUGIN_META_NAME}','${PLUGIN_CONFIG}');"
- docker exec -i newimage curl -X GET "http://localhost/wp-content/plugins/${PLUGIN_NAME}/update-wp-config.php?url=${STAGING_URL}"
- docker exec -it newimage rm /app/wp-content/plugins/${PLUGIN_NAME}/update-wp-config.php
- docker exec -it newimage touch test5.txt
- - run:
- name: Clear useless files
- command: |
- docker exec -it newimage sh -c "cd /app/wp-content/plugins/${PLUGIN_NAME}" && \
- rm -rf .github .circleci .plugin-data .git .gitignore .editorconfig && \
- rm -rf Dockerfile update-wp-config.php wait-for-mysql.sh LICENSE *.MD
- - deploy:
- name: Commit and push Docker image
- command: |
- sleep 5 && docker stop newimage
- docker login ${DOCKER_ACCOUNT} -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
- docker commit newimage ${DOCKER_ACCOUNT}/${PROJECT_NAME}:latest
- docker tag ${DOCKER_ACCOUNT}/${PROJECT_NAME} "${DOCKER_ACCOUNT}/${PROJECT_NAME}:latest"
- docker tag ${DOCKER_ACCOUNT}/${PROJECT_NAME} "${DOCKER_ACCOUNT}/${PROJECT_NAME}:${CIRCLE_BRANCH}"
- docker tag ${DOCKER_ACCOUNT}/${PROJECT_NAME} "${DOCKER_ACCOUNT}/${PROJECT_NAME}:${CIRCLE_SHA1:0:8}"
- docker push "${DOCKER_ACCOUNT}/${PROJECT_NAME}"
-
- deploy_staging:
- machine: true
- steps:
- - run:
- name: Send deployment webhook to Rancher
- command: |
- BODY='{"push_data":{"tag":"'"${CIRCLE_BRANCH}"'"},"repository":{"repo_name":"'"${DOCKER_ACCOUNT}/${PROJECT_NAME}"'"}}'
- curl -X POST ${RANCHER_STG_DEPLOY_URL} -H 'Content-Type: application/json' -d "${BODY}"
-
-workflows:
- version: 2
- build_publish_deploy:
- jobs:
- - build
- - publish:
- context: acceptance
- requires:
- - build
- filters:
- branches:
- only:
- - test
- - stg
- - develop
- - master
- - deploy_staging:
- context: acceptance
- requires:
- - publish
- filters:
- branches:
- only:
- - test
- - stg
- - develop
- - master
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index de869482..9e4f16b0 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -42,7 +42,7 @@ jobs:
run: find . -name \*.php -exec php -l "{}" \;
-
name: Install project dependences
- run:
+ run:
php composer.phar install
sonar:
@@ -51,6 +51,8 @@ jobs:
steps:
- name: Checkout project
uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
- name: Run Sonar
uses: sonarsource/sonarcloud-github-action@master
From b704a2a0a56b265722c77fd0e776f80586a0590c Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 13 Apr 2023 22:27:33 -0300
Subject: [PATCH 106/156] delete deprecated files
---
.../front/checkout/model/payment/card.js | 616 ++++++++++--------
src/Core.php | 47 +-
src/Model/Payment.php | 450 +------------
src/Model/Payment/CreditCard.php | 78 ++-
templates/checkout/2-cards-item.php | 170 -----
templates/checkout/billet-and-card-item.php | 129 ----
templates/checkout/billet-item.php | 38 --
templates/checkout/choose-credit-card.php | 53 --
templates/checkout/common-card-item.php | 57 --
templates/checkout/common-voucher-item.php | 64 --
templates/checkout/credit-card-item.php | 78 ---
templates/checkout/environment.phtml | 20 -
.../checkout/field-enable-multicustomers.php | 29 -
templates/checkout/field-save-card.php | 40 --
templates/checkout/main.php | 79 ---
templates/checkout/multicustomers-form.php | 92 ---
templates/checkout/pix-item.php | 38 --
templates/checkout/voucher-item.php | 42 --
18 files changed, 469 insertions(+), 1651 deletions(-)
delete mode 100644 templates/checkout/2-cards-item.php
delete mode 100644 templates/checkout/billet-and-card-item.php
delete mode 100644 templates/checkout/billet-item.php
delete mode 100644 templates/checkout/choose-credit-card.php
delete mode 100644 templates/checkout/common-card-item.php
delete mode 100644 templates/checkout/common-voucher-item.php
delete mode 100644 templates/checkout/credit-card-item.php
delete mode 100644 templates/checkout/environment.phtml
delete mode 100644 templates/checkout/field-enable-multicustomers.php
delete mode 100644 templates/checkout/field-save-card.php
delete mode 100644 templates/checkout/main.php
delete mode 100644 templates/checkout/multicustomers-form.php
delete mode 100644 templates/checkout/pix-item.php
delete mode 100644 templates/checkout/voucher-item.php
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index c93c2e81..dc6f9bf7 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -1,335 +1,379 @@
/* globals wc_pagarme_checkout */
+$ = jQuery;
-(function ($) {
- const cardEl = $('[data-element="fields-cc-data"]');
- const cardNumberTarget = 'input[data-element="pagarme-card-number"]';
- const brandTarget = '[data-pagarmecheckout-element="brand-input"]';
- const brandImgTarget = 'span[name="brand-image"]';
- const valueTarget = '[data-pagarmecheckout-element="order-value"]';
- const installmentsTarget = '[data-pagarme-component="installments"]';
- const mundiCdn = 'https://cdn.mundipagg.com/assets/images/logos/brands/png/';
- const limit = 10;
- const tokenElement = '[data-pagarmecheckout-element="token"]';
- let canSubmit = false;
- let cardsMethods = [];
- let brands = [];
+const cardNumberTarget = 'input[data-element="pagarme-card-number"]';
+const brandTarget = '[data-pagarmecheckout-element="brand-input"]';
+const brandImgTarget = 'span[name="brand-image"]';
+const valueTarget = '[data-pagarmecheckout-element="order-value"]';
+const installmentsTarget = '[data-pagarme-component="installments"]';
+const mundiCdn = 'https://cdn.mundipagg.com/assets/images/logos/brands/png/';
+const tokenElement = '[data-pagarmecheckout-element="token"]';
+let cardsMethods = [];
+let brands = [];
- let pagarme = {
- getCheckoutPaymentElement: function () {
- let value = $('form.checkout input[name="payment_method"]:checked').val();
- return $('.wc_payment_method.payment_method_' + value);
- },
- isPagarmePayment: function () {
- return $('form.checkout input[name="payment_method"]:checked').val().indexOf('pagarme');
- },
- keyEventHandlerCard: function (e) {
- loadBrand(e);
- },
- formHandler: function () {
- if (pagarme.isPagarmePayment()) {
- let e = pagarme.getCheckoutPaymentElement();
- let cardsForm = e.find('fieldset[data-pagarmecheckout="card"]');
- return checkTokenCard(cardsForm);
- }
- return true;
- },
- hasSelectedWallet: function (el) {
- let elWallet = $(el).find('select[data-element="choose-credit-card"]');
- if (elWallet.length) {
- return elWallet.val().trim() !== '';
- }
- return false;
- },
- };
-
- function checkTokenCard(e)
- {
- let allResult = [];
- e.each(async function () {
- if (pagarme.hasSelectedWallet(this)) {
- allResult.push(true);
- return;
- }
- allResult.push(checkToken(this));
- });
- return !allResult.includes(false);
+let pagarmeCard = {
+ limitTokenize: 10,
+ canSubmit: false,
+ started: false,
+ isStarted: function (){
+ if (!this.started){
+ this.started = true;
+ return false;
}
-
- async function wait(ms = 1000) {
- return new Promise(resolve => {
- setTimeout(resolve, ms);
- });
+ return true;
+ },
+ haveCardForm: function (e) {
+ let elem = null;
+ if (e instanceof $) {
+ elem = e;
+ }
+ if (e instanceof $.Event) {
+ elem = $(e.currentTarget);
}
+ if (!elem) {
+ throw "Cant check card form: Invalid element received";
+ }
+ if (elem.is("fieldset") && elem.attr("data-pagarmecheckout") === 'card') {
+ return true;
+ }
+ if (elem.has('fieldset[data-pagarmecheckout="card"]').length) {
+ return true;
+ }
+ return false;
+ },
+ getCheckoutPaymentElement: function () {
+ let value = $('form.checkout input[name="payment_method"]:checked').val();
+ return $('.wc_payment_method.payment_method_' + value);
+ },
+ isPagarmePayment: function () {
+ return $('form.checkout input[name="payment_method"]:checked').val().indexOf('pagarme');
+ },
+ keyEventHandlerCard: function (e) {
+ this.loadBrand(e);
+ },
+ formHandler: function () {
+ if (this.isPagarmePayment()) {
+ let e = this.getCheckoutPaymentElement();
+ let cardsForm = e.find('fieldset[data-pagarmecheckout="card"]');
+ return this.checkTokenCard(cardsForm);
+ }
+ return true;
+ },
+ hasSelectedWallet: function (el) {
+ let elWallet = $(el).find('select[data-element="choose-credit-card"]');
+ if (elWallet.length) {
+ return elWallet.val().trim() !== '';
+ }
+ return false;
+ },
- function checkToken(e, step = 0) {
- if (!(e instanceof jQuery)) {
- e = $(e);
- }
- if (e.find(tokenElement).length) {
- return true;
+ checkTokenCard: function (e) {
+ let allResult = [];
+ e.each(async function () {
+ if (pagarmeCard.hasSelectedWallet(this)) {
+ allResult.push(true);
+ return;
}
- return false;
+ allResult.push(pagarmeCard.checkToken(this));
+ });
+ return !allResult.includes(false);
+ },
+
+ wait: async function (ms = 1000) {
+ return new Promise(resolve => {
+ setTimeout(resolve, ms);
+ });
+ },
+
+ getBrandTarget: function () {
+ return brandTarget;
+ },
+
+ checkToken: function (e, step = 0) {
+ if (!(e instanceof jQuery)) {
+ e = $(e);
}
+ return !!e.find(tokenElement).length;
+ },
- async function getCardDataContingency(cardNumber) {
- let oldPrefix = '',
- types = await getBrands(true),
- bin = cardNumber.substr(0, 6),
- currentBrand,
- data;
- for (var i = 0; i < types.length; i += 1) {
- var current_type = types[i];
- for (var j = 0; j < current_type.prefixes.length; j += 1) {
- var prefix = current_type.prefixes[j].toString();
- if (bin.indexOf(prefix) === 0 && oldPrefix.length < prefix.length) {
- oldPrefix = prefix;
- currentBrand = current_type.brand;
- data = current_type;
- }
+ getCardDataContingency: async function (cardNumber) {
+ let oldPrefix = '',
+ types = await this.getBrands(true),
+ bin = cardNumber.substring(0, 6),
+ currentBrand,
+ data;
+ for (let i = 0; i < types.length; i += 1) {
+ let current_type = types[i];
+ for (let j = 0; j < current_type.prefixes.length; j += 1) {
+ let prefix = current_type.prefixes[j].toString();
+ if (bin.indexOf(prefix) === 0 && oldPrefix.length < prefix.length) {
+ oldPrefix = prefix;
+ currentBrand = current_type.brand;
+ data = current_type;
}
}
- return data;
}
+ return data;
+ },
- function getBrands(onlyBrands = false) {
- return new Promise((resolve) => {
- if (onlyBrands) {
- let types = [];
- cardsMethods.forEach(function (key) {
- $.each(wc_pagarme_checkout.config.payment[key].brands, function (method) {
- types.push(this);
- });
- });
- resolve(types);
- }
+ getBrands: function (onlyBrands = false) {
+ return new Promise((resolve) => {
+ if (onlyBrands) {
+ let types = [];
cardsMethods.forEach(function (key) {
- brands[key] = wc_pagarme_checkout.config.payment[key].brands;
+ $.each(wc_pagarme_checkout.config.payment[key].brands, function () {
+ types.push(this);
+ });
});
+ resolve(types);
+ }
+ cardsMethods.forEach(function (key) {
+ brands[key] = wc_pagarme_checkout.config.payment[key].brands;
});
- }
+ });
+ },
- function getCardsMethods() {
- $.each(wc_pagarme_checkout.config.payment, function (method) {
- if (wc_pagarme_checkout.config.payment[method].is_card) {
- cardsMethods.push(method);
- }
- });
- }
+ getCardsMethods: function () {
+ $.each(wc_pagarme_checkout.config.payment, function (method) {
+ if (wc_pagarme_checkout.config.payment[method].is_card) {
+ cardsMethods.push(method);
+ }
+ });
+ },
- async function loadBrand(e) {
- let elem = e.currentTarget;
- let cardNumber = elem.value.replace(/\s/g, '');
- let card = await getCardData(cardNumber);
- changeBrand(e, card);
- updateInstallmentsElement(e);
+ loadBrand: async function (e) {
+ let elem = e.currentTarget;
+ if (!elem.checkVisibility()) {
+ return;
+ }
+ let cardNumber = elem.value.replace(/\s/g, '');
+ if (cardNumber.length < 6) {
+ return;
}
+ let card = await this.getCardData(cardNumber);
+ this.changeBrand(e, card);
+ this.updateInstallmentsElement(e);
+ },
- async function getCardData(cardNumber) {
- let result = [];
- if (cardNumber.length < 6) {
- throw "Invalid card number";
- }
- let value = await getCardDataByApi(cardNumber);
- if (value === 'error' || typeof value == 'undefined') {
- value = await getCardDataContingency(cardNumber);
- }
- let codeWithArray = {
- name: 'CVV',
- size: value.cvv
- };
- value = {
- title: value.brandName,
- type: value.brandName,
- gaps: value.gaps,
- lengths: value.lenghts,
- image: value.brandImage,
- mask: value.mask,
- size: value.size,
- brand: value.brand,
- possibleBrands: value.possibleBrands,
- code: codeWithArray
- };
- result.push($.extend(true, {}, value));
- return result;
+ getCardData: async function (cardNumber) {
+ let result = [];
+ let value = await this.getCardDataByApi(cardNumber);
+ if (value === 'error' || typeof value == 'undefined') {
+ value = await this.getCardDataContingency(cardNumber);
}
+ let codeWithArray = {
+ name: 'CVV',
+ size: value.cvv
+ };
+ value = {
+ title: value.brandName,
+ type: value.brandName,
+ gaps: value.gaps,
+ lengths: value.lenghts,
+ image: value.brandImage,
+ mask: value.mask,
+ size: value.size,
+ brand: value.brand,
+ possibleBrands: value.possibleBrands,
+ code: codeWithArray
+ };
+ result.push($.extend(true, {}, value));
+ return result;
+ },
- function getCardDataByApi(cardNumber) {
- return new Promise((resolve) => {
- $.ajax({
- type: "GET",
- dataType: "json",
- url: 'https://api.mundipagg.com/bin/v1/' + cardNumber,
- async: false,
- cache: true,
- success: function (data) {
- resolve(data);
- },
- error: function (xhr, textStatus, errorThrown) {
- resolve(textStatus);
- }
- });
+ getCardDataByApi: function (cardNumber) {
+ return new Promise((resolve) => {
+ $.ajax({
+ type: "GET",
+ dataType: "json",
+ url: 'https://api.mundipagg.com/bin/v1/' + cardNumber,
+ async: false,
+ cache: true,
+ success: function (data) {
+ resolve(data);
+ },
+ error: function (xhr, textStatus, errorThrown) {
+ resolve(textStatus);
+ }
});
- }
+ });
+ },
- function changeBrand(e, card) {
- if (typeof e == 'undefined' || typeof card == 'undefined') {
- throw "Invalid data to change card brand";
- }
- let elem = e.currentTarget;
- let imageSrc = getImageSrc(card);
- let imgElem = $(elem).parent().find(brandImgTarget).find('img');
- $(elem).parent().find(brandTarget).attr('value', card[0].brand);
- if (imgElem.length) {
- imgElem.attr('src', imageSrc);
- } else {
- let img = $(document.createElement('img'));
- $(elem).parent().find(brandImgTarget).append(
- img.attr(
- 'src', imageSrc
- )
- );
- }
+ changeBrand: function (e, card) {
+ if (typeof e == 'undefined' || typeof card == 'undefined') {
+ throw "Invalid data to change card brand";
+ }
+ let elem = e.currentTarget;
+ let imageSrc = this.getImageSrc(card);
+ let imgElem = $(elem).parent().find(brandImgTarget).find('img');
+ $(elem).parent().find(brandTarget).attr('value', card[0].brand);
+ if (imgElem.length) {
+ imgElem.attr('src', imageSrc);
+ } else {
+ let img = $(document.createElement('img'));
+ $(elem).parent().find(brandImgTarget).append(
+ img.attr(
+ 'src', imageSrc
+ )
+ );
}
+ },
- function getImageSrc(card) {
- if (card[0].image) {
- return card[0].image;
- }
- return mundiCdn + card[0].brand + '.png';
+ getImageSrc: function (card) {
+ if (card[0].image) {
+ return card[0].image;
}
+ return mundiCdn + card[0].brand + '.png';
+ },
- function addsMask() {
- $('.pagarme-card-form-card-number').mask('0000 0000 0000 0000');
- $('.pagarme-card-form-card-expiry').mask('00 / 00');
- $('.pagarme-card-form-card-cvc').mask('0000');
- $('#billet-value').mask('#.##0,00', {
- reverse: true
+ updateInstallmentsElement: function (e) {
+ let elem = null;
+ if (e instanceof $) {
+ elem = e;
+ }
+ if (e instanceof $.Event) {
+ elem = $(e.currentTarget);
+ }
+ if (!elem) {
+ return false;
+ }
+ let brand = elem.closest('fieldset').find(brandTarget).val();
+ let total = elem.closest('fieldset').find(valueTarget).val();
+ if (!total)
+ total = cartTotal;
+ if (!brand || !total)
+ return false;
+ let storageName = btoa(brand + total);
+ sessionStorage.removeItem(storageName);
+ let storage = sessionStorage.getItem(storageName);
+ let cardForm = elem.closest("fieldset");
+ let select = cardForm.find(installmentsTarget);
+ if (storage) {
+ select.html(storage);
+ } else {
+ let ajax = $.ajax({
+ 'url': ajaxUrl,
+ 'data': {
+ 'action': 'xqRhBHJ5sW',
+ 'flag': brand,
+ 'total': total
+ }
+ });
+ ajax.done(function (response) {
+ pagarmeCard._done(select, storageName, cardForm, response);
});
- $('input[name*=\\[cpf\\]]').mask('000.000.000-00');
- $('input[name*=\\[zip_code\\]]').mask('00000-000');
+ ajax.fail(function () {
+ pagarmeCard._fail(cardForm);
+ });
+ pagarmeCard.showLoader(cardForm);
}
+ },
- function updateInstallmentsElement(e) {
- let elem = e.currentTarget;
- let brand = $(elem).parent().find(brandTarget).val();
- let total = $(elem).closest('fieldset').find(valueTarget).val();
- if (!total)
- total = cartTotal;
- if (!brand || !total)
- throw "Cant update installments: invalid total and/or brand";
- let storageName = btoa(brand + total);
- sessionStorage.removeItem(storageName);
- let storage = sessionStorage.getItem(storageName);
- let cardForm = $(elem).closest("fieldset");
- let select = cardForm.find(installmentsTarget);
- if (storage) {
- select.html(storage);
- } else {
- let ajax = $.ajax({
- 'url': ajaxUrl,
- 'data': {
- 'action': 'xqRhBHJ5sW',
- 'flag': brand,
- 'total': total
- }
- });
- ajax.done($.proxy(_done, this, select, storageName, cardForm));
- ajax.fail(function () {
- removeLoader(cardForm);
- });
- showLoader(cardForm);
- }
- }
+ _done: function (select, storageName, e, response) {
+ select.html(response);
+ sessionStorage.setItem(storageName, response);
+ this.removeLoader(e);
+ },
- const _done = function (select, storageName, e, response) {
- select.html(response);
- sessionStorage.setItem(storageName, response);
- removeLoader(e);
- };
+ _fail: function (e) {
+ this.removeLoader(e);
+ },
- const _fail = function (e) {
- removeLoader(e);
- };
+ removeLoader: function (e) {
+ if (!(e instanceof jQuery)) {
+ e = $(e);
+ }
+ e.unblock();
+ },
- const removeLoader = function (e) {
- if (!(e instanceof jQuery)) {
- e = $(e);
+ showLoader: function (e) {
+ if (!(e instanceof jQuery)) {
+ e = $(e);
+ }
+ e.block({
+ message: null,
+ overlayCSS: {
+ background: '#fff',
+ opacity: 0.6
}
- e.unblock();
- };
+ });
+ },
- const showLoader = function (e) {
- if (!(e instanceof jQuery)) {
- e = $(e);
- }
- e.block({
- message: null,
- overlayCSS: {
- background: '#fff',
- opacity: 0.6
- }
- });
+ showError: function (text) {
+ const message = {
+ type: 'error',
+ html: text,
+ allowOutsideClick: false
};
-
- function showError(text)
- {
- const message = {
- type: 'error',
- html: text,
- allowOutsideClick: false
- };
- try {
- swal(message);
- } catch (e) {
- new swal(message);
- }
+ try {
+ swal(message);
+ } catch (e) {
+ new swal(message);
}
-
- async function execute() {
- let result = pagarme.formHandler(),
- i = 1;
- try {
- while(!result && i <= limit) {
- if (i === limit) {
- removeLoader(pagarme.getCheckoutPaymentElement());
- throw "Tokenize timeout";
- }
- await wait();
- result = pagarme.formHandler();
- i++;
+ },
+ execute: async function () {
+ let result = pagarmeCard.formHandler(),
+ i = 1;
+ try {
+ while (!result && i <= this.limitTokenize) {
+ if (i === this.limit) {
+ this.removeLoader(this.getCheckoutPaymentElement());
+ throw "Tokenize timeout";
}
- canSubmit = true;
- $("form.checkout, form#order_review").submit();
- } catch (er) {
- if (typeof er === 'string') {
- showError(er);
- } else {
- showError(er.message);
+ if (wc_pagarme_checkout.errorTokenize === true) {
+ this.removeLoader(this.getCheckoutPaymentElement());
+ return;
}
+ await pagarmeCard.wait();
+ result = pagarmeCard.formHandler();
+ i++;
}
- }
+ this.canSubmit = true;
+ $("form.checkout, form#order_review").submit();
+ } catch (er) {
+ if (typeof er === 'string') {
+ this.showError(er);
+ } else {
+ this.showError(er.message);
+ }
+ }
+ },
+ canExecute: function(e) {
+ e.preventDefault();
+ if (!wc_pagarme_checkout.validate() || wc_pagarme_checkout.errorTokenize === true) {
+ return false;
+ }
+ if (pagarmeCard.isPagarmePayment() && !pagarmeCard.canSubmit) {
+ // pagarmeCard.showLoader(pagarmeCard.getCheckoutPaymentElement());
+ pagarmeCard.execute();
+ return false;
+ }
+ return true;
+ },
+ addEventListener: function () {
$(cardNumberTarget).on('blur', function (e) {
- pagarme.keyEventHandlerCard(e);
+ pagarmeCard.keyEventHandlerCard(e);
});
-
- $( document ).ready(function() {
- getCardsMethods();
- getBrands();
- addsMask();
- });
-
$("form.checkout").on(
"checkout_place_order",
function (e) {
- e.preventDefault();
- if (pagarme.isPagarmePayment() && !canSubmit) {
- showLoader(pagarme.getCheckoutPaymentElement());
- execute();
- return false;
- }
- return true;
+ return pagarmeCard.canExecute(e);
}
);
- } (jQuery)
-);
+ $('#billing_cpf').change(function () {
+ $('input[name="pagarme[voucher][cards][1][document-holder]"]').empty();
+ $('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).trigger('input');
+ });
+ $('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).trigger('input');
+
+ },
+ start: function () {
+ // if (this.isStarted()) {
+ // return;
+ // }
+ this.getCardsMethods();
+ this.getBrands();
+ this.addEventListener();
+ },
+};
diff --git a/src/Core.php b/src/Core.php
index 6db0c307..92ed4d5f 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -117,20 +117,6 @@ public static function scripts_front()
public static function enqueue_scripts($type, $deps = array(), $localize_args = array())
{
- wp_enqueue_script(
- 'sweetalert2',
- self::plugins_url("assets/javascripts/vendor/sweetalert2.js"),
- array_merge(array('jquery'), $deps),
- self::filemtime("assets/javascripts/vendor/sweetalert2.js"),
- false
- );
- wp_enqueue_script(
- 'izimodal',
- self::plugins_url("assets/javascripts/admin/vendor/izimodal.js"),
- array_merge(['jquery'], $deps),
- self::filemtime("assets/javascripts/admin/vendor/izimodal.js"),
- false
- );
wp_enqueue_script(
'jquery.mask',
self::plugins_url("assets/javascripts/vendor/jquery.mask.js"),
@@ -138,6 +124,39 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
'1.14.16',
false
);
+ wp_enqueue_script(
+ 'sweetalert2',
+ self::plugins_url("assets/javascripts/vendor/sweetalert2.js"),
+ array_merge(array('jquery'), $deps),
+ self::filemtime("assets/javascripts/vendor/sweetalert2.js"),
+ false
+ );
+ if ($type == 'admin') {
+ wp_enqueue_script(
+ 'izimodal',
+ self::plugins_url("assets/javascripts/admin/vendor/izimodal.js"),
+ array_merge(['jquery'], $deps),
+ self::filemtime("assets/javascripts/admin/vendor/izimodal.js"),
+ false
+ );
+ }
+ if ($type == 'front') {
+ $id = "{$type}-script-" . self::SLUG;
+ wp_enqueue_script(
+ 'pagarme-checkout-card',
+ self::plugins_url("assets/javascripts/front/checkout/model/payment.js"),
+ array_merge(array('jquery'), $deps),
+ self::filemtime("assets/javascripts/front/checkout/model/payment.js"),
+ true
+ );
+ $x = self::get_localize_script_args();
+ wp_localize_script(
+ 'pagarme-checkout-card',
+ 'PagarmeGlobalVars',
+ $x
+ );
+ }
+
}
public static function enqueue_styles($type)
diff --git a/src/Model/Payment.php b/src/Model/Payment.php
index 5673e28a..a40319c9 100644
--- a/src/Model/Payment.php
+++ b/src/Model/Payment.php
@@ -1,439 +1,57 @@
payment_method = $payment_method;
- $this->settings = Setting::get_instance();
- }
-
- /**
- * Return the payment array for API request
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function get_payment_data($wc_order, $form_fields, $customer)
- {
- $method_name = $this->get_method_name();
-
- if (!method_exists($this, $method_name)) {
- throw new \Exception('Payment method name not exists');
- }
-
- $data = $this->{$method_name}($wc_order, $form_fields, $customer);
-
- if ($method_name == 'pay_billet_and_card' || $method_name == 'pay_2_cards') {
- return $data;
- }
-
- return array($data);
- }
-
- /**
- * Return method name according to the selected payment method
- *
- * @return string
- */
- public function get_method_name()
- {
- return "pay_{$this->payment_method}";
- }
-
- /**
- * Return payment data for "boleto"
- *
- * @return array
- */
- public function pay_billet($wc_order, $form_fields)
- {
- $billet = $this->pay_billet_base();
- $billet['amount'] = Utils::format_order_price($wc_order->get_total());
- $multicustomer = $this->get_multicustomer_data('billet', $form_fields);
-
- if ($multicustomer) {
- $billet['customer'] = $multicustomer;
- }
-
- return $billet;
- }
-
- /**
- * Return payment data for "pix"
- *
- * @return array
- */
- public function pay_pix($wc_order, $form_fields)
- {
- $pix = $this->pay_pix_base();
- $pix['amount'] = Utils::format_order_price($wc_order->get_total());
- $multicustomer = $this->get_multicustomer_data('pix', $form_fields);
-
- if ($multicustomer) {
- $pix['customer'] = $multicustomer;
- }
-
- return $pix;
- }
-
- /**
- * Return payment data for "voucher"
- *
- * @return array
- */
- public function pay_voucher($wc_order, $form_fields, $customer)
- {
- $card = $this->pay_voucher_base($wc_order, $form_fields, $customer);
- $card_amount = $wc_order->get_total();
- $card['amount'] = Utils::format_order_price($card_amount);
- $multicustomer = $this->get_multicustomer_data('voucher', $form_fields);
-
- if ($multicustomer) {
- $card['customer'] = $multicustomer;
- }
-
- if (!$multicustomer && !empty($customer->email)) {
- $card['customer'] = $customer;
- }
-
- return $card;
- }
-
- /**
- * Return payment data for "voucher" base
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- private function pay_voucher_base($wc_order, $form_fields, $customer)
- {
- $card_data = array(
- 'payment_method' => 'voucher',
- 'voucher' => array(
- 'statement_descriptor' => $this->settings->voucher_soft_descriptor,
- 'card' => array(
- 'billing_address' => $this->get_billing_address_from_customer($customer, $wc_order)
- )
- ),
- );
-
- return $this->handle_credit_card_type($form_fields, $card_data, '');
- }
-
- /**
- * Return payment data for "credit_card"
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function pay_credit_card($wc_order, $form_fields, $customer)
- {
- $card = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
- $card_installments = Utils::get_value_by($form_fields, 'installments');
- $card_brand = Utils::get_value_by($form_fields, 'brand');
- $card_amount = $this->get_price_with_interest($wc_order->get_total(), $card_installments, $card_brand);
- $card['amount'] = Utils::format_order_price($card_amount);
- $multicustomer = $this->get_multicustomer_data('card', $form_fields);
-
- if ($multicustomer) {
- $card['customer'] = $multicustomer;
- }
-
- if (!$multicustomer && !empty($customer->email)) {
- $card['customer'] = $customer;
- }
-
- return $card;
- }
-
- /**
- * Return payment data for "billet_and_card"
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function pay_billet_and_card($wc_order, $form_fields, $customer)
- {
- $billet_amount = Utils::get_value_by($form_fields, 'billet_value');
- $billet = $this->pay_billet_base();
- $billet['amount'] = Utils::format_desnormalized_order_price($billet_amount);
- $billet_multicustomer = $this->get_multicustomer_data('billet', $form_fields);
-
- if ($billet_multicustomer) {
- $billet['customer'] = $billet_multicustomer;
- }
-
- $card = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
-
- if (!is_array($card) && $card->code != 200) {
- return $card;
- }
-
- $card_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value'));
- $card_installments = Utils::get_value_by($form_fields, 'installments');
- $card_brand = Utils::get_value_by($form_fields, 'brand');
-
- $card_amount = $this->get_price_with_interest($card_amount, $card_installments, $card_brand);
- $card['amount'] = Utils::format_order_price($card_amount);
- $multicustomer = $this->get_multicustomer_data('card', $form_fields);
-
- if ($multicustomer) {
- $card['customer'] = $multicustomer;
- }
-
- return array($billet, $card);
- }
-
- /**
- * Return payment data for "2_cards"
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
- */
- public function pay_2_cards($wc_order, $form_fields, $customer)
- {
- $card1_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value'));
- $card2_amount = Utils::normalize_price(Utils::get_value_by($form_fields, 'card_order_value2'));
-
- $card1 = $this->pay_credit_card_base($wc_order, $form_fields, $customer);
- $card2 = $this->pay_credit_card_base($wc_order, $form_fields, $customer, true);
-
- $card1_installments = Utils::get_value_by($form_fields, 'installments');
- $card2_installments = Utils::get_value_by($form_fields, 'installments2');
-
- $card1_brand = Utils::get_value_by($form_fields, 'brand');
- $card2_brand = Utils::get_value_by($form_fields, 'brand2');
-
- $card1_amount = $this->get_price_with_interest($card1_amount, $card1_installments, $card1_brand);
- $card2_amount = $this->get_price_with_interest($card2_amount, $card2_installments, $card2_brand);
-
- $card1['amount'] = Utils::format_order_price($card1_amount);
- $card2['amount'] = Utils::format_order_price($card2_amount);
-
- $multicustomer_card1 = $this->get_multicustomer_data('card1', $form_fields);
- $multicustomer_card2 = $this->get_multicustomer_data('card2', $form_fields);
-
- if ($multicustomer_card1) {
- $card1['customer'] = $multicustomer_card1;
- }
-
- if ($multicustomer_card2) {
- $card2['customer'] = $multicustomer_card2;
- }
-
- return array($card1, $card2);
- }
+ /** @var Gateway */
+ private $gateway;
/**
- * Return payment data for "credit_card" base (without amount)
- *
- * @param $wc_order object order from woocommerce
- * @param $form_fields array Sent form fields
- * @param $customer object response of Woocommerce\Pagarme\Resource\Customer
- *
- * @return array
+ * @var PaymentInterface
*/
- private function pay_credit_card_base($wc_order, $form_fields, $customer, $is_second_card = false)
- {
- $suffix = $is_second_card ? '2' : '';
- $card_data = array(
- 'payment_method' => 'credit_card',
- 'credit_card' => array(
- 'installments' => Utils::get_value_by($form_fields, "installments{$suffix}"),
- 'statement_descriptor' => $this->settings->cc_soft_descriptor,
- 'capture' => $this->settings->is_active_capture(),
- 'card' => array(
- 'billing_address' => $this->get_billing_address_from_customer($customer, $wc_order)
- )
- ),
- );
-
- return $this->handle_credit_card_type($form_fields, $card_data, $suffix);
- }
-
- private function get_billing_address_from_customer($customer, $wc_order)
- {
- $addressArray = isset($customer->address) ? (array) $customer->address : [];
-
- if (empty($addressArray)) {
- $addressArray = $this->get_customer_address_from_wc_order($wc_order);
- }
-
- return array(
- 'street' => $addressArray["street"],
- 'complement' => $addressArray["complement"],
- 'number' => $addressArray["number"],
- 'zip_code' => $addressArray["zip_code"],
- 'neighborhood' => $addressArray["neighborhood"],
- 'city' => $addressArray["city"],
- 'state' => $addressArray["state"],
- 'country' => $addressArray["country"]
- );
- }
-
- private function get_customer_address_from_wc_order($wc_order)
- {
- $order = new Order($wc_order->get_order_number());
-
- return Utils::build_customer_address_from_order($order);
- }
+ protected $paymentInstance;
/**
- * Return payment data for "boleto"
- *
- * @return array
+ * @param string $paymentMethod
+ * @param Gateway|null $gateway
+ * @throws \Exception
*/
- private function pay_billet_base()
- {
- $expiration_date = new \DateTime();
- $days = (int) $this->settings->billet_deadline_days;
-
- if ($days) {
- $expiration_date->modify("+{$days} day");
+ public function __construct(
+ string $paymentMethod,
+ Gateway $gateway = null
+ ) {
+ if (!$gateway) {
+ $gateway = new Gateway;
}
-
- return array(
- 'payment_method' => 'boleto',
- 'boleto' => array(
- 'bank' => $this->settings->billet_bank,
- 'instructions' => $this->settings->billet_instructions,
- 'due_at' => $expiration_date->format('c'),
- ),
- );
+ $this->gateway = $gateway;
+ $this->paymentInstance = $this->gateway->getPaymentInstace($paymentMethod);
}
/**
- * Return payment data for "pix"
- *
- * @return array
- */
- private function pay_pix_base()
- {
- return array(
- 'payment_method' => 'pix'
- );
- }
-
- /**
- * Return which credit card type will be send. (card ou card_token)
- *
- * @param array $form_fields
- * @param array $card_data
- * @param string $suffix Suffix for each attribute
- *
+ * Return the payment array for API request
* @return array
*/
- private function handle_credit_card_type($form_fields, $card_data, $suffix = '')
- {
- $card_id = Utils::get_value_by($form_fields, "card_id{$suffix}", false);
- $pagarmetoken = !$suffix ? 'pagarmetoken1' : "pagarmetoken{$suffix}";
-
- if ($card_id) {
- $card_data['credit_card']['card_id'] = $card_id;
- } else {
- $card_data['credit_card']['card_token'] = Utils::get_value_by($form_fields, $pagarmetoken);
- }
-
- return $card_data;
- }
-
- private function get_price_with_interest($price, $installments, $flag = '')
+ public function get_payment_data(WC_Order $wc_order, array $form_fields, $customer = null)
{
- $type = intval($this->settings->cc_installment_type);
- $amount = $price;
-
- if ($type === Gateway::CC_TYPE_SINGLE) { // Parcelamento único
- $no_interest = intval($this->settings->cc_installments_without_interest);
- $interest = Utils::str_to_float($this->settings->cc_installments_interest);
- $interest_increase = Utils::str_to_float($this->settings->cc_installments_interest_increase);
- $max_installments = intval($this->settings->cc_installments_maximum);
- } else { // Parcelamento por bandeira
- $settings_by_flag = $this->settings->cc_installments_by_flag;
- $no_interest = intval($settings_by_flag['no_interest'][$flag]);
- $interest = Utils::str_to_float($settings_by_flag['interest'][$flag]);
- $interest_increase = Utils::str_to_float($settings_by_flag['interest_increase'][$flag]);
- $max_installments = intval($settings_by_flag['max_installment'][$flag]);
- }
-
- if ($installments <= $no_interest) {
- return $amount;
- }
-
- if ($interest) {
-
- if ($interest_increase && $installments > $no_interest + 1) {
- $interest += ($interest_increase * ($installments - ($no_interest + 1)));
- }
-
- $amount += Utils::calc_percentage($interest, $price);
- }
-
- return $amount;
- }
-
- private function get_multicustomer_data($type, $form_fields)
- {
- $prefix = "multicustomer_{$type}";
- $is_enabled = Utils::get_value_by($form_fields, "enable_multicustomers_{$type}");
-
- if (!$is_enabled) {
- return false;
- }
-
- $cpf = Utils::get_value_by($form_fields, $prefix . '[cpf]');
- $zip_code = Utils::get_value_by($form_fields, $prefix . '[zip_code]');
-
- return array(
- 'name' => Utils::get_value_by($form_fields, $prefix . '[name]'),
- 'email' => Utils::get_value_by($form_fields, $prefix . '[email]'),
- 'document' => Utils::format_document($cpf),
- 'type' => 'individual',
- 'address' => array(
- 'street' => Utils::get_value_by($form_fields, $prefix . '[street]'),
- 'number' => Utils::get_value_by($form_fields, $prefix . '[number]'),
- 'complement' => Utils::get_value_by($form_fields, $prefix . '[complement]'),
- 'neighborhood' => Utils::get_value_by($form_fields, $prefix . '[neighborhood]'),
- 'zip_code' => preg_replace('/[^\d]+/', '', $zip_code),
- 'city' => Utils::get_value_by($form_fields, $prefix . '[city]'),
- 'state' => Utils::get_value_by($form_fields, $prefix . '[state]'),
- 'country' => 'BR',
- ),
- );
+ return $this->paymentInstance->getPayRequest($wc_order, $form_fields, $customer);
}
}
diff --git a/src/Model/Payment/CreditCard.php b/src/Model/Payment/CreditCard.php
index 8da781a7..ced81e7e 100644
--- a/src/Model/Payment/CreditCard.php
+++ b/src/Model/Payment/CreditCard.php
@@ -11,22 +11,88 @@
namespace Woocommerce\Pagarme\Model\Payment;
-use ReflectionClass;
+use WC_Order;
+use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Model\Payment\CreditCard\Brands;
+use Woocommerce\Pagarme\Model\Payment\CreditCard\BrandsInterface;
+use Woocommerce\Pagarme\Resource\Customers;
defined( 'ABSPATH' ) || exit;
/**
- * Class Voucher
+ * Class CreditCard
* @package Woocommerce\Pagarme\Model\Payment
*/
-class Voucher extends AbstractPayment implements PaymentInterface
+class CreditCard extends Card implements PaymentInterface
{
+ /** @var string */
+ const PAYMENT_CODE = 'credit_card';
+
/** @var int */
- protected $suffix = 3;
+ protected $suffix = 1;
/** @var string */
- protected $name = 'CreditCard';
+ protected $name = 'Credit Card';
/** @var string */
- protected $code = 'credit-card';
+ protected $code = self::PAYMENT_CODE;
+
+ /** @var string[] */
+ protected $requirementsData = [
+ 'brand1',
+ 'pagarmetoken1',
+ 'installments_card',
+ 'multicustomer_card',
+ 'payment_method',
+ 'enable_multicustomers_card',
+ 'save_credit_card1',
+ 'card_id'
+ ];
+
+ /** @var array */
+ protected $dictionary = [
+ 'installments_card' => 'installments',
+ 'brand1' => 'brand',
+ 'save_credit_card1' => 'save_credit_card'
+ ];
+
+ /**
+ * @return array
+ */
+ public function getConfigDataProvider()
+ {
+ $jsConfigProvider = parent::getConfigDataProvider();
+ $brands = new Brands;
+ foreach ($brands->getBrands() as $class) {
+ /** @var BrandsInterface $bank */
+ $brand = new $class;
+ $jsConfigProvider['brands'][$brand->getBrandCode()] = $brand->getConfigDataProvider();
+ }
+ return $jsConfigProvider;
+ }
+
+ /**
+ * @param WC_Order $wc_order
+ * @param array $form_fields
+ * @param Customers|null $customer
+ * @return null[]|string[]
+ * @throws \Exception
+ */
+ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer = null)
+ {
+ $request = [];
+ $content = current(parent::getPayRequest($wc_order, $form_fields, $customer));
+ $content['amount'] = Utils::format_order_price(
+ $this->getPriceWithInterest(
+ $this->getAmount($wc_order, $form_fields),
+ Utils::get_value_by($form_fields, 'installments'),
+ Utils::get_value_by($form_fields, 'brand')
+ )
+ );
+ if (!isset($content['customer']) && isset($customer->email)) {
+ $content['customer'] = $customer;
+ }
+ $request[] = $content;
+ return $request;
+ }
}
diff --git a/templates/checkout/2-cards-item.php b/templates/checkout/2-cards-item.php
deleted file mode 100644
index d125f266..00000000
--- a/templates/checkout/2-cards-item.php
+++ /dev/null
@@ -1,170 +0,0 @@
-settings->is_active_2_cards()) {
- return;
-}
-
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
-use Woocommerce\Pagarme\View\Checkouts;
-
-global $woocommerce;
-
-$total = $woocommerce->cart->total;
-
-$installments_type = Setting::get_instance()->cc_installment_type;
-$ref1 = sha1(random_int(1, 1000));
-$ref2 = sha1(random_int(1, 1000));
-
-?>
-
-
-
-
-
-
-
-
- 1º Cartão
-
- 2]); ?>
-
-
-
- *
-
-
-
-
-
-
- 2,
- ]
- );
- ?>
-
-
-
-
-
- *
-
-
- data-total="" data-type="" data-action="select2" data-required="true" data-element="installments" name="installments" style="font-size: 1.41575em">
-
- ...', array('option' => array('value' => true)));
- };
- ?>
-
-
-
-
- 2]);
- Utils::get_template(
- 'templates/checkout/field-enable-multicustomers',
- array(
- 'ref' => $ref1,
- 'type' => 'card1',
- )
- );
- ?>
-
-
-
- $ref1,
- 'type' => 'card1',
- )
- );
- ?>
-
-
-
- 2º Cartão
-
- 3]); ?>
-
-
-
- *
-
-
-
-
-
-
- $installments_type,
- 'suffix' => 3,
- )
- );
- ?>
-
-
-
-
-
- *
-
-
- data-total="" data-type="" data-action="select2" data-required="true" data-element="installments" name="installments2" style="font-size: 1.41575em">
-
- ...', array('option' => array('value' => true)));;
- };
- ?>
-
-
-
-
- 3]);
- Utils::get_template(
- 'templates/checkout/field-enable-multicustomers',
- array(
- 'ref' => $ref2,
- 'type' => 'card2',
- )
- );
- ?>
-
-
-
- $ref2,
- 'type' => 'card2',
- )
- );
- ?>
-
-
-
diff --git a/templates/checkout/billet-and-card-item.php b/templates/checkout/billet-and-card-item.php
deleted file mode 100644
index c8025acb..00000000
--- a/templates/checkout/billet-and-card-item.php
+++ /dev/null
@@ -1,129 +0,0 @@
-settings->is_active_billet_and_card()) {
- return;
-}
-
-global $woocommerce;
-
-$total = $woocommerce->cart->total;
-
-use Pagarme\Core\Kernel\ValueObjects\TransactionType;
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\View\Checkouts;
-use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
-
-$installments_type = Setting::get_instance()->cc_installment_type;
-$billet_and_card = true;
-$ref_billet = sha1(random_int(1, 1000));
-$ref_card = sha1(random_int(1, 1000));
-
-?>
-
-
-
-
-
-
-
-
- 4, 'cardType' => [TransactionType::CREDIT_CARD,TransactionType::DEBIT_CARD]]); ?>
-
-
-
-
- 4,
- ]
- );
- ?>
-
-
-
-
-
- *
-
-
- data-total="" data-type="" data-action="select2" data-required="true" data-element="installments" name="installments3" style="font-size: 1.41575em">
-
- ...', array('option' => array('value' => true)));;
- };
- ?>
-
-
-
-
- 4]); ?>
-
-
-
- $ref_billet,
- 'type' => 'billet',
- 'title' => 'Dados comprador (Boleto)',
- 'suffix' => '_card'
- )
- );
-
- Utils::get_template(
- 'templates/checkout/multicustomers-form',
- array(
- 'ref' => $ref_card,
- 'type' => 'card',
- 'title' => 'Dados comprador (Cartão)',
- 'suffix' => '_billet'
- )
- );
- ?>
-
-
-
diff --git a/templates/checkout/billet-item.php b/templates/checkout/billet-item.php
deleted file mode 100644
index ae987ac6..00000000
--- a/templates/checkout/billet-item.php
+++ /dev/null
@@ -1,38 +0,0 @@
-settings->is_active_billet()) {
- return;
-}
-
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-
-$ref = sha1(random_int(1, 1000));
-$type = 'billet';
-
-?>
-
-
-
-
-
-
- O Boleto bancário será exibido após a confirmação da compra e poderá ser pago em qualquer agência bancária, pelo seu smartphone ou computador através de serviços digitais de bancos.
-
-
- ',
- esc_url(Core::plugins_url('assets/images/barcode.svg')),
- esc_html__('Boleto', 'woo-pagarme-payments')
- );
- ?>
-
-
-
-
-
-
diff --git a/templates/checkout/choose-credit-card.php b/templates/checkout/choose-credit-card.php
deleted file mode 100644
index bab7ee1b..00000000
--- a/templates/checkout/choose-credit-card.php
+++ /dev/null
@@ -1,53 +0,0 @@
-is_allowed_save_voucher_card())
- || !$setting->is_allowed_save_credit_card()) {
- return;
-}
-
-$cards = $customer->get_cards($cardType, true);
-if (!$cards) {
- return;
-}
-
-?>
-
-
-
-
-
-
-
-
-
-
- (%1$s) •••• •••• •••• %4$s',
- esc_html(strtoupper($card->getBrand()->getName())),
- esc_attr($card->getPagarmeId()->getValue()),
- esc_html(strtolower($card->getBrand()->getName())),
- esc_html($card->getLastFourDigits()->getValue())
- );
- endforeach;
- ?>
-
-
diff --git a/templates/checkout/common-card-item.php b/templates/checkout/common-card-item.php
deleted file mode 100644
index 6f5b9a79..00000000
--- a/templates/checkout/common-card-item.php
+++ /dev/null
@@ -1,57 +0,0 @@
-
-
-
diff --git a/templates/checkout/common-voucher-item.php b/templates/checkout/common-voucher-item.php
deleted file mode 100644
index a8907e5a..00000000
--- a/templates/checkout/common-voucher-item.php
+++ /dev/null
@@ -1,64 +0,0 @@
-
-
-
diff --git a/templates/checkout/credit-card-item.php b/templates/checkout/credit-card-item.php
deleted file mode 100644
index cbe6a25a..00000000
--- a/templates/checkout/credit-card-item.php
+++ /dev/null
@@ -1,78 +0,0 @@
-cart->total;
-
-if (!$model->settings->is_active_credit_card()) {
- return;
-}
-
-use Pagarme\Core\Kernel\ValueObjects\TransactionType;
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\View\Checkouts;
-use Woocommerce\Pagarme\Model\Customer;
-use Woocommerce\Pagarme\Model\Setting;
-use Woocommerce\Pagarme\Helper\Utils;
-
-$installments_type = Setting::get_instance()->cc_installment_type;
-$ref = sha1(random_int(1, 1000));
-$type = 'card';
-$cardType = [TransactionType::CREDIT_CARD, TransactionType::DEBIT_CARD];
-
-?>
-
-
-
-
-
-
-
-
-
-
-
- 1,
- 'installments_type' => $installments_type
- ]
- );
- ?>
-
-
-
-
-
- *
-
-
- data-total="" data-type="" data-action="select2" data-required="true" data-element="installments" name="installments_card" style="font-size: 1.41575em">
-
- ...';
- };
- ?>
-
-
-
-
- 1]); ?>
-
-
-
-
-
-
-
-
diff --git a/templates/checkout/environment.phtml b/templates/checkout/environment.phtml
deleted file mode 100644
index 33b68598..00000000
--- a/templates/checkout/environment.phtml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-getConfig()->getIsSandboxMode()) : ?>
-
-
- = __('Important! This store is in the testing phase. Orders placed in this environment will not be carried out.', 'woo-pagarme-payments'); ?>
-
-
-
diff --git a/templates/checkout/field-enable-multicustomers.php b/templates/checkout/field-enable-multicustomers.php
deleted file mode 100644
index 87830f36..00000000
--- a/templates/checkout/field-enable-multicustomers.php
+++ /dev/null
@@ -1,29 +0,0 @@
-is_active_multicustomers()) {
- return;
-}
-
-$p = isset($without_container) && $without_container ? false : true;
-
-echo wp_kses($p ? "" : '', array('p' => array('class' => true, 'data-element' => true)));
-?>
-
-
-
-
-
-' : '', array('p' => array())); ?>
diff --git a/templates/checkout/field-save-card.php b/templates/checkout/field-save-card.php
deleted file mode 100644
index 228cd2d1..00000000
--- a/templates/checkout/field-save-card.php
+++ /dev/null
@@ -1,40 +0,0 @@
-is_allowed_save_voucher_card()) {
- return;
- }
- break;
- default:
- if (!$setting->is_allowed_save_credit_card()) {
- return;
- }
- break;
-}
-
-?>
-
-
-
- save_credit_card, true); ?>>
-
-
-
-
diff --git a/templates/checkout/main.php b/templates/checkout/main.php
deleted file mode 100644
index 6616abfb..00000000
--- a/templates/checkout/main.php
+++ /dev/null
@@ -1,79 +0,0 @@
-get_active_tab();
-$wc_api = get_home_url(null, '/wc-api/' . Checkout::API_REQUEST);
-$swal_data = array(
- 'title' => __('Waiting...', 'woo-pagarme-payments'),
- 'text' => __('We are processing your request.', 'woo-pagarme-payments'),
- 'text_default' => __('An error occurred while processing.', 'woo-pagarme-payments'),
- 'text_success' => __('Your transaction has been processed successfully.', 'woo-pagarme-payments'),
-);
-
-?>
-
-
-is_sandbox_mode()) : ?>
-
-
- = __('Important! This store is in the testing phase. Orders placed in this environment will not be carried out.', 'woo-pagarme-payments'); ?>
-
-
-
->
- $model)
- );
-
- Utils::get_template(
- 'templates/checkout/2-cards-item',
- array('model' => $model)
- );
-
- Utils::get_template(
- 'templates/checkout/billet-and-card-item',
- array('model' => $model)
- );
-
- Utils::get_template(
- 'templates/checkout/billet-item',
- array('model' => $model)
- );
-
- Utils::get_template(
- 'templates/checkout/pix-item',
- array('model' => $model)
- );
-
- Utils::get_template(
- 'templates/checkout/voucher-item',
- array('model' => $model)
- );
-
- ?>
-
-
-
-
diff --git a/templates/checkout/multicustomers-form.php b/templates/checkout/multicustomers-form.php
deleted file mode 100644
index 876d6699..00000000
--- a/templates/checkout/multicustomers-form.php
+++ /dev/null
@@ -1,92 +0,0 @@
-is_active_multicustomers()) {
- return;
-}
-
-$wc_countries = new WC_Countries();
-$states = $wc_countries->get_states('BR');
-/** phpcs:disable */
-?>
-
-
- {$title}" : "", array('h4' => array())); ?>
-
-
diff --git a/templates/checkout/pix-item.php b/templates/checkout/pix-item.php
deleted file mode 100644
index 594cb1d5..00000000
--- a/templates/checkout/pix-item.php
+++ /dev/null
@@ -1,38 +0,0 @@
-settings->is_active_pix()) {
- return;
-}
-
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-
-$ref = sha1(random_int(1, 1000));
-$type = 'pix';
-
-?>
-
-
-
-
-
-
- O QR Code para seu pagamento através de PIX será gerado após a confirmação da compra. Aponte seu celular para a tela para capturar o código ou copie e cole o código em seu aplicativo de pagamentos.
-
-
- ',
- esc_url(Core::plugins_url('assets/images/pix.svg')),
- esc_html__('Pix', 'woo-pagarme-payments')
- );
- ?>
-
-
-
-
-
-
diff --git a/templates/checkout/voucher-item.php b/templates/checkout/voucher-item.php
deleted file mode 100644
index ec00df76..00000000
--- a/templates/checkout/voucher-item.php
+++ /dev/null
@@ -1,42 +0,0 @@
-settings->is_active_voucher()) {
- return;
-}
-
-use Pagarme\Core\Kernel\ValueObjects\TransactionType;
-use Woocommerce\Pagarme\Helper\Utils;
-
-$ref = sha1(random_int(1, 1000));
-$type = 'voucher';
-
-?>
-
-
-
-
-
-
-
- 6, 'cardType' => [TransactionType::VOUCHER]]); ?>
-
-
- 6
- ]
- );
- ?>
-
-
- 6, 'type' => $type]); ?>
-
-
-
-
-
From 4358a67b80f5963e831729acda1ff388ac742d53 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 13 Apr 2023 22:57:34 -0300
Subject: [PATCH 107/156] delete deprecated files
---
languages/woo-pagarme-payments-pt_BR.mo | Bin 19890 -> 21939 bytes
languages/woo-pagarme-payments-pt_BR.po | 85 +++++-
.../WoocommercePlatformOrderDecorator.php | 4 +-
src/Controller/Gateways/TwoCreditCard.php | 16 ++
src/Controller/Settings.php | 244 +++++++++++++++++-
src/Core.php | 28 +-
6 files changed, 354 insertions(+), 23 deletions(-)
diff --git a/languages/woo-pagarme-payments-pt_BR.mo b/languages/woo-pagarme-payments-pt_BR.mo
index 24c2a0c8d82a0c4b4ca23ff882bebc39f6f41b31..31bfdadb837fdb70bf821bfcecf2d945f1af5531 100644
GIT binary patch
delta 7191
zcmZYD3wRXO8OHGw5&{HcfB->JGm!)$2?>UKxCkUdxCImts)!D|6S9!(hP{CCwiGK~
zO4YikRD>$l3so?>TC7@>rrJ`eBDO`rTH0Dcs@5vBRodGBJ2OFS=i$rmoY~zu=X~co
zn>;+VF(dt0M)KWWS$7$(>Bhv{jqo^
zPR9$-!E$^EvvD8x$G1_>KaTt}y$X!!X-v|bM`I8-#$pu)P#?S-2jC{m$6eSPf8%=;
z2h#r%HNe1r#^mB;?1poYIh#vyA+}%^?#9me8fG)T`8AF1+&JjoFy=67@gHLzeu?@(
z-WlEieK3>$0MzFOp(Z{ICu0L@0b8*U+mNK1y{HMijXC%(c4vI^0S&F-IBMXY)6_v?^$i
zLn%It`oKr1`(L2;Fym}50|lsB8HDVLnT?ugBWi%Fu@~O#yAf48+flXjQ`E%YM`f(X
zIpkj}EIh}%G1zwuYJfV_%52okn^7yf5l3Mfm65-oCS1&h%QDo&t56fD!(q4xmHInS
zTXS!ch6dPz+T-mw6?fts%(jdP;R1XdcOjEE;UceA)*)qMHX++;cKH2${_7v2GWu`S
zgmTXH`WBL0lN>@rshN&iVc2&qYM{-imA-&l$uU&QyYeC3KNIWlVjPScQ8n-iGN$<_
zYHQ9c_A*+EJLpeBialvQr=bkwlz6G>i^_n7S=fk5RWoYO5~xgl3+Li`)XI+_b!ajN
zdIJ@r-ap#!Per}&O4J0e!CamHZ8Vgk=TS5M1rEZas0s92E+y)Bzs`)rlFKRf*NoK>U{1;3fp{$T6uRi
zSoTAmjuO8=0rmbFsOMdYU2ui}dMkFOzZP?Fo$oz^$-h##g&Xo&R1v<0O5OXY6@27t
z%DiIDM`dIbs<@`1Cb|Gu<4Wv`|3H1Q={J&|Q-E6NVAO=F%gMh6n#c_~6&cIaV>PxS
zb!DE$v3LM=-usg8kvJRmzO~3$W*2G!A7P&i2B|RSP5S*Sz4QN9)W8EMD0yCz#%VMv
zQF}KIHPcC`qM3&}b^+g2*n|GJ{r-J^zYTM^zYDdHJ*cgG6SaWPP|rPs((i%gI1!WM
zX}Cp(ncUcnO3@bViBI8d{28h!dslfY8HwC7%di;lL&h+>P^teES8+^EpcWDvVa#}3
zgL?fXWNVUUHx1435RSua@;V%AP%F6#wYN#sL^q>~Zzt+J??*mrK1FRsDc?#;Z2&nK
zCWQJTyAxHUZP*82M%AA=NWcq8fq2T?0{4>h4&mZxJ?fO@?Ub-xsq
znJVmu7yGX-M=dDs-@nQ4-;c^j8k2g^8#Gj82T-a07`4J&N?rr@#_o6)2Cx*hr|VFk
z+lcyQ@&pdVJ=h;VL%p8IzUovBz+qUA91yc+9QoG^ZQRfR2a&~^!${Ul5f!8Rm!eKd
z1D=U7EWq1PRsS$*Yo5eh+=0r>%czXJj>^OlWKQM;s%S?|AphFqMH9R|T!AW%HF!2|
zKn?gK)QsOit>8=4%7$Iw4LB9`ocX9zvkW!CYf%|qkE)SPs8h2YNwPVVq`?U>{U>^F
ztVgAO0V9xHMpTVFidx|z)QUewZP78*g#LxIu*W20F2TjP9G}6*v1qclu-8z}
zNq$J<3>sgcR@%G9tAR??it16R4`5$x@%uNS_IN!OVH+xQ`%o!Af?7aEt@m566!rQt
z)N@zk2%Z1CXpl|wD(V9{7kYbhK9%1?hGSur=q6Q9QDJHQ3
zA4N@IKMuurFdK8HdG~u`5#yUPXsBApVj*6LnxTVTFyZ&FLsjp0(8AqVj7L$`oj2X9
zp>uHn{W8?^W}|8&g4(JZP!oCxlS=7tX`F}0Q8O-_;T@}D)Sg%RPVv1QRTFX4UVal*
zJ9qm&i8?)da1b6vWvbUqZ=x3J^!2MrG{QS>#`hP25nb+Hf`QMQy=F_1=VRR0^+0
z-MHo>IacEb$byrmc)pkV
zIjHY}7E~&qKoa0iY7s6W789!YJVKYgN)Hn{6&)8}3uX`TC7}%I`hvKC&{pXBJ@E~q
zht9u_imtyBH@Yn^u5xXIkpA!EdwEs0k1(DRA>QW8p>P={WT8QruTM1oopoz
z5I-mGA>Jgq5SI|T{zm+oVEgrFUxiz}v`vh7pSYAr6AuvjQrb`GYA5EVdgkXRH`BV8
z7)6XEt|8ip<-|us5z%qQX*@yPPSp7~JK<8|X<{5Ph`65k38AZ*Q0ae8OeO9onh0G_
zYR|t%V}#rFe(Zyd#1`UNVm$FrLRSVks>ex0A7UEu2+?s3r12|aDDgX@FYy8KQ{pY+
zb)t$mNE{=gs<|6zgorB%T{jW=guVeft~+S_%kMZHH*q)deZN21cb2dCka(VGREKLK
zv5nYE=z2vZdy(7ZPgDF2k;N+S!aov2h;I@7i2I1UiIv1J30;-M8X}k2Ky+NE(a`@w
z>bi``c3a-}Z>`@J$#?nj3GoiGlhCz;NVqNUmvcGoDa2F67-AEl>xUlhpRucGf1Bv$
z-xIeIZxi1n{!DaYLjOixrxO#r-E{kAt%v*b(No&L_1p8&B3g;<#O1`<#A@O};%CGy
zZb=`Z^(P`otS3Gr9wKxdB~rxI>Tuoc;rSfz0&u()VP9*lv6N0
zdx5Q&Q(Fsaa_nf(TIF?*7M#ebi8{ehyoS5!_xcUU>R%UW3OZ4%-fnhGU1Et93dfzL
zQ9B-rgwxq)kIl^UJ64Mm4u--@Q{$}9CkE}fZ8b!qR*T)*?1bZ1vlDNO1gkAGExgih
z3I(l5l&7BT{qNgS)kQnIPl+U=R&8i$C>~3HT2$XDHNLnc&x$$$J{#ldiEywYbw%-k
z(L=0BLFUYi>?Uhkm~ork`I$NPQaf7F>{vsr8oMQ)h&q)ub~xZPHMy^+DodUn8I6Zn
zd@FCz3r>&^eRa$I%&E67c2+vkm_u$#l3B^Hvx@mNId;sk0+Dds4uxY@Aesp9NXw1}
z8bfg>pkXaL9JCq|;ea>EP`uSjw2&kxR$(o0tj5sNMy8;pHIuHO)f!1yCFd8%me_&i
zi57LER*Z*POB`0`@L{qZOp@-Bs$!loEpCNk|MwUtXvHJ!OH>(gr{LzEVXb(h9-;UWhfd6yL;!4=|4xW`k(HpkMqHnXe5|$mzG{MxFDl@B+l|D
zxfPjOQTE(`Qx@hg=xfX1iAAZ>@>|l|%8zH9Hf+ey;X}?JY7HGzJv_C&;$UV~MOAuT
z<)1oro~P%g!&M71Iu+KRJE-
z*vm8XPr0pHr>vdS2NU)$swA{D9Hn!VLSI?e=3dd7)ySV94vl~C;e4~Xp_5O2PzoZ9wDQB||1@Azkg
z2OIA=(Xu!$C*Pp6bFyQ(XC)pArgzsK$x2>GX<6aOO54&2Qf@WN_N^3VJi%AO)wVx9
z@BC2CWX_JRNKp11A={!-IY90q4+ZU@Q^5e77k0vKCh02@j(cPpc#duPb;cuNPC`c~
zsWZrVbD!!D81)WM`z@B;6n9tbc%{lS+aFlzG+EA7P9PDtqYUmHohbWy%6wTxOElC>
zbwya4Wj8Mgxrt(2#v)@U$1FMdsQ-O{)9f7}6?*Mg)D+dERm>$AYyAGwuBHWiqIfx=-8X6jG(sYnCP2|sj)Prx2nce
zZLOvDm!hqpmd@A(L)9><)cUlZnoi5pn(yzuC(rae{q=M1ec$)qbN=Vtn?Ch^fGPFPp1+mwxBMw69e!dYCvCLH++P#m|n-2U>t^_I0mcW
zB-DUrqHeGhHJ}Yx9e1FtBtg{tNTJuQM9!Nlq
zJPWl6r=cn`+aAAZU5>iJCe+N1pax!!n%Es|k5TMERiqzkB6I6ee{~jeLL*;-8o(w@
z!2_t0{|B`sPw-g`dWwr+Hs<3B+=!v|jiGCHq4vOeq?qO=GDqJA(s2wMNuRg%&`}9{
zpazg*kMogxnL<=09Mp_oq6h48xjnwwocf3I!GAfS8Thww*DeHg!9>J7EU)wV#)wDzF(<
z!7|Lo)2K}x$A-~>yPvJq=uG!#om;sh_wZ>tAC#iLa2!?o^QaQu
z!%i5%Roh@TYT&a`OE(|2`8J>)yQ8Sb?mD)`Us08A)7stSo{4nyB6%0J`94N%rejFe
z%{7d}Fs2iMEinW$P~Y#3!*K*^Y06LoI)veP4E4sljGEAos2AH44AApmk7?+Q6^GB`
zU}V3T&8Qn)K>hHVJ-&mQ;X~96Yceh0z);5-_IL&B5D(LVrS}yS*Q_@z$RFPdM~U-RcIeF8FL3&O;exQ=zJg4b*E!0mY{b1UVHvW
z4CDUBpR-z{>R1Pxp*CeVR7v|{Rm?$EWE4i>IMmE%qaLdzs7-bjYvNC+C8)~XYhis<
zMcSb5HvqN&%y>GQ!7|j0PoZvj9d)4xSOY7wb2Pvx)RH8jZjg%XE7KeK#}x4|wvE|^
z`raK>$$vmq@DcK7!Zhee{i%ZK&hT}^BGioMVP9N`gYXKD!?tYwjkppuljqXi-xXk8
zj%Q#rzKvSzEvN~c#4x;$wefp<9MqZm$8e%%XZN{HLX~O&M&Vf0h+jkfFhnC*fTp0HuGz>d$9Oi;(Eu)E5?({CRm3xH
zMe3q9T}RY_GEoD4-X0G_R>zFTI9!jaz){rZ{0_AT{JXn*s|q&YI2O5|$8@DrpA(ZY
z5f@<~eu{bu_M_JB7^?IaQEPnP8l36wg?QxemFbF_aXxAQ)9vT;P)o25wO2mDdV2oP
z(a{JWpf<-Ndt9T3`}{_u2GRue!(>$Hvrq%iMOCB(_51m#J+ul{>fNY;T(dsJSdN39
zHKv&Rn*=&4?K;%j?M6L@=k591SefIWt@;nU0FHw&0jnUZW>T;r7GgVGYCVlw+Mr&p
z9gx3wCLcZ8REz0c!fn_A7xZ>#bQtvpJAr}tC2D3@P@D82>h}RzuCb{1Lr2t7<)D^o
zEQVqU24g8U!zEeNU#0n+6CrpWnWVXjahTA@UCW-R(hfpB4dYRp=m@6aEo_eQyfjqW
zY}8{p5ml+p=!d^;BRHs~^;dg~93a=oLK05a5S4u>sYFha9HRC+qFw)Ya+p-KH*H6Q
zQ~L+WC3*+6Ae+d)NE~^Q1nB%!}QDZ{p3~5Xz6Ftjn
z^T=6Wk3Z#B_M5M1v#RBhQu03W&Hp_*Y9Eq0B!i?7wJoF{Sx=UdvE&W%Iw>OO$REfB
zqD`xoPqhC2L>o_Qy@RN|N@B?gQm*?4(NQZQnZBO;FE*|3saS%y?fHM>V%x7^1|98z
zf%Zf^Zm|7#@hJJq9*a+GpDn|l@y*};KNmXR#(sDl8<9))_y*pxec>goNj4cnmXp`W
zm!ubYndnJcMn;jVWF}FYMYj5S#{9+J-}L6h6taq>lZx{b=_itk_Io+P-DesdJyt7;LspX}M6HbcnT#ao$w#Cqd4Xh+
zFrwDo#rL0ZZRvka_7lBw3&;ebw`WzNHl2L&|9SHE0Eb`^Ksn-=j*zePD*sTQxyHPw>YL@ptmeG
zEx-wje^_ba>J
zA0$8U3v1mnIjLoGYFz7-v}9*h%2xr&t&+XPZLa%!^V<*7ttU7mQ%jtCsm-0(w7$-?
zw4vThX>I+y@tw{Ddc(U84RB_4KNsFFFE>ATVqE@&!h 1);\n"
-"X-Generator: Poedit 3.1.1\n"
+"X-Generator: Poedit 3.2.2\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;_n_noop:1,2;_c;_nc:1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2\n"
"X-Poedit-Basepath: ..\n"
@@ -145,6 +145,12 @@ msgstr "Chave pública Produção"
msgid "Boleto Bancário"
msgstr "Boleto Bancário"
+msgid "Billet Bank"
+msgstr "Boleto Bancário"
+
+msgid "Billet"
+msgstr "Boleto"
+
#: src/Controller/Gateways.php:253
msgid "Enables Boleto Bancário"
msgstr "Ativar Boleto Bancário"
@@ -551,6 +557,18 @@ msgstr "Código do cartão"
msgid "Card Holder Document Number"
msgstr "Documento do titular do cartão"
+msgid "Bank "
+msgstr "Banco "
+
+msgid "Integration pending"
+msgstr "Integração pendente"
+
+msgid "Invalid data for payment method: "
+msgstr "Dados inválidos para a forma de pagamento: "
+
+msgid "Invalid payment method: "
+msgstr "Forma de pagamento inválido: "
+
#: templates/checkout/field-enable-multicustomers.php:31
msgid "Fill other buyer data"
msgstr "Preencher com dados de outro comprador"
@@ -899,6 +917,69 @@ msgstr "Importante! Esta loja está em fase de testes. Os pedidos realizados nes
msgid "Important! This store is linked to the Pagar.me test environment. This environment is intended for integration validation and does not generate real financial transactions."
msgstr "Importante! Esta loja está vinculada ao ambiente de testes da Pagar.me. Este ambiente é destinado a validação de integração e não gera operações financeiras reais."
+msgid "Yes"
+msgstr "Sim"
+
+msgid "No"
+msgstr "Não"
+
+msgid "Hub integration"
+msgstr "Integração de HUB"
+
+msgid "Card Wallet"
+msgstr "Carteira"
+
+msgid "Card wallet"
+msgstr "Carteira"
+
+msgid "Cancel"
+msgstr "Cancelar"
+
+msgid "Card"
+msgstr "Cartão"
+
+msgid "CREDIT CARD"
+msgstr "CARTÃO DE CRÉDITO"
+
+msgid "CreditCard"
+msgstr "Cartão de crédito"
+
+msgid "Amount"
+msgstr "Total"
+
+msgid "Pagar.me - Capture/Cancellation"
+msgstr "Pagar.me - Captura/Cancelamento"
+
+msgid "Last Four Digits"
+msgstr "Últimos quatro dÃgitos"
+
+msgid "Holder Name"
+msgstr "Titular"
+
+msgid "No records found."
+msgstr "Nenhum registro foi encontrado."
+
+msgid "Partially Reversed"
+msgstr "Parcialmente Revertido"
+
+msgid "Partially Canceled"
+msgstr "Parcialmente Cancelado"
+
+msgid "Partially Captured"
+msgstr "Capturado Parcialmente"
+
+msgid "Total Amount"
+msgstr "Total"
+
+msgid "Pagar.me - Additional Information"
+msgstr "Pagar.me - Informações Adicionais"
+
+msgid "This new release contains crucial architecture and functionality updates. We highly recommend you %1$sbackup your site before upgrading%2$s. It is highly recommended to perform and validate the update first in the staging environment before performing the update in production."
+msgstr "Esta nova versão contém atualizações cruciais de arquitetura e funcionalidade. Recomendamos que %1$sfaça backup de seu site antes de atualizar%2$s. É altamente recomendável executar e validar a atualização primeiro no ambiente de teste antes de executar a atualização em produção."
+
+msgid "We recommend backup before upgrading!"
+msgstr "Recomendamos backup antes de atualizar!"
+
#~ msgid "If you have not yet received the billet, please click the button below to print."
#~ msgstr "Se você ainda não efetuou o pagamento, por favor clique no botão abaixo para pagar."
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index e8cadd31..07e03944 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -1028,13 +1028,13 @@ private function extractPaymentDataFromVoucher(&$paymentData)
$amount = str_replace('.', '', $amount);
$amount = str_replace(',', '', $amount);
$newPaymentData->amount = $amount;
-
+
if ($this->formData["enable_multicustomers_voucher"]) {
$newPaymentData->customer = $this->extractMultibuyerData(
'voucher'
);
}
-
+
$voucherDataIndex = NewVoucherPayment::getBaseCode();
$newPaymentData->saveOnSuccess =
isset($this->formData["save_credit_card"]);
diff --git a/src/Controller/Gateways/TwoCreditCard.php b/src/Controller/Gateways/TwoCreditCard.php
index 4bf49afc..c5282375 100644
--- a/src/Controller/Gateways/TwoCreditCard.php
+++ b/src/Controller/Gateways/TwoCreditCard.php
@@ -11,6 +11,7 @@
namespace Woocommerce\Pagarme\Controller\Gateways;
+use Woocommerce\Pagarme\Model\Config\Source\Yesno;
use Woocommerce\Pagarme\Model\Payment\TwoCards;
defined('ABSPATH') || exit;
@@ -27,4 +28,19 @@ class TwoCreditCard extends AbstractGateway
{
/** @var string */
protected $method = TwoCards::PAYMENT_CODE;
+
+ /**
+ * @return array
+ */
+ public function field_enabled()
+ {
+ return [
+ 'title' => __('Enable/Disable', 'woocommerce'),
+ 'type' => 'select',
+ 'options' => $this->yesnoOptions->toLabelsArray(),
+ 'label' => __('Enable multi-means (2 Credit cards)', 'woo-pagarme-payments'),
+ 'old_name' => 'multimethods_2_cards',
+ 'default' => $this->config->getData('multimethods_2_cards') ?? strtolower(Yesno::NO),
+ ];
+ }
}
diff --git a/src/Controller/Settings.php b/src/Controller/Settings.php
index 3f880c3a..7b046d71 100644
--- a/src/Controller/Settings.php
+++ b/src/Controller/Settings.php
@@ -1,4 +1,13 @@
select = $select;
+ if (!$select) {
+ $this->select = new Select();
+ }
+ $this->config = $config;
+ if (!$config) {
+ $this->config = new Config();
+ }
+ $this->model = new Gateway();
+ $this->yesNoOptions = new Yesno();
+ add_action('admin_enqueue_scripts', array($this, 'admin_scripts'));
add_filter(Core::plugin_basename('plugin_action_links_'), array($this, 'plugin_link'));
+ add_action('admin_menu', array($this, 'settings_menu'), 58);
+ add_action('admin_init', array($this, 'plugin_settings'));
$this->gateway_load();
+ $this->select = $select;
+ if (!$select) {
+ $this->select = new Select();
+ }
+ $this->setSectionsFields();
+ }
+
+ public function jsUrl($jsFileName)
+ {
+ return Core::plugins_url('assets/javascripts/admin/' . $jsFileName . '.js');
+ }
+
+ public function admin_scripts()
+ {
+ wp_register_script('pagarme_settings', $this->jsUrl('pagarme_settings'), array('jquery'), false, true);
+ wp_enqueue_script('pagarme_settings');
+ wp_register_style('woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css', array());
+ wp_enqueue_style('woocommerce_admin_styles');
+
+ $params = array(
+ 'ajax_url' => admin_url('admin-ajax.php'),
+ 'nonces' => array(
+ 'gateway_toggle' => wp_create_nonce('woocommerce-toggle-payment-gateway-enabled'),
+ )
+ );
+ wp_localize_script('pagarme_settings', 'pagarme_settings', $params);
+ }
+
+ private function setSectionsFields(array $value = null)
+ {
+ if ($value) {
+ $this->sectionsFields = $value;
+ return;
+ }
+ $this->sectionsFields = [
+ 'section' => [
+ [
+ 'id' => 'options_section',
+ 'title' => 'General',
+ 'fields' => [
+ [
+ 'fieldObject' => Select::class,
+ 'id' => 'enabled',
+ 'title' => 'Enable',
+ 'options' => $this->yesNoOptions->toOptionArray(),
+ 'default' => Yesno::NO_VALUE,
+ ],
+ [
+ 'fieldObject' => Integration::class,
+ 'id' => 'hub_button_integration',
+ 'title' => 'Hub integration',
+ ],
+ [
+ 'fieldObject' => Environment::class,
+ 'id' => 'hub_environment',
+ 'title' => 'Integration environment',
+ 'default' => 'Develop',
+ ],
+ [
+ 'fieldObject' => Select::class,
+ 'id' => 'multicustomers',
+ 'title' => 'Multi-buyers',
+ 'options' => $this->yesNoOptions->toOptionArray(),
+ 'default' => Yesno::NO_VALUE,
+ ],
+ ]
+ ],
+ [
+
+ 'id' => 'tools_section',
+ 'title' => 'Tools',
+ 'fields' => [
+ [
+ 'fieldObject' => Select::class,
+ 'id' => 'is_gateway_integration_type',
+ 'title' => 'Advanced settings',
+ 'options' => $this->yesNoOptions->toOptionArray(),
+ 'default' => Yesno::NO_VALUE,
+ 'description' => 'Configurations that only works for Gateway customers, who have a direct contract with an acquirer.'
+ ],
+ [
+ 'fieldObject' => Select::class,
+ 'id' => 'enable_logs',
+ 'title' => 'Logs',
+ 'options' => $this->yesNoOptions->toOptionArray(),
+ 'default' => Yesno::NO_VALUE,
+ 'description' => 'Log Pagar.me events, you can check this log in WooCommerce>Status>Logs.'
+ ]
+ ],
+ ]
+ ]
+ ];
}
/**
@@ -78,8 +224,96 @@ private function getGateways()
public function autoLoad()
{
- foreach(glob( __DIR__ . '/Gateways/*.php') as $file) {
+ foreach (glob(__DIR__ . '/Gateways/*.php') as $file) {
include_once($file);
}
}
+
+ /**
+ * Add the settings page.
+ */
+ public function settings_menu() {
+ add_submenu_page(
+ 'woocommerce',
+ "Pagar.me",
+ "Pagar.me",
+ 'manage_options',
+ 'woo-pagarme-payments',
+ array( $this, 'settings_page' )
+ );
+ }
+
+ /**
+ * Render the settings page for this plugin.
+ */
+ public function settings_page() {
+ $options = $this->get_option_key();
+ $pageSettings = new PageSettings($options, $this->getGateways());
+ $pageSettings->includeTemplate();
+ }
+
+
+ /**
+ * @return string
+ */
+ public function get_option_key()
+ {
+ return $this->model->config->getOptionKey();
+ }
+
+ /**
+ * @param $values
+ * @return void
+ * @throws \Exception
+ */
+ public function getField($values)
+ {
+ if (class_exists($values['fieldObject'])) {
+ $field = new $values['fieldObject']();
+ $field->setData($values)->toHtml();
+ return;
+ }
+ throw new \Exception(sprintf('Field object class %s not exists. ', $values['fieldObject']));
+ }
+
+ /**
+ * Plugin settings form fields.
+ */
+ public function plugin_settings() {
+ $option = $this->get_option_key();
+ foreach ($this->sectionsFields['section'] as $key => $value) {
+ $section = new Section(
+ [
+ 'id' => $value['id'],
+ 'title' => $value['title'],
+ 'page' => $option,
+ ]
+ );
+ $section->toHtml();
+ foreach ($value['fields'] as $key => $field) {
+ $field['page'] = $option;
+ $field['section'] = $section->getId();
+ $field['name'] = $option;
+ $this->getField($field);
+ }
+ }
+ // Register settings.
+ register_setting( $option, $option, array( $this, 'validate_options' ) );
+ }
+
+ /**
+ * @param $input
+ * @return array
+ */
+ public function validate_options($input ) {
+ $output = array();
+ // Loop through each of the incoming options.
+ foreach ( $input as $key => $value ) {
+ // Check to see if the current option has a value. If so, process it.
+ if ( isset( $input[ $key ] ) ) {
+ $output[ $key ] = sanitize_text_field( $input[ $key ] );
+ }
+ }
+ return $output;
+ }
}
diff --git a/src/Core.php b/src/Core.php
index 92ed4d5f..a80f7f62 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -282,20 +282,20 @@ public static function get_hub_name()
public static function credit_card_errors_pt_br()
{
return array(
- 'A value is required.' => 'Validade: O mês é obrigatório.',
- 'The field exp_month must be between 1 and 12.' => 'Validade: O mês deve estar entre 1 e 12.',
- "The value 'undefined' is not valid for exp_year." => 'Validade: Ano inválido.',
- 'The card expiration date is invalid.' => 'Validade: Data de expiração inválida.',
- 'Card expired.' => 'Validade: Cartão expirado.',
- 'The holder_name field is required.' => 'O nome impresso no cartão é obrigatório.',
- 'The number field is required.' => 'O número do cartão é obrigatório.',
- 'The number field is not a valid number.' => 'O número do cartão é inválido.',
- 'The number field is not a valid credit card number.' => 'O número do cartão é inválido.',
- 'The field number must be a string with a minimum length of 13 and a maximum length of 19.'
- => 'O tamanho do número do cartão deve ter entre 13 e 19 caracteres.',
- 'The field cvv must be a string with a minimum length of 3 and a maximum length of 4.'
- => 'O campo cvv deve ter entre 3 e 4 caracteres.',
- 'The cvv field is not a valid number.' => 'O CVV é inválido',
+ 'exp_month: A value is required.' => 'Validade: O mês é obrigatório.',
+ 'exp_month: The field exp_month must be between 1 and 12.' => 'Validade: O mês deve estar entre 1 e 12.',
+ "exp_year: The value 'undefined' is not valid for exp_year." => 'Validade: Ano inválido.',
+ 'request: The card expiration date is invalid.' => 'Validade: Data de expiração inválida.',
+ 'request: Card expired.' => 'Validade: Cartão expirado.',
+ 'holder_name: The holder_name field is required.' => 'O nome impresso no cartão é obrigatório.',
+ 'number: The number field is required.' => 'O número do cartão é obrigatório.',
+ 'number: The number field is not a valid credit card number.' => 'Este número de cartão é inválido.',
+ 'card: The number field is not a valid card number' => 'Este número de cartão é inválido.',
+ 'card.number: The field number must be a string with a minimum length of 13 and a maximum length of 19.'
+ => 'O numéro do cartão deve ter entre 13 e 19 caracteres.',
+ 'card: Card expired.' => 'A validade do cartão está expirada',
+ 'card.cvv: The field cvv must be a string with a minimum length of 3 and a maximum length of 4.'
+ => 'O número cvv deve ter 3 ou 4 caracteres.',
);
}
}
From 35f211647ba6e389d58d62803e92bc5556360a1d Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 13 Apr 2023 23:15:11 -0300
Subject: [PATCH 108/156] delete deprecated files
---
.github/workflows/pr.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 9e4f16b0..a0625d53 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -52,7 +52,7 @@ jobs:
- name: Checkout project
uses: actions/checkout@v3
with:
- fetch-depth: 0
+ fetch-depth: 0
- name: Run Sonar
uses: sonarsource/sonarcloud-github-action@master
From 9fd255b863f59b690de448a0c1318d17f1adab13 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 14 Apr 2023 12:11:31 -0300
Subject: [PATCH 109/156] delete deprecated Model/Settings
---
src/Concrete/WoocommerceCoreSetup.php | 8 -
src/Controller/Checkout.php | 8 +-
src/Controller/Orders.php | 6 +-
src/Controller/Webhooks.php | 4 +-
src/Core.php | 3 +-
src/Helper/Utils.php | 4 +-
src/Model/Account.php | 4 +-
src/Model/Charge.php | 3 -
src/Model/Checkout.php | 4 -
src/Model/Config.php | 6 +
src/Model/Gateway.php | 4 -
src/Model/Order.php | 6 +-
src/Model/Setting.php | 356 --------------------------
src/Resource/Base.php | 10 +-
templates/myaccount/wallet.php | 1 -
15 files changed, 24 insertions(+), 403 deletions(-)
delete mode 100644 src/Model/Setting.php
diff --git a/src/Concrete/WoocommerceCoreSetup.php b/src/Concrete/WoocommerceCoreSetup.php
index f2c2ca75..20579b10 100644
--- a/src/Concrete/WoocommerceCoreSetup.php
+++ b/src/Concrete/WoocommerceCoreSetup.php
@@ -8,16 +8,8 @@
use Pagarme\Core\Kernel\Services\MoneyService;
use Pagarme\Core\Kernel\ValueObjects\CardBrand;
use Pagarme\Core\Kernel\ValueObjects\Configuration\CardConfig;
-use Woocommerce\Pagarme\Concrete\WoocommerceDatabaseDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommerceDataService;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformCreditmemoDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformInvoiceDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformOrderDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformPaymentMethodDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformProductDecorator;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Config;
-use Woocommerce\Pagarme\Model\Setting;
final class WoocommerceCoreSetup extends AbstractModuleCoreSetup
{
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index f56bd0ef..073d3e02 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -8,13 +8,11 @@
use Woocommerce\Pagarme\Controller\Gateways\AbstractGateway;
use Woocommerce\Pagarme\Model\CardInstallments;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Customer;
-use Woocommerce\Pagarme\Model\Gateway;
-use Woocommerce\Pagarme\Model\Setting;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model;
-use Woocommerce\Pagarme\Controller\Orders;
use WC_Order;
@@ -266,11 +264,11 @@ private function validate_amount_2_cards($fields, WC_Order $wc_order)
private function validate_brands($fields)
{
- $setting = Setting::get_instance();
+ $config = new Config();
$brand1 = Utils::get_value_by($fields, 'brand');
$brand2 = Utils::get_value_by($fields, 'brand2');
- $flags = $setting->cc_flags;
+ $flags = $config->getCcFlags;
if (empty($flags)) {
return;
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index 43411463..1395e8a6 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -9,7 +9,7 @@
use Woocommerce\Pagarme\Block\Adminhtml\Sales\Order as BlockOrder;
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Model\Order;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Concrete\WoocommerceCoreSetup;
use Woocommerce\Pagarme\Concrete\WoocommercePlatformOrderDecorator;
use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup;
@@ -26,8 +26,8 @@ class Orders
public function __construct(
BlockOrder $blockOrder = null
) {
- $this->settings = Setting::get_instance();
- $this->debug = $this->settings->is_enabled_logs();
+ $this->settings = new Config();
+ $this->debug = $this->settings->getData('enable_logs');
$this->blockOrder = $blockOrder ?? new BlockOrder;
add_action('on_pagarme_order_paid', array($this, 'set_order_paid'), 20, 2);
add_action('on_pagarme_order_created', array($this, 'set_order_created'), 20, 2);
diff --git a/src/Controller/Webhooks.php b/src/Controller/Webhooks.php
index 547acef4..3e4e10ed 100644
--- a/src/Controller/Webhooks.php
+++ b/src/Controller/Webhooks.php
@@ -8,8 +8,8 @@
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Core;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Order;
-use Woocommerce\Pagarme\Model\Setting;
use Exception;
class Webhooks
@@ -18,7 +18,7 @@ class Webhooks
public function __construct()
{
- $this->settings = Setting::get_instance();
+ $this->settings = new Config();
add_action('woocommerce_api_' . Core::get_webhook_name(), array($this, 'handle_requests'));
}
diff --git a/src/Core.php b/src/Core.php
index a80f7f62..29916bf3 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -7,7 +7,6 @@
}
use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
class Core
{
@@ -55,7 +54,7 @@ public static function redirect_on_activate()
public static function initialize()
{
$controllers = array(
- 'Settings',
+ 'Config',
'Checkout',
'Webhooks',
'Hub',
diff --git a/src/Helper/Utils.php b/src/Helper/Utils.php
index b46432bd..d6650316 100644
--- a/src/Helper/Utils.php
+++ b/src/Helper/Utils.php
@@ -7,7 +7,7 @@
}
use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Order;
use WC_Order;
@@ -479,7 +479,7 @@ public static function is_cnpj($cnpj = null)
*/
public static function get_option_key()
{
- $settings = Setting::get_instance();
+ $settings = new Config();
return $settings->get_option_key();
}
diff --git a/src/Model/Account.php b/src/Model/Account.php
index d20d5af4..8c8e8f0e 100644
--- a/src/Model/Account.php
+++ b/src/Model/Account.php
@@ -10,12 +10,12 @@
class Account
{
- private $setting;
+ private $config;
const WALLET_ENDPOINT = 'zff3yg2have4pcw';
public function __construct()
{
- $this->setting = Setting::get_instance();
+ $this->config = new Config();
}
}
diff --git a/src/Model/Charge.php b/src/Model/Charge.php
index d11bd518..572a3109 100644
--- a/src/Model/Charge.php
+++ b/src/Model/Charge.php
@@ -8,9 +8,6 @@
use Pagarme\Core\Webhook\Factories\WebhookFactory;
use Pagarme\Core\Webhook\Services\ChargeHandlerService;
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
use WC_Order;
class Charge
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 39435250..26b0c2f8 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -28,9 +28,6 @@
class Checkout
{
- /** @var Setting|null */
- private $setting;
-
/** @var Config */
private $config;
@@ -65,7 +62,6 @@ public function __construct(
$wooOrderRepository = new WooOrderRepository;
}
$this->config = $config;
- $this->setting = Setting::get_instance();
$this->orders = $orders;
$this->gateway = $gateway;
$this->wooOrderRepository = $wooOrderRepository;
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 153c8d17..b78be8ec 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -232,4 +232,10 @@ public function getCcFlags()
}
return $ccFlags;
}
+
+ public function log()
+ {
+ return new \WC_Logger();
+ }
+
}
diff --git a/src/Model/Gateway.php b/src/Model/Gateway.php
index e223438f..cc8132fe 100644
--- a/src/Model/Gateway.php
+++ b/src/Model/Gateway.php
@@ -15,7 +15,6 @@
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Payment\PaymentInterface;
-use Woocommerce\Pagarme\Model\Setting;
// WooCommerce
use WC_Order;
@@ -41,15 +40,12 @@ class Gateway
*/
const CC_TYPE_BY_FLAG = 2;
- public $settings;
-
/** @var Config|null */
public $config;
public function __construct(
Config $config = null
) {
- $this->settings = Setting::get_instance();
if (!$config) {
$config = new Config();
}
diff --git a/src/Model/Order.php b/src/Model/Order.php
index 269d2f6d..0dc4f7b5 100644
--- a/src/Model/Order.php
+++ b/src/Model/Order.php
@@ -7,13 +7,9 @@
}
use Pagarme\Core\Kernel\ValueObjects\OrderStatus;
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
use Pagarme\Core\Kernel\Services\OrderService;
-
// WooCommerce
use WC_Order;
-use Woocommerce\Pagarme\Model\Setting;
class Order extends Meta
{
@@ -63,7 +59,7 @@ public function __construct($ID = false)
{
parent::__construct($ID);
$this->wc_order = new WC_Order($this->ID);
- $this->settings = Setting::get_instance();
+ $this->settings = new Config();
}
/** phpcs:enable */
diff --git a/src/Model/Setting.php b/src/Model/Setting.php
deleted file mode 100644
index 8b614f2e..00000000
--- a/src/Model/Setting.php
+++ /dev/null
@@ -1,356 +0,0 @@
- array(),
- 'title' => array(),
- 'description' => array(),
- 'hub_install_id' => array(),
- 'hub_environment' => array(),
- 'environment' => array(),
- 'sandbox_secret_key' => array(),
- 'sandbox_public_key' => array(),
- 'production_secret_key' => array(),
- 'production_public_key' => array(),
- 'account_management_key' => array(),
- 'account_id' => array(),
- 'is_gateway_integration_type' => array(),
- 'section_payment_settings' => array(),
- 'enable_billet' => array(),
- 'enable_pix' => array(),
- 'enable_voucher' => array(),
- 'voucher_card_wallet' => array(),
- 'voucher_soft_descriptor' => array(),
- 'voucher_flags' => array(),
- 'pix_qrcode_expiration_time' => array(),
- 'pix_additional_data' => array(),
- 'enable_credit_card' => array(),
- 'multimethods_billet_card' => array(),
- 'multimethods_2_cards' => array(),
- 'multicustomers' => array(),
- 'antifraud_enabled' => array(),
- 'antifraud_min_value' => array(),
- 'billet_bank' => array(),
- 'billet_instructions' => array(),
- 'billet_deadline_days' => array(),
- 'cc_soft_descriptor' => array(),
- 'cc_operation_type' => array(),
- 'cc_flags' => array(),
- 'cc_allow_save' => array(),
- 'cc_installment_type' => ['sanitize' => 'intval'],
- 'cc_installments_maximum' => ['sanitize' => 'intval'],
- 'cc_installments_without_interest' => ['sanitize' => 'intval'],
- 'cc_installments_interest' => ['sanitize' => 'floatval'],
- 'cc_installments_min_amount' => ['sanitize' => 'floatval'],
- 'cc_installments_interest_increase' => ['sanitize' => 'floatval'],
- 'cc_installments_by_flag' => array(),
- 'webhook_id' => array(),
- 'enable_logs' => array(),
- 'migrations' => array(),
- );
-
- private function __construct($settings)
- {
- $this->set_settings($settings);
- }
-
- public function __get($key)
- {
- if (isset($this->{$key})) {
- return $this->{$key};
- }
-
- return $this->_get_property($key);
- }
-
- public function set($key, $value)
- {
- if (!$this->is_valid_key($key)) {
- return;
- }
-
- $settings = $this->get_settings();
-
- $settings[$key] = Utils::rm_tags($value);
-
- $this->update_settings($settings);
- }
-
- public function delete($key)
- {
- $settings = $this->get_settings();
-
- if (!isset($settings[$key])) {
- return;
- }
-
- unset($settings[$key]);
-
- $this->update_settings($settings);
- }
-
- private function _get_property($key)
- {
- if (!$this->is_valid_key($key)) {
- return false;
- }
-
- $sanitize = Utils::get_value_by($this->_fields[$key], 'sanitize');
- $value = Utils::get_value_by($this->get_settings(), $key);
- $this->{$key} = Utils::sanitize($value, $sanitize);
-
- return $this->{$key};
- }
-
- public function get_option_key()
- {
- return Core::tag_name('settings');
- }
-
- public function get_flags_list()
- {
- //Some brands are hidden for PSP
- return array(
- 'visa' => 'Visa',
- 'mastercard' => 'MasterCard',
- 'amex' => 'Amex',
- 'hipercard' => 'HiperCard',
- 'diners' => 'Diners',
- 'elo' => 'Elo',
- 'discover' => 'Discover',
- 'aura' => 'Aura',
- 'jcb' => 'JCB',
- 'credz' => 'Credz',
- // 'sodexoalimentacao' => 'SodexoAlimentacao',
- // 'sodexocultura' => 'SodexoCultura',
- // 'sodexogift' => 'SodexoGift',
- // 'sodexopremium' => 'SodexoPremium',
- // 'sodexorefeicao' => 'SodexoRefeicao',
- // 'sodexocombustivel' => 'SodexoCombustivel',
- // 'vr' => 'VR',
- // 'alelo' => 'Alelo',
- 'banese' => 'Banese',
- 'cabal' => 'Cabal',
- );
- }
-
- public function get_voucher_flags_list()
- {
- return array(
- 'alelo' => 'Alelo',
- 'sodexoalimentacao' => 'SodexoAlimentacao',
- 'sodexocultura' => 'SodexoCultura',
- 'sodexogift' => 'SodexoGift',
- 'sodexopremium' => 'SodexoPremium',
- 'sodexorefeicao' => 'SodexoRefeicao',
- 'sodexocombustivel' => 'SodexoCombustivel',
- 'vr' => 'VR'
-
- );
- }
-
- public function set_settings($settings)
- {
- $this->_settings = ($settings) ? $settings : get_option($this->get_option_key());
- }
-
- public function get_settings()
- {
- return empty($this->_settings) ? array() : $this->_settings;
- }
-
- public function update_settings(array $settings)
- {
- update_option($this->get_option_key(), $settings);
-
- $this->set_settings($settings);
- }
-
- public function log()
- {
- return new \WC_Logger();
- }
-
- public function is_enabled()
- {
- return ('yes' === $this->__get('enabled'));
- }
-
- public function is_gateway_integration_type()
- {
- return (bool) $this->__get('is_gateway_integration_type');
- }
-
- public function is_enabled_logs()
- {
- return ('yes' === $this->__get('enable_logs'));
- }
-
- public function is_active_credit_card()
- {
- return ('yes' === $this->__get('enable_credit_card'));
- }
-
- public function is_allowed_save_credit_card()
- {
- return ('yes' === $this->__get('cc_allow_save'));
- }
-
- public function is_allowed_save_voucher_card()
- {
- return ('yes' === $this->__get('voucher_card_wallet'));
- }
-
- public function is_active_billet()
- {
- return ('yes' === $this->__get('enable_billet'));
- }
-
- public function is_active_billet_and_card()
- {
- return ('yes' === $this->__get('multimethods_billet_card'));
- }
-
- public function is_active_2_cards()
- {
- return ('yes' === $this->__get('multimethods_2_cards'));
- }
-
- public function is_active_pix()
- {
- return ('yes' === $this->__get('enable_pix'));
- }
-
- public function is_active_voucher()
- {
- return ('yes' === $this->__get('enable_voucher'));
- }
-
- public function is_active_capture()
- {
- $operation_type = $this->__get('cc_operation_type');
-
- return intval($operation_type) === 1 ? false : true;
- }
-
- public function is_active_multicustomers()
- {
- return ('yes' === $this->__get('multicustomers'));
- }
-
- public function is_valid_key($key)
- {
- return isset($this->_fields[$key]);
- }
-
- public function isAntifraudEnabled()
- {
- return ($this->__get('antifraud_enabled') === 'yes' ? true : false);
- }
-
- public function isInstallmentsDefaultConfig()
- {
- return ($this->__get('cc_installment_type') === Gateway::CC_TYPE_BY_FLAG ? false : true);
- }
-
- public function isCardStatementDescriptor()
- {
- return $this->__get('cc_soft_descriptor');
- }
-
- public function isVoucherStatementDescriptor()
- {
- return $this->__get('voucher_soft_descriptor');
- }
-
- public function isHubEnabled()
- {
- return !empty($this->__get('hub_install_id'));
- }
-
- /**
- * Get the secret key according to the environment
- *
- * @return string
- */
- public function get_secret_key()
- {
- return $this->__get($this->is_sandbox() ? 'sandbox_secret_key' : 'production_secret_key');
- }
-
- /**
- * Get the public key according to the environment
- *
- * @return string
- */
- public function get_public_key()
- {
- return $this->__get($this->is_sandbox() ? 'sandbox_public_key' : 'production_public_key');
- }
-
- public function is_sandbox()
- {
- return ($this->__get('environment') === 'sandbox');
- }
-
- public function get_active_tab()
- {
- switch (Utils::get('tab')) {
- case 'creditCard':
- return 1;
-
- case 'boleto':
- return 2;
-
- case 'pix':
- return 3;
-
- case 'billetAndCard':
- return 4;
-
- case '2cards':
- return 5;
-
- case 'voucher':
- return 6;
-
- default:
- return 0;
- }
- }
-
- public function getCardOperationForCore()
- {
- return ($this->is_active_capture() ? 'auth_and_capture' : 'auth_only');
- }
-
- public static function get_instance($settings = false)
- {
- if (is_null(self::$_instance)) {
- self::$_instance = new self($settings);
- }
-
- return self::$_instance;
- }
-}
diff --git a/src/Resource/Base.php b/src/Resource/Base.php
index 586bce65..cc960dde 100644
--- a/src/Resource/Base.php
+++ b/src/Resource/Base.php
@@ -6,15 +6,13 @@
exit(0);
}
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
use Unirest\Request;
+use Woocommerce\Pagarme\Model\Config;
abstract class Base
{
/**
- * @var \Woocommerce\Pagarme\Model\Setting
+ * @var \Woocommerce\Pagarme\Model\Config
*/
protected $settings;
@@ -25,7 +23,7 @@ abstract class Base
public function __construct($auth = true)
{
- $this->settings = Setting::get_instance();
+ $this->settings = new Config();
Request::verifyPeer(false);
Request::verifyHost(false);
@@ -42,7 +40,7 @@ public function __construct($auth = true)
*/
public function auth()
{
- Request::auth($this->settings->get_secret_key(), '');
+ Request::auth($this->settings->getSecretKey(), '');
}
/**
diff --git a/templates/myaccount/wallet.php b/templates/myaccount/wallet.php
index c97c9a8f..46a073a6 100644
--- a/templates/myaccount/wallet.php
+++ b/templates/myaccount/wallet.php
@@ -5,7 +5,6 @@
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Model\Customer;
-use Woocommerce\Pagarme\Model\Setting;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Account;
From 232a5c27d0057292f6c80f95a82f59b7bb29bc45 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 14 Apr 2023 14:10:19 -0300
Subject: [PATCH 110/156] delete deprecated Model/Settings
---
src/Core.php | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/Core.php b/src/Core.php
index 29916bf3..e160d68c 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -54,7 +54,6 @@ public static function redirect_on_activate()
public static function initialize()
{
$controllers = array(
- 'Config',
'Checkout',
'Webhooks',
'Hub',
From 4fc01496df5ab74277edaa408daad300705fcc0b Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Mon, 17 Apr 2023 10:13:39 -0300
Subject: [PATCH 111/156] Retirada do Settings.php e suas dependencias
---
src/Concrete/WoocommerceCoreSetup.php | 8 --------
src/Controller/Checkout.php | 8 +++-----
src/Controller/Gateways/CreditCard.php | 25 +++++++++++++++++++++++--
src/Controller/Gateways/Pix.php | 2 +-
src/Controller/Orders.php | 6 +++---
src/Controller/Webhooks.php | 10 +++++-----
src/Core.php | 1 -
src/Helper/Utils.php | 4 ++--
src/Model/Account.php | 4 ++--
src/Model/Charge.php | 3 ---
src/Model/Checkout.php | 4 ----
src/Model/Config.php | 6 ++++++
src/Model/Gateway.php | 4 ----
src/Model/Order.php | 6 +-----
src/Resource/Base.php | 10 ++++------
templates/myaccount/wallet.php | 1 -
16 files changed, 50 insertions(+), 52 deletions(-)
diff --git a/src/Concrete/WoocommerceCoreSetup.php b/src/Concrete/WoocommerceCoreSetup.php
index f2c2ca75..20579b10 100644
--- a/src/Concrete/WoocommerceCoreSetup.php
+++ b/src/Concrete/WoocommerceCoreSetup.php
@@ -8,16 +8,8 @@
use Pagarme\Core\Kernel\Services\MoneyService;
use Pagarme\Core\Kernel\ValueObjects\CardBrand;
use Pagarme\Core\Kernel\ValueObjects\Configuration\CardConfig;
-use Woocommerce\Pagarme\Concrete\WoocommerceDatabaseDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommerceDataService;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformCreditmemoDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformInvoiceDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformOrderDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformPaymentMethodDecorator;
-use Woocommerce\Pagarme\Concrete\WoocommercePlatformProductDecorator;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Config;
-use Woocommerce\Pagarme\Model\Setting;
final class WoocommerceCoreSetup extends AbstractModuleCoreSetup
{
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index f56bd0ef..073d3e02 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -8,13 +8,11 @@
use Woocommerce\Pagarme\Controller\Gateways\AbstractGateway;
use Woocommerce\Pagarme\Model\CardInstallments;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Customer;
-use Woocommerce\Pagarme\Model\Gateway;
-use Woocommerce\Pagarme\Model\Setting;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model;
-use Woocommerce\Pagarme\Controller\Orders;
use WC_Order;
@@ -266,11 +264,11 @@ private function validate_amount_2_cards($fields, WC_Order $wc_order)
private function validate_brands($fields)
{
- $setting = Setting::get_instance();
+ $config = new Config();
$brand1 = Utils::get_value_by($fields, 'brand');
$brand2 = Utils::get_value_by($fields, 'brand2');
- $flags = $setting->cc_flags;
+ $flags = $config->getCcFlags;
if (empty($flags)) {
return;
diff --git a/src/Controller/Gateways/CreditCard.php b/src/Controller/Gateways/CreditCard.php
index c3b9e9f4..c4011a45 100644
--- a/src/Controller/Gateways/CreditCard.php
+++ b/src/Controller/Gateways/CreditCard.php
@@ -13,6 +13,8 @@
use Woocommerce\Pagarme\Model\Config\Source\Yesno;
use Woocommerce\Pagarme\Model\Gateway;
+use Woocommerce\Pagarme\Model\Payment\CreditCard\Brands;
+use Woocommerce\Pagarme\Model\Payment\CreditCard\BrandsInterface;
defined('ABSPATH') || exit;
@@ -144,7 +146,7 @@ public function field_cc_flags()
'title' => __('Card Brands', 'woo-pagarme-payments'),
'select_buttons' => false,
'class' => 'wc-enhanced-select',
- 'options' => $this->model->settings->get_flags_list(),
+ 'options' => $this->getBrandsList(),
'custom_attributes' => array(
'data-field' => 'flags-select',
'data-element' => 'flags-select',
@@ -316,7 +318,7 @@ public function generate_installments_by_flag_html($key, $data)
$data = wp_parse_args($data, $defaults);
$value = (array) $this->get_option($key, array());
- $flags = $this->model->settings->get_flags_list();
+ $flags = $this->getBrandsList();
ob_start();
@@ -392,4 +394,23 @@ public function validate_installments_by_flag_field($key, $value)
}
return $value;
}
+
+ public function getBrandsList()
+ {
+ //Some brands are hidden for PSP
+ return array(
+ 'visa' => 'Visa',
+ 'mastercard' => 'MasterCard',
+ 'amex' => 'Amex',
+ 'hipercard' => 'HiperCard',
+ 'diners' => 'Diners',
+ 'elo' => 'Elo',
+ 'discover' => 'Discover',
+ 'aura' => 'Aura',
+ 'jcb' => 'JCB',
+ 'credz' => 'Credz',
+ 'banese' => 'Banese',
+ 'cabal' => 'Cabal',
+ );
+ }
}
diff --git a/src/Controller/Gateways/Pix.php b/src/Controller/Gateways/Pix.php
index 69f02789..c052762a 100644
--- a/src/Controller/Gateways/Pix.php
+++ b/src/Controller/Gateways/Pix.php
@@ -58,7 +58,7 @@ public function field_pix_additional_data()
'title' => __('Additional information', 'woo-pagarme-payments'),
'description' => __('Set of key and value used to add information to the generated pix. This will be visible to the buyer during the payment process.', 'woo-pagarme-payments'),
'desc_tip' => true,
- 'type' => 'pix_additional_data',
+// 'type' => 'pix_additional_data',
];
}
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index 43411463..1395e8a6 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -9,7 +9,7 @@
use Woocommerce\Pagarme\Block\Adminhtml\Sales\Order as BlockOrder;
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Model\Order;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Concrete\WoocommerceCoreSetup;
use Woocommerce\Pagarme\Concrete\WoocommercePlatformOrderDecorator;
use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup;
@@ -26,8 +26,8 @@ class Orders
public function __construct(
BlockOrder $blockOrder = null
) {
- $this->settings = Setting::get_instance();
- $this->debug = $this->settings->is_enabled_logs();
+ $this->settings = new Config();
+ $this->debug = $this->settings->getData('enable_logs');
$this->blockOrder = $blockOrder ?? new BlockOrder;
add_action('on_pagarme_order_paid', array($this, 'set_order_paid'), 20, 2);
add_action('on_pagarme_order_created', array($this, 'set_order_created'), 20, 2);
diff --git a/src/Controller/Webhooks.php b/src/Controller/Webhooks.php
index 547acef4..560003ec 100644
--- a/src/Controller/Webhooks.php
+++ b/src/Controller/Webhooks.php
@@ -8,17 +8,17 @@
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Core;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Order;
-use Woocommerce\Pagarme\Model\Setting;
use Exception;
class Webhooks
{
- private $settings;
+ private $config;
public function __construct()
{
- $this->settings = Setting::get_instance();
+ $this->config = new Config();
add_action('woocommerce_api_' . Core::get_webhook_name(), array($this, 'handle_requests'));
}
@@ -27,10 +27,10 @@ public function handle_requests()
$body = Utils::get_json_post_data();
if (empty($body)) {
- $this->settings->log()->add('woo-pagarme', 'Webhook Received: empty body!');
+ $this->config->log()->add('woo-pagarme', 'Webhook Received: empty body!');
return;
}
- $this->settings->log()->add('woo-pagarme', 'Webhook Received: ' . json_encode($body, JSON_PRETTY_PRINT));
+ $this->config->log()->add('woo-pagarme', 'Webhook Received: ' . json_encode($body, JSON_PRETTY_PRINT));
$event = $this->sanitize_event_name($body->type);
diff --git a/src/Core.php b/src/Core.php
index a80f7f62..16dbd7c9 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -7,7 +7,6 @@
}
use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
class Core
{
diff --git a/src/Helper/Utils.php b/src/Helper/Utils.php
index b46432bd..d6650316 100644
--- a/src/Helper/Utils.php
+++ b/src/Helper/Utils.php
@@ -7,7 +7,7 @@
}
use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Model\Setting;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Order;
use WC_Order;
@@ -479,7 +479,7 @@ public static function is_cnpj($cnpj = null)
*/
public static function get_option_key()
{
- $settings = Setting::get_instance();
+ $settings = new Config();
return $settings->get_option_key();
}
diff --git a/src/Model/Account.php b/src/Model/Account.php
index d20d5af4..8c8e8f0e 100644
--- a/src/Model/Account.php
+++ b/src/Model/Account.php
@@ -10,12 +10,12 @@
class Account
{
- private $setting;
+ private $config;
const WALLET_ENDPOINT = 'zff3yg2have4pcw';
public function __construct()
{
- $this->setting = Setting::get_instance();
+ $this->config = new Config();
}
}
diff --git a/src/Model/Charge.php b/src/Model/Charge.php
index d11bd518..572a3109 100644
--- a/src/Model/Charge.php
+++ b/src/Model/Charge.php
@@ -8,9 +8,6 @@
use Pagarme\Core\Webhook\Factories\WebhookFactory;
use Pagarme\Core\Webhook\Services\ChargeHandlerService;
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
use WC_Order;
class Charge
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 39435250..26b0c2f8 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -28,9 +28,6 @@
class Checkout
{
- /** @var Setting|null */
- private $setting;
-
/** @var Config */
private $config;
@@ -65,7 +62,6 @@ public function __construct(
$wooOrderRepository = new WooOrderRepository;
}
$this->config = $config;
- $this->setting = Setting::get_instance();
$this->orders = $orders;
$this->gateway = $gateway;
$this->wooOrderRepository = $wooOrderRepository;
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 153c8d17..b78be8ec 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -232,4 +232,10 @@ public function getCcFlags()
}
return $ccFlags;
}
+
+ public function log()
+ {
+ return new \WC_Logger();
+ }
+
}
diff --git a/src/Model/Gateway.php b/src/Model/Gateway.php
index e223438f..cc8132fe 100644
--- a/src/Model/Gateway.php
+++ b/src/Model/Gateway.php
@@ -15,7 +15,6 @@
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Payment\PaymentInterface;
-use Woocommerce\Pagarme\Model\Setting;
// WooCommerce
use WC_Order;
@@ -41,15 +40,12 @@ class Gateway
*/
const CC_TYPE_BY_FLAG = 2;
- public $settings;
-
/** @var Config|null */
public $config;
public function __construct(
Config $config = null
) {
- $this->settings = Setting::get_instance();
if (!$config) {
$config = new Config();
}
diff --git a/src/Model/Order.php b/src/Model/Order.php
index 269d2f6d..0dc4f7b5 100644
--- a/src/Model/Order.php
+++ b/src/Model/Order.php
@@ -7,13 +7,9 @@
}
use Pagarme\Core\Kernel\ValueObjects\OrderStatus;
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
use Pagarme\Core\Kernel\Services\OrderService;
-
// WooCommerce
use WC_Order;
-use Woocommerce\Pagarme\Model\Setting;
class Order extends Meta
{
@@ -63,7 +59,7 @@ public function __construct($ID = false)
{
parent::__construct($ID);
$this->wc_order = new WC_Order($this->ID);
- $this->settings = Setting::get_instance();
+ $this->settings = new Config();
}
/** phpcs:enable */
diff --git a/src/Resource/Base.php b/src/Resource/Base.php
index 586bce65..34c44b11 100644
--- a/src/Resource/Base.php
+++ b/src/Resource/Base.php
@@ -6,15 +6,13 @@
exit(0);
}
-use Woocommerce\Pagarme\Core;
-use Woocommerce\Pagarme\Helper\Utils;
-use Woocommerce\Pagarme\Model\Setting;
use Unirest\Request;
+use Woocommerce\Pagarme\Model\Config;
abstract class Base
{
/**
- * @var \Woocommerce\Pagarme\Model\Setting
+ * @var \Woocommerce\Pagarme\Model\Config
*/
protected $settings;
@@ -25,7 +23,7 @@ abstract class Base
public function __construct($auth = true)
{
- $this->settings = Setting::get_instance();
+ $this->config = new Config();
Request::verifyPeer(false);
Request::verifyHost(false);
@@ -42,7 +40,7 @@ public function __construct($auth = true)
*/
public function auth()
{
- Request::auth($this->settings->get_secret_key(), '');
+ Request::auth($this->config->getSecretKey(), '');
}
/**
diff --git a/templates/myaccount/wallet.php b/templates/myaccount/wallet.php
index c97c9a8f..46a073a6 100644
--- a/templates/myaccount/wallet.php
+++ b/templates/myaccount/wallet.php
@@ -5,7 +5,6 @@
use Woocommerce\Pagarme\Core;
use Woocommerce\Pagarme\Model\Customer;
-use Woocommerce\Pagarme\Model\Setting;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Account;
From 4347f4ef83f0d74716424dba3fd5ad90e388c7d6 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Mon, 17 Apr 2023 16:51:28 -0300
Subject: [PATCH 112/156] Retirada do Settings.php e suas dependencias
---
src/Core.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/Core.php b/src/Core.php
index e160d68c..16dbd7c9 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -54,6 +54,7 @@ public static function redirect_on_activate()
public static function initialize()
{
$controllers = array(
+ 'Settings',
'Checkout',
'Webhooks',
'Hub',
From 6b4bfea6300df15d4bb84dc706159227fbb668d9 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Tue, 18 Apr 2023 08:49:34 -0300
Subject: [PATCH 113/156] :sparkles: more translates
---
languages/woo-pagarme-payments-pt_BR.mo | Bin 21939 -> 22087 bytes
languages/woo-pagarme-payments-pt_BR.po | 11 ++++++++++-
2 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/languages/woo-pagarme-payments-pt_BR.mo b/languages/woo-pagarme-payments-pt_BR.mo
index 31bfdadb837fdb70bf821bfcecf2d945f1af5531..0bf42bab281918c5d7e08b7747fca54241fd5aca 100644
GIT binary patch
delta 5841
zcmYk=33!cH9>?*Mo86uuL@co+BDP3^Al8HsThvbN!B9epT7s)(imIheEmNxY#)z7_
zwGC5d!o;+yBc=-mGeM{J)G$g7{r>KI@;rT?{_f|TbMJlM^Zw6yZ#?zv@hQyrabF4b
zTWdIieT=DznL);kp`BkzqsGLA8B+mUU~BAzE}Vmbm}B2xj5X-Liyd(c&*TTGn`srk{qoKo*wAw=ftt
zU{&0PL+~*AVMw?!{#@UL(a?ozVnwWvWii2ycSIGVn|*&U`qQ6?y3kbg#T?Z4+^8E^
zfnD%3)cJiVPaO}Yv
z@EJD3mMm}_jzXPp4Yt5d*c8uVIeb==`m2P&wVV@GLtUsjs${9CQujoCp`RTeiCWX~
zs7mCZ_Rb1qd5s4((KD#?U%^nkV|{_zOQE%?zcyENZD;1`sM2Ml?r^c~ud;rCxNEwPQs&@k5P4bBCrUxXG)NLXME~8dm{qXZ-sh4165J?7#f;UmK|7vERT5yRhf@b
zcUWY-g}RW7H+83xs5=>gD)|&Uz7V_9KZvpT0<{NX8}J)|FC$CiHVbK}q;KOP+=-gu
zh$yE5S*Xg)Lsei2`r#Q=rOu(2>;h^p{DA%OCuGB$UeV4|FcEc~#i-A3^7h^Q(9qBa
zPoidc6}4$X8agGagPL&@I7}e;exa`%vdQ
ziGldFegASS>+jFNEe6V9iS=hx2?HpDtclu$@u+bj3Rr3cwKhVb~XA
zP@8fNCgA(XSIk*#fEr{@CJI&hK{%VoWE65EZu4zR{xQHC-=jXzfck01O;LY*l29}4
zi^(_(6LCN4j{bvM<9nzHm*-bWo3JVBvF?VP+KfRh$$C_!i!g@ko9}4o7tMzS)NZYV
z+H{GiHBZM#oQ0vd4)v7mMt$CcBk?rq#0}dx6KiTsL{+w(wU-?qp+46)nKZ(27ODcP
zQ9r>OP^CYBmGKBNSMwzfM1O9_yPGkFekN*SD^ZWxdi(x|c03PNq5W7Li_onT+@_&B
zduZPXWJ{|biKT~^26B&joc@}C3R-!KW9+t&TI1ckro3$M4rtd{qo1<RbW1H6J|APH-CXz^AgmW`ge5pN*LCn-vo8Rbku~$
zqi!GVm9}$;NoxhgyFdKEpZ=jZH8EQiAH8gtD*nxxa0ltDgx;X!^IDopdu_?}p7GXI3Rj517
z!`fJYx}#!L=^tYl`lUMk2-FhCU|mc_o-((YKtm;;kGg}k$Q;Zu=L6cmyLI?r(<
zr21wQ>hqhi0iHsBmCY?w<*IdaCKiLA&`(2M=LxFfp=tV@n=jKC!$3>)!}S=5n^3!V
z2kLKw2Zvw*>P~8QcT7T^cmS%@Q!yHIuqJN9L_BWae~6l(s|VHK`ld3CW|)kcz$+Ms
z(=hGonUeuZ`L0&0R!Fc5>&oqh;v^VY>k9D%CTLe%Eoj^5}0AdUJA97mn-
z8ftU+_H-^-4K<-QsI{Jqjc_??!X7Mxhf!-@V7+Ml5w$0RdO1s36}5L_dr^Nix-y_m
zHX0k^LR2Ytp=SE2eZLU3b~jL)@G+{yA?)BFY=)XZYuoRGW$6z_O>i9Qds(O@Th^QU
z>yEZEpwgW{o!~U;Z@^WI!AGcx)b8Wh0#&J0T!fjZCAfi_&?8g@L-`Y_@o3aiwz9TI
zU;3$T8oJ}|$dhKKqn=+6w!&|$r%7?##c#(dUmz-b3`=}d>
z>F-n`4*lsTqn6Iyg@*1l4J+UX)Cs3pm!W=`cAy@^W2hxNhbrkEROugMESdq%4K+qp
ztUm_h1Wd!}7>S3G3b@S$8s!r9aBPbUP3w-vPftPAOB6
z0+`$6Wm1k@B|2`AdnBHGK{}EjNE+E7QxKZ%Zc9K{zBJv^8@dpR<8|3%M{E4t7%u=G`w`4jg;QHS6UWM9`I?j=Q6KzZ#+OZqRB=R}Y
z@hKTk^nD$wkd8zL@9V#KeMAySOTxoqh7%osC9Ifn2T-%cH1tE!l<0S$m}v89opZ=@
zQkG~3|N79zolRc<)!=E{*6)M%jgDy!=4Wh1&X5D-l;*#NhK^(8D^funj`n1Zx5dBl
zupfC$-XvOgA1yXVE@|Oyv9lT5NBbwTmPC;|WFz50@*dihm2LZfs^4zg5wDReuC#;yP@9YE|DxTcshzIh0T=y&sAB|)BVUuvB$Mpa`u&CIi1fZX
zFWqcA5Z@;|$PnVo347pw$$e6Kd~6%v;3kqz&Xe~@5*bSLyw4(f+H`Cs?yBCV^UM#U
zT|{<~1|*1!W#jLOj*$-D*F(Hkvi%r*iTsglvt!$>rMzt$LD+=UC52l5>ondWGstoB
zJ*h~ZkM8_wjGwDJekfUTj8ANm(b}%Vge_uND?ZB6K
ziBut@$pBJ%JfX3IEF%-i|49kakxxD%Pt~zU^U{WO3BF6pkYF;Ce5>`>F~Pwsunxu(
z#NYNs7`Z?`BV$SF@z6Gw;|<$hh%ZQQ+h30-ZCm`!wuer(jZxT`yhWzkvCBAyTqARd
ziQM&?XU+ps)WQ0J`7NOe6Is}FJcd0Vj&
zGpYwBMaCtyO-%A^Pl$1qVK}?s!1$RaKKJ#3RXtZ*K6C|**VnQOw&&id9`3o8RNx9u
bnNhGib5iy+lY6yYcy3gWik^aYCE>pS@6&8N
delta 5723
zcmZYD33OD|9mnyT1dU?{whrO^9j=>b%
zjQ)5M>*E>J_3t77OjwjLb&PSFrgV}x(H>i2A?k~(urY4Hx>$+f___5OCUX1;b%Vrc
zV}daoYhVE~W-|c(}br!L$GHIo*ofu!5>
zxyU~=&>l}hEyZlqb(W%Tv;_ljJL-lWdJ!o+L%Jr7pEgt
zHYJ#jYp^Mvz?S$Bb)6Iz_;F0f=2(Qaa1Cl{HlwcNLEYzY1M06*UF3vHd>QqH8>sUS
zP;2PZ(5XNaYOf?At77`1209LPgIO4cORVcqd#4<=mp()d{1U2Sp^s62%`o;c=R`AW
z2I>a6sF{sMjeH_%W(zS5J*bL&iyCkO3oesU18;>IKrXh%;i%FtLoLl(Hyzzz6Kaji
zF$ecy0s6-oGaiTF4y;55Z;Iocy;6#78?ymfR6UbiN+uVt;Ig>ri{(6Xc%eN7T~POK>Xc!aW>!
zK{mVF+^3@o1T}F=6N#!o99F||s8UTtt=V)`rJlzDScaPU6=WY8zeMLov8d0d+v6P6
z=SHChI2(iY{J%*@C3+7v;!iONub~DI#({Qu6zX%i=!=6;B^`>IKryN^v+Qvx`g6Pn
zHISFF3zj4Q%q?D$xxa~aIUneT`k@$r8pv>D8<=^h3vaZ?705qxoEOdbK5A1&u(dVd
zuBc6&i+UOcSjSptVhzrhqMJ1^tLUhtZ=i0t2lafOMmDy&j+%K*7Fb53o{lE=xFhQG
zy;0X2g#kFlzCRPIbG!(Hu++M`8TD5QH*rGlMQy^PsM1|R&ESUBBs-h6E~+AFsLjOBA7p>Eum4JDhp>C~c=idwrY)JVIaHqAiP
zV^?UMfuS6~V2{_^;|dJod?jikM^H<73N?W{sO!eC^+PcQJEOY;9q%SXKTd2!m1q;z
z!MCt4evI0b;jNsRv_nprB22*b$URIYs`R&U29L=@)I_GXHKqg3N4>uvSsJ%FL`NgM
zh*{`QUE5$+)J&d5t*sk1(2c0gw-5C^pGLlFZljjM#jlb|TZlXuW<2VLY&mL^R$v4k
zKob$)Lj+Odbxxg{Uu_L(SkD)PRDSo*t_x)cdih^Db0nT46Nyx9?9tO=y}u
zzt|qXf~trI-MY{TI@)AsQKi0#nqe?oUN;QKn%Dpf(S=&mQq=d>q5hcc#6&!T_3;ks
z{SekwPgP@Vjrqs}V&-R2f4xz`3EkivGFfvOshWvr$LRbp)KfAR>)}+4!k19HehX@8
zc408?K~?4esv^fwmAHb8$vi}D+O&?;Uu!(PqqBxnP@7{uHpDfk8@_`Y@d?xn9-(H|
zx|4Im9Mp9Np`Mx|)Bxw8DqM!zBO6dpO*v9zbJ0zQC&bk6?0hgERr(>QQjSFa;+lo1
zJ+c)w!;7dH-$X6ZUDSYn!aNM^V$5J1i4*W`+=21g&cu$QuH(K=Cx*@g)J(&>I(r}$
zHKTk~=?gIuC)?x2s5LIbc&tEG?j)+@S5Oo1>E`^^bD`cZLS456+v@pWNr!5h!>BI=
zb$8b0aZKTOFsgJ5@G&gIUFbpGXiN{M-<0^quw8dx^XeO(2Xr{D{26zu_c~Ie+=&FoDau%
z?r&n~Xt%bGpUoYWKc~ad-$5@EU4&hxBsxP$O*2aWd+9eNlU35^AXy
zpa!%V-74u9beiHl)QDqyJC9WYYRyxvJ**>8dtw@DEuTZ}omJLdsHf)$CgC+yrNa6+
z1C2wy-?|U=*W=QU6WWA@s1nb`KwOI&z-#vSU98FRM;L_1P~SU?TC%&S2?ggll}kZ=
zzYS{h^+p$tMpbNS9`#pe11D6f3M|3ns3qu^?+j=(s)X}U=a-|_a+7r%`f*%=n(=Pr
zfimZ@5ytj){(B+YIuo@76>i)48k0E@R^V*Lj@ZP9Up_p``I3IlFXEH^otc%PDzP4`
z<5twtm7`|r!PQ~Cnb@4#eKDR&|T@D6G?K1D_n
z?f4L)rk~QwL{CLk<7dGfA&-bEr1pSxB3cTyzmq3OsGfg4Dr(=6h2EZ1a&@(t)aH;a
zM5UyH-Zq3+zV2nM)p$KDvO)Q`Ji8Od|KlJND$)
z$Tsl);d#lPE5hF7&pPIY%V9q`L9~2tlkMbF@-EpyZj&E~*1s!hLEKtXHSGblaH92@
zOkO10h}uQ+Z*^z~2>aFeapS`{mQ=N)bbdt+lGWrC2_S=s+V|u$!t(1s``q5$OW#Z-
zm&h>UA+HksD4iy19})K2|Fw;rSxeGLJ2IP8kO|}li6>QU8l9cw_axVQlKT77`3>1k
zvPcq{NB%<8CK5df_elg2Y?~!pjpmip1lH)|}6VlJy<3CjKb5f02uEc+k=Hz)2P1ciD~-Xa-f15x`^
z)dO6}!3^>OsX?mRQaWeIbL3ydmjV5ZYPCs6Z_jyI^o#!1U-ZAQ{XrNLqUeB@aV;}4+qClpv~h8|U7+8JyqM4x-DAQ$
S(=&GYuE@^{^kipMulHYyjZifJ
diff --git a/languages/woo-pagarme-payments-pt_BR.po b/languages/woo-pagarme-payments-pt_BR.po
index f3cad6cb..dbffaa5a 100644
--- a/languages/woo-pagarme-payments-pt_BR.po
+++ b/languages/woo-pagarme-payments-pt_BR.po
@@ -5,7 +5,7 @@ msgstr ""
"Project-Id-Version: WooCommerce Pagar.me Payments 1.0\n"
"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woo-pagarme-payments\n"
"POT-Creation-Date: 2018-06-22 13:58-0300\n"
-"PO-Revision-Date: 2023-04-10 09:46-0300\n"
+"PO-Revision-Date: 2023-04-18 08:48-0300\n"
"Last-Translator: Pagar.me\n"
"Language-Team: \n"
"Language: pt_BR\n"
@@ -944,9 +944,18 @@ msgstr "CARTÃO DE CRÉDITO"
msgid "CreditCard"
msgstr "Cartão de crédito"
+msgid "Credit Card"
+msgstr "Cartão de Crédito"
+
+msgid "2 Cards"
+msgstr "2 Cartões"
+
msgid "Amount"
msgstr "Total"
+msgid "Billet And Card"
+msgstr "Boleto e Cartão"
+
msgid "Pagar.me - Capture/Cancellation"
msgstr "Pagar.me - Captura/Cancelamento"
From c3c9cd3f14a215d140bf5cfec8ff9d6c08e11e12 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 18 Apr 2023 10:27:33 -0300
Subject: [PATCH 114/156] =?UTF-8?q?Corre=C3=A7=C3=A3o=20da=20MASK=20no=20a?=
=?UTF-8?q?dmin?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
assets/javascripts/admin/pagarme_payments.js | 8 +-
assets/javascripts/admin/pagarme_settings.js | 102 +++++++++----------
2 files changed, 52 insertions(+), 58 deletions(-)
diff --git a/assets/javascripts/admin/pagarme_payments.js b/assets/javascripts/admin/pagarme_payments.js
index 491b460e..7fc6ae7f 100644
--- a/assets/javascripts/admin/pagarme_payments.js
+++ b/assets/javascripts/admin/pagarme_payments.js
@@ -1,4 +1,4 @@
-(function ($) {
+( function ($) {
const installmentsTypeSelect = $('[data-element="installments-type-select"]');
const installmentsMax = $('[data-field="installments-maximum"]');
const installmentsInterest = $('[data-field="installments-interest"]');
@@ -7,8 +7,8 @@
const installmentsWithoutInterest = $('[data-field="installments-without-interest"]');
const installmentsInterestIncrease = $('[data-field="installments-interest-increase"]');
const flagsSelect = $('[data-element="flags-select"]');
- const ccInstallmentsByFlag = $("woocommerce_woo-pagarme-payments-credit-card_cc_installments_by_flag[max_installment][visa]");
+ $.jMaskGlobals.watchDataMask = true;
handleInstallmentFieldsVisibility(installmentsTypeSelect.val());
addEventListener();
@@ -103,10 +103,6 @@
flagsSelect.on('select2:selecting', function (event) {
setInstallmentsByFlags(event, false);
});
- ccInstallmentsByFlag.on('change', function (event) {
- alert('oi');
- maxInstallmentsNoInterest(event);
- });
};
}(jQuery)
diff --git a/assets/javascripts/admin/pagarme_settings.js b/assets/javascripts/admin/pagarme_settings.js
index bb69053b..fa686a61 100644
--- a/assets/javascripts/admin/pagarme_settings.js
+++ b/assets/javascripts/admin/pagarme_settings.js
@@ -1,56 +1,54 @@
/* globals jquery, ajaxurl, pagarme_settings */
-(function ($) {
+( function ($) {
+ $('.wc_gateways').on(
+ 'click',
+ '.wc-payment-gateway-method-toggle-enabled',
+ function () {
+ var $link = $(this),
+ $row = $link.closest('tr'),
+ $toggle = $link.find('.woocommerce-input-toggle');
- $('.wc_gateways').on(
- 'click',
- '.wc-payment-gateway-method-toggle-enabled',
- function () {
- var $link = $(this),
- $row = $link.closest('tr'),
- $toggle = $link.find('.woocommerce-input-toggle');
+ var data = {
+ action: 'woocommerce_toggle_gateway_enabled',
+ security: pagarme_settings.nonces.gateway_toggle,
+ gateway_id: $row.data('gateway_id'),
+ };
- var data = {
- action: 'woocommerce_toggle_gateway_enabled',
- security: pagarme_settings.nonces.gateway_toggle,
- gateway_id: $row.data('gateway_id'),
- };
+ $toggle.addClass('woocommerce-input-toggle--loading');
- $toggle.addClass('woocommerce-input-toggle--loading');
-
- $.ajax({
- url: ajaxurl,
- data: data,
- dataType: 'json',
- type: 'POST',
- success: function (response) {
- if (true === response.data) {
- $toggle.removeClass(
- 'woocommerce-input-toggle--enabled, woocommerce-input-toggle--disabled'
- );
- $toggle.addClass(
- 'woocommerce-input-toggle--enabled'
- );
- $toggle.removeClass(
- 'woocommerce-input-toggle--loading'
- );
- } else if (false === response.data) {
- $toggle.removeClass(
- 'woocommerce-input-toggle--enabled, woocommerce-input-toggle--disabled'
- );
- $toggle.addClass(
- 'woocommerce-input-toggle--disabled'
- );
- $toggle.removeClass(
- 'woocommerce-input-toggle--loading'
- );
- } else if ('needs_setup' === response.data) {
- window.location.href = $link.attr('href');
- }
- },
- });
-
- return false;
- }
- );
-
-})(jQuery);
+ $.ajax({
+ url: ajaxurl,
+ data: data,
+ dataType: 'json',
+ type: 'POST',
+ success: function (response) {
+ if (true === response.data) {
+ $toggle.removeClass(
+ 'woocommerce-input-toggle--enabled, woocommerce-input-toggle--disabled'
+ ).addClass(
+ 'woocommerce-input-toggle--enabled'
+ ).removeClass(
+ 'woocommerce-input-toggle--loading'
+ );
+ return;
+ }
+ if (false === response.data) {
+ $toggle.removeClass(
+ 'woocommerce-input-toggle--enabled, woocommerce-input-toggle--disabled'
+ ).addClass(
+ 'woocommerce-input-toggle--disabled'
+ ).removeClass(
+ 'woocommerce-input-toggle--loading'
+ );
+ return;
+ }
+ if ('needs_setup' === response.data) {
+ window.location.href = $link.attr('href');
+ }
+ },
+ });
+ return false;
+ }
+ );
+ }(jQuery)
+);
From 41e6868c86714d077b08a5aace95f70f09e08a8f Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Wed, 19 Apr 2023 23:48:52 -0300
Subject: [PATCH 115/156] :bug: convert values between woo config and
pagarme_core_config
---
src/Concrete/WoocommerceCoreSetup.php | 2 +-
src/Model/Config/PagarmeCoreConfigManagement.php | 9 +++++++++
2 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/src/Concrete/WoocommerceCoreSetup.php b/src/Concrete/WoocommerceCoreSetup.php
index 20579b10..5f42cda5 100644
--- a/src/Concrete/WoocommerceCoreSetup.php
+++ b/src/Concrete/WoocommerceCoreSetup.php
@@ -142,7 +142,7 @@ static private function fillWithCardConfig($dataObj, $storeConfig)
$dataObj->installmentsEnabled = true;
$dataObj->cardOperation = $storeConfig->getCardOperationForCore();
$dataObj->cardStatementDescriptor = $storeConfig->getIsCardStatementDescriptor();
- $dataObj->antifraudEnabled = $storeConfig->getAntifraudEnabled();
+ $dataObj->antifraudEnabled = (bool) $storeConfig->getAntifraudEnabled();
$dataObj->antifraudMinAmount = intval($storeConfig->getAntifraudMinValue());
$dataObj->saveCards = $storeConfig->getCcAllowSave();
$dataObj->saveVoucherCards = $storeConfig->getVoucherCardWallet();
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index d490fe12..0a2e1a72 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -151,6 +151,15 @@ public function convertDataSaveCards($datum)
return (bool) $datum;
}
+ /**
+ * @param $datum
+ * @return bool
+ */
+ public function convertDataAntifraudEnabled($datum)
+ {
+ return (bool) $datum;
+ }
+
/**
* @param $datum
* @return bool
From 41fff99868bb4010ff6d097c5e760b0b501f19d0 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 20 Apr 2023 00:23:40 -0300
Subject: [PATCH 116/156] Excesso de chamadas a API nos JS
---
.../front/checkout/model/multicustomers.js | 11 -----------
.../front/checkout/model/payment/card.js | 19 ++++---------------
.../checkout/model/payment/order-value.js | 19 ++++---------------
.../front/checkout/model/payment/pix.js | 11 -----------
src/Core.php | 3 +--
.../Config/PagarmeCoreConfigManagement.php | 5 +++++
templates/checkout/form/card.phtml | 6 +-----
templates/checkout/payment/2-cards.phtml | 12 +++++++++---
.../checkout/payment/billet-and-card.phtml | 13 ++++++++++---
templates/checkout/payment/credit-card.phtml | 7 +++++++
templates/checkout/payment/voucher.phtml | 6 ++++++
11 files changed, 47 insertions(+), 65 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/multicustomers.js b/assets/javascripts/front/checkout/model/multicustomers.js
index 050fd6db..623b256f 100644
--- a/assets/javascripts/front/checkout/model/multicustomers.js
+++ b/assets/javascripts/front/checkout/model/multicustomers.js
@@ -2,18 +2,7 @@ jQuery(function ($) {
const multiCustomerTarget = 'input[data-element=enable-multicustomers]';
const form = 'fieldset[data-pagarme-payment-element=multicustomers]'
window.pagarmeMultiCustomer = {
- started: false,
- isStarted: function (){
- if (!this.started){
- this.started = true;
- return false;
- }
- return true;
- },
start: function () {
- // if (this.isStarted()) {
- // return;
- // }
this.addEventListener();
},
addEventListener: function () {
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index dc6f9bf7..7cd08881 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -14,14 +14,6 @@ let brands = [];
let pagarmeCard = {
limitTokenize: 10,
canSubmit: false,
- started: false,
- isStarted: function (){
- if (!this.started){
- this.started = true;
- return false;
- }
- return true;
- },
haveCardForm: function (e) {
let elem = null;
if (e instanceof $) {
@@ -351,8 +343,8 @@ let pagarmeCard = {
}
return true;
},
- addEventListener: function () {
- $(cardNumberTarget).on('blur', function (e) {
+ addEventListener: function (paymentTarget) {
+ $(paymentTarget + ' ' + cardNumberTarget).on('blur', function (e) {
pagarmeCard.keyEventHandlerCard(e);
});
$("form.checkout").on(
@@ -368,12 +360,9 @@ let pagarmeCard = {
$('input[name="pagarme[voucher][cards][1][document-holder]"]').val($('#billing_cpf').val()).trigger('input');
},
- start: function () {
- // if (this.isStarted()) {
- // return;
- // }
+ start: function (cardNumberTarget) {
this.getCardsMethods();
this.getBrands();
- this.addEventListener();
+ this.addEventListener(cardNumberTarget);
},
};
diff --git a/assets/javascripts/front/checkout/model/payment/order-value.js b/assets/javascripts/front/checkout/model/payment/order-value.js
index 985c89b7..585ee627 100644
--- a/assets/javascripts/front/checkout/model/payment/order-value.js
+++ b/assets/javascripts/front/checkout/model/payment/order-value.js
@@ -2,19 +2,8 @@ const cardValueTarget = 'input[data-pagarmecheckout-element="order-value"]';
const firstCardValue = '[data-pagarmecheckout-card-num="1"]';
let pagarmeOrderValue = {
- started: false,
- isStarted: function () {
- if (!this.started) {
- this.started = true;
- return false;
- }
- return true;
- },
- start: function () {
- // if (this.isStarted()) {
- // return;
- // }
- this.addEventListener();
+ start: function (paymentTarget) {
+ this.addEventListener(paymentTarget);
},
fillAnotherInput: async function (e) {
let input = jQuery(e.currentTarget);
@@ -73,8 +62,8 @@ let pagarmeOrderValue = {
new swal(message);
}
},
- addEventListener: function () {
- jQuery(cardValueTarget).on('change', function (e) {
+ addEventListener: function (paymentTarget) {
+ $(paymentTarget + ' ' + cardValueTarget).on('change', function (e) {
pagarmeOrderValue.keyEventHandler(e);
});
},
diff --git a/assets/javascripts/front/checkout/model/payment/pix.js b/assets/javascripts/front/checkout/model/payment/pix.js
index 24038057..ba5705c7 100644
--- a/assets/javascripts/front/checkout/model/payment/pix.js
+++ b/assets/javascripts/front/checkout/model/payment/pix.js
@@ -1,18 +1,7 @@
const qrRawCodeTarget = '#pagarme-qr-code';
$ = jQuery;
let pagarmePix = {
- started: false,
- isStarted: function () {
- if (!this.started) {
- this.started = true;
- return false;
- }
- return true;
- },
start: function () {
- // if (this.isStarted()) {
- // return;
- // }
this.addEventListener();
},
addEventListener: function () {
diff --git a/src/Core.php b/src/Core.php
index 16dbd7c9..242ba155 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -148,11 +148,10 @@ public static function enqueue_scripts($type, $deps = array(), $localize_args =
self::filemtime("assets/javascripts/front/checkout/model/payment.js"),
true
);
- $x = self::get_localize_script_args();
wp_localize_script(
'pagarme-checkout-card',
'PagarmeGlobalVars',
- $x
+ self::get_localize_script_args()
);
}
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index d490fe12..ce3ccd7c 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -160,6 +160,11 @@ public function convertDataSaveVoucherCards($datum)
return (bool) $datum;
}
+ public function convertDataAntifraudEnabled($datum)
+ {
+ return (bool) $datum;
+ }
+
/**
* @param $datum
* @return GUID
diff --git a/templates/checkout/form/card.phtml b/templates/checkout/form/card.phtml
index 8a4cf70e..02e9f264 100644
--- a/templates/checkout/form/card.phtml
+++ b/templates/checkout/form/card.phtml
@@ -120,8 +120,4 @@ if (!function_exists('add_action')) {
-
+
diff --git a/templates/checkout/payment/2-cards.phtml b/templates/checkout/payment/2-cards.phtml
index f2a6bc5b..2d52651b 100644
--- a/templates/checkout/payment/2-cards.phtml
+++ b/templates/checkout/payment/2-cards.phtml
@@ -9,7 +9,7 @@
/** @var \Woocommerce\Pagarme\Block\Checkout\Payment\TwoCards $this */
-declare( strict_types=1 );
+declare(strict_types=1);
if (!function_exists('add_action')) {
exit(0);
@@ -27,7 +27,13 @@ if (!function_exists('add_action')) {
diff --git a/templates/checkout/payment/billet-and-card.phtml b/templates/checkout/payment/billet-and-card.phtml
index 9cc8f683..e987be92 100644
--- a/templates/checkout/payment/billet-and-card.phtml
+++ b/templates/checkout/payment/billet-and-card.phtml
@@ -9,7 +9,7 @@
/** @var \Woocommerce\Pagarme\Block\Checkout\Payment\BilletAndCard $this */
-declare( strict_types=1 );
+declare(strict_types=1);
if (!function_exists('add_action')) {
exit(0);
@@ -37,7 +37,14 @@ if (!function_exists('add_action')) {
]
)->toHtml() ?>
diff --git a/templates/checkout/payment/credit-card.phtml b/templates/checkout/payment/credit-card.phtml
index 46f3a557..733d1129 100644
--- a/templates/checkout/payment/credit-card.phtml
+++ b/templates/checkout/payment/credit-card.phtml
@@ -22,3 +22,10 @@ $this->createBlock(
'qty_cards' => $this->getQtyCards()
]
)->toHtml();
+?>
+
diff --git a/templates/checkout/payment/voucher.phtml b/templates/checkout/payment/voucher.phtml
index d0b3b6aa..9ff4c60b 100644
--- a/templates/checkout/payment/voucher.phtml
+++ b/templates/checkout/payment/voucher.phtml
@@ -23,3 +23,9 @@ if (!function_exists('add_action')) {
'qty_cards' => $this->getQtyCards()
]
)->toHtml() ?>
+
From 0b7c554dbcf8213795ad9ef7427db852bb418f46 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 20 Apr 2023 00:39:58 -0300
Subject: [PATCH 117/156] convertDataAntifraudEnabled
---
src/Model/Config/PagarmeCoreConfigManagement.php | 5 -----
1 file changed, 5 deletions(-)
diff --git a/src/Model/Config/PagarmeCoreConfigManagement.php b/src/Model/Config/PagarmeCoreConfigManagement.php
index 5efa7926..0a2e1a72 100644
--- a/src/Model/Config/PagarmeCoreConfigManagement.php
+++ b/src/Model/Config/PagarmeCoreConfigManagement.php
@@ -169,11 +169,6 @@ public function convertDataSaveVoucherCards($datum)
return (bool) $datum;
}
- public function convertDataAntifraudEnabled($datum)
- {
- return (bool) $datum;
- }
-
/**
* @param $datum
* @return GUID
From 48ee8d65ba0058a9d47f2f1cdab1a76dd81616f8 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Thu, 20 Apr 2023 12:15:06 -0300
Subject: [PATCH 118/156] :sparkles: update ecommerce-module-core and update
value price for totals
---
src/Model/CardInstallments.php | 1 +
.../Abstractions/AbstractModuleCoreSetup.php | 17 +++++++++--------
2 files changed, 10 insertions(+), 8 deletions(-)
diff --git a/src/Model/CardInstallments.php b/src/Model/CardInstallments.php
index d38b1e04..36dd176a 100644
--- a/src/Model/CardInstallments.php
+++ b/src/Model/CardInstallments.php
@@ -48,6 +48,7 @@ public function __construct(
*/
public function getInstallmentsByType($total, $flag = false)
{
+ $total = Utils::str_to_float($total);
$type = $this->config->getCcInstallmentType() ?? 1;
$maxInstallments = $this->config->getCcInstallmentsMaximum();
$minAmount = Utils::str_to_float($this->config->getCcInstallmentsMinAmount());
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php
index 576bdb6e..77702962 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php
@@ -87,27 +87,21 @@ protected static function setApiBaseUrl()
protected static function updateModuleConfiguration()
{
- $configurationRepository = new ConfigurationRepository;
-
static::loadSavedConfiguration();
-
$savedConfig = static::$moduleConfig;
static::$instance->loadModuleConfigurationFromPlatform();
static::$moduleConfig->setStoreId(static::getCurrentStoreId());
-
if (
$savedConfig !== null &&
($savedConfigId = $savedConfig->getId()) !== null
) {
static::$moduleConfig->setid($savedConfigId);
}
-
if (self::getDefaultConfigSaved() === null) {
static::$moduleConfig->setStoreId(static::getDefaultStoreId());
- $configurationRepository->save(static::$moduleConfig);
+ static::saveModuleConfig();
static::$moduleConfig->setStoreId(static::getCurrentStoreId());
}
-
if (
static::$moduleConfig->getStoreId() != static::getDefaultStoreId() &&
$savedConfig === null
@@ -116,8 +110,15 @@ protected static function updateModuleConfiguration()
static::$moduleConfig->setInheritAll(true);
static::$moduleConfig->setId(null);
}
+ static::saveModuleConfig();
+ }
- $configurationRepository->save(static::$moduleConfig);
+ protected static function saveModuleConfig()
+ {
+ if (strpos(static::$instance->getPlatformVersion(), 'Wordpress') === false) {
+ $configurationRepository = new ConfigurationRepository;
+ $configurationRepository->save(static::$moduleConfig);
+ }
}
protected static function loadSavedConfiguration()
From ea258fd65b459bc46ce1bd072039f2072174e167 Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Wed, 26 Apr 2023 17:45:19 -0300
Subject: [PATCH 119/156] :bug: fix remove card from wallet
---
.../javascripts/front/app/component-wallet.js | 67 --------------
assets/javascripts/front/my-account/wallet.js | 67 ++++++++++++++
src/Block/Account/Wallet.php | 87 +++++++++++++++++++
src/Controller/Accounts.php | 17 +++-
.../myaccount/{wallet.php => wallet.phtml} | 34 ++------
5 files changed, 174 insertions(+), 98 deletions(-)
delete mode 100644 assets/javascripts/front/app/component-wallet.js
create mode 100644 assets/javascripts/front/my-account/wallet.js
create mode 100644 src/Block/Account/Wallet.php
rename templates/myaccount/{wallet.php => wallet.phtml} (60%)
diff --git a/assets/javascripts/front/app/component-wallet.js b/assets/javascripts/front/app/component-wallet.js
deleted file mode 100644
index dc704086..00000000
--- a/assets/javascripts/front/app/component-wallet.js
+++ /dev/null
@@ -1,67 +0,0 @@
-MONSTER( 'Pagarme.Components.Wallet', function(Model, $, utils) {
-
- Model.fn.start = function() {
- this.addEventListener();
- };
-
- Model.fn.addEventListener = function() {
- this.click( 'remove-card' );
- };
-
- Model.fn._onClickRemoveCard = function(event) {
- event.preventDefault();
-
- swal({
- title : this.data.swal.confirm_title,
- text : this.data.swal.confirm_text,
- type : 'warning',
- showCancelButton : true,
- confirmButtonColor : this.data.swal.confirm_color,
- cancelButtonColor : this.data.swal.cancel_color,
- confirmButtonText : this.data.swal.confirm_button,
- cancelButtonText : this.data.swal.cancel_button,
- allowOutsideClick : false,
- }).then( this._request.bind( this, event.currentTarget.dataset.value ), function() {} );
- };
-
- Model.fn._request = function(cardId) {
- swal.showLoading();
-
- this.ajax({
- url : this.data.apiRequest,
- data : {
- card_id : cardId
- }
- });
- };
-
- Model.fn._done = function(response) {
- if ( response.success ) {
- this.successMessage( response.data );
- } else {
- this.failMessage( response.data );
- }
- };
-
- Model.fn._fail = function(jqXHR, textStatus, errorThrown) {
-
- };
-
- Model.fn.failMessage = function(message) {
- swal({
- type : 'error',
- html : message
- }).then(function() {});
- };
-
- Model.fn.successMessage = function(message) {
- swal({
- type : 'success',
- html : message,
- allowOutsideClick : false
- }).then(function(){
- window.location.reload(true);
- });
- };
-
-});
diff --git a/assets/javascripts/front/my-account/wallet.js b/assets/javascripts/front/my-account/wallet.js
new file mode 100644
index 00000000..541ac2ab
--- /dev/null
+++ b/assets/javascripts/front/my-account/wallet.js
@@ -0,0 +1,67 @@
+$ = jQuery
+const removeCard = '[data-action="remove-card"]'
+
+let pagarmeWallet = {
+start: function () {
+ this.addEventListener();
+},
+addEventListener: function () {
+ $(removeCard).click(function (e) {
+ pagarmeWallet._onClickRemoveCard(e);
+
+ });
+},
+_onClickRemoveCard: function (event) {
+ event.preventDefault();
+ swal({
+ title: dataSwal.confirm_title,
+ text: dataSwal.confirm_text,
+ type: 'warning',
+ showCancelButton: true,
+ confirmButtonColor: dataSwal.confirm_color,
+ cancelButtonColor: dataSwal.cancel_color,
+ confirmButtonText: dataSwal.confirm_button,
+ cancelButtonText: dataSwal.cancel_button,
+ allowOutsideClick: false,
+ }).then(this._request.bind(this, event.currentTarget.dataset.value), function () {
+ });
+ },
+_request: function (cardId) {
+ swal.showLoading();
+ $.ajax({
+ method: 'post',
+ url: apiRoute,
+ data: {
+ card_id: cardId
+ }
+ })
+ .done(this._done)
+},
+_done: function (response) {
+ if (response.success) {
+ pagarmeWallet.successMessage(response.data);
+ } else {
+ pagarmeWallet.failMessage(response.data);
+ }
+},
+_fail: function (jqXHR, textStatus, errorThrown) {
+},
+failMessage: function (message) {
+ swal({
+ type: 'error',
+ html: message
+ }).then(function () {
+ });
+},
+successMessage: function (message) {
+ swal({
+ type: 'success',
+ html: message,
+ allowOutsideClick: false
+ }).then(function () {
+ location.reload(true);
+ });
+},
+}
+
+pagarmeWallet.start();
\ No newline at end of file
diff --git a/src/Block/Account/Wallet.php b/src/Block/Account/Wallet.php
new file mode 100644
index 00000000..fb3e9899
--- /dev/null
+++ b/src/Block/Account/Wallet.php
@@ -0,0 +1,87 @@
+walletCards = $this->getCards();
+ parent::__construct();
+ $this->addDataToJs();
+ }
+
+ public function getCards()
+ {
+ $customer = new Customer(get_current_user_id());
+ return $customer->cards;
+ }
+
+ private function addDataToJs()
+ {
+ wp_localize_script(
+ 'pagarme_scripts_wallet',
+ 'apiRoute',
+ $this->getApiRoute()
+ );
+ wp_localize_script(
+ 'pagarme_scripts_wallet',
+ 'dataSwal',
+ $this->getSwalData()
+ );
+ }
+
+ private function getApiRoute()
+ {
+ return get_home_url(null, '/wc-api/' . Account::WALLET_ENDPOINT);
+ }
+
+ private function getSwalData()
+ {
+ $swalData = [
+ 'title' => __('Waiting...', 'woo-pagarme-payments'),
+ 'text' => __('We are processing your request.', 'woo-pagarme-payments'),
+ 'confirm_title' => __('Are you sure?', 'woo-pagarme-payments'),
+ 'confirm_text' => __('You won\'t be able to revert this!', 'woo-pagarme-payments'),
+ 'confirm_button' => __('Yes, delete it!', 'woo-pagarme-payments'),
+ 'cancel_button' => __('No, cancel!', 'woo-pagarme-payments'),
+ 'confirm_color' => '#3085d6',
+ 'cancel_color' => '#d33',
+ ];
+ return $swalData;
+ }
+}
diff --git a/src/Controller/Accounts.php b/src/Controller/Accounts.php
index 4ccb214f..712088f3 100644
--- a/src/Controller/Accounts.php
+++ b/src/Controller/Accounts.php
@@ -6,25 +6,31 @@
exit(0);
}
+use Woocommerce\Pagarme\Block\Account\Wallet;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Account;
use Woocommerce\Pagarme\Model\Customer;
use Pagarme\Core\Payment\Repositories\SavedCardRepository as CoreSavedCardRepository;
+use Woocommerce\Pagarme\Block\Template;
class Accounts
{
protected $wallet_endpoint;
protected $card_repository;
+ protected $template;
const WALLET_ENDPOINT = 'wallet-pagarme';
const OPT_WALLET_ENDPOINT = 'woocommerce_pagarme_wallet_endpoint';
- public function __construct()
+ public function __construct(
+ Template $template = null
+ )
{
+ $this->template = $template ?? new Template();
+
$this->wallet_endpoint = get_option(self::OPT_WALLET_ENDPOINT, self::WALLET_ENDPOINT);
$this->card_repository = new CoreSavedCardRepository();
-
add_action('init', array($this, 'add_endpoints'));
add_filter('woocommerce_account_settings', array($this, 'settings_account'));
add_filter('woocommerce_account_menu_items', array($this, 'menu_items'));
@@ -78,7 +84,10 @@ public function settings_account($settings)
public function wallet_content()
{
- Utils::get_template('templates/myaccount/wallet');
+ $this->template->createBlock(
+ \Woocommerce\Pagarme\Block\Account\Wallet::class,
+ 'pagarme-wallet'
+ )->toHtml();
}
public function remove_credit_card()
@@ -98,7 +107,7 @@ public function remove_credit_card()
foreach ($saved_cards as $saved_card) {
$saved_card_id = $saved_card->getPagarmeId()->getValue();
if ($saved_card_id === $card_id) {
- $this->remove_core_card($customer, $saved_card);
+ // $this->remove_core_card($customer, $saved_card);
wp_send_json_success(
__('Card removed successfully.', 'woo-pagarme-payments')
);
diff --git a/templates/myaccount/wallet.php b/templates/myaccount/wallet.phtml
similarity index 60%
rename from templates/myaccount/wallet.php
rename to templates/myaccount/wallet.phtml
index 46a073a6..013b0f3d 100644
--- a/templates/myaccount/wallet.php
+++ b/templates/myaccount/wallet.phtml
@@ -1,34 +1,15 @@
cards) :
- $api_route = get_home_url(null, '/wc-api/' . Account::WALLET_ENDPOINT);
- $swal_data = apply_filters(Core::tag_name('account_wallet_swal_data'), array(
- 'title' => __('Waiting...', 'woo-pagarme-payments'),
- 'text' => __('We are processing your request.', 'woo-pagarme-payments'),
- 'confirm_title' => __('Are you sure?', 'woo-pagarme-payments'),
- 'confirm_text' => __('You won\'t be able to revert this!', 'woo-pagarme-payments'),
- 'confirm_button' => __('Yes, delete it!', 'woo-pagarme-payments'),
- 'cancel_button' => __('No, cancel!', 'woo-pagarme-payments'),
- 'confirm_color' => '#3085d6',
- 'cancel_color' => '#d33',
- ));
+if ($this->walletCards) :
?>
-
- >
+
@@ -52,8 +33,7 @@
-
- cards as $card_id => $card) : ?>
+ walletCards as $card_id => $card) : ?>
@@ -82,7 +62,6 @@
-
From fd9ce616b08caad680eaa1a882e605da269425c1 Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Wed, 26 Apr 2023 17:48:15 -0300
Subject: [PATCH 120/156] fix indentation
---
assets/javascripts/front/my-account/wallet.js | 114 +++++++++---------
1 file changed, 57 insertions(+), 57 deletions(-)
diff --git a/assets/javascripts/front/my-account/wallet.js b/assets/javascripts/front/my-account/wallet.js
index 541ac2ab..8487da05 100644
--- a/assets/javascripts/front/my-account/wallet.js
+++ b/assets/javascripts/front/my-account/wallet.js
@@ -2,66 +2,66 @@ $ = jQuery
const removeCard = '[data-action="remove-card"]'
let pagarmeWallet = {
-start: function () {
- this.addEventListener();
-},
-addEventListener: function () {
- $(removeCard).click(function (e) {
- pagarmeWallet._onClickRemoveCard(e);
+ start: function () {
+ this.addEventListener();
+ },
+ addEventListener: function () {
+ $(removeCard).click(function (e) {
+ pagarmeWallet._onClickRemoveCard(e);
- });
-},
-_onClickRemoveCard: function (event) {
- event.preventDefault();
- swal({
- title: dataSwal.confirm_title,
- text: dataSwal.confirm_text,
- type: 'warning',
- showCancelButton: true,
- confirmButtonColor: dataSwal.confirm_color,
- cancelButtonColor: dataSwal.cancel_color,
- confirmButtonText: dataSwal.confirm_button,
- cancelButtonText: dataSwal.cancel_button,
- allowOutsideClick: false,
- }).then(this._request.bind(this, event.currentTarget.dataset.value), function () {
- });
+ });
+ },
+ _onClickRemoveCard: function (event) {
+ event.preventDefault();
+ swal({
+ title: dataSwal.confirm_title,
+ text: dataSwal.confirm_text,
+ type: 'warning',
+ showCancelButton: true,
+ confirmButtonColor: dataSwal.confirm_color,
+ cancelButtonColor: dataSwal.cancel_color,
+ confirmButtonText: dataSwal.confirm_button,
+ cancelButtonText: dataSwal.cancel_button,
+ allowOutsideClick: false,
+ }).then(this._request.bind(this, event.currentTarget.dataset.value), function () {
+ });
+ },
+ _request: function (cardId) {
+ swal.showLoading();
+ $.ajax({
+ method: 'post',
+ url: apiRoute,
+ data: {
+ card_id: cardId
+ }
+ })
+ .done(this._done)
},
-_request: function (cardId) {
- swal.showLoading();
- $.ajax({
- method: 'post',
- url: apiRoute,
- data: {
- card_id: cardId
+ _done: function (response) {
+ if (response.success) {
+ pagarmeWallet.successMessage(response.data);
+ } else {
+ pagarmeWallet.failMessage(response.data);
}
- })
- .done(this._done)
-},
-_done: function (response) {
- if (response.success) {
- pagarmeWallet.successMessage(response.data);
- } else {
- pagarmeWallet.failMessage(response.data);
- }
-},
-_fail: function (jqXHR, textStatus, errorThrown) {
-},
-failMessage: function (message) {
- swal({
- type: 'error',
- html: message
- }).then(function () {
- });
-},
-successMessage: function (message) {
- swal({
- type: 'success',
- html: message,
- allowOutsideClick: false
- }).then(function () {
- location.reload(true);
- });
-},
+ },
+ _fail: function (jqXHR, textStatus, errorThrown) {
+ },
+ failMessage: function (message) {
+ swal({
+ type: 'error',
+ html: message
+ }).then(function () {
+ });
+ },
+ successMessage: function (message) {
+ swal({
+ type: 'success',
+ html: message,
+ allowOutsideClick: false
+ }).then(function () {
+ location.reload(true);
+ });
+ },
}
pagarmeWallet.start();
\ No newline at end of file
From a734f61b0fb04f47e49a5789a6848047ac1f54da Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Wed, 26 Apr 2023 17:49:54 -0300
Subject: [PATCH 121/156] remove unnecessary comment
---
src/Controller/Accounts.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controller/Accounts.php b/src/Controller/Accounts.php
index 712088f3..f6edf3f8 100644
--- a/src/Controller/Accounts.php
+++ b/src/Controller/Accounts.php
@@ -107,7 +107,7 @@ public function remove_credit_card()
foreach ($saved_cards as $saved_card) {
$saved_card_id = $saved_card->getPagarmeId()->getValue();
if ($saved_card_id === $card_id) {
- // $this->remove_core_card($customer, $saved_card);
+ $this->remove_core_card($customer, $saved_card);
wp_send_json_success(
__('Card removed successfully.', 'woo-pagarme-payments')
);
From 2abb240fe7616fc95cf0ae3702d9630507c6da2e Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Fri, 28 Apr 2023 11:11:21 -0300
Subject: [PATCH 122/156] :bug: fix payment_method_title translation
---
src/Block/Order/PaymentDetails.php | 4 +++-
src/Controller/Gateways/AbstractGateway.php | 2 ++
src/Model/Checkout.php | 8 ++------
3 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/Block/Order/PaymentDetails.php b/src/Block/Order/PaymentDetails.php
index 8a2b0e97..62d84fec 100644
--- a/src/Block/Order/PaymentDetails.php
+++ b/src/Block/Order/PaymentDetails.php
@@ -49,7 +49,9 @@ public function getCharges()
public function isPagarmePaymentMethod(Order $order)
{
if (property_exists($order, 'wc_order')) {
- return $order->wc_order->get_payment_method() === AbstractGateway::PAGARME;
+ $paymentMethod = $order->wc_order->get_payment_method();
+ return $paymentMethod === AbstractGateway::PAGARME ||
+ str_starts_with($paymentMethod, AbstractGateway::WC_PAYMENT_PAGARME);
}
return false;
}
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index affca12e..0643af1a 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -40,6 +40,8 @@ abstract class AbstractGateway extends WC_Payment_Gateway
/** @var string */
const PAGARME = 'Pagar.me';
+ const WC_PAYMENT_PAGARME = 'woo-pagarme-payments';
+
/** @var string */
const PAYMENT_OPTION_UPDATE_SLUG = 'woocommerce_update_options_payment_gateways_';
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 26b0c2f8..b888e383 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -74,14 +74,14 @@ public function validateCheckout($fields, $errors)
$fields['billing_number'] == 0 &&
!key_exists('billing_number_required', $errors->errors)
) {
- $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigatório.');
+ $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento É um campo obrigatório.');
}
if (
$fields['ship_to_different_address'] &&
$fields['shipping_number'] == 0 &&
!key_exists('shipping_number_required', $errors->errors)
) {
- $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigatório.');
+ $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega É um campo obrigatório.');
}
}
@@ -118,12 +118,8 @@ public function process(WC_Order $wc_order = null, string $type = CheckoutTypes:
$fields
);
- $paymentInstance = $this->gateway->getPaymentInstace($fields['payment_method']);
-
$order = new Order($wc_order->get_id());
$order->payment_method = $fields['payment_method'];
- $order->update_meta('_payment_method_title', $paymentInstance->getName());
- $order->update_meta('_payment_method', AbstractGateway::PAGARME);
WC()->cart->empty_cart();
if ($response) {
$order->transaction_id = $response->getPagarmeId()->getValue();
From e31c41a57f512d6f866321a7e9e20683a830b505 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 28 Apr 2023 19:57:13 -0300
Subject: [PATCH 123/156] Revert ":bug: fix payment_method_title translation"
This reverts commit 2abb240fe7616fc95cf0ae3702d9630507c6da2e.
---
src/Block/Order/PaymentDetails.php | 4 +---
src/Controller/Gateways/AbstractGateway.php | 2 --
src/Model/Checkout.php | 8 ++++++--
3 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/Block/Order/PaymentDetails.php b/src/Block/Order/PaymentDetails.php
index 62d84fec..8a2b0e97 100644
--- a/src/Block/Order/PaymentDetails.php
+++ b/src/Block/Order/PaymentDetails.php
@@ -49,9 +49,7 @@ public function getCharges()
public function isPagarmePaymentMethod(Order $order)
{
if (property_exists($order, 'wc_order')) {
- $paymentMethod = $order->wc_order->get_payment_method();
- return $paymentMethod === AbstractGateway::PAGARME ||
- str_starts_with($paymentMethod, AbstractGateway::WC_PAYMENT_PAGARME);
+ return $order->wc_order->get_payment_method() === AbstractGateway::PAGARME;
}
return false;
}
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 0643af1a..affca12e 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -40,8 +40,6 @@ abstract class AbstractGateway extends WC_Payment_Gateway
/** @var string */
const PAGARME = 'Pagar.me';
- const WC_PAYMENT_PAGARME = 'woo-pagarme-payments';
-
/** @var string */
const PAYMENT_OPTION_UPDATE_SLUG = 'woocommerce_update_options_payment_gateways_';
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index b888e383..26b0c2f8 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -74,14 +74,14 @@ public function validateCheckout($fields, $errors)
$fields['billing_number'] == 0 &&
!key_exists('billing_number_required', $errors->errors)
) {
- $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento É um campo obrigatório.');
+ $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigatório.');
}
if (
$fields['ship_to_different_address'] &&
$fields['shipping_number'] == 0 &&
!key_exists('shipping_number_required', $errors->errors)
) {
- $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega É um campo obrigatório.');
+ $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigatório.');
}
}
@@ -118,8 +118,12 @@ public function process(WC_Order $wc_order = null, string $type = CheckoutTypes:
$fields
);
+ $paymentInstance = $this->gateway->getPaymentInstace($fields['payment_method']);
+
$order = new Order($wc_order->get_id());
$order->payment_method = $fields['payment_method'];
+ $order->update_meta('_payment_method_title', $paymentInstance->getName());
+ $order->update_meta('_payment_method', AbstractGateway::PAGARME);
WC()->cart->empty_cart();
if ($response) {
$order->transaction_id = $response->getPagarmeId()->getValue();
From 36a72bbb4320865117d267ede9fb361af45b27e4 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 2 May 2023 10:30:25 -0300
Subject: [PATCH 124/156] create general configuration default
---
src/Controller/Accounts.php | 2 +-
src/Controller/Gateways/AbstractGateway.php | 2 +-
src/Controller/Gateways/CreditCard.php | 19 ++++++----
src/Controller/Gateways/Pix.php | 40 +++++++++++++++++++--
src/Controller/Gateways/Voucher.php | 2 ++
src/Controller/Settings.php | 40 ++++++++++-----------
6 files changed, 74 insertions(+), 31 deletions(-)
diff --git a/src/Controller/Accounts.php b/src/Controller/Accounts.php
index f6edf3f8..ce7fb40c 100644
--- a/src/Controller/Accounts.php
+++ b/src/Controller/Accounts.php
@@ -28,7 +28,7 @@ public function __construct(
)
{
$this->template = $template ?? new Template();
-
+
$this->wallet_endpoint = get_option(self::OPT_WALLET_ENDPOINT, self::WALLET_ENDPOINT);
$this->card_repository = new CoreSavedCardRepository();
add_action('init', array($this, 'add_endpoints'));
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index affca12e..78a0111f 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -256,7 +256,7 @@ protected function gateway_form_fields()
* @return bool
*/
public function isGatewayType(){
- return $this->model->config->getIsGatewayIntegrationType();
+ return ($this->model->config->getIsGatewayIntegrationType() === 'yes');
}
/**
diff --git a/src/Controller/Gateways/CreditCard.php b/src/Controller/Gateways/CreditCard.php
index c4011a45..2ba13771 100644
--- a/src/Controller/Gateways/CreditCard.php
+++ b/src/Controller/Gateways/CreditCard.php
@@ -87,7 +87,7 @@ public function field_cc_operation_type()
'type' => 'select',
'title' => __('Operation Type', 'woo-pagarme-payments'),
'class' => 'wc-enhanced-select',
- 'default' => 1,
+ 'default' => $this->config->getCcOperationType() ?? 1,
'options' => array(
1 => __('Authorize', 'woo-pagarme-payments'),
2 => __('Authorize and Capture', 'woo-pagarme-payments'),
@@ -107,6 +107,7 @@ public function field_cc_soft_descriptor()
'desc_tip' => __('Description that appears on the credit card bill.', 'woo-pagarme-payments'),
'description' => sprintf(__("Max length of %s characters.",
'woo-pagarme-payments'), $maxLength),
+ 'default' => $this->config->getData('cc_soft_descriptor') ?? '',
'custom_attributes' => array(
'data-field' => 'soft-descriptor',
'data-action' => 'soft-descriptor',
@@ -127,7 +128,7 @@ public function field_cc_allow_save()
'type' => 'select',
'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable card wallet', 'woo-pagarme-payments'),
- 'default' => Yesno::NO_VALUE,
+ 'default' => $this->config->getData('cc_allow_save') ?? strtolower(Yesno::NO),
'description' => __('Allows for cards to be saved for future purchases.', 'woo-pagarme-payments'),
'desc_tip' => true,
'custom_attributes' => array(
@@ -147,6 +148,7 @@ public function field_cc_flags()
'select_buttons' => false,
'class' => 'wc-enhanced-select',
'options' => $this->getBrandsList(),
+ 'default' => $this->config->getData('cc_flags') ?? '',
'custom_attributes' => array(
'data-field' => 'flags-select',
'data-element' => 'flags-select',
@@ -165,7 +167,7 @@ public function field_cc_installment_type()
'type' => 'select',
'class' => 'wc-enhanced-select',
'label' => __('Choose the installment configuration', 'woo-pagarme-payments'),
- 'default' => 1,
+ 'default' => $this->config->getData('cc_installment_type') ?? 1,
'options' => array(
Gateway::CC_TYPE_SINGLE => __('For all card brands', 'woo-pagarme-payments'),
Gateway::CC_TYPE_BY_FLAG => __('By card brand', 'woo-pagarme-payments'),
@@ -187,7 +189,7 @@ public function field_cc_installment_fields($field)
$installments['maximum'] = array(
'title' => __('Max number of installments', 'woo-pagarme-payments'),
'type' => 'select',
- 'default' => 12,
+ 'default' => $this->config->getData('cc_installments_maximum') ?? 12,
'options' => $this->model->get_installment_options(),
'custom_attributes' => array(
'data-field' => 'installments-maximum',
@@ -197,6 +199,7 @@ public function field_cc_installment_fields($field)
$installments['installment_min_amount'] = array(
'title' => __('Minimum installment amount', 'woo-pagarme-payments'),
'type' => 'text',
+ 'default' => $this->config->getData('cc_installments_min_amount') ?? '',
'description' => __('Defines the minimum value that an installment can assume', 'woo-pagarme-payments'),
'desc_tip' => true,
'placeholder' => '0.00',
@@ -210,6 +213,7 @@ public function field_cc_installment_fields($field)
$installments['interest'] = array(
'title' => __('Initial interest rate (%)', 'woo-pagarme-payments'),
'type' => 'text',
+ 'default' => $this->config->getData('cc_installments_interest') ?? '',
'description' => __('Interest rate applied starting with the first installment with interest.', 'woo-pagarme-payments'),
'desc_tip' => true,
'placeholder' => '0.00',
@@ -223,6 +227,7 @@ public function field_cc_installment_fields($field)
$installments['interest_increase'] = array(
'title' => __('Incremental interest rate (%)', 'woo-pagarme-payments'),
'type' => 'text',
+ 'default' => $this->config->getData('cc_installments_interest_increase') ?? '',
'description' => __('Interest rate added for each installment with interest.', 'woo-pagarme-payments'),
'desc_tip' => true,
'placeholder' => '0.00',
@@ -236,7 +241,7 @@ public function field_cc_installment_fields($field)
$installments['without_interest'] = array(
'title' => __('Number of installments without interest', 'woo-pagarme-payments'),
'type' => 'select',
- 'default' => 3,
+ 'default' => $this->config->getData('cc_installments_without_interest') ?? 3,
'options' => $this->model->get_installment_options(),
'custom_attributes' => array(
'data-field' => 'installments-without-interest',
@@ -246,6 +251,7 @@ public function field_cc_installment_fields($field)
$installments['flags'] = array(
'title' => __('Settings by card brand', 'woo-pagarme-payments'),
'type' => 'installments_by_flag',
+ 'default' => $this->config->getData('cc_installments_by_flag') ?? '',
);
return $installments[$field];
@@ -273,9 +279,9 @@ public function antifraud_enabled()
return array(
'title' => __('Enable', 'woo-pagarme-payments'),
'type' => 'select',
+ 'default' => $this->config->getData('antifraud_enabled') ?? Yesno::NO_VALUE,
'options' => $this->yesnoOptions->toArray(),
'label' => __('Enable anti fraud', 'woo-pagarme-payments'),
- 'default' => Yesno::NO_VALUE,
'custom_attributes' => array(
'data-field' => 'antifraud-enabled',
)
@@ -290,6 +296,7 @@ public function antifraud_min_value()
return array(
'title' => __('Minimum amount', 'woo-pagarme-payments'),
'type' => 'text',
+ 'default' => $this->config->getData('antifraud_min_value') ?? '',
'description' => __('Minimum order amount to send it to the anti fraud', 'woo-pagarme-payments'),
'desc_tip' => true,
'placeholder' => '100,00',
diff --git a/src/Controller/Gateways/Pix.php b/src/Controller/Gateways/Pix.php
index c052762a..c7c0443a 100644
--- a/src/Controller/Gateways/Pix.php
+++ b/src/Controller/Gateways/Pix.php
@@ -43,8 +43,8 @@ public function field_pix_qrcode_expiration_time()
'title' => __('QR code expiration time', 'woo-pagarme-payments'),
'description' => __('Expiration time in seconds of the generated pix QR code.', 'woo-pagarme-payments'),
'desc_tip' => true,
- 'placeholder' => 3500,
- 'default' => 3500,
+ 'placeholder' => 3600,
+ 'default' => $this->config->getData('pix_qrcode_expiration_time') ?? 3600,
'custom_attributes' => [
'data-mask' => '##0',
'data-mask-reverse' => 'true',
@@ -58,10 +58,44 @@ public function field_pix_additional_data()
'title' => __('Additional information', 'woo-pagarme-payments'),
'description' => __('Set of key and value used to add information to the generated pix. This will be visible to the buyer during the payment process.', 'woo-pagarme-payments'),
'desc_tip' => true,
-// 'type' => 'pix_additional_data',
+ 'default' => $this->config->getData('pix_additional_data') ?? '',
+ 'type' => 'pix_additional_data',
];
}
+ public function generate_pix_additional_data_html($key, $data)
+ {
+ $field_key = $this->get_field_key($key);
+
+ $value = (array) $this->get_option($key, array());
+ ob_start();
+
+ ?>
+
+
+
+
+
+ get_tooltip_html($data), ['span' => array('class' => true, 'data-tip' => true)]); ?>
+
+
+
+
+
+ " placeholder="" />
+ " placeholder="" />
+
+
+
+ __('Description that appears on the voucher bill.', 'woo-pagarme-payments'),
'description' => sprintf(__("Max length of %s characters.",
'woo-pagarme-payments'), $maxLength),
+ 'default' => $this->config->getData('voucher_soft_descriptor') ?? '',
'custom_attributes' => [
'data-field' => 'voucher-soft-descriptor',
'data-action' => 'voucher-soft-descriptor',
@@ -87,6 +88,7 @@ public function field_voucher_flags()
return [
'type' => 'multiselect',
'title' => __('Voucher Card Brands', 'woo-pagarme-payments'),
+ 'default' => $this->config->getData('field_voucher_flags') ?? '',
'select_buttons' => false,
'class' => 'wc-enhanced-select',
'options' => $options,
diff --git a/src/Controller/Settings.php b/src/Controller/Settings.php
index 7b046d71..260c7076 100644
--- a/src/Controller/Settings.php
+++ b/src/Controller/Settings.php
@@ -118,8 +118,8 @@ private function setSectionsFields(array $value = null)
'fieldObject' => Select::class,
'id' => 'enabled',
'title' => 'Enable',
- 'options' => $this->yesNoOptions->toOptionArray(),
- 'default' => Yesno::NO_VALUE,
+ 'options' => $this->yesNoOptions->toLabelsArray(),
+ 'default' => strtolower(Yesno::NO),
],
[
'fieldObject' => Integration::class,
@@ -130,14 +130,14 @@ private function setSectionsFields(array $value = null)
'fieldObject' => Environment::class,
'id' => 'hub_environment',
'title' => 'Integration environment',
- 'default' => 'Develop',
+ 'default' => '',
],
[
'fieldObject' => Select::class,
'id' => 'multicustomers',
'title' => 'Multi-buyers',
- 'options' => $this->yesNoOptions->toOptionArray(),
- 'default' => Yesno::NO_VALUE,
+ 'options' => $this->yesNoOptions->toLabelsArray(),
+ 'default' => strtolower(Yesno::NO),
],
]
],
@@ -150,16 +150,16 @@ private function setSectionsFields(array $value = null)
'fieldObject' => Select::class,
'id' => 'is_gateway_integration_type',
'title' => 'Advanced settings',
- 'options' => $this->yesNoOptions->toOptionArray(),
- 'default' => Yesno::NO_VALUE,
+ 'options' => $this->yesNoOptions->toLabelsArray(),
+ 'default' => strtolower(Yesno::NO),
'description' => 'Configurations that only works for Gateway customers, who have a direct contract with an acquirer.'
],
[
'fieldObject' => Select::class,
'id' => 'enable_logs',
'title' => 'Logs',
- 'options' => $this->yesNoOptions->toOptionArray(),
- 'default' => Yesno::NO_VALUE,
+ 'options' => $this->yesNoOptions->toLabelsArray(),
+ 'default' => strtolower(Yesno::NO),
'description' => 'Log Pagar.me events, you can check this log in WooCommerce>Status>Logs.'
]
],
@@ -305,15 +305,15 @@ public function plugin_settings() {
* @param $input
* @return array
*/
- public function validate_options($input ) {
- $output = array();
- // Loop through each of the incoming options.
- foreach ( $input as $key => $value ) {
- // Check to see if the current option has a value. If so, process it.
- if ( isset( $input[ $key ] ) ) {
- $output[ $key ] = sanitize_text_field( $input[ $key ] );
- }
- }
- return $output;
- }
+// public function validate_options($input ) {
+// $output = array();
+// // Loop through each of the incoming options.
+// foreach ( $input as $key => $value ) {
+// // Check to see if the current option has a value. If so, process it.
+// if ( isset( $input[ $key ] ) ) {
+// $output[ $key ] = sanitize_text_field( $input[ $key ] );
+// }
+// }
+// return $output;
+// }
}
From cf769690b22318af38b1b4d144fe988ccf8bcc3b Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 2 May 2023 14:40:46 -0300
Subject: [PATCH 125/156] Bugfix payment_method_title translation
---
src/Block/Order/PaymentDetails.php | 5 +++--
src/Model/Checkout.php | 8 ++------
2 files changed, 5 insertions(+), 8 deletions(-)
diff --git a/src/Block/Order/PaymentDetails.php b/src/Block/Order/PaymentDetails.php
index 8a2b0e97..9453396b 100644
--- a/src/Block/Order/PaymentDetails.php
+++ b/src/Block/Order/PaymentDetails.php
@@ -49,8 +49,9 @@ public function getCharges()
public function isPagarmePaymentMethod(Order $order)
{
if (property_exists($order, 'wc_order')) {
- return $order->wc_order->get_payment_method() === AbstractGateway::PAGARME;
- }
+ $paymentMethod = $order->wc_order->get_payment_method();
+ return $paymentMethod === AbstractGateway::PAGARME ||
+ str_starts_with($paymentMethod, AbstractGateway::WC_PAYMENT_PAGARME); }
return false;
}
}
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 26b0c2f8..504d3c1a 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -74,14 +74,14 @@ public function validateCheckout($fields, $errors)
$fields['billing_number'] == 0 &&
!key_exists('billing_number_required', $errors->errors)
) {
- $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigatório.');
+ $errors->add('billing_number_required', 'O campo "N�mero" do endere�o de faturamento � um campo obrigat�rio.');
}
if (
$fields['ship_to_different_address'] &&
$fields['shipping_number'] == 0 &&
!key_exists('shipping_number_required', $errors->errors)
) {
- $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigatório.');
+ $errors->add('shipping_number_required', 'O campo "N�mero" do endere�o de entrega � um campo obrigat�rio.');
}
}
@@ -118,12 +118,8 @@ public function process(WC_Order $wc_order = null, string $type = CheckoutTypes:
$fields
);
- $paymentInstance = $this->gateway->getPaymentInstace($fields['payment_method']);
-
$order = new Order($wc_order->get_id());
$order->payment_method = $fields['payment_method'];
- $order->update_meta('_payment_method_title', $paymentInstance->getName());
- $order->update_meta('_payment_method', AbstractGateway::PAGARME);
WC()->cart->empty_cart();
if ($response) {
$order->transaction_id = $response->getPagarmeId()->getValue();
From 99ed45ebf58f11685afdcce660eabe571d2bdeba Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 2 May 2023 15:01:39 -0300
Subject: [PATCH 126/156] Update version for 3.0.0
---
.plugin-data/README.md | 4 ++--
composer.json | 2 +-
constants.php | 2 +-
package.json | 2 +-
src/Model/Checkout.php | 4 ++--
woo-pagarme-payments.php | 2 +-
6 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/.plugin-data/README.md b/.plugin-data/README.md
index 5d4c6cd1..022bdc3a 100644
--- a/.plugin-data/README.md
+++ b/.plugin-data/README.md
@@ -4,8 +4,8 @@ Plugin URI: https://github.com/pagarme/woocommerce
Contributors: pagarme
Tags: ecommerce, e-commerce, store, sales, sell, shop, cart, checkout, woocommerce, pagarme, payments, creditcard
Requires at least: 5.0
-Tested up to: 6.0
-Stable tag: 2.1.2
+Tested up to: 7.6.1
+Stable tag: 3.0.0
Requires PHP: 7.2
License: MIT
License URI: https://github.com/pagarme/woocommerce/blob/master/LICENSE
diff --git a/composer.json b/composer.json
index a3ae6f35..3b404c60 100644
--- a/composer.json
+++ b/composer.json
@@ -2,7 +2,7 @@
"name": "pagarme/woocommerce-pagarme-payments",
"description": "Pagar.me module for Woocommerce",
"type": "wordpress-plugin",
- "version": "2.1.2",
+ "version": "3.0.0",
"license": "GPL",
"autoload": {
"psr-4": {
diff --git a/constants.php b/constants.php
index 0854c3d8..366a9970 100644
--- a/constants.php
+++ b/constants.php
@@ -12,7 +12,7 @@ function wc_pagarme_define($name, $value)
wc_pagarme_define('WCMP_SLUG', 'woo-pagarme-payments');
wc_pagarme_define('WCMP_PREFIX', 'pagarme');
-wc_pagarme_define('WCMP_VERSION', '2.1.2');
+wc_pagarme_define('WCMP_VERSION', '3.0.0');
wc_pagarme_define('WCMP_ROOT_PATH', dirname(__FILE__) . '/');
wc_pagarme_define('WCMP_ROOT_SRC', WCMP_ROOT_PATH . 'src/');
wc_pagarme_define('WCMP_ROOT_FILE', WCMP_ROOT_PATH . WCMP_SLUG . '.php');
diff --git a/package.json b/package.json
index 5a165b28..19a320d9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "woo-pagarme-payments",
- "version": "2.1.2",
+ "version": "3.0.0",
"description": "Pagar.me module for Woocommerce",
"main": "woo-pagarme-payments.php",
"dependencies": {},
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 504d3c1a..4c0c99d7 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -74,14 +74,14 @@ public function validateCheckout($fields, $errors)
$fields['billing_number'] == 0 &&
!key_exists('billing_number_required', $errors->errors)
) {
- $errors->add('billing_number_required', 'O campo "N�mero" do endere�o de faturamento � um campo obrigat�rio.');
+ $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigat�rio.');
}
if (
$fields['ship_to_different_address'] &&
$fields['shipping_number'] == 0 &&
!key_exists('shipping_number_required', $errors->errors)
) {
- $errors->add('shipping_number_required', 'O campo "N�mero" do endere�o de entrega � um campo obrigat�rio.');
+ $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigat�rio.');
}
}
diff --git a/woo-pagarme-payments.php b/woo-pagarme-payments.php
index e7b8780c..2a728cb7 100644
--- a/woo-pagarme-payments.php
+++ b/woo-pagarme-payments.php
@@ -1,7 +1,7 @@
Date: Wed, 3 May 2023 16:30:26 -0300
Subject: [PATCH 127/156] bug select
---
templates/adminhtml/system/config/form/field/select.phtml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/templates/adminhtml/system/config/form/field/select.phtml b/templates/adminhtml/system/config/form/field/select.phtml
index 4e1139d9..3654e627 100644
--- a/templates/adminhtml/system/config/form/field/select.phtml
+++ b/templates/adminhtml/system/config/form/field/select.phtml
@@ -14,7 +14,7 @@ if ( ! defined( 'ABSPATH' ) ) {
}
?>
getReadonly() ? '' : 'readonly' ; ?>>
- getOptions() as $option) : ?>
- getCurrent(), $option['value'], true) ?>>= esc_html(__($option['label'], 'woo-pagarme-payments')) ?>
+ getOptions() as $key => $option) : ?>
+ getCurrent(), $key, true) ?>>= esc_html(__($option, 'woo-pagarme-payments')) ?>
From 4e4c0815405e57fc7e29b58a2a8d7f423ab13134 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Thu, 4 May 2023 09:29:12 -0300
Subject: [PATCH 128/156] Bug Yes/No
---
.../Checkout/Field/EnableMulticustomers.php | 4 +++
src/Controller/Gateways/AbstractGateway.php | 4 ++-
src/Controller/Gateways/CreditCard.php | 6 ++--
src/Controller/Gateways/TwoCreditCard.php | 2 +-
src/Controller/Gateways/Voucher.php | 4 +--
src/Controller/Orders.php | 2 +-
src/Controller/Settings.php | 29 +++++++++++-------
.../2023-04-04-0000-InitialModuleConfig.php | 20 ++++++++++---
src/Model/Checkout.php | 4 +--
src/Model/Config.php | 30 +++++++++++++++++++
.../form/field/enable-multicustomers.phtml | 2 +-
11 files changed, 81 insertions(+), 26 deletions(-)
diff --git a/src/Block/Checkout/Field/EnableMulticustomers.php b/src/Block/Checkout/Field/EnableMulticustomers.php
index 2db90136..f7d2be81 100644
--- a/src/Block/Checkout/Field/EnableMulticustomers.php
+++ b/src/Block/Checkout/Field/EnableMulticustomers.php
@@ -38,4 +38,8 @@ public function getElementId(string $id)
$id = '[multicustomers][' . $this->getSequence() . '][' . $id . ']';
return parent::getElementId($id);
}
+
+ public function isEnable() {
+ return $this->getConfig()->getMulticustomers();
+ }
}
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 78a0111f..0643af1a 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -40,6 +40,8 @@ abstract class AbstractGateway extends WC_Payment_Gateway
/** @var string */
const PAGARME = 'Pagar.me';
+ const WC_PAYMENT_PAGARME = 'woo-pagarme-payments';
+
/** @var string */
const PAYMENT_OPTION_UPDATE_SLUG = 'woocommerce_update_options_payment_gateways_';
@@ -256,7 +258,7 @@ protected function gateway_form_fields()
* @return bool
*/
public function isGatewayType(){
- return ($this->model->config->getIsGatewayIntegrationType() === 'yes');
+ return $this->model->config->getIsGatewayIntegrationType();
}
/**
diff --git a/src/Controller/Gateways/CreditCard.php b/src/Controller/Gateways/CreditCard.php
index 2ba13771..a00fba49 100644
--- a/src/Controller/Gateways/CreditCard.php
+++ b/src/Controller/Gateways/CreditCard.php
@@ -126,7 +126,7 @@ public function field_cc_allow_save()
return array(
'title' => __('Card wallet', 'woo-pagarme-payments'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
'label' => __('Enable card wallet', 'woo-pagarme-payments'),
'default' => $this->config->getData('cc_allow_save') ?? strtolower(Yesno::NO),
'description' => __('Allows for cards to be saved for future purchases.', 'woo-pagarme-payments'),
@@ -279,8 +279,8 @@ public function antifraud_enabled()
return array(
'title' => __('Enable', 'woo-pagarme-payments'),
'type' => 'select',
- 'default' => $this->config->getData('antifraud_enabled') ?? Yesno::NO_VALUE,
- 'options' => $this->yesnoOptions->toArray(),
+ 'default' => $this->config->getData('antifraud_enabled') ?? strtolower(Yesno::NO),
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
'label' => __('Enable anti fraud', 'woo-pagarme-payments'),
'custom_attributes' => array(
'data-field' => 'antifraud-enabled',
diff --git a/src/Controller/Gateways/TwoCreditCard.php b/src/Controller/Gateways/TwoCreditCard.php
index c5282375..375b8490 100644
--- a/src/Controller/Gateways/TwoCreditCard.php
+++ b/src/Controller/Gateways/TwoCreditCard.php
@@ -37,7 +37,7 @@ public function field_enabled()
return [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'select',
- 'options' => $this->yesnoOptions->toLabelsArray(),
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
'label' => __('Enable multi-means (2 Credit cards)', 'woo-pagarme-payments'),
'old_name' => 'multimethods_2_cards',
'default' => $this->config->getData('multimethods_2_cards') ?? strtolower(Yesno::NO),
diff --git a/src/Controller/Gateways/Voucher.php b/src/Controller/Gateways/Voucher.php
index f9010017..a202e31b 100644
--- a/src/Controller/Gateways/Voucher.php
+++ b/src/Controller/Gateways/Voucher.php
@@ -110,8 +110,8 @@ public function field_voucher_card_wallet()
'desc_tip' => __('Enable Card Wallet', 'woo-pagarme-payments'),
'type' => 'select',
'label' => __('Card Wallet', 'woo-pagarme-payments'),
- 'options' => $this->yesnoOptions->toArray(),
- 'default' => Yesno::NO_VALUE,
+ 'options' => $this->yesnoOptions->toLabelsArray(true),
+ 'default' => $this->config->getData('voucher_card_wallet') ?? Yesno::NO,
'custom_attributes' => [
'data-field' => 'voucher-card-wallet',
]
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index 1395e8a6..80b5c002 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -27,7 +27,7 @@ public function __construct(
BlockOrder $blockOrder = null
) {
$this->settings = new Config();
- $this->debug = $this->settings->getData('enable_logs');
+ $this->debug = $this->settings->getEnableLogs();
$this->blockOrder = $blockOrder ?? new BlockOrder;
add_action('on_pagarme_order_paid', array($this, 'set_order_paid'), 20, 2);
add_action('on_pagarme_order_created', array($this, 'set_order_created'), 20, 2);
diff --git a/src/Controller/Settings.php b/src/Controller/Settings.php
index 260c7076..2b8679ec 100644
--- a/src/Controller/Settings.php
+++ b/src/Controller/Settings.php
@@ -305,15 +305,22 @@ public function plugin_settings() {
* @param $input
* @return array
*/
-// public function validate_options($input ) {
-// $output = array();
-// // Loop through each of the incoming options.
-// foreach ( $input as $key => $value ) {
-// // Check to see if the current option has a value. If so, process it.
-// if ( isset( $input[ $key ] ) ) {
-// $output[ $key ] = sanitize_text_field( $input[ $key ] );
-// }
-// }
-// return $output;
-// }
+ public function validate_options($fields ) {
+ $sanitizedData = [];
+ foreach ($fields as $key => $field) {
+ if (isset($fields[$key])) {
+ $sanitizedData[$key] = $this->sanitize_field($field);
+ }
+ }
+ return $sanitizedData;
+ }
+
+ private function sanitize_field($field)
+ {
+ if (is_array($field)) {
+ return $this->validate_options($field);
+ }
+ return sanitize_text_field($field);
+ }
+
}
diff --git a/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php b/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
index 94ae74c7..3e1736f0 100644
--- a/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
+++ b/src/DB/Migration/Migrations/2023-04-04-0000-InitialModuleConfig.php
@@ -32,6 +32,10 @@ class InitialModuleConfig extends AbstractMigration implements MigrationInterfac
*/
public function apply(): void
{
+ if ($this->isMigrated()) {
+ return;
+ }
+ $data = [self::PARAM => true];
if ($this->validate()) {
$data = [
'multicustomers' => '0',
@@ -39,7 +43,7 @@ public function apply(): void
'enable_pix' => 'no',
'pix_title' => 'Pix',
'pix_qrcode_expiration_time' => 3500,
- 'pix_additional_data' => 'Custom Store PIX',
+ 'pix_additional_data' => ['name' => '', 'value' => ''],
'enable_credit_card' => 'no',
'credit_card_title' => 'Credit Card',
'cc_operation_type' => '2',
@@ -50,13 +54,13 @@ public function apply(): void
'cc_installments_interest' => '',
'cc_installments_interest_increase' => '',
'cc_installments_without_interest' => '',
- 'cc_allow_save' => '0',
- 'antifraud_enabled' => '0',
+ 'cc_allow_save' => 'no',
+ 'antifraud_enabled' => 'no',
'antifraud_min_value' => '',
self::PARAM => true
];
- $this->settings->addData($data)->save();
}
+ $this->settings->addData($data)->save();
}
/**
@@ -64,6 +68,14 @@ public function apply(): void
* @return bool
*/
public function validate(): bool
+ {
+ if (!$this->settings->getData('hub_install_id')) {
+ return true;
+ }
+ return false;
+ }
+
+ public function isMigrated(): bool
{
if (!$this->settings->getData(self::PARAM)) {
return true;
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index 4c0c99d7..81dc724c 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -74,14 +74,14 @@ public function validateCheckout($fields, $errors)
$fields['billing_number'] == 0 &&
!key_exists('billing_number_required', $errors->errors)
) {
- $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigat�rio.');
+ $errors->add('billing_number_required', 'O campo "Número" do endereço de faturamento é um campo obrigatório.');
}
if (
$fields['ship_to_different_address'] &&
$fields['shipping_number'] == 0 &&
!key_exists('shipping_number_required', $errors->errors)
) {
- $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigat�rio.');
+ $errors->add('shipping_number_required', 'O campo "Número" do endereço de entrega é um campo obrigatório.');
}
}
diff --git a/src/Model/Config.php b/src/Model/Config.php
index b78be8ec..681f9ef8 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -233,6 +233,36 @@ public function getCcFlags()
return $ccFlags;
}
+ public function getMulticustomers()
+ {
+ return $this->getData('multicustomers') === 'yes';
+ }
+
+ public function getCcAllowSave()
+ {
+ return $this->getData('cc-allow-save') === 'yes';
+ }
+
+ public function getVoucherCardWallet()
+ {
+ return $this->getData('enable_logs') === 'yes';
+ }
+
+ public function getEnableLogs()
+ {
+ return $this->getData('enable_logs') === 'yes';
+ }
+
+ public function getIsGatewayIntegrationType()
+ {
+ return $this->getData('is_gateway_integration_type') === 'yes';
+ }
+
+ public function getAntifraudEnabled()
+ {
+ return $this->getData('antifraud_enabled') === 'yes';
+ }
+
public function log()
{
return new \WC_Logger();
diff --git a/templates/checkout/form/field/enable-multicustomers.phtml b/templates/checkout/form/field/enable-multicustomers.phtml
index 7372707b..c0b4fe44 100644
--- a/templates/checkout/form/field/enable-multicustomers.phtml
+++ b/templates/checkout/form/field/enable-multicustomers.phtml
@@ -11,7 +11,7 @@
declare( strict_types=1 );
?>
-getConfig()->getMulticustomers()) : ?>
+isEnable()) : ?>
= $this->setIncludeContainer()->formatElement(
'',
['p' => ['class' => true, 'data-element' => true]]
From 419cce391c5275b97729f3a30e9734210a1acdbb Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Thu, 4 May 2023 14:33:13 -0300
Subject: [PATCH 129/156] :bug: fix getHubInstallId from hub
---
.../src/Kernel/Aggregates/Configuration.php | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
index b8c3649a..0caf14ea 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
@@ -309,10 +309,12 @@ protected function isTestMode()
*/
public function isHubEnabled()
{
- if ($this->hubInstallId === null) {
- return false;
+ if ($this->getHubInstallId() && $this->getHubInstallId() instanceof GUID) {
+ return
+ $this->getHubInstallId()->getValue() !== null &&
+ $this->getHubInstallId()->getValue() !== "00000000-0000-0000-0000-000000000000";
}
- return $this->hubInstallId->getValue() !== null;
+ return false;
}
public function setHubInstallId(GUID $hubInstallId)
@@ -705,7 +707,7 @@ public function setBoletoDueDays($boletoDueDays)
if (!is_numeric($boletoDueDays)) {
throw new InvalidParamException("Boleto due days should be an integer!", $boletoDueDays);
}
-
+
$this->boletoDueDays = (int) $boletoDueDays;
}
From f030d0cf7993835757e76d5eadd796ee96149e91 Mon Sep 17 00:00:00 2001
From: Aislan Cedraz
Date: Thu, 4 May 2023 15:01:01 -0300
Subject: [PATCH 130/156] :bug: id thankyou page
---
src/Controller/Gateways/AbstractGateway.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 0643af1a..4456f031 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -114,7 +114,7 @@ public function __construct(
add_action(self::PAYMENT_OPTION_UPDATE_SLUG . $this->id, [$this, 'process_admin_options']);
}
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
- add_action('woocommerce_thankyou_' . $this->vendor, [$this, 'thank_you_page']);
+ add_action('woocommerce_thankyou_' . $this->id, [$this, 'thank_you_page']);
add_action('admin_enqueue_scripts', array($this, 'payments_scripts'));
}
From 35960090c5a992424a7800d06f177b6ae441dbb6 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 5 May 2023 12:56:51 -0300
Subject: [PATCH 131/156] Icnoe Pagarme do checkout
---
src/Controller/Gateways/AbstractGateway.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Controller/Gateways/AbstractGateway.php b/src/Controller/Gateways/AbstractGateway.php
index 4456f031..41e00853 100644
--- a/src/Controller/Gateways/AbstractGateway.php
+++ b/src/Controller/Gateways/AbstractGateway.php
@@ -103,7 +103,7 @@ public function __construct(
$this->method_title = $this->getPaymentMethodTitle();
$this->method_description = __('Payment Gateway Pagar.me', 'woo-pagarme-payments') . ' ' . $this->method_title;
$this->has_fields = false;
- $this->icon = Core::plugins_url('assets/images/logo.svg');
+// $this->icon = Core::plugins_url('assets/images/logo.svg');
$this->init_form_fields();
$this->init_settings();
$this->enabled = $this->get_option('enabled', 'no');
From 1558a4e3dd97294b5099f419c406462b227923f2 Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Fri, 5 May 2023 13:29:24 -0300
Subject: [PATCH 132/156] Show Wallet in Checkout
---
src/Model/Config.php | 4 +--
.../src/Kernel/Aggregates/Configuration.php | 26 +++++++++----------
2 files changed, 14 insertions(+), 16 deletions(-)
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 681f9ef8..e23bb209 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -240,7 +240,7 @@ public function getMulticustomers()
public function getCcAllowSave()
{
- return $this->getData('cc-allow-save') === 'yes';
+ return $this->getData('cc_allow_save') === 'yes';
}
public function getVoucherCardWallet()
@@ -258,7 +258,7 @@ public function getIsGatewayIntegrationType()
return $this->getData('is_gateway_integration_type') === 'yes';
}
- public function getAntifraudEnabled()
+ public function getAntifraudEnabled()
{
return $this->getData('antifraud_enabled') === 'yes';
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
index 0caf14ea..f422cf4e 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
@@ -267,7 +267,7 @@ protected function getSecretKey()
/**
*
- * @param string|array $key
+ * @param string|array $key
* @return $this
*/
public function setPublicKey(AbstractPublicKey $key)
@@ -285,7 +285,7 @@ public function setPublicKey(AbstractPublicKey $key)
/**
*
- * @param string|array $key
+ * @param string|array $key
* @return $this
*/
public function setSecretKey(AbstractSecretKey $key)
@@ -339,7 +339,7 @@ public function getHubEnvironment()
/**
*
- * @param bool $boletoEnabled
+ * @param bool $boletoEnabled
* @return Configuration
*/
public function setBoletoEnabled($boletoEnabled)
@@ -353,7 +353,7 @@ public function setBoletoEnabled($boletoEnabled)
/**
*
- * @param bool $creditCardEnabled
+ * @param bool $creditCardEnabled
* @return Configuration
*/
public function setCreditCardEnabled($creditCardEnabled)
@@ -393,7 +393,7 @@ public function setCreateOrderEnabled($createOrderEnabled)
/**
*
- * @param bool $twoCreditCardsEnabled
+ * @param bool $twoCreditCardsEnabled
* @return Configuration
*/
public function setTwoCreditCardsEnabled($twoCreditCardsEnabled)
@@ -407,7 +407,7 @@ public function setTwoCreditCardsEnabled($twoCreditCardsEnabled)
/**
*
- * @param bool $boletoCreditCardEnabled
+ * @param bool $boletoCreditCardEnabled
* @return Configuration
*/
public function setBoletoCreditCardEnabled($boletoCreditCardEnabled)
@@ -560,10 +560,7 @@ public function setAntifraudMinAmount($antifraudMinAmount)
$minAmount = preg_replace($numbers, $replace, $antifraudMinAmount);
if ($minAmount < 0) {
- throw new InvalidParamException(
- 'AntifraudMinAmount should be at least 0!',
- $minAmount
- );
+ $minAmount = 0;
}
$this->antifraudMinAmount = $minAmount;
}
@@ -708,7 +705,7 @@ public function setBoletoDueDays($boletoDueDays)
throw new InvalidParamException("Boleto due days should be an integer!", $boletoDueDays);
}
- $this->boletoDueDays = (int) $boletoDueDays;
+ $this->boletoDueDays = (int)$boletoDueDays;
}
/**
@@ -871,7 +868,7 @@ public function __call($method, $arguments)
{
$methodSplited = explode(
"_",
- preg_replace('/(?<=\\w)(?=[A-Z])/',"_$1", $method)
+ preg_replace('/(?<=\\w)(?=[A-Z])/', "_$1", $method)
);
$targetObject = $this;
@@ -892,8 +889,9 @@ public function __call($method, $arguments)
return call_user_func([$targetObject, $method], $arguments);
}
- private function isMethodsIgnoringFather($method, $methodSplited, $actions, $targetObject) {
- $methodsIgnoringFather = ["getSecretKey","getPublicKey","isHubEnabled"];
+ private function isMethodsIgnoringFather($method, $methodSplited, $actions, $targetObject)
+ {
+ $methodsIgnoringFather = ["getSecretKey", "getPublicKey", "isHubEnabled"];
if (
in_array($method, $methodsIgnoringFather) &&
From b5059cdc35029070b2801aac315adb629e64b7a4 Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Mon, 8 May 2023 08:47:14 -0300
Subject: [PATCH 133/156] :bug: fix update of installments when interest by
flag
---
.../front/checkout/model/payment/card/wallet.js | 10 ++++------
templates/checkout/form/card/wallet.phtml | 11 ++++++-----
2 files changed, 10 insertions(+), 11 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card/wallet.js b/assets/javascripts/front/checkout/model/payment/card/wallet.js
index efe95474..4ed9bc2f 100644
--- a/assets/javascripts/front/checkout/model/payment/card/wallet.js
+++ b/assets/javascripts/front/checkout/model/payment/card/wallet.js
@@ -6,7 +6,7 @@ const cardFields = [
'[data-element="save-cc-check"]',
'[data-element="enable-multicustomers-check"]'
];
-let pagarmeWallet = {
+let pagarmeCheckoutWallet = {
started: false,
isStarted: function (){
if (!this.started){
@@ -22,19 +22,17 @@ let pagarmeWallet = {
let brand = select.find('option:selected').data('brand');
let brandInput = wrapper.find(pagarmeCard.getBrandTarget());
brandInput.val(brand);
+ pagarmeCard.updateInstallmentsElement(e);
cardFields.forEach( function (field) {
wrapper.find(field)[method]();
});
},
addEventListener: function () {
$(cardSaveTarget).on('change', function (e) {
- pagarmeWallet.onChangeCard(e);
+ pagarmeCheckoutWallet.onChangeCard(e);
});
},
start: function () {
- // if (this.isStarted()) {
- // return;
- // }
this.addEventListener();
- },
+ }
}
diff --git a/templates/checkout/form/card/wallet.phtml b/templates/checkout/form/card/wallet.phtml
index 81726ede..d7e6257a 100644
--- a/templates/checkout/form/card/wallet.phtml
+++ b/templates/checkout/form/card/wallet.phtml
@@ -36,9 +36,10 @@ if (!function_exists('add_action')) {
+
-
+
From a2b34816e9e6c289863215752d721cd7808b2e4b Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Tue, 9 May 2023 14:28:11 -0300
Subject: [PATCH 134/156] :bug: fix value displayed incorrectly in the
installments field
---
assets/javascripts/front/checkout/model/payment/card.js | 8 ++++----
src/Block/Checkout/Form/Installments.php | 7 +++++++
src/Model/CardInstallments.php | 3 +++
templates/checkout/form/card/installments.phtml | 8 +-------
4 files changed, 15 insertions(+), 11 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index 7cd08881..ab4e5a8d 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -231,15 +231,15 @@ let pagarmeCard = {
}
let brand = elem.closest('fieldset').find(brandTarget).val();
let total = elem.closest('fieldset').find(valueTarget).val();
+ let cardForm = elem.closest("fieldset");
+ let select = cardForm.find(installmentsTarget);
if (!total)
total = cartTotal;
- if (!brand || !total)
+ if ((!total) || (!brand && select.data("type") == 2))
return false;
let storageName = btoa(brand + total);
sessionStorage.removeItem(storageName);
let storage = sessionStorage.getItem(storageName);
- let cardForm = elem.closest("fieldset");
- let select = cardForm.find(installmentsTarget);
if (storage) {
select.html(storage);
} else {
@@ -344,7 +344,7 @@ let pagarmeCard = {
return true;
},
addEventListener: function (paymentTarget) {
- $(paymentTarget + ' ' + cardNumberTarget).on('blur', function (e) {
+ $(paymentTarget + ' ' + cardNumberTarget).on('change', function (e) {
pagarmeCard.keyEventHandlerCard(e);
});
$("form.checkout").on(
diff --git a/src/Block/Checkout/Form/Installments.php b/src/Block/Checkout/Form/Installments.php
index 1bc1a68d..f19390e3 100644
--- a/src/Block/Checkout/Form/Installments.php
+++ b/src/Block/Checkout/Form/Installments.php
@@ -72,6 +72,13 @@ public function getInstallmentsType()
return intval($this->getConfig()->getCcInstallmentType());
}
+ /**
+ * @return boolean
+ */
+ public function isInterestForAllFlags()
+ {
+ return ($this->getInstallmentsType() == CardInstallments::INSTALLMENTS_FOR_ALL_FLAGS);
+ }
/**
* @return String
*/
diff --git a/src/Model/CardInstallments.php b/src/Model/CardInstallments.php
index 36dd176a..007af9d0 100644
--- a/src/Model/CardInstallments.php
+++ b/src/Model/CardInstallments.php
@@ -29,6 +29,9 @@ class CardInstallments
/** @var */
private $config;
+ const INSTALLMENTS_FOR_ALL_FLAGS = 1;
+ const INSTALLMENTS_BY_FLAG = 2;
+
/**
* @param Config|null $config
*/
diff --git a/templates/checkout/form/card/installments.phtml b/templates/checkout/form/card/installments.phtml
index bf113f7b..b3232eb9 100644
--- a/templates/checkout/form/card/installments.phtml
+++ b/templates/checkout/form/card/installments.phtml
@@ -19,11 +19,5 @@ if (!function_exists('add_action')) {
*
getInstallmentsComponent() ?> data-total="= esc_html($this->getCartTotals()); ?>" data-type="= $this->getInstallmentsType(); ?>" data-action="select2" data-required="true" data-element="installments" name="= $this->getElementId('installment') ?>">
- getInstallmentsType() !== 2) : ?>
- render() as $options) : ?>
- = $options['content'] ?>
-
-
- ...
-
+ ...
From 603b4672d1cf20a3e433e34770591e98c03e6341 Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Wed, 10 May 2023 09:50:14 -0300
Subject: [PATCH 135/156] :bug: fix hide disintegrate button when advanced
options is disabled
---
.../adminhtml/system/config/form/field/hub/integration.phtml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/templates/adminhtml/system/config/form/field/hub/integration.phtml b/templates/adminhtml/system/config/form/field/hub/integration.phtml
index 08bff326..e1752295 100644
--- a/templates/adminhtml/system/config/form/field/hub/integration.phtml
+++ b/templates/adminhtml/system/config/form/field/hub/integration.phtml
@@ -18,7 +18,7 @@ if ( ! defined( 'ABSPATH' ) ) {
-config->getHubInstallId()) : ?>
+config->getHubInstallId() && $this->config->getIsGatewayIntegrationType()) : ?>
= esc_attr(__('Disintegrate', 'woo-pagarme-payments')); ?>
From 70f425e6307dc8d316544ce73cda580a59127718 Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Thu, 11 May 2023 15:57:25 -0300
Subject: [PATCH 136/156] :bug: fix duplicate orders
---
assets/javascripts/front/checkout/model/payment/card.js | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index ab4e5a8d..ca8760a8 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -336,7 +336,8 @@ let pagarmeCard = {
if (!wc_pagarme_checkout.validate() || wc_pagarme_checkout.errorTokenize === true) {
return false;
}
- if (pagarmeCard.isPagarmePayment() && !pagarmeCard.canSubmit) {
+ let el = pagarmeCard.getCheckoutPaymentElement();
+ if (pagarmeCard.isPagarmePayment() && !pagarmeCard.canSubmit && pagarmeCard.haveCardForm(el) !== false) {
// pagarmeCard.showLoader(pagarmeCard.getCheckoutPaymentElement());
pagarmeCard.execute();
return false;
From 7b8971b2ddb8bde17fe1d0b1315cd07dda76f5ff Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 16 May 2023 16:02:31 -0300
Subject: [PATCH 137/156] Remove general option enable/disable
---
src/Controller/Settings.php | 7 -------
1 file changed, 7 deletions(-)
diff --git a/src/Controller/Settings.php b/src/Controller/Settings.php
index 2b8679ec..cd728bdf 100644
--- a/src/Controller/Settings.php
+++ b/src/Controller/Settings.php
@@ -114,13 +114,6 @@ private function setSectionsFields(array $value = null)
'id' => 'options_section',
'title' => 'General',
'fields' => [
- [
- 'fieldObject' => Select::class,
- 'id' => 'enabled',
- 'title' => 'Enable',
- 'options' => $this->yesNoOptions->toLabelsArray(),
- 'default' => strtolower(Yesno::NO),
- ],
[
'fieldObject' => Integration::class,
'id' => 'hub_button_integration',
From 2ee38db6a84c0886697ab7229cf1875371e69537 Mon Sep 17 00:00:00 2001
From: Fabiano Mallmann <25328512+fabiano-mallmann@users.noreply.github.com>
Date: Thu, 18 May 2023 09:26:54 -0300
Subject: [PATCH 138/156] :bug: fix value being sent to number_format
---
src/Model/Payment/CreditCard.php | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/Model/Payment/CreditCard.php b/src/Model/Payment/CreditCard.php
index ced81e7e..c37f8451 100644
--- a/src/Model/Payment/CreditCard.php
+++ b/src/Model/Payment/CreditCard.php
@@ -82,9 +82,10 @@ public function getPayRequest(WC_Order $wc_order, array $form_fields, $customer
{
$request = [];
$content = current(parent::getPayRequest($wc_order, $form_fields, $customer));
+ $amount = Utils::str_to_float($this->getAmount($wc_order, $form_fields));
$content['amount'] = Utils::format_order_price(
$this->getPriceWithInterest(
- $this->getAmount($wc_order, $form_fields),
+ $amount,
Utils::get_value_by($form_fields, 'installments'),
Utils::get_value_by($form_fields, 'brand')
)
From bef04d61163b2fe43d398763b4c37b7134f84e2e Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Mon, 22 May 2023 16:51:35 -0300
Subject: [PATCH 139/156] CheckVisibility not work in Safari
---
assets/javascripts/front/checkout/model/payment/card.js | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index ca8760a8..f5e0c00c 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -135,7 +135,7 @@ let pagarmeCard = {
loadBrand: async function (e) {
let elem = e.currentTarget;
- if (!elem.checkVisibility()) {
+ if (!this.isVisible(elem)) {
return;
}
let cardNumber = elem.value.replace(/\s/g, '');
@@ -146,6 +146,9 @@ let pagarmeCard = {
this.changeBrand(e, card);
this.updateInstallmentsElement(e);
},
+ isVisible: function (obj) {
+ return obj.offsetWidth > 0 && obj.offsetHeight > 0;
+ },
getCardData: async function (cardNumber) {
let result = [];
From 5f55b6a2b0fbc806ead8144ec0749e47881f0f6e Mon Sep 17 00:00:00 2001
From: mauriciohaygert
Date: Tue, 23 May 2023 16:40:27 -0300
Subject: [PATCH 140/156] duplicate orders with wallet
---
assets/javascripts/front/checkout/model/payment/card.js | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index f5e0c00c..c70f1e5f 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -340,8 +340,9 @@ let pagarmeCard = {
return false;
}
let el = pagarmeCard.getCheckoutPaymentElement();
- if (pagarmeCard.isPagarmePayment() && !pagarmeCard.canSubmit && pagarmeCard.haveCardForm(el) !== false) {
- // pagarmeCard.showLoader(pagarmeCard.getCheckoutPaymentElement());
+ if (pagarmeCard.isPagarmePayment() && !pagarmeCard.canSubmit &&
+ pagarmeCard.haveCardForm(el) && !pagarmeCard.hasSelectedWallet(el)
+ ) {
pagarmeCard.execute();
return false;
}
From ad476131629b73effcd179bf50d2cd9ea76870df Mon Sep 17 00:00:00 2001
From: RafaMelazzo
Date: Thu, 25 May 2023 10:58:25 -0300
Subject: [PATCH 141/156] PAOPN-410 Frontend review
---
assets/images/logo.png | Bin 17593 -> 0 bytes
assets/images/logo.svg | 11 -
assets/images/pagarme-white-avatar.svg | 7 +
.../front/app/component-pagarme-checkout.js | 2 +-
.../front/checkout/model/payment.js | 2 +-
.../front/checkout/model/payment/card.js | 8 +-
.../front/checkout/model/payment/pix.js | 2 +-
.../front/checkout/model/thankyou/billet.js | 8 +
.../javascripts/vendor/sweetalert2.all.min.js | 1 +
assets/javascripts/vendor/sweetalert2.js | 1606 -----------
assets/stylesheets/admin/components/index.php | 2 -
.../stylesheets/admin/components/js/index.php | 2 -
assets/stylesheets/admin/elements/_form.scss | 99 -
.../stylesheets/admin/elements/_spinner.scss | 21 -
assets/stylesheets/admin/elements/index.php | 2 -
assets/stylesheets/admin/style.css | 2355 +----------------
assets/stylesheets/admin/style.css.map | 1 -
assets/stylesheets/admin/style.scss | 21 -
.../stylesheets/admin/vendor/_izimodal.scss | 1097 --------
.../admin/vendor/_sweetalert2.scss | 708 -----
assets/stylesheets/base/_functions.scss | 20 -
assets/stylesheets/base/_helpers.scss | 114 -
assets/stylesheets/base/_mixins.scss | 0
assets/stylesheets/base/_variables.scss | 23 -
assets/stylesheets/base/index.php | 2 -
assets/stylesheets/front/_checkout.scss | 119 -
.../stylesheets/front/elements/_spinner.scss | 3 -
assets/stylesheets/front/elements/index.php | 2 -
assets/stylesheets/front/style.css | 1126 +-------
assets/stylesheets/front/style.css.map | 1 -
assets/stylesheets/front/style.scss | 20 -
.../front/vendor/_sweetalert2.scss | 708 -----
assets/stylesheets/vendor/sweetalert2.min.css | 1 +
languages/woo-pagarme-payments-pt_BR.po | 32 +-
languages/woo-pagarme-payments.pot | 4 +-
src/Block/Checkout/Gateway.php | 2 +-
src/Block/Checkout/ThankYou/Billet.php | 6 +-
src/Block/Checkout/ThankYou/Pix.php | 8 +-
src/Block/Order/Transaction/Pix.php | 8 +-
src/Core.php | 15 +-
src/Model/CardInstallments.php | 26 +-
src/Model/Gateway.php | 10 +-
.../config/form/field/hub/environment.phtml | 4 +-
.../config/form/field/hub/integration.phtml | 16 +-
templates/checkout/form/billet.phtml | 57 +-
templates/checkout/form/card.phtml | 74 +-
templates/checkout/form/card/wallet.phtml | 10 +-
templates/checkout/form/field/card-save.phtml | 2 +-
.../form/field/enable-multicustomers.phtml | 3 +-
templates/checkout/form/multicustomers.php | 96 +-
templates/checkout/form/pix.phtml | 6 +-
templates/checkout/thankyou/billet.phtml | 19 +-
templates/checkout/thankyou/pix.phtml | 50 +-
templates/order/transaction/billet.phtml | 25 +-
templates/order/transaction/pix.phtml | 33 +-
55 files changed, 454 insertions(+), 8146 deletions(-)
delete mode 100644 assets/images/logo.png
delete mode 100644 assets/images/logo.svg
create mode 100644 assets/images/pagarme-white-avatar.svg
create mode 100644 assets/javascripts/front/checkout/model/thankyou/billet.js
create mode 100644 assets/javascripts/vendor/sweetalert2.all.min.js
delete mode 100644 assets/javascripts/vendor/sweetalert2.js
delete mode 100644 assets/stylesheets/admin/components/index.php
delete mode 100644 assets/stylesheets/admin/components/js/index.php
delete mode 100644 assets/stylesheets/admin/elements/_form.scss
delete mode 100644 assets/stylesheets/admin/elements/_spinner.scss
delete mode 100644 assets/stylesheets/admin/elements/index.php
delete mode 100644 assets/stylesheets/admin/style.css.map
delete mode 100644 assets/stylesheets/admin/style.scss
delete mode 100644 assets/stylesheets/admin/vendor/_izimodal.scss
delete mode 100644 assets/stylesheets/admin/vendor/_sweetalert2.scss
delete mode 100644 assets/stylesheets/base/_functions.scss
delete mode 100644 assets/stylesheets/base/_helpers.scss
delete mode 100644 assets/stylesheets/base/_mixins.scss
delete mode 100644 assets/stylesheets/base/_variables.scss
delete mode 100644 assets/stylesheets/base/index.php
delete mode 100644 assets/stylesheets/front/_checkout.scss
delete mode 100644 assets/stylesheets/front/elements/_spinner.scss
delete mode 100644 assets/stylesheets/front/elements/index.php
delete mode 100644 assets/stylesheets/front/style.css.map
delete mode 100644 assets/stylesheets/front/style.scss
delete mode 100644 assets/stylesheets/front/vendor/_sweetalert2.scss
create mode 100644 assets/stylesheets/vendor/sweetalert2.min.css
diff --git a/assets/images/logo.png b/assets/images/logo.png
deleted file mode 100644
index 0bca9fd7c1dc250f6794821720723e63609829f9..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 17593
zcmX6^1yoeu*By`skw&_t8$=jVT4Lz#?w+B$M37LrJEXfCq$EeAOG3I4kQ%=C`+tkY
zV)5R+@AkRp?7dI4nu`2OEOIOm2=r3ngNz0Ug!KBqUko(hNmTqnEbs@#RuUo!0@WvA
zKboTg|I=E2(13tIeoP=xNCXIU4?GIl2Z20!K%hf25J)&31R{0I?oby6UZ7bh$;*JA
z|NF`BE=vNQpu-d(vgm)1(Q$d`{yw}v10Er{dZ=h2O&5A+f)ws5S?eD{-X?+y6p1B^zv%^GeF~%f_6a%WoS2o33iUwoB^9y)#zD99
z*v-1jndbCa0tzz0PeG{nZC8K~wUw*y^lE#a|Lz3X79%~-VCkI5iRsk>_3Bp5nepat
zFrm+s%w(8$D+bq^%Z?j#}$dIC?GqV
z5>ZuBm`(6DW_oyeXUKIRo25`YMca3ddyZs;@A
zB6OWQvB}Hcu1e+%)AZI0xD-2^oJHKg1=Vr`DH|w>K_zurf$3TS?+VMQ+niD5&Imt(
z?W+2Y(NP&`zoV&Dma@;}>sfOiAWNZs2(@tC%zyBChx#59V`%SHvDR#gn<8%OQ3t^m
zm^UL?`Xr~|$UPsL*W-^w{C*&LVi-_~}N)YUZhGw>*GMF@HkzmzU+S|kScSfoQM
zv8?rH@s(}|ttSQiba^Ml>ye?fFw>zIp!Yp$x}*I)S_W}{inr^tpTty(6yM^xt|cZ9
zo`BRg9uy|0RS>&OvPtwz{UoqVC;{*x|L1=<7ngqO7Z~*NZ226nvd!
zPo}F7^({3As6y4g-+q{aAiA{YOhtmxWTkqcV|qL6lk^G@AOAv6=(c_MBEqZ~oKzEvZ}umdfzQ)U?gFduA|%=m!U661e%_VctO$
zcAoGF(((8TrP6h~!N1cga~PZ44Vgwy6e}icEe#jt!dXkYgHVg2wVflX9EsY~>9YwH
zEn<$oVQ*e%>MVyVJo%H2|gWoSHoi2hn{fQpb
z(~=}8jUVuiNq&xzEAfyTRZ$*aYWF-_|0w48_~7%LcXidXZP`lZhV1)}i7?CdmCV-7
zlIw*sZ?B*bUvF-yvp~M1PV;!6YY!Jo&DKRw%B6RBW~%*gSVn?UC_P9PWP|7SNhx$E
zv(%OgQH-d!X%z_Wp4%kAYvxHS;A*C-YVMv_J7g_7Cyta>UJ
z*x6@Ql`s)}iQd#&cob}X+7vBgEHj-=nWV%wA@#jVUAOCAo#`Y{0LLmY+LCo+PSAR&
zZ3})Z64OL&SPnNlTc7KEWGlL&6zLp6#mWXtVk}tV=gbv(?DcH%JeU~5eM1Hpy6S
zAf@^@e3?fTD0JEI&+tjh?DN+7p}Q-
zG#5JmGQUf*mDj-PftR1?t^Mk?d8qojk+e1+P~Bq7%2M)yomUUSRkY2IW{Cm^*gnm+FIji%WHi=_=*x4}N#MRZNx_rMoqlQDgg%@u1qb8x$|M>l
z>tQt%l;pz?Y@3)s1%a#;6aU8p^kAP?bgRgD-EW`KpSk2Ta3wVefNtQv=#;t?(0M0{
zS~-?8hrfK2W-K<|>j=x;443-N$r{Sv`ohmv_6Cz1!rghk!HKwLEn_6z{!Btf^#zP_
z%qNg!j-drP^S2=jBjCO&`n<3Lj$r>dswrJjfclZC^EuDFp{j%eF!|
z+~SD2{log`g_kbz$U<`HdBaVNuwntzB+*`VmsVpRwA*4E{N6M;@XFP*a?BalWS#(Y
zmX0CwFk^<)@!yfO(sb`nn@eT8eZxr4Np9ev6sNSoFFrB?JA{srF>3s$!(()f+w}_<
z$NoED=eM6j2q(g*Hf7R)LR9}1`WT{-gZ;*Ubogg?LY1>0;`AA@TiOV6quQj>TX;-_
zBSjJGnBm4k%3c=}c(Ale%>S!K=xwjny4+vS=_GZ&N!|~6Ab$^kQ?&gO8yKlH2@(>j
ztRim0S&Y^*BFQ*mJxRxcKiGE}R{ZBRxt}gMmHQ}QM93~#Sbi%0B2|P1R5CPOyKZBt
zbPt%1c^qmDWe)Gf#tRnLBM;(Wqo4?Dw>J^wEa9(v-3ALjUXnm`uQ2H_z8k`~Hq2n(
z>3|(;qgRmsrCBS;)@QGo!oajA0q-=nji|1(8dXo{whkC3<-3{FzHe}(^rFup?`IjK
zB-VW-^9!s^?B|pBAYo7I0eg!kimcZo24A)-c!YPq^cnC>@W|#LR4B}q49xcpS04FG
z1div~Wv-Aq<4II>zN!v|$e~jb=!Jsu=7Y#C-x@bNbci;091SwJHgV_nx=nbNx)l-%
z7}JnZInMxtHTT+vRp`vaxP5(~D~`4#zRU)#O}(M-yQp#sa^!3&n)E`KxRLALO}I&E
z8I!BecJK7h#i^PqVCe2Pl3r2ubN*X%v|Ktq9_+)y84Ms(_iQijIh#e_PJGUDb$J>D
zi!$HaXc@)q%^O+5S|p=@D|C@xKBU>~BVCSz1arB}#dO$6gd
zSh}XBYu5-)l;XO#j^siEMH2H?u&&q-K!D9+SBNhj>bh1Us2GxjEwUw
zU(vSpTOG64yR>+CqXs|8m2Qn&s<%&igY^P8GEDsI`|xqI3`_-tO@=KrQGrtUc;5^R
zv;^!CHS5;xplb*#__kL8{HEG52%n#wi&xlU*qrnANAR1@TF%mx#kP*zKi)3(rUC71
ziO#9XLM8^c*hPcZl)wp1AC#gkuWwk+O>jL+5KzYRJ#ytJ2m#eP&`UyX~omqTjYn&F##$m~4m!)VLA4<(0*jm!q#+KSQQE2P!6KiqXZ
z^lvnZcRs=4IR6_sYG%!1lE?4A5a-%QYv(IyQgE*i!5hZVmOh)JBC?q4ex3>S!h;Gh
zo~u}(^X%0lSTpEZy0tog+~(4*-$>6Sqwk)(lJ#OJRPtO7oqk*f_Pm!9&6}M53;r
zL-^wfvJT)F(^wnxOceZt4IL*4=CwB-g>MAkuP`&OC{s^akI6!xg^P-)pjCa8uPb>b
z%xTq{evQo;E1f>n-S_xX8{+TP6Tj?C#R2SMI#Qu#+~;CHlDB^Y9nkh&Rj9n5m`UIT
z50;#xUa1sRXX$2~=`SofU+>o8OMUqw)tLEsgSe;4=ep{r>Wif*kN7=hxe;=n<8dhM_kGZW8j*@8m(kkeabDizUq$rk
z3u&)7QysIOk9`?*ZZ?pe>L(KT68rhC(0dI~&*dwmuNa$FQbN|#5^PBDxOFrpsC|cp
ziedq(4*YHeu%>PEZ^b@adnS-m9euOhHtRv76BQbe1)m4+U<6Ab(b3YHcG*G7RpfW4
zysSmo6a^}DemL;uNs(%LycNWArKV8yiU-l+4P;<`3h6$fGb!sBtqFPMDy&`oRA0)@
z%7X7R9!GDh!ddH2#2j~54~NH-1AQeyMV(`{OV%J?TVRmskGU#cUt)ADzi;Uqw%*hd
zEIVQo8h~zEG1neqNznV3me249byX;63RDMr!0V
zvqX_;r)7uw91WQmDm2c1eflB`D{<&dE37aJ1scVgA9O?6Isk#f+$sqBWhk~ZKpi#o
zTz7D)n#jH^_a)3%1qH5*q>5f{6hpV5(-?FKHBH%UrUUPoFqmG&{5$%ibM-wlUv<&Nav{5gLe%I{0enNy;9
zja{a5yiK7v5f-?x7^WHQd%5ViftFvE^16yC4PGCQAtJ>eQdLTON%D7y93OHmHD`@N
z=zKns^_$0*VL`wHCWS@STXJ%J=U(3Xi$kbE@5dRHJgAn%!~CJ~6W{aNb&aQC@UZ?NgV)Nj)*5a#ZBvHh*8l_jvkC
zB12tI)iK*oTK<}IB2Y+a<$m<9iiT99AJDCzrr9^*Elpj#?n)0^vi6Mc^misL
zwTxL+#x_M|m98QteO|x8u;R3iF81RR#J<^&y>xx@T&5~^ovjXset7ZVOMz_gNb$Qd
zEx+`E;qhr(>Ef*Nn=ND(sx9_)xzMe`v8i;-cDNX!U%}*__j1pikD>&aH?mP^oFChW
zx-a)M=34tH{M(N_S6GwuKztM3o79^@^C_v%!7mJuDexe-TiIi+?lg0vLggYFjbHFw
zbTqJN03Rt;ecy~G*rq6-=jz6%-t{tWPqq81eE#%y<56ktG#@SHw&6ZaA6{XS-hg
zkvj)@aJSxCcX3VB7W?z1goZvVr>(7oBmdgN(6JSiSN?{^v=D1mUlCF{x0@jr4N
z3aXfBUY*X%pY}eP7RX(jI8^D&@YkkH%5TAet@WT=n@e`L>6b&2`Gv$z~(UrhiF(
z>1W&ul5e&ABvy<^OhScIS$w7_x&Ov?-WraqJ;;M%3Ke)TGiD*f@o2kWA_;QN7qQ^0
zy|~0+{<~L|XIV>R>+Z6mYr*CQaeH<2&|@{VbRWa*#jwZ)m$QJ|H3||=Ug4i
zzxbZW(nh>reNrmNAE@qeTQ+Vb@?%C-_p{n>X@TM_wyH*QQB*OQbK!rE|eP=t{8yI7)P3#P7CmX`=))Q|Scqm7^PVd-Z^bn`eiU6Rw&aMf;6Q*1Y
zr#I&y2Ed)sQrEx@^f!E1u@r3T0sy19_#rGD=->b9uIPu-Ps_YTpC4gl?6E%mMkC5c
zzZcOdG%(WVVh!$NvCw!v_T=QA2(%a?wtM9)AdDv>Yk{UBeWoarNadz?Wehl6BsX$L
z!88z0)#Ci)DCa)4#mS|WfSU%#qVinTsXRYsmbtIn4CDtk8V1=H};lIf#>w&?C%F
zrPQ19uo$#_-qcVO70EmluN9~}xKAb^gOpFj_apT|OYK4{553FcABMJ_`zICD>nx<;
z_9LR`4{jMqqzX5E)|1lC(|lTgrqSt8xT`u{bVN^rc`{FPhGQoB>S9j4YPYZ)KIe%Ltw0kxUEX+iPEX7Ro!$x<@mSZ*Jv^z)>cV(qAiNvbaaiLdKV(UXzwH#$51*rP%q+71
z@k?{~DZ9<-ZqXCRkng`LnHqk$M4XYu1kO+Mu@7f%dJQhkF{g4;LORy*iA@BPC(-k(
zT`hNam;mgUt?x$Jcx!|Dk$1JJ0lN<$39xO?3A^2H!Lm0KoyuL+)B8r!3OsOe2|U+M
zJL4;CDWN6ziS;x9d|-$j%ZqZ7C$kcWo*mx!m#9!@vfZ@fV)^1So@AgIRnTOoVMpa+
zNhx9JHWw&vsRwaE*>c{;aZV6?Sm-s{Cwq46Tw1V$)f9v#Mi7yA7hQE9nQUB&1X&Mi
zj_epOftZ;X)D;VkD$XY|pS?AJSR?TZGDFL#!JrDwr<7<}+nzn|wKEIL`r@-$sAV^92>SNLu
zd--{@$;uvxp#q2KJA!}LS)CzMus~&4=Gyf-f`?=7M_gE739|BLD?kJ6Jj%mZOv^~1
zPCp5CuJoG`V$@Ujh4$*ZmAEN^Mf(mX>@q(Umsd{Z8h`(W^pO6Cw@{Z5?f4*H!G61@
z8Tqvo57VSITTy4d@oi&K4l8oCfRhPABc9V{6F=Kq@4Xro0giss1#rQ@IEPwRQn!C@
z)BJ1W^PY$3z%@tY9;vyIA!z}CtFMwPcrRZ#ZGx;%m5z7~02Z;f{QmDTLKk#Ug1Z=e
zcOwNQ2JugWatSSgK)UL!F}{We>@@N4Vfx8x!IB4a9?6$x{<{?#v4TP&f7eT35c;)F
z9e;KadV_PBT!u>p0s9yj9EFY-k+aW_Pai5ofTJpXqu%2*34j3k79`FyFk4D_r^ja|EPhGx`%&U
z{YF?`CXP5mTK0>M1vs$&Bes`Uk7;wwovdAlU-Cw%Ia)aozhW>7e@Pyk&3vppi!1iq
zZOrPTV#7)@OAwv}3yvEcZmKoB5X`$cQ1|!z4|l5OywLMa7`#_c5;TBs
z!Y{n=TZ)zyQ&%xMSG>ke{jTcASs}0wfJ(rmNuI<;_YSngd(Qyau51l(=e(SP(hlM1#18R;=3=r{`c+ltRAoolO~224#)$30k1+U6vAc``HyO_y>^|Q
zgRj1IF#&hem#=%&aYKeCCAO;fC+`xPf0N)5pmcf#o@0a-mZ&bSBK%|_3j{Efga8xP
z|B7F(dlF4ocgy7&c=g}IeXm@2Fk6C(_+OHspcGh*e3w}c{@I!kJX5-F&yop~sU5?@
z;V&-U!I;YOW2O#xetYm8U$@I>E60QVC;{vvJeR-!b5)fBkzqRfg#Vr4__Mk0*L1ov
z&NgDv%?m{QbNGUZFkkku&vKq!hV0^IkQ&CPt!C2TBmc%czoPo!msA=4TlifhgE;Ed
z2nfq$rh{MLRdrem+B<~w9Ag$d0}VYUU}15=Bb%WHUOu0)M;;EG5UP3hdSD?&x4`)9
zhk40LftnH%?m9igrTCN_VYzlE`hXvfS*F?+osRlo-b?V`sI`x?J{?$ZdNqOlEn&z*7Chn~{j7;K4e3`uTa
zUqA;i9XCaz%Y<}+OU13G9m;vfIsl2Y7x(9Vys-Hz=M8UULfjkIR_|{x^|Li@@}iTZ
zArrGQUQQBUKR3O*sg*Nr+WcY~4&ZX5eA-vCIKmsl>BTf#%aTJ|+BT^PI`EfTme
zTpc>Jgd4XAJcN>HmrQIvMgqva_eRcd4~?rENU)!ZP7)!3M_syc$9iuuCEIMdpN8}F
z2!xf9jpp!5KlBb+HtD@&!8e6b2P|Q2NmkTpOgtaU181@T7!-yF7#5%v~whK!4GZrkiW_5NhB7Oi5f|C7z0B0kg*E
zo0)fSio0jEi8$l3ruD{N)Rpdh)1GCNEK4TzZL|<*p9K-92KhyjsCWe-I)Ivt>tpB3
zN?-o4L`Ansm5~Dn;GJJmMxc-D$a5$&y>gf*e5&S_MtQV=w~DyY^w*n3;rQBrQ}&kF
zDm9+^&{ySG4x=q*9fQqyLco~6G@-ovQl|3+0xUI&Q(>*fLi0Au{s%Q-;`byse`TY)
zA|J2AHBqF5a`EDsX;DBd?^)*r6a^x~*!
zAJ&u1j4|%bG!aD3?Y#3#;{lPx^-@z6oUmM|Alh2|4-|7hF?d#7%I*CylY##P1D@NG
z;qt~ebhi(mZ*Zf3b~it9e(EAd_z*lC$^y4boTE68ktd$u!2+68eV-ZLdbxsH$O!wfPGb
z4~+|bzg)-Un}mev+1ktpj_g#U4-S;uSgO2!w=YFRgg4|l)?OjIOnsbBqgG(AzmT*2
zVHM%#5bA$?B+6{kQg=wsIs)GM4FpyHq#0Q;(@`igpN?k8mP2ixh4;1k3oisO0T%3?
z?rydam=1mKmsfCrq#`aUA%M(mRwW;jn%30<8i`K8}
zULdSq6Xx@-5$!&fx=V@cEnJ$yXSsqz4Q9X8PE-3`&gVz^3Of)kw<9F)=IYdbGCbe+
z(UjF-*%4N%JdAIyn_A?wJj9R4tot+-9<-j%$^(GM08O0efuZDZI+C#0{oU2>uC}?x
zHlu{0DJ9P&2>!Q6Z%`ZHfQ%rz*~y1YSef`#J}5HG5t^`yvhJ3FYQ~=OGr8GrSEdrR
z>2F=_mzWG(N>4!-GS^KPf>OUH)Aik>;a{V=?$_7Y_p(qs_nIer1Et{_SFuycV?qPB
z)6{p}{9u(uwcV_EBi%oeV%*!<%7$kA04oqGL*epon$_p}@SEpQ4f84h8$>fa9st*t
z{#PyCl2S)pAvkKjBKfRlJ6!c00+p6a^$HxN)4sAFuLtA7=$tQsl)^=^`L%
zioD&AQbpUi_L((X6=f&^-Zu=Su4g`bCJJ$+WI3#w?h$EF<06wx^`MJaN?l2eSxZp0
z>G6H!*LhRwAce5a!opJotyy?9
z6Z|6$EI}jywT{H6iq9kOsL#jDPbeR84@zw=ix^@1IDh))=2nb8a90{1@)m|2~26fxi`0H}cQpvVvL
zn!6SG#LOzIS&SRV?}_@DH=h<%ofJuO8?q+UG?6ck`hA@
zo@sCX%(NqXW-mI+R&2F)kly#>t9$ET9a7nBblSl0Hm*un>uXvbESvlIaTUN3Qqw|3
z(zvXlKJ2Ml6111u=X>+NOC4F~WQ+K%>5-8`TLXlIpNnN>b1?zA#jd0%^NTmdJWfo4
zEzP}=+HtCu{fmxDEzR7yT#jQ(4~21i_FDK+D`qTMSjc@gmoBU~Dm|_`e^QhHeTcD$
z@Vd19JWNJY3}C0<0#pfrt|fKkmTUt+=~YiLlb-3s!f&wo)!po=uqOPcSdqso(ez*E
zl^l~#NBx9I&{KNAOe!`|{@E~C`8#3UFSAnA{neQCK#R(22zBwv5ee^2@$cmLnfcE3
zWv>xa({;DmTci0dj|D;K3}N+)5~5I_EVz19#QnOeU1PAbX0GEzR0Lkj$Fqgs(RvMy
zSK(Lw44pGu8*Y6g6!(+H3xDamS}bBGvYh>#ud2%;37mC5H~;`|^v;pipc@CrgOqmy
z!`=MXq$CbWK>W!$9=;%(FHpf&+T5-<@t+U5s;qk
znYdd-nOD+T4!fnuoC)iYFWjf#~55
z*z(*CuUrDD@|lXD*7Ujjj8vsn=q&rS!LXlK4}r(LC*kF1PehcPn~iCoXmp;h|Jpn+
z2Y+zbGKwZnlP-0zk1A%Gsy#vcJAHO(yGV0!>;ZqVlXf&qg2T}mLk0V39EU50gB<~E
zm2N}KFB+b~mr^?3@}Z;iEgkv{$zsFC2z4X!ER7@DbOx;>>(xke@Pi!WHt~UoQ_TF<
zRNoy8>%7(1z)d)g*V?$OP1*1lWt5jovxW@*M;GD>vT%|IzZfRXjpt{66yB{T>9&UD
zPRN?$=lCvg`0yuCn@!Awkf#6fObFA6F)M_8D(+x*wGZCr2DArHorMZTvFi}&$ik99
z1u$$3UF0m#!um^?OMHyVWKF
zO=nyJD^9uQAF}QEJ`2||%LIfPS;G#Hl`1R0ZVrvfwb^0D)?$BOgsD~TJ6tTsAo!r)
z|0L+_PW%!uE=kM`d7|Bm$MFW(Kp@Y%f+lM-om*)7O2n_bp&wsV?w@j;#|9Px
z(7UC;not~<@+1<8&Odu;qWyRPPImBoo%xbbFAf|tC*UZeN`_x7j!EYyc?F}Shd
zTF@yjUc=cFKW$1oXB{el3Jvc}lXeV<)Yu&xj>U}gCTq~k0;qSd$=vxb0l-u7eDS`e
zXmwvN{9^?x%LSyrElf7(YpVTg-Mh!I0W
z*H=Fjw~RZ-Rs!>7wYKzv>je#-n-fGTPWn;|05y)s5T*dtOq5yr=W4Gvx(*J-_F^>+F}Lk|KTWeh!c(^{8Nb=OuWK%
z912L06VNrS>L-QV2A%MF{<>NId=!L>MFk2FFjlH@IW&FxR6NYws5B!-|KUdg5CjB|
zq}~X+R2-Nj25v-^_1lk0%G*T&gyQ-{jO(@ph3oNr`Av^3Om305q#FZ6!=t!xsn_d=
zgm@254%g_SXTjbiQkv+7~qzdzaP
zx+x%9U;^dj$9*cewj*Mc)W3=qO}gC7HToL_XH+POhFm<~n;5R&OnKklr898x)Hl)G
zo$?BKu5t@Obf>TxMQR|G?xgHo84&=1?r_HNnQ(jcpzG1R}bN?Cz8;
zc1ol?idm`=?#qXZiZW%SJ=!@X`82!s*^-Fi$qB$MPhtd9+!&64<
zoB}GlL&JxZ5lXL6g%5OA;2)rnRsW0eq=&+5LFPZ_I66jrhKkWd!^J&@F{|6X1)4d>
zhj-uiKafFYiMs&0#vvE_i`grw^`kN5o*r2N(#A5!WE`}`pc5a^45IN0tle`#
z7h7ENM_5S9FZrt|1H-C64E=kXUE4S;uhgh(p!%EPP
zA!D%Upkj^2wOvttTf%VVFLDP%^S;%#<&8ZI5imh>l{A-Gb8Ph#Ybpc47y6r8x?V}a
zFFOVVOz)5Ah+iwR79NOKx%kb`9-DgS6e`@wxl%)|-Uxi%pmFWmVZJgY&p9K1k=Om-
z`jk%yzVz<#G+G2)3KCz(uxr8766ybZ#{rtDrBld$$DlB`1|`twbof|H
z(ighhAe;EuLZ-6nZ^2trK*W)-ynI2@($d(RiqL&C7tYU&Am?Y}@|EA26sYP7Ktcrx
zn;Tz!Mm;I0Hoc#fB>gnpGxu)_^A!W0E0@!;=^YhBcWJ9uIzmoclV>RiQFg70*!dTu
zWR7nvC;vl;+7O9@iImzn2)>(4;A~Z<;E#_iquH%l(J9X2a8WC73Omd14Cmru>|q7u
zWg=R}_xwoaf~DjZunJ5YIInBqxDxaIHe_)g(E|U7Sam
z+9s@eGG)LAe*%0BZ~MPvRY+JI=jJ&o5z$h7jQjIl{gxB5OqYue#@3|{s1!Nw28c+G~0zQ>ce-62w34>Y(4+#;4d%j%4
zk+XfjX$s}z?v;HcY-Ql}rBM;5t8?#FRD@fKoGS{y8wTBnu}#dEPwdl^?pht)E%Z&O
z?K4|eE99j0*|O3Xw*-<@AkJ;K#BEjmn`
z-j6dwBak$RUXhNDr#U$^^qK-73m^8Q^QT00Unl@f7W@))j_S)QI`+6WacAWzEDw&W
z}WwF*S4Z`K>Xlb&+S3xD-aB2a6zGC2}j-;VUfqr-IUwFLYq(k&zK
zfDH(hbe>LJn*G7`+nFf=nEIF%9h8LX;)F28V|j0GNSbUe|I+$e&%Z0f*TE;qq%Q+2
z>&mZ*M-4neOUH{AT_{yB0BuuR@*rt&!_kFy1y{2dN^8-gAbj79te;~M;NFroZYm#o
zJ#rYv*AZj_&FHN^`hpC2BHV;*f1LPYvc5IcNaE5dk0O;4LLsRBj2xZXj$K)Uk7*v>
zA^~Vc0hZN8%ahdtmZ}VZJnaf#2Nm`Qux!Nv;4t2o{KZy-I{%4gvh0p+V+*A@P
zMhL)T7;f|qz^Tg7>Jr3Xe{D4b=*Us`SRoY+LgsxfbatM>v{H7i$}#>*u{O^@9yp1h
zuxcsGrE*B20!1rakPsv)w>L&4Jm=JqxkC&=u1g?Me!CV$GvPZ-rrb33x$LRxdVn_j
zSk%|@XnblIAT2RmBrZuQk(Ils0HBsaz}Q^&7Mlp-0Vs6prp40%c-8LMG&1GoGdTn!
zSQJo&y#PJc4ch-7|5n0hT0J~C)&wK#hOu9~FUu^N5p%iuEU{|kvTuqCS%{6dYKzGxd#&rk
z21usQEaNd)fm0uoOmIE)GqAL62mL%!{53?gt|X9`JZpid*51#ip!iKyg!XG2!JibB
zy&S)0F0kZL%0;?n0n0A=don-YzU~g$^lwSwg>PuP_ZaJ_cl^guL$)pZXQ%mV;Ftk1
zX=(gemT9})BlqAWqWL%(6f$baiu&?J@<~EBMu{*WAaQH(KV$t#M(8s9hgsZ4k+pui
zP{R~_v})b+32*AhRVntnCd9}u!ZmAHcI=mJO3bW%W7YC0m9IBjtMkZ5rt86^O#MBr
zeIFDluLJXTg*d^paVn!$)QYS?B0__k;mC@GA}$3LGefd1q{uNV*Zx=e4>XKG$y|SB
z*#|ML;{<_YE*^Wv_?iy_hyJ>4Ngh7MaHI@n8Gv(WZTK!S@Aj{zlk8Qv;H4i8aPmwK2j(vOwo%iFl_M(z<2$v4<8@Va*IdGNcvnNkn&*f~#
zP>{I`0Wplp4q0z1UOXgVRl2M~kPa19A?}QeXA*JkbN}$`xM@dw%phisGvrRV^nI7L
zy1yAVJCDEBl2ZA2>c)#YOn-m;jt2{Zr9fgA`$W?yoF}jRP8kIokjM?!9H4S6;VOCcHeoKNK%MPw@VEX^Ff$WJL#*(5=^+)hOJ5
zUo1XI>NosA{pb~e@l{KZh|_r*|RV|coNiV%y
zsB>%&wGW$!NEoITa^1^=9*L*&CE2H?w4S|jLL5JrFffr|JEDy!qOb&2AJV}7VWOX&
zNO;7>_KLCU`4Wmk^ovlr2`VK7$IK;!D1fz`U>r7h1<7^%Vch1ZyVxvqC#;M=FnP;q
zC^u2`A=VUBF=Uh&7-jqRmALPObC(2j99o)y28xML-uvV@xD-kAhNE$pW0I;yFa(zr
zgg2Y@glJ4w9TMQ*tX3x!g)Hr>P2@|yg|w&*81OuYuk}%Y-h;8&96FFgPsI{!h||G#
zM9FIN=;0jxWIifd%3&u%ybcb`UZiBmAwey{UcvRFw$N5IgumR)`YS8%PnMV9zyrwT
znq{Tfd|1j{S)2A+3<_OEr{ygY$4B0>M-v!1kNrdjneCmoM00;<5
zN=45hj>U(`!ohtO<&WE|^HRz8r3#drnQ^#-IJg}(KVq1gZAIi>Q$>!s8TI(%7|myE
z@xXg#|Gx*#!L?-fNp)p@A|0yPQw6
zh1gab?}iA0MjO)T7r^w+g4Ui5jc;~ATCL6bYmVIJ=vdJA$e_0B$hzoLm11|
z&m^6~v(H^AkN_)08XuqcO%hZtP{Pv)3=mZPcU^sU9Wk#Yx@d@(n1A`4Fdi-5cTJG$
z%g8J7z!8XFE2_GsX@KsVGJ6_3cI{ZU-kU&${HcgZu~`+v@F@I_vY@1=+!avh$cp!D
zDzF&**ndAkdr|VxX4er0piaE~&{AR`_zU;E;pU=VP?FiJCbV~N#hWi5I;xodn?icicETK4HvrD9B7r0=
zV0J}%e&-o=*Qz4R5tK;z!!q)%Ye{az9PMi@(d!%sJ%fi=T|C6=CGMH7dzKP!JT4ghF$<#Jk13aN7em-O)iF#?9_w-?;uI!xPcm^yyqbIc8?X%
zz`p~!IeL6GAJ7dq{`YNH5@h8my-{`zhi$wb*kyUC1n{I4U)vjB$gW45T_vPT51kxI
z#E*ih8KAb704l_;ZM-xPGk*RZpAKKKsaw4H?`lvQBf1j;ANsAW_CdPbl^lV%X#a}5
zuxL#JpBuTi_?RcUkWL!U{xH7_fMfL8$9%%L{1}1Gq0uD|^>&YO>HLT2XLwQ-`s_CU
z^7GvcJdPk?CrjR5t7}O|l#$?~9@qcO64
zug0@EXxXFrc;xI^Sn;qVhW8Hl1da&0Q|hnV>WH_G_b>)Jo`V@fcT(T=l8Wt!Z3FY!-Ota*^Hu5u(oI(7n_t}keqvP{kNgmlh_8et
zzdvmyD}d@brhu8no9j<{p-78y>!97y=q|<_XYSx@5oXc9Of0CIi;VWW`$EMGV{i0$
ziyjR#M|A$G1IV}q$ccUj?|onOv}at8E1*2rP%;aLyQkCbdcz$Uft)J_RPXRVL4e2Z_bhJ^h|Vd15DKI6z}|hd_qMpJ8L2Bj5$LEpT&@Px
z7q1qTP2Lf@eAxu^^3$MWdNqz(4L!G-I!5V8P#Na6?yr78J|sH@BAP>fsTjzS
zc?$IzM}C(=tBH@%Rqm?+Us{M81tYo}st&M@yv@;m(&ffoNa50-S%tHXy<5
zVJ?v|W(A9CmytV8S-oyFtNm|<1-0+4Hf~1@Q%Vs6a`F}*+ln+$COU0b4=b3u)3#q<
z@JE6D1>}8x)R@^~0YZ;TY9L%#M%C8kW{ODSEPRpD&P+}fOSToS7+RkdNE;CnCN-O)
zE$)B7+4(uPFDAC%OZ7#acEUu))41%miyrldCI=#-qN_bJsyH&V_`{dqOoIYmjyBDm
zFB&=f)~Ls2*2L<(El&??APjt=rlu!jYwJ57YdDqpH>*`@Oofv*O6@qu4))e2UFh)X
z4L3qhR^E>Nt+DYbGc
zJbY#wkE9Dvlqi%wDncUJhxd>-b5P_Gr^BCpMZZ6NII%g?sjdFEL2U@X5@o(wR;JF@
z^KFN3rkmTm&m!@k|FXHhdLNYmhdsCY7kNq)YPG)ZhD*=oT9f`%flgJnPknurD|RQ1IqeV}7?7b}sO2jHq%5$v^X7gAs7>V6z`CX38^;zUE5
zMA9Dl6?<@@wR3Ql`jlt9)lekwLp!(Y=&lx^52)P6B7KV7i-^yxVI1{HZmg7zEr{1YbJX==HZcfhsL8zIUNKxj_!t=-
z2EWNXtQJls`^Xl`k3QZ|_B=QtLJhXus`UfyJ4J9MVa6}1FH)}}SMEzWy73#$2lNc}
zx|paI-|PYzxKbd|#gb!bS@3|8xc^cn{q#TiuK1s~9nvBUwh#m-pl0xKLY3RIOlQbq
zb7N5q&;%Wy{$sTKG~ZkA?i&v7>~~~uuLB^Ghl{3Q98_f|v-ME?fpVLExO%R@wtb^n
zu!qCJUALhK$vCw?zREw&m
zks)L#N>g&rd@Zl4B>>fZZ>3#1zVO`QGGAWNZ*WqvW_8go!RwTOg>>{`(y6mcuw0>t
zQFwqiv0+^N*atFqt(%d|uO}>kxN&VWv(Vdn^{Fv}s7-HPqa@kkjkEkpOMVy3cJemc>i+4$T*#Jwqfi(IC
zqRXZw=3EN;c;6I0J^vG5NS)Bv5ncYDF@U8pa|xev*8*S+3y_}&Tz=O;ZeV(NqPkdE
ziN5A$!)`xY2S|}LN^^~Ly5{lpmGOL66y@&mOTgoxSbSil^uwqs6mb%~d$$77S5;;c
zf7p}Ac>W;^nAc~J+OZ7{;0WX=!Y4!HIBVa}y)nAoD)G6mu%4xO(1AE$ItfwG@)Ky(
zp;(=_+Oc@m+V#74oi^+Q?lcp3ivVs^1#8J(jj{Uk8vw+mFOgB}*khv{#9<f5axf>PzDybi%L!&?6F+%pFIfacr7N8s7lhA(oR()(g%n%BQ6TuJA0Bsnygk
zFUCpZIyZ;ns<{_*cBcj|h|}m9<<0p0fdp2bDCd~~28J=}wklt{o7%xo+1o(AJSk^+
zPjCew@zC6H=C?Rl*SBZfMGl!T3dpv&T~)=B5^Afu6JcaTDEi*G9|7`-nV$1?*_HLK
z8%8}@QYMl-bC}*oFdG^q^iJ8;iu9O?8&E}mJ99s
zzFpHT*L0r73hL~A-1&AK)*ZRiNDpX1L?-m9ypn3QiK;jg2{sZn3IzZk>o(bzij@2-
zRB8m^S#_`0v_FjDXTRN*mpfDZNQM{Q(H9{1Km7otx|TNca43H2)@^d^b0mQ7x0gI!
zSLJ@Fu4LCZ(GZA+8eUQ9$H%aOsB$z4hX7FijXuQZ<~T-rndbkdc2MeTME9!Pw0vVm
zap0~R|KG{HcNs1MSBD9)zT3Fb>HLuwH=0=gvD;Y%uR9gr5cAw)Mul|As>Gm^k#6s;
z+9U&x=jdH($Yas3d-?zS@mUwevxEMAd=?PZ+a3~oaNg9f9~aB-?>O-5+S0WLeZS4i
zm}@%eRau~e3WM$^pEHF~MW;9vZ(3coner-)>y&VT&~eU0rbqtT7vJ5>sP%W^I$HzAmrxV3@I6d8?Dk)w96f=jD}b6E_D<
zHx1V<=?}N;3)idY$oTB0-*h56@PS;n49KtAT(-g!-b*!45o)|WE&a