edb_info.go 70 KB

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