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

Commit 50bbc82

Browse files
authored
Merge pull request #82 from gabriellucius/partial-refund
Partial refund
2 parents f3204f1 + a6fc58a commit 50bbc82

File tree

14 files changed

+381
-72
lines changed

14 files changed

+381
-72
lines changed

CHANGELOG.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
Changelog
22
---------
3+
3.11.0
4+
- Checkout sem endereço (para produtos do tipo 'virtual' e 'downloadable')
5+
- Valida se o telefone do comprador foi configurado antes de tentar usar o telefone do endereço de entrega
6+
- Habilitar/desabilitar recuperação de carrinho do PagSeguro via admin
7+
- Atualizada versão da biblioteca PHP do PagSeguro usada no módulo
8+
- Tela de listar transações no admin, permitindo ver detalhes da transação
9+
- Estorno parcial
10+
- Fix: Corrigido id dos itens do pedido (carrinho) enviados para o PagSeguro
11+
312
3.5.1
413
- Corrigido bug de incompatibilidade com PHP 5.4 no checkout
514

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Com o módulo instalado e configurado, você pode pode oferecer o PagSeguro como
3030
3131
- Certifique-se de que não há instalação de outros módulos para o PagSeguro em seu sistema;
3232
- Caso utilize a compilação do Magento, desative-a e limpe-a *(Sistema -> Ferramentas -> Compilação)*;
33-
- 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;
33+
- 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;
3434
- 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;
3535
- 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;
3636
- Caso utilize a compilação, volte para a área administrativa do Magento, ative-a e execute-a novamente;
@@ -97,6 +97,7 @@ Para acessar e configurar o módulo acesse o menu PagSeguro -> Configurações.
9797
- **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.
9898
- **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.
9999
- **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.
100+
- **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".
100101
- **requisitos**: exibe se os pré-requisitos básicos para o correto funcionamento do módulo estão sendo atendidos
101102
> É 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.
102103

UOL_PagSeguro-3.11.0.tgz

526 KB
Binary file not shown.

UOL_PagSeguro-3.5.1.tgz

-504 KB
Binary file not shown.

app/code/community/UOL/PagSeguro/Helper/Data.php

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ class UOL_PagSeguro_Helper_Data extends Mage_Payment_Helper_Data
4949
7 => "cancelada_ps",
5050
8 => "chargeback_debitado_ps",
5151
9 => "em_contestacao_ps",
52+
10 => "partially_refunded",
5253
);
5354

5455
/**
@@ -456,25 +457,32 @@ final public function notificationModel()
456457
*
457458
* @throws Exception
458459
*/
459-
public function updateOrderStatusMagento($class, $orderId, $transactionCode, $orderStatus)
460+
public function updateOrderStatusMagento($class, $orderId, $transactionCode, $orderStatus, $refundValue = null)
460461
{
461462
try {
462463
if (
463464
$this->getLastStatusOrder($orderId) != $orderStatus
464465
|| $class == self::CANCELED_CLASS
465466
|| $class == self::REFUND_CLASS
466467
) {
468+
$comment = null;
467469
if ($class == self::CANCELED_CLASS) {
468470
if ($this->webserviceHelper()->cancelRequest($transactionCode)->getResult() == 'OK') {
469471
$orderStatus = 'cancelada_ps';
470472
}
471473
}
472474
if ($class == self::REFUND_CLASS) {
473-
if ($this->webserviceHelper()->refundRequest($transactionCode)->getResult() == 'OK') {
474-
$orderStatus = 'devolvida_ps';
475+
if ($this->webserviceHelper()->refundRequest($transactionCode, $refundValue)->getResult() == 'OK') {
476+
/* if have refund value is an partially refund, so the status should be keeped */
477+
if ($refundValue) {
478+
$comment = 'Estornado valor de R$' . $refundValue . ' do seu pedido.';
479+
$this->setPartiallyRefundedStatus($orderId);
480+
} else {
481+
$orderStatus = 'devolvida_ps';
482+
}
475483
}
476484
}
477-
$this->notifyCustomer($orderId, $orderStatus);
485+
$this->notifyCustomer($orderId, $orderStatus, $comment);
478486
Mage::helper('pagseguro/log')->setUpdateOrderLog($class, $orderId, $transactionCode, $orderStatus);
479487
}
480488
$this->setTransactionRecord($orderId, $transactionCode);
@@ -499,10 +507,9 @@ protected function getLastStatusOrder($orderId)
499507
* @param $orderId
500508
* @param $orderStatus
501509
*/
502-
private function notifyCustomer($orderId, $orderStatus)
510+
private function notifyCustomer($orderId, $orderStatus, $comment = null)
503511
{
504512
$status = $orderStatus;
505-
$comment = null;
506513
$notify = true;
507514
$order = Mage::getModel('sales/order')->load($orderId);
508515
$order->addStatusToHistory($status, $comment, $notify);
@@ -811,4 +818,19 @@ public function getTransactionTypeName($transactionTypeCode)
811818
}
812819
}
813820
}
821+
822+
/**
823+
* Updates respective order partially refunded status to 1 in pagseguro_orders table
824+
*
825+
* @param string $orderId
826+
* @return void
827+
*/
828+
public function setPartiallyRefundedStatus($orderId)
829+
{
830+
try {
831+
Mage::helper('pagseguro/refund')->setPartiallyRefunded($orderId);
832+
} catch (Exception $pse) {
833+
throw $pse;
834+
}
835+
}
814836
}

