Snowflake for the CREDIT_ADJ on its own invoice
353104
private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit(final Currency currency, final Iterable<InvoiceItem> invoiceItems) {
        BigDecimal amountAdjusted = BigDecimal.ZERO;
        if (invoiceItems == null || !invoiceItems.iterator().hasNext()) {
            return KillBillMoney.of(amountAdjusted, currency);
        }

        for (final InvoiceItem invoiceItem : invoiceItems) {
            final Iterable<InvoiceItem> otherInvoiceItems = Iterables.filter(invoiceItems, new Predicate<InvoiceItem>() {
                @Override
                public boolean apply(final InvoiceItem input) {
                    return !input.getId().equals(invoiceItem.getId());
                }
            });

            if (InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType()) &&
                (Iterables.size(otherInvoiceItems) == 1 &&
                 InvoiceItemType.CBA_ADJ.equals(otherInvoiceItems.iterator().next().getInvoiceItemType()) &&
                 otherInvoiceItems.iterator().next().getInvoiceId().equals(invoiceItem.getInvoiceId()) &&
                 otherInvoiceItems.iterator().next().getAmount().compareTo(invoiceItem.getAmount().negate()) == 0)) {
                amountAdjusted = amountAdjusted.add(invoiceItem.getAmount());
            }
        }

        return KillBillMoney.of(amountAdjusted, currency);
    }
173822
def create_proforma_invoice(sender, instance, created, **kwargs):
    
    if created:
        Invoice.create(instance, Invoice.INVOICE_TYPES['PROFORMA'])
1343410
def get_without_invoice(self):
        
        qs = Transaction.objects.filter(
            children__isnull=True, invoice__isnull=True)
        return qs
1121673
def invoice_items(self, **params):
        """"""
        params['customer'] = self.id
        return InvoiceItem.all(self.api_key, **params)
1233113
def to_array(self):
        
        array = super(Invoice, self).to_array()
        array['title'] = u(self.title)  # py2: type unicode, py3: type str
        array['description'] = u(self.description)  # py2: type unicode, py3: type str
        array['start_parameter'] = u(self.start_parameter)  # py2: type unicode, py3: type str
        array['currency'] = u(self.currency)  # py2: type unicode, py3: type str
        array['total_amount'] = int(self.total_amount)  # type int
        return array
1091192
def to_request
        credit = {
          delayed:              self.delayed,
          authenticated:        self.authenticated,
          pre_authorization:    self.pre_authorization,
          save_card_data:       self.save_card_data,
          transaction_type:     self.transaction_type,
          number_installments:  self.number_installments.to_i,
          soft_descriptor:      self.soft_descriptor,
          dynamic_mcc:          self.dynamic_mcc,
          card:                 self.card.to_request,
        }

      return credit
    end
610614
def initialize_properties_with_values_from_owner(invoice)
      if owner.is_a?(Debtor)
        invoice.debtor = owner

        invoice.debtor_name         ||= owner.name
        invoice.debtor_address      ||= owner.address
        invoice.debtor_postal_code  ||= owner.postal_code
        invoice.debtor_city         ||= owner.city

        invoice.term_of_payment_handle  ||= owner.term_of_payment_handle
        invoice.layout_handle           ||= owner.layout_handle
        invoice.currency_handle         ||= owner.currency_handle
      end
    end
