edb_info.go 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  1. package data_manage
  2. import (
  3. "encoding/json"
  4. "eta/eta_mobile/models/data_manage/line_equation/request"
  5. "eta/eta_mobile/models/mgo"
  6. "eta/eta_mobile/services/alarm_msg"
  7. "eta/eta_mobile/utils"
  8. "fmt"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "go.mongodb.org/mongo-driver/bson"
  13. "github.com/beego/beego/v2/client/orm"
  14. "github.com/rdlucklib/rdluck_tools/paging"
  15. )
  16. type EdbInfo struct {
  17. EdbInfoId int `orm:"column(edb_info_id);pk"`
  18. EdbInfoType int `description:"指标类型,0:普通指标,1:预测指标"`
  19. SourceName string `description:"来源名称"`
  20. Source int `description:"来源id"`
  21. EdbCode string `description:"指标编码"`
  22. EdbName string `description:"指标名称"`
  23. EdbNameEn string `description:"英文指标名称"`
  24. EdbNameSource string `description:"指标名称来源"`
  25. Frequency string `description:"频率"`
  26. Unit string `description:"单位"`
  27. UnitEn string `description:"英文单位"`
  28. StartDate string `description:"起始日期"`
  29. EndDate string `description:"终止日期"`
  30. ClassifyId int `description:"分类id"`
  31. SysUserId int
  32. SysUserRealName string
  33. UniqueCode string `description:"指标唯一编码"`
  34. CreateTime time.Time
  35. ModifyTime time.Time
  36. MinValue float64 `description:"指标最小值"`
  37. MaxValue float64 `description:"指标最大值"`
  38. CalculateFormula string `description:"计算公式"`
  39. EdbType 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. DataDateType string `orm:"column(data_date_type);size(255);null;default(交易日)"`
  51. ManualSave int `description:"是否有手动保存过上下限: 0-否; 1-是"`
  52. TerminalCode string `description:"终端编码,用于配置在机器上"`
  53. DataUpdateTime string `description:"最近一次数据发生变化的时间"`
  54. ErDataUpdateDate string `description:"本次更新,数据发生变化的最早日期"`
  55. SourceIndexName string `description:"数据源中的指标名称"`
  56. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  57. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  58. SubSource int `description:"子数据来源:0:经济数据库,1:日期序列"`
  59. SubSourceName string `description:"子数据来源名称"`
  60. IndicatorCode string `description:"指标代码"`
  61. StockCode string `description:"证券代码"`
  62. Extra string `description:"指标额外配置"`
  63. IsJoinPermission int `description:"是否加入权限管控,0:不加入;1:加入;默认:0"`
  64. }
  65. type EdbInfoFullClassify struct {
  66. *EdbInfo
  67. CorrelationStr string `description:"相关性系数字符串"`
  68. ClassifyList []*EdbClassifyIdItems
  69. HaveOperaAuth bool `description:"是否有数据权限,默认:false"`
  70. }
  71. func AddEdbInfo(item *EdbInfo) (lastId int64, err error) {
  72. o := orm.NewOrmUsingDB("data")
  73. lastId, err = o.Insert(item)
  74. return
  75. }
  76. type BaseEdbNameItem struct {
  77. EdbInfoId int `description:"指标id"`
  78. EdbInfoType int `description:"指标类型,0:普通指标,1:预测指标"`
  79. SourceName string `description:"来源名称"`
  80. Source int `description:"来源id"`
  81. EdbCode string `description:"指标编码"`
  82. EdbName string `description:"指标名称"`
  83. EdbNameEn string `description:"指标英文名称"`
  84. Frequency string `description:"频率"`
  85. Unit string `description:"单位"`
  86. UnitEn string `description:"英文单位"`
  87. HaveOperaAuth bool `description:"是否有数据权限,默认:false"`
  88. }
  89. type BaseEdbInfoResp struct {
  90. List []*BaseEdbNameItem
  91. }
  92. // GetEdbInfoAll 用于分类展示
  93. func GetEdbInfoAll(edbInfoType uint8) (items []*EdbClassifyItems, err error) {
  94. o := orm.NewOrmUsingDB("data")
  95. sql := ` SELECT edb_info_id,classify_id,edb_name_source AS classify_name,edb_name_en AS classify_name_en,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE edb_info_type = ? order by sort asc,edb_info_id asc`
  96. _, err = o.Raw(sql, edbInfoType).QueryRows(&items)
  97. return
  98. }
  99. // GetPredictEdbInfoAll 用于分类展示(预测指标)
  100. func GetPredictEdbInfoAll(edbInfoType uint8) (items []*EdbClassifyItems, err error) {
  101. o := orm.NewOrmUsingDB("data")
  102. sql := ` SELECT edb_info_id,classify_id,edb_name AS classify_name,edb_name_en AS classify_name_en,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type FROM edb_info WHERE edb_info_type = ? order by sort asc,edb_info_id asc`
  103. _, err = o.Raw(sql, edbInfoType).QueryRows(&items)
  104. return
  105. }
  106. // 用于分类展示
  107. func GetEdbInfoAllList() (items []*EdbInfo, err error) {
  108. o := orm.NewOrmUsingDB("data")
  109. sql := ` SELECT * FROM edb_info `
  110. _, err = o.Raw(sql).QueryRows(&items)
  111. return
  112. }
  113. // 指标检索数据
  114. type EdbInfoSearch struct {
  115. EdbCode string `description:"指标编码"`
  116. StartDate string `description:"起始日期"`
  117. EndDate string `description:"终止日期"`
  118. EdbName string `description:"指标名称"`
  119. Unit string `description:"单位"`
  120. Frequency string `description:"频率"`
  121. DataList []*EdbInfoSearchData
  122. StockList []*StockInfo `description:"时序数据"`
  123. }
  124. type StockInfo struct {
  125. StockCode string
  126. EdbCode string
  127. DataList []*EdbInfoSearchData
  128. }
  129. type EdbInfoSearchData struct {
  130. DataTime string `description:"数据日期"`
  131. Value float64 `description:"数据"`
  132. }
  133. type BaseIndexInfo struct {
  134. IndexName string `description:"数据日期"`
  135. Unit string `description:"单位"`
  136. Frequency string `description:"频率"`
  137. }
  138. type EdbInfoSearchResp struct {
  139. SearchItem *EdbInfoSearch `description:"指标分类"`
  140. Status int `description:"1:数据已存在于弘则数据库,2:新数据,3:数据已存在于弘则数据库,但是当前账号无权限"`
  141. ClassifyList []*EdbClassifySimplify
  142. StockSearchList []*EdbInfoSearch
  143. }
  144. func GetEdbInfoByEdbCode(source int, edbCode string) (item *EdbInfo, err error) {
  145. o := orm.NewOrmUsingDB("data")
  146. sql := ` SELECT * FROM edb_info WHERE source=? AND edb_code=? `
  147. err = o.Raw(sql, source, edbCode).QueryRow(&item)
  148. return
  149. }
  150. func GetEdbInfoById(edbInfoId int) (item *EdbInfo, err error) {
  151. o := orm.NewOrmUsingDB("data")
  152. sql := ` SELECT * FROM edb_info WHERE edb_info_id=? `
  153. err = o.Raw(sql, edbInfoId).QueryRow(&item)
  154. return
  155. }
  156. // GetEdbInfoByUniqueCode
  157. // @Description: 根据uniqueCode获取指标详情
  158. // @author: Roc
  159. // @datetime 2024-01-18 13:40:01
  160. // @param uniqueCode string
  161. // @return item *EdbInfo
  162. // @return err error
  163. func GetEdbInfoByUniqueCode(uniqueCode string) (item *EdbInfo, err error) {
  164. o := orm.NewOrmUsingDB("data")
  165. sql := ` SELECT * FROM edb_info WHERE unique_code=? `
  166. err = o.Raw(sql, uniqueCode).QueryRow(&item)
  167. return
  168. }
  169. // GetEdbInfoByIdList 根据指标id集合 获取 指标列表
  170. func GetEdbInfoByIdList(edbInfoIdList []int) (items []*EdbInfo, err error) {
  171. num := len(edbInfoIdList)
  172. if num <= 0 {
  173. return
  174. }
  175. o := orm.NewOrmUsingDB("data")
  176. sql := ` SELECT * FROM edb_info WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  177. _, err = o.Raw(sql, edbInfoIdList).QueryRows(&items)
  178. return
  179. }
  180. type AddEdbInfoReq struct {
  181. Source int `description:"来源id"`
  182. EdbCode string `description:"指标编码"`
  183. EdbName string `description:"指标名称"`
  184. Frequency string `description:"频率"`
  185. Unit string `description:"单位"`
  186. ClassifyId int `description:"分类id"`
  187. StartDate string `description:"起始日期"`
  188. EndDate string `description:"终止日期"`
  189. }
  190. func DeleteEdbInfoAndData(edbInfoId, source, subSource int) (err error) {
  191. o := orm.NewOrmUsingDB("data")
  192. to, err := o.Begin()
  193. if err != nil {
  194. return
  195. }
  196. defer func() {
  197. if err != nil {
  198. _ = to.Rollback()
  199. } else {
  200. _ = to.Commit()
  201. }
  202. }()
  203. // 删除指标信息
  204. sql := ` DELETE FROM edb_info WHERE edb_info_id=? `
  205. _, err = to.Raw(sql, edbInfoId).Exec()
  206. if err != nil {
  207. return
  208. }
  209. // 删除指标的明细数据
  210. if source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  211. err = deleteAllEdbDataByMongo(to, edbInfoId, source, subSource)
  212. } else if source == utils.DATA_SOURCE_THS && subSource == utils.DATA_SUB_SOURCE_HIGH_FREQUENCY && utils.UseMongo {
  213. mogDataObj := mgo.EdbDataThsHf{}
  214. err = mogDataObj.RemoveMany(bson.M{"edb_info_id": edbInfoId})
  215. } else {
  216. err = deleteAllEdbDataByMysql(to, edbInfoId, source, subSource)
  217. }
  218. if err != nil {
  219. return
  220. }
  221. //calculateTableName := GetEdbInfoCalculateTableName(source)
  222. //if calculateTableName != "" {
  223. // sql = ` DELETE FROM %s WHERE edb_info_id=? `
  224. // sql = fmt.Sprintf(sql, calculateTableName)
  225. // _, err = to.Raw(sql, edbInfoId).Exec()
  226. // return
  227. //}
  228. //return
  229. // 删除计算指标的关系
  230. sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=? `
  231. _, err = to.Raw(sql, edbInfoId).Exec()
  232. // 删除预测指标的配置
  233. sql = ` DELETE FROM predict_edb_conf WHERE predict_edb_info_id=? `
  234. _, err = to.Raw(sql, edbInfoId).Exec()
  235. return
  236. }
  237. // deleteAllEdbDataByMysql
  238. // @Description: 删除指标的明细数据(mysql)
  239. // @author: Roc
  240. // @datetime 2024-05-09 13:31:54
  241. // @param to orm.TxOrmer
  242. // @param edbInfoId int
  243. // @param source int
  244. // @param subSource int
  245. // @return err error
  246. func deleteAllEdbDataByMysql(to orm.TxOrmer, edbInfoId, source, subSource int) (err error) {
  247. tableName := GetEdbDataTableName(source, subSource)
  248. if tableName == `` {
  249. return
  250. }
  251. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id=? `, tableName)
  252. _, err = to.Raw(sql, edbInfoId).Exec()
  253. return
  254. }
  255. // deleteAllEdbDataByMongo
  256. // @Description: 删除指标的明细数据(mongo)
  257. // @author: Roc
  258. // @datetime 2024-05-09 13:31:37
  259. // @param to orm.TxOrmer
  260. // @param edbInfoId int
  261. // @param source int
  262. // @param subSource int
  263. // @return err error
  264. func deleteAllEdbDataByMongo(to orm.TxOrmer, edbInfoId, source, subSource int) (err error) {
  265. mogDataObj := mgo.EdbDataBusiness{}
  266. err = mogDataObj.RemoveMany(bson.M{"edb_info_id": edbInfoId})
  267. return
  268. }
  269. func GetEdbInfoCountByCondition(condition string, pars []interface{}) (count int, err error) {
  270. o := orm.NewOrmUsingDB("data")
  271. sql := ` SELECT COUNT(1) AS count FROM edb_info WHERE 1=1 `
  272. if condition != "" {
  273. sql += condition
  274. }
  275. err = o.Raw(sql, pars).QueryRow(&count)
  276. return
  277. }
  278. type EditEdbInfoReq struct {
  279. EdbInfoId int `description:"指标ID"`
  280. EdbName string `description:"指标名称"`
  281. Frequency string `description:"频率"`
  282. Unit string `description:"单位"`
  283. ClassifyId int `description:"分类id"`
  284. CalculateFormula string `description:"计算公式"`
  285. }
  286. type EditEdbEnInfoReq struct {
  287. EdbInfoId int `description:"指标ID"`
  288. EdbNameEn string `description:"英文指标名称"`
  289. UnitEn string `description:"英文单位"`
  290. }
  291. // EditEdbBaseInfoReq
  292. // @Description: 修改指标基础信息请求参数
  293. type EditEdbBaseInfoReq struct {
  294. EdbInfoId int `description:"指标ID"`
  295. EdbName string `description:"指标名称"`
  296. Unit string `description:"指标单位"`
  297. }
  298. func ModifyEdbInfo(item *EditEdbInfoReq) (err error) {
  299. o := orm.NewOrmUsingDB("data")
  300. sql := ` UPDATE edb_info
  301. SET
  302. edb_name =?,
  303. edb_name_source =?,
  304. frequency = ?,
  305. unit = ?,
  306. classify_id = ?,
  307. modify_time = NOW()
  308. WHERE edb_info_id = ?`
  309. _, err = o.Raw(sql, item.EdbName, item.EdbName, item.Frequency, item.Unit, item.ClassifyId, item.EdbInfoId).Exec()
  310. return
  311. }
  312. // ModifyEdbEnInfo 修改指标英文信息
  313. func ModifyEdbEnInfo(item *EditEdbEnInfoReq) (err error) {
  314. o := orm.NewOrmUsingDB("data")
  315. sql := ` UPDATE edb_info
  316. SET
  317. edb_name_en =?,
  318. unit_en = ?,
  319. modify_time = NOW()
  320. WHERE edb_info_id = ?`
  321. _, err = o.Raw(sql, item.EdbNameEn, item.UnitEn, item.EdbInfoId).Exec()
  322. return
  323. }
  324. type EdbInfoList struct {
  325. EdbInfoId int `orm:"column(edb_info_id);pk"`
  326. EdbInfoType int `description:"指标类型,0:普通指标,1:预测指标"`
  327. SourceName string `description:"来源名称"`
  328. Source int `description:"来源id"`
  329. EdbCode string `description:"指标编码"`
  330. EdbNameEn string `description:"英文指标名称"`
  331. EdbName string `description:"指标名称"`
  332. Frequency string `description:"频率"`
  333. FrequencyEn string `description:"英文频率"`
  334. Unit string `description:"单位"`
  335. UnitEn string `description:"英文单位"`
  336. StartDate string `description:"起始日期"`
  337. EndDate string `description:"终止日期"`
  338. LatestDate string `description:"数据最新日期(实际日期)"`
  339. LatestValue float64 `description:"数据最新值(实际值)"`
  340. EndValue float64 `description:"数据的最新值(预测日期的最新值)"`
  341. ClassifyId int `description:"分类id"`
  342. UniqueCode string `description:"指标唯一编码"`
  343. SysUserId int `description:"创建人id"`
  344. SysUserRealName string `description:"创建人姓名"`
  345. ModifyTime string `description:"最新修改时间"`
  346. CreateTime string `description:"创建时间"`
  347. EdbNameAlias string `json:"-" description:"指标名称,别名"`
  348. EdbType int `description:"指标类型:1:基础指标,2:计算指标"`
  349. ChartImage string `description:"图表图片"`
  350. RuleType int `description:"预测规则,1:最新,2:固定值"`
  351. FixedValue float64 `description:"固定值"`
  352. DataList []*EdbData `description:"实际指标数据"`
  353. PredictDataList []*EdbData `description:"预测指标数据"`
  354. Button EdbClassifyItemsButton `description:"操作权限"`
  355. IsEnEdb bool `description:"是否展示英文标识"`
  356. DataInsertConfig EdbDataInsertConfigItem `description:"指标数据插入配置"`
  357. DataDateType string `description:"数据日期类型,枚举值:交易日、自然日"`
  358. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  359. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  360. SubSource int `description:"子数据来源:0:经济数据库,1:日期序列"`
  361. SubSourceName string `description:"子数据来源名称"`
  362. IndicatorCode string `description:"指标代码"`
  363. StockCode string `description:"证券代码"`
  364. NoUpdate int8 `description:"是否停止更新,0:继续更新;1:停止更新"`
  365. IsJoinPermission int `description:"是否加入权限管控,0:不加入;1:加入;默认:0"`
  366. HaveOperaAuth bool `description:"是否有数据权限,默认:false"`
  367. SearchText string `description:"搜索结果(含高亮)"`
  368. }
  369. type EdbDataInsertConfigItem struct {
  370. Date string `description:"插入的日期"`
  371. RealDate string `description:"实际最晚的日期"`
  372. Value string `description:"插入的值"`
  373. }
  374. type EdbData struct {
  375. EdbDataId int `orm:"column(edb_data_id);pk"`
  376. EdbInfoId int
  377. DataTime string
  378. Value float64
  379. }
  380. type EdbInfoListResp struct {
  381. Paging *paging.PagingItem
  382. Item *EdbInfoList
  383. ClassifyList []*EdbClassifyIdItems
  384. }
  385. func GetEdbInfoByCondition(condition string, pars []interface{}) (item *EdbInfoList, err error) {
  386. o := orm.NewOrmUsingDB("data")
  387. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  388. if condition != "" {
  389. sql += condition
  390. }
  391. err = o.Raw(sql, pars).QueryRow(&item)
  392. return
  393. }
  394. func GetEdbDataCountByCondition(condition string, pars []interface{}, source, subSource int) (count int, err error) {
  395. o := orm.NewOrmUsingDB("data")
  396. tableName := GetEdbDataTableName(source, subSource)
  397. sql := ` SELECT COUNT(1) AS count FROM %s WHERE 1=1 `
  398. sql = fmt.Sprintf(sql, tableName)
  399. if condition != "" {
  400. sql += condition
  401. }
  402. err = o.Raw(sql, pars).QueryRow(&count)
  403. return
  404. }
  405. func GetEdbDataListByCondition(condition string, pars []interface{}, source, subSource, pageSize, startSize int) (item []*EdbData, err error) {
  406. o := orm.NewOrmUsingDB("data")
  407. tableName := GetEdbDataTableName(source, subSource)
  408. sql := ` SELECT * FROM %s WHERE 1=1 `
  409. sql = fmt.Sprintf(sql, tableName)
  410. if condition != "" {
  411. sql += condition
  412. }
  413. sql += ` ORDER BY data_time DESC `
  414. sql += ` LIMIT ?,? `
  415. _, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&item)
  416. return
  417. }
  418. // GetAllEdbDataListByCondition 根据条件获取所有的数据
  419. func GetAllEdbDataListByCondition(condition string, pars []interface{}, source, subSource int) (item []*EdbData, err error) {
  420. o := orm.NewOrmUsingDB("data")
  421. tableName := GetEdbDataTableName(source, subSource)
  422. sql := ` SELECT * FROM %s WHERE 1=1 `
  423. sql = fmt.Sprintf(sql, tableName)
  424. if condition != "" {
  425. sql += condition
  426. }
  427. sql += ` ORDER BY data_time DESC `
  428. _, err = o.Raw(sql, pars).QueryRows(&item)
  429. return
  430. }
  431. func GetEdbInfoByNewest() (item *EdbInfoList, err error) {
  432. o := orm.NewOrmUsingDB("data")
  433. sql := ` SELECT * FROM edb_info WHERE 1=1 ORDER BY modify_time DESC LIMIT 1 `
  434. err = o.Raw(sql).QueryRow(&item)
  435. return
  436. }
  437. func ModifyEdbInfoModifyTime(edbInfoId int64) (err error) {
  438. o := orm.NewOrmUsingDB("data")
  439. sql := ` UPDATE edb_info SET modify_time = NOW() WHERE edb_info_id = ? `
  440. _, err = o.Raw(sql, edbInfoId).Exec()
  441. return
  442. }
  443. type MoveEdbInfoReq struct {
  444. EdbInfoId int `description:"指标ID"`
  445. PrevEdbInfoId int `description:"上一个指标ID"`
  446. NextEdbInfoId int `description:"下一个指标ID"`
  447. ClassifyId int `description:"分类id"`
  448. }
  449. func MoveEdbInfo(edbInfoId, classifyId int) (err error) {
  450. o := orm.NewOrmUsingDB("data")
  451. sql := ` UPDATE edb_info
  452. SET
  453. classify_id = ?
  454. WHERE edb_info_id = ?`
  455. _, err = o.Raw(sql, classifyId, edbInfoId).Exec()
  456. return
  457. }
  458. // GetEdbInfoByName 根据名称获取普通的指标
  459. func GetEdbInfoByName(edbName string) (items []*EdbInfoList, err error) {
  460. o := orm.NewOrmUsingDB("data")
  461. sql := ` SELECT * FROM edb_info WHERE edb_name=? AND edb_info_type = 0 `
  462. _, err = o.Raw(sql, edbName).QueryRows(&items)
  463. return
  464. }
  465. // GetPredictEdbInfoByName 根据指标名称获取预测指标
  466. func GetPredictEdbInfoByName(edbName string) (items []*EdbInfoList, err error) {
  467. o := orm.NewOrmUsingDB("data")
  468. sql := ` SELECT * FROM edb_info WHERE edb_name=? AND edb_info_type = 1 `
  469. _, err = o.Raw(sql, edbName).QueryRows(&items)
  470. return
  471. }
  472. func GetEdbInfoByEnName(edbNameEn string) (items []*EdbInfoList, err error) {
  473. o := orm.NewOrmUsingDB("data")
  474. sql := ` SELECT * FROM edb_info WHERE edb_name_en=? AND edb_info_type = 0 `
  475. _, err = o.Raw(sql, edbNameEn).QueryRows(&items)
  476. return
  477. }
  478. func ModifyEdbInfoNameSource(edbNameSource string, edbInfoId int) (err error) {
  479. o := orm.NewOrmUsingDB("data")
  480. sql := ` UPDATE edb_info SET edb_name_source=? WHERE edb_info_id = ? `
  481. _, err = o.Raw(sql, edbNameSource, edbInfoId).Exec()
  482. return
  483. }
  484. func GetChartEdbMappingCount(edbInfoId int) (count int, err error) {
  485. o := orm.NewOrmUsingDB("data")
  486. sql := ` SELECT COUNT(1) AS count FROM chart_edb_mapping WHERE edb_info_id=? `
  487. err = o.Raw(sql, edbInfoId).QueryRow(&count)
  488. return
  489. }
  490. type ChartEdbInfo struct {
  491. EdbInfoId int `description:"指标id"`
  492. EdbName string `description:"指标名称"`
  493. SourceName string `json:"-"`
  494. EdbNameAlias string `json:"-" description:"指标名称,别名"`
  495. }
  496. func EdbInfoSearchByKeyWord(keyword string) (searchList []*ChartEdbInfo, err error) {
  497. pars := make([]interface{}, 0)
  498. o := orm.NewOrmUsingDB("data")
  499. sql := ` SELECT edb_info_id,edb_name,source_name FROM edb_info WHERE 1=1 AND edb_info_type = 0 `
  500. if keyword != "" {
  501. sql += ` AND (edb_name LIKE ? OR edb_code LIKE ? ) `
  502. pars = append(pars, utils.GetLikeKeyword(keyword), utils.GetLikeKeyword(keyword))
  503. }
  504. sql += ` ORDER BY create_time DESC `
  505. _, err = o.Raw(sql, pars...).QueryRows(&searchList)
  506. return
  507. }
  508. type EdbInfoMaxAndMinInfo struct {
  509. MinDate string `description:"最小日期"`
  510. MaxDate string `description:"最大日期"`
  511. MinValue float64 `description:"最小值"`
  512. MaxValue float64 `description:"最大值"`
  513. LatestValue float64 `description:"最新值"`
  514. }
  515. // GetEdbInfoMaxAndMinInfo
  516. // @Description: 获取指标最大最小值
  517. // @author: Roc
  518. // @datetime 2024-05-07 15:34:00
  519. // @param source int
  520. // @param subSource int
  521. // @param edbCode string
  522. // @return item *EdbInfoMaxAndMinInfo
  523. // @return err error
  524. func GetEdbInfoMaxAndMinInfo(source, subSource int, edbCode string) (item *EdbInfoMaxAndMinInfo, err error) {
  525. // 自有数据需要额外处理(从mongo获取)
  526. if source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  527. return GetEdbInfoMaxAndMinInfoByMongo(source, subSource, edbCode)
  528. }
  529. if source == utils.DATA_SOURCE_THS && subSource == utils.DATA_SUB_SOURCE_HIGH_FREQUENCY && utils.UseMongo {
  530. return GetThsHfEdbInfoMaxAndMinInfoByMongo(source, subSource, edbCode)
  531. }
  532. // 默认走mysql
  533. return GetEdbInfoMaxAndMinInfoByMysql(source, subSource, edbCode)
  534. }
  535. // GetEdbInfoMaxAndMinInfoByMysql
  536. // @Description: 从mysql中获取指标最大最小值
  537. // @author: Roc
  538. // @datetime 2024-05-07 15:33:43
  539. // @param source int
  540. // @param subSource int
  541. // @param edbCode string
  542. // @return item *EdbInfoMaxAndMinInfo
  543. // @return err error
  544. func GetEdbInfoMaxAndMinInfoByMysql(source, subSource int, edbCode string) (item *EdbInfoMaxAndMinInfo, err error) {
  545. o := orm.NewOrmUsingDB("data")
  546. sql := ``
  547. tableName := GetEdbDataTableName(source, subSource)
  548. 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=? `
  549. sql = fmt.Sprintf(sql, tableName)
  550. err = o.Raw(sql, edbCode).QueryRow(&item)
  551. if err != nil {
  552. return
  553. }
  554. var latest_value float64
  555. sql = ` SELECT value AS latest_value FROM %s WHERE edb_code=? ORDER BY data_time DESC LIMIT 1 `
  556. sql = fmt.Sprintf(sql, tableName)
  557. err = o.Raw(sql, edbCode).QueryRow(&latest_value)
  558. item.LatestValue = latest_value
  559. return
  560. }
  561. // GetEdbInfoMaxAndMinInfoByMongo
  562. // @Description: 从mongo中获取指标最大最小值
  563. // @author: Roc
  564. // @datetime 2024-05-07 15:33:53
  565. // @param source int
  566. // @param subSource int
  567. // @param edbCode string
  568. // @return item *EdbInfoMaxAndMinInfo
  569. // @return err error
  570. func GetEdbInfoMaxAndMinInfoByMongo(source, subSource int, edbCode string) (item *EdbInfoMaxAndMinInfo, err error) {
  571. mogDataObj := new(mgo.EdbDataBusiness)
  572. pipeline := []bson.M{
  573. {"$match": bson.M{"edb_code": edbCode}},
  574. {"$group": bson.M{
  575. "_id": nil,
  576. "min_date": bson.M{"$min": "$data_time"},
  577. "max_date": bson.M{"$max": "$data_time"},
  578. "min_value": bson.M{"$min": "$value"},
  579. "max_value": bson.M{"$max": "$value"},
  580. }},
  581. {"$project": bson.M{"_id": 0}}, // 可选,如果不需要_id字段
  582. }
  583. result, err := mogDataObj.GetEdbInfoMaxAndMinInfo(pipeline)
  584. if err != nil {
  585. fmt.Println("EdbDataBusiness getEdbDataBusinessList Err:" + err.Error())
  586. return
  587. }
  588. if !result.MaxDate.IsZero() {
  589. whereQuery := bson.M{"edb_code": edbCode, "data_time": result.MaxDate}
  590. selectParam := bson.D{{"value", 1}, {"_id", 0}}
  591. latestValue, tmpErr := mogDataObj.GetLatestValue(whereQuery, selectParam)
  592. if tmpErr != nil {
  593. err = tmpErr
  594. return
  595. }
  596. result.LatestValue = latestValue.Value
  597. result.EndValue = latestValue.Value
  598. }
  599. item = &EdbInfoMaxAndMinInfo{
  600. MinDate: result.MinDate.Format(utils.FormatDate),
  601. MaxDate: result.MaxDate.Format(utils.FormatDate),
  602. MinValue: result.MinValue,
  603. MaxValue: result.MaxValue,
  604. LatestValue: result.LatestValue,
  605. }
  606. return
  607. }
  608. func ModifyEdbInfoMaxAndMinInfo(edbInfoId int, item *EdbInfoMaxAndMinInfo) (err error) {
  609. o := orm.NewOrmUsingDB("data")
  610. sql := ` UPDATE edb_info SET start_date=?,end_date=?,min_value=?,max_value=?,is_update=2,latest_date=?,latest_value=?,modify_time=NOW() WHERE edb_info_id=? `
  611. _, err = o.Raw(sql, item.MinDate, item.MaxDate, item.MinValue, item.MaxValue, item.MaxDate, item.LatestValue, edbInfoId).Exec()
  612. return
  613. }
  614. func GetEdbInfoFilter(condition string, pars []interface{}) (list []*EdbInfoList, err error) {
  615. o := orm.NewOrmUsingDB("data")
  616. sql := ` SELECT * FROM edb_info WHERE 1=1 AND edb_info_type = 0 `
  617. if condition != "" {
  618. sql += condition
  619. }
  620. sql += ` ORDER BY create_time DESC `
  621. _, err = o.Raw(sql, pars).QueryRows(&list)
  622. return
  623. }
  624. type AddEdbInfoResp struct {
  625. EdbInfoId int `description:"指标ID"`
  626. UniqueCode string `description:"指标唯一编码"`
  627. ClassifyId int `description:"分类id"`
  628. ExistEdbName []string `description:"重复指标名称"`
  629. }
  630. // GetEdbInfoCalculateListByCondition 获取指标关系列表
  631. func GetEdbInfoCalculateListByCondition(condition string, pars []interface{}) (items []*EdbInfoCalculateMapping, err error) {
  632. o := orm.NewOrmUsingDB("data")
  633. //calculateTableName := GetEdbInfoCalculateTableName(source)
  634. //if calculateTableName == "" {
  635. // err = errors.New("无效的表名")
  636. // return
  637. //}
  638. sql := ` SELECT * FROM edb_info_calculate_mapping WHERE 1=1 `
  639. //sql = fmt.Sprintf(sql, calculateTableName)
  640. if condition != "" {
  641. sql += condition
  642. }
  643. _, err = o.Raw(sql, pars).QueryRows(&items)
  644. return
  645. }
  646. // GetEdbInfoAllCalculateByEdbInfoIdList 根据指标id集合 获取基础指标对应的所有计算指标
  647. func GetEdbInfoAllCalculateByEdbInfoIdList(edbInfoIdList []int) (list []*EdbInfo, err error) {
  648. num := len(edbInfoIdList)
  649. if num <= 0 {
  650. return
  651. }
  652. o := orm.NewOrmUsingDB("data")
  653. sql := ` SELECT b.* FROM edb_info_calculate_mapping AS a
  654. INNER JOIN edb_info AS b ON a.edb_info_id=b.edb_info_id
  655. WHERE a.from_edb_info_id in (` + utils.GetOrmInReplace(num) + `)
  656. GROUP BY a.edb_info_id
  657. ORDER BY a.edb_info_id ASC `
  658. _, err = o.Raw(sql, edbInfoIdList).QueryRows(&list)
  659. return
  660. }
  661. func GetRefreshEdbInfoFromBase(edbInfoId, source int) (baseEdbInfoArr, calculateInfoArr []*EdbInfo, err error) {
  662. calculateList, err := GetEdbInfoCalculateMap(edbInfoId, source)
  663. if err != nil && err.Error() != utils.ErrNoRow() {
  664. return
  665. }
  666. for _, item := range calculateList {
  667. if item.EdbInfoId == edbInfoId { // 如果查出来关联的指标就是自己的话,那么就过滤
  668. continue
  669. }
  670. if item.EdbType == 1 {
  671. baseEdbInfoArr = append(baseEdbInfoArr, item)
  672. } else {
  673. calculateInfoArr = append(calculateInfoArr, item)
  674. newBaseEdbInfoArr, newCalculateInfoArr, _ := GetRefreshEdbInfoFromBase(item.EdbInfoId, item.Source)
  675. baseEdbInfoArr = append(baseEdbInfoArr, newBaseEdbInfoArr...)
  676. calculateInfoArr = append(calculateInfoArr, newCalculateInfoArr...)
  677. }
  678. }
  679. return
  680. }
  681. func ModifyEdbInfoDataStatus(edbInfoId int64, source, subSource int, edbCode string) (err error) {
  682. o := orm.NewOrmUsingDB("data")
  683. sql := ``
  684. tableName := GetEdbDataTableName(source, subSource)
  685. sql = ` UPDATE %s SET edb_info_id=?,modify_time=NOW() WHERE edb_code=? `
  686. sql = fmt.Sprintf(sql, tableName)
  687. _, err = o.Raw(sql, edbInfoId, edbCode).Exec()
  688. return
  689. }
  690. // GetFirstEdbInfoByClassifyId 获取当前分类下,且排序数相同 的排序第一条的数据
  691. func GetFirstEdbInfoByClassifyId(classifyId int) (item *EdbInfo, err error) {
  692. o := orm.NewOrmUsingDB("data")
  693. sql := ` SELECT * FROM edb_info WHERE classify_id=? order by sort asc,edb_info_id asc limit 1`
  694. err = o.Raw(sql, classifyId).QueryRow(&item)
  695. return
  696. }
  697. // UpdateEdbInfoSortByClassifyId 根据分类id更新排序
  698. func UpdateEdbInfoSortByClassifyId(classifyId, nowSort int, prevEdbInfoId int, updateSort string) (err error) {
  699. o := orm.NewOrmUsingDB("data")
  700. sql := ` update edb_info set sort = ` + updateSort + ` WHERE classify_id=?`
  701. if prevEdbInfoId > 0 {
  702. sql += ` AND ( sort > ? or ( edb_info_id > ` + fmt.Sprint(prevEdbInfoId) + ` and sort=` + fmt.Sprint(nowSort) + ` )) `
  703. } else {
  704. sql += ` AND ( sort > ? )`
  705. }
  706. _, err = o.Raw(sql, classifyId, nowSort).Exec()
  707. return
  708. }
  709. // Update 更新指标基础信息
  710. func (edbInfo *EdbInfo) Update(cols []string) (err error) {
  711. o := orm.NewOrmUsingDB("data")
  712. _, err = o.Update(edbInfo, cols...)
  713. return
  714. }
  715. type EdbInfoDataResp struct {
  716. EdbInfo *EdbInfo
  717. DataList []*EdbDataList
  718. }
  719. type EdbInfoDataFullClassifyResp struct {
  720. EdbInfo *EdbInfoFullClassify
  721. DataList []*EdbDataList
  722. }
  723. type EdbInfoReplaceReq struct {
  724. OldEdbInfoId int `description:"原指标ID"`
  725. NewEdbInfoId int `description:"替换为指标ID"`
  726. }
  727. // EdbInfoReplaceV2 替换指标v2版本(更换时间:2022年01月05日15:33:42)
  728. //func EdbInfoReplaceV2(oldEdbInfo, newEdbInfo *EdbInfo, sysAdminId int, sysAdminRealName string) (mappingList,replaceChartTotal, replaceCalculateTotal int, err error) {
  729. // defer func() {
  730. // if err != nil {
  731. // fmt.Println("ERR:", err.Error())
  732. // }
  733. // }()
  734. //
  735. // // 替换关联表中的source_edb_info_id
  736. // mappingList, replaceChartTotal, replaceCalculateTotal, err := replaceChartEdb(oldEdbInfo, newEdbInfo)
  737. // if err != nil {
  738. // return
  739. // }
  740. // err = replaceRelationEdbInfo(mappingList, oldEdbInfo, newEdbInfo, sysAdminId, sysAdminRealName)
  741. // return
  742. //}
  743. // ReplaceChartEdb 替换图表中的指标
  744. func ReplaceChartEdb(oldEdbInfo, newEdbInfo *EdbInfo) (relationEdbInfoIdList []int, replaceChartTotal, replaceCalculateTotal int, err error) {
  745. var errmsg string
  746. relationEdbInfoIdList = make([]int, 0) // 关联的指标id
  747. logMsg := `` // 记录替换的日志
  748. o := orm.NewOrmUsingDB("data")
  749. to, err := o.Begin()
  750. if err != nil {
  751. return
  752. }
  753. defer func() {
  754. if err != nil {
  755. _ = to.Rollback()
  756. } else {
  757. _ = to.Commit()
  758. if logMsg != `` {
  759. utils.FileLog.Info(fmt.Sprintf("替换指标记录,旧的指标id:%d,新的指标id:%d;%s", oldEdbInfo.EdbInfoId, newEdbInfo.EdbInfoId, logMsg))
  760. }
  761. }
  762. if errmsg != "" {
  763. fmt.Println("errmsg:" + errmsg)
  764. }
  765. if err != nil && errmsg != "" {
  766. go alarm_msg.SendAlarmMsg("替换图表中的指标失败提醒,errmsg:"+errmsg, 3)
  767. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"替换指标失败提醒", "errmsg:"+errmsg, utils.EmailSendToUsers)
  768. }
  769. }()
  770. //替换图表
  771. {
  772. chartEdbMappingList := make([]*ChartEdbInfoMapping, 0)
  773. csql := `SELECT * FROM chart_edb_mapping WHERE edb_info_id=?`
  774. _, err = to.Raw(csql, oldEdbInfo.EdbInfoId).QueryRows(&chartEdbMappingList)
  775. if err != nil {
  776. errmsg = "获取指标关联图表信息失败:Err:" + err.Error()
  777. return
  778. }
  779. replaceChartTotal = len(chartEdbMappingList)
  780. // 查询所有的相关的图表信息
  781. chartInfoIds := make([]string, 0)
  782. if len(chartEdbMappingList) > 0 {
  783. for _, chartEdbMapping := range chartEdbMappingList {
  784. chartInfoIds = append(chartInfoIds, strconv.Itoa(chartEdbMapping.ChartInfoId))
  785. }
  786. }
  787. if len(chartInfoIds) > 0 {
  788. chartInfoList, e := GetChartInfoListByChartIdList(chartInfoIds)
  789. if e != nil {
  790. err = e
  791. errmsg = "获取图表信息失败:Err:" + e.Error()
  792. return
  793. }
  794. for _, chartInfo := range chartInfoList {
  795. updateStr := make([]string, 0)
  796. if chartInfo.EdbInfoIds != "" && strings.Contains(chartInfo.EdbInfoIds, strconv.Itoa(oldEdbInfo.EdbInfoId)) {
  797. //需要更换
  798. //解析字符串
  799. edbInfoIds := strings.Split(chartInfo.EdbInfoIds, ",")
  800. for i, edbInfoId := range edbInfoIds {
  801. if edbInfoId == strconv.Itoa(oldEdbInfo.EdbInfoId) {
  802. edbInfoIds[i] = strconv.Itoa(newEdbInfo.EdbInfoId)
  803. }
  804. }
  805. chartInfo.EdbInfoIds = strings.Join(edbInfoIds, ",")
  806. updateStr = append(updateStr, "EdbInfoIds")
  807. }
  808. if chartInfo.ExtraConfig != "" {
  809. //判断是否是拟合方程或者散点图截面图
  810. if chartInfo.Source == utils.CHART_SOURCE_LINE_EQUATION {
  811. //解析配置内容
  812. var lineChartInfoConfig request.LineChartInfoReq
  813. err = json.Unmarshal([]byte(chartInfo.ExtraConfig), &lineChartInfoConfig)
  814. if err != nil {
  815. errmsg = "获取图表配置信息失败 json.Unmarshal:Err:" + err.Error()
  816. return
  817. }
  818. xEdbInfoIdList := lineChartInfoConfig.XEdbInfoIdList
  819. yEdbInfoIdList := lineChartInfoConfig.YEdbInfoIdList
  820. if len(xEdbInfoIdList) > 0 {
  821. // 循环判断是否存在
  822. for k, xEdbInfoId := range xEdbInfoIdList {
  823. if xEdbInfoId == oldEdbInfo.EdbInfoId {
  824. xEdbInfoIdList[k] = newEdbInfo.EdbInfoId
  825. }
  826. }
  827. }
  828. if len(yEdbInfoIdList) > 0 {
  829. // 循环判断是否存在
  830. for k, yEdbInfoId := range yEdbInfoIdList {
  831. if yEdbInfoId == oldEdbInfo.EdbInfoId {
  832. yEdbInfoIdList[k] = newEdbInfo.EdbInfoId
  833. }
  834. }
  835. }
  836. // 替换新的指标信息
  837. lineChartInfoConfig.XEdbInfoIdList = xEdbInfoIdList
  838. lineChartInfoConfig.YEdbInfoIdList = yEdbInfoIdList
  839. // 重新序列化
  840. lineChartInfoConfigJson, e := json.Marshal(lineChartInfoConfig)
  841. if e != nil {
  842. err = e
  843. errmsg = "图表配置信息序列化失败:json.Marshal Err: " + e.Error()
  844. return
  845. }
  846. lineChartInfoConfigStr := string(lineChartInfoConfigJson)
  847. // 更新图表配置信息
  848. chartInfo.ExtraConfig = lineChartInfoConfigStr
  849. updateStr = append(updateStr, "ExtraConfig")
  850. } else if chartInfo.ChartType == utils.CHART_TYPE_SECTION_SCATTER {
  851. //解析配置内容
  852. var tmpExtraConfig SectionScatterReq
  853. err = json.Unmarshal([]byte(chartInfo.ExtraConfig), &tmpExtraConfig)
  854. if err != nil {
  855. errmsg = "获取截面散点图配置信息失败 json.Unmarshal:Err:" + err.Error()
  856. return
  857. }
  858. //找到指标信息,并替换
  859. if len(tmpExtraConfig.SeriesList) > 0 {
  860. for k1, series := range tmpExtraConfig.SeriesList {
  861. for k2, item := range series.EdbInfoList {
  862. if item.XEdbInfoId == oldEdbInfo.EdbInfoId {
  863. tmpExtraConfig.SeriesList[k1].EdbInfoList[k2].XEdbInfoId = newEdbInfo.EdbInfoId
  864. }
  865. if item.YEdbInfoId == oldEdbInfo.EdbInfoId {
  866. tmpExtraConfig.SeriesList[k1].EdbInfoList[k2].YEdbInfoId = newEdbInfo.EdbInfoId
  867. }
  868. }
  869. }
  870. }
  871. // 重新序列化
  872. sectionScatterConfigJson, e := json.Marshal(tmpExtraConfig)
  873. if e != nil {
  874. err = e
  875. errmsg = "图表配置信息序列化失败:json.Marshal Err: " + e.Error()
  876. return
  877. }
  878. sectionScatterConfigStr := string(sectionScatterConfigJson)
  879. // 更新图表配置信息
  880. chartInfo.ExtraConfig = sectionScatterConfigStr
  881. updateStr = append(updateStr, "ExtraConfig")
  882. }
  883. }
  884. if len(updateStr) > 0 {
  885. updateStr = append(updateStr, "ModifyTime")
  886. chartInfo.ModifyTime = time.Now()
  887. err = chartInfo.Update(updateStr)
  888. if err != nil {
  889. errmsg = "更新图表信息失败:chartInfo.Update Err: " + err.Error()
  890. return
  891. }
  892. }
  893. }
  894. }
  895. if len(chartEdbMappingList) > 0 {
  896. chartInfoIdList := make([]string, 0)
  897. for _, mv := range chartEdbMappingList {
  898. //获取图表所有指标信息
  899. chartEdbList := make([]*ChartEdbInfoMapping, 0)
  900. csql := `SELECT * FROM chart_edb_mapping WHERE chart_info_id=?`
  901. _, err = to.Raw(csql, mv.ChartInfoId).QueryRows(&chartEdbList)
  902. if err != nil {
  903. errmsg = "获取图表所有指标信息失败:Err:" + err.Error()
  904. return
  905. }
  906. var minData, maxData float64
  907. minData = newEdbInfo.MinValue
  908. maxData = newEdbInfo.MaxValue
  909. for _, cv := range chartEdbList {
  910. if mv.IsAxis == cv.IsAxis {
  911. if minData > cv.MinData {
  912. minData = cv.MinData
  913. }
  914. if maxData < cv.MaxData {
  915. maxData = cv.MaxData
  916. }
  917. }
  918. }
  919. //修改图表关联指标
  920. rsql := ` UPDATE chart_edb_mapping SET edb_info_id=?,max_data=?,min_data=?,modify_time=NOW() WHERE chart_edb_mapping_id=? `
  921. _, err = to.Raw(rsql, newEdbInfo.EdbInfoId, maxData, minData, mv.ChartEdbMappingId).Exec()
  922. if err != nil {
  923. errmsg = "更新图库指标信息失败:Err:" + err.Error()
  924. return
  925. }
  926. chartInfoIdList = append(chartInfoIdList, fmt.Sprint(mv.ChartInfoId))
  927. }
  928. logMsg += `涉及到的图表id:` + strings.Join(chartInfoIdList, ",") + ";"
  929. }
  930. }
  931. //替换计算指标
  932. {
  933. //获取所有包含的计算指标
  934. mappingList := make([]*EdbInfoCalculateMapping, 0)
  935. msql := ` SELECT * FROM edb_info_calculate_mapping WHERE from_edb_info_id=? GROUP BY edb_info_id `
  936. _, err = to.Raw(msql, oldEdbInfo.EdbInfoId).QueryRows(&mappingList)
  937. if err != nil {
  938. errmsg = "获取计算指标关联基础指标信息失败:Err:" + err.Error()
  939. return
  940. }
  941. replaceCalculateTotal = len(mappingList)
  942. //计算指标
  943. if len(mappingList) > 0 {
  944. edbInfoIdList := make([]string, 0)
  945. for _, mv := range mappingList {
  946. //如果即将替换的指标与当前指标id一致,那么就退出当前循环,进入下一循环
  947. if mv.EdbInfoId == newEdbInfo.EdbInfoId {
  948. continue
  949. }
  950. //替换原指标
  951. msql := `UPDATE edb_info_calculate_mapping SET from_edb_info_id=?,from_edb_code=?,from_edb_name=?,from_source=?,from_source_name=? WHERE edb_info_calculate_mapping_id=? `
  952. _, err = to.Raw(msql, newEdbInfo.EdbInfoId, newEdbInfo.EdbCode, newEdbInfo.EdbName, newEdbInfo.Source, newEdbInfo.SourceName, mv.EdbInfoCalculateMappingId).Exec()
  953. if err != nil {
  954. return
  955. }
  956. relationEdbInfoIdList = append(relationEdbInfoIdList, mv.EdbInfoId)
  957. edbInfoIdList = append(edbInfoIdList, fmt.Sprint(mv.EdbInfoId))
  958. }
  959. logMsg += `涉及到的指标id:` + strings.Join(edbInfoIdList, ",") + ";"
  960. }
  961. }
  962. // 替换预测指标中的来源指标
  963. {
  964. //获取所有包含的计算指标
  965. predictEdbConfList := make([]*PredictEdbConf, 0)
  966. msql := ` SELECT * FROM predict_edb_conf WHERE source_edb_info_id=? GROUP BY predict_edb_info_id `
  967. _, err = to.Raw(msql, oldEdbInfo.EdbInfoId).QueryRows(&predictEdbConfList)
  968. if err != nil {
  969. errmsg = "获取关联的预测指标信息失败:Err:" + err.Error()
  970. return
  971. }
  972. replaceCalculateTotal += len(predictEdbConfList)
  973. //替换预测指标的来源指标
  974. msql = `UPDATE predict_edb_conf SET source_edb_info_id=? WHERE source_edb_info_id=? `
  975. _, err = to.Raw(msql, newEdbInfo.EdbInfoId, oldEdbInfo.EdbInfoId).Exec()
  976. if err != nil {
  977. return
  978. }
  979. if len(predictEdbConfList) > 0 {
  980. edbInfoIdList := make([]string, 0)
  981. for _, v := range predictEdbConfList {
  982. relationEdbInfoIdList = append(relationEdbInfoIdList, v.PredictEdbInfoId)
  983. edbInfoIdList = append(edbInfoIdList, fmt.Sprint(v.PredictEdbInfoId))
  984. }
  985. logMsg += `涉及到的预测指标id:` + strings.Join(edbInfoIdList, ",") + ";"
  986. }
  987. }
  988. return
  989. }
  990. type EdbInfoView struct {
  991. EdbInfoId int `orm:"column(edb_info_id);pk"`
  992. EdbInfoType int `description:"指标类型,0:普通指标,1:预测指标"`
  993. SourceName string `description:"来源名称"`
  994. Source int `description:"来源id"`
  995. EdbCode string `description:"指标编码"`
  996. EdbName string `description:"指标名称"`
  997. EdbNameSource string `description:"指标名称来源"`
  998. Frequency string `description:"频率"`
  999. Unit string `description:"单位"`
  1000. StartDate string `description:"起始日期"`
  1001. EndDate string `description:"终止日期"`
  1002. ClassifyId int `description:"分类id"`
  1003. SysUserId int
  1004. SysUserRealName string
  1005. UniqueCode string `description:"指标唯一编码"`
  1006. CreateTime string
  1007. ModifyTime string
  1008. MinValue float64 `description:"指标最小值"`
  1009. MaxValue float64 `description:"指标最大值"`
  1010. CalculateFormula string `description:"计算公式"`
  1011. EdbType int `description:"指标类型:1:基础指标,2:计算指标"`
  1012. Sort int `description:"排序字段"`
  1013. IsUpdate int `description:"当天是否已更新,1:未更新,2:已更新"`
  1014. LatestDate string `description:"数据最新日期(实际日期)"`
  1015. LatestValue float64 `description:"数据最新值(实际值)"`
  1016. SubSource int `description:"子数据来源:0:经济数据库,1:日期序列"`
  1017. SubSourceName string `description:"子数据来源名称"`
  1018. IndicatorCode string `description:"指标代码"`
  1019. StockCode string `description:"证券代码"`
  1020. EndValue float64 `description:"数据的最新值(预测日期的最新值)"`
  1021. }
  1022. // 获取指标的所有计算指标,以及计算指标所依赖计算指标
  1023. func GetAllCalculateByEdbInfoId(edbInfoId int) (mappingList []*EdbInfoCalculateMapping, err error) {
  1024. o := orm.NewOrmUsingDB("data")
  1025. msql := ` SELECT * FROM edb_info_calculate_mapping WHERE from_edb_info_id=? GROUP BY edb_info_id `
  1026. _, err = o.Raw(msql, edbInfoId).QueryRows(&mappingList)
  1027. if err != nil {
  1028. return
  1029. }
  1030. return
  1031. }
  1032. func GetAllCalculate(edbInfoId int, edbInfoMap map[int]int) (mappingList []*EdbInfoCalculateMapping, err error) {
  1033. calculateList, err := GetAllCalculateByEdbInfoId(edbInfoId)
  1034. if err != nil && err.Error() != utils.ErrNoRow() {
  1035. return
  1036. }
  1037. for _, item := range calculateList {
  1038. _, ok := edbInfoMap[item.EdbInfoId]
  1039. if !ok {
  1040. edbInfoMap[item.EdbInfoId] = item.EdbInfoId
  1041. mappingList = append(mappingList, item)
  1042. newCalculateInfoArr, _ := GetAllCalculate(item.EdbInfoId, edbInfoMap)
  1043. mappingList = append(mappingList, newCalculateInfoArr...)
  1044. }
  1045. }
  1046. return
  1047. }
  1048. // GetAllCalculateByEdbInfoIdV2 获取计算指标的所有所依赖的指标(基础指标+计算指标)
  1049. func GetAllCalculateByEdbInfoIdV2(edbInfoId int) (mappingList []*EdbInfoCalculateMapping, err error) {
  1050. o := orm.NewOrmUsingDB("data")
  1051. msql := ` SELECT * FROM edb_info_calculate_mapping WHERE edb_info_id=? GROUP BY from_edb_info_id `
  1052. _, err = o.Raw(msql, edbInfoId).QueryRows(&mappingList)
  1053. if err != nil {
  1054. return
  1055. }
  1056. return
  1057. }
  1058. // GetAllCalculateV2 获取所有的指标(如果下层指标包含了待替换指标,那么就不加入)
  1059. func GetAllCalculateV2(oldEdbInfoId, replaceEdbInfoId int, edbInfoMap map[int]int) (mappingList []*EdbInfoCalculateMapping, err error) {
  1060. calculateList, err := GetAllCalculateByEdbInfoId(oldEdbInfoId)
  1061. if err != nil && err.Error() != utils.ErrNoRow() {
  1062. return
  1063. }
  1064. tmpMappingList := make([]*EdbInfoCalculateMapping, 0)
  1065. for _, item := range calculateList {
  1066. //如果计算指标里面存在即将替换的指标id,那么退出当前循环,进入下一循环
  1067. if item.EdbInfoId == replaceEdbInfoId {
  1068. err = fmt.Errorf("指标重复1")
  1069. return
  1070. }
  1071. //获取该指标的依赖指标列表,如果依赖指标列表中存在即将替换的指标,那么过滤该指标
  1072. childCalculateList, tmpErr := GetAllCalculateByEdbInfoIdV2(item.EdbInfoId)
  1073. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  1074. err = tmpErr
  1075. return
  1076. }
  1077. for _, childCalculate := range childCalculateList {
  1078. if childCalculate.FromEdbInfoId == replaceEdbInfoId {
  1079. err = fmt.Errorf("指标重复2")
  1080. return
  1081. }
  1082. }
  1083. _, ok := edbInfoMap[item.EdbInfoId]
  1084. if !ok {
  1085. edbInfoMap[item.EdbInfoId] = item.EdbInfoId
  1086. newCalculateInfoArr, tmpErr := GetAllCalculateV2(item.EdbInfoId, replaceEdbInfoId, edbInfoMap)
  1087. if tmpErr != nil {
  1088. err = tmpErr
  1089. continue
  1090. } else {
  1091. mappingList = append(mappingList, item)
  1092. tmpMappingList = append(tmpMappingList, newCalculateInfoArr...)
  1093. }
  1094. }
  1095. }
  1096. mappingList = append(mappingList, tmpMappingList...)
  1097. return
  1098. }
  1099. // EdbInfoFilterDataResp 搜索指标列表数据返回
  1100. type EdbInfoFilterDataResp struct {
  1101. Paging *paging.PagingItem
  1102. List []*EdbInfoList
  1103. }
  1104. // GetEdbInfoFilterList 获取指指标列表数据接口
  1105. func GetEdbInfoFilterList(condition string, pars []interface{}, startSize, pageSize int) (total int64, list []*EdbInfoList, err error) {
  1106. o := orm.NewOrmUsingDB("data")
  1107. sql := ` SELECT count(1) total FROM edb_info where 1=1 ` + condition + ` ORDER BY edb_info_id DESC `
  1108. err = o.Raw(sql, pars).QueryRow(&total)
  1109. if err != nil {
  1110. return
  1111. }
  1112. sql = ` SELECT * FROM edb_info where 1=1 ` + condition + ` ORDER BY edb_info_id DESC LIMIT ?,? `
  1113. _, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
  1114. return
  1115. }
  1116. // SetEdbInfoImageReq 设置指标图片
  1117. type SetEdbInfoImageReq struct {
  1118. EdbInfoId int `description:"指标ID"`
  1119. ImageUrl string `description:"指标图片地址"`
  1120. }
  1121. // GetNextEdbInfoByCondition 根据条件获取下一个指标
  1122. func GetNextEdbInfoByCondition(condition string, pars []interface{}) (item *EdbInfo, err error) {
  1123. o := orm.NewOrmUsingDB("data")
  1124. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  1125. if condition != "" {
  1126. sql += condition
  1127. }
  1128. sql += " ORDER BY sort asc , edb_info_id asc LIMIT 1 "
  1129. err = o.Raw(sql, pars).QueryRow(&item)
  1130. return
  1131. }
  1132. // GetNextEdbInfo 根据分类id获取下一个 指标
  1133. func GetNextEdbInfo(classifyId, classifySort, classifyType, edbInfoType int) (item *EdbInfo, err error) {
  1134. o := orm.NewOrmUsingDB("data")
  1135. sql := ` SELECT b.* FROM edb_classify AS a
  1136. INNER JOIN edb_info AS b ON a.classify_id=b.classify_id
  1137. WHERE (a.sort>? OR (a.sort=? and a.classify_id>?) )
  1138. AND a.classify_type=? AND b.edb_info_type=?
  1139. ORDER BY a.sort ASC,b.sort asc,b.edb_info_id asc
  1140. LIMIT 1 `
  1141. err = o.Raw(sql, classifySort, classifySort, classifyId, classifyType, edbInfoType).QueryRow(&item)
  1142. return
  1143. }
  1144. // GetEdbInfoByEdbCodeList 根据指标code集合获取指标列表
  1145. func GetEdbInfoByEdbCodeList(source int, edbCodeList []string) (items []*EdbInfo, err error) {
  1146. num := len(edbCodeList)
  1147. if num <= 0 {
  1148. return
  1149. }
  1150. o := orm.NewOrmUsingDB("data")
  1151. sql := ` SELECT * FROM edb_info WHERE source=? AND edb_code in (` + utils.GetOrmInReplace(num) + `) `
  1152. _, err = o.Raw(sql, source, edbCodeList).QueryRows(&items)
  1153. return
  1154. }
  1155. // GetEdbInfoByConditionCount 根据条件获取指标列表数据总数
  1156. func GetEdbInfoByConditionCount(condition string, pars []interface{}) (count int, err error) {
  1157. o := orm.NewOrmUsingDB("data")
  1158. sql := ` SELECT COUNT(1) AS count FROM edb_info WHERE 1=1 `
  1159. if condition != "" {
  1160. sql += condition
  1161. }
  1162. err = o.Raw(sql, pars).QueryRow(&count)
  1163. return
  1164. }
  1165. // GetEdbInfoListByCondition 根据条件获取指标列表数据
  1166. func GetEdbInfoListByCondition(condition string, pars []interface{}, startSize, pageSize int, orderDesc string) (items []*EdbInfoList, err error) {
  1167. o := orm.NewOrmUsingDB("data")
  1168. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  1169. if condition != "" {
  1170. sql += condition
  1171. }
  1172. if orderDesc == `` {
  1173. orderDesc = ` ASC `
  1174. }
  1175. sql += ` ORDER BY edb_info_id `
  1176. sql += orderDesc
  1177. sql += ` LIMIT ?,? `
  1178. _, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
  1179. return
  1180. }
  1181. // GetEdbInfoListV2ByCondition 根据条件获取指标列表数据(EdbInfo原始数据结构)
  1182. func GetEdbInfoListV2ByCondition(condition string, pars []interface{}, startSize, pageSize int) (items []*EdbInfo, err error) {
  1183. o := orm.NewOrmUsingDB("data")
  1184. sql := ` SELECT * FROM edb_info WHERE 1=1 `
  1185. if condition != "" {
  1186. sql += condition
  1187. }
  1188. sql += ` ORDER BY edb_info_id ASC LIMIT ?,? `
  1189. _, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
  1190. return
  1191. }
  1192. // GetEdbInfoListGroupByUserId 根据指标id列表、用户分组获取指标信息
  1193. func GetEdbInfoListGroupByUserId(edbIdList []string) (items []*EdbInfo, err error) {
  1194. num := len(edbIdList)
  1195. if num <= 0 {
  1196. return
  1197. }
  1198. o := orm.NewOrmUsingDB("data")
  1199. sql := ` SELECT * FROM edb_info WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) GROUP BY sys_user_id `
  1200. _, err = o.Raw(sql, edbIdList).QueryRows(&items)
  1201. return
  1202. }
  1203. // GetEdbInfoListByEdbInfoId
  1204. // @Description: 根据指标id列表获取列表信息
  1205. // @param edbIdList
  1206. // @return items
  1207. // @return err
  1208. func GetEdbInfoListByEdbInfoId(edbIdList []string) (items []*EdbInfo, err error) {
  1209. num := len(edbIdList)
  1210. if num <= 0 {
  1211. return
  1212. }
  1213. o := orm.NewOrmUsingDB("data")
  1214. sql := ` SELECT * FROM edb_info WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  1215. _, err = o.Raw(sql, edbIdList).QueryRows(&items)
  1216. return
  1217. }
  1218. // GetEdbInfoListByUserId
  1219. // @Description: 根据指标id列表获取列表信息
  1220. // @param userIdList []int
  1221. // @param edbInfoType int
  1222. // @return items
  1223. // @return err
  1224. func GetEdbInfoListByUserId(userIdList []int, edbInfoType int) (items []*EdbInfo, err error) {
  1225. num := len(userIdList)
  1226. if num <= 0 {
  1227. return
  1228. }
  1229. o := orm.NewOrmUsingDB("data")
  1230. sql := ` SELECT * FROM edb_info WHERE edb_info_type = ? AND sys_user_id in (` + utils.GetOrmInReplace(num) + `) `
  1231. _, err = o.Raw(sql, edbInfoType, userIdList).QueryRows(&items)
  1232. return
  1233. }
  1234. // ModifyEdbInfoUserIdByCodeList 根据指标code列表修改创建人
  1235. func ModifyEdbInfoUserIdByCodeList(edbIdList []string, userId int, userName string) (err error) {
  1236. num := len(edbIdList)
  1237. if num <= 0 {
  1238. return
  1239. }
  1240. o := orm.NewOrmUsingDB("data")
  1241. sql := `UPDATE edb_info SET sys_user_id=?,sys_user_real_name=? WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  1242. _, err = o.Raw(sql, userId, userName, edbIdList).Exec()
  1243. return
  1244. }
  1245. // ModifyEdbInfoUserIdByOldUserId
  1246. // @Description: 根据旧用户id修改新用户id
  1247. // @author: Roc
  1248. // @datetime 2024-03-25 19:17:09
  1249. // @param edbIdList []string
  1250. // @param userId int
  1251. // @param userName string
  1252. // @return err error
  1253. func ModifyEdbInfoUserIdByOldUserId(oldUserIdList []int, edbInfoType, userId int, userName string) (err error) {
  1254. num := len(oldUserIdList)
  1255. if num <= 0 {
  1256. return
  1257. }
  1258. o := orm.NewOrmUsingDB("data")
  1259. sql := `UPDATE edb_info SET sys_user_id=?,sys_user_real_name=? WHERE sys_user_id in (` + utils.GetOrmInReplace(num) + `) and edb_info_type = ?`
  1260. _, err = o.Raw(sql, userId, userName, oldUserIdList, edbInfoType).Exec()
  1261. return
  1262. }
  1263. // MoveEdbChartList 图表/指标信息
  1264. type MoveEdbChartList struct {
  1265. DataId string `description:"指标/图表唯一id"`
  1266. Code string `description:"指标code"`
  1267. Name string `description:"指标/图表名称"`
  1268. NameEn string `description:"指标/图表名称"`
  1269. ClassifyName string `description:"分类名称"`
  1270. ClassifyNameEn string `description:"分类名称"`
  1271. CreateUserId int `description:"创建人id"`
  1272. CreateUserName string `description:"创建人名称"`
  1273. }
  1274. // MoveEdbChartListResp 更改创建人返回数据
  1275. type MoveEdbChartListResp struct {
  1276. Paging *paging.PagingItem
  1277. List []MoveEdbChartList
  1278. }
  1279. type EdbChartClassifyResp struct {
  1280. List []*EdbChartClassify
  1281. }
  1282. type EdbChartClassify struct {
  1283. ClassifyId int
  1284. ClassifyName string
  1285. ParentId int
  1286. IsJoinPermission int `description:"是否加入权限管控,0:不加入;1:加入;默认:0"`
  1287. Child []*EdbChartClassify
  1288. }
  1289. // EdbInfoDataSeasonalResp 指标季节性数据返回
  1290. type EdbInfoDataSeasonalResp struct {
  1291. EdbInfo *EdbInfo
  1292. DataList interface{}
  1293. }
  1294. // SetEdbDataInsertConfigReq 设置插入规则的请求
  1295. type SetEdbDataInsertConfigReq struct {
  1296. EdbInfoId int `description:"指标ID"`
  1297. Date string `description:"日期"`
  1298. Value string `description:"值"`
  1299. }
  1300. // GetEdbInfoByClassifyId 用于分类展示
  1301. func GetEdbInfoByClassifyId(classifyId, edbInfoType, adminId int) (items []*EdbClassifyItems, err error) {
  1302. o := orm.NewOrmUsingDB("data")
  1303. sql := ` SELECT edb_info_id,classify_id,edb_name AS classify_name,edb_name_en AS classify_name_en,unique_code,source_name,source,sys_user_id,sys_user_real_name,start_date,edb_code,edb_type, sort,is_join_permission FROM edb_info WHERE classify_id = ? AND edb_info_type = ?`
  1304. pars := []interface{}{classifyId, edbInfoType}
  1305. // 如果筛选了用户id
  1306. if adminId > 0 {
  1307. sql += ` AND sys_user_id = ? `
  1308. pars = append(pars, adminId)
  1309. }
  1310. sql += ` order by sort asc,edb_info_id asc `
  1311. _, err = o.Raw(sql, pars).QueryRows(&items)
  1312. return
  1313. }
  1314. type EdbAndClassify struct {
  1315. EdbInfoId int `description:"指标id"`
  1316. EdbCode string `description:"指标code"`
  1317. UniqueCode string `description:"唯一code"`
  1318. EdbName string `description:"指标名称"`
  1319. ClassifyId int `description:"所属分类id"`
  1320. FirstClassifyId int `description:"第1级的分类id"`
  1321. FirstClassifyName string `description:"第1级的分类名称"`
  1322. SecondClassifyId int `description:"第2级的分类id"`
  1323. SecondClassifyName string `description:"第2级的分类名称"`
  1324. }
  1325. // GetEdbInfoAndClassifyListByEdbIdList 根据指标id列表获取 指标及分类信息
  1326. func GetEdbInfoAndClassifyListByEdbIdList(edbIdList []int) (items []*EdbAndClassify, err error) {
  1327. num := len(edbIdList)
  1328. if num <= 0 {
  1329. return
  1330. }
  1331. o := orm.NewOrmUsingDB("data")
  1332. sql := ` SELECT a.edb_info_id,a.edb_code,a.unique_code,a.edb_name,a.classify_id FROM edb_info AS a
  1333. WHERE a.edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  1334. _, err = o.Raw(sql, edbIdList).QueryRows(&items)
  1335. return
  1336. }
  1337. // TraceEdbInfoResp 指标追溯数据返回
  1338. type TraceEdbInfoResp struct {
  1339. EdbInfoId int `description:"指标id"`
  1340. EdbInfoType int `description:"指标类型: 0-普通指标; 1-预测指标"`
  1341. EdbName string `description:"指标名称"`
  1342. EdbNameEn string `description:"指标英文名称"`
  1343. EdbType int `description:"指标类型: 1-基础指标; 2-计算指标"`
  1344. RuleTitle string `description:"指标规则"`
  1345. RuleTitleEn string `description:"指标规则(英文)"`
  1346. UniqueCode string `description:"唯一编码"`
  1347. ClassifyId int `description:"分类ID"`
  1348. Child []TraceEdbInfoResp `description:"下级来源"`
  1349. IsStop int8 `description:"是否终止"`
  1350. EdbInfo *EdbInfo `description:"指标信息" json:"-"`
  1351. HaveOperaAuth bool `description:"是否有数据权限,默认:false"`
  1352. }
  1353. // BeforeAndAfterDateDataResp 前后几期数据
  1354. type BeforeAndAfterDateDataResp struct {
  1355. List []*EdbDataList `description:"list"`
  1356. Date string `description:"实际日期"`
  1357. ShowValue string `description:"展示值"`
  1358. }
  1359. // GetEdbInfoAdminList
  1360. func GetEdbInfoAdminList(edbType int) (list []int, err error) {
  1361. o := orm.NewOrmUsingDB("data")
  1362. sql := ` SELECT sys_user_id FROM edb_info WHERE edb_info_type = ? GROUP BY sys_user_id `
  1363. _, err = o.Raw(sql, edbType).QueryRows(&list)
  1364. return
  1365. }
  1366. type EdbInfoExistCheckResp struct {
  1367. IndexExist bool `description:"指标是否存在:true,存在,false:不存在"`
  1368. ExistStockCodeArr []string `description:"存在的证券代码"`
  1369. ExistEdbCodeArr []string `description:"存在的指标代码"`
  1370. ExistClassifyId []int `description:"存在的分类id"`
  1371. ExistIndexId []int `description:"存在的指标id"`
  1372. ExistEdbInfo []*EdbInfo `description:"存在的指标"`
  1373. }
  1374. type BatchAddEdbInfoReq struct {
  1375. BatchList []*BatchAddEdbInfo
  1376. }
  1377. type BatchAddEdbInfo struct {
  1378. Source int `description:"来源id"`
  1379. EdbName string `description:"指标名称"`
  1380. Frequency string `description:"频率"`
  1381. Unit string `description:"单位"`
  1382. ClassifyId int `description:"分类id"`
  1383. StockCode string `description:"证券代码"`
  1384. EdbCode string `description:"指标编码"`
  1385. }
  1386. func GetEdbInfoWsdMaxAndMinInfo(source, subSource int, edbCode string) (item *EdbInfoMaxAndMinInfo, err error) {
  1387. o := orm.NewOrmUsingDB("data")
  1388. sql := ``
  1389. tableName := GetEdbDataTableNameAndSubSource(source, subSource)
  1390. 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=? `
  1391. sql = fmt.Sprintf(sql, tableName)
  1392. err = o.Raw(sql, edbCode).QueryRow(&item)
  1393. if err != nil {
  1394. return
  1395. }
  1396. var latest_value float64
  1397. sql = ` SELECT value AS latest_value FROM %s WHERE edb_code=? ORDER BY data_time DESC LIMIT 1 `
  1398. sql = fmt.Sprintf(sql, tableName)
  1399. err = o.Raw(sql, edbCode).QueryRow(&latest_value)
  1400. item.LatestValue = latest_value
  1401. return
  1402. }
  1403. // GetEdbInfoByNames 根据名称获取普通的指标
  1404. func GetEdbInfoByNames(edbNames string) (items []*EdbInfoList, err error) {
  1405. o := orm.NewOrmUsingDB("data")
  1406. sql := ` SELECT * FROM edb_info WHERE edb_name IN (` + edbNames + `) AND edb_info_type = 0 `
  1407. _, err = o.Raw(sql).QueryRows(&items)
  1408. return
  1409. }
  1410. func GetSmmEdbInfoMaxAndMinInfo(edbCodes []string) (item *EdbInfoMaxAndMinInfo, err error) {
  1411. o := orm.NewOrmUsingDB("data")
  1412. sql := ``
  1413. 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 edb_data_ys WHERE edb_code IN (` + utils.GetOrmInReplace(len(edbCodes)) + `)`
  1414. err = o.Raw(sql, edbCodes).QueryRow(&item)
  1415. if err != nil {
  1416. return
  1417. }
  1418. var latest_value float64
  1419. sql = ` SELECT value AS latest_value FROM edb_data_ys WHERE edb_code IN (` + utils.GetOrmInReplace(len(edbCodes)) + `) ORDER BY data_time DESC LIMIT 1 `
  1420. err = o.Raw(sql, edbCodes).QueryRow(&latest_value)
  1421. item.LatestValue = latest_value
  1422. return
  1423. }
  1424. type EdbInfoSmmExistCheckResp struct {
  1425. EdbInfoExistCheckResp
  1426. ExistAll bool `description:"是否全部重复"`
  1427. }
  1428. // GetEdbBaseInfoList
  1429. // @Description: 获取指标库数据列表
  1430. // @author: Roc
  1431. // @datetime 2024-01-10 14:28:22
  1432. // @param condition string
  1433. // @param pars []interface{}
  1434. // @param orderBy string
  1435. // @param startSize int
  1436. // @param pageSize int
  1437. // @return total int
  1438. // @return items []*BaseRefreshEdbInfo
  1439. // @return err error
  1440. func GetEdbBaseInfoList(condition string, pars []interface{}, orderBy string, startSize, pageSize int) (total int, items []*BaseRefreshEdbInfo, err error) {
  1441. o := orm.NewOrmUsingDB("data")
  1442. // 数量汇总
  1443. totalSql := ` SELECT count(1) FROM edb_info WHERE 1=1 `
  1444. if condition != "" {
  1445. totalSql += condition
  1446. }
  1447. err = o.Raw(totalSql, pars).QueryRow(&total)
  1448. if err != nil {
  1449. return
  1450. }
  1451. // 列表数据
  1452. sql := ` SELECT edb_info_id as edb_info_id, classify_id as classify_id,edb_code as index_code,edb_name as index_name,end_date,end_value,sys_user_id,sys_user_real_name,frequency,no_update as is_stop,terminal_code FROM edb_info WHERE 1=1 `
  1453. if condition != "" {
  1454. sql += condition
  1455. }
  1456. if orderBy != "" {
  1457. sql += ` ORDER BY ` + orderBy
  1458. } else {
  1459. sql += ` ORDER BY edb_info_id ASC `
  1460. }
  1461. sql += ` LIMIT ?,? `
  1462. _, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
  1463. return
  1464. }
  1465. // ModifyEdbInfoUpdateStatus
  1466. // @Description: 修改指标库停更状态
  1467. // @author: Roc
  1468. // @datetime 2024-01-08 16:23:31
  1469. // @param edbIdList []int
  1470. // @param indexCodeList []string
  1471. // @param isStop int
  1472. // @return err error
  1473. func ModifyEdbInfoUpdateStatus(edbIdList []int, isStop int) (err error) {
  1474. idNum := len(edbIdList)
  1475. if idNum <= 0 {
  1476. return
  1477. }
  1478. o, err := orm.NewOrmUsingDB("data").Begin()
  1479. if err != nil {
  1480. return
  1481. }
  1482. defer func() {
  1483. if err != nil {
  1484. _ = o.Rollback()
  1485. return
  1486. }
  1487. _ = o.Commit()
  1488. }()
  1489. // 更改指标的更新状态
  1490. sql := ` UPDATE edb_info SET no_update = ? WHERE edb_info_id IN (` + utils.GetOrmInReplace(idNum) + `) `
  1491. _, err = o.Raw(sql, isStop, edbIdList).Exec()
  1492. if err != nil {
  1493. return
  1494. }
  1495. return
  1496. }
  1497. func GetEdbInfoCount(source int, edbCode string) (count int, err error) {
  1498. o := orm.NewOrmUsingDB("data")
  1499. sql := ` SELECT COUNT(1) AS count FROM edb_info
  1500. WHERE source=? AND edb_code = ?`
  1501. err = o.Raw(sql, source, edbCode).QueryRow(&count)
  1502. return
  1503. }
  1504. type EdbInfoEditRecord struct {
  1505. EdbInfoId int `description:"指标ID"`
  1506. EdbName string `description:"指标名称"`
  1507. Frequency string `description:"频率"`
  1508. Unit string `description:"单位"`
  1509. ClassifyId int `description:"分类id"`
  1510. CalculateFormula string `description:"计算公式"`
  1511. OperateUserId int `description:"操作人id"`
  1512. OperateUserRealName string `description:"操作人姓名"`
  1513. }
  1514. func ModifyEdbInfoBaseTimeById(edbInfoId int, cTime time.Time) (err error) {
  1515. o := orm.NewOrmUsingDB("data")
  1516. // 更新修改时间
  1517. sql := ` UPDATE edb_info SET base_modify_time = ? WHERE edb_info_id = ? `
  1518. _, err = o.Raw(sql, cTime, edbInfoId).Exec()
  1519. return
  1520. }
  1521. // GetEdbInfoByNameArr 根据名称获取指标
  1522. func GetEdbInfoByNameArr(names []string, edbInfoType int) (items []*EdbInfo, err error) {
  1523. if len(names) == 0 {
  1524. return
  1525. }
  1526. o := orm.NewOrmUsingDB("data")
  1527. sql := fmt.Sprintf(`SELECT edb_info_id, edb_code, edb_name FROM edb_info WHERE edb_name IN (%s) AND edb_info_type = ? `, utils.GetOrmInReplace(len(names)))
  1528. _, err = o.Raw(sql, names, edbInfoType).QueryRows(&items)
  1529. return
  1530. }
  1531. // GetEdbCodesBySource 根据来源获取指标编码
  1532. func GetEdbCodesBySource(source int) (items []*EdbInfo, err error) {
  1533. o := orm.NewOrmUsingDB("data")
  1534. sql := ` SELECT edb_info_id, edb_code, unique_code, classify_id FROM edb_info WHERE source = ? `
  1535. _, err = o.Raw(sql, source).QueryRows(&items)
  1536. return
  1537. }
  1538. // GetAllEdbDataListData
  1539. // @Description: 获取指标的所有数据
  1540. // @author: Roc
  1541. // @datetime 2024-05-07 15:18:27
  1542. // @param edbInfoId int
  1543. // @param source int
  1544. // @param subSource int
  1545. // @param startDataTime string
  1546. // @return dataList []*EdbData
  1547. // @return err error
  1548. func GetAllEdbDataListData(edbInfoId, source, subSource int, startDataTime string) (dataList []*EdbData, err error) {
  1549. // 自有数据需要额外处理(从mongo获取)
  1550. if source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  1551. return getAllDataByMongo(edbInfoId, source, subSource, startDataTime)
  1552. }
  1553. if source == utils.DATA_SOURCE_THS && subSource == utils.DATA_SUB_SOURCE_HIGH_FREQUENCY && utils.UseMongo {
  1554. return getThsHfAllDataByMongo(edbInfoId, source, subSource, startDataTime)
  1555. }
  1556. // 默认走mysql
  1557. return getAllDataByMysql(edbInfoId, source, subSource, startDataTime)
  1558. }
  1559. // getAllDataByMysql
  1560. // @Description: 从mysql获取指标的所有数据
  1561. // @author: Roc
  1562. // @datetime 2024-05-07 15:18:41
  1563. // @param edbInfoId int
  1564. // @param source int
  1565. // @param subSource int
  1566. // @param startDataTime string
  1567. // @return dataList []*data_manage.EdbData
  1568. // @return err error
  1569. func getAllDataByMysql(edbInfoId, source, subSource int, startDataTime string) (dataList []*EdbData, err error) {
  1570. dataList = make([]*EdbData, 0)
  1571. var dataCondition string
  1572. var dataPars []interface{}
  1573. dataCondition += ` AND edb_info_id=? `
  1574. dataPars = append(dataPars, edbInfoId)
  1575. // 结束日期
  1576. if startDataTime != "" {
  1577. dataCondition += ` AND data_time > ? `
  1578. dataPars = append(dataPars, startDataTime)
  1579. }
  1580. // 获取列表数据
  1581. dataList, err = GetAllEdbDataListByCondition(dataCondition, dataPars, source, subSource)
  1582. if err != nil {
  1583. return
  1584. }
  1585. return
  1586. }
  1587. // getAllDataByMongo
  1588. // @Description: 从mongo获取指标的所有数据
  1589. // @author: Roc
  1590. // @datetime 2024-05-07 15:18:53
  1591. // @param edbInfoId int
  1592. // @param source int
  1593. // @param subSource int
  1594. // @param startDataTime string
  1595. // @return dataList []*data_manage.EdbData
  1596. // @return err error
  1597. func getAllDataByMongo(edbInfoId, source, subSource int, startDataTime string) (dataList []*EdbData, err error) {
  1598. dataList = make([]*EdbData, 0)
  1599. mogDataObj := mgo.EdbDataBusiness{}
  1600. // 构建查询条件
  1601. queryConditions := bson.M{
  1602. "edb_info_id": edbInfoId,
  1603. }
  1604. // 数据日期
  1605. dateCondition, err := mgo.BuildDateCondition(startDataTime, "")
  1606. if err != nil {
  1607. return
  1608. }
  1609. if len(dateCondition) > 0 {
  1610. queryConditions["data_time"] = dateCondition
  1611. }
  1612. // 获取列表数据
  1613. tmpDataList, tmpErr := mogDataObj.GetAllDataList(queryConditions, []string{"-data_time"})
  1614. if tmpErr != nil {
  1615. err = tmpErr
  1616. return
  1617. }
  1618. for k, v := range tmpDataList {
  1619. dataList = append(dataList, &EdbData{
  1620. EdbDataId: k + 1,
  1621. EdbInfoId: v.EdbInfoId,
  1622. DataTime: v.DataTime.Format(utils.FormatDate),
  1623. Value: v.Value,
  1624. })
  1625. }
  1626. return
  1627. }
  1628. type ReplaceEdbInfoItem struct {
  1629. OldEdbInfo *EdbInfo
  1630. NewEdbInfo *EdbInfo
  1631. }
  1632. func GetThsHfEdbInfoMaxAndMinInfoByMongo(source, subSource int, edbCode string) (item *EdbInfoMaxAndMinInfo, err error) {
  1633. mogDataObj := new(mgo.EdbDataThsHf)
  1634. pipeline := []bson.M{
  1635. {"$match": bson.M{"edb_code": edbCode}},
  1636. {"$group": bson.M{
  1637. "_id": nil,
  1638. "min_date": bson.M{"$min": "$data_time"},
  1639. "max_date": bson.M{"$max": "$data_time"},
  1640. "min_value": bson.M{"$min": "$value"},
  1641. "max_value": bson.M{"$max": "$value"},
  1642. }},
  1643. {"$project": bson.M{"_id": 0}}, // 可选,如果不需要_id字段
  1644. }
  1645. result, err := mogDataObj.GetEdbInfoMaxAndMinInfo(pipeline)
  1646. if err != nil {
  1647. fmt.Println("EdbDataThsHf getEdbDataThsHfList Err:" + err.Error())
  1648. return
  1649. }
  1650. if !result.MaxDate.IsZero() {
  1651. whereQuery := bson.M{"edb_code": edbCode, "data_time": result.MaxDate}
  1652. selectParam := bson.D{{"value", 1}, {"_id", 0}}
  1653. latestValue, tmpErr := mogDataObj.GetLatestValue(whereQuery, selectParam)
  1654. if tmpErr != nil {
  1655. err = tmpErr
  1656. return
  1657. }
  1658. result.LatestValue = latestValue.Value
  1659. result.EndValue = latestValue.Value
  1660. }
  1661. item = &EdbInfoMaxAndMinInfo{
  1662. MinDate: result.MinDate.Format(utils.FormatDate),
  1663. MaxDate: result.MaxDate.Format(utils.FormatDate),
  1664. MinValue: result.MinValue,
  1665. MaxValue: result.MaxValue,
  1666. LatestValue: result.LatestValue,
  1667. }
  1668. return
  1669. }
  1670. func getThsHfAllDataByMongo(edbInfoId, source, subSource int, startDataTime string) (dataList []*EdbData, err error) {
  1671. dataList = make([]*EdbData, 0)
  1672. mogDataObj := mgo.EdbDataThsHf{}
  1673. // 构建查询条件
  1674. queryConditions := bson.M{
  1675. "edb_info_id": edbInfoId,
  1676. }
  1677. // 开始日期
  1678. dateCondition, err := mgo.BuildDateCondition(startDataTime, "")
  1679. if err != nil {
  1680. return
  1681. }
  1682. if len(dateCondition) > 0 {
  1683. queryConditions["data_time"] = dateCondition
  1684. }
  1685. // 获取列表数据
  1686. tmpDataList, tmpErr := mogDataObj.GetAllDataList(queryConditions, []string{"-data_time"})
  1687. if tmpErr != nil {
  1688. err = tmpErr
  1689. return
  1690. }
  1691. for k, v := range tmpDataList {
  1692. dataList = append(dataList, &EdbData{
  1693. EdbDataId: k + 1,
  1694. EdbInfoId: v.EdbInfoId,
  1695. DataTime: v.DataTime.Format(utils.FormatDate),
  1696. Value: v.Value,
  1697. })
  1698. }
  1699. return
  1700. }