package asset import ( "context" "sort" "time" "gorm.io/gorm" "github.com/break/junhong_cmp_fiber/internal/domain/cardflow" "github.com/break/junhong_cmp_fiber/internal/model" "github.com/break/junhong_cmp_fiber/internal/model/dto" "github.com/break/junhong_cmp_fiber/pkg/constants" "github.com/break/junhong_cmp_fiber/pkg/errors" ) // maxCollectionQuerySpan 是采集记录单次查询的最长时间跨度。 const maxCollectionQuerySpan = 31 * 24 * time.Hour // collectionTimeLayouts 是采集记录查询时间参数接受的格式(无时区时按上海时间解析)。 var collectionTimeLayouts = []string{time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"} // ListCardTrafficCollections 按卡与采集时间范围分页查询卡流量采集记录,按采集时间倒序。 func (s *Service) ListCardTrafficCollections(ctx context.Context, cardID uint, req *dto.CardTrafficCollectionListRequest) (*dto.CardTrafficCollectionListResponse, error) { from, err := parseCollectionTime(req.StartTime) if err != nil { return nil, err } to, err := parseCollectionTime(req.EndTime) if err != nil { return nil, err } if !to.After(from) || to.Sub(from) > maxCollectionQuerySpan { return nil, errors.New(errors.CodeInvalidParam, "结束时间必须晚于开始时间,且跨度不超过 31 天") } page, size := req.Page, req.PageSize if page <= 0 { page = 1 } if size <= 0 { size = 50 } success := s.db.WithContext(ctx).Model(&model.CardTrafficCollection{}). Where("iot_card_id = ? AND observed_at >= ? AND observed_at < ? AND result = ?", cardID, from, to, constants.TrafficCollectionResultOK) success = applyStringFilters(success, map[string]string{"decision": req.Decision, "source": req.Source, "scene": req.Scene}) if !req.IncludeFailures { rows, total, err := pageQuery[model.CardTrafficCollection](success, "observed_at DESC, id DESC", page, size) if err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集记录失败") } items := make([]dto.CardTrafficCollectionItem, 0, len(rows)) for _, row := range rows { items = append(items, collectionSuccessItem(row)) } return &dto.CardTrafficCollectionListResponse{Items: items, Total: total}, nil } return s.listCardCollectionsWithFailures(ctx, success, cardID, from, to, req, page, size) } // listCardCollectionsWithFailures 合并单卡的成功与失败记录,按采集时间倒序分页(单卡 31 天内数据量有限,取前 page*size 条归并)。 func (s *Service) listCardCollectionsWithFailures(ctx context.Context, success *gorm.DB, cardID uint, from, to time.Time, req *dto.CardTrafficCollectionListRequest, page, size int) (*dto.CardTrafficCollectionListResponse, error) { failure := s.db.WithContext(ctx).Model(&model.CardTrafficCollectionFailure{}). Where("iot_card_id = ? AND observed_at >= ? AND observed_at < ?", cardID, from, to) failure = applyStringFilters(failure, map[string]string{"source": req.Source, "scene": req.Scene}) var successTotal, failureTotal int64 if err := success.Count(&successTotal).Error; err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集记录失败") } if err := failure.Count(&failureTotal).Error; err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集失败记录失败") } window := page * size var successRows []model.CardTrafficCollection if err := success.Order("observed_at DESC, id DESC").Limit(window).Find(&successRows).Error; err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集记录失败") } var failureRows []model.CardTrafficCollectionFailure if err := failure.Order("observed_at DESC, id DESC").Limit(window).Find(&failureRows).Error; err != nil { return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询卡流量采集失败记录失败") } merged := make([]dto.CardTrafficCollectionItem, 0, len(successRows)+len(failureRows)) for _, row := range successRows { merged = append(merged, collectionSuccessItem(row)) } for _, row := range failureRows { f := collectionFailureItem(row) merged = append(merged, dto.CardTrafficCollectionItem{ ID: f.ID, ObservedAt: f.ObservedAt, ObservationID: f.ObservationID, Source: f.Source, Scene: f.Scene, Result: f.Result, RecordKind: "failure", ErrorCategory: f.ErrorCategory, ProviderCode: f.ProviderCode, ProviderMessage: f.ProviderMessage, DurationMS: f.DurationMS, GatewayRawItem: f.GatewayRawItem, }) } sort.SliceStable(merged, func(i, j int) bool { if !merged[i].ObservedAt.Equal(merged[j].ObservedAt) { return merged[i].ObservedAt.After(merged[j].ObservedAt) } return merged[i].ID > merged[j].ID }) start := (page - 1) * size if start > len(merged) { start = len(merged) } end := start + size if end > len(merged) { end = len(merged) } return &dto.CardTrafficCollectionListResponse{Items: merged[start:end], Total: successTotal + failureTotal}, nil } func parseCollectionTime(value string) (time.Time, error) { location := cardflow.ShanghaiDate(time.Now()).Location() for _, layout := range collectionTimeLayouts { if t, err := time.ParseInLocation(layout, value, location); err == nil { return t, nil } } return time.Time{}, errors.New(errors.CodeInvalidParam, "时间格式无效") }