siteInfoManageRepo.go 15 KB

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