def refund(): """ " Refund real bet: " This step make sure user's feed will update pending status """ try: uid = int(request.headers['Uid']) 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) offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') outcome = None if 'm' in offchain: offchain = int(offchain.replace('m', '')) handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first() if handshake is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) elif 's' in offchain: offchain = int(offchain.replace('s', '')) shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first() if shaker is None: return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND) handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) handshakes = db.session.query(Handshake).filter(and_(Handshake.status.in_([HandshakeStatus['STATUS_INITED'], HandshakeStatus['STATUS_RESOLVED']]), Handshake.user_id==user.id, Handshake.outcome_id==outcome.id)).all() shakers = db.session.query(Shaker).filter(and_(Shaker.status.in_([HandshakeStatus['STATUS_SHAKER_SHAKED'], HandshakeStatus['STATUS_RESOLVED']]), Shaker.shaker_id==user.id, Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==outcome.id)))).all() for h in handshakes: h.bk_status = h.status h.status = HandshakeStatus['STATUS_REFUND_PENDING'] db.session.merge(h) for s in shakers: s.bk_status = s.status s.status = HandshakeStatus['STATUS_REFUND_PENDING'] db.session.merge(s) db.session.commit() handshake_bl.update_handshakes_feed(handshakes, shakers) return response_ok() except Exception, ex: db.session.rollback() return response_error(ex.message)
def can_withdraw(handshake, shaker=None): outcome = None result = None if shaker is None: if handshake is not None: if handshake.status == HandshakeStatus[ 'STATUS_INITED'] or handshake.status == HandshakeStatus[ 'STATUS_RESOLVED']: outcome = Outcome.find_outcome_by_id(handshake.outcome_id) result = handshake.side else: return MESSAGE.CANNOT_WITHDRAW else: return MESSAGE.CANNOT_WITHDRAW else: if shaker.status == HandshakeStatus[ 'STATUS_SHAKER_SHAKED'] or shaker.status == HandshakeStatus[ 'STATUS_RESOLVED']: handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) result = shaker.side else: return MESSAGE.CANNOT_WITHDRAW if outcome is not None: if outcome.result != result: return MESSAGE.HANDSHAKE_NOT_THE_SAME_RESULT if match_bl.is_exceed_dispute_time(outcome.match_id) == False: return MESSAGE.HANDSHAKE_WITHDRAW_AFTER_DISPUTE else: return MESSAGE.OUTCOME_INVALID return ''
def test_has_result_outcome(self): self.clear_data_before_test() o = Outcome() db.session.add(o) db.session.commit() actual = outcome_bl.has_result(o) expected = False self.assertEqual(actual, expected) o.result = 4 db.session.merge(o) db.session.commit() actual = outcome_bl.has_result(o) expected = False self.assertEqual(actual, expected) o.result = 1 db.session.merge(o) db.session.commit() actual = outcome_bl.has_result(o) expected = True self.assertEqual(actual, expected)
def test_build_submission_dict(self): o1 = Outcome(id=1, title='Test Outcome', course_id=39775, outcome_id=123) a1 = Assignment(id=190128, title='Test Assignment', course_id=39775) db.session.add_all([o1, a1]) db.session.commit() o1.align(a1) db.session.commit() course = self.canvas.get_course(self.course_id) enrollments = [31874, 31875] assignment_list = [190128] submissions = [] all_submissions = course.get_multiple_submissions( assignment_ids=assignment_list, student_ids=enrollments, include=("user", "assignment"), grouped=True, ) for student in all_submissions: items = student.submissions for item in items: submissions.append( Assignments.process_enrollment_submissions(item)) self.assertIsInstance(submissions, list)
def setUpModule(): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all() o1 = Outcome(title='Some outcome 1', course_id=999, outcome_id=123) o2 = Outcome(title='Some outcome 1', course_id=888, outcome_id=123) a1 = Assignment(title="Some assignment", course_id=999, id=111) db.session.add_all([o1, o2, a1]) db.session.commit()
def add(match_id): """ "" Add outcome to match "" Inputs: "" match_id "" Outputs: "" match json with contract address for frontend """ try: from_request = request.headers.get('Request-From', 'mobile') uid = int(request.headers['Uid']) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) match = Match.find_match_by_id(match_id) if match is None: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) contract = contract_bl.get_active_smart_contract() if contract is None: return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION) outcomes = [] response_json = [] for item in data: outcome = Outcome(name=item['name'], match_id=match_id, modified_user_id=uid, created_user_id=uid, contract_id=contract.id, from_request=from_request, approved=CONST.OUTCOME_STATUS['PENDING']) db.session.add(outcome) db.session.flush() outcomes.append(outcome) outcome_json = outcome.to_json() # Return match_id for client add outcome outcome_json["match_id"] = match_id outcome_json["contract"] = contract.to_json() response_json.append(outcome_json) db.session.add_all(outcomes) db.session.commit() return response_ok(response_json) except Exception, ex: db.session.rollback() return response_error(ex.message)
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 setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all() o2 = Outcome(outcome_id=123, course_id=999, title="Some Outcome") a2 = Assignment(id=999, course_id=999, title="Some Assignment") db.session.add_all([o2, a2]) db.session.commit()
def test_is_able_to_create_new_task_passed_if_there_is_no_outcome_in_tasks( self): self.clear_data_before_test() outcome = Outcome(id=10, match_id=1, hid=88) db.session.add(outcome) db.session.commit() task = Task(data=json.dumps({ "odds": "2.7", "match_date": 1530767741, "match_name": "1 vs 2", "outcome_name": "Belgium wins (Handicap 0:2)", "hid": 17, "outcome_id": 122, "side": 2 }), action='INIT', date_created=datetime.now(), date_modified=datetime.now(), contract_address=app.config['PREDICTION_SMART_CONTRACT'], contract_json=app.config['PREDICTION_JSON']) db.session.add(task) db.session.commit() actual = task_bl.is_able_to_create_new_task(outcome.id) expected = True self.assertEqual(actual, expected)
def save_refund_state_for_all(user_id, outcome_id): outcome = Outcome.find_outcome_by_id(outcome_id) handshakes = db.session.query(Handshake).filter( and_( Handshake.status.in_([ HandshakeStatus['STATUS_REFUND_PENDING'], HandshakeStatus['STATUS_INITED'] ]), Handshake.user_id == user_id, Handshake.outcome_id == outcome_id)).all() shakers = db.session.query(Shaker).filter( and_( Shaker.status == HandshakeStatus['STATUS_REFUND_PENDING'], Shaker.shaker_id == user_id, Shaker.handshake_id.in_( db.session.query(Handshake.id).filter( Handshake.outcome_id == outcome_id)))).all() for hs in handshakes: hs.bk_status = hs.status hs.status = HandshakeStatus['STATUS_REFUNDED'] db.session.merge(hs) for sk in shakers: sk.bk_status = sk.status sk.status = HandshakeStatus['STATUS_REFUNDED'] db.session.merge(sk) return handshakes, shakers
def update_amount_for_outcome(outcome_id, user_id, side, outcome_result): side_arr = ', '.join( [str(x) for x in ([side] if outcome_result != 3 else [1, 2])]) outcome = Outcome.find_outcome_by_id(outcome_id) dispute_amount_query_m = "(SELECT SUM(amount) AS total FROM (SELECT amount FROM handshake WHERE handshake.outcome_id = {} AND handshake.side IN ({}) AND handshake.user_id = {} AND handshake.status IN ({},{},{})) AS tmp) AS total_dispute_amount_m".format( outcome.id, side_arr, user_id, HandshakeStatus['STATUS_USER_DISPUTED'], HandshakeStatus['STATUS_DISPUTED'], HandshakeStatus['STATUS_DISPUTE_PENDING']) dispute_amount_query_s = '(SELECT SUM(total_amount) AS total FROM (SELECT shaker.amount as total_amount FROM handshake JOIN shaker ON handshake.id = shaker.handshake_id WHERE handshake.outcome_id = {} AND shaker.side IN ({}) AND shaker.shaker_id = {} AND shaker.status IN ({},{},{})) AS tmp) AS total_dispute_amount_s'.format( outcome.id, side_arr, user_id, HandshakeStatus['STATUS_USER_DISPUTED'], HandshakeStatus['STATUS_DISPUTED'], HandshakeStatus['STATUS_DISPUTE_PENDING']) amount_query_m = '(SELECT SUM(amount) AS total FROM (SELECT amount FROM handshake WHERE handshake.outcome_id = {} AND handshake.side IN ({})) AS tmp) AS total_amount_m'.format( outcome.id, side_arr) amount_query_s = '(SELECT SUM(total_amount) AS total FROM (SELECT shaker.amount as total_amount FROM handshake JOIN shaker ON handshake.id = shaker.handshake_id WHERE handshake.outcome_id = {} AND shaker.side IN ({})) AS tmp) AS total_amount_s'.format( outcome.id, side_arr) total_amount = db.engine.execute('SELECT {}, {}, {}, {}'.format( dispute_amount_query_m, dispute_amount_query_s, amount_query_m, amount_query_s)).first() outcome.total_dispute_amount = ( total_amount['total_dispute_amount_m'] if total_amount['total_dispute_amount_m'] is not None else 0) + (total_amount['total_dispute_amount_s'] if total_amount['total_dispute_amount_s'] is not None else 0) outcome.total_amount = (total_amount['total_amount_m'] if total_amount['total_amount_m'] is not None else 0) + (total_amount['total_amount_s'] if total_amount['total_amount_s'] is not None else 0) db.session.flush()
def report_match(match_id): """ "" report: report outcomes "" input: "" match_id """ try: uid = int(request.headers['Uid']) data = request.json response = [] if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) match = Match.find_match_by_id(match_id) if match is not None: result = data['result'] if result is None: return response_error(MESSAGE.MATCH_RESULT_EMPTY, CODE.MATCH_RESULT_EMPTY) if not match_bl.is_exceed_closing_time(match.id): return response_error(MESSAGE.MATCH_CANNOT_SET_RESULT, CODE.MATCH_CANNOT_SET_RESULT) for item in result: if 'side' not in item: return response_error(MESSAGE.OUTCOME_INVALID_RESULT, CODE.OUTCOME_INVALID_RESULT) if 'outcome_id' not in item: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) outcome = Outcome.find_outcome_by_id(item['outcome_id']) if outcome is not None and outcome.created_user_id == uid: 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 outcome.result = CONST.RESULT_TYPE['PROCESSING'] outcome_json = outcome.to_json() response.append(outcome_json) else: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) return response_ok(response) else: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) except Exception, ex: return response_error(ex.message)
def get_text_list_need_approve(self): t = datetime.now().timetuple() seconds = local_to_utc(t) items = [] match = Match(public=1, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() items.append(match) outcome = Outcome(match_id=match.id, name="test approve", approved=-1) db.session.add(outcome) items.append(outcome) db.session.commit() match1 = Match(public=0, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match1) db.session.commit() items.append(match1) outcome1 = Outcome(match_id=match1.id, name="test approve", approved=-1) db.session.add(outcome1) db.session.commit() items.append(outcome1) text = match_bl.get_text_list_need_approve() for item in items: db.session.delete(item) db.session.commit() self.assertTrue(text != '')
def test_generate_link(self): Uid = 66 # create outcome outcome = Outcome.find_outcome_by_id(88) if outcome is None: outcome = Outcome(id=88, match_id=1, name="1", hid=88, created_user_id=Uid) db.session.add(outcome) db.session.commit() else: outcome.match_id = 1 outcome.name = "1" outcome.created_user_id = Uid db.session.commit() with self.client: params = {"match_id": 1} response = self.client.post('/outcome/generate-link', data=json.dumps(params), content_type='application/json', headers={ "Uid": "{}".format(Uid), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) data_json = data['data'] self.assertTrue(data['status'] == 1) self.assertTrue(data_json['slug'] == '?match=1&ref=66')
def test_align_assignment_to_outcome(self): o3 = Outcome(outcome_id=1, course_id=999, title="Test Outcome 1") a1 = Assignment(title='Some Assignment', course_id=999, id=1) db.session.add_all([o3, a1]) db.session.commit() outcome_id = 1 assignment_id = 1 course_id = 999 Outcomes.align_assignment_to_outcome(course_id, outcome_id, assignment_id) outcome = Outcome.query.filter_by(outcome_id=1).first() self.assertIsNotNone(outcome.assignment_id)
def setUp(self): # 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 outcome outcome = Outcome.find_outcome_by_id(88) if outcome is None: outcome = Outcome(id=88, match_id=1, name="1", hid=88, created_user_id=66) db.session.add(outcome) db.session.commit() else: outcome.name = "1" outcome.created_user_id = 66 db.session.commit()
def test_has_valid_shaker(self): self.clear_data_before_test() arr_hs = [] outcome = Outcome.find_outcome_by_id(88) outcome.result = 1 # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.5, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() arr_hs.append(handshake) actual = handshake_bl.has_valid_shaker(handshake) expected = False self.assertEqual(actual, expected) shaker = Shaker( shaker_id=66, amount=0.2, currency='ETH', odds=6, side=1, handshake_id=handshake.id, from_address='0x123', chain_id=4, status=2 ) db.session.add(shaker) db.session.commit() arr_hs.append(shaker) actual = handshake_bl.has_valid_shaker(handshake) expected = True self.assertEqual(actual, expected) for item in arr_hs: db.session.delete(item) db.session.commit()
def test_find_available_against_handshakes_in_event_which_noone_play(self): self.clear_data_before_test() outcome = Outcome( match_id=1, hid=69, contract_id=1 ) db.session.add(outcome) db.session.commit() handshakes = handshake_bl.find_available_against_handshakes(outcome.id) self.assertEqual(len(handshakes), 1) self.assertEqual(float(handshakes[0].amount), 0) self.assertEqual(float(handshakes[0].odds), 2)
def test_get_list_match_resolve_by_admin(self): self.clear_data_before_test() arr_hs = [] t = datetime.now().timetuple() seconds = local_to_utc(t) # ----- match2 = Match(date=seconds - 200, reportTime=seconds - 100, disputeTime=seconds + 300, created_user_id=88, name="Dispute") db.session.add(match2) db.session.commit() # ----- outcome1 = Outcome(match_id=match2.id, hid=1, result=CONST.RESULT_TYPE['DISPUTED'], contract_id=1) db.session.add(outcome1) db.session.commit() with self.client: response = self.client.get( 'admin/match/resolve', headers={ "Authorization": "Bearer {}".format( create_access_token(identity=app.config.get("EMAIL"), fresh=True)), "Uid": "{}".format(88), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) data_json = data['data'] tmp = None for m in data_json: if m['id'] == match2.id: tmp = m break self.assertNotEqual(tmp, None)
def clear_data_before_test(self): outcome1 = Outcome.find_outcome_by_id(10) outcome2 = Outcome.find_outcome_by_id(11) outcome3 = Outcome.find_outcome_by_id(12) outcome4 = Outcome.find_outcome_by_id(13) if outcome1 is not None: db.session.delete(outcome1) db.session.flush() if outcome2 is not None: db.session.delete(outcome2) db.session.flush() if outcome3 is not None: db.session.delete(outcome3) db.session.flush() if outcome4 is not None: db.session.delete(outcome4) db.session.flush() Task.query.delete() db.session.commit()
def can_refund(handshake, shaker=None): if handshake is None and shaker is None: return False outcome = None if handshake is not None: if handshake.status == HandshakeStatus['STATUS_REFUNDED']: return False outcome = Outcome.find_outcome_by_id(handshake.outcome_id) else: if shaker.status == HandshakeStatus['STATUS_REFUNDED']: return False handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is not None and outcome.hid is not None: if outcome.result == CONST.RESULT_TYPE['DRAW'] or ( match_bl.is_exceed_report_time(outcome.match_id) and outcome.result == -1): return True return False
def test_data_need_set_result_for_outcome(self): self.clear_data_before_test() arr_hs = [] outcome = Outcome.find_outcome_by_id(88) outcome.result = 1 # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.5, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() arr_hs.append(handshake) shaker = Shaker( shaker_id=66, amount=0.2, currency='ETH', odds=6, side=1, handshake_id=handshake.id, from_address='0x123', chain_id=4, status=-1 ) db.session.add(shaker) db.session.commit() arr_hs.append(shaker) handshake_bl.data_need_set_result_for_outcome(outcome) hs = Handshake.find_handshake_by_id(handshake.id) self.assertEqual(hs.status, HandshakeStatus['STATUS_MAKER_SHOULD_UNINIT']) for item in arr_hs: db.session.delete(item) db.session.commit()
def save_failed_handshake_method_for_event(method, tx): if method == 'init' or method == 'initTestDrive': offchain = tx.offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') offchain = int(offchain.replace('m', '')) handshake = Handshake.find_handshake_by_id(offchain) if handshake is not None: handshake.status = HandshakeStatus['STATUS_INIT_FAILED'] db.session.flush() arr = [] arr.append(handshake) return arr, None elif method == 'shake' or method == 'shakeTestDrive': offchain = tx.offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') offchain = int(offchain.replace('s', '')) shaker = Shaker.find_shaker_by_id(offchain) if shaker is not None: if shaker.status == HandshakeStatus['STATUS_PENDING']: shaker = rollback_shake_state(shaker) shaker.status = HandshakeStatus['STATUS_SHAKE_FAILED'] db.session.flush() arr = [] arr.append(shaker) return None, arr elif method == 'report': payload = tx.payload data = json.loads(payload) if '_options' in data: options = data['_options'] if 'onchainData' in options: onchain = options['onchainData'] if 'hid' in onchain: hid = int(onchain['hid']) outcome = Outcome.find_outcome_by_hid(hid) if outcome is not None and outcome.result == CONST.RESULT_TYPE[ 'PROCESSING']: outcome.result = CONST.RESULT_TYPE['REPORT_FAILED'] db.session.flush() send_report_slack.delay(outcome.id, result, status=2) return None, None return None, None
def handshakes(): uid = int(request.headers['Uid']) try: data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) outcome_id = data.get('outcome_id', -1) outcome = Outcome.find_outcome_by_id(outcome_id) if outcome is None: return response_error(MESSAGE.INVALID_BET, CODE.INVALID_BET) match = Match.find_match_by_id(outcome.match_id) supports = handshake_bl.find_available_support_handshakes(outcome_id) againsts = handshake_bl.find_available_against_handshakes(outcome_id) total = Decimal('0', 2) traded_volumns = db.session.query(func.sum(Handshake.amount*Handshake.odds).label('traded_volumn')).filter(and_(Handshake.outcome_id==outcome_id, Handshake.status==CONST.Handshake['STATUS_INITED'])).group_by(Handshake.odds).all() for traded in traded_volumns: total += traded[0] arr_supports = [] for support in supports: data = {} data['odds'] = support.odds data['amount'] = support.amount arr_supports.append(data) arr_against = [] for against in againsts: data = {} data['odds'] = against.odds data['amount'] = against.amount arr_against.append(data) response = { "support": arr_supports, "against": arr_against, "traded_volumn": total, "market_fee": match.market_fee } return response_ok(response) except Exception, ex: return response_error(ex.message)
def test_save_collect_state_for_shaker(self): self.clear_data_before_test() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() # ----- shaker = Shaker( shaker_id=66, amount=0.2, currency='ETH', odds=6, side=1, handshake_id=handshake.id, from_address='0x123', chain_id=4, status=2 ) db.session.add(shaker) db.session.commit() outcome = Outcome.find_outcome_by_id(88) outcome.result = 1 db.session.flush() handshake_bl.save_collect_state_for_shaker(shaker) db.session.commit() h = Handshake.find_handshake_by_id(handshake.id) s = Shaker.find_shaker_by_id(shaker.id) self.assertEqual(h.status, 6) self.assertEqual(s.status, 6)
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 save_collect_state_for_maker(handshake): if handshake is not None: outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is not None: if handshake.side == outcome.result: shaker = Shaker.find_shaker_by_handshake_id(handshake.id) if shaker is not None: shaker.bk_status = shaker.status shaker.status = HandshakeStatus['STATUS_DONE'] db.session.merge(shaker) db.session.flush() handshakes, shakers = save_status_all_bet_which_user_win( handshake.user_id, outcome) if shakers is None: shakers = [] shakers.append(shaker) return handshakes, shakers return None, None
def save_collect_state_for_shaker(shaker): if shaker is not None: handshake = Handshake.find_handshake_by_id(shaker.handshake_id) outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is not None: if shaker.side == outcome.result: handshake.bk_status = handshake.status handshake.status = HandshakeStatus['STATUS_DONE'] db.session.merge(handshake) db.session.flush() handshakes, shakers = save_status_all_bet_which_user_win( shaker.shaker_id, outcome) if handshakes is None: handshakes = [] handshakes.append(handshake) return handshakes, shakers return None, None
def save_outcome_data(canvas, course_id): """ Get Outcomes from Canvas for the course and store them in the database :param canvas: Canvas object :type canvas: Object :param course_id: Canvas course ID :type course_id: int :param assignment_group_id: Assignment group to update :type assignment_group_id: Int :returns data: List of all assignments stored from the assignment group :rtype: List data """ course = canvas.get_course(course_id) outcome_groups = course.get_outcome_groups_in_context() outcome_commits = [] for group in outcome_groups: outcomes = group.get_linked_outcomes() for o in outcomes: outcome_data = o.outcome query = Outcome.query.filter_by(outcome_id=outcome_data["id"], course_id=course_id) if query.first() is None: outcome = Outcome( outcome_id=outcome_data["id"], title=outcome_data["title"], course_id=course_id, ) outcome_commits.append(outcome) db.session.bulk_save_objects(outcome_commits) db.session.commit()
def test_update_outcome_scenarios( self, other_oc_brief_based, initial_brief_based, other_oc_data, initial_data, put_values, expected_status_code, expected_response_data, ): """ A number of arguments control the background context this test is run in and the parameters PUT to the endpoint. Not all of the combinations make sense together and a caller should not expect a test to pass with a nonsensical combination of arguments :param other_oc_brief_based: whether the "other", existing Outcome should be Brief-based as opposed to Direct Award-based :param initial_brief_based: whether the target Outcome should initially be set up to be Brief-based as opposed to Direct Award-based :param other_oc_data: field values to set up the "other" Outcome with, ``None`` for no "other" Outcome to be created :param initial_data: field values to initially set up the target Outcome with :param put_values: payload dictionary to be PUT to the target endpoint (without the ``outcome`` wrapper) :param expected_status_code: :param expected_response_data: """ user_id = self.setup_dummy_user(id=1, role='buyer') self.setup_dummy_suppliers(3) project = None search = None chosen_archived_service = other_archived_service = None if not (other_oc_brief_based and initial_brief_based): # create required objects for direct award-based Outcome self.setup_dummy_services(3, model=ArchivedService) project = DirectAwardProject( name="Lambay Island", users=[User.query.get(user_id)], ) db.session.add(project) search = DirectAwardSearch( project=project, created_by=user_id, active=True, search_url="http://nothing.nowhere", ) db.session.add(search) for archived_service in db.session.query(ArchivedService).filter( ArchivedService.service_id.in_(("2000000000", "2000000001",)) ).all(): search.archived_services.append(archived_service) chosen_archived_service, other_archived_service = search.archived_services[:2] # else skip creating these to save time brief = None chosen_brief_response = other_brief_response = None if other_oc_brief_based or initial_brief_based: # create required objects for brief-based Outcome brief = self.setup_dummy_brief(status="closed", user_id=user_id, data={}) chosen_brief_response, other_brief_response = (BriefResponse( brief=brief, supplier_id=i, submitted_at=datetime.datetime.utcnow(), data={}, ) for i in (1, 2,)) db.session.add(chosen_brief_response) db.session.add(other_brief_response) # else skip creating these to save time other_outcome = None if other_oc_data is not None: # create "other" Outcome for our target one to potentially clash with other_outcome = Outcome( **({"brief": brief} if other_oc_brief_based else {"direct_award_project": project}), **({ "result": other_oc_data.get("result", "awarded"), **({ "brief_response": other_brief_response, } if other_oc_brief_based else { "direct_award_search": search, "direct_award_archived_service": other_archived_service, }), } if other_oc_data.get("result", "awarded") == "awarded" else {"result": other_oc_data["result"]}), **{k: v for k, v in (other_oc_data or {}).items() if k not in ("completed_at", "result",)}, ) if "completed_at" in other_oc_data: other_outcome.completed_at = other_oc_data["completed_at"] db.session.add(other_outcome) # create our target Outcome in its initial state outcome = Outcome( **({"brief": brief} if initial_brief_based else {"direct_award_project": project}), **({ "result": initial_data.get("result", "awarded"), **({ "brief_response": chosen_brief_response, } if initial_brief_based else { "direct_award_search": search, "direct_award_archived_service": chosen_archived_service, }), } if initial_data.get("result", "awarded") == "awarded" else {"result": initial_data["result"]}), **{k: v for k, v in (initial_data or {}).items() if k not in ("completed_at", "result",)}, ) if "completed_at" in initial_data: # can only set completed_at after other fields have been set outcome.completed_at = initial_data["completed_at"] db.session.add(outcome) # must assign ids before we can lock project db.session.flush() if project: project.locked_at = datetime.datetime.now() # make a concrete note of these so we don't have to fetch them back from the database after the request, # potentially getting back values which have been inadvertantly changed outcome_external_id = outcome.external_id project_external_id = project and project.external_id search_id = search and search.id chosen_archived_service_id = chosen_archived_service and chosen_archived_service.id chosen_archived_service_service_id = chosen_archived_service and chosen_archived_service.service_id brief_id = brief and brief.id chosen_brief_response_id = chosen_brief_response and chosen_brief_response.id audit_event_count = AuditEvent.query.count() db.session.commit() # keep an nice concrete representation for later comparison outcome_serialization_before = outcome.serialize() res = self.client.put( f"/outcomes/{outcome.external_id}", data=json.dumps({ "updated_by": "*****@*****.**", "outcome": put_values, }), content_type="application/json", ) assert res.status_code == expected_status_code response_data = json.loads(res.get_data()) assert response_data == expected_response_data # allow these to be re-used in this session, "refreshed" db.session.add_all(x for x in (outcome, project, search, chosen_archived_service,) if x is not None) db.session.expire_all() if res.status_code != 200: # assert change wasn't made, audit event wasn't added assert outcome.serialize() == outcome_serialization_before assert AuditEvent.query.count() == audit_event_count else: # an additional check of values we should be able to figure out the "correct" values for assert response_data == { "outcome": { "id": outcome_external_id, "result": initial_data.get("result", "awarded"), "completed": ( bool(outcome_serialization_before.get("completedAt")) or put_values.get("completed") is True ), "completedAt": ( outcome_serialization_before.get("completedAt") or ( AnyStringMatching(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z") if put_values.get("completed") else None ) ), **({ "resultOfFurtherCompetition": { "brief": { "id": brief_id, }, **({ "briefResponse": { "id": chosen_brief_response_id, }, } if initial_data.get("result", "awarded") == "awarded" else {}), }, } if initial_brief_based else { "resultOfDirectAward": { "project": { "id": project_external_id, }, **({ "search": { "id": search_id, }, "archivedService": { "id": chosen_archived_service_id, "service": { "id": chosen_archived_service_service_id, }, }, } if initial_data.get("result", "awarded") == "awarded" else {}) }, }), **({"award": AnySupersetOf({})} if initial_data.get("result", "awarded") == "awarded" else {}), } } # check changes actually got committed assert response_data == { "outcome": outcome.serialize(), } # check audit event(s) were saved expect_complete_audit_event = put_values.get("completed") is True and not initial_data.get("completed_at") n_expected_new_audit_events = 2 if expect_complete_audit_event else 1 assert AuditEvent.query.count() == audit_event_count + n_expected_new_audit_events # grab those most recent (1 or) 2 audit events from the db, re-sorting them to be in a predictable order - # we don't care whether the complete_outcome or update_outcome comes out of the db first audit_events = sorted( db.session.query(AuditEvent).order_by( desc(AuditEvent.created_at), desc(AuditEvent.id), )[:n_expected_new_audit_events], key=lambda ae: ae.type, reverse=True, ) assert audit_events[0].type == "update_outcome" assert audit_events[0].object is outcome assert audit_events[0].acknowledged is False assert audit_events[0].acknowledged_at is None assert not audit_events[0].acknowledged_by assert audit_events[0].user == "*****@*****.**" assert audit_events[0].data == put_values if expect_complete_audit_event: assert audit_events[1].type == "complete_outcome" assert audit_events[1].created_at == audit_events[0].created_at == outcome.completed_at assert audit_events[1].object is outcome assert audit_events[1].acknowledged is False assert audit_events[1].acknowledged_at is None assert not audit_events[1].acknowledged_by assert audit_events[1].user == "*****@*****.**" assert audit_events[1].data == {}
def save_handshake_for_event(event_name, inputs): offchain, hid, state, outcome_result = parse_inputs(inputs) offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '') if event_name == '__createMarket': print '__createMarket' offchain = int(offchain.replace('createMarket', '')) outcome = Outcome.find_outcome_by_id(offchain) if outcome is not None: outcome.hid = hid if 'closingTime' in inputs and \ 'reportTime' in inputs and \ 'disputeTime' in inputs: m = Match.find_match_by_id(outcome.match_id) m.date = int(inputs['closingTime']) m.reportTime = int(inputs['reportTime']) m.disputeTime = int(inputs['disputeTime']) db.session.flush() if outcome_bl.is_outcome_created_by_user(outcome): send_email_event_verification_success.delay( outcome.match_id, outcome.created_user_id) return None, None elif event_name == '__report': print '__report' # report{outcome_id}_{side} # side 1: SUPPORT, 2: OPPOSE, 3: DRAW outcome_id, result = offchain.replace('report', '').split('_') if outcome_id is None or result is None: return None, None outcome = Outcome.find_outcome_by_id(outcome_id) if len(result) > -1 and outcome is not None: result = int(result) outcome.result = result db.session.flush() handshakes, shakers = data_need_set_result_for_outcome(outcome) # send result email to users who play in send_result_email(outcome.id, result) send_report_slack.delay(outcome.id, result, status=1) return handshakes, shakers return None, None elif event_name == '__shake': print '__shake' offchain = offchain.replace('s', '') shaker = Shaker.find_shaker_by_id(int(offchain)) if shaker is not None: shaker.status = HandshakeStatus['STATUS_SHAKER_SHAKED'] shaker.bk_status = HandshakeStatus['STATUS_SHAKER_SHAKED'] db.session.flush() # Add shuriken if shaker.free_bet == 1: add_shuriken.delay(shaker.shaker_id, CONST.SHURIKEN_TYPE['FREE']) else: add_shuriken.delay(shaker.shaker_id, CONST.SHURIKEN_TYPE['REAL']) # Give redeem code for referral user u = User.find_user_with_id(shaker.shaker_id) if u is not None and u.played_bet == 0: referral_bl.give_redeem_code_for_referred_user( shaker.shaker_id) u.played_bet = 1 db.session.flush() arr = [] arr.append(shaker) return None, arr return None, None elif event_name == '__collect': print '__collect' if 's' in offchain: offchain = offchain.replace('s', '') shaker = Shaker.find_shaker_by_id(int(offchain)) if shaker is not None: # update status of shaker and handshake to done # find all bets belongs to this outcome which user join # update all statuses (shaker and handshake) of them to done return save_collect_state_for_shaker(shaker) elif 'm' in offchain: offchain = offchain.replace('m', '') handshake = Handshake.find_handshake_by_id(int(offchain)) if handshake is not None: # update status of shaker and handshake to done # find all bets belongs to this outcome which user join # update all statuses (shaker and handshake) of them to done return save_collect_state_for_maker(handshake) return None, None elif event_name == '__init': print '__init' offchain = offchain.replace('m', '') handshake = Handshake.find_handshake_by_id(int(offchain)) if handshake is not None: handshake.status = HandshakeStatus['STATUS_INITED'] handshake.bk_status = HandshakeStatus['STATUS_INITED'] db.session.flush() arr = [] arr.append(handshake) # Add shuriken if handshake.free_bet == 1: add_shuriken.delay(handshake.user_id, CONST.SHURIKEN_TYPE['FREE']) else: add_shuriken.delay(handshake.user_id, CONST.SHURIKEN_TYPE['REAL']) # Give redeem code for referral user u = User.find_user_with_id(handshake.user_id) if u is not None and u.played_bet == 0: referral_bl.give_redeem_code_for_referred_user( handshake.user_id) u.played_bet = 1 db.session.flush() return arr, None return None, None elif event_name == '__uninit': print '__uninit' offchain = offchain.replace('m', '') handshake = Handshake.find_handshake_by_id(int(offchain)) if handshake is not None: handshake.status = HandshakeStatus['STATUS_MAKER_UNINITED'] handshake.bk_status = HandshakeStatus['STATUS_MAKER_UNINITED'] db.session.flush() arr = [] arr.append(handshake) return arr, None return None, None elif event_name == '__refund': print '__refund' handshake = None user_id = None free_bet = False if 's' in offchain: offchain = offchain.replace('s', '') shaker = Shaker.find_shaker_by_id(int(offchain)) if shaker is None: return None, None user_id = shaker.shaker_id free_bet = shaker.free_bet handshake = Handshake.find_handshake_by_id(shaker.handshake_id) elif 'm' in offchain: offchain = offchain.replace('m', '') handshake = Handshake.find_handshake_by_id(int(offchain)) user_id = handshake.user_id free_bet = handshake.free_bet if handshake is None or user_id is None: return None, None if free_bet is True: redeem_bl.issue_new_redeem_code_for_user(user_id) return save_refund_state_for_all(user_id, handshake.outcome_id) elif event_name == '__dispute': print '__dispute' shaker_dispute = [] handshake_dispute = [] handshake = None user_id = None side = None if outcome_result is None: return None, None if state < 2: return None, None if 's' in offchain: offchain = offchain.replace('s', '') shaker = Shaker.find_shaker_by_id(int(offchain)) user_id = shaker.shaker_id side = shaker.side if shaker is not None: handshake = Handshake.find_handshake_by_id(shaker.handshake_id) elif 'm' in offchain: offchain = offchain.replace('m', '') handshake = Handshake.find_handshake_by_id(int(offchain)) user_id = handshake.user_id side = handshake.side if handshake is None or user_id is None: return None, None outcome = Outcome.find_outcome_by_id(handshake.outcome_id) if outcome is None: return None, None update_amount_for_outcome(outcome.id, user_id, side, outcome_result) if state == 3 and outcome.result != CONST.RESULT_TYPE['DISPUTED']: outcome.result = CONST.RESULT_TYPE['DISPUTED'] db.session.flush() handshake_dispute, shaker_dispute = save_disputed_state(outcome.id) # Send mail to admin send_dispute_email.delay(outcome.match.name) else: handshake_dispute, shaker_dispute = save_user_disputed_state( handshake, user_id, side, outcome_result) return handshake_dispute, shaker_dispute elif event_name == '__resolve': # resolve{outcome_id}_{side} print '__resolve' outcome_id, result = offchain.replace('resolve', '').split('_') if outcome_id is None or result is None: return None, None # 1: SUPPORT, 2: OPPOSE, 3: DRAW: It's depended on smart contract definition. if len(result) == 0 or int(result) not in [1, 2, 3]: return None, None outcome = Outcome.find_outcome_by_id(outcome_id) if outcome is None: return None, None result = int(result) outcome.total_dispute_amount = 0 outcome.result = result db.session.flush() handshakes, shakers = save_resolve_state_for_outcome(outcome.id) # send result email to users who play in send_result_email(outcome.id, result) return handshakes, shakers