Save user billing address

@param Delivery $delivery
480808
private function saveUserBillingAddress($delivery)
    {
                    
        
        // get billing address
        /** @var Address $billingAddress */
        $billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array(
            'actor' => $this->securityContext->getToken()->getUser(),
            'forBilling' => true
        ));

        
            
        // build new billing address when it does not exist
        if (is_null($billingAddress)) {
            $billingAddress = new Address();
            $billingAddress->setForBilling(true);
            $billingAddress->setActor($this->securityContext->getToken()->getUser());
        }

        
            
        $billingAddress->setContactPerson($delivery->getContactPerson());
        $billingAddress->setDni($delivery->getDni());
        $billingAddress->setAddressInfo($delivery->getAddressInfo());
        $billingAddress->setPhone($delivery->getPhone());
        $billingAddress->setPhone2($delivery->getPhone2());
        $billingAddress->setPreferredSchedule($delivery->getPreferredSchedule());
        $country = $this->manager->getRepository('CoreBundle:Country')->find('es');
        $billingAddress->setCountry($country);

        $this->manager->persist($billingAddress);
        $this->manager->flush();
      
    }
715677
public function verifyResumeAuthorization(DeliveryExecutionInterface $deliveryExecution, User $user)
    {
        $stateId = $deliveryExecution->getState()->getUri();
        if (!in_array($stateId, $this->getResumableStates())) {
            \common_Logger::w('Unexpected state "'.$stateId);
            throw new \common_exception_Unauthorized();
        }
    }
531181
public function updateAddress( CustomerVault\Address $address )
    {
        $address->setRequiredFields(array(
            'profileID',
            'id'
        ));
        $address->checkRequiredFields();
        $address->setRequiredFields(array('country'));
        $address->setOptionalFields(array(
            'nickName',
            'street',
            'street2',
            'city',
            'state',
            'zip',
            'recipientName',
            'phone',
            'defaultShippingAddressIndicator',
        ));

        $request = new Request(array(
            'method' => Request::PUT,
            'uri' => $this->prepareURI("/profiles/" . $address->profileID . "/addresses/" . $address->id),
            'body' => $address
        ));
        $response = $this->client->processRequest($request);
        $response['profileID'] = $address->profileID;

        return new CustomerVault\Address($response);
    }
544188
protected function removeItemAddressesThatAreEqualToOrderAddress($order)
    {
        $deliveryAddressId = $order->getDeliveryAddress()->getContactAddress()->getId();
        foreach ($order->getItems() as $item) {
            $itemEntity = $item->getEntity();
            $this->removeOrderAddressIfContactAddressIdIsEqualTo($itemEntity, $deliveryAddressId);
        }
    }
869900
public function delivery(Money $delivery)
    {
        if ($this->price->isSameCurrency($delivery)) {
            $this->delivery = $delivery;
        }
    }
692291
public function ChangeSelectedAddress()
    {
        $oUser = self::getExtranetUserProvider()->getActiveUser();
        if ($oUser->IsLoggedIn()) {
            $newShippingAddressId = $this->GetShippingAddressData('selectedAddressId');
            $newBillingAddressId = $this->GetBillingAddressData('selectedAddressId');
            if ('new' !== $newShippingAddressId) {
                $this->updateStepAddressDataForAddressId($newShippingAddressId, $newBillingAddressId);

                if ($newShippingAddressId === $newBillingAddressId &&
                    true === $this->isShipToBillingAddressAndBillingAddressIsPackstation()
                ) {
                    $this->SetShipToBillingAddress('0');
                    $newBillingAddress = $oUser->GetBillingAddress();
                    $this->SetBillingAddressData($newBillingAddress->sqlData);
                    $this->getFlashMessageService()->addMessage(
                        TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING,
                        'PkgShopDhlPackstation-ERROR-BILLING-MAY-NOT-BE-PACKSTATION'
                    );
                }
            }
        }
        parent::ChangeSelectedAddress();
    }
348844
public function createDeliveryExecution($deliveryId, User $user, $label)
    {
        $status = $this->getInitialStatus($deliveryId, $user);
        $deliveryExecution = $this->getStorageEngine()->spawnDeliveryExecution($label, $deliveryId, $user->getIdentifier(), $status);
        // trigger event
        $event = new DeliveryExecutionCreated($deliveryExecution, $user);
        $this->getServiceLocator()->get(EventManager::SERVICE_ID)->trigger($event);
        return $deliveryExecution;
    }
