siteInfoManageRepo.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package mongo
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "fwh-toolbox-server/database"
  7. "fwh-toolbox-server/domain"
  8. "fwh-toolbox-server/dto"
  9. "time"
  10. "go.mongodb.org/mongo-driver/bson"
  11. "go.mongodb.org/mongo-driver/bson/primitive"
  12. "go.mongodb.org/mongo-driver/mongo"
  13. "go.mongodb.org/mongo-driver/mongo/options"
  14. "go.uber.org/zap"
  15. )
  16. const (
  17. CollectionName_SiteInfoManageRecord = "SiteInfoManageRecord"
  18. CollectionName_SiteInfoManageData = "SiteInfoManageData"
  19. CollectionName_SiteInfoTags = "SiteInfoTags"
  20. )
  21. // 更新站点信息获取结果
  22. func CreateSiteInfoUpdateInfo() (*primitive.ObjectID, error) {
  23. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  24. defer cancel()
  25. collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
  26. result, err := collection.InsertOne(ctx, domain.SiteInfoUpdateRecord{
  27. Progress: domain.ProgressPending,
  28. CreateTime: time.Now(),
  29. UpdateTime: time.Now(),
  30. Total: 0,
  31. })
  32. if err != nil {
  33. return nil, err
  34. }
  35. id := result.InsertedID.(primitive.ObjectID)
  36. return &id, nil
  37. }
  38. // 更新站点信息获取结果
  39. func UpdateSiteInfoUpdateResult(id primitive.ObjectID, progress domain.Progress, total uint64) error {
  40. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  41. defer cancel()
  42. collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
  43. filter := bson.M{"_id": id}
  44. var update map[string]interface{}
  45. if progress == domain.ProgressComplete {
  46. update = bson.M{
  47. "$set": bson.M{
  48. "progress": progress,
  49. "updateTime": time.Now(),
  50. "total": total,
  51. },
  52. }
  53. } else {
  54. update = bson.M{
  55. "$set": bson.M{
  56. "progress": progress,
  57. },
  58. }
  59. }
  60. _, err := collection.UpdateOne(ctx, filter, update)
  61. if err != nil {
  62. return err
  63. }
  64. return nil
  65. }
  66. // 获取最新站点信息记录数据
  67. func GetSiteInfoUpdateNewRecord() (*domain.SiteInfoUpdateRecord, error) {
  68. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  69. defer cancel()
  70. collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
  71. opts := options.FindOne().SetSort(bson.D{{Key: "_id", Value: -1}})
  72. var result domain.SiteInfoUpdateRecord
  73. err := collection.FindOne(ctx, bson.M{}, opts).Decode(&result)
  74. if err != nil {
  75. if errors.Is(err, mongo.ErrNoDocuments) {
  76. return nil, nil // 没有数据返回空指针
  77. }
  78. return nil, err
  79. }
  80. return &result, nil
  81. }
  82. // 获取最近一次成功完成的站点信息更新记录;没有时返回 nil
  83. func GetSiteInfoUpdateLastComplete() (*domain.SiteInfoUpdateRecord, error) {
  84. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  85. defer cancel()
  86. collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
  87. opts := options.FindOne().SetSort(bson.D{{Key: "_id", Value: -1}})
  88. var result domain.SiteInfoUpdateRecord
  89. err := collection.FindOne(ctx, bson.M{"progress": domain.ProgressComplete}, opts).Decode(&result)
  90. if err != nil {
  91. if errors.Is(err, mongo.ErrNoDocuments) {
  92. return nil, nil
  93. }
  94. return nil, err
  95. }
  96. return &result, nil
  97. }
  98. // 从数据库获取站点信息列表
  99. func GetSiteInfoManageList(page, size uint, filter *domain.SiteInfoFilter, search string) (*dto.ResPage[domain.SiteInfoDomain], error) {
  100. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  101. defer cancel()
  102. collection := database.GetCollection(CollectionName_SiteInfoManageData)
  103. mainFilter := bson.M{}
  104. // 条件
  105. if filter != nil {
  106. subFilterConfig := bson.M{}
  107. mainFilterSet := []bson.M{}
  108. for _, subFilter := range filter.SubFilter {
  109. subFilterSet := []bson.M{}
  110. filterConfigItem := bson.M{}
  111. for _, filterItem := range subFilter.Config {
  112. switch filterItem.Type {
  113. case domain.FilterEqualInt:
  114. // 等于指定值(整数)
  115. if filterItem.Para1.Int != nil {
  116. filterConfigItem[filterItem.Key] = bson.M{"$eq": *filterItem.Para1.Int}
  117. }
  118. case domain.FilterEqualFloat:
  119. // 等于指定值(浮点数)
  120. if filterItem.Para1.Float != nil {
  121. filterConfigItem[filterItem.Key] = bson.M{"$eq": *filterItem.Para1.Float}
  122. }
  123. case domain.FilterEqualString:
  124. // 等于指定字符串
  125. filterConfigItem[filterItem.Key] = bson.M{"$eq": *filterItem.Para1.String}
  126. case domain.FilterIncludeString:
  127. // 包含指定字符串
  128. filterConfigItem[filterItem.Key] = bson.M{"$regex": *filterItem.Para1.String, "$options": "i"} // 选项 $options:大小写不敏感 (i)
  129. case domain.FilterRangeInt:
  130. // 数值范围检索(整数)
  131. if filterItem.Para2 != nil {
  132. if filterItem.Para1.Int != nil && filterItem.Para2 != nil && filterItem.Para2.Int != nil {
  133. filterConfigItem[filterItem.Key] = bson.M{"$gte": *filterItem.Para1.Int, "$lte": *filterItem.Para2.Int}
  134. }
  135. }
  136. case domain.FilterRangeFloat:
  137. // 数值范围检索(浮点数)
  138. if filterItem.Para2 != nil {
  139. if filterItem.Para1.Float != nil && filterItem.Para2 != nil && filterItem.Para2.Float != nil {
  140. filterConfigItem[filterItem.Key] = bson.M{"$gte": *filterItem.Para1.Float, "$lte": *filterItem.Para2.Float}
  141. }
  142. }
  143. case domain.FilterRangeTime:
  144. // 数值范围检索(时间)
  145. if filterItem.Para1.String != nil && filterItem.Para2 != nil && filterItem.Para2.String != nil {
  146. // start, e1 := time.Parse(time.DateTime, *filterItem.Para1.String)
  147. // end, e2 := time.Parse(time.DateTime, *filterItem.Para2.String)
  148. // if e1 == nil && e2 == nil {
  149. // filterConfigItem[filterItem.Key] = bson.M{"$gte": start, "$lte": end}
  150. // }
  151. start := *filterItem.Para1.String
  152. end := *filterItem.Para2.String
  153. filterConfigItem[filterItem.Key] = bson.M{"$gte": start, "$lte": end}
  154. }
  155. case domain.FilterExists:
  156. // 判断字段是否存在或不为空
  157. // filterConfigItem[filterItem.Key] = bson.M{"$exists": true}
  158. value := *filterItem.Para1.String
  159. switch value {
  160. case "yes":
  161. filterConfigItem[filterItem.Key] = bson.M{"$exists": true, "$ne": nil}
  162. case "no":
  163. filterConfigItem["$or"] = bson.M{
  164. filterItem.Key: bson.M{"$exists": false},
  165. filterItem.Key: bson.M{"$eq": nil},
  166. }
  167. }
  168. }
  169. subFilterSet = append(subFilterSet, filterConfigItem)
  170. }
  171. if len(subFilterSet) > 0 {
  172. switch subFilter.Logic {
  173. case "and":
  174. subFilterConfig["$and"] = subFilterSet
  175. case "or":
  176. subFilterConfig["$or"] = subFilterSet
  177. }
  178. }
  179. mainFilterSet = append(mainFilterSet, subFilterConfig)
  180. }
  181. if len(mainFilterSet) > 0 {
  182. switch filter.Logic {
  183. case "and":
  184. mainFilter["$and"] = mainFilterSet
  185. case "or":
  186. mainFilter["$or"] = mainFilterSet
  187. }
  188. }
  189. }
  190. dbFilter := bson.M{}
  191. if len(search) > 0 {
  192. dbFilter["$and"] = []bson.M{
  193. mainFilter,
  194. {
  195. "$or": []bson.M{
  196. {"_id": bson.M{"$regex": search, "$options": "i"}}, // 选项 $options:大小写不敏感 (i)
  197. {"name": bson.M{"$regex": search, "$options": "i"}},
  198. {"distributorName": bson.M{"$regex": search, "$options": "i"}},
  199. {"installerName": bson.M{"$regex": search, "$options": "i"}},
  200. {"maintName": bson.M{"$regex": search, "$options": "i"}},
  201. {"accountName": bson.M{"$regex": search, "$options": "i"}},
  202. {"iccId": bson.M{"$regex": search, "$options": "i"}},
  203. {"imei": bson.M{"$regex": search, "$options": "i"}},
  204. {"fhpSn": bson.M{"$regex": search, "$options": "i"}},
  205. {"version": bson.M{"$regex": search, "$options": "i"}},
  206. {"protocolVer": bson.M{"$regex": search, "$options": "i"}},
  207. {"realSysHdVersion": bson.M{"$regex": search, "$options": "i"}},
  208. {"financierName": bson.M{"$regex": search, "$options": "i"}},
  209. {"remark": bson.M{"$regex": search, "$options": "i"}},
  210. {"country": bson.M{"$regex": search, "$options": "i"}},
  211. {"province": bson.M{"$regex": search, "$options": "i"}},
  212. {"city": bson.M{"$regex": search, "$options": "i"}},
  213. {"site": bson.M{"$regex": search, "$options": "i"}},
  214. {"jobCode": bson.M{"$regex": search, "$options": "i"}},
  215. },
  216. },
  217. }
  218. } else {
  219. dbFilter = mainFilter
  220. }
  221. var findOptions *options.FindOptions
  222. findOptions = options.Find().
  223. SetSkip(int64((page - 1) * size)).
  224. SetLimit(int64(size))
  225. cursor, err := collection.Find(ctx, dbFilter, findOptions)
  226. if err != nil {
  227. return nil, err
  228. }
  229. defer cursor.Close(ctx)
  230. var infoList []domain.SiteInfoDomain
  231. for cursor.Next(ctx) {
  232. var info domain.SiteInfoDomain
  233. if err := cursor.Decode(&info); err != nil {
  234. return nil, err
  235. }
  236. infoList = append(infoList, info)
  237. }
  238. // 查询总数
  239. total, err := collection.CountDocuments(ctx, dbFilter)
  240. if err != nil {
  241. return nil, err
  242. }
  243. res := dto.ResPage[domain.SiteInfoDomain]{
  244. Data: infoList,
  245. PageSize: size,
  246. PageNum: page,
  247. Total: uint(total),
  248. }
  249. return &res, nil
  250. }
  251. // 从数据库获取站点信息列表(基于GICCID)
  252. func GetSiteInfoManageListFromGiccid(giccid string) ([]domain.SiteInfoDomain, error) {
  253. // 判断GICCID的有效性
  254. if len(giccid) != 19 {
  255. return nil, fmt.Errorf("giccid len is %s, not 19", giccid)
  256. }
  257. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  258. defer cancel()
  259. collection := database.GetCollection(CollectionName_SiteInfoManageData)
  260. // 条件
  261. filter := bson.M{
  262. "iccId": bson.M{
  263. "$regex": giccid, "$options": "i"},
  264. }
  265. cursor, err := collection.Find(ctx, filter, options.Find())
  266. if err != nil {
  267. return nil, err
  268. }
  269. defer cursor.Close(ctx)
  270. var infoList []domain.SiteInfoDomain
  271. for cursor.Next(ctx) {
  272. var info domain.SiteInfoDomain
  273. if err := cursor.Decode(&info); err != nil {
  274. return nil, err
  275. }
  276. infoList = append(infoList, info)
  277. }
  278. return infoList, nil
  279. }
  280. // 插入站点信息数据
  281. func InsertSiteInfoData(data domain.SiteInfoDomain) error {
  282. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  283. defer cancel()
  284. collection := database.GetCollection(CollectionName_SiteInfoManageData)
  285. filter := bson.M{"_id": data.Sn} // 按ID匹配
  286. opts := options.Replace().SetUpsert(true)
  287. _, err := collection.ReplaceOne(ctx, filter, data, opts)
  288. if err != nil {
  289. return err
  290. }
  291. return nil
  292. }
  293. // 查询站点信息标签列表
  294. func GetSiteInfoTags(page, size uint, search string) (*dto.ResPage[domain.SiteTagDomain], error) {
  295. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  296. defer cancel()
  297. collection := database.GetCollection(CollectionName_SiteInfoTags)
  298. // 查询条件
  299. filter := bson.M{}
  300. if search != "" {
  301. filter["name"] = bson.M{
  302. "$regex": primitive.Regex{
  303. Pattern: search,
  304. Options: "i", // 忽略大小写
  305. },
  306. }
  307. }
  308. // 总数
  309. total, err := collection.CountDocuments(ctx, filter)
  310. if err != nil {
  311. return nil, err
  312. }
  313. // 查询选项
  314. opts := options.Find().
  315. SetSkip(int64((page - 1) * size)).
  316. SetLimit(int64(size)).
  317. SetSort(bson.D{
  318. {Key: "name", Value: 1}, // 按名称升序
  319. })
  320. cursor, err := collection.Find(ctx, filter, opts)
  321. if err != nil {
  322. return nil, err
  323. }
  324. defer cursor.Close(ctx)
  325. list := make([]domain.SiteTagDomain, 0)
  326. if err := cursor.All(ctx, &list); err != nil {
  327. return nil, err
  328. }
  329. return &dto.ResPage[domain.SiteTagDomain]{
  330. Data: list,
  331. PageSize: size,
  332. PageNum: page,
  333. Total: uint(total),
  334. }, nil
  335. }
  336. // 查询站点信息标签列表(根据id列表)
  337. func GetSiteInfoTagsFromId(idList []string) (map[string]*dto.SiteTagDTO, error) {
  338. tagMap := make(map[string]*dto.SiteTagDTO)
  339. if len(idList) == 0 {
  340. return tagMap, nil
  341. }
  342. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  343. defer cancel()
  344. collection := database.GetCollection(CollectionName_SiteInfoTags)
  345. // 转换为 ObjectID
  346. objectIDs := make([]primitive.ObjectID, 0, len(idList))
  347. for _, id := range idList {
  348. objectID, err := primitive.ObjectIDFromHex(id)
  349. if err != nil {
  350. // 非法 ID
  351. zap.L().Warn("GetSiteInfoTagsFromId illegal ID", zap.String("err", err.Error()), zap.String("id", id))
  352. continue
  353. }
  354. objectIDs = append(objectIDs, objectID)
  355. }
  356. if len(objectIDs) == 0 {
  357. return tagMap, nil
  358. }
  359. filter := bson.M{
  360. "_id": bson.M{
  361. "$in": objectIDs,
  362. },
  363. }
  364. cursor, err := collection.Find(ctx, filter)
  365. if err != nil {
  366. return nil, err
  367. }
  368. defer cursor.Close(ctx)
  369. for cursor.Next(ctx) {
  370. var tag domain.SiteTagDomain
  371. if err := cursor.Decode(&tag); err != nil {
  372. return nil, err
  373. }
  374. tagMap[tag.Id.Hex()] = dto.SiteTagDomainToSiteTagDTO(&tag)
  375. }
  376. if err := cursor.Err(); err != nil {
  377. return nil, err
  378. }
  379. return tagMap, nil
  380. }
  381. // 创建或更新站点信息标签
  382. func UpdateSiteInfoTag(tag domain.SiteTagDomain) error {
  383. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  384. defer cancel()
  385. collection := database.GetCollection(CollectionName_SiteInfoTags)
  386. filter := bson.M{"_id": tag.Id}
  387. update := bson.M{
  388. "$set": bson.M{
  389. "name": tag.Name,
  390. "count": tag.Count,
  391. "color": tag.Color,
  392. "description": tag.Description,
  393. },
  394. }
  395. opts := options.Update().SetUpsert(true)
  396. _, err := collection.UpdateOne(ctx, filter, update, opts)
  397. if err != nil {
  398. return err
  399. }
  400. return nil
  401. }