Creates an invoice from the pending charges on the account.
 Raises an error if it fails.

 @return [InvoiceCollection] A newly-created invoice.
 @raise [Invalid] Raised if the account cannot be invoiced.
431298
def invoice!(attrs={})
      InvoiceCollection.from_response API.post(invoices.uri, attrs.empty? ? nil : Invoice.to_xml(attrs))
    rescue Recurly::API::UnprocessableEntity => e
      raise Invalid, e.message
    end
1072790
def make_transaction(self):
        
        if self.pk:
            raise CannotRecreateTransactionOnRecurredCost(
                'The transaction for this recurred cost has already been created. You cannot create it again.'
            )

        amount = self.recurring_cost.get_amount(self.billing_cycle)

        # It is quite possible that there will be nothing to bill, in which
        # case we cannot create a transaction with no legs, nor can we create
        # legs with zero values. Therefore we don't create any transaction.
        if not amount:
            return None

        self.transaction = Transaction.objects.create(
            description='Created by recurring cost',
            date=self.billing_cycle.date_range.lower
        )

        # Use the SplitManager's custom queryset's split() method to get the
        # amount to be billed for each split
        splits = self.recurring_cost.splits.all().split(amount)

        # Create the transaction leg for the outbound funds
        # (normally to an expense account)
        self.transaction.legs.add(Leg.objects.create(
            transaction=self.transaction,
            amount=Money(amount, self.recurring_cost.currency),
            account=self.recurring_cost.to_account,
        ))

        for split, split_amount in splits:
            # Create the transaction legs for the inbound funds
            # (from housemate accounts)
            if split_amount:
                self.transaction.legs.add(Leg.objects.create(
                    transaction=self.transaction,
                    amount=Money(split_amount * -1, self.recurring_cost.currency),
                    account=split.from_account,
                ))

        return self.transaction
1200351
public Charge create(Charge charge) throws BaseException {

		logger.debug("Enter ChargeService::create");
		
		// prepare API url
		String apiUrl = requestContext.getBaseUrl() + "charges".replaceAll("\\{format\\}", "json");
		logger.info("apiUrl - " + apiUrl);
		
		// assign TypeReference for deserialization
		TypeReference<Charge> typeReference = new TypeReference<Charge>() {
		};

		// prepare service request
		Request request = new Request.RequestBuilder(MethodType.POST, apiUrl).requestObject(charge)
				.typeReference(typeReference).context(requestContext).build();

		// make API call
		Response response = sendRequest(request);

		// retrieve response
		Charge chargeResponse = (Charge) response.getResponseObject();

		// set additional attributes
		prepareResponse(request, response, chargeResponse);
		return chargeResponse;
	}
1091960
def retry_unpaid_invoices(self):
		

		self._sync_invoices()
		for invoice in self.invoices.filter(paid=False, closed=False):
			try:
				invoice.retry()  # Always retry unpaid invoices
			except InvalidRequestError as exc:
				if str(exc) != "Invoice is already paid":
					raise
834832
protected function _prepareCollection()
    {

        /** @var Adyen_Payment_Model_Resource_Billing_Agreement_Collection $collection */
        $collection = Mage::getResourceModel('adyen/billing_agreement_collection')
            ->addCustomerDetails();
        $collection->addNameToSelect();
        $this->setCollection($collection);

        call_user_func(array(get_parent_class(get_parent_class($this)), __FUNCTION__));
        return $this;
    }
178536
def clean_entries(self, source_invoice: Invoice or None, settled_invoice: Invoice or None, account: Account, **kw):
        
        for form in self.forms:
            obj = form.instance
            assert isinstance(obj, AccountEntry)
            obj.account = account
            obj.source_invoice = source_invoice
            obj.settled_invoice = settled_invoice
            if obj.parent:
                if obj.amount is None:
                    obj.amount = obj.parent.amount
                if obj.type is None:
                    obj.type = obj.parent.type
                if obj.amount > obj.parent.amount > Decimal(0) or obj.amount < obj.parent.amount < Decimal(0):
                    raise ValidationError(_('Derived account entry amount cannot be larger than original'))
            for k, v in kw.items():
                setattr(obj, k, v)
851393
def init_cart            
      # Check if the cart ID is defined and that it exists in the database
      create_new_invoice = false
      if session[:cart_id]
        @invoice = Caboose::Invoice.where(:id => session[:cart_id]).first
        create_new_invoice = true if @invoice.nil? || @invoice.status != 'cart'                    
      else                        
        create_new_invoice = true                         
      end

      if create_new_invoice # Create an invoice to associate with the session        
        @invoice = Caboose::Invoice.new        
        @invoice.site_id          = @site ? @site.id : nil
        @invoice.status           = Caboose::Invoice::STATUS_CART
        @invoice.financial_status = Caboose::Invoice::STATUS_PENDING
        @invoice.date_created     = DateTime.now
        @invoice.referring_site   = request.env['HTTP_REFERER']
        @invoice.landing_page     = request.fullpath
        @invoice.landing_page_ref = params[:ref] || nil
        @invoice.payment_terms    = @site.store_config.default_payment_terms
        @invoice.save
        
        InvoiceLog.create(
          :invoice_id     => @invoice.id,          
          :user_id        => logged_in_user.id,
          :date_logged    => DateTime.now.utc,
          :invoice_action => InvoiceLog::ACTION_INVOICE_CREATED                
        )
        
        # Save the cart ID in the session
        session[:cart_id] = @invoice.id
      end                  
    end
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;
    }
