Apply Amasty Gift Card coupon to cart

@param string $code Gift Card coupon code
@param \Amasty\GiftCard\Model\Account $accountModel
@param Quote $quote
@return float
@throws LocalizedException
763763
public function applyAmastyGiftCard($code, $accountModel, $quote)
    {
        // Get current gift card balance before applying it to the quote
        // in case "fixed_amount" / "pay for everything" discount type is used
        $giftAmount = $accountModel->getCurrentValue();

        $quoteId = $quote->getId();

        $isValid = $this->amastyGiftCardManagement->getInstance()->validateCode($quote, $code);

        if (!$isValid) {
            throw new LocalizedException(__('Coupon with specified code "%1" is not valid.', $code));
        }

        if ($accountModel->canApplyCardForQuote($quote)) {
            $quoteGiftCard = $this->amastyQuoteFactory->getInstance()->create();
            $this->amastyQuoteResource->getInstance()->load($quoteGiftCard, $quoteId, 'quote_id');
            $subtotal = $quoteGiftCard->getSubtotal($quote);

            if ($quoteGiftCard->getCodeId() && $accountModel->getCodeId() == $quoteGiftCard->getCodeId()) {

                throw new LocalizedException(__('This gift card account is already in the quote.'));

            } elseif ($quoteGiftCard->getGiftAmount() && $subtotal == $quoteGiftCard->getGiftAmount()) {

                throw new LocalizedException(__('Gift card can\'t be applied. Maximum discount reached.'));

            } else {
                $quoteGiftCard->unsetData($quoteGiftCard->getIdFieldName());
                $quoteGiftCard->setQuoteId($quoteId);
                $quoteGiftCard->setCodeId($accountModel->getCodeId());
                $quoteGiftCard->setAccountId($accountModel->getId());

                $this->amastyQuoteRepository->getInstance()->save($quoteGiftCard);
                $this->updateTotals($quote);

                if ($this->getAmastyPayForEverything()) {
                    // pay for everything, items, shipping, tax
                    return $giftAmount;
                } else {
                    // pay for items only
                    $totals = $quote->getTotals();
                    return $totals[self::AMASTY_GIFTCARD]->getValue();
                }
            }
        } else {
            throw new LocalizedException(__('Gift card can\'t be applied.'));
        }
    }
678426
private function setPaymentMethod($quote)
    {
        $quote->setPaymentMethod(Payment::METHOD_CODE);
        // Set Sales Order Payment
        $quote->getPayment()->importData(['method' => Payment::METHOD_CODE])->save();
    }
15487
public function resetGuest(MageQuote $quote)
    {
        if ($this->sgBase->isGuest()) {
            $quote->getBillingAddress()->isObjectNew(false);
            $quote->getShippingAddress()->isObjectNew(false);
        }
    }
1266509
protected function disabledQuoteAddressValidation(Quote $quote) {
        $billingAddress = $quote->getBillingAddress();
        $billingAddress->setShouldIgnoreValidation(true);

        if (!$quote->getIsVirtual()) {
            $shippingAddress = $quote->getShippingAddress();
            $shippingAddress->setShouldIgnoreValidation(true);

            if (!$billingAddress->getEmail()) {
                $billingAddress->setSameAsBilling(1);
            }
        }
    }
13817
private function setQuotePaymentInfoData($quote, $data)
    {
        foreach ($data as $key => $value) {
            $this->getQuotePaymentInfoInstance($quote)->setData($key, $value)->save();
        }
    }
457435
public function loadAmastyGiftCard($code)
    {
        try {
            if (!$this->isAmastyGiftCardAvailable()) {
                return null;
            }

            $accountModel = $this->amastyAccountFactory->getInstance()
                ->create()
                ->loadByCode($code);
            return $accountModel && $accountModel->getId() ? $accountModel : null;
        } catch (\Exception $e) {
            return null;
        }
    }
