Esempio n. 1
0
def main():
    # Get the power bill
    config = get_config()
    fetch = get_fetch_email(config)
    encrypted_bill = process_power_bill_email(fetch)
    decrypted_bill = decrypt_power_pdf(encrypted_bill)
    pwr_amt_due, service_start, service_end = process_power_bill_pdf(
        decrypted_bill)

    power_bill = Bill(start_date=service_start,
                      end_date=service_end,
                      category=categories[2][0],
                      total=pwr_amt_due)

    # Get the gas amount
    gas_amt_due = process_gas_bill_email(fetch)

    gas_bill = Bill(start_date=datetime(year=2019, month=7, day=26),
                    end_date=datetime(year=2019, month=8, day=15),
                    category=categories[0][0],
                    total=gas_amt_due)

    # Manually construct the water bill
    water_bill = Bill(start_date=datetime(year=2019, month=6, day=24),
                      end_date=datetime(year=2019, month=7, day=23),
                      category=categories[3][0],
                      total=107.30)

    # Get the internet bill
    internet_bill = get_internet_bill(2019, 8)

    bills = [gas_bill, internet_bill, power_bill, water_bill]

    summarize_bills(bills)
    split_bills_between_housemates(bills)

    start_fourway_split = datetime(year=2019, month=6, day=24)
    end_fourway_split = datetime(year=2019, month=7, day=6)
    water_fourway_split = split_bill(water_bill, start_fourway_split,
                                     end_fourway_split, 4)
    print("Water bill owed per person, split four ways: ${:.2f}".format(
        water_fourway_split))

    start_threeway_split = datetime(year=2019, month=7, day=6)
    water_threeway_split = split_bill(water_bill, start_threeway_split,
                                      water_bill.end_date, 3)
    print("Water bill owed per person, split three ways: ${:.2f}".format(
        water_threeway_split))

    start_flask(config["FLASK"]["DEBUG"])
Esempio n. 2
0
def add_bill():
    """добавление счета"""

    agent_id = int(input('id контрагента: '))
    contract_number = input('Номер договора: ')
    contract = session.query(Contract).filter_by(
        agent_id=agent_id, number=contract_number).first()

    if not contract:
        print('Не верно указан id или номер договора')
        return

    bill_number = input('Номер счета: ')

    # проверяем добавлен ли уже счет с таким номером к договору
    if bill_number not in [b.bill_number for b in contract.bills]:
        act_number = input('Номер акта: ')
        bill_sum = int(input('Сумма счета: '))
        act_sum = int(input('Сумма акта: '))

        new_bill = Bill(agent_id=agent_id,
                        contract_number=contract_number,
                        bill_number=bill_number,
                        act_number=act_number,
                        bill_sum=bill_sum,
                        act_sum=act_sum)
        session.add(new_bill)
        session.commit()
    else:
        print('Данный счет уже есть в базе')

    return
Esempio n. 3
0
def add_bill(request):
    saved = False

    if request.method == 'POST':
        form = BillForm(request.POST)

        if form.is_valid():
            bill = Bill()

            bill.identifier = get_random_string(length=20)
            """Get user"""
            user = User.objects.get(id_card='080123123F')

            bill.user = user
            bill.bill_date = timezone.now()
            bill.amount_price = form.cleaned_data['amount_price']
            bill.taxes = form.cleaned_data['taxes']
            bill.power_consumed = form.cleaned_data['power_consumed']
            saved = True
            bill.save()
        else:
            print(form.errors)
            form = BillForm()

    return render(request, 'views/bill-new.html', locals())
Esempio n. 4
0
 def add(self, project):
     form = get_billform_for(project, True, csrf_enabled=False)
     if form.validate():
         bill = Bill()
         form.save(bill, project)
         db.session.add(bill)
         db.session.commit()
         return 201, bill.id
     return 400, form.errors
