示例#1
0
def addNewBetOrder(var_message: dict, conn):
    sql = tbl.insert().values(
        wagerId=var_message["wagerId"],
        oddsFormat=var_message["oddsFormat"],
        odds=var_message["odds"],
        stake=var_message["stake"],
        toWin=var_message["toWin"],
        toRisk=var_message["toRisk"],
        winLoss=var_message["winLoss"],
        currencyCode=var_message["currencyCode"],
        status=var_message["status"],
        loginId=var_message["loginId"],
        wagerDateFm=timeHelp.strToTimestamp(var_message["wagerDateFm"]),
        settleDateFm=0 if var_message["settleDateFm"] is None else
        timeHelp.strToTimestamp(var_message["settleDateFm"]),
        messageData=json.dumps(var_message['messageData']),
    )

    trans = yield from conn.begin()
    try:
        yield from conn.execute(sql)
    except Exception as e:
        logging.error(e)
        yield from trans.rollback()
        return False, 'add'
    else:
        # 日志
        dictBill = {}
        dictBill['billType'] = 'pingboBetResultBill'
        dictBill.update(var_message)
        dictBill['agentId'] = agentId
        logging.getLogger('bill').info(json.dumps(dictBill))
        yield from trans.commit()
        return True, 'add'
示例#2
0
    def getSqlObj(dictBill: dict):
        tbl = Base.metadata.tables["dj_shababetbill"]
        from lib.timehelp.timeHelp import strToTimestamp
        objSql = tbl.insert().values(
            vendorMemberId=dictBill["vendorMember_id"],
            transId=dictBill['trans_id'],
            sportType=dictBill['sport_type'],
            leagueId=dictBill["league_id"],
            betTag=dictBill["bet_tag"],
            homeId=dictBill["home_id"],
            awayId=dictBill["away_id"],
            betTeam=dictBill['bet_team'],
            oddsType=dictBill["odds_type"],
            odds=dictBill["odds"],
            stake=dictBill["stake"],
            betType=dictBill["bet_type"],
            transActionTime=strToTimestamp(dictBill["transaction_time"]),
            winLostDateTime=strToTimestamp(dictBill['winlost_datetime']),
            ticketStatus=dictBill["ticket_status"],
            winLostAmount=dictBill["winlost_amount"],
            currency=dictBill['currency'],
            agentId=dictBill['agentId'],
            operatorId=dictBill['operator_id'],
            baStatus=dictBill['ba_status'],
        )

        return objSql
示例#3
0
    def getSqlObj(dictBill: dict):
        from lib.timehelp.timeHelp import strToTimestamp, str2TimeStamp
        tbl = Base.metadata.tables["dj_pingbobetbill"]
        objSql = tbl.insert().values(
            wagerId=dictBill['wagerId'],
            sport=dictBill['sport'],
            league=dictBill["league"],
            eventName=dictBill["eventName"],
            homeTeam=dictBill["homeTeam"],
            awayTeam=dictBill["awayTeam"],
            selection=dictBill['selection'],
            oddsFormat=dictBill["oddsFormat"],
            odds=dictBill["odds"],
            stake=dictBill["stake"],
            betType=dictBill["betType"],
            eventDateFm=str2TimeStamp(dictBill["eventDateFm"]),
            result=dictBill['result'],
            settleDateFm=0 if dictBill['settleDateFm'] is None
            or dictBill['settleDateFm'] == '' else strToTimestamp(
                dictBill['settleDateFm']),
            status=dictBill["status"],
            toWin=dictBill["toWin"],
            toRisk=dictBill["toRisk"],
            winLoss=dictBill['winLoss'],
            currencyCode=dictBill['currencyCode'],
            userCode=dictBill['userCode'],
            loginId=dictBill['loginId'],
            product=dictBill['product'],
            wagerDateFm=strToTimestamp(dictBill['wagerDateFm']),
            agentId=dictBill['agentId'])

        return objSql
