Provede "Zaplacení" vydané faktury

@param \FlexiPeeHP\FakturaVydana $invoice Invoice to settle
@param \FlexiPeeHP\Banka         $payment Payment to settle by

@return int vysledek 0 = chyba, 1 = sparovano
188620
public function settleInvoice($invoice, $payment)
    {
        $success       = 0;
        $zbytek        = 'ne';
        $prijataCastka = (float) $payment->getDataValue('sumCelkem');
        $zbyvaUhradit  = $invoice->getDataValue('zbyvaUhradit');

        if ($prijataCastka < $zbyvaUhradit) { //Castecna uhrada
            $this->addStatusMessage(sprintf(_('Castecna uhrada - FAKTURA: prijato: %s %s ma byt zaplaceno %s %s'),
                    $prijataCastka,
                    \FlexiPeeHP\FlexiBeeRO::uncode($payment->getDataValue('mena')),
                    $zbyvaUhradit,
                    \FlexiPeeHP\FlexiBeeRO::uncode($invoice->getDataValue('mena'))),
                'warning');
            $zbytek = 'castecnaUhrada';
        }
        if ($prijataCastka > $zbyvaUhradit) { //Castecna uhrada
            $this->addStatusMessage(sprintf(_('Přeplatek - FAKTURA: prijato: %s %s ma byt zaplaceno %s %s'),
                    $prijataCastka,
                    \FlexiPeeHP\FlexiBeeRO::uncode($payment->getDataValue('mena')),
                    $zbyvaUhradit,
                    \FlexiPeeHP\FlexiBeeRO::uncode($invoice->getDataValue('mena'))),
                'warning');

            //$this->banker->insertToFlexiBee(['id'=>$payment->getDataValue('id'), 'stitky'=>$this->config['LABEL_CASTECNAUHRADA']]);
            $zbytek = 'ignorovat';
        }

        if ($invoice->sparujPlatbu($payment, $zbytek)) { //Jak se ma FlexiBee zachovat pri preplatku/nedoplatku
            $success = 1;
            $invoice->insertToFlexiBee(['id' => (string) $invoice, 'stavMailK' => 'stavMail.odeslat']);
            $invoice->addStatusMessage(sprintf(_('Platba %s  %s %s byla sparovana s fakturou %s'),
                    \FlexiPeeHP\FlexiBeeRO::uncode($payment->getRecordIdent()),
                    $prijataCastka,
                    \FlexiPeeHP\FlexiBeeRO::uncode($payment->getDataValue('mena')),
                    \FlexiPeeHP\FlexiBeeRO::uncode($invoice->getRecordIdent())),
                'success');
        }

        return $success;
    }
1049819
public function capture(Varien_Object $payment, $amount)
    {
        parent::capture($payment, $amount);
        $payment->setStatus(self::STATUS_APPROVED)
            ->setTransactionId($this->getTransactionId())
            ->setIsTransactionClosed(0);
        $order = $payment->getOrder();
        $currency = $order->getOrderCurrencyCode();

        if ($payment->hasCurrentInvoice() && $currency != $order->getBaseCurrencyCode()) {
            $invoice = $payment->getCurrentInvoice();
            $amount = $invoice->getGrandTotal();
        }

        // do capture request to adyen
        $order = $payment->getOrder();
        $pspReference = Mage::getModel('adyen/event')->getOriginalPspReference($order->getIncrementId());
        $order->getPayment()->getMethodInstance()->sendCaptureRequest($payment, $amount, $pspReference);

        return $this;
    }
