Populate the table with billing cycles starting from `as_of`

        Args:
            as_of (date): The date at which to begin the populating
            delete (bool): Should future billing cycles be deleted?
185171
def _populate(cls, as_of=None, delete=False):
        
        billing_cycle_helper = get_billing_cycle()
        billing_cycles_exist = BillingCycle.objects.exists()

        try:
            current_billing_cycle = BillingCycle.objects.as_of(date=as_of)
        except BillingCycle.DoesNotExist:
            current_billing_cycle = None

        # If no cycles exist then disable the deletion logic
        if not billing_cycles_exist:
            delete = False

        # Cycles exist, but a date has been specified outside of them
        if billing_cycles_exist and not current_billing_cycle:
            raise CannotPopulateForDateOutsideExistingCycles()

        # Omit the current billing cycle if we are deleting (as
        # deleting the current billing cycle will be a Bad Idea)
        omit_current = (current_billing_cycle and delete)

        stop_date = as_of + relativedelta(years=settings.SWIFTWIND_BILLING_CYCLE_YEARS)
        date_ranges = billing_cycle_helper.generate_date_ranges(as_of, stop_date=stop_date, omit_current=omit_current)
        date_ranges = list(date_ranges)

        beginning_date = date_ranges[0][0]

        with db_transaction.atomic():

            if delete:
                # Delete all the future unused transactions
                cls.objects.filter(start_date__gte=beginning_date).delete()

            for start_date, end_date in date_ranges:
                exists = BillingCycle.objects.filter(date_range=(start_date, end_date)).exists()
                if exists:
                    if delete:
                        raise Exception(
                            'It should not be possible to get here as future billing cycles have just been deleted'
                        )
                    else:
                        # We're updating, so we can just ignore cycles that already exist
                        pass
                else:
                    BillingCycle.objects.create(
                        date_range=(start_date, end_date),
                    )
596804
def index(self, date):
        
        for (i, (start, end, ruler)) in enumerate(self.table):
            if start <= date.jd <= end:
                return i
        return None
545741
private void populateCalendar(Record record, ProjectCalendar calendar, boolean isBaseCalendar)
   {
      if (isBaseCalendar == true)
      {
         calendar.setName(record.getString(0));
      }
      else
      {
         calendar.setParent(m_projectFile.getCalendarByName(record.getString(0)));
      }

      calendar.setWorkingDay(Day.SUNDAY, DayType.getInstance(record.getInteger(1)));
      calendar.setWorkingDay(Day.MONDAY, DayType.getInstance(record.getInteger(2)));
      calendar.setWorkingDay(Day.TUESDAY, DayType.getInstance(record.getInteger(3)));
      calendar.setWorkingDay(Day.WEDNESDAY, DayType.getInstance(record.getInteger(4)));
      calendar.setWorkingDay(Day.THURSDAY, DayType.getInstance(record.getInteger(5)));
      calendar.setWorkingDay(Day.FRIDAY, DayType.getInstance(record.getInteger(6)));
      calendar.setWorkingDay(Day.SATURDAY, DayType.getInstance(record.getInteger(7)));

      m_eventManager.fireCalendarReadEvent(calendar);
   }
1174776
def listing(self):
        

        now = Environment.get_instance().calendar_dt
        return self.listed_date <= now <= self.de_listed_date
4323
def get_amount_arrears_transactions(self, billing_cycle):
        """"""
        previous_billing_cycle = billing_cycle.get_previous()
        if not previous_billing_cycle:
            return Decimal(0)
        return self.to_account.balance(
            transaction__date__lt=previous_billing_cycle.date_range.upper,
            transaction__date__gte=previous_billing_cycle.date_range.lower,
        )
874447
def _get_date_range_query(self, start_date, end_date, timespan= 'DAY', date_field= None):
        '''
        
        '''
        if date_field is None:
            date_field = self._date_field
        query ={'q':'*:*',
                'rows':0,
                'facet':'true',
                'facet.range': date_field,
                'facet.range.gap': '+1{}'.format(timespan),
                'facet.range.end': '{}'.format(end_date),
                'facet.range.start': '{}'.format(start_date),
                'facet.range.include': 'all'
                }
        if self._per_shard:
            query['distrib'] = 'false'
        return query
1249300
def upcoming_invoice(self, **kwargs):
		
		from .billing import Invoice

		kwargs["customer"] = self
		return Invoice.upcoming(**kwargs)
1141083
def truncate_date_to_first_of_month(
        dt: Optional[DateLikeType]) -> Optional[DateLikeType]:
    
    if dt is None:
        return None
    return dt.replace(day=1)
1284624
private void populateCalendarException(Record record, ProjectCalendar calendar) throws MPXJException
   {
      Date fromDate = record.getDate(0);
      Date toDate = record.getDate(1);
      boolean working = record.getNumericBoolean(2);

      // I have found an example MPX file where a single day exception is expressed with just the start date set.
      // If we find this for we assume that the end date is the same as the start date.
      if (fromDate != null && toDate == null)
      {
         toDate = fromDate;
      }

      ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);
      if (working)
      {
         addExceptionRange(exception, record.getTime(3), record.getTime(4));
         addExceptionRange(exception, record.getTime(5), record.getTime(6));
         addExceptionRange(exception, record.getTime(7), record.getTime(8));
      }
   }
