def create_billingcycle(membership):
    """
    Creates a new billing cycle for a membership.

    If a previous billing cycle exists, the end date is used as the start
    date for the new one.  If a previous one doesn't exist, e.g. it is a new
    user, we use the time when they were approved.
    """
    billing_cycle = None
    try:
        if membership.status != 'A':
            logger.critical("%s not Approved. Cannot send bill" % repr(membership))
            raise MembershipNotApproved("%s not Approved. Cannot send bill" % repr(membership))
        try:
            newest_existing_billing_cycle = membership.billingcycle_set.latest('end')
        except __HOLE__:
            newest_existing_billing_cycle = None

        if newest_existing_billing_cycle != None:
            cycle_start = newest_existing_billing_cycle.end
        elif membership.approved != None:
            cycle_start = membership.approved
        else:
            logger.critical("%s is missing the approved timestamp. Cannot send bill" % repr(membership))
            raise MembershipNotApproved("%s is missing the approved timestamp. Cannot send bill" % repr(membership))

        with transaction.atomic():
            billing_cycle = BillingCycle(membership=membership, start=cycle_start)
            billing_cycle.save()
            bill = Bill(billingcycle=billing_cycle)
            bill.save()
        bill.send_as_email()
        return billing_cycle
    except Exception as e:
        logger.critical("%s" % traceback.format_exc())
        logger.critical("Transaction rolled back, billing cycle not created!")
        raise
dataset/ETHPy150Open kapsiry/sikteeri/membership/management/commands/makebills.py/create_billingcycle