edb_info.go 80 KB

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