1264787
function parseAccountOrder(address: string, order: Object): Object {
  const direction = (order.flags & flags.Sell) === 0 ? 'buy' : 'sell'
  const takerGetsAmount = parseAmount(order.taker_gets)
  const takerPaysAmount = parseAmount(order.taker_pays)
  const quantity = (direction === 'buy') ? takerPaysAmount : takerGetsAmount
  const totalPrice = (direction === 'buy') ? takerGetsAmount : takerPaysAmount

  // note: immediateOrCancel and fillOrKill orders cannot enter the order book
  // so we can omit those flags here
  const specification = utils.removeUndefined({
    direction: direction,
    quantity: quantity,
    totalPrice: totalPrice,
    passive: ((order.flags & flags.Passive) !== 0) || undefined,
    // rippled currently does not provide "expiration" in account_offers
    expirationTime: utils.parseTimestamp(order.expiration)
  })

  const makerExchangeRate = order.quality ?
      utils.adjustQualityForZXC(order.quality.toString(),
        takerGetsAmount.currency, takerPaysAmount.currency) :
      computeQuality(takerGetsAmount, takerPaysAmount)
  const properties = {
    maker: address,
    sequence: order.seq,
    makerExchangeRate: makerExchangeRate
  }

  return {specification, properties}
}
181037
private int appendAffix(StringBuffer buf, boolean isNegative, boolean isPrefix,
                            FieldPosition fieldPosition,
                            boolean parseAttr) {
        if (currencyChoice != null) {
            String affixPat = null;
            if (isPrefix) {
                affixPat = isNegative ? negPrefixPattern : posPrefixPattern;
            } else {
                affixPat = isNegative ? negSuffixPattern : posSuffixPattern;
            }
            StringBuffer affixBuf = new StringBuffer();
            expandAffix(affixPat, null, affixBuf);
            buf.append(affixBuf);
            return affixBuf.length();
        }

        String affix = null;
        String pattern;
        if (isPrefix) {
            affix = isNegative ? negativePrefix : positivePrefix;
            pattern = isNegative ? negPrefixPattern : posPrefixPattern;
        } else {
            affix = isNegative ? negativeSuffix : positiveSuffix;
            pattern = isNegative ? negSuffixPattern : posSuffixPattern;
        }
        // [Spark/CDL] Invoke formatAffix2Attribute to add attributes for affix
        if (parseAttr) {
            // Updates for Ticket 11805.
            int offset = affix.indexOf(symbols.getCurrencySymbol());
            if (offset > -1) {
                formatAffix2Attribute(isPrefix, Field.CURRENCY, buf, offset,
                        symbols.getCurrencySymbol().length());
            }
            offset = affix.indexOf(symbols.getMinusSignString());
            if (offset > -1) {
                formatAffix2Attribute(isPrefix, Field.SIGN, buf, offset,
                        symbols.getMinusSignString().length());
            }
            offset = affix.indexOf(symbols.getPercentString());
            if (offset > -1) {
                formatAffix2Attribute(isPrefix, Field.PERCENT, buf, offset,
                        symbols.getPercentString().length());
            }
            offset = affix.indexOf(symbols.getPerMillString());
            if (offset > -1) {
                formatAffix2Attribute(isPrefix, Field.PERMILLE, buf, offset,
                        symbols.getPerMillString().length());
            }
            offset = pattern.indexOf("¤¤¤");
            if (offset > -1) {
                formatAffix2Attribute(isPrefix, Field.CURRENCY, buf, offset,
                        affix.length() - offset);
            }
        }

        // Look for SIGN, PERCENT, PERMILLE in the formatted affix.
        if (fieldPosition.getFieldAttribute() == NumberFormat.Field.SIGN) {
            String sign = isNegative ? symbols.getMinusSignString() : symbols.getPlusSignString();
            int firstPos = affix.indexOf(sign);
            if (firstPos > -1) {
                int startPos = buf.length() + firstPos;
                fieldPosition.setBeginIndex(startPos);
                fieldPosition.setEndIndex(startPos + sign.length());
            }
        } else if (fieldPosition.getFieldAttribute() == NumberFormat.Field.PERCENT) {
            int firstPos = affix.indexOf(symbols.getPercentString());
            if (firstPos > -1) {
                int startPos = buf.length() + firstPos;
                fieldPosition.setBeginIndex(startPos);
                fieldPosition.setEndIndex(startPos + symbols.getPercentString().length());
            }
        } else if (fieldPosition.getFieldAttribute() == NumberFormat.Field.PERMILLE) {
            int firstPos = affix.indexOf(symbols.getPerMillString());
            if (firstPos > -1) {
                int startPos = buf.length() + firstPos;
                fieldPosition.setBeginIndex(startPos);
                fieldPosition.setEndIndex(startPos + symbols.getPerMillString().length());
            }
        } else
        // If CurrencySymbol or InternationalCurrencySymbol is in the affix, check for currency symbol.
        // Get spelled out name if "¤¤¤" is in the pattern.
        if (fieldPosition.getFieldAttribute() == NumberFormat.Field.CURRENCY) {
            if (affix.indexOf(symbols.getCurrencySymbol()) > -1) {
                String aff = symbols.getCurrencySymbol();
                int firstPos = affix.indexOf(aff);
                int start = buf.length() + firstPos;
                int end = start + aff.length();
                fieldPosition.setBeginIndex(start);
                fieldPosition.setEndIndex(end);
            } else if (affix.indexOf(symbols.getInternationalCurrencySymbol()) > -1) {
                String aff = symbols.getInternationalCurrencySymbol();
                int firstPos = affix.indexOf(aff);
                int start = buf.length() + firstPos;
                int end = start + aff.length();
                fieldPosition.setBeginIndex(start);
                fieldPosition.setEndIndex(end);
            } else if (pattern.indexOf("¤¤¤") > -1) {
                // It's a plural, and we know where it is in the pattern.
                int firstPos = pattern.indexOf("¤¤¤");
                int start = buf.length() + firstPos;
                int end = buf.length() + affix.length(); // This seems clunky and wrong.
                fieldPosition.setBeginIndex(start);
                fieldPosition.setEndIndex(end);
            }
        }

        buf.append(affix);
        return affix.length();
    }
