edb_info.go 69 KB

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