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())
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'})
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
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()
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')
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))
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))
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)
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")