Skip to content
This repository has been archived by the owner on Apr 24, 2023. It is now read-only.

Commit

Permalink
Merge pull request #82 from gabriellucius/partial-refund
Browse files Browse the repository at this point in the history
Partial refund
  • Loading branch information
s2it-moscou committed Mar 28, 2018
2 parents f3204f1 + a6fc58a commit 50bbc82
Show file tree
Hide file tree
Showing 14 changed files with 381 additions and 72 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
Changelog
---------
3.11.0
- Checkout sem endereço (para produtos do tipo 'virtual' e 'downloadable')
- Valida se o telefone do comprador foi configurado antes de tentar usar o telefone do endereço de entrega
- Habilitar/desabilitar recuperação de carrinho do PagSeguro via admin
- Atualizada versão da biblioteca PHP do PagSeguro usada no módulo
- Tela de listar transações no admin, permitindo ver detalhes da transação
- Estorno parcial
- Fix: Corrigido id dos itens do pedido (carrinho) enviados para o PagSeguro

3.5.1
- Corrigido bug de incompatibilidade com PHP 5.4 no checkout

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Com o módulo instalado e configurado, você pode pode oferecer o PagSeguro como
- Certifique-se de que não há instalação de outros módulos para o PagSeguro em seu sistema;
- Caso utilize a compilação do Magento, desative-a e limpe-a *(Sistema -> Ferramentas -> Compilação)*;
- Baixe a última versão do módulo **[nesse link](https://github.com/pagseguro/magento/raw/master/UOL_PagSeguro-3.5.1.tgz)** ou então baixe o repositório como arquivo zip através do botão do GitHub;
- Baixe a última versão do módulo **[nesse link](https://github.com/pagseguro/magento/raw/master/UOL_PagSeguro-3.11.0.tgz)** ou então baixe o repositório como arquivo zip através do botão do GitHub;
- Na área administrativa do seu Magento, acesse o menu *Sistema/System -> Magento Connect -> Magento Connect Manager*. Caso tenha uma versão anterior do módulo instalada faça a remoção agora;
- No Magento Connect Manger, dentro da seção Direct package file upload, clique em **Escolher arquivo/Choose file**, selecione o arquivo UOL_PagSeguro-x.x.x.tgz (baixado anteriormente), clique no botão de upload e acompanhe a instalação do módulo no console da página;
- Caso utilize a compilação, volte para a área administrativa do Magento, ative-a e execute-a novamente;
Expand Down Expand Up @@ -97,6 +97,7 @@ Para acessar e configurar o módulo acesse o menu PagSeguro -> Configurações.
- **transações -> cancelamento**: esta pesquisa retornará todas as transações que estejam com status "em análise" e "aguardando pagamento", dentro da quantidade de dias definidos para a pesquisa. Desta forma você pode solicitar o cancelamento destas transações.
- **transações -> conciliação**: permite consultar as transações efetivadas no PagSeguro nos últimos 30 dias. A pesquisa retornará um comparativo com o status das transações em sua base local e o status atual da transação no PagSeguro, desta forma você pode identificar e atualizar transações com status divergentes.
- **transações -> estorno**: esta pesquisa retornará todas as transações que estejam com status "paga", "disponível" e "em disputa", dentro da quantidade de dias definidos para a pesquisa. Desta forma você pode solicitar o estorno dos valores pagos para seus compradores.
- **transações -> listar transações**: esta pesquisa retorna as últimas transações realizadas pela sua loja no PagSeguro, permitindo utilizar diversos filtros (data, id do pedido, do pagseguro, status) ao realizar uma consulta. A partir do resultado dessa consulta é possível ver os detalhes de cada pedido no PagSeguro através da ação "Ver detalhes transação".
- **requisitos**: exibe se os pré-requisitos básicos para o correto funcionamento do módulo estão sendo atendidos
> É aconselhável que antes de usar as funcionalidades de **estorno** ou **cancelamento** você faça a **conciliação** de suas transações para obter os status mais atuais.
Expand Down
Binary file added UOL_PagSeguro-3.11.0.tgz
Binary file not shown.
Binary file removed UOL_PagSeguro-3.5.1.tgz
Binary file not shown.
34 changes: 28 additions & 6 deletions app/code/community/UOL/PagSeguro/Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class UOL_PagSeguro_Helper_Data extends Mage_Payment_Helper_Data
7 => "cancelada_ps",
8 => "chargeback_debitado_ps",
9 => "em_contestacao_ps",
10 => "partially_refunded",
);

/**
Expand Down Expand Up @@ -456,25 +457,32 @@ final public function notificationModel()
*
* @throws Exception
*/
public function updateOrderStatusMagento($class, $orderId, $transactionCode, $orderStatus)
public function updateOrderStatusMagento($class, $orderId, $transactionCode, $orderStatus, $refundValue = null)
{
try {
if (
$this->getLastStatusOrder($orderId) != $orderStatus
|| $class == self::CANCELED_CLASS
|| $class == self::REFUND_CLASS
) {
$comment = null;
if ($class == self::CANCELED_CLASS) {
if ($this->webserviceHelper()->cancelRequest($transactionCode)->getResult() == 'OK') {
$orderStatus = 'cancelada_ps';
}
}
if ($class == self::REFUND_CLASS) {
if ($this->webserviceHelper()->refundRequest($transactionCode)->getResult() == 'OK') {
$orderStatus = 'devolvida_ps';
if ($this->webserviceHelper()->refundRequest($transactionCode, $refundValue)->getResult() == 'OK') {
/* if have refund value is an partially refund, so the status should be keeped */
if ($refundValue) {
$comment = 'Estornado valor de R$' . $refundValue . ' do seu pedido.';
$this->setPartiallyRefundedStatus($orderId);
} else {
$orderStatus = 'devolvida_ps';
}
}
}
$this->notifyCustomer($orderId, $orderStatus);
$this->notifyCustomer($orderId, $orderStatus, $comment);
Mage::helper('pagseguro/log')->setUpdateOrderLog($class, $orderId, $transactionCode, $orderStatus);
}
$this->setTransactionRecord($orderId, $transactionCode);
Expand All @@ -499,10 +507,9 @@ protected function getLastStatusOrder($orderId)
* @param $orderId
* @param $orderStatus
*/
private function notifyCustomer($orderId, $orderStatus)
private function notifyCustomer($orderId, $orderStatus, $comment = null)
{
$status = $orderStatus;
$comment = null;
$notify = true;
$order = Mage::getModel('sales/order')->load($orderId);
$order->addStatusToHistory($status, $comment, $notify);
Expand Down Expand Up @@ -811,4 +818,19 @@ public function getTransactionTypeName($transactionTypeCode)
}
}
}

/**
* Updates respective order partially refunded status to 1 in pagseguro_orders table
*
* @param string $orderId
* @return void
*/
public function setPartiallyRefundedStatus($orderId)
{
try {
Mage::helper('pagseguro/refund')->setPartiallyRefunded($orderId);
} catch (Exception $pse) {
throw $pse;
}
}
}
63 changes: 61 additions & 2 deletions app/code/community/UOL/PagSeguro/Helper/Refund.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,13 @@ protected function getMagentoPayments()
$date = $date->format("Y-m-d\TH:i:s");
$collection = Mage::getModel('sales/order')->getCollection()
->addAttributeToFilter('created_at', array('from' => $date, 'to' => date('Y-m-d H:i:s')));
/** used to validate if an order is already refunded (could be refunded only one time) */
$partiallyRefundedOrdersArray = $this->getPartiallyRefundedOrders();

foreach ($collection as $order) {
$this->magentoPaymentList[] = $order->getId();
if (! in_array($order->getId(), $partiallyRefundedOrdersArray)) {
$this->magentoPaymentList[] = $order->getId();
}
}
}

