Provede "Zaplacení" vydaného dobropisu

@param \FlexiPeeHP\FakturaVydana $invoice
@param \FlexiPeeHP\Banka $payment

@return int vysledek 0 = chyba, 1 = sparovano
968400
public function settleCreditNote($invoice, $payment)
    {
        $success       = 0;
        $prijataCastka = (float) $payment->getDataValue('sumCelkem');

        if ($prijataCastka < $invoice->getDataValue('zbyvaUhradit')) { //Castecna uhrada
            $this->addStatusMessages(sprinf(_('Castecna uhrada - DOBROPIS: prijato: %s ma byt zaplaceno %s'),
                    $prijataCastka, $invoice->getDataValue('zbyvaUhradit')),
                'warning');
        }
        if ($prijataCastka > $invoice->getDataValue('zbyvaUhradit')) { //Castecna uhrada
            $this->addStatusMessages(sprinf(_('Přeplatek - DOBROPIS: prijato: %s ma byt zaplaceno %s'),
                    $prijataCastka, $invoice->getDataValue('zbyvaUhradit')),
                'warning');

            $this->banker->dataReset();
            $this->banker->setDataValue('id', $payment['id']);
            $this->banker->setDataValue('stitky',
                $this->config['LABEL_PREPLATEK']);
            $this->banker->insertToFlexiBee();
        }

        if ($invoice->sparujPlatbu($payment, 'castecnaUhrada')) { //Jak se ma FlexiBee zachovat pri preplatku/nedoplatku
            $success = 1;
            $invoice->addStatusMessage(sprintf(_('Platba %s  %s byla sparovana s dobropisem %s'),
                    (string) $payment, $prijataCastka, (string) $invoice),
                'success');
            //PDF Danoveho dokladu priloz k nemu samemu
            //PDF Danoveho dokladu odesli mailem zakaznikovi y FLEXIBEE( nasledne pouzit tabulku Mail/Gandalf)
        }

        return $success;
    }
1172925
public static function generate($invoice)
    {
        if ($invoice->getNumber() !== null) {
            return $invoice->getNumber();
        }

        $repo = self::$em->getRepository(Invoice::class);
        $regexp = sprintf('^%s(\d{%d})$', self::$codePrefix, self::$codeLength);
        $res = $repo->createQueryBuilder('i')
            ->select('i.number')
            ->where("SUBSTRING(i.number, '$regexp') != ''")
            ->setMaxResults(1)
            ->addOrderBy('i.number', 'desc')
            ->getQuery()
            ->getScalarResult();
        $max = $res ? (int) $res[0]['number'] : 0;

        return sprintf('%s%0' . self::$codeLength . 'd', self::$codePrefix, $max + 1);
    }
1063376
public function createPaymentByInvoiceTitleAndCustomerIdQuery($invoiceTitle, $customerId)
    {
        $query = $this->getFactory()->createPaymentPayoneQuery();
        $query->useSpySalesOrderQuery()
            ->filterByFkCustomer($customerId)
            ->endUse()
            ->useSpyPaymentPayoneDetailQuery()
            ->filterByInvoiceTitle($invoiceTitle)
            ->endUse()
            ->useSpyPaymentPayoneApiLogQuery()
            ->filterByStatus(PayoneApiConstants::RESPONSE_TYPE_APPROVED)
            ->endUse();

        return $query;
    }