示例#4
0
def updateBetOrder(messageDataList: list, conn):
    accountIds = set()
    for var_message in messageDataList:
        if var_message['status'] == 'SETTLED':
            accountIds.add(var_message['loginId'][7:])

        sql = tbl.update().where(
            tbl.c.wagerId == var_message["wagerId"]).values(
                oddsFormat=var_message["oddsFormat"],  #滚球
                odds=var_message["odds"],
                stake=var_message["stake"],
                toWin=var_message["toWin"],
                toRisk=var_message["toRisk"],
                winLoss=var_message["winLoss"],
                currencyCode=var_message["currencyCode"],
                status=var_message["status"],
                loginId=var_message["loginId"],
                wagerDateFm=timeHelp.strToTimestamp(
                    var_message["wagerDateFm"]),
                settleDateFm=0 if var_message["settleDateFm"] is None else
                timeHelp.strToTimestamp(var_message["settleDateFm"]),
                messageData=json.dumps(var_message),
            )
        trans = yield from conn.begin()
        try:
            for accountId in accountIds:
                yield from classDataBaseMgr.getInstance(
                ).addUpdatePingboAccountId(accountId)
            yield from conn.execute(sql)
        except IntegrityError as e:
            #如果主键重复则更新数据
            logging.debug(repr(e))
            yield from updateBetOrder([var_message])
            yield from trans.commit()
            continue
        except Exception as e:
            logging.error(e)
            logging.error(var_message)
            yield from trans.rollback()
            continue
        else:
            yield from trans.commit()
示例#5
0
def addNewBetOrder(messageDataList: list, conn):

    for var_message in messageDataList:

        sql = tbl.insert().values(
            wagerId=var_message["wagerId"],
            oddsFormat=var_message["oddsFormat"],
            odds=var_message["odds"],
            stake=var_message["stake"],
            toWin=var_message["toWin"],
            toRisk=var_message["toRisk"],
            winLoss=var_message["winLoss"],
            currencyCode=var_message["currencyCode"],
            status=var_message["status"],
            loginId=var_message["loginId"],
            wagerDateFm=timeHelp.strToTimestamp(var_message["wagerDateFm"]),
            settleDateFm=0 if var_message["settleDateFm"] is None else
            timeHelp.strToTimestamp(var_message["settleDateFm"]),
            messageData=json.dumps(var_message),
        )

        trans = yield from conn.begin()
        try:
            yield from conn.execute(sql)
        except IntegrityError as e:
            #主键重复,更新一遍
            logging.debug(repr(e))
            yield from trans.rollback()
            yield from updateBetOrder([var_message])
            continue
        except Exception as e:
            logging.error(e)
            yield from trans.rollback()
            continue
        else:
            yield from trans.commit()
