Cron.php 58.4 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

    /**
     * @var
     */
99
    protected $_merchantReference;
100 101 102 103

    /**
     * @var
     */
104
    protected $_eventCode;
105 106 107 108

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

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

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

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

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

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

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

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

    /**
     * @var
     */
149 150 151
    protected $_fraudManualReview;

    /**
152 153
     * Cron constructor.
     *
154 155 156 157 158 159 160
     * @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
161
     * @param Billing\AgreementFactory $billingAgreementFactory
162
     * @param Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
163
     * @param Api\PaymentRequest $paymentRequest
164 165 166 167 168 169 170
     */
    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
171
        OrderSender $orderSender,
172 173 174 175
        \Magento\Framework\DB\TransactionFactory $transactionFactory,
        \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory,
        \Adyen\Payment\Model\Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
        \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
176
    ) {
177
        $this->_scopeConfig = $scopeConfig;
178
        $this->_adyenLogger = $adyenLogger;
179 180 181 182
        $this->_notificationFactory = $notificationFactory;
        $this->_orderFactory = $orderFactory;
        $this->_adyenHelper = $adyenHelper;
        $this->_orderSender = $orderSender;
rikterbeek's avatar
rikterbeek committed
183
        $this->_transactionFactory = $transactionFactory;
184 185 186
        $this->_billingAgreementFactory = $billingAgreementFactory;
        $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
        $this->_adyenPaymentRequest = $paymentRequest;
187 188
    }

189 190 191 192
    /**
     * Process the notification
     * @return void
     */
193 194
    public function processNotification()
    {
195 196
        $this->_order = null;

197
        $this->_adyenLogger->addAdyenNotificationCronjob("START OF THE CRONJOB");
198

199
        // execute notifications from 2 minute or earlier because order could not yet been created by magento
200
        $dateStart = new \DateTime();
201
        $dateStart->modify('-5 day');
202
        $dateEnd = new \DateTime();
203
        $dateEnd->modify('-1 minute');
204 205
        $dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true];

206
        // create collection
207 208 209 210
        $notifications = $this->_notificationFactory->create();
        $notifications->addFieldToFilter('done', 0);
        $notifications->addFieldToFilter('created_at', $dateRange);

211
        // loop over the notifications
212
        foreach ($notifications as $notification) {
213

214
            // log the executed notification
215
            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($notification->debug(), 1));
216

217 218 219 220 221
            // get order
            $incrementId = $notification->getMerchantReference();

            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
            if (!$this->_order->getId()) {
222 223 224 225

                // order does not exists remove from queue
                $notification->delete();
                continue;
226 227 228 229 230 231 232 233 234
            }

            // 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');
235

236 237
            // update order details
            $this->_updateAdyenAttributes($notification);