1105678
public void doCBAComplexityFromTransaction(final UUID invoiceId,
                                               final List<Tag> invoicesTags,
                                               final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
                                               final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException {
        final InvoiceSqlDao transInvoiceDao = entitySqlDaoWrapperFactory.become(InvoiceSqlDao.class);
        final InvoiceModelDao invoice = transInvoiceDao.getById(invoiceId.toString(), context);
        invoiceDaoHelper.populateChildren(invoice, invoicesTags, entitySqlDaoWrapperFactory, context);

        doCBAComplexityFromTransaction(invoice, invoicesTags, entitySqlDaoWrapperFactory, context);
    }
303125
public function removeInvoice(\Gpupo\CommonSchema\ORM\Entity\Trading\Order\Shipping\Invoice\Invoice $invoice)
    {
        return $this->invoices->removeElement($invoice);
    }
137019
public function addPayment(\OxidEsales\PayPalModule\Model\OrderPayment $payment)
    {
        $paymentList = $this->getPaymentList();
        $paymentList->addPayment($payment);
        $this->setPaymentList(null);
    }
117488
public function settle(IncomingInvoice $invoiceA, IncomingInvoice $invoiceB)
    {
        return $this->connector->settle($invoiceA, $invoiceB);
    }
1268691
public function send(Invoice $invoice, $method = 'email', $email = null, $message = null)
    {
        return $this->connector->send($invoice, $this->buildEnvelope($method, $email, $message));
    }
914762
public function payment(Payment $payment, &$paymentParams)
    {
        if (!$this->checkCurrency($payment->currency)) {
            Yii::$app->session->setFlash(Yii::t('payment', 'The gateway does not support the current currency!'));
        } else {
            $params = [
                'MerNo' => $this->merNo,
                'BillNo' => $payment->id,
                'Amount' => round($payment->money, 2),
                'ReturnURL' => $this->getReturnUrl(),
                'AdviceURL' => $this->getNoticeUrl(),
                'products' => !empty($payment->model_id) ? $payment->model_id : '充值',
                'Remark' => 'Remark',
                'defaultBankNumber' => $this->defaultBankNumber,
                'orderTime' => date('YmdHis')
            ];
            $md5src = $this->merNo . '&' . $payment->id . '&' . $params['Amount'] . '&' . $params['ReturnURL'] . '&' . $this->md5Key;        //校验源字符串
            $params['SignInfo'] = strtoupper(md5($md5src));//MD5检验结果
            $this->getRedirectResponse($params);
        }
    }
1014894
public function payment(Payment $payment, &$paymentParams)
    {
        if (!$this->checkCurrency($payment->currency)) {
            Yii::$app->session->setFlash(Yii::t('payment', 'The gateway does not support the current currency!'));
        } else {
            $params = $this->buildPaymentParameter([
                'body' => !empty($payment->model_id) ? $payment->model_id : '充值',
                'out_trade_no' => $payment->id,
                'total_fee' => round($payment->money * 100),
                'fee_type' => $payment->currency,
                'spbill_create_ip' => $payment->ip,
                'trade_type' => $this->tradeTypeMap[$payment->trade_type],
            ]);
            if ($payment->trade_type == Payment::TYPE_JS_API) {//微信扫码付必须得字段
                $params['openid'] = $payment->user->wechat->openid;
            }
            $params['sign'] = $this->createSign($params);
            /** @var \yii\httpclient\Response $response */
            $response = $this->api('https://api.mch.weixin.qq.com/pay/unifiedorder', 'POST', $params);//统一下单
            if ($response->isOk && $response->data['return_code'] == 'SUCCESS') {
                $payment->updateAttributes(['pay_id' => $response->data['prepay_id']]);
                if ($payment->trade_type == Payment::TYPE_JS_API) {
                    $paymentParams = [
                        'appId' => $this->appId,
                        'timeStamp' => time(),
                        'nonceStr' => md5(uniqid()),
                        'package' => 'prepay_id=' . $response->data['prepay_id'],
                        'signType' => 'MD5',
                    ];
                    $paymentParams['paySign'] = $this->makeSign($paymentParams);
                    return;
                } elseif ($payment->trade_type == Payment::TYPE_NATIVE) {
                    $paymentParams['url'] = $response->data['code_url'];
                    $paymentParams['data'] = (new QrCode())->setText($response->data['code_url'])->setSize(240)->setPadding(10)->getDataUri();
                    return;
                }
            } else {
                $paymentParams = $response->data;
            }
        }
    }
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());
					});
				}
			});
		}
	}
36681
public function acumulusInvoiceCreated($invoice, BaseSource $invoiceSource, Result $localResult)
    {
        $invoice = $this->supportBundleProducts($invoice, $invoiceSource, $localResult);
        $invoice = $this->supportTMExtraProductOptions($invoice, $invoiceSource, $localResult);
        return $invoice;
    }
279291
public function listPaymentsForInvoice(string $invoiceId, array $headers = [])
    {
        $url = $this->url('invoices/%s/payments', $invoiceId);

        return $this->get($url, [], $headers);
    }
202086
public function issue(Invoice $invoice)
    {
        $result = $this->update($invoice, [
            'issued_at'  => new \DateTime(),
            'expires_at' => (new \DateTime())->modify('+1 month'),
            'number'     => $this->getNumberManager()->calculateNextFreeNumber(),
        ]);

        $result->ok() && event(new Events\InvoiceIssued($invoice));

        return $result;
    }