525026
public function createInvoice($delivery=null, $transaction=null)
    {
        /** @var Transaction $transaction */
        if(is_null($transaction))
        $transaction = $this->getCurrentTransaction();
        
        
        $invoiceNumber = $this->manager->getRepository('EcommerceBundle:Invoice')->getNextNumber();

        $invoice = new Invoice();
        $invoice->setInvoiceNumber($invoiceNumber);
        //Actor invoices  = ONE SHOT
        
        if($transaction->getItems()->first()->getAdvert() instanceof Advert || 
           $transaction->getItems()->first()->getProduct() instanceof Product
            ){
            $invoice->setFullName($this->securityContext->getToken()->getUser()->getFullName());
            if(!is_null($delivery)){
               $invoice->setDni($delivery->getDni());
               $invoice->setAddressInfo($delivery->getAddressInfo()); 
            }else{
                $invoice->setAddressInfo($this->getBillingAddress($transaction->getActor()));
            }
            
            $invoice->setTransaction($transaction);
            $this->manager->persist($invoice);
            $this->manager->flush();

            $totals = $this->calculateTotals($transaction, $delivery);

           
            if($transaction->getItems()->first()->getProduct() instanceof Product){
                $this->mailer->sendPurchaseNotification($invoice);
                $this->mailer->sendPurchaseConfirmationMessage($invoice, $totals['amount']);
            }elseif($transaction->getItems()->first()->getAdvert() instanceof Advert){
                $this->mailer->sendAdvertPurchaseNotification($invoice);
                $this->mailer->sendAdvertPurchaseConfirmationMessage($invoice, $totals['amount']);
            }
            
        
        }
        elseif($transaction->getItems()->first()->getPlan() instanceof Plan){
            $name = $transaction->getActor()->getName();
            $invoice->setFullName($name);
            $invoice->setAddress($transaction->getActor()->getAddress());
            $invoice->setPostalCode($transaction->getActor()->getPostalCode());
            $invoice->setCity($transaction->getActor()->getCity());
            if(!is_null($transaction->getActor()->getState()))$invoice->setState($transaction->getActor()->getState());
            $invoice->setCountry($transaction->getActor()->getCountry());
            
            $invoice->setTransaction($transaction);
            $this->manager->persist($invoice);
            $this->manager->flush();

            $totals = $this->calculateTotals($transaction, $delivery);

            $this->mailer->sendPlanPurchaseNotification($invoice);
            $this->mailer->sendPlanPurchaseConfirmationMessage($invoice, $totals['amount']);

        }
       

        return $invoice;
    }
798836
public Transaction enterOfflinePayment(final String invoiceId, final Transaction payment) {
        return doPOST(Invoices.INVOICES_RESOURCE + "/" + invoiceId + "/transactions", payment, Transaction.class);
    }
1249756
public function pay($amount, $parameters) {
        $payment = new InvoicePayment();
        $payment->amount = $amount;

        $payment->setPreCommitMetadataArray($parameters['metadata']);

        $payment->invoice()->associate($this);
        $payment->type()->associate($parameters['type']);

        if(isset($parameters['id'])) {
            $payment->payment_id = $parameters['id'];
        }

        $payment->save();
        return $payment;
    }