238 239 240

            // check if success is true of false
            if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) {
241 242 243 244 245 246 247 248
                /*
                 * 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) {

249
                    $this->_adyenLogger->addAdyenNotificationCronjob('Going to cancel the order');
250 251

                    // if payment is API check, check if API result pspreference is the same as reference
252
                    if ($this->_eventCode == NOTIFICATION::AUTHORISATION && $this->_getPaymentMethodType() == 'api') {
253
                        // don't cancel the order becasue order was successfull through api
254 255 256
                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'order is not cancelled because api result was succesfull'
                        );
257
                    } else {
258 259 260 261 262 263 264
                        /*
                         * 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) {
265 266 267
                            $this->_holdCancelOrder(false);
                        } else {
                            $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode);
268 269 270 271
                            $this->_adyenLogger->addAdyenNotificationCronjob(
                                'order is not cancelled because previous notification 
                                was an authorisation that succeeded'
                            );
272 273 274
                        }
                    }
                } else {
275 276 277
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Order is already processed so ignore this notification state is:' . $this->_order->getState()
                    );
278 279 280 281 282 283 284 285
                }
            } else {
                // Notification is successful
                $this->_processNotification();
            }

            $this->_order->save();

286 287 288 289 290
            // set done to true
            $dateEnd = new \DateTime();
            $notification->setDone(true);
            $notification->setUpdatedAt($dateEnd);
            $notification->save();
291
        }
292
        $this->_adyenLogger->addAdyenNotificationCronjob("END OF THE CRONJOB");
293 294
    }

295 296 297 298 299 300
    /**
     * Declare private variables for processing notification
     *
     * @param Object $notification
     * @return void
     */
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    protected function _declareVariables($notification)
    {
        //  declare the common parameters
        $this->_pspReference = $notification->getPspreference();
        $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
316 317
        if ($this->_paymentMethodCode() == "adyen_boleto") {
            if ($additionalData && is_array($additionalData)) {
318
                $boletobancario = isset($additionalData['boletobancario']) ? $additionalData['boletobancario'] : null;
319 320 321 322 323
                if ($boletobancario && is_array($boletobancario)) {
                    $this->_boletoOriginalAmount =
                        isset($boletobancario['originalAmount']) ? trim($boletobancario['originalAmount']) : "";
                    $this->_boletoPaidAmount =
                        isset($boletobancario['paidAmount']) ? trim($boletobancario['paidAmount']) : "";
324 325 326 327
                }
            }
        }

328
        if ($additionalData && is_array($additionalData)) {
329 330

            // check if the payment is in status manual review
331 332 333
            $fraudManualReview = isset($additionalData['fraudManualReview']) ?
                $additionalData['fraudManualReview'] : "";
            if ($fraudManualReview == "true") {
334 335 336 337 338
                $this->_fraudManualReview = true;
            } else {
                $this->_fraudManualReview = false;
            }

339
            // modification.action is it for JSON
340 341 342
            $modificationActionJson = isset($additionalData['modification.action']) ?
                $additionalData['modification.action'] : null;
            if ($modificationActionJson != "") {
343 344 345
                $this->_modificationResult = $modificationActionJson;
            }

346
            $modification = isset($additionalData['modification']) ? $additionalData['modification'] : null;
347
            if ($modification && is_array($modification)) {
348
                $this->_modificationResult = isset($modification['action']) ? trim($modification['action']) : "";
349 350
            }
            $additionalData2 = isset($additionalData['additionalData']) ? $additionalData['additionalData'] : null;
351
            if ($additionalData2 && is_array($additionalData2)) {
352 353 354 355 356 357 358 359 360 361 362 363 364
                $this->_klarnaReservationNumber = isset($additionalData2['acquirerReference']) ? trim($additionalData2['acquirerReference']) : "";
            }
        }
    }

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

365 366 367 368 369
    /**
     * @return mixed
     */
    protected function _getPaymentMethodType()
    {
rikterbeek's avatar
rikterbeek committed
370 371 372
        return $this->_order->getPayment()->getPaymentMethodType();
    }

373 374 375 376 377 378
    /**
     * @desc order comments or history
     * @param type $order
     */
    protected function _addStatusHistoryComment()
    {
379 380 381
        $successResult = (strcmp($this->_success, 'true') == 0 ||
            strcmp($this->_success, '1') == 0) ? 'true' : 'false';
        $success = (!empty($this->_reason)) ? "$successResult <br />reason:$this->_reason" : $successResult;
382

383
        if ($this->_eventCode == Notification::REFUND || $this->_eventCode == Notification::CAPTURE) {
384 385 386 387 388 389 390

            $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);

391 392 393
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'amount notification:'.$amount . ' amount order:'.$orderAmount
            );
394

395 396 397 398
            if ($amount == $orderAmount) {
                $this->_order->setData(
                    'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
                );
399
            } else {
400 401 402 403
                $this->_order->setData(
                    'adyen_notification_event_code', "(PARTIAL) " .
                    $this->_eventCode . " : " . strtoupper($successResult)
                );
404 405
            }
        } else {
406 407 408
            $this->_order->setData(
                'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
            );
409 410 411
        }

        // if payment method is klarna or openinvoice/afterpay show the reservartion number
412 413 414
        if (($this->_paymentMethod == "klarna" || $this->_paymentMethod == "afterpay_default" ||
                $this->_paymentMethod == "openinvoice") && ($this->_klarnaReservationNumber != null &&
                $this->_klarnaReservationNumber != "")) {
415 416 417 418 419
            $klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber;
        } else {
            $klarnaReservationNumberText = "";
        }

420
        if ($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") {
421 422 423 424 425 426
            $boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount;
        } else {
            $boletoPaidAmountText = "";
        }

        $type = 'Adyen HTTP Notification(s):';
427 428 429
        $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);
430 431

        // If notification is pending status and pending status is set add the status change to the comment history
432
        if ($this->_eventCode == Notification::PENDING) {
433
            $pendingStatus = $this->_getConfigData('pending_status', 'adyen_abstract', $this->_order->getStoreId());
434
            if ($pendingStatus != "") {
435
                $this->_order->addStatusHistoryComment($comment, $pendingStatus);
436 437 438
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Created comment history for this notification with status change to: ' . $pendingStatus
                );
439 440 441 442 443
                return;
            }
        }

        // if manual review is accepted and a status is selected. Change the status through this comment history item
444 445
        if ($this->_eventCode == Notification::MANUAL_REVIEW_ACCEPT
            && $this->_getFraudManualReviewAcceptStatus() != "") {
446 447
            $manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus();
            $this->_order->addStatusHistoryComment($comment, $manualReviewAcceptStatus);
448
            $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus);