722057
public function setDelivery(Delivery $delivery)
    {
        if (!$delivery->id) {
            throw new InvalidArgumentException("Can not set delivery. Delivery id is empty.");
        }

        $this->updateParams['deliveryProviderId'] = $delivery->id;
        $this->updateParams['deliveryCost']       = $delivery->getCost();

        return $this;
    }
44131
protected function SetShipToBillingAddress($sShipToBillingAddress)
    {
        $this->aUserData['bShipToBillingAddress'] = $sShipToBillingAddress;
        $_SESSION['shopstepuserdata_bShipToBillingAddress'] = $this->aUserData['bShipToBillingAddress'];
        $oUser = self::getExtranetUserProvider()->getActiveUser();

        // if the user is logged in, we need to update him accordingly
        $bShipToBilling = ('1' == $sShipToBillingAddress) ? (true) : (false);
        if ($oUser && !empty($oUser->id) && $bShipToBilling != $oUser->ShipToBillingAddress() && $oUser->IsLoggedIn()) {
            // we change to ship to billing.... but we have to make sure the correct address is leading
            $sNewPrimaryAddress = '';
            if (TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING == $this->AddressUsedAsPrimaryAddress()) {
                $sNewPrimaryAddress = $this->GetBillingAddressData('selectedAddressId');
            } else {
                $sNewPrimaryAddress = $this->GetShippingAddressData('selectedAddressId');
            }
            if ($bShipToBilling) {
                // if $sNewPrimaryAddress is empty, we don't have saved the address, yet. So we won't update the user just yet. It will be updated and saved when the step is completed
                if (!empty($sNewPrimaryAddress)) {
                    $oUser->SetAddressAsBillingAddress($sNewPrimaryAddress);
                }
                $oUser->ShipToBillingAddress(true);
            } else {
                // need to pick another billing address
                $sAlternativeFor = (TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING == $this->AddressUsedAsPrimaryAddress()) ? (TdbDataExtranetUserAddress::FORM_DATA_NAME_SHIPPING) : (TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING);
                $sNewAddressId = $this->GetAnotherAddressFromUser($sNewPrimaryAddress, $sAlternativeFor);
                $aAdrData = array();
                $oAdr = TdbDataExtranetUserAddress::GetNewInstance();
                if ($oAdr->LoadFromFields(array('id' => $sNewAddressId, 'data_extranet_user_id' => $oUser->id))) {
                    $aAdrData = $oAdr->sqlData;
                }
                if (TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING == $this->AddressUsedAsPrimaryAddress()) {
                    $this->SetShippingAddressData($aAdrData);
                } else {
                    $this->SetBillingAddressData($aAdrData);
                }
            }
            //$this->ChangeSelectedAddress();
        }
    }
289306
public function assignBankAccountToAddress($address, $payment)
    {
        $bucer = new \FlexiPeeHP\FlexiBeeRW(null,
            ['evidence' => 'adresar-bankovni-ucet']);
        $bucer->insertToFlexiBee(['firma' => $address, 'buc' => $payment->getDataValue('buc'),
            'smerKod' => $payment->getDataValue('smerKod'), 'poznam' => _('Added by script')]);
        return $bucer->lastResponseCode == 201;
    }
1186281
public function setDeliveryPeople(\Core\Entity\People $delivery_people = null) {
        $this->delivery_people = $delivery_people;

        return $this;
    }
659252
protected function SetShipToBillingAddress($sShipToBillingAddress)
    {
        $bAllowChange = true;
        if ('1' == $sShipToBillingAddress) {
            if (TdbDataExtranetUserAddress::FORM_DATA_NAME_SHIPPING == $this->AddressUsedAsPrimaryAddress()) {
                if ('1' == $this->GetShippingAddressData('is_dhl_packstation')) {
                    $bAllowChange = false;
                    $oMsgManager = TCMSMessageManager::GetInstance();
                    $oMsgManager->AddMessage(TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING, 'PkgShopDhlPackstation-ERROR-BILLING-MAY-NOT-BE-PACKSTATION');
                }
            }
        }
        if ($bAllowChange) {
            parent::SetShipToBillingAddress($sShipToBillingAddress);
        }
    }
