edb_info.go 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_index_lib/models/mgo"
  6. "eta/eta_index_lib/utils"
  7. "fmt"
  8. "strconv"
  9. "time"
  10. "go.mongodb.org/mongo-driver/bson"
  11. "github.com/beego/beego/v2/client/orm"
  12. "github.com/shopspring/decimal"
  13. )
  14. type EdbInfo struct {
  15. EdbInfoId int `orm:"column(edb_info_id);pk"`
  16. EdbInfoType int `description:"指标类型,0:普通指标,1:预测指标"`
  17. SourceName string `description:"来源名称"`
  18. Source int `description:"来源id"`
  19. EdbCode string `description:"指标编码"`
  20. EdbName string `description:"指标名称"`
  21. EdbNameEn string `description:"英文指标名称"`
  22. EdbNameSource string `description:"指标名称来源"`
  23. Frequency string `description:"频率"`
  24. Unit string `description:"单位"`
  25. UnitEn string `description:"英文单位"`
  26. StartDate string `description:"起始日期"`
  27. EndDate string `description:"终止日期"`
  28. ClassifyId int `description:"分类id"`
  29. SysUserId int
  30. SysUserRealName string
  31. UniqueCode string `description:"指标唯一编码"`
  32. CreateTime time.Time
  33. ModifyTime time.Time
  34. BaseModifyTime time.Time
  35. MinValue float64 `description:"指标最小值"`
  36. MaxValue float64 `description:"指标最大值"`
  37. CalculateFormula string `description:"计算公式"`
  38. EdbType int `description:"指标类型:1:基础指标,2:计算指标"`
  39. IsUpdate int `description:"当天是否已更新,1:未更新,2:已更新"`
  40. Sort int `description:"排序字段"`
  41. LatestDate string `description:"数据最新日期(实际日期)"`
  42. LatestValue float64 `description:"数据最新值(实际值)"`
  43. EndValue float64 `description:"数据的最新值(预测日期的最新值)"`
  44. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  45. MoveFrequency string `description:"移动频度"`
  46. NoUpdate int8 `description:"是否停止更新,0:继续更新;1:停止更新"`
  47. ServerUrl string `description:"服务器地址"`
  48. ChartImage string `description:"图表图片"`
  49. Calendar string `description:"公历/农历" orm:"default(公历);"`
  50. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  51. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  52. DataDateType string `orm:"column(data_date_type);size(255);null;default(交易日)"`
  53. ManualSave int `description:"是否有手动保存过上下限: 0-否; 1-是"`
  54. TerminalCode string `description:"终端编码,用于配置在机器上"`
  55. DataUpdateTime string `description:"最近一次数据发生变化的时间"`
  56. ErDataUpdateDate string `description:"本次更新,数据发生变化的最早日期"`
  57. SourceIndexName string `description:"数据源中的指标名称"`
  58. SubSource int `description:"子数据来源:0:经济数据库,1:日期序列"`
  59. SubSourceName string `description:"子数据来源名称"`
  60. IndicatorCode string `description:"指标代码"`
  61. StockCode string `description:"证券代码"`
  62. Extra string `description:"指标的额外配置"`
  63. IsStaticData int `description:"是否是静态指标,0否,1是"`
  64. EndDateType int `description:"预测指标截止日期类型:0:未来日期,1未来期数"`
  65. }
  66. func (e *EdbInfo) Add() (err error) {
  67. o := orm.NewOrm()
  68. _, err = o.Insert(e)
  69. return
  70. }
  71. // AddEdbInfo 添加指标
  72. func AddEdbInfo(item *EdbInfo) (lastId int64, err error) {
  73. o := orm.NewOrm()
  74. lastId, err = o.Insert(item)
  75. return
  76. }
  77. // EdbInfoList 指标数据列表
  78. type EdbInfoList struct {
  79. EdbInfoId int `orm:"column(edb_info_id);pk"`
  80. EdbInfoType int `description:"指标类型,0:普通指标,1:预测指标"`
  81. SourceName string `description:"来源名称"`
  82. Source int `description:"来源id"`
  83. EdbCode string `description:"指标编码"`
  84. EdbNameEn string `description:"英文指标名称"`
  85. EdbName string `description:"指标名称"`
  86. Frequency string `description:"频率"`
  87. FrequencyEn string `description:"英文频率"`
  88. Unit string `description:"单位"`
  89. UnitEn string `description:"英文单位"`
  90. StartDate string `description:"起始日期"`
  91. EndDate string `description:"终止日期"`
  92. LatestDate string `description:"数据最新日期(实际日期)"`
  93. LatestValue float64 `description:"数据最新值(实际值)"`
  94. EndValue float64 `description:"数据的最新值(预测日期的最新值)"`
  95. ClassifyId int `description:"分类id"`
  96. UniqueCode string `description:"指标唯一编码"`
  97. SysUserId int `description:"创建人id"`
  98. SysUserRealName string `description:"创建人姓名"`
  99. ModifyTime string `description:"最新修改时间"`
  100. CreateTime string `description:"创建时间"`
  101. EdbNameAlias string `json:"-" description:"指标名称,别名"`
  102. EdbType int `description:"指标类型:1:基础指标,2:计算指标"`
  103. ChartImage string `description:"图表图片"`
  104. RuleType int `description:"预测规则,1:最新,2:固定值"`
  105. FixedValue float64 `description:"固定值"`
  106. DataList []*EdbData `description:"实际指标数据"`
  107. PredictDataList []*EdbData `description:"预测指标数据"`
  108. Button EdbClassifyItemsButton `description:"操作权限"`
  109. IsEnEdb bool `description:"是否展示英文标识"`
  110. DataDateType string `description:"数据日期类型,枚举值:交易日、自然日"`
  111. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  112. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  113. SubSource int `description:"子数据来源:0:经济数据库,1:日期序列"`
  114. SubSourceName string `description:"子数据来源名称"`
  115. IndicatorCode string `description:"指标代码"`
  116. StockCode string `description:"证券代码"`
  117. NoUpdate int8 `description:"是否停止更新,0:继续更新;1:停止更新"`
  118. }
  119. // EdbClassifyItemsButton 操作按钮
  120. type EdbClassifyItemsButton struct {
  121. AddButton bool `description:"是否可添加"`
  122. OpButton bool `description:"是否可编辑"`
  123. DeleteButton bool `description:"是否可删除"`
  124. MoveButton bool `description:"是否可移动"`
  125. ShowEdbRelation bool `description:"是否展示关联指标"`
  126. ShowChartRelation bool `description:"是否展示关联图表"`
  127. }
  128. // GetEdbInfoByName 根据指标名称获取所有的指标数据列表
  129. func GetEdbInfoByName(edbName string) (items []*EdbInfoList, err error) {
  130. o := orm.NewOrm()
  131. sql := ` SELECT * FROM edb_info WHERE edb_name=? `
  132. _, err = o.Raw(sql, edbName).QueryRows(&items)
  133. return
  134. }
  135. // ModifyEdbInfoNameSource 根据来源修改指标名称
  136. func ModifyEdbInfoNameSource(edbNameSource string, edbInfoId int) (err error) {
  137. o := orm.NewOrm()
  138. sql := ` UPDATE edb_info SET edb_name_source=? WHERE edb_info_id = ? `
  139. _, err = o.Raw(sql, edbNameSource, edbInfoId).Exec()
  140. return
  141. }
  142. // GetEdbInfoById 根据指标id获取指标信息
  143. func GetEdbInfoById(edbInfoId int) (item *EdbInfo, err error) {
  144. o := orm.NewOrm()
  145. sql := ` SELECT * FROM edb_info WHERE edb_info_id=? `
  146. err = o.Raw(sql, edbInfoId).QueryRow(&item)
  147. return
  148. }
  149. // GetEdbInfoByUniqueCode 根据指标唯一编码获取指标信息
  150. func GetEdbInfoByUniqueCode(uniqueCode string) (item *EdbInfo, err error) {
  151. o := orm.NewOrm()
  152. sql := ` SELECT * FROM edb_info WHERE unique_code=? `
  153. err = o.Raw(sql, uniqueCode).QueryRow(&item)
  154. return
  155. }
  156. // GetEdbInfoByIdList 根据指标id列表获取指标信息
  157. func GetEdbInfoByIdList(edbInfoIdList []int) (items []*EdbInfo, err error) {
  158. num := len(edbInfoIdList)
  159. if num <= 0 {
  160. return
  161. }
  162. o := orm.NewOrm()
  163. sql := ` SELECT * FROM edb_info WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  164. _, err = o.Raw(sql, edbInfoIdList).QueryRows(&items)
  165. return
  166. }
  167. // Update 更新EdbInfo信息
  168. func (edbInfo *EdbInfo) Update(cols []string) (err error) {
  169. o := orm.NewOrm()
  170. _, err = o.Update(edbInfo, cols...)
  171. return
  172. }
  173. // EdbInfoSearchData
  174. type EdbInfoSearchData struct {
  175. EdbDataId int `description:"数据ID"`
  176. EdbInfoId int `description:"指标ID"`
  177. DataTime string `description:"数据日期"`
  178. Value float64 `description:"数据"`
  179. EdbCode string `description:"指标编码"`
  180. DataTimestamp int64 `description:"时间戳"`
  181. }
  182. type FindEdbDataListAllCond struct {
  183. EdbInfoId int
  184. StartDataTime string
  185. StartDataTimeCond string
  186. EndDataTime string
  187. EndDataTimeCond string
  188. }
  189. // GetEdbDataListAll
  190. // @Description: 获取指标数据列表 order:1升序,其余值为降序
  191. // @author: Roc
  192. // @datetime 2024-05-08 15:34:01
  193. // @param source int
  194. // @param subSource int
  195. // @param findEdbDataListAllCond FindEdbDataListAllCond
  196. // @param order int order:1升序,其余值为降序
  197. // @return item []*EdbInfoSearchData
  198. // @return err error
  199. func GetEdbDataListAll(source, subSource int, findEdbDataListAllCond FindEdbDataListAllCond, order int) (item []*EdbInfoSearchData, err error) {
  200. if source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  201. return GetEdbDataListAllByMongo(source, subSource, findEdbDataListAllCond, order)
  202. }
  203. return GetEdbDataListAllByMysql(source, subSource, findEdbDataListAllCond, order)
  204. }
  205. // GetEdbDataListAllByMysql
  206. // @Description: 从mysql数据库中获取指标数据列表 order:1升序,其余值为降序
  207. // @author: Roc
  208. // @datetime 2024-05-08 15:32:55
  209. // @param source int
  210. // @param subSource int
  211. // @param findEdbDataListAllCond FindEdbDataListAllCond
  212. // @param order int
  213. // @return item []*EdbInfoSearchData
  214. // @return err error
  215. func GetEdbDataListAllByMysql(source, subSource int, findEdbDataListAllCond FindEdbDataListAllCond, order int) (item []*EdbInfoSearchData, err error) {
  216. if findEdbDataListAllCond.EdbInfoId <= 0 {
  217. return
  218. }
  219. to := orm.NewOrm()
  220. sql := ``
  221. tableName := GetEdbDataTableName(source, subSource)
  222. sql = ` SELECT * FROM %s WHERE 1=1 `
  223. sql = fmt.Sprintf(sql, tableName)
  224. var condition string
  225. var pars []interface{}
  226. condition += " AND edb_info_id=? "
  227. pars = append(pars, findEdbDataListAllCond.EdbInfoId)
  228. // 开始日期
  229. if findEdbDataListAllCond.StartDataTime != "" && findEdbDataListAllCond.StartDataTimeCond != `` {
  230. condition += fmt.Sprintf(" AND data_time %s ? ", findEdbDataListAllCond.StartDataTimeCond)
  231. pars = append(pars, findEdbDataListAllCond.StartDataTime)
  232. }
  233. // 结束日期
  234. if findEdbDataListAllCond.EndDataTime != "" && findEdbDataListAllCond.EndDataTimeCond != `` {
  235. condition += fmt.Sprintf(" AND data_time %s ? ", findEdbDataListAllCond.EndDataTimeCond)
  236. pars = append(pars, findEdbDataListAllCond.EndDataTime)
  237. }
  238. if condition != "" {
  239. sql += condition
  240. }
  241. if order == 1 {
  242. sql += ` ORDER BY data_time ASC `
  243. } else {
  244. sql += ` ORDER BY data_time DESC `
  245. }
  246. _, err = to.Raw(sql, pars).QueryRows(&item)
  247. return
  248. }
  249. // GetEdbDataListAllByTo
  250. // @Description: 根据事务链接获取指标数据列表 order:1升序,其余值为降序
  251. // @author: Roc
  252. // @datetime 2024-05-08 15:34:06
  253. // @param to orm.TxOrmer
  254. // @param source int
  255. // @param subSource int
  256. // @param findEdbDataListAllCond FindEdbDataListAllCond
  257. // @param order int
  258. // @return item []*EdbInfoSearchData
  259. // @return err error
  260. func GetEdbDataListAllByTo(to orm.TxOrmer, source, subSource int, findEdbDataListAllCond FindEdbDataListAllCond, order int) (item []*EdbInfoSearchData, err error) {
  261. if source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  262. return GetEdbDataListAllByMongo(source, subSource, findEdbDataListAllCond, order)
  263. }
  264. return GetEdbDataListAllByMysqlTo(to, source, subSource, findEdbDataListAllCond, order)
  265. }
  266. // GetEdbDataListAllByMysqlTo
  267. // @Description: 根据事务链接获取指标数据列表 order:1升序,其余值为降序(Mysql)
  268. // @author: Roc
  269. // @datetime 2024-05-08 15:34:13
  270. // @param to orm.TxOrmer
  271. // @param source int
  272. // @param subSource int
  273. // @param findEdbDataListAllCond FindEdbDataListAllCond
  274. // @param order int
  275. // @return item []*EdbInfoSearchData
  276. // @return err error
  277. func GetEdbDataListAllByMysqlTo(to orm.TxOrmer, source, subSource int, findEdbDataListAllCond FindEdbDataListAllCond, order int) (item []*EdbInfoSearchData, err error) {
  278. if findEdbDataListAllCond.EdbInfoId <= 0 {
  279. return
  280. }
  281. sql := ``
  282. tableName := GetEdbDataTableName(source, subSource)
  283. sql = ` SELECT * FROM %s WHERE 1=1 `
  284. sql = fmt.Sprintf(sql, tableName)
  285. var condition string
  286. var pars []interface{}
  287. condition += " AND edb_info_id=? "
  288. pars = append(pars, findEdbDataListAllCond.EdbInfoId)
  289. // 开始日期
  290. if findEdbDataListAllCond.StartDataTime != "" && findEdbDataListAllCond.StartDataTimeCond != `` {
  291. condition += fmt.Sprintf(" AND data_time %s ? ", findEdbDataListAllCond.StartDataTimeCond)
  292. pars = append(pars, findEdbDataListAllCond.StartDataTime)
  293. }
  294. // 结束日期
  295. if findEdbDataListAllCond.EndDataTime != "" && findEdbDataListAllCond.EndDataTimeCond != `` {
  296. condition += fmt.Sprintf(" AND data_time %s ? ", findEdbDataListAllCond.EndDataTimeCond)
  297. pars = append(pars, findEdbDataListAllCond.EndDataTime)
  298. }
  299. if condition != "" {
  300. sql += condition
  301. }
  302. if order == 1 {
  303. sql += ` ORDER BY data_time ASC `
  304. } else {
  305. sql += ` ORDER BY data_time DESC `
  306. }
  307. _, err = to.Raw(sql, pars).QueryRows(&item)
  308. return
  309. }
  310. // GetEdbDataListAllByMongo
  311. // @Description: 根据事务链接获取指标数据列表 order:1升序,其余值为降序(Mongo)
  312. // @author: Roc
  313. // @datetime 2024-05-08 15:34:24
  314. // @param source int
  315. // @param subSource int
  316. // @param findEdbDataListAllCond FindEdbDataListAllCond
  317. // @param order int
  318. // @return dataList []*EdbInfoSearchData
  319. // @return err error
  320. func GetEdbDataListAllByMongo(source, subSource int, findEdbDataListAllCond FindEdbDataListAllCond, order int) (dataList []*EdbInfoSearchData, err error) {
  321. dataList = make([]*EdbInfoSearchData, 0)
  322. if findEdbDataListAllCond.EdbInfoId <= 0 {
  323. return
  324. }
  325. mogDataObj := mgo.EdbDataBusiness{}
  326. // 构建查询条件
  327. queryConditions := bson.M{
  328. "edb_info_id": findEdbDataListAllCond.EdbInfoId,
  329. }
  330. dateCondition, err := mgo.BuildDateCondition(findEdbDataListAllCond.StartDataTime, findEdbDataListAllCond.EndDataTime)
  331. if err != nil {
  332. return
  333. }
  334. if len(dateCondition) > 0 {
  335. queryConditions["data_time"] = dateCondition
  336. }
  337. sortList := make([]string, 0)
  338. if order == 1 {
  339. sortList = append(sortList, "data_time")
  340. } else {
  341. sortList = append(sortList, "-data_time")
  342. }
  343. // 获取列表数据
  344. tmpDataList, tmpErr := mogDataObj.GetAllDataList(queryConditions, sortList)
  345. if tmpErr != nil {
  346. err = tmpErr
  347. return
  348. }
  349. for k, v := range tmpDataList {
  350. dataList = append(dataList, &EdbInfoSearchData{
  351. EdbDataId: k + 1,
  352. EdbInfoId: v.EdbInfoId,
  353. EdbCode: v.EdbCode,
  354. DataTime: v.DataTime.Format(utils.FormatDate),
  355. Value: v.Value,
  356. DataTimestamp: v.DataTimestamp,
  357. })
  358. }
  359. return
  360. }
  361. // EdbInfoMaxAndMinInfo 指标最新数据记录结构体
  362. type EdbInfoMaxAndMinInfo struct {
  363. MinDate string `description:"最小日期" bson:"min_date"`
  364. MaxDate string `description:"最大日期" bson:"max_date"`
  365. MinValue float64 `description:"最小值" bson:"min_value"`
  366. MaxValue float64 `description:"最大值" bson:"max_value"`
  367. LatestValue float64 `description:"最新值" bson:"latest_value"`
  368. LatestDate string `description:"实际数据最新日期" bson:"latest_date"`
  369. EndValue float64 `description:"最新值" bson:"end_value"`
  370. }
  371. // GetEdbInfoMaxAndMinInfo 获取指标的最新数据记录信息
  372. func GetEdbInfoMaxAndMinInfo(source, subSource int, edbCode string) (item *EdbInfoMaxAndMinInfo, err error) {
  373. o := orm.NewOrm()
  374. sql := ``
  375. tableName := GetEdbDataTableName(source, subSource)
  376. sql = ` SELECT MIN(data_time) AS min_date,MAX(data_time) AS max_date,MIN(value) AS min_value,MAX(value) AS max_value FROM %s WHERE edb_code=? `
  377. sql = fmt.Sprintf(sql, tableName)
  378. err = o.Raw(sql, edbCode).QueryRow(&item)
  379. var latest_value float64
  380. sql = ` SELECT value AS latest_value FROM %s WHERE edb_code=? ORDER BY data_time DESC LIMIT 1 `
  381. sql = fmt.Sprintf(sql, tableName)
  382. err = o.Raw(sql, edbCode).QueryRow(&latest_value)
  383. item.LatestValue = latest_value
  384. return
  385. }
  386. type EdbIndoDataUpdateTime struct {
  387. MinDate string `description:"本次更新,数据发生变化的最早日期"`
  388. }
  389. // GetEdbDataUpdateTimeByModify 获取指标的刷新时间获取最早的一条记录
  390. func GetEdbDataUpdateTimeByModify(source, subSource int, edbCode string, dataUpdateTime string) (item *EdbIndoDataUpdateTime, err error) {
  391. o := orm.NewOrm()
  392. sql := ``
  393. tableName := GetEdbDataTableName(source, subSource)
  394. sql = ` SELECT MIN(data_time) AS min_date FROM %s WHERE edb_code=? and modify_time>=?`
  395. sql = fmt.Sprintf(sql, tableName)
  396. err = o.Raw(sql, edbCode, dataUpdateTime).QueryRow(&item)
  397. return
  398. }
  399. // ModifyEdbInfoMaxAndMinInfo 修改指标的最新数据信息
  400. func ModifyEdbInfoMaxAndMinInfo(edbInfoId int, item *EdbInfoMaxAndMinInfo) (err error) {
  401. o := orm.NewOrm()
  402. sql := ` UPDATE edb_info SET start_date=?,end_date=?,min_value=?,max_value=?,is_update=2,latest_date=?,latest_value=?, end_value = ?,modify_time=NOW() WHERE edb_info_id=? `
  403. _, err = o.Raw(sql, item.MinDate, item.MaxDate, item.MinValue, item.MaxValue, item.MaxDate, item.LatestValue, item.LatestValue, edbInfoId).Exec()
  404. return
  405. }
  406. // ModifyEdbTimeAndLastInfo 修改指标的最新数据信息(除上下限)
  407. func ModifyEdbTimeAndLastInfo(edbInfoId int, item *EdbInfoMaxAndMinInfo) (err error) {
  408. o := orm.NewOrm()
  409. sql := `UPDATE edb_info SET start_date = ?, end_date = ?, is_update = 2,latest_date = ?, latest_value = ?, end_value = ?, modify_time = NOW() WHERE edb_info_id = ?`
  410. _, err = o.Raw(sql, item.MinDate, item.MaxDate, item.MaxDate, item.LatestValue, item.LatestValue, edbInfoId).Exec()
  411. return
  412. }
  413. // ModifyEdbDataUpdateTime 修改指标刷新,本次数据刷新的最早日期
  414. func ModifyEdbDataUpdateTime(edbInfoId int, dataUpdateTime, erDataUpdateDate string) (err error) {
  415. o := orm.NewOrm()
  416. sql := `UPDATE edb_info SET data_update_time = ?, er_data_update_date = ?, modify_time = NOW() WHERE edb_info_id = ?`
  417. _, err = o.Raw(sql, dataUpdateTime, erDataUpdateDate, edbInfoId).Exec()
  418. return
  419. }
  420. // GetLteZeroEdbDataCount
  421. // @Description: 获取小于等于0的数据数量
  422. // @author: Roc
  423. // @datetime 2024-05-31 10:44:39
  424. // @param source int
  425. // @param subSource int
  426. // @param edbInfoId int
  427. // @return count int
  428. // @return err error
  429. func GetLteZeroEdbDataCount(source, subSource, edbInfoId int) (count int, err error) {
  430. if source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  431. return GetLteZeroEdbDataCountByMongo(source, subSource, edbInfoId)
  432. }
  433. return GetLteZeroEdbDataCountByMysql(source, subSource, edbInfoId)
  434. }
  435. // GetLteZeroEdbDataCountByMongo
  436. // @Description: 获取小于等于0的数据数量(从mongo)
  437. // @author: Roc
  438. // @datetime 2024-05-31 10:41:04
  439. // @param source int
  440. // @param subSource int
  441. // @param edbInfoId int
  442. // @return count int
  443. // @return err error
  444. func GetLteZeroEdbDataCountByMongo(source, subSource, edbInfoId int) (count int, err error) {
  445. mogDataObj := mgo.EdbDataBusiness{}
  446. // 构建查询条件
  447. whereQuery := bson.M{
  448. "edb_info_id": edbInfoId,
  449. "value": bson.M{"$lte": 0},
  450. }
  451. // 获数量数据
  452. tmpCount, err := mogDataObj.GetCountDataList(whereQuery)
  453. if err != nil {
  454. return
  455. }
  456. count = int(tmpCount)
  457. return
  458. }
  459. // GetLteZeroEdbDataCountByMysql
  460. // @Description: 获取小于等于0的数据数量(从mysql)
  461. // @author: Roc
  462. // @datetime 2024-05-31 10:29:19
  463. // @param source int
  464. // @param subSource int
  465. // @param edbInfoId int
  466. // @return count int
  467. // @return err error
  468. func GetLteZeroEdbDataCountByMysql(source, subSource, edbInfoId int) (count int, err error) {
  469. o := orm.NewOrm()
  470. sql := ``
  471. tableName := GetEdbDataTableName(source, subSource)
  472. sql = ` SELECT COUNT(1) AS count FROM %s WHERE 1=1 AND edb_info_id =? AND value <=0 `
  473. sql = fmt.Sprintf(sql, tableName)
  474. err = o.Raw(sql, edbInfoId).QueryRow(&count)
  475. return
  476. }
  477. // GetLastEdbData 获取最近的一条指标数据
  478. func GetLastEdbData(condition string, pars []interface{}, source, subSource int) (item *EdbInfoSearchData, err error) {
  479. o := orm.NewOrm()
  480. sql := ``
  481. tableName := GetEdbDataTableName(source, subSource)
  482. sql = ` SELECT * FROM %s WHERE 1=1 `
  483. sql = fmt.Sprintf(sql, tableName)
  484. if condition != "" {
  485. sql += condition
  486. }
  487. sql += ` ORDER BY data_time DESC `
  488. err = o.Raw(sql, pars).QueryRow(&item)
  489. return
  490. }
  491. // GetEdbInfoByEdbCode 根据指标code获取指标信息
  492. func GetEdbInfoByEdbCode(source int, edbCode string) (item *EdbInfo, err error) {
  493. o := orm.NewOrm()
  494. sql := ` SELECT * FROM edb_info WHERE source=? AND edb_code=? `
  495. err = o.Raw(sql, source, edbCode).QueryRow(&item)
  496. return
  497. }
  498. // GetEdbInfoOnlyByEdbCode 仅根据指标code获取指标信息
  499. func GetEdbInfoOnlyByEdbCode(edbCode string) (item *EdbInfo, err error) {
  500. o := orm.NewOrm()
  501. sql := ` SELECT * FROM edb_info WHERE edb_code=? `
  502. err = o.Raw(sql, edbCode).QueryRow(&item)
  503. return
  504. }
  505. // GetEdbInfoCalculateListByCondition 获取指标关系列表
  506. func GetEdbInfoCalculateListByCondition(condition string, pars []interface{}) (items []*EdbInfoCalculateMapping, err error) {
  507. o := orm.NewOrm()
  508. sql := ` SELECT * FROM edb_info_calculate_mapping WHERE 1=1 `
  509. if condition != "" {
  510. sql += condition
  511. }
  512. _, err = o.Raw(sql, pars).QueryRows(&items)
  513. return
  514. }
  515. // GetEdbInfoCalculateCountByCondition 获取关联指标数量
  516. func GetEdbInfoCalculateCountByCondition(condition string, pars []interface{}) (count int, err error) {
  517. o := orm.NewOrm()
  518. sql := ` SELECT COUNT(1) AS count FROM edb_info_calculate_mapping WHERE 1=1 `
  519. if condition != "" {
  520. sql += condition
  521. }
  522. err = o.Raw(sql, pars).QueryRow(&count)
  523. return
  524. }
  525. // 优化版本-处理数据精度问题
  526. type EdbInfoSearchDataV1 struct {
  527. EdbDataId int `description:"数据ID"`
  528. DataTime string `description:"数据日期"`
  529. Value string `description:"数据"`
  530. }
  531. // 优化版本-处理数据精度问题
  532. func GetEdbDataListAllV1(condition string, pars []interface{}, source, subSource, order int) (item []*EdbInfoSearchDataV1, err error) {
  533. o := orm.NewOrm()
  534. sql := ``
  535. tableName := GetEdbDataTableName(source, subSource)
  536. sql = ` SELECT * FROM %s WHERE 1=1 `
  537. sql = fmt.Sprintf(sql, tableName)
  538. if condition != "" {
  539. sql += condition
  540. }
  541. if order == 1 {
  542. sql += ` ORDER BY data_time ASC `
  543. } else {
  544. sql += ` ORDER BY data_time DESC `
  545. }
  546. _, err = o.Raw(sql, pars).QueryRows(&item)
  547. return
  548. }
  549. // GetEdbDataListAllV1ByTo 通过事务链接获取数据列表
  550. func GetEdbDataListAllV1ByTo(to orm.TxOrmer, condition string, pars []interface{}, source, subSource, order int) (item []*EdbInfoSearchDataV1, err error) {
  551. sql := ``
  552. tableName := GetEdbDataTableName(source, subSource)
  553. sql = ` SELECT * FROM %s WHERE 1=1 `
  554. sql = fmt.Sprintf(sql, tableName)
  555. if condition != "" {
  556. sql += condition
  557. }
  558. if order == 1 {
  559. sql += ` ORDER BY data_time ASC `
  560. } else {
  561. sql += ` ORDER BY data_time DESC `
  562. }
  563. _, err = to.Raw(sql, pars).QueryRows(&item)
  564. return
  565. }
  566. // GetEdbInfoByCondition 获取指标列表
  567. func GetEdbInfoByCondition(condition string, pars []interface{}, order int) (item []*EdbInfo, err error) {
  568. o := orm.NewOrm()
  569. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  570. if condition != "" {
  571. sql += condition
  572. }
  573. if order == 1 {
  574. sql += ` ORDER BY end_date ASC `
  575. } else {
  576. sql += ` ORDER BY edb_info_id ASC `
  577. }
  578. _, err = o.Raw(sql, pars).QueryRows(&item)
  579. return
  580. }
  581. // UnifiedModifyEdbInfoMaxAndMinInfo 统一修改指标的最大最小值
  582. func UnifiedModifyEdbInfoMaxAndMinInfo(edbInfo *EdbInfo) (err error, errMsg string) {
  583. // 修改最大最小值
  584. maxAndMinItem, err := GetEdbInfoMaxAndMinInfo(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode)
  585. if err != nil {
  586. if err.Error() == utils.ErrNoRow() {
  587. err = nil
  588. return
  589. }
  590. errMsg = "刷新指标失败!"
  591. err = errors.New("获取指标最大最小值失败,err:" + err.Error())
  592. return
  593. }
  594. if maxAndMinItem != nil {
  595. // ETA1.0.3改-如果指标有手动保存过, 那么就不更新指标的最大最小值
  596. if edbInfo.ManualSave == 1 {
  597. err = ModifyEdbTimeAndLastInfo(edbInfo.EdbInfoId, maxAndMinItem)
  598. if err != nil {
  599. errMsg = "刷新指标失败!"
  600. err = errors.New("修改指标最新日期和数据失败,err:" + err.Error())
  601. return
  602. }
  603. } else {
  604. err = ModifyEdbInfoMaxAndMinInfo(edbInfo.EdbInfoId, maxAndMinItem)
  605. if err != nil {
  606. errMsg = "刷新指标失败!"
  607. err = errors.New("修改指标最大最小值失败,err:" + err.Error())
  608. return
  609. }
  610. }
  611. }
  612. // 刷新关联的预测指标
  613. go RefreshPredictStandardBaseByGeneralEdbInfoId(edbInfo.EdbInfoId)
  614. //go ModifyPredictEdbInfoMaxAndMinInfoBySourceEdbInfoId(edbInfo.EdbInfoId, maxAndMinItem)
  615. return
  616. }
  617. // UnifiedModifyEdbInfoMaxAndMinInfoDataUpdate 统一修改指标的最大最小值以及数据更新时间点
  618. func UnifiedModifyEdbInfoMaxAndMinInfoDataUpdate(edbInfo *EdbInfo, dataUpdateTime string) (erDataUpdateDate string, err error, errMsg string) {
  619. err, errMsg = UnifiedModifyEdbInfoMaxAndMinInfo(edbInfo)
  620. if err != nil {
  621. return
  622. }
  623. // 获取本次刷新,指标数据更新的最早日期
  624. erDataUpdateTime, tErr := GetEdbDataUpdateTimeByModify(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode, dataUpdateTime)
  625. if tErr != nil {
  626. if tErr.Error() != utils.ErrNoRow() { //本次刷新指标数据无变化
  627. errMsg = "刷新指标失败!"
  628. err = errors.New("查询指标刷新,数据更新的最早日期失败,err:" + tErr.Error())
  629. return
  630. }
  631. } else if erDataUpdateTime.MinDate != "" {
  632. err = ModifyEdbDataUpdateTime(edbInfo.EdbInfoId, dataUpdateTime, erDataUpdateTime.MinDate)
  633. if err != nil {
  634. errMsg = "刷新指标失败!"
  635. err = errors.New("修改指标数据更新的最早日期失败,err:" + tErr.Error())
  636. return
  637. }
  638. erDataUpdateDate = erDataUpdateTime.MinDate
  639. }
  640. return
  641. }
  642. // UnifiedModifyPredictEdbInfoMaxAndMinInfo 统一修改预测运算指标的最大最小值
  643. func UnifiedModifyPredictEdbInfoMaxAndMinInfo(edbInfo *EdbInfo, latestDateStr string, latestValue float64) (err error, errMsg string) {
  644. // 修改最大最小值
  645. maxAndMinItem, err := GetEdbInfoMaxAndMinInfo(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode)
  646. if err != nil {
  647. if err.Error() == utils.ErrNoRow() {
  648. err = nil
  649. return
  650. }
  651. errMsg = "刷新指标失败!"
  652. err = errors.New("获取指标最大最小值失败,err:" + err.Error())
  653. return
  654. }
  655. // 最晚的日期的值
  656. maxAndMinItem.EndValue = maxAndMinItem.LatestValue
  657. if maxAndMinItem != nil {
  658. maxAndMinItem.LatestDate = latestDateStr
  659. maxAndMinItem.LatestValue = latestValue
  660. err = ModifyPredictEdbInfoMaxAndMinInfo(edbInfo.EdbInfoId, maxAndMinItem)
  661. if err != nil {
  662. errMsg = "刷新指标失败!"
  663. err = errors.New("修改指标最大最小值失败,err:" + err.Error())
  664. return
  665. }
  666. }
  667. return
  668. }
  669. // GetChartPredictEdbInfoDataListByConfList 获取图表的预测指标的未来数据
  670. func GetChartPredictEdbInfoDataListByConfList(predictEdbConfList []*PredictEdbConfAndData, filtrateStartDateStr, latestDateStr, endDateStr, frequency, dataDateType string, endDateType int, realPredictEdbInfoData []*EdbInfoSearchData) (predictEdbInfoData []*EdbInfoSearchData, minValue, maxValue float64, err error) {
  671. hasEndNum := 0 //如果选择了未来期数,用来保存已经预测过的期数
  672. var endDate time.Time
  673. if endDateStr != `` {
  674. endDate, err = time.ParseInLocation(utils.FormatDate, endDateStr, time.Local)
  675. if err != nil {
  676. return
  677. }
  678. }
  679. latestDate, err := time.ParseInLocation(utils.FormatDate, latestDateStr, time.Local)
  680. if err != nil {
  681. return
  682. }
  683. // 开始预测数据的时间
  684. startDate := latestDate
  685. // 如果有筛选时间的话
  686. if filtrateStartDateStr != `` {
  687. filtrateStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, filtrateStartDateStr, time.Local)
  688. if tmpErr != nil {
  689. err = tmpErr
  690. return
  691. }
  692. //如果筛选时间晚于实际数据时间,那么就以筛选时间作为获取预测数据的时间
  693. if filtrateStartDate.After(latestDate) {
  694. startDate = filtrateStartDate.AddDate(0, 0, -1)
  695. }
  696. }
  697. //var dateArr []string
  698. // 对应日期的值
  699. existMap := make(map[string]float64)
  700. for _, v := range realPredictEdbInfoData {
  701. //dateArr = append(dateArr, v.DataTime)
  702. existMap[v.DataTime] = v.Value
  703. }
  704. predictEdbInfoData = make([]*EdbInfoSearchData, 0)
  705. //dataValue := lastDataValue
  706. //预测规则,1:最新,2:固定值,3:同比,4:同差,5:环比,6:环差,7:N期移动均值,8:N期段线性外推值
  707. for _, predictEdbConf := range predictEdbConfList {
  708. //dataEndTime := endDate
  709. //if predictEdbConf.EndDate.Before(dataEndTime) {
  710. // dataEndTime = predictEdbConf.EndDate
  711. //}
  712. //endDate = predictEdbConf.EndDate
  713. var tmpMinValue, tmpMaxValue float64 // 当前预测结果中的最大/最小值
  714. endNum := predictEdbConf.EndNum - hasEndNum
  715. dayList := getPredictEdbDayList(startDate, predictEdbConf.EndDate, frequency, dataDateType, endDateType, endNum)
  716. if len(dayList) <= 0 { // 如果未来没有日期的话,那么就退出当前循环,进入下一个循环
  717. continue
  718. }
  719. endDate = dayList[len(dayList)-1]
  720. switch predictEdbConf.RuleType {
  721. case 1: //1:最新
  722. var lastDataValue float64 //最新值
  723. tmpAllData := make([]*EdbInfoSearchData, 0)
  724. tmpAllData = append(tmpAllData, realPredictEdbInfoData...)
  725. tmpAllData = append(tmpAllData, predictEdbInfoData...)
  726. lenTmpAllData := len(tmpAllData)
  727. if lenTmpAllData > 0 {
  728. lastDataValue = tmpAllData[lenTmpAllData-1].Value
  729. }
  730. predictEdbInfoData = GetChartPredictEdbInfoDataListByRule1(predictEdbConf.PredictEdbInfoId, lastDataValue, dayList, predictEdbInfoData, existMap)
  731. tmpMaxValue = lastDataValue
  732. tmpMinValue = lastDataValue
  733. case 2: //2:固定值
  734. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  735. if tmpErr != nil {
  736. err = tmpErr
  737. return
  738. }
  739. dataValue, _ := tmpValDecimal.Float64()
  740. predictEdbInfoData = GetChartPredictEdbInfoDataListByRule1(predictEdbConf.PredictEdbInfoId, dataValue, dayList, predictEdbInfoData, existMap)
  741. tmpMaxValue = dataValue
  742. tmpMinValue = dataValue
  743. case 3: //3:同比
  744. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  745. if tmpErr != nil {
  746. err = tmpErr
  747. return
  748. }
  749. tbValue, _ := tmpValDecimal.Float64()
  750. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTb(predictEdbConf.PredictEdbInfoId, tbValue, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
  751. case 4: //4:同差
  752. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  753. if tmpErr != nil {
  754. err = tmpErr
  755. return
  756. }
  757. tcValue, _ := tmpValDecimal.Float64()
  758. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTc(predictEdbConf.PredictEdbInfoId, tcValue, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
  759. case 5: //5:环比
  760. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  761. if tmpErr != nil {
  762. err = tmpErr
  763. return
  764. }
  765. hbValue, _ := tmpValDecimal.Float64()
  766. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleHb(predictEdbConf.PredictEdbInfoId, hbValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  767. case 6: //6:环差
  768. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  769. if tmpErr != nil {
  770. err = tmpErr
  771. return
  772. }
  773. hcValue, _ := tmpValDecimal.Float64()
  774. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleHc(predictEdbConf.PredictEdbInfoId, hcValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  775. case 7: //7:N期移动均值
  776. nValue, tmpErr := strconv.Atoi(predictEdbConf.Value)
  777. if tmpErr != nil {
  778. err = tmpErr
  779. return
  780. }
  781. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleNMoveMeanValue(predictEdbConf.PredictEdbInfoId, nValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  782. case 8: //8:N期段线性外推值
  783. nValue, tmpErr := strconv.Atoi(predictEdbConf.Value)
  784. if tmpErr != nil {
  785. err = tmpErr
  786. return
  787. }
  788. predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleNLinearRegression(predictEdbConf.PredictEdbInfoId, nValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  789. if err != nil {
  790. return
  791. }
  792. case 9: //9:动态环差”预测规则;
  793. hcDataMap := make(map[string]float64) //规则计算的环差值map
  794. if predictEdbConf.PredictEdbInfoId > 0 {
  795. tmpPredictEdbRuleDataList, tmpErr := GetPredictEdbRuleDataItemList(predictEdbConf.PredictEdbInfoId, predictEdbConf.ConfigId, startDate.Format(utils.FormatDate), endDate.Format(utils.FormatDate))
  796. if tmpErr != nil {
  797. err = tmpErr
  798. return
  799. }
  800. for _, v := range tmpPredictEdbRuleDataList {
  801. hcDataMap[v.DataTime] = v.Value
  802. }
  803. } else {
  804. if len(predictEdbConf.DataList) <= 0 {
  805. return
  806. }
  807. for _, v := range predictEdbConf.DataList {
  808. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  809. if tmpErr != nil {
  810. continue
  811. }
  812. // 只处理时间段内的数据
  813. if currentDate.Before(startDate) || currentDate.After(endDate) {
  814. continue
  815. }
  816. hcDataMap[v.DataTime] = v.Value
  817. }
  818. }
  819. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTrendsHC(predictEdbConf.PredictEdbInfoId, dayList, realPredictEdbInfoData, predictEdbInfoData, hcDataMap, existMap)
  820. case 10: //10:根据 给定终值后插值 规则获取预测数据
  821. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  822. if tmpErr != nil {
  823. err = tmpErr
  824. return
  825. }
  826. finalValue, _ := tmpValDecimal.Float64()
  827. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleFinalValueHc(predictEdbConf.PredictEdbInfoId, finalValue, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  828. case 11: //11:根据 季节性 规则获取预测数据
  829. var seasonConf SeasonConf
  830. tmpErr := json.Unmarshal([]byte(predictEdbConf.Value), &seasonConf)
  831. if tmpErr != nil {
  832. err = errors.New("季节性配置信息异常:" + tmpErr.Error())
  833. return
  834. }
  835. calendar := "公历"
  836. if seasonConf.Calendar == "农历" {
  837. calendar = "农历"
  838. }
  839. yearList := make([]int, 0)
  840. //选择方式,1:连续N年;2:指定年份
  841. if seasonConf.YearType == 1 {
  842. if seasonConf.NValue < 1 {
  843. err = errors.New("连续N年不允许小于1")
  844. return
  845. }
  846. currYear := time.Now().Year()
  847. for i := 0; i < seasonConf.NValue; i++ {
  848. yearList = append(yearList, currYear-i-1)
  849. }
  850. } else {
  851. yearList = seasonConf.YearList
  852. }
  853. predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleSeason(predictEdbConf.PredictEdbInfoId, yearList, calendar, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  854. if err != nil {
  855. return
  856. }
  857. case 12: //12:根据 移动平均同比 规则获取预测数据
  858. var moveAverageConf MoveAverageConf
  859. tmpErr := json.Unmarshal([]byte(predictEdbConf.Value), &moveAverageConf)
  860. if tmpErr != nil {
  861. err = errors.New("季节性配置信息异常:" + tmpErr.Error())
  862. return
  863. }
  864. predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleMoveAverageTb(predictEdbConf.PredictEdbInfoId, moveAverageConf.NValue, moveAverageConf.Year, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  865. if err != nil {
  866. return
  867. }
  868. case 13: //13:根据 同比增速差值 规则获取预测数据
  869. tmpValDecimal, tmpErr := decimal.NewFromString(predictEdbConf.Value)
  870. if tmpErr != nil {
  871. err = tmpErr
  872. return
  873. }
  874. tbEndValue, _ := tmpValDecimal.Float64()
  875. predictEdbInfoData, tmpMinValue, tmpMaxValue = GetChartPredictEdbInfoDataListByRuleTbzscz(predictEdbConf.PredictEdbInfoId, tbEndValue, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
  876. case 14: //14:根据 一元线性拟合 规则获取预测数据
  877. var ruleConf RuleLineNhConf
  878. err = json.Unmarshal([]byte(predictEdbConf.Value), &ruleConf)
  879. if err != nil {
  880. err = errors.New("一元线性拟合规则配置信息异常:" + err.Error())
  881. return
  882. }
  883. // 规则计算的拟合残差值map
  884. newNhccDataMap := make(map[string]float64)
  885. if predictEdbConf.PredictEdbInfoId > 0 { //已经生成的动态数据
  886. tmpPredictEdbRuleDataList, tmpErr := GetPredictEdbRuleDataItemList(predictEdbConf.PredictEdbInfoId, predictEdbConf.ConfigId, startDate.Format(utils.FormatDate), endDate.Format(utils.FormatDate))
  887. if tmpErr != nil {
  888. err = tmpErr
  889. return
  890. }
  891. for _, v := range tmpPredictEdbRuleDataList {
  892. newNhccDataMap[v.DataTime] = v.Value
  893. }
  894. } else { //未生成的动态数据,需要使用外部传入的数据进行计算
  895. newNhccDataMap, err, _ = getCalculateNhccData(append(realPredictEdbInfoData, predictEdbInfoData...), ruleConf)
  896. }
  897. predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleLineNh(predictEdbConf.PredictEdbInfoId, dayList, realPredictEdbInfoData, predictEdbInfoData, newNhccDataMap, existMap)
  898. if err != nil {
  899. return
  900. }
  901. case 15: //15:N年均值:过去N年同期均值。过去N年可以连续或者不连续,指标数据均用线性插值补全为日度数据后计算;
  902. predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleNAnnualAverage(predictEdbConf.PredictEdbInfoId, predictEdbConf.Value, dayList, realPredictEdbInfoData, predictEdbInfoData, existMap)
  903. if err != nil {
  904. return
  905. }
  906. case 16: //16:年度值倒推
  907. predictEdbInfoData, tmpMinValue, tmpMaxValue, err = GetChartPredictEdbInfoDataListByRuleAnnualValueInversion(predictEdbConf.PredictEdbInfoId, predictEdbConf.Value, dayList, frequency, realPredictEdbInfoData, predictEdbInfoData, existMap)
  908. if err != nil {
  909. return
  910. }
  911. }
  912. // 下一个规则的开始日期
  913. {
  914. lenPredictEdbInfoData := len(predictEdbInfoData)
  915. if lenPredictEdbInfoData > 0 {
  916. if endDateType == 1 {
  917. hasEndNum = predictEdbConf.EndNum
  918. }
  919. tmpDataEndTime, _ := time.ParseInLocation(utils.FormatDate, predictEdbInfoData[lenPredictEdbInfoData-1].DataTime, time.Local)
  920. if startDate.Before(tmpDataEndTime) {
  921. startDate = tmpDataEndTime
  922. }
  923. }
  924. }
  925. if tmpMinValue < minValue {
  926. minValue = tmpMinValue
  927. }
  928. if tmpMaxValue < maxValue {
  929. maxValue = tmpMaxValue
  930. }
  931. }
  932. return
  933. }
  934. // GetPredictEdbDayList 获取预测指标日期列表
  935. // GetPredictEdbDayList 获取预测指标日期列表
  936. func getPredictEdbDayList(startDate, endDate time.Time, frequency, dataDateType string, endDateType, endNum int) (dayList []time.Time) {
  937. if dataDateType == `` {
  938. dataDateType = `交易日`
  939. }
  940. if endDateType == 0 { // 截止日期
  941. switch frequency {
  942. case "日度":
  943. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
  944. // 如果日期类型是交易日的时候,那么需要将周六、日排除
  945. if dataDateType == `交易日` && (currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday) {
  946. continue
  947. }
  948. dayList = append(dayList, currDate)
  949. }
  950. case "周度":
  951. //nextDate := startDate.AddDate(0, 0, 7)
  952. for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
  953. dayList = append(dayList, currDate)
  954. }
  955. case "旬度":
  956. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
  957. nextDate := currDate.AddDate(0, 0, 1)
  958. //每个月的10号、20号、最后一天,那么就写入
  959. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  960. dayList = append(dayList, currDate)
  961. }
  962. currDate = nextDate
  963. }
  964. case "月度":
  965. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  966. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  967. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  968. dayList = append(dayList, currDate)
  969. }
  970. currDate = currDate.AddDate(0, 0, 1)
  971. }
  972. case "季度":
  973. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  974. // 每月的最后一天
  975. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  976. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  977. // 季度日期就写入,否则不写入
  978. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  979. dayList = append(dayList, currDate)
  980. }
  981. }
  982. currDate = currDate.AddDate(0, 0, 1)
  983. }
  984. case "半年度":
  985. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  986. // 每月的最后一天
  987. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  988. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  989. // 半年度日期就写入,否则不写入
  990. if currDate.Month() == 6 || currDate.Month() == 12 {
  991. dayList = append(dayList, currDate)
  992. }
  993. }
  994. currDate = currDate.AddDate(0, 0, 1)
  995. }
  996. case "年度":
  997. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  998. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  999. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1000. dayList = append(dayList, currDate)
  1001. }
  1002. }
  1003. }
  1004. } else { // 截止期数
  1005. switch frequency {
  1006. case "日度":
  1007. for i := 1; i <= endNum; i++ {
  1008. currDate := startDate.AddDate(0, 0, i)
  1009. // 如果日期类型是交易日的时候,那么需要将周六、日排除
  1010. if dataDateType == `交易日` && (currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday) {
  1011. continue
  1012. }
  1013. dayList = append(dayList, currDate)
  1014. }
  1015. case "周度":
  1016. for i := 1; i <= endNum; i++ {
  1017. currDate := startDate.AddDate(0, 0, i*7)
  1018. dayList = append(dayList, currDate)
  1019. }
  1020. case "旬度":
  1021. currDate := startDate
  1022. for i := 1; len(dayList) < endNum; i++ {
  1023. currDate = currDate.AddDate(0, 0, 1)
  1024. nextDate := currDate.AddDate(0, 0, 1)
  1025. //每个月的10号、20号、最后一天,那么就写入
  1026. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1027. dayList = append(dayList, currDate)
  1028. }
  1029. }
  1030. case "月度":
  1031. currDate := startDate
  1032. for i := 0; i <= endNum; i++ {
  1033. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1034. if !currDate.Equal(startDate) {
  1035. dayList = append(dayList, currDate)
  1036. }
  1037. currDate = currDate.AddDate(0, 0, 1)
  1038. }
  1039. case "季度":
  1040. currDate := startDate
  1041. endNum = endNum * 3
  1042. for i := 0; i <= endNum; i++ {
  1043. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1044. if currDate.After(startDate) {
  1045. // 季度日期就写入,否则不写入
  1046. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1047. dayList = append(dayList, currDate)
  1048. }
  1049. }
  1050. currDate = currDate.AddDate(0, 0, 1)
  1051. }
  1052. case "半年度":
  1053. currDate := startDate
  1054. endNum = endNum * 6
  1055. for i := 0; i <= endNum; i++ {
  1056. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1057. if currDate.After(startDate) {
  1058. // 季度日期就写入,否则不写入
  1059. if currDate.Month() == 6 || currDate.Month() == 12 {
  1060. dayList = append(dayList, currDate)
  1061. }
  1062. }
  1063. currDate = currDate.AddDate(0, 0, 1)
  1064. }
  1065. case "年度":
  1066. for i := 1; i <= endNum; i++ {
  1067. currDate := startDate.AddDate(i, 0, 0)
  1068. currDate, _ = time.ParseInLocation(utils.FormatDate, fmt.Sprintf(`%d-12-31`, currDate.Year()), time.Local)
  1069. dayList = append(dayList, currDate)
  1070. }
  1071. }
  1072. }
  1073. return
  1074. }
  1075. // GetPredictDataListByPredictEdbInfo 根据预测指标信息获取预测指标的数据,order:1升序,其余值为降序
  1076. func GetPredictDataListByPredictEdbInfo(edbInfo *EdbInfo, order int, startDate string) (dataList []*EdbInfoSearchData, sourceEdbInfoItem *EdbInfo, err error, errMsg string) {
  1077. // 查找该预测指标配置
  1078. predictEdbConfList, err := GetPredictEdbConfAndDataListById(edbInfo.EdbInfoId)
  1079. if err != nil && err.Error() != utils.ErrNoRow() {
  1080. errMsg = "获取预测指标配置信息失败"
  1081. return
  1082. }
  1083. if len(predictEdbConfList) == 0 {
  1084. errMsg = "获取预测指标配置信息失败"
  1085. err = errors.New(errMsg)
  1086. return
  1087. }
  1088. predictEdbConf := predictEdbConfList[0]
  1089. // 来源指标
  1090. sourceEdbInfoItem, err = GetEdbInfoById(predictEdbConf.SourceEdbInfoId)
  1091. if err != nil {
  1092. if err.Error() == utils.ErrNoRow() {
  1093. errMsg = "找不到来源指标信息"
  1094. err = errors.New(errMsg)
  1095. }
  1096. return
  1097. }
  1098. dataList, err, errMsg = GetPredictDataListByPredictEdbConfList(edbInfo, sourceEdbInfoItem, predictEdbConfList, order, startDate)
  1099. return
  1100. }
  1101. // GetPredictDataListByPredictEdbConfList 根据预测指标信息获取预测指标的数据,order:1升序,其余值为降序
  1102. func GetPredictDataListByPredictEdbConfList(edbInfo, sourceEdbInfoItem *EdbInfo, predictEdbConfList []*PredictEdbConfAndData, order int, startDate string) (dataList []*EdbInfoSearchData, err error, errMsg string) {
  1103. allDataList := make([]*EdbInfoSearchData, 0)
  1104. //获取指标数据(实际已生成)
  1105. tmpDataList, err := GetEdbDataListAll(sourceEdbInfoItem.Source, sourceEdbInfoItem.SubSource, FindEdbDataListAllCond{
  1106. EdbInfoId: sourceEdbInfoItem.EdbInfoId,
  1107. StartDataTime: startDate,
  1108. StartDataTimeCond: ">=",
  1109. }, 1)
  1110. if err != nil {
  1111. return
  1112. }
  1113. // 默认认为上一个查询是把所有的数据查出来了
  1114. allDataList = tmpDataList
  1115. // 如果条件中有选择了日期,那么上次查询实际并不是把所有的数据查出来了
  1116. // 那么需要把日期给过滤掉,然后筛选所有的数据,用于未来指标的生成
  1117. if startDate != `` {
  1118. allDataList, err = GetEdbDataListAll(sourceEdbInfoItem.Source, sourceEdbInfoItem.SubSource, FindEdbDataListAllCond{
  1119. EdbInfoId: sourceEdbInfoItem.EdbInfoId,
  1120. }, 1)
  1121. if err != nil {
  1122. return
  1123. }
  1124. }
  1125. // 获取预测指标未来的数据
  1126. predictDataList := make([]*EdbInfoSearchData, 0)
  1127. endDateStr := edbInfo.EndDate //预测指标的结束日期
  1128. var predictMinValue, predictMaxValue float64
  1129. // 如果有配置的预测规则,那么就进行预测
  1130. if len(predictEdbConfList) > 0 {
  1131. predictDataList, predictMinValue, predictMaxValue, err = GetChartPredictEdbInfoDataListByConfList(predictEdbConfList, startDate, sourceEdbInfoItem.LatestDate, endDateStr, edbInfo.Frequency, edbInfo.DataDateType, edbInfo.EndDateType, allDataList)
  1132. if err != nil {
  1133. return
  1134. }
  1135. }
  1136. //order:1升序,其余值为降序
  1137. if order == 1 {
  1138. dataList = append(tmpDataList, predictDataList...)
  1139. } else {
  1140. // 先倒序预测数据
  1141. lenPredictDataList := len(predictDataList)
  1142. if lenPredictDataList > 0 {
  1143. for k := range predictDataList {
  1144. dataList = append(dataList, predictDataList[lenPredictDataList-k-1])
  1145. }
  1146. }
  1147. // 接着倒序实际指标
  1148. lenDataList := len(tmpDataList)
  1149. for k := range tmpDataList {
  1150. dataList = append(dataList, tmpDataList[lenDataList-k-1])
  1151. }
  1152. }
  1153. if len(predictDataList) > 0 {
  1154. // 如果最小值 大于 预测值,那么将预测值作为最小值数据返回
  1155. if edbInfo.MinValue > predictMinValue {
  1156. edbInfo.MinValue = predictMinValue
  1157. }
  1158. // 如果最大值 小于 预测值,那么将预测值作为最大值数据返回
  1159. if edbInfo.MaxValue < predictMaxValue {
  1160. edbInfo.MaxValue = predictMaxValue
  1161. }
  1162. }
  1163. return
  1164. }
  1165. // GetPredictEdbDataListAll 获取该预测指标所有的数据 ,order:1升序,其余值为降序
  1166. func GetPredictEdbDataListAll(edbInfo *EdbInfo, order int) (items []*EdbInfoSearchData, err error) {
  1167. /*if edbInfo.Source == utils.DATA_SOURCE_PREDICT { //普通的预测指标是没有入库数据的,直接往配置里面获取
  1168. items, _, err, _ = GetPredictDataListByPredictEdbInfo(edbInfo, 1, "")
  1169. } else {*/
  1170. items, err = GetEdbDataListAll(edbInfo.Source, edbInfo.SubSource, FindEdbDataListAllCond{
  1171. EdbInfoId: edbInfo.EdbInfoId,
  1172. }, order)
  1173. //}
  1174. return
  1175. }
  1176. // GetPredictEdbDataListAllByStartDate 根据开始日期获取该预测指标所有的数据 ,order:1升序,其余值为降序
  1177. func GetPredictEdbDataListAllByStartDate(edbInfo *EdbInfo, order int, startDate string) (items []*EdbInfoSearchData, err error) {
  1178. /*if edbInfo.Source == utils.DATA_SOURCE_PREDICT { //普通的预测指标是没有入库数据的,直接往配置里面获取
  1179. items, _, err, _ = GetPredictDataListByPredictEdbInfo(edbInfo, order, startDate)
  1180. } else {*/
  1181. items, err = GetEdbDataListAll(edbInfo.Source, edbInfo.SubSource, FindEdbDataListAllCond{
  1182. EdbInfoId: edbInfo.EdbInfoId,
  1183. StartDataTime: startDate,
  1184. StartDataTimeCond: ">=",
  1185. }, order)
  1186. //}
  1187. return
  1188. }
  1189. // ModifyPredictEdbInfoMaxAndMinInfo 修改预测指标的最新数据信息
  1190. func ModifyPredictEdbInfoMaxAndMinInfo(edbInfoId int, item *EdbInfoMaxAndMinInfo) (err error) {
  1191. o := orm.NewOrm()
  1192. sql := ` UPDATE edb_info SET start_date=?,end_date=?,min_value=?,max_value=?,is_update=2,latest_date=?,latest_value=?,end_value=?,modify_time=NOW() WHERE edb_info_id=? `
  1193. _, err = o.Raw(sql, item.MinDate, item.MaxDate, item.MinValue, item.MaxValue, item.LatestDate, item.LatestValue, item.EndValue, edbInfoId).Exec()
  1194. return
  1195. }
  1196. // ModifyCalculateEdbInfo 修改计算指标信息
  1197. func ModifyCalculateEdbInfo(edbName, frequency, unit, calculateFormula string, classifyId, edbInfoId int) (err error) {
  1198. o := orm.NewOrm()
  1199. sql := ` UPDATE edb_info
  1200. SET
  1201. edb_name =?,
  1202. edb_name_source =?,
  1203. frequency = ?,
  1204. unit = ?,
  1205. classify_id = ?,
  1206. calculate_formula=?,
  1207. modify_time = NOW()
  1208. WHERE edb_info_id = ?`
  1209. _, err = o.Raw(sql, edbName, edbName, frequency, unit, classifyId, calculateFormula, edbInfoId).Exec()
  1210. return
  1211. }
  1212. func GetEdbInfoItemByCondition(condition string, pars []interface{}) (item *EdbInfoList, err error) {
  1213. o := orm.NewOrm()
  1214. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  1215. if condition != "" {
  1216. sql += condition
  1217. }
  1218. err = o.Raw(sql, pars).QueryRow(&item)
  1219. return
  1220. }
  1221. func GetEdbInfoItemListByCondition() (items []*EdbInfoList, err error) {
  1222. o := orm.NewOrm()
  1223. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  1224. _, err = o.Raw(sql).QueryRows(&items)
  1225. return
  1226. }
  1227. // EdbInfoDetailReq 指标详情请求
  1228. type EdbInfoDetailReq struct {
  1229. UniqueCode string `description:"指标唯一编码"`
  1230. EdbCode string `description:"指标编码"`
  1231. }
  1232. // EdbInfoDetailResp 指标详情返回
  1233. type EdbInfoDetailResp struct {
  1234. SourceName string `description:"来源名称"`
  1235. EdbCode string `description:"指标编码"`
  1236. EdbName string `description:"指标名称"`
  1237. EdbNameSource string `description:"指标名称来源"`
  1238. Frequency string `description:"频率"`
  1239. Unit string `description:"单位"`
  1240. StartDate string `description:"起始日期"`
  1241. EndDate string `description:"终止日期"`
  1242. UniqueCode string `description:"指标唯一编码"`
  1243. CreateTime time.Time
  1244. ModifyTime time.Time
  1245. MinValue float64 `description:"指标最小值"`
  1246. MaxValue float64 `description:"指标最大值"`
  1247. EdbNameEn string `description:"英文指标名称"`
  1248. UnitEn string `description:"英文单位"`
  1249. LatestDate string `description:"数据最新日期"`
  1250. LatestValue float64 `description:"数据最新值"`
  1251. ChartImage string `description:"图表图片"`
  1252. DataList []*EdbInfoSearchData
  1253. }
  1254. type AddEdbInfoParams struct {
  1255. Source int `description:"来源id"`
  1256. EdbCode string `description:"指标编码"`
  1257. EdbName string `description:"指标名称"`
  1258. Frequency string `description:"频率"`
  1259. Unit string `description:"单位"`
  1260. ClassifyId int `description:"分类id"`
  1261. TerminalCode string `description:"终端编码"`
  1262. AdminId int `description:"创建人ID"`
  1263. AdminName string `description:"创建人姓名"`
  1264. }
  1265. // EdbInfoAdd 添加指标到指标库
  1266. func EdbInfoAdd(req *AddEdbInfoParams, serverUrl string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  1267. source := req.Source
  1268. //判断指标名称是否存在
  1269. var condition string
  1270. var pars []interface{}
  1271. //condition += " AND source=? "
  1272. //pars = append(pars, source)
  1273. condition += " AND edb_code=? "
  1274. pars = append(pars, req.EdbCode)
  1275. items, err := GetEdbInfoByCondition(condition, pars, 0)
  1276. if err != nil {
  1277. err = errors.New("判断指标是否存在失败,Err:" + err.Error())
  1278. return
  1279. }
  1280. if len(items) > 0 {
  1281. sql := ` UPDATE edb_info SET classify_id=?,modify_time=NOW() WHERE edb_code=? `
  1282. o := orm.NewOrm()
  1283. _, err = o.Raw(sql, req.ClassifyId, req.EdbCode).Exec()
  1284. if err != nil {
  1285. err = errors.New("更新指标分类信息失败,Err:" + err.Error())
  1286. return
  1287. }
  1288. edbInfo = items[0]
  1289. return
  1290. }
  1291. edbInfo = new(EdbInfo)
  1292. edbInfo.Source = source
  1293. sourceNameMap := map[int]string{
  1294. utils.DATA_SOURCE_THS: "同花顺",
  1295. utils.DATA_SOURCE_WIND: "wind",
  1296. utils.DATA_SOURCE_PB: "彭博",
  1297. utils.DATA_SOURCE_PB_FINANCE: "彭博财务",
  1298. utils.DATA_SOURCE_MANUAL: "手工数据",
  1299. utils.DATA_SOURCE_LZ: "隆众",
  1300. utils.DATA_SOURCE_YS: "SMM",
  1301. utils.DATA_SOURCE_GL: "上海钢联",
  1302. utils.DATA_SOURCE_ZZ: "郑商所",
  1303. utils.DATA_SOURCE_DL: "大商所",
  1304. utils.DATA_SOURCE_SH: "上期所",
  1305. utils.DATA_SOURCE_CFFEX: "中金所",
  1306. utils.DATA_SOURCE_SHFE: "上期能源",
  1307. utils.DATA_SOURCE_GIE: "欧洲天然气",
  1308. utils.DATA_SOURCE_LT: "路透",
  1309. utils.DATA_SOURCE_COAL: "中国煤炭市场网",
  1310. utils.DATA_SOURCE_GOOGLE_TRAVEL: "our world in data",
  1311. utils.DATA_SOURCE_MYSTEEL_CHEMICAL: "上海钢联",
  1312. utils.DATA_SOURCE_EIA_STEO: "EIA STEO报告",
  1313. utils.DATA_SOURCE_COM_TRADE: "UN",
  1314. utils.DATA_SOURCE_SCI: "SCI",
  1315. utils.DATA_SOURCE_BAIINFO: "BAIINFO",
  1316. utils.DATA_SOURCE_STOCK_PLANT: "存量装置",
  1317. utils.DATA_SOURCE_NATIONAL_STATISTICS: "国家统计局",
  1318. utils.DATA_SOURCE_FUBAO: "富宝数据",
  1319. }
  1320. sourceName, ok := sourceNameMap[source]
  1321. if !ok {
  1322. edbSource := EdbSourceIdMap[source]
  1323. if edbSource != nil {
  1324. sourceName = edbSource.SourceName
  1325. }
  1326. if sourceName == "" {
  1327. err = errors.New("指标来源异常")
  1328. return
  1329. }
  1330. }
  1331. edbInfo.SourceName = sourceName
  1332. edbType := 1 //基础指标
  1333. if source == utils.DATA_SOURCE_STOCK_PLANT {
  1334. edbType = 2 //计算指标
  1335. }
  1336. var sourceIndexName string
  1337. // 上海钢联需要校验下信息是否完整
  1338. if source == utils.DATA_SOURCE_MYSTEEL_CHEMICAL {
  1339. indexObj := new(BaseFromMysteelChemicalIndex)
  1340. tmpItem, tmpErr := indexObj.GetIndexItem(req.EdbCode)
  1341. if tmpErr != nil {
  1342. err = tmpErr
  1343. return
  1344. }
  1345. if tmpItem == nil || tmpItem.IndexName == `` {
  1346. err = errors.New("指标信息不全")
  1347. return
  1348. }
  1349. // 兼容数据
  1350. {
  1351. if req.Frequency == `` {
  1352. req.Frequency = tmpItem.Frequency
  1353. }
  1354. if req.Unit == `` {
  1355. req.Unit = tmpItem.Unit
  1356. }
  1357. }
  1358. }
  1359. edbInfo.EdbCode = req.EdbCode
  1360. edbInfo.EdbName = req.EdbName
  1361. edbInfo.EdbNameSource = req.EdbName
  1362. edbInfo.EdbNameEn = req.EdbName
  1363. edbInfo.Frequency = req.Frequency
  1364. edbInfo.Unit = req.Unit
  1365. edbInfo.UnitEn = req.Unit
  1366. edbInfo.ClassifyId = req.ClassifyId
  1367. edbInfo.SysUserId = sysUserId
  1368. edbInfo.SysUserRealName = sysUserRealName
  1369. edbInfo.StartDate = "1990-01-01"
  1370. edbInfo.CreateTime = time.Now()
  1371. edbInfo.ModifyTime = time.Now()
  1372. edbInfo.ServerUrl = serverUrl
  1373. edbInfo.TerminalCode = req.TerminalCode
  1374. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, 0)
  1375. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  1376. edbInfo.UniqueCode = utils.MD5(utils.DATA_PREFIX + "_" + req.EdbCode + timestamp)
  1377. itemVal, err := GetEdbInfoMaxAndMinInfo(source, utils.DATA_SUB_SOURCE_EDB, req.EdbCode)
  1378. if itemVal != nil && err == nil {
  1379. edbInfo.MaxValue = itemVal.MaxValue
  1380. edbInfo.MinValue = itemVal.MinValue
  1381. }
  1382. edbInfo.EdbType = edbType
  1383. edbInfo.SourceIndexName = sourceIndexName
  1384. edbInfoId, err := AddEdbInfo(edbInfo)
  1385. if err != nil {
  1386. err = errors.New("保存失败,Err:" + err.Error())
  1387. return
  1388. }
  1389. edbInfo.EdbInfoId = int(edbInfoId)
  1390. return
  1391. }
  1392. func ModifyEdbInfoBaseTimeById(edbInfoId int, cTime time.Time) (err error) {
  1393. o := orm.NewOrm()
  1394. // 更新修改时间
  1395. sql := ` UPDATE edb_info SET base_modify_time = ? WHERE edb_info_id = ? `
  1396. _, err = o.Raw(sql, cTime, edbInfoId).Exec()
  1397. return
  1398. }
  1399. // EdbInfoRefreshCheckReq 指标数据更新情况查询
  1400. type EdbInfoRefreshCheckReq struct {
  1401. Source int `description:"来源id"`
  1402. LatestDate string `description:"数据最新日期"`
  1403. FrequencyBatch string `description:"更新频度"`
  1404. }
  1405. // EdbInfoRefreshCheckResp 指标数据更新情况查询
  1406. type EdbInfoRefreshCheckResp struct {
  1407. UpdateNum int `description:"已更新指标数"`
  1408. UnUpdateNum int `description:"未更新指标数"`
  1409. }
  1410. // ResetEdbClassifyReq 指标重新分类请求体
  1411. type ResetEdbClassifyReq struct {
  1412. IndexCode string `description:"指标编码"`
  1413. ClassifyFirst string `description:"一级分类名称"`
  1414. ClassifySecond string `description:"二级分类名称"`
  1415. ClassifyThird string `description:"三级分类名称"`
  1416. }
  1417. // GetEdbInfoMaxSortByClassifyId 获取分类下指标的最大的排序数
  1418. func GetEdbInfoMaxSortByClassifyId(classifyId int) (sort int, err error) {
  1419. o := orm.NewOrm()
  1420. sql := `SELECT Max(sort) AS sort FROM edb_info WHERE classify_id=? `
  1421. err = o.Raw(sql, classifyId).QueryRow(&sort)
  1422. return
  1423. }
  1424. func GetEdbAndClassifyMaxSort(parentId int, classifyType uint8) (maxSort int, err error) {
  1425. //获取该层级下最大的排序数
  1426. classifyMaxSort, err := GetEdbClassifyMaxSort(parentId, classifyType)
  1427. if err != nil {
  1428. return
  1429. }
  1430. maxSort = classifyMaxSort
  1431. edbMaxSort, err := GetEdbInfoMaxSortByClassifyId(parentId)
  1432. if err != nil {
  1433. return
  1434. }
  1435. if maxSort < edbMaxSort {
  1436. maxSort = edbMaxSort
  1437. }
  1438. return
  1439. }
  1440. // CalculateEdbExtra 指标运算额外配置
  1441. type CalculateEdbExtra struct {
  1442. DateTag string `description:"时间序列的生成方式,all 表示所选指标的时间序列并集"`
  1443. }
  1444. // CalculateLjzEdbExtra 累计值额外配置
  1445. type CalculateLjzEdbExtra struct {
  1446. LastValType int `description:"最新值处理:0默认、均值填充"`
  1447. }
  1448. type EdbInfoEditRecord struct {
  1449. EdbInfoId int `description:"指标ID"`
  1450. EdbName string `description:"指标名称"`
  1451. Frequency string `description:"频率"`
  1452. Unit string `description:"单位"`
  1453. ClassifyId int `description:"分类id"`
  1454. CalculateFormula string `description:"计算公式"`
  1455. OperateUserId int `description:"操作人id"`
  1456. OperateUserRealName string `description:"操作人姓名"`
  1457. }
  1458. // GetEdbInfoByEdbCodeList
  1459. // @Description: 根据来源和指标编码列表获取指标信息列表
  1460. // @author: Roc
  1461. // @datetime 2024-05-31 16:31:52
  1462. // @param source int
  1463. // @param edbCodeList []string
  1464. // @return items []*EdbInfo
  1465. // @return err error
  1466. func GetEdbInfoByEdbCodeList(source int, edbCodeList []string) (items []*EdbInfo, err error) {
  1467. num := len(edbCodeList)
  1468. if num <= 0 {
  1469. return
  1470. }
  1471. o := orm.NewOrm()
  1472. sql := ` SELECT * FROM edb_info WHERE source=? AND edb_code IN (` + utils.GetOrmInReplace(num) + `) `
  1473. _, err = o.Raw(sql, source, edbCodeList).QueryRows(&items)
  1474. return
  1475. }
  1476. // EdbInfoExtra 指标额外数据-extra字段
  1477. type EdbInfoExtra struct {
  1478. ApiExtraPars string `description:"API-额外参数(如同花顺日期序列)"`
  1479. }
  1480. // GetEdbInfoNoUpdateTotalByIdList 根据指标id列表获取指标信息
  1481. func GetEdbInfoNoUpdateTotalByIdList(edbInfoIdList []int) (total int, err error) {
  1482. num := len(edbInfoIdList)
  1483. if num <= 0 {
  1484. return
  1485. }
  1486. o := orm.NewOrm()
  1487. sql := ` SELECT count(*) FROM edb_info WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) and no_update=1`
  1488. err = o.Raw(sql, edbInfoIdList).QueryRow(&total)
  1489. return
  1490. }
  1491. func TransEdbInfoSearchData2DataList(items []*EdbInfoSearchData) (list []*EdbDataList) {
  1492. if len(items) == 0 {
  1493. return
  1494. }
  1495. list = make([]*EdbDataList, 0)
  1496. for _, v := range items {
  1497. list = append(list, &EdbDataList{
  1498. EdbDataId: v.EdbDataId,
  1499. EdbInfoId: v.EdbInfoId,
  1500. DataTime: v.DataTime,
  1501. DataTimestamp: v.DataTimestamp,
  1502. Value: v.Value,
  1503. })
  1504. }
  1505. return
  1506. }
  1507. func TransEdbInfoDataList2SearchData(items []*EdbDataList) (list []*EdbInfoSearchData) {
  1508. if len(items) == 0 {
  1509. return
  1510. }
  1511. list = make([]*EdbInfoSearchData, 0)
  1512. for _, v := range items {
  1513. list = append(list, &EdbInfoSearchData{
  1514. EdbDataId: v.EdbDataId,
  1515. EdbInfoId: v.EdbInfoId,
  1516. DataTime: v.DataTime,
  1517. DataTimestamp: v.DataTimestamp,
  1518. Value: v.Value,
  1519. })
  1520. }
  1521. return
  1522. }
  1523. // GetAddEdbMaxSortByClassifyId
  1524. // @Description: 获取添加指标时,该分类下最大的排序(忽略错误信息)
  1525. // @author: Roc
  1526. // @datetime 2024-07-05 09:39:46
  1527. // @param classifyId int
  1528. // @param classifyType uint8
  1529. // @return sort int
  1530. func GetAddEdbMaxSortByClassifyId(classifyId int, classifyType uint8) (sort int) {
  1531. sort, _ = GetEdbAndClassifyMaxSort(classifyId, classifyType)
  1532. sort = sort + 1
  1533. return
  1534. }
  1535. type SortEdbDataList []*EdbInfoSearchData
  1536. func (m SortEdbDataList) Len() int {
  1537. return len(m)
  1538. }
  1539. func (m SortEdbDataList) Less(i, j int) bool {
  1540. return m[i].DataTime > m[j].DataTime
  1541. }
  1542. func (m SortEdbDataList) Swap(i, j int) {
  1543. m[i], m[j] = m[j], m[i]
  1544. }
  1545. func ModifyEdbInfoDataStatus(edbInfoId int64, source, subSource int, edbCode string) (err error) {
  1546. o := orm.NewOrm()
  1547. sql := ``
  1548. tableName := GetEdbDataTableName(source, subSource)
  1549. sql = ` UPDATE %s SET edb_info_id=?,modify_time=NOW() WHERE edb_code=? `
  1550. sql = fmt.Sprintf(sql, tableName)
  1551. _, err = o.Raw(sql, edbInfoId, edbCode).Exec()
  1552. return
  1553. }