Commit bfbf66af Harvey

no message

1 个父辈 6a639c77
import {Match} from './match'
import {Issue} from './issue'
import {Lottery} from './lottery'
import {Odds100} from './odds100'
import {MatchJson} from './matchJson'
import {Team,NBATeam} from './team'
export{
Match,
Issue,
Lottery,
Odds100,
Team,
NBATeam,
MatchJson,
};
const pginfo =require( '../table');
const Issue = pginfo.core_issue;
export {Issue};
const pginfo =require( '../table');
const Lottery = pginfo.core_lottery;
export {Lottery};
\ No newline at end of file
import * as pginfo from '../table';
pginfo.core_match.belongsTo(pginfo.core_lottery, { foreignKey: 'LotteryId' });
pginfo.core_match.belongsTo(pginfo.core_issue, { foreignKey: 'IssueId' } );
const Match = pginfo.core_match;
export {Match};
/**
* Created by sunney on 7/3/17.
*/
const pginfo =require( '../table');
const MatchJson = pginfo.T_MatchJson;
export {MatchJson};
\ No newline at end of file
const pginfo =require( '../table');
const News = pginfo.core_news;
export {News};
/**
* Created by sunney on 6/7/17.
*/
const pginfo =require( '../table');
const Odds100 = pginfo.T_Odds100;
const NBAOdds100 = pginfo.T_Odds100;
export {Odds100};
/**
* Created by sunney on 6/7/17.
*/
const pginfo =require( '../table');
const Team = pginfo.T_Team;
const NBATeam = pginfo.T_NBATeam;
export {Team,NBATeam};
import * as info_db from '../../info_mysql/table';
//充值接口控制充值通道
export async function getRechargeChannelsList({ root, args, context }: any) {
let where :any={
is_enable: 1
}
if(process.env.ALPHA){//灰度
where={}
}
let ms_recharge_channels_list: any = JSON.parse(JSON.stringify(await info_db.ms_recharge_channels.findAndCountAll({
where: where,
order: [["sort_serial", "DESC"]]
})))
return ms_recharge_channels_list.rows;
}
import { db as Info } from '../table'
import _ = require('lodash');
import redis = require('redis');
const config = require("../../../../config");
import moment = require('moment');
import api_hemera = require('../../../api_hemera');
export const historySameOddsTemp= {
"ResultSps": null,
"BetSps": null,
"AllCount": null,
"WinCount": null,
"FlatCount": null,
"LostCount": null,
"WinRate": null,
"FlatRate": null,
"LostRate": null,
"SameOddsList": null,
"LastEndBet": null
}
export async function getHistorySameOdds(winBet:any,flatBet:any,lossBet:any){
//只比较最小的两个,winBet>5.0的时候比较负、平, 浮动0.02
let delta = 0.02
if(isNaN(winBet)||isNaN(winBet)||isNaN(winBet)){
throw "获取历史同赔参数错误"
}
let sql = `select * from ms_soccer_hdaodds_814
where
last_odds_win>=${(parseFloat(winBet)-delta).toFixed(2)} and last_odds_win<=${(parseFloat(winBet)+delta).toFixed(2)}
and last_odds_draw>=${(parseFloat(flatBet)-delta).toFixed(2)} and last_odds_draw<=${(parseFloat(flatBet)+delta).toFixed(2)}`
if(parseFloat(winBet)>3.1){
sql = `select * from ms_soccer_hdaodds_814
where
last_odds_loss>=${(parseFloat(lossBet)-delta).toFixed(2)} and last_odds_loss<=${(parseFloat(lossBet)+delta).toFixed(2)}
and last_odds_draw>=${(parseFloat(flatBet)-delta).toFixed(2)} and last_odds_draw<=${(parseFloat(flatBet)+delta).toFixed(2)}`
}
let list =await Info.db.query(sql)
if(list!=null&&list.length>0){
list=list[0]
let result:any = {
"ResultSps": null,
"BetSps": null,
"AllCount": list.length,
"WinCount": _.filter(list,(item)=>{return item.home_score>item.away_score}).length,
"FlatCount": _.filter(list,(item)=>{return item.home_score==item.away_score}).length,
"LostCount": _.filter(list,(item)=>{return item.home_score<item.away_score}).length,
"WinRate": null,
"FlatRate": null,
"LostRate": null,
"SameOddsList": JSON.stringify(_.map(list,(item)=>{
return {
BeginTime: moment.unix(item.game_date/1000).format('YYYY-MM-DD'),
HostTeamId: item.home_team_id,
HostTeam: item.home_team_name,
GuestTeamId: item.away_team_id,
GuestTeam: item.away_team_name,
HostScore: item.home_score,
GuestScore: item.away_score,
ShortName: item.competition_name,
}
})),
"LastEndBet": null
}
if(result.AllCount>0){
result.WinRate = (result.WinCount/result.AllCount).toFixed(4)
result.FlatRate = (result.FlatCount/result.AllCount).toFixed(4)
result.LostRate = (result.LostCount/result.AllCount).toFixed(4)
}
return result
}
return historySameOddsTemp
}
\ No newline at end of file
import * as Core from '../table';
import Model = require('../model');
import moment = require('moment');
import _ = require('lodash');
const config = require("../../../../config");
import { cache,redis as client, redis, task_lock } from '../../../cache'
async function Issue(issueId: any) {
let t = await Model.Issue.findOne({
where: {
Id: issueId
}
});
return t;
};
const Issues = async (root: any, args: any, context: any, isUpdateCache: any = false) => {
let lotId = 72
if (parseInt(args.lotId) > 0) {
lotId = parseInt(args.lotId)
}
// console.info(args);
return cache(async ({lotId,limit}: any) => {
let sql = `select * from core_issue where LotteryId=${lotId}
and (EndTime<'${moment().add(3, `hour`).format(`YYYY-MM-DD HH:mm:ss`)}')
order by Name desc limit ${args.limit||30}
`
if([45,73,72,74,75].includes(lotId)&&(args.is_end==null||args.is_end==1)){
let old_match: any = await Core.Match.findOne({
where: {
//MatchTime:{$lt:`${moment().add(-118,"minute").format(`YYYY-MM-DD HH:mm:ss`)}`},
//IssueName:`${moment().format(`YYYY-MM-DD HH:mm:ss`)}`,
LotteryId: lotId,
MatchState: '完',
},
limit: 1,
order: [["MatchTime", "desc"]]
})
if (old_match != null) {
if(lotId==72&&old_match.IssueName!=moment().format(`YYYY-MM-DD`)){
sql = `select * from core_issue where LotteryId=${lotId}
and (EndTime<'${moment().add(3, `hour`).format(`YYYY-MM-DD HH:mm:ss`)}')
order by Name desc limit ${args.limit||30}
`
}else{
sql = `select * from core_issue where LotteryId=${lotId}
and Name<='${old_match.IssueName}'
order by StartTime desc limit ${args.limit||30}
`
}
}
}
else if([45,72,73,74,75].includes(lotId)){
// 1 完场的期号 2 是未完场的期号 3不限制是否完场 0 代表当前期号
switch(args.is_end){
case 2:
sql = `select * from core_issue where LotteryId=${lotId}
and EndTime>'${moment().format(`YYYY-MM-DD HH:mm`)}'
order by Name desc limit ${args.limit||30}
`;
break;
case 3:
sql = `select * from core_issue where LotteryId=${lotId}
and StartTime>'${moment().add(-100,`day`).format(`YYYY-MM-DD HH:mm:ss`)}'
order by Name desc limit ${args.limit||30}
`;
break;
case 0:
sql = `select * from core_issue where LotteryId=${lotId}
and StartTime>'${moment().add(-3,`hour`).format(`YYYY-MM-DD HH:mm:ss`)}'
order by Name asc limit 1
`;
break;
}
}
// console.info(sql);
let t = await Core.sequelize.query(sql)
t = checkList(t);
return t;
}, {lotId,is_end:args.is_end}, 5, "pginfo_issue:vy5", 60, 100)
};
const MatchTimes = async (root: any, args: any, context: any, isUpdateCache: any = false) => {
let lotId = 72
if (parseInt(args.lotId) > 0) {
lotId = parseInt(args.lotId)
}
let key = `${config.CachePrefix}match:matchMatchDates:v1_${args.lotId}`
let reply = await client.get(key);
try {
if (reply && reply.length > 0 && !isUpdateCache) {
return JSON.parse(reply)
}
} catch (e:any) {
console.info(e)
}
let sql = `
select distinct to_char("MatchTime",'YYYY-MM-DD') as "MatchTime"
from core_match
where "LotteryId"=${lotId} and "MatchTime">'${moment().add(-20, 'day').format('YYYY-MM-DD')}'
ORDER BY "MatchTime" desc limit 13
`
let t = await Core.sequelize.query(sql)
t = checkList(t)
t = _.map(t, o => o.MatchTime)
await client.set(key, JSON.stringify(t))
client.expire(key, 60)
return t;
};
function checkList(list: any) {
if (list && list.length > 0) {
return list[0]
}
return []
}
export { Issue, Issues, MatchTimes }
import * as _ from 'lodash';
import * as api_hemera from '../../../api_hemera'
import * as moment from 'moment'
import { cache } from '../../../cache'
import db = require('../table');
export async function getlineupfromsporttery({ sportsdt_gameid, type, lotteryId, issueName, matchNumber }: any) {
// let gameprediction = await cache(async (args: any) => {
// return await api_hemera.query('sport', `getgameprediction`, {}, { gameid: args.gameid })
// }, { gameid: sportsdt_gameid }, 30, 'getgameprediction')
// let dataLineup = gameprediction.Lineup
try {
if(moment(issueName)>moment().add(1,'day')){
throw "时间范围不正确"
}
let t: any = await db.sporttery_match_lineup.findOne({
where: {
issue_name: issueName,
match_number: matchNumber
}
})
if (t == null) {
return JSON.stringify([
["", "", ""],
[],
[],
[],
[],
[],
[],
])
}
let jsonBody = t
//let Formation = ['', dataLineup.HFormation, dataLineup.AFormation]
let Formation = [``, ``, ``]
if (jsonBody.referee_name != null)
Formation[0] = jsonBody.referee_name
let positionName: any = {
Goalkeeper: "守门员",
Defender: "后卫",
Midfielder: "中场",
Attacker: "前锋",
}
let position_x_name: any = {
"":"0",
GK: '1',
D1: '2',
D2: '3',
D: '3',
DM: '4',
M: '5',
AM: '6',
A: '7',
}
let position_y_name: any = {
"":"0",
L: '1',
CL: '2',
C: '3',
CR: '4',
R: '5',
}
let h_lineups_info_lineups: any = _.map(jsonBody.h_lineups_info.lineups, (item: any) => {
return [item.shirtnumber,
item.person,
positionName[item.position],
position_x_name[item.position_x],
position_y_name[item.position_y]
]
})
let a_lineups_info_lineups: any = _.map(jsonBody.a_lineups_info.lineups, (item: any) => {
return [item.shirtnumber,
item.person,
positionName[item.position],
position_x_name[item.position_x],
position_y_name[item.position_y]
]
})
let h_lineups_info_lineups_bench = _.map(jsonBody.h_lineups_info.lineups_bench, (item: any) => {
return [item.shirtnumber,
item.person,
positionName[item.position],
"0",
"0"
]
})
let a_lineups_info_lineups_bench = _.map(jsonBody.a_lineups_info.lineups_bench, (item: any) => {
return [item.shirtnumber,
item.person,
positionName[item.position],
"0",
"0"
]
})
for (let i = 2; i <= 7; i++) {
let leng: any = _.countBy(h_lineups_info_lineups, (item: any) => { return item[3] + '' == i + '' })
if (leng.true > 0) {
Formation[1] = `${Formation[1]}${leng.true}`
}
}
for (let i = 2; i <= 7; i++) {
let leng: any = _.countBy(a_lineups_info_lineups, (item: any) => { return item[3] + '' == i + '' })
if (leng.true > 0) {
Formation[2] = `${Formation[2]}${leng.true}`
}
}
return JSON.stringify([
Formation,
h_lineups_info_lineups,
a_lineups_info_lineups,
h_lineups_info_lineups_bench,
a_lineups_info_lineups_bench,
[],
[],
])
} catch (e:any) {
return JSON.stringify([
["", "", ""],
[],
[],
[],
[],
[],
[],
])
}
}
export async function get_sports_injury(gameid: Number) {
try {
let gameprediction = await cache(async (args: any) => {
return await api_hemera.query('sport', `getgameprediction`, {}, { gameid: args.gameid })
}, { gameid: gameid }, 30, 'getgameprediction')
// 状态,整型
// 0:后备球员
// 1:停赛球员
// 2:伤病球员
// 3:首发球员
// 4:其它原因缺阵球员
// const Ontype = ["受伤", "伤疑", "停赛", "国家队上调", "预计缺席"]
// const StateType = ["不出战", " 出战"]
let injuries_info_h_injuries: any = _.map(
_.filter(gameprediction.Lineup.HomePlayers, (o) => { return o.Status == 2 || o.Status == 1 }), (item: any) => {
if (item.Status == 1) {
return { "Id": item.Id, "Name": item.Name, "ShirtNum": item.ShitNo, "State": 0, "On": 2 }
} else {
return { "Id": item.Id, "Name": item.Name, "ShirtNum": item.ShitNo, "State": 0, "On": 0 }
}
})
let injuries_info_a_injuries: any = _.map(
_.filter(gameprediction.Lineup.AwayPlayers, (o) => { return o.Status == 2 || o.Status == 1 }), (item: any) => {
if (item.Status == 1) {
return { "Id": item.Id, "Name": item.Name, "ShirtNum": item.ShitNo, "State": 0, "On": 2 }
} else {
return { "Id": item.Id, "Name": item.Name, "ShirtNum": item.ShitNo, "State": 0, "On": 0 }
}
})
return JSON.stringify({
Home: injuries_info_h_injuries,
Away: injuries_info_a_injuries
})
} catch (e:any) {
return JSON.stringify({
Home: [],
Away: []
})
}
}
/**
* Created by sunney on 7/3/17.
*/
import Model = require('../model');
import { cache,redis as client, redis, task_lock } from '../../../cache'
export async function getMatchJson({type,match}:any) {
try {
let match_team_info_key = `${config.CachePrefix}match:match_json:v1_${match.Id}_${type}`
let t:any = await client.get(match_team_info_key);
if (t && t.length > 0 && !match.isUpdateCache) {
return t
} else {
t = await
Model.MatchJson.findOne({
where: {
Type: type,
LotteryId: match.LotteryId,
IssueName: match.IssueName,
MatchNumber: match.MatchNumber
}
})
client.set(match_team_info_key, t.Json)
client.expire(match_team_info_key, 60*60*24)
}
if (t == null)
return '{}'
return t.Json;
}catch (e:any){
return '{}'
}
}
/**
* Created by sunney on 7/4/17.
*/
import Info = require('../table');
import { cache,redis as client, redis, task_lock } from '../../../cache'
export async function getMatchTeamInfo(match:any) {
let sql=`DECLARE @InfoId INT
SET @InfoId=${match.InfoId}
DECLARE @HostId INT
DECLARE @GuestId INT
DECLARE @MatchSeason VARCHAR(20)
DECLARE @BeginTime VARCHAR(20)
SELECT @HostId=HostTeamId,@GuestId=GuestTeamId,@MatchSeason=MatchSeason,@BeginTime=BeginTime FROM T_match WHERE Id=@InfoId;
DECLARE @Temp_Result TABLE(TeamId INT,zcc INT,zcs INT,zj INT,zs INT,jj DECIMAL(8,1),js DECIMAL(8,1),zcjj DECIMAL(8,1),zcjs DECIMAL(8,1),scs INT,
pcs INT,fcs INT,zscs INT,zpcs INT,zfcs INT,sbcjj DECIMAL(8,1),sbcjs DECIMAL(8,1),xbcjj DECIMAL(8,1),xbcjs DECIMAL(8,1),
s1q INT,s2q INT,f1q INT,f2q INT,nzcc INT,nzj INT,nzs INT,njj DECIMAL(8,1),njs DECIMAL(8,1))
DECLARE @Temp_Score TABLE(Score INT,HalfScore INT,Lose INT,HalfLose INT,BeginTime VARCHAR(20),IsHost INT)
DECLARE @N INT
SET @N=1
WHILE @N>=0
BEGIN
DECLARE @TeamId INT
SET @TeamId=CASE WHEN @N=1 THEN @HostId ELSE @GuestId END
INSERT INTO @Temp_Score( Score, HalfScore, Lose, HalfLose,BeginTime, IsHost)
SELECT HostScore Score,HostHalfScore HalfScore,GuestScore Lose,GuestHalfScore HalfLose,BeginTime,1 IsHost
FROM T_match WHERE matchSeason=@MatchSeason AND [Status]=-1 And BeginTime <@BeginTime AND HostTeamId=@TeamId
INSERT INTO @Temp_Score( Score, HalfScore, Lose, HalfLose,BeginTime, IsHost)
SELECT GuestScore Score,GuestHalfScore HalfScore,HostScore Lose,HostHalfScore HalfLose,BeginTime,0 IsHost
FROM T_match WHERE matchSeason=@MatchSeason AND [Status]=-1 And BeginTime <@BeginTime AND GuestTeamId=@TeamId
IF NOT EXISTS(SELECT TOP 1 1 FROM @Temp_Score)
BEGIN
BREAK
END;
WITH t1 AS (
SELECT
@TeamId TeamId,
COUNT(1) zcc,
SUM(IsHost) zcs,
SUM(Score) zj,
SUM(Lose) zs,
SUM(Score)*1.0/COUNT(1) jj,
SUM(Lose)*1.0/COUNT(1) js,
SUM(CASE WHEN IsHost=1 THEN Score ELSE 0 END)*1.0/(CASE WHEN SUM(IsHost)=0 THEN 1 ELSE SUM(IsHost) END) zcjj,
SUM(CASE WHEN IsHost=1 THEN Lose ELSE 0 END)*1.0/(CASE WHEN SUM(IsHost)=0 THEN 1 ELSE SUM(IsHost) END) zcjs,
SUM(CASE WHEN Score>Lose THEN 1 ELSE 0 END) scs,
SUM(CASE WHEN Score=Lose THEN 1 ELSE 0 END) pcs,
SUM(CASE WHEN Score<Lose THEN 1 ELSE 0 END) fcs,
SUM(CASE WHEN IsHost=@N AND Score>Lose THEN 1 ELSE 0 END) zscs,
SUM(CASE WHEN IsHost=@N AND Score=Lose THEN 1 ELSE 0 END) zpcs,
SUM(CASE WHEN IsHost=@N AND Score<Lose THEN 1 ELSE 0 END) zfcs,
SUM(HalfScore)*1.0/COUNT(1) sbcjj,
SUM(HalfLose)*1.0/COUNT(1) sbcjs,
SUM(Score-HalfScore)*1.0/COUNT(1) xbcjj,
SUM(Lose-HalfLose)*1.0/COUNT(1) xbcjs,
SUM(CASE WHEN Score-Lose=1 THEN 1 ELSE 0 END) s1q,
SUM(CASE WHEN Score-Lose>1 THEN 1 ELSE 0 END) s2q,
SUM(CASE WHEN Score-Lose=-1 THEN 1 ELSE 0 END) f1q,
SUM(CASE WHEN Score-Lose<-1 THEN 1 ELSE 0 END) f2q
FROM @Temp_Score),
t2 AS (
SELECT
@TeamId TeamId,
COUNT(1) nzcc,
SUM(Score) nzj,
SUM(Lose) nzs,
SUM(Score)*1.0/COUNT(1) njj,
SUM(Lose)*1.0/COUNT(1) njs
FROM (SELECT TOP 6 * FROM @Temp_Score ORDER BY BeginTime DESC) temp)
INSERT INTO @Temp_Result (TeamId,zcc,zcs,zj,zs,jj,js,zcjj,zcjs,scs,pcs,fcs,zscs,zpcs,zfcs,sbcjj,sbcjs,xbcjj,xbcjs,s1q,s2q,f1q,f2q,nzcc,nzj,nzs,njj,njs)
SELECT t1.TeamId,zcc,zcs,zj,zs,jj,js,zcjj,zcjs,scs,pcs,fcs,zscs,zpcs,zfcs,sbcjj,sbcjs,xbcjj,xbcjs,s1q,s2q,f1q,f2q,nzcc,nzj,nzs,njj,njs FROM t1 JOIN t2 ON t1.TeamId=t2.TeamId
SET @N=@N-1
DELETE @Temp_Score
END
SELECT * FROM @Temp_Result
`
try {
//添加redis
let match_team_info_key = `${config.CachePrefix}match:match_team_info:v1_${match.Id}`
let t = await client.get(match_team_info_key);
if (t && t.length > 0 && !match.isUpdateCache) {
return t
}else{
t = await Info.db.query(sql)
}
if (t == null)
return '[]'
if (t && t.length > 0) {
client.set(match_team_info_key,JSON.stringify(t[0]))
client.expire(match_team_info_key, 60*60*24)
return JSON.stringify(t[0])
} else {
return '[]'
}
}catch (e:any){
return '[]'
}
}
import * as infodb from '../table'
import moment = require('moment');
import { cache,redis as client, redis, task_lock } from '../../../cache';
//ms_schedule
async function getMsSchedulesByLottery({lotteryId}:any) {
let key = `${config.CachePrefix}match:match_ms_schedule:v1_${moment().add(-10,'day').format('YYYY-MM-DD')}_${lotteryId}`
let reply = await client.get(key);
if (reply) {
return JSON.parse(reply)
}
let result = await infodb.ms_schedule.findAll({
where:{
core_lottery_id:lotteryId,
core_match_time:{$gt:moment().add(-10,'day').format('YYYY-MM-DD')},
},
limit:1000,
attributes: ['core_match_id', 'sportsdt_match_id', 'sportsdt_host_team_id'
, 'sportsdt_guest_team_id', 'sportsdt_competition_id', 'sportsdt_type', 'sportsdt_degree'
, 'sportsdt_num', 'sportsdt_starttime', 'sportsdt_isah'],
})
await client.set(key,JSON.stringify(result))
await client.expire(key, 60*10)
return result
}
async function getMsSchedulesByCoreIds({CoreIds}:any) {
return cache(async ({CoreIds}:any)=>{
let result = (await infodb.ms_schedule.findAll({
where:{
core_match_id:{$in:CoreIds},
core_match_time:{$gt:moment().add(-120,'day').format('YYYY-MM-DD')},
},
limit:1000,
attributes: ['core_match_id', 'sportsdt_match_id', 'sportsdt_host_team_id'
, 'sportsdt_guest_team_id', 'sportsdt_competition_id', 'sportsdt_type', 'sportsdt_degree'
, 'sportsdt_num', 'sportsdt_starttime', 'sportsdt_isah', 'sportsdt_n'
, 'yiqiu_match_id', 'sporttery_match_id', 'w500_match_id', 'info_match_id'],
})).map((o:any)=>o.dataValues)
return result
},{CoreIds},10,"getMsSchedulesByCoreIds:v1",60,100)
}
export {getMsSchedulesByLottery,getMsSchedulesByCoreIds}
\ No newline at end of file
/**
* Created by sunney on 7/19/17.
*/
import {db as Info} from '../table'
import { cache,redis as client, redis, task_lock } from '../../../cache'
export async function getNBALeagueRank(match:any) {
if(match.LotteryId == 72) {
return []
}
let match_NBALeagueRank_key = `${config.CachePrefix}match:matchNBALeagueRank:v2_${match.Id}`
let t = await client.get(match_NBALeagueRank_key);
if (t && t.length > 0 && ! match.isUpdateCache) {
return t
}
if(match.LotteryId == 73) {
t = await Info.db.query(`SELECT
a.Id,a.TeamId,c.Name as TeamName,c.ShortName TeamShortNam,a.Win,a.Lose,a.WinPoint,
a.LosePoint,a.WinAverage,a.LostAverage,a.State,a.Type,b.FullName
as MatchTypeName,b.ShortName as MatchTypeShortName
FROM T_NBAMatch t
join T_NBALeagueRank a on a.MatchSeason=t.MatchSeason and a.MatchTypeId=t.MatchTypeId
JOIN T_NBAMatchType b ON a.MatchTypeId=b.Id AND b.ParentId=0 AND a.MatchSeason=t.MatchSeason and a.MatchTypeId=t.MatchTypeId
JOIN T_NBATeam c ON a.TeamId=c.Id
where t.Id=${match.InfoId}
ORDER BY Type, Id
`)
if (t == null || t.length == 0)
return []
client.set(match_NBALeagueRank_key, JSON.stringify(t[0]))
client.expire(match_NBALeagueRank_key, 60 *60*24)
return JSON.stringify(t[0]);
}
return []
};
import Core = require('../table');
import _ = require('lodash');
import { cache,redis as client, redis, task_lock } from '../../../cache'
const News = async (match:any) => {
let news_key = `${config.CachePrefix}match:matchnews:v3_${match.LotteryId}_${match.Id}`
let replyData = await client.get(news_key);
if (replyData && replyData.length > 0 && !match.isUpdateCache) {
return JSON.parse(replyData)
}
let sql = `SELECT * FROM core_news WHERE \`IsShow\`=true AND \`LotId\`=${match.LotteryId} AND \`MatchId\` = ${match.Id} ORDER BY \`UpdateTime\` DESC limit 10`
let t= await Core.sequelize.query(sql)
t=checkList(t)
client.set(news_key,JSON.stringify(t))
client.expire(news_key, 60*60)
return t;
};
function checkList(list:any){
if(list && list.length>0){
return _.map(list[0],(item)=>{
let rand= Math.round(Math.random()*10)
if(item.ImageUrl == null || item.ImageUrl == ''){
item.ImageUrl = `https://m.ydniu.com/images/info/00${rand}.png`
item.Contents = item.Contents.replace(new RegExp(/一定牛/g),'球道')
}
return item;
})
}
return []
}
const NewsList = async () => {
let sql = `SELECT * FROM core_news WHERE \`IsShow\`=true ORDER BY \`UpdateTime\` DESC limit 10`
let list= await Core.sequelize.query(sql)
return list;
};
export {News,NewsList}
import _ = require('lodash');
import api_hemera = require('../../../api_hemera');
import moment = require('moment');
import { cache,redis as client, redis, task_lock } from '../../../cache'
async function getOdds100LogByCompany(root:any,args:any,context:any){
//功能:获取单场的欧盘指数单公司赔率变化历史
//接口地址:http://{API_Url}/soccer/?type=gethdaoddslog
try{
let newargs={
gameid:args.sportsdtMatchId,
pid:args.companyId,
}
let result = await api_hemera.query('sport', 'gethdaoddslog', {}, newargs,30,"v1")
result = JSON.stringify(_.map(result.Logs,(log)=>{
return [round(log.Data[0]),
round(log.Data[1]),round(log.Data[2]),moment(parseInt(log.Date)).format("MM-DD HH:mm")]
}))
return result
} catch (e) {
console.info(e);
return []
}
}
function round(value:any) {
return (Math.round(value * 100) / 100).toFixed(2)
}
export {getOdds100LogByCompany}
\ No newline at end of file
export async function getHostTeam(
{ sportdtLogo, match }: any) {
if (match.Sportsdt) {
sportdtLogo = `https://data.7m.com.cn/team_data/${match.Sportsdt.SportsdtHostTeamId}/logo_img/club_logo.jpg`
if (match.LotteryId == 73) {
sportdtLogo = `https://bdata.7m.com.cn/basketball_team_data/${match.Sportsdt.SportsdtHostTeamId}/logo_img/club_logo.jpg`
}
if (match.Sportsdt.SportsdtHostTeamId == null) {
sportdtLogo = null
}
}
let result:any={}
result['SportsDtLogo'] = sportdtLogo
result[`LogoFullPath`]= sportdtLogo
result[`Logo`]= sportdtLogo
return result
}
export async function getGuestTeam(
{ sportdtLogo, match }: any) {
if (match.Sportsdt) {
sportdtLogo = `https://data.7m.com.cn/team_data/${match.Sportsdt.SportsdtGuestTeamId}/logo_img/club_logo.jpg`
if (match.LotteryId == 73) {
sportdtLogo = `https://bdata.7m.com.cn/basketball_team_data/${match.Sportsdt.SportsdtGuestTeamId}/logo_img/club_logo.jpg`
}
if (match.Sportsdt.SportsdtGuestTeamId == null) {
sportdtLogo = null
}
}
let result:any={}
result['SportsDtLogo'] = sportdtLogo
result[`LogoFullPath`]= sportdtLogo
result[`Logo`]= sportdtLogo
return result
}
export async function getTeam(
{ lotteryId, id, InfoId, isUpdateCache, sportdtLogo, match, }: any) {
if (match.Sportsdt&&id==match.GuestId) {
sportdtLogo = `https://data.7m.com.cn/team_data/${match.Sportsdt.SportsdtGuestTeamId}/logo_img/club_logo.jpg`
if (match.LotteryId == 73) {
sportdtLogo = `https://bdata.7m.com.cn/basketball_team_data/${match.Sportsdt.SportsdtGuestTeamId}/logo_img/club_logo.jpg`
}
if (match.Sportsdt.SportsdtGuestTeamId == null) {
sportdtLogo = null
}
}else if (match.Sportsdt&&id==match.HostId) {
sportdtLogo = `https://data.7m.com.cn/team_data/${match.Sportsdt.SportsdtHostTeamId}/logo_img/club_logo.jpg`
if (match.LotteryId == 73) {
sportdtLogo = `https://bdata.7m.com.cn/basketball_team_data/${match.Sportsdt.SportsdtHostTeamId}/logo_img/club_logo.jpg`
}
if (match.Sportsdt.SportsdtHostTeamId == null) {
sportdtLogo = null
}
}
let result:any={}
result['SportsDtLogo'] = sportdtLogo
result[`LogoFullPath`]= sportdtLogo
result[`Logo`]= sportdtLogo
return result
// let key = `${config.CachePrefix}match:match_getTeam:v2_${lotteryId}_${id}_${InfoId}`
// let reply:any = await client.getAsync(key);
// if (reply && !isUpdateCache) {
// reply = JSON.parse(reply)
// if (reply != null) {
// reply['SportsDtLogo'] = sportdtLogo
// // if(reply[`LogoFullPath`]==null){
// // reply[`LogoFullPath`]= sportdtLogo
// // }
// reply[`LogoFullPath`]= sportdtLogo
// return reply
// }
// }
// let result: any = {}
// if (id && lotteryId == 73) {
// let t = await Info.db.query(`SELECT
// c.*,b.\`ShortName\` as \`MatchTypeShortName\`, a.\`Id\` as \`Rank\`, a.\`Type\` as \`RankType\`
// FROM \`T_NBAMatch\` t
// join \`T_NBALeagueRank\` a on a.\`MatchSeason\`=t.\`MatchSeason\` and a.\`MatchTypeId\`=t.\`MatchTypeId\`
// JOIN \`T_NBAMatchType\` b ON a.\`MatchTypeId\`=b.\`Id\` AND b.\`ParentId\`=0 AND a.\`MatchSeason\`=t.\`MatchSeason\` and a.\`MatchTypeId\`=t.\`MatchTypeId\`
// JOIN \`T_NBATeam\` c ON a.\`TeamId\`=c.\`Id\` and c.\`Id\`=${id}
// where t.\`Id\`=${InfoId} and c.\`Id\`=${id}
// ORDER BY a.\`Type\`, a.\`Id\`
// `)
// if (t == null || t.length <= 0 || t[0].length <= 0)
// result = {}
// else {
// result = t[0][0];
// }
// } else if (id && lotteryId != 73) {
// let t = await Info.db.query(`select t.*,m.\`ShortName\` as \`MatchTypeShortName\` from \`T_Team\` t left join \`T_MatchType\` m on t.\`MatchTypeId\`=m.\`Id\` where t.\`Id\`=${id}`)
// if (t == null || t.length <= 0 || t[0].length <= 0)
// result = {}
// else {
// result = t[0][0];
// }
// }
// if (result != null) {
// result['SportsDtLogo'] = sportdtLogo
// result[`LogoFullPath`]= sportdtLogo
// // if(result[`LogoFullPath`]==null){
// // result[`LogoFullPath`]= sportdtLogo
// // }
// await client.setAsync(key, JSON.stringify(result))
// client.expire(key, 60 * 60 * 24)
// return result
// }
};
import * as moment from 'moment'
import * as _ from 'lodash'
import { v1 as Uid } from 'uuid';
import { ms_unscramble_order as order, db as info_db, ms_user } from '../table'
export async function createUnscrambleOrder(cramble: any, userid: number) {
let money = cramble.plan_saleprice
const user: any = await ms_user.findById(userid)
if (!user || !user.user_id) throw new Error('用户不存在')
//是否购买过
const isBought = await order.count({ where: { userid } }) > 0
if (isBought && await order.count({ where: { dbno: cramble.dbno, userid } }) > 0)
throw new Error('您已购买过,请勿重复购买')
//首单免费
if (!isBought) money = 0
if (isBought && user.balance < money) throw new Error('余额不够,请充值')
const scrambleOrder = {
userid,
buytime: moment(),
buymoney: money,
username: user.user_name,
..._.pick(cramble, ['dbno', 'typeid', 'expertid', 'author_name', 'plan_lotterytype', 'plan_issueno', 'plan_title', 'plan_summary', 'plan_begintime', 'plan_endtime', 'plan_passtype'])
}
return info_db.sequelize.transaction(async (transaction: any) => {
let res: any = await order.create(scrambleOrder, { transaction })
const orderId = res.id
if (!orderId) throw Error('推荐购买异常')
if (money > 0) {
const updateUser = `UPDATE ms_user SET balance=balance-${money} WHERE user_id=${userid} and balance>=${money}`;
res = await info_db.sequelize.query(updateUser, { transaction, type: info_db.sequelize.QueryTypes.UPDATE });
if (res[1] !== 1) throw Error('余额不够,请充值')
}
const updateUserOperation = `INSERT INTO ms_user_operation (uuid,user_id,created_at,user_name,user_nick_name,user_safe_code,type_name,type_id,money,balance,freeze,memo)SELECT '${Uid()}',user_id,'${moment().format('YYYY-MM-DD HH:mm:ss')}',user_name,nick_name,safe_code,'购买推荐订单',-1,${money},balance,freeze,'购买大神推荐,订单编号:${orderId}' FROM ms_user WHERE user_id=${userid}`;
await info_db.sequelize.query(updateUserOperation, { transaction });
return orderId
});
}
export async function getUnscrambleOrder(args: any) {
return order.findAll({
where: { userid: args.userid },
offset: args.offset,
limit: args.limit,
order: [['buytime', 'desc']]
})
}
// /**
// * 检查用户余额是否足够
// * @param data
// */
// @Dct.api({
// dbNo: Joi.number().required().error(() => '查询条件不能为空!'),
// buyedMoney: Joi.number().integer(),
// chargePayType: Joi.number().integer(),
// userId: Joi.number().integer()
// })
// public static async CheckUserMoney(data) {
// if (!data.userId) {
// return;
// }
// const user = await UserAdapter.getUserById(data.userId);
// if (!user) {
// return;
// }
// //余额不足直接充值
// if (user.Balance < data.buyedMoney) {
// const balance = _.floor(user.Balance);//向下取整数
// const money = (data.buyedMoney - balance).toString();
// return await PaymentAdapter.buildRequestUrl(Unscramble.PayTypeId[config.expert.PayTypeId], money, 'IOS', '', '', data.chargePayType, data.userId);
// }
// //余额不足
// if (data.Balance < data.buyedMoney) throw Error('账户余额不足请充值。');
// const unscramb = await UnscrambleInfo.find({ attributes: ['dbNo', 'plan_salePrice', 'typeId'], where: { dbNo: data.dbNo } });
// if (!unscramb) {
// throw Error('解读信息错误。');
// }
// if (data.buyedMoney !== unscramb.plan_salePrice) {
// throw Error('购买金额错误。');
// }
// if (data.UserStatus > 0 && data.UserStatus <= 50) {
// throw Error('用户已限制消费');
// }
// const cramble = await UnscrambleInfo.find({ where: { dbNo: data.dbNo } });
// if (!cramble) {
// throw Error('解读信息错误');
// }
// const trade = []
// const orderId = await Cache.getUniqId('unscrambleorder')
// const tradeno = `unscrambleorder:${orderId}`;
// const scrambleOrder = {
// Id: orderId,
// dbNo: data.dbNo,
// userId: data.userId,
// typeId: cramble.typeId,
// expertId: cramble.expertId,
// author_name: cramble.author_name,
// buyTime: moment(),
// userName: user.Name,
// buyMoney: data.buyedMoney,
// plan_lotteryType: cramble.plan_lotteryType,
// plan_issueNo: cramble.plan_issueNo,
// plan_title: cramble.plan_title,
// plan_summary: cramble.plan_summary,
// plan_beginTime: cramble.plan_beginTime,
// plan_endTime: cramble.plan_endTime,
// plan_passType: cramble.plan_passType
// };
// trade.push({
// sourceid: orderId,
// userid: user.Id,
// opertypeid: 2611,
// money: -data.buyedMoney,
// memo: `购买大神推荐,订单编号:${orderId}`,
// tradeno: tradeno
// })
// const time = Date.now()
// const msg: any = await sendMsg({
// topic: topicName.Account.AccoutnBackMoney, content: JSON.stringify({
// userid: user.Id,
// sourceid: orderId,
// tradeno: tradeno
// }),
// nextSendTime: moment().add(1, 'm').format('YYYY-MM-DD HH:mm:ss')
// })//退钱消息 60秒后发送
// const result = await AccountAdapter.trade(trade).catch(() => false)
// if (!result) {
// if (Date.now() - time < buyTimeout) Message.Model.update({ nextSendTime: moment().format('YYYY-MM-DD HH:mm:ss') }, { where: { id: msg.id, deletedAt: null } })
// throw new Error('扣款失败')
// }
// await Db.dbs[0].transaction(async (transaction) => {
// await UnscrambleOrder.create(scrambleOrder, { transaction });
// const r = await Message.Model.destroy({ where: { id: msg.id, deletedAt: null }, transaction })
// if (r < 1) throw new Error('下单失败')
// if (Date.now() - time > buyTimeout) throw new Error('购买超时')
// });
// if (unscramb.typeId === 0)//只有购买天天赢球接口的推荐才通知到他们接口
// {
// const timestamp = moment().format("YYYYMMDDHHmmss");
// const sign = await md5Sign(`${orderId}${config.expert.AppSecret}${timestamp}`, 'utf8', 'hex').toLocaleLowerCase();//md5(orderId+key+timestamp)
// const postData = `orderId=${orderId}&timestamp=${timestamp}&sign=${sign}`;
// await Unscramble.httpPostRequest(config.expert.postPay, postData);
// }
// return 1;
// }
\ No newline at end of file
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!