edb_info.go 62 KB

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