We will work on Apr 26th (Saturday) and will be off from Apr 30th (Wednesday) until May 2nd (Friday) for public holiday in our country

Cron.php 63.6 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
use Magento\Sales\Model\Order\Email\Sender\OrderSender;
28
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
29
use Magento\Framework\App\Area;
30 31 32
use Magento\Framework\App\AreaList;
use Magento\Framework\Phrase\Renderer\Placeholder;
use Magento\Framework\Phrase;
33 34 35 36 37 38 39 40 41 42

class Cron
{

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

43 44 45
    /**
     * @var Resource\Notification\CollectionFactory
     */
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    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;

65 66 67
    /**
     * @var \Adyen\Payment\Helper\Data
     */
68 69 70 71 72 73 74
    protected $_adyenHelper;

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

75 76 77 78 79
    /**
     * @var InvoiceSender
     */
    protected $_invoiceSender;

rikterbeek's avatar
rikterbeek committed
80 81 82 83 84
    /**
     * @var \Magento\Framework\DB\TransactionFactory
     */
    protected $_transactionFactory;

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    /**
     * @var \Adyen\Payment\Model\Billing\AgreementFactory
     */
    protected $_billingAgreementFactory;

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

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

100 101 102
    /**
     * notification attributes
     */
103
    protected $_pspReference;
104

105 106 107 108 109
    /**
     * @var
     */
    protected $_originalReference;

110 111 112
    /**
     * @var
     */
113
    protected $_merchantReference;
114 115 116 117

    /**
     * @var
     */
118
    protected $_eventCode;
119 120 121 122

    /**
     * @var
     */
123
    protected $_success;
124 125 126 127

    /**
     * @var
     */
128
    protected $_paymentMethod;
129 130 131 132

    /**
     * @var
     */
133
    protected $_reason;
134 135 136 137

    /**
     * @var
     */
138
    protected $_value;
139 140 141 142

    /**
     * @var
     */
143
    protected $_boletoOriginalAmount;
144 145 146 147

    /**
     * @var
     */
148
    protected $_boletoPaidAmount;
149 150 151 152

    /**
     * @var
     */
153
    protected $_modificationResult;
154 155 156 157

    /**
     * @var
     */
158
    protected $_klarnaReservationNumber;
159 160 161 162

    /**
     * @var
     */
163 164
    protected $_fraudManualReview;

165 166 167 168 169 170 171 172 173 174
    /**
     * @var Order\PaymentFactory
     */
    protected $_adyenOrderPaymentFactory;

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

175
    /**
176
     * @var AreaList
177
     */
178
    protected $_areaList;
179

180
    /**
181 182
     * Cron constructor.
     *
183 184 185 186 187 188
     * @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
189
     * @param InvoiceSender $invoiceSender
190
     * @param \Magento\Framework\DB\TransactionFactory $transactionFactory
191
     * @param Billing\AgreementFactory $billingAgreementFactory
192
     * @param Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
193
     * @param Api\PaymentRequest $paymentRequest
194 195
     * @param Order\PaymentFactory $adyenOrderPaymentFactory
     * @param Resource\Order\Payment\CollectionFactory $adyenOrderPaymentCollectionFactory
196
     * @param AreaList $areaList
197 198 199 200 201 202 203
     */
    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
204
        OrderSender $orderSender,
205
        InvoiceSender $invoiceSender,
206 207 208
        \Magento\Framework\DB\TransactionFactory $transactionFactory,
        \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory,
        \Adyen\Payment\Model\Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
209 210
        \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest,
        \Adyen\Payment\Model\Order\PaymentFactory $adyenOrderPaymentFactory,
211
        \Adyen\Payment\Model\Resource\Order\Payment\CollectionFactory $adyenOrderPaymentCollectionFactory,
212
        AreaList $areaList
213
    ) {
214
        $this->_scopeConfig = $scopeConfig;
215
        $this->_adyenLogger = $adyenLogger;
216 217 218 219
        $this->_notificationFactory = $notificationFactory;
        $this->_orderFactory = $orderFactory;
        $this->_adyenHelper = $adyenHelper;
        $this->_orderSender = $orderSender;
220
        $this->_invoiceSender = $invoiceSender;
rikterbeek's avatar
rikterbeek committed
221
        $this->_transactionFactory = $transactionFactory;
222 223 224
        $this->_billingAgreementFactory = $billingAgreementFactory;
        $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
        $this->_adyenPaymentRequest = $paymentRequest;
225 226
        $this->_adyenOrderPaymentFactory = $adyenOrderPaymentFactory;
        $this->_adyenOrderPaymentCollectionFactory = $adyenOrderPaymentCollectionFactory;
227
        $this->_areaList = $areaList;
228 229
    }

230 231 232 233
    /**
     * Process the notification
     * @return void
     */
234
    public function processNotification()
235 236 237 238 239 240 241 242 243 244
    {
        try {
            $this->execute();
        } catch(\Exception $e) {
            $this->_adyenLogger->addAdyenNotificationCronjob($e->getMessage() . "\n" . $e->getTraceAsString());
            throw $e;
        }
    }

    public function execute()
245
    {
246
        // needed for Magento < 2.2.0 https://github.com/magento/magento2/pull/8413
247
        $renderer = Phrase::getRenderer();
248
        if ($renderer instanceof Placeholder) {
249
            $this->_areaList->getArea(Area::AREA_CRONTAB)->load(Area::PART_TRANSLATE);
250 251
        }

252 253
        $this->_order = null;

254
        // execute notifications from 2 minute or earlier because order could not yet been created by magento
255
        $dateStart = new \DateTime();
256
        $dateStart->modify('-5 day');
257
        $dateEnd = new \DateTime();
258
        $dateEnd->modify('-1 minute');
259 260
        $dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true];

261
        // create collection
262 263
        $notifications = $this->_notificationFactory->create();
        $notifications->addFieldToFilter('done', 0);
264
        $notifications->addFieldToFilter('processing', 0);