441661
public function settleProforma($zaloha, $payment)
    {
        $success       = 0;
        $prijataCastka = (float) $payment['sumCelkem'];

        $platba = new \FlexiPeeHP\Banka((int) $payment['id'], $this->config);

        if ($zaloha->sparujPlatbu($platba, 'castecnaUhrada')) {
            $success = 1;
            $zaloha->addStatusMessage(sprintf(_('Platba %s  %s %s byla sparovana s zalohou %s'),
                    \FlexiPeeHP\FlexiBeeRO::uncode($platba), $prijataCastka,
                    \FlexiPeeHP\FlexiBeeRO::uncode($payment['mena']),
                    (string) $zaloha), 'success');

            if ($zaloha->getDataValue('zbyvaUhradit') > $prijataCastka) { // Castecna Uhrada
//                //Castecna uhrada
//                //Vytvorit ZDD ve vysi payment
//                $zdd = new \FlexiPeeHP\FakturaVydana(['firma' => $zaloha->getDataValue('firma'),
//                    'zavTxt' => $zaloha->getDataValue('zavTxt').' DOPLNIT!!! ',
//                    'varSym' => $zaloha->getDataValue('varSym'),
//                    'popis' => 'Částečná úhrada '.$zaloha->getDataValue('kod')
//                ]);
//
//                $zdd->setDataValue('typDokl', 'code:ZDD');
////                $zdd->setDataValue('zbyvaUhradit', 0); //Mozna nemusime resit -vymazat
////                $zdd->setDataValue('sumCelkem', $prijataCastka);
//                $zdd->setDataValue('szbDphZakl',
//                    $zaloha->getDataValue('szbDphZakl'));
//                $zdd->setDataValue('bezPolozek', true);
////                $zdd->setDataValue('stavUhrK', '');
//                $zdd->unsetDataValue('polozkyFaktury');
//
//                // ---------- Tady se resi sazby - nahrdit objektem pro praci s castkami --------------//
//                // DPH21
//                if ((float) $zaloha->getDataValue('sumCelkZakl')) {
//                    $sumZklZakl = $prijataCastka / ( 1 + (float) $zaloha->getDataValue('szbDphZakl')
//                        / 100 );
//
////                    $zdd->setDataValue('sumZklZakl', round($sumZklZakl, 2));
////                    $zdd->setDataValue('sumDphZakl',
////                        round($prijataCastka - $sumZklZakl, 2));
//                    $zdd->setDataValue('sumCelkZakl', round($prijataCastka, 2));
//                    // DPH00
//                } else {
//                    if ((float) $zaloha->getDataValue('sumOsv')) {
////                        $zdd->setDataValue('sumOsv', round($prijataCastka),
////                            2);
//                    }
//                }
//                $result = $zdd->insertToFlexiBee();
//
//                $zdd->loadFromFlexiBee();
//                $zaloha->debug = true;
//                $zdd->debug    = true;
//
//
//                $targt      = $platba->apiURL.'/vytvor-zdd.json';
//                $zauctovani = '01-02';
//                $value      = $zaloha->getDataValue('kod').'^^^'.$zauctovani;
//                $sender     = new \FlexiPeeHP\FlexiBeeRW();
//                $sender->setPostFields(['zalohaACleneni' => $value]);
//                $result     = $sender->performRequest($targt, 'POST', 'json');
//
//                $result = $zdd->odpocetZDD($zaloha,
//                    ['castkaMen' => $prijataCastka]);
//                if (isset($result['success']) && ($result['success'] == 'true')) {
//                    $success = 2;
//                    $zaloha->addStatusMessage(sprintf(_('Faktura #%s byla sparovana se ZDD'),
//                            $kod), 'success');
//                } else {
//                    $success = -1;
//                    $zaloha->addStatusMessage(sprintf(_('Faktura #%s nebyla sparovana se ZDD'),
//                            $kod), 'error');
//                }
                $zaloha->addStatusMessage(sprintf(_('Částečná úhrada %s'),
                        self::apiUrlToLink($zaloha->apiURL)), 'warning');

                $zaloha->addStatusMessage(sprintf(_('Vytvoř ZDD: %s'),
                        self::apiUrlToLink($platba->apiURL.'/vytvor-zdd')),
                    'debug');
            } else {

                if ($prijataCastka > $zaloha->getDataValue('zbyvaUhradit')) { // Preplatek
                    $zaloha->addStatusMessage(sprintf(_('Přeplatek %s'),
                            self::apiUrlToLink($platba->apiURL)), 'warning');
                }

                //Plna uhrada
                //$toCopy['sumCelkem'] = $payment->getDataValue('sumCelkem');
                //Dopsat pro vsechny mozne sazby dane - vytvorit objekt

                $faktura2 = $this->invoiceCopy($zaloha,
                    ['duzpUcto' => $platba->getDataValue('datVyst'), 'datVyst' => $platba->getDataValue('datVyst')]);
                $id       = (int) $faktura2->getLastInsertedId();
                $faktura2->loadFromFlexiBee($id);
                $kod      = $faktura2->getDataValue('kod');
                $faktura2->dataReset();
                $faktura2->setDataValue('id', 'code:'.$kod);
                $faktura2->setDataValue('typDokl', 'code:FAKTURA');

                $result = $faktura2->odpocetZalohy($zaloha);
                if (isset($result['success']) && ($result['success'] == 'true')) {
                    $success = 2;
                    $zaloha->addStatusMessage(sprintf(_('Faktura #%s byla sparovana'),
                            $kod), 'success');
                } else {
                    $success = -1;
                    $zaloha->addStatusMessage(sprintf(_('Faktura #%s nebyla sparovana'),
                            $kod), 'error');
                }
            }

            //PDF Danoveho dokladu priloz k nemu samemu
            //PDF Danoveho dokladu odesli mailem zakaznikovi y FLEXIBEE( nasledne pouzit tabulku Mail/Gandalf)
        }
        return $success;
    }