示例#6
0
def updateMatchPlatform():
    global g_iCheckTime

    listMatchType = ["kog", "lol", "dota2"]
    gameTypeMapping = {2: "kog", 3: "lol", 4: "dota2"}

    objRedis = classDataBaseMgr.getInstance()

    # 获取上次的更新时间
    #iCheckTime = yield from objRedis.getLastAddCheckTime()
    iNowTime = timeHelp.getNow()
    if g_iCheckTime is None or g_iCheckTime == 0:
        #yield from objRedis.setLastAddCheckTime(iNowTime)
        g_iCheckTime = iNowTime
    else:

        dictGameKinds = {v: k for k, v in gameTypeMapping.items()}

        # 每5秒检查一次数据
        if (iNowTime - g_iCheckTime) >= 5:
            # 获取比赛竞猜的相关配置数据  竞猜玩法(第一滴血等)、竞猜目标(A队B队)

            try:
                for var_match_type in listMatchType:

                    try:
                        if procVariable.debug:

                            if not procVariable.dataDebug:
                                strPostUrl = matchcenter_config.dataPlatformReleaseBaseUrlForDebug + matchcenter_config.dataPlatformPostGetMatchData.format(
                                    var_match_type)
                            else:
                                strPostUrl = matchcenter_config.dataPlatformDebugBaseUrl + matchcenter_config.dataPlatformPostGetMatchData.format(var_match_type) + \
                                         matchcenter_config.debugAppend

                        else:
                            strPostUrl = matchcenter_config.dataPlatformReleaseBaseUrl + matchcenter_config.dataPlatformPostGetMatchData.format(
                                var_match_type)

                        strBeginTime = timeHelp.timestamp2Str(iNowTime)
                        strEndTime = timeHelp.timestamp2Str(
                            iNowTime +
                            86400 * matchcenter_config.getMatchPreDay)  # 7天以后

                        dictParam = {
                            'matchId': -1,
                            'startTime': strBeginTime,
                            'endTime': strEndTime
                        }

                        dictPost = getPostFormat(dictParam)

                        dictHeader = {
                            'Accept': 'text/html',
                            'Content-Type': 'application/x-www-form-urlencoded'
                        }

                        with aiohttp.Timeout(100):
                            try:
                                client = aiohttp.ClientSession(
                                    response_class=aiohttpClientResponseWrap)
                                logging.debug(
                                    "data center [{}]".format(strPostUrl))
                                # 请求数据中心的接口
                                result = yield from client.post(
                                    strPostUrl,
                                    data=dictPost,
                                    headers=dictHeader)

                                if result.status != 200:
                                    logging.error(
                                        "get status[{}] game_type[{}]".format(
                                            result.status, var_match_type))
                                else:
                                    #print(dir(result))
                                    response = yield from result.read(
                                    )  # 获取返回信息
                                    #logging.debug(response)
                                    dictResponse = json.loads(response)
                                    dictData = dictResponse['data']
                                    #print(dictData)
                                    if len(dictData) <= 0:
                                        continue

                                    for var_match_id, var_match_data in dictData.items(
                                    ):
                                        #查看本场比赛是否已经被添加进去
                                        matchId = var_match_type + var_match_id
                                        bIsAdd = yield from objRedis.checkPreMatchIdExist(
                                            matchId, var_match_type)
                                        if bIsAdd:
                                            #logging.info("{} matchId have already added".format(matchId))
                                            continue

                                        # 添加一个赛事
                                        objNewMatchData = matchData.classMatchData(
                                        )
                                        objNewMatchData.strMatchId = matchId
                                        objNewMatchData.iMatchState = 0

                                        objNewMatchData.strMatchType = var_match_type
                                        objNewMatchData.strTeamAName = var_match_data[
                                            'team1Name']
                                        objNewMatchData.strTeamBName = var_match_data[
                                            'team2Name']

                                        objNewMatchData.iMatchState = 0  # 0:未开始  1:停止下注 2:比赛中  3:已结束 4:赛事被官方取消  5:后台主动关闭
                                        var_match_data[
                                            'matchStartTime'] = var_match_data[
                                                'matchStartTime']
                                        objNewMatchData.iMatchStartTimestamp = timeHelp.strToTimestamp(
                                            var_match_data['matchStartTime'])
                                        objNewMatchData.iMatchEndTimestamp = objNewMatchData.iMatchStartTimestamp + 3600

                                        objNewMatchData.iTeamAScore = 0
                                        objNewMatchData.iTeamBScore = 0

                                        objNewMatchData.strMatchName = var_match_data[
                                            'eventName']
                                        objNewMatchData.iMatchRoundNum = int(
                                            var_match_data['roundCount'])

                                        objNewMatchData.arrayGuess = [
                                        ]  # Guess  GuessID = matchId + '_' + str(type)

                                        objNewMatchData.strTeamALogoUrl = var_match_data[
                                            'team1Logo']
                                        objNewMatchData.strTeamBLogoUrl = var_match_data[
                                            'team2Logo']

                                        #objNewMatchData.strTeamAId = var_match_data['team1Id']
                                        #objNewMatchData.strTeamBId = var_match_data['team2Id']

                                        yield from objRedis.addPreMatchForApproval(
                                            objNewMatchData)
                                        logging.info(
                                            "save new have not template match[{}] matchAName[{}] matchBName[{}]"
                                            .format(
                                                objNewMatchData.strMatchId,
                                                objNewMatchData.strTeamAName,
                                                objNewMatchData.strTeamBName))

                            finally:
                                yield from client.close()

                    except Exception as e:
                        logging.error(
                            repr(e) +
                            str(" game_type {}".format(var_match_type)))
                        logging.error(traceback.extract_stack())
                        continue
            finally:
                #yield from objRedis.setLastAddCheckTime(iNowTime)
                g_iCheckTime = iNowTime
