edb_info.go 62 KB

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