app/code/community/UOL/PagSeguro/Helper/Refund.php

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,13 @@ protected function getMagentoPayments()
117117
$date = $date->format("Y-m-d\TH:i:s");
118118
$collection = Mage::getModel('sales/order')->getCollection()
119119
->addAttributeToFilter('created_at', array('from' => $date, 'to' => date('Y-m-d H:i:s')));
120+
/** used to validate if an order is already refunded (could be refunded only one time) */
121+
$partiallyRefundedOrdersArray = $this->getPartiallyRefundedOrders();
122+
120123
foreach ($collection as $order) {
121-
$this->magentoPaymentList[] = $order->getId();
124+
if (! in_array($order->getId(), $partiallyRefundedOrdersArray)) {
125+
$this->magentoPaymentList[] = $order->getId();
126+
}
122127
}
123128
}
124129

@@ -211,10 +216,14 @@ public function build($PagSeguroSummaryItem, $order)
211216
$config = " onclick='Modal.alertConciliation(""
212217
.$this->alertConciliation($this->__('estornar'))."")'";
213218
}
219+
//echo '<pre>';print_r($PagSeguroSummaryItem);exit;
214220
$actionOrder = "<a class='edit' target='_blank' href='".$this->getEditOrderUrl($order->getId())."'>";
215221
$actionOrder .= $this->__('Ver detalhes')."</a>";
216222
$actionOrder .= "<a ".$config." href='javascript:void(0)'>";
217-
$actionOrder .= $this->__('Estornar')."</a>";
223+
$actionOrder .= $this->__('Estorno total')."</a>";
224+
$config = "class='action' data-config='".$order->getId().'/'.$PagSeguroSummaryItem->getCode().'/'.$this->getPaymentStatusFromKey($PagSeguroSummaryItem->getStatus()).'/'.$PagSeguroSummaryItem->getGrossAmount().'/'.$order->getIncrementId()."'";
225+
$actionOrder .= "<a ".$config." href='javascript:void(0)'>";
226+
$actionOrder .= $this->__('Estorno parcial')."</a>";
218227