449 450 451 452
            return;
        }

        $this->_order->addStatusHistoryComment($comment);
453
        $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification');
454 455
    }

456 457 458
    /**
     * @param $notification
     */
459 460
    protected function _updateAdyenAttributes($notification)
    {
461
        $this->_adyenLogger->addAdyenNotificationCronjob('Updating the Adyen attributes of the order');
462 463 464 465 466 467

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

        if ($this->_eventCode == Notification::AUTHORISATION
            || $this->_eventCode == Notification::HANDLED_EXTERNALLY
468 469 470 471 472 473 474 475 476 477
            || ($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) {

478 479 480 481 482 483 484 485 486 487
                $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
                if ($previousAdyenEventCode != "AUTHORISATION : TRUE") {
                    $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
                }
            } else {
                $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
            }
        }
    }

488 489 490
    /**
     * @param $additionalData
     */
491 492 493 494 495 496 497 498
    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'] : "";
499 500
            $acquirerReference = (isset($additionalData['acquirerReference'])) ?
                $additionalData['acquirerReference'] : "";
501 502 503 504 505 506 507 508 509 510 511 512
            $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 != "") {
513 514 515
            $this->_order->getPayment()->setAdditionalInformation(
                'adyen_klarna_number', $this->_klarnaReservationNumber
            );
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        }
        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 = "";

553
        if ($reason != "") {
554
            $reasonArray = explode(":", $reason);
555 556
            if ($reasonArray != null && is_array($reasonArray)) {
                if (isset($reasonArray[1])) {
557 558 559 560 561 562 563
                    $result = $reasonArray[1];
                }
            }
        }
        return $result;
    }

564
    /**
565 566
     * @param $ignoreHasInvoice
     * @throws \Magento\Framework\Exception\LocalizedException
567 568 569 570 571 572 573 574
     */
    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()) {

575
            if ($orderStatus == \Magento\Sales\Model\Order::STATE_HOLDED) {
576 577 578 579

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

580 581 582
                if ($this->_order->canHold()) {
                    $this->_order->hold();
                } else {
583
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not hold or is already on Hold');
584 585 586
                    return;
                }
            } else {
587 588 589
                // Allow magento to cancel order
                $this->_order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_CANCEL, true);

590 591 592
                if ($this->_order->canCancel()) {
                    $this->_order->cancel();
                } else {
593
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not be canceled');
594 595 596 597
                    return;
                }
            }
        } else {
598
            $this->_adyenLogger->addAdyenNotificationCronjob('Order has already an invoice so cannot be canceled');
599 600 601 602
        }
    }

    /**
603
     * Process the Notification
604 605 606
     */
    protected function _processNotification()
    {
607
        $this->_adyenLogger->addAdyenNotificationCronjob('Processing the notification');
608 609 610 611 612 613 614
        $_paymentCode = $this->_paymentMethodCode();

        switch ($this->_eventCode) {
            case Notification::REFUND_FAILED:
                // do nothing only inform the merchant with order comment history
                break;
            case Notification::REFUND:
615 616 617 618
                $ignoreRefundNotification = $this->_getConfigData(
                    'ignore_refund_notification', 'adyen_abstract', $this->_order->getStoreId()
                );
                if ($ignoreRefundNotification != true) {
rikterbeek's avatar
rikterbeek committed
619
                    $this->_refundOrder();
620
                    //refund completed
rikterbeek's avatar
rikterbeek committed
621
                    $this->_setRefundAuthorized();
622
                } else {
623 624 625
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Setting to ignore refund notification is enabled so ignore this notification'
                    );
626 627 628
                }
                break;
            case Notification::PENDING:
629 630 631
                if ($this->_getConfigData(
                    'send_email_bank_sepa_on_pending', 'adyen_abstract', $this->_order->getStoreId())
                ) {
632
                    // Check if payment is banktransfer or sepa if true then send out order confirmation email
rikterbeek's avatar
rikterbeek committed
633
                    $isBankTransfer = $this->_isBankTransfer();
634 635
                    if ($isBankTransfer || $this->_paymentMethod == 'sepadirectdebit') {
                        if (!$this->_order->getEmailSent()) {
636
                            $this->_orderSender->send($this->_order);
637
                            $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
638
                        }
639 640 641 642 643 644
                    }
                }
                break;
            case Notification::HANDLED_EXTERNALLY:
            case Notification::AUTHORISATION:
                // for POS don't do anything on the AUTHORIZATION
645
                if ($_paymentCode != "adyen_pos") {
646 647 648 649 650 651 652
                    $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:
653 654 655 656
                /*
                 * only process this if you are on auto capture.
                 * On manual capture you will always get Capture or CancelOrRefund notification
                 */
657
                if ($this->_isAutoCapture()) {
658
                    $this->_setPaymentAuthorized(false);
659 660 661
                }
                break;
            case Notification::CAPTURE:
662 663 664 665 666
                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
                     */
667
                    if (!$this->_isAutoCapture()) {
668
                        $this->_setPaymentAuthorized(false, true);
669 670 671
                    }
                } else {
                    // FOR POS authorize the payment on the CAPTURE notification
rikterbeek's avatar
rikterbeek committed
672
                    $this->_authorizePayment();
673 674 675 676 677 678 679 680
                }
                break;
            case Notification::CAPTURE_FAILED:
            case Notification::CANCELLATION:
            case Notification::CANCELLED:
                $this->_holdCancelOrder(true);
                break;
            case Notification::CANCEL_OR_REFUND:
681 682
                if (isset($this->_modificationResult) && $this->_modificationResult != "") {
                    if ($this->_modificationResult == "cancel") {
683
                        $this->_holdCancelOrder(true);
684
                    } elseif ($this->_modificationResult == "refund") {
rikterbeek's avatar
rikterbeek committed
685
                        $this->_refundOrder();
686
                        //refund completed
rikterbeek's avatar
rikterbeek committed
687
                        $this->_setRefundAuthorized();
688 689
                    }
                } else {
690 691 692 693 694 695
                    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
696
                    } else if ($this->_order->canCancel() || $this->_order->canHold()) {
697
                        $this->_adyenLogger->addAdyenNotificationCronjob('try to cancel the order');
rikterbeek's avatar
rikterbeek committed
698
                        $this->_holdCancelOrder(true);
699
                    } else {
700
                        $this->_adyenLogger->addAdyenNotificationCronjob('try to refund the order');
701
                        // refund
rikterbeek's avatar
rikterbeek committed
702
                        $this->_refundOrder();
703
                        //refund completed
rikterbeek's avatar
rikterbeek committed
704
                        $this->_setRefundAuthorized();
705 706 707
                    }
                }
                break;
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
            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();

