Cron.php 59.9 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/**
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * Adyen Payment module (https://www.adyen.com/)
 *
 * Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
 * See LICENSE.txt for license details.
 *
 * Author: Adyen <magento@adyen.com>
 */
23 24 25

namespace Adyen\Payment\Model;

26
use Magento\Framework\Webapi\Exception;
27 28 29 30 31 32 33 34 35 36 37
use Magento\Sales\Model\Order\Email\Sender\OrderSender;

class Cron
{

    /**
     * Logging instance
     * @var \Adyen\Payment\Logger\AdyenLogger
     */
    protected $_logger;

38

39 40 41
    /**
     * @var Resource\Notification\CollectionFactory
     */
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    protected $_notificationFactory;

    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $_orderFactory;

    /**
     * @var \Magento\Sales\Model\Order
     */
    protected $_order;

    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

61 62 63
    /**
     * @var \Adyen\Payment\Helper\Data
     */
64 65 66 67 68 69 70
    protected $_adyenHelper;

    /**
     * @var OrderSender
     */
    protected $_orderSender;

rikterbeek's avatar
rikterbeek committed
71 72 73 74 75
    /**
     * @var \Magento\Framework\DB\TransactionFactory
     */
    protected $_transactionFactory;

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    /**
     * @var \Adyen\Payment\Model\Billing\AgreementFactory
     */
    protected $_billingAgreementFactory;

    /**
     * @var Resource\Billing\Agreement\CollectionFactory
     */
    protected $_billingAgreementCollectionFactory;

    /**
     * @var Api\PaymentRequest
     */
    protected $_adyenPaymentRequest;

91 92 93
    /**
     * notification attributes
     */
94
    protected $_pspReference;
95

96 97 98 99 100
    /**
     * @var
     */
    protected $_originalReference;

101 102 103
    /**
     * @var
     */
104
    protected $_merchantReference;
105 106 107 108

    /**
     * @var
     */
109
    protected $_eventCode;
110 111 112 113

    /**
     * @var
     */
114
    protected $_success;
115 116 117 118

    /**
     * @var
     */
119
    protected $_paymentMethod;
120 121 122 123

    /**
     * @var
     */
124
    protected $_reason;
125 126 127 128

    /**
     * @var
     */
129
    protected $_value;
130 131 132 133

    /**
     * @var
     */
134
    protected $_boletoOriginalAmount;
135 136 137 138

    /**
     * @var
     */
139
    protected $_boletoPaidAmount;
140 141 142 143

    /**
     * @var
     */
144
    protected $_modificationResult;
145 146 147 148

    /**
     * @var
     */
149
    protected $_klarnaReservationNumber;
150 151 152 153

    /**
     * @var
     */
154 155
    protected $_fraudManualReview;

156 157 158 159 160 161 162 163 164 165
    /**
     * @var Order\PaymentFactory
     */
    protected $_adyenOrderPaymentFactory;

    /**
     * @var Resource\Order\Payment\CollectionFactory
     */
    protected $_adyenOrderPaymentCollectionFactory;

166
    /**
167 168
     * Cron constructor.
     *
169 170 171 172 173 174 175
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
     * @param Resource\Notification\CollectionFactory $notificationFactory
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Adyen\Payment\Helper\Data $adyenHelper
     * @param OrderSender $orderSender
     * @param \Magento\Framework\DB\TransactionFactory $transactionFactory
176
     * @param Billing\AgreementFactory $billingAgreementFactory
177
     * @param Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
178
     * @param Api\PaymentRequest $paymentRequest
179 180 181 182 183 184 185
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
        \Adyen\Payment\Model\Resource\Notification\CollectionFactory $notificationFactory,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Adyen\Payment\Helper\Data $adyenHelper,
rikterbeek's avatar
rikterbeek committed
186
        OrderSender $orderSender,
187 188 189
        \Magento\Framework\DB\TransactionFactory $transactionFactory,
        \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory,
        \Adyen\Payment\Model\Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
190 191 192
        \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest,
        \Adyen\Payment\Model\Order\PaymentFactory $adyenOrderPaymentFactory,
        \Adyen\Payment\Model\Resource\Order\Payment\CollectionFactory $adyenOrderPaymentCollectionFactory
193
    ) {
194
        $this->_scopeConfig = $scopeConfig;
195
        $this->_adyenLogger = $adyenLogger;
196 197 198 199
        $this->_notificationFactory = $notificationFactory;
        $this->_orderFactory = $orderFactory;
        $this->_adyenHelper = $adyenHelper;
        $this->_orderSender = $orderSender;
rikterbeek's avatar
rikterbeek committed
200
        $this->_transactionFactory = $transactionFactory;
201 202 203
        $this->_billingAgreementFactory = $billingAgreementFactory;
        $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
        $this->_adyenPaymentRequest = $paymentRequest;
204 205
        $this->_adyenOrderPaymentFactory = $adyenOrderPaymentFactory;
        $this->_adyenOrderPaymentCollectionFactory = $adyenOrderPaymentCollectionFactory;
206 207
    }

208 209 210 211
    /**
     * Process the notification
     * @return void
     */
212 213
    public function processNotification()
    {
214 215
        $this->_order = null;

216
        // execute notifications from 2 minute or earlier because order could not yet been created by magento
217
        $dateStart = new \DateTime();
218
        $dateStart->modify('-5 day');
219
        $dateEnd = new \DateTime();
220
        $dateEnd->modify('-1 minute');
221 222
        $dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true];

223
        // create collection
224 225 226 227
        $notifications = $this->_notificationFactory->create();
        $notifications->addFieldToFilter('done', 0);
        $notifications->addFieldToFilter('created_at', $dateRange);

228
        // loop over the notifications
229
        $count = 0;
230
        foreach ($notifications as $notification) {
231

232 233 234 235
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf("Processing notification %s", $notification->getEntityId())
            );

236
            // log the executed notification
237
            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($notification->debug(), 1));
238

239 240 241 242 243
            // get order
            $incrementId = $notification->getMerchantReference();

            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
            if (!$this->_order->getId()) {
244 245 246 247

                // order does not exists remove from queue
                $notification->delete();
                continue;
248 249 250 251 252 253 254 255 256
            }

            // declare all variables that are needed
            $this->_declareVariables($notification);

            // add notification to comment history status is current status
            $this->_addStatusHistoryComment();

            $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
257

258 259
            // update order details
            $this->_updateAdyenAttributes($notification);
