edb_info.go 62 KB

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