예제 #1
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())
예제 #2
0
파일: views.py 프로젝트: imclab/zipcodegrid
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
예제 #3
0
def receive_bills(request):
    received_bills = json.loads(request.body)
    for received_bill in received_bills:
        title = received_bill['title']
        # TODO: use authorization by API key
        institution = Institution.objects.first()
        bill = Bill(title=title,
                    url=received_bill['url'],
                    key=hashlib.sha1(title.encode('utf-8')).hexdigest(),
                    institution=institution)
        bill.save()
    return JsonResponse({'status': 'ok'})
예제 #4
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"])
예제 #5
0
    def destroy(self, request, ID):

        bill = Bill.get_by_id(int(ID))
        if bill:
            bill.key.delete()
            return Response(status=status.HTTP_202_ACCEPTED)
        return Response(status=status.HTTP_400_BAD_REQUEST)
예제 #6
0
  def update_bill(self, bill):
	"""
	Check if a bill exists in datastore, and update its stats.
	"""
	this_bill = Bill.get_by_key_name(bill['title']) 
	logging.info(bill['title']) 
	if this_bill is None: 
		this_bill = self.create_bill(bill)
		is_new_bill = True
	else: is_new_bill = False
	this_bill.rank = bill['rank']
	import urllib
	self.request_args = {'bill_id':  bill['id']}
	self.formatted_args = urllib.urlencode(self.request_args)
	from google.appengine.api import urlfetch
	fetch_page = urlfetch.fetch( url = OPENCONGRESS_INFO_URL + self.formatted_args,
								method = urlfetch.GET) 
	from utils.BeautifulSoup import BeautifulSoup	
	document = BeautifulSoup(fetch_page.content)
	property_count = 0	 
	this_bill.introduction_date = str(document.findAll('li')[property_count]).split('</strong> ')[1].split('</li>')[0]
	this_bill.status = str(document.findAll('li')[property_count + 1]).split('</strong> ')[1].split('</li>')[0]
	if this_bill.status == "This Bill Has Become Law":  property_count = -1 # no next step
	else: this_bill.next_step = str(document.findAll('li')[property_count + 2]).split('</strong> ')[1].split('</li>')[0]
	this_bill.latest_action = str(document.findAll('li')[property_count + 3]).split('</strong> ')[1].split('</li>')[0]
	if len( this_bill.latest_action ) > 68: this_bill.latest_action = " ".join(this_bill.latest_action.split(' ')[:9]) + "..."
	this_bill.sponsor = str(document.findAll('li')[property_count + 4]).split('</strong> ')[1].split('</li>')[0].decode('utf-8')
	this_bill.sponsor_name = this_bill.sponsor.split("[")[0] 
	self.save.append(this_bill)
	if is_new_bill: self.send_email_updates(this_bill)
	return
예제 #7
0
def search(search):
    # time window in years
    time_window = "1y"
    session_tw = session.get("time_window", None)
    if session_tw:
        time_window = session_tw

    per_page = 10
    page = request.args.get(get_page_parameter(), type=int, default=1)
    offset = (page - 1) * per_page

    if search == 'all':
        query = get_all_keywords()
    else:
        query = [search]

    bills, total = Bill.get_monitoring_results(query,
                                               page=page,
                                               per_page=per_page,
                                               time_limit=time_window)
    pagination = Pagination(page=page,
                            total=total,
                            per_page=per_page,
                            offset=offset,
                            css_framework='bootstrap4')
    return render_template('results.html',
                           results=bills,
                           per_page=per_page,
                           page=page,
                           pagination=pagination,
                           escape=escape)
예제 #8
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
예제 #9
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
예제 #10
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
예제 #11
0
    def payment(self, request, ID):

        bill = Bill.get_by_id(int(ID))
        serializer = BillPaymentSerializer(request.data)
        if serializer.is_valid():
            bill.status = serializer.validated_data.get('status')
            bill.date_of_payment = serializer.validated_data.get('date_of_payment')
            bill.notes = serializer.validated_data.get('notes')
            bill.put()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #12
0
    def generate_bill(self, bill_start_month):
        """
        根据给定的日期, 获取指定的账单记录
        :param bill_start_month:
        :return:
        """
        bill = json.loads(Bill.objects(mobile=self.phone, bill_month__gte=bill_start_month).to_json())
        for item in bill:
            del item["_id"]
            del item["task_id"]
            del item["mobile"]

        return bill
