edb_info.go 70 KB

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