Sends an invoice
3029
def send_invoice(invoice)
      response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'})
      InvoiceParser.parse(response, invoice)
    end
827252
protected function sendPayRequest()
	{
		$dateTime = new DateTime();

		$this->newTransaction();

		$fields = array(
			'terminalId' => $this->config->get('gateway.mellat.terminalId'),
			'userName' => $this->config->get('gateway.mellat.username'),
			'userPassword' => $this->config->get('gateway.mellat.password'),
			'orderId' => $this->transactionId(),
			'amount' => $this->amount,
			'localDate' => $dateTime->format('Ymd'),
			'localTime' => $dateTime->format('His'),
			'additionalData' => '',
			'callBackUrl' => $this->getCallback(),
			'payerId' => 0,
		);

		try {
			$soap = new \SoapClient($this->serverUrl);
            $response = $soap->bpPayRequest($fields);

		} catch (\SoapFault $e) {
			$this->transactionFailed();
			$this->newLog('SoapFault', $e->getMessage());
			throw $e;
		}

		$response = explode(',', $response->return);

		if ($response[0] != '0') {
			$this->transactionFailed();
			$this->newLog($response[0], MellatException::$errors[$response[0]]);
			throw new MellatException($response[0]);
		}
		$this->refId = $response[1];
		$this->transactionSetRefId();
	}
424380
def notify_by(self, invoice_id, medium, **kwargs):
        "
        url = "{}/{}/notify_by/{}".format(self.base_url, invoice_id, medium)
        return self.post_url(url, {}, **kwargs)