예제 #13
0
def accountinput_create_input(request):
    try:
        person_show=name = request.session["Uid"]
    except:
        return render_to_response( "login.html",{'nameerror':'非法'})
    time=request.GET["time"]
    money=request.GET["money"]
    pid=request.GET["pid"]
    billid=request.GET["billid"]
    note=request.GET["note"]
    paykind=request.GET["paykind"]
    namecontent=request.GET["namecontent"]
    numcontent = request.GET["numcontent"]
    person_id=request.session["Uid"]
    s=Bill(time = time,name = namecontent,money = string.atof(money),transactor = person_id,note = note,paykind = paykind,proid = pid,change = False, bill_id=billid,)
    s.save()
    str1=namecontent
    str2=numcontent
    s1 = str1.split(',')
    s2 = str2.split(',')
    if numcontent != "":
        for i  in range(0,len(s2)-1):
            bsave = Billdevice_record(Bill_sqlid = s.id, proid = pid,name = s1[i],number = string.atof(s2[i]),paykind = paykind,)
            bsave.save()
    a=Account.objects.get(project_id=pid)
    a.money_cost =+a.money_cost+string.atof(money)
    a.save()
    b=Prokindaccount.objects.get(proid=pid,payname=paykind)
    b.money_cost=b.money_cost+string.atof(money)
    b.save()
    alldata=[]
    onedata = [0,0]
    onedata[0] = "1"
    onedata[1] = '2'
    alldata.append(onedata)
    data = simplejson.dumps(alldata)
    return HttpResponse(data, 'application/javascript')
예제 #14
0
파일: views.py 프로젝트: medelect/cache
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})
예제 #15
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']
    )
예제 #16
0
    def update(self, request, ID):

        bill = Bill.get_by_id(int(ID))
        serializer = BillCreateSerializer(data=request.data)
        if serializer.is_valid():
            bill.vendor = serializer.validated_data.get('vendor')
            bill.bill_date = serializer.validated_data.get('bill_date')
            bill.amount = serializer.validated_data.get('amount')
            bill.due_date = serializer.validated_data.get('due_date')
            bill.line_items = serializer.validated_data.get('line_items')
            bill.company = serializer.validated_data.get('company')
            bill.branch = serializer.validated_data.get('branch')
            bill.status = serializer.validated_data.get('status')
            bill.date_of_payment = serializer.validated_data.get('date_of_payment')
            bill.notes = serializer.validated_data.get('notes')
            bill.put()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #17
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
예제 #18
0
  def get(self):    
	"""
	
	Renders an frame with a webpage used to create quizzes. For this app,
	the frame contains the text of pending Congressional legislation.
	
	"""
	import urllib 
	bill_name = urllib.unquote( self.request.path.split('/bill/')[1] )
	self.this_bill = Bill.get_by_key_name(bill_name)
	if self.this_bill is None:
	  logging.error('bill %s not found', bill_name) 
	  return self.redirect('/bill_not_found')
	  	  
	from models import ProficiencyTopic
	template_values = {'url': self.get_bill_url(), 'subject_key': APP_NAME,
	                   'topic_name': self.this_bill.title, }
	path = tpl_path(TEMPLATE_PATH + 'iframe.html')
	self.response.out.write(template.render(path, template_values))
	return
예제 #19
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)
예제 #20
0
def process_bill_data(bill_id, vote, bills):
    global invalid_specific_bill
    if bill_id in bills:
        return

    bill_slug = bill_id.split('-')[0]
    bill_url = SPECIFIC_BILL_API_URL.format_map({
        'congress': vote.congress,
        'bill_slug': bill_slug
    })
    r = requests.get(bill_url, headers=HEADERS)
    bill_api_data = r.json()

    if invalid_api_result(bill_api_data):
        print('proess_bill_data: bill_api_data invalid')
        invalid_specific_bill += 1
        print(bill_url)
        return
    bill_data = bill_api_data['results'][0]
    bill = Bill.from_api_data(bill_data)
    bills[bill_id] = bill
예제 #21
0
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
예제 #22
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")
예제 #23
0
from init_app import app
from models import Bill

if __name__ == '__main__':
    with app.app_context():
        Bill.reindex()
예제 #24
0
    def retrieve(self, request, ID):

        queryset = Bill.get_by_id(int(ID))
        serializer = BillDetailSerializer(queryset)
        return Response(serializer.data)
예제 #25
0
    def list(self, request):

        queryset = Bill.query().fetch()
        serializer = BillListSerializer(queryset, many=True)
        return Response(serializer.data)
