siteInfoManageRepo.go 13 KB

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