Esempio n. 5
0
def commit_bill(output, reqdata, user):
    errors = []
    to_commit_billitems = []
    to_commit_extras = []
    try:
        items = _get_items(reqdata)
        bill = Bill(customer_name=reqdata['customer_name'],
                    server=User.objects.get(pk=user.id).username,
                    customer_id=output['customer_id'],
                    total=0)
        for r_billitem in reqdata['items']:
            # r_data = reqdata['items'][r_billitem]
            # print r_billitem['name']
            item = items[r_billitem['name']]
            billitem, ok = _create_item(r_billitem, BillItem, item)
            billitem_total = 0
            if ok:
                billitem_total += billitem.item_price
                # print billitem.item.name, billitem.item_price
                billitem.bill = bill
                billitem.category = billitem.item.category
                billitem.note = r_billitem['notes']
                to_commit_billitems.append(billitem)
            else:
                errors.append((billitem.item.name, billitem.item.quantity))
            for r_extra in r_billitem['extras']:
                r_data = r_billitem['extras'][r_extra]
                item = items[r_extra]
                extra, ok = _create_item(r_data, BillItemExtra, item)
                if ok:
                    billitem_total += extra.item_price * extra.quantity
                    # print extra.item.name, extra.item_price * extra.quantity
                    extra.billitem = billitem
                    to_commit_extras.append(extra)
                else:
                    errors.append((extra.item.name, extra.item.quantity))
            bill.total += billitem_total * billitem.quantity
            # print billitem.item.name, billitem.quantity
            # print 'Total', bill.total
    except KeyError as e:
        raise FormatError('Missing key: {}'.format(str(e)))
    if errors:
        output['total'] = 0
        output['customer_id'] = None
        output['errors'] = dict(errors)
        bill = None
    else:
        bill = _commit_bill_to_db(bill, to_commit_billitems, to_commit_extras,
                                  items)
        output['total'] = bill.total
        output['customer_id'] = bill.customer_id
        output['errors'] = {}
        output['date'] = bill.date
        output['billid'] = bill.id
    return output, bill
Esempio n. 6
0
def create_bill(user_uuid, name, host_uuid, run_time, month, total_fee):
    try:
        new_bill = Bill()
        new_bill.user_uuid = user_uuid
        new_bill.host_uuid = host_uuid
        new_bill.run_time = run_time
        new_bill.month = month
        new_bill.name = name
        new_bill.total_fee = total_fee
        new_bill.bill_account_time = datetime.datetime.now()
        new_bill.save()
        return new_bill
    except Exception as e:
        log.error('[bill] create_bill error.{}'.format(e.__str__()))
        return None
Esempio n. 7
0
def BillView(request):
    if request.method == 'POST':
        form = BillForm(request.POST)
        if form.validate():
            dataFromForm = {}
            for field in form:
                dataFromForm[field.name] = field._value()
            newRecord = Bill(**dataFromForm)
            session.add(newRecord)
            session.commit()


#            return HttpResponseRedirect('cache/???.html') # show saved record
    else:
        form = BillForm()
    return render(request, 'cache/inpt.html', {'form': form})
Esempio n. 8
0
def build_bill(info):
    """
    Builds a Bill given the info for that Bill.

    info -- the dict of bill information

    Returns the Bill
    """

    return Bill(
        number=info['number'],
        short_title=info['short_title'],
        sponsor_id=info['sponsor_id'],
        congressdotgov_url=info['congressdotgov_url'],
        introduced_date=info['introduced_date'],
        latest_major_action=info['latest_major_action']
    )
Esempio n. 9
0
def get_internet_bill(year, month):
    """
    Create a Bill object for the internet bill using
    the given month to determine the service period.
    :param year: Integer representing the year of
    service covered by the bill.
    :param month: Integer representing the month
    of service covered by the bill.
    :return: Bill object for the internet.
    """
    last_day_of_month = calendar.monthrange(year, month)[1]
    internet_bill = Bill(start_date=datetime(year=year, month=month, day=1),
                         end_date=datetime(year=year,
                                           month=month,
                                           day=last_day_of_month),
                         category=categories[1][0],
                         total=50.00)

    return internet_bill
Esempio n. 10
0
def add_bill():
    form = get_billform_for(g.project)
    if request.method == 'POST':
        if form.validate():
            # save last selected payer in session
            session['last_selected_payer'] = form.payer.data
            session.update()

            bill = Bill()
            db.session.add(form.save(bill, g.project))
            db.session.commit()

            flash(_("The bill has been added"))

            args = {}
            if form.submit2.data:
                args['add_bill'] = True

            return redirect(url_for('.list_bills', **args))

    return render_template("add_bill.html", form=form)