265 266
        $notifications->addFieldToFilter('created_at', $dateRange);

267 268
        foreach ($notifications as $notification) {
            // set Cron processing to true
269
            $this->_updateNotification($notification, true, false);
270 271
        }

272
        // loop over the notifications
273
        $count = 0;
274
        foreach ($notifications as $notification) {
275

276 277 278 279
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf("Processing notification %s", $notification->getEntityId())
            );

280 281 282 283 284 285 286 287 288
            // ignore duplicate notification
            if ($this->_isDuplicate($notification)) {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    "This is a duplicate notification and will be ignored"
                );
                $this->_updateNotification($notification, false, true);
                ++$count;
                continue;
            }
289

290 291 292 293
            /**
             *  If the event is a RECURRING_CONTRACT wait an extra 5 minutes
             * before processing so we are sure the RECURRING_CONTRACT
             */
Rik ter Beek's avatar
Rik ter Beek committed
294
            if (trim($notification->getEventCode()) == Notification::RECURRING_CONTRACT &&
295 296
                strtotime($notification->getCreatedAt()) >= strtotime('-5 minutes', time())
            ) {
297 298 299 300
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    "This is a recurring_contract notification wait an extra 5 minutes 
                    before processing this to make sure the contract exists"
                );
301
                // set processing back to false
302
                $this->_updateNotification($notification, false, false);
303 304 305
                continue;
            }

306
            // log the executed notification
307
            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($notification->debug(), 1));
308

309 310 311 312 313
            // get order
            $incrementId = $notification->getMerchantReference();

            $this->_order = $this->_orderFactory->create()->loadByIncrementId($incrementId);
            if (!$this->_order->getId()) {
314 315 316 317

                // order does not exists remove from queue
                $notification->delete();
                continue;
318 319 320 321 322 323 324 325 326
            }

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

328 329
            // update order details
            $this->_updateAdyenAttributes($notification);
330 331 332

            // check if success is true of false
            if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) {
333 334 335 336 337 338
                /*
                 * 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 ||
339 340
                    $this->_eventCode == Notification::ORDER_CLOSED
                ) {
341

342
                    $this->_adyenLogger->addAdyenNotificationCronjob('Going to cancel the order');
343 344

                    // if payment is API check, check if API result pspreference is the same as reference
345
                    if ($this->_eventCode == NOTIFICATION::AUTHORISATION && $this->_getPaymentMethodType() == 'api') {
346
                        // don't cancel the order becasue order was successfull through api
347 348 349
                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'order is not cancelled because api result was succesfull'
                        );
350
                    } else {
351 352 353 354 355 356
                        /*
                         * 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" ||
357 358
                            $this->_eventCode == Notification::ORDER_CLOSED
                        ) {
359 360 361
                            $this->_holdCancelOrder(false);
                        } else {
                            $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode);
362 363 364 365
                            $this->_adyenLogger->addAdyenNotificationCronjob(
                                'order is not cancelled because previous notification 
                                was an authorisation that succeeded'
                            );
366 367 368
                        }
                    }
                } else {
369 370 371
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Order is already processed so ignore this notification state is:' . $this->_order->getState()
                    );
372 373 374 375 376 377 378
                }
            } else {
                // Notification is successful
                $this->_processNotification();
            }

            $this->_order->save();
379
            // set done to true
380
            $this->_updateNotification($notification, false, true);
381 382 383 384 385 386 387 388
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf("Notification %s is processed", $notification->getEntityId())
            );
            ++$count;
        }

        if ($count > 0) {
            $this->_adyenLogger->addAdyenNotificationCronjob(sprintf("Cronjob updated %s notification(s)", $count));
389 390 391
        }
    }

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    /**
     * @param $notification
     * @param $processing
     * @param $done
     */
    protected function _updateNotification($notification, $processing, $done)
    {
        if ($done) {
            $notification->setDone(true);
        }
        $notification->setProcessing($processing);
        $notification->setUpdatedAt(new \DateTime());
        $notification->save();
    }

    /**
     * Check if the notification is already executed if so this is a duplicate and ignore this one
     *
     * @param $notification
     * @return bool
     */
    protected function _isDuplicate($notification)
    {
        return $notification->isDuplicate(
            $notification->getPspreference(), $notification->getEventCode(), $notification->getSuccess(),
            $notification->getOriginalReference(), true
        );
    }

421 422 423 424 425 426
    /**
     * Declare private variables for processing notification
     *
     * @param Object $notification
     * @return void
     */
427 428 429 430
    protected function _declareVariables($notification)
    {
        //  declare the common parameters
        $this->_pspReference = $notification->getPspreference();
431
        $this->_originalReference = $notification->getOriginalReference();
432 433 434 435 436 437 438 439 440 441 442
        $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
443 444
        if ($this->_paymentMethodCode() == "adyen_boleto") {
            if ($additionalData && is_array($additionalData)) {
445
                $boletobancario = isset($additionalData['boletobancario']) ? $additionalData['boletobancario'] : null;
446 447 448 449 450
                if ($boletobancario && is_array($boletobancario)) {
                    $this->_boletoOriginalAmount =
                        isset($boletobancario['originalAmount']) ? trim($boletobancario['originalAmount']) : "";
                    $this->_boletoPaidAmount =
                        isset($boletobancario['paidAmount']) ? trim($boletobancario['paidAmount']) : "";
451 452 453 454
                }
            }
        }

455
        if ($additionalData && is_array($additionalData)) {
456 457

            // check if the payment is in status manual review
458 459 460
            $fraudManualReview = isset($additionalData['fraudManualReview']) ?
                $additionalData['fraudManualReview'] : "";
            if ($fraudManualReview == "true") {
461 462 463 464 465
                $this->_fraudManualReview = true;
            } else {
                $this->_fraudManualReview = false;
            }

466
            // modification.action is it for JSON
467 468 469
            $modificationActionJson = isset($additionalData['modification.action']) ?
                $additionalData['modification.action'] : null;
            if ($modificationActionJson != "") {
470 471 472
                $this->_modificationResult = $modificationActionJson;
            }

473
            $modification = isset($additionalData['modification']) ? $additionalData['modification'] : null;
474
            if ($modification && is_array($modification)) {
475
                $this->_modificationResult = isset($modification['action']) ? trim($modification['action']) : "";
476 477
            }
            $additionalData2 = isset($additionalData['additionalData']) ? $additionalData['additionalData'] : null;
478
            if ($additionalData2 && is_array($additionalData2)) {
479 480 481 482 483 484 485 486 487 488 489 490 491
                $this->_klarnaReservationNumber = isset($additionalData2['acquirerReference']) ? trim($additionalData2['acquirerReference']) : "";
            }
        }
    }

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

492 493 494 495 496
    /**
     * @return mixed
     */
    protected function _getPaymentMethodType()
    {
rikterbeek's avatar
rikterbeek committed
497 498 499
        return $this->_order->getPayment()->getPaymentMethodType();
    }

500 501 502 503 504 505
    /**
     * @desc order comments or history
     * @param type $order
     */
    protected function _addStatusHistoryComment()
    {
506 507 508
        $successResult = (strcmp($this->_success, 'true') == 0 ||
            strcmp($this->_success, '1') == 0) ? 'true' : 'false';
        $success = (!empty($this->_reason)) ? "$successResult <br />reason:$this->_reason" : $successResult;
509

510
        if ($this->_eventCode == Notification::REFUND || $this->_eventCode == Notification::CAPTURE) {
511 512 513 514 515

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

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

518
            $this->_adyenLogger->addAdyenNotificationCronjob(
519
                'amount notification:' . $amount . ' amount order:' . $orderAmount
520
            );
521

522 523 524 525
            if ($amount == $orderAmount) {
                $this->_order->setData(
                    'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
                );
526
            } else {
527 528 529 530
                $this->_order->setData(
                    'adyen_notification_event_code', "(PARTIAL) " .
                    $this->_eventCode . " : " . strtoupper($successResult)
                );
531 532
            }
        } else {
533 534 535
            $this->_order->setData(
                'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
            );
536 537
        }

Rik ter Beek's avatar
Rik ter Beek committed
538
        // if payment method is klarna, ratepay or openinvoice/afterpay show the reservartion number
539
        if (($this->_paymentMethod == "klarna" || $this->_paymentMethod == "afterpay_default" ||
Rik ter Beek's avatar
Rik ter Beek committed
540 541
                $this->_paymentMethod == "openinvoice" || $this->_paymentMethod == "ratepay"
            ) && ($this->_klarnaReservationNumber != null &&
542 543
                $this->_klarnaReservationNumber != "")
        ) {
544 545 546 547 548
            $klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber;
        } else {
            $klarnaReservationNumberText = "";
        }

549
        if ($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") {
550 551 552 553 554 555
            $boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount;
        } else {
            $boletoPaidAmountText = "";
        }

        $type = 'Adyen HTTP Notification(s):';
556 557 558
        $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);
559 560

        // If notification is pending status and pending status is set add the status change to the comment history
561
        if ($this->_eventCode == Notification::PENDING) {
562 563 564
            $pendingStatus = $this->_getConfigData(
                'pending_status', 'adyen_abstract', $this->_order->getStoreId()
            );
565
            if ($pendingStatus != "") {
566
                $this->_order->addStatusHistoryComment($comment, $pendingStatus);
567 568 569
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Created comment history for this notification with status change to: ' . $pendingStatus
                );
570 571 572 573 574
                return;
            }
        }

        // if manual review is accepted and a status is selected. Change the status through this comment history item