1069350
function prefix(event, properties) {
  var prefixed = {};
  each(properties, function(key, val) {
    if (key === 'Billing Amount') {
      prefixed[key] = val;
    } else {
      prefixed[event + ' - ' + key] = val;
    }
  });
  return prefixed;
}
1244866
private List<InvoiceItem> processRecurringEvent(final UUID invoiceId, final UUID accountId, final BillingEvent thisEvent, @Nullable final BillingEvent nextEvent,
                                                    final LocalDate targetDate, final Currency currency,
                                                    final InvoiceItemGeneratorLogger invoiceItemGeneratorLogger, final BillingMode billingMode,
                                                    final Map<UUID, SubscriptionFutureNotificationDates> perSubscriptionFutureNotificationDate,
                                                    final InternalCallContext internalCallContext) throws InvoiceApiException {

        try {
            final List<InvoiceItem> items = new ArrayList<InvoiceItem>();

            // For FIXEDTERM phases we need to stop when the specified duration has been reached
            final LocalDate maxEndDate = thisEvent.getPlanPhase().getPhaseType() == PhaseType.FIXEDTERM ?
                                         thisEvent.getPlanPhase().getDuration().addToLocalDate(internalCallContext.toLocalDate(thisEvent.getEffectiveDate())) :
                                         null;

            // Handle recurring items
            final BillingPeriod billingPeriod = thisEvent.getBillingPeriod();
            if (billingPeriod != BillingPeriod.NO_BILLING_PERIOD) {
                final LocalDate startDate = internalCallContext.toLocalDate(thisEvent.getEffectiveDate());

                if (!startDate.isAfter(targetDate)) {
                    final LocalDate endDate = (nextEvent == null) ? null : internalCallContext.toLocalDate(nextEvent.getEffectiveDate());

                    final int billCycleDayLocal = thisEvent.getBillCycleDayLocal();

                    final RecurringInvoiceItemDataWithNextBillingCycleDate itemDataWithNextBillingCycleDate;
                    try {
                        itemDataWithNextBillingCycleDate = generateInvoiceItemData(startDate, endDate, targetDate, billCycleDayLocal, billingPeriod, billingMode);
                    } catch (final InvalidDateSequenceException e) {
                        throw new InvoiceApiException(ErrorCode.INVOICE_INVALID_DATE_SEQUENCE, startDate, endDate, targetDate);
                    }
                    for (final RecurringInvoiceItemData itemDatum : itemDataWithNextBillingCycleDate.getItemData()) {

                        // Stop if there a maxEndDate and we have reached it
                        if (maxEndDate != null && maxEndDate.compareTo(itemDatum.getEndDate()) < 0) {
                            break;
                        }

                        final BigDecimal rate = thisEvent.getRecurringPrice(internalCallContext.toUTCDateTime(itemDatum.getStartDate()));
                        if (rate != null) {
                            final BigDecimal amount = KillBillMoney.of(itemDatum.getNumberOfCycles().multiply(rate), currency);
                            final RecurringInvoiceItem recurringItem = new RecurringInvoiceItem(invoiceId,
                                                                                                accountId,
                                                                                                thisEvent.getBundleId(),
                                                                                                thisEvent.getSubscriptionId(),
                                                                                                thisEvent.getPlan().getProduct().getName(),
                                                                                                thisEvent.getPlan().getName(),
                                                                                                thisEvent.getPlanPhase().getName(),
                                                                                                itemDatum.getStartDate(),
                                                                                                itemDatum.getEndDate(),
                                                                                                amount, rate, currency);
                            items.add(recurringItem);
                        }
                    }
                    updatePerSubscriptionNextNotificationDate(thisEvent.getSubscriptionId(), itemDataWithNextBillingCycleDate.getNextBillingCycleDate(), items, billingMode,
                                                              perSubscriptionFutureNotificationDate);
                }
            }

            // For debugging purposes
            invoiceItemGeneratorLogger.append(thisEvent, items);

            return items;
        } catch (final CatalogApiException e) {
            throw new InvoiceApiException(e);
        }
    }