Esempio n. 11
0
def run_billing(bill_time=timezone.localtime(timezone.now())):
    """Generate billing records for every member who deserves it."""
    bill_date = datetime.date(bill_time)
    #print "Running billing for %s" % bill_date
    try:
        latest_billing_log = BillingLog.objects.latest()
    except ObjectDoesNotExist:
        latest_billing_log = None
    if latest_billing_log and not latest_billing_log.ended:
        print 'The last billing log (%s) claims to be in progress.	Aborting billing.' % latest_billing_log
        return

    billing_log = BillingLog.objects.create()
    billing_success = False
    bill_count = 0
    try:
        for member in Member.objects.all():
            last_bill = member.last_bill()
            if last_bill:
                start_date = last_bill.created + timedelta(days=1)
            else:
                start_date = bill_date - timedelta(days=62)
                if start_date < settings.BILLING_START_DATE:
                    start_date = settings.BILLING_START_DATE
            run = Run(member, start_date, bill_date)
            for day_index in range(
                    0, len(run.days)
            ):  # look for days on which we should bill for a membership
                day = run.days[day_index]
                if day.is_membership_anniversary(
                ) or day.is_membership_end_date():  # calculate a member bill
                    bill_dropins = []
                    bill_guest_dropins = []
                    recent_days = run.days[0:day_index + 1]
                    recent_days.reverse()
                    for recent_day in recent_days:  # gather the daily logs for this member and guests under this membership
                        if recent_day.bill:
                            break
                        if recent_day.daily_log:
                            bill_dropins.append(recent_day.daily_log)
                        for guest_daily_log in recent_day.guest_daily_logs:
                            bill_guest_dropins.append(guest_daily_log)
                    # now calculate the bill amount
                    bill_amount = 0
                    monthly_fee = day.membership.monthly_rate
                    if day.is_membership_end_date(): monthly_fee = 0
                    billable_dropin_count = max(
                        0,
                        len(bill_dropins) + len(bill_guest_dropins) -
                        day.membership.dropin_allowance)
                    bill_amount = monthly_fee + (billable_dropin_count *
                                                 day.membership.daily_rate)

                    day.bill = Bill(created=day.date,
                                    amount=bill_amount,
                                    member=member,
                                    paid_by=day.membership.guest_of,
                                    membership=day.membership)
                    #print 'saving bill: %s - %s - %s' % (day.bill, day, billable_dropin_count)
                    day.bill.save()
                    bill_count += 1
                    day.bill.dropins = [dropin.id for dropin in bill_dropins]
                    day.bill.guest_dropins = [
                        dropin.id for dropin in bill_guest_dropins
                    ]
                    day.bill.save()

                    # Close out the transaction if no money is due
                    if bill_amount == 0:
                        transaction = Transaction(member=member,
                                                  amount=0,
                                                  status='closed')
                        transaction.save()
                        transaction.bills = [day.bill]
                        transaction.save()

            # Now calculate a bill for non-member drop-ins if they exist and it has been two weeks since we billed them
            bill_dropins, guest_bill_dropins = run.non_member_daily_logs()
            if len(bill_dropins) > 0 or len(guest_bill_dropins) > 0:
                time_to_bill_guests = len(guest_bill_dropins) > 0 and (
                    bill_date -
                    guest_bill_dropins[0].visit_date) >= timedelta(weeks=2)
                time_to_bill_dropins = len(bill_dropins) > 0 and (
                    bill_date -
                    bill_dropins[0].visit_date) >= timedelta(weeks=2)
                if time_to_bill_guests or time_to_bill_dropins:
                    bill_amount = (len(bill_dropins) + len(guest_bill_dropins)
                                   ) * settings.NON_MEMBER_DROPIN_FEE
                    last_day = run.days[len(run.days) - 1]
                    last_day.bill = Bill(created=last_day.date,
                                         amount=bill_amount,
                                         member=member)
                    last_day.bill.save()
                    bill_count += 1
                    last_day.bill.dropins = [
                        dropin.id for dropin in bill_dropins
                    ]
                    last_day.bill.guest_dropins = [
                        dropin.id for dropin in guest_bill_dropins
                    ]
                    last_day.bill.save()

        billing_success = True
        #print 'Successfully created %s bills' % bill_count
    except:
        billing_log.note = traceback.format_exc()
    finally:
        billing_log.ended = timezone.localtime(timezone.now())
        billing_log.successful = billing_success
        billing_log.save()
        #print 'Completed billing %s' % billing_success
        if not billing_success: print billing_log.note