1226037
public function payWithStripeAction(Invoice $invoice, Request $request)
    {
        $buyer = $this->get('security.context')
            ->getToken()
            ->getUser()
            ->getCurrentProfile()
        ;

        if ($buyer !== $invoice->getCustomer()) {
            throw new NotFoundHttpException('Buyer is not Invoice Customer');
        }

        // First we need to create a payment
        $payment = new InvoicePayment(array($invoice));

        // Save the Payment, so that we get an id
        $em = $this->get('doctrine')->getEntityManager();
        $em->persist($payment);
        $em->flush();

        $this->get('payment.stripe');

        // Grap Stripe token
        $token  = $_POST['stripeToken'];

        try {
            // First create a Stripe customer
            $customer = \Stripe_Customer::create(array(
              'card'        => $token,
              'description' => '#'.$invoice->getCustomer()->getId().' '.$invoice->getCustomer()->getName(),
            ));

            $charge = \Stripe_Charge::create(array(
                'customer'    => $customer->id,
                'amount'      => floor($payment->getAmount()*100),
                'currency'    => 'usd',
                'description' => 'Invoice Payment #'.$payment->getId(),
            )); //, $invoice->getVendor()->getStripeAccessToken());

            // Create SavedCreditCard
            $creditCard = new \HarvestCloud\CoreBundle\Entity\Payment\SavedCreditCard();
            $creditCard->setPaymentServiceKey('stripe');
            $creditCard->setPaymentServiceToken($customer->id);
            $creditCard->setType($charge['card']['type']);
            $creditCard->setExpiryDateFromYearAndMonth($charge['card']['exp_year'], $charge['card']['exp_month']);
            $creditCard->setLastFourDigits($charge['card']['last4']);
            $creditCard->setNameOnCard($charge['card']['name']);

            $invoice->getCustomer()->addSavedCreditCard($creditCard);

            $em->persist($invoice->getCustomer());
            $em->flush();


            // Everything went OK, so let's post the Payment
            $payment->post();

            // Create a Customer
        } catch (\Stripe_CardError $e) {
            // @todo Send some messages back to the browser
            // for now, we'll just re-throw the exception
            throw $e;
        }

        // Save the Payment again after the post()
        $em->persist($payment);
        $em->flush();

        return $this->redirect($this->generateurl('Buyer_invoice_show', array(
            'id' => $invoice->getId(),
        )));
    }
699891
def void
            
      resp = StdClass.new
      t = InvoiceTransaction.where(:invoice_id => self.id, :transaction_type => InvoiceTransaction::TYPE_AUTHORIZE, :success => true).first
      
      if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED
        resp.error = "This invoice has already been captured, you will need to refund instead"
      elsif t.nil?
        resp.error = "This invoice doesn't seem to be authorized."
      else
                
        sc = self.site.store_config
        ot = Caboose::InvoiceTransaction.new(
          :invoice_id => self.id,
          :date_processed => DateTime.now.utc,
          :transaction_type => InvoiceTransaction::TYPE_VOID,
          :payment_processor => sc.pp_name,
          :amount => self.total
        )
        
        case sc.pp_name
          when 'authorize.net'            
            response = AuthorizeNet::SIM::Transaction.new(
              sc.authnet_api_login_id, 
              sc.authnet_api_transaction_key,                      
              self.total,
              :transaction_type => InvoiceTransaction::TYPE_VOID,
              :transaction_id => t.transaction_id,
              :test => sc.pp_testing
            )                    
            self.update_attributes(
              :financial_status => Invoice::FINANCIAL_STATUS_VOIDED,
              :status => Invoice::STATUS_CANCELED
            )
            self.save          
            # TODO: Add the variant quantities invoiceed back        
            resp.success = "Invoice voided successfully"
                        
            ot.success        = response.response_code && response.response_code == '1'            
            ot.transaction_id = response.transaction_id
            #ot.auth_code      = response.authorization_code
            ot.response_code  = response.response_code            
            ot.save
          
          when 'stripe'
            # TODO: Implement void invoice for strip
            
          when 'payscape'
            # TODO: Implement void invoice for payscape
            
        end
        
      end
      return resp      
    end
