edb_info.go 69 KB

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