Esempio n. 12
0
def get_estimate():
    today = datetime.date.today()

    this_month = today.month
    this_year = today.year
    day = 1

    ip_address = request.remote_addr
    zipcode = int(valueFromRequest(key="zip_in", request=request))
    num_in_house = int(valueFromRequest(key="num_in_house", request=request))

    months = the_months()
    monthly_data = {}

    for month in months:
        try:
            d = float(valueFromRequest(key=month, request=request))
            monthly_data[month] = d
        except:
            continue

    # store the data
    user = User.query.filter_by(ip=ip_address).first()
    # add the user if they don't exist
    if user is None:

        user = User(name="",
                    email="",
                    ip=ip_address,
                    zip=zipcode,
                    state="NY",
                    num_in_house=num_in_house)
        db.session.add(user)
        db.session.commit()

    # run through the last 12 months. If there's a data entry, then check for a bill object. If one doesn't exist, add it.
    for i in range(1, 13):
        t_year = this_year
        t_month = this_month - i
        if t_month <= 0:
            t_month += 12
            t_year -= 1

        month_str = months[t_month - 1]
        if month_str not in monthly_data.keys():
            continue

        date = datetime.date(day=day, month=t_month, year=t_year)
        bill = Bill.query.filter_by(month=date).filter_by(
            user_id=user.id).first()

        if bill is None:
            bill = Bill(month=date,
                        user_id=user.id,
                        kwh=monthly_data[month_str])
            db.session.add(bill)
        else:
            bill.kwh = monthly_data[month_str]
        db.session.commit()

    ratio, average_ratio, normalized_ratio, metric, annual_usage = analyze_user(
        monthly_data, usage_by_unit, US_norm)
    pred_use, pred_uncert = predict_all_months(monthly_data, US_norm)

    response = make_response(
        json.dumps({
            "num_in_house": num_in_house,
            "zipcode": zipcode,
            "us_monthly": US_norm,
            "ratio": ratio,
            "average_ratio": average_ratio,
            "normalized_ratio": normalized_ratio,
            "metric": metric,
            "annual_usage": annual_usage,
            "predicted_usage": pred_use,
            "predicted_uncertainty": pred_uncert,
            "zipcode_usage": usage_by_unit,
            "monthly_usage": monthly_data
        }))
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response
Esempio n. 13
0
def check_host_bill(host, user_name, choice):
    """
    通过主机id来生成账单,如果是用户查询不需要结算,如果是生成月账单,则需要结算
    :param kwargs:
    :return:
    """
    cpu = host['hostInfo']['cpuCores']
    mem = host['hostInfo']['memSize']
    disk = host['hostInfo']['diskSize']
    name = host['hostInfo'].get('hostname', '')
    # 获取上次结算后的lifetime,不存在则返回新的账单记录表
    bill_record = get_record_bill(host_uuid=host['id'],
                                  name=name,
                                  cpu=cpu,
                                  disk=disk,
                                  mem=mem)
    current_month = datetime.datetime.now().month
    last_month = 12 if current_month == 1 else current_month - 1
    # 当主机还在运行时候需要生成账单,如果是用户查询不需要结算,如果是生成月账单,则需要结算
    if host['lifetime'] > bill_record.lifetime:
        # 只统计没有删除的主机
        price = gain_price_for_rancher(cpu=cpu, mem=mem, disk=disk)
        if price:
            # 主机从上次结帐到当前还没结帐的时间
            run_time = math.ceil(
                (host['lifetime'] - bill_record.lifetime) / 60) + 1
            fee = run_time * price
            # 当是月账单定时任务,需要结算
            if choice == "month_account":
                # 先查看有没有该主机的上个月账单(当用户在查看账单时候会根据用户查询时间生成账单,没有扣费),并且是没有支付的,bill_status=False
                try:

                    check_bill = Bill.objects.get(user_uuid=user_name, host_uuid=host['id'], month=last_month, \
                                                  pay_status=False,
                                                  bill_status=True)
                except Bill.DoesNotExist:
                    log.info(
                        '[bill] build month bill. bill not exist. create new bill '
                    )
                    # mutex.acquire(1)
                    # if mutex.acquire(1):
                    new_bill = Bill(user_uuid=user_name,
                                    name=name,
                                    host_uuid=host['id'],
                                    run_time=run_time,
                                    month=last_month,
                                    total_fee=fee)
                    new_bill.save()
                    log.info('[bill] create a new month bill:{}'.format(
                        new_bill.bill_uuid))

                    status = change_balance(user_name, 'bill', -fee,
                                            new_bill.bill_uuid)

                    if status is True:
                        pay_status = True
                        log.info(
                            '[bill] change_balance successful.modify balance:{}'
                            .format(-fee))
                    else:
                        pay_status = False
                        log.info('[bill] change_balance faild')

                    new_bill.pay_status = pay_status
                    new_bill.bill_account_time = datetime.datetime.now()
                    new_bill.bill_status = False
                    new_bill.save()
                    change_recordbill(host_uuid=host['id'],
                                      lifetime=host['lifetime'])
                    return
                except Exception as e:
                    log.error('[bill] check_host_bill other error:{}'.format(
                        e.__str__()))
                    return

                status = change_balance(user_name, 'bill', -fee,
                                        check_bill.bill_uuid)
                if status is True:
                    pay_status = True
                    log.info('[bill] no pay bill:{}'.format(
                        check_bill.bill_uuid))
                    log.info(
                        '[bill] change_balance successful.modify balance:{}'.
                        format(-fee))
                else:
                    pay_status = False
                    log.info('[bill] change_balance faild')
                # mutex.acquire()
                check_bill.pay_status = pay_status
                check_bill.run_time = run_time
                check_bill.total_fee = fee
                check_bill.bill_account_time = datetime.datetime.now()
                check_bill.bill_status = False
                check_bill.save()
                change_recordbill(host_uuid=host['id'],
                                  lifetime=host['lifetime'])

            else:
                # 先查看有没有该主机的当月账单(当用户在查看账单时候会根据用户查询时间生成账单,没有扣费),并且是没有支付的,bill_status=False
                try:
                    check_bill = Bill.objects.get(host_uuid=host['id'],
                                                  month=current_month,
                                                  pay_status=False,
                                                  bill_status=True)
                    check_bill.run_time = run_time
                    check_bill.total_fee = fee
                    check_bill.save()
                except Bill.DoesNotExist:
                    new_bill = Bill(user_uuid=user_name,
                                    host_uuid=host['id'],
                                    name=name,
                                    run_time=run_time,
                                    month=current_month,
                                    total_fee=fee)
                    new_bill.save()
                    log.info('[bill] user see bill.create a new month bill')
                except Exception as e:
                    log.error(
                        '[bill] check_host_bill more than one bill meet the condition:{}'
                        .format(e.__str__()))
                    return
        else:
            log.error('[bill] the price startegy is not existed.cpu=%d,mem=%d,disk=%d', \
                      cpu, mem, disk)