575
        if ($this->_eventCode == Notification::MANUAL_REVIEW_ACCEPT
576 577
            && $this->_getFraudManualReviewAcceptStatus() != ""
        ) {
578 579
            $manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus();
            $this->_order->addStatusHistoryComment($comment, $manualReviewAcceptStatus);
580
            $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus);
581 582 583 584
            return;
        }

        $this->_order->addStatusHistoryComment($comment);
585
        $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification');
586 587
    }

588 589 590
    /**
     * @param $notification
     */
591 592
    protected function _updateAdyenAttributes($notification)
    {
593
        $this->_adyenLogger->addAdyenNotificationCronjob('Updating the Adyen attributes of the order');
594 595 596 597 598 599

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

        if ($this->_eventCode == Notification::AUTHORISATION
            || $this->_eventCode == Notification::HANDLED_EXTERNALLY
600 601
            || ($this->_eventCode == Notification::CAPTURE && $_paymentCode == "adyen_pos")
        ) {
602 603 604 605 606 607 608

            /*
             * 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 ||
609 610
                strcmp($this->_success, '') == 0
            ) {
611

612 613 614 615 616 617 618 619 620 621
                $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
                if ($previousAdyenEventCode != "AUTHORISATION : TRUE") {
                    $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
                }
            } else {
                $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
            }
        }
    }

622 623 624
    /**
     * @param $additionalData
     */
625 626 627 628 629 630 631 632
    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'] : "";
633 634
            $acquirerReference = (isset($additionalData['acquirerReference'])) ?
                $additionalData['acquirerReference'] : "";
635 636 637 638 639 640 641 642 643 644 645 646
            $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 != "") {
647 648 649
            $this->_order->getPayment()->setAdditionalInformation(
                'adyen_klarna_number', $this->_klarnaReservationNumber
            );
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
        }
        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 = "";

687
        if ($reason != "") {
688
            $reasonArray = explode(":", $reason);
689 690
            if ($reasonArray != null && is_array($reasonArray)) {
                if (isset($reasonArray[1])) {
691 692 693 694 695 696 697
                    $result = $reasonArray[1];
                }
            }
        }
        return $result;
    }

