edb_info.go 69 KB

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