예제 #26
0
def update_bills_in_elasticsearch(leginfo_ids):
    with app.app_context():
        Bill.reindex_by_leginfo_ids(leginfo_ids=leginfo_ids)
예제 #27
0
def bill_create(request):
#    static = STATIC_URL
    user = request.user
    try:
        if user.get_profile().utype < 2:
            return HttpResponseForbidden()
        else:
            if request.POST:
                try:
                    tprice = 0
                    profile = user.get_profile()
                    bill = Bill(user=user)
                    bill.name = request.POST['name']
                    bill.address = request.POST['address']
                    bill.zipcode = request.POST['zipcode']
                    bill.contact = request.POST['contact']
                    bill.express = request.POST['express'] or 'EMS'
                    bill.note = request.POST['note']
                    bill.save()
                    cartlist = profile.cart.all()
                    for l in cartlist:
                        tprice = tprice + l.price
                    bill.price = tprice
                    bill.cartlists.add(*cartlist)
                    bill.save()
                    cart = profile.cart
                    cart.clear()
                    profile.save()
                except:
                    return HttpResponseForbidden()
                return HttpResponse('ok')
            else:
                tprice = 0
                tnum = 0
                cart = user.get_profile().cart.all()
                for l in cart:
                    tprice = tprice + l.price
                    tnum = tnum + l.num
                return render_to_response('category/bill.html', locals(), context_instance=RequestContext(request))
    except:
        return HttpResponseForbidden()
예제 #28
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
예제 #29
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
예제 #30
0
def get_msg_text(changes, email):
    logger.info("Getting message text")
    unsubscribe_link = site_addr + "unsubs/" + email
    kws_msgs = []
    with app.app_context():
        for kw, items in changes.items():
            added, updated = items
            added_msgs = ["Added bills:"]
            for id_ in added:
                bill = Bill.find_by_leginfo_id(id_)
                bill_subject = bill.subject
                bill_link = status_client_url + '?' + id_
                bill = Bill.find_by_leginfo_id(id_)
                bill_code = bill.code
                added_msgs.append(bill_code + " (" + bill_subject +
                                  "). Link: " + bill_link)
            updated_msgs = ["Updated bills:"]
            for bill_info in updated:
                bill_id = bill_info.id
                prev_last_action_name = bill_info.last_action_name
                bill = Bill.find_by_leginfo_id(bill_id)
                bill_subject = bill.subject
                last_action_name = bill.last_action_name
                bill_code = bill.code
                bill_link = status_client_url + '?' + bill_id
                if last_action_name:
                    la_change = prev_last_action_name + " - " + last_action_name
                else:
                    la_change = prev_last_action_name
                updated_msgs.append(bill_code + " (" + bill_subject +
                                    "). Last action change: " + la_change +
                                    ". Link: " + bill_link)
            if len(added_msgs) > 1:
                added_msg = "\n    ".join(added_msgs)
            else:
                added_msg = ""

            if len(updated_msgs) > 1:
                updated_msg = "\n    ".join(updated_msgs)
            else:
                updated_msg = ""

            kw_msg = f"""
{kw}

"""
            if added_msg:
                kw_msg += added_msg + "\n"
            if updated_msg:
                kw_msg += updated_msg + "\n"
            if added_msg or updated_msg:
                kws_msgs.append(kw_msg)
        kws_msgs = "\n".join(kws_msgs)
        text = \
        f"""
Here are updates for every keyword you subsribed on California Bills Monitoring App.

{kws_msgs} 
You can unsubscribe using following link: {unsubscribe_link}
"""
        logger.info("Email text: \n" + text)
        return text
예제 #31
0
 def get_bills(self):
     top_ten_bills = Bill.all().order('rank').fetch(BILL_LIMIT)
     return top_ten_bills 