698
    /**
699 700
     * @param $ignoreHasInvoice
     * @throws \Magento\Framework\Exception\LocalizedException
701 702 703
     */
    protected function _holdCancelOrder($ignoreHasInvoice)
    {
704 705 706
        $orderStatus = $this->_getConfigData(
            'payment_cancelled', 'adyen_abstract', $this->_order->getStoreId()
        );
707 708 709 710

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

711
            if ($orderStatus == \Magento\Sales\Model\Order::STATE_HOLDED) {
712 713 714 715

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

716 717 718
                if ($this->_order->canHold()) {
                    $this->_order->hold();
                } else {
719
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not hold or is already on Hold');
720 721 722
                    return;
                }
            } else {
723 724 725
                // Allow magento to cancel order
                $this->_order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_CANCEL, true);

726 727 728
                if ($this->_order->canCancel()) {
                    $this->_order->cancel();
                } else {
729
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not be canceled');
730 731 732 733
                    return;
                }
            }
        } else {
734
            $this->_adyenLogger->addAdyenNotificationCronjob('Order has already an invoice so cannot be canceled');
735 736 737 738
        }
    }

    /**
739
     * Process the Notification
740 741 742
     */
    protected function _processNotification()
    {
743

744
        $this->_adyenLogger->addAdyenNotificationCronjob('Processing the notification');
745 746 747 748 749 750 751
        $_paymentCode = $this->_paymentMethodCode();

        switch ($this->_eventCode) {
            case Notification::REFUND_FAILED:
                // do nothing only inform the merchant with order comment history
                break;
            case Notification::REFUND:
752 753 754 755
                $ignoreRefundNotification = $this->_getConfigData(
                    'ignore_refund_notification', 'adyen_abstract', $this->_order->getStoreId()
                );
                if ($ignoreRefundNotification != true) {
rikterbeek's avatar
rikterbeek committed
756
                    $this->_refundOrder();
757
                    //refund completed
rikterbeek's avatar
rikterbeek committed
758
                    $this->_setRefundAuthorized();
759
                } else {
760 761 762
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Setting to ignore refund notification is enabled so ignore this notification'
                    );
763 764 765
                }
                break;
            case Notification::PENDING:
766 767 768
                if ($this->_getConfigData(
                    'send_email_bank_sepa_on_pending', 'adyen_abstract', $this->_order->getStoreId())
                ) {
769
                    // Check if payment is banktransfer or sepa if true then send out order confirmation email
rikterbeek's avatar
rikterbeek committed
770
                    $isBankTransfer = $this->_isBankTransfer();
771 772
                    if ($isBankTransfer || $this->_paymentMethod == 'sepadirectdebit') {
                        if (!$this->_order->getEmailSent()) {
773
                            $this->_sendOrderMail();
774
                        }
775 776 777 778 779 780
                    }
                }
                break;
            case Notification::HANDLED_EXTERNALLY:
            case Notification::AUTHORISATION:
                // for POS don't do anything on the AUTHORIZATION
781
                if ($_paymentCode != "adyen_pos") {
782 783 784 785 786 787 788
                    $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:
789 790 791 792
                /*
                 * only process this if you are on auto capture.
                 * On manual capture you will always get Capture or CancelOrRefund notification
                 */
793
                if ($this->_isAutoCapture()) {
794
                    $this->_setPaymentAuthorized(false);
795 796 797
                }
                break;
            case Notification::CAPTURE:
798 799 800 801 802
                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
                     */
803
                    if (!$this->_isAutoCapture()) {
804
                        $this->_setPaymentAuthorized(false, true);
805 806 807
                    }
                } else {
                    // FOR POS authorize the payment on the CAPTURE notification
rikterbeek's avatar
rikterbeek committed
808
                    $this->_authorizePayment();
809 810
                }
                break;
811
            case Notification::OFFER_CLOSED:
812
                if (!$this->_order->canCancel()) {
813 814 815 816 817
                    // Move the order from PAYMENT_REVIEW to NEW, so that can be cancelled
                    $this->_order->setState(\Magento\Sales\Model\Order::STATE_NEW);
                }
                $this->_holdCancelOrder(true);
                break;
818 819 820 821 822 823
            case Notification::CAPTURE_FAILED:
            case Notification::CANCELLATION:
            case Notification::CANCELLED:
                $this->_holdCancelOrder(true);
                break;
            case Notification::CANCEL_OR_REFUND:
824 825
                if (isset($this->_modificationResult) && $this->_modificationResult != "") {
                    if ($this->_modificationResult == "cancel") {
826
                        $this->_holdCancelOrder(true);
827
                    } elseif ($this->_modificationResult == "refund") {
rikterbeek's avatar
rikterbeek committed
828
                        $this->_refundOrder();
829
                        //refund completed
rikterbeek's avatar
rikterbeek committed
830
                        $this->_setRefundAuthorized();
831 832
                    }
                } else {
833
                    if ($this->_order->isCanceled() ||
834 835
                        $this->_order->getState() === \Magento\Sales\Model\Order::STATE_HOLDED
                    ) {
836 837 838 839

                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'Order is already cancelled or holded so do nothing'
                        );
840
                    } else {
841 842 843 844 845 846 847 848 849 850
                        if ($this->_order->canCancel() || $this->_order->canHold()) {
                            $this->_adyenLogger->addAdyenNotificationCronjob('try to cancel the order');
                            $this->_holdCancelOrder(true);
                        } else {
                            $this->_adyenLogger->addAdyenNotificationCronjob('try to refund the order');
                            // refund
                            $this->_refundOrder();
                            //refund completed
                            $this->_setRefundAuthorized();
                        }
851 852 853
                    }
                }
                break;
854

855
            case Notification::RECURRING_CONTRACT:
856 857 858
                // storedReferenceCode
                $recurringDetailReference = $this->_pspReference;

