Skip to content

Commit

Permalink
Merge pull request #223 from mundipagg/hotfix/PAOP-269/enhance-valida…
Browse files Browse the repository at this point in the history
…tions

Improve field validations
  • Loading branch information
netorodrigues authored Aug 17, 2021
2 parents 2cfd0be + c249da4 commit 1e78f71
Show file tree
Hide file tree
Showing 18 changed files with 491 additions and 228 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/.idea/
/vendor/
composer.lock
/tests/report
/tests/mock/db_test.sqlite
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "mundipagg/ecommerce-module-core",
"description": "Core component for Mundipagg e-commerce platform modules.",
"license": "MIT",
"version": "2.8.6",
"version": "2.8.7",
"authors": [
{
"name": "MundiPagg Embeddables Team",
Expand Down
43 changes: 27 additions & 16 deletions src/Kernel/Aggregates/Charge.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Mundipagg\Core\Kernel\Aggregates;

use Mundipagg\Core\Kernel\Abstractions\AbstractEntity;
use Mundipagg\Core\Kernel\Exceptions\InvalidOperationException;
use Mundipagg\Core\Kernel\Services\LogService;
use Mundipagg\Core\Kernel\Exceptions\InvalidParamException;
use Mundipagg\Core\Kernel\ValueObjects\ChargeStatus;
use Mundipagg\Core\Kernel\ValueObjects\Id\OrderId;
Expand All @@ -17,17 +17,17 @@ final class Charge extends AbstractEntity implements ChargeInterface

/**
*
* @var OrderId
* @var OrderId
*/
private $orderId;
/**
*
* @var int
* @var int
*/
private $amount;
/**
*
* @var int
* @var int
*/
private $paidAmount;
/**
Expand All @@ -45,25 +45,31 @@ final class Charge extends AbstractEntity implements ChargeInterface

/**
*
* @var string
* @var string
*/
private $code;
/**
*
* @var ChargeStatus
* @var ChargeStatus
*/
private $status;

/**
*
* @var Transaction[]
* @var Transaction[]
*/
private $transactions;

private $metadata;

private $customerId;


public function __construct()
{
$this->logService = new LogService('Charge', true);
}

/**
*
* @return OrderId
Expand Down Expand Up @@ -94,16 +100,16 @@ public function pay($amount)
$this->setPaidAmount($amount);

if ($this->getStatus()->equals(ChargeStatus::underpaid())) {
$this->status = ChargeStatus::underpaid();
$this->setStatus(ChargeStatus::underpaid());
return;
}

$this->status = ChargeStatus::paid();
$this->setStatus(ChargeStatus::paid());
$amountToCancel = $this->amount - $this->getPaidAmount();
$this->setCanceledAmount($amountToCancel);

if ($this->getLastTransaction()->getPaidAmount() > $this->getAmount()) {
$this->status = ChargeStatus::overpaid();
$this->setStatus(ChargeStatus::overpaid());
$this->setPaidAmount($this->getLastTransaction()->getPaidAmount());
}
}
Expand All @@ -124,15 +130,15 @@ public function cancel($amount = 0)

//if all the paid amount was canceled, the charge should be canceled.
if ($amount == $this->paidAmount) {
$this->status = ChargeStatus::canceled();
$this->setStatus(ChargeStatus::canceled());
}

return;
}

//if the charge wasn't payed yet the charge should be canceled.
$this->setCanceledAmount($this->amount);
$this->status = ChargeStatus::canceled();
$this->setStatus(ChargeStatus::canceled());
}

/**
Expand Down Expand Up @@ -305,6 +311,12 @@ public function getStatus()
*/
public function setStatus(ChargeStatus $status)
{
if (!empty($this->logService)) {
$this->logService->info(
"Charge {$this->getMundipaggId()} status changing to {$status->getStatus()}"
);
}

$this->status = $status;
return $this;
}
Expand Down Expand Up @@ -336,7 +348,7 @@ public function getLastTransaction()

public function failed()
{
$this->status = ChargeStatus::failed();
$this->setStatus(ChargeStatus::failed());
}

/**
Expand All @@ -351,8 +363,7 @@ public function addTransaction(Transaction $newTransaction)
foreach ($transactions as $transaction) {
if ($transaction->getMundipaggId()->equals(
$newTransaction->getMundipaggId()
)
) {
)) {
return $this;
}
}
Expand Down Expand Up @@ -475,4 +486,4 @@ public function jsonSerialize()

return $obj;
}
}
}
11 changes: 10 additions & 1 deletion src/Kernel/I18N/ENUS.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,18 @@ protected function getTable()
"The card '%s' couldn't be deleted." => null,
"Different paid amount for this invoice. Paid value: %.2f" => null,
"The %s should not be empty!" => null,
"The %s is invalid!" => null,
"street" => null,
"number" => null,
"neighborhood" => null,
"zipCode" => null,
"city" => null,
"country" => null,
"state" => null,
"phone" => null,
"document" => null,
"Can't create order." => null,
"Can't create payment. Please review the information and try again." => null,
'Invalid address configuration. Please fill the address configuration on admin panel.' => null,
'week' => null,
'weeks' => null,
Expand Down Expand Up @@ -85,6 +89,11 @@ protected function getTable()
'Antifraud reproved' => null,
'Antifraud pending' => null,
'Waiting manual analise in antifraud' => null,
"Can't connect to the payment service. Please contact the store administrator." => null,
"The sum of payments is different than the order amount! Review the information and try again." => null,
"The sum of payments is greater than the order amount! Review the information and try again." => null,
"The card brand '%s' or the amount %.2f doesn't allow %d installment(s)! Please review the information and try again." => null,
"Passed value:" => null,
];
}
}
}
17 changes: 13 additions & 4 deletions src/Kernel/I18N/PTBR.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,19 @@ protected function getTable()
"The card '%s' was deleted." => "O cartão '%s' foi deletado.",
"The card '%s' couldn't be deleted." => "O cartão '%s' não pôde ser deletado.",
"Different paid amount for this invoice. Paid value: %.2f" => "Esta Invoice foi paga com um valor diferente do Grand Total do pedido. Valor pago: %.2f",
"The %s should not be empty!" => "O campo %s não deve estar vazio",
"The %s should not be empty!" => "O campo %s é obrigatório!",
"The %s is invalid!" => "Campo %s inválido!",
"street" => "rua",
"number" => "número",
"neighborhood" => "bairro",
"zipCode" => "CEP",
"city" => "cidade",
"country" => "país",
"state" => "estado",
"document" => "CPF",
"Can't create order." => "Não foi possível criar o pedido",
"phone" => "telefone",
"document" => "CPF/CNPJ",
"Can't create order." => "Não foi possível criar o pedido.",
"Can't create payment. Please review the information and try again." => "Não foi possível realizar o pagamento. Por favor revise os dados e tente novamente.",
'Invalid address configuration. Please fill the address configuration on admin panel.' => 'Configurações de endereço inválidas. Preencha as configurações de endereço no painel de administração',
'week' => "semana",
'weeks' => "semanas",
Expand Down Expand Up @@ -86,6 +90,11 @@ protected function getTable()
'Antifraud reproved' => 'Reprovado no antifraude',
'Antifraud pending' => 'Analise pendente no antifraude',
'Waiting manual analise in antifraud' => 'Aguardando análise manual em antifraude',
"Can't connect to the payment service. Please contact the store administrator." => "Não foi possivel conectar com o serviço de pagamento. Por favor contate o administrador da loja.",
"The sum of payments is different than the order amount! Review the information and try again." => "A soma dos pagamentos é diferente do valor do pedido! Verifique as informações de sua compra e tente novamente.",
"The sum of payments is greater than the order amount! Review the information and try again." => "A soma dos pagamentos é maior do que o valor do pedido! Verifique as informações de sua compra e tente novamente.",
"The card brand '%s' or the amount %.2f doesn't allow %d installment(s)! Please review the information and try again." => "A bandeira do cartão '%s' ou o valor %.2f não permite %d parcela(s)! Por favor revise os dados e tente novamente.",
"Passed value:" => "Valor informado:"
];
}
}
}
10 changes: 10 additions & 0 deletions src/Kernel/Services/APIService.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ private function getCustomerController()

private function getMundiPaggApiClient()
{
$i18n = new LocalizationService();
$config = MPSetup::getModuleConfiguration();

$secretKey = null;
Expand All @@ -231,6 +232,15 @@ private function getMundiPaggApiClient()
}
$password = '';

if (empty($secretKey)) {
$message = $i18n->getDashboard(
"Can't connect to the payment service. " .
"Please contact the store administrator."
);

throw new \Exception($message, 400);
}

Configuration::$basicAuthPassword = '';

return new MundiAPIClient($secretKey, $password);
Expand Down
21 changes: 16 additions & 5 deletions src/Kernel/Services/OrderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,10 @@ public function createOrderAtMundipagg(PlatformOrderInterface $platformOrder)

$this->persistListChargeFailed($response);

$message = $i18n->getDashboard("Can't create order.");
$message = $i18n->getDashboard(
"Can't create payment. " .
"Please review the information and try again."
);
throw new \Exception($message, 400);
}

Expand All @@ -301,7 +304,10 @@ public function createOrderAtMundipagg(PlatformOrderInterface $platformOrder)
"Can't create order. - Force Create Order: {$forceCreateOrder} | Order or charge status failed",
$orderInfo
);
$message = $i18n->getDashboard("Can't create order.");
$message = $i18n->getDashboard(
"Can't create payment. " .
"Please review the information and try again."
);
throw new \Exception($message, 400);
}

Expand Down Expand Up @@ -337,6 +343,8 @@ private function getResponseHandler($response)
public function extractPaymentOrderFromPlatformOrder(
PlatformOrderInterface $platformOrder
) {
$i18n = new LocalizationService();

$moduleConfig = MPSetup::getModuleConfiguration();

$moneyService = new MoneyService();
Expand All @@ -359,9 +367,12 @@ public function extractPaymentOrderFromPlatformOrder(
foreach ($payments as $payment) {
$order->addPayment($payment);
}

$orderInfo = $this->getOrderInfo($platformOrder);
if (!$order->isPaymentSumCorrect()) {
$message = 'The sum of payments is different than the order amount!';
$message = $i18n->getDashboard(
"The sum of payments is different than the order amount! " .
"Review the information and try again."
);
$this->logService->orderInfo(
$platformOrder->getCode(),
$message,
Expand Down Expand Up @@ -445,7 +456,7 @@ private function persistListChargeFailed($response)
private function createChargesFromResponse($response)
{
if (empty($response['charges'])) {
return;
return [];
}

$charges = [];
Expand Down
2 changes: 1 addition & 1 deletion src/Maintenance/Assets/integrityData

Large diffs are not rendered by default.

41 changes: 34 additions & 7 deletions src/Payment/Aggregates/Address.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,19 @@ public function getZipCode()
*/
public function setZipCode($zipCode)
{
$zipCode = str_replace('-', '', $zipCode);
$this->zipCode = substr($zipCode, 0, 16);
$zipCode = trim($zipCode);

if (empty($zipCode)) {
$inputName = $this->i18n->getDashboard('zipCode');
$message = $this->i18n->getDashboard(
"The %s should not be empty!",
$inputName
);

throw new \Exception($message, 400);
}

$this->zipCode = $this->formatZipCode($zipCode);

return $this;
}
Expand All @@ -227,8 +238,9 @@ public function getCity()
*/
public function setCity($city)
{
$this->city = substr($city, 0, 64);

$this->city = trim(
substr($city, 0, 64)
);
if (empty($this->city)) {

$inputName = $this->i18n->getDashboard('city');
Expand Down Expand Up @@ -281,7 +293,7 @@ public function getLine1()
$line[] = $this->getStreet();
$line[] = $this->getNeighborhood();

return implode (self::ADDRESS_LINE_SEPARATOR, $line);
return implode(self::ADDRESS_LINE_SEPARATOR, $line);
}

public function getLine2()
Expand Down Expand Up @@ -341,7 +353,7 @@ public function jsonSerialize()
$obj->country = $this->country;
$obj->line1 = $this->getLine1();
$obj->line2 = $this->getLine2();

return $obj;
}

Expand All @@ -365,4 +377,19 @@ public function convertToSDKRequest()

return $addressRequest;
}
}

private function formatZipCode($zipCode)
{
$zipCode = str_replace('-', '', $zipCode);

$brazilianZipCodeLength = 8;
if (strtoupper($this->country) === 'BR') {
$zipCode = sprintf("%0${brazilianZipCodeLength}s", $zipCode);
$zipCode = substr($zipCode, 0, $brazilianZipCodeLength);
return $zipCode;
}

$zipCode = substr($zipCode, 0, 16);
return $zipCode;
}
}
Loading

0 comments on commit 1e78f71

Please sign in to comment.