748 749 750 751 752
                    /*
                     * for quest checkout users we can't save this in the billing agreement
                     * because it is linked to customer
                     */
                    if ($customerReference && $storeId) {
753

754 755
                        $listRecurringContracts = null;
                        try {
756 757 758
                            $listRecurringContracts = $this->_adyenPaymentRequest->getRecurringContractsForShopper(
                                $customerReference, $storeId
                            );
759 760
                        } catch(\Exception $exception) {
                            $this->_adyenLogger->addAdyenNotificationCronjob($exception->getMessage());
761 762
                        }

763 764
                        $contractDetail = null;
                        // get currenct Contract details and get list of all current ones
765
                        $recurringReferencesList = [];
766

767
                        if ($listRecurringContracts) {
768 769
                            foreach ($listRecurringContracts as $rc) {
                                $recurringReferencesList[] = $rc['recurringDetailReference'];
770 771 772
                                if (isset($rc['recurringDetailReference']) &&
                                    $rc['recurringDetailReference'] == $recurringDetailReference) {

773 774 775 776
                                    $contractDetail = $rc;
                                }
                            }
                        }
777

778
                        if ($contractDetail != null) {
779 780 781 782 783 784
                            // update status of all the current saved agreements in magento
                            $billingAgreements = $this->_billingAgreementCollectionFactory->create();
                            $billingAgreements->addFieldToFilter('customer_id', $customerReference);

                            // get collection

785 786 787 788 789
                            foreach ($billingAgreements as $updateBillingAgreement) {
                                if (!in_array($updateBillingAgreement->getReferenceId(), $recurringReferencesList)) {
                                    $updateBillingAgreement->setStatus(
                                        \Adyen\Payment\Model\Billing\Agreement::STATUS_CANCELED
                                    );
790 791
                                    $updateBillingAgreement->save();
                                } else {
792 793 794
                                    $updateBillingAgreement->setStatus(
                                        \Adyen\Payment\Model\Billing\Agreement::STATUS_ACTIVE
                                    );
795 796
                                    $updateBillingAgreement->save();
                                }
797 798
                            }

799 800 801 802
                            // add this billing agreement
                            $billingAgreement->parseRecurringContractData($contractDetail);
                            if ($billingAgreement->isValid()) {
                                $message = __('Created billing agreement #%1.', $billingAgreement->getReferenceId());
803

804 805
                                // save into sales_billing_agreement_order
                                $billingAgreement->addOrderRelation($this->_order);
806

807 808 809 810 811
                                // add to order to save agreement
                                $this->_order->addRelatedObject($billingAgreement);
                            } else {
                                $message = __('Failed to create billing agreement for this order.');
                            }
812 813


814 815 816 817 818 819
                        } else {
                            $this->_adyenLogger->addAdyenNotificationCronjob(
                                'Failed to create billing agreement for this order ' .
                                '(listRecurringCall did not contain contract)'
                            );
                            $this->_adyenLogger->addAdyenNotificationCronjob(
820
                                sprintf('recurringDetailReference in notification is %1', $recurringDetailReference)
821 822
                            );
                            $this->_adyenLogger->addAdyenNotificationCronjob(
823
                                sprintf('CustomerReference is: %1 and storeId is %2', $customerReference, $storeId)
824
                            );
825
                            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($listRecurringContracts, 1));
826 827 828 829
                            $message = __(
                                'Failed to create billing agreement for this order ' .
                                '(listRecurringCall did not contain contract)'
                            );
830
                        }