859 860 861 862
                $storeId = $this->_order->getStoreId();
                $customerReference = $this->_order->getCustomerId();
                $listRecurringContracts = null;
                $this->_adyenLogger->addAdyenNotificationCronjob(
863 864
                    __('CustomerReference is: %1 and storeId is %2 and RecurringDetailsReference is %3',
                        $customerReference, $storeId, $recurringDetailReference)
865 866 867 868 869 870 871 872
                );
                try {
                    $listRecurringContracts = $this->_adyenPaymentRequest->getRecurringContractsForShopper(
                        $customerReference, $storeId
                    );
                    $contractDetail = null;
                    // get current Contract details and get list of all current ones
                    $recurringReferencesList = [];
873

874 875 876 877 878 879 880
                    if (!$listRecurringContracts) {
                        throw new \Exception("Empty list recurring contracts");
                    }
                    // Find the reference on the list
                    foreach ($listRecurringContracts as $rc) {
                        $recurringReferencesList[] = $rc['recurringDetailReference'];
                        if (isset($rc['recurringDetailReference']) &&
881 882
                            $rc['recurringDetailReference'] == $recurringDetailReference
                        ) {
883 884
                            $contractDetail = $rc;
                        }
885 886
                    }

887 888 889 890 891 892 893 894
                    if ($contractDetail == null) {
                        $this->_adyenLogger->addAdyenNotificationCronjob(print_r($listRecurringContracts, 1));
                        $message = __(
                            'Failed to create billing agreement for this order ' .
                            '(listRecurringCall did not contain contract)'
                        );
                        throw new \Exception($message);
                    }
895

896 897
                    $billingAgreements = $this->_billingAgreementCollectionFactory->create();
                    $billingAgreements->addFieldToFilter('customer_id', $customerReference);
898

899
                    // Get collection and update existing agreements
900

901 902 903 904 905 906 907 908
                    foreach ($billingAgreements as $updateBillingAgreement) {
                        if (!in_array($updateBillingAgreement->getReferenceId(), $recurringReferencesList)) {
                            $updateBillingAgreement->setStatus(
                                \Adyen\Payment\Model\Billing\Agreement::STATUS_CANCELED
                            );
                        } else {
                            $updateBillingAgreement->setStatus(
                                \Adyen\Payment\Model\Billing\Agreement::STATUS_ACTIVE
909
                            );
910
                        }
Aleffio's avatar
Aleffio committed
911
                        $updateBillingAgreement->save();
912
                    }
913

914 915 916 917 918 919 920 921 922 923 924 925 926
                    // Get or create billing agreement
                    $billingAgreement = $this->_billingAgreementFactory->create();
                    $billingAgreement->load($recurringDetailReference, 'reference_id');
                    // check if BA exists
                    if (!($billingAgreement && $billingAgreement->getAgreementId() > 0 && $billingAgreement->isValid())) {
                        // create new
                        $this->_adyenLogger->addAdyenNotificationCronjob("Creating new Billing Agreement");
                        $this->_order->getPayment()->setBillingAgreementData(
                            [
                                'billing_agreement_id' => $recurringDetailReference,
                                'method_code' => $this->_order->getPayment()->getMethodCode(),
                            ]
                        );
927

928 929 930 931
                        $billingAgreement = $this->_billingAgreementFactory->create();
                        $billingAgreement->setStoreId($this->_order->getStoreId());
                        $billingAgreement->importOrderPayment($this->_order->getPayment());
                        $message = __('Created billing agreement #%1.', $recurringDetailReference);
932
                    } else {
933 934
                        $this->_adyenLogger->addAdyenNotificationCronjob("Using existing Billing Agreement");
                        $billingAgreement->setIsObjectChanged(true);
Aleffio's avatar
Aleffio committed
935
                        $message = __('Updated billing agreement #%1.', $recurringDetailReference);
936
                    }
937

938 939 940
                    // Populate billing agreement data
                    $billingAgreement->parseRecurringContractData($contractDetail);
                    if ($billingAgreement->isValid()) {
941

942 943
                        // save into sales_billing_agreement_order
                        $billingAgreement->addOrderRelation($this->_order);
944

945 946 947 948 949
                        // add to order to save agreement
                        $this->_order->addRelatedObject($billingAgreement);
                    } else {
                        $message = __('Failed to create billing agreement for this order.');
                        throw new \Exception($message);
950
                    }
951

952
                } catch (\Exception $exception) {
953
                    $message = $exception->getMessage();
954
                }
955 956 957 958

                $this->_adyenLogger->addAdyenNotificationCronjob($message);
                $comment = $this->_order->addStatusHistoryComment($message);
                $this->_order->addRelatedObject($comment);
959
                break;
960
            default:
961 962 963
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    sprintf('This notification event: %s is not supported so will be ignored', $this->_eventCode)
                );
964 965 966 967
                break;
        }
    }

rikterbeek's avatar
rikterbeek committed
968 969 970 971 972 973
    /**
     * Not implemented
     * @return bool
     */
    protected function _refundOrder()
    {
974 975
        $this->_adyenLogger->addAdyenNotificationCronjob('Refunding the order');

976 977 978 979 980 981 982 983 984 985 986 987
        // 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();
988
                $amountRefunded = $amountRefunded = $orderPayment->getTotalRefunded() +
989 990 991 992 993 994 995 996 997 998
                    $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');
            }
        }

999 1000 1001 1002
        /*
         * Don't create a credit memo if refund is initialize in Magento
         * because in this case the credit memo already exists
         */
1003
        $lastTransactionId = $this->_order->getPayment()->getLastTransId();
1004
        if ($lastTransactionId != $this->_pspReference) {
1005 1006 1007 1008 1009 1010

            // 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
1011 1012 1013 1014 1015 1016
                // Invalid method Magento\Sales\Model\Order\Creditmemo::register
                /*
                $currency = $this->_order->getOrderCurrencyCode();
                $amount = $this->_adyenHelper->originalAmount($this->_value, $currency);
                $order->getPayment()->registerRefundNotification($amount);
                */
1017

1018
                $this->_adyenLogger->addAdyenNotificationCronjob('Please create your credit memo inside magento');
1019 1020 1021 1022
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob('Could not create a credit memo for order');
            }
        } else {
1023
            $this->_adyenLogger->addAdyenNotificationCronjob(
1024
                'Did not create a credit memo for this order because refund is done through Magento'
1025
            );
1026
        }