111052
public function create()
    {
        if (!userHasPermission('admin:invoice:invoice:create')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Page Title
        $this->data['page']->title = 'Create Invoice';

        // --------------------------------------------------------------------------

        $oInput                    = Factory::service('Input');
        $this->data['customer_id'] = $oInput->get('customer_id');

        if ($oInput->post()) {
            if ($this->validatePost()) {
                $oInvoice = $this->oInvoiceModel->create($this->getObjectFromPost(), true);
                if (!empty($oInvoice)) {

                    //  Send invoice if needed
                    $this->sendInvoice($oInvoice);

                    $oSession = Factory::service('Session', 'nails/module-auth');
                    $oSession->setFlashData('success', 'Invoice created successfully.');

                    redirect('admin/invoice/invoice/index');

                } else {
                    $this->data['error'] = 'Failed to create invoice. ' . $this->oInvoiceModel->lastError();
                }

            } else {
                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

        // --------------------------------------------------------------------------

        //  Page data
        $aItemUnits = $this->oInvoiceItemModel->getUnits();
        $aTaxes     = $this->oTaxModel->getAll();

        $this->data['invoiceStates'] = $this->oInvoiceModel->getSelectableStates();

        // --------------------------------------------------------------------------

        //  Invoice Items
        $oInput = Factory::service('Input');
        if ($oInput->post()) {

            $aItems = $oInput->post('items') ?: [];
            //  Tidy up post data as expected by JS
            foreach ($aItems as &$aItem) {

                $aItem['label'] = html_entity_decode($aItem['label'], ENT_QUOTES, 'UTF-8');
                $aItem['body']  = html_entity_decode($aItem['body'], ENT_QUOTES, 'UTF-8');

                $sUnitCost                     = $aItem['unit_cost'];
                $aItem['unit_cost']            = new \stdClass();
                $aItem['unit_cost']->formatted = new \stdClass();
                $aItem['unit_cost']->formatted = !empty($sUnitCost) ? $sUnitCost : null;

                $aItem['tax']     = new \stdClass();
                $aItem['tax']->id = !empty($aItem['tax_id']) ? (int) $aItem['tax_id'] : null;

                $sUnit             = !empty($aItem['unit']) ? $aItem['unit'] : null;
                $aItem['unit']     = new \stdClass();
                $aItem['unit']->id = $sUnit;
            }

        } else {
            $aItems = [];
        }

        // --------------------------------------------------------------------------

        $oCurrency                = Factory::service('Currency', 'nails/module-currency');
        $aCurrencies              = $oCurrency->getAllEnabled();
        $this->data['currencies'] = $aCurrencies;

        // --------------------------------------------------------------------------

        $oAsset = Factory::service('Asset');
        //  @todo (Pablo - 2018-11-30) - Load the minified version once the JS bundling has been sorted
        $oAsset->load('invoice.edit.js', 'nails/module-invoice');
        $oAsset->inline(
            'ko.applyBindings(
                new invoiceEdit(
                    ' . json_encode($aItemUnits) . ',
                    ' . json_encode($aTaxes) . ',
                    ' . json_encode($aItems) . ',
                    ' . json_encode($aCurrencies) . '
                )
            );',
            'JS'
        );

        //  Load views
        Helper::loadView('edit');
    }
550806
public function send(int $iInvoiceId, string $sEmailOverride = null): bool
    {
        try {

            $oInvoice = $this->getById($iInvoiceId);

            if (empty($oInvoice)) {
                throw new InvoiceException('Invalid Invoice ID', 1);
            }

            if ($oInvoice->state->id !== self::STATE_OPEN) {
                throw new InvoiceException('Invoice must be in an open state to send.', 1);
            }

            if (!empty($sEmailOverride)) {

                //  @todo, validate email address (or addresses if an array)
                $aEmails = explode(',', $sEmailOverride);

            } elseif (!empty($oInvoice->customer->billing_email)) {

                $aEmails = explode(',', $oInvoice->customer->billing_email);

            } elseif (!empty($oInvoice->customer->email)) {

                $aEmails = [$oInvoice->customer->email];

            } elseif (!empty($oInvoice->email)) {

                $aEmails = [$oInvoice->email];

            } else {
                throw new InvoiceException('No email address to send the invoice to', 1);
            }

            $oEmailer           = Factory::service('Emailer', 'nails/module-email');
            $oInvoiceEmailModel = Factory::model('InvoiceEmail', 'nails/module-invoice');

            $oEmail       = new \stdClass();
            $oEmail->type = 'send_invoice';
            $oEmail->data = [
                'invoice' => $oInvoice,
            ];

            foreach ($aEmails as $sEmail) {

                $oEmail->to_email = $sEmail;

                $oResult = $oEmailer->send($oEmail);

                if (!empty($oResult)) {

                    $oInvoiceEmailModel->create(
                        [
                            'invoice_id' => $oInvoice->id,
                            'email_id'   => $oResult->id,
                            'email_type' => $oEmail->type,
                            'recipient'  => $oEmail->to_email,
                        ]
                    );

                } else {
                    throw new InvoiceException($oEmailer->lastError(), 1);
                }
            }

        } catch (\Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }

        return true;
    }
798128
def sendfrom(self, account, address, amount):
        """"""
        return self.req("sendfrom", [account, address, amount])
1284221
private function addInvoice($trans, $invoice_no, $ref_no, $options)
    {
        $trans->addChild('InvoiceNo', $invoice_no);
        $trans->addChild('RefNo', $ref_no ?: $invoice_no);
        if ($options['merchant']) {
            $trans->addChild('OperatorID', $options['merchant']);
        }
        if ($options['description']) {
            $trans->addChild('Memo', $options['description']);
        }
    }
211016
private function invoice() {
		$invoiceService = df_o(InvoiceService::class); /** @var InvoiceService $invoiceService */
		/** @var Invoice|DfInvoice $result */
		if (!($result = $invoiceService->prepareInvoice($this->o()))) {
			throw new LE(__('We can\'t save the invoice right now.'));
		}
		if (!$result->getTotalQty()) {
			throw new LE(__('You can\'t create an invoice without products.'));
		}
		df_register('current_invoice', $result);
		/**
		 * 2016-03-26
		 * @used-by \Magento\Sales\Model\Order\Invoice::register()
		 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Invoice.php#L599-L609
		 * Используем именно @see \Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE,
		 * а не @see \Magento\Sales\Model\Order\Invoice::CAPTURE_OFFINE,
		 * чтобы была создана транзакция capture.
		 */
		$result->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
		$result->register();
		return $result;
	}
1348453
def send(self, send_string, newline=None):
        """"""
        self.current_send_string = send_string
        newline = newline if newline is not None else self.newline

        self.channel.send(send_string + newline)
1002513
def get_invoice(invoice_id_or_number, format = :xml)
      request_params = {}
      headers        = {}

      headers.merge!("Accept" => "application/pdf") if format == :pdf

      url  = "#{@xero_url}/Invoices/#{CGI.escape(invoice_id_or_number)}"

      response = http_get(@client, url, request_params, headers)

      if format == :pdf
        Tempfile.open(invoice_id_or_number) do |f|
          f.write(response)
          f
        end
      else
        parse_response(response, {:request_params => request_params}, {:request_signature => 'GET/Invoice'})
      end
    end
146534
public function sendPurchaseConfirmationMessage(Invoice $invoice, $amount)
    {
        $templateName = 'PaymentBundle:Email:sale.confirmation.html.twig';
        $toEmail = $invoice->getTransaction()->getActor()->getEmail();

      
        $orderUrl = $this->router->generate('payment_checkout_showinvoice', array('number' => $invoice->getInvoiceNumber()), UrlGeneratorInterface::ABSOLUTE_URL);

        $context = array(
            'order_number' => $invoice->getTransaction()->getTransactionKey(),
            'amount'         => $amount,
            'payment_type'   => $invoice->getTransaction()->getPaymentMethod()->getName(),
            'order_url'      => $orderUrl,
        );

        $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email') , $toEmail);
        
        //send email to optic to confirm purchase
        //check empty bank number account
        $templateName = 'PaymentBundle:Email:sale.confirmation.actor.html.twig';
        $productItems = $invoice->getTransaction()->getItems();
        $actor = $productItems->first()->getProduct()->getActor();
        if($actor instanceof Actor) {
            $toEmail = $actor->getEmail();
            $token = null;
            if($actor->getBankAccountNumber() == ''){
                $token = sha1(uniqid());
                $date = new \DateTime();
                $actor->setBankAccountToken($token);
                $actor->setBankAccountTime($date->getTimestamp());
                $this->manager->persist($actor);
                $this->manager->flush();
            }
            $context = array(
                'order_number' => $invoice->getTransaction()->getTransactionKey(),
                'products' => $productItems,
                'token' => $token,
                'actor' => $actor
            );

            $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email') , $toEmail);
        }
        
    }
647298
public function send()
    {
        $aParams = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('editval', true);
        if (!is_array($aParams)) {
            return;
        }

        // storing used written values
        $oParams = (object) $aParams;
        $this->setSuggestData((object) \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('editval'));

        $oUtilsView = \OxidEsales\Eshop\Core\Registry::getUtilsView();

        // filled not all fields ?
        foreach ($this->_aReqFields as $sFieldName) {
            if (!isset($aParams[$sFieldName]) || !$aParams[$sFieldName]) {
                $oUtilsView->addErrorToDisplay('SUGGEST_COMLETECORRECTLYFIELDS');

                return;
            }
        }

        if (!oxNew(\OxidEsales\Eshop\Core\MailValidator::class)->isValidEmail($aParams["rec_email"]) || !oxNew(\OxidEsales\Eshop\Core\MailValidator::class)->isValidEmail($aParams["send_email"])) {
            $oUtilsView->addErrorToDisplay('SUGGEST_INVALIDMAIL');

            return;
        }

        $sReturn = "";
        // #1834M - specialchar search
        $sSearchParamForLink = rawurlencode(\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('searchparam', true));
        if ($sSearchParamForLink) {
            $sReturn .= "&searchparam=$sSearchParamForLink";
        }

        $sSearchCatId = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('searchcnid');
        if ($sSearchCatId) {
            $sReturn .= "&searchcnid=$sSearchCatId";
        }

        $sSearchVendor = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('searchvendor');
        if ($sSearchVendor) {
            $sReturn .= "&searchvendor=$sSearchVendor";
        }

        if (($sSearchManufacturer = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('searchmanufacturer'))) {
            $sReturn .= "&searchmanufacturer=$sSearchManufacturer";
        }

        $sListType = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter('listtype');
        if ($sListType) {
            $sReturn .= "&listtype=$sListType";
        }

        // sending suggest email
        $oEmail = oxNew(\OxidEsales\Eshop\Core\Email::class);
        $oProduct = $this->getProduct();
        if ($oProduct && $oEmail->sendSuggestMail($oParams, $oProduct)) {
            return 'details?anid=' . $oProduct->getId() . $sReturn;
        } else {
            $oUtilsView->addErrorToDisplay('SUGGEST_INVALIDMAIL');
        }
    }
850876
def cli(env, identifier, details):
    """"""

    manager = AccountManager(env.client)
    top_items = manager.get_billing_items(identifier)

    title = "Invoice %s" % identifier
    table = formatting.Table(["Item Id", "Category", "Description", "Single",
                              "Monthly", "Create Date", "Location"], title=title)
    table.align['category'] = 'l'
    table.align['description'] = 'l'
    for item in top_items:
        fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', ''))
        # category id=2046, ram_usage doesn't have a name...
        category = utils.lookup(item, 'category', 'name') or item.get('categoryCode')
        description = nice_string(item.get('description'))
        if fqdn != '.':
            description = "%s (%s)" % (item.get('description'), fqdn)
        table.add_row([
            item.get('id'),
            category,
            nice_string(description),
            "$%.2f" % float(item.get('oneTimeAfterTaxAmount')),
            "$%.2f" % float(item.get('recurringAfterTaxAmount')),
            utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"),
            utils.lookup(item, 'location', 'name')
        ])
        if details:
            for child in item.get('children', []):
                table.add_row([
                    '>>>',
                    utils.lookup(child, 'category', 'name'),
                    nice_string(child.get('description')),
                    "$%.2f" % float(child.get('oneTimeAfterTaxAmount')),
                    "$%.2f" % float(child.get('recurringAfterTaxAmount')),
                    '---',
                    '---'
                ])

    env.fout(table)
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;
    }
834596
def send(self, msg):
        """"""
        debug('sent %s', msg)
        self.loop.send(self._packer.pack(msg))
242695
public function sendData($data)
    {
        $invoice = new Invoice();
        $invoice->setFullNotifications(true);
        $invoice->setItem($this->createItem());
        $invoice->setCurrency(new Currency($this->getCurrency()));
        $invoice->setRedirectUrl($this->getReturnUrl());
        $invoice->setNotificationUrl($this->getNotifyUrl());
        $invoice->setPosData(json_encode($this->buildPosData()));

        $response = $this->getClient()->createInvoice($invoice);

        return $this->response = new PurchaseResponse($this, $response);
    }
1072073
@Override
    public InvoiceWithMetadata generateInvoice(final ImmutableAccountData account,
                                               @Nullable final BillingEventSet events,
                                               @Nullable final Iterable<Invoice> existingInvoices,
                                               @Nullable final UUID targetInvoiceId,
                                               final LocalDate targetDate,
                                               final Currency targetCurrency,
                                               final InternalCallContext context) throws InvoiceApiException {
        if ((events == null) || (events.size() == 0) || events.isAccountAutoInvoiceOff()) {
            return new InvoiceWithMetadata(null, ImmutableSet.of(), ImmutableMap.<UUID, SubscriptionFutureNotificationDates>of());
        }

        validateTargetDate(targetDate, context);
        final LocalDate adjustedTargetDate = adjustTargetDate(existingInvoices, targetDate);

        final LocalDate invoiceDate = context.toLocalDate(context.getCreatedDate());
        final InvoiceStatus invoiceStatus = events.isAccountAutoInvoiceDraft() ? InvoiceStatus.DRAFT : InvoiceStatus.COMMITTED;
        final DefaultInvoice invoice = targetInvoiceId != null ?
                                       new DefaultInvoice(targetInvoiceId, account.getId(), null, invoiceDate, adjustedTargetDate, targetCurrency, false, invoiceStatus) :
                                       new DefaultInvoice(account.getId(), invoiceDate, adjustedTargetDate, targetCurrency, invoiceStatus);

        final Map<UUID, SubscriptionFutureNotificationDates> perSubscriptionFutureNotificationDates = new HashMap<UUID, SubscriptionFutureNotificationDates>();

        final InvoiceGeneratorResult fixedAndRecurringItems = recurringInvoiceItemGenerator.generateItems(account, invoice.getId(), events, existingInvoices, adjustedTargetDate, targetCurrency, perSubscriptionFutureNotificationDates, context);
        invoice.addInvoiceItems(fixedAndRecurringItems.getItems());

        final InvoiceGeneratorResult usageItemsWithTrackingIds = usageInvoiceItemGenerator.generateItems(account, invoice.getId(), events, existingInvoices, adjustedTargetDate, targetCurrency, perSubscriptionFutureNotificationDates, context);
        invoice.addInvoiceItems(usageItemsWithTrackingIds.getItems());

        if (targetInvoiceId != null) {
            final Invoice originalInvoice = Iterables.tryFind(existingInvoices, new Predicate<Invoice>() {
                @Override
                public boolean apply(final Invoice input) {
                    return input.getId().equals(targetInvoiceId);
                }
            }).orNull();
            Preconditions.checkNotNull(originalInvoice, "Expecting to find an existing invoice matching the targetInvoiceId");
            invoice.addInvoiceItems(originalInvoice.getInvoiceItems());
        }

        return new InvoiceWithMetadata(invoice.getInvoiceItems().isEmpty() ? null : invoice,
                                       usageItemsWithTrackingIds.getTrackingIds(),
                                       perSubscriptionFutureNotificationDates);
    }