36681
public function acumulusInvoiceCreated($invoice, BaseSource $invoiceSource, Result $localResult)
    {
        $invoice = $this->supportBundleProducts($invoice, $invoiceSource, $localResult);
        $invoice = $this->supportTMExtraProductOptions($invoice, $invoiceSource, $localResult);
        return $invoice;
    }
493697
public function createForOrder(OrderInterface $order, $type = Invoice::TYPE_DEBIT)
    {
        $invoice = new Invoice();
        $number = $this->codeGenerator::generate($invoice);

        $data = [
            'order'        => $order,
            'number'       => $number,
            'date'         => date('d/m/Y'),
            'base_dir'     => $this->rootDir . '/../web',
            'invoice_type' => $type,
        ];

        $html = $this->templating->render($this->template, $data);
        $pdf = $this->pdfGenerator->getOutputFromHtml($html);

        $total = $type === Invoice::TYPE_DEBIT ?
            $order->getTotal() :
            $order->getTotal() * -1
        ;

        $order->addInvoice($invoice);
        $invoice->setOrder($order);
        $invoice->setNumber($number);
        $invoice->setMimeType('application/pdf');
        $invoice->setFile($pdf);
        $invoice->setType($type);
        $invoice->setTotal($total);

        return $invoice;
    }
585743
public function update(int $invoice, array $data)
    {
        $response = $this->httpPut('/3/invoices/'.$invoice, ['Invoice' => $data]);

        if (!$this->hydrator) {
            return $response;
        }

        // Use any valid status code here
        if (200 !== $response->getStatusCode()) {
            $this->handleErrors($response);
        }

        return $this->hydrator->hydrate($response, Model::class);
    }
162490
public function invoice()
    {
        if ($this->stripe_id) {
            try {
                return StripeInvoice::create(['customer' => $this->stripe_id], $this->getStripeKey())->pay();
            } catch (InvalidRequest $e) {
                return false;
            }
        }

        return true;
    }
774772
function execute(Ob $o) {
		$provider = $o[Plugin::PROVIDER]; /** @var Provider $provider */
		/** @var ISearchResult|ApiSearchResult|UiSearchResult|OrderGC|InvoiceGC|CreditmemoGC $result */
		$result = $o[Plugin::RESULT];
		// 2017-08-02 For now, we do not handle «sales_order_invoice_grid_data_source»
		// and «sales_order_creditmemo_grid_data_source».
		if ('sales_order_grid_data_source' === $provider->getName()) {
			/**
			 * 2016-07-28
			 * https://github.com/magento/magento2/blob/2.1.0/lib/internal/Magento/Framework/View/Element/UiComponent/DataProvider/SearchResult.php#L37-L40
			 * @see \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult::$document
			 * The document's structure is described here: https://mage2.pro/t/1908
			 */
			$cacheKey = __METHOD__; /** @var string $cacheKey */
			$prop = 'payment_method';  /** @var string $prop */
			df_map($result, function(Document $item) use($cacheKey, $prop) {
				/** @var string|null $methodCode */
				if (($methodCode = $item[$prop]) && df_starts_with($methodCode, 'dfe_')) {
					/**
					 * 2017-05-09
					 * Как оказалось, наличие приставки «dfe_» ешё не гарантирует,
					 * что @uses dfpm() (вызываемый ниже опосредованно через dfpm_title())
					 * действительно вернёт наследника @see \Df\Payment\Method
					 * Возможна ситуация, когда админтратор установил какой-либо из моих патёжных модулей,
					 * сделал платёж посредством него, а затем либо удалил модуль,
					 * либо из-за каких-то некорректных действий модуль стал отключенным,
					 * и вот тогда M2 вернёт не наследника @see \Df\Payment\Method,
					 * а экземпляр класса @see \Magento\Payment\Model\Method\Substitution:
					 * «How is @see \Magento\Payment\Model\Method\Substitution implemented and used?»
					 * https://mage2.pro/t/3924
					 * 1) @see \Magento\Sales\Model\Order\Payment\Info::getMethodInstance()
					 *	try {
					 *		$instance = $this->paymentData->getMethodInstance($this->getMethod());
					 *	} catch (\UnexpectedValueException $e) {
					 *		$instance = $this->paymentData->getMethodInstance(Substitution::CODE);
					 *	}
					 * https://github.com/magento/magento2/blob/2.1.6/app/code/Magento/Sales/Model/Order/Payment/Info.php#L113-L117
					 * 2) @see \Magento\Payment\Model\Info::getMethodInstance()
					 *	try {
					 *		$instance = $this->_paymentData->getMethodInstance($this->getMethod());
					 *	} catch (\UnexpectedValueException $e) {
					 *		$instance = $this->_paymentData->getMethodInstance(Method\Substitution::CODE);
					 *	}
					 * https://github.com/magento/magento2/blob/2.1.6/app/code/Magento/Payment/Model/Info.php#L106-L110
					 */
					$id = $item['entity_id']; /** @var int $id */
					// 2016-07-29
					// Эта операция очень ресурсоёмка:
					// для каждой строки таблицы заказов она делает кучу запросов к базе данных.
					// Поэтому кэшируем результаты в постоянном кэше.
					$item[$prop] = df_cache_get_simple([$cacheKey, $id], function() use($id) {
						$m = dfpm($o = df_order($id)); /** @var O $o */ /** @var M|Substitution $m */
						return !dfp_my($m) ? $m->getTitle() : df_cc_br(dfpm_title($m), dfp_choice($o)->title());
					});
				}
			});
		}
	}
