manual.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. package data
  2. import (
  3. "errors"
  4. "eta/eta_api/models"
  5. "eta/eta_api/models/data_manage"
  6. "eta/eta_api/models/system"
  7. "eta/eta_api/services/alarm_msg"
  8. "eta/eta_api/utils"
  9. "fmt"
  10. "github.com/shopspring/decimal"
  11. "github.com/tealeg/xlsx"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. func GetManualSysUser(keyWord string) (list []*data_manage.ManualSysUser, err error) {
  17. //departmentId := 1
  18. list = make([]*data_manage.ManualSysUser, 0)
  19. departmentItems, err := system.GetSysDepartmentAll()
  20. if err != nil {
  21. return list, err
  22. }
  23. for _, dv := range departmentItems {
  24. department := new(data_manage.ManualSysUser)
  25. department.ItemId = dv.DepartmentId * 10000
  26. department.ItemName = dv.DepartmentName
  27. fmt.Println(department.ItemId, department.ItemName)
  28. //GetSysuserList
  29. var condition string
  30. var pars []interface{}
  31. if keyWord != "" {
  32. condition += ` AND (real_name LIKE ? OR admin_name LIKE ? OR mobile LIKE ? ) `
  33. pars = utils.GetLikeKeywordPars(pars, keyWord, 3)
  34. }
  35. sysUsers, err := system.GetSysUserItems(condition, pars)
  36. if err != nil {
  37. return list, err
  38. }
  39. groups, err := system.GetSysGroupByDepartmentId(dv.DepartmentId)
  40. if err != nil {
  41. return list, err
  42. }
  43. dg := make([]*data_manage.ManualSysUser, 0)
  44. for _, v := range groups {
  45. group := new(data_manage.ManualSysUser)
  46. group.ItemId = v.DepartmentId * 100000
  47. group.ItemName = v.GroupName
  48. for _, sv := range sysUsers {
  49. user := new(data_manage.ManualSysUser)
  50. user.ItemId = sv.AdminId
  51. user.ItemName = sv.RealName
  52. if sv.GroupId == v.GroupId {
  53. group.Children = append(group.Children, user)
  54. }
  55. }
  56. if len(group.Children) > 0 {
  57. dg = append(dg, group)
  58. }
  59. }
  60. if len(groups) <= 0 {
  61. group := new(data_manage.ManualSysUser)
  62. group.ItemId = dv.DepartmentId * 100000
  63. group.ItemName = "无分组"
  64. for _, sv := range sysUsers {
  65. user := new(data_manage.ManualSysUser)
  66. user.ItemId = sv.AdminId
  67. user.ItemName = sv.RealName
  68. if sv.DepartmentId == dv.DepartmentId && sv.GroupId == 0 {
  69. group.Children = append(group.Children, user)
  70. }
  71. }
  72. if len(group.Children) > 0 {
  73. dg = append(dg, group)
  74. }
  75. }
  76. if len(dg) > 0 {
  77. department.Children = dg
  78. list = append(list, department)
  79. }
  80. }
  81. return
  82. }
  83. // GetManualEdbClassifyListByAdminId
  84. // @Description: 根据账户类型获取手工指标分类ID集合
  85. // @author: Roc
  86. // @datetime 2024-07-16 13:18:39
  87. // @param adminId int64
  88. // @return classifyIdList []int
  89. // @return err error
  90. func GetManualEdbClassifyListByAdminId(adminId int64) (classifyIdList []int, err error) {
  91. var list []*models.EdbdataClassify
  92. if adminId <= 0 {
  93. list, err = models.GetAllChildManualEdbClassify()
  94. } else {
  95. userClassifyList, _ := models.GetManualUserClassify(int(adminId))
  96. var userClassifyIdList []int
  97. for _, v := range userClassifyList {
  98. userClassifyIdList = append(userClassifyIdList, v.ClassifyId)
  99. }
  100. list, err = models.GetChildManualEdbClassifyByIdList(userClassifyIdList)
  101. }
  102. if err != nil {
  103. return
  104. }
  105. for _, classify := range list {
  106. classifyIdList = append(classifyIdList, classify.ClassifyId)
  107. }
  108. return
  109. }
  110. type ManualIndexSource2EdbReq struct {
  111. EdbCode string
  112. EdbName string
  113. Frequency string
  114. Unit string
  115. ClassifyId int
  116. AdminId int
  117. AdminRealName string
  118. }
  119. // ManualIndexSource2Edb
  120. // @Description: 新增手工数据源到指标库
  121. // @author: Roc
  122. // @datetime 2024-07-26 13:23:19
  123. // @param req ManualIndexSource2EdbReq
  124. // @param lang string
  125. // @return edb *data_manage.EdbInfo
  126. // @return err error
  127. // @return errMsg string
  128. // @return skip bool
  129. func ManualIndexSource2Edb(req ManualIndexSource2EdbReq, lang string) (edb *data_manage.EdbInfo, err error, errMsg string, skip bool) {
  130. if req.EdbCode == "" {
  131. err = fmt.Errorf("指标ID为空")
  132. return
  133. }
  134. defer func() {
  135. if err != nil {
  136. tips := fmt.Sprintf("ManualIndexSource2Edb新增失败, Err: %s", err.Error())
  137. fmt.Println(tips)
  138. utils.FileLog.Info(tips)
  139. }
  140. }()
  141. source := utils.DATA_SOURCE_MANUAL
  142. // 是否已有指标数据
  143. dataList, e := data_manage.GetEdbDataAllByEdbCode(req.EdbCode, source, utils.DATA_SUB_SOURCE_EDB, utils.EDB_DATA_LIMIT)
  144. if e != nil {
  145. err = fmt.Errorf("获取指标数据失败, Err: %s", e.Error())
  146. return
  147. }
  148. // 新增指标数据
  149. if len(dataList) == 0 {
  150. res, e := AddEdbData(source, req.EdbCode, req.Frequency)
  151. if e != nil {
  152. err = fmt.Errorf("index_lib: 新增指标数据失败, Err: %s", e.Error())
  153. return
  154. }
  155. if res == nil {
  156. err = fmt.Errorf("index_lib: 新增指标数据失败, res nil")
  157. return
  158. }
  159. if res.Ret != 200 {
  160. err = fmt.Errorf("index_lib: 新增指标数据失败, Ret: %d", res.Ret)
  161. return
  162. }
  163. }
  164. // 是否新增过指标
  165. exist, e := data_manage.GetEdbInfoByEdbCode(source, req.EdbCode)
  166. if e != nil && e.Error() != utils.ErrNoRow() {
  167. err = fmt.Errorf("获取指标是否存在失败, err: %s", e.Error())
  168. return
  169. }
  170. if exist != nil {
  171. skip = true
  172. return
  173. }
  174. // 开始结束时间
  175. var startDate, endDate string
  176. minMax, e := data_manage.GetEdbInfoMaxAndMinInfo(source, utils.DATA_SUB_SOURCE_EDB, req.EdbCode)
  177. if e != nil && e.Error() != utils.ErrNoRow() {
  178. err = fmt.Errorf("MinMax: 获取指标极值失败, err: %s", e.Error())
  179. return
  180. }
  181. if minMax != nil {
  182. startDate = minMax.MinDate
  183. endDate = minMax.MaxDate
  184. }
  185. // 新增指标库
  186. edbInfo, e, msg, _ := EdbInfoAdd(source, utils.DATA_SUB_SOURCE_EDB, req.ClassifyId, req.EdbCode, req.EdbName, req.Frequency, req.Unit, startDate, endDate, req.AdminId, req.AdminRealName, lang)
  187. if e != nil {
  188. errMsg = msg
  189. err = fmt.Errorf("EdbInfo: 新增指标失败, err: %s", e.Error())
  190. return
  191. }
  192. edb = edbInfo
  193. // 新增es
  194. go AddOrEditEdbInfoToEs(edbInfo.EdbInfoId)
  195. return
  196. }
  197. // ImportManualData
  198. // @Description: 数据导入
  199. // @author: Roc
  200. // @datetime 2024-08-01 11:27:21
  201. // @param path string
  202. // @param sysUser *system.Admin
  203. // @return successCount int
  204. // @return failCount int
  205. // @return err error
  206. // @return errMsg string
  207. func ImportManualData(path string, sysUser *system.Admin) (successCount, failCount int, indexCount int, err error, errMsg string) {
  208. // 错误信息
  209. errMsgList := make([]string, 0)
  210. // 操作记录
  211. recordMap := make(map[string]string)
  212. defer func() {
  213. recordList := make([]*models.EdbinfoOpRecord, 0)
  214. for tradeCode, remark := range recordMap {
  215. recordList = append(recordList, &models.EdbinfoOpRecord{
  216. TradeCode: tradeCode,
  217. Remark: remark,
  218. UserId: sysUser.AdminId,
  219. UserName: sysUser.RealName,
  220. CreateTime: time.Now(),
  221. })
  222. // 修改最大最小值
  223. go ModifyManualEdbMaxMinDate(tradeCode)
  224. }
  225. if len(recordList) > 0 {
  226. go func() {
  227. obj := models.EdbinfoOpRecord{}
  228. _ = obj.MulCreate(recordList)
  229. }()
  230. }
  231. // 错误信息记录
  232. if len(errMsgList) > 0 {
  233. utils.FileLog.Info("导入失败, errMsgList: %v", strings.Join(errMsgList, "\n"))
  234. }
  235. }()
  236. errMsg = `导入失败`
  237. xlFile, err := xlsx.OpenFile(path)
  238. if err != nil {
  239. fmt.Println(err.Error())
  240. return
  241. }
  242. if len(xlFile.Sheets) <= 0 {
  243. errMsg = "导入模板异常"
  244. err = errors.New(errMsg)
  245. return
  246. }
  247. //导入失败数据
  248. failDataList := make([]*models.EdbdataImportFail, 0)
  249. var indexDataList []ImportManualIndexData
  250. // 指标名称列表
  251. indexNameList := make([]string, 0)
  252. // 模板校验,然后处理成标准化格式
  253. for _, sheet := range xlFile.Sheets {
  254. var tmpIndexDataList []ImportManualIndexData
  255. var tmpFailDataList []*models.EdbdataImportFail
  256. rowList := sheet.Rows
  257. if len(rowList) <= 0 {
  258. errMsg = sheet.Name + "页异常"
  259. err = errors.New(errMsg)
  260. return
  261. }
  262. templateType := 1 // 模板类型
  263. minCellNum := 6 // 模板最小列数
  264. headerCell := rowList[0].Cells
  265. // 确定模板
  266. for _, v := range headerCell {
  267. if v.String() == "导入模板2/Import Template 2" {
  268. templateType = 2
  269. minCellNum = 2
  270. break
  271. }
  272. }
  273. // 如果小于最少列数,则报错
  274. if len(headerCell) < minCellNum {
  275. errMsg = sheet.Name + "页模板异常"
  276. err = errors.New(errMsg)
  277. return
  278. }
  279. switch templateType {
  280. case 2:
  281. // 模板2需要走对应的取数逻辑
  282. tmpIndexDataList, tmpFailDataList, err, errMsg = getDataByTemplate2(sheet, sysUser.AdminId)
  283. default:
  284. // 模板1需要走对应的取数逻辑
  285. tmpIndexDataList, tmpFailDataList, err, errMsg = getDataByTemplate1(sheet, sysUser.AdminId)
  286. }
  287. indexDataList = append(indexDataList, tmpIndexDataList...)
  288. failDataList = append(failDataList, tmpFailDataList...)
  289. }
  290. indexDataListMap := make(map[string]ImportManualIndexData)
  291. for _, v := range indexDataList {
  292. indexData, ok := indexDataListMap[v.IndexName]
  293. if !ok {
  294. // 没有就赋值
  295. indexDataListMap[v.IndexName] = v
  296. indexNameList = append(indexNameList, v.IndexName)
  297. continue
  298. }
  299. indexData.Unit = v.Unit
  300. indexData.ClassName = v.ClassName
  301. indexData.Frequency = v.Frequency
  302. indexData.DataMap = v.DataMap
  303. }
  304. if len(indexNameList) <= 0 {
  305. return
  306. }
  307. //超管账号可以查看分类下的所有频度数据
  308. userId := sysUser.AdminId
  309. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
  310. userId = 0
  311. }
  312. //获取账户所拥有权限的分类id集合
  313. classifyNameStrList, edbDataClassifyMap, err := GetEdbClassifyNameListByAdminId(int64(userId))
  314. if err != nil {
  315. errMsg = "获取分类数据失败"
  316. return
  317. }
  318. //指标map
  319. targetMap := make(map[string]*models.Edbinfo)
  320. defer func() {
  321. for _, target := range targetMap {
  322. //结束后,清除掉对应的缓存
  323. key := "import:edbinfo:data:" + target.TradeCode
  324. utils.Rc.Delete(key)
  325. //将该指标的code加入到 “手工数据导入后刷新” 缓存
  326. if utils.Re == nil {
  327. err := utils.Rc.LPush(utils.CACHE_IMPORT_MANUAL_DATA, target.TradeCode)
  328. if err != nil {
  329. fmt.Println("CACHE_IMPORT_MANUAL_DATA LPush Err:" + err.Error())
  330. }
  331. }
  332. }
  333. }()
  334. // 所有的指标数据map
  335. edbCodeDataMap := make(map[string]map[string]string)
  336. {
  337. // 获取指标信息
  338. manualIndexList, tmpErr := models.GetEdbinfoListBySecNameList(indexNameList)
  339. if tmpErr != nil {
  340. err = tmpErr
  341. errMsg = "获取指标信息失败"
  342. return
  343. }
  344. tradeCodeList := make([]string, 0)
  345. for _, v := range manualIndexList {
  346. targetMap[v.SecName] = v
  347. tradeCodeList = append(tradeCodeList, v.TradeCode)
  348. recordMap[v.TradeCode] = "更新数据"
  349. }
  350. // 获取明细数据
  351. dataList, tmpErr := models.GetTargetsDataListByCodeList(tradeCodeList)
  352. if tmpErr != nil {
  353. err = tmpErr
  354. errMsg = "获取指标明细数据失败"
  355. return
  356. }
  357. for _, tmpData := range dataList {
  358. _, ok := edbCodeDataMap[tmpData.TradeCode]
  359. if !ok {
  360. edbCodeDataMap[tmpData.TradeCode] = make(map[string]string)
  361. }
  362. edbCodeDataMap[tmpData.TradeCode][tmpData.Dt] = tmpData.Close
  363. }
  364. }
  365. //// TODO 成功数量超过20个指标,那就不导入了
  366. //if len(targetMap) >= 150 {
  367. // failItem := new(models.EdbdataImportFail)
  368. // failItem.SysUserId = strconv.Itoa(sysUser.AdminId)
  369. // failItem.ClassifyName = classifyName
  370. // failItem.CreateDate = createDate
  371. // failItem.SecName = secName
  372. // failItem.Close = closeVal
  373. // failItem.Remark = "导入指标数量过多"
  374. // failItem.Frequency = frequency
  375. // failItem.Unit = unit
  376. // failDataList = append(failDataList, failItem)
  377. // //go utils.SendEmail(utils.APPNAME+"失败提醒", "导入数据 获取分类:Err:"+err.Error(), utils.EmailSendToUsers)
  378. // continue
  379. //}
  380. addDataList := make([]*models.Edbdata, 0)
  381. for _, v := range indexDataListMap {
  382. if len(v.DataMap) <= 0 {
  383. continue
  384. }
  385. var tmpDate, tmpValue string
  386. for date, val := range v.DataMap {
  387. tmpDate = date
  388. tmpValue = val
  389. break
  390. }
  391. // 指标名称是空的,说明是空列
  392. if v.IndexName == `` {
  393. continue
  394. }
  395. if !strings.Contains(strings.Join(classifyNameStrList, ","), v.ClassName) {
  396. failItem := &models.EdbdataImportFail{
  397. ClassifyName: v.ClassName,
  398. CreateDate: tmpDate,
  399. SecName: v.IndexName,
  400. Close: tmpValue,
  401. Remark: "没有该品种分类权限",
  402. SysUserId: fmt.Sprint(sysUser.AdminId),
  403. Frequency: v.Frequency,
  404. Unit: v.Unit,
  405. }
  406. failDataList = append(failDataList, failItem)
  407. continue
  408. }
  409. //获取指标分类信息
  410. classify, ok := edbDataClassifyMap[v.ClassName]
  411. if !ok {
  412. failItem := &models.EdbdataImportFail{
  413. ClassifyName: v.ClassName,
  414. CreateDate: tmpDate,
  415. SecName: v.IndexName,
  416. Close: tmpValue,
  417. Remark: "指标分类不存在",
  418. SysUserId: fmt.Sprint(sysUser.AdminId),
  419. Frequency: v.Frequency,
  420. Unit: v.Unit,
  421. }
  422. failDataList = append(failDataList, failItem)
  423. continue
  424. }
  425. target, ok := targetMap[v.IndexName]
  426. if !ok {
  427. if v.Frequency == "" {
  428. failItem := &models.EdbdataImportFail{
  429. ClassifyName: v.ClassName,
  430. CreateDate: tmpDate,
  431. SecName: v.IndexName,
  432. Close: tmpValue,
  433. Remark: "新增指标失败,频度字段为空",
  434. SysUserId: fmt.Sprint(sysUser.AdminId),
  435. Frequency: v.Frequency,
  436. Unit: v.Unit,
  437. }
  438. failDataList = append(failDataList, failItem)
  439. continue
  440. }
  441. if v.Unit == "" {
  442. failItem := &models.EdbdataImportFail{
  443. ClassifyName: v.ClassName,
  444. CreateDate: tmpDate,
  445. SecName: v.IndexName,
  446. Close: tmpValue,
  447. Remark: "新增指标失败,单位字段为空",
  448. SysUserId: fmt.Sprint(sysUser.AdminId),
  449. Frequency: v.Frequency,
  450. Unit: v.Unit,
  451. }
  452. failDataList = append(failDataList, failItem)
  453. continue
  454. }
  455. tmpErr := AddEdbInfo(v.IndexName, v.Unit, v.Frequency, "", sysUser.Mobile, classify.ClassifyId, sysUser.AdminId, sysUser.RealName)
  456. if tmpErr != nil {
  457. fmt.Println("line 158")
  458. failItem := &models.EdbdataImportFail{
  459. ClassifyName: v.ClassName,
  460. CreateDate: tmpDate,
  461. SecName: v.IndexName,
  462. Close: tmpValue,
  463. Remark: "新增指标失败",
  464. SysUserId: fmt.Sprint(sysUser.AdminId),
  465. Frequency: v.Frequency,
  466. Unit: v.Unit,
  467. }
  468. failDataList = append(failDataList, failItem)
  469. continue
  470. }
  471. // 新增指标记录数
  472. indexCount++
  473. tmpTarget, tmpErr := models.GetTargetBySecName(v.IndexName)
  474. target = tmpTarget
  475. targetMap[v.IndexName] = target
  476. recordMap[target.TradeCode] = "创建指标"
  477. }
  478. if target == nil {
  479. fmt.Println("指标不存在")
  480. failItem := &models.EdbdataImportFail{
  481. ClassifyName: v.ClassName,
  482. CreateDate: tmpDate,
  483. SecName: v.IndexName,
  484. Close: tmpValue,
  485. Remark: "指标不存在",
  486. SysUserId: fmt.Sprint(sysUser.AdminId),
  487. Frequency: v.Frequency,
  488. Unit: v.Unit,
  489. }
  490. failDataList = append(failDataList, failItem)
  491. continue
  492. }
  493. //设置10分钟缓存,不允许其他地方删除
  494. key := "import:edbinfo:data:" + target.TradeCode
  495. utils.Rc.SetNX(key, 1, time.Second*600)
  496. //更新指标信息
  497. {
  498. if v.Frequency == "" {
  499. failItem := &models.EdbdataImportFail{
  500. ClassifyName: v.ClassName,
  501. CreateDate: tmpDate,
  502. SecName: v.IndexName,
  503. Close: tmpValue,
  504. Remark: "更新指标失败,频度字段为空",
  505. SysUserId: fmt.Sprint(sysUser.AdminId),
  506. Frequency: v.Frequency,
  507. Unit: v.Unit,
  508. }
  509. failDataList = append(failDataList, failItem)
  510. continue
  511. }
  512. if v.Unit == "" {
  513. failItem := &models.EdbdataImportFail{
  514. ClassifyName: v.ClassName,
  515. CreateDate: tmpDate,
  516. SecName: v.IndexName,
  517. Close: tmpValue,
  518. Remark: "更新指标失败,单位字段为空",
  519. SysUserId: fmt.Sprint(sysUser.AdminId),
  520. Frequency: v.Frequency,
  521. Unit: v.Unit,
  522. }
  523. failDataList = append(failDataList, failItem)
  524. continue
  525. }
  526. updateCols := make([]string, 0)
  527. //更新指标分类
  528. if target.ClassifyId <= 0 && classify.ClassifyId > 0 {
  529. target.ClassifyId = classify.ClassifyId
  530. updateCols = append(updateCols, "ClassifyId")
  531. }
  532. if target.Frequency != v.Frequency {
  533. target.Frequency = v.Frequency
  534. target.NoticeTime = ""
  535. updateCols = append(updateCols, "Frequency", "NoticeTime")
  536. }
  537. if target.Unit != v.Unit {
  538. target.Unit = v.Unit
  539. updateCols = append(updateCols, "Unit")
  540. }
  541. if len(updateCols) > 0 {
  542. _ = target.Update(updateCols)
  543. }
  544. }
  545. {
  546. // 判断指标数据列表是否已经存在
  547. tmpDataMap, ok := edbCodeDataMap[target.TradeCode]
  548. if !ok {
  549. tmpDataMap = make(map[string]string)
  550. edbCodeDataMap[target.TradeCode] = tmpDataMap
  551. }
  552. for createDate, closeVal := range v.DataMap {
  553. //判断数据是否已经存在
  554. tmpVal, ok := tmpDataMap[createDate]
  555. //数据已存在,进行更新操作
  556. if ok {
  557. if tmpVal != closeVal {
  558. edbCodeDataMap[target.TradeCode][createDate] = closeVal
  559. tmpErr := models.ModifyTargetsDataByImport(target.TradeCode, createDate, closeVal)
  560. if tmpErr != nil {
  561. errMsgList = append(errMsgList, fmt.Sprintf("%s修改数据失败,日期:%s,值:%v,Err:%s", target.TradeCode, createDate, closeVal, tmpErr.Error()))
  562. }
  563. }
  564. } else { //数据不存在,进行新增操作
  565. if target.TradeCode != "" && createDate != "" && closeVal != "" {
  566. addDataList = append(addDataList, &models.Edbdata{
  567. TradeCode: target.TradeCode,
  568. Dt: createDate,
  569. Close: closeVal,
  570. ModifyTime: time.Now(),
  571. })
  572. edbCodeDataMap[target.TradeCode][createDate] = closeVal
  573. }
  574. }
  575. successCount++
  576. }
  577. }
  578. }
  579. // 批量添加明细数据
  580. if len(addDataList) > 0 {
  581. tmpErr := models.OnlyMultiAddEdbdata(addDataList)
  582. if tmpErr != nil {
  583. fmt.Println("line 221")
  584. errMsgList = append(errMsgList, fmt.Sprintf("批量添加明细数据失败,Err:%s", tmpErr.Error()))
  585. }
  586. }
  587. // 失败数量
  588. failCount = len(failDataList)
  589. //fmt.Println("failDataList:", len(failDataList))
  590. if failCount > 0 {
  591. //先删除导入失败记录
  592. _ = models.DelEdbDataImportFail(sysUser.AdminId)
  593. // 批量添加导入失败记录
  594. err = models.MultiAddEdbdataImportFail(failDataList)
  595. if err != nil {
  596. go alarm_msg.SendAlarmMsg("导入数据 新增失败记录失败,Err:"+err.Error(), 3)
  597. //go utils.SendEmail(utils.APPNAME+"失败提醒", "导入数据 新增失败记录失败:Err:"+err.Error(), utils.EmailSendToUsers)
  598. }
  599. {
  600. //错误信息字符串切片,最后作为发送邮件通知使用
  601. failContents := make([]string, 0)
  602. for _, v := range failDataList {
  603. failContents = append(failContents, fmt.Sprint(v.SecName, "导入失败:", v.Remark))
  604. }
  605. utils.FileLog.Info("导入数据 存在部分数据导入失败:" + strings.Join(failContents, ";"))
  606. //导入失败的话,最后统一邮件提醒就好啦,不需要每次都去提醒
  607. go alarm_msg.SendAlarmMsg("导入数据 存在部分数据导入失败:"+strings.Join(failContents, ";"), 3)
  608. }
  609. }
  610. return
  611. }
  612. // ImportManualIndexData
  613. // @Description: excel模板后的内容
  614. type ImportManualIndexData struct {
  615. IndexName string `description:"指标名称"`
  616. Unit string `description:"单位"`
  617. ClassName string `description:"所属品种"`
  618. Frequency string `description:"频度"`
  619. DataMap map[string]string `description:"时间数据"`
  620. }
  621. // getDataByTemplate1
  622. // @Description: 根据模板1获取数据
  623. // @author: Roc
  624. // @datetime 2024-07-24 16:17:45
  625. // @param sheet *xlsx.Sheet
  626. // @return indexDataList []ImportManualIndexData
  627. // @return err error
  628. // @return errMsg string
  629. func getDataByTemplate1(sheet *xlsx.Sheet, sysUserId int) (indexDataList []ImportManualIndexData, failDataList []*models.EdbdataImportFail, err error, errMsg string) {
  630. fmt.Println("sheet name: ", sheet.Name)
  631. indexDataList = make([]ImportManualIndexData, 0)
  632. indexDataListMap := make(map[string]ImportManualIndexData, 0)
  633. failDataList = make([]*models.EdbdataImportFail, 0)
  634. //遍历行读取
  635. maxRow := sheet.MaxRow
  636. fmt.Println("maxRow:", maxRow)
  637. // 表头信息
  638. if maxRow <= 2 {
  639. errMsg = "模板异常1"
  640. err = errors.New(errMsg)
  641. return
  642. }
  643. // 表头校验
  644. {
  645. headerRow := sheet.Row(1)
  646. cells := headerRow.Cells
  647. if len(cells) < 6 {
  648. errMsg = "导入文件异常,请下载最新导入模板文件"
  649. err = errors.New(errMsg)
  650. return
  651. }
  652. templateFail := false
  653. if cells[0].Value != "品种/Variety" {
  654. templateFail = true
  655. }
  656. if cells[1].Value != "指标名称/Indicator Name" {
  657. templateFail = true
  658. }
  659. if cells[2].Value != "指标日期/Indicator Date" {
  660. templateFail = true
  661. }
  662. if cells[3].Value != "值/Value" {
  663. templateFail = true
  664. }
  665. if cells[4].Value != "频度/Frequency" {
  666. templateFail = true
  667. }
  668. if cells[5].Value != "单位/Unit" {
  669. templateFail = true
  670. }
  671. if templateFail {
  672. errMsg = "导入文件异常,请下载最新导入模板文件"
  673. err = errors.New(errMsg)
  674. return
  675. }
  676. }
  677. for i := 2; i < maxRow; i++ {
  678. row := sheet.Row(i)
  679. cells := row.Cells
  680. lenCell := len(cells)
  681. // 过滤空白行
  682. if lenCell <= 0 {
  683. continue
  684. }
  685. if lenCell < 6 {
  686. if cells[0].Value == `` {
  687. continue
  688. }
  689. errMsg = "导入文件异常,请下载最新导入模板文件"
  690. err = errors.New(errMsg)
  691. return
  692. }
  693. classifyName := strings.TrimSpace(cells[0].Value) //分类
  694. if classifyName == "" { //过滤空白行
  695. continue
  696. }
  697. // 指标名称
  698. cell1 := cells[1].Value
  699. indexName := strings.TrimSpace(cell1)
  700. if indexName == "" { //过滤空白行
  701. continue
  702. }
  703. //createDate := utils.ConvertToFormatDay(cell1) //录入日期
  704. createDate := cells[2].Value //指标日期
  705. frequency := strings.TrimSpace(cells[4].String()) //频度
  706. unit := strings.TrimSpace(cells[5].String()) //单位
  707. closeVal := cells[3].Value //值
  708. if strings.Contains(closeVal, "#N/A") {
  709. continue
  710. }
  711. currDate, tmpErr := getExcelDate(createDate)
  712. if tmpErr != nil {
  713. failDataList = append(failDataList, &models.EdbdataImportFail{
  714. //Id: 0,
  715. ClassifyName: classifyName,
  716. CreateDate: createDate,
  717. SecName: indexName,
  718. Close: closeVal,
  719. Remark: "日期格式异常",
  720. SysUserId: strconv.Itoa(sysUserId),
  721. Frequency: frequency,
  722. Unit: unit,
  723. })
  724. continue
  725. }
  726. closeValFloat, tmpErr := cells[3].Float() //值
  727. if tmpErr != nil {
  728. failDataList = append(failDataList, &models.EdbdataImportFail{
  729. //Id: 0,
  730. ClassifyName: classifyName,
  731. CreateDate: currDate,
  732. SecName: indexName,
  733. Close: cells[3].Value,
  734. Remark: "值类型异常",
  735. SysUserId: strconv.Itoa(sysUserId),
  736. Frequency: frequency,
  737. Unit: unit,
  738. })
  739. continue
  740. }
  741. newDecimal := decimal.NewFromFloat(closeValFloat)
  742. newDecimal.Round(4)
  743. closeVal = newDecimal.String()
  744. if strings.Contains(closeVal, "#N/A") {
  745. continue
  746. }
  747. _, ok := indexDataListMap[indexName]
  748. if !ok {
  749. indexDataListMap[indexName] = ImportManualIndexData{
  750. IndexName: indexName,
  751. Unit: unit,
  752. ClassName: classifyName,
  753. Frequency: frequency,
  754. DataMap: make(map[string]string),
  755. }
  756. }
  757. indexDataListMap[indexName].DataMap[currDate] = closeVal
  758. }
  759. for _, v := range indexDataListMap {
  760. indexDataList = append(indexDataList, v)
  761. }
  762. return
  763. }
  764. // getDataByTemplate2
  765. // @Description: 根据模板2获取数据
  766. // @author: Roc
  767. // @datetime 2024-07-24 16:17:56
  768. // @param sheet *xlsx.Sheet
  769. // @return indexDataList []ImportManualIndexData
  770. // @return err error
  771. // @return errMsg string
  772. func getDataByTemplate2(sheet *xlsx.Sheet, sysUserId int) (indexDataList []ImportManualIndexData, failDataList []*models.EdbdataImportFail, err error, errMsg string) {
  773. //fmt.Println("sheet name: ", sheet.Name)
  774. indexDataList = make([]ImportManualIndexData, 0)
  775. failDataList = make([]*models.EdbdataImportFail, 0)
  776. //遍历行读取
  777. maxRow := sheet.MaxRow
  778. //fmt.Println("maxRow:", maxRow)
  779. varietyList := make([]string, 0)
  780. indexNameList := make([]string, 0)
  781. unitList := make([]string, 0)
  782. frequencyList := make([]string, 0)
  783. // make(map[指标下标]map[日期]值)
  784. indexDateValueMap := make(map[int]map[string]string)
  785. // 表头信息
  786. if maxRow <= 4 {
  787. errMsg = "模板异常1"
  788. err = errors.New(errMsg)
  789. return
  790. }
  791. // 表头处理
  792. for i := 1; i <= 4; i++ {
  793. row := sheet.Row(i)
  794. cells := row.Cells
  795. //if len(cells) < 1 {
  796. // errMsg = "模板异常2"
  797. // err = errors.New(errMsg)
  798. // return
  799. //}
  800. switch i {
  801. case 1:
  802. for k, v := range cells {
  803. if k == 0 {
  804. continue
  805. }
  806. varietyList = append(varietyList, strings.TrimSpace(v.String()))
  807. }
  808. case 2:
  809. for k, v := range cells {
  810. if k == 0 {
  811. continue
  812. }
  813. indexNameList = append(indexNameList, strings.TrimSpace(v.String()))
  814. }
  815. case 3:
  816. for k, v := range cells {
  817. if k == 0 {
  818. continue
  819. }
  820. unitList = append(unitList, strings.TrimSpace(v.String()))
  821. }
  822. case 4:
  823. for k, v := range cells {
  824. if k == 0 {
  825. continue
  826. }
  827. frequencyList = append(frequencyList, strings.TrimSpace(v.String()))
  828. }
  829. }
  830. }
  831. maxNameIndex := len(indexNameList) - 1
  832. maxUnitIndex := len(unitList) - 1
  833. maxClassNameIndex := len(varietyList) - 1
  834. maxFrequencyIndex := len(frequencyList) - 1
  835. // 数据处理
  836. for i := 5; i < maxRow; i++ {
  837. row := sheet.Row(i)
  838. cells := row.Cells
  839. //if len(cells) < 1 {
  840. // errMsg = "模板异常2"
  841. // err = errors.New(errMsg)
  842. // return
  843. //}
  844. // 当前日期
  845. var currDate string
  846. // 日期是否异常,异常的话,就跳过,进入下一行数据处理
  847. var dateErr bool
  848. var emptyDate bool
  849. // 数据处理
  850. for k, v := range cells {
  851. if k == 0 {
  852. // 空日期数据
  853. if v.Value == `` {
  854. emptyDate = true
  855. continue
  856. }
  857. tmpCurrDate, tmpErr := getExcelDate(v.Value)
  858. if tmpErr != nil {
  859. dateErr = true
  860. }
  861. currDate = tmpCurrDate
  862. continue
  863. }
  864. key := k - 1
  865. // 空日期数据,那就不处理了,不记录该行错误信息
  866. if emptyDate {
  867. continue
  868. }
  869. // 日期异常,所以不处理该行了同时记录该行错误信息
  870. if dateErr {
  871. var indexName, unit, classifyName, frequency string
  872. if key <= maxNameIndex {
  873. indexName = indexNameList[key]
  874. }
  875. if key <= maxUnitIndex {
  876. unit = unitList[key]
  877. }
  878. if key <= maxClassNameIndex {
  879. classifyName = varietyList[key]
  880. }
  881. if key <= maxFrequencyIndex {
  882. frequency = frequencyList[key]
  883. }
  884. failDataList = append(failDataList, &models.EdbdataImportFail{
  885. //Id: 0,
  886. ClassifyName: classifyName,
  887. CreateDate: currDate,
  888. SecName: indexName,
  889. Close: v.Value,
  890. Remark: "日期格式异常",
  891. SysUserId: strconv.Itoa(sysUserId),
  892. Frequency: frequency,
  893. Unit: unit,
  894. })
  895. continue
  896. }
  897. _, ok := indexDateValueMap[key]
  898. if !ok {
  899. indexDateValueMap[key] = make(map[string]string)
  900. }
  901. closeVal := v.Value //值
  902. // 没有数据,说明是空串
  903. if strings.Contains(closeVal, "#N/A") {
  904. indexDateValueMap[key][currDate] = ""
  905. continue
  906. }
  907. closeValFloat, tmpErr := v.Float() //值
  908. if tmpErr != nil {
  909. // TODO 错误数据记录
  910. //failItem := new(models.EdbdataImportFail)
  911. //failItem.SysUserId = strconv.Itoa(sysUser.AdminId)
  912. //failItem.ClassifyName = classifyName
  913. //failItem.CreateDate = createDate
  914. //failItem.SecName = secName
  915. //failItem.Close = cells[3].Value
  916. //failItem.Remark = "值类型异常"
  917. //failItem.Frequency = frequency
  918. //failItem.Unit = unit
  919. //failDataList = append(failDataList, failItem)
  920. indexDateValueMap[key][currDate] = ""
  921. continue
  922. }
  923. newDecimal := decimal.NewFromFloat(closeValFloat)
  924. newDecimal.Round(4)
  925. closeVal = newDecimal.String()
  926. if strings.Contains(closeVal, "#N/A") {
  927. indexDateValueMap[key][currDate] = ""
  928. continue
  929. }
  930. indexDateValueMap[key][currDate] = closeVal
  931. }
  932. }
  933. for i, indexName := range indexNameList {
  934. var unit, classifyName, frequency string
  935. if i <= maxUnitIndex {
  936. unit = unitList[i]
  937. }
  938. if i <= maxClassNameIndex {
  939. classifyName = varietyList[i]
  940. }
  941. if i <= maxFrequencyIndex {
  942. frequency = frequencyList[i]
  943. }
  944. indexData := ImportManualIndexData{
  945. IndexName: indexName,
  946. Unit: unit,
  947. ClassName: classifyName,
  948. Frequency: frequency,
  949. DataMap: indexDateValueMap[i],
  950. }
  951. indexDataList = append(indexDataList, indexData)
  952. }
  953. return
  954. }
  955. // getExcelDate
  956. // @Description: 获取excel的日期
  957. // @author: Roc
  958. // @datetime 2024-07-23 17:26:12
  959. // @param createDate string
  960. // @return newCreateDate string
  961. // @return err error
  962. func getExcelDate(createDate string) (newCreateDate string, err error) {
  963. if strings.Contains(createDate, "-") {
  964. //如果是带有 - 的普通日期格式文本
  965. _, err = time.Parse("2006-1-2", createDate)
  966. if err == nil {
  967. newCreateDate = createDate
  968. }
  969. } else if strings.Contains(createDate, "/") {
  970. //如果是带有 / 的普通日期格式文本
  971. createDateTime, timeErr := time.Parse("2006/1/2", createDate)
  972. if timeErr != nil {
  973. err = timeErr
  974. } else {
  975. newCreateDate = createDateTime.Format("2006-01-02")
  976. }
  977. } else {
  978. //可能是excel的日期格式
  979. _, tmpErr := strconv.Atoi(createDate)
  980. if tmpErr != nil {
  981. err = tmpErr
  982. } else {
  983. newCreateDate = utils.ConvertToFormatDay(createDate) //录入日期
  984. }
  985. }
  986. return
  987. }
  988. // ModifyManualEdbMaxMinDate
  989. // @Description: 修改手动录入的edb数据的最大最小日期
  990. // @author: Roc
  991. // @datetime 2024-08-01 15:34:31
  992. // @param tradeCode string
  993. func ModifyManualEdbMaxMinDate(tradeCode string) {
  994. // 获取最大最小日期
  995. item, err := models.GetEdbdataMaxMinDate(tradeCode)
  996. if err != nil {
  997. return
  998. }
  999. // 最新值
  1000. latestValue, err := models.GetEdbdataLatestValue(tradeCode)
  1001. if err != nil {
  1002. return
  1003. }
  1004. // 修改指标的最大最小日期和最新值
  1005. err = models.ModifyEdbinfoMaxMinDate(tradeCode, item.MinDate, item.MaxDate, latestValue)
  1006. return
  1007. }
  1008. // GetUserManualClassifyIdList
  1009. // @Description: 获取用户手动录入的分类id列表
  1010. // @author: Roc
  1011. // @datetime 2024-08-02 15:09:11
  1012. // @param userId int
  1013. // @return classifyIdList []int
  1014. // @return err error
  1015. func GetUserManualClassifyIdList(userId int) (classifyIdList []int, err error) {
  1016. classifyIdList = make([]int, 0)
  1017. // 获取有用权限的分类
  1018. classifyList, err := models.GetEdbdataClassify(int64(userId))
  1019. if err != nil {
  1020. return
  1021. }
  1022. if len(classifyList) > 0 {
  1023. for _, v := range classifyList {
  1024. classifyIdList = append(classifyIdList, v.ClassifyId)
  1025. if v.Child != nil && len(v.Child) > 0 {
  1026. for _, v2 := range v.Child {
  1027. classifyIdList = append(classifyIdList, v2.ClassifyId)
  1028. }
  1029. }
  1030. }
  1031. }
  1032. return
  1033. }