示例#7
0
def handleHttp(request: dict):
    # 根据条件查询数据库用户竞猜信息
    userId = request.get('userId', '')
    phone = request.get('phone', '')
    email = request.get('email', '')
    # 竞猜单号
    guessUId = request.get('guessUId', '')
    product = request.get('product', '')
    startTime = request.get('startTime', sevenDayTimestamp())
    endTime = request.get('endTime', getNow())
    pn = request.get('pn', 1)
    try:
        pn = int(pn)
    except Exception as e:
        logging.debug(errorLogic.client_param_invalid)
        raise exceptionLogic(errorLogic.client_param_invalid)
    try:
        conn = classSqlBaseMgr.getInstance()
        probet_sql = None
        pinbo_sql = None
        if guessUId:
            if product == 'all':
                probet_sql = "select guessUId from dj_bet WHERE guessUId='{}'".format(
                    guessUId)
                pinbo_sql = "select wagerId from dj_pinbo_wagers WHERE dj_pinbo_wagers.wagerId='{}'".format(
                    guessUId)

            elif product == 'probet':
                probet_sql = "select guessUId from dj_bet WHERE guessUId='{}'".format(
                    guessUId)

            else:
                pinbo_sql = "select wagerId from dj_pinbo_wagers WHERE wagerId='{}'".format(
                    guessUId)

        else:
            accountId = None
            if userId:
                sql = "select accountId from dj_account WHERE dj_account.accountId='{}' ".format(
                    userId)
                listRest = yield from conn._exeCute(sql)
                accountId = yield from listRest.fetchone()
                if accountId is None:
                    logging.debug(errorLogic.player_data_not_found)
                    raise exceptionLogic(errorLogic.player_data_not_found)
                accountId = accountId[0]

            elif phone:
                sql = "select accountId from dj_account WHERE dj_account.phone='{}' ".format(
                    phone)
                listRest = yield from conn._exeCute(sql)
                accountId = yield from listRest.fetchone()
                if accountId is None:
                    logging.debug(errorLogic.player_data_not_found)
                    raise exceptionLogic(errorLogic.player_data_not_found)
                accountId = accountId[0]

            elif email:
                sql = "select accountId from dj_account WHERE dj_account.email='{}' ".format(
                    email)
                listRest = yield from conn._exeCute(sql)
                accountId = yield from listRest.fetchone()
                if accountId is None:
                    logging.debug(errorLogic.player_data_not_found)
                    raise exceptionLogic(errorLogic.player_data_not_found)
                accountId = accountId[0]

            if product == 'all':
                # 查全部 todo 两张不同表分页暂时没想到好的解决方案
                if not accountId:
                    probet_sql = "select guessUId from dj_bet WHERE dj_bet.time BETWEEN {} AND {} ORDER BY dj_bet.time DESC ".format(
                        startTime, endTime)
                    pinbo_sql = "select wagerId from dj_pinbo_wagers WHERE dj_pinbo_wagers.wagerDateFm BETWEEN {} AND {} ORDER BY wagerDateFm DESC ".format(
                        startTime, endTime)
                else:
                    probet_sql = "select guessUId from dj_bet WHERE dj_bet.accountId='{}' AND dj_bet.time BETWEEN {} AND {} ORDER BY dj_bet.time DESC ".format(
                        accountId, startTime, endTime)

                    pinbo_sql = "select wagerId from dj_pinbo_wagers WHERE dj_pinbo_wagers.loginId='{}' AND dj_pinbo_wagers.wagerDateFm BETWEEN {} AND {} ORDER BY wagerDateFm DESC ".format(
                        'probet.' + accountId, startTime, endTime)

            elif product == 'probet':
                #查自己平台
                if not accountId:
                    probet_sql = "select guessUId from dj_bet WHERE dj_bet.time BETWEEN {} AND {} ORDER BY dj_bet.time DESC ".format(
                        startTime, endTime)
                else:
                    probet_sql = "select guessUId from dj_bet WHERE dj_bet.accountId='{}' AND dj_bet.time BETWEEN {} AND {} ORDER BY wagerDateFm DESC ".format(
                        accountId, startTime, endTime)

            else:
                #查平博
                if not accountId:
                    pinbo_sql = "select wagerId from dj_pinbo_wagers WHERE dj_pinbo_wagers.wagerDateFm BETWEEN {} AND {} ORDER BY wagerDateFm DESC ".format(
                        startTime, endTime)
                else:
                    pinbo_sql = "select wagerId from dj_pinbo_wagers WHERE dj_pinbo_wagers.loginId='{}' AND dj_pinbo_wagers.wagerDateFm BETWEEN {} AND {} ORDER BY wagerDateFm DESC ".format(
                        'probet.' + accountId, startTime, endTime)

        probet_bets = []
        pinbo_bets = []
        probet_betids = None
        pinbo_betids = None
        if probet_sql is not None:
            listRest = yield from conn._exeCute(probet_sql)
            probet_betids = yield from listRest.fetchall()

        if pinbo_sql is not None:
            listRest = yield from conn._exeCute(pinbo_sql)
            pinbo_betids = yield from listRest.fetchall()

        if probet_betids is not None:
            for x in probet_betids:
                probet_bets.append({"probet": x[0]})
        if pinbo_betids is not None:
            for x in pinbo_betids:
                pinbo_bets.append({"pingbo": x[0]})

        probet_bets.extend(pinbo_bets)
        count = len(probet_bets)
        betids = probet_bets[(pn - 1) * MSG_PAGE_COUNT:pn * MSG_PAGE_COUNT:]
        resp = cResp()
        for x in betids:
            if "probet" in x.keys():
                sql = "select * from dj_bet WHERE guessUId='{}' ".format(
                    x['probet'])
                listRest = yield from conn._exeCute(sql)
                probet_row = yield from listRest.fetchone()
                data = cData()
                data.orders = probet_row['guessUId']
                data.accountId = probet_row['accountId']
                data.product = '电竞竞猜'
                data.time = probet_row['time']
                data.game = probet_row['matchType']
                sql = "select teamAName,teamBName from dj_match WHERE matchId='{}' ".format(
                    probet_row['matchId'])
                listRest = yield from conn._exeCute(sql)
                match = yield from listRest.fetchone()
                data.msg = "{} vs {}".format(match['teamAName'],
                                             match['teamBName'])
                ctr = json.loads(probet_row['ctr'])
                data.content = "{}/{}@{}".format(
                    ctr[probet_row['chooseId']]['strChooseName'],
                    probet_row['guessName'],
                    ctr[probet_row['chooseId']]['fRate'])
                data.money = float("%.2f" %
                                   round(probet_row['betCoin'] / 100, 2))
                data.winning = float("%.2f" %
                                     round(probet_row['winCoin'] / 100, 2))
                data.status = probet_row['result']
                resp.data.append(data)

            if "pingbo" in x.keys():
                sql = "select * from dj_pinbo_wagers WHERE wagerId='{}' ".format(
                    x['pingbo'])
                listRest = yield from conn._exeCute(sql)
                pinbo_row = yield from listRest.fetchone()
                data = cData()
                data.orders = pinbo_row['wagerId']
                data.accountId = pinbo_row['loginId'][7:]
                messageData = json.loads(pinbo_row['messageData'])
                messageData = json.loads(messageData)
                data.product = '平博体育'
                data.time = strToTimestamp(messageData['wagerDateFm'])
                data.game = messageData['league']
                data.msg = messageData["eventName"]
                #todo 玩法
                data.content = "{}/{}@{}".format(
                    pingboBetType[messageData['betType']],
                    messageData['selection'], pinbo_row['odds'])
                data.money = float("%.2f" % round(pinbo_row['stake'], 2))
                data.winning = float("%.2f" % round(pinbo_row['winLoss'], 2))
                data.status = pinbo_row['status']
                resp.data.append(data)

        resp.count = count
        resp.ret = errorLogic.success[0]
        if pn == 1:
            fileName = __name__
            nameList = fileName.split('.')
            methodName = nameList.pop()
            # 日志
            dictActionBill = {
                'billType': 'adminActionBill',
                'accountId': request.get('accountId', ''),
                'action': "查询注单信息",
                'actionTime': getNow(),
                'actionMethod': methodName,
                'actionDetail': "查询用户:{},注单信息".format(userId),
                'actionIp': request.get('srcIp', ''),
            }
            logging.getLogger('bill').info(json.dumps(dictActionBill))
        return classJsonDump.dumps(resp)
    except exceptionLogic as e:
        logging.exception(e)
        raise e
    except Exception as e:
        logging.exception(e)
        raise exceptionLogic(errorLogic.db_error)