rikterbeek's avatar
rikterbeek committed
1027 1028 1029 1030 1031 1032 1033
    }

    /**
     * @param $order
     */
    protected function _setRefundAuthorized()
    {
1034 1035 1036
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Status update to default status or refund_authorized status if this is set'
        );
rikterbeek's avatar
rikterbeek committed
1037 1038 1039
        $this->_order->addStatusHistoryComment(__('Adyen Refund Successfully completed'));
    }

1040
    /**
1041
     * authorize payment
1042 1043 1044
     */
    protected function _authorizePayment()
    {
1045
        $this->_adyenLogger->addAdyenNotificationCronjob('Authorisation of the order');
1046 1047 1048
        $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();

        // If manual review is active and a seperate status is used then ignore the pre authorized status
1049
        if ($this->_fraudManualReview != true || $fraudManualReviewStatus == "") {
1050 1051
            $this->_setPrePaymentAuthorized();
        } else {
1052 1053 1054 1055
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Ignore the pre authorized status because the order is ' .
                'under manual review and use the Manual review status'
            );
1056 1057 1058 1059 1060 1061
        }

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

        // for boleto confirmation mail is send on order creation
1062
        if ($this->_paymentMethod != "adyen_boleto") {
1063
            // send order confirmation mail after invoice creation so merchant can add invoicePDF to this mail
1064
            if (!$this->_order->getEmailSent()) {
1065
                $this->_sendOrderMail();
1066
            }
1067

1068 1069
        }

1070 1071 1072
        if (($this->_paymentMethod == "c_cash" &&
                $this->_getConfigData('create_shipment', 'adyen_cash', $this->_order->getStoreId())) ||
            ($this->_getConfigData('create_shipment', 'adyen_pos', $this->_order->getStoreId()) &&
1073 1074
                $_paymentCode == "adyen_pos")
        ) {
1075

rikterbeek's avatar
rikterbeek committed
1076
            $this->_createShipment();
1077 1078 1079
        }
    }

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    /**
     * Send order Mail
     *
     * @return void
     */
    private function _sendOrderMail()
    {
        try {
            $this->_orderSender->send($this->_order);
            $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
1090
        } catch (\Exception $exception) {
1091 1092 1093 1094 1095 1096 1097
            $this->_adyenLogger->addAdyenNotificationCronjob(
                "Exception in Send Mail in Magento. This is an issue in the the core of Magento" .
                $exception->getMessage()
            );
        }
    }

1098 1099
    /**
     * Set status on authorisation
1100 1101
     *
     * @return void
1102
     */
1103 1104
    private function _setPrePaymentAuthorized()
    {
1105 1106 1107
        $status = $this->_getConfigData(
            'payment_pre_authorized', 'adyen_abstract', $this->_order->getStoreId()
        );
1108 1109

        // only do this if status in configuration is set
1110
        if (!empty($status)) {
rikterbeek's avatar
rikterbeek committed
1111
            $this->_order->addStatusHistoryComment(__('Payment is authorised waiting for capture'), $status);
1112 1113 1114
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Order status is changed to Pre-authorised status, status is ' . $status
            );
1115
        } else {
1116
            $this->_adyenLogger->addAdyenNotificationCronjob('No pre-authorised status is used so ignore');
1117 1118 1119 1120
        }
    }

    /**
1121
     * @throws Exception
1122
     * @return void
1123 1124 1125
     */
    protected function _prepareInvoice()
    {
1126
        $this->_adyenLogger->addAdyenNotificationCronjob('Prepare invoice for order');
1127 1128 1129 1130 1131

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

1133 1134 1135 1136 1137 1138 1139 1140 1141
        $paymentObj = $this->_order->getPayment();

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

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

1142 1143 1144
        //capture mode
        if (!$this->_isAutoCapture()) {
            $this->_order->addStatusHistoryComment(__('Capture Mode set to Manual'));
1145
            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to Manual');
1146 1147

            // show message if order is in manual review
1148
            if ($this->_fraudManualReview) {
1149 1150
                // check if different status is selected
                $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1151
                if ($fraudManualReviewStatus != "") {
1152 1153 1154 1155 1156 1157
                    $status = $fraudManualReviewStatus;
                    $comment = "Adyen Payment is in Manual Review check the Adyen platform";
                    $this->_order->addStatusHistoryComment(__($comment), $status);
                }
            }

1158
            $createPendingInvoice = (bool)$this->_getConfigData(
1159 1160 1161 1162 1163 1164 1165
                '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'
                );
1166 1167 1168 1169 1170 1171
                return;
            }
        }

        // validate if amount is total amount
        $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        $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)) {
1189
            $this->_createInvoice();
1190
        } else {
1191 1192 1193
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'This is a partial AUTHORISATION and the full amount is not reached'
            );
1194 1195 1196 1197 1198 1199 1200 1201
        }
    }

    /**
     * @return bool
     */
    protected function _isAutoCapture()
    {
1202
        // validate if payment methods allowes manual capture
1203
        if ($this->_manualCaptureAllowed()) {
1204 1205 1206 1207 1208 1209
            $captureMode = trim($this->_getConfigData(
                'capture_mode', 'adyen_abstract', $this->_order->getStoreId())
            );
            $sepaFlow = trim($this->_getConfigData(
                'sepa_flow', 'adyen_abstract', $this->_order->getStoreId())
            );
1210
            $_paymentCode = $this->_paymentMethodCode();
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
            $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") &&
1223 1224
                $sepaFlow == "authcap"
            ) {
1225 1226 1227
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Manual Capture is applied for sepa because it is in authcap flow'
                );
1228 1229
                return false;
            }
1230

1231
            // payment method ideal, cash adyen_boleto or adyen_pos has direct capture
1232
            if ($_paymentCode == "adyen_pos" || (($_paymentCode == "adyen_sepa" ||
1233 1234
                        $this->_paymentMethod == "sepadirectdebit") && $sepaFlow != "authcap")
            ) {
1235 1236
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method does not allow manual capture.(2) paymentCode:' .
1237
                    $_paymentCode . ' paymentMethod:' . $this->_paymentMethod . ' sepaFLow:' . $sepaFlow
1238
                );