1154021
protected function InitBillingAddress()
    {
        $inputFilterUtil = $this->getInputFilterUtil();
        $billingAddressData = $inputFilterUtil->getFilteredPostInput(TdbDataExtranetUserAddress::FORM_DATA_NAME_BILLING);
        if (null !== $billingAddressData) {
            $this->SetBillingAddressData($billingAddressData);
            $this->bUserDataSubmission = true;
        } else {
            $shippingAddressData = $inputFilterUtil->getFilteredPostInput(TdbDataExtranetUserAddress::FORM_DATA_NAME_SHIPPING);
            if (null !== $shippingAddressData && TdbDataExtranetUserAddress::FORM_DATA_NAME_SHIPPING == $this->AddressUsedAsPrimaryAddress()) {
                $this->SetBillingAddressData($this->GetShippingAddressData());
            } else {
                $oUser = self::getExtranetUserProvider()->getActiveUser();
                $oBilling = $oUser->GetBillingAddress();
                $aBilling = array();
                if ($oBilling) {
                    $aBilling = $oBilling->sqlData;
                }
                $this->SetBillingAddressData($aBilling);
            }
        }
    }
1092816
protected function hasDeliveryGuestAccess(core_kernel_classes_Resource $delivery )
    {
        $returnValue = false;
    
        $properties = $delivery->getPropertiesValues(array(
            new core_kernel_classes_Property(DeliveryContainerService::PROPERTY_ACCESS_SETTINGS ),
        ));
        $propAccessSettings = current($properties[DeliveryContainerService::PROPERTY_ACCESS_SETTINGS ]);
        $accessSetting = (!(is_object($propAccessSettings)) or ($propAccessSettings=="")) ? null : $propAccessSettings->getUri();
    
        if( !is_null($accessSetting) ){
            $returnValue = ($accessSetting === DeliveryAssemblyService::PROPERTY_DELIVERY_GUEST_ACCESS);
        }
    
        return $returnValue;
    }
1111371
public function processBraintree(Transaction $transaction, $delivery, $request)
    {
        // in your controller
        $transactionService = $this->braintreeFactory->get('transaction');
        $nonce = $request->get('payment_method_nonce');

        $result = $transactionService::sale([
            'amount' => $transaction->getTotalPrice(),
            'paymentMethodNonce' => $nonce
        ]);

        $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('braintree');
        if ($result->success || !is_null($result->transaction)) {
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_PAID);
            $transaction->setPaymentMethod($pm);
            
            //details
            $details = new stdClass();
            $details->id = $result->transaction->id;
            $details->status = $result->transaction->status;
            $details->type = $result->transaction->type;
            $details->currencyIsoCode = $result->transaction->currencyIsoCode;
            $details->amount = $result->transaction->amount;
            $details->merchantAccountId = $result->transaction->merchantAccountId;
            $details->createdAt = $result->transaction->createdAt;
            $details->updatedAt = $result->transaction->updatedAt;
            $details->customer = $result->transaction->customer;
            $details->billing = $result->transaction->billing;
            $details->shipping = $result->transaction->shipping;
            
            $transaction->setPaymentDetails(json_encode($details));
            $this->manager->persist($transaction);
            $this->manager->flush();

            //confirmation payment
            $answer = new \stdClass();
            $answer->redirectUrl = $this->router->generate('ecommerce_checkout_confirmationpayment');

            return $answer;
       }else{
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_CANCELLED);
            $transaction->setPaymentMethod($pm);
            
            //details
            $errorString = "";
            foreach($result->errors->deepAll() as $error) {
               $errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
            }
            $this->session->getFlashBag()->add('error', $errorString);
            
            $transaction->setPaymentDetails(json_encode($errorString));
            $this->manager->persist($transaction);
            $this->manager->flush();

            //cancel payment
            $answer = new \stdClass();
            $answer->redirectUrl = $this->paypalFactory->getCancelUrl();

            return $answer;
        }
 
    }
807515
private function isAddressBillingAddress(array $addressData, TdbDataExtranetUser $user)
    {
        if (false === isset($addressData['id'])) {
            return false;
        }
        if ($addressData['id'] !== $user->fieldDefaultBillingAddressId) {
            return false;
        }

        return true;
    }
742113
protected function verifyDeliveryStartAuthorized($deliveryId)
    {
        $user = common_session_SessionManager::getSession()->getUser();
        $this->getAuthorizationProvider()->verifyStartAuthorization($deliveryId, $user);
    }