1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\Order\Invoice\Validation;
use Magento\Payment\Model\InfoInterface;
use Magento\Payment\Model\MethodInterface;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\OrderPaymentRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Invoice;
use Magento\Sales\Model\ValidatorInterface;
/**
* Class CanRefund
*/
class CanRefund implements ValidatorInterface
{
/**
* @var OrderPaymentRepositoryInterface
*/
private $paymentRepository;
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* CanRefund constructor.
*
* @param OrderPaymentRepositoryInterface $paymentRepository
* @param OrderRepositoryInterface $orderRepository
*/
public function __construct(
OrderPaymentRepositoryInterface $paymentRepository,
OrderRepositoryInterface $orderRepository
) {
$this->paymentRepository = $paymentRepository;
$this->orderRepository = $orderRepository;
}
/**
* @inheritdoc
*/
public function validate($entity)
{
if ($entity->getState() == Invoice::STATE_PAID &&
$this->isGrandTotalEnoughToRefund($entity) &&
$this->isPaymentAllowRefund($entity)
) {
return [];
}
return [__('We can\'t create creditmemo for the invoice.')];
}
/**
* @param InvoiceInterface $invoice
* @return bool
*/
private function isPaymentAllowRefund(InvoiceInterface $invoice)
{
$order = $this->orderRepository->get($invoice->getOrderId());
$payment = $order->getPayment();
if (!$payment instanceof InfoInterface) {
return false;
}
$method = $payment->getMethodInstance();
return $this->canPartialRefund($method, $payment) || $this->canFullRefund($invoice, $method);
}
/**
* @param InvoiceInterface $entity
* @return bool
*/
private function isGrandTotalEnoughToRefund(InvoiceInterface $entity)
{
return abs($entity->getBaseGrandTotal() - $entity->getBaseTotalRefunded()) >= .0001;
}
/**
* @param MethodInterface $method
* @param InfoInterface $payment
* @return bool
*/
private function canPartialRefund(MethodInterface $method, InfoInterface $payment)
{
return $method->canRefund() &&
$method->canRefundPartialPerInvoice() &&
$payment->getAmountPaid() > $payment->getAmountRefunded();
}
/**
* @param InvoiceInterface $invoice
* @param MethodInterface $method
* @return bool
*/
private function canFullRefund(InvoiceInterface $invoice, MethodInterface $method)
{
return $method->canRefund() && !$invoice->getIsUsedForRefund();
}
}