260 261 262

            // check if success is true of false
            if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) {
263 264 265 266 267 268 269 270
                /*
                 * Only cancel the order when it is in state pending, payment review or
                 * if the ORDER_CLOSED is failed (means split payment has not be successful)
                 */
                if ($this->_order->getState() === \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT ||
                    $this->_order->getState() === \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW ||
                    $this->_eventCode == Notification::ORDER_CLOSED) {

271
                    $this->_adyenLogger->addAdyenNotificationCronjob('Going to cancel the order');
272 273

                    // if payment is API check, check if API result pspreference is the same as reference
274
                    if ($this->_eventCode == NOTIFICATION::AUTHORISATION && $this->_getPaymentMethodType() == 'api') {
275
                        // don't cancel the order becasue order was successfull through api
276 277 278
                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'order is not cancelled because api result was succesfull'
                        );
279
                    } else {
280 281 282 283 284 285 286
                        /*
                         * don't cancel the order if previous state is authorisation with success=true
                         * Split payments can fail if the second payment has failed the first payment is
                         * refund/cancelled as well so if it is a split payment that failed cancel the order as well
                         */
                        if ($previousAdyenEventCode != "AUTHORISATION : TRUE" ||
                            $this->_eventCode == Notification::ORDER_CLOSED) {
287 288 289
                            $this->_holdCancelOrder(false);
                        } else {
                            $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode);
290 291 292 293
                            $this->_adyenLogger->addAdyenNotificationCronjob(
                                'order is not cancelled because previous notification 
                                was an authorisation that succeeded'
                            );
294 295 296
                        }
                    }
                } else {
297 298 299
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Order is already processed so ignore this notification state is:' . $this->_order->getState()
                    );
300 301 302 303 304 305 306 307
                }
            } else {
                // Notification is successful
                $this->_processNotification();
            }

            $this->_order->save();

308 309 310 311 312
            // set done to true
            $dateEnd = new \DateTime();
            $notification->setDone(true);
            $notification->setUpdatedAt($dateEnd);
            $notification->save();
313 314 315 316 317 318 319 320
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf("Notification %s is processed", $notification->getEntityId())
            );
            ++$count;
        }

        if ($count > 0) {
            $this->_adyenLogger->addAdyenNotificationCronjob(sprintf("Cronjob updated %s notification(s)", $count));
321 322 323
        }
    }

324 325 326 327 328 329
    /**
     * Declare private variables for processing notification
     *
     * @param Object $notification
     * @return void
     */
330 331 332 333
    protected function _declareVariables($notification)
    {
        //  declare the common parameters
        $this->_pspReference = $notification->getPspreference();
334
        $this->_originalReference = $notification->getOriginalReference();
335 336 337 338 339 340 341 342 343 344 345
        $this->_merchantReference = $notification->getMerchantReference();
        $this->_eventCode = $notification->getEventCode();
        $this->_success = $notification->getSuccess();
        $this->_paymentMethod = $notification->getPaymentMethod();
        $this->_reason = $notification->getPaymentMethod();
        $this->_value = $notification->getAmountValue();


        $additionalData = unserialize($notification->getAdditionalData());

        // boleto data
346 347
        if ($this->_paymentMethodCode() == "adyen_boleto") {
            if ($additionalData && is_array($additionalData)) {
348
                $boletobancario = isset($additionalData['boletobancario']) ? $additionalData['boletobancario'] : null;
349 350 351 352 353
                if ($boletobancario && is_array($boletobancario)) {
                    $this->_boletoOriginalAmount =
                        isset($boletobancario['originalAmount']) ? trim($boletobancario['originalAmount']) : "";
                    $this->_boletoPaidAmount =
                        isset($boletobancario['paidAmount']) ? trim($boletobancario['paidAmount']) : "";
354 355 356 357
                }
            }
        }

358
        if ($additionalData && is_array($additionalData)) {
359 360

            // check if the payment is in status manual review
361 362 363
            $fraudManualReview = isset($additionalData['fraudManualReview']) ?
                $additionalData['fraudManualReview'] : "";
            if ($fraudManualReview == "true") {
364 365 366 367 368
                $this->_fraudManualReview = true;
            } else {
                $this->_fraudManualReview = false;
            }

369
            // modification.action is it for JSON
370 371 372
            $modificationActionJson = isset($additionalData['modification.action']) ?
                $additionalData['modification.action'] : null;
            if ($modificationActionJson != "") {
373 374 375
                $this->_modificationResult = $modificationActionJson;
            }

376
            $modification = isset($additionalData['modification']) ? $additionalData['modification'] : null;
377
            if ($modification && is_array($modification)) {
378
                $this->_modificationResult = isset($modification['action']) ? trim($modification['action']) : "";
379 380
            }
            $additionalData2 = isset($additionalData['additionalData']) ? $additionalData['additionalData'] : null;
381
            if ($additionalData2 && is_array($additionalData2)) {
382 383 384 385 386 387 388 389 390 391 392 393 394
                $this->_klarnaReservationNumber = isset($additionalData2['acquirerReference']) ? trim($additionalData2['acquirerReference']) : "";
            }
        }
    }

    /**
     * @return mixed
     */
    protected function _paymentMethodCode()
    {
        return $this->_order->getPayment()->getMethod();
    }

395 396 397 398 399
    /**
     * @return mixed
     */
    protected function _getPaymentMethodType()
    {
rikterbeek's avatar
rikterbeek committed
400 401 402
        return $this->_order->getPayment()->getPaymentMethodType();
    }

403 404 405 406 407 408
    /**
     * @desc order comments or history
     * @param type $order
     */
    protected function _addStatusHistoryComment()
    {
409 410 411
        $successResult = (strcmp($this->_success, 'true') == 0 ||
            strcmp($this->_success, '1') == 0) ? 'true' : 'false';
        $success = (!empty($this->_reason)) ? "$successResult <br />reason:$this->_reason" : $successResult;
412

413
        if ($this->_eventCode == Notification::REFUND || $this->_eventCode == Notification::CAPTURE) {
414 415 416 417 418 419 420

            $currency = $this->_order->getOrderCurrencyCode();

            // check if it is a full or partial refund
            $amount = $this->_value;
            $orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency);

421 422 423
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'amount notification:'.$amount . ' amount order:'.$orderAmount
            );
424

425 426 427 428
            if ($amount == $orderAmount) {
                $this->_order->setData(
                    'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
                );
429
            } else {
430 431 432 433
                $this->_order->setData(
                    'adyen_notification_event_code', "(PARTIAL) " .
                    $this->_eventCode . " : " . strtoupper($successResult)
                );
434 435
            }
        } else {
436 437 438
            $this->_order->setData(
                'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
            );
439 440
        }

Rik ter Beek's avatar
Rik ter Beek committed
441
        // if payment method is klarna, ratepay or openinvoice/afterpay show the reservartion number
