Get the amount due on the given billing cycle

        For regular recurring costs this is simply `fixed_amount`. For
        one-off costs this is the portion of `fixed_amount` for the given
        billing_cycle.
323669
def get_amount_normal(self, billing_cycle):
        
        if self.is_one_off():
            billing_cycle_number = self._get_billing_cycle_number(billing_cycle)

            if billing_cycle_number > self.total_billing_cycles:
                # A future billing cycle after this one has ended
                return Decimal('0')
            else:
                # This is a current cycle. Split the amount into
                # equal parts then return the part for this cycle
                splits = ratio_split(
                    amount=self.fixed_amount,
                    ratios=[Decimal('1')] * self.total_billing_cycles,
                )
                return splits[billing_cycle_number - 1]
        else:
            # This is a none-one-off recurring cost, so the logic is simple
            return self.fixed_amount
1004377
def charges_net_effect(self):
        
        return Decimal(sum([charge.charge_value for charge in self.charges.values()
                            if charge.net_affecting]))
866259
def _is_billing_complete(self):
        
        if self.is_one_off():
            return self.get_billed_amount() >= Balance(self.fixed_amount, self.currency)
        else:
            return False
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);
        }
    }
903740
def TotalFees(self):
        
        amount = Fixed8.Zero()
        for tx in self.Transactions:
            amount += tx.SystemFee()
        return amount
751972
def get_due(self, estimated):
        """"""
        due = 0
        due = round((estimated - datetime.utcnow()).seconds / 60)
        return due
1050169
def balance(self) -> Decimal:
        
        return sum_queryset(AccountEntry.objects.filter(account=self.account, timestamp__lte=self.timestamp).exclude(timestamp=self.timestamp, id__gt=self.id))
514082
def calculate_current_allocation(self):
        
        for ac in self.asset_classes:
            ac.curr_alloc = ac.curr_value * 100 / self.total_amount
607515
public InvoiceData getInvoice(Calendar calendar, String pricingAccountAlias) {
        return getInvoice(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, pricingAccountAlias);
    }
628328
public static Quarters parsePeriod(String period) throws ParseException {

        int amount = SingleUnitTimeSpan.parsePeriod(period, 'Q');
        return Quarters.of(amount);

    }
1364716
private Billing generateDefaultBillingWithReservation() {
        Billing billing = new Billing();
        billing.withReservation(new Reservation().withReservationLength(1));
        return billing;
    }
315448
def get_all_payments_of_incoming(self, incoming_id):
        
        return self._iterate_through_pages(
            get_function=self.get_payments_of_incoming_per_page,
            resource=INCOMING_PAYMENTS,
            **{'incoming_id': incoming_id}
        )
454067
private static int getDayOfCycle(long epochDay, int cycleNumber) {
        Long day;

        try {
            day = ADJUSTED_CYCLES[cycleNumber];
        } catch (ArrayIndexOutOfBoundsException e) {
            day = null;
        }
        if (day == null) {
            day = Long.valueOf(cycleNumber * 10631);
        }
        return (int) (epochDay - day.longValue());
    }
737200
def compute_payments(self, precision=None):
        '''
        
        '''
        return quantize(sum([payment.amount for payment in self.__payments]),
                        precision)
1018279
public function initBillingAgreementPaymentInfo(
        Adyen_Payment_Model_Billing_Agreement $billingAgreement,
        Mage_Sales_Model_Quote_Payment $paymentInfo
    ) {
        try {
            $recurringDetailReference = $billingAgreement->getReferenceId();
            $paymentInfo->setMethod('adyen_oneclick_' . $recurringDetailReference);
            $paymentInfo->setAdditionalInformation('recurring_detail_reference', $recurringDetailReference);

            // set the ccType needed for Sepa, Sofort and Ideal
            $agreementData = $billingAgreement->getAgreementData();
            if (isset($agreementData['variant'])) {
                $paymentInfo->setCcType($agreementData['variant']);
            }
        } catch (Exception $e) {
            Adyen_Payment_Exception::logException($e);
        }

        return $this;
    }