417042
public function findInvoices($paymentData)
    {
        $invoices  = [];
        $vInvoices = [];
        $sInvoices = [];
        $uInvoices = [];
        $bInvoices = [];

        if (!empty($paymentData['varSym'])) {
            $vInvoices = $this->findInvoice(['varSym' => $paymentData['varSym']]);
        }

        if (empty($vInvoices)) {

            if (!empty($paymentData['specSym'])) {

                // Faktury vydane "firma":"code:02100",
                // Adresar: ext:lms.cstmr:2365
                $uInvoices = $this->findInvoice(['firma' => sprintf("code:%05s",
                        $paymentData['specSym'])]);
            }

            if (!empty($paymentData['specSym'])) {
                $sInvoices = $this->findInvoice(['specSym' => $paymentData['specSym']]);
            }

            if ($paymentData['buc']) {
                $bInvoices = $this->findInvoice(['buc' => $paymentData['buc']]);
            }
        }

        self::unifyInvoices($vInvoices, $invoices);
        self::unifyInvoices($uInvoices, $invoices);
        self::unifyInvoices($sInvoices, $invoices);
        self::unifyInvoices($bInvoices, $invoices);

        $invoices = self::reorderInvoicesByAge($invoices);

        if (empty($paymentData['varSym']) && empty($paymentData['specSym'])) {
            $this->banker->dataReset();
            $this->banker->setDataValue('id', $paymentData['id']);
            $this->banker->setDataValue('stitky', 'NEIDENTIFIKOVANO');
            $this->addStatusMessage(_('Neidentifikovaná platba').': '.$this->banker->getApiURL(),
                'warning');
            $this->banker->insertToFlexiBee();
        } elseif (count($invoices) == 0) {
            $this->banker->dataReset();
            $this->banker->setDataValue('id', $paymentData['id']);
            $this->banker->setDataValue('stitky', 'CHYBIFAKTURA');
            $this->addStatusMessage(_('Platba bez faktury').': '.$this->banker->getApiURL(),
                'warning');
            $this->banker->insertToFlexiBee();
        }

        return $invoices;
    }
507103
public function registerPayment(SalesInvoicePayment $salesInvoicePayment)
    {
        if (! isset($salesInvoicePayment->payment_date)) {
            throw new ApiException('Required [payment_date] is missing');
        }

        if (! isset($salesInvoicePayment->price)) {
            throw new ApiException('Required [price] is missing');
        }

        $this->connection()->post($this->endpoint . '/' . $this->id . '/payments',
            $salesInvoicePayment->jsonWithNamespace()
        );

        return $this;
    }
1214704
protected function _setPaymentStatus( MShop_Order_Item_Interface $invoice, array $response )
	{
		if( !isset( $response['PAYMENTSTATUS'] ) ) {
			return;
		}

		switch ( $response['PAYMENTSTATUS'] )
		{
			case 'Pending':
				if( isset( $response['PENDINGREASON'] ) )
				{
					if( $response['PENDINGREASON'] === 'authorization' )
					{
						$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_AUTHORIZED );
						break;
					}

					$str = 'PayPal Express: order ID = ' . $invoice->getId() . ', PENDINGREASON = ' . $response['PENDINGREASON'];
					$this->_getContext()->getLogger()->log( $str, MW_Logger_Abstract::INFO );
				}

				$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_PENDING );
				break;

			case 'In-Progress':
				$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_PENDING );
				break;

			case 'Completed':
			case 'Processed':
				$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_RECEIVED );
				break;

			case 'Failed':
			case 'Denied':
			case 'Expired':
				$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_REFUSED );
				break;

			case 'Refunded':
			case 'Partially-Refunded':
			case 'Reversed':
				$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_REFUND );
				break;

			case 'Canceled-Reversal':
			case 'Voided':
				$invoice->setPaymentStatus( MShop_Order_Item_Abstract::PAY_CANCELED );
				break;

			default:
				$str = 'PayPal Express: order ID = ' . $invoice->getId() . ', response = ' . print_r( $response, true );
				$this->_getContext()->getLogger()->log( $str, MW_Logger_Abstract::INFO );
		}
	}
658008
public function _build($payment, $type)
        {
            $order    = $payment->getOrder();
            $billing  = $order->getBillingAddress();
            $shipping = $order->getShippingAddress();

            # Should be only used in the developement environment
            # without it we get duplicate order id.
            $token = $this->getConfigData('order_token');
            $token = (empty($token)) ? "" : "-" . $token;


            $transaction = array(
                'type'       => $type,
                'order_id'   => $order->getIncrementId() . $token,
                'crypt_type' => self::CRYPT_TYPE,
            );


            switch($type) {
                case self::TRANSACTION_PREAUTH :
                    $transaction = $transaction + array(
                        'cust_id'    => $billing->getCustomerId(),
                        'amount'     => sprintf("%01.2f", $payment->getAmount()),
                        'pan'        => $this->_cleanCC($payment->getCcNumber()),
                        'expdate'    => $this->_formatExpirationDate($payment->getCcExpYear(), $payment->getCcExpMonth()),
                        'cvd_value'  => $payment->getCcCid(),
                        'cvd_indicator' => 1
                    );

                    break;
                case self::TRANSACTION_COMPLETION :
                    $transaction = $transaction + array(
                        'comp_amount' => sprintf("%01.2f", $payment->getAmount()),
                        'txn_number'  => $payment->getCcTransId(),
                    );

                    break;
                case self::TRANSACTION_VOID :
                    $transaction = $transaction + array(
                        'comp_amount' => sprintf("%01.2f", $payment->getAmount()),
                        'txn_number'  => $payment->getCcTransId(),
                    );
                    break;

            }

            return new mpgTransaction($transaction);
        }