442
        if (($this->_paymentMethod == "klarna" || $this->_paymentMethod == "afterpay_default" ||
Rik ter Beek's avatar
Rik ter Beek committed
443 444
                $this->_paymentMethod == "openinvoice" || $this->_paymentMethod == "ratepay"
            ) && ($this->_klarnaReservationNumber != null &&
445
                $this->_klarnaReservationNumber != "")) {
446 447 448 449 450
            $klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber;
        } else {
            $klarnaReservationNumberText = "";
        }

451
        if ($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") {
452 453 454 455 456 457
            $boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount;
        } else {
            $boletoPaidAmountText = "";
        }

        $type = 'Adyen HTTP Notification(s):';
458 459 460
        $comment = __('%1 <br /> eventCode: %2 <br /> pspReference: %3 <br /> paymentMethod: %4 <br />' .
            ' success: %5 %6 %7', $type, $this->_eventCode, $this->_pspReference, $this->_paymentMethod,
            $success, $klarnaReservationNumberText, $boletoPaidAmountText);
461 462

        // If notification is pending status and pending status is set add the status change to the comment history
463
        if ($this->_eventCode == Notification::PENDING) {
464
            $pendingStatus = $this->_getConfigData('pending_status', 'adyen_abstract', $this->_order->getStoreId());
465
            if ($pendingStatus != "") {
466
                $this->_order->addStatusHistoryComment($comment, $pendingStatus);
467 468 469
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Created comment history for this notification with status change to: ' . $pendingStatus
                );
470 471 472 473 474
                return;
            }
        }

        // if manual review is accepted and a status is selected. Change the status through this comment history item
475 476
        if ($this->_eventCode == Notification::MANUAL_REVIEW_ACCEPT
            && $this->_getFraudManualReviewAcceptStatus() != "") {
477 478
            $manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus();
            $this->_order->addStatusHistoryComment($comment, $manualReviewAcceptStatus);
479
            $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus);
480 481 482 483
            return;
        }

        $this->_order->addStatusHistoryComment($comment);
484
        $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification');
485 486
    }

487 488 489
    /**
     * @param $notification
     */
490 491
    protected function _updateAdyenAttributes($notification)
    {
492
        $this->_adyenLogger->addAdyenNotificationCronjob('Updating the Adyen attributes of the order');
493 494 495 496 497 498

        $additionalData = unserialize($notification->getAdditionalData());
        $_paymentCode = $this->_paymentMethodCode();

        if ($this->_eventCode == Notification::AUTHORISATION
            || $this->_eventCode == Notification::HANDLED_EXTERNALLY
499 500 501 502 503 504 505 506 507 508
            || ($this->_eventCode == Notification::CAPTURE && $_paymentCode == "adyen_pos")) {

            /*
             * if current notification is authorisation : false and
             * the  previous notification was authorisation : true do not update pspreference
             */
            if (strcmp($this->_success, 'false') == 0 ||
                strcmp($this->_success, '0') == 0 ||
                strcmp($this->_success, '') == 0) {

509 510 511 512 513 514 515 516 517 518
                $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
                if ($previousAdyenEventCode != "AUTHORISATION : TRUE") {
                    $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
                }
            } else {
                $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
            }
        }
    }

519 520 521
    /**
     * @param $additionalData
     */
522 523 524 525 526 527 528 529
    protected function _updateOrderPaymentWithAdyenAttributes($additionalData)
    {
        if ($additionalData && is_array($additionalData)) {
            $avsResult = (isset($additionalData['avsResult'])) ? $additionalData['avsResult'] : "";
            $cvcResult = (isset($additionalData['cvcResult'])) ? $additionalData['cvcResult'] : "";
            $totalFraudScore = (isset($additionalData['totalFraudScore'])) ? $additionalData['totalFraudScore'] : "";
            $ccLast4 = (isset($additionalData['cardSummary'])) ? $additionalData['cardSummary'] : "";
            $refusalReasonRaw = (isset($additionalData['refusalReasonRaw'])) ? $additionalData['refusalReasonRaw'] : "";
530 531
            $acquirerReference = (isset($additionalData['acquirerReference'])) ?
                $additionalData['acquirerReference'] : "";
532 533 534 535 536 537 538 539 540 541 542 543
            $authCode = (isset($additionalData['authCode'])) ? $additionalData['authCode'] : "";
        }

        // if there is no server communication setup try to get last4 digits from reason field
        if (!isset($ccLast4) || $ccLast4 == "") {
            $ccLast4 = $this->_retrieveLast4DigitsFromReason($this->_reason);
        }

        $this->_order->getPayment()->setAdyenPspReference($this->_pspReference);
        $this->_order->getPayment()->setAdditionalInformation('pspReference', $this->_pspReference);

        if ($this->_klarnaReservationNumber != "") {
544 545 546
            $this->_order->getPayment()->setAdditionalInformation(
                'adyen_klarna_number', $this->_klarnaReservationNumber
            );
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        }
        if (isset($ccLast4) && $ccLast4 != "") {
            // this field is column in db by core
            $this->_order->getPayment()->setccLast4($ccLast4);
        }
        if (isset($avsResult) && $avsResult != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_avs_result', $avsResult);
        }
        if (isset($cvcResult) && $cvcResult != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_cvc_result', $cvcResult);
        }
        if ($this->_boletoPaidAmount != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_boleto_paid_amount', $this->_boletoPaidAmount);
        }
        if (isset($totalFraudScore) && $totalFraudScore != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_total_fraud_score', $totalFraudScore);
        }
        if (isset($refusalReasonRaw) && $refusalReasonRaw != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_refusal_reason_raw', $refusalReasonRaw);
        }
        if (isset($acquirerReference) && $acquirerReference != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_acquirer_reference', $acquirerReference);
        }
        if (isset($authCode) && $authCode != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_auth_code', $authCode);
        }
    }

    /**
     * retrieve last 4 digits of card from the reason field
     * @param $reason
     * @return string
     */
    protected function _retrieveLast4DigitsFromReason($reason)
    {
        $result = "";

584
        if ($reason != "") {
585
            $reasonArray = explode(":", $reason);
586 587
            if ($reasonArray != null && is_array($reasonArray)) {
                if (isset($reasonArray[1])) {
588 589 590 591 592 593 594
                    $result = $reasonArray[1];
                }
            }
        }
        return $result;
    }

