| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476 |
- package mongo
- import (
- "context"
- "errors"
- "fmt"
- "fwh-toolbox-server/database"
- "fwh-toolbox-server/domain"
- "fwh-toolbox-server/dto"
- "time"
- "go.mongodb.org/mongo-driver/bson"
- "go.mongodb.org/mongo-driver/bson/primitive"
- "go.mongodb.org/mongo-driver/mongo"
- "go.mongodb.org/mongo-driver/mongo/options"
- "go.uber.org/zap"
- )
- const (
- CollectionName_SiteInfoManageRecord = "SiteInfoManageRecord"
- CollectionName_SiteInfoManageData = "SiteInfoManageData"
- CollectionName_SiteInfoTags = "SiteInfoTags"
- )
- // 更新站点信息获取结果
- func CreateSiteInfoUpdateInfo() (*primitive.ObjectID, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
- result, err := collection.InsertOne(ctx, domain.SiteInfoUpdateRecord{
- Progress: domain.ProgressPending,
- CreateTime: time.Now(),
- UpdateTime: time.Now(),
- Total: 0,
- })
- if err != nil {
- return nil, err
- }
- id := result.InsertedID.(primitive.ObjectID)
- return &id, nil
- }
- // 更新站点信息获取结果
- func UpdateSiteInfoUpdateResult(id primitive.ObjectID, progress domain.Progress, total uint64) error {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
- filter := bson.M{"_id": id}
- var update map[string]interface{}
- if progress == domain.ProgressComplete {
- update = bson.M{
- "$set": bson.M{
- "progress": progress,
- "updateTime": time.Now(),
- "total": total,
- },
- }
- } else {
- update = bson.M{
- "$set": bson.M{
- "progress": progress,
- },
- }
- }
- _, err := collection.UpdateOne(ctx, filter, update)
- if err != nil {
- return err
- }
- return nil
- }
- // 获取最新站点信息记录数据
- func GetSiteInfoUpdateNewRecord() (*domain.SiteInfoUpdateRecord, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
- opts := options.FindOne().SetSort(bson.D{{Key: "_id", Value: -1}})
- var result domain.SiteInfoUpdateRecord
- err := collection.FindOne(ctx, bson.M{}, opts).Decode(&result)
- if err != nil {
- if errors.Is(err, mongo.ErrNoDocuments) {
- return nil, nil // 没有数据返回空指针
- }
- return nil, err
- }
- return &result, nil
- }
- // 获取最近一次成功完成的站点信息更新记录;没有时返回 nil
- func GetSiteInfoUpdateLastComplete() (*domain.SiteInfoUpdateRecord, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageRecord)
- opts := options.FindOne().SetSort(bson.D{{Key: "_id", Value: -1}})
- var result domain.SiteInfoUpdateRecord
- err := collection.FindOne(ctx, bson.M{"progress": domain.ProgressComplete}, opts).Decode(&result)
- if err != nil {
- if errors.Is(err, mongo.ErrNoDocuments) {
- return nil, nil
- }
- return nil, err
- }
- return &result, nil
- }
- // 从数据库获取站点信息列表
- func GetSiteInfoManageList(page, size uint, filter *domain.SiteInfoFilter, search string) (*dto.ResPage[domain.SiteInfoDomain], error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageData)
- mainFilter := bson.M{}
- // 条件
- if filter != nil {
- subFilterConfig := bson.M{}
- mainFilterSet := []bson.M{}
- for _, subFilter := range filter.SubFilter {
- subFilterSet := []bson.M{}
- filterConfigItem := bson.M{}
- for _, filterItem := range subFilter.Config {
- switch filterItem.Type {
- case domain.FilterEqualInt:
- // 等于指定值(整数)
- if filterItem.Para1.Int != nil {
- filterConfigItem[filterItem.Key] = bson.M{"$eq": *filterItem.Para1.Int}
- }
- case domain.FilterEqualFloat:
- // 等于指定值(浮点数)
- if filterItem.Para1.Float != nil {
- filterConfigItem[filterItem.Key] = bson.M{"$eq": *filterItem.Para1.Float}
- }
- case domain.FilterEqualString:
- // 等于指定字符串
- filterConfigItem[filterItem.Key] = bson.M{"$eq": *filterItem.Para1.String}
- case domain.FilterIncludeString:
- // 包含指定字符串
- filterConfigItem[filterItem.Key] = bson.M{"$regex": *filterItem.Para1.String, "$options": "i"} // 选项 $options:大小写不敏感 (i)
- case domain.FilterRangeInt:
- // 数值范围检索(整数)
- if filterItem.Para2 != nil {
- if filterItem.Para1.Int != nil && filterItem.Para2 != nil && filterItem.Para2.Int != nil {
- filterConfigItem[filterItem.Key] = bson.M{"$gte": *filterItem.Para1.Int, "$lte": *filterItem.Para2.Int}
- }
- }
- case domain.FilterRangeFloat:
- // 数值范围检索(浮点数)
- if filterItem.Para2 != nil {
- if filterItem.Para1.Float != nil && filterItem.Para2 != nil && filterItem.Para2.Float != nil {
- filterConfigItem[filterItem.Key] = bson.M{"$gte": *filterItem.Para1.Float, "$lte": *filterItem.Para2.Float}
- }
- }
- case domain.FilterRangeTime:
- // 数值范围检索(时间)
- if filterItem.Para1.String != nil && filterItem.Para2 != nil && filterItem.Para2.String != nil {
- // start, e1 := time.Parse(time.DateTime, *filterItem.Para1.String)
- // end, e2 := time.Parse(time.DateTime, *filterItem.Para2.String)
- // if e1 == nil && e2 == nil {
- // filterConfigItem[filterItem.Key] = bson.M{"$gte": start, "$lte": end}
- // }
- start := *filterItem.Para1.String
- end := *filterItem.Para2.String
- filterConfigItem[filterItem.Key] = bson.M{"$gte": start, "$lte": end}
- }
- case domain.FilterExists:
- // 判断字段是否存在或不为空
- // filterConfigItem[filterItem.Key] = bson.M{"$exists": true}
- value := *filterItem.Para1.String
- switch value {
- case "yes":
- filterConfigItem[filterItem.Key] = bson.M{"$exists": true, "$ne": nil}
- case "no":
- filterConfigItem["$or"] = bson.M{
- filterItem.Key: bson.M{"$exists": false},
- filterItem.Key: bson.M{"$eq": nil},
- }
- }
- }
- subFilterSet = append(subFilterSet, filterConfigItem)
- }
- if len(subFilterSet) > 0 {
- switch subFilter.Logic {
- case "and":
- subFilterConfig["$and"] = subFilterSet
- case "or":
- subFilterConfig["$or"] = subFilterSet
- }
- }
- mainFilterSet = append(mainFilterSet, subFilterConfig)
- }
- if len(mainFilterSet) > 0 {
- switch filter.Logic {
- case "and":
- mainFilter["$and"] = mainFilterSet
- case "or":
- mainFilter["$or"] = mainFilterSet
- }
- }
- }
- dbFilter := bson.M{}
- if len(search) > 0 {
- dbFilter["$and"] = []bson.M{
- mainFilter,
- {
- "$or": []bson.M{
- {"_id": bson.M{"$regex": search, "$options": "i"}}, // 选项 $options:大小写不敏感 (i)
- {"name": bson.M{"$regex": search, "$options": "i"}},
- {"distributorName": bson.M{"$regex": search, "$options": "i"}},
- {"installerName": bson.M{"$regex": search, "$options": "i"}},
- {"maintName": bson.M{"$regex": search, "$options": "i"}},
- {"accountName": bson.M{"$regex": search, "$options": "i"}},
- {"iccId": bson.M{"$regex": search, "$options": "i"}},
- {"imei": bson.M{"$regex": search, "$options": "i"}},
- {"fhpSn": bson.M{"$regex": search, "$options": "i"}},
- {"version": bson.M{"$regex": search, "$options": "i"}},
- {"protocolVer": bson.M{"$regex": search, "$options": "i"}},
- {"realSysHdVersion": bson.M{"$regex": search, "$options": "i"}},
- {"financierName": bson.M{"$regex": search, "$options": "i"}},
- {"remark": bson.M{"$regex": search, "$options": "i"}},
- {"country": bson.M{"$regex": search, "$options": "i"}},
- {"province": bson.M{"$regex": search, "$options": "i"}},
- {"city": bson.M{"$regex": search, "$options": "i"}},
- {"site": bson.M{"$regex": search, "$options": "i"}},
- {"jobCode": bson.M{"$regex": search, "$options": "i"}},
- },
- },
- }
- } else {
- dbFilter = mainFilter
- }
- var findOptions *options.FindOptions
- findOptions = options.Find().
- SetSkip(int64((page - 1) * size)).
- SetLimit(int64(size))
- cursor, err := collection.Find(ctx, dbFilter, findOptions)
- if err != nil {
- return nil, err
- }
- defer cursor.Close(ctx)
- var infoList []domain.SiteInfoDomain
- for cursor.Next(ctx) {
- var info domain.SiteInfoDomain
- if err := cursor.Decode(&info); err != nil {
- return nil, err
- }
- infoList = append(infoList, info)
- }
- // 查询总数
- total, err := collection.CountDocuments(ctx, dbFilter)
- if err != nil {
- return nil, err
- }
- res := dto.ResPage[domain.SiteInfoDomain]{
- Data: infoList,
- PageSize: size,
- PageNum: page,
- Total: uint(total),
- }
- return &res, nil
- }
- // 从数据库获取站点信息列表(基于GICCID)
- func GetSiteInfoManageListFromGiccid(giccid string) ([]domain.SiteInfoDomain, error) {
- // 判断GICCID的有效性
- if len(giccid) != 19 {
- return nil, fmt.Errorf("giccid len is %s, not 19", giccid)
- }
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageData)
- // 条件
- filter := bson.M{
- "iccId": bson.M{
- "$regex": giccid, "$options": "i"},
- }
- cursor, err := collection.Find(ctx, filter, options.Find())
- if err != nil {
- return nil, err
- }
- defer cursor.Close(ctx)
- var infoList []domain.SiteInfoDomain
- for cursor.Next(ctx) {
- var info domain.SiteInfoDomain
- if err := cursor.Decode(&info); err != nil {
- return nil, err
- }
- infoList = append(infoList, info)
- }
- return infoList, nil
- }
- // 插入站点信息数据
- func InsertSiteInfoData(data domain.SiteInfoDomain) error {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoManageData)
- filter := bson.M{"_id": data.Sn} // 按ID匹配
- opts := options.Replace().SetUpsert(true)
- _, err := collection.ReplaceOne(ctx, filter, data, opts)
- if err != nil {
- return err
- }
- return nil
- }
- // 查询站点信息标签列表
- func GetSiteInfoTags(page, size uint, search string) (*dto.ResPage[domain.SiteTagDomain], error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoTags)
- // 查询条件
- filter := bson.M{}
- if search != "" {
- filter["name"] = bson.M{
- "$regex": primitive.Regex{
- Pattern: search,
- Options: "i", // 忽略大小写
- },
- }
- }
- // 总数
- total, err := collection.CountDocuments(ctx, filter)
- if err != nil {
- return nil, err
- }
- // 查询选项
- opts := options.Find().
- SetSkip(int64((page - 1) * size)).
- SetLimit(int64(size)).
- SetSort(bson.D{
- {Key: "name", Value: 1}, // 按名称升序
- })
- cursor, err := collection.Find(ctx, filter, opts)
- if err != nil {
- return nil, err
- }
- defer cursor.Close(ctx)
- list := make([]domain.SiteTagDomain, 0)
- if err := cursor.All(ctx, &list); err != nil {
- return nil, err
- }
- return &dto.ResPage[domain.SiteTagDomain]{
- Data: list,
- PageSize: size,
- PageNum: page,
- Total: uint(total),
- }, nil
- }
- // 查询站点信息标签列表(根据id列表)
- func GetSiteInfoTagsFromId(idList []string) (map[string]*dto.SiteTagDTO, error) {
- tagMap := make(map[string]*dto.SiteTagDTO)
- if len(idList) == 0 {
- return tagMap, nil
- }
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoTags)
- // 转换为 ObjectID
- objectIDs := make([]primitive.ObjectID, 0, len(idList))
- for _, id := range idList {
- objectID, err := primitive.ObjectIDFromHex(id)
- if err != nil {
- // 非法 ID
- zap.L().Warn("GetSiteInfoTagsFromId illegal ID", zap.String("err", err.Error()), zap.String("id", id))
- continue
- }
- objectIDs = append(objectIDs, objectID)
- }
- if len(objectIDs) == 0 {
- return tagMap, nil
- }
- filter := bson.M{
- "_id": bson.M{
- "$in": objectIDs,
- },
- }
- cursor, err := collection.Find(ctx, filter)
- if err != nil {
- return nil, err
- }
- defer cursor.Close(ctx)
- for cursor.Next(ctx) {
- var tag domain.SiteTagDomain
- if err := cursor.Decode(&tag); err != nil {
- return nil, err
- }
- tagMap[tag.Id.Hex()] = dto.SiteTagDomainToSiteTagDTO(&tag)
- }
- if err := cursor.Err(); err != nil {
- return nil, err
- }
- return tagMap, nil
- }
- // 创建或更新站点信息标签
- func UpdateSiteInfoTag(tag domain.SiteTagDomain) error {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection(CollectionName_SiteInfoTags)
- filter := bson.M{"_id": tag.Id}
- update := bson.M{
- "$set": bson.M{
- "name": tag.Name,
- "count": tag.Count,
- "color": tag.Color,
- "description": tag.Description,
- },
- }
- opts := options.Update().SetUpsert(true)
- _, err := collection.UpdateOne(ctx, filter, update, opts)
- if err != nil {
- return err
- }
- return nil
- }
|