CanRefund.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sales\Model\Order\Validation;
  7. use Magento\Framework\Pricing\PriceCurrencyInterface;
  8. use Magento\Sales\Api\Data\OrderInterface;
  9. use Magento\Sales\Model\Order;
  10. use Magento\Sales\Model\ValidatorInterface;
  11. /**
  12. * Class CanRefund
  13. */
  14. class CanRefund implements ValidatorInterface
  15. {
  16. /**
  17. * @var PriceCurrencyInterface
  18. */
  19. private $priceCurrency;
  20. /**
  21. * CanRefund constructor.
  22. *
  23. * @param PriceCurrencyInterface $priceCurrency
  24. */
  25. public function __construct(PriceCurrencyInterface $priceCurrency)
  26. {
  27. $this->priceCurrency = $priceCurrency;
  28. }
  29. /**
  30. * @inheritdoc
  31. */
  32. public function validate($entity)
  33. {
  34. $messages = [];
  35. if ($entity->getState() === Order::STATE_PAYMENT_REVIEW ||
  36. $entity->getState() === Order::STATE_HOLDED ||
  37. $entity->getState() === Order::STATE_CANCELED ||
  38. $entity->getState() === Order::STATE_CLOSED
  39. ) {
  40. $messages[] = __(
  41. 'A creditmemo can not be created when an order has a status of %1',
  42. $entity->getStatus()
  43. );
  44. } elseif (!$this->isTotalPaidEnoughForRefund($entity)) {
  45. $messages[] = __('The order does not allow a creditmemo to be created.');
  46. }
  47. return $messages;
  48. }
  49. /**
  50. * We can have problem with float in php (on some server $a=762.73;$b=762.73; $a-$b!=0)
  51. * for this we have additional diapason for 0
  52. * TotalPaid - contains amount, that were not rounded.
  53. *
  54. * @param OrderInterface $order
  55. * @return bool
  56. */
  57. private function isTotalPaidEnoughForRefund(OrderInterface $order)
  58. {
  59. return !abs($this->priceCurrency->round($order->getTotalPaid()) - $order->getTotalRefunded()) < .0001;
  60. }
  61. }