simCardManageRepo.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package mongo
  2. import (
  3. "context"
  4. "fmt"
  5. "fwh-toolbox-server/database"
  6. "fwh-toolbox-server/domain"
  7. "fwh-toolbox-server/dto"
  8. "time"
  9. "go.mongodb.org/mongo-driver/bson"
  10. "go.mongodb.org/mongo-driver/mongo"
  11. "go.mongodb.org/mongo-driver/mongo/options"
  12. "go.uber.org/zap"
  13. )
  14. const (
  15. CollectionName_SimCardManage = "SimCardManage"
  16. CollectionName_SimCardMonthlyData = "SimCardMonthlyData"
  17. )
  18. // 查询SIM卡信息(批量)
  19. func GetSimCardBatchInfo(page, size uint, search string, status *string) (*dto.ResPage[domain.SimCardInfo], error) {
  20. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  21. defer cancel()
  22. collection := database.GetCollection(CollectionName_SimCardManage)
  23. // 查询条件
  24. filter := bson.M{}
  25. // 搜索 _id (GICCID)
  26. if search != "" {
  27. filter["_id"] = bson.M{
  28. "$regex": search,
  29. "$options": "i", // 不区分大小写,可去掉
  30. }
  31. }
  32. // 过滤状态
  33. if status != nil {
  34. filter["status"] = bson.M{
  35. "$eq": *status,
  36. }
  37. }
  38. findOptions := options.Find().
  39. SetSkip(int64((page - 1) * size)).
  40. SetLimit(int64(size)).
  41. SetSort(bson.D{
  42. {Key: "allDataUsage", Value: -1}, // 降序
  43. })
  44. cursor, err := collection.Find(ctx, filter, findOptions)
  45. if err != nil {
  46. return nil, err
  47. }
  48. defer cursor.Close(ctx)
  49. var infoList []domain.SimCardInfo
  50. for cursor.Next(ctx) {
  51. var info domain.SimCardInfo
  52. if err := cursor.Decode(&info); err != nil {
  53. return nil, err
  54. }
  55. infoList = append(infoList, info)
  56. }
  57. // 查询总数
  58. total, err := collection.CountDocuments(ctx, bson.M{})
  59. if err != nil {
  60. return nil, err
  61. }
  62. res := dto.ResPage[domain.SimCardInfo]{
  63. Data: infoList,
  64. PageSize: size,
  65. PageNum: page,
  66. Total: uint(total),
  67. }
  68. return &res, nil
  69. }
  70. // 查询SIM卡信息(单卡)
  71. func GetSimCardInfo(id string) (*domain.SimCardInfo, error) {
  72. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  73. defer cancel()
  74. collection := database.GetCollection(CollectionName_SimCardManage)
  75. var info domain.SimCardInfo
  76. err := collection.FindOne(ctx, bson.M{"_id": id}).Decode(&info)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return &info, nil
  81. }
  82. // 查询SIM卡月数据(单卡)
  83. func GetSimCardMonthlyData(month string, id string) (*domain.SimCardMonthlyData, error) {
  84. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  85. defer cancel()
  86. collection := database.GetCollection(CollectionName_SimCardMonthlyData)
  87. var info domain.SimCardMonthlyData
  88. err := collection.FindOne(ctx, bson.M{"simId": id, "month": month}).Decode(&info)
  89. if err != nil {
  90. return nil, err
  91. }
  92. return &info, nil
  93. }
  94. // 插入SIM卡基本信息数据
  95. func UpdateSimCardInfo(info domain.SimCardInfo) error {
  96. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  97. defer cancel()
  98. collection := database.GetCollection(CollectionName_SimCardManage)
  99. filter := bson.M{"_id": info.GICCID} // 按ID匹配
  100. _, err := collection.ReplaceOne(ctx, filter, info, options.Replace().SetUpsert(true))
  101. if err != nil {
  102. return err
  103. }
  104. return nil
  105. }
  106. // 批量插入SIM卡基本信息数据
  107. func UpdateSimCardBatchInfo(infoList []domain.SimCardInfo) (int64, error) {
  108. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  109. defer cancel()
  110. collection := database.GetCollection(CollectionName_SimCardManage)
  111. batchSize := 1000
  112. var totalInserted int64
  113. for start := 0; start < len(infoList); start += batchSize {
  114. end := start + batchSize
  115. if end > len(infoList) {
  116. end = len(infoList)
  117. }
  118. models := make([]mongo.WriteModel, 0, end-start)
  119. for _, doc := range infoList[start:end] {
  120. model := mongo.NewReplaceOneModel().
  121. SetFilter(bson.M{
  122. "_id": doc.GICCID,
  123. }).
  124. SetReplacement(doc).
  125. SetUpsert(true)
  126. models = append(models, model)
  127. }
  128. result, err := collection.BulkWrite(
  129. ctx,
  130. models,
  131. options.BulkWrite().
  132. SetOrdered(false),
  133. )
  134. if err != nil {
  135. zap.L().Error("UpdateSimCardBatchInfo bulk insert failed.", zap.String("err", err.Error()), zap.Int("start", start), zap.Int("end", end), zap.Int64("totalInserted", totalInserted))
  136. return totalInserted, fmt.Errorf(
  137. "bulk insert failed (%d~%d): %w",
  138. start,
  139. end,
  140. err,
  141. )
  142. }
  143. totalInserted += result.InsertedCount
  144. }
  145. return totalInserted, nil
  146. }
  147. // 插入SIM卡日流量数据
  148. func UpdateSimCardDayData(data domain.SimCardDayData) error {
  149. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  150. defer cancel()
  151. collection := database.GetCollection(CollectionName_SimCardMonthlyData)
  152. dailyUsageField := fmt.Sprintf(
  153. "dailyUsage.%d",
  154. data.Day,
  155. )
  156. update := bson.M{
  157. "$set": bson.M{
  158. "allDataUsage": data.AllDataUsage,
  159. "updateTime": data.UpdateTime,
  160. dailyUsageField: data.DailyUsage,
  161. },
  162. "$setOnInsert": bson.M{
  163. "simId": data.SimId,
  164. "month": data.Month,
  165. },
  166. }
  167. filter := bson.M{"simId": data.SimId, "month": data.Month} // 按ID和month匹配
  168. _, err := collection.UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
  169. if err != nil {
  170. return err
  171. }
  172. return nil
  173. }
  174. // 批量插入SIM卡日流量数据
  175. func UpdateSimCardBatchDayData(dataList []domain.SimCardDayData) (int64, error) {
  176. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  177. defer cancel()
  178. collection := database.GetCollection(CollectionName_SimCardMonthlyData)
  179. batchSize := 1000
  180. var totalInserted int64
  181. for start := 0; start < len(dataList); start += batchSize {
  182. end := start + batchSize
  183. if end > len(dataList) {
  184. end = len(dataList)
  185. }
  186. models := make([]mongo.WriteModel, 0, end-start)
  187. for _, doc := range dataList[start:end] {
  188. dailyUsageField := fmt.Sprintf("dailyUsage.%d", doc.Day)
  189. update := bson.M{
  190. "$set": bson.M{
  191. "allDataUsage": doc.AllDataUsage,
  192. "updateTime": doc.UpdateTime,
  193. dailyUsageField: doc.DailyUsage,
  194. },
  195. "$setOnInsert": bson.M{
  196. "simId": doc.SimId,
  197. "month": doc.Month,
  198. },
  199. }
  200. model := mongo.NewUpdateOneModel().
  201. SetFilter(bson.M{
  202. "simId": doc.SimId,
  203. "month": doc.Month,
  204. }).
  205. SetUpdate(update).
  206. SetUpsert(true)
  207. models = append(models, model)
  208. }
  209. result, err := collection.BulkWrite(
  210. ctx,
  211. models,
  212. options.BulkWrite().
  213. SetOrdered(false),
  214. )
  215. if err != nil {
  216. zap.L().Error("UpdateSimCardBatchMonthlyData bulk insert failed.", zap.String("err", err.Error()), zap.Int("start", start), zap.Int("end", end), zap.Int64("totalInserted", totalInserted))
  217. return totalInserted, fmt.Errorf(
  218. "bulk insert failed (%d~%d): %w",
  219. start,
  220. end,
  221. err,
  222. )
  223. }
  224. totalInserted += result.InsertedCount
  225. }
  226. return totalInserted, nil
  227. }