def createtransfer(): id = session.get("user_id", None) if id is None: return redirect(url_for("core.homepage")) user = User.query.get(id) if user is None: return redirect(url_for("core.homepage")) if request.method == "POST": value= request.form.get("value", None) tujuan= request.form.get("tujuan", None) errors = [] if value is None or value == "": errors.append(dict(field="value", message="Input Empty")) if tujuan is None or tujuan == "": errors.append(dict(field="tujuan", message="Input Empty")) if len(errors) > 0: return render_template("create_transfer.html", errors=errors), 400 transfer = Transfer(value, tujuan, session.get("user_id", None)) transfer.createdtime = datetime.datetime.now() user.saldo = int(user.saldo) - int(value) database.session.add(transfer) database.session.add(user) database.session.commit() return redirect(url_for("user.listtransaksi")), 201 return render_template("create_transfer.html", **locals())
def check_total_transfers(): num_people = Person.select().count() total_incoming = Transfer.select().where(Transfer.from_facility >> None).count() total_outgoing = Transfer.select().where(Transfer.to_facility >> None).count() if total_incoming == num_people and total_outgoing == num_people: print "Looks good" return True if total_incoming != num_people: print "Incoming transfers don't match: %d != %d" % (total_incoming, num_people) if total_outgoing != num_people: print "Outgoing transfers don't match: %d != %d" % (total_outgoing, num_people) return False
def get_data(): (start, end) = get_boundary_dates() data = { 'start_date': start.isoformat(), 'end_date': end.isoformat(), 'detentions': {}, 'deportations': {}, } detentions_to_date = 0 deportations_to_date = 0 for transfer in Transfer.select().where( (Transfer.from_facility >> None) | (Transfer.to_facility >> None)).order_by(Transfer.date): datestr = transfer.date.isoformat() if transfer.from_facility is None: if datestr not in data['detentions']: data['detentions'][datestr] = { 'facilities': set(), 'to_date': detentions_to_date, } detentions_to_date += 1 data['detentions'][datestr]['facilities'].add(transfer.to_facility.get_id()) data['detentions'][datestr]['to_date'] = detentions_to_date elif transfer.to_facility is None and transfer.reason == "Removed": if datestr not in data['deportations']: data['deportations'][datestr] = { 'facilities': set(), 'to_date': deportations_to_date, } deportations_to_date += 1 data['deportations'][datestr]['facilities'].add(transfer.from_facility.get_id()) data['deportations'][datestr]['to_date'] = deportations_to_date else: pass return sets_to_lists(data)
def CreateOrEditTransfer_view(request, transfer_id=None): response_data = {} # словарь для JSON-ответа if (transfer_id == None or transfer_id == '999999'): _transfer = Transfer() _message = 'Заявка добавлена успешно' else: _transfer = get_object_or_404(Transfer, id=transfer_id) _message = 'Заявка отредактирована успешно' if request.method == "GET" and request.is_ajax(): # сериализуем только queryset поэтому заворчаиваем объект в [obj,] data = serializers.serialize( 'json', [ _transfer, ], fields=('date_departure', 'time_departure', 'place_departure', 'place_arrival', 'quantity_total', 'quantity_adult', 'quantity_member', 'status', 'status_comment')) return _json_response(data) if request.POST: formTransfer = TransferForm(request.POST, instance=_transfer) if formTransfer.is_valid(): res = formTransfer.save(commit=False) res.user_id = auth.get_user( request ).id #передаем ID директора , к которому привязан участник # Если участник использует чекбокс "Свое название", то сохраняем его в базу if ('transDepartureSelf' in request.POST) and \ request.POST['transDepartureSelf'] not in \ list(Place_departure_choices.objects.filter(user_id = auth.get_user(request)).values_list('place_name',\ flat=True)): new_dep_place = Place_departure_choices( user=auth.get_user(request), place_name=request.POST['transDepartureSelf']) new_dep_place.save() res.place_departure = new_dep_place if ('transArrivalSelf' in request.POST) and \ request.POST['transArrivalSelf'] not in \ list(Place_departure_choices.objects.filter(user_id = auth.get_user(request)).values_list('place_name',\ flat=True)): new_arriv_place = Place_departure_choices( user=auth.get_user(request), place_name=request.POST['transArrivalSelf']) new_arriv_place.save() res.place_arrival = new_arriv_place # Рассчитываем сумму заявки и сохраняем ; res.payment = fee_transfer formTransfer.save() messages.add_message(request, messages.SUCCESS, _message) return HttpResponse('ok') else: response_data['errors'] = u'Неправильно заполнена форма.' response_data['formErrors'] = simplejson.dumps(formTransfer.errors) return _json_response(response_data) return redirect('/')
def set_data_for(self, number): try: self.data = [(transf.number, transf.date.strftime(u"%d/%m/%Y a %Hh:%Mmn"), transf.amount) for transf in Transfer.all()\ if transf.number.contact == number.contact] except AttributeError: pass
def set_data_for(self, number): if not number: return try: self.data = [(transf.contact.number, transf.date.strftime(u"%c"), formatted_number(transf.amount), transf.response) for transf in Transfer.filter(contact__number=number).order_by(Transfer.date.desc())] except AttributeError: raise self.hheaders = [u"Vide", ] self.data = ["", "Aucun transfers", "", ]
def multiple_sender(data): """ data = {phone_num: [76027211, 76433890], code: 03944, amount: 100} """ amount = data.get("amount") code = data.get("code") for phone_num in data.get("phone_num"): transfer = Transfer() transfer.amount = amount transfer.contact = Contact.get_or_create(phone_num) transfer.response = u"{}".format( send_ussd(format_str(phone_num, amount, code)).message) transfer.save()
def submit(self, session, source, record=None, overwrite=False): """ Submit a job and store it in the database """ metadata = 'NA62 raw data file' attemp = 1 # I am receiving further information from an existing record on the database if record is not None: metadata = 'NA62 raw data file, resubmitting from job_id: ' + str(record.job_id) + \ ' mariadb_id: ' + str(record.id) attemp = record.transfer_attemp + 1 try: job_id = self.fts_instance.submit( source.get_fts_source(), source.get_fts_castor_destination(), metadata, overwrite=overwrite) except: self.logger.error('Cannot submit the job: ' + source.get_source()) raise try: # def __init__(self, file_id, file_size, dst_host_id, dst_path, job_id, attemp): new_transfer = Transfer( # self.host, # source.get_dir_name(), # source.get_base_name(), source.get_file_id(), source.get_size(), 9, source.get_destination(), job_id, attemp) session.add(new_transfer) session.flush() database_id = new_transfer.id # should be not None session.commit() except: session.rollback() self.logger.error('Error cannot add the job_id: ' + job_id + ' to the database') raise finally: # release the connection to the pool session.close() return (job_id, database_id)
def addressbook_transfer(contact_id): numbers = PhoneNumber.filter(contact=Contact.get(id=int(contact_id))) data = {'transfers': [tr.to_dict() \ for tr in Transfer.filter(number__in=numbers)]} return json.dumps(data)
def get_boundary_dates(): earliest_date = datetime.strptime(Transfer.select().where((Transfer.from_facility >> None) | (Transfer.to_facility >> None)).aggregate(fn.Min(Transfer.date)), "%Y-%m-%d").date() latest_date = datetime.strptime(Transfer.select().where((Transfer.from_facility >> None) | (Transfer.to_facility >> None)).aggregate(fn.Max(Transfer.date)), "%Y-%m-%d").date() return (earliest_date, latest_date)
Group.filter(id=1).get() l_cont_group = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 1), (3, 3), (4, 1), (4, 3), (5, 4)] for c, g in l_cont_group: try: ContactGroup(contact=c, group=g).save() print c, g, "............. OK" except: print c, g, "............. OK" print "Transfer" for i in range(1, 15): try: num = randint(1, 5) Transfer(amount=randint(100, 1000), date=datetime(2012, 11, randint(1, 29), randint(1, 23), randint(1, 59), randint(1, 59)), number=num).save() print (u"Transfert N:", i, " de ", Transfer.filter(number=num).get().number.contact.name, "............. OK") except: raise print i, "no"
def populate(self, doc_name): row = 7 des_col = 5 deb_col = 11 # Debit column cre_col = 12 # Credit column db.drop_all() db.create_all() info(doc_name) self.update_state(state='PROGRESS') sheet = doc_open(doc_name) while parse(sheet, row, des_col): self.update_state(state='PROGRESS') desc = parse(sheet, row, des_col) datetime = parse(sheet, row, 1).split(' ') date = datetime[0] time = datetime[1] try: credit = float(parse(sheet, row, cre_col)) debit = float(parse(sheet, row, deb_col)) except: credit = float(parse(sheet, row, cre_col).replace(',', "")) debit = float(parse(sheet, row, deb_col).replace(',', "")) status = parse(sheet, row, stat_col) # cashback is common on most of the parsed data denoting profit if refine('cashback', desc): # second most common data if refine('ADSL', desc): command_execute('cashback', 'NTC', desc, 'adsl', 'Topup', credit, status, date, time) elif refine('prepaid', desc): command_execute('cashback', 'NTC', desc, 'prepaid', 'Topup', credit, status, date, time) elif refine('postpaid', desc): command_execute('cashback', 'NTC', desc, 'postpaid', 'Topup', credit, status, date, time) elif refine('landline', desc): command_execute('cashback', 'NTC', desc, 'landline', 'Topup', credit, status, date, time) elif refine('NT Recharge Card', desc): command_execute('cashback', 'NTC', desc, 'recharge card', 'Recharge Card', credit, status, date, time) elif refine('Ncell', desc): command_execute('cashback', 'NCELL', desc, 'prepaid', 'Topup', credit, status, date, time) elif refine('SIM TV Payment', desc): command_execute('cashback', 'SIMTV', desc, 'simtv', 'Topup', credit, status, date, time) elif refine('Worldlink', desc): command_execute('cashback', 'WORLDLINK', desc, 'worldlink', 'Topup', credit, status, date, time) elif refine('UTL', desc): command_execute('cashback', 'UTL', desc, 'utl', 'recharge card', credit, status, date, time) elif refine('Vianet', desc): command_execute('cashback', 'VIANET', desc, 'vianet', 'Topup', credit, status, date, time) # Greedy Sewa cash back is assumed to be cashback of dish home # recharge card elif refine('eSewa', desc): command_execute('cashback', 'DISHHOME', desc, 'recharge card', 'Topup', credit, status, date, time) elif refine('SUBISU', desc): command_execute('cashback', 'SUBISU', desc, 'subisu', 'Topup', credit, status, date, time) else: command_execute('other', 'other', desc, 'unknown', 'Topup', credit, status, date, time) elif refine('sim commission', desc): command_execute('cashback', 'SIM', desc, 'sim commission', 'Transfer', credit, status, date, time) elif refine('WEBSURFER.COM', desc): command_execute('payment', 'WEBSURFER', desc, 'websurfer', 'Payment', debit, status, date, time) elif refine('Cash Back', desc): if refine('SUBISU', desc): command_execute('cashback', 'SUBISU', desc, 'subisu', 'Payment', credit, status, date, time) else: command_execute('cashback', 'WEBSURFER', desc, 'websurfer', 'Payment', credit, status, date, time) elif refine('topup', desc): if refine('prepaid', desc): command_execute('payment', 'NTC', desc, 'prepaid', 'Topup', debit, status, date, time) elif refine('postpaid', desc): command_execute('payment', 'NTC', desc, 'postpaid', 'Topup', debit, status, date, time) elif refine('adsl', desc): command_execute('payment', 'NTC', desc, 'adsl', 'Topup', debit, status, date, time) elif refine('landline', desc): command_execute('payment', 'NTC', desc, 'landline', 'Topup', debit, status, date, time) elif refine('7190*', desc): command_execute('payment', 'DISHHOME', desc, 'topup', 'Topup', debit, status, date, time) elif refine('1000*', desc): command_execute('payment', 'SIMTV', desc, 'simtv', 'Topup', debit, status, date, time) else: command_execute('other', 'other', desc, 'unknown', 'Topup', debit, status, date, time) elif refine('payment', desc): if refine('980*', desc) or refine('981*', desc): command_execute('payment', 'NCELL', desc, 'ncell', 'Topup', debit, status, date, time) elif refine('subisu', desc): command_execute('payment', 'SUBISU', desc, 'subisu', 'Payment', debit, status, date, time) elif refine('NEA BILL', desc): command_execute('payment', 'NEA', desc, 'nea', 'Payment', debit, status, date, time) else: command_execute('other', 'other', desc, 'unknown', 'Payment', debit, status, date, time) elif refine('paid', desc): if refine('VIANET', desc): command_execute('payment', 'VIANET', desc, 'vianet', 'Payment', debit, status, date, time) else: pass elif refine('Bought recharge', desc): if refine('NTGSM', desc): command_execute('payment', 'NTC', desc, 'ntcgsm', 'Recharge Card', debit, status, date, time) elif refine('DHOME', desc): command_execute('payment', 'DISHHOME', desc, 'recharge card', 'Recharge Card', debit, status, date, time) elif refine('NTCDMA', desc): command_execute('payment', 'NTC', desc, 'ntrecharge', 'Recharge Card', debit, status, date, time) else: command_execute('other', 'other', desc, 'unknown', 'Recharge Card', debit, status, date, time) elif refine('Money Transfer', desc): db.session.add( Transfer('BANK', desc, 'received', 'Transfer', float(credit), status, date, time, desc.replace('Money Transferred from ', ''))) elif refine('Balance Transfer', desc): if refine('to', desc): db.session.add( Transfer('PEER', desc, 'transferred', 'Transfer', float(debit), status, date, time, desc.replace('Balance Transferred to ', ''))) else: db.session.add( Transfer('PEER', desc, 'received', 'Transfer', float(credit), status, date, time, desc.replace('Balance Transferred by ', ''))) else: # saving unknown transaction description to file f = open('unknown.lst', 'r') lines = f.readlines() f.close() with open('unknown.lst', 'a+') as f: if desc + '\n' not in lines: f.write(desc + '\n') lines.append(desc) else: f.flush() if float(credit) != 0: db.session.add( Other('other', desc, ' Unknown Cashback', 'cashback', float(credit), status, date, time)) else: db.session.add( Other('other', desc, ' Unknown Payment', 'payment', float(debit), status, date, time)) row += 1 db.session.commit() return {'result': 'Task Completed'}