1074550
def get_next_occurrence(tx: ScheduledTransaction) -> date:
    
    # Reference documentation:
    # https://github.com/MisterY/gnucash-portfolio/issues/3

    # Preparing ref day is an important part before the calculation.
    # It should be:
    #   a) the last occurrence date + 1, or
    #   b) the recurrence start date - 1.
    # because the refDate is the date from which the due dates are being calculated. To include
    # the ones starting today, we need to calculate from the day before.
    ref_datum: Datum = Datum()
    if tx.last_occur:
        #ref_datum.set_value(tx.last_occur)
        ref_datum.from_date(tx.last_occur)
        ref_datum.add_days(1)
    else:
        ref_datum.from_date(tx.recurrence.recurrence_period_start)
        ref_datum.subtract_days(1)
    ref_date: datetime = ref_datum.value

    # today = datetimeutils.today_date()
    #today = Datum().today()
    # skipped schedule
    #if ref_date > today: 
    #    ref_date = today

    ###########################################################
    # The code below mimics the function
    # recurrenceNextInstance(const Recurrence *r, const GDate *refDate, GDate *nextDate)
    # https://github.com/Gnucash/gnucash/blob/115c0bf4a4afcae4269fe4b9d1e4a73ec7762ec6/libgnucash/engine/Recurrence.c#L172

    start_date: Datum = Datum()
    #start_date: datetime = tx.recurrence.recurrence_period_start
    start_date.from_date(tx.recurrence.recurrence_period_start)
    if ref_date < start_date.value:
        # If the occurrence hasn't even started, the next date is the start date.
        # this should also handle the "once" type in most cases.
        return start_date.value.date()

    # start at refDate.
    next_date: Datum = Datum()
    # next_date: datetime = ref_date
    next_date.from_datetime(ref_date)

    # last_date: datetime = tx.last_occur
    # print(tx.name, base_date, tx.recurrence.recurrence_period_start,
    #       tx.recurrence.recurrence_mult, tx.recurrence.recurrence_period_type)

    # /* Step 1: move FORWARD one period, passing exactly one occurrence. */

    mult: int = tx.recurrence.recurrence_mult
    period: str = tx.recurrence.recurrence_period_type
    wadj = tx.recurrence.recurrence_weekend_adjust

    # Not all periods from the original file are included at the moment.
    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        if period == RecurrencePeriod.YEAR.value:
            mult *= 12

        # handle weekend adjustment here.
        ## Takes care of short months.
        # next_weekday = datetimeutils.get_day_name(next_date)
        next_weekday = next_date.get_day_name()
        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and
                (next_weekday == "Saturday" or next_weekday == "Sunday")):
            # "Allows the following Friday-based calculations to proceed if 'next'
            #  is between Friday and the target day."
            days_to_subtract = 1 if next_weekday == "Saturday" else 2

            # next_date = datetimeutils.subtract_days(next_date, days_to_subtract)
            next_date.subtract_days(days_to_subtract)

        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and next_weekday == "Friday"):
            next_date = handle_friday(next_date, period, mult, start_date)

        # Line 274.
        temp_date = next_date.clone()
        if (temp_date.is_end_of_month() or
                (period in [RecurrencePeriod.MONTH.value, RecurrencePeriod.YEAR.value]
                 and (next_date.get_day() >= start_date.get_day()))
           ):
            # next_date = datetimeutils.add_months(next_date, mult)
            next_date.add_months(mult)
            # Set at end of month again (?!)
            #next_date = datetimeutils.get_end_of_month(next_date)
        else:
            # one fewer month fwd because of the occurrence in this month.
            next_date.add_months(mult - 1)

    # elif period == "once":
    #     next_date = tx.recurrence.recurrence_period_start

    elif period == RecurrencePeriod.DAY.value:
        logging.warning("daily not handled")

    else:
        logging.info(f"recurrence not handled: {period}")

    #######################
    # Step 2
    # "Back up to align to the base phase. To ensure forward
    # progress, we never subtract as much as we added (x % mult < mult)"

    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        n_months = (
            12 * (next_date.get_year() - start_date.get_year()) +
            (next_date.get_month() - start_date.get_month())
        )
        next_date.subtract_months(n_months % mult)

        # dim
        days_in_month = datetimeutils.get_days_in_month(
            next_date.get_year(), next_date.get_month())

        # Handle adjustment for 3 ways.
        if (period == RecurrencePeriod.END_OF_MONTH.value or
                next_date.get_day() >= days_in_month):
            # Set to last day of the month.
            next_date.set_day(days_in_month)
        else:
            # Same day as the start.
            next_date.set_day(start_date.get_day())

        # Adjust for dates on the weekend.
        if (period == RecurrencePeriod.YEAR.value or period == RecurrencePeriod.MONTH.value or
                period == RecurrencePeriod.END_OF_MONTH.value):
            weekday = next_date.get_day_name()
            if weekday == "Saturday" or weekday == "Sunday":
                if wadj == WeekendAdjustment.BACK.value:
                    next_date.subtract_days(1 if weekday == "Saturday" else 2)
                elif wadj == WeekendAdjustment.FORWARD.value:
                    next_date.add_days(2 if weekday == "Saturday" else 1)

    return next_date.value.date()
242844
def total_charges(self):
        
        selected_charges = Charge.objects \
            .filter(invoice=self) \
            .charges() \
            .exclude(product_code=CARRIED_FORWARD)
        return total_amount(selected_charges)