예제 #32
0
def input_continue(request):
    try:
        accid=request.GET["accid"]
        cokind=request.GET["cokind"]
        time=request.GET["time"]
        name=request.GET["name"]
        money=string.atof(request.GET["money"])
        person=request.GET["person"]
        pnum=request.GET["pnum"]
        note=request.GET["note"]
        p=Project.objects.get(pid=accid)
        
        billobj=Bill(time=time, name=name, money=money,transactor=person,bill_id=pnum,paykind=cokind,proid=accid,note=note)
        
        billobj.save()
        print p.prokind
        if p.prokind=='863':
            a = Templetcost863.objects.get(temp_id = accid)
            if cokind==u'设备费':
                b = a.device_cost+money
                a.device_cost=b
            if cokind==u'材料费':
                b = a.material_cost+money
                a.material_cost=b
            if cokind==u'测试费':
                b = a.test_cost+money
                a.test_cost=b
            if cokind==u'燃料费':
                b = a.fuel_cost+money
                a.fuel_cost=b
            if cokind==u'差旅费':
                b = a.trip_cost+money
                a.trip_cost=b
            if cokind==u'会议费':
                b = a.meeting_cost+money
                a.meeting_cost=b
            if cokind==u'国际合作交流费':
                b = a.coperation_cost+money
                a.coperation_cost=b
            if cokind==u'出版文献等':
                b = a.publish_cost+money
                a.publish_cost=b
            if cokind==u'劳务费':
                b = a.labor_cost+money
                a.labor_cost=b
            if cokind==u'其他费用':
                b = a.other_cost+money
                a.other_cost=b
        if p.prokind==u'自然基金':
            a = TempletcostNature.objects.get(temp_id = accid)
            if cokind==u'设备费':
                b = a.device_cost+money
                a.device_cost=b
            if cokind==u'数据采集费':
                b = a.data_cost+money
                a.data_cost=b
            if cokind==u'专家咨询费':
                b = a.consult_cost+money
                a.consult_cost=b
            if cokind==u'印刷费':
                b = a.print_cost+money
                a.print_cost=b
            if cokind==u'差旅费':
                b = a.trip_cost+money
                a.trip_cost=b
            if cokind==u'会议费':
                b = a.meeting_cost+money
                a.meeting_cost=b
            if cokind==u'国际合作交流费':
                b = a.coperation_cost+money
                a.coperation_cost=b
            if cokind==u'资料费':
                b = a.info_cost+money
                a.info_cost=b
            if cokind==u'劳务费':
                b = a.labor_cost+money
                a.labor_cost=b
            if cokind==u'其他费用':
                b = a.other_cost+money
                a.other_cost=b
            a.save()
        c = Account.objects.get(project_id = accid)
        b = c.money_lef - money
        c.money_lef = b
        c.save()
        
        alldata=[]
        onedata = [0,0]
        onedata[0] = "1"
        onedata[1] = '2'
        alldata.append(onedata)
        json = simplejson.dumps(alldata)
        return HttpResponse(json, 'application/javascript')
    except:
        return render_to_response("input_search.html",{'error':'网页出错请联系工作人员'},context_instance = RequestContext(request))  
예제 #33
0
파일: util.py 프로젝트: liyq1406/haihang
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
예제 #34
0
파일: util.py 프로젝트: liyq1406/haihang
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)
예제 #35
0
def input_finish(request):
    try:
        #if request.method == 'POST':
        accid=request.POST["projectnum"]
        cokind=request.POST["costkind"]
        time=request.POST["time"]
        name=request.POST["name"]
        money=string.atof(request.POST["money"])
        person=request.POST["person"]
        pnum=request.POST["pnum"]
        note=request.POST["note"]
        p=Project.objects.get(pid=accid)
        
        billobj=Bill(time=time, name=name, money=money,transactor=person,bill_id=pnum,paykind=cokind,proid=accid)
        
        billobj.save()
        if p.prokind=='863':
            a = Templetcost863.objects.get(temp_id = accid)
            if cokind==u'设备费':
                b = a.device_cost+money
                a.device_cost=b
            if cokind==u'材料费':
                b = a.material_cost+money
                a.material_cost=b
            if cokind==u'测试费':
                b = a.test_cost+money
                a.test_cost=b
            if cokind==u'燃料费':
                b = a.fuel_cost+money
                a.fuel_cost=b
            if cokind==u'差旅费':
                b = a.trip_cost+money
                a.trip_cost=b
            if cokind==u'会议费':
                b = a.meeting_cost+money
                a.meeting_cost=b
            if cokind==u'国际合作交流费':
                b = a.coperation_cost+money
                a.coperation_cost=b
            if cokind==u'出版文献等':
                b = a.publish_cost+money
                a.publish_cost=b
            if cokind==u'劳务费':
                b = a.labor_cost+money
                a.labor_cost=b
            if cokind==u'其他费用':
                b = a.other_cost+money
                a.other_cost=b
        if p.prokind==u'自然基金':
            a = TempletcostNature.objects.get(temp_id = accid)
            if cokind==u'设备费':
                b = a.device_cost+money
                a.device_cost=b
            if cokind==u'数据采集费':
                b = a.data_cost+money
                a.data_cost=b
            if cokind==u'专家咨询费':
                b = a.consult_cost+money
                a.consult_cost=b
            if cokind==u'印刷费':
                b = a.print_cost+money
                a.print_cost=b
            if cokind==u'差旅费':
                b = a.trip_cost+money
                a.trip_cost=b
            if cokind==u'会议费':
                b = a.meeting_cost+money
                a.meeting_cost=b
            if cokind==u'国际合作交流费':
                b = a.coperation_cost+money
                a.coperation_cost=b
            if cokind==u'资料费':
                b = a.info_cost+money
                a.info_cost=b
            if cokind==u'劳务费':
                b = a.labor_cost+money
                a.labor_cost=b
            if cokind==u'其他费用':
                b = a.other_cost+money
                a.other_cost=b
            a.save()
        c = Account.objects.get(project_id = accid)
        b = c.money_lef - money
        c.money_lef = b
        c.save()
        return render_to_response("input_search.html",{'error':'录入成功'},context_instance = RequestContext(request)) 
    except:
        return render_to_response("input_search.html",{'error':'错误'},context_instance = RequestContext(request)) 
