def get_active_smart_contract(contract_type=CONST.CONTRACT_TYPE['ETH']): if contract_type == CONST.CONTRACT_TYPE['ETH']: return Contract.find_contract_by_address_and_json( g.PREDICTION_SMART_CONTRACT, g.PREDICTION_JSON) return Contract.find_contract_by_address_and_json( g.ERC20_PREDICTION_SMART_CONTRACT, g.ERC20_PREDICTION_JSON)
def test_create_invalid_contract(self): contract_data = { 'organizer_email': '1234', 'signed_date': INVALID_SIGN_DATE, 'description': 'some description', 'case_number': '345978', 'salesforce_id': '23465789', 'salesforce_case_id': '4680990', } expected_error_dict_messages = { 'link_to_salesforce_case': ['This field cannot be blank.'], 'organizer_account_name': ['This field cannot be blank.'], 'organizer_email': ['Enter a valid email address.'], 'signed_date': [ "'{}' value has an invalid date format. " "It must be in YYYY-MM-DD format.".format(INVALID_SIGN_DATE) ] } contract = Contract(**contract_data) with self.assertRaises(ValidationError) as cm: contract.full_clean() self.assertEqual(expected_error_dict_messages, cm.exception.message_dict)
def delete_account(): logged_user = User.get_by_username(get_jwt_identity()) logged_customer = Customer.get_by_user_id(logged_user.id) customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif( logged_customer.nif) for customer_dwelling_contract in customers_dwellings_contracts: contract_number = customer_dwelling_contract.contract_number Contract.get_by_contract_number(contract_number).delete() logged_user.delete() return "", 200
def setUp(self): # create contract contract = Contract.find_contract_by_id(1) if contract is None: contract = Contract(id=1, contract_name="contract1", contract_address="0x123", json_name="name1") db.session.add(contract) db.session.commit() # create match match = Match.find_match_by_id(1) if match is None: match = Match(id=1) db.session.add(match) db.session.commit() # create user user = User.find_user_with_id(88) if user is None: user = User(id=88) db.session.add(user) db.session.commit() user = User.find_user_with_id(99) if user is None: user = User(id=99) db.session.add(user) db.session.commit() user = User.find_user_with_id(66) if user is None: user = User(id=66) db.session.add(user) db.session.commit() # create outcome outcome = Outcome.find_outcome_by_id(88) if outcome is None: outcome = Outcome(id=88, match_id=1, hid=88, contract_id=contract.id) db.session.add(outcome) db.session.commit() else: outcome.contract_id = contract.id
def counter_contract(contract_id): contract = Contract.query.filter(Contract.id == contract_id).first_or_404() parent = contract if contract.parent_id is None else Contract.query.get(contract.parent_id) role = 'owner' if contract.owner_id == current_user.id else 'cparty' if 'counter' not in contract_transitions[contract.status][role]: flash('This action is not permitted') return redirect(url_for('index')) form = EditProposalForm() form.template_id.choices = [(t.id, t.title) for t in Template.query.order_by('title')] if form.validate_on_submit(): proposal = Contract(template_id=form.template_id.data, params=form.params.data, memo=form.memo.data, status="draft", owner_id=current_user.id, parent_id=parent.id) db.session.add(proposal) db.session.flush() for p in contract.party: party = Party(contract_id=proposal.id, role=p.role, user_id=p.user_id) db.session.add(party) db.session.flush() description = 'Created a counter draft' alog = ActivityLog(contract_id=proposal.id, timestamp=datetime.now(), method='/contract/counter', description=description, user_id=current_user.id) db.session.add(alog) db.session.commit() flash('Draft edited.') return redirect(url_for('index')) form.template_id.data = contract.template_id form.params.data = contract.params return render_template('edit_draft.html', title='Edit a Draft Proposal', form=form, contract_id=contract_id, parties=contract.party, deal=parent.memo)
def add(): form = Contract_add() time = str(datetime.datetime.today()).split(' ')[0].split('-') nav = [ 'Добавить договор', [['Лист неоплативших', '/unpaid'], ['Архив', '/archive'], ['Все договоры', '/all'], ['История', '/history'], ['Удалить контракт', '/delete']] ] history_cancel = History_cancel() history_clear = History_clear() deals = get_non_deleted_deals() if form.validate_on_submit(): contract = Contract(number=form.number.data, is_arch=form.is_arch.data, date=form.date.data, paid=form.paid.data) db.session.add(contract) db.session.commit() # return redirect(url_for('quiz_2')) print(form.data) return render_template('add-user.html', form=form, time=1, nav=nav, history_clear=history_clear, deals=deals, history_cancel=history_cancel)
def contract_create(): try: data = request.get_json() except: return jsonify( {'status': 'error', 'error': 'missing data'} ) if data == None: return jsonify( {'status': 'error', 'error': 'missing data'} ) # query if contract already exists current_app.logger.info('check contract: ' + data['localSymbol']) contract = Contract.query.get(data['localSymbol']) if contract != None: current_app.logger.info('existing contract') else: if 'localSymbol' in data: if data['localSymbol'] == '': return jsonify( {'status': 'error', 'error': 'empty localSymbol'} ) else: contract = Contract( localSymbol=data['localSymbol'] ) else: return jsonify( {'status': 'error', 'error': 'missing localSymbol'} ) if 'strike' in data: if data['strike'] > 0: contract.strike = data['strike'] if 'right' in data: if data['right'] != '': contract.right = data['right'] # no processing std_fields = ['secType', 'symbol', 'currency', 'exchange', 'primaryExchange', 'lastTradeDateOrContractMonth', 'multiplier' ] for std_field in std_fields: if std_field in data: setattr(contract, std_field, data[std_field]) db.session.add(contract) db.session.commit() current_app.logger.info('new contract') return jsonify( {'status': 'ok'} )
def post(self): current_app.logger.info(f'Received POST on contracts') name = request.form.get('name') description = request.form.get('description') amount_due = request.form.get('amount_due') if not amount_due: return dict(error=f'amount_due must be specified'), 400 amount_due = int(amount_due) scm = SCManager(current_web3) # 1000000000000000000 = 1 ether cfg = current_app.config contract_eth_addr = scm.create_contract( amount_due, owner=cfg['ETH_CONTRACT_OWNER'], contract_path=os.path.join( cfg['ETH_CONTRACTS_DIR'], cfg['ETH_CONTRACTS']['payment']['filename']), contract_name=cfg['ETH_CONTRACTS']['payment']['name']) contract = ContractModel(amount_due=amount_due, name=name, description=description, ethereum_addr=contract_eth_addr) try: db.session.add(contract) db.session.commit() except exc.IntegrityError as e: current_app.logger.error(e) db.session.rollback() return dict( error=f'There was an error creating the contract:{e.orig}' ), 400 return dict(contract=contract.to_dict()), 201
def add(): try: uid = int(request.headers['Uid']) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) response_json = [] for item in data: contract = Contract( contract_name=item['contract_name'], contract_address=item['contract_address'], json_name=item['json_name'] ) db.session.add(contract) db.session.flush() response_json.append(contract.to_json()) db.session.commit() return response_ok(response_json) except Exception, ex: db.session.rollback() return response_error(ex.message)
def get_invoices_data(): logged_user = User.get_by_username(get_jwt_identity()) logged_customer = Customer.get_by_user_id(logged_user.id) customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif( logged_customer.nif) data = [] for customer_dwelling_contract in customers_dwellings_contracts: contract_number = customer_dwelling_contract.contract_number contract = Contract.get_by_contract_number(contract_number).to_dict() dwelling = Dwelling.get_by_cups(customer_dwelling_contract.cups) contract["address"] = dwelling.address invoices = __get_invoices(contract_number) contract = {"contract_data": contract, "invoices": invoices} data.append(contract) return jsonify(data)
def init_default_odds(): """ " Admin create odds for market in ETH """ try: data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) for item in data: outcome_id = item['outcome_id'] outcome_data = item['outcomes'] outcome = Outcome.find_outcome_by_id(outcome_id) if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) if outcome.result != CONST.RESULT_TYPE['PENDING']: return response_error(MESSAGE.OUTCOME_HAS_RESULT, CODE.OUTCOME_HAS_RESULT) match = Match.find_match_by_id(outcome.match_id) for o in outcome_data: o['outcome_id'] = outcome_id o['hid'] = outcome.hid o['match_date'] = match.date o['match_name'] = match.name o['outcome_name'] = outcome.name contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) task = Task( task_type=CONST.TASK_TYPE['REAL_BET'], data=json.dumps(o), action=CONST.TASK_ACTION['INIT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.flush() return response_ok() except Exception, ex: db.session.rollback() return response_error(ex.message)
def delete_invoice(invoice_number): invoice = Invoice.get_by_invoice_number(invoice_number) invoice.delete() contract = Contract.get_by_contract_number(invoice.contract_number) invoices = __get_invoices(contract.contract_number) if len(invoices) == 0: logged_user = User.get_by_username(get_jwt_identity()) logged_customer = Customer.get_by_user_id(logged_user.id) nif = logged_customer.nif cus_dwe_con = Customer_Dwelling_Contract \ .get_by_nif_and_contract_number( nif, invoice.contract_number ) cus_dwe_con.delete() contract.delete() return "", 200
def create_draft(): form = CreateProposalForm() form.template_id.choices = [(t.id, t.title) for t in Template.query.order_by('title')] if form.validate_on_submit(): proposal = Contract(template_id=form.template_id.data, memo=form.memo.data, params=form.params.data, status="draft", owner_id=current_user.id) db.session.add(proposal) db.session.flush() for p in json.loads(form.parties.data): party = Party(contract_id=proposal.id, role=p['label'], user_id=p['user_id']) db.session.add(party) db.session.flush() description = 'Creation of a new draft' alog = ActivityLog(contract_id=proposal.id, timestamp=datetime.now(), method='/contract/new', description=description, user_id=current_user.id) db.session.add(alog) db.session.commit() flash('Draft saved.') return redirect(url_for('index')) contacts = User.query.all() return render_template('create_draft.html', title='Create a new Draft Proposal', form=form, contacts=contacts)
def my_bills(): customer = None contracts = None contract_invoices = None if current_user.user_type == 1: customer = Customer.get_by_user_id(current_user.id) customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif( customer.nif) contracts = [] for customer_dwelling_contract in customers_dwellings_contracts: contracts.append( Contract.get_by_contract_number( customer_dwelling_contract.contract_number)) contract_invoices = {} for contract in contracts: contract_invoices[contract] = Invoice.get_by_contract_number( contract.contract_number) return render_template("bills/my_bills.html", contracts=contracts, contract_invoices=contract_invoices)
def test_create_valid_contract(self): contract_data = { 'organizer_account_name': 'Planner Eventos', 'organizer_email': '*****@*****.**', 'signed_date': '2019-09-14', 'description': 'some description', 'case_number': '345978', 'salesforce_id': '23465789', 'salesforce_case_id': '4680990', 'link_to_salesforce_case': 'https://pe33.zzxxzzz.com/5348fObs', } contract = Contract(**contract_data) contract.full_clean() contract_data.pop('signed_date') contract.full_clean()
def showContracts(): date = datetime.today() + timedelta(2) form = NewContract() if form.validate_on_submit(): newContract = Contract(number=form.number.data, sign_date=form.sign_date.data, ground=form.ground.data, company=form.company.data, notes=form.notes.data, customer=form.customer.data, supply=form.supply.data, author=current_user) db.session.add(newContract) db.session.commit() flash('Новый контракт в "{}" добавлен!'.format(form.customer.data)) return redirect(url_for('contract.showContracts')) contracts = Contract.query.order_by(Contract.sign_date.asc()) return render_template("/contract/contracts.html", title='Контракты', contracts=contracts, form=form, date=date)
def can_admin_report_this_outcome(outcome): if outcome is None or outcome.result != CONST.RESULT_TYPE[ 'PENDING'] or outcome.hid is None: return False contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return False # created by admin if outcome.created_user_id is None: return True if is_contract_support_report_for_creator_method( contract.json_name) is False: return False if outcome.match.grant_permission == 1 and \ outcome.match.creator_wallet_address is not None and \ len(outcome.match.creator_wallet_address) > 0: return True return False
def get_stats(): customer = None contracts = None contract_invoices = None if current_user.user_type == 1: customer = Customer.get_by_user_id(current_user.id) customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif( customer.nif) contracts = [] for customer_dwelling_contract in customers_dwellings_contracts: contracts.append( Contract.get_by_contract_number( customer_dwelling_contract.contract_number)) contract_invoices = {} for contract in contracts: year = int(contract.init_date.strftime("%Y")) year_invoices = Invoice.get_by_contract_number( contract.contract_number) total_amounts = [] for invoice in year_invoices: total_amounts.append(invoice.total_amount) contract_invoices[year] = total_amounts return contract_invoices
def init_data_before_test(self): # create token token = Token.find_token_by_id(1) if token is None: token = Token(id=1, name="SHURIKEN", symbol="SHURI", decimal=18) db.session.add(token) db.session.commit() # create contract contract = Contract.find_contract_by_id(1) if contract is None: contract = Contract(id=1, contract_name="contract1", contract_address="0x123", json_name="name1") db.session.add(contract) db.session.commit() # create match match = Match.find_match_by_id(1) if match is None: match = Match(id=1) db.session.add(match) db.session.commit() # create user user = User.find_user_with_id(88) if user is None: user = User(id=88) db.session.add(user) db.session.commit() user = User.find_user_with_id(99) if user is None: user = User(id=99) db.session.add(user) db.session.commit() user = User.find_user_with_id(100) if user is None: user = User(id=100) db.session.add(user) db.session.commit() user = User.find_user_with_id(109) if user is None: user = User(id=109) db.session.add(user) db.session.commit() user = User.find_user_with_id(66) if user is None: user = User(id=66) db.session.add(user) db.session.commit() # create outcome outcome = Outcome.find_outcome_by_id(88) if outcome is None: outcome = Outcome(id=88, match_id=1, hid=88, contract_id=contract.id) db.session.add(outcome) db.session.commit() else: outcome.result = -1 outcome.contract_id = contract.id db.session.commit() # add redeem try: for i in range(1, 3): chars = string.ascii_uppercase + string.ascii_lowercase code = ''.join(random.choice(chars) for _ in range(i)) if Redeem.find_redeem_by_code(code) is None: r = Redeem(code=code) db.session.add(r) db.session.commit() except Exception as ex: db.session.rollback()
def process_bill(): if request.method == "POST": file = request.files["inputFile"] if not file.filename: flash("No se ha seleccionado ningún archivo") return redirect(url_for("customer.upload_bill")) if file and __allowed_file(file.filename): # save file to upload directory with a hash code file_extension = file.filename.rsplit(".", 1)[1].lower() filename = str(uuid.uuid4()) + "." + file_extension bill_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) file.save(bill_path) # information extraction from the bill results = docreco.process_bill(bill_path, file_extension) # return results # Delete the bill uploaded os.remove(bill_path) contract_number = __get_first_value(results["Datos del contrato"]["ReferenciaContrato"]) \ .split('/')[0] \ .split('-')[0] \ .split(' ')[0] if contract_number: contract = Contract.get_by_contract_number(contract_number) if not contract: company_name = __get_first_value( results["Datos de la factura"]["Comercializadora"]) if company_name: trading_company = Company.get_trading_company_by_name( company_name, unidecode.unidecode(company_name)) if trading_company: cif = trading_company.cif else: flash( "No se encuentra la comercializadora ni existe cif en la factura" ) return redirect(url_for("customer.my_bills")) else: flash( "No se encuentra el nombre de la comercializadora en la factura" ) return redirect(url_for("customer.my_bills")) contract_data = __get_contract_data(results) contract = Contract( contract_number=contract_number, contracted_power=contract_data["contracted_power"], toll_access=contract_data["toll_access"], end_date=contract_data["end_date"], CNAE=contract_data["CNAE"], tariff_access=contract_data["tariff_access"], cif=cif) contract.save() else: flash("No se encuentra el número de referencia del contrato") return redirect(url_for("customer.my_bills")) invoice_data = __get_invoice_data(results, contract_number) invoice = Invoice( invoice_number=invoice_data["invoice_number"], contracted_power_amount=invoice_data[ "contracted_power_amount"], consumed_energy_amount=invoice_data["consumed_energy_amount"], issue_date=invoice_data["issue_date"], charge_date=invoice_data["charge_date"], init_date=invoice_data["init_date"], end_date=invoice_data["end_date"], total_amount=invoice_data["total_amount"], contract_reference=invoice_data["contract_reference"], contract_number=invoice_data["contract_number"], document=file.read()) try: invoice.save() except IntegrityError: flash("Esta factura ya está registrada") return redirect(url_for("customer.my_bills")) cups = __get_first_value(results["Datos del contrato"]["CUPS"]) if cups and not Dwelling.get_by_cups(cups): __create_dwelling_with_cups(results, cups) else: cups = __create_dwelling_with_random_cups(results) customer_dwelling_contract = Customer_Dwelling_Contract( nif=Customer.get_by_user_id(current_user.id).nif, cups=cups, contract_number=contract_number) customer_dwelling_contract.save() flash("La factura se ha guardado con éxito") return redirect( url_for("customer.show_bill", invoice_number=invoice.invoice_number)) else: flash( "Los tipos de fichero permitidos son txt, pdf, png, jpg, jpeg, gif" ) return redirect(url_for("customer.upload_bill")) return "Error POST"
def get_consumption_data(): contract_invoices = {} logged_user = User.get_by_username(get_jwt_identity()) if logged_user.user_type == 1: logged_customer = Customer.get_by_user_id(logged_user.id) customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif( logged_customer.nif) contracts = [] for customer_dwelling_contract in customers_dwellings_contracts: contracts.append( Contract.get_by_contract_number( customer_dwelling_contract.contract_number)) for contract in contracts: invoices = Invoice.get_by_contract_number(contract.contract_number) for invoice in invoices: year = int(invoice.init_date.strftime("%Y")) total_amount_list = [0 for _ in range(12)] consumed_energy_list = [0 for _ in range(12)] contracted_power_amount_list = [0 for _ in range(12)] consumed_energy_amount_list = [0 for _ in range(12)] tax_amount_list = [0 for _ in range(12)] if year in contract_invoices: total_amount_list = contract_invoices[year][ "total_amount_list"] consumed_energy_list = contract_invoices[year][ "consumed_energy_list"] contracted_power_amount_list = contract_invoices[year][ "contracted_power_amount_list"] consumed_energy_amount_list = contract_invoices[year][ "consumed_energy_amount_list"] tax_amount_list = contract_invoices[year][ "tax_amount_list"] month = int(invoice.init_date.strftime("%m")) - 1 if invoice.total_amount: total_amount_list[month] = round(invoice.total_amount, 2) else: total_amount_list[month] = 0 if invoice.consumed_energy: consumed_energy_list[month] = invoice.consumed_energy else: consumed_energy_list[month] = 0 if invoice.contracted_power_amount: contracted_power_amount_list[month] = round( invoice.contracted_power_amount, 2) else: contracted_power_amount_list[month] = 0 if invoice.consumed_energy_amount: consumed_energy_amount_list[month] = round( invoice.consumed_energy_amount, 2) else: consumed_energy_amount_list[month] = 0 if invoice.tax_amount: tax_amount_list[month] = round(invoice.tax_amount, 2) else: tax_amount_list[month] = 0 contract_invoices[year] = { "total_amount_list": total_amount_list, "consumed_energy_list": consumed_energy_list, "contracted_power_amount_list": contracted_power_amount_list, "consumed_energy_amount_list": consumed_energy_amount_list, "tax_amount_list": tax_amount_list } else: return "No tienes permiso", 403 return contract_invoices
def report_match(match_id): """ Report match by match_id: "" If report is 'PROCESSING' status, tnx's action is 'REPORT' "" If report is 'DISPUTED' status, tnx's action is 'RESOLVE' "" "" Input: "" match_id """ try: t = datetime.now().timetuple() seconds = local_to_utc(t) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) match = db.session.query(Match).filter(\ Match.date < seconds, Match.id == match_id).first() if match is not None: result = data['result'] if result is None: return response_error(MESSAGE.MATCH_RESULT_EMPTY) disputed = False for item in result: if 'side' not in item: return response_error(MESSAGE.OUTCOME_INVALID_RESULT) if 'outcome_id' not in item: return response_error(MESSAGE.OUTCOME_INVALID) outcome = db.session.query(Outcome).filter(Outcome.id==item['outcome_id'], Outcome.match_id==match.id).first() if outcome is not None: message, code = match_bl.is_able_to_set_result_for_outcome(outcome) if message is not None and code is not None: return message, code if outcome.result == CONST.RESULT_TYPE['DISPUTED']: disputed = True outcome.result = CONST.RESULT_TYPE['PROCESSING'] else: return response_error(MESSAGE.OUTCOME_INVALID) contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) report = {} report['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + ('resolve' if disputed else 'report') + str(outcome.id) + '_' + str(item['side']) report['hid'] = outcome.hid report['outcome_id'] = outcome.id report['outcome_result'] = item['side'] report['creator_wallet_address'] = match.creator_wallet_address report['grant_permission'] = match.grant_permission task = Task( task_type=CONST.TASK_TYPE['REAL_BET'], data=json.dumps(report), action=CONST.TASK_ACTION['RESOLVE' if disputed else 'REPORT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.flush() db.session.commit() return response_ok(match.to_json()) else: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) except Exception, ex: db.session.rollback() return response_error(ex.message)
def process_bill(): try: file = request.files["file"] except BadRequestKeyError: return { "message": "No se ha seleccionado ningún archivo", "type": "error" }, 200 if not __allowed_file(file.filename): return { "message": "Los tipos de fichero permitidos son txt, pdf, png, jpg, jpeg, gif", "type": "error" }, 200 # save file to upload directory with a hash code file_extension = file.filename.rsplit(".", 1)[1].lower() filename = str(uuid.uuid4()) + "." + file_extension bill_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) file.save(bill_path) # information extraction from the bill results = docreco.process_bill(bill_path, file_extension) # Delete the bill uploaded os.remove(bill_path) contract_number = __get_first_value( results["Datos del contrato"]["ReferenciaContrato"]).split( '/')[0].split('-')[0].split(' ')[0] if contract_number: contract = Contract.get_by_contract_number(contract_number) if not contract: cif = __get_first_value(results["Datos de la factura"]["CIF"]) if cif: trading_company = Company.get_by_cif(cif) if not trading_company: return { "message": "No se encuentra la comercializadora", "type": "error" }, 200 else: company_name = __get_first_value( results["Datos de la factura"]["Comercializadora"]) if company_name: trading_company = Company.get_trading_company_by_name( company_name, unidecode.unidecode(company_name)) if trading_company: cif = trading_company.cif else: return { "message": "No se encuentra la comercializadora ni el cif en la factura", "type": "error" }, 200 else: return { "message": "No se encuentra el nombre de la comercializadora en la factura", "type": "error" }, 200 contract_data = __get_contract_data(results) contract = Contract( contract_number=contract_number, contracted_power=contract_data["contracted_power"], toll_access=contract_data["toll_access"], end_date=contract_data["end_date"], CNAE=contract_data["CNAE"], tariff_access=contract_data["tariff_access"], cif=cif) contract.save() else: return { "message": "No se encuentra el número de referencia del contrato", "type": "error" }, 200 invoice_data = __get_invoice_data(results, contract_number) invoice = Invoice( invoice_number=invoice_data["invoice_number"], contracted_power_amount=invoice_data["contracted_power_amount"], consumed_energy_amount=invoice_data["consumed_energy_amount"], issue_date=invoice_data["issue_date"], charge_date=invoice_data["charge_date"], init_date=invoice_data["init_date"], end_date=invoice_data["end_date"], total_amount=invoice_data["total_amount"], contract_reference=invoice_data["contract_reference"], contract_number=invoice_data["contract_number"], document=file.read()) try: invoice.save() except IntegrityError: return { "message": "Esta factura ya está registrada", "type": "error" }, 200 cups = __get_first_value(results["Datos del contrato"]["CUPS"]) if cups: if not Dwelling.get_by_cups(cups): __create_dwelling_with_cups(results, cups) else: cups = __create_dwelling_with_random_cups(results) logged_user = User.get_by_username(get_jwt_identity()) logged_customer = Customer.get_by_user_id(logged_user.id) nif = logged_customer.nif if not Customer_Dwelling_Contract.get_by_nif_and_contract_number( nif, contract_number): customer_dwelling_contract = Customer_Dwelling_Contract( nif=nif, cups=cups, contract_number=contract_number) try: customer_dwelling_contract.save() except IntegrityError: pass return { "message": "La factura se ha guardado con éxito", "type": "success" }, 200
def submit(request): contractname = request.POST['contractname'] a = request.POST['a'] b = request.POST['b'] c = request.POST['c'] d = request.POST['d'] e = request.POST['e'] f = request.POST['f'] g = request.POST['g'] h = request.POST['h'] i = request.POST['i'] j = request.POST['j'] k = request.POST['k'] l = request.POST['l'] m = request.POST['m'] n = request.POST['n'] o = request.POST['o'] time_format = time.strftime('%Y-%m-%d_%H%M%S', time.localtime(time.time())) file = open('LCR_' + time_format + '.txt', 'wt') file.write('Letter of Credit' + '\n' '1.Advising bank:' + a + '\n' '2.Credit No.:' + b + '\n' '3.Beneficiary:' + c + '\n' '4.Applicant:' + d + '\n' '5.L/C Amount and Tolerance:' + e + '\n' '6.Type:' + f + '\n' '7.Partial shipment:' + g + '\n' '8.Transshipment:' + h + '\n' '9.Trnasport mode:' + i + '\n' '10.Loading(shipment from):' + j + '\n' '11.Discharging(shipment to):' + k + '\n' '12.Latest shipment date:' + l + '\n' '13.All banking charges:' + m + '\n' '14.Confirmation:' + n + '\n' '15.T/T reimbursement:' + o + '\n') file.close() file = open('LCR_' + time_format + '.txt', 'rb') data = file.read() # hasher = hashlib.md5() # with open('myfile.jpg', 'rb') as afile: # buf = afile.read() # hasher.update(buf) # print(hasher.hexdigest()) # a = 'MD5 : ' + hashlib.md5(data).hexdigest() # b = 'SHA-1 : ' + hashlib.sha1(data).hexdigest() hash = 'SHA-256 : ' + hashlib.sha256(data).hexdigest() file.close() # 데이터 저장 contract = Contract(contractname=contractname, sha256=hash, filename='LCR_' + time_format + '.txt') # 로그인한 사용자 정보를 Contract에 같이 저장 user_id = request.session['user_id'] member = Member.objects.get(user_id=user_id) contract.owner = member contract.save() return redirect('ing')
def create(): try: data = request.get_json() except: return jsonify({'status': 'error', 'error': 'missing data'}) if data == None: return jsonify({'status': 'error', 'error': 'missing data'}) # query if contract already exists current_app.logger.info('check contract: ' + data['localSymbol']) contract = Contract.query.get(data['localSymbol']) if contract != None: current_app.logger.info('existing contract') else: if data['localSymbol'] == '': localSymbol = data['symbol'] else: localSymbol = data['localSymbol'] if data['strike'] > 0: strike = data['strike'] else: strike = None if data['right'] != '': right = data['right'] else: right = None contract = Contract( secType=data['secType'], localSymbol=localSymbol, symbol=data['symbol'], currency=data['currency'], exchange=data['exchange'], primaryExchange=data['primaryExchange'], lastTradeDateOrContractMonth=data[ 'lastTradeDateOrContractMonth'], #datetime multiplier=data['multiplier'], strike=strike, right=right) db.session.add(contract) db.session.commit() current_app.logger.info('new contract') # insert executions current_app.logger.info('check execution: ' + data['execId']) execution = Execution.query.get(data['execId']) if execution != None: current_app.logger.info('existing execution') else: shares = abs(data['shares']) cumQty = abs(data['cumQty']) if data['side'][0].upper() == 'B': pass elif data['side'][0].upper() == 'S': shares = -shares cumQty = -cumQty execution = Execution( execId=data['execId'], orderId=data['orderId'], asset=contract, # object time=datetime.strptime(data['time'], '%Y%m%d %H:%M:%S'), # 20180604 13:32:52 acctNumber=data['acctNumber'], exchange=data['exchange'], side=data['side'], shares=shares, cumQty=cumQty, price=data['price'], avgPrice=data['avgPrice'], permId=data['permId']) db.session.add(execution) db.session.commit() current_app.logger.info('new execution') return jsonify({ 'status': 'ok', 'inputData': data, 'contract': { 'localSymbol': contract.localSymbol }, 'order': { 'orderId': execution.orderId }, 'execution': { 'execId': execution.execId } })
def add_fake_data(number_users, number_contracts): """Adds fake data to the database.""" User.generate_fake(count=number_users) Contract.generate_fake(count=number_contracts)
def init(): """ " User plays bet in binary event. """ try: from_request = request.headers.get('Request-From', 'mobile') uid = int(request.headers['Uid']) chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY'])) user = User.find_user_with_id(uid) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) hs_type = data.get('type', -1) extra_data = data.get('extra_data', '') description = data.get('description', '') outcome_id = data.get('outcome_id', -1) match_id = data.get('match_id', -1) odds = Decimal(data.get('odds', '2')).quantize(Decimal('.1'), rounding=ROUND_HALF_DOWN) amount = Decimal(data.get('amount')) currency = data.get('currency', 'ETH') side = int(data.get('side', CONST.SIDE_TYPE['SUPPORT'])) chain_id = int(data.get('chain_id', CONST.BLOCKCHAIN_NETWORK['RINKEBY'])) from_address = data.get('from_address', '') free_bet = data.get('free_bet', 0) print '-------- DEBUG INIT -------' print '-------- amount = {}, type = {}, request = {} -------'.format(amount, type(amount), data.get('amount')) if hs_type != CONST.Handshake['INDUSTRIES_BETTING']: return response_error(MESSAGE.HANDSHAKE_INVALID_BETTING_TYPE, CODE.HANDSHAKE_INVALID_BETTING_TYPE) if len(from_address) < 40: return response_error(MESSAGE.INVALID_ADDRESS, CODE.INVALID_ADDRESS) # check valid outcome or not outcome = None if match_id == -1: outcome = Outcome.find_outcome_by_id(outcome_id) else: match = Match.find_match_by_id(match_id) if match is not None and len(match.outcomes.all()) > 0: outcome = match.outcomes[0] if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) if outcome.result != CONST.RESULT_TYPE['PENDING']: return response_error(MESSAGE.OUTCOME_HAS_RESULT, CODE.OUTCOME_HAS_RESULT) outcome_id = outcome.id # make sure user cannot call free-bet in ERC20 if free_bet == 1: token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_CREATE_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_CREATE_FREEBET_IN_ERC20) if odds <= 1: return response_error(MESSAGE.INVALID_ODDS, CODE.INVALID_ODDS) contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) # add to history history = History( chain_id=chain_id, description=description, free_bet=free_bet, from_address=from_address, contract_address=contract.contract_address, contract_json=contract.json_name, odds=odds, amount=amount, currency=currency, from_request=from_request, side=side, user_id=uid, outcome_id=outcome_id ) db.session.add(history) db.session.flush() # filter all handshakes which able be to match first handshakes = handshake_bl.find_all_matched_handshakes(side, odds, outcome_id, amount, uid) arr_hs = [] if len(handshakes) == 0: handshake = Handshake( hs_type=hs_type, extra_data=extra_data, description=description, chain_id=chain_id, user_id=user.id, outcome_id=outcome_id, odds=odds, amount=amount, currency=currency, side=side, remaining_amount=amount, from_address=from_address, free_bet=free_bet, contract_address=contract.contract_address, contract_json=contract.json_name, from_request=from_request, history_id=history.id ) db.session.add(handshake) db.session.commit() update_feed.delay(handshake.id) # response data hs_json = handshake.to_json() hs_json['maker_address'] = handshake.from_address hs_json['maker_odds'] = handshake.odds hs_json['hid'] = outcome.hid hs_json['type'] = 'init' hs_json['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 'm' + str(handshake.id) arr_hs.append(hs_json) logfile.debug("Uid -> {}, json --> {}".format(uid, arr_hs)) else: shaker_amount = amount hs_feed = [] sk_feed = [] for handshake in handshakes: if shaker_amount.quantize(Decimal('.00000000000000001'), rounding=ROUND_DOWN) <= 0: break handshake.shake_count += 1 handshake_win_value = handshake.remaining_amount*handshake.odds shaker_win_value = shaker_amount*odds subtracted_amount_for_shaker = 0 subtracted_amount_for_handshake = 0 if is_equal(handshake_win_value, shaker_win_value): subtracted_amount_for_shaker = shaker_amount subtracted_amount_for_handshake = handshake.remaining_amount elif handshake_win_value >= shaker_win_value: subtracted_amount_for_shaker = shaker_amount subtracted_amount_for_handshake = shaker_win_value - subtracted_amount_for_shaker else: subtracted_amount_for_handshake = handshake.remaining_amount subtracted_amount_for_shaker = handshake_win_value - subtracted_amount_for_handshake handshake.remaining_amount -= subtracted_amount_for_handshake shaker_amount -= subtracted_amount_for_shaker db.session.merge(handshake) o = Outcome.find_outcome_by_id(handshake.outcome_id) if o is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) c = Contract.find_contract_by_id(o.contract_id) if c is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) # create shaker shaker = Shaker( shaker_id=user.id, amount=subtracted_amount_for_shaker, currency=currency, odds=odds, side=side, handshake_id=handshake.id, from_address=from_address, chain_id=chain_id, free_bet=free_bet, contract_address=c.contract_address, contract_json=c.json_name, from_request=from_request, history_id=history.id ) db.session.add(shaker) db.session.flush() sk_feed.append(shaker) shaker_json = shaker.to_json() shaker_json['maker_address'] = handshake.from_address shaker_json['maker_odds'] = handshake.odds shaker_json['hid'] = outcome.hid shaker_json['type'] = 'shake' shaker_json['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 's' + str(shaker.id) arr_hs.append(shaker_json) if shaker_amount.quantize(Decimal('.00000000000000001'), rounding=ROUND_DOWN) > Decimal(CONST.CRYPTOSIGN_MINIMUM_MONEY): handshake = Handshake( hs_type=hs_type, extra_data=extra_data, description=description, chain_id=chain_id, user_id=user.id, outcome_id=outcome_id, odds=odds, amount=shaker_amount, currency=currency, side=side, remaining_amount=shaker_amount, from_address=from_address, free_bet=free_bet, contract_address=contract.contract_address, contract_json=contract.json_name, from_request=from_request, history_id=history.id ) db.session.add(handshake) db.session.flush() hs_feed.append(handshake) hs_json = handshake.to_json() hs_json['maker_address'] = handshake.from_address hs_json['maker_odds'] = handshake.odds hs_json['hid'] = outcome.hid hs_json['type'] = 'init' hs_json['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 'm' + str(handshake.id) arr_hs.append(hs_json) db.session.commit() logfile.debug("Uid -> {}, json --> {}".format(uid, arr_hs)) handshake_bl.update_handshakes_feed(hs_feed, sk_feed) # make response response = { "handshakes": arr_hs, "total_bets": handshake_bl.get_total_real_bets() } return response_ok(response) except Exception, ex: db.session.rollback() return response_error(ex.message)
def create_free_bet(): """ " Create a free-bet in ETH """ try: setting = Setting.find_setting_by_name(CONST.SETTING_TYPE['FREE_BET']) if setting is not None and setting.status == 0: return response_error(MESSAGE.FREE_BET_UNABLE, CODE.FREE_BET_UNABLE) uid = int(request.headers['Uid']) chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY'])) user = User.find_user_with_id(uid) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) redeem = data.get('redeem', '') match_id = data.get('match_id', -1) odds = Decimal(data.get('odds', Decimal('2'))) amount = Decimal(CONST.CRYPTOSIGN_FREE_BET_AMOUNT) side = int(data.get('side', CONST.SIDE_TYPE['SUPPORT'])) from_address = data.get('from_address', '') # check valid address if len(from_address) < 40: return response_error(MESSAGE.INVALID_ADDRESS, CODE.INVALID_ADDRESS) # check valid redeem or not r = Redeem.find_redeem_by_code_and_user(redeem, uid) if r is None: return response_error(MESSAGE.REDEEM_NOT_FOUND, CODE.REDEEM_NOT_FOUND) else: if r.used_user > 0: return response_error(MESSAGE.REDEEM_INVALID, CODE.REDEEM_INVALID) r.used_user = uid db.session.flush() outcome_id = data.get('outcome_id') outcome = None if match_id == -1: outcome = Outcome.find_outcome_by_id(outcome_id) if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) elif outcome.result != -1: return response_error(MESSAGE.OUTCOME_HAS_RESULT, CODE.OUTCOME_HAS_RESULT) else: match = Match.find_match_by_id(match_id) if match is not None and len(match.outcomes.all()) > 0: outcome = match.outcomes[0] else: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) # check erc20 token or not token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_CREATE_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_CREATE_FREEBET_IN_ERC20) contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) match = Match.find_match_by_id(outcome.match_id) data['hid'] = outcome.hid data['outcome_name'] = outcome.name data['match_date'] = match.date data['match_name'] = match.name data['uid'] = uid data['payload'] = user.payload data['free_bet'] = 1 data['amount'] = CONST.CRYPTOSIGN_FREE_BET_AMOUNT user.free_bet += 1 task = Task( task_type=CONST.TASK_TYPE['FREE_BET'], data=json.dumps(data), action=CONST.TASK_ACTION['INIT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.commit() # this is for frontend handshakes = handshake_bl.find_all_matched_handshakes(side, odds, outcome.id, amount, uid) response = {} if len(handshakes) == 0: response['match'] = 0 else: response['match'] = 1 return response_ok(response) except Exception, ex: db.session.rollback() return response_error(ex.message)
def uninit_free_bet(handshake_id): """ " Uninit free-bet in ETH """ try: uid = int(request.headers['Uid']) chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY'])) user = User.find_user_with_id(uid) handshake = db.session.query(Handshake).filter(and_(Handshake.id==handshake_id, Handshake.chain_id==chain_id, Handshake.user_id==uid, Handshake.free_bet==1)).first() if handshake is not None and \ (handshake.status == CONST.Handshake['STATUS_INITED'] or \ handshake.status == CONST.Handshake['STATUS_MAKER_SHOULD_UNINIT']): if handshake_bl.can_uninit(handshake) == False: return response_error(MESSAGE.HANDSHAKE_CANNOT_UNINIT, CODE.HANDSHAKE_CANNOT_UNINIT) else: outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) else: # check erc20 token or not token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_UNINIT_FREE_BET_IN_ERC20, CODE.HANDSHAKE_CANNOT_UNINIT_FREE_BET_IN_ERC20) contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) handshake.status = CONST.Handshake['STATUS_MAKER_UNINIT_PENDING'] db.session.flush() data = { 'hid': outcome.hid, 'side': handshake.side, 'odds': handshake.odds, 'maker': handshake.from_address, 'value': handshake.amount, 'offchain': CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + 'm{}'.format(handshake.id), 'uid': uid, 'payload': user.payload, 'free_bet': 1 } task = Task( task_type=CONST.TASK_TYPE['FREE_BET'], data=json.dumps(data, use_decimal=True), action=CONST.TASK_ACTION['UNINIT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.commit() update_feed.delay(handshake.id) return response_ok(handshake.to_json()) else: return response_error(MESSAGE.HANDSHAKE_NOT_FOUND, CODE.HANDSHAKE_NOT_FOUND) except Exception, ex: db.session.rollback() return response_error(ex.message)
def collect_free_bet(): """ " Collect free-bet in ETH """ try: uid = int(request.headers['Uid']) chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY'])) user = User.find_user_with_id(uid) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) offchain = data.get('offchain', '') if len(offchain) == 0: return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN) h = [] s = [] offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') if 's' in offchain: offchain = int(offchain.replace('s', '')) shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first() msg = handshake_bl.can_withdraw(handshake=None, shaker=shaker) if len(msg) != 0: return response_error(msg, CODE.CANNOT_WITHDRAW) hs = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(hs.outcome_id) # check erc20 token or not token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20) h = db.session.query(Handshake).filter(and_(Handshake.user_id==user.id, Handshake.outcome_id==hs.outcome_id, Handshake.side==shaker.side, Handshake.status==HandshakeStatus['STATUS_INITED'])).all() s = db.session.query(Shaker).filter(and_(Shaker.shaker_id==user.id, Shaker.side==shaker.side, Shaker.status==HandshakeStatus['STATUS_SHAKER_SHAKED'], Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==hs.outcome_id)))).all() data['hid'] = outcome.hid data['winner'] = shaker.from_address else: offchain = int(offchain.replace('m', '')) handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first() msg = handshake_bl.can_withdraw(handshake) if len(msg) != 0: return response_error(msg, CODE.CANNOT_WITHDRAW) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) # check erc20 token or not token = Token.find_token_by_id(outcome.token_id) if token is not None: return response_error(MESSAGE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20, CODE.HANDSHAKE_CANNOT_WITHDRAW_FREEBET_IN_ERC20) h = db.session.query(Handshake).filter(and_(Handshake.user_id==user.id, Handshake.outcome_id==handshake.outcome_id, Handshake.side==handshake.side, Handshake.status==HandshakeStatus['STATUS_INITED'])).all() s = db.session.query(Shaker).filter(and_(Shaker.shaker_id==user.id, Shaker.side==handshake.side, Shaker.status==HandshakeStatus['STATUS_SHAKER_SHAKED'], Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==handshake.outcome_id)))).all() data['hid'] = outcome.hid data['winner'] = handshake.from_address handshakes = [] shakers = [] response = {} # update status for hs in h: hs.status = HandshakeStatus['STATUS_COLLECT_PENDING'] db.session.flush() handshakes.append(hs) if hs.id == offchain: response = hs.to_json() for sk in s: sk.status = HandshakeStatus['STATUS_COLLECT_PENDING'] db.session.flush() shakers.append(sk) if sk.id == offchain: response = sk.to_json() data['uid'] = uid data['payload'] = user.payload data['free_bet'] = 1 contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) # add task task = Task( task_type=CONST.TASK_TYPE['FREE_BET'], data=json.dumps(data), action=CONST.TASK_ACTION['COLLECT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.commit() handshake_bl.update_handshakes_feed(handshakes, shakers) return response_ok(response) except Exception, ex: db.session.rollback() return response_error(ex.message)