831

832 833 834
                        $comment = $this->_order->addStatusHistoryComment($message);
                        $this->_order->addRelatedObject($comment);
                    }
835 836
                }
                break;
837
            default:
838 839 840
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    sprintf('This notification event: %s is not supported so will be ignored', $this->_eventCode)
                );
841 842 843 844
                break;
        }
    }

rikterbeek's avatar
rikterbeek committed
845 846 847 848 849 850
    /**
     * Not implemented
     * @return bool
     */
    protected function _refundOrder()
    {
851 852
        $this->_adyenLogger->addAdyenNotificationCronjob('Refunding the order');

853 854 855 856
        /*
         * Don't create a credit memo if refund is initialize in Magento
         * because in this case the credit memo already exists
         */
857
        $lastTransactionId = $this->_order->getPayment()->getLastTransId();
858
        if ($lastTransactionId != $this->_pspReference) {
859 860 861 862 863 864

            // 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
865 866 867 868 869 870
                // Invalid method Magento\Sales\Model\Order\Creditmemo::register
                /*
                $currency = $this->_order->getOrderCurrencyCode();
                $amount = $this->_adyenHelper->originalAmount($this->_value, $currency);
                $order->getPayment()->registerRefundNotification($amount);
                */
871 872 873 874 875 876

                $this->_adyenLogger->addAdyenNotificationCronjob('Please create your credit memo inside magentos');
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob('Could not create a credit memo for order');
            }
        } else {
877 878 879
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Did not create a credit memo for this order becasue refund is done through Magento'
            );
880
        }
rikterbeek's avatar
rikterbeek committed
881 882 883 884 885 886 887
    }

    /**
     * @param $order
     */
    protected function _setRefundAuthorized()
    {
888 889 890
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Status update to default status or refund_authorized status if this is set'
        );
rikterbeek's avatar
rikterbeek committed
891 892 893
        $this->_order->addStatusHistoryComment(__('Adyen Refund Successfully completed'));
    }

894
    /**
895
     * authorize payment
896 897 898
     */
    protected function _authorizePayment()
    {
899
        $this->_adyenLogger->addAdyenNotificationCronjob('Authorisation of the order');
900 901 902
        $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();

        // If manual review is active and a seperate status is used then ignore the pre authorized status
903
        if ($this->_fraudManualReview != true || $fraudManualReviewStatus == "") {
904 905
            $this->_setPrePaymentAuthorized();
        } else {
906 907 908 909
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Ignore the pre authorized status because the order is ' .
                'under manual review and use the Manual review status'
            );
910 911 912 913 914 915
        }

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

        // for boleto confirmation mail is send on order creation
916
        if ($this->_paymentMethod != "adyen_boleto") {
917
            // send order confirmation mail after invoice creation so merchant can add invoicePDF to this mail
918
            if (!$this->_order->getEmailSent()) {
919
                $this->_orderSender->send($this->_order);
920
                $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
921
            }
922 923
        }

924 925 926 927 928
        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
929
            $this->_createShipment();
930 931 932
        }
    }

933 934 935
    /**
     * Set status on authorisation
     */
936 937 938 939 940
    private function _setPrePaymentAuthorized()
    {
        $status = $this->_getConfigData('payment_pre_authorized', 'adyen_abstract', $this->_order->getStoreId());

        // only do this if status in configuration is set
941
        if (!empty($status)) {
rikterbeek's avatar
rikterbeek committed
942
            $this->_order->addStatusHistoryComment(__('Payment is authorised waiting for capture'), $status);
943 944 945
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Order status is changed to Pre-authorised status, status is ' . $status
            );
946
        } else {
947
            $this->_adyenLogger->addAdyenNotificationCronjob('No pre-authorised status is used so ignore');
948 949 950 951
        }
    }

    /**
952
     * @throws Exception
953 954 955
     */
    protected function _prepareInvoice()
    {
956
        $this->_adyenLogger->addAdyenNotificationCronjob('Prepare invoice for order');
957 958 959 960 961

        //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);
        }
