edb_info.go 70 KB

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