package cardobservation import ( "context" "time" "go.uber.org/zap" "gorm.io/gorm" cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation" carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation" "github.com/break/junhong_cmp_fiber/internal/gateway" "github.com/break/junhong_cmp_fiber/internal/model" "github.com/break/junhong_cmp_fiber/internal/store/postgres" "github.com/break/junhong_cmp_fiber/pkg/constants" ) // PreActivationSettler 在资产从"无生效主套餐"变为"有生效主套餐"之前,对已切换日快照计量的卡查一次流量并按现有观测入账。 // 此时资产无生效套餐,增量只记为已结算,不扣新套餐、不产生流量扣减事件,因此也不会触发停复机评估。 // 结算尽力而为:查询失败、限流、超时只告警,不阻塞激活。 type PreActivationSettler struct { db *gorm.DB gateway *gateway.Client observation *cardapp.Service carrier *postgres.CarrierStore logger *zap.Logger } // NewPreActivationSettler 创建激活前流量结算器。 func NewPreActivationSettler(db *gorm.DB, gatewayClient *gateway.Client, observation *cardapp.Service, carrier *postgres.CarrierStore, logger *zap.Logger) *PreActivationSettler { if logger == nil { logger = zap.NewNop() } return &PreActivationSettler{db: db, gateway: gatewayClient, observation: observation, carrier: carrier, logger: logger} } // SettleBeforeActivation 对载体(卡或设备)执行激活前流量结算;资产已有生效主套餐时直接返回。 func (s *PreActivationSettler) SettleBeforeActivation(ctx context.Context, carrierType string, carrierID uint) { if s == nil || s.db == nil || s.gateway == nil || s.observation == nil { return } hasMain, err := s.hasActiveMainPackage(ctx, carrierType, carrierID) if err != nil { s.logger.Warn("激活前流量结算:查询生效主套餐失败,跳过结算", zap.String("carrier_type", carrierType), zap.Uint("carrier_id", carrierID), zap.Error(err)) return } if hasMain { return } s.logger.Info("激活前流量结算开始", zap.String("carrier_type", carrierType), zap.Uint("asset_id", carrierID)) cards, err := s.cardsOf(ctx, carrierType, carrierID) if err != nil { s.logger.Warn("激活前流量结算:查询载体下卡失败,跳过结算", zap.String("carrier_type", carrierType), zap.Uint("carrier_id", carrierID), zap.Error(err)) return } deadline := time.Now().Add(constants.PreActivationSettlementTotalTimeoutSeconds * time.Second) for _, card := range cards { if !s.observation.TrafficSwitched(card.ID) { continue } if time.Now().After(deadline) { s.alert(card, carrierType, carrierID, "整次结算达到总超时,跳过该卡") continue } s.settleCard(ctx, card, carrierType, carrierID, deadline) } } func (s *PreActivationSettler) settleCard(ctx context.Context, card *model.IotCard, carrierType string, carrierID uint, deadline time.Time) { stepDeadline := time.Now().Add(constants.PreActivationSettlementStepTimeoutSeconds * time.Second) if stepDeadline.After(deadline) { stepDeadline = deadline } stepCtx, cancel := context.WithDeadline(context.WithoutCancel(ctx), stepDeadline) defer cancel() response, err := s.gateway.QueryFlow(gateway.WithCarrier(stepCtx, card.CarrierID), &gateway.FlowQueryReq{CardNo: card.ICCID}) if err != nil { reason := "查询流量失败" if gateway.IsRateLimited(err) { reason = "运营商账户网关限流" } s.alert(card, carrierType, carrierID, reason) return } resetDay := 1 if s.carrier != nil { resetDay = s.carrier.GetDataResetDay(stepCtx, card.CarrierID) } observedAt := time.Now().UTC() decision, err := s.observation.ApplyTrafficObservation(stepCtx, carddomain.TrafficObservation{ CardID: card.ID, GatewayReadingMB: float64(response.Used), ResetDay: resetDay, Metadata: carddomain.ObservationMetadata{ ObservationID: "pre-activation-" + card.ICCID + "-" + observedAt.Format("20060102150405.000"), Source: constants.CardObservationSourceBusinessEvent, Scene: constants.CardObservationScenePreActivationSettlement, ObservedAt: observedAt, }, }) if err != nil { s.alert(card, carrierType, carrierID, "流量结算入账失败") return } s.logger.Info("激活前流量结算完成", zap.Uint("card_id", card.ID), zap.String("iccid", card.ICCID), zap.String("carrier_type", carrierType), zap.Uint("asset_id", carrierID), zap.Float64("gateway_flow_mb", float64(response.Used)), zap.Float64("increment_mb", decision.IncrementMB), zap.String("metric", "package.pre_activation_settlement.done")) } // alert 写激活前结算失败告警:该卡本月可能多计无套餐期间用量,由运营核对。 func (s *PreActivationSettler) alert(card *model.IotCard, carrierType string, carrierID uint, reason string) { s.logger.Error("激活前流量结算未完成,该卡本月可能多计无套餐期间用量,请运营核对", zap.Uint("card_id", card.ID), zap.String("iccid", card.ICCID), zap.String("carrier_type", carrierType), zap.Uint("asset_id", carrierID), zap.String("reason", reason), zap.String("metric", "package.pre_activation_settlement.failed")) } func (s *PreActivationSettler) hasActiveMainPackage(ctx context.Context, carrierType string, carrierID uint) (bool, error) { column := "iot_card_id" if carrierType == constants.AssetTypeDevice { column = "device_id" } var count int64 err := s.db.WithContext(ctx).Model(&model.PackageUsage{}). Where(column+" = ? AND status = ? AND master_usage_id IS NULL", carrierID, constants.PackageUsageStatusActive). Count(&count).Error return count > 0, err } func (s *PreActivationSettler) cardsOf(ctx context.Context, carrierType string, carrierID uint) ([]*model.IotCard, error) { var cards []*model.IotCard if carrierType == constants.AssetTypeDevice { err := s.db.WithContext(ctx).Model(&model.IotCard{}). Joins("JOIN tb_device_sim_binding b ON b.iot_card_id = tb_iot_card.id AND b.bind_status = 1 AND b.deleted_at IS NULL"). Where("b.device_id = ?", carrierID).Find(&cards).Error return cards, err } err := s.db.WithContext(ctx).Where("id = ?", carrierID).Find(&cards).Error return cards, err }