595
    /**
596 597
     * @param $ignoreHasInvoice
     * @throws \Magento\Framework\Exception\LocalizedException
598 599 600 601 602 603 604 605
     */
    protected function _holdCancelOrder($ignoreHasInvoice)
    {
        $orderStatus = $this->_getConfigData('payment_cancelled', 'adyen_abstract', $this->_order->getStoreId());

        // check if order has in invoice only cancel/hold if this is not the case
        if ($ignoreHasInvoice || !$this->_order->hasInvoices()) {

606
            if ($orderStatus == \Magento\Sales\Model\Order::STATE_HOLDED) {
607 608 609 610

                // Allow magento to hold order
                $this->_order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_HOLD, true);

611 612 613
                if ($this->_order->canHold()) {
                    $this->_order->hold();
                } else {
614
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not hold or is already on Hold');
615 616 617
                    return;
                }
            } else {
618 619 620
                // Allow magento to cancel order
                $this->_order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_CANCEL, true);

621 622 623
                if ($this->_order->canCancel()) {
                    $this->_order->cancel();
                } else {
624
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not be canceled');
625 626 627 628
                    return;
                }
            }
        } else {
629
            $this->_adyenLogger->addAdyenNotificationCronjob('Order has already an invoice so cannot be canceled');
630 631 632 633
        }
    }

    /**
634
     * Process the Notification
635 636 637
     */
    protected function _processNotification()
    {
638
        $this->_adyenLogger->addAdyenNotificationCronjob('Processing the notification');
639 640 641 642 643 644 645
        $_paymentCode = $this->_paymentMethodCode();

        switch ($this->_eventCode) {
            case Notification::REFUND_FAILED:
                // do nothing only inform the merchant with order comment history
                break;
            case Notification::REFUND:
646 647 648 649
                $ignoreRefundNotification = $this->_getConfigData(
                    'ignore_refund_notification', 'adyen_abstract', $this->_order->getStoreId()
                );
                if ($ignoreRefundNotification != true) {
rikterbeek's avatar
rikterbeek committed
650
                    $this->_refundOrder();
651
                    //refund completed
rikterbeek's avatar
rikterbeek committed
652
                    $this->_setRefundAuthorized();
653
                } else {
654 655 656
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Setting to ignore refund notification is enabled so ignore this notification'
                    );
657 658 659
                }
                break;
            case Notification::PENDING:
660 661 662
                if ($this->_getConfigData(
                    'send_email_bank_sepa_on_pending', 'adyen_abstract', $this->_order->getStoreId())
                ) {
663
                    // Check if payment is banktransfer or sepa if true then send out order confirmation email
rikterbeek's avatar
rikterbeek committed
664
                    $isBankTransfer = $this->_isBankTransfer();
665 666
                    if ($isBankTransfer || $this->_paymentMethod == 'sepadirectdebit') {
                        if (!$this->_order->getEmailSent()) {
667
                            $this->_orderSender->send($this->_order);
668
                            $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
669
                        }
670 671 672 673 674 675
                    }
                }
                break;
            case Notification::HANDLED_EXTERNALLY:
            case Notification::AUTHORISATION:
                // for POS don't do anything on the AUTHORIZATION
676
                if ($_paymentCode != "adyen_pos") {
677 678 679 680 681 682 683
                    $this->_authorizePayment();
                }
                break;
            case Notification::MANUAL_REVIEW_REJECT:
                // don't do anything it will send a CANCEL_OR_REFUND notification when this payment is captured
                break;
            case Notification::MANUAL_REVIEW_ACCEPT:
684 685 686 687
                /*
                 * only process this if you are on auto capture.
                 * On manual capture you will always get Capture or CancelOrRefund notification
                 */
688
                if ($this->_isAutoCapture()) {
689
                    $this->_setPaymentAuthorized(false);
690 691 692
                }
                break;
            case Notification::CAPTURE:
693 694 695 696 697
                if ($_paymentCode != "adyen_pos") {
                    /*
                     * ignore capture if you are on auto capture
                     * this could be called if manual review is enabled and you have a capture delay
                     */
698
                    if (!$this->_isAutoCapture()) {
699
                        $this->_setPaymentAuthorized(false, true);
700 701 702
                    }
                } else {
                    // FOR POS authorize the payment on the CAPTURE notification
rikterbeek's avatar
rikterbeek committed
703
                    $this->_authorizePayment();
704 705 706 707 708 709 710 711
                }
                break;
            case Notification::CAPTURE_FAILED:
            case Notification::CANCELLATION:
            case Notification::CANCELLED:
                $this->_holdCancelOrder(true);
                break;
            case Notification::CANCEL_OR_REFUND:
712 713
                if (isset($this->_modificationResult) && $this->_modificationResult != "") {
                    if ($this->_modificationResult == "cancel") {
714
                        $this->_holdCancelOrder(true);
715
                    } elseif ($this->_modificationResult == "refund") {
rikterbeek's avatar
rikterbeek committed
716
                        $this->_refundOrder();
717
                        //refund completed
rikterbeek's avatar
rikterbeek committed
718
                        $this->_setRefundAuthorized();
719 720
                    }
                } else {
721 722 723 724 725 726
                    if ($this->_order->isCanceled() ||
                        $this->_order->getState() === \Magento\Sales\Model\Order::STATE_HOLDED) {

                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'Order is already cancelled or holded so do nothing'
                        );
rikterbeek's avatar
rikterbeek committed
727
                    } else if ($this->_order->canCancel() || $this->_order->canHold()) {
728
                        $this->_adyenLogger->addAdyenNotificationCronjob('try to cancel the order');
rikterbeek's avatar
rikterbeek committed
729
                        $this->_holdCancelOrder(true);
730
                    } else {
731
                        $this->_adyenLogger->addAdyenNotificationCronjob('try to refund the order');
732
                        // refund
rikterbeek's avatar
rikterbeek committed
733
                        $this->_refundOrder();
734
                        //refund completed
rikterbeek's avatar
rikterbeek committed
735
                        $this->_setRefundAuthorized();
736 737 738
                    }
                }
                break;
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
            case Notification::RECURRING_CONTRACT:

                // storedReferenceCode
                $recurringDetailReference = $this->_pspReference;

                // check if there is already a BillingAgreement
                $billingAgreement = $this->_billingAgreementFactory->create();
                $billingAgreement->load($recurringDetailReference, 'reference_id');


                if ($billingAgreement && $billingAgreement->getAgreementId() > 0 && $billingAgreement->isValid()) {

                    try {
                        $billingAgreement->addOrderRelation($this->_order);
                        $billingAgreement->setStatus($billingAgreement::STATUS_ACTIVE);
                        $billingAgreement->setIsObjectChanged(true);
                        $this->_order->addRelatedObject($billingAgreement);
                        $message = __('Used existing billing agreement #%s.', $billingAgreement->getReferenceId());
                    } catch (Exception $e) {
                        // could be that it is already linked to this order
                        $message = __('Used existing billing agreement #%s.', $billingAgreement->getReferenceId());
                    }
                } else {

                    $this->_order->getPayment()->setBillingAgreementData(
                        [
                            'billing_agreement_id' => $recurringDetailReference,
                            'method_code' => $this->_order->getPayment()->getMethodCode(),
                        ]
                    );

                    // create new object
                    $billingAgreement = $this->_billingAgreementFactory->create();
                    $billingAgreement->setStoreId($this->_order->getStoreId());
                    $billingAgreement->importOrderPayment($this->_order->getPayment());

                    // get all data for this contract by doing a listRecurringCall
                    $customerReference = $billingAgreement->getCustomerReference();
                    $storeId = $billingAgreement->getStoreId();

779 780 781 782 783
                    /*
                     * for quest checkout users we can't save this in the billing agreement
                     * because it is linked to customer
                     */
                    if ($customerReference && $storeId) {
784

785 786
                        $listRecurringContracts = null;
                        try {
787 788 789
                            $listRecurringContracts = $this->_adyenPaymentRequest->getRecurringContractsForShopper(
                                $customerReference, $storeId
                            );
790 791
                        } catch(\Exception $exception) {
                            $this->_adyenLogger->addAdyenNotificationCronjob($exception->getMessage());
792 793
                        }

794
                        $contractDetail = null;
795
                        // get current Contract details and get list of all current ones
796
                        $recurringReferencesList = [];
797

798
                        if ($listRecurringContracts) {
799 800
                            foreach ($listRecurringContracts as $rc) {
                                $recurringReferencesList[] = $rc['recurringDetailReference'];
801 802
                                if (isset($rc['recurringDetailReference']) &&
                                    $rc['recurringDetailReference'] == $recurringDetailReference) {
803 804 805 806
                                    $contractDetail = $rc;
                                }
                            }
                        }
807

808
                        if ($contractDetail != null) {
809 810 811 812 813 814
                            // update status of all the current saved agreements in magento
                            $billingAgreements = $this->_billingAgreementCollectionFactory->create();
                            $billingAgreements->addFieldToFilter('customer_id', $customerReference);

                            // get collection

815 816 817 818 819
                            foreach ($billingAgreements as $updateBillingAgreement) {
                                if (!in_array($updateBillingAgreement->getReferenceId(), $recurringReferencesList)) {
                                    $updateBillingAgreement->setStatus(
                                        \Adyen\Payment\Model\Billing\Agreement::STATUS_CANCELED
                                    );
820 821
                                    $updateBillingAgreement->save();
                                } else {
822 823 824
                                    $updateBillingAgreement->setStatus(
                                        \Adyen\Payment\Model\Billing\Agreement::STATUS_ACTIVE
                                    );
825 826
                                    $updateBillingAgreement->save();
                                }
827 828
                            }

829 830 831 832
                            // add this billing agreement
                            $billingAgreement->parseRecurringContractData($contractDetail);
                            if ($billingAgreement->isValid()) {
                                $message = __('Created billing agreement #%1.', $billingAgreement->getReferenceId());
833

834 835
                                // save into sales_billing_agreement_order
                                $billingAgreement->addOrderRelation($this->_order);
836

837 838 839 840 841
                                // add to order to save agreement
                                $this->_order->addRelatedObject($billingAgreement);
                            } else {
                                $message = __('Failed to create billing agreement for this order.');
                            }
842 843


844 845 846 847 848 849
                        } else {
                            $this->_adyenLogger->addAdyenNotificationCronjob(
                                'Failed to create billing agreement for this order ' .
                                '(listRecurringCall did not contain contract)'
                            );
                            $this->_adyenLogger->addAdyenNotificationCronjob(
850
                                __('recurringDetailReference in notification is %1', $recurringDetailReference)
851 852
                            );
                            $this->_adyenLogger->addAdyenNotificationCronjob(
853
                                __('CustomerReference is: %1 and storeId is %2', $customerReference, $storeId)
854
                            );
855
                            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($listRecurringContracts, 1));
856 857 858 859
                            $message = __(
                                'Failed to create billing agreement for this order ' .
                                '(listRecurringCall did not contain contract)'
                            );
860
                        }
861

862 863 864
                        $comment = $this->_order->addStatusHistoryComment($message);
                        $this->_order->addRelatedObject($comment);
                    }