1238571
function DoDirectPayment($cc, $cvv2 = '', $exp, $fname = null, $lname = null, $cc_type, $options = array(), $nvp = array() ) {
    $values = $options;
    $values['ACCT'] = $cc;
    if ($cvv2 != '') $values['CVV2'] = $cvv2;
    $values['FIRSTNAME'] = $fname;
    $values['LASTNAME'] = $lname;
    if (isset($values['NAME'])) unset ($values['NAME']);

    if ($this->_mode == 'payflow') {
      $values['EXPDATE'] = $exp;
      $values['TENDER'] = 'C';
      $values['TRXTYPE'] = $this->_trxtype;
      $values['VERBOSITY'] = 'MEDIUM';
      $values['NOTIFYURL'] = zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true);
    } elseif ($this->_mode == 'nvp') {
      $values = array_merge($values, $nvp);
      if (isset($values['ECI'])) {
        $values['ECI3DS'] = $values['ECI'];
        unset($values['ECI']);
      }
      $values['CREDITCARDTYPE'] = ($cc_type == 'American Express') ? 'Amex' : $cc_type;
      $values['NOTIFYURL'] = urlencode(zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true));
      if (!isset($values['PAYMENTACTION'])) $values['PAYMENTACTION'] = ($this->_trxtype == 'S' ? 'Sale' : 'Authorization');

      if (isset($values['COUNTRY'])) unset ($values['COUNTRY']);
      if (isset($values['COMMENT1'])) unset ($values['COMMENT1']);
      if (isset($values['COMMENT2'])) unset ($values['COMMENT2']);
      if (isset($values['CUSTREF'])) unset ($values['CUSTREF']);
    }
    $this->values = $values;
    $this->notify('NOTIFY_PAYPAL_DODIRECTPAYMENT');
    ksort($this->values);
    return $this->_request($this->values, 'DoDirectPayment');
  }
752676
def create_invoice_from_albaran(pk, list_lines):
        
        context = {}
        if list_lines:
            new_list_lines = [x[0] for x in SalesLineAlbaran.objects.values_list('line_order__pk').filter(
                pk__in=[int(x) for x in list_lines]
            ).exclude(invoiced=True)]
            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]
                    context = GenLineProduct.create_invoice_from_order(new_pk, new_list_lines)
                    if 'error' not in context or not context['error']:
                        SalesLineAlbaran.objects.filter(
                            pk__in=[int(x) for x in list_lines]
                        ).exclude(invoiced=True).update(invoiced=True)
                    return context
                else:
                    error = _('Pedido no encontrado')
            else:
                error = _('Lineas no relacionadas con pedido')
        else:
            error = _('Lineas no seleccionadas')
        context['error'] = error
        return context
829641
def transaction_insert_dict_auto_inc(self, transaction_cursor, tblname, d, unique_id_fields = [], fields = None, check_existing = False, id_field = 'ID'):
        ''''''
        sql, params, record_exists = self.create_insert_dict_string(tblname, d, PKfields=unique_id_fields, fields=fields, check_existing = check_existing)
        if not record_exists:
            transaction_cursor.execute(sql, params)
        id = transaction_cursor.lastrowid
        if id == None:
            id = self.get_unique_record('SELECT * FROM {0} WHERE {1}'.format(tblname, ' AND '.join([f + '=%s' for f in unique_id_fields])), parameters = tuple([d[f] for f in unique_id_fields]))[id_field]
        assert(id)
        return id
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)
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
365841
function composeMinimalJoint(params){
	var estimated_amount = (params.send_all || params.retrieveMessages) ? 0 : params.outputs.reduce(function(acc, output){ return acc+output.amount; }, 0) + TYPICAL_FEE;
	readSortedFundedAddresses(null, params.available_paying_addresses, estimated_amount, params.spend_unconfirmed || 'own', function(arrFundedPayingAddresses){
		if (arrFundedPayingAddresses.length === 0)
			return params.callbacks.ifNotEnoughFunds("all paying addresses are unfunded");
		var minimal_params = _.clone(params);
		delete minimal_params.available_paying_addresses;
		minimal_params.minimal = true;
		minimal_params.paying_addresses = arrFundedPayingAddresses;
		composeJoint(minimal_params);
	});
}