219228
return array(
220229
'date' => $this->getOrderMagetoDateConvert($order->getCreatedAt()),
@@ -224,4 +233,54 @@ public function build($PagSeguroSummaryItem, $order)
224233
'action' => $actionOrder,
225234
);
226235
}
236+
237+
/**
238+
* Get all pagseguro partially refunded orders id
239+
*
240+
* @return array
241+
*/
242+
private function getPartiallyRefundedOrders()
243+
{
244+
$pagseguroOrdersIdArray = array();
245+
$resource = Mage::getSingleton('core/resource');
246+
$read = $resource->getConnection('core_read');
247+
$pagseguroTable = Mage::getConfig()->getTablePrefix().'pagseguro_orders';
248+
249+
250+
$select = $read->select()
251+
->from(array('ps' => $pagseguroTable), array('order_id'))
252+
->where('ps.partially_refunded = ?', '1')
253+
;
254+
255+
if (!is_null(Mage::getSingleton('core/session')->getData("store_id"))) {
256+
$select = $select->where('ps.store_id = ?', Mage::getSingleton('core/session')->getData("store_id"));
257+
}
258+
259+
if (Mage::getStoreConfig('payment/pagseguro/environment')) {
260+
$select = $select->where('ps.environment = ?', Mage::getStoreConfig('payment/pagseguro/environment'));
261+
}
262+
263+
$read->prepare($select);
264+
265+
foreach ($read->fetchAll($select) as $value) {
266+
$pagseguroOrdersIdArray[] = $value['order_id'];
267+
}
268+
269+
return $pagseguroOrdersIdArray;
270+
}
271+
272+
/**
273+
* Set 1 to partially_refunded field in pagseguro_orders table
274+
*
275+
* @param string $orderId
276+
* @return void
277+
*/
278+
public function setPartiallyRefunded($orderId)
279+
{
280+
$pagseguroTable = Mage::getConfig()->getTablePrefix().'pagseguro_orders';
281+
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
282+
$where = $connection->quoteInto('order_id = ?', $orderId);
283+
$data = array('partially_refunded' => 1);
284+
$connection->update($pagseguroTable, $data, $where);
285+
}
227286
}

app/code/community/UOL/PagSeguro/Helper/Transactions.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ private function getTransactionsDatabase($paramsFilter)
7070
->join(array('ps' => $pagseguroTable), 'order.entity_id = ps.order_id')
7171
->where('ps.transaction_code != ?', '')
7272
->order('created_at DESC')
73+
->limit(400)
7374
;
7475

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

9192
if (isset($paramsFilter['status'])) {
92-
$select = $select->where('order.status = ?', $this->getPaymentStatusFromKey($paramsFilter['status']));
93+
$select = ($this->getPaymentStatusFromKey($paramsFilter['status']) == 'partially_refunded')
94+
? $select->where('ps.partially_refunded = ?', 1)
95+
: $select->where('order.status = ?', $this->getPaymentStatusFromKey($paramsFilter['status']));
9396
}
9497

9598
if (isset($paramsFilter['startDate']) && isset($paramsFilter['endDate'])) {

app/code/community/UOL/PagSeguro/controllers/Adminhtml/RefundController.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,14 @@ public function doRefundAction()
4646
if ($this->getRequest()->getPost('data')) {
4747
$data = current($this->getRequest()->getPost('data'));
4848
try {
49+
$refundValue = $data['refundValue'] ? number_format(floatval($data['refundValue']), 2, '.', '') : null;
4950
$this->refund->updateOrderStatusMagento(get_class($this->refund), $data['id'], $data['code'],
50-
$data['status']);
51+
$data['status'], $refundValue);
5152
} catch (Exception $pse) {
53+
$erro = simplexml_load_string($pse->getMessage());
5254
print json_encode(array(
5355
"status" => false,
54-
"err" => trim($pse->getMessage()),
56+
"err" => trim(current($erro->error->code)),
5557
)
5658
);
5759
exit();

app/code/community/UOL/PagSeguro/etc/config.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ limitations under the License.
1919
<config>
2020
<modules>
2121
<UOL_PagSeguro>
22-
<version>3.5.1</version>
22+
<version>3.11.0</version>
2323
</UOL_PagSeguro>
2424
</modules>
2525
<global>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
/**
4+
************************************************************************
5+
Copyright [2015] [PagSeguro Internet Ltda.]
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
************************************************************************
19+
*/
20+
21+
$installer = $this;
22+
$installer->startSetup();
23+
/**
24+
* Add column to validate if a transaction has been already partially refunded
25+
*/
26+
$installer->getConnection()
27+
->addColumn($installer->getTable('pagseguro_orders'), 'partially_refunded', array(
28+
'type' => Varien_Db_Ddl_Table::TYPE_BOOLEAN,
29+
'nullable' => false,
30+
'default' => 0,
31+
'comment' => 'Show if order is already partially refunded',
32+
)
33+
);
34+
35+
$installer->endSetup();

0 commit comments

Comments
 (0)