865 866
                }
                break;
867
            default:
868 869 870
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    sprintf('This notification event: %s is not supported so will be ignored', $this->_eventCode)
                );
871 872 873 874
                break;
        }
    }

rikterbeek's avatar
rikterbeek committed
875 876 877 878 879 880
    /**
     * Not implemented
     * @return bool
     */
    protected function _refundOrder()
    {
881 882
        $this->_adyenLogger->addAdyenNotificationCronjob('Refunding the order');

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        // check if it is a split payment if so save the refunded data
        if ($this->_originalReference != "") {

            $this->_adyenLogger->addAdyenNotificationCronjob('Going to update the refund to split payments table');

            $orderPayment = $this->_adyenOrderPaymentCollectionFactory
                ->create()
                ->addFieldToFilter(\Adyen\Payment\Model\Notification::PSPREFRENCE, $this->_originalReference)
                ->getFirstItem();

            if ($orderPayment->getId() > 0) {
                $currency = $this->_order->getOrderCurrencyCode();
                $amountRefunded = $amountRefunded =  $orderPayment->getTotalRefunded() +
                    $this->_adyenHelper->originalAmount($this->_value, $currency);
                $orderPayment->setUpdatedAt(new \DateTime());
                $orderPayment->setTotalRefunded($amountRefunded);
                $orderPayment->save();
                $this->_adyenLogger->addAdyenNotificationCronjob('Update the refund in the split payments table');
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob('Payment not found in split payment table');
            }
        }

906 907 908 909
        /*
         * Don't create a credit memo if refund is initialize in Magento
         * because in this case the credit memo already exists
         */
910
        $lastTransactionId = $this->_order->getPayment()->getLastTransId();
911
        if ($lastTransactionId != $this->_pspReference) {
912 913 914 915 916 917

            // refund is done through adyen backoffice so create an invoice
            $order = $this->_order;
            if ($order->canCreditmemo()) {

                // there is a bug in this function of Magento see #2656 magento\magento2 repo
918 919 920 921 922 923
                // Invalid method Magento\Sales\Model\Order\Creditmemo::register
                /*
                $currency = $this->_order->getOrderCurrencyCode();
                $amount = $this->_adyenHelper->originalAmount($this->_value, $currency);
                $order->getPayment()->registerRefundNotification($amount);
                */
924

925
                $this->_adyenLogger->addAdyenNotificationCronjob('Please create your credit memo inside magento');
926 927 928 929
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob('Could not create a credit memo for order');
            }
        } else {
930 931 932
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Did not create a credit memo for this order becasue refund is done through Magento'
            );
933
        }
rikterbeek's avatar
rikterbeek committed
934 935 936 937 938 939 940
    }

    /**
     * @param $order
     */
    protected function _setRefundAuthorized()
    {
941 942 943
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Status update to default status or refund_authorized status if this is set'
        );