1239 1240
                return true;
            }
1241

1242
            // if auto capture mode for openinvoice is turned on then use auto capture
1243
            if ($captureModeOpenInvoice == true &&
1244 1245
                $this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod)
            ) {
1246 1247 1248
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method is configured to be working as auto capture '
                );
1249
                return true;
1250 1251
            }
            // if PayPal capture modues is different from the default use this one
1252 1253
            if (strcmp($this->_paymentMethod, 'paypal') === 0 && $captureModePayPal != "") {
                if (strcmp($captureModePayPal, 'auto') === 0) {
1254 1255 1256
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as auto capture'
                    );
1257
                    return true;
1258
                } elseif (strcmp($captureModePayPal, 'manual') === 0) {
1259 1260 1261
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as manual capture'
                    );
1262 1263 1264 1265
                    return false;
                }
            }
            if (strcmp($captureMode, 'manual') === 0) {
1266
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for this payment is set to manual');
1267 1268
                return false;
            }
1269 1270 1271 1272 1273

            /*
             * online capture after delivery, use Magento backend to online invoice
             * (if the option auto capture mode for openinvoice is not set)
             */
1274
            if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod)) {
1275
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for klarna is by default set to manual');
1276 1277
                return false;
            }
1278 1279

            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to auto capture');
1280 1281 1282 1283
            return true;

        } else {
            // does not allow manual capture so is always immediate capture
1284
            $this->_adyenLogger->addAdyenNotificationCronjob('This payment method does not allow manual capture');
1285
            return true;
1286
        }
1287 1288 1289 1290 1291 1292

    }

    /**
     * Validate if this payment methods allows manual capture
     * This is a default can be forced differently to overrule on acquirer level
1293 1294
     *
     * @return bool|null
1295 1296 1297 1298 1299 1300
     */
    protected function _manualCaptureAllowed()
    {
        $manualCaptureAllowed = null;
        $paymentMethod = $this->_paymentMethod;

1301
        switch ($paymentMethod) {
1302 1303 1304
            case 'cup':
            case 'cartebancaire':
            case 'visa':
1305
            case 'visadankort':
1306 1307 1308 1309 1310
            case 'mc':
            case 'uatp':
            case 'amex':
            case 'bcmc':
            case 'maestro':
rikterbeek's avatar
rikterbeek committed
1311
            case 'maestrouk':
1312 1313 1314 1315 1316 1317 1318
            case 'diners':
            case 'discover':
            case 'jcb':
            case 'laser':
            case 'paypal':
            case 'klarna':
            case 'afterpay_default':
Rik ter Beek's avatar
Rik ter Beek committed
1319
            case 'ratepay':
1320 1321 1322 1323 1324
            case 'sepadirectdebit':
                $manualCaptureAllowed = true;
                break;
            default:
                // To be sure check if it payment method starts with afterpay_ then manualCapture is allowed
1325
                if (strlen($this->_paymentMethod) >= 9 && substr($this->_paymentMethod, 0, 9) == "afterpay_") {
1326 1327 1328
                    $manualCaptureAllowed = true;
                }
                $manualCaptureAllowed = false;
1329
        }
1330 1331

        return $manualCaptureAllowed;
1332 1333 1334 1335 1336
    }

    /**
     * @return bool
     */
1337 1338
    protected function _isBankTransfer()
    {
1339
        if (strlen($this->_paymentMethod) >= 12 && substr($this->_paymentMethod, 0, 12) == "bankTransfer") {
1340 1341 1342 1343 1344 1345 1346
            $isBankTransfer = true;
        } else {
            $isBankTransfer = false;
        }
        return $isBankTransfer;
    }

1347 1348 1349
    /**
     * @return mixed
     */
1350 1351
    protected function _getFraudManualReviewStatus()
    {
1352 1353 1354
        return $this->_getConfigData(
            'fraud_manual_review_status', 'adyen_abstract', $this->_order->getStoreId()
        );
1355 1356
    }

1357 1358 1359
    /**
     * @return mixed
     */
1360 1361
    protected function _getFraudManualReviewAcceptStatus()
    {
1362 1363 1364
        return $this->_getConfigData(
            'fraud_manual_review_accept_status', 'adyen_abstract', $this->_order->getStoreId()
        );
1365 1366
    }

1367
    /**
1368 1369
     * @param int $paymentId
     * @param string $orderCurrencyCode
1370 1371
     * @return bool
     */
1372
    protected function _isTotalAmount($paymentId, $orderCurrencyCode)
1373 1374 1375 1376
    {
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Validate if AUTHORISATION notification has the total amount of the order'
        );
1377

1378
        // get total amount of the order
1379
        $grandTotal = (int)$this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode);
1380 1381 1382 1383 1384

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

1386
        if ($res && isset($res[0]) && is_array($res[0])) {
1387 1388
            $amount = $res[0]['total_amount'];
            $orderAmount = $this->_adyenHelper->formatAmount($amount, $orderCurrencyCode);
1389 1390 1391 1392 1393 1394
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf('The grandtotal amount is %s and the total order amount that is authorised is: %s',
                    $grandTotal,
                    $orderAmount
                )
            );
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

            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;
            }
1405
        }
1406
        return false;
1407 1408
    }

1409 1410 1411
    /**
     * @throws Exception
     * @throws \Magento\Framework\Exception\LocalizedException
1412
     * @return void
1413
     */