148485
public function invoices($includePending = false, $parameters = []): Collection
    {
        $invoices = [];

        $customer = $this->asBraintreeCustomer();

        $parameters = array_merge([
            'id' => TransactionSearch::customerId()->is($customer->id),
            'range' => TransactionSearch::createdAt()->between(
                Carbon::today()->subYears(2)->format('m/d/Y H:i'),
                Carbon::tomorrow()->format('m/d/Y H:i')
            ),
        ], $parameters);

        $transactions = BraintreeTransaction::search($parameters);

        // Here we will loop through the Braintree invoices and create our own custom Invoice
        // instance that gets more helper methods and is generally more convenient to work
        // work than the plain Braintree objects are. Then, we'll return the full array.
        if (! is_null($transactions)) {
            foreach ($transactions as $transaction) {
                if ($transaction->status == BraintreeTransaction::SETTLED || $includePending) {
                    $invoices[] = new Invoice($this, $transaction);
                }
            }
        }

        return new Collection($invoices);
    }
885375
def create_invoice_from_ticket(pk, list_lines):
        
        context = {}
        if list_lines:
            new_list_lines = [x[0] for x in SalesLineTicket.objects.values_list('line_order__pk').filter(pk__in=[int(x) for x in list_lines])]
            if new_list_lines:
                lo = SalesLineOrder.objects.values_list('order__pk').filter(pk__in=new_list_lines)[:1]
                if lo and lo[0] and lo[0][0]:
                    new_pk = lo[0][0]
                    return GenLineProduct.create_invoice_from_order(new_pk, new_list_lines)
                else:
                    error = _('Pedido no encontrado')
            else:
                error = _('Lineas no relacionadas con pedido')
        else:
            error = _('Lineas no seleccionadas')
        context['error'] = error
        return context
1207524
public static function createInheritedAccount()
    {
        if (!Podium::getInstance()->user->isGuest) {
            $transaction = static::getDb()->beginTransaction();
            try {
                $newUser = new static;
                $newUser->setScenario('installation');
                $newUser->inherited_id = Podium::getInstance()->user->id;
                $newUser->status = self::STATUS_ACTIVE;
                $newUser->role = self::ROLE_MEMBER;
                $newUser->generateUsername();
                if (!$newUser->save()) {
                    throw new Exception('Account creating error');
                }
                if (!Podium::getInstance()->rbac->assign(Podium::getInstance()->rbac->getRole(Rbac::ROLE_USER), $newUser->id)) {
                    throw new Exception('User role assigning error');
                }
                PodiumCache::clearAfter('activate');
                Log::info('Inherited account created', $newUser->id, __METHOD__);
                $transaction->commit();
                return true;
            } catch (Exception $e) {
                $transaction->rollBack();
                Log::error($e->getMessage(), null, __METHOD__);
            }
        }
        return false;
    }
1214573
def transfer_funds
      raise "payment must be paid" if !payment.paid?

      bank_account = PagarMe::BankAccount.new(bank_account_attributes.delete(:bank_account))
      bank_account.create
      raise "unable to create an bank account" unless bank_account.id.present?

      transfer = PagarMe::Transfer.new({
        bank_account_id: bank_account.id,
        amount: value_for_transaction
      })
      transfer.create
      raise "unable to create a transfer" unless transfer.id.present?

      #avoid sending notification
      payment.update_attributes(state: 'pending_refund')
      payment.payment_transfers.create!({
        user: payment.user,
        transfer_id: transfer.id,
        transfer_data: transfer.to_json
      })
    end
575469
def cancel_invoice(self, invoice_id):
        
        return self._create_put_request(
            resource=INVOICES,
            billomat_id=invoice_id,
            command=CANCEL,
        )
924310
def create(self,params=None, headers=None):
        
        path = '/creditor_bank_accounts'
        
        if params is not None:
            params = {self._envelope_key(): params}

        try:
          response = self._perform_request('POST', path, params, headers,
                                            retry_failures=True)
        except errors.IdempotentCreationConflictError as err:
          return self.get(identity=err.conflicting_resource_id,
                          params=params,
                          headers=headers)
        return self._resource_for(response)
894285
def complete_invoice(self, invoice_id, complete_dict):
        
        return self._create_put_request(
            resource=INVOICES,
            billomat_id=invoice_id,
            command=COMPLETE,
            send_data=complete_dict
        )
1367161
def set_invoices(invoices_attributes)
      @invoices = invoices_attributes.map.with_index do |invoice_attributes, index|
        existing_invoice = invoices[index]

        if existing_invoice
          existing_invoice.assign_all_attributes(invoice_attributes)
        else
          Invoice.new_from_json(invoice_attributes)
        end
      end
    end
390941
def due(self):
        
        invoice_charges = Charge.objects.filter(invoice=self)
        invoice_transactions = Transaction.successful.filter(invoice=self)
        return total_amount(invoice_charges) - total_amount(invoice_transactions)