122962
def _init_date_range(self, start_date=None, end_date=None):
        """"""
        self.end_date = end_date
        self.start_date = start_date
        if self.end_date is None:
            today = now_utc().date()
            end_date = self.event.end_dt.date()
            self.end_date = end_date if end_date < today else today
        if self.start_date is None:
            self.start_date = self.end_date - timedelta(days=ReportBase.default_report_interval)
887087
def populate_from_staging(self, staging_table, from_column_list, output_table):
        
        self.sql_text += 'INSERT INTO ' + output_table + ' (\n'
        for c in self.col_list:
            if c != '':
                self.sql_text += '    ' + c + ',\n'
        self.sql_text += '    ' + self.date_updated_col + ') (\n'
        self.sql_text += '    SELECT \n'
        for c in from_column_list:
            if c != '':
                self.sql_text += '        ' + c + ',\n'
        self.sql_text += '        SYSDATE \n    FROM ' + staging_table
        self.sql_text += '\n);\n'
1148769
def delta(self, fromdate, todate):
        '''
        
        '''
#CONSIDER: raise an exception if a date is not in self
        return self.index(todate) - self.index(fromdate)
1304177
def delete(self, table):
        
        self._table = table
        self._limit = None
        self._query = "DELETE FROM {0}".format(self._table)

        return self
1179788
def _occursOn(self, myDate):
        
        # TODO analyse which is faster (rrule or db) and test that first
        if myDate not in self.repeat:
            return False
        if CancellationPage.events.child_of(self)                            \
                           .filter(except_date=myDate).exists():
            return False
        return True
890541
def create_invoices
      
      self.calculate_date_started_full if self.date_started_full.nil?
      
      v  = self.variant
      interval = case v.subscription_interval
        when Variant::SUBSCRIPTION_INTERVAL_MONTHLY then 1.month
        when Variant::SUBSCRIPTION_INTERVAL_YEARLY  then 1.year
      end      
      sc = v.product.site.store_config      
      unit_price = v.clearance && v.clearance_price ? v.clearance_price : (v.on_sale? ? v.sale_price : v.price)
      
      # Special case if the subscription starts on specific day
      if v.subscription_start_on_day && (Date.today > self.date_started_full)
        li = self.line_items.where("date_starts = ? date_ends = ?", self.date_started, self.date_started_full - 1.day).first
        if li.nil?
          prorated_unit_price = unit_price + 0.00          
          if v.subscription_prorate             
            prorated_unit_price = case v.subscription_prorate_method
              when Variant::SUBSCRIPTION_PRORATE_METHOD_FLAT       then v.subscription_prorate_flat_amount
              when Variant::SUBSCRIPTION_PRORATE_METHOD_PERCENTAGE then unit_price * ((self.date_started_full - self.date_started).to_f / ((self.date_started_full + interval) - self.date_started_full).to_f)
              when Variant::SUBSCRIPTION_PRORATE_METHOD_CUSTOM     then self.custom_prorate                                            
            end
          end
          invoice = Caboose::Invoice.create(        
            :site_id          => v.product.site_id,
            :status           => Caboose::Invoice::STATUS_PENDING,
            :financial_status => Caboose::Invoice::STATUS_PENDING,
            :date_created     => DateTime.now,                                    
            :payment_terms    => sc.default_payment_terms,
            :invoice_number   => sc.next_invoice_number
          )          
          LineItem.create(
            :invoice_id       => invoice.id,
            :variant_id       => v.id,
            :quantity         => 1,
            :unit_price       => prorated_unit_price,
            :subtotal         => prorated_unit_price,
            :status           => 'pending',
            :subscription_id  => self.id,            
            :date_starts      => d,
            :date_ends        => d + interval - 1.day
          )
          invoice.calculate
          invoice.save                    
        end
      end        

      d2 = self.date_started_full + 1.day - 1.day
      while d2 <= Date.today do
        d2 = d2 + interval
      end
      d  = self.date_started + 1.day - 1.day
      while d <= d2 do
        # See if an invoice has already been created for today      
        li = self.line_items.where("date_starts = ? AND date_ends = ?", d, d + interval - 1.day).first
        if li.nil?
          invoice = Caboose::Invoice.create(        
            :site_id          => v.product.site_id,
            :customer_id      => self.user_id,
            :status           => Caboose::Invoice::STATUS_PENDING,
            :financial_status => Caboose::Invoice::STATUS_PENDING,
            :date_created     => DateTime.now,                                    
            :payment_terms    => sc.default_payment_terms,
            :invoice_number   => sc.next_invoice_number
          )          
          LineItem.create(
            :invoice_id       => invoice.id,
            :variant_id       => v.id,
            :quantity         => 1,
            :unit_price       => unit_price,
            :subtotal         => unit_price,
            :status           => 'pending',
            :subscription_id  => self.id,            
            :date_starts      => d,
            :date_ends        => d + interval - 1.day
          )
          invoice.calculate
          invoice.save                    
        end
        d = d + interval
      end        
      return true      
    end
921006
def bind_to(self, table, name):
        
        if self.bound_to is not None:
            raise AttributeError(
                "Column is already bound to '%s' as '%s'" %\
                    self.bound_to)

        self.bound_to = (table, name)
1108259
def from_(self, table, alias=None):
        
        if isinstance(table, str):
            table = [[table, alias]]
        self.raw_tables = table
        return self