1414 1415
    protected function _createInvoice()
    {
1416
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating invoice for order');
1417 1418 1419

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

1420 1421
            /* We do not use this inside a transaction because order->save()
             * is always done on the end of the notification
1422 1423 1424 1425 1426 1427 1428
             * 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
1429
                $invoice->setTransactionId($this->_pspReference);
1430

1431

1432
                $autoCapture = $this->_isAutoCapture();
1433
                $createPendingInvoice = (bool)$this->_getConfigData(
1434 1435
                    'create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()
                );
1436

1437
                if ((!$autoCapture) && ($createPendingInvoice)) {
1438 1439 1440

                    // if amount is zero create a offline invoice
                    $value = (int)$this->_value;
1441
                    if ($value == 0) {
rikterbeek's avatar
rikterbeek committed
1442
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
1443
                    } else {
rikterbeek's avatar
rikterbeek committed
1444
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::NOT_CAPTURE);
1445 1446 1447 1448 1449 1450 1451 1452
                    }

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

                $invoice->save();
1453
                $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice');
1454
            } catch (Exception $e) {
1455 1456 1457
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Error saving invoice. The error message is: ' . $e->getMessage()
                );
1458 1459 1460 1461 1462
                throw new Exception(sprintf('Error saving invoice. The error message is:', $e->getMessage()));
            }

            $this->_setPaymentAuthorized();

1463 1464 1465 1466
            $invoiceAutoMail = (bool)$this->_scopeConfig->isSetFlag(
                \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity::XML_PATH_EMAIL_ENABLED,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->_order->getStoreId()
1467 1468
            );

1469
            if ($invoiceAutoMail) {
1470
                $this->_invoiceSender->send($invoice);
1471 1472
            }
        } else {
1473
            $this->_adyenLogger->addAdyenNotificationCronjob('It is not possible to create invoice for this order');
1474 1475 1476 1477
        }
    }

    /**
1478 1479 1480
     * @param bool $manualReviewComment
     * @param bool $createInvoice
     * @throws Exception
1481 1482 1483
     */
    protected function _setPaymentAuthorized($manualReviewComment = true, $createInvoice = false)
    {
1484
        $this->_adyenLogger->addAdyenNotificationCronjob('Set order to authorised');
1485 1486 1487 1488

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

        // create invoice for the capture notification if you are on manual capture
1492 1493
        if ($createInvoice == true && $amount == $orderAmount) {
            $this->_adyenLogger->addAdyenNotificationCronjob(
1494
                'amount notification:' . $amount . ' amount order:' . $orderAmount
1495
            );
rikterbeek's avatar
rikterbeek committed
1496
            $this->_createInvoice();
1497
        }
1498

1499 1500 1501
        $status = $this->_getConfigData(
            'payment_authorized', 'adyen_abstract', $this->_order->getStoreId()
        );
1502 1503

        // virtual order can have different status
1504
        if ($this->_order->getIsVirtual()) {
1505
            $this->_adyenLogger->addAdyenNotificationCronjob('Product is a virtual product');
1506 1507 1508
            $virtualStatus = $this->_getConfigData(
                'payment_authorized_virtual', 'adyen_abstract', $this->_order->getStoreId()
            );
1509 1510
            if ($virtualStatus != "") {
                $status = $virtualStatus;
1511 1512 1513 1514
            }
        }

        // check for boleto if payment is totally paid
1515
        if ($this->_paymentMethodCode() == "adyen_boleto") {
1516 1517 1518 1519 1520

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

1521
            if ($orginalAmount != $paidAmount) {
1522 1523 1524

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

1528
                $paidAmount = str_replace("BRL", "", $paidAmount);
1529 1530
                $paidAmount = floatval(trim($paidAmount));

1531
                if ($paidAmount > $orginalAmount) {
1532
                    $overpaidStatus = $this->_getConfigData(
1533 1534
                        'order_overpaid_status', 'adyen_boleto', $this->_order->getStoreId()
                    );
1535 1536 1537
                    // check if there is selected a status if not fall back to the default
                    $status = (!empty($overpaidStatus)) ? $overpaidStatus : $status;
                } else {
1538 1539 1540
                    $underpaidStatus = $this->_getConfigData(
                        'order_underpaid_status', 'adyen_boleto', $this->_order->getStoreId()
                    );
1541 1542 1543 1544 1545 1546 1547 1548 1549
                    // 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
1550
        if ($manualReviewComment == true && $this->_fraudManualReview) {
1551 1552
            // check if different status is selected
            $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1553
            if ($fraudManualReviewStatus != "") {
1554 1555 1556 1557 1558 1559 1560
                $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);
1561 1562 1563
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Order status is changed to authorised status, status is ' . $status
        );
1564 1565
    }

1566

rikterbeek's avatar
rikterbeek committed
1567
    /**
1568
     * Create shipment
rikterbeek's avatar
rikterbeek committed
1569
     *
1570
     * @throws bool
rikterbeek's avatar
rikterbeek committed
1571
     */
1572 1573
    protected function _createShipment()
    {
1574
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order');
rikterbeek's avatar
rikterbeek committed
1575 1576
        // create shipment for cash payment
        $payment = $this->_order->getPayment()->getMethodInstance();
1577 1578
        if ($this->_order->canShip()) {
            $itemQty = [];
rikterbeek's avatar
rikterbeek committed
1579
            $shipment = $this->_order->prepareShipment($itemQty);
1580
            if ($shipment) {
rikterbeek's avatar
rikterbeek committed
1581 1582 1583 1584
                $shipment->register();
                $shipment->getOrder()->setIsInProcess(true);
                $comment = __('Shipment created by Adyen');
                $shipment->addComment($comment);
rikterbeek's avatar
rikterbeek committed
1585 1586 1587 1588

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

1592
                $this->_adyenLogger->addAdyenNotificationCronjob('Order is shipped');
rikterbeek's avatar
rikterbeek committed
1593 1594
            }
        } else {
1595
            $this->_adyenLogger->addAdyenNotificationCronjob('Order can\'t be shipped');
rikterbeek's avatar
rikterbeek committed
1596 1597 1598
        }
    }

1599 1600 1601
    /**
     * Retrieve information from payment configuration
     *
1602 1603 1604
     * @param $field
     * @param string $paymentMethodCode
     * @param $storeId
1605 1606 1607 1608 1609 1610 1611
     * @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);
    }
1612
}