Expand Down Expand Up @@ -211,10 +216,14 @@ public function build($PagSeguroSummaryItem, $order)
$config = " onclick='Modal.alertConciliation(""
.$this->alertConciliation($this->__('estornar'))."")'";
}
//echo '<pre>';print_r($PagSeguroSummaryItem);exit;
$actionOrder = "<a class='edit' target='_blank' href='".$this->getEditOrderUrl($order->getId())."'>";
$actionOrder .= $this->__('Ver detalhes')."</a>";
$actionOrder .= "<a ".$config." href='javascript:void(0)'>";
$actionOrder .= $this->__('Estornar')."</a>";
$actionOrder .= $this->__('Estorno total')."</a>";
$config = "class='action' data-config='".$order->getId().'/'.$PagSeguroSummaryItem->getCode().'/'.$this->getPaymentStatusFromKey($PagSeguroSummaryItem->getStatus()).'/'.$PagSeguroSummaryItem->getGrossAmount().'/'.$order->getIncrementId()."'";
$actionOrder .= "<a ".$config." href='javascript:void(0)'>";
$actionOrder .= $this->__('Estorno parcial')."</a>";

return array(
'date' => $this->getOrderMagetoDateConvert($order->getCreatedAt()),
Expand All @@ -224,4 +233,54 @@ public function build($PagSeguroSummaryItem, $order)
'action' => $actionOrder,
);
}