962

963 964 965
        //capture mode
        if (!$this->_isAutoCapture()) {
            $this->_order->addStatusHistoryComment(__('Capture Mode set to Manual'));
966
            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to Manual');
967 968

            // show message if order is in manual review
969
            if ($this->_fraudManualReview) {
970 971
                // check if different status is selected
                $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
972
                if ($fraudManualReviewStatus != "") {
973 974 975 976 977 978
                    $status = $fraudManualReviewStatus;
                    $comment = "Adyen Payment is in Manual Review check the Adyen platform";
                    $this->_order->addStatusHistoryComment(__($comment), $status);
                }
            }

979 980 981 982 983 984 985 986
            $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'
                );
987 988 989 990 991 992 993 994
                return;
            }
        }

        // validate if amount is total amount
        $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
        $orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode);

995
        if ($this->_isTotalAmount($orderAmount)) {
996
            $this->_createInvoice();
997
        } else {
998
            $this->_adyenLogger->addAdyenNotificationCronjob('This is a partial AUTHORISATION');
999 1000 1001 1002

            // Check if this is the first partial authorisation or if there is already been an authorisation
            $paymentObj = $this->_order->getPayment();
            $authorisationAmount = $paymentObj->getAdyenAuthorisationAmount();
1003 1004 1005 1006 1007
            if ($authorisationAmount != "") {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'There is already a partial AUTHORISATION received check if this combined with the ' .
                    'previous amounts match the total amount of the order'
                );
1008 1009 1010 1011 1012 1013 1014
                $authorisationAmount = (int) $authorisationAmount;
                $currentValue = (int) $this->_value;
                $totalAuthorisationAmount = $authorisationAmount + $currentValue;

                // update amount in column
                $paymentObj->setAdyenAuthorisationAmount($totalAuthorisationAmount);

1015 1016 1017 1018
                if ($totalAuthorisationAmount == $orderAmount) {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'The full amount is paid. This is the latest AUTHORISATION notification. Create the invoice'
                    );
1019
                    $this->_createInvoice();
1020 1021
                } else {
                    // this can be multiple times so use envenData as unique key
1022 1023 1024 1025
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'The full amount is not reached. Wait for the next AUTHORISATION notification. ' .
                        'The current amount that is authorized is:' . $totalAuthorisationAmount
                    );
1026 1027
                }
            } else {
1028 1029 1030
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This is the first partial AUTHORISATION save this into the adyen_authorisation_amount field'
                );
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
                $paymentObj->setAdyenAuthorisationAmount($this->_value);
            }
        }
    }

    /**
     * @return bool
     */
    protected function _isAutoCapture()
    {
1041
        // validate if payment methods allowes manual capture
1042
        if ($this->_manualCaptureAllowed()) {
1043
            $captureMode = trim($this->_getConfigData('capture_mode', 'adyen_abstract', $this->_order->getStoreId()));
1044
            $sepaFlow = trim($this->_getConfigData('sepa_flow', 'adyen_abstract', $this->_order->getStoreId()));
1045
            $_paymentCode = $this->_paymentMethodCode();
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
            $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'
                );
1062 1063
                return false;
            }
1064

1065
            // payment method ideal, cash adyen_boleto or adyen_pos has direct capture
1066 1067 1068 1069 1070 1071
            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:' .
                    $_paymentCode . ' paymentMethod:' . $this->_paymentMethod
                );
1072 1073
                return true;
            }
1074

1075
            // if auto capture mode for openinvoice is turned on then use auto capture
1076 1077 1078 1079 1080 1081 1082 1083
            if ($captureModeOpenInvoice == true &&
                (strcmp($this->_paymentMethod, 'openinvoice') === 0 ||
                    strcmp($this->_paymentMethod, 'afterpay_default') === 0 ||
                    strcmp($this->_paymentMethod, 'klarna') === 0)) {

                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method is configured to be working as auto capture '
                );
1084
                return true;
1085 1086
            }
            // if PayPal capture modues is different from the default use this one
1087 1088 1089 1090 1091
            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'
                    );
1092
                    return true;
1093 1094 1095 1096
                } elseif (strcmp($captureModePayPal, 'manual') === 0 ) {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as manual capture'
                    );
1097 1098 1099 1100
                    return false;
                }
            }
            if (strcmp($captureMode, 'manual') === 0) {
1101
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for this payment is set to manual');
1102 1103
                return false;
            }