391684
public function manageMandate(QuoteTransfer $quoteTransfer)
    {
        $manageMandateTransfer = new PayoneManageMandateTransfer();
        $manageMandateTransfer->setBankCountry($quoteTransfer->getPayment()->getPayoneDirectDebit()->getBankcountry());
        $manageMandateTransfer->setBankAccount($quoteTransfer->getPayment()->getPayoneDirectDebit()->getBankaccount());
        $manageMandateTransfer->setBankCode($quoteTransfer->getPayment()->getPayoneDirectDebit()->getBankcode());
        $manageMandateTransfer->setIban($quoteTransfer->getPayment()->getPayoneDirectDebit()->getIban());
        $manageMandateTransfer->setBic($quoteTransfer->getPayment()->getPayoneDirectDebit()->getBic());
        $personalData = new PayonePersonalDataTransfer();
        $customer = $quoteTransfer->getCustomer();
        $billingAddress = $quoteTransfer->getBillingAddress();
        $personalData->setCustomerId($customer->getIdCustomer());
        $personalData->setLastName($billingAddress->getLastName());
        $personalData->setFirstName($billingAddress->getFirstName());
        $personalData->setCompany($billingAddress->getCompany());
        $personalData->setCountry($billingAddress->getIso2Code());
        $personalData->setCity($billingAddress->getCity());
        $personalData->setStreet($billingAddress->getAddress1());
        $personalData->setZip($billingAddress->getZipCode());
        $personalData->setEmail($billingAddress->getEmail() ?? $customer->getEmail());
        $manageMandateTransfer->setPersonalData($personalData);

        return $this->getFactory()->createZedStub()->manageMandate($manageMandateTransfer);
    }
618555
public function applyCode($code, $callback = null)
    {
        try {
            if ($promocode = Promocodes::check($code)) {
                if ($promocode->users()->wherePivot(config('promocodes.related_pivot_key'), $this->id)->exists()) {
                    throw new AlreadyUsedException;
                }

                $promocode->users()->attach($this->id, [
                    config('promocodes.foreign_pivot_key') => $promocode->id,
                    'used_at' => Carbon::now(),
                ]);

                $promocode->load('users');

                if (is_callable($callback)) {
                    $callback($promocode);
                }

                return $promocode;
            }
        } catch (InvalidPromocodeException $exception) {
            //
        }

        if (is_callable($callback)) {
            $callback(null);
        }

        return null;
    }
523006
public function prepareGuestQuote($quote, $email = null) {
        // Retrieve the user email 
        $guestEmail = $email
        ?? $this->customerSession->getData('checkoutSessionData')['customerEmail']
        ?? $quote->getCustomerEmail() 
        ?? $quote->getBillingAddress()->getEmail()
        ?? $this->cookieManager->getCookie(self::EMAIL_COOKIE_NAME);

        // Set the quote as guest
        $quote->setCustomerId(null)
        ->setCustomerEmail($guestEmail)
        ->setCustomerIsGuest(true)
        ->setCustomerGroupId(GroupInterface::NOT_LOGGED_IN_ID);

        // Delete the cookie
        $this->cookieManager->deleteCookie(self::EMAIL_COOKIE_NAME);

        return $quote;
    }
473578
private function createCustomerFirstAbandonedCart($quoteCollection, $storeId, $campaignId)
    {
        $result = 0;
        foreach ($quoteCollection as $quote) {
            $websiteId = $this->helper->storeManager->getStore($storeId)->getWebsiteId();
            if (! $this->updateDataFieldAndCreateAc($quote, $websiteId, $storeId)) {
                continue;
            }

            //send campaign; check if valid to be sent
            if ($this->isLostBasketCustomerEnabled(self::CUSTOMER_LOST_BASKET_ONE, $storeId)) {
                $this->sendEmailCampaign(
                    $quote->getCustomerEmail(),
                    $quote,
                    $campaignId,
                    self::CUSTOMER_LOST_BASKET_ONE,
                    $websiteId
                );
            }

            $this->totalCustomers++;
            $result = $this->totalCustomers;
        }

        return $result;
    }
304390
public Redemption getCouponRedemptionByAccount(final String accountCode) {
        return doGET(Accounts.ACCOUNTS_RESOURCE + "/" + accountCode + Redemption.REDEMPTION_RESOURCE,
                     Redemption.class);
    }