/**
* Get all pagseguro partially refunded orders id
*
* @return array
*/
private function getPartiallyRefundedOrders()
{
$pagseguroOrdersIdArray = array();
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('core_read');
$pagseguroTable = Mage::getConfig()->getTablePrefix().'pagseguro_orders';


$select = $read->select()
->from(array('ps' => $pagseguroTable), array('order_id'))
->where('ps.partially_refunded = ?', '1')
;

if (!is_null(Mage::getSingleton('core/session')->getData("store_id"))) {
$select = $select->where('ps.store_id = ?', Mage::getSingleton('core/session')->getData("store_id"));
}

if (Mage::getStoreConfig('payment/pagseguro/environment')) {
$select = $select->where('ps.environment = ?', Mage::getStoreConfig('payment/pagseguro/environment'));
}

$read->prepare($select);

foreach ($read->fetchAll($select) as $value) {
$pagseguroOrdersIdArray[] = $value['order_id'];
}

return $pagseguroOrdersIdArray;
}

/**
* Set 1 to partially_refunded field in pagseguro_orders table
*
* @param string $orderId
* @return void
*/
public function setPartiallyRefunded($orderId)
{
$pagseguroTable = Mage::getConfig()->getTablePrefix().'pagseguro_orders';
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$where = $connection->quoteInto('order_id = ?', $orderId);
$data = array('partially_refunded' => 1);
$connection->update($pagseguroTable, $data, $where);
}
}
5 changes: 4 additions & 1 deletion app/code/community/UOL/PagSeguro/Helper/Transactions.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ private function getTransactionsDatabase($paramsFilter)
->join(array('ps' => $pagseguroTable), 'order.entity_id = ps.order_id')
->where('ps.transaction_code != ?', '')
->order('created_at DESC')
->limit(400)
;

if (!is_null(Mage::getSingleton('core/session')->getData("store_id"))) {
Expand All @@ -89,7 +90,9 @@ private function getTransactionsDatabase($paramsFilter)
}

if (isset($paramsFilter['status'])) {
$select = $select->where('order.status = ?', $this->getPaymentStatusFromKey($paramsFilter['status']));
$select = ($this->getPaymentStatusFromKey($paramsFilter['status']) == 'partially_refunded')
? $select->where('ps.partially_refunded = ?', 1)
: $select->where('order.status = ?', $this->getPaymentStatusFromKey($paramsFilter['status']));
}

if (isset($paramsFilter['startDate']) && isset($paramsFilter['endDate'])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,14 @@ public function doRefundAction()
if ($this->getRequest()->getPost('data')) {
$data = current($this->getRequest()->getPost('data'));
try {
$refundValue = $data['refundValue'] ? number_format(floatval($data['refundValue']), 2, '.', '') : null;
$this->refund->updateOrderStatusMagento(get_class($this->refund), $data['id'], $data['code'],
$data['status']);
$data['status'], $refundValue);
} catch (Exception $pse) {
$erro = simplexml_load_string($pse->getMessage());
print json_encode(array(
"status" => false,
"err" => trim($pse->getMessage()),
"err" => trim(current($erro->error->code)),
)
);
exit();
Expand Down
2 changes: 1 addition & 1 deletion app/code/community/UOL/PagSeguro/etc/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ limitations under the License.
<config>
<modules>
<UOL_PagSeguro>
<version>3.5.1</version>
<version>3.11.0</version>
</UOL_PagSeguro>
</modules>
<global>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/**
************************************************************************
Copyright [2015] [PagSeguro Internet Ltda.]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************
*/

$installer = $this;
$installer->startSetup();
/**
* Add column to validate if a transaction has been already partially refunded
*/
$installer->getConnection()
->addColumn($installer->getTable('pagseguro_orders'), 'partially_refunded', array(
'type' => Varien_Db_Ddl_Table::TYPE_BOOLEAN,
'nullable' => false,
'default' => 0,
'comment' => 'Show if order is already partially refunded',
)
);

$installer->endSetup();
Loading

0 comments on commit 50bbc82

Please sign in to comment.