1104 1105 1106 1107 1108 1109 1110 1111 1112

            /*
             * online capture after delivery, use Magento backend to online invoice
             * (if the option auto capture mode for openinvoice is not set)
             */
            if (strcmp($this->_paymentMethod, 'openinvoice') === 0 ||
                strcmp($this->_paymentMethod, 'afterpay_default') === 0 ||
                strcmp($this->_paymentMethod, 'klarna') === 0) {

1113
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for klarna is by default set to manual');
1114 1115
                return false;
            }
1116 1117

            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to auto capture');
1118 1119 1120 1121
            return true;

        } else {
            // does not allow manual capture so is always immediate capture
1122
            $this->_adyenLogger->addAdyenNotificationCronjob('This payment method does not allow manual capture');
1123
            return true;
1124
        }
1125 1126 1127 1128 1129 1130

    }

    /**
     * Validate if this payment methods allows manual capture
     * This is a default can be forced differently to overrule on acquirer level
1131 1132
     *
     * @return bool|null
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
     */
    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
1148
            case 'maestrouk':
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
            case 'diners':
            case 'discover':
            case 'jcb':
            case 'laser':
            case 'paypal':
            case 'klarna':
            case 'afterpay_default':
            case 'sepadirectdebit':
                $manualCaptureAllowed = true;
                break;
            default:
                // To be sure check if it payment method starts with afterpay_ then manualCapture is allowed
1161
                if (strlen($this->_paymentMethod) >= 9 && substr($this->_paymentMethod, 0, 9) == "afterpay_") {
1162 1163 1164
                    $manualCaptureAllowed = true;
                }
                $manualCaptureAllowed = false;
1165
        }
1166 1167

        return $manualCaptureAllowed;
1168 1169 1170 1171 1172 1173
    }

    /**
     * @return bool
     */
    protected function _isBankTransfer() {
1174
        if (strlen($this->_paymentMethod) >= 12 && substr($this->_paymentMethod, 0, 12) == "bankTransfer") {
1175 1176 1177 1178 1179 1180 1181
            $isBankTransfer = true;
        } else {
            $isBankTransfer = false;
        }
        return $isBankTransfer;
    }

1182 1183 1184
    /**
     * @return mixed
     */
1185 1186 1187 1188 1189
    protected function _getFraudManualReviewStatus()
    {
        return $this->_getConfigData('fraud_manual_review_status', 'adyen_abstract', $this->_order->getStoreId());
    }

1190 1191 1192
    /**
     * @return mixed
     */
1193 1194
    protected function _getFraudManualReviewAcceptStatus()
    {
1195 1196 1197
        return $this->_getConfigData(
            'fraud_manual_review_accept_status', 'adyen_abstract', $this->_order->getStoreId()
        );
1198 1199
    }

1200 1201 1202 1203 1204 1205 1206 1207 1208
    /**
     * @param $orderAmount
     * @return bool
     */
    protected function _isTotalAmount($orderAmount)
    {
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Validate if AUTHORISATION notification has the total amount of the order'
        );
1209 1210
        $value = (int)$this->_value;

1211
        if ($value == $orderAmount) {
1212
            $this->_adyenLogger->addAdyenNotificationCronjob('AUTHORISATION has the full amount');
1213 1214
            return true;
        } else {
1215 1216 1217
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'This is a partial AUTHORISATION, the amount is ' . $this->_value
            );
1218 1219 1220 1221
            return false;
        }
    }

1222 1223 1224 1225
    /**
     * @throws Exception
     * @throws \Magento\Framework\Exception\LocalizedException
     */