http = "https://sozd.duma.gov.ru/calendar/b/day/{}/{}".format(
    yesterday, yesterday)
resp = requests.get(http)
soup = BeautifulSoup(resp.text, 'lxml')
bills = []
for link in soup.find_all("a", class_="calen_num"):
    if link.text not in bills:
        bills.append(link.text)

for bill in bills:

    if db_session.query(exists().where(Bill.num == bill)).scalar():
        bill_obj = db_session.query(Bill).filter_by(num=bill).first()
        added_links = bill_obj.get_links()
    else:
        bill_obj = Bill(bill)
        added_links = []
    url = "https://sozd.duma.gov.ru/bill/" + bill
    print("================================================")
    print(url)
    print(f"{bill_obj.description}\n{bill_obj.authors}")
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text, 'lxml')
    links = []
    for link_ in soup.find_all(href=re.compile("download")):
        if link_["href"][0] == "/":
            link = "http://sozd.duma.gov.ru" + link_["href"]
        else:
            link = link_["href"]
        if link in added_links:
            continue
Esempio n. 15
0
def addBooking(roomType , roomNumber):  
  data= request.form

  if data and current_user.is_authenticated:
    #Get the current user's info: for tab bar
    user= User.query.filter_by(email= current_user.email).first()
    user= user.toDict()

    #Get dates for calculation
    endDate = data['trip-end']
    startDate = data['trip-start']

    

    #Split Date Strings into [year, month, day]
    endDate = data['trip-end'].split('-')
    startDate = data['trip-start'].split('-')
    #Create Date object using datetime
    d1= datetime.datetime( int(endDate[0]), int(endDate[1]), int(endDate[2]) )
    d2= datetime.datetime( int(startDate[0]), int(startDate[1]), int(startDate[2])  )
    print(endDate)
    print(startDate)
    print("Room \n\n",  type(roomNumber) )

    #Note
    #Initially you had the check out date being store as the check in date and vice versa

    #Make Booking object
    booking = Booking( roomNumber = int(roomNumber) , roomType = roomType , check_in_Date= d2 , check_out_Date=d1 , userEmail= current_user.email)
    #Get room and 
    room = Room.query.filter_by(roomNumber= int(roomNumber) ).first()
    #set room.available=False
    room.book()

    try:
      db.session.add(booking)
      db.session.add(room)
      db.session.commit()

      #Create Bill - Once booking is sucessful
      room= Room.query.filter_by(roomType = roomType).first()
      roomRate = room.roomRate
      print("Room rate: ",roomRate)

      
      bill = Bill(roomNumber = int(roomNumber) , roomType = roomType , check_in_Date= d2 , check_out_Date=d1 , userEmail= current_user.email , roomRate = float(roomRate) )

      bill.calculateBill()
      try:
        db.session.add(bill)
        db.session.commit()
      except IntegrityError:
        db.session.rollback()
      
      flash("Your room has been successfully booked.")
      return redirect("/MyBookings")
      
    except IntegrityError:
      db.session.rollback()
      flash("Your booking already exist.")
    
    return render_template('Book.html', user= user, roomNumber= roomNumber, roomType= roomType)

  flash("Invalid request.")
  return redirect("/loginForm")
