edb_info.go 80 KB

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