321549
public function sendAdvertPurchaseConfirmationMessage(Invoice $invoice, $amount)
    {
        //send email to optic to confirm plan purchase
        //check empty bank number account
        $templateName = 'PaymentBundle:Email:advert.confirmation.html.twig';
        $advert = $invoice->getTransaction()->getItems()->first()->getAdvert();
        
        if($invoice->getTransaction()->getActor() instanceof Actor){
            $user = $invoice->getTransaction()->getActor();
        }elseif($invoice->getTransaction()->getOptic() instanceof Optic){
            $user = $invoice->getTransaction()->getOptic();
        }
            
        $toEmail = $user->getEmail();
        $token = null;
            
         $context = array(
            'order_number' => $invoice->getTransaction()->getTransactionKey(),
            'advert' => $advert,
            'user' => $user,
            'token' => $token
        );
        
        $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email') , $toEmail);
        
    }
30600
public function sendPurchaseNotification($invoice)
    {
        $templateName = 'PaymentBundle:Email:sale.notification.admin.html.twig';

        if($invoice->getTransaction()->getItems()->first()->getProduct() instanceof Product){
            $product = $invoice->getTransaction()->getItems()->first()->getProduct();
        }
        
        $sellerEmails = array();
        if($invoice->getTransaction()->getItems()->first()->getProduct()->getActor() instanceof Actor){
            $sellerEmails[] = $invoice->getTransaction()->getItems()->first()->getProduct()->getActor()->getEmail();
        } 
            
        $context = array(
            'order_number'    => $invoice->getTransaction()->getTransactionKey(),
            'invoice_date'      => $invoice->getCreated(),
            'user_email'        => $invoice->getTransaction()->getActor()->getEmail(),
            'seller_email'        => implode(',', $sellerEmails),
            'order_details_url' => $this->router->generate('payment_checkout_showinvoice', array('number' => $invoice->getInvoiceNumber()), UrlGeneratorInterface::ABSOLUTE_URL),
        );

        $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email'), $this->twigGlobal->getParameter('admin_email'));
    }
459938
public function showAction(Invoice $invoice, Request $request)
    {
        $buyer = $this->get('security.context')
            ->getToken()
            ->getUser()
            ->getCurrentProfile()
        ;

        // $savedCreditCards = $buyer->getSavedCreditCards();

        return $this->render('HarvestCloudCoreBundle:Buyer/Invoice:show.html.twig', array(
            'invoice' => $invoice,
        ));
    }