303764
public function decrementQuantity(Coupon $coupon, $customerId = null)
    {
        if ($coupon->isUsageUnlimited()) {
            return true;
        } else {
            try {
                $usageLeft = $coupon->getUsagesLeft($customerId);

                if ($usageLeft > 0) {
                    // If the coupon usage is per user, add an entry to coupon customer usage count table
                    if ($coupon->getPerCustomerUsageCount()) {
                        if (null == $customerId) {
                            throw new \LogicException("Customer should not be null at this time.");
                        }

                        $ccc = CouponCustomerCountQuery::create()
                            ->filterByCouponId($coupon->getId())
                            ->filterByCustomerId($customerId)
                            ->findOne()
                        ;

                        if ($ccc === null) {
                            $ccc = new CouponCustomerCount();

                            $ccc
                                ->setCustomerId($customerId)
                                ->setCouponId($coupon->getId())
                                ->setCount(0);
                        }

                        $newCount = 1 + $ccc->getCount();

                        $ccc
                            ->setCount($newCount)
                            ->save()
                        ;

                        return $usageLeft - $newCount;
                    } else {
                        $coupon->setMaxUsage(--$usageLeft);

                        $coupon->save();

                        return $usageLeft;
                    }
                }
            } catch (\Exception $ex) {
                // Just log the problem.
                Tlog::getInstance()->addError(sprintf("Failed to decrement coupon %s: %s", $coupon->getCode(), $ex->getMessage()));
            }
        }

        return false;
    }
551782
public function buildCouponFromModel(Coupon $model)
    {
        $isCumulative = ($model->getIsCumulative() == 1 ? true : false);
        $isRemovingPostage = ($model->getIsRemovingPostage() == 1 ? true : false);

        if (!$this->container->has($model->getType())) {
            return false;
        }

        /** @var CouponInterface $couponManager*/
        $couponManager = $this->container->get($model->getType());
        $couponManager->set(
            $this->facade,
            $model->getCode(),
            $model->getTitle(),
            $model->getShortDescription(),
            $model->getDescription(),
            $model->getEffects(),
            $isCumulative,
            $isRemovingPostage,
            $model->getIsAvailableOnSpecialOffers(),
            $model->getIsEnabled(),
            $model->getMaxUsage(),
            $model->getExpirationDate(),
            $model->getFreeShippingForCountries(),
            $model->getFreeShippingForModules(),
            $model->getPerCustomerUsageCount()
        );

        /** @var ConditionFactory $conditionFactory */
        $conditionFactory = $this->container->get('thelia.condition.factory');
        $conditions = $conditionFactory->unserializeConditionCollection(
            $model->getSerializedConditions()
        );

        $couponManager->setConditions($conditions);

        return clone $couponManager;
    }
737780
private function setBillingAddress($quote, $transaction)
    {
        $address = @$transaction->order->cart->billing_address;
        if ($address) {
            $this->setAddress($quote->getBillingAddress(), $address);
        }
    }
386095
protected function _extractQuoteSkuData(Mage_Sales_Model_Quote $quote)
    {
        $skuData = [];
        // use getAllVisibleItems to prevent dupes due to parent config + child used both being included
        foreach ($quote->getAllVisibleItems() as $item) {
            // before item's have been saved, getAllVisible items won't properly
            // filter child items...this extra check fixes it
            if ($item->getParentItem()) {
                continue;
            }
            $skuData[$item->getSku()] = [
                'item_id' => $item->getId(),
                'managed' => Mage::helper('radial_core/quote_item')->isItemInventoried($item),
                'virtual' => $item->getIsVirtual(),
                'qty' => $item->getQty(),
            ];
        }
        return $skuData;
    }
1348551
public function setCoupon()
    {
        foreach ($this->cart->getExternalCoupons() as $coupon) {
            $this->setCouponToQuote($coupon);
        }

        return $this->quote;
    }
388851
public function setAddress(MageQuote $quote)
    {
        $billing = $this->sgBase->getInvoiceAddress();
        if (!empty($billing)) {
            $data = $this->sgCustomer->createAddressData($this->sgBase, $billing, $quote->getCustomerId());
            $quote->getBillingAddress()
                  ->addData($data)
                  ->setCustomerAddressId($billing->getId())
                  ->setCustomerId($this->sgBase->getExternalCustomerId())
                  ->setData('should_ignore_validation', true);
        }

        $shipping = $this->sgBase->getDeliveryAddress();
        if (!empty($shipping)) {
            $data = $this->sgCustomer->createAddressData($this->sgBase, $shipping, $quote->getCustomerId());
            $quote->getShippingAddress()
                  ->addData($data)
                  ->setCustomerAddressId($shipping->getId())
                  ->setCustomerId($this->sgBase->getExternalCustomerId())
                  ->setData('should_ignore_validation', true);
        }

        if (!$quote->getShippingAddress()->getCountryId()) {
            $defaultCountryItem = $this->sgCoreConfig->getConfigByPath(Custom::XML_PATH_GENERAL_COUNTRY_DEFAULT);
            $quote->getShippingAddress()->setCountryId($defaultCountryItem->getValue());
        }
    }