def add_receipt(id_user):
    bill = Bill(id_user=id_user)
    db.session.add(bill)

    id_cart, list_item = list_item_of_user(id_user)
Esempio n. 17
0
def add_new_bill(data: dict):
    """
    валидация и добавление нового счета
    data (dict): словарь с данными счета из bill_add.js
    """

    # проверка на заполнение всех полей
    for k, v in data.items():
        if not v:
            eel.alert_message(f'параметр: {k} не заполнен')
            print(f'параметр: {k} не заполнен')
            return False

    # проверяем верно ли указан контрагент
    valid_agent = session.query(Agent).filter_by(
        name=data['agent_name']).first()

    if valid_agent:
        agent_id = int(valid_agent.id)
    else:
        eel.alert_message(
            f"Контрагент '{data['agent_name']}' отсутствует в базе данных")
        print(f"Контрагент '{data['agent_name']}' отсутствует в базе данных")
        return False

    # проверка валидности договора
    contract = session.query(Contract).filter_by(
        agent_id=agent_id, number=data['contract_number']).first()
    # print(contract)

    if contract:
        # проверим вдруг счет с таким номером у данного договора уже есть
        bill_number = data['bill_number']

        if bill_number not in [b.bill_number for b in contract.bills]:
            bill_sum = float(data['bill_sum'])
            act_number = data['act_number']
            act_sum = float(data['act_sum'])
            bill_date = data['bill_date']
            act_date = data['act_date']

            new_bill = Bill(agent_id=agent_id,
                            contract_number=data['contract_number'],
                            bill_number=bill_number,
                            act_number=act_number,
                            bill_sum=bill_sum,
                            act_sum=act_sum,
                            bill_date=bill_date,
                            act_date=act_date)
            session.add(new_bill)
            session.commit()

            eel.alert_message(f'Счет {bill_number} успешно добавлен!')
            print(f'Счет {bill_number} успешно добавлен!')
            return True
        else:
            eel.alert_message('Данный счет уже есть в базе')
            print('Данный счет уже есть в базе')
    else:
        eel.alert_message(
            f"У контрагента {data['agent_name']} нет договора № {data['contract_number']}"
        )
        print(
            f"У контрагента {data['agent_name']} нет договора № {data['contract_number']}"
        )

    return False