rikterbeek's avatar
rikterbeek committed
944 945 946
        $this->_order->addStatusHistoryComment(__('Adyen Refund Successfully completed'));
    }

947
    /**
948
     * authorize payment
949 950 951
     */
    protected function _authorizePayment()
    {
952
        $this->_adyenLogger->addAdyenNotificationCronjob('Authorisation of the order');
953 954 955
        $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();

        // If manual review is active and a seperate status is used then ignore the pre authorized status
956
        if ($this->_fraudManualReview != true || $fraudManualReviewStatus == "") {
957 958
            $this->_setPrePaymentAuthorized();
        } else {
959 960 961 962
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Ignore the pre authorized status because the order is ' .
                'under manual review and use the Manual review status'
            );
963 964 965 966 967 968
        }

        $this->_prepareInvoice();
        $_paymentCode = $this->_paymentMethodCode();

        // for boleto confirmation mail is send on order creation
969
        if ($this->_paymentMethod != "adyen_boleto") {
970
            // send order confirmation mail after invoice creation so merchant can add invoicePDF to this mail
971
            if (!$this->_order->getEmailSent()) {
972
                $this->_orderSender->send($this->_order);
973
                $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
974
            }
975 976
        }

977 978 979 980 981
        if (($this->_paymentMethod == "c_cash" &&
                $this->_getConfigData('create_shipment', 'adyen_cash', $this->_order->getStoreId())) ||
            ($this->_getConfigData('create_shipment', 'adyen_pos', $this->_order->getStoreId()) &&
                $_paymentCode == "adyen_pos")) {

rikterbeek's avatar
rikterbeek committed
982
            $this->_createShipment();
983 984 985
        }
    }

986 987 988
    /**
     * Set status on authorisation
     */
989 990 991 992 993
    private function _setPrePaymentAuthorized()
    {
        $status = $this->_getConfigData('payment_pre_authorized', 'adyen_abstract', $this->_order->getStoreId());

        // only do this if status in configuration is set
994
        if (!empty($status)) {
rikterbeek's avatar
rikterbeek committed
995
            $this->_order->addStatusHistoryComment(__('Payment is authorised waiting for capture'), $status);
996 997 998
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Order status is changed to Pre-authorised status, status is ' . $status
            );
999
        } else {
1000
            $this->_adyenLogger->addAdyenNotificationCronjob('No pre-authorised status is used so ignore');
1001 1002 1003 1004
        }
    }

    /**
1005
     * @throws Exception
1006 1007 1008
     */
    protected function _prepareInvoice()
    {
1009
        $this->_adyenLogger->addAdyenNotificationCronjob('Prepare invoice for order');
1010 1011 1012 1013 1014

        //Set order state to new because with order state payment_review it is not possible to create an invoice
        if (strcmp($this->_order->getState(), \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW) == 0) {
            $this->_order->setState(\Magento\Sales\Model\Order::STATE_NEW);
        }
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024
        $paymentObj = $this->_order->getPayment();

        // set pspReference as transactionId
        $paymentObj->setCcTransId($this->_pspReference);
        $paymentObj->setLastTransId($this->_pspReference);

        // set transaction
        $paymentObj->setTransactionId($this->_pspReference);

1025 1026 1027
        //capture mode
        if (!$this->_isAutoCapture()) {
            $this->_order->addStatusHistoryComment(__('Capture Mode set to Manual'));
1028
            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to Manual');
1029 1030

            // show message if order is in manual review
1031
            if ($this->_fraudManualReview) {
1032 1033
                // check if different status is selected
                $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1034
                if ($fraudManualReviewStatus != "") {
1035 1036 1037 1038 1039 1040
                    $status = $fraudManualReviewStatus;
                    $comment = "Adyen Payment is in Manual Review check the Adyen platform";
                    $this->_order->addStatusHistoryComment(__($comment), $status);
                }
            }

1041 1042 1043 1044 1045 1046 1047 1048
            $createPendingInvoice = (bool) $this->_getConfigData(
                'create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()
            );

            if (!$createPendingInvoice) {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Setting pending invoice is off so don\'t create an invoice wait for the capture notification'
                );
1049 1050 1051 1052 1053 1054
                return;
            }
        }

        // validate if amount is total amount
        $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        $amount = $this->_adyenHelper->originalAmount($this->_value, $orderCurrencyCode);

        // add to order payment
        $date = new \DateTime();
        $this->_adyenOrderPaymentFactory->create()
            ->setPspreference($this->_pspReference)
            ->setMerchantReference($this->_merchantReference)
            ->setPaymentId($paymentObj->getId())
            ->setPaymentMethod($this->_paymentMethod)
            ->setAmount($amount)
            ->setTotalRefunded(0)
            ->setCreatedAt($date)
            ->setUpdatedAt($date)
            ->save();


        if ($this->_isTotalAmount($paymentObj->getEntityId(), $orderCurrencyCode)) {
1072
            $this->_createInvoice();
1073
        } else {
1074 1075 1076
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'This is a partial AUTHORISATION and the full amount is not reached'
            );
1077 1078 1079 1080 1081 1082 1083 1084
        }
    }

    /**
     * @return bool
     */
    protected function _isAutoCapture()
    {
1085
        // validate if payment methods allowes manual capture
1086
        if ($this->_manualCaptureAllowed()) {
1087
            $captureMode = trim($this->_getConfigData('capture_mode', 'adyen_abstract', $this->_order->getStoreId()));
1088
            $sepaFlow = trim($this->_getConfigData('sepa_flow', 'adyen_abstract', $this->_order->getStoreId()));
1089
            $_paymentCode = $this->_paymentMethodCode();
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
            $captureModeOpenInvoice = $this->_getConfigData(
                'auto_capture_openinvoice', 'adyen_abstract', $this->_order->getStoreId()
            );
            $captureModePayPal = trim($this->_getConfigData(
                'paypal_capture_mode', 'adyen_abstract', $this->_order->getStoreId())
            );

            /*
             * if you are using authcap the payment method is manual.
             * There will be a capture send to indicate if payment is successful
             */
            if (($_paymentCode == "adyen_sepa" || $this->_paymentMethod == "sepadirectdebit") &&
                $sepaFlow == "authcap") {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Manual Capture is applied for sepa because it is in authcap flow'
                );
1106 1107
                return false;
            }
1108

1109
            // payment method ideal, cash adyen_boleto or adyen_pos has direct capture
1110 1111 1112 1113
            if ($_paymentCode == "adyen_pos" || (($_paymentCode == "adyen_sepa" ||
                        $this->_paymentMethod == "sepadirectdebit") && $sepaFlow != "authcap")) {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method does not allow manual capture.(2) paymentCode:' .
1114
                    $_paymentCode . ' paymentMethod:' . $this->_paymentMethod . ' sepaFLow:'.$sepaFlow
1115
                );
1116 1117
                return true;
            }
1118

1119
            // if auto capture mode for openinvoice is turned on then use auto capture
1120
            if ($captureModeOpenInvoice == true &&
1121 1122
                $this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod)
            ) {
1123 1124 1125
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method is configured to be working as auto capture '
                );
1126
                return true;
1127 1128
            }
            // if PayPal capture modues is different from the default use this one
1129 1130 1131 1132 1133
            if (strcmp($this->_paymentMethod, 'paypal' ) === 0 && $captureModePayPal != "") {
                if (strcmp($captureModePayPal, 'auto') === 0 ) {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as auto capture'
                    );
1134
                    return true;
1135 1136 1137 1138
                } elseif (strcmp($captureModePayPal, 'manual') === 0 ) {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as manual capture'
                    );
1139 1140 1141 1142
                    return false;
                }
            }
            if (strcmp($captureMode, 'manual') === 0) {
1143
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for this payment is set to manual');
1144 1145
                return false;
            }
1146 1147 1148 1149 1150

            /*
             * online capture after delivery, use Magento backend to online invoice
             * (if the option auto capture mode for openinvoice is not set)
             */
1151
            if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod)) {
1152
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for klarna is by default set to manual');
1153 1154
                return false;
            }
1155 1156

            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to auto capture');
1157 1158 1159 1160
            return true;

        } else {
            // does not allow manual capture so is always immediate capture
1161
            $this->_adyenLogger->addAdyenNotificationCronjob('This payment method does not allow manual capture');
1162
            return true;
1163
        }
1164 1165 1166 1167 1168 1169

    }

    /**
     * Validate if this payment methods allows manual capture
     * This is a default can be forced differently to overrule on acquirer level
1170 1171
     *
     * @return bool|null
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
     */
    protected function _manualCaptureAllowed()
    {
        $manualCaptureAllowed = null;
        $paymentMethod = $this->_paymentMethod;

        switch($paymentMethod) {
            case 'cup':
            case 'cartebancaire':
            case 'visa':
            case 'mc':
            case 'uatp':
            case 'amex':
            case 'bcmc':
            case 'maestro':
rikterbeek's avatar
rikterbeek committed
1187
            case 'maestrouk':
1188 1189 1190 1191 1192 1193 1194
            case 'diners':
            case 'discover':
            case 'jcb':
            case 'laser':
            case 'paypal':
            case 'klarna':
            case 'afterpay_default':
Rik ter Beek's avatar
Rik ter Beek committed
1195
            case 'ratepay':
1196 1197 1198 1199 1200
            case 'sepadirectdebit':
                $manualCaptureAllowed = true;
                break;
            default:
                // To be sure check if it payment method starts with afterpay_ then manualCapture is allowed
1201
                if (strlen($this->_paymentMethod) >= 9 && substr($this->_paymentMethod, 0, 9) == "afterpay_") {
1202 1203 1204
                    $manualCaptureAllowed = true;
                }
                $manualCaptureAllowed = false;
1205
        }
1206 1207

        return $manualCaptureAllowed;
1208 1209 1210 1211 1212 1213
    }

    /**
     * @return bool
     */
    protected function _isBankTransfer() {
1214
        if (strlen($this->_paymentMethod) >= 12 && substr($this->_paymentMethod, 0, 12) == "bankTransfer") {
1215 1216 1217 1218 1219 1220 1221
            $isBankTransfer = true;
        } else {
            $isBankTransfer = false;
        }
        return $isBankTransfer;
    }

1222 1223 1224
    /**
     * @return mixed
     */
1225 1226 1227 1228 1229
    protected function _getFraudManualReviewStatus()
    {
        return $this->_getConfigData('fraud_manual_review_status', 'adyen_abstract', $this->_order->getStoreId());
    }

1230 1231 1232
    /**
     * @return mixed
     */
1233 1234
    protected function _getFraudManualReviewAcceptStatus()
    {
1235 1236 1237
        return $this->_getConfigData(
            'fraud_manual_review_accept_status', 'adyen_abstract', $this->_order->getStoreId()
        );
1238 1239
    }

1240 1241 1242 1243
    /**
     * @param $orderAmount
     * @return bool
     */
1244
    protected function _isTotalAmount($paymentId, $orderCurrencyCode)
1245 1246 1247 1248
    {
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Validate if AUTHORISATION notification has the total amount of the order'
        );
1249

1250 1251 1252 1253 1254 1255 1256
        // get total amount of the order
        $grandTotal = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode);

        // check if total amount of the order is authorised
        $res = $this->_adyenOrderPaymentCollectionFactory
            ->create()
            ->getTotalAmount($paymentId);
1257

1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
        if($res && isset($res[0]) && is_array($res[0])) {
            $amount = $res[0]['total_amount'];
            $orderAmount = $this->_adyenHelper->formatAmount($amount, $orderCurrencyCode);
            $this->_adyenLogger->addAdyenNotificationCronjob(sprintf('The grandtotal amount is %s and the total order amount that is authorised is: %s', $grandTotal, $orderAmount));

            if ($grandTotal == $orderAmount) {
                $this->_adyenLogger->addAdyenNotificationCronjob('AUTHORISATION has the full amount');
                return true;
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This is a partial AUTHORISATION, the amount is ' . $this->_value
                );
                return false;
            }
1272
        }
1273
        return false;
1274 1275
    }

1276 1277 1278 1279
    /**
     * @throws Exception
     * @throws \Magento\Framework\Exception\LocalizedException
     */
1280 1281
    protected function _createInvoice()
    {
1282
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating invoice for order');
1283 1284 1285

        if ($this->_order->canInvoice()) {

1286 1287
            /* We do not use this inside a transaction because order->save()
             * is always done on the end of the notification
1288 1289 1290 1291 1292 1293 1294
             * and it could result in a deadlock see https://github.com/Adyen/magento/issues/334
             */
            try {
                $invoice = $this->_order->prepareInvoice();
                $invoice->getOrder()->setIsInProcess(true);

                // set transaction id so you can do a online refund from credit memo
1295
                $invoice->setTransactionId($this->_pspReference);
1296

1297

1298
                $autoCapture = $this->_isAutoCapture();
1299 1300 1301
                $createPendingInvoice = (bool) $this->_getConfigData(
                    'create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()
                );
1302

1303
                if ((!$autoCapture) && ($createPendingInvoice)) {
1304 1305 1306

                    // if amount is zero create a offline invoice
                    $value = (int)$this->_value;
1307
                    if ($value == 0) {
rikterbeek's avatar
rikterbeek committed
1308
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
1309
                    } else {
rikterbeek's avatar
rikterbeek committed
1310
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::NOT_CAPTURE);
1311 1312 1313 1314 1315 1316 1317 1318
                    }

                    $invoice->register();
                } else {
                    $invoice->register()->pay();
                }

                $invoice->save();
1319
                $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice');
1320
            } catch (Exception $e) {
1321 1322 1323
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Error saving invoice. The error message is: ' . $e->getMessage()
                );
1324 1325 1326 1327 1328
                throw new Exception(sprintf('Error saving invoice. The error message is:', $e->getMessage()));
            }

            $this->_setPaymentAuthorized();

1329 1330 1331 1332
            $invoiceAutoMail = (bool) $this->_getConfigData(
                'send_invoice_update_mail', 'adyen_abstract', $this->_order->getStoreId()
            );

1333 1334 1335 1336
            if ($invoiceAutoMail) {
                $invoice->sendEmail();
            }
        } else {
1337
            $this->_adyenLogger->addAdyenNotificationCronjob('It is not possible to create invoice for this order');
1338 1339 1340 1341
        }
    }

    /**
1342 1343 1344
     * @param bool $manualReviewComment
     * @param bool $createInvoice
     * @throws Exception
1345 1346 1347
     */
    protected function _setPaymentAuthorized($manualReviewComment = true, $createInvoice = false)
    {
1348
        $this->_adyenLogger->addAdyenNotificationCronjob('Set order to authorised');
1349 1350 1351 1352 1353 1354 1355

        // if full amount is captured create invoice
        $currency = $this->_order->getOrderCurrencyCode();
        $amount = $this->_value;
        $orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency);

        // create invoice for the capture notification if you are on manual capture
1356 1357 1358 1359
        if ($createInvoice == true && $amount == $orderAmount) {
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'amount notification:'.$amount . ' amount order:'.$orderAmount
            );
rikterbeek's avatar
rikterbeek committed
1360
            $this->_createInvoice();
1361
        }
1362 1363
        
        $status = $this->_getConfigData('payment_authorized', 'adyen_abstract', $this->_order->getStoreId());
1364 1365

        // virtual order can have different status
1366
        if ($this->_order->getIsVirtual()) {
1367
            $this->_adyenLogger->addAdyenNotificationCronjob('Product is a virtual product');
1368 1369 1370
            $virtualStatus = $this->_getConfigData('payment_authorized_virtual');
            if ($virtualStatus != "") {
                $status = $virtualStatus;
1371 1372 1373 1374
            }
        }

        // check for boleto if payment is totally paid
1375
        if ($this->_paymentMethodCode() == "adyen_boleto") {
1376 1377 1378 1379 1380

            // check if paid amount is the same as orginal amount
            $orginalAmount = $this->_boletoOriginalAmount;
            $paidAmount = $this->_boletoPaidAmount;

1381
            if ($orginalAmount != $paidAmount) {
1382 1383 1384

                // not the full amount is paid. Check if it is underpaid or overpaid
                // strip the  BRL of the string
1385
                $orginalAmount = str_replace("BRL", "", $orginalAmount);
1386 1387
                $orginalAmount = floatval(trim($orginalAmount));

1388
                $paidAmount = str_replace("BRL", "", $paidAmount);
1389 1390
                $paidAmount = floatval(trim($paidAmount));

1391
                if ($paidAmount > $orginalAmount) {
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
                    $overpaidStatus =  $this->_getConfigData('order_overpaid_status', 'adyen_boleto');
                    // check if there is selected a status if not fall back to the default
                    $status = (!empty($overpaidStatus)) ? $overpaidStatus : $status;
                } else {
                    $underpaidStatus = $this->_getConfigData('order_underpaid_status', 'adyen_boleto');
                    // check if there is selected a status if not fall back to the default
                    $status = (!empty($underpaidStatus)) ? $underpaidStatus : $status;
                }
            }
        }

        $comment = "Adyen Payment Successfully completed";

        // if manual review is true use the manual review status if this is set
1406
        if ($manualReviewComment == true && $this->_fraudManualReview) {
1407 1408
            // check if different status is selected
            $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1409
            if ($fraudManualReviewStatus != "") {
1410 1411 1412 1413 1414 1415 1416
                $status = $fraudManualReviewStatus;
                $comment = "Adyen Payment is in Manual Review check the Adyen platform";
            }
        }

        $status = (!empty($status)) ? $status : $this->_order->getStatus();
        $this->_order->addStatusHistoryComment(__($comment), $status);
1417 1418 1419
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Order status is changed to authorised status, status is ' . $status
        );
1420 1421
    }

1422

rikterbeek's avatar
rikterbeek committed
1423
    /**
1424
     * Create shipment
rikterbeek's avatar
rikterbeek committed
1425
     *
1426
     * @throws bool
rikterbeek's avatar
rikterbeek committed
1427
     */
1428 1429
    protected function _createShipment()
    {
1430
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order');
rikterbeek's avatar
rikterbeek committed
1431 1432
        // create shipment for cash payment
        $payment = $this->_order->getPayment()->getMethodInstance();
1433 1434
        if ($this->_order->canShip()) {
            $itemQty = [];
rikterbeek's avatar
rikterbeek committed
1435
            $shipment = $this->_order->prepareShipment($itemQty);
1436
            if ($shipment) {
rikterbeek's avatar
rikterbeek committed
1437 1438 1439 1440
                $shipment->register();
                $shipment->getOrder()->setIsInProcess(true);
                $comment = __('Shipment created by Adyen');
                $shipment->addComment($comment);
rikterbeek's avatar
rikterbeek committed
1441 1442 1443 1444

                /** @var \Magento\Framework\DB\Transaction $transaction */
                $transaction = $this->_transactionFactory->create();
                $transaction->addObject($shipment)
rikterbeek's avatar
rikterbeek committed
1445 1446
                    ->addObject($shipment->getOrder())
                    ->save();
rikterbeek's avatar
rikterbeek committed
1447

1448
                $this->_adyenLogger->addAdyenNotificationCronjob('Order is shipped');
rikterbeek's avatar
rikterbeek committed
1449 1450
            }
        } else {
1451
            $this->_adyenLogger->addAdyenNotificationCronjob('Order can\'t be shipped');
rikterbeek's avatar
rikterbeek committed
1452 1453 1454
        }
    }

1455 1456 1457
    /**
     * Retrieve information from payment configuration
     *
1458 1459 1460
     * @param $field
     * @param string $paymentMethodCode
     * @param $storeId
1461 1462 1463 1464 1465 1466 1467 1468
     * @return mixed
     */
    protected function _getConfigData($field, $paymentMethodCode = 'adyen_cc', $storeId)
    {
        $path = 'payment/' . $paymentMethodCode . '/' . $field;
        return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
    }
}