1226 1227
    protected function _createInvoice()
    {
1228
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating invoice for order');
1229 1230 1231

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

1232 1233
            /* We do not use this inside a transaction because order->save()
             * is always done on the end of the notification
1234 1235 1236 1237 1238 1239 1240
             * 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
1241
                $invoice->setTransactionId($this->_pspReference);
1242

1243

1244
                $autoCapture = $this->_isAutoCapture();
1245 1246 1247
                $createPendingInvoice = (bool) $this->_getConfigData(
                    'create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()
                );
1248

1249
                if ((!$autoCapture) && ($createPendingInvoice)) {
1250 1251 1252

                    // if amount is zero create a offline invoice
                    $value = (int)$this->_value;
1253
                    if ($value == 0) {
rikterbeek's avatar
rikterbeek committed
1254
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
1255
                    } else {
rikterbeek's avatar
rikterbeek committed
1256
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::NOT_CAPTURE);
1257 1258 1259 1260 1261 1262 1263 1264
                    }

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

                $invoice->save();
1265
                $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice');
1266
            } catch (Exception $e) {
1267 1268 1269
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Error saving invoice. The error message is: ' . $e->getMessage()
                );
1270 1271 1272 1273 1274
                throw new Exception(sprintf('Error saving invoice. The error message is:', $e->getMessage()));
            }

            $this->_setPaymentAuthorized();

1275 1276 1277 1278
            $invoiceAutoMail = (bool) $this->_getConfigData(
                'send_invoice_update_mail', 'adyen_abstract', $this->_order->getStoreId()
            );

1279 1280 1281 1282
            if ($invoiceAutoMail) {
                $invoice->sendEmail();
            }
        } else {
1283
            $this->_adyenLogger->addAdyenNotificationCronjob('It is not possible to create invoice for this order');
1284 1285 1286 1287
        }
    }

    /**
1288 1289 1290
     * @param bool $manualReviewComment
     * @param bool $createInvoice
     * @throws Exception
1291 1292 1293
     */
    protected function _setPaymentAuthorized($manualReviewComment = true, $createInvoice = false)
    {
1294
        $this->_adyenLogger->addAdyenNotificationCronjob('Set order to authorised');
1295 1296 1297 1298 1299 1300 1301

        // 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
1302 1303 1304 1305
        if ($createInvoice == true && $amount == $orderAmount) {
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'amount notification:'.$amount . ' amount order:'.$orderAmount
            );
rikterbeek's avatar
rikterbeek committed
1306
            $this->_createInvoice();
1307 1308 1309
        }

        // if you have capture on shipment enabled don't set update the status of the payment
1310 1311 1312 1313 1314
        $captureOnShipment = $this->_getConfigData(
            'capture_on_shipment', 'adyen_abstract', $this->_order->getStoreId()
        );

        if (!$captureOnShipment) {
1315 1316 1317 1318
            $status = $this->_getConfigData('payment_authorized', 'adyen_abstract', $this->_order->getStoreId());
        }

        // virtual order can have different status
1319
        if ($this->_order->getIsVirtual()) {
1320
            $this->_adyenLogger->addAdyenNotificationCronjob('Product is a virtual product');
1321 1322 1323
            $virtualStatus = $this->_getConfigData('payment_authorized_virtual');
            if ($virtualStatus != "") {
                $status = $virtualStatus;
1324 1325 1326 1327
            }
        }

        // check for boleto if payment is totally paid
1328
        if ($this->_paymentMethodCode() == "adyen_boleto") {
1329 1330 1331 1332 1333

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

1334
            if ($orginalAmount != $paidAmount) {
1335 1336 1337

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

1341
                $paidAmount = str_replace("BRL", "", $paidAmount);
1342 1343
                $paidAmount = floatval(trim($paidAmount));

1344
                if ($paidAmount > $orginalAmount) {
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
                    $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
1359
        if ($manualReviewComment == true && $this->_fraudManualReview) {
1360 1361
            // check if different status is selected
            $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1362
            if ($fraudManualReviewStatus != "") {
1363 1364 1365 1366 1367 1368 1369
                $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);
1370 1371 1372
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Order status is changed to authorised status, status is ' . $status
        );
1373 1374
    }

1375

rikterbeek's avatar
rikterbeek committed
1376
    /**
1377
     * Create shipment
rikterbeek's avatar
rikterbeek committed
1378
     *
1379
     * @throws bool
rikterbeek's avatar
rikterbeek committed
1380
     */
1381 1382
    protected function _createShipment()
    {
1383
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order');
rikterbeek's avatar
rikterbeek committed
1384 1385
        // create shipment for cash payment
        $payment = $this->_order->getPayment()->getMethodInstance();
1386 1387
        if ($this->_order->canShip()) {
            $itemQty = [];
rikterbeek's avatar
rikterbeek committed
1388
            $shipment = $this->_order->prepareShipment($itemQty);
1389
            if ($shipment) {
rikterbeek's avatar
rikterbeek committed
1390 1391 1392 1393
                $shipment->register();
                $shipment->getOrder()->setIsInProcess(true);
                $comment = __('Shipment created by Adyen');
                $shipment->addComment($comment);
rikterbeek's avatar
rikterbeek committed
1394 1395 1396 1397

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

1401
                $this->_adyenLogger->addAdyenNotificationCronjob('Order is shipped');
rikterbeek's avatar
rikterbeek committed
1402 1403
            }
        } else {
1404
            $this->_adyenLogger->addAdyenNotificationCronjob('Order can\'t be shipped');
rikterbeek's avatar
rikterbeek committed
1405 1406 1407
        }
    }

1408 1409 1410
    /**
     * Retrieve information from payment configuration
     *
1411 1412 1413
     * @param $field
     * @param string $paymentMethodCode
     * @param $storeId
1414 1415 1416 1417 1418 1419 1420 1421
     * @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);
    }
}