예제 #36
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
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)
예제 #38
0
def notify_url_handler(request):
    """
    Handler for notify_url for asynchronous updating billing information.
    Logging the information.
    """
    if request.method == 'POST':
        logger1.info('get post')
        logger1.info(request.POST)
        if notify_verify(request.POST):
            logger1.info('verify ok')
            # save the bill
            bill = Bill(out_trade_no=request.POST.get('out_trade_no'),
                        in_trade_no=gen_inner_trade_no(_TYPE_ALIPAY),  # inner trade number
                        subject=request.POST.get('subject'),
                        type=request.POST.get('type'),
                        trade_no=request.POST.get('trade_no'),
                        trade_status=request.POST.get('trade_status'),
                        seller_id=request.POST.get('seller_id'),
                        seller_email=request.POST.get('seller_email'),
                        buyer_id=request.POST.get('buyer_id'),
                        buyer_email=request.POST.get('buyer_email'),
                        total_fee=request.POST.get('total_fee'),
                        quantity=request.POST.get('quantity'),
                        price=request.POST.get('price'),
                        body=request.POST.get('body'),
                        gmt_create=request.POST.get('gmt_create'),
                        gmt_payment=request.POST.get('gmt_payment'),
                        is_total_fee_adjust=request.POST.get('is_total_fee_adjust'),
                        use_coupon=request.POST.get('use_coupon'),
                        discount=request.POST.get('discount'))
            bill.save()
            logger1.info('save bill')
            logger1.info(bill.as_list())

            # save the user
            users = Buyer.objects.filter(buyer_id=request.POST.get('buyer_id'))
            if not users:
                users = Buyer(name='',
                              buyer_id=bill.buyer_id,
                              buyer_email=bill.buyer_email)
                users.save()
                logger1.info('save user')
                logger1.info(users.as_list())

            # save this notify
            notify = Notify(time=request.POST.get('notify_time'),
                            type=request.POST.get('notify_type'),
                            nid=request.POST.get('notify_id'),
                            sign_type=request.POST.get('sign_type'),
                            sign=request.POST.get('sign'),
                            bill=bill)
            notify.save()
            logger1.info('save notify')
            logger1.info(notify.as_list())

            # start new thread to notify partner
            appid = bill.get_appid()
            logger1.info('appid: ' + appid)
            partner = Partner.objects.get(app_id=appid)
            if partner.real != 1:
                return HttpResponse("fail")
            params = {'out_trade_no':str(bill.out_trade_no)[len(partner.app_id):],
                      'in_trade_no': str(bill.in_trade_no),
                      'subject': str(bill.subject),
                      'buyer_id': str(bill.buyer_id),
                      'buyer_email': str(bill.buyer_email),
                      'fee': str(bill.total_fee),
                      'sign_type': 'MD5'}
            _, paramstr = params_filter(params)
            sign = build_mysign(paramstr, partner.app_key)
            params.update({'sign': sign, })
            if partner:
                thread = Thread(target=notify_partner, args=(bill, partner.get_doamin(), partner.get_url(), params))
                thread.